diff --git a/.gitattributes b/.gitattributes index e4d03c43895f47a6671cc9ca345237dc62d1d677..fa9468d2c9853ec334bec3e96835b119bd1b262c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,3 +16,18 @@ tools/msvs/find_python.cmd text eol=crlf *.so filter=lfs diff=lfs merge=lfs -text *.bin filter=lfs diff=lfs merge=lfs -text *.dll filter=lfs diff=lfs merge=lfs -text +deps/brotli/c/common/dictionary.bin filter=lfs diff=lfs merge=lfs -text +deps/npm/node_modules/term-size/vendor/windows/term-size.exe filter=lfs diff=lfs merge=lfs -text +deps/npm/test/fixtures/forked-underscore-1.5.1.tgz filter=lfs diff=lfs merge=lfs -text +deps/npm/test/fixtures/gitignore-and-npmignore.tgz filter=lfs diff=lfs merge=lfs -text +deps/npm/test/fixtures/gitignore.tgz filter=lfs diff=lfs merge=lfs -text +deps/npm/test/fixtures/npmignore.tgz filter=lfs diff=lfs merge=lfs -text +deps/npm/test/fixtures/scoped-underscore-1.3.1.tgz filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/evil.zip filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/evil_via_absolute_file_name.zip filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/evil_via_invalid_utf8.zip filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/test.zip filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/test_encrypted.zip filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/test_mismatch_size.zip filter=lfs diff=lfs merge=lfs -text +deps/zlib/google/test/data/test_nocompress.zip filter=lfs diff=lfs merge=lfs -text +test/fixtures/google_ssl_hello.bin filter=lfs diff=lfs merge=lfs -text diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f865c5a63e5a4e7a319a81bcce86d911d33a738..7cb8c234c20cc85b23020a6bacc5a435044fbeba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,15 @@ release. -12.21.0
+12.22.7
+12.22.6
+12.22.5
+12.22.4
+12.22.3
+12.22.2
+12.22.1
+12.22.0
+12.21.0
12.20.2
12.20.1
12.20.0
diff --git a/README.OpenSource b/README.OpenSource index 3fece76c244713c865e32d543c81a430477cc0c7..996e2e689dc1d0d6c2dc8fbd64191c7121dd3209 100644 --- a/README.OpenSource +++ b/README.OpenSource @@ -3,7 +3,7 @@ "Name": "node", "License": "ISC License,Public Domain,MIT License,Free Software Foundation - MIT License,Apache License V2.0,ICU License,zlib/libpng License,BSD 2-Clause License,BSD 3-Clause License", "License File": "LICENSE", - "Version Number": "12.21.0", + "Version Number": "12.22.7", "Owner": "sunbingxin@huawei.com", "Upstream URL": "http://www.nodejs.org/", "Description": "Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser." diff --git a/benchmark/.eslintrc.yaml b/benchmark/.eslintrc.yaml deleted file mode 100644 index 8ce0f9f6e148c1ab38942c1c8f0797cb3f5d2d7a..0000000000000000000000000000000000000000 --- a/benchmark/.eslintrc.yaml +++ /dev/null @@ -1,15 +0,0 @@ -## Benchmark-specific linter rules - -env: - node: true - es6: true - -rules: - no-var: error - comma-dangle: - - error - - arrays: 'always-multiline' - objects: 'only-multiline' - imports: 'only-multiline' - exports: 'only-multiline' - prefer-arrow-callback: error diff --git a/benchmark/worker/bench-eventlooputil.js b/benchmark/worker/bench-eventlooputil.js new file mode 100644 index 0000000000000000000000000000000000000000..2d59f9f19ed563fd050e3ab60ffeddf06665738f --- /dev/null +++ b/benchmark/worker/bench-eventlooputil.js @@ -0,0 +1,61 @@ +'use strict'; + +const common = require('../common.js'); +const { Worker, parentPort } = require('worker_threads'); + +if (process.argv[2] === 'idle cats') { + return parentPort.once('message', () => {}); +} + +const bench = common.createBenchmark(main, { + n: [1e6], + method: [ + 'ELU_simple', + 'ELU_passed', + ], +}); + +function main({ method, n }) { + switch (method) { + case 'ELU_simple': + benchELUSimple(n); + break; + case 'ELU_passed': + benchELUPassed(n); + break; + default: + throw new Error(`Unsupported method ${method}`); + } +} + +function benchELUSimple(n) { + const worker = new Worker(__filename, { argv: ['idle cats'] }); + + spinUntilIdle(worker, () => { + bench.start(); + for (let i = 0; i < n; i++) + worker.performance.eventLoopUtilization(); + bench.end(n); + worker.postMessage('bye'); + }); +} + +function benchELUPassed(n) { + const worker = new Worker(__filename, { argv: ['idle cats'] }); + + spinUntilIdle(worker, () => { + let elu = worker.performance.eventLoopUtilization(); + bench.start(); + for (let i = 0; i < n; i++) + elu = worker.performance.eventLoopUtilization(elu); + bench.end(n); + worker.postMessage('bye'); + }); +} + +function spinUntilIdle(w, cb) { + const t = w.performance.eventLoopUtilization(); + if (t.idle + t.active > 0) + return process.nextTick(cb); + setTimeout(() => spinUntilIdle(w, cb), 1); +} diff --git a/deps/brotli/c/common/dictionary.bin b/deps/brotli/c/common/dictionary.bin index 0b2fd25652513884e1b2042cc31ccba903a4966b..a585c0e292eba19e594ef95f5c4fb38fcb1f7a84 100644 --- a/deps/brotli/c/common/dictionary.bin +++ b/deps/brotli/c/common/dictionary.bin @@ -1,3 +1,432 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:20e42eb1b511c21806d4d227d07e5dd06877d8ce7b3a817f378f313653f35c70 -size 122784 +timedownlifeleftbackcodedatashowonlysitecityopenjustlikefreeworktextyearoverbodyloveformbookplaylivelinehelphomesidemorewordlongthemviewfindpagedaysfullheadtermeachareafromtruemarkableuponhighdatelandnewsevennextcasebothpostusedmadehandherewhatnameLinkblogsizebaseheldmakemainuser') +holdendswithNewsreadweresigntakehavegameseencallpathwellplusmenufilmpartjointhislistgoodneedwayswestjobsmindalsologorichuseslastteamarmyfoodkingwilleastwardbestfirePageknowaway.pngmovethanloadgiveselfnotemuchfeedmanyrockicononcelookhidediedHomerulehostajaxinfoclublawslesshalfsomesuchzone100%onescareTimeracebluefourweekfacehopegavehardlostwhenparkkeptpassshiproomHTMLplanTypedonesavekeepflaglinksoldfivetookratetownjumpthusdarkcardfilefearstaykillthatfallautoever.comtalkshopvotedeepmoderestturnbornbandfellroseurl(skinrolecomeactsagesmeetgold.jpgitemvaryfeltthensenddropViewcopy1.0"stopelseliestourpack.gifpastcss?graymean>rideshotlatesaidroadvar feeljohnrickportfast'UA-deadpoorbilltypeU.S.woodmust2px;Inforankwidewantwalllead[0];paulwavesure$('#waitmassarmsgoesgainlangpaid!-- lockunitrootwalkfirmwifexml"songtest20pxkindrowstoolfontmailsafestarmapscorerainflowbabyspansays4px;6px;artsfootrealwikiheatsteptriporg/lakeweaktoldFormcastfansbankveryrunsjulytask1px;goalgrewslowedgeid="sets5px;.js?40pxif (soonseatnonetubezerosentreedfactintogiftharm18pxcamehillboldzoomvoideasyringfillpeakinitcost3px;jacktagsbitsrolleditknewnearironfreddiskwentsoilputs/js/holyT22:ISBNT20:adamsees

json', 'contT21: RSSloopasiamoon

soulLINEfortcartT14:

80px!--<9px;T04:mike:46ZniceinchYorkricezh:ä'));puremageparatonebond:37Z_of_']);000,zh:çtankyardbowlbush:56ZJava30px +|} +%C3%:34ZjeffEXPIcashvisagolfsnowzh:équer.csssickmeatmin.binddellhirepicsrent:36ZHTTP-201fotowolfEND xbox:54ZBODYdick; +} +exit:35Zvarsbeat'});diet999;anne}}sonyguysfuckpipe|- +!002)ndow[1];[]; +Log salt + bangtrimbath){ +00px +});ko:ìfeesad> s:// [];tollplug(){ +{ + .js'200pdualboat.JPG); +}quot); + +'); + +} 201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037201320122011201020092008200720062005200420032002200120001999199819971996199519941993199219911990198919881987198619851984198319821981198019791978197719761975197419731972197119701969196819671966196519641963196219611960195919581957195619551954195319521951195010001024139400009999comomásesteestaperotodohacecadaañobiendíaasívidacasootroforosolootracualdijosidograntipotemadebealgoquéestonadatrespococasabajotodasinoaguapuesunosantediceluisellamayozonaamorpisoobraclicellodioshoracasiзанаомрарутанепоотизнодотожеонихÐаеебымыВыÑовывоÐообПолиниРФÐеМытыОнимдаЗаДаÐуОбтеИзейнуммТыужÙيأنمامعكلأوردياÙىهولملكاولهبسالإنهيأيقدهلثمبهلوليبلايبكشيامأمنتبيلنحبهممشوشfirstvideolightworldmediawhitecloseblackrightsmallbooksplacemusicfieldorderpointvalueleveltableboardhousegroupworksyearsstatetodaywaterstartstyledeathpowerphonenighterrorinputabouttermstitletoolseventlocaltimeslargewordsgamesshortspacefocusclearmodelblockguideradiosharewomenagainmoneyimagenamesyounglineslatercolorgreenfront&watchforcepricerulesbeginaftervisitissueareasbelowindextotalhourslabelprintpressbuiltlinksspeedstudytradefoundsenseundershownformsrangeaddedstillmovedtakenaboveflashfixedoftenotherviewschecklegalriveritemsquickshapehumanexistgoingmoviethirdbasicpeacestagewidthloginideaswrotepagesusersdrivestorebreaksouthvoicesitesmonthwherebuildwhichearthforumthreesportpartyClicklowerlivesclasslayerentrystoryusagesoundcourtyour birthpopuptypesapplyImagebeinguppernoteseveryshowsmeansextramatchtrackknownearlybegansuperpapernorthlearngivennamedendedTermspartsGroupbrandusingwomanfalsereadyaudiotakeswhile.com/livedcasesdailychildgreatjudgethoseunitsneverbroadcoastcoverapplefilescyclesceneplansclickwritequeenpieceemailframeolderphotolimitcachecivilscaleenterthemetheretouchboundroyalaskedwholesincestock namefaithheartemptyofferscopeownedmightalbumthinkbloodarraymajortrustcanonunioncountvalidstoneStyleLoginhappyoccurleft:freshquitefilmsgradeneedsurbanfightbasishoverauto;route.htmlmixedfinalYour slidetopicbrownalonedrawnsplitreachRightdatesmarchquotegoodsLinksdoubtasyncthumballowchiefyouthnovel10px;serveuntilhandsCheckSpacequeryjamesequaltwice0,000Startpanelsongsroundeightshiftworthpostsleadsweeksavoidthesemilesplanesmartalphaplantmarksratesplaysclaimsalestextsstarswrong

thing.org/multiheardPowerstandtokensolid(thisbringshipsstafftriedcallsfullyfactsagentThis //-->adminegyptEvent15px;Emailtrue"crossspentblogsbox">notedleavechinasizesguestrobotheavytrue,sevengrandcrimesignsawaredancephase> + + +name=diegopage swiss--> + +#fff;">Log.com"treatsheet) && 14px;sleepntentfiledja:ãƒid="cName"worseshots-box-delta +<bears:48Z spendbakershops= "";php">ction13px;brianhellosize=o=%2F joinmaybe, fjsimg" ")[0]MTopBType"newlyDanskczechtrailknowsfaq">zh-cn10); +-1");type=bluestrulydavis.js';> + +form jesus100% menu. + +walesrisksumentddingb-likteachgif" vegasdanskeestishqipsuomisobredesdeentretodospuedeañosestátienehastaotrospartedondenuevohacerformamismomejormundoaquídíassóloayudafechatodastantomenosdatosotrassitiomuchoahoralugarmayorestoshorastenerantesfotosestaspaísnuevasaludforosmedioquienmesespoderchileserávecesdecirjoséestarventagrupohechoellostengoamigocosasnivelgentemismaairesjuliotemashaciafavorjuniolibrepuntobuenoautorabrilbuenatextomarzosaberlistaluegocómoenerojuegoperúhaberestoynuncamujervalorfueralibrogustaigualvotoscasosguíapuedosomosavisousteddebennochebuscafaltaeurosseriedichocursoclavecasasleónplazolargoobrasvistaapoyojuntotratavistocrearcampohemoscincocargopisosordenhacenáreadiscopedrocercapuedapapelmenorútilclarojorgecalleponertardenadiemarcasigueellassiglocochemotosmadreclaserestoniñoquedapasarbancohijosviajepabloéstevienereinodejarfondocanalnorteletracausatomarmanoslunesautosvillavendopesartipostengamarcollevapadreunidovamoszonasambosbandamariaabusomuchasubirriojavivirgradochicaallíjovendichaestantalessalirsuelopesosfinesllamabuscoéstalleganegroplazahumorpagarjuntadobleislasbolsabañohablaluchaÃreadicenjugarnotasvalleallácargadolorabajoestégustomentemariofirmacostofichaplatahogarartesleyesaquelmuseobasespocosmitadcielochicomiedoganarsantoetapadebesplayaredessietecortecoreadudasdeseoviejodeseaaguas"domaincommonstatuseventsmastersystemactionbannerremovescrollupdateglobalmediumfilternumberchangeresultpublicscreenchoosenormaltravelissuessourcetargetspringmodulemobileswitchphotosborderregionitselfsocialactivecolumnrecordfollowtitle>eitherlengthfamilyfriendlayoutauthorcreatereviewsummerserverplayedplayerexpandpolicyformatdoublepointsseriespersonlivingdesignmonthsforcesuniqueweightpeopleenergynaturesearchfigurehavingcustomoffsetletterwindowsubmitrendergroupsuploadhealthmethodvideosschoolfutureshadowdebatevaluesObjectothersrightsleaguechromesimplenoticesharedendingseasonreportonlinesquarebuttonimagesenablemovinglatestwinterFranceperiodstrongrepeatLondondetailformeddemandsecurepassedtoggleplacesdevicestaticcitiesstreamyellowattackstreetflighthiddeninfo">openedusefulvalleycausesleadersecretseconddamagesportsexceptratingsignedthingseffectfieldsstatesofficevisualeditorvolumeReportmuseummoviesparentaccessmostlymother" id="marketgroundchancesurveybeforesymbolmomentspeechmotioninsidematterCenterobjectexistsmiddleEuropegrowthlegacymannerenoughcareeransweroriginportalclientselectrandomclosedtopicscomingfatheroptionsimplyraisedescapechosenchurchdefinereasoncorneroutputmemoryiframepolicemodelsNumberduringoffersstyleskilledlistedcalledsilvermargindeletebetterbrowselimitsGlobalsinglewidgetcenterbudgetnowrapcreditclaimsenginesafetychoicespirit-stylespreadmakingneededrussiapleaseextentScriptbrokenallowschargedividefactormember-basedtheoryconfigaroundworkedhelpedChurchimpactshouldalwayslogo" bottomlist">){var prefixorangeHeader.push(couplegardenbridgelaunchReviewtakingvisionlittledatingButtonbeautythemesforgotSearchanchoralmostloadedChangereturnstringreloadMobileincomesupplySourceordersviewed courseAbout islandPhilipawardshandleimportOfficeregardskillsnationSportsdegreeweekly (e.g.behinddoctorloggedunitedbeyond-scaleacceptservedmarineFootercamera +_form"leavesstress" /> +.gif" onloadloaderOxfordsistersurvivlistenfemaleDesignsize="appealtext">levelsthankshigherforcedanimalanyoneAfricaagreedrecentPeople
wonderpricesturned|| {};main">inlinesundaywrap">failedcensusminutebeaconquotes150px|estateremoteemail"linkedright;signalformal1.htmlsignupprincefloat:.png" forum.AccesspaperssoundsextendHeightsliderUTF-8"& Before. WithstudioownersmanageprofitjQueryannualparamsboughtfamousgooglelongeri++) {israelsayingdecidehome">headerensurebranchpiecesblock;statedtop">boston.test(avatartested_countforumsschemaindex,filledsharesreaderalert(appearSubmitline">body"> +* TheThoughseeingjerseyNews +System DavidcancertablesprovedApril reallydriveritem">more">boardscolorscampusfirst || [];media.guitarfinishwidth:showedOther .php" assumelayerswilsonstoresreliefswedenCustomeasily your String + +Whiltaylorclear:resortfrenchthough") + "buyingbrandsMembername">oppingsector5px;">vspacepostermajor coffeemartinmaturehappenkansaslink">Images=falsewhile hspace0& + +In powerPolski-colorjordanBottomStart -count2.htmlnews">01.jpgOnline-rightmillerseniorISBN 00,000 guidesvalue)ectionrepair.xml" rights.html-blockregExp:hoverwithinvirginphones using + var >'); + + +bahasabrasilgalegomagyarpolskisrpskiردو中文简体ç¹é«”ä¿¡æ¯ä¸­å›½æˆ‘们一个公å¸ç®¡ç†è®ºå›å¯ä»¥æœåŠ¡æ—¶é—´ä¸ªäººäº§å“自己ä¼ä¸šæŸ¥çœ‹å·¥ä½œè”系没有网站所有评论中心文章用户首页作者技术问题相关下载æœç´¢ä½¿ç”¨è½¯ä»¶åœ¨çº¿ä¸»é¢˜èµ„æ–™è§†é¢‘å›žå¤æ³¨å†Œç½‘络收è—内容推è市场消æ¯ç©ºé—´å‘布什么好å‹ç”Ÿæ´»å›¾ç‰‡å‘展如果手机新闻最新方å¼åŒ—京æä¾›å…³äºŽæ›´å¤šè¿™ä¸ªç³»ç»ŸçŸ¥é“游æˆå¹¿å‘Šå…¶ä»–å‘表安全第一会员进行点击版æƒç”µå­ä¸–界设计å…费教育加入活动他们商å“åšå®¢çŽ°åœ¨ä¸Šæµ·å¦‚ä½•å·²ç»ç•™è¨€è¯¦ç»†ç¤¾åŒºç™»å½•本站需è¦ä»·æ ¼æ”¯æŒå›½é™…链接国家建设朋å‹é˜…读法律ä½ç½®ç»æµŽé€‰æ‹©è¿™æ ·å½“å‰åˆ†ç±»æŽ’行因为交易最åŽéŸ³ä¹ä¸èƒ½é€šè¿‡è¡Œä¸šç§‘技å¯èƒ½è®¾å¤‡åˆä½œå¤§å®¶ç¤¾ä¼šç ”究专业全部项目这里还是开始情况电脑文件å“牌帮助文化资æºå¤§å­¦å­¦ä¹ åœ°å€æµè§ˆæŠ•èµ„å·¥ç¨‹è¦æ±‚怎么时候功能主è¦ç›®å‰èµ„讯城市方法电影招è˜å£°æ˜Žä»»ä½•å¥åº·æ•°æ®ç¾Žå›½æ±½è½¦ä»‹ç»ä½†æ˜¯äº¤æµç”Ÿäº§æ‰€ä»¥ç”µè¯æ˜¾ç¤ºä¸€äº›å•ä½äººå‘˜åˆ†æžåœ°å›¾æ—…游工具学生系列网å‹å¸–å­å¯†ç é¢‘é“æŽ§åˆ¶åœ°åŒºåŸºæœ¬å…¨å›½ç½‘ä¸Šé‡è¦ç¬¬äºŒå–œæ¬¢è¿›å…¥å‹æƒ…这些考试å‘现培训以上政府æˆä¸ºçŽ¯å¢ƒé¦™æ¸¯åŒæ—¶å¨±ä¹å‘é€ä¸€å®šå¼€å‘ä½œå“æ ‡å‡†æ¬¢è¿Žè§£å†³åœ°æ–¹ä¸€ä¸‹ä»¥åŠè´£ä»»æˆ–者客户代表积分女人数ç é”€å”®å‡ºçŽ°ç¦»çº¿åº”ç”¨åˆ—è¡¨ä¸åŒç¼–辑统计查询ä¸è¦æœ‰å…³æœºæž„å¾ˆå¤šæ’­æ”¾ç»„ç»‡æ”¿ç­–ç›´æŽ¥èƒ½åŠ›æ¥æºæ™‚間看到热门关键专区éžå¸¸è‹±è¯­ç™¾åº¦å¸Œæœ›ç¾Žå¥³æ¯”较知识规定建议部门æ„è§ç²¾å½©æ—¥æœ¬æé«˜å‘言方é¢åŸºé‡‘å¤„ç†æƒé™å½±ç‰‡é“¶è¡Œè¿˜æœ‰åˆ†äº«ç‰©å“ç»è¥æ·»åŠ ä¸“å®¶è¿™ç§è¯é¢˜èµ·æ¥ä¸šåŠ¡å…¬å‘Šè®°å½•ç®€ä»‹è´¨é‡ç”·äººå½±å“引用报告部分快速咨询时尚注æ„申请学校应该历å²åªæ˜¯è¿”回购买å称为了æˆåŠŸè¯´æ˜Žä¾›åº”å­©å­ä¸“题程åºä¸€èˆ¬æœƒå“¡åªæœ‰å…¶å®ƒä¿æŠ¤è€Œä¸”今天窗å£åЍæ€çжæ€ç‰¹åˆ«è®¤ä¸ºå¿…须更新å°è¯´æˆ‘å€‘ä½œä¸ºåª’ä½“åŒ…æ‹¬é‚£ä¹ˆä¸€æ ·å›½å†…æ˜¯å¦æ ¹æ®ç”µè§†å­¦é™¢å…·æœ‰è¿‡ç¨‹ç”±äºŽäººæ‰å‡ºæ¥ä¸è¿‡æ­£åœ¨æ˜Žæ˜Ÿæ•…事关系标题商务输入一直基础教学了解建筑结果全çƒé€šçŸ¥è®¡åˆ’对于艺术相册å‘生真的建立等级类型ç»éªŒå®žçŽ°åˆ¶ä½œæ¥è‡ªæ ‡ç­¾ä»¥ä¸‹åŽŸåˆ›æ— æ³•å…¶ä¸­å€‹äººä¸€åˆ‡æŒ‡å—关闭集团第三关注因此照片深圳商业广州日期高级最近综åˆè¡¨ç¤ºä¸“辑行为交通评价觉得精åŽå®¶åº­å®Œæˆæ„Ÿè§‰å®‰è£…得到邮件制度食å“虽然转载报价记者方案行政人民用å“东西æå‡ºé…’店然åŽä»˜æ¬¾çƒ­ç‚¹ä»¥å‰å®Œå…¨å‘帖设置领导工业医院看看ç»å…¸åŽŸå› å¹³å°å„ç§å¢žåŠ ææ–™æ–°å¢žä¹‹åŽèŒä¸šæ•ˆæžœä»Šå¹´è®ºæ–‡æˆ‘国告诉版主修改å‚与打å°å¿«ä¹æœºæ¢°è§‚点存在精神获得利用继续你们这么模å¼è¯­è¨€èƒ½å¤Ÿé›…虎æ“作风格一起科学体育短信æ¡ä»¶æ²»ç–—è¿åŠ¨äº§ä¸šä¼šè®®å¯¼èˆªå…ˆç”Ÿè”ç›Ÿå¯æ˜¯å•題结构作用调查資料自动负责农业访问实施接å—讨论那个å馈加强女性范围æœå‹™ä¼‘闲今日客æœè§€çœ‹å‚加的è¯ä¸€ç‚¹ä¿è¯å›¾ä¹¦æœ‰æ•ˆæµ‹è¯•移动æ‰èƒ½å†³å®šè‚¡ç¥¨ä¸æ–­éœ€æ±‚ä¸å¾—办法之间采用è¥é”€æŠ•诉目标爱情摄影有些複製文学机会数字装修购物农æ‘å…¨é¢ç²¾å“其实事情水平æç¤ºä¸Šå¸‚谢谢普通教师上传类别歌曲拥有创新é…ä»¶åªè¦æ—¶ä»£è³‡è¨Šè¾¾åˆ°äººç”Ÿè®¢é˜…è€å¸ˆå±•示心ç†è´´å­ç¶²ç«™ä¸»é¡Œè‡ªç„¶çº§åˆ«ç®€å•改é©é‚£äº›æ¥è¯´æ‰“开代ç åˆ é™¤è¯åˆ¸èŠ‚ç›®é‡ç‚¹æ¬¡æ•¸å¤šå°‘规划资金找到以åŽå¤§å…¨ä¸»é¡µæœ€ä½³å›žç­”天下ä¿éšœçŽ°ä»£æ£€æŸ¥æŠ•ç¥¨å°æ—¶æ²’有正常甚至代ç†ç›®å½•公开å¤åˆ¶é‡‘èžå¹¸ç¦ç‰ˆæœ¬å½¢æˆå‡†å¤‡è¡Œæƒ…å›žåˆ°æ€æƒ³æ€Žæ ·åè®®è®¤è¯æœ€å¥½äº§ç”ŸæŒ‰ç…§æœè£…å¹¿ä¸œåŠ¨æ¼«é‡‡è´­æ–°æ‰‹ç»„å›¾é¢æ¿å‚考政治容易天地努力人们å‡çº§é€Ÿåº¦äººç‰©è°ƒæ•´æµè¡Œé€ æˆæ–‡å­—éŸ©å›½è´¸æ˜“å¼€å±•ç›¸é—œè¡¨çŽ°å½±è§†å¦‚æ­¤ç¾Žå®¹å¤§å°æŠ¥é“æ¡æ¬¾å¿ƒæƒ…许多法规家居书店连接立å³ä¸¾æŠ¥æŠ€å·§å¥¥è¿ç™»å…¥ä»¥æ¥ç†è®ºäº‹ä»¶è‡ªç”±ä¸­åŽåŠžå…¬å¦ˆå¦ˆçœŸæ­£ä¸é”™å…¨æ–‡åˆåŒä»·å€¼åˆ«äººç›‘ç£å…·ä½“ä¸–çºªå›¢é˜Ÿåˆ›ä¸šæ‰¿æ‹…å¢žé•¿æœ‰äººä¿æŒå•†å®¶ç»´ä¿®å°æ¹¾å·¦å³è‚¡ä»½ç­”案实际电信ç»ç†ç”Ÿå‘½å®£ä¼ ä»»åŠ¡æ­£å¼ç‰¹è‰²ä¸‹æ¥å会åªèƒ½å½“ç„¶é‡æ–°å…§å®¹æŒ‡å¯¼è¿è¡Œæ—¥å¿—賣家超过土地浙江支付推出站长æ­å·žæ‰§è¡Œåˆ¶é€ ä¹‹ä¸€æŽ¨å¹¿çŽ°åœºæè¿°å˜åŒ–传统歌手ä¿é™©è¯¾ç¨‹åŒ»ç–—ç»è¿‡è¿‡å޻之剿”¶å…¥å¹´åº¦æ‚志美丽最高登陆未æ¥åŠ å·¥å…责教程版å—身体é‡åº†å‡ºå”®æˆæœ¬å½¢å¼åœŸè±†å‡ºåƒ¹ä¸œæ–¹é‚®ç®±å—京求èŒå–å¾—èŒä½ç›¸ä¿¡é¡µé¢åˆ†é’Ÿç½‘页确定图例网å€ç§¯æžé”™è¯¯ç›®çš„å®è´æœºå…³é£Žé™©æŽˆæƒç—…æ¯’å® ç‰©é™¤äº†è©•è«–ç–¾ç—…åŠæ—¶æ±‚购站点儿童æ¯å¤©ä¸­å¤®è®¤è¯†æ¯ä¸ªå¤©æ´¥å­—体å°ç£ç»´æŠ¤æœ¬é¡µä¸ªæ€§å®˜æ–¹å¸¸è§ç›¸æœºæˆ˜ç•¥åº”当律师方便校园股市房屋æ ç›®å‘˜å·¥å¯¼è‡´çªç„¶é“å…·æœ¬ç½‘ç»“åˆæ¡£æ¡ˆåŠ³åŠ¨å¦å¤–美元引起改å˜ç¬¬å››ä¼šè®¡èªªæ˜Žéšç§å®å®è§„范消费共åŒå¿˜è®°ä½“系带æ¥å字發表开放加盟å—åˆ°äºŒæ‰‹å¤§é‡æˆäººæ•°é‡å…±äº«åŒºåŸŸå¥³å­©åŽŸåˆ™æ‰€åœ¨ç»“æŸé€šä¿¡è¶…级é…ç½®å½“æ—¶ä¼˜ç§€æ€§æ„Ÿæˆ¿äº§éŠæˆ²å‡ºå£æäº¤å°±ä¸šä¿å¥ç¨‹åº¦å‚数事业整个山东情感特殊分類æœå°‹å±žäºŽé—¨æˆ·è´¢åŠ¡å£°éŸ³åŠå…¶è´¢ç»åšæŒå¹²éƒ¨æˆç«‹åˆ©ç›Šè€ƒè™‘æˆéƒ½åŒ…装用戶比赛文明招商完整真是眼ç›ä¼™ä¼´å¨æœ›é¢†åŸŸå«ç”Ÿä¼˜æƒ è«–壇公共良好充分符åˆé™„件特点ä¸å¯è‹±æ–‡èµ„äº§æ ¹æœ¬æ˜Žæ˜¾å¯†ç¢¼å…¬ä¼—æ°‘æ—æ›´åŠ äº«å—åŒå­¦å¯åЍ适åˆåŽŸæ¥é—®ç­”本文美食绿色稳定终于生物供求æœç‹åŠ›é‡ä¸¥é‡æ°¸è¿œå†™çœŸæœ‰é™ç«žäº‰å¯¹è±¡è´¹ç”¨ä¸å¥½ç»å¯¹å分促进点评影音优势ä¸å°‘欣èµå¹¶ä¸”有点方å‘全新信用设施形象资格çªç ´éšç€é‡å¤§äºŽæ˜¯æ¯•ä¸šæ™ºèƒ½åŒ–å·¥å®Œç¾Žå•†åŸŽç»Ÿä¸€å‡ºç‰ˆæ‰“é€ ç”¢å“æ¦‚况用于ä¿ç•™å› ç´ ä¸­åœ‹å­˜å‚¨è´´å›¾æœ€æ„›é•¿æœŸå£ä»·ç†è´¢åŸºåœ°å®‰æŽ’武汉里é¢åˆ›å»ºå¤©ç©ºé¦–先完善驱动下é¢ä¸å†è¯šä¿¡æ„义阳光英国漂亮军事玩家群众农民å³å¯å稱家具动画想到注明å°å­¦æ€§èƒ½è€ƒç ”硬件观看清楚æžç¬‘首é é»„金适用江è‹çœŸå®žä¸»ç®¡é˜¶æ®µè¨»å†Šç¿»è¯‘æƒåˆ©åšå¥½ä¼¼ä¹Žé€šè®¯æ–½å·¥ç‹€æ…‹ä¹Ÿè®¸çޝä¿åŸ¹å…»æ¦‚念大型机票ç†è§£åŒ¿åcuandoenviarmadridbuscariniciotiempoporquecuentaestadopuedenjuegoscontraestánnombretienenperfilmaneraamigosciudadcentroaunquepuedesdentroprimerpreciosegúnbuenosvolverpuntossemanahabíaagostonuevosunidoscarlosequiponiñosmuchosalgunacorreoimagenpartirarribamaríahombreempleoverdadcambiomuchasfueronpasadolíneaparecenuevascursosestabaquierolibroscuantoaccesomiguelvarioscuatrotienesgruposseráneuropamediosfrenteacercademásofertacochesmodeloitalialetrasalgúncompracualesexistecuerposiendoprensallegarviajesdineromurciapodrápuestodiariopuebloquieremanuelpropiocrisisciertoseguromuertefuentecerrargrandeefectopartesmedidapropiaofrecetierrae-mailvariasformasfuturoobjetoseguirriesgonormasmismosúnicocaminositiosrazóndebidopruebatoledoteníajesúsesperococinaorigentiendacientocádizhablarseríalatinafuerzaestiloguerraentraréxitolópezagendavídeoevitarpaginametrosjavierpadresfácilcabezaáreassalidaenvíojapónabusosbienestextosllevarpuedanfuertecomúnclaseshumanotenidobilbaounidadestáseditarcreadoдлÑчтокакилиÑтовÑеегопритакещеужеКакбезбылониВÑеподЭтотомчемнетлетразонагдемнеДлÑПринаÑнихтемктогодвоттамСШÐмаÑЧтоваÑвамемуТакдванамÑтиÑтуВамтехпротутнадднÑВоттринейВаÑнимÑамтотрубОнимирнееОООлицÑтаОнанемдоммойдвеоноÑудकेहैकीसेकाकोऔरपरनेà¤à¤•किभीइसकरतोहोआपहीयहयातकथाjagranआजजोअबदोगईजागà¤à¤¹à¤®à¤‡à¤¨à¤µà¤¹à¤¯à¥‡à¤¥à¥‡à¤¥à¥€à¤˜à¤°à¤œà¤¬à¤¦à¥€à¤•ईजीवेनईनà¤à¤¹à¤°à¤‰à¤¸à¤®à¥‡à¤•मवोलेसबमईदेओरआमबसभरबनचलमनआगसीलीعلىإلىهذاآخرعددالىهذهصورغيركانولابينعرضذلكهنايومقالعليانالكنحتىقبلوحةاخرÙقطعبدركنإذاكمااحدإلاÙÙŠÙ‡Ø¨Ø¹Ø¶ÙƒÙŠÙØ¨Ø­Ø«ÙˆÙ…نوهوأناجدالهاسلمعندليسعبرصلىمنذبهاأنهمثلكنتالاحيثمصرشرححولوÙÙŠØ§Ø°Ø§Ù„ÙƒÙ„Ù…Ø±Ø©Ø§Ù†ØªØ§Ù„ÙØ£Ø¨ÙˆØ®Ø§ØµØ£Ù†ØªØ§Ù†Ù‡Ø§Ù„ÙŠØ¹Ø¶ÙˆÙˆÙ‚Ø¯Ø§Ø¨Ù†Ø®ÙŠØ±Ø¨Ù†ØªÙ„ÙƒÙ…Ø´Ø§Ø¡ÙˆÙ‡ÙŠØ§Ø¨ÙˆÙ‚ØµØµÙˆÙ…Ø§Ø±Ù‚Ù…Ø£Ø­Ø¯Ù†Ø­Ù†Ø¹Ø¯Ù…Ø±Ø£ÙŠØ§Ø­Ø©ÙƒØªØ¨Ø¯ÙˆÙ†ÙŠØ¬Ø¨Ù…Ù†Ù‡ØªØ­ØªØ¬Ù‡Ø©Ø³Ù†Ø©ÙŠØªÙ…ÙƒØ±Ø©ØºØ²Ø©Ù†ÙØ³Ø¨ÙŠØªÙ„لهلناتلكقلبلماعنهأولشيءنورأماÙيكبكلذاترتببأنهمسانكبيعÙقدحسنلهمشعرأهلشهرقطرطلبprofileservicedefaulthimselfdetailscontentsupportstartedmessagesuccessfashioncountryaccountcreatedstoriesresultsrunningprocesswritingobjectsvisiblewelcomearticleunknownnetworkcompanydynamicbrowserprivacyproblemServicerespectdisplayrequestreservewebsitehistoryfriendsoptionsworkingversionmillionchannelwindow.addressvisitedweathercorrectproductedirectforwardyou canremovedsubjectcontrolarchivecurrentreadinglibrarylimitedmanagerfurthersummarymachineminutesprivatecontextprogramsocietynumberswrittenenabledtriggersourcesloadingelementpartnerfinallyperfectmeaningsystemskeepingculture",journalprojectsurfaces"expiresreviewsbalanceEnglishContentthroughPlease opinioncontactaverageprimaryvillageSpanishgallerydeclinemeetingmissionpopularqualitymeasuregeneralspeciessessionsectionwriterscounterinitialreportsfiguresmembersholdingdisputeearlierexpressdigitalpictureAnothermarriedtrafficleadingchangedcentralvictoryimages/reasonsstudiesfeaturelistingmust beschoolsVersionusuallyepisodeplayinggrowingobviousoverlaypresentactions</ul> +wrapperalreadycertainrealitystorageanotherdesktopofferedpatternunusualDigitalcapitalWebsitefailureconnectreducedAndroiddecadesregular & animalsreleaseAutomatgettingmethodsnothingPopularcaptionletterscapturesciencelicensechangesEngland=1&History = new CentralupdatedSpecialNetworkrequirecommentwarningCollegetoolbarremainsbecauseelectedDeutschfinanceworkersquicklybetweenexactlysettingdiseaseSocietyweaponsexhibit<!--Controlclassescoveredoutlineattacksdevices(windowpurposetitle="Mobile killingshowingItaliandroppedheavilyeffects-1']); +confirmCurrentadvancesharingopeningdrawingbillionorderedGermanyrelated</form>includewhetherdefinedSciencecatalogArticlebuttonslargestuniformjourneysidebarChicagoholidayGeneralpassage,"animatefeelingarrivedpassingnaturalroughly. + +The but notdensityBritainChineselack oftributeIreland" data-factorsreceivethat isLibraryhusbandin factaffairsCharlesradicalbroughtfindinglanding:lang="return leadersplannedpremiumpackageAmericaEdition]"Messageneed tovalue="complexlookingstationbelievesmaller-mobilerecordswant tokind ofFirefoxyou aresimilarstudiedmaximumheadingrapidlyclimatekingdomemergedamountsfoundedpioneerformuladynastyhow to SupportrevenueeconomyResultsbrothersoldierlargelycalling."AccountEdward segmentRobert effortsPacificlearnedup withheight:we haveAngelesnations_searchappliedacquiremassivegranted: falsetreatedbiggestbenefitdrivingStudiesminimumperhapsmorningsellingis usedreversevariant role="missingachievepromotestudentsomeoneextremerestorebottom:evolvedall thesitemapenglishway to AugustsymbolsCompanymattersmusicalagainstserving})(); +paymenttroubleconceptcompareparentsplayersregionsmonitor ''The winningexploreadaptedGalleryproduceabilityenhancecareers). The collectSearch ancientexistedfooter handlerprintedconsoleEasternexportswindowsChannelillegalneutralsuggest_headersigning.html">settledwesterncausing-webkitclaimedJusticechaptervictimsThomas mozillapromisepartieseditionoutside:false,hundredOlympic_buttonauthorsreachedchronicdemandssecondsprotectadoptedprepareneithergreatlygreateroverallimprovecommandspecialsearch.worshipfundingthoughthighestinsteadutilityquarterCulturetestingclearlyexposedBrowserliberal} catchProjectexamplehide();FloridaanswersallowedEmperordefenseseriousfreedomSeveral-buttonFurtherout of != nulltrainedDenmarkvoid(0)/all.jspreventRequestStephen + +When observe</h2> +Modern provide" alt="borders. + +For + +Many artistspoweredperformfictiontype ofmedicalticketsopposedCouncilwitnessjusticeGeorge Belgium...</a>twitternotablywaitingwarfare Other rankingphrasesmentionsurvivescholar</p> + Countryignoredloss ofjust asGeorgiastrange<head><stopped1']); +islandsnotableborder:list ofcarried100,000</h3> + severalbecomesselect wedding00.htmlmonarchoff theteacherhighly biologylife ofor evenrise of»plusonehunting(thoughDouglasjoiningcirclesFor theAncientVietnamvehiclesuch ascrystalvalue =Windowsenjoyeda smallassumed<a id="foreign All rihow theDisplayretiredhoweverhidden;battlesseekingcabinetwas notlook atconductget theJanuaryhappensturninga:hoverOnline French lackingtypicalextractenemieseven ifgeneratdecidedare not/searchbeliefs-image:locatedstatic.login">convertviolententeredfirst">circuitFinlandchemistshe was10px;">as suchdivided</span>will beline ofa greatmystery/index.fallingdue to railwaycollegemonsterdescentit withnuclearJewish protestBritishflowerspredictreformsbutton who waslectureinstantsuicidegenericperiodsmarketsSocial fishingcombinegraphicwinners<br /><by the NaturalPrivacycookiesoutcomeresolveSwedishbrieflyPersianso muchCenturydepictscolumnshousingscriptsnext tobearingmappingrevisedjQuery(-width:title">tooltipSectiondesignsTurkishyounger.match(})(); + +burningoperatedegreessource=Richardcloselyplasticentries</tr> +color:#ul id="possessrollingphysicsfailingexecutecontestlink toDefault<br /> +: true,chartertourismclassicproceedexplain</h1> +online.?xml vehelpingdiamonduse theairlineend -->).attr(readershosting#ffffffrealizeVincentsignals src="/ProductdespitediversetellingPublic held inJoseph theatreaffects<style>a largedoesn'tlater, ElementfaviconcreatorHungaryAirportsee theso thatMichaelSystemsPrograms, and width=e"tradingleft"> +personsGolden Affairsgrammarformingdestroyidea ofcase ofoldest this is.src = cartoonregistrCommonsMuslimsWhat isin manymarkingrevealsIndeed,equally/show_aoutdoorescape(Austriageneticsystem,In the sittingHe alsoIslandsAcademy + <!--Daniel bindingblock">imposedutilizeAbraham(except{width:putting).html(|| []; +DATA[ *kitchenmountedactual dialectmainly _blank'installexpertsif(typeIt also© ">Termsborn inOptionseasterntalkingconcerngained ongoingjustifycriticsfactoryits ownassaultinvitedlastinghis ownhref="/" rel="developconcertdiagramdollarsclusterphp?id=alcohol);})();using a><span>vesselsrevivalAddressamateurandroidallegedillnesswalkingcentersqualifymatchesunifiedextinctDefensedied in + <!-- customslinkingLittle Book ofeveningmin.js?are thekontakttoday's.html" target=wearingAll Rig; +})();raising Also, crucialabout">declare--> +<scfirefoxas muchappliesindex, s, but type = + +<!--towardsRecordsPrivateForeignPremierchoicesVirtualreturnsCommentPoweredinline;povertychamberLiving volumesAnthonylogin" RelatedEconomyreachescuttinggravitylife inChapter-shadowNotable</td> + returnstadiumwidgetsvaryingtravelsheld bywho arework infacultyangularwho hadairporttown of + +Some 'click'chargeskeywordit willcity of(this);Andrew unique checkedor more300px; return;rsion="pluginswithin herselfStationFederalventurepublishsent totensionactresscome tofingersDuke ofpeople,exploitwhat isharmonya major":"httpin his menu"> +monthlyofficercouncilgainingeven inSummarydate ofloyaltyfitnessand wasemperorsupremeSecond hearingRussianlongestAlbertalateralset of small">.appenddo withfederalbank ofbeneathDespiteCapitalgrounds), and percentit fromclosingcontainInsteadfifteenas well.yahoo.respondfighterobscurereflectorganic= Math.editingonline paddinga wholeonerroryear ofend of barrierwhen itheader home ofresumedrenamedstrong>heatingretainscloudfrway of March 1knowingin partBetweenlessonsclosestvirtuallinks">crossedEND -->famous awardedLicenseHealth fairly wealthyminimalAfricancompetelabel">singingfarmersBrasil)discussreplaceGregoryfont copursuedappearsmake uproundedboth ofblockedsaw theofficescoloursif(docuwhen heenforcepush(fuAugust UTF-8">Fantasyin mostinjuredUsuallyfarmingclosureobject defenceuse of Medical<body> +evidentbe usedkeyCodesixteenIslamic#000000entire widely active (typeofone cancolor =speakerextendsPhysicsterrain<tbody>funeralviewingmiddle cricketprophetshifteddoctorsRussell targetcompactalgebrasocial-bulk ofman and</td> + he left).val()false);logicalbankinghome tonaming Arizonacredits); +}); +founderin turnCollinsbefore But thechargedTitle">CaptainspelledgoddessTag -->Adding:but wasRecent patientback in=false&Lincolnwe knowCounterJudaismscript altered']); + has theunclearEvent',both innot all + +<!-- placinghard to centersort ofclientsstreetsBernardassertstend tofantasydown inharbourFreedomjewelry/about..searchlegendsis mademodern only ononly toimage" linear painterand notrarely acronymdelivershorter00&as manywidth="/* <![Ctitle =of the lowest picked escapeduses ofpeoples PublicMatthewtacticsdamagedway forlaws ofeasy to windowstrong simple}catch(seventhinfoboxwent topaintedcitizenI don'tretreat. Some ww."); +bombingmailto:made in. Many carries||{};wiwork ofsynonymdefeatsfavoredopticalpageTraunless sendingleft"><comScorAll thejQuery.touristClassicfalse" Wilhelmsuburbsgenuinebishops.split(global followsbody ofnominalContactsecularleft tochiefly-hidden-banner</li> + +. When in bothdismissExplorealways via thespañolwelfareruling arrangecaptainhis sonrule ofhe tookitself,=0&(calledsamplesto makecom/pagMartin Kennedyacceptsfull ofhandledBesides//--></able totargetsessencehim to its by common.mineralto takeways tos.org/ladvisedpenaltysimple:if theyLettersa shortHerbertstrikes groups.lengthflightsoverlapslowly lesser social </p> + it intoranked rate oful> + attemptpair ofmake itKontaktAntoniohaving ratings activestreamstrapped").css(hostilelead tolittle groups,Picture--> + + rows=" objectinverse<footerCustomV><\/scrsolvingChamberslaverywoundedwhereas!= 'undfor allpartly -right:Arabianbacked centuryunit ofmobile-Europe,is homerisk ofdesiredClintoncost ofage of become none ofp"Middle ead')[0Criticsstudios>©group">assemblmaking pressedwidget.ps:" ? rebuiltby someFormer editorsdelayedCanonichad thepushingclass="but arepartialBabylonbottom carrierCommandits useAs withcoursesa thirddenotesalso inHouston20px;">accuseddouble goal ofFamous ).bind(priests Onlinein Julyst + "gconsultdecimalhelpfulrevivedis veryr'+'iptlosing femalesis alsostringsdays ofarrivalfuture <objectforcingString(" /> + here isencoded. The balloondone by/commonbgcolorlaw of Indianaavoidedbut the2px 3pxjquery.after apolicy.men andfooter-= true;for usescreen.Indian image =family,http://  driverseternalsame asnoticedviewers})(); + is moreseasonsformer the newis justconsent Searchwas thewhy theshippedbr><br>width: height=made ofcuisineis thata very Admiral fixed;normal MissionPress, ontariocharsettry to invaded="true"spacingis mosta more totallyfall of}); + immensetime inset outsatisfyto finddown tolot of Playersin Junequantumnot thetime todistantFinnishsrc = (single help ofGerman law andlabeledforestscookingspace">header-well asStanleybridges/globalCroatia About [0]; + it, andgroupedbeing a){throwhe madelighterethicalFFFFFF"bottom"like a employslive inas seenprintermost ofub-linkrejectsand useimage">succeedfeedingNuclearinformato helpWomen'sNeitherMexicanprotein<table by manyhealthylawsuitdevised.push({sellerssimply Through.cookie Image(older">us.js"> Since universlarger open to!-- endlies in']); + marketwho is ("DOMComanagedone fortypeof Kingdomprofitsproposeto showcenter;made itdressedwere inmixtureprecisearisingsrc = 'make a securedBaptistvoting + var March 2grew upClimate.removeskilledway the</head>face ofacting right">to workreduceshas haderectedshow();action=book ofan area== "htt<header +<html>conformfacing cookie.rely onhosted .customhe wentbut forspread Family a meansout theforums.footage">MobilClements" id="as highintense--><!--female is seenimpliedset thea stateand hisfastestbesidesbutton_bounded"><img Infoboxevents,a youngand areNative cheaperTimeoutand hasengineswon the(mostlyright: find a -bottomPrince area ofmore ofsearch_nature,legallyperiod,land ofor withinducedprovingmissilelocallyAgainstthe wayk"px;"> +pushed abandonnumeralCertainIn thismore inor somename isand, incrownedISBN 0-createsOctobermay notcenter late inDefenceenactedwish tobroadlycoolingonload=it. TherecoverMembersheight assumes<html> +people.in one =windowfooter_a good reklamaothers,to this_cookiepanel">London,definescrushedbaptismcoastalstatus title" move tolost inbetter impliesrivalryservers SystemPerhapses and contendflowinglasted rise inGenesisview ofrising seem tobut in backinghe willgiven agiving cities.flow of Later all butHighwayonly bysign ofhe doesdiffersbattery&lasinglesthreatsintegertake onrefusedcalled =US&See thenativesby thissystem.head of:hover,lesbiansurnameand allcommon/header__paramsHarvard/pixel.removalso longrole ofjointlyskyscraUnicodebr /> +AtlantanucleusCounty,purely count">easily build aonclicka givenpointerh"events else { +ditionsnow the, with man whoorg/Webone andcavalryHe diedseattle00,000 {windowhave toif(windand itssolely m"renewedDetroitamongsteither them inSenatorUs</a><King ofFrancis-produche usedart andhim andused byscoringat hometo haverelatesibilityfactionBuffalolink"><what hefree toCity ofcome insectorscountedone daynervoussquare };if(goin whatimg" alis onlysearch/tuesdaylooselySolomonsexual - <a hrmedium"DO NOT France,with a war andsecond take a > + + +market.highwaydone inctivity"last">obligedrise to"undefimade to Early praisedin its for hisathleteJupiterYahoo! termed so manyreally s. The a woman?value=direct right" bicycleacing="day andstatingRather,higher Office are nowtimes, when a pay foron this-link">;borderaround annual the Newput the.com" takin toa brief(in thegroups.; widthenzymessimple in late{returntherapya pointbanninginks"> +();" rea place\u003Caabout atr> + ccount gives a<SCRIPTRailwaythemes/toolboxById("xhumans,watchesin some if (wicoming formats Under but hashanded made bythan infear ofdenoted/iframeleft involtagein eacha"base ofIn manyundergoregimesaction </p> +<ustomVa;></importsor thatmostly &re size="</a></ha classpassiveHost = WhetherfertileVarious=[];(fucameras/></td>acts asIn some> + +<!organis <br />Beijingcatalàdeutscheuropeueuskaragaeilgesvenskaespañamensajeusuariotrabajoméxicopáginasiempresistemaoctubreduranteañadirempresamomentonuestroprimeratravésgraciasnuestraprocesoestadoscalidadpersonanúmeroacuerdomúsicamiembroofertasalgunospaísesejemploderechoademásprivadoagregarenlacesposiblehotelessevillaprimeroúltimoeventosarchivoculturamujeresentradaanuncioembargomercadograndesestudiomejoresfebrerodiseñoturismocódigoportadaespaciofamiliaantoniopermiteguardaralgunaspreciosalguiensentidovisitastítuloconocersegundoconsejofranciaminutossegundatenemosefectosmálagasesiónrevistagranadacompraringresogarcíaacciónecuadorquienesinclusodeberámateriahombresmuestrapodríamañanaúltimaestamosoficialtambienningúnsaludospodemosmejorarpositionbusinesshomepagesecuritylanguagestandardcampaignfeaturescategoryexternalchildrenreservedresearchexchangefavoritetemplatemilitaryindustryservicesmaterialproductsz-index:commentssoftwarecompletecalendarplatformarticlesrequiredmovementquestionbuildingpoliticspossiblereligionphysicalfeedbackregisterpicturesdisabledprotocolaudiencesettingsactivityelementslearninganythingabstractprogressoverviewmagazineeconomictrainingpressurevarious <strong>propertyshoppingtogetheradvancedbehaviordownloadfeaturedfootballselectedLanguagedistanceremembertrackingpasswordmodifiedstudentsdirectlyfightingnortherndatabasefestivalbreakinglocationinternetdropdownpracticeevidencefunctionmarriageresponseproblemsnegativeprogramsanalysisreleasedbanner">purchasepoliciesregionalcreativeargumentbookmarkreferrerchemicaldivisioncallbackseparateprojectsconflicthardwareinterestdeliverymountainobtained= false;for(var acceptedcapacitycomputeridentityaircraftemployedproposeddomesticincludesprovidedhospitalverticalcollapseapproachpartnerslogo"><adaughterauthor" culturalfamilies/images/assemblypowerfulteachingfinisheddistrictcriticalcgi-bin/purposesrequireselectionbecomingprovidesacademicexerciseactuallymedicineconstantaccidentMagazinedocumentstartingbottom">observed: "extendedpreviousSoftwarecustomerdecisionstrengthdetailedslightlyplanningtextareacurrencyeveryonestraighttransferpositiveproducedheritageshippingabsolutereceivedrelevantbutton" violenceanywherebenefitslaunchedrecentlyalliancefollowedmultiplebulletinincludedoccurredinternal$(this).republic><tr><tdcongressrecordedultimatesolution<ul id="discoverHome</a>websitesnetworksalthoughentirelymemorialmessagescontinueactive">somewhatvictoriaWestern title="LocationcontractvisitorsDownloadwithout right"> +measureswidth = variableinvolvedvirginianormallyhappenedaccountsstandingnationalRegisterpreparedcontrolsaccuratebirthdaystrategyofficialgraphicscriminalpossiblyconsumerPersonalspeakingvalidateachieved.jpg" />machines</h2> + keywordsfriendlybrotherscombinedoriginalcomposedexpectedadequatepakistanfollow" valuable</label>relativebringingincreasegovernorplugins/List of Header">" name=" ("graduate</head> +commercemalaysiadirectormaintain;height:schedulechangingback to catholicpatternscolor: #greatestsuppliesreliable</ul> + <select citizensclothingwatching<li id="specificcarryingsentence<center>contrastthinkingcatch(e)southernMichael merchantcarouselpadding:interior.split("lizationOctober ){returnimproved--> + +coveragechairman.png" />subjectsRichard whateverprobablyrecoverybaseballjudgmentconnect..css" /> websitereporteddefault"/></a> +electricscotlandcreationquantity. ISBN 0did not instance-search-" lang="speakersComputercontainsarchivesministerreactiondiscountItalianocriteriastrongly: 'http:'script'coveringofferingappearedBritish identifyFacebooknumerousvehiclesconcernsAmericanhandlingdiv id="William provider_contentaccuracysection andersonflexibleCategorylawrence<script>layout="approved maximumheader"></table>Serviceshamiltoncurrent canadianchannels/themes//articleoptionalportugalvalue=""intervalwirelessentitledagenciesSearch" measuredthousandspending…new Date" size="pageNamemiddle" " /></a>hidden">sequencepersonaloverflowopinionsillinoislinks"> + <title>versionssaturdayterminalitempropengineersectionsdesignerproposal="false"Españolreleasessubmit" er"additionsymptomsorientedresourceright"><pleasurestationshistory.leaving border=contentscenter">. + +Some directedsuitablebulgaria.show();designedGeneral conceptsExampleswilliamsOriginal"><span>search">operatorrequestsa "allowingDocumentrevision. + +The yourselfContact michiganEnglish columbiapriorityprintingdrinkingfacilityreturnedContent officersRussian generate-8859-1"indicatefamiliar qualitymargin:0 contentviewportcontacts-title">portable.length eligibleinvolvesatlanticonload="default.suppliedpaymentsglossary + +After guidance</td><tdencodingmiddle">came to displaysscottishjonathanmajoritywidgets.clinicalthailandteachers<head> + affectedsupportspointer;toString</small>oklahomawill be investor0" alt="holidaysResourcelicensed (which . After considervisitingexplorerprimary search" android"quickly meetingsestimate;return ;color:# height=approval, " checked.min.js"magnetic></a></hforecast. While thursdaydvertiseéhasClassevaluateorderingexistingpatients Online coloradoOptions"campbell<!-- end</span><<br /> +_popups|sciences," quality Windows assignedheight: <b classle" value=" Companyexamples<iframe believespresentsmarshallpart of properly). + +The taxonomymuch of </span> +" data-srtuguêsscrollTo project<head> +attorneyemphasissponsorsfancyboxworld's wildlifechecked=sessionsprogrammpx;font- Projectjournalsbelievedvacationthompsonlightingand the special border=0checking</tbody><button Completeclearfix +<head> +article <sectionfindingsrole in popular Octoberwebsite exposureused to changesoperatedclickingenteringcommandsinformed numbers </div>creatingonSubmitmarylandcollegesanalyticlistingscontact.loggedInadvisorysiblingscontent"s")s. This packagescheckboxsuggestspregnanttomorrowspacing=icon.pngjapanesecodebasebutton">gamblingsuch as , while </span> missourisportingtop:1px .</span>tensionswidth="2lazyloadnovemberused in height="cript"> + </<tr><td height:2/productcountry include footer" <!-- title"></jquery.</form> +(简体)(ç¹é«”)hrvatskiitalianoromânătürkçeاردوtambiénnoticiasmensajespersonasderechosnacionalserviciocontactousuariosprogramagobiernoempresasanunciosvalenciacolombiadespuésdeportesproyectoproductopúbliconosotroshistoriapresentemillonesmediantepreguntaanteriorrecursosproblemasantiagonuestrosopiniónimprimirmientrasaméricavendedorsociedadrespectorealizarregistropalabrasinterésentoncesespecialmiembrosrealidadcórdobazaragozapáginassocialesbloqueargestiónalquilersistemascienciascompletoversióncompletaestudiospúblicaobjetivoalicantebuscadorcantidadentradasaccionesarchivossuperiormayoríaalemaniafunciónúltimoshaciendoaquellosediciónfernandoambientefacebooknuestrasclientesprocesosbastantepresentareportarcongresopublicarcomerciocontratojóvenesdistritotécnicaconjuntoenergíatrabajarasturiasrecienteutilizarboletínsalvadorcorrectatrabajosprimerosnegocioslibertaddetallespantallapróximoalmeríaanimalesquiénescorazónsecciónbuscandoopcionesexteriorconceptotodavíagaleríaescribirmedicinalicenciaconsultaaspectoscríticadólaresjusticiadeberánperíodonecesitamantenerpequeñorecibidatribunaltenerifecancióncanariasdescargadiversosmallorcarequieretécnicodeberíaviviendafinanzasadelantefuncionaconsejosdifícilciudadesantiguasavanzadatérminounidadessánchezcampañasoftonicrevistascontienesectoresmomentosfacultadcréditodiversassupuestofactoressegundospequeñaгодаеÑлиеÑтьбылобытьÑтомЕÑлитогоменÑвÑехÑтойдажебылигодуденьÑтотбылаÑебÑодинÑебенадоÑайтфотонегоÑвоиÑвойигрытожевÑемÑвоюлишьÑтихпокаднейдомамиралиботемухотÑдвухÑетилюдиделомиретебÑÑвоевидечегоÑтимÑчеттемыценыÑталведьтемеводытебевышенамитипатомуправлицаоднагодызнаюмогудругвÑейидеткиноодноделаделеÑрокиюнÑвеÑьЕÑÑ‚ÑŒÑ€Ð°Ð·Ð°Ð½Ð°ÑˆÐ¸Ø§Ù„Ù„Ù‡Ø§Ù„ØªÙŠØ¬Ù…ÙŠØ¹Ø®Ø§ØµØ©Ø§Ù„Ø°ÙŠØ¹Ù„ÙŠÙ‡Ø¬Ø¯ÙŠØ¯Ø§Ù„Ø¢Ù†Ø§Ù„Ø±Ø¯ØªØ­ÙƒÙ…ØµÙØ­Ø©ÙƒØ§Ù†ØªØ§Ù„لييكونشبكةÙيهابناتحواءأكثرخلالالحبدليلدروساضغطتكونهناكساحةناديالطبعليكشكرايمكنمنهاشركةرئيسنشيطماذاالÙÙ†Ø´Ø¨Ø§Ø¨ØªØ¹Ø¨Ø±Ø±Ø­Ù…Ø©ÙƒØ§ÙØ©ÙŠÙ‚ÙˆÙ„Ù…Ø±ÙƒØ²ÙƒÙ„Ù…Ø©Ø£Ø­Ù…Ø¯Ù‚Ù„Ø¨ÙŠÙŠØ¹Ù†ÙŠØµÙˆØ±Ø©Ø·Ø±ÙŠÙ‚Ø´Ø§Ø±ÙƒØ¬ÙˆØ§Ù„Ø£Ø®Ø±Ù‰Ù…Ø¹Ù†Ø§Ø§Ø¨Ø­Ø«Ø¹Ø±ÙˆØ¶Ø¨Ø´ÙƒÙ„Ù…Ø³Ø¬Ù„Ø¨Ù†Ø§Ù†Ø®Ø§Ù„Ø¯ÙƒØªØ§Ø¨ÙƒÙ„ÙŠØ©Ø¨Ø¯ÙˆÙ†Ø£ÙŠØ¶Ø§ÙŠÙˆØ¬Ø¯ÙØ±ÙŠÙ‚ÙƒØªØ¨ØªØ£ÙØ¶Ù„Ù…Ø·Ø¨Ø®Ø§ÙƒØ«Ø±Ø¨Ø§Ø±ÙƒØ§ÙØ¶Ù„Ø§Ø­Ù„Ù‰Ù†ÙØ³Ù‡Ø£ÙŠØ§Ù…ردودأنهاديناالانمعرضتعلمداخلممكن���������������������� +  + ÿÿÿÿ��������ÿÿÿÿ������������������ÿÿ������ÿÿ����������������resourcescountriesquestionsequipmentcommunityavailablehighlightDTD/xhtmlmarketingknowledgesomethingcontainerdirectionsubscribeadvertisecharacter" value="</select>Australia" class="situationauthorityfollowingprimarilyoperationchallengedevelopedanonymousfunction functionscompaniesstructureagreement" title="potentialeducationargumentssecondarycopyrightlanguagesexclusivecondition</form> +statementattentionBiography} else { +solutionswhen the Analyticstemplatesdangeroussatellitedocumentspublisherimportantprototypeinfluence»</effectivegenerallytransformbeautifultransportorganizedpublishedprominentuntil thethumbnailNational .focus();over the migrationannouncedfooter"> +exceptionless thanexpensiveformationframeworkterritoryndicationcurrentlyclassNamecriticismtraditionelsewhereAlexanderappointedmaterialsbroadcastmentionedaffiliate</option>treatmentdifferent/default.Presidentonclick="biographyotherwisepermanentFrançaisHollywoodexpansionstandards</style> +reductionDecember preferredCambridgeopponentsBusiness confusion> +<title>presentedexplaineddoes not worldwideinterfacepositionsnewspaper</table> +mountainslike the essentialfinancialselectionaction="/abandonedEducationparseInt(stabilityunable to +relationsNote thatefficientperformedtwo yearsSince thethereforewrapper">alternateincreasedBattle ofperceivedtrying tonecessaryportrayedelectionsElizabethdiscoveryinsurances.length;legendaryGeographycandidatecorporatesometimesservices.inheritedCommunityreligiouslocationsCommitteebuildingsthe worldno longerbeginningreferencecannot befrequencytypicallyinto the relative;recordingpresidentinitiallytechniquethe otherit can beexistenceunderlinethis timetelephoneitemscopepracticesadvantage);return For otherprovidingdemocracyboth the extensivesufferingsupportedcomputers functionpracticalsaid thatit may beEnglish +suspectedmargin: 0spiritual + +microsoftgraduallydiscussedhe becameexecutivejquery.jshouseholdconfirmedpurchasedliterallydestroyedup to thevariationremainingit is notcenturiesJapanese among thecompletedalgorithminterestsrebellionundefinedencourageresizableinvolvingsensitiveuniversalprovision(althoughfeaturingconducted), which continued-header">February numerous overflow:componentfragmentsexcellentcolspan="technicalnear the Advanced source ofexpressedHong Kong Facebookmultiple mechanismelevationoffensive + sponsoreddocument.or "there arethose whomovementsprocessesdifficultsubmittedrecommendconvincedpromoting" width=".replace(classicalcoalitionhis firstdecisionsassistantindicatedevolution-wrapper"enough toalong thedelivered--> + + +
Archbishop class="nobeing usedapproachesprivilegesnoscript> +results inmay be theEaster eggmechanismsreasonablePopulationCollectionselected">noscript> /index.phparrival of-jssdk'));managed toincompletecasualtiescompletionChristiansSeptember arithmeticproceduresmight haveProductionit appearsPhilosophyfriendshipleading togiving thetoward theguaranteeddocumentedcolor:#000video gamecommissionreflectingchange theassociatedsans-serifonkeypress; padding:He was theunderlyingtypically , and the srcElementsuccessivesince the should be networkingaccountinguse of thelower thanshows that + complaintscontinuousquantitiesastronomerhe did notdue to itsapplied toan averageefforts tothe futureattempt toTherefore,capabilityRepublicanwas formedElectronickilometerschallengespublishingthe formerindigenousdirectionssubsidiaryconspiracydetails ofand in theaffordablesubstancesreason forconventionitemtype="absolutelysupposedlyremained aattractivetravellingseparatelyfocuses onelementaryapplicablefound thatstylesheetmanuscriptstands for no-repeat(sometimesCommercialin Americaundertakenquarter ofan examplepersonallyindex.php? +percentagebest-knowncreating a" dir="ltrLieutenant +
is said tostructuralreferendummost oftena separate-> +
implementedcan be seenthere was ademonstratecontainer">connectionsthe Britishwas written!important;px; margin-followed byability to complicatedduring the immigrationalso called

as follows:merged withthrough thecommercial pointed outopportunityview of therequirementdivision ofprogramminghe receivedsetInterval">maintainingChristopherMuch of thewritings of" height="2size of theversion of mixture of between theExamples ofeducationalcompetitive onsubmit="director ofdistinctive/DTD XHTML relating totendency toprovince ofwhich woulddespite thescientific legislature.innerHTML allegationsAgriculturewas used inapproach tointelligentyears later,sans-serifdeterminingPerformanceappearances, which is foundationsabbreviatedhigher thans from the individual composed ofsupposed toclaims thatattributionfont-size:1elements ofHistorical his brotherat the timeanniversarygoverned byrelated to ultimately innovationsit is stillcan only bedefinitionstoGMTStringA number ofimg class="Eventually,was changedoccurred inneighboringdistinguishwhen he wasintroducingterrestrialMany of theargues thatan Americanconquest ofwidespread were killedscreen and In order toexpected todescendantsare locatedlegislativegenerations backgroundmost peopleyears afterthere is nothe highestfrequently they do notargued thatshowed thatpredominanttheologicalby the timeconsideringshort-livedcan be usedvery littleone of the had alreadyinterpretedcommunicatefeatures ofgovernment,entered the" height="3Independentpopulationslarge-scale. Although used in thedestructionpossibilitystarting intwo or moreexpressionssubordinatelarger thanhistory and +Continentaleliminatingwill not bepractice ofin front ofsite of theensure thatto create amississippipotentiallyoutstandingbetter thanwhat is nowsituated inmeta name="TraditionalsuggestionsTranslationthe form ofatmosphericideologicalenterprisescalculatingeast of theremnants ofpluginspage/index.php?remained intransformedHe was alsowas alreadystatisticalin favor ofMinistry ofmovement offormulationis required +question ofwas electedto become abecause of some peopleinspired bysuccessful a time whenmore commonamongst thean officialwidth:100%;technology,was adoptedto keep thesettlementslive birthsindex.html"Connecticutassigned to&times;account foralign=rightthe companyalways beenreturned toinvolvementBecause thethis period" name="q" confined toa result ofvalue="" />is actuallyEnvironment + +Conversely,> +
this is notthe presentif they areand finallya matter of +
+ +faster thanmajority ofafter whichcomparativeto maintainimprove theawarded theer" class="frameborderrestorationin the sameanalysis oftheir firstDuring the continentalsequence offunction(){font-size: work on the +adopted theproperty ofdirected byeffectivelywas broughtchildren ofProgramminglonger thanmanuscriptswar againstby means ofand most ofsimilar to proprietaryoriginatingprestigiousgrammaticalexperience.to make theIt was alsois found incompetitorsin the U.S.replace thebrought thecalculationfall of thethe generalpracticallyin honor ofreleased inresidentialand some ofking of thereaction to1st Earl ofculture andprincipally + they can beback to thesome of hisexposure toare similarform of theaddFavoritecitizenshippart in thepeople within practiceto continue&minus;approved by the first allowed theand for thefunctioningplaying thesolution toheight="0" in his bookmore than afollows thecreated thepresence in nationalistthe idea ofa characterwere forced class="btndays of thefeatured inshowing theinterest inin place ofturn of thethe head ofLord of thepoliticallyhas its ownEducationalapproval ofsome of theeach other,behavior ofand becauseand anotherappeared onrecorded inblack"may includethe world'scan lead torefers to aborder="0" government winning theresulted in while the Washington,the subjectcity in the>

+ reflect theto completebecame moreradioactiverejected bywithout anyhis father,which couldcopy of theto indicatea politicalaccounts ofconstitutesworked witherof his lifeaccompaniedclientWidthprevent theLegislativedifferentlytogether inhas severalfor anothertext of thefounded thee with the is used forchanged theusually theplace wherewhereas the> The currentthe site ofsubstantialexperience,in the Westthey shouldslovenÄinacomentariosuniversidadcondicionesactividadesexperienciatecnologíaproducciónpuntuaciónaplicacióncontraseñacategoríasregistrarseprofesionaltratamientoregístratesecretaríaprincipalesprotecciónimportantesimportanciaposibilidadinteresantecrecimientonecesidadessuscribirseasociacióndisponiblesevaluaciónestudiantesresponsableresoluciónguadalajararegistradosoportunidadcomercialesfotografíaautoridadesingenieríatelevisióncompetenciaoperacionesestablecidosimplementeactualmentenavegaciónconformidadline-height:font-family:" : "http://applicationslink" href="specifically// +/index.html"window.open( !important;application/independence//www.googleorganizationautocompleterequirementsconservative
most notably/>
notification'undefined')Furthermore,believe thatinnerHTML = prior to thedramaticallyreferring tonegotiationsheadquartersSouth AfricaunsuccessfulPennsylvaniaAs a result, +
English (US)appendChild(transmissions. However, intelligence" tabindex="float:right;Commonwealthranging fromin which theat least onereproductionencyclopedia;font-size:1jurisdictionat that time">compensationchampionshipmedia="all" violation ofreference toreturn true;Strict//EN" transactionsinterventionverificationInformation difficultiesChampionshipcapabilities} + +Christianityfor example,Professionalrestrictionssuggest thatwas released(such as theremoveClass(unemploymentthe Americanstructure of/index.html published inspan class=""> + +f (document.border: 1px {font-size:1treatment of0" height="1modificationIndependencedivided intogreater thanachievementsestablishingJavaScript" neverthelesssignificanceBroadcasting> container"> +such as the influence ofa particularsrc='http://navigation" half of the substantial  advantage ofdiscovery offundamental metropolitanthe opposite" xml:lang="deliberatelyalign=centerevolution ofpreservationimprovementsbeginning inJesus ChristPublicationsdisagreementtext-align:r, function()similaritiesbody>is currentlyalphabeticalis sometimestype="image/many of the flow:hidden;available indescribe theexistence ofall over thethe Internet
    + +an effort toincrease theto the southspacing="0">sufficientlythe Europeanconverted toclearTimeoutdid not haveconsequentlyfor the nextextension ofeconomic andalthough theare producedand with theinsufficientgiven by thestating thatexpenditures +thought thaton the basiscellpadding=image of thereturning toinformation,separated byassassinateds" content="authority ofnorthwestern +
    + consultationcommunity ofthe nationalit should beparticipants align="leftthe greatestselection ofsupernaturaldependent onis mentionedallowing thewas inventedaccompanyinghis personalavailable atstudy of theon the otherexecution ofHuman Rightsterms of theassociationsresearch andsucceeded bydefeated theand from thebut they arecommander ofstate of theyears of agethe study of
      Roman Empireequal to theIn contrast,however, andis typicallyand his wife(also called> + +philosophicallocation.hrefwas publishedSan Francisco(function(){ +
      has been usedreturn to thealthough thischange in theseveral otherbut there areunprecedentedis similar toespecially inweight: bold;is called thecomputationalindicate thatrestricted to
      +
      large part ofInstitute forthe so-called against the In this case,was appointedclaimed to beHowever, thisDepartment ofthe remainingeffect on theparticularly deal with the +
      the structure />
      Many of thesecaused by theof the Unitedspan class="mcan be tracedis related tobecame one ofis frequentlyliving in thetheoreticallyFollowing theRevolutionarygovernment inis determinedthe politicalintroduced insufficient todescription">short storiesseparation ofas to whetherknown for itswas initiallydisplay:blockis an examplethe principalconsists of arecognized as/body>a substantialreconstructedhead of stateresistance toundergraduateThere are twogravitationalare describedintentionallyserved as theclass="headeropposition tofundamentallydominated theand the otheralliance withwas forced torespectively,and politicalin support ofpeople in the20th century.and publishedloadChartbeatto understandmember statesenvironmentalfirst half ofcountries andarchitecturalbe consideredcharacterizedclearIntervalauthoritativeFederation ofwas succeededand there area consequencethe Presidentalso includedfree softwaresuccession ofdeveloped thewas destroyedaway from the; + +
      +=http%3A%2F%2F +.setAttribute(Administration= new Array(); +display:block;Unfortunately,"> 
      /favicon.ico">='stylesheet' identification, for example,
    • +type="submit" +(function() {recommendationform action="/transformationreconstruction.style.display According to hidden" name="along with thedocument.body.approximately Communicationspost" action="meaning "--Prime Ministercharacteristic + +depends on theUniversity of in contrast to placeholder="in the case ofinternational constitutionalstyle="border-: function() {Because of the-strict.dtd"> +combination of marginwidth="createElement(w.attachEvent(src="https://aIn particular, align="left" Czech RepublicUnited Kingdomcorrespondenceconcluded that.html" title="(function () {comes from theapplication offounder of theattempting to carbon dioxide + +
      +opportunity tocommunications +
      + +Department of ecclesiasticalthere has beenresulting fromhas never beenthe first timein response toautomatically + +
      collection of descended fromsection of theaccept-charsetto be confusedmember of the padding-right:translation ofinterpretation href='http://whether or notThere are alsothere are manya small numberother parts ofimpossible to class="buttonlocated in the. However, theand eventuallyAt the end of because of itsrepresents themany countriesfor many yearsearliest knownbecause it waspt"> valign="top" inhabitants offollowing year +
      + + +style="margin-instead of theintroduced thethe process ofincreasing thedifferences inestimated thatespecially the/div>
      class="footerand especiallytype="button" which included> +media="screen"
      /page> + +
      the United States + + + " action="http:// +
      + +beginning of the revealed that thetelevision series" rel="nofollow"> target="_blank">claiming that thehttp%3A%2F%2Fwww.manifestations ofPrime Minister ofinfluenced by theclass="clearfix">/div> + + +three-dimensionalChurch of Englandof North Carolinasquare kilometres.addEventListenerdistinct from thecommonly known asPhonetic Alphabetdeclared that thecontrolled by theBenjamin Franklinrole-playing gamethe University ofin Western Europepersonal computerProject Gutenbergregardless of thehas been proposedtogether with the>
    • of the populationofficial language +the InternationalAccording to the pe="text/css" /> +coincide with thetwo-thirds of theDuring this time,during the periodannounced that hethe internationaland more recentlybelieved that theconsciousness andformerly known assurrounded by thefirst appeared inoccasionally usedposition:absolute;" target="_blank" position:relative;text-align:center;jax/libs/jquery/1.background-color:#type="application/anguage" content=" + +
      +distinction between/" target="_blank"> +w.addEventListener?action="http://www.icon" href="http:// style="background:type="text/css" /> +meta property="og:t + + + + + +
      +
      type="text/css" /> +interchangeably withmore closely relatedsocial and politicalthat would otherwiseperpendicular to thestyle type="text/csstype="submit" name="families residing indeveloping countriescomputer programmingeconomic developmentdetermination of thefor more informationon several occasionsportuguês (Europeu)УкраїнÑькаукраїнÑькаРоÑÑийÑкойматериаловинформацииуправлениÑнеобходимоинформациÑИнформациÑРеÑпубликиколичеÑтвоинформациютерриториидоÑтаточноالمتواجدونالاشتراكاتالاقتراحاتhtml; charset=UTF-8" setTimeout(function()display:inline-block; # [4.0.0](https://github.com/yargs/y18n/compare/v3.2.1...v4.0.0) (2017-10-10) diff --git a/deps/npm/node_modules/y18n/index.js b/deps/npm/node_modules/y18n/index.js index d72068162876a4cba2368060e445c763bf372770..727362aac0664d8a54d9a41cb21e331c168fc2d3 100644 --- a/deps/npm/node_modules/y18n/index.js +++ b/deps/npm/node_modules/y18n/index.js @@ -11,7 +11,7 @@ function Y18N (opts) { this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true // internal stuff. - this.cache = {} + this.cache = Object.create(null) this.writeQueue = [] } diff --git a/deps/npm/node_modules/y18n/package.json b/deps/npm/node_modules/y18n/package.json index 24016e224a737b07164af6d1b746da21f77392b0..a8bab2cc194f8eaf3836590e545e721e0a3a2db8 100644 --- a/deps/npm/node_modules/y18n/package.json +++ b/deps/npm/node_modules/y18n/package.json @@ -1,30 +1,32 @@ { - "_from": "y18n@^4.0.0", - "_id": "y18n@4.0.0", + "_from": "y18n@4.0.1", + "_id": "y18n@4.0.1", "_inBundle": false, - "_integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "_integrity": "sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ==", "_location": "/y18n", "_phantomChildren": {}, "_requested": { - "type": "range", + "type": "version", "registry": true, - "raw": "y18n@^4.0.0", + "raw": "y18n@4.0.1", "name": "y18n", "escapedName": "y18n", - "rawSpec": "^4.0.0", + "rawSpec": "4.0.1", "saveSpec": null, - "fetchSpec": "^4.0.0" + "fetchSpec": "4.0.1" }, "_requiredBy": [ + "#USER", + "/", "/cacache", "/libnpx", - "/npm-profile/cacache", - "/npm-registry-fetch/cacache" + "/nyc/yargs", + "/yargs" ], - "_resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", - "_shasum": "95ef94f85ecc81d007c264e190a120f0a3c8566b", - "_spec": "y18n@^4.0.0", - "_where": "/Users/rebecca/code/npm/node_modules/cacache", + "_resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.1.tgz", + "_shasum": "8db2b83c31c5d75099bb890b23f3094891e247d4", + "_spec": "y18n@4.0.1", + "_where": "/Users/ruyadorno/Documents/workspace/cli-release/cli", "author": { "name": "Ben Coe", "email": "ben@npmjs.com" @@ -66,5 +68,5 @@ "release": "standard-version", "test": "nyc mocha" }, - "version": "4.0.0" + "version": "4.0.1" } diff --git a/deps/npm/package.json b/deps/npm/package.json index fdbb33e23cd53c9caff45b1950571a22fb905c42..f04a4c14ec677f06a48c84bbacb59099170f6573 100644 --- a/deps/npm/package.json +++ b/deps/npm/package.json @@ -1,5 +1,5 @@ { - "version": "6.14.11", + "version": "6.14.15", "name": "npm", "description": "a package manager for JavaScript", "keywords": [ @@ -63,7 +63,7 @@ "glob": "^7.1.6", "graceful-fs": "^4.2.4", "has-unicode": "~2.0.1", - "hosted-git-info": "^2.8.8", + "hosted-git-info": "^2.8.9", "iferr": "^1.0.2", "infer-owner": "^1.0.4", "inflight": "~1.0.6", @@ -132,9 +132,9 @@ "slide": "~1.1.6", "sorted-object": "~2.0.1", "sorted-union-stream": "~2.1.3", - "ssri": "^6.0.1", + "ssri": "^6.0.2", "stringify-package": "^1.0.1", - "tar": "^4.4.13", + "tar": "^4.4.19", "text-table": "~0.2.0", "tiny-relative-date": "^1.3.0", "uid-number": "0.0.6", diff --git a/deps/npm/test/fixtures/forked-underscore-1.5.1.tgz b/deps/npm/test/fixtures/forked-underscore-1.5.1.tgz index afc38bc11e1a8af12bf6792c1e3a2ecf6937aa23..5aca6247ac395de449e8dd6bc758591aff21a0b5 100644 Binary files a/deps/npm/test/fixtures/forked-underscore-1.5.1.tgz and b/deps/npm/test/fixtures/forked-underscore-1.5.1.tgz differ diff --git a/deps/npm/test/fixtures/gitignore-and-npmignore.tgz b/deps/npm/test/fixtures/gitignore-and-npmignore.tgz index 56c522724d93e9e8080448ffa0a2751edcff82dd..4be4364104f570e282888cc7b321d212a29d0002 100644 Binary files a/deps/npm/test/fixtures/gitignore-and-npmignore.tgz and b/deps/npm/test/fixtures/gitignore-and-npmignore.tgz differ diff --git a/deps/npm/test/fixtures/gitignore.tgz b/deps/npm/test/fixtures/gitignore.tgz index 21957c53852ad617a913d71b7a1d624cee101b23..7f5f2d71bfa9fb24a82b037851b409a5f97746eb 100644 Binary files a/deps/npm/test/fixtures/gitignore.tgz and b/deps/npm/test/fixtures/gitignore.tgz differ diff --git a/deps/npm/test/fixtures/npmignore.tgz b/deps/npm/test/fixtures/npmignore.tgz index c72385a0a1e5b3fa6d1951560d55615144c9f8f3..765593decb0a7be1b2c9965e4f542d539d1979ba 100644 Binary files a/deps/npm/test/fixtures/npmignore.tgz and b/deps/npm/test/fixtures/npmignore.tgz differ diff --git a/deps/npm/test/fixtures/scoped-underscore-1.3.1.tgz b/deps/npm/test/fixtures/scoped-underscore-1.3.1.tgz index 0ab2c68009b0a858df288efe89a9b5411a5f268b..d98a345996b5b4eb6aaa9f82233f0b1f9ef503eb 100644 Binary files a/deps/npm/test/fixtures/scoped-underscore-1.3.1.tgz and b/deps/npm/test/fixtures/scoped-underscore-1.3.1.tgz differ diff --git a/deps/npm/test/tap/git-npmignore.js b/deps/npm/test/tap/git-npmignore.js index 2ab7db7304f0f3ef87bc9a66363258f692462cf6..ba022b69892d6d8ef1f4c63313e0a63cf3d45762 100644 --- a/deps/npm/test/tap/git-npmignore.js +++ b/deps/npm/test/tap/git-npmignore.js @@ -7,6 +7,7 @@ var rimraf = require('rimraf') var test = require('tap').test var which = require('which') +var GITHUB_ACTIONS = process.env.GITHUB_ACTIONS var common = require('../common-tap.js') var escapeArg = require('../../lib/utils/escape-arg.js') var Tacks = require('tacks') @@ -151,8 +152,9 @@ function setup (cb) { if (er) return cb(er) var git = escapeArg(gitPath) + var extraOpts = GITHUB_ACTIONS ? ' --initial-branch=main' : '' - exec(git + ' init', {cwd: dep}, init) + exec(git + ' init' + extraOpts, {cwd: dep}, init) function init (er, _, stderr) { if (er) return cb(er) diff --git a/deps/zlib/contrib/bench/OWNERS b/deps/zlib/contrib/bench/OWNERS deleted file mode 100644 index f1e3d4f472e484beff933c658272c099486d14ff..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/bench/OWNERS +++ /dev/null @@ -1 +0,0 @@ -noel@chromium.org diff --git a/deps/zlib/contrib/bench/zlib_bench.cc b/deps/zlib/contrib/bench/zlib_bench.cc deleted file mode 100644 index 5dcdef09f36b769001f4302a7402785a37d89f37..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/bench/zlib_bench.cc +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright 2018 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the Chromium source repository LICENSE file. - * - * A benchmark test harness for measuring decoding performance of gzip or zlib - * (deflate) encoded compressed data. Given a file containing any data, encode - * (compress) it into gzip or zlib format and then decode (uncompress). Output - * the median and maximum encoding and decoding rates in MB/s. - * - * Raw deflate (no gzip or zlib stream wrapper) mode is also supported. Select - * it with the [raw] argument. Use the [gzip] [zlib] arguments to select those - * stream wrappers. - * - * Note this code can be compiled outside of the Chromium build system against - * the system zlib (-lz) with g++ or clang++ as follows: - * - * g++|clang++ -O3 -Wall -std=c++11 -lstdc++ -lz zlib_bench.cc - */ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "zlib.h" - -void error_exit(const char* error, int code) { - fprintf(stderr, "%s (%d)\n", error, code); - exit(code); -} - -inline char* string_data(std::string* s) { - return s->empty() ? 0 : &*s->begin(); -} - -struct Data { - Data(size_t s) { data.reset(new (std::nothrow) char[size = s]); } - std::unique_ptr data; - size_t size; -}; - -Data read_file_data_or_exit(const char* name) { - std::ifstream file(name, std::ios::in | std::ios::binary); - if (!file) { - perror(name); - exit(1); - } - - file.seekg(0, std::ios::end); - Data data(file.tellg()); - file.seekg(0, std::ios::beg); - - if (file && data.data) - file.read(data.data.get(), data.size); - - if (!file || !data.data || !data.size) { - perror((std::string("failed: reading ") + name).c_str()); - exit(1); - } - - return data; -} - -size_t zlib_estimate_compressed_size(size_t input_size) { - return compressBound(input_size); -} - -enum zlib_wrapper { - kWrapperNONE, - kWrapperZLIB, - kWrapperGZIP, - kWrapperZRAW, -}; - -inline int zlib_stream_wrapper_type(zlib_wrapper type) { - if (type == kWrapperZLIB) // zlib DEFLATE stream wrapper - return MAX_WBITS; - if (type == kWrapperGZIP) // gzip DEFLATE stream wrapper - return MAX_WBITS + 16; - if (type == kWrapperZRAW) // no wrapper, use raw DEFLATE - return -MAX_WBITS; - error_exit("bad wrapper type", int(type)); - return 0; -} - -const char* zlib_wrapper_name(zlib_wrapper type) { - if (type == kWrapperZLIB) - return "ZLIB"; - if (type == kWrapperGZIP) - return "GZIP"; - if (type == kWrapperZRAW) - return "RAW"; - error_exit("bad wrapper type", int(type)); - return 0; -} - -static int zlib_compression_level; - -void zlib_compress( - const zlib_wrapper type, - const char* input, - const size_t input_size, - std::string* output, - bool resize_output = false) -{ - if (resize_output) - output->resize(zlib_estimate_compressed_size(input_size)); - size_t output_size = output->size(); - - z_stream stream; - memset(&stream, 0, sizeof(stream)); - - int result = deflateInit2(&stream, zlib_compression_level, Z_DEFLATED, - zlib_stream_wrapper_type(type), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); - if (result != Z_OK) - error_exit("deflateInit2 failed", result); - - stream.next_out = (Bytef*)string_data(output); - stream.avail_out = (uInt)output_size; - stream.next_in = (z_const Bytef*)input; - stream.avail_in = (uInt)input_size; - - result = deflate(&stream, Z_FINISH); - if (result == Z_STREAM_END) - output_size = stream.total_out; - result |= deflateEnd(&stream); - if (result != Z_STREAM_END) - error_exit("compress failed", result); - - if (resize_output) - output->resize(output_size); -} - -void zlib_uncompress( - const zlib_wrapper type, - const std::string& input, - const size_t output_size, - std::string* output) -{ - z_stream stream; - memset(&stream, 0, sizeof(stream)); - - int result = inflateInit2(&stream, zlib_stream_wrapper_type(type)); - if (result != Z_OK) - error_exit("inflateInit2 failed", result); - - stream.next_out = (Bytef*)string_data(output); - stream.avail_out = (uInt)output->size(); - stream.next_in = (z_const Bytef*)input.data(); - stream.avail_in = (uInt)input.size(); - - result = inflate(&stream, Z_FINISH); - if (stream.total_out != output_size) - result = Z_DATA_ERROR; - result |= inflateEnd(&stream); - if (result == Z_STREAM_END) - return; - - std::string error("uncompress failed: "); - if (stream.msg) - error.append(stream.msg); - error_exit(error.c_str(), result); -} - -void verify_equal(const char* input, size_t size, std::string* output) { - const char* data = string_data(output); - if (output->size() == size && !memcmp(data, input, size)) - return; - fprintf(stderr, "uncompressed data does not match the input data\n"); - exit(3); -} - -void zlib_file(const char* name, const zlib_wrapper type) { - /* - * Read the file data. - */ - const auto file = read_file_data_or_exit(name); - const int length = static_cast(file.size); - const char* data = file.data.get(); - printf("%-40s :\n", name); - - /* - * Chop the data into blocks. - */ - const int block_size = 1 << 20; - const int blocks = (length + block_size - 1) / block_size; - - std::vector input(blocks); - std::vector input_length(blocks); - std::vector compressed(blocks); - std::vector output(blocks); - - for (int b = 0; b < blocks; ++b) { - int input_start = b * block_size; - int input_limit = std::min((b + 1) * block_size, length); - input[b] = data + input_start; - input_length[b] = input_limit - input_start; - } - - /* - * Run the zlib compress/uncompress loop a few times with |repeats| to - * process about 10MB of data if the length is small relative to 10MB. - * If length is large relative to 10MB, process the data once. - */ - const int mega_byte = 1024 * 1024; - const int repeats = (10 * mega_byte + length) / (length + 1); - const int runs = 5; - double ctime[runs]; - double utime[runs]; - - for (int run = 0; run < runs; ++run) { - const auto now = [] { return std::chrono::steady_clock::now(); }; - - // Pre-grow the output buffer so we don't measure string resize time. - for (int b = 0; b < blocks; ++b) - compressed[b].resize(zlib_estimate_compressed_size(block_size)); - - auto start = now(); - for (int b = 0; b < blocks; ++b) - for (int r = 0; r < repeats; ++r) - zlib_compress(type, input[b], input_length[b], &compressed[b]); - ctime[run] = std::chrono::duration(now() - start).count(); - - // Compress again, resizing compressed, so we don't leave junk at the - // end of the compressed string that could confuse zlib_uncompress(). - for (int b = 0; b < blocks; ++b) - zlib_compress(type, input[b], input_length[b], &compressed[b], true); - - for (int b = 0; b < blocks; ++b) - output[b].resize(input_length[b]); - - start = now(); - for (int r = 0; r < repeats; ++r) - for (int b = 0; b < blocks; ++b) - zlib_uncompress(type, compressed[b], input_length[b], &output[b]); - utime[run] = std::chrono::duration(now() - start).count(); - - for (int b = 0; b < blocks; ++b) - verify_equal(input[b], input_length[b], &output[b]); - } - - /* - * Output the median/maximum compress/uncompress rates in MB/s. - */ - size_t output_length = 0; - for (size_t i = 0; i < compressed.size(); ++i) - output_length += compressed[i].size(); - - std::sort(ctime, ctime + runs); - std::sort(utime, utime + runs); - - double deflate_rate_med = length * repeats / mega_byte / ctime[runs / 2]; - double inflate_rate_med = length * repeats / mega_byte / utime[runs / 2]; - double deflate_rate_max = length * repeats / mega_byte / ctime[0]; - double inflate_rate_max = length * repeats / mega_byte / utime[0]; - - // type, block size, compression ratio, etc - printf("%s: [b %dM] bytes %6d -> %6u %4.1f%%", - zlib_wrapper_name(type), block_size / (1 << 20), length, - static_cast(output_length), output_length * 100.0 / length); - - // compress / uncompress median (max) rates - printf(" comp %5.1f (%5.1f) MB/s uncomp %5.1f (%5.1f) MB/s\n", - deflate_rate_med, deflate_rate_max, inflate_rate_med, inflate_rate_max); -} - -static int argn = 1; - -char* get_option(int argc, char* argv[], const char* option) { - if (argn < argc) - return !strcmp(argv[argn], option) ? argv[argn++] : 0; - return 0; -} - -bool get_compression(int argc, char* argv[], int* value) { - if (argn < argc) - *value = atoi(argv[argn++]); - return *value >= 1 && *value <= 9; -} - -void usage_exit(const char* program) { - printf("usage: %s gzip|zlib|raw [--compression 1:9] files...\n", program); - exit(1); -} - -int main(int argc, char* argv[]) { - zlib_wrapper type; - if (get_option(argc, argv, "zlib")) - type = kWrapperZLIB; - else if (get_option(argc, argv, "gzip")) - type = kWrapperGZIP; - else if (get_option(argc, argv, "raw")) - type = kWrapperZRAW; - else - usage_exit(argv[0]); - - if (!get_option(argc, argv, "--compression")) - zlib_compression_level = Z_DEFAULT_COMPRESSION; - else if (!get_compression(argc, argv, &zlib_compression_level)) - usage_exit(argv[0]); - - if (argn >= argc) - usage_exit(argv[0]); - while (argn < argc) - zlib_file(argv[argn++], type); - - return 0; -} diff --git a/deps/zlib/contrib/minizip/ChangeLogUnzip b/deps/zlib/contrib/minizip/ChangeLogUnzip deleted file mode 100644 index e62af147dce682747739e7061cd4bf8aa0f19c3a..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/ChangeLogUnzip +++ /dev/null @@ -1,67 +0,0 @@ -Change in 1.01e (12 feb 05) -- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter) -- Fix possible memory leak in unzip.c (Zoran Stevanovic) - -Change in 1.01b (20 may 04) -- Integrate patch from Debian package (submited by Mark Brown) -- Add tools mztools from Xavier Roche - -Change in 1.01 (8 may 04) -- fix buffer overrun risk in unzip.c (Xavier Roche) -- fix a minor buffer insecurity in minizip.c (Mike Whittaker) - -Change in 1.00: (10 sept 03) -- rename to 1.00 -- cosmetic code change - -Change in 0.22: (19 May 03) -- crypting support (unless you define NOCRYPT) -- append file in existing zipfile - -Change in 0.21: (10 Mar 03) -- bug fixes - -Change in 0.17: (27 Jan 02) -- bug fixes - -Change in 0.16: (19 Jan 02) -- Support of ioapi for virtualize zip file access - -Change in 0.15: (19 Mar 98) -- fix memory leak in minizip.c - -Change in 0.14: (10 Mar 98) -- fix bugs in minizip.c sample for zipping big file -- fix problem in month in date handling -- fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for - comment handling - -Change in 0.13: (6 Mar 98) -- fix bugs in zip.c -- add real minizip sample - -Change in 0.12: (4 Mar 98) -- add zip.c and zip.h for creates .zip file -- fix change_file_date in miniunz.c for Unix (Jean-loup Gailly) -- fix miniunz.c for file without specific record for directory - -Change in 0.11: (3 Mar 98) -- fix bug in unzGetCurrentFileInfo for get extra field and comment -- enhance miniunz sample, remove the bad unztst.c sample - -Change in 0.10: (2 Mar 98) -- fix bug in unzReadCurrentFile -- rename unzip* to unz* function and structure -- remove Windows-like hungary notation variable name -- modify some structure in unzip.h -- add somes comment in source -- remove unzipGetcCurrentFile function -- replace ZUNZEXPORT by ZEXPORT -- add unzGetLocalExtrafield for get the local extrafield info -- add a new sample, miniunz.c - -Change in 0.4: (25 Feb 98) -- suppress the type unzipFileInZip. - Only on file in the zipfile can be open at the same time -- fix somes typo in code -- added tm_unz structure in unzip_file_info (date/time in readable format) diff --git a/deps/zlib/contrib/minizip/Makefile b/deps/zlib/contrib/minizip/Makefile deleted file mode 100644 index 84eaad20d4fb19b00965268dd75d7e9b66c8cc21..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -CC=cc -CFLAGS=-O -I../.. - -UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a -ZIP_OBJS = minizip.o zip.o ioapi.o ../../libz.a - -.c.o: - $(CC) -c $(CFLAGS) $*.c - -all: miniunz minizip - -miniunz: $(UNZ_OBJS) - $(CC) $(CFLAGS) -o $@ $(UNZ_OBJS) - -minizip: $(ZIP_OBJS) - $(CC) $(CFLAGS) -o $@ $(ZIP_OBJS) - -test: miniunz minizip - ./minizip test readme.txt - ./miniunz -l test.zip - mv readme.txt readme.old - ./miniunz test.zip - -clean: - /bin/rm -f *.o *~ minizip miniunz diff --git a/deps/zlib/contrib/minizip/crypt.h b/deps/zlib/contrib/minizip/crypt.h deleted file mode 100644 index 1e9e8200b201ff600aecd9eb7df1ac6989931266..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/crypt.h +++ /dev/null @@ -1,131 +0,0 @@ -/* crypt.h -- base code for crypt/uncrypt ZIPfile - - - Version 1.01e, February 12th, 2005 - - Copyright (C) 1998-2005 Gilles Vollant - - This code is a modified version of crypting code in Infozip distribution - - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) - - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). - - If you don't need crypting in your application, just define symbols - NOCRYPT and NOUNCRYPT. - - This code support the "Traditional PKWARE Encryption". - - The new AES encryption added on Zip format by Winzip (see the page - http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong - Encryption is not supported. -*/ - -#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8)) - -/*********************************************************************** - * Return the next byte in the pseudo-random sequence - */ -static int decrypt_byte(unsigned long* pkeys, const z_crc_t* pcrc_32_tab) -{ - unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an - * unpredictable manner on 16-bit systems; not a problem - * with any known compiler so far, though */ - - temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2; - return (int)(((temp * (temp ^ 1)) >> 8) & 0xff); -} - -/*********************************************************************** - * Update the encryption keys with the next byte of plain text - */ -static int update_keys(unsigned long* pkeys,const z_crc_t* pcrc_32_tab,int c) -{ - (*(pkeys+0)) = CRC32((*(pkeys+0)), c); - (*(pkeys+1)) += (*(pkeys+0)) & 0xff; - (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1; - { - register int keyshift = (int)((*(pkeys+1)) >> 24); - (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift); - } - return c; -} - - -/*********************************************************************** - * Initialize the encryption keys and the random header according to - * the given password. - */ -static void init_keys(const char* passwd,unsigned long* pkeys,const z_crc_t* pcrc_32_tab) -{ - *(pkeys+0) = 305419896L; - *(pkeys+1) = 591751049L; - *(pkeys+2) = 878082192L; - while (*passwd != '\0') { - update_keys(pkeys,pcrc_32_tab,(int)*passwd); - passwd++; - } -} - -#define zdecode(pkeys,pcrc_32_tab,c) \ - (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab))) - -#define zencode(pkeys,pcrc_32_tab,c,t) \ - (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c)) - -#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED - -#define RAND_HEAD_LEN 12 - /* "last resort" source for second part of crypt seed pattern */ -# ifndef ZCR_SEED2 -# define ZCR_SEED2 3141592654UL /* use PI as default pattern */ -# endif - -static int crypthead(const char* passwd, /* password string */ - unsigned char* buf, /* where to write header */ - int bufSize, - unsigned long* pkeys, - const z_crc_t* pcrc_32_tab, - unsigned long crcForCrypting) -{ - int n; /* index in random header */ - int t; /* temporary */ - int c; /* random byte */ - unsigned char header[RAND_HEAD_LEN-2]; /* random header */ - static unsigned calls = 0; /* ensure different random header each time */ - - if (bufSize> 7) & 0xff; - header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t); - } - /* Encrypt random header (last two bytes is high word of crc) */ - init_keys(passwd, pkeys, pcrc_32_tab); - for (n = 0; n < RAND_HEAD_LEN-2; n++) - { - buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t); - } - buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t); - buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t); - return n; -} - -#endif diff --git a/deps/zlib/contrib/minizip/ioapi.c b/deps/zlib/contrib/minizip/ioapi.c deleted file mode 100644 index 543910b5e118a4100801ee5b38f1a9d2c2e2a094..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/ioapi.c +++ /dev/null @@ -1,247 +0,0 @@ -/* ioapi.h -- IO base function header for compress/uncompress .zip - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - -*/ - -#if defined(_WIN32) && (!(defined(_CRT_SECURE_NO_WARNINGS))) - #define _CRT_SECURE_NO_WARNINGS -#endif - -#if defined(__APPLE__) || defined(__Fuchsia__) || defined(IOAPI_NO_64) -// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions -#define FOPEN_FUNC(filename, mode) fopen(filename, mode) -#define FTELLO_FUNC(stream) ftello(stream) -#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) -#else -#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) -#define FTELLO_FUNC(stream) ftello64(stream) -#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) -#endif - - -#include "ioapi.h" - -voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode) -{ - if (pfilefunc->zfile_func64.zopen64_file != NULL) - return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode); - else - { - return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode); - } -} - -long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin) -{ - if (pfilefunc->zfile_func64.zseek64_file != NULL) - return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin); - else - { - uLong offsetTruncated = (uLong)offset; - if (offsetTruncated != offset) - return -1; - else - return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin); - } -} - -ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream) -{ - if (pfilefunc->zfile_func64.zseek64_file != NULL) - return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream); - else - { - uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream); - if ((tell_uLong) == MAXU32) - return (ZPOS64_T)-1; - else - return tell_uLong; - } -} - -void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32) -{ - p_filefunc64_32->zfile_func64.zopen64_file = NULL; - p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file; - p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; - p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file; - p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file; - p_filefunc64_32->zfile_func64.ztell64_file = NULL; - p_filefunc64_32->zfile_func64.zseek64_file = NULL; - p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file; - p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file; - p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque; - p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file; - p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file; -} - - - -static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode)); -static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); -static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size)); -static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream)); -static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); -static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream)); -static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream)); - -static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode) -{ - FILE* file = NULL; - const char* mode_fopen = NULL; - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else - if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else - if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename!=NULL) && (mode_fopen != NULL)) - file = fopen(filename, mode_fopen); - return file; -} - -static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode) -{ - FILE* file = NULL; - const char* mode_fopen = NULL; - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else - if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else - if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename!=NULL) && (mode_fopen != NULL)) - file = FOPEN_FUNC((const char*)filename, mode_fopen); - return file; -} - - -static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size) -{ - uLong ret; - ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream); - return ret; -} - -static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size) -{ - uLong ret; - ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream); - return ret; -} - -static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream) -{ - long ret; - ret = ftell((FILE *)stream); - return ret; -} - - -static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream) -{ - ZPOS64_T ret; - ret = FTELLO_FUNC((FILE *)stream); - return ret; -} - -static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin) -{ - int fseek_origin=0; - long ret; - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - fseek_origin = SEEK_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END : - fseek_origin = SEEK_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - fseek_origin = SEEK_SET; - break; - default: return -1; - } - ret = 0; - if (fseek((FILE *)stream, offset, fseek_origin) != 0) - ret = -1; - return ret; -} - -static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin) -{ - int fseek_origin=0; - long ret; - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - fseek_origin = SEEK_CUR; - break; - case ZLIB_FILEFUNC_SEEK_END : - fseek_origin = SEEK_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - fseek_origin = SEEK_SET; - break; - default: return -1; - } - ret = 0; - - if(FSEEKO_FUNC((FILE *)stream, offset, fseek_origin) != 0) - ret = -1; - - return ret; -} - - -static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream) -{ - int ret; - ret = fclose((FILE *)stream); - return ret; -} - -static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream) -{ - int ret; - ret = ferror((FILE *)stream); - return ret; -} - -void fill_fopen_filefunc (pzlib_filefunc_def) - zlib_filefunc_def* pzlib_filefunc_def; -{ - pzlib_filefunc_def->zopen_file = fopen_file_func; - pzlib_filefunc_def->zread_file = fread_file_func; - pzlib_filefunc_def->zwrite_file = fwrite_file_func; - pzlib_filefunc_def->ztell_file = ftell_file_func; - pzlib_filefunc_def->zseek_file = fseek_file_func; - pzlib_filefunc_def->zclose_file = fclose_file_func; - pzlib_filefunc_def->zerror_file = ferror_file_func; - pzlib_filefunc_def->opaque = NULL; -} - -void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen64_file = fopen64_file_func; - pzlib_filefunc_def->zread_file = fread_file_func; - pzlib_filefunc_def->zwrite_file = fwrite_file_func; - pzlib_filefunc_def->ztell64_file = ftell64_file_func; - pzlib_filefunc_def->zseek64_file = fseek64_file_func; - pzlib_filefunc_def->zclose_file = fclose_file_func; - pzlib_filefunc_def->zerror_file = ferror_file_func; - pzlib_filefunc_def->opaque = NULL; -} diff --git a/deps/zlib/contrib/minizip/ioapi.h b/deps/zlib/contrib/minizip/ioapi.h deleted file mode 100644 index c1b7a54847f552fd54d8716152a002b11b863d74..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/ioapi.h +++ /dev/null @@ -1,208 +0,0 @@ -/* ioapi.h -- IO base function header for compress/uncompress .zip - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - Changes - - Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this) - Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux. - More if/def section may be needed to support other platforms - Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows. - (but you should use iowin32.c for windows instead) - -*/ - -#ifndef _ZLIBIOAPI64_H -#define _ZLIBIOAPI64_H - -#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) - - // Linux needs this to support file operation on files larger then 4+GB - // But might need better if/def to select just the platforms that needs them. - - #ifndef __USE_FILE_OFFSET64 - #define __USE_FILE_OFFSET64 - #endif - #ifndef __USE_LARGEFILE64 - #define __USE_LARGEFILE64 - #endif - #ifndef _LARGEFILE64_SOURCE - #define _LARGEFILE64_SOURCE - #endif - #ifndef _FILE_OFFSET_BIT - #define _FILE_OFFSET_BIT 64 - #endif - -#endif - -#include -#include -#include "third_party/zlib/zlib.h" - -#if defined(USE_FILE32API) -#define fopen64 fopen -#define ftello64 ftell -#define fseeko64 fseek -#else -#ifdef __FreeBSD__ -#define fopen64 fopen -#define ftello64 ftello -#define fseeko64 fseeko -#endif -#ifdef _MSC_VER - #define fopen64 fopen - #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC))) - #define ftello64 _ftelli64 - #define fseeko64 _fseeki64 - #else // old MSC - #define ftello64 ftell - #define fseeko64 fseek - #endif -#endif -#endif - -/* -#ifndef ZPOS64_T - #ifdef _WIN32 - #define ZPOS64_T fpos_t - #else - #include - #define ZPOS64_T uint64_t - #endif -#endif -*/ - -#ifdef HAVE_MINIZIP64_CONF_H -#include "mz64conf.h" -#endif - -/* a type choosen by DEFINE */ -#ifdef HAVE_64BIT_INT_CUSTOM -typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T; -#else -#ifdef HAS_STDINT_H -#include "stdint.h" -typedef uint64_t ZPOS64_T; -#else - -/* Maximum unsigned 32-bit value used as placeholder for zip64 */ -#define MAXU32 0xffffffff - -#if defined(_MSC_VER) || defined(__BORLANDC__) -typedef unsigned __int64 ZPOS64_T; -#else -typedef unsigned long long int ZPOS64_T; -#endif -#endif -#endif - - - -#ifdef __cplusplus -extern "C" { -#endif - - -#define ZLIB_FILEFUNC_SEEK_CUR (1) -#define ZLIB_FILEFUNC_SEEK_END (2) -#define ZLIB_FILEFUNC_SEEK_SET (0) - -#define ZLIB_FILEFUNC_MODE_READ (1) -#define ZLIB_FILEFUNC_MODE_WRITE (2) -#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) - -#define ZLIB_FILEFUNC_MODE_EXISTING (4) -#define ZLIB_FILEFUNC_MODE_CREATE (8) - - -#ifndef ZCALLBACK - #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK) - #define ZCALLBACK CALLBACK - #else - #define ZCALLBACK - #endif -#endif - - - - -typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode)); -typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size)); -typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); -typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream)); -typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream)); - -typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream)); -typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin)); - - -/* here is the "old" 32 bits structure structure */ -typedef struct zlib_filefunc_def_s -{ - open_file_func zopen_file; - read_file_func zread_file; - write_file_func zwrite_file; - tell_file_func ztell_file; - seek_file_func zseek_file; - close_file_func zclose_file; - testerror_file_func zerror_file; - voidpf opaque; -} zlib_filefunc_def; - -typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream)); -typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); -typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode)); - -typedef struct zlib_filefunc64_def_s -{ - open64_file_func zopen64_file; - read_file_func zread_file; - write_file_func zwrite_file; - tell64_file_func ztell64_file; - seek64_file_func zseek64_file; - close_file_func zclose_file; - testerror_file_func zerror_file; - voidpf opaque; -} zlib_filefunc64_def; - -void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def)); -void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); - -/* now internal definition, only for zip.c and unzip.h */ -typedef struct zlib_filefunc64_32_def_s -{ - zlib_filefunc64_def zfile_func64; - open_file_func zopen32_file; - tell_file_func ztell32_file; - seek_file_func zseek32_file; -} zlib_filefunc64_32_def; - - -#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) -#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size)) -//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream)) -//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode)) -#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream)) -#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream)) - -voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)); -long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)); -ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)); - -void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32); - -#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode))) -#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream))) -#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode))) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/deps/zlib/contrib/minizip/iowin32.c b/deps/zlib/contrib/minizip/iowin32.c deleted file mode 100644 index 246ceb91a13942f0b5312830946235ae8d4b2e20..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/iowin32.c +++ /dev/null @@ -1,469 +0,0 @@ -/* iowin32.c -- IO base function header for compress/uncompress .zip - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - -*/ - -#include - -#include "zlib.h" -#include "ioapi.h" -#include "iowin32.h" - -#ifndef INVALID_HANDLE_VALUE -#define INVALID_HANDLE_VALUE (0xFFFFFFFF) -#endif - -#ifndef INVALID_SET_FILE_POINTER -#define INVALID_SET_FILE_POINTER ((DWORD)-1) -#endif - - -#ifdef _WIN32_WINNT -#undef _WIN32_WINNT -#define _WIN32_WINNT 0x601 -#endif - -#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 -// see Include/shared/winapifamily.h in the Windows Kit -#if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) -#if WINAPI_FAMILY_ONE_PARTITION(WINAPI_FAMILY, WINAPI_PARTITION_APP) -#define IOWIN32_USING_WINRT_API 1 -#endif -#endif -#endif - -voidpf ZCALLBACK win32_open_file_func OF((voidpf opaque, const char* filename, int mode)); -uLong ZCALLBACK win32_read_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size)); -uLong ZCALLBACK win32_write_file_func OF((voidpf opaque, voidpf stream, const void* buf, uLong size)); -ZPOS64_T ZCALLBACK win32_tell64_file_func OF((voidpf opaque, voidpf stream)); -long ZCALLBACK win32_seek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)); -int ZCALLBACK win32_close_file_func OF((voidpf opaque, voidpf stream)); -int ZCALLBACK win32_error_file_func OF((voidpf opaque, voidpf stream)); - -typedef struct -{ - HANDLE hf; - int error; -} WIN32FILE_IOWIN; - - -static void win32_translate_open_mode(int mode, - DWORD* lpdwDesiredAccess, - DWORD* lpdwCreationDisposition, - DWORD* lpdwShareMode, - DWORD* lpdwFlagsAndAttributes) -{ - *lpdwDesiredAccess = *lpdwShareMode = *lpdwFlagsAndAttributes = *lpdwCreationDisposition = 0; - - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ) - { - *lpdwDesiredAccess = GENERIC_READ; - *lpdwCreationDisposition = OPEN_EXISTING; - *lpdwShareMode = FILE_SHARE_READ; - } - else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - { - *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ; - *lpdwCreationDisposition = OPEN_EXISTING; - } - else if (mode & ZLIB_FILEFUNC_MODE_CREATE) - { - *lpdwDesiredAccess = GENERIC_WRITE | GENERIC_READ; - *lpdwCreationDisposition = CREATE_ALWAYS; - } -} - -static voidpf win32_build_iowin(HANDLE hFile) -{ - voidpf ret=NULL; - - if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE)) - { - WIN32FILE_IOWIN w32fiow; - w32fiow.hf = hFile; - w32fiow.error = 0; - ret = malloc(sizeof(WIN32FILE_IOWIN)); - - if (ret==NULL) - CloseHandle(hFile); - else - *((WIN32FILE_IOWIN*)ret) = w32fiow; - } - return ret; -} - -voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode) -{ - const char* mode_fopen = NULL; - DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; - HANDLE hFile = NULL; - - win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); - -#ifdef IOWIN32_USING_WINRT_API -#ifdef UNICODE - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); -#else - if ((filename!=NULL) && (dwDesiredAccess != 0)) - { - WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; - MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); - hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); - } -#endif -#else - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); -#endif - - return win32_build_iowin(hFile); -} - - -voidpf ZCALLBACK win32_open64_file_funcA (voidpf opaque,const void* filename,int mode) -{ - const char* mode_fopen = NULL; - DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; - HANDLE hFile = NULL; - - win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); - -#ifdef IOWIN32_USING_WINRT_API - if ((filename!=NULL) && (dwDesiredAccess != 0)) - { - WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; - MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); - hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); - } -#else - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFileA((LPCSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); -#endif - - return win32_build_iowin(hFile); -} - - -voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode) -{ - const char* mode_fopen = NULL; - DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; - HANDLE hFile = NULL; - - win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); - -#ifdef IOWIN32_USING_WINRT_API - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition,NULL); -#else - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); -#endif - - return win32_build_iowin(hFile); -} - - -voidpf ZCALLBACK win32_open_file_func (voidpf opaque,const char* filename,int mode) -{ - const char* mode_fopen = NULL; - DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; - HANDLE hFile = NULL; - - win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); - -#ifdef IOWIN32_USING_WINRT_API -#ifdef UNICODE - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); -#else - if ((filename!=NULL) && (dwDesiredAccess != 0)) - { - WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; - MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); - hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); - } -#endif -#else - if ((filename!=NULL) && (dwDesiredAccess != 0)) - hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); -#endif - - return win32_build_iowin(hFile); -} - - -uLong ZCALLBACK win32_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size) -{ - uLong ret=0; - HANDLE hFile = NULL; - if (stream!=NULL) - hFile = ((WIN32FILE_IOWIN*)stream) -> hf; - - if (hFile != NULL) - { - if (!ReadFile(hFile, buf, size, &ret, NULL)) - { - DWORD dwErr = GetLastError(); - if (dwErr == ERROR_HANDLE_EOF) - dwErr = 0; - ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; - } - } - - return ret; -} - - -uLong ZCALLBACK win32_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size) -{ - uLong ret=0; - HANDLE hFile = NULL; - if (stream!=NULL) - hFile = ((WIN32FILE_IOWIN*)stream) -> hf; - - if (hFile != NULL) - { - if (!WriteFile(hFile, buf, size, &ret, NULL)) - { - DWORD dwErr = GetLastError(); - if (dwErr == ERROR_HANDLE_EOF) - dwErr = 0; - ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; - } - } - - return ret; -} - -static BOOL MySetFilePointerEx(HANDLE hFile, LARGE_INTEGER pos, LARGE_INTEGER *newPos, DWORD dwMoveMethod) -{ -#ifdef IOWIN32_USING_WINRT_API - return SetFilePointerEx(hFile, pos, newPos, dwMoveMethod); -#else - LONG lHigh = pos.HighPart; - DWORD dwNewPos = SetFilePointer(hFile, pos.LowPart, &lHigh, dwMoveMethod); - BOOL fOk = TRUE; - if (dwNewPos == 0xFFFFFFFF) - if (GetLastError() != NO_ERROR) - fOk = FALSE; - if ((newPos != NULL) && (fOk)) - { - newPos->LowPart = dwNewPos; - newPos->HighPart = lHigh; - } - return fOk; -#endif -} - -long ZCALLBACK win32_tell_file_func (voidpf opaque,voidpf stream) -{ - long ret=-1; - HANDLE hFile = NULL; - if (stream!=NULL) - hFile = ((WIN32FILE_IOWIN*)stream) -> hf; - if (hFile != NULL) - { - LARGE_INTEGER pos; - pos.QuadPart = 0; - - if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT)) - { - DWORD dwErr = GetLastError(); - ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; - ret = -1; - } - else - ret=(long)pos.LowPart; - } - return ret; -} - -ZPOS64_T ZCALLBACK win32_tell64_file_func (voidpf opaque, voidpf stream) -{ - ZPOS64_T ret= (ZPOS64_T)-1; - HANDLE hFile = NULL; - if (stream!=NULL) - hFile = ((WIN32FILE_IOWIN*)stream)->hf; - - if (hFile) - { - LARGE_INTEGER pos; - pos.QuadPart = 0; - - if (!MySetFilePointerEx(hFile, pos, &pos, FILE_CURRENT)) - { - DWORD dwErr = GetLastError(); - ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; - ret = (ZPOS64_T)-1; - } - else - ret=pos.QuadPart; - } - return ret; -} - - -long ZCALLBACK win32_seek_file_func (voidpf opaque,voidpf stream,uLong offset,int origin) -{ - DWORD dwMoveMethod=0xFFFFFFFF; - HANDLE hFile = NULL; - - long ret=-1; - if (stream!=NULL) - hFile = ((WIN32FILE_IOWIN*)stream) -> hf; - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - dwMoveMethod = FILE_CURRENT; - break; - case ZLIB_FILEFUNC_SEEK_END : - dwMoveMethod = FILE_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - dwMoveMethod = FILE_BEGIN; - break; - default: return -1; - } - - if (hFile != NULL) - { - LARGE_INTEGER pos; - pos.QuadPart = offset; - if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod)) - { - DWORD dwErr = GetLastError(); - ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; - ret = -1; - } - else - ret=0; - } - return ret; -} - -long ZCALLBACK win32_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin) -{ - DWORD dwMoveMethod=0xFFFFFFFF; - HANDLE hFile = NULL; - long ret=-1; - - if (stream!=NULL) - hFile = ((WIN32FILE_IOWIN*)stream)->hf; - - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_CUR : - dwMoveMethod = FILE_CURRENT; - break; - case ZLIB_FILEFUNC_SEEK_END : - dwMoveMethod = FILE_END; - break; - case ZLIB_FILEFUNC_SEEK_SET : - dwMoveMethod = FILE_BEGIN; - break; - default: return -1; - } - - if (hFile) - { - LARGE_INTEGER pos; - pos.QuadPart = offset; - if (!MySetFilePointerEx(hFile, pos, NULL, dwMoveMethod)) - { - DWORD dwErr = GetLastError(); - ((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr; - ret = -1; - } - else - ret=0; - } - return ret; -} - -int ZCALLBACK win32_close_file_func (voidpf opaque, voidpf stream) -{ - int ret=-1; - - if (stream!=NULL) - { - HANDLE hFile; - hFile = ((WIN32FILE_IOWIN*)stream) -> hf; - if (hFile != NULL) - { - CloseHandle(hFile); - ret=0; - } - free(stream); - } - return ret; -} - -int ZCALLBACK win32_error_file_func (voidpf opaque,voidpf stream) -{ - int ret=-1; - if (stream!=NULL) - { - ret = ((WIN32FILE_IOWIN*)stream) -> error; - } - return ret; -} - -void fill_win32_filefunc (zlib_filefunc_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen_file = win32_open_file_func; - pzlib_filefunc_def->zread_file = win32_read_file_func; - pzlib_filefunc_def->zwrite_file = win32_write_file_func; - pzlib_filefunc_def->ztell_file = win32_tell_file_func; - pzlib_filefunc_def->zseek_file = win32_seek_file_func; - pzlib_filefunc_def->zclose_file = win32_close_file_func; - pzlib_filefunc_def->zerror_file = win32_error_file_func; - pzlib_filefunc_def->opaque = NULL; -} - -void fill_win32_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen64_file = win32_open64_file_func; - pzlib_filefunc_def->zread_file = win32_read_file_func; - pzlib_filefunc_def->zwrite_file = win32_write_file_func; - pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; - pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; - pzlib_filefunc_def->zclose_file = win32_close_file_func; - pzlib_filefunc_def->zerror_file = win32_error_file_func; - pzlib_filefunc_def->opaque = NULL; -} - - -void fill_win32_filefunc64A(zlib_filefunc64_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen64_file = win32_open64_file_funcA; - pzlib_filefunc_def->zread_file = win32_read_file_func; - pzlib_filefunc_def->zwrite_file = win32_write_file_func; - pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; - pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; - pzlib_filefunc_def->zclose_file = win32_close_file_func; - pzlib_filefunc_def->zerror_file = win32_error_file_func; - pzlib_filefunc_def->opaque = NULL; -} - - -void fill_win32_filefunc64W(zlib_filefunc64_def* pzlib_filefunc_def) -{ - pzlib_filefunc_def->zopen64_file = win32_open64_file_funcW; - pzlib_filefunc_def->zread_file = win32_read_file_func; - pzlib_filefunc_def->zwrite_file = win32_write_file_func; - pzlib_filefunc_def->ztell64_file = win32_tell64_file_func; - pzlib_filefunc_def->zseek64_file = win32_seek64_file_func; - pzlib_filefunc_def->zclose_file = win32_close_file_func; - pzlib_filefunc_def->zerror_file = win32_error_file_func; - pzlib_filefunc_def->opaque = NULL; -} diff --git a/deps/zlib/contrib/minizip/iowin32.h b/deps/zlib/contrib/minizip/iowin32.h deleted file mode 100644 index 0ca0969a7d09a487b1b2b5d74b805837a3bf2e96..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/iowin32.h +++ /dev/null @@ -1,28 +0,0 @@ -/* iowin32.h -- IO base function header for compress/uncompress .zip - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - -*/ - -#include - - -#ifdef __cplusplus -extern "C" { -#endif - -void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def)); -void fill_win32_filefunc64 OF((zlib_filefunc64_def* pzlib_filefunc_def)); -void fill_win32_filefunc64A OF((zlib_filefunc64_def* pzlib_filefunc_def)); -void fill_win32_filefunc64W OF((zlib_filefunc64_def* pzlib_filefunc_def)); - -#ifdef __cplusplus -} -#endif diff --git a/deps/zlib/contrib/minizip/miniunz.c b/deps/zlib/contrib/minizip/miniunz.c deleted file mode 100644 index 3d65401be5cdd7b58c57d681e28347278942917b..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/miniunz.c +++ /dev/null @@ -1,660 +0,0 @@ -/* - miniunz.c - Version 1.1, February 14h, 2010 - sample part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications of Unzip for Zip64 - Copyright (C) 2007-2008 Even Rouault - - Modifications for Zip64 support on both zip and unzip - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) -*/ - -#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__)) - #ifndef __USE_FILE_OFFSET64 - #define __USE_FILE_OFFSET64 - #endif - #ifndef __USE_LARGEFILE64 - #define __USE_LARGEFILE64 - #endif - #ifndef _LARGEFILE64_SOURCE - #define _LARGEFILE64_SOURCE - #endif - #ifndef _FILE_OFFSET_BIT - #define _FILE_OFFSET_BIT 64 - #endif -#endif - -#ifdef __APPLE__ -// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions -#define FOPEN_FUNC(filename, mode) fopen(filename, mode) -#define FTELLO_FUNC(stream) ftello(stream) -#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) -#else -#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) -#define FTELLO_FUNC(stream) ftello64(stream) -#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) -#endif - - -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -# include -# include -#else -# include -# include -#endif - - -#include "unzip.h" - -#define CASESENSITIVITY (0) -#define WRITEBUFFERSIZE (8192) -#define MAXFILENAME (256) - -#ifdef _WIN32 -#define USEWIN32IOAPI -#include "iowin32.h" -#endif -/* - mini unzip, demo of unzip package - - usage : - Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir] - - list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT - if it exists -*/ - - -/* change_file_date : change the date/time of a file - filename : the filename of the file where date/time must be modified - dosdate : the new date at the MSDos format (4 bytes) - tmu_date : the SAME new date at the tm_unz format */ -void change_file_date(filename,dosdate,tmu_date) - const char *filename; - uLong dosdate; - tm_unz tmu_date; -{ -#ifdef _WIN32 - HANDLE hFile; - FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite; - - hFile = CreateFileA(filename,GENERIC_READ | GENERIC_WRITE, - 0,NULL,OPEN_EXISTING,0,NULL); - GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite); - DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal); - LocalFileTimeToFileTime(&ftLocal,&ftm); - SetFileTime(hFile,&ftm,&ftLastAcc,&ftm); - CloseHandle(hFile); -#else -#ifdef unix || __APPLE__ - struct utimbuf ut; - struct tm newdate; - newdate.tm_sec = tmu_date.tm_sec; - newdate.tm_min=tmu_date.tm_min; - newdate.tm_hour=tmu_date.tm_hour; - newdate.tm_mday=tmu_date.tm_mday; - newdate.tm_mon=tmu_date.tm_mon; - if (tmu_date.tm_year > 1900) - newdate.tm_year=tmu_date.tm_year - 1900; - else - newdate.tm_year=tmu_date.tm_year ; - newdate.tm_isdst=-1; - - ut.actime=ut.modtime=mktime(&newdate); - utime(filename,&ut); -#endif -#endif -} - - -/* mymkdir and change_file_date are not 100 % portable - As I don't know well Unix, I wait feedback for the unix portion */ - -int mymkdir(dirname) - const char* dirname; -{ - int ret=0; -#ifdef _WIN32 - ret = _mkdir(dirname); -#elif unix - ret = mkdir (dirname,0775); -#elif __APPLE__ - ret = mkdir (dirname,0775); -#endif - return ret; -} - -int makedir (newdir) - char *newdir; -{ - char *buffer ; - char *p; - int len = (int)strlen(newdir); - - if (len <= 0) - return 0; - - buffer = (char*)malloc(len+1); - if (buffer==NULL) - { - printf("Error allocating memory\n"); - return UNZ_INTERNALERROR; - } - strcpy(buffer,newdir); - - if (buffer[len-1] == '/') { - buffer[len-1] = '\0'; - } - if (mymkdir(buffer) == 0) - { - free(buffer); - return 1; - } - - p = buffer+1; - while (1) - { - char hold; - - while(*p && *p != '\\' && *p != '/') - p++; - hold = *p; - *p = 0; - if ((mymkdir(buffer) == -1) && (errno == ENOENT)) - { - printf("couldn't create directory %s\n",buffer); - free(buffer); - return 0; - } - if (hold == 0) - break; - *p++ = hold; - } - free(buffer); - return 1; -} - -void do_banner() -{ - printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n"); - printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); -} - -void do_help() -{ - printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \ - " -e Extract without pathname (junk paths)\n" \ - " -x Extract with pathname\n" \ - " -v list files\n" \ - " -l list files\n" \ - " -d directory to extract into\n" \ - " -o overwrite files without prompting\n" \ - " -p extract crypted file using password\n\n"); -} - -void Display64BitsSize(ZPOS64_T n, int size_char) -{ - /* to avoid compatibility problem , we do here the conversion */ - char number[21]; - int offset=19; - int pos_string = 19; - number[20]=0; - for (;;) { - number[offset]=(char)((n%10)+'0'); - if (number[offset] != '0') - pos_string=offset; - n/=10; - if (offset==0) - break; - offset--; - } - { - int size_display_string = 19-pos_string; - while (size_char > size_display_string) - { - size_char--; - printf(" "); - } - } - - printf("%s",&number[pos_string]); -} - -int do_list(uf) - unzFile uf; -{ - uLong i; - unz_global_info64 gi; - int err; - - err = unzGetGlobalInfo64(uf,&gi); - if (err!=UNZ_OK) - printf("error %d with zipfile in unzGetGlobalInfo \n",err); - printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); - printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); - for (i=0;i0) - ratio = (uLong)((file_info.compressed_size*100)/file_info.uncompressed_size); - - /* display a '*' if the file is crypted */ - if ((file_info.flag & 1) != 0) - charCrypt='*'; - - if (file_info.compression_method==0) - string_method="Stored"; - else - if (file_info.compression_method==Z_DEFLATED) - { - uInt iLevel=(uInt)((file_info.flag & 0x6)/2); - if (iLevel==0) - string_method="Defl:N"; - else if (iLevel==1) - string_method="Defl:X"; - else if ((iLevel==2) || (iLevel==3)) - string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ - } - else - if (file_info.compression_method==Z_BZIP2ED) - { - string_method="BZip2 "; - } - else - string_method="Unkn. "; - - Display64BitsSize(file_info.uncompressed_size,7); - printf(" %6s%c",string_method,charCrypt); - Display64BitsSize(file_info.compressed_size,7); - printf(" %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", - ratio, - (uLong)file_info.tmu_date.tm_mon + 1, - (uLong)file_info.tmu_date.tm_mday, - (uLong)file_info.tmu_date.tm_year % 100, - (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, - (uLong)file_info.crc,filename_inzip); - if ((i+1)='a') && (rep<='z')) - rep -= 0x20; - } - while ((rep!='Y') && (rep!='N') && (rep!='A')); - } - - if (rep == 'N') - skip = 1; - - if (rep == 'A') - *popt_overwrite=1; - } - - if ((skip==0) && (err==UNZ_OK)) - { - fout=FOPEN_FUNC(write_filename,"wb"); - /* some zipfile don't contain directory alone before file */ - if ((fout==NULL) && ((*popt_extract_without_path)==0) && - (filename_withoutpath!=(char*)filename_inzip)) - { - char c=*(filename_withoutpath-1); - *(filename_withoutpath-1)='\0'; - makedir(write_filename); - *(filename_withoutpath-1)=c; - fout=FOPEN_FUNC(write_filename,"wb"); - } - - if (fout==NULL) - { - printf("error opening %s\n",write_filename); - } - } - - if (fout!=NULL) - { - printf(" extracting: %s\n",write_filename); - - do - { - err = unzReadCurrentFile(uf,buf,size_buf); - if (err<0) - { - printf("error %d with zipfile in unzReadCurrentFile\n",err); - break; - } - if (err>0) - if (fwrite(buf,err,1,fout)!=1) - { - printf("error in writing extracted file\n"); - err=UNZ_ERRNO; - break; - } - } - while (err>0); - if (fout) - fclose(fout); - - if (err==0) - change_file_date(write_filename,file_info.dosDate, - file_info.tmu_date); - } - - if (err==UNZ_OK) - { - err = unzCloseCurrentFile (uf); - if (err!=UNZ_OK) - { - printf("error %d with zipfile in unzCloseCurrentFile\n",err); - } - } - else - unzCloseCurrentFile(uf); /* don't lose the error */ - } - - free(buf); - return err; -} - - -int do_extract(uf,opt_extract_without_path,opt_overwrite,password) - unzFile uf; - int opt_extract_without_path; - int opt_overwrite; - const char* password; -{ - uLong i; - unz_global_info64 gi; - int err; - FILE* fout=NULL; - - err = unzGetGlobalInfo64(uf,&gi); - if (err!=UNZ_OK) - printf("error %d with zipfile in unzGetGlobalInfo \n",err); - - for (i=0;i -#include -#include -#include -#include -#include - -#ifdef _WIN32 -# include -# include -#else -# include -# include -# include -# include -#endif - -#include "zip.h" - -#ifdef _WIN32 - #define USEWIN32IOAPI - #include "iowin32.h" -#endif - - - -#define WRITEBUFFERSIZE (16384) -#define MAXFILENAME (256) - -#ifdef _WIN32 -uLong filetime(f, tmzip, dt) - char *f; /* name of file to get info on */ - tm_zip *tmzip; /* return value: access, modific. and creation times */ - uLong *dt; /* dostime */ -{ - int ret = 0; - { - FILETIME ftLocal; - HANDLE hFind; - WIN32_FIND_DATAA ff32; - - hFind = FindFirstFileA(f,&ff32); - if (hFind != INVALID_HANDLE_VALUE) - { - FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal); - FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0); - FindClose(hFind); - ret = 1; - } - } - return ret; -} -#else -#ifdef unix || __APPLE__ -uLong filetime(f, tmzip, dt) - char *f; /* name of file to get info on */ - tm_zip *tmzip; /* return value: access, modific. and creation times */ - uLong *dt; /* dostime */ -{ - int ret=0; - struct stat s; /* results of stat() */ - struct tm* filedate; - time_t tm_t=0; - - if (strcmp(f,"-")!=0) - { - char name[MAXFILENAME+1]; - int len = strlen(f); - if (len > MAXFILENAME) - len = MAXFILENAME; - - strncpy(name, f,MAXFILENAME-1); - /* strncpy doesnt append the trailing NULL, of the string is too long. */ - name[ MAXFILENAME ] = '\0'; - - if (name[len - 1] == '/') - name[len - 1] = '\0'; - /* not all systems allow stat'ing a file with / appended */ - if (stat(name,&s)==0) - { - tm_t = s.st_mtime; - ret = 1; - } - } - filedate = localtime(&tm_t); - - tmzip->tm_sec = filedate->tm_sec; - tmzip->tm_min = filedate->tm_min; - tmzip->tm_hour = filedate->tm_hour; - tmzip->tm_mday = filedate->tm_mday; - tmzip->tm_mon = filedate->tm_mon ; - tmzip->tm_year = filedate->tm_year; - - return ret; -} -#else -uLong filetime(f, tmzip, dt) - char *f; /* name of file to get info on */ - tm_zip *tmzip; /* return value: access, modific. and creation times */ - uLong *dt; /* dostime */ -{ - return 0; -} -#endif -#endif - - - - -int check_exist_file(filename) - const char* filename; -{ - FILE* ftestexist; - int ret = 1; - ftestexist = FOPEN_FUNC(filename,"rb"); - if (ftestexist==NULL) - ret = 0; - else - fclose(ftestexist); - return ret; -} - -void do_banner() -{ - printf("MiniZip 1.1, demo of zLib + MiniZip64 package, written by Gilles Vollant\n"); - printf("more info on MiniZip at http://www.winimage.com/zLibDll/minizip.html\n\n"); -} - -void do_help() -{ - printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]\n\n" \ - " -o Overwrite existing file.zip\n" \ - " -a Append to existing file.zip\n" \ - " -0 Store only\n" \ - " -1 Compress faster\n" \ - " -9 Compress better\n\n" \ - " -j exclude path. store only the file name.\n\n"); -} - -/* calculate the CRC32 of a file, - because to encrypt a file, we need known the CRC32 of the file before */ -int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc) -{ - unsigned long calculate_crc=0; - int err=ZIP_OK; - FILE * fin = FOPEN_FUNC(filenameinzip,"rb"); - - unsigned long size_read = 0; - unsigned long total_read = 0; - if (fin==NULL) - { - err = ZIP_ERRNO; - } - - if (err == ZIP_OK) - do - { - err = ZIP_OK; - size_read = (int)fread(buf,1,size_buf,fin); - if (size_read < size_buf) - if (feof(fin)==0) - { - printf("error in reading %s\n",filenameinzip); - err = ZIP_ERRNO; - } - - if (size_read>0) - calculate_crc = crc32(calculate_crc,buf,size_read); - total_read += size_read; - - } while ((err == ZIP_OK) && (size_read>0)); - - if (fin) - fclose(fin); - - *result_crc=calculate_crc; - printf("file %s crc %lx\n", filenameinzip, calculate_crc); - return err; -} - -int isLargeFile(const char* filename) -{ - int largeFile = 0; - ZPOS64_T pos = 0; - FILE* pFile = FOPEN_FUNC(filename, "rb"); - - if(pFile != NULL) - { - int n = FSEEKO_FUNC(pFile, 0, SEEK_END); - pos = FTELLO_FUNC(pFile); - - printf("File : %s is %lld bytes\n", filename, pos); - - if(pos >= 0xffffffff) - largeFile = 1; - - fclose(pFile); - } - - return largeFile; -} - -int main(argc,argv) - int argc; - char *argv[]; -{ - int i; - int opt_overwrite=0; - int opt_compress_level=Z_DEFAULT_COMPRESSION; - int opt_exclude_path=0; - int zipfilenamearg = 0; - char filename_try[MAXFILENAME+16]; - int zipok; - int err=0; - int size_buf=0; - void* buf=NULL; - const char* password=NULL; - - - do_banner(); - if (argc==1) - { - do_help(); - return 0; - } - else - { - for (i=1;i='0') && (c<='9')) - opt_compress_level = c-'0'; - if ((c=='j') || (c=='J')) - opt_exclude_path = 1; - - if (((c=='p') || (c=='P')) && (i+1='a') && (rep<='z')) - rep -= 0x20; - } - while ((rep!='Y') && (rep!='N') && (rep!='A')); - if (rep=='N') - zipok = 0; - if (rep=='A') - opt_overwrite = 2; - } - } - - if (zipok==1) - { - zipFile zf; - int errclose; -# ifdef USEWIN32IOAPI - zlib_filefunc64_def ffunc; - fill_win32_filefunc64A(&ffunc); - zf = zipOpen2_64(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc); -# else - zf = zipOpen64(filename_try,(opt_overwrite==2) ? 2 : 0); -# endif - - if (zf == NULL) - { - printf("error opening %s\n",filename_try); - err= ZIP_ERRNO; - } - else - printf("creating %s\n",filename_try); - - for (i=zipfilenamearg+1;(i='0') || (argv[i][1]<='9'))) && - (strlen(argv[i]) == 2))) - { - FILE * fin; - int size_read; - const char* filenameinzip = argv[i]; - const char *savefilenameinzip; - zip_fileinfo zi; - unsigned long crcFile=0; - int zip64 = 0; - - zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = - zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0; - zi.dosDate = 0; - zi.internal_fa = 0; - zi.external_fa = 0; - filetime(filenameinzip,&zi.tmz_date,&zi.dosDate); - -/* - err = zipOpenNewFileInZip(zf,filenameinzip,&zi, - NULL,0,NULL,0,NULL / * comment * /, - (opt_compress_level != 0) ? Z_DEFLATED : 0, - opt_compress_level); -*/ - if ((password != NULL) && (err==ZIP_OK)) - err = getFileCrc(filenameinzip,buf,size_buf,&crcFile); - - zip64 = isLargeFile(filenameinzip); - - /* The path name saved, should not include a leading slash. */ - /*if it did, windows/xp and dynazip couldn't read the zip file. */ - savefilenameinzip = filenameinzip; - while( savefilenameinzip[0] == '\\' || savefilenameinzip[0] == '/' ) - { - savefilenameinzip++; - } - - /*should the zip file contain any path at all?*/ - if( opt_exclude_path ) - { - const char *tmpptr; - const char *lastslash = 0; - for( tmpptr = savefilenameinzip; *tmpptr; tmpptr++) - { - if( *tmpptr == '\\' || *tmpptr == '/') - { - lastslash = tmpptr; - } - } - if( lastslash != NULL ) - { - savefilenameinzip = lastslash+1; // base filename follows last slash. - } - } - - /**/ - err = zipOpenNewFileInZip3_64(zf,savefilenameinzip,&zi, - NULL,0,NULL,0,NULL /* comment*/, - (opt_compress_level != 0) ? Z_DEFLATED : 0, - opt_compress_level,0, - /* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */ - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - password,crcFile, zip64); - - if (err != ZIP_OK) - printf("error in opening %s in zipfile\n",filenameinzip); - else - { - fin = FOPEN_FUNC(filenameinzip,"rb"); - if (fin==NULL) - { - err=ZIP_ERRNO; - printf("error in opening %s for reading\n",filenameinzip); - } - } - - if (err == ZIP_OK) - do - { - err = ZIP_OK; - size_read = (int)fread(buf,1,size_buf,fin); - if (size_read < size_buf) - if (feof(fin)==0) - { - printf("error in reading %s\n",filenameinzip); - err = ZIP_ERRNO; - } - - if (size_read>0) - { - err = zipWriteInFileInZip (zf,buf,size_read); - if (err<0) - { - printf("error in writing %s in the zipfile\n", - filenameinzip); - } - - } - } while ((err == ZIP_OK) && (size_read>0)); - - if (fin) - fclose(fin); - - if (err<0) - err=ZIP_ERRNO; - else - { - err = zipCloseFileInZip(zf); - if (err!=ZIP_OK) - printf("error in closing %s in the zipfile\n", - filenameinzip); - } - } - } - errclose = zipClose(zf,NULL); - if (errclose != ZIP_OK) - printf("error in closing %s\n",filename_try); - } - else - { - do_help(); - } - - free(buf); - return 0; -} diff --git a/deps/zlib/contrib/minizip/mztools.c b/deps/zlib/contrib/minizip/mztools.c deleted file mode 100644 index 8bf9cca326338a0de6634359069bc8bd0d0b40db..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/mztools.c +++ /dev/null @@ -1,291 +0,0 @@ -/* - Additional tools for Minizip - Code: Xavier Roche '2004 - License: Same as ZLIB (www.gzip.org) -*/ - -/* Code */ -#include -#include -#include -#include "third_party/zlib/zlib.h" -#include "unzip.h" - -#define READ_8(adr) ((unsigned char)*(adr)) -#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) ) -#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) ) - -#define WRITE_8(buff, n) do { \ - *((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \ -} while(0) -#define WRITE_16(buff, n) do { \ - WRITE_8((unsigned char*)(buff), n); \ - WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \ -} while(0) -#define WRITE_32(buff, n) do { \ - WRITE_16((unsigned char*)(buff), (n) & 0xffff); \ - WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \ -} while(0) - -extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered) -const char* file; -const char* fileOut; -const char* fileOutTmp; -uLong* nRecovered; -uLong* bytesRecovered; -{ - int err = Z_OK; - FILE* fpZip = fopen(file, "rb"); - FILE* fpOut = fopen(fileOut, "wb"); - FILE* fpOutCD = fopen(fileOutTmp, "wb"); - if (fpZip != NULL && fpOut != NULL) { - int entries = 0; - uLong totalBytes = 0; - char header[30]; - char filename[1024]; - char extra[1024]; - int offset = 0; - int offsetCD = 0; - while ( fread(header, 1, 30, fpZip) == 30 ) { - int currentOffset = offset; - - /* File entry */ - if (READ_32(header) == 0x04034b50) { - unsigned int version = READ_16(header + 4); - unsigned int gpflag = READ_16(header + 6); - unsigned int method = READ_16(header + 8); - unsigned int filetime = READ_16(header + 10); - unsigned int filedate = READ_16(header + 12); - unsigned int crc = READ_32(header + 14); /* crc */ - unsigned int cpsize = READ_32(header + 18); /* compressed size */ - unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */ - unsigned int fnsize = READ_16(header + 26); /* file name length */ - unsigned int extsize = READ_16(header + 28); /* extra field length */ - filename[0] = extra[0] = '\0'; - - /* Header */ - if (fwrite(header, 1, 30, fpOut) == 30) { - offset += 30; - } else { - err = Z_ERRNO; - break; - } - - /* Filename */ - if (fnsize > 0) { - if (fnsize < sizeof(filename)) { - if (fread(filename, 1, fnsize, fpZip) == fnsize) { - if (fwrite(filename, 1, fnsize, fpOut) == fnsize) { - offset += fnsize; - } else { - err = Z_ERRNO; - break; - } - } else { - err = Z_ERRNO; - break; - } - } else { - err = Z_ERRNO; - break; - } - } else { - err = Z_STREAM_ERROR; - break; - } - - /* Extra field */ - if (extsize > 0) { - if (extsize < sizeof(extra)) { - if (fread(extra, 1, extsize, fpZip) == extsize) { - if (fwrite(extra, 1, extsize, fpOut) == extsize) { - offset += extsize; - } else { - err = Z_ERRNO; - break; - } - } else { - err = Z_ERRNO; - break; - } - } else { - err = Z_ERRNO; - break; - } - } - - /* Data */ - { - int dataSize = cpsize; - if (dataSize == 0) { - dataSize = uncpsize; - } - if (dataSize > 0) { - char* data = malloc(dataSize); - if (data != NULL) { - if ((int)fread(data, 1, dataSize, fpZip) == dataSize) { - if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) { - offset += dataSize; - totalBytes += dataSize; - } else { - err = Z_ERRNO; - } - } else { - err = Z_ERRNO; - } - free(data); - if (err != Z_OK) { - break; - } - } else { - err = Z_MEM_ERROR; - break; - } - } - } - - /* Central directory entry */ - { - char header[46]; - char* comment = ""; - int comsize = (int) strlen(comment); - WRITE_32(header, 0x02014b50); - WRITE_16(header + 4, version); - WRITE_16(header + 6, version); - WRITE_16(header + 8, gpflag); - WRITE_16(header + 10, method); - WRITE_16(header + 12, filetime); - WRITE_16(header + 14, filedate); - WRITE_32(header + 16, crc); - WRITE_32(header + 20, cpsize); - WRITE_32(header + 24, uncpsize); - WRITE_16(header + 28, fnsize); - WRITE_16(header + 30, extsize); - WRITE_16(header + 32, comsize); - WRITE_16(header + 34, 0); /* disk # */ - WRITE_16(header + 36, 0); /* int attrb */ - WRITE_32(header + 38, 0); /* ext attrb */ - WRITE_32(header + 42, currentOffset); - /* Header */ - if (fwrite(header, 1, 46, fpOutCD) == 46) { - offsetCD += 46; - - /* Filename */ - if (fnsize > 0) { - if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) { - offsetCD += fnsize; - } else { - err = Z_ERRNO; - break; - } - } else { - err = Z_STREAM_ERROR; - break; - } - - /* Extra field */ - if (extsize > 0) { - if (fwrite(extra, 1, extsize, fpOutCD) == extsize) { - offsetCD += extsize; - } else { - err = Z_ERRNO; - break; - } - } - - /* Comment field */ - if (comsize > 0) { - if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) { - offsetCD += comsize; - } else { - err = Z_ERRNO; - break; - } - } - - - } else { - err = Z_ERRNO; - break; - } - } - - /* Success */ - entries++; - - } else { - break; - } - } - - /* Final central directory */ - { - int entriesZip = entries; - char header[22]; - char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools"; - int comsize = (int) strlen(comment); - if (entriesZip > 0xffff) { - entriesZip = 0xffff; - } - WRITE_32(header, 0x06054b50); - WRITE_16(header + 4, 0); /* disk # */ - WRITE_16(header + 6, 0); /* disk # */ - WRITE_16(header + 8, entriesZip); /* hack */ - WRITE_16(header + 10, entriesZip); /* hack */ - WRITE_32(header + 12, offsetCD); /* size of CD */ - WRITE_32(header + 16, offset); /* offset to CD */ - WRITE_16(header + 20, comsize); /* comment */ - - /* Header */ - if (fwrite(header, 1, 22, fpOutCD) == 22) { - - /* Comment field */ - if (comsize > 0) { - if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) { - err = Z_ERRNO; - } - } - - } else { - err = Z_ERRNO; - } - } - - /* Final merge (file + central directory) */ - fclose(fpOutCD); - if (err == Z_OK) { - fpOutCD = fopen(fileOutTmp, "rb"); - if (fpOutCD != NULL) { - int nRead; - char buffer[8192]; - while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) { - if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) { - err = Z_ERRNO; - break; - } - } - fclose(fpOutCD); - } - } - - /* Close */ - fclose(fpZip); - fclose(fpOut); - - /* Wipe temporary file */ - (void)remove(fileOutTmp); - - /* Number of recovered entries */ - if (err == Z_OK) { - if (nRecovered != NULL) { - *nRecovered = entries; - } - if (bytesRecovered != NULL) { - *bytesRecovered = totalBytes; - } - } - } else { - err = Z_STREAM_ERROR; - } - return err; -} diff --git a/deps/zlib/contrib/minizip/mztools.h b/deps/zlib/contrib/minizip/mztools.h deleted file mode 100644 index f295ffeda6afcfdcfce36f71f1b290eec978e069..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/mztools.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Additional tools for Minizip - Code: Xavier Roche '2004 - License: Same as ZLIB (www.gzip.org) -*/ - -#ifndef _zip_tools_H -#define _zip_tools_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef _ZLIB_H -#include "third_party/zlib/zlib.h" -#endif - -#include "unzip.h" - -/* Repair a ZIP file (missing central directory) - file: file to recover - fileOut: output file after recovery - fileOutTmp: temporary file name used for recovery -*/ -extern int ZEXPORT unzRepair(const char* file, - const char* fileOut, - const char* fileOutTmp, - uLong* nRecovered, - uLong* bytesRecovered); - - -#ifdef __cplusplus -} -#endif - - -#endif diff --git a/deps/zlib/contrib/minizip/unzip.c b/deps/zlib/contrib/minizip/unzip.c deleted file mode 100644 index e8b2bc5c766c8aed7b1d7db902efcdd076122c5f..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/unzip.c +++ /dev/null @@ -1,2117 +0,0 @@ -/* unzip.c -- IO for uncompress .zip files using zlib - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications of Unzip for Zip64 - Copyright (C) 2007-2008 Even Rouault - - Modifications for Zip64 support on both zip and unzip - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - - ------------------------------------------------------------------------------------ - Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of - compatibility with older software. The following is from the original crypt.c. - Code woven in by Terry Thorsen 1/2003. - - Copyright (c) 1990-2000 Info-ZIP. All rights reserved. - - See the accompanying file LICENSE, version 2000-Apr-09 or later - (the contents of which are also included in zip.h) for terms of use. - If, for some reason, all these files are missing, the Info-ZIP license - also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html - - crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h] - - The encryption/decryption parts of this source code (as opposed to the - non-echoing password parts) were originally written in Europe. The - whole source package can be freely distributed, including from the USA. - (Prior to January 2000, re-export from the US was a violation of US law.) - - This encryption code is a direct transcription of the algorithm from - Roger Schlafly, described by Phil Katz in the file appnote.txt. This - file (appnote.txt) is distributed with the PKZIP program (even in the - version without encryption capabilities). - - ------------------------------------------------------------------------------------ - - Changes in unzip.c - - 2007-2008 - Even Rouault - Addition of cpl_unzGetCurrentFileZStreamPos - 2007-2008 - Even Rouault - Decoration of symbol names unz* -> cpl_unz* - 2007-2008 - Even Rouault - Remove old C style function prototypes - 2007-2008 - Even Rouault - Add unzip support for ZIP64 - - Copyright (C) 2007-2008 Even Rouault - - - Oct-2009 - Mathias Svensson - Removed cpl_* from symbol names (Even Rouault added them but since this is now moved to a new project (minizip64) I renamed them again). - Oct-2009 - Mathias Svensson - Fixed problem if uncompressed size was > 4G and compressed size was <4G - should only read the compressed/uncompressed size from the Zip64 format if - the size from normal header was 0xFFFFFFFF - Oct-2009 - Mathias Svensson - Applied some bug fixes from paches recived from Gilles Vollant - Oct-2009 - Mathias Svensson - Applied support to unzip files with compression mathod BZIP2 (bzip2 lib is required) - Patch created by Daniel Borca - - Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer - - Copyright (C) 1998 - 2010 Gilles Vollant, Even Rouault, Mathias Svensson - -*/ - - -#include -#include -#include - -#include "third_party/zlib/zlib.h" -#include "unzip.h" - -#ifdef STDC -# include -# include -# include -#endif -#ifdef NO_ERRNO_H - extern int errno; -#else -# include -#endif - - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - - -#ifndef CASESENSITIVITYDEFAULT_NO -# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) -# define CASESENSITIVITYDEFAULT_NO -# endif -#endif - - -#ifndef UNZ_BUFSIZE -#define UNZ_BUFSIZE (16384) -#endif - -#ifndef UNZ_MAXFILENAMEINZIP -#define UNZ_MAXFILENAMEINZIP (256) -#endif - -#ifndef ALLOC -# define ALLOC(size) (malloc(size)) -#endif -#ifndef TRYFREE -# define TRYFREE(p) {if (p) free(p);} -#endif - -#define SIZECENTRALDIRITEM (0x2e) -#define SIZEZIPLOCALHEADER (0x1e) - - -const char unz_copyright[] = - " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; - -/* unz_file_info_interntal contain internal info about a file in zipfile*/ -typedef struct unz_file_info64_internal_s -{ - ZPOS64_T offset_curfile;/* relative offset of local header 8 bytes */ -} unz_file_info64_internal; - - -/* file_in_zip_read_info_s contain internal information about a file in zipfile, - when reading and decompress it */ -typedef struct -{ - char *read_buffer; /* internal buffer for compressed data */ - z_stream stream; /* zLib stream structure for inflate */ - -#ifdef HAVE_BZIP2 - bz_stream bstream; /* bzLib stream structure for bziped */ -#endif - - ZPOS64_T pos_in_zipfile; /* position in byte on the zipfile, for fseek*/ - uLong stream_initialised; /* flag set if stream structure is initialised*/ - - ZPOS64_T offset_local_extrafield;/* offset of the local extra field */ - uInt size_local_extrafield;/* size of the local extra field */ - ZPOS64_T pos_local_extrafield; /* position in the local extra field in read*/ - ZPOS64_T total_out_64; - - uLong crc32; /* crc32 of all data uncompressed */ - uLong crc32_wait; /* crc32 we must obtain after decompress all */ - ZPOS64_T rest_read_compressed; /* number of byte to be decompressed */ - ZPOS64_T rest_read_uncompressed;/*number of byte to be obtained after decomp*/ - zlib_filefunc64_32_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - uLong compression_method; /* compression method (0==store) */ - ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - int raw; -} file_in_zip64_read_info_s; - - -/* unz64_s contain internal information about the zipfile -*/ -typedef struct -{ - zlib_filefunc64_32_def z_filefunc; - int is64bitOpenFunction; - voidpf filestream; /* io structore of the zipfile */ - unz_global_info64 gi; /* public global information */ - ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - ZPOS64_T num_file; /* number of the current file in the zipfile*/ - ZPOS64_T pos_in_central_dir; /* pos of the current file in the central dir*/ - ZPOS64_T current_file_ok; /* flag about the usability of the current file*/ - ZPOS64_T central_pos; /* position of the beginning of the central dir*/ - - ZPOS64_T size_central_dir; /* size of the central directory */ - ZPOS64_T offset_central_dir; /* offset of start of central directory with - respect to the starting disk number */ - - unz_file_info64 cur_file_info; /* public info about the current file in zip*/ - unz_file_info64_internal cur_file_info_internal; /* private info about it*/ - file_in_zip64_read_info_s* pfile_in_zip_read; /* structure about the current - file if we are decompressing it */ - int encrypted; - - int isZip64; - -# ifndef NOUNCRYPT - unsigned long keys[3]; /* keys defining the pseudo-random sequence */ - const z_crc_t* pcrc_32_tab; -# endif -} unz64_s; - - -#ifndef NOUNCRYPT -#include "crypt.h" -#endif - -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been successfully opened for reading. -*/ - - -local int unz64local_getByte OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - int *pi)); - -local int unz64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi) -{ - unsigned char c; - int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); - if (err==1) - { - *pi = (int)c; - return UNZ_OK; - } - else - { - if (ZERROR64(*pzlib_filefunc_def,filestream)) - return UNZ_ERRNO; - else - return UNZ_EOF; - } -} - - -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ -local int unz64local_getShort OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX)); - -local int unz64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX) -{ - uLong x ; - int i = 0; - int err; - - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((uLong)i)<<8; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -} - -local int unz64local_getLong OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX)); - -local int unz64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - uLong *pX) -{ - uLong x ; - int i = 0; - int err; - - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((uLong)i)<<8; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((uLong)i)<<16; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<24; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -} - -local int unz64local_getLong64 OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - ZPOS64_T *pX)); - - -local int unz64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream, - ZPOS64_T *pX) -{ - ZPOS64_T x ; - int i = 0; - int err; - - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (ZPOS64_T)i; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<8; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<16; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<24; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<32; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<40; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<48; - - if (err==UNZ_OK) - err = unz64local_getByte(pzlib_filefunc_def,filestream,&i); - x |= ((ZPOS64_T)i)<<56; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -} - -/* My own strcmpi / strcasecmp */ -local int strcmpcasenosensitive_internal (const char* fileName1, const char* fileName2) -{ - for (;;) - { - char c1=*(fileName1++); - char c2=*(fileName2++); - if ((c1>='a') && (c1<='z')) - c1 -= 0x20; - if ((c2>='a') && (c2<='z')) - c2 -= 0x20; - if (c1=='\0') - return ((c2=='\0') ? 0 : -1); - if (c2=='\0') - return 1; - if (c1c2) - return 1; - } -} - - -#ifdef CASESENSITIVITYDEFAULT_NO -#define CASESENSITIVITYDEFAULTVALUE 2 -#else -#define CASESENSITIVITYDEFAULTVALUE 1 -#endif - -#ifndef STRCMPCASENOSENTIVEFUNCTION -#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal -#endif - -/* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) - -*/ -extern int ZEXPORT unzStringFileNameCompare (const char* fileName1, - const char* fileName2, - int iCaseSensitivity) - -{ - if (iCaseSensitivity==0) - iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; - - if (iCaseSensitivity==1) - return strcmp(fileName1,fileName2); - - return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); -} - -#ifndef BUFREADCOMMENT -#define BUFREADCOMMENT (0x400) -#endif - -/* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ -local ZPOS64_T unz64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); -local ZPOS64_T unz64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) -{ - unsigned char* buf; - ZPOS64_T uSizeFile; - ZPOS64_T uBackRead; - ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ - ZPOS64_T uPosFound=0; - - if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); - if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - return uPosFound; -} - - -/* - Locate the Central directory 64 of a zipfile (at the end, just before - the global comment) -*/ -local ZPOS64_T unz64local_SearchCentralDir64 OF(( - const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream)); - -local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, - voidpf filestream) -{ - unsigned char* buf; - ZPOS64_T uSizeFile; - ZPOS64_T uBackRead; - ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ - ZPOS64_T uPosFound=0; - uLong uL; - ZPOS64_T relativeOffset; - - if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); - if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - if (uPosFound == 0) - return 0; - - /* Zip64 end of central directory locator */ - if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) - return 0; - - /* the signature, already checked */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - - /* number of the disk with the start of the zip64 end of central directory */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - if (uL != 0) - return 0; - - /* relative offset of the zip64 end of central directory record */ - if (unz64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=UNZ_OK) - return 0; - - /* total number of disks */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - if (uL != 1) - return 0; - - /* Goto end of central directory record */ - if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) - return 0; - - /* the signature */ - if (unz64local_getLong(pzlib_filefunc_def,filestream,&uL)!=UNZ_OK) - return 0; - - if (uL != 0x06064b50) - return 0; - - return relativeOffset; -} - -/* - Open a Zip file. path contain the full pathname (by example, - on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer - "zlib/zlib114.zip". - If the zipfile cannot be opened (file doesn't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ -local unzFile unzOpenInternal (const void *path, - zlib_filefunc64_32_def* pzlib_filefunc64_32_def, - int is64bitOpenFunction) -{ - unz64_s us; - unz64_s *s; - ZPOS64_T central_pos; - uLong uL; - - uLong number_disk; /* number of the current dist, used for - spaning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spaning ZIP, unsupported, always 0*/ - ZPOS64_T number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ - - int err=UNZ_OK; - - if (unz_copyright[0]!=' ') - return NULL; - - us.z_filefunc.zseek32_file = NULL; - us.z_filefunc.ztell32_file = NULL; - if (pzlib_filefunc64_32_def==NULL) - fill_fopen64_filefunc(&us.z_filefunc.zfile_func64); - else - us.z_filefunc = *pzlib_filefunc64_32_def; - us.is64bitOpenFunction = is64bitOpenFunction; - - - - us.filestream = ZOPEN64(us.z_filefunc, - path, - ZLIB_FILEFUNC_MODE_READ | - ZLIB_FILEFUNC_MODE_EXISTING); - if (us.filestream==NULL) - return NULL; - - central_pos = unz64local_SearchCentralDir64(&us.z_filefunc,us.filestream); - if (central_pos) - { - uLong uS; - ZPOS64_T uL64; - - us.isZip64 = 1; - - if (ZSEEK64(us.z_filefunc, us.filestream, - central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - /* the signature, already checked */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - - /* size of zip64 end of central directory record */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&uL64)!=UNZ_OK) - err=UNZ_ERRNO; - - /* version made by */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) - err=UNZ_ERRNO; - - /* version needed to extract */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uS)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of this disk */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of the disk with the start of the central directory */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central directory on this disk */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central directory */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - if ((number_entry_CD!=us.gi.number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=UNZ_BADZIPFILE; - - /* size of the central directory */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - /* offset of start of central directory with respect to the - starting disk number */ - if (unz64local_getLong64(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - us.gi.size_comment = 0; - } - else - { - central_pos = unz64local_SearchCentralDir(&us.z_filefunc,us.filestream); - if (central_pos==0) - err=UNZ_ERRNO; - - us.isZip64 = 0; - - if (ZSEEK64(us.z_filefunc, us.filestream, - central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - /* the signature, already checked */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of this disk */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of the disk with the start of the central directory */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central dir on this disk */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - us.gi.number_entry = uL; - - /* total number of entries in the central dir */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - number_entry_CD = uL; - - if ((number_entry_CD!=us.gi.number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=UNZ_BADZIPFILE; - - /* size of the central directory */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - us.size_central_dir = uL; - - /* offset of start of central directory with respect to the - starting disk number */ - if (unz64local_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - us.offset_central_dir = uL; - - /* zipfile comment length */ - if (unz64local_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK) - err=UNZ_ERRNO; - } - - if ((central_pospfile_in_zip_read!=NULL) - unzCloseCurrentFile(file); - - ZCLOSE64(s->z_filefunc, s->filestream); - TRYFREE(s); - return UNZ_OK; -} - - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ -extern int ZEXPORT unzGetGlobalInfo64 (unzFile file, unz_global_info64* pglobal_info) -{ - unz64_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - *pglobal_info=s->gi; - return UNZ_OK; -} - -extern int ZEXPORT unzGetGlobalInfo (unzFile file, unz_global_info* pglobal_info32) -{ - unz64_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - /* to do : check if number_entry is not truncated */ - pglobal_info32->number_entry = (uLong)s->gi.number_entry; - pglobal_info32->size_comment = s->gi.size_comment; - return UNZ_OK; -} -/* - Translate date/time from Dos format to tm_unz (readable more easilty) -*/ -local void unz64local_DosDateToTmuDate (ZPOS64_T ulDosDate, tm_unz* ptm) -{ - ZPOS64_T uDate; - uDate = (ZPOS64_T)(ulDosDate>>16); - ptm->tm_mday = (uInt)(uDate&0x1f) ; - ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; - ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; - - ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); - ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; - ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; -} - -/* - Get Info about the current file in the zipfile, with internal only info -*/ -local int unz64local_GetCurrentFileInfoInternal OF((unzFile file, - unz_file_info64 *pfile_info, - unz_file_info64_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); - -local int unz64local_GetCurrentFileInfoInternal (unzFile file, - unz_file_info64 *pfile_info, - unz_file_info64_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize) -{ - unz64_s* s; - unz_file_info64 file_info; - unz_file_info64_internal file_info_internal; - int err=UNZ_OK; - uLong uMagic; - long lSeek=0; - uLong uL; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (ZSEEK64(s->z_filefunc, s->filestream, - s->pos_in_central_dir+s->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET)!=0) - err=UNZ_ERRNO; - - - /* we check the magic */ - if (err==UNZ_OK) - { - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x02014b50) - err=UNZ_BADZIPFILE; - } - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK) - err=UNZ_ERRNO; - - unz64local_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - file_info.compressed_size = uL; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - file_info.uncompressed_size = uL; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK) - err=UNZ_ERRNO; - - // relative offset of local header - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - file_info_internal.offset_curfile = uL; - - lSeek+=file_info.size_filename; - if ((err==UNZ_OK) && (szFileName!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_filename0) && (fileNameBufferSize>0)) - if (ZREAD64(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - lSeek -= uSizeRead; - } - - // Read extrafield - if ((err==UNZ_OK) && (extraField!=NULL)) - { - ZPOS64_T uSizeRead ; - if (file_info.size_file_extraz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - } - - if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) - if (ZREAD64(s->z_filefunc, s->filestream,extraField,(uLong)uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - - lSeek += file_info.size_file_extra - (uLong)uSizeRead; - } - else - lSeek += file_info.size_file_extra; - - - if ((err==UNZ_OK) && (file_info.size_file_extra != 0)) - { - uLong acc = 0; - - // since lSeek now points to after the extra field we need to move back - lSeek -= file_info.size_file_extra; - - if (lSeek!=0) - { - if (ZSEEK64(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - } - - while(acc < file_info.size_file_extra) - { - uLong headerId; - uLong dataSize; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&headerId) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&dataSize) != UNZ_OK) - err=UNZ_ERRNO; - - /* ZIP64 extra fields */ - if (headerId == 0x0001) - { - uLong uL; - - if(file_info.uncompressed_size == MAXU32) - { - if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK) - err=UNZ_ERRNO; - } - - if(file_info.compressed_size == MAXU32) - { - if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK) - err=UNZ_ERRNO; - } - - if(file_info_internal.offset_curfile == MAXU32) - { - /* Relative Header offset */ - if (unz64local_getLong64(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK) - err=UNZ_ERRNO; - } - - if(file_info.disk_num_start == MAXU32) - { - /* Disk Start Number */ - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uL) != UNZ_OK) - err=UNZ_ERRNO; - } - - } - else - { - if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0) - err=UNZ_ERRNO; - } - - acc += 2 + 2 + dataSize; - } - } - - if ((err==UNZ_OK) && (szComment!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_file_commentz_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - } - - if ((file_info.size_file_comment>0) && (commentBufferSize>0)) - if (ZREAD64(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead) - err=UNZ_ERRNO; - lSeek+=file_info.size_file_comment - uSizeRead; - } - else - lSeek+=file_info.size_file_comment; - - - if ((err==UNZ_OK) && (pfile_info!=NULL)) - *pfile_info=file_info; - - if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) - *pfile_info_internal=file_info_internal; - - return err; -} - - - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. -*/ -extern int ZEXPORT unzGetCurrentFileInfo64 (unzFile file, - unz_file_info64 * pfile_info, - char * szFileName, uLong fileNameBufferSize, - void *extraField, uLong extraFieldBufferSize, - char* szComment, uLong commentBufferSize) -{ - return unz64local_GetCurrentFileInfoInternal(file,pfile_info,NULL, - szFileName,fileNameBufferSize, - extraField,extraFieldBufferSize, - szComment,commentBufferSize); -} - -extern int ZEXPORT unzGetCurrentFileInfo (unzFile file, - unz_file_info * pfile_info, - char * szFileName, uLong fileNameBufferSize, - void *extraField, uLong extraFieldBufferSize, - char* szComment, uLong commentBufferSize) -{ - int err; - unz_file_info64 file_info64; - err = unz64local_GetCurrentFileInfoInternal(file,&file_info64,NULL, - szFileName,fileNameBufferSize, - extraField,extraFieldBufferSize, - szComment,commentBufferSize); - if ((err==UNZ_OK) && (pfile_info != NULL)) - { - pfile_info->version = file_info64.version; - pfile_info->version_needed = file_info64.version_needed; - pfile_info->flag = file_info64.flag; - pfile_info->compression_method = file_info64.compression_method; - pfile_info->dosDate = file_info64.dosDate; - pfile_info->crc = file_info64.crc; - - pfile_info->size_filename = file_info64.size_filename; - pfile_info->size_file_extra = file_info64.size_file_extra; - pfile_info->size_file_comment = file_info64.size_file_comment; - - pfile_info->disk_num_start = file_info64.disk_num_start; - pfile_info->internal_fa = file_info64.internal_fa; - pfile_info->external_fa = file_info64.external_fa; - - pfile_info->tmu_date = file_info64.tmu_date, - - - pfile_info->compressed_size = (uLong)file_info64.compressed_size; - pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size; - - } - return err; -} -/* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ -extern int ZEXPORT unzGoToFirstFile (unzFile file) -{ - int err=UNZ_OK; - unz64_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - s->pos_in_central_dir=s->offset_central_dir; - s->num_file=0; - err=unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; -} - -/* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ -extern int ZEXPORT unzGoToNextFile (unzFile file) -{ - unz64_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */ - if (s->num_file+1==s->gi.number_entry) - return UNZ_END_OF_LIST_OF_FILE; - - s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + - s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; - s->num_file++; - err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; -} - - -/* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ -extern int ZEXPORT unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) -{ - unz64_s* s; - int err; - - /* We remember the 'current' position in the file so that we can jump - * back there if we fail. - */ - unz_file_info64 cur_file_infoSaved; - unz_file_info64_internal cur_file_info_internalSaved; - ZPOS64_T num_fileSaved; - ZPOS64_T pos_in_central_dirSaved; - - - if (file==NULL) - return UNZ_PARAMERROR; - - if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) - return UNZ_PARAMERROR; - - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - - /* Save the current state */ - num_fileSaved = s->num_file; - pos_in_central_dirSaved = s->pos_in_central_dir; - cur_file_infoSaved = s->cur_file_info; - cur_file_info_internalSaved = s->cur_file_info_internal; - - err = unzGoToFirstFile(file); - - while (err == UNZ_OK) - { - char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; - err = unzGetCurrentFileInfo64(file,NULL, - szCurrentFileName,sizeof(szCurrentFileName)-1, - NULL,0,NULL,0); - if (err == UNZ_OK) - { - if (unzStringFileNameCompare(szCurrentFileName, - szFileName,iCaseSensitivity)==0) - return UNZ_OK; - err = unzGoToNextFile(file); - } - } - - /* We failed, so restore the state of the 'current file' to where we - * were. - */ - s->num_file = num_fileSaved ; - s->pos_in_central_dir = pos_in_central_dirSaved ; - s->cur_file_info = cur_file_infoSaved; - s->cur_file_info_internal = cur_file_info_internalSaved; - return err; -} - - -/* -/////////////////////////////////////////// -// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) -// I need random access -// -// Further optimization could be realized by adding an ability -// to cache the directory in memory. The goal being a single -// comprehensive file read to put the file I need in a memory. -*/ - -/* -typedef struct unz_file_pos_s -{ - ZPOS64_T pos_in_zip_directory; // offset in file - ZPOS64_T num_of_file; // # of file -} unz_file_pos; -*/ - -extern int ZEXPORT unzGetFilePos64(unzFile file, unz64_file_pos* file_pos) -{ - unz64_s* s; - - if (file==NULL || file_pos==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - - file_pos->pos_in_zip_directory = s->pos_in_central_dir; - file_pos->num_of_file = s->num_file; - - return UNZ_OK; -} - -extern int ZEXPORT unzGetFilePos( - unzFile file, - unz_file_pos* file_pos) -{ - unz64_file_pos file_pos64; - int err = unzGetFilePos64(file,&file_pos64); - if (err==UNZ_OK) - { - file_pos->pos_in_zip_directory = (uLong)file_pos64.pos_in_zip_directory; - file_pos->num_of_file = (uLong)file_pos64.num_of_file; - } - return err; -} - -extern int ZEXPORT unzGoToFilePos64(unzFile file, const unz64_file_pos* file_pos) -{ - unz64_s* s; - int err; - - if (file==NULL || file_pos==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - - /* jump to the right spot */ - s->pos_in_central_dir = file_pos->pos_in_zip_directory; - s->num_file = file_pos->num_of_file; - - /* set the current file */ - err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - /* return results */ - s->current_file_ok = (err == UNZ_OK); - return err; -} - -extern int ZEXPORT unzGoToFilePos( - unzFile file, - unz_file_pos* file_pos) -{ - unz64_file_pos file_pos64; - if (file_pos == NULL) - return UNZ_PARAMERROR; - - file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; - file_pos64.num_of_file = file_pos->num_of_file; - return unzGoToFilePos64(file,&file_pos64); -} - -/* -// Unzip Helper Functions - should be here? -/////////////////////////////////////////// -*/ - -/* - Read the local header of the current zipfile - Check the coherency of the local header and info in the end of central - directory about this file - store in *piSizeVar the size of extra info in local header - (filename and size of extra field data) -*/ -local int unz64local_CheckCurrentFileCoherencyHeader (unz64_s* s, uInt* piSizeVar, - ZPOS64_T * poffset_local_extrafield, - uInt * psize_local_extrafield) -{ - uLong uMagic,uData,uFlags; - uLong size_filename; - uLong size_extra_field; - int err=UNZ_OK; - - *piSizeVar = 0; - *poffset_local_extrafield = 0; - *psize_local_extrafield = 0; - - if (ZSEEK64(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile + - s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - - if (err==UNZ_OK) - { - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x04034b50) - err=UNZ_BADZIPFILE; - } - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) - err=UNZ_ERRNO; -/* - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) - err=UNZ_BADZIPFILE; -*/ - if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) - err=UNZ_ERRNO; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) - err=UNZ_BADZIPFILE; - - if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && -/* #ifdef HAVE_BZIP2 */ - (s->cur_file_info.compression_method!=Z_BZIP2ED) && -/* #endif */ - (s->cur_file_info.compression_method!=Z_DEFLATED)) - err=UNZ_BADZIPFILE; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */ - err=UNZ_ERRNO; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */ - err=UNZ_ERRNO; - else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unz64local_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */ - err=UNZ_ERRNO; - else if (uData != 0xFFFFFFFF && (err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) - err=UNZ_BADZIPFILE; - - *piSizeVar += (uInt)size_filename; - - if (unz64local_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK) - err=UNZ_ERRNO; - *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + - SIZEZIPLOCALHEADER + size_filename; - *psize_local_extrafield = (uInt)size_extra_field; - - *piSizeVar += (uInt)size_extra_field; - - return err; -} - -/* - Open for reading data the current file in the zipfile. - If there is no error and the file is opened, the return value is UNZ_OK. -*/ -extern int ZEXPORT unzOpenCurrentFile3 (unzFile file, int* method, - int* level, int raw, const char* password) -{ - int err=UNZ_OK; - uInt iSizeVar; - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - ZPOS64_T offset_local_extrafield; /* offset of the local extra field */ - uInt size_local_extrafield; /* size of the local extra field */ -# ifndef NOUNCRYPT - char source[12]; -# else - if (password != NULL) - return UNZ_PARAMERROR; -# endif - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return UNZ_PARAMERROR; - - if (s->pfile_in_zip_read != NULL) - unzCloseCurrentFile(file); - - if (unz64local_CheckCurrentFileCoherencyHeader(s,&iSizeVar, &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) - return UNZ_BADZIPFILE; - - pfile_in_zip_read_info = (file_in_zip64_read_info_s*)ALLOC(sizeof(file_in_zip64_read_info_s)); - if (pfile_in_zip_read_info==NULL) - return UNZ_INTERNALERROR; - - pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE); - pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; - pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; - pfile_in_zip_read_info->pos_local_extrafield=0; - pfile_in_zip_read_info->raw=raw; - - if (pfile_in_zip_read_info->read_buffer==NULL) - { - TRYFREE(pfile_in_zip_read_info); - return UNZ_INTERNALERROR; - } - - pfile_in_zip_read_info->stream_initialised=0; - - if (method!=NULL) - *method = (int)s->cur_file_info.compression_method; - - if (level!=NULL) - { - *level = 6; - switch (s->cur_file_info.flag & 0x06) - { - case 6 : *level = 1; break; - case 4 : *level = 2; break; - case 2 : *level = 9; break; - } - } - - if ((s->cur_file_info.compression_method!=0) && -/* #ifdef HAVE_BZIP2 */ - (s->cur_file_info.compression_method!=Z_BZIP2ED) && -/* #endif */ - (s->cur_file_info.compression_method!=Z_DEFLATED)) - - err=UNZ_BADZIPFILE; - - pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; - pfile_in_zip_read_info->crc32=0; - pfile_in_zip_read_info->total_out_64=0; - pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method; - pfile_in_zip_read_info->filestream=s->filestream; - pfile_in_zip_read_info->z_filefunc=s->z_filefunc; - pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; - - pfile_in_zip_read_info->stream.total_out = 0; - - if ((s->cur_file_info.compression_method==Z_BZIP2ED) && (!raw)) - { -#ifdef HAVE_BZIP2 - pfile_in_zip_read_info->bstream.bzalloc = (void *(*) (void *, int, int))0; - pfile_in_zip_read_info->bstream.bzfree = (free_func)0; - pfile_in_zip_read_info->bstream.opaque = (voidpf)0; - pfile_in_zip_read_info->bstream.state = (voidpf)0; - - pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; - pfile_in_zip_read_info->stream.zfree = (free_func)0; - pfile_in_zip_read_info->stream.opaque = (voidpf)0; - pfile_in_zip_read_info->stream.next_in = (voidpf)0; - pfile_in_zip_read_info->stream.avail_in = 0; - - err=BZ2_bzDecompressInit(&pfile_in_zip_read_info->bstream, 0, 0); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=Z_BZIP2ED; - else - { - TRYFREE(pfile_in_zip_read_info); - return err; - } -#else - pfile_in_zip_read_info->raw=1; -#endif - } - else if ((s->cur_file_info.compression_method==Z_DEFLATED) && (!raw)) - { - pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; - pfile_in_zip_read_info->stream.zfree = (free_func)0; - pfile_in_zip_read_info->stream.opaque = (voidpf)0; - pfile_in_zip_read_info->stream.next_in = 0; - pfile_in_zip_read_info->stream.avail_in = 0; - - err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=Z_DEFLATED; - else - { - TRYFREE(pfile_in_zip_read_info); - return err; - } - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. - * In unzip, i don't wait absolutely Z_STREAM_END because I known the - * size of both compressed and uncompressed data - */ - } - pfile_in_zip_read_info->rest_read_compressed = - s->cur_file_info.compressed_size ; - pfile_in_zip_read_info->rest_read_uncompressed = - s->cur_file_info.uncompressed_size ; - - - pfile_in_zip_read_info->pos_in_zipfile = - s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + - iSizeVar; - - pfile_in_zip_read_info->stream.avail_in = (uInt)0; - - s->pfile_in_zip_read = pfile_in_zip_read_info; - s->encrypted = 0; - -# ifndef NOUNCRYPT - if (password != NULL) - { - int i; - s->pcrc_32_tab = get_crc_table(); - init_keys(password,s->keys,s->pcrc_32_tab); - if (ZSEEK64(s->z_filefunc, s->filestream, - s->pfile_in_zip_read->pos_in_zipfile + - s->pfile_in_zip_read->byte_before_the_zipfile, - SEEK_SET)!=0) - return UNZ_INTERNALERROR; - if(ZREAD64(s->z_filefunc, s->filestream,source, 12)<12) - return UNZ_INTERNALERROR; - - for (i = 0; i<12; i++) - zdecode(s->keys,s->pcrc_32_tab,source[i]); - - s->pfile_in_zip_read->pos_in_zipfile+=12; - s->pfile_in_zip_read->rest_read_compressed-=12; - s->encrypted=1; - } -# endif - - - return UNZ_OK; -} - -extern int ZEXPORT unzOpenCurrentFile (unzFile file) -{ - return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); -} - -extern int ZEXPORT unzOpenCurrentFilePassword (unzFile file, const char* password) -{ - return unzOpenCurrentFile3(file, NULL, NULL, 0, password); -} - -extern int ZEXPORT unzOpenCurrentFile2 (unzFile file, int* method, int* level, int raw) -{ - return unzOpenCurrentFile3(file, method, level, raw, NULL); -} - -/** Addition for GDAL : START */ - -extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64( unzFile file) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - s=(unz64_s*)file; - if (file==NULL) - return 0; //UNZ_PARAMERROR; - pfile_in_zip_read_info=s->pfile_in_zip_read; - if (pfile_in_zip_read_info==NULL) - return 0; //UNZ_PARAMERROR; - return pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile; -} - -/** Addition for GDAL : END */ - -/* - Read bytes from the current file. - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ -extern int ZEXPORT unzReadCurrentFile (unzFile file, voidp buf, unsigned len) -{ - int err=UNZ_OK; - uInt iRead = 0; - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if (pfile_in_zip_read_info->read_buffer == NULL) - return UNZ_END_OF_LIST_OF_FILE; - if (len==0) - return 0; - - pfile_in_zip_read_info->stream.next_out = (Bytef*)buf; - - pfile_in_zip_read_info->stream.avail_out = (uInt)len; - - if ((len>pfile_in_zip_read_info->rest_read_compressed+ - pfile_in_zip_read_info->stream.avail_in) && - (pfile_in_zip_read_info->raw)) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_compressed+ - pfile_in_zip_read_info->stream.avail_in; - - while (pfile_in_zip_read_info->stream.avail_out>0) - { - if ((pfile_in_zip_read_info->stream.avail_in==0) && - (pfile_in_zip_read_info->rest_read_compressed>0)) - { - uInt uReadThis = UNZ_BUFSIZE; - if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; - if (uReadThis == 0) - return UNZ_EOF; - if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile, - ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - if (ZREAD64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->read_buffer, - uReadThis)!=uReadThis) - return UNZ_ERRNO; - - -# ifndef NOUNCRYPT - if(s->encrypted) - { - uInt i; - for(i=0;iread_buffer[i] = - zdecode(s->keys,s->pcrc_32_tab, - pfile_in_zip_read_info->read_buffer[i]); - } -# endif - - - pfile_in_zip_read_info->pos_in_zipfile += uReadThis; - - pfile_in_zip_read_info->rest_read_compressed-=uReadThis; - - pfile_in_zip_read_info->stream.next_in = - (Bytef*)pfile_in_zip_read_info->read_buffer; - pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; - } - - if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw)) - { - uInt uDoCopy,i ; - - if ((pfile_in_zip_read_info->stream.avail_in == 0) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - return (iRead==0) ? UNZ_EOF : iRead; - - if (pfile_in_zip_read_info->stream.avail_out < - pfile_in_zip_read_info->stream.avail_in) - uDoCopy = pfile_in_zip_read_info->stream.avail_out ; - else - uDoCopy = pfile_in_zip_read_info->stream.avail_in ; - - for (i=0;istream.next_out+i) = - *(pfile_in_zip_read_info->stream.next_in+i); - - pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uDoCopy; - - pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, - pfile_in_zip_read_info->stream.next_out, - uDoCopy); - pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; - pfile_in_zip_read_info->stream.avail_in -= uDoCopy; - pfile_in_zip_read_info->stream.avail_out -= uDoCopy; - pfile_in_zip_read_info->stream.next_out += uDoCopy; - pfile_in_zip_read_info->stream.next_in += uDoCopy; - pfile_in_zip_read_info->stream.total_out += uDoCopy; - iRead += uDoCopy; - } - else if (pfile_in_zip_read_info->compression_method==Z_BZIP2ED) - { -#ifdef HAVE_BZIP2 - uLong uTotalOutBefore,uTotalOutAfter; - const Bytef *bufBefore; - uLong uOutThis; - - pfile_in_zip_read_info->bstream.next_in = (char*)pfile_in_zip_read_info->stream.next_in; - pfile_in_zip_read_info->bstream.avail_in = pfile_in_zip_read_info->stream.avail_in; - pfile_in_zip_read_info->bstream.total_in_lo32 = pfile_in_zip_read_info->stream.total_in; - pfile_in_zip_read_info->bstream.total_in_hi32 = 0; - pfile_in_zip_read_info->bstream.next_out = (char*)pfile_in_zip_read_info->stream.next_out; - pfile_in_zip_read_info->bstream.avail_out = pfile_in_zip_read_info->stream.avail_out; - pfile_in_zip_read_info->bstream.total_out_lo32 = pfile_in_zip_read_info->stream.total_out; - pfile_in_zip_read_info->bstream.total_out_hi32 = 0; - - uTotalOutBefore = pfile_in_zip_read_info->bstream.total_out_lo32; - bufBefore = (const Bytef *)pfile_in_zip_read_info->bstream.next_out; - - err=BZ2_bzDecompress(&pfile_in_zip_read_info->bstream); - - uTotalOutAfter = pfile_in_zip_read_info->bstream.total_out_lo32; - uOutThis = uTotalOutAfter-uTotalOutBefore; - - pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; - - pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,bufBefore, (uInt)(uOutThis)); - pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis; - iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); - - pfile_in_zip_read_info->stream.next_in = (Bytef*)pfile_in_zip_read_info->bstream.next_in; - pfile_in_zip_read_info->stream.avail_in = pfile_in_zip_read_info->bstream.avail_in; - pfile_in_zip_read_info->stream.total_in = pfile_in_zip_read_info->bstream.total_in_lo32; - pfile_in_zip_read_info->stream.next_out = (Bytef*)pfile_in_zip_read_info->bstream.next_out; - pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->bstream.avail_out; - pfile_in_zip_read_info->stream.total_out = pfile_in_zip_read_info->bstream.total_out_lo32; - - if (err==BZ_STREAM_END) - return (iRead==0) ? UNZ_EOF : iRead; - if (err!=BZ_OK) - break; -#endif - } // end Z_BZIP2ED - else - { - ZPOS64_T uTotalOutBefore,uTotalOutAfter; - const Bytef *bufBefore; - ZPOS64_T uOutThis; - int flush=Z_SYNC_FLUSH; - - uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; - bufBefore = pfile_in_zip_read_info->stream.next_out; - - /* - if ((pfile_in_zip_read_info->rest_read_uncompressed == - pfile_in_zip_read_info->stream.avail_out) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - flush = Z_FINISH; - */ - err=inflate(&pfile_in_zip_read_info->stream,flush); - - if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL)) - err = Z_DATA_ERROR; - - uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; - uOutThis = uTotalOutAfter-uTotalOutBefore; - - pfile_in_zip_read_info->total_out_64 = pfile_in_zip_read_info->total_out_64 + uOutThis; - - pfile_in_zip_read_info->crc32 = - crc32(pfile_in_zip_read_info->crc32,bufBefore, - (uInt)(uOutThis)); - - pfile_in_zip_read_info->rest_read_uncompressed -= - uOutThis; - - iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); - - if (err==Z_STREAM_END) - return (iRead==0) ? UNZ_EOF : iRead; - if (err!=Z_OK) - break; - } - } - - if (err==Z_OK) - return iRead; - return err; -} - - -/* - Give the current position in uncompressed data -*/ -extern z_off_t ZEXPORT unztell (unzFile file) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - return (z_off_t)pfile_in_zip_read_info->stream.total_out; -} - -extern ZPOS64_T ZEXPORT unztell64 (unzFile file) -{ - - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return (ZPOS64_T)-1; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return (ZPOS64_T)-1; - - return pfile_in_zip_read_info->total_out_64; -} - - -/* - return 1 if the end of file was reached, 0 elsewhere -*/ -extern int ZEXPORT unzeof (unzFile file) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - if (pfile_in_zip_read_info->rest_read_uncompressed == 0) - return 1; - else - return 0; -} - - - -/* -Read extra field from the current file (opened by unzOpenCurrentFile) -This is the local-header version of the extra field (sometimes, there is -more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field that can be read - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ -extern int ZEXPORT unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len) -{ - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - uInt read_now; - ZPOS64_T size_to_read; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - size_to_read = (pfile_in_zip_read_info->size_local_extrafield - - pfile_in_zip_read_info->pos_local_extrafield); - - if (buf==NULL) - return (int)size_to_read; - - if (len>size_to_read) - read_now = (uInt)size_to_read; - else - read_now = (uInt)len ; - - if (read_now==0) - return 0; - - if (ZSEEK64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - pfile_in_zip_read_info->offset_local_extrafield + - pfile_in_zip_read_info->pos_local_extrafield, - ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - if (ZREAD64(pfile_in_zip_read_info->z_filefunc, - pfile_in_zip_read_info->filestream, - buf,read_now)!=read_now) - return UNZ_ERRNO; - - return (int)read_now; -} - -/* - Close the file in zip opened with unzOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ -extern int ZEXPORT unzCloseCurrentFile (unzFile file) -{ - int err=UNZ_OK; - - unz64_s* s; - file_in_zip64_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) && - (!pfile_in_zip_read_info->raw)) - { - if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) - err=UNZ_CRCERROR; - } - - - TRYFREE(pfile_in_zip_read_info->read_buffer); - pfile_in_zip_read_info->read_buffer = NULL; - if (pfile_in_zip_read_info->stream_initialised == Z_DEFLATED) - inflateEnd(&pfile_in_zip_read_info->stream); -#ifdef HAVE_BZIP2 - else if (pfile_in_zip_read_info->stream_initialised == Z_BZIP2ED) - BZ2_bzDecompressEnd(&pfile_in_zip_read_info->bstream); -#endif - - - pfile_in_zip_read_info->stream_initialised = 0; - TRYFREE(pfile_in_zip_read_info); - - s->pfile_in_zip_read=NULL; - - return err; -} - - -/* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ -extern int ZEXPORT unzGetGlobalComment (unzFile file, char * szComment, uLong uSizeBuf) -{ - unz64_s* s; - uLong uReadThis ; - if (file==NULL) - return (int)UNZ_PARAMERROR; - s=(unz64_s*)file; - - uReadThis = uSizeBuf; - if (uReadThis>s->gi.size_comment) - uReadThis = s->gi.size_comment; - - if (ZSEEK64(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0) - return UNZ_ERRNO; - - if (uReadThis>0) - { - *szComment='\0'; - if (ZREAD64(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis) - return UNZ_ERRNO; - } - - if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) - *(szComment+s->gi.size_comment)='\0'; - return (int)uReadThis; -} - -/* Additions by RX '2004 */ -extern ZPOS64_T ZEXPORT unzGetOffset64(unzFile file) -{ - unz64_s* s; - - if (file==NULL) - return 0; //UNZ_PARAMERROR; - s=(unz64_s*)file; - if (!s->current_file_ok) - return 0; - if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff) - if (s->num_file==s->gi.number_entry) - return 0; - return s->pos_in_central_dir; -} - -extern uLong ZEXPORT unzGetOffset (unzFile file) -{ - ZPOS64_T offset64; - - if (file==NULL) - return 0; //UNZ_PARAMERROR; - offset64 = unzGetOffset64(file); - return (uLong)offset64; -} - -extern int ZEXPORT unzSetOffset64(unzFile file, ZPOS64_T pos) -{ - unz64_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz64_s*)file; - - s->pos_in_central_dir = pos; - s->num_file = s->gi.number_entry; /* hack */ - err = unz64local_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; -} - -extern int ZEXPORT unzSetOffset (unzFile file, uLong pos) -{ - return unzSetOffset64(file,pos); -} diff --git a/deps/zlib/contrib/minizip/unzip.h b/deps/zlib/contrib/minizip/unzip.h deleted file mode 100644 index 3c0143529b914464781d7c6a4666c13232e0c5ca..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/unzip.h +++ /dev/null @@ -1,437 +0,0 @@ -/* unzip.h -- IO for uncompress .zip files using zlib - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications of Unzip for Zip64 - Copyright (C) 2007-2008 Even Rouault - - Modifications for Zip64 support on both zip and unzip - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - --------------------------------------------------------------------------------- - - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - --------------------------------------------------------------------------------- - - Changes - - See header of unzip64.c - -*/ - -#ifndef _unz64_H -#define _unz64_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef _ZLIB_H -#include "third_party/zlib/zlib.h" -#endif - -#ifndef _ZLIBIOAPI_H -#include "ioapi.h" -#endif - -#ifdef HAVE_BZIP2 -#include "bzlib.h" -#endif - -#define Z_BZIP2ED 12 - -#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) -/* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ -typedef struct TagunzFile__ { int unused; } unzFile__; -typedef unzFile__ *unzFile; -#else -typedef voidp unzFile; -#endif - - -#define UNZ_OK (0) -#define UNZ_END_OF_LIST_OF_FILE (-100) -#define UNZ_ERRNO (Z_ERRNO) -#define UNZ_EOF (0) -#define UNZ_PARAMERROR (-102) -#define UNZ_BADZIPFILE (-103) -#define UNZ_INTERNALERROR (-104) -#define UNZ_CRCERROR (-105) - -/* tm_unz contain date/time info */ -typedef struct tm_unz_s -{ - uInt tm_sec; /* seconds after the minute - [0,59] */ - uInt tm_min; /* minutes after the hour - [0,59] */ - uInt tm_hour; /* hours since midnight - [0,23] */ - uInt tm_mday; /* day of the month - [1,31] */ - uInt tm_mon; /* months since January - [0,11] */ - uInt tm_year; /* years - [1980..2044] */ -} tm_unz; - -/* unz_global_info structure contain global data about the ZIPfile - These data comes from the end of central dir */ -typedef struct unz_global_info64_s -{ - ZPOS64_T number_entry; /* total number of entries in - the central dir on this disk */ - uLong size_comment; /* size of the global comment of the zipfile */ -} unz_global_info64; - -typedef struct unz_global_info_s -{ - uLong number_entry; /* total number of entries in - the central dir on this disk */ - uLong size_comment; /* size of the global comment of the zipfile */ -} unz_global_info; - -/* unz_file_info contain information about a file in the zipfile */ -typedef struct unz_file_info64_s -{ - uLong version; /* version made by 2 bytes */ - uLong version_needed; /* version needed to extract 2 bytes */ - uLong flag; /* general purpose bit flag 2 bytes */ - uLong compression_method; /* compression method 2 bytes */ - uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ - uLong crc; /* crc-32 4 bytes */ - ZPOS64_T compressed_size; /* compressed size 8 bytes */ - ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */ - uLong size_filename; /* filename length 2 bytes */ - uLong size_file_extra; /* extra field length 2 bytes */ - uLong size_file_comment; /* file comment length 2 bytes */ - - uLong disk_num_start; /* disk number start 2 bytes */ - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ - - tm_unz tmu_date; -} unz_file_info64; - -typedef struct unz_file_info_s -{ - uLong version; /* version made by 2 bytes */ - uLong version_needed; /* version needed to extract 2 bytes */ - uLong flag; /* general purpose bit flag 2 bytes */ - uLong compression_method; /* compression method 2 bytes */ - uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ - uLong crc; /* crc-32 4 bytes */ - uLong compressed_size; /* compressed size 4 bytes */ - uLong uncompressed_size; /* uncompressed size 4 bytes */ - uLong size_filename; /* filename length 2 bytes */ - uLong size_file_extra; /* extra field length 2 bytes */ - uLong size_file_comment; /* file comment length 2 bytes */ - - uLong disk_num_start; /* disk number start 2 bytes */ - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ - - tm_unz tmu_date; -} unz_file_info; - -extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, - const char* fileName2, - int iCaseSensitivity)); -/* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) -*/ - - -extern unzFile ZEXPORT unzOpen OF((const char *path)); -extern unzFile ZEXPORT unzOpen64 OF((const void *path)); -/* - Open a Zip file. path contain the full pathname (by example, - on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer - "zlib/zlib113.zip". - If the zipfile cannot be opened (file don't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. - the "64" function take a const void* pointer, because the path is just the - value passed to the open64_file_func callback. - Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path - is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* - does not describe the reality -*/ - - -extern unzFile ZEXPORT unzOpen2 OF((const char *path, - zlib_filefunc_def* pzlib_filefunc_def)); -/* - Open a Zip file, like unzOpen, but provide a set of file low level API - for read/write the zip file (see ioapi.h) -*/ - -extern unzFile ZEXPORT unzOpen2_64 OF((const void *path, - zlib_filefunc64_def* pzlib_filefunc_def)); -/* - Open a Zip file, like unz64Open, but provide a set of file low level API - for read/write the zip file (see ioapi.h) -*/ - -extern int ZEXPORT unzClose OF((unzFile file)); -/* - Close a ZipFile opened with unzOpen. - If there is files inside the .Zip opened with unzOpenCurrentFile (see later), - these files MUST be closed with unzCloseCurrentFile before call unzClose. - return UNZ_OK if there is no problem. */ - -extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, - unz_global_info *pglobal_info)); - -extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file, - unz_global_info64 *pglobal_info)); -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ - - -extern int ZEXPORT unzGetGlobalComment OF((unzFile file, - char *szComment, - uLong uSizeBuf)); -/* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ - - -/***************************************************************************/ -/* Unzip package allow you browse the directory of the zipfile */ - -extern int ZEXPORT unzGoToFirstFile OF((unzFile file)); -/* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ - -extern int ZEXPORT unzGoToNextFile OF((unzFile file)); -/* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ - -extern int ZEXPORT unzLocateFile OF((unzFile file, - const char *szFileName, - int iCaseSensitivity)); -/* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ - - -/* ****************************************** */ -/* Ryan supplied functions */ -/* unz_file_info contain information about a file in the zipfile */ -typedef struct unz_file_pos_s -{ - uLong pos_in_zip_directory; /* offset in zip file directory */ - uLong num_of_file; /* # of file */ -} unz_file_pos; - -extern int ZEXPORT unzGetFilePos( - unzFile file, - unz_file_pos* file_pos); - -extern int ZEXPORT unzGoToFilePos( - unzFile file, - unz_file_pos* file_pos); - -typedef struct unz64_file_pos_s -{ - ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */ - ZPOS64_T num_of_file; /* # of file */ -} unz64_file_pos; - -extern int ZEXPORT unzGetFilePos64( - unzFile file, - unz64_file_pos* file_pos); - -extern int ZEXPORT unzGoToFilePos64( - unzFile file, - const unz64_file_pos* file_pos); - -/* ****************************************** */ - -extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file, - unz_file_info64 *pfile_info, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); - -extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, - unz_file_info *pfile_info, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize)); -/* - Get Info about the current file - if pfile_info!=NULL, the *pfile_info structure will contain somes info about - the current file - if szFileName!=NULL, the filemane string will be copied in szFileName - (fileNameBufferSize is the size of the buffer) - if extraField!=NULL, the extra field information will be copied in extraField - (extraFieldBufferSize is the size of the buffer). - This is the Central-header version of the extra field - if szComment!=NULL, the comment string of the file will be copied in szComment - (commentBufferSize is the size of the buffer) -*/ - - -/** Addition for GDAL : START */ - -extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file)); - -/** Addition for GDAL : END */ - - -/***************************************************************************/ -/* for reading the content of the current zipfile, you can open it, read data - from it, and close it (you can close it before reading all the file) - */ - -extern int ZEXPORT unzOpenCurrentFile OF((unzFile file)); -/* - Open for reading data the current file in the zipfile. - If there is no error, the return value is UNZ_OK. -*/ - -extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, - const char* password)); -/* - Open for reading data the current file in the zipfile. - password is a crypting password - If there is no error, the return value is UNZ_OK. -*/ - -extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, - int* method, - int* level, - int raw)); -/* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL -*/ - -extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, - int* method, - int* level, - int raw, - const char* password)); -/* - Same than unzOpenCurrentFile, but open for read raw the file (not uncompress) - if raw==1 - *method will receive method of compression, *level will receive level of - compression - note : you can set level parameter as NULL (if you did not want known level, - but you CANNOT set method parameter as NULL -*/ - - -extern int ZEXPORT unzCloseCurrentFile OF((unzFile file)); -/* - Close the file in zip opened with unzOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ - -extern int ZEXPORT unzReadCurrentFile OF((unzFile file, - voidp buf, - unsigned len)); -/* - Read bytes from the current file (opened by unzOpenCurrentFile) - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ - -extern z_off_t ZEXPORT unztell OF((unzFile file)); - -extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file)); -/* - Give the current position in uncompressed data -*/ - -extern int ZEXPORT unzeof OF((unzFile file)); -/* - return 1 if the end of file was reached, 0 elsewhere -*/ - -extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, - voidp buf, - unsigned len)); -/* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ - -/***************************************************************************/ - -/* Get the current file offset */ -extern ZPOS64_T ZEXPORT unzGetOffset64 (unzFile file); -extern uLong ZEXPORT unzGetOffset (unzFile file); - -/* Set the current file offset */ -extern int ZEXPORT unzSetOffset64 (unzFile file, ZPOS64_T pos); -extern int ZEXPORT unzSetOffset (unzFile file, uLong pos); - - - -#ifdef __cplusplus -} -#endif - -#endif /* _unz64_H */ diff --git a/deps/zlib/contrib/minizip/zip.c b/deps/zlib/contrib/minizip/zip.c deleted file mode 100644 index 65c0c7251843c06fda42eac15210c710cf9f7f34..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/zip.c +++ /dev/null @@ -1,2007 +0,0 @@ -/* zip.c -- IO on .zip files using zlib - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - Changes - Oct-2009 - Mathias Svensson - Remove old C style function prototypes - Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives - Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions. - Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data - It is used when recreting zip archive with RAW when deleting items from a zip. - ZIP64 data is automatically added to items that needs it, and existing ZIP64 data need to be removed. - Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required) - Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer - -*/ - - -#include -#include -#include -#include -#include "third_party/zlib/zlib.h" -#include "zip.h" - -#ifdef STDC -# include -# include -# include -#endif -#ifdef NO_ERRNO_H - extern int errno; -#else -# include -#endif - - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -#ifndef VERSIONMADEBY -# define VERSIONMADEBY (0x0) /* platform depedent */ -#endif - -#ifndef Z_BUFSIZE -#define Z_BUFSIZE (64*1024) //(16384) -#endif - -#ifndef Z_MAXFILENAMEINZIP -#define Z_MAXFILENAMEINZIP (256) -#endif - -#ifndef ALLOC -# define ALLOC(size) (malloc(size)) -#endif -#ifndef TRYFREE -# define TRYFREE(p) {if (p) free(p);} -#endif - -/* -#define SIZECENTRALDIRITEM (0x2e) -#define SIZEZIPLOCALHEADER (0x1e) -*/ - -/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ - - -// NOT sure that this work on ALL platform -#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32)) - -#ifndef SEEK_CUR -#define SEEK_CUR 1 -#endif - -#ifndef SEEK_END -#define SEEK_END 2 -#endif - -#ifndef SEEK_SET -#define SEEK_SET 0 -#endif - -#ifndef DEF_MEM_LEVEL -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -#endif -const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll"; - - -#define SIZEDATA_INDATABLOCK (4096-(4*4)) - -#define LOCALHEADERMAGIC (0x04034b50) -#define CENTRALHEADERMAGIC (0x02014b50) -#define ENDHEADERMAGIC (0x06054b50) -#define ZIP64ENDHEADERMAGIC (0x6064b50) -#define ZIP64ENDLOCHEADERMAGIC (0x7064b50) - -#define FLAG_LOCALHEADER_OFFSET (0x06) -#define CRC_LOCALHEADER_OFFSET (0x0e) - -#define SIZECENTRALHEADER (0x2e) /* 46 */ - -typedef struct linkedlist_datablock_internal_s -{ - struct linkedlist_datablock_internal_s* next_datablock; - uLong avail_in_this_block; - uLong filled_in_this_block; - uLong unused; /* for future use and alignment */ - unsigned char data[SIZEDATA_INDATABLOCK]; -} linkedlist_datablock_internal; - -typedef struct linkedlist_data_s -{ - linkedlist_datablock_internal* first_block; - linkedlist_datablock_internal* last_block; -} linkedlist_data; - - -typedef struct -{ - z_stream stream; /* zLib stream structure for inflate */ -#ifdef HAVE_BZIP2 - bz_stream bstream; /* bzLib stream structure for bziped */ -#endif - - int stream_initialised; /* 1 is stream is initialised */ - uInt pos_in_buffered_data; /* last written byte in buffered_data */ - - ZPOS64_T pos_local_header; /* offset of the local header of the file - currenty writing */ - char* central_header; /* central header data for the current file */ - uLong size_centralExtra; - uLong size_centralheader; /* size of the central header for cur file */ - uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */ - uLong flag; /* flag of the file currently writing */ - - int method; /* compression method of file currenty wr.*/ - int raw; /* 1 for directly writing raw data */ - Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/ - uLong dosDate; - uLong crc32; - int encrypt; - int zip64; /* Add ZIP64 extened information in the extra field */ - ZPOS64_T pos_zip64extrainfo; - ZPOS64_T totalCompressedData; - ZPOS64_T totalUncompressedData; -#ifndef NOCRYPT - unsigned long keys[3]; /* keys defining the pseudo-random sequence */ - const z_crc_t* pcrc_32_tab; - int crypt_header_size; -#endif -} curfile64_info; - -typedef struct -{ - zlib_filefunc64_32_def z_filefunc; - voidpf filestream; /* io structore of the zipfile */ - linkedlist_data central_dir;/* datablock with central dir in construction*/ - int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/ - curfile64_info ci; /* info on the file curretly writing */ - - ZPOS64_T begin_pos; /* position of the beginning of the zipfile */ - ZPOS64_T add_position_when_writing_offset; - ZPOS64_T number_entry; - -#ifndef NO_ADDFILEINEXISTINGZIP - char *globalcomment; -#endif - -} zip64_internal; - - -#ifndef NOCRYPT -#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED -#include "crypt.h" -#endif - -local linkedlist_datablock_internal* allocate_new_datablock() -{ - linkedlist_datablock_internal* ldi; - ldi = (linkedlist_datablock_internal*) - ALLOC(sizeof(linkedlist_datablock_internal)); - if (ldi!=NULL) - { - ldi->next_datablock = NULL ; - ldi->filled_in_this_block = 0 ; - ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ; - } - return ldi; -} - -local void free_datablock(linkedlist_datablock_internal* ldi) -{ - while (ldi!=NULL) - { - linkedlist_datablock_internal* ldinext = ldi->next_datablock; - TRYFREE(ldi); - ldi = ldinext; - } -} - -local void init_linkedlist(linkedlist_data* ll) -{ - ll->first_block = ll->last_block = NULL; -} - -local void free_linkedlist(linkedlist_data* ll) -{ - free_datablock(ll->first_block); - ll->first_block = ll->last_block = NULL; -} - - -local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len) -{ - linkedlist_datablock_internal* ldi; - const unsigned char* from_copy; - - if (ll==NULL) - return ZIP_INTERNALERROR; - - if (ll->last_block == NULL) - { - ll->first_block = ll->last_block = allocate_new_datablock(); - if (ll->first_block == NULL) - return ZIP_INTERNALERROR; - } - - ldi = ll->last_block; - from_copy = (unsigned char*)buf; - - while (len>0) - { - uInt copy_this; - uInt i; - unsigned char* to_copy; - - if (ldi->avail_in_this_block==0) - { - ldi->next_datablock = allocate_new_datablock(); - if (ldi->next_datablock == NULL) - return ZIP_INTERNALERROR; - ldi = ldi->next_datablock ; - ll->last_block = ldi; - } - - if (ldi->avail_in_this_block < len) - copy_this = (uInt)ldi->avail_in_this_block; - else - copy_this = (uInt)len; - - to_copy = &(ldi->data[ldi->filled_in_this_block]); - - for (i=0;ifilled_in_this_block += copy_this; - ldi->avail_in_this_block -= copy_this; - from_copy += copy_this ; - len -= copy_this; - } - return ZIP_OK; -} - - - -/****************************************************************************/ - -#ifndef NO_ADDFILEINEXISTINGZIP -/* =========================================================================== - Inputs a long in LSB order to the given file - nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T) -*/ - -local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)); -local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte) -{ - unsigned char buf[8]; - int n; - for (n = 0; n < nbByte; n++) - { - buf[n] = (unsigned char)(x & 0xff); - x >>= 8; - } - if (x != 0) - { /* data overflow - hack for ZIP64 (X Roche) */ - for (n = 0; n < nbByte; n++) - { - buf[n] = 0xff; - } - } - - if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) - return ZIP_ERRNO; - else - return ZIP_OK; -} - -local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte)); -local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte) -{ - unsigned char* buf=(unsigned char*)dest; - int n; - for (n = 0; n < nbByte; n++) { - buf[n] = (unsigned char)(x & 0xff); - x >>= 8; - } - - if (x != 0) - { /* data overflow - hack for ZIP64 */ - for (n = 0; n < nbByte; n++) - { - buf[n] = 0xff; - } - } -} - -/****************************************************************************/ - - -local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm) -{ - uLong year = (uLong)ptm->tm_year; - if (year>=1980) - year-=1980; - else if (year>=80) - year-=80; - return - (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) | - ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour)); -} - - -/****************************************************************************/ - -local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi)); - -local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi) -{ - unsigned char c; - int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1); - if (err==1) - { - *pi = (int)c; - return ZIP_OK; - } - else - { - if (ZERROR64(*pzlib_filefunc_def,filestream)) - return ZIP_ERRNO; - else - return ZIP_EOF; - } -} - - -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ -local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); - -local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX) -{ - uLong x ; - int i = 0; - int err; - - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<8; - - if (err==ZIP_OK) - *pX = x; - else - *pX = 0; - return err; -} - -local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX)); - -local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX) -{ - uLong x ; - int i = 0; - int err; - - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (uLong)i; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<8; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<16; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((uLong)i)<<24; - - if (err==ZIP_OK) - *pX = x; - else - *pX = 0; - return err; -} - -local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)); - - -local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX) -{ - ZPOS64_T x; - int i = 0; - int err; - - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x = (ZPOS64_T)i; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<8; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<16; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<24; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<32; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<40; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<48; - - if (err==ZIP_OK) - err = zip64local_getByte(pzlib_filefunc_def,filestream,&i); - x += ((ZPOS64_T)i)<<56; - - if (err==ZIP_OK) - *pX = x; - else - *pX = 0; - - return err; -} - -#ifndef BUFREADCOMMENT -#define BUFREADCOMMENT (0x400) -#endif -/* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ -local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); - -local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) -{ - unsigned char* buf; - ZPOS64_T uSizeFile; - ZPOS64_T uBackRead; - ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ - ZPOS64_T uPosFound=0; - - if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - - uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); - if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - TRYFREE(buf); - return uPosFound; -} - -/* -Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before -the global comment) -*/ -local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)); - -local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream) -{ - unsigned char* buf; - ZPOS64_T uSizeFile; - ZPOS64_T uBackRead; - ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */ - ZPOS64_T uPosFound=0; - uLong uL; - ZPOS64_T relativeOffset; - - if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0) - return 0; - - uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos); - if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0) - break; - - if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - { - // Signature "0x07064b50" Zip64 end of central directory locater - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07)) - { - uPosFound = uReadPos+i; - break; - } - } - - if (uPosFound!=0) - break; - } - - TRYFREE(buf); - if (uPosFound == 0) - return 0; - - /* Zip64 end of central directory locator */ - if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0) - return 0; - - /* the signature, already checked */ - if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) - return 0; - - /* number of the disk with the start of the zip64 end of central directory */ - if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) - return 0; - if (uL != 0) - return 0; - - /* relative offset of the zip64 end of central directory record */ - if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK) - return 0; - - /* total number of disks */ - if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) - return 0; - if (uL != 1) - return 0; - - /* Goto Zip64 end of central directory record */ - if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0) - return 0; - - /* the signature */ - if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK) - return 0; - - if (uL != 0x06064b50) // signature of 'Zip64 end of central directory' - return 0; - - return relativeOffset; -} - -int LoadCentralDirectoryRecord(zip64_internal* pziinit) -{ - int err=ZIP_OK; - ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ - - ZPOS64_T size_central_dir; /* size of the central directory */ - ZPOS64_T offset_central_dir; /* offset of start of central directory */ - ZPOS64_T central_pos; - uLong uL; - - uLong number_disk; /* number of the current dist, used for - spaning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spaning ZIP, unsupported, always 0*/ - ZPOS64_T number_entry; - ZPOS64_T number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ - uLong VersionMadeBy; - uLong VersionNeeded; - uLong size_comment; - - int hasZIP64Record = 0; - - // check first if we find a ZIP64 record - central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream); - if(central_pos > 0) - { - hasZIP64Record = 1; - } - else if(central_pos == 0) - { - central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream); - } - -/* disable to allow appending to empty ZIP archive - if (central_pos==0) - err=ZIP_ERRNO; -*/ - - if(hasZIP64Record) - { - ZPOS64_T sizeEndOfCentralDirectory; - if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0) - err=ZIP_ERRNO; - - /* the signature, already checked */ - if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK) - err=ZIP_ERRNO; - - /* size of zip64 end of central directory record */ - if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK) - err=ZIP_ERRNO; - - /* version made by */ - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK) - err=ZIP_ERRNO; - - /* version needed to extract */ - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK) - err=ZIP_ERRNO; - - /* number of this disk */ - if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK) - err=ZIP_ERRNO; - - /* number of the disk with the start of the central directory */ - if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK) - err=ZIP_ERRNO; - - /* total number of entries in the central directory on this disk */ - if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK) - err=ZIP_ERRNO; - - /* total number of entries in the central directory */ - if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK) - err=ZIP_ERRNO; - - if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) - err=ZIP_BADZIPFILE; - - /* size of the central directory */ - if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK) - err=ZIP_ERRNO; - - /* offset of start of central directory with respect to the - starting disk number */ - if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK) - err=ZIP_ERRNO; - - // TODO.. - // read the comment from the standard central header. - size_comment = 0; - } - else - { - // Read End of central Directory info - if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0) - err=ZIP_ERRNO; - - /* the signature, already checked */ - if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK) - err=ZIP_ERRNO; - - /* number of this disk */ - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK) - err=ZIP_ERRNO; - - /* number of the disk with the start of the central directory */ - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK) - err=ZIP_ERRNO; - - /* total number of entries in the central dir on this disk */ - number_entry = 0; - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) - err=ZIP_ERRNO; - else - number_entry = uL; - - /* total number of entries in the central dir */ - number_entry_CD = 0; - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) - err=ZIP_ERRNO; - else - number_entry_CD = uL; - - if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) - err=ZIP_BADZIPFILE; - - /* size of the central directory */ - size_central_dir = 0; - if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) - err=ZIP_ERRNO; - else - size_central_dir = uL; - - /* offset of start of central directory with respect to the starting disk number */ - offset_central_dir = 0; - if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK) - err=ZIP_ERRNO; - else - offset_central_dir = uL; - - - /* zipfile global comment length */ - if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK) - err=ZIP_ERRNO; - } - - if ((central_posz_filefunc, pziinit->filestream); - return ZIP_ERRNO; - } - - if (size_comment>0) - { - pziinit->globalcomment = (char*)ALLOC(size_comment+1); - if (pziinit->globalcomment) - { - size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment); - pziinit->globalcomment[size_comment]=0; - } - } - - byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir); - pziinit->add_position_when_writing_offset = byte_before_the_zipfile; - - { - ZPOS64_T size_central_dir_to_read = size_central_dir; - size_t buf_size = SIZEDATA_INDATABLOCK; - void* buf_read = (void*)ALLOC(buf_size); - if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0) - err=ZIP_ERRNO; - - while ((size_central_dir_to_read>0) && (err==ZIP_OK)) - { - ZPOS64_T read_this = SIZEDATA_INDATABLOCK; - if (read_this > size_central_dir_to_read) - read_this = size_central_dir_to_read; - - if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this) - err=ZIP_ERRNO; - - if (err==ZIP_OK) - err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this); - - size_central_dir_to_read-=read_this; - } - TRYFREE(buf_read); - } - pziinit->begin_pos = byte_before_the_zipfile; - pziinit->number_entry = number_entry_CD; - - if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0) - err=ZIP_ERRNO; - - return err; -} - - -#endif /* !NO_ADDFILEINEXISTINGZIP*/ - - -/************************************************************/ -extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def) -{ - zip64_internal ziinit; - zip64_internal* zi; - int err=ZIP_OK; - - ziinit.z_filefunc.zseek32_file = NULL; - ziinit.z_filefunc.ztell32_file = NULL; - if (pzlib_filefunc64_32_def==NULL) - fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64); - else - ziinit.z_filefunc = *pzlib_filefunc64_32_def; - - ziinit.filestream = ZOPEN64(ziinit.z_filefunc, - pathname, - (append == APPEND_STATUS_CREATE) ? - (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) : - (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING)); - - if (ziinit.filestream == NULL) - return NULL; - - if (append == APPEND_STATUS_CREATEAFTER) - ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END); - - ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream); - ziinit.in_opened_file_inzip = 0; - ziinit.ci.stream_initialised = 0; - ziinit.number_entry = 0; - ziinit.add_position_when_writing_offset = 0; - init_linkedlist(&(ziinit.central_dir)); - - - - zi = (zip64_internal*)ALLOC(sizeof(zip64_internal)); - if (zi==NULL) - { - ZCLOSE64(ziinit.z_filefunc,ziinit.filestream); - return NULL; - } - - /* now we add file in a zipfile */ -# ifndef NO_ADDFILEINEXISTINGZIP - ziinit.globalcomment = NULL; - if (append == APPEND_STATUS_ADDINZIP) - { - // Read and Cache Central Directory Records - err = LoadCentralDirectoryRecord(&ziinit); - } - - if (globalcomment) - { - *globalcomment = ziinit.globalcomment; - } -# endif /* !NO_ADDFILEINEXISTINGZIP*/ - - if (err != ZIP_OK) - { -# ifndef NO_ADDFILEINEXISTINGZIP - TRYFREE(ziinit.globalcomment); -# endif /* !NO_ADDFILEINEXISTINGZIP*/ - TRYFREE(zi); - return NULL; - } - else - { - *zi = ziinit; - return (zipFile)zi; - } -} - -extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def) -{ - if (pzlib_filefunc32_def != NULL) - { - zlib_filefunc64_32_def zlib_filefunc64_32_def_fill; - fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def); - return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill); - } - else - return zipOpen3(pathname, append, globalcomment, NULL); -} - -extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def) -{ - if (pzlib_filefunc_def != NULL) - { - zlib_filefunc64_32_def zlib_filefunc64_32_def_fill; - zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def; - zlib_filefunc64_32_def_fill.ztell32_file = NULL; - zlib_filefunc64_32_def_fill.zseek32_file = NULL; - return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill); - } - else - return zipOpen3(pathname, append, globalcomment, NULL); -} - - - -extern zipFile ZEXPORT zipOpen (const char* pathname, int append) -{ - return zipOpen3((const void*)pathname,append,NULL,NULL); -} - -extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append) -{ - return zipOpen3(pathname,append,NULL,NULL); -} - -int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local) -{ - /* write the local header */ - int err; - uInt size_filename = (uInt)strlen(filename); - uInt size_extrafield = size_extrafield_local; - - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4); - - if (err==ZIP_OK) - { - if(zi->ci.zip64) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */ - else - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */ - } - - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2); - - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2); - - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4); - - // CRC / Compressed size / Uncompressed size will be filled in later and rewritten later - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */ - if (err==ZIP_OK) - { - if(zi->ci.zip64) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */ - else - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */ - } - if (err==ZIP_OK) - { - if(zi->ci.zip64) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */ - else - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */ - } - - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2); - - if(zi->ci.zip64) - { - size_extrafield += 20; - } - - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2); - - if ((err==ZIP_OK) && (size_filename > 0)) - { - if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename) - err = ZIP_ERRNO; - } - - if ((err==ZIP_OK) && (size_extrafield_local > 0)) - { - if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local) - err = ZIP_ERRNO; - } - - - if ((err==ZIP_OK) && (zi->ci.zip64)) - { - // write the Zip64 extended info - short HeaderID = 1; - short DataSize = 16; - ZPOS64_T CompressedSize = 0; - ZPOS64_T UncompressedSize = 0; - - // Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file) - zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream); - - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2); - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2); - - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8); - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8); - } - - return err; -} - -/* - NOTE. - When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped - before calling this function it can be done with zipRemoveExtraInfoBlock - - It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize - unnecessary allocations. - */ -extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void* extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int raw, - int windowBits,int memLevel, int strategy, - const char* password, uLong crcForCrypting, - uLong versionMadeBy, uLong flagBase, int zip64) -{ - zip64_internal* zi; - uInt size_filename; - uInt size_comment; - uInt i; - int err = ZIP_OK; - -# ifdef NOCRYPT - (crcForCrypting); - if (password != NULL) - return ZIP_PARAMERROR; -# endif - - if (file == NULL) - return ZIP_PARAMERROR; - -#ifdef HAVE_BZIP2 - if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED)) - return ZIP_PARAMERROR; -#else - if ((method!=0) && (method!=Z_DEFLATED)) - return ZIP_PARAMERROR; -#endif - - zi = (zip64_internal*)file; - - if (zi->in_opened_file_inzip == 1) - { - err = zipCloseFileInZip (file); - if (err != ZIP_OK) - return err; - } - - if (filename==NULL) - filename="-"; - - if (comment==NULL) - size_comment = 0; - else - size_comment = (uInt)strlen(comment); - - size_filename = (uInt)strlen(filename); - - if (zipfi == NULL) - zi->ci.dosDate = 0; - else - { - if (zipfi->dosDate != 0) - zi->ci.dosDate = zipfi->dosDate; - else - zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date); - } - - zi->ci.flag = flagBase; - if ((level==8) || (level==9)) - zi->ci.flag |= 2; - if (level==2) - zi->ci.flag |= 4; - if (level==1) - zi->ci.flag |= 6; - if (password != NULL) - zi->ci.flag |= 1; - - zi->ci.crc32 = 0; - zi->ci.method = method; - zi->ci.encrypt = 0; - zi->ci.stream_initialised = 0; - zi->ci.pos_in_buffered_data = 0; - zi->ci.raw = raw; - zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream); - - zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment; - zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data - - zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree); - - zi->ci.size_centralExtra = size_extrafield_global; - zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4); - /* version info */ - zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2); - zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2); - zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2); - zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2); - zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4); - zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/ - zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/ - zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/ - zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2); - zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2); - zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2); - zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ - - if (zipfi==NULL) - zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); - else - zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); - - if (zipfi==NULL) - zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); - else - zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); - - if(zi->ci.pos_local_header >= 0xffffffff) - zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4); - else - zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writing_offset,4); - - for (i=0;ici.central_header+SIZECENTRALHEADER+i) = *(filename+i); - - for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+i) = - *(((const char*)extrafield_global)+i); - - for (i=0;ici.central_header+SIZECENTRALHEADER+size_filename+ - size_extrafield_global+i) = *(comment+i); - if (zi->ci.central_header == NULL) - return ZIP_INTERNALERROR; - - zi->ci.zip64 = zip64; - zi->ci.totalCompressedData = 0; - zi->ci.totalUncompressedData = 0; - zi->ci.pos_zip64extrainfo = 0; - - err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local); - -#ifdef HAVE_BZIP2 - zi->ci.bstream.avail_in = (uInt)0; - zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; - zi->ci.bstream.total_in_hi32 = 0; - zi->ci.bstream.total_in_lo32 = 0; - zi->ci.bstream.total_out_hi32 = 0; - zi->ci.bstream.total_out_lo32 = 0; -#endif - - zi->ci.stream.avail_in = (uInt)0; - zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.stream.next_out = zi->ci.buffered_data; - zi->ci.stream.total_in = 0; - zi->ci.stream.total_out = 0; - zi->ci.stream.data_type = Z_BINARY; - -#ifdef HAVE_BZIP2 - if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) -#else - if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) -#endif - { - if(zi->ci.method == Z_DEFLATED) - { - zi->ci.stream.zalloc = (alloc_func)0; - zi->ci.stream.zfree = (free_func)0; - zi->ci.stream.opaque = (voidpf)0; - - if (windowBits>0) - windowBits = -windowBits; - - err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy); - - if (err==Z_OK) - zi->ci.stream_initialised = Z_DEFLATED; - } - else if(zi->ci.method == Z_BZIP2ED) - { -#ifdef HAVE_BZIP2 - // Init BZip stuff here - zi->ci.bstream.bzalloc = 0; - zi->ci.bstream.bzfree = 0; - zi->ci.bstream.opaque = (voidpf)0; - - err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35); - if(err == BZ_OK) - zi->ci.stream_initialised = Z_BZIP2ED; -#endif - } - - } - -# ifndef NOCRYPT - zi->ci.crypt_header_size = 0; - if ((err==Z_OK) && (password != NULL)) - { - unsigned char bufHead[RAND_HEAD_LEN]; - unsigned int sizeHead; - zi->ci.encrypt = 1; - zi->ci.pcrc_32_tab = get_crc_table(); - /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/ - - sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting); - zi->ci.crypt_header_size = sizeHead; - - if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead) - err = ZIP_ERRNO; - } -# endif - - if (err==Z_OK) - zi->in_opened_file_inzip = 1; - return err; -} - -extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void* extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int raw, - int windowBits,int memLevel, int strategy, - const char* password, uLong crcForCrypting, - uLong versionMadeBy, uLong flagBase) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - windowBits, memLevel, strategy, - password, crcForCrypting, versionMadeBy, flagBase, 0); -} - -extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void* extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int raw, - int windowBits,int memLevel, int strategy, - const char* password, uLong crcForCrypting) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - windowBits, memLevel, strategy, - password, crcForCrypting, VERSIONMADEBY, 0, 0); -} - -extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void* extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int raw, - int windowBits,int memLevel, int strategy, - const char* password, uLong crcForCrypting, int zip64) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - windowBits, memLevel, strategy, - password, crcForCrypting, VERSIONMADEBY, 0, zip64); -} - -extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void* extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int raw) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0, VERSIONMADEBY, 0, 0); -} - -extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void* extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int raw, int zip64) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, raw, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0, VERSIONMADEBY, 0, zip64); -} - -extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void*extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level, int zip64) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, 0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0, VERSIONMADEBY, 0, zip64); -} - -extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi, - const void* extrafield_local, uInt size_extrafield_local, - const void*extrafield_global, uInt size_extrafield_global, - const char* comment, int method, int level) -{ - return zipOpenNewFileInZip4_64 (file, filename, zipfi, - extrafield_local, size_extrafield_local, - extrafield_global, size_extrafield_global, - comment, method, level, 0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0, VERSIONMADEBY, 0, 0); -} - -local int zip64FlushWriteBuffer(zip64_internal* zi) -{ - int err=ZIP_OK; - - if (zi->ci.encrypt != 0) - { -#ifndef NOCRYPT - uInt i; - int t; - for (i=0;ici.pos_in_buffered_data;i++) - zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t); -#endif - } - - if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data) - err = ZIP_ERRNO; - - zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data; - -#ifdef HAVE_BZIP2 - if(zi->ci.method == Z_BZIP2ED) - { - zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32; - zi->ci.bstream.total_in_lo32 = 0; - zi->ci.bstream.total_in_hi32 = 0; - } - else -#endif - { - zi->ci.totalUncompressedData += zi->ci.stream.total_in; - zi->ci.stream.total_in = 0; - } - - - zi->ci.pos_in_buffered_data = 0; - - return err; -} - -extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len) -{ - zip64_internal* zi; - int err=ZIP_OK; - - if (file == NULL) - return ZIP_PARAMERROR; - zi = (zip64_internal*)file; - - if (zi->in_opened_file_inzip == 0) - return ZIP_PARAMERROR; - - zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len); - -#ifdef HAVE_BZIP2 - if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw)) - { - zi->ci.bstream.next_in = (void*)buf; - zi->ci.bstream.avail_in = len; - err = BZ_RUN_OK; - - while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0)) - { - if (zi->ci.bstream.avail_out == 0) - { - if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) - err = ZIP_ERRNO; - zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; - } - - - if(err != BZ_RUN_OK) - break; - - if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) - { - uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32; -// uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32; - err=BZ2_bzCompress(&zi->ci.bstream, BZ_RUN); - - zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ; - } - } - - if(err == BZ_RUN_OK) - err = ZIP_OK; - } - else -#endif - { - zi->ci.stream.next_in = (Bytef*)buf; - zi->ci.stream.avail_in = len; - - while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0)) - { - if (zi->ci.stream.avail_out == 0) - { - if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) - err = ZIP_ERRNO; - zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.stream.next_out = zi->ci.buffered_data; - } - - - if(err != ZIP_OK) - break; - - if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - { - uLong uTotalOutBefore = zi->ci.stream.total_out; - err=deflate(&zi->ci.stream, Z_NO_FLUSH); - if(uTotalOutBefore > zi->ci.stream.total_out) - { - int bBreak = 0; - bBreak++; - } - - zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; - } - else - { - uInt copy_this,i; - if (zi->ci.stream.avail_in < zi->ci.stream.avail_out) - copy_this = zi->ci.stream.avail_in; - else - copy_this = zi->ci.stream.avail_out; - - for (i = 0; i < copy_this; i++) - *(((char*)zi->ci.stream.next_out)+i) = - *(((const char*)zi->ci.stream.next_in)+i); - { - zi->ci.stream.avail_in -= copy_this; - zi->ci.stream.avail_out-= copy_this; - zi->ci.stream.next_in+= copy_this; - zi->ci.stream.next_out+= copy_this; - zi->ci.stream.total_in+= copy_this; - zi->ci.stream.total_out+= copy_this; - zi->ci.pos_in_buffered_data += copy_this; - } - } - }// while(...) - } - - return err; -} - -extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32) -{ - return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32); -} - -extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32) -{ - zip64_internal* zi; - ZPOS64_T compressed_size; - uLong invalidValue = 0xffffffff; - short datasize = 0; - int err=ZIP_OK; - - if (file == NULL) - return ZIP_PARAMERROR; - zi = (zip64_internal*)file; - - if (zi->in_opened_file_inzip == 0) - return ZIP_PARAMERROR; - zi->ci.stream.avail_in = 0; - - if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - { - while (err==ZIP_OK) - { - uLong uTotalOutBefore; - if (zi->ci.stream.avail_out == 0) - { - if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) - err = ZIP_ERRNO; - zi->ci.stream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.stream.next_out = zi->ci.buffered_data; - } - uTotalOutBefore = zi->ci.stream.total_out; - err=deflate(&zi->ci.stream, Z_FINISH); - zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ; - } - } - else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) - { -#ifdef HAVE_BZIP2 - err = BZ_FINISH_OK; - while (err==BZ_FINISH_OK) - { - uLong uTotalOutBefore; - if (zi->ci.bstream.avail_out == 0) - { - if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO) - err = ZIP_ERRNO; - zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE; - zi->ci.bstream.next_out = (char*)zi->ci.buffered_data; - } - uTotalOutBefore = zi->ci.bstream.total_out_lo32; - err=BZ2_bzCompress(&zi->ci.bstream, BZ_FINISH); - if(err == BZ_STREAM_END) - err = Z_STREAM_END; - - zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore); - } - - if(err == BZ_FINISH_OK) - err = ZIP_OK; -#endif - } - - if (err==Z_STREAM_END) - err=ZIP_OK; /* this is normal */ - - if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK)) - { - if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO) - err = ZIP_ERRNO; - } - - if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw)) - { - int tmp_err = deflateEnd(&zi->ci.stream); - if (err == ZIP_OK) - err = tmp_err; - zi->ci.stream_initialised = 0; - } -#ifdef HAVE_BZIP2 - else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw)) - { - int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream); - if (err==ZIP_OK) - err = tmperr; - zi->ci.stream_initialised = 0; - } -#endif - - if (!zi->ci.raw) - { - crc32 = (uLong)zi->ci.crc32; - uncompressed_size = zi->ci.totalUncompressedData; - } - compressed_size = zi->ci.totalCompressedData; - -# ifndef NOCRYPT - compressed_size += zi->ci.crypt_header_size; -# endif - - // update Current Item crc and sizes, - if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff) - { - /*version Made by*/ - zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2); - /*version needed*/ - zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2); - - } - - zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/ - - - if(compressed_size >= 0xffffffff) - zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/ - else - zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/ - - /// set internal file attributes field - if (zi->ci.stream.data_type == Z_ASCII) - zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2); - - if(uncompressed_size >= 0xffffffff) - zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/ - else - zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/ - - // Add ZIP64 extra info field for uncompressed size - if(uncompressed_size >= 0xffffffff) - datasize += 8; - - // Add ZIP64 extra info field for compressed size - if(compressed_size >= 0xffffffff) - datasize += 8; - - // Add ZIP64 extra info field for relative offset to local file header of current file - if(zi->ci.pos_local_header >= 0xffffffff) - datasize += 8; - - if(datasize > 0) - { - char* p = NULL; - - if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree) - { - // we can not write more data to the buffer that we have room for. - return ZIP_BADZIPFILE; - } - - p = zi->ci.central_header + zi->ci.size_centralheader; - - // Add Extra Information Header for 'ZIP64 information' - zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID - p += 2; - zip64local_putValue_inmemory(p, datasize, 2); // DataSize - p += 2; - - if(uncompressed_size >= 0xffffffff) - { - zip64local_putValue_inmemory(p, uncompressed_size, 8); - p += 8; - } - - if(compressed_size >= 0xffffffff) - { - zip64local_putValue_inmemory(p, compressed_size, 8); - p += 8; - } - - if(zi->ci.pos_local_header >= 0xffffffff) - { - zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8); - p += 8; - } - - // Update how much extra free space we got in the memory buffer - // and increase the centralheader size so the new ZIP64 fields are included - // ( 4 below is the size of HeaderID and DataSize field ) - zi->ci.size_centralExtraFree -= datasize + 4; - zi->ci.size_centralheader += datasize + 4; - - // Update the extra info size field - zi->ci.size_centralExtra += datasize + 4; - zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2); - } - - if (err==ZIP_OK) - err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader); - - free(zi->ci.central_header); - - if (err==ZIP_OK) - { - // Update the LocalFileHeader with the new values. - - ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream); - - if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0) - err = ZIP_ERRNO; - - if (err==ZIP_OK) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */ - - if(uncompressed_size >= 0xffffffff || compressed_size >= 0xffffffff ) - { - if(zi->ci.pos_zip64extrainfo > 0) - { - // Update the size in the ZIP64 extended field. - if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0) - err = ZIP_ERRNO; - - if (err==ZIP_OK) /* compressed size, unknown */ - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8); - - if (err==ZIP_OK) /* uncompressed size, unknown */ - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8); - } - else - err = ZIP_BADZIPFILE; // Caller passed zip64 = 0, so no room for zip64 info -> fatal - } - else - { - if (err==ZIP_OK) /* compressed size, unknown */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4); - - if (err==ZIP_OK) /* uncompressed size, unknown */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4); - } - - if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0) - err = ZIP_ERRNO; - } - - zi->number_entry ++; - zi->in_opened_file_inzip = 0; - - return err; -} - -extern int ZEXPORT zipCloseFileInZip (zipFile file) -{ - return zipCloseFileInZipRaw (file,0,0); -} - -int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip) -{ - int err = ZIP_OK; - ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writing_offset; - - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4); - - /*num disks*/ - if (err==ZIP_OK) /* number of the disk with the start of the central directory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); - - /*relative offset*/ - if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8); - - /*total disks*/ /* Do not support spawning of disk so always say 1 here*/ - if (err==ZIP_OK) /* number of the disk with the start of the central directory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4); - - return err; -} - -int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip) -{ - int err = ZIP_OK; - - uLong Zip64DataSize = 44; - - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4); - - if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ? - - if (err==ZIP_OK) /* version made by */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2); - - if (err==ZIP_OK) /* version needed */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2); - - if (err==ZIP_OK) /* number of this disk */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); - - if (err==ZIP_OK) /* number of the disk with the start of the central directory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); - - if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8); - - if (err==ZIP_OK) /* total number of entries in the central dir */ - err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8); - - if (err==ZIP_OK) /* size of the central directory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8); - - if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ - { - ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; - err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8); - } - return err; -} -int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip) -{ - int err = ZIP_OK; - - /*signature*/ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4); - - if (err==ZIP_OK) /* number of this disk */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); - - if (err==ZIP_OK) /* number of the disk with the start of the central directory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2); - - if (err==ZIP_OK) /* total number of entries in the central dir on this disk */ - { - { - if(zi->number_entry >= 0xFFFF) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record - else - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); - } - } - - if (err==ZIP_OK) /* total number of entries in the central dir */ - { - if(zi->number_entry >= 0xFFFF) - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record - else - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2); - } - - if (err==ZIP_OK) /* size of the central directory */ - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4); - - if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */ - { - ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; - if(pos >= 0xffffffff) - { - err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4); - } - else - err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writing_offset),4); - } - - return err; -} - -int Write_GlobalComment(zip64_internal* zi, const char* global_comment) -{ - int err = ZIP_OK; - uInt size_global_comment = 0; - - if(global_comment != NULL) - size_global_comment = (uInt)strlen(global_comment); - - err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2); - - if (err == ZIP_OK && size_global_comment > 0) - { - if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment) - err = ZIP_ERRNO; - } - return err; -} - -extern int ZEXPORT zipClose (zipFile file, const char* global_comment) -{ - zip64_internal* zi; - int err = 0; - uLong size_centraldir = 0; - ZPOS64_T centraldir_pos_inzip; - ZPOS64_T pos; - - if (file == NULL) - return ZIP_PARAMERROR; - - zi = (zip64_internal*)file; - - if (zi->in_opened_file_inzip == 1) - { - err = zipCloseFileInZip (file); - } - -#ifndef NO_ADDFILEINEXISTINGZIP - if (global_comment==NULL) - global_comment = zi->globalcomment; -#endif - - centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream); - - if (err==ZIP_OK) - { - linkedlist_datablock_internal* ldi = zi->central_dir.first_block; - while (ldi!=NULL) - { - if ((err==ZIP_OK) && (ldi->filled_in_this_block>0)) - { - if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block) - err = ZIP_ERRNO; - } - - size_centraldir += ldi->filled_in_this_block; - ldi = ldi->next_datablock; - } - } - free_linkedlist(&(zi->central_dir)); - - pos = centraldir_pos_inzip - zi->add_position_when_writing_offset; - if(pos >= 0xffffffff || zi->number_entry > 0xFFFF) - { - ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream); - Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip); - - Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos); - } - - if (err==ZIP_OK) - err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip); - - if(err == ZIP_OK) - err = Write_GlobalComment(zi, global_comment); - - if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0) - if (err == ZIP_OK) - err = ZIP_ERRNO; - -#ifndef NO_ADDFILEINEXISTINGZIP - TRYFREE(zi->globalcomment); -#endif - TRYFREE(zi); - - return err; -} - -extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader) -{ - char* p = pData; - int size = 0; - char* pNewHeader; - char* pTmp; - short header; - short dataSize; - - int retVal = ZIP_OK; - - if(pData == NULL || *dataLen < 4) - return ZIP_PARAMERROR; - - pNewHeader = (char*)ALLOC(*dataLen); - pTmp = pNewHeader; - - while(p < (pData + *dataLen)) - { - header = *(short*)p; - dataSize = *(((short*)p)+1); - - if( header == sHeader ) // Header found. - { - p += dataSize + 4; // skip it. do not copy to temp buffer - } - else - { - // Extra Info block should not be removed, So copy it to the temp buffer. - memcpy(pTmp, p, dataSize + 4); - p += dataSize + 4; - size += dataSize + 4; - } - - } - - if(size < *dataLen) - { - // clean old extra info block. - memset(pData,0, *dataLen); - - // copy the new extra info block over the old - if(size > 0) - memcpy(pData, pNewHeader, size); - - // set the new extra info size - *dataLen = size; - - retVal = ZIP_OK; - } - else - retVal = ZIP_ERRNO; - - TRYFREE(pNewHeader); - - return retVal; -} diff --git a/deps/zlib/contrib/minizip/zip.h b/deps/zlib/contrib/minizip/zip.h deleted file mode 100644 index 8c06c0aa7bb08b5f0bdb24d6faee70edba4a17cf..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/minizip/zip.h +++ /dev/null @@ -1,362 +0,0 @@ -/* zip.h -- IO on .zip files using zlib - Version 1.1, February 14h, 2010 - part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html ) - - Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html ) - - Modifications for Zip64 support - Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com ) - - For more info read MiniZip_info.txt - - --------------------------------------------------------------------------- - - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - --------------------------------------------------------------------------- - - Changes - - See header of zip.h - -*/ - -#ifndef _zip12_H -#define _zip12_H - -#ifdef __cplusplus -extern "C" { -#endif - -//#define HAVE_BZIP2 - -#ifndef _ZLIB_H -#include "third_party/zlib/zlib.h" -#endif - -#ifndef _ZLIBIOAPI_H -#include "ioapi.h" -#endif - -#ifdef HAVE_BZIP2 -#include "bzlib.h" -#endif - -#define Z_BZIP2ED 12 - -#if defined(STRICTZIP) || defined(STRICTZIPUNZIP) -/* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ -typedef struct TagzipFile__ { int unused; } zipFile__; -typedef zipFile__ *zipFile; -#else -typedef voidp zipFile; -#endif - -#define ZIP_OK (0) -#define ZIP_EOF (0) -#define ZIP_ERRNO (Z_ERRNO) -#define ZIP_PARAMERROR (-102) -#define ZIP_BADZIPFILE (-103) -#define ZIP_INTERNALERROR (-104) - -#ifndef DEF_MEM_LEVEL -# if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -# else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -# endif -#endif -/* default memLevel */ - -/* tm_zip contain date/time info */ -typedef struct tm_zip_s -{ - uInt tm_sec; /* seconds after the minute - [0,59] */ - uInt tm_min; /* minutes after the hour - [0,59] */ - uInt tm_hour; /* hours since midnight - [0,23] */ - uInt tm_mday; /* day of the month - [1,31] */ - uInt tm_mon; /* months since January - [0,11] */ - uInt tm_year; /* years - [1980..2044] */ -} tm_zip; - -typedef struct -{ - tm_zip tmz_date; /* date in understandable format */ - uLong dosDate; /* if dos_date == 0, tmu_date is used */ -/* uLong flag; */ /* general purpose bit flag 2 bytes */ - - uLong internal_fa; /* internal file attributes 2 bytes */ - uLong external_fa; /* external file attributes 4 bytes */ -} zip_fileinfo; - -typedef const char* zipcharpc; - - -#define APPEND_STATUS_CREATE (0) -#define APPEND_STATUS_CREATEAFTER (1) -#define APPEND_STATUS_ADDINZIP (2) - -extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); -extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append)); -/* - Create a zipfile. - pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on - an Unix computer "zlib/zlib113.zip". - if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip - will be created at the end of the file. - (useful if the file contain a self extractor code) - if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will - add files in existing zip (be sure you don't add file that doesn't exist) - If the zipfile cannot be opened, the return value is NULL. - Else, the return value is a zipFile Handle, usable with other function - of this zip package. -*/ - -/* Note : there is no delete function into a zipfile. - If you want delete file into a zipfile, you must open a zipfile, and create another - Of couse, you can use RAW reading and writing to copy the file you did not want delte -*/ - -extern zipFile ZEXPORT zipOpen2 OF((const char *pathname, - int append, - zipcharpc* globalcomment, - zlib_filefunc_def* pzlib_filefunc_def)); - -extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname, - int append, - zipcharpc* globalcomment, - zlib_filefunc64_def* pzlib_filefunc_def)); - -extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level)); - -extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int zip64)); - -/* - Open a file in the ZIP for writing. - filename : the filename in zip (if NULL, '-' without quote will be used - *zipfi contain supplemental information - if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local - contains the extrafield data the the local header - if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global - contains the extrafield data the the local header - if comment != NULL, comment contain the comment string - method contain the compression method (0 for store, Z_DEFLATED for deflate) - level contain the level of compression (can be Z_DEFAULT_COMPRESSION) - zip64 is set to 1 if a zip64 extended information block should be added to the local file header. - this MUST be '1' if the uncompressed size is >= 0xffffffff. - -*/ - - -extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw)); - - -extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw, - int zip64)); -/* - Same than zipOpenNewFileInZip, except if raw=1, we write raw file - */ - -extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw, - int windowBits, - int memLevel, - int strategy, - const char* password, - uLong crcForCrypting)); - -extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw, - int windowBits, - int memLevel, - int strategy, - const char* password, - uLong crcForCrypting, - int zip64 - )); - -/* - Same than zipOpenNewFileInZip2, except - windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 - password : crypting password (NULL for no crypting) - crcForCrypting : crc of file to compress (needed for crypting) - */ - -extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw, - int windowBits, - int memLevel, - int strategy, - const char* password, - uLong crcForCrypting, - uLong versionMadeBy, - uLong flagBase - )); - - -extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file, - const char* filename, - const zip_fileinfo* zipfi, - const void* extrafield_local, - uInt size_extrafield_local, - const void* extrafield_global, - uInt size_extrafield_global, - const char* comment, - int method, - int level, - int raw, - int windowBits, - int memLevel, - int strategy, - const char* password, - uLong crcForCrypting, - uLong versionMadeBy, - uLong flagBase, - int zip64 - )); -/* - Same than zipOpenNewFileInZip4, except - versionMadeBy : value for Version made by field - flag : value for flag field (compression level info will be added) - */ - - -extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, - const void* buf, - unsigned len)); -/* - Write data in the zipfile -*/ - -extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); -/* - Close the current file in the zipfile -*/ - -extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, - uLong uncompressed_size, - uLong crc32)); - -extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file, - ZPOS64_T uncompressed_size, - uLong crc32)); - -/* - Close the current file in the zipfile, for file opened with - parameter raw=1 in zipOpenNewFileInZip2 - uncompressed_size and crc32 are value for the uncompressed size -*/ - -extern int ZEXPORT zipClose OF((zipFile file, - const char* global_comment)); -/* - Close the zipfile -*/ - - -extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader)); -/* - zipRemoveExtraInfoBlock - Added by Mathias Svensson - - Remove extra information block from a extra information data for the local file header or central directory header - - It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode. - - 0x0001 is the signature header for the ZIP64 extra information blocks - - usage. - Remove ZIP64 Extra information from a central director extra field data - zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001); - - Remove ZIP64 Extra information from a Local File Header extra field data - zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001); -*/ - -#ifdef __cplusplus -} -#endif - -#endif /* _zip64_H */ diff --git a/deps/zlib/contrib/tests/OWNERS b/deps/zlib/contrib/tests/OWNERS deleted file mode 100644 index 9a2fb6fbdc6b3f0721b84ed6eb6cd5b2f68c9102..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/OWNERS +++ /dev/null @@ -1 +0,0 @@ -cblume@chromium.org diff --git a/deps/zlib/contrib/tests/fuzzers/BUILD.gn b/deps/zlib/contrib/tests/fuzzers/BUILD.gn deleted file mode 100644 index c46b66440073a5d93ea043fd5009a762925b4392..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/fuzzers/BUILD.gn +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//testing/libfuzzer/fuzzer_test.gni") - -# root BUILD depends on this target. Needed for package discovery -group("fuzzers") { -} - -fuzzer_test("zlib_uncompress_fuzzer") { - sources = [ - "uncompress_fuzzer.cc", - ] - deps = [ - "../../../:zlib", - ] -} - -fuzzer_test("zlib_inflate_fuzzer") { - sources = [ - "inflate_fuzzer.cc", - ] - deps = [ - "../../../:zlib", - ] -} - -fuzzer_test("zlib_deflate_set_dictionary_fuzzer") { - sources = [ - "deflate_set_dictionary_fuzzer.cc", - ] - deps = [ - "../../../:zlib", - ] -} - -fuzzer_test("zlib_deflate_fuzzer") { - sources = [ - "deflate_fuzzer.cc", - ] - deps = [ - "../../../:zlib", - ] -} diff --git a/deps/zlib/contrib/tests/fuzzers/OWNERS b/deps/zlib/contrib/tests/fuzzers/OWNERS deleted file mode 100644 index 6397ce69c70649d594302e2b4b0d0badc7124a9e..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/fuzzers/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -cblume@chromium.org -mmoroz@chromium.org diff --git a/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc deleted file mode 100644 index 6098ff162ce1c037d88f15b55263b96446e74481..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/fuzzers/deflate_fuzzer.cc +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include - -#include "third_party/zlib/zlib.h" - -static Bytef buffer[256 * 1024] = {0}; - -// Entry point for LibFuzzer. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - // zlib's deflate requires non-zero input sizes - if (!size) - return 0; - - // We need to strip the 'const' for zlib. - std::vector input_buffer{data, data+size}; - - uLongf buffer_length = static_cast(sizeof(buffer)); - - z_stream stream; - stream.next_in = input_buffer.data(); - stream.avail_in = size; - stream.total_in = size; - stream.next_out = buffer; - stream.avail_out = buffer_length; - stream.total_out = buffer_length; - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - - if (Z_OK != deflateInit(&stream, Z_DEFAULT_COMPRESSION)) { - deflateEnd(&stream); - assert(false); - } - - auto deflate_result = deflate(&stream, Z_NO_FLUSH); - deflateEnd(&stream); - if (Z_OK != deflate_result) - assert(false); - - return 0; -} diff --git a/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc deleted file mode 100644 index febbfcb86f0c3e813845085505e1231cf2a13488..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/fuzzers/deflate_set_dictionary_fuzzer.cc +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include - -#include "third_party/zlib/zlib.h" - -static Bytef buffer[256 * 1024] = {0}; - -// Entry point for LibFuzzer. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - // We need to strip the 'const' for zlib. - std::vector input_buffer{data, data + size}; - - uLongf buffer_length = static_cast(sizeof(buffer)); - - z_stream stream; - stream.next_in = input_buffer.data(); - stream.avail_in = size; - stream.total_in = size; - stream.next_out = buffer; - stream.avail_out = buffer_length; - stream.total_out = buffer_length; - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - - if (Z_OK != deflateInit(&stream, Z_DEFAULT_COMPRESSION)) { - deflateEnd(&stream); - assert(false); - } - - auto deflate_set_dictionary_result = - deflateSetDictionary(&stream, data, size); - deflateEnd(&stream); - if (Z_OK != deflate_set_dictionary_result) - assert(false); - - return 0; -} diff --git a/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc deleted file mode 100644 index 44f9c72c18df8a6566012fadf4cdfe392226ccc0..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/fuzzers/inflate_fuzzer.cc +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include -#include -#include - -#include "third_party/zlib/zlib.h" - -static Bytef buffer[256 * 1024] = {0}; - -// Entry point for LibFuzzer. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - // We need to strip the 'const' for zlib - std::vector input_buffer{data, data+size}; - - uLongf buffer_length = static_cast(sizeof(buffer)); - - z_stream stream; - stream.next_in = input_buffer.data(); - stream.avail_in = size; - stream.total_in = size; - stream.next_out = buffer; - stream.avail_out = buffer_length; - stream.total_out = buffer_length; - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - - if (Z_OK != inflateInit(&stream)) { - inflateEnd(&stream); - assert(false); - } - - inflate(&stream, Z_NO_FLUSH); - inflateEnd(&stream); - - return 0; -} diff --git a/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc b/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc deleted file mode 100644 index bca5244e8b38b41bf04e853ac6a0e5f47227af2a..0000000000000000000000000000000000000000 --- a/deps/zlib/contrib/tests/fuzzers/uncompress_fuzzer.cc +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include -#include -#include - -#include "third_party/zlib/zlib.h" - -static Bytef buffer[256 * 1024] = {0}; - -// Entry point for LibFuzzer. -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { - uLongf buffer_length = static_cast(sizeof(buffer)); - if (Z_OK != - uncompress(buffer, &buffer_length, data, static_cast(size))) { - return 0; - } - return 0; -} diff --git a/deps/zlib/google/test/data/evil.zip b/deps/zlib/google/test/data/evil.zip index 2100011493ee72ac0dd90c4d6113c5e6bd972119..8fb908a96abdf0be7d5a20cd94b59a5782cbfca2 100644 Binary files a/deps/zlib/google/test/data/evil.zip and b/deps/zlib/google/test/data/evil.zip differ diff --git a/deps/zlib/google/test/data/evil_via_absolute_file_name.zip b/deps/zlib/google/test/data/evil_via_absolute_file_name.zip index e8977c291b9172818343ae1a85acc82a957d42ea..2415f81b63751bc9bee461d57e0c3af9d646b77f 100644 Binary files a/deps/zlib/google/test/data/evil_via_absolute_file_name.zip and b/deps/zlib/google/test/data/evil_via_absolute_file_name.zip differ diff --git a/deps/zlib/google/test/data/evil_via_invalid_utf8.zip b/deps/zlib/google/test/data/evil_via_invalid_utf8.zip index 827eb2100ea1a093e5f1fe49739f49206e6194bc..94b633e0aa5c2c49c34e7b451ef88e8da99eb866 100644 Binary files a/deps/zlib/google/test/data/evil_via_invalid_utf8.zip and b/deps/zlib/google/test/data/evil_via_invalid_utf8.zip differ diff --git a/deps/zlib/google/test/data/test.zip b/deps/zlib/google/test/data/test.zip index db9b651ffcdbdb0313d4f281b66fffd70107d8e9..4bafe30898eb9cc7b33b547967ea620ea6f72b34 100644 Binary files a/deps/zlib/google/test/data/test.zip and b/deps/zlib/google/test/data/test.zip differ diff --git a/deps/zlib/google/test/data/test_encrypted.zip b/deps/zlib/google/test/data/test_encrypted.zip index 2d6989235d4be74476a1d6b4561d4c2f75598a0d..5e2a75759a19148515c4a0850f66cc58ffb16be8 100644 Binary files a/deps/zlib/google/test/data/test_encrypted.zip and b/deps/zlib/google/test/data/test_encrypted.zip differ diff --git a/deps/zlib/google/test/data/test_mismatch_size.zip b/deps/zlib/google/test/data/test_mismatch_size.zip index 8bfad8509a2701661e70d5ae8361982aad623d18..b83c66fe79125cf3c6a74c1a15d7000526ccb634 100644 Binary files a/deps/zlib/google/test/data/test_mismatch_size.zip and b/deps/zlib/google/test/data/test_mismatch_size.zip differ diff --git a/deps/zlib/google/test/data/test_nocompress.zip b/deps/zlib/google/test/data/test_nocompress.zip index 442a203cd33b53ca6e761c42fc5385024472bb8d..25d66c287e2c75af4b8c9c6a542f8d9f4242a527 100644 Binary files a/deps/zlib/google/test/data/test_nocompress.zip and b/deps/zlib/google/test/data/test_nocompress.zip differ diff --git a/doc/.eslintrc.yaml b/doc/.eslintrc.yaml deleted file mode 100644 index 49c4f4f64736c77bc7f5b15e7521b2df5deaf6c2..0000000000000000000000000000000000000000 --- a/doc/.eslintrc.yaml +++ /dev/null @@ -1,17 +0,0 @@ -## Docs-specific linter rules - -rules: - # ease some restrictions in doc examples - no-restricted-properties: off - no-undef: off - no-unused-vars: off - symbol-description: off - - # add new ECMAScript features gradually - no-var: error - prefer-const: error - prefer-rest-params: error - prefer-template: error - - # Stylistic Issues - no-multiple-empty-lines: [error, {max: 1, maxEOF: 0, maxBOF: 0}] diff --git a/doc/api/addons.html b/doc/api/addons.html new file mode 100644 index 0000000000000000000000000000000000000000..067dcc02864686318f5821b0e652559e1a10cde8 --- /dev/null +++ b/doc/api/addons.html @@ -0,0 +1,1352 @@ + + + + + + + C++ addons | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      C++ addons#

      + + +

      Addons are dynamically-linked shared objects written in C++. The +require() function can load addons as ordinary Node.js modules. +Addons provide an interface between JavaScript and C/C++ libraries.

      +

      There are three options for implementing addons: N-API, nan, or direct +use of internal V8, libuv and Node.js libraries. Unless there is a need for +direct access to functionality which is not exposed by N-API, use N-API. +Refer to C/C++ addons with N-API for more information on N-API.

      +

      When not using N-API, implementing addons is complicated, +involving knowledge of several components and APIs:

      +
        +
      • +

        V8: the C++ library Node.js uses to provide the +JavaScript implementation. V8 provides the mechanisms for creating objects, +calling functions, etc. V8's API is documented mostly in the +v8.h header file (deps/v8/include/v8.h in the Node.js source +tree), which is also available online.

        +
      • +
      • +

        libuv: The C library that implements the Node.js event loop, its worker +threads and all of the asynchronous behaviors of the platform. It also +serves as a cross-platform abstraction library, giving easy, POSIX-like +access across all major operating systems to many common system tasks, such +as interacting with the filesystem, sockets, timers, and system events. libuv +also provides a pthreads-like threading abstraction that may be used to +power more sophisticated asynchronous addons that need to move beyond the +standard event loop. Addon authors are encouraged to think about how to +avoid blocking the event loop with I/O or other time-intensive tasks by +off-loading work via libuv to non-blocking system operations, worker threads +or a custom use of libuv's threads.

        +
      • +
      • +

        Internal Node.js libraries. Node.js itself exports C++ APIs that addons can +use, the most important of which is the node::ObjectWrap class.

        +
      • +
      • +

        Node.js includes other statically linked libraries including OpenSSL. These +other libraries are located in the deps/ directory in the Node.js source +tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully +re-exported by Node.js and may be used to various extents by addons. See +Linking to libraries included with Node.js for additional information.

        +
      • +
      +

      All of the following examples are available for download and may +be used as the starting-point for an addon.

      +

      Hello world#

      +

      This "Hello world" example is a simple addon, written in C++, that is the +equivalent of the following JavaScript code:

      +
      module.exports.hello = () => 'world';
      +

      First, create the file hello.cc:

      +
      // hello.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void Method(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  args.GetReturnValue().Set(String::NewFromUtf8(
      +      isolate, "world", NewStringType::kNormal).ToLocalChecked());
      +}
      +
      +void Initialize(Local<Object> exports) {
      +  NODE_SET_METHOD(exports, "hello", Method);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
      +
      +}  // namespace demo
      +

      All Node.js addons must export an initialization function following +the pattern:

      +
      void Initialize(Local<Object> exports);
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
      +

      There is no semi-colon after NODE_MODULE as it's not a function (see +node.h).

      +

      The module_name must match the filename of the final binary (excluding +the .node suffix).

      +

      In the hello.cc example, then, the initialization function is Initialize +and the addon module name is addon.

      +

      When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as +the first parameter of NODE_MODULE() will ensure that the name of the final +binary will be passed to NODE_MODULE().

      +

      Context-aware addons#

      +

      There are environments in which Node.js addons may need to be loaded multiple +times in multiple contexts. For example, the Electron runtime runs multiple +instances of Node.js in a single process. Each instance will have its own +require() cache, and thus each instance will need a native addon to behave +correctly when loaded via require(). From the addon's perspective, this means +that it must support multiple initializations.

      +

      A context-aware addon can be constructed by using the macro +NODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js +will expect to find when it loads an addon. An addon can thus be initialized as +in the following example:

      +
      using namespace v8;
      +
      +extern "C" NODE_MODULE_EXPORT void
      +NODE_MODULE_INITIALIZER(Local<Object> exports,
      +                        Local<Value> module,
      +                        Local<Context> context) {
      +  /* Perform addon initialization steps here. */
      +}
      +

      Another option is to use the macro NODE_MODULE_INIT(), which will also +construct a context-aware addon. Unlike NODE_MODULE(), which is used to +construct an addon around a given addon initializer function, +NODE_MODULE_INIT() serves as the declaration of such an initializer to be +followed by a function body.

      +

      The following three variables may be used inside the function body following an +invocation of NODE_MODULE_INIT():

      +
        +
      • Local<Object> exports,
      • +
      • Local<Value> module, and
      • +
      • Local<Context> context
      • +
      +

      The choice to build a context-aware addon carries with it the responsibility of +carefully managing global static data. Since the addon may be loaded multiple +times, potentially even from different threads, any global static data stored +in the addon must be properly protected, and must not contain any persistent +references to JavaScript objects. The reason for this is that JavaScript +objects are only valid in one context, and will likely cause a crash when +accessed from the wrong context or from a different thread than the one on which +they were created.

      +

      The context-aware addon can be structured to avoid global static data by +performing the following steps:

      +
        +
      • Define a class which will hold per-addon-instance data and which has a static +member of the form +
        static void DeleteInstance(void* data) {
        +  // Cast `data` to an instance of the class and delete it.
        +}
        +
      • +
      • Heap-allocate an instance of this class in the addon initializer. This can be +accomplished using the new keyword.
      • +
      • Call node::AddEnvironmentCleanupHook(), passing it the above-created +instance and a pointer to DeleteInstance(). This will ensure the instance is +deleted when the environment is torn down.
      • +
      • Store the instance of the class in a v8::External, and
      • +
      • Pass the v8::External to all methods exposed to JavaScript by passing it +to v8::FunctionTemplate::New() or v8::Function::New() which creates the +native-backed JavaScript functions. The third parameter of +v8::FunctionTemplate::New() or v8::Function::New() accepts the +v8::External and makes it available in the native callback using the +v8::FunctionCallbackInfo::Data() method.
      • +
      +

      This will ensure that the per-addon-instance data reaches each binding that can +be called from JavaScript. The per-addon-instance data must also be passed into +any asynchronous callbacks the addon may create.

      +

      The following example illustrates the implementation of a context-aware addon:

      +
      #include <node.h>
      +
      +using namespace v8;
      +
      +class AddonData {
      + public:
      +  explicit AddonData(Isolate* isolate):
      +      call_count(0) {
      +    // Ensure this per-addon-instance data is deleted at environment cleanup.
      +    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
      +  }
      +
      +  // Per-addon data.
      +  int call_count;
      +
      +  static void DeleteInstance(void* data) {
      +    delete static_cast<AddonData*>(data);
      +  }
      +};
      +
      +static void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
      +  // Retrieve the per-addon-instance data.
      +  AddonData* data =
      +      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());
      +  data->call_count++;
      +  info.GetReturnValue().Set((double)data->call_count);
      +}
      +
      +// Initialize this addon to be context-aware.
      +NODE_MODULE_INIT(/* exports, module, context */) {
      +  Isolate* isolate = context->GetIsolate();
      +
      +  // Create a new instance of `AddonData` for this instance of the addon and
      +  // tie its life cycle to that of the Node.js environment.
      +  AddonData* data = new AddonData(isolate);
      +
      +  // Wrap the data in a `v8::External` so we can pass it to the method we
      +  // expose.
      +  Local<External> external = External::New(isolate, data);
      +
      +  // Expose the method `Method` to JavaScript, and make sure it receives the
      +  // per-addon-instance data we created above by passing `external` as the
      +  // third parameter to the `FunctionTemplate` constructor.
      +  exports->Set(context,
      +               String::NewFromUtf8(isolate, "method", NewStringType::kNormal)
      +                  .ToLocalChecked(),
      +               FunctionTemplate::New(isolate, Method, external)
      +                  ->GetFunction(context).ToLocalChecked()).FromJust();
      +}
      +

      Worker support#

      +
    • + + + +
      VersionChanges
      v12.19.0

      Cleanup hooks may now be asynchronous.

      + +
    • +

      In order to be loaded from multiple Node.js environments, +such as a main thread and a Worker thread, an add-on needs to either:

      +
        +
      • Be an N-API addon, or
      • +
      • Be declared as context-aware using NODE_MODULE_INIT() as described above
      • +
      +

      In order to support Worker threads, addons need to clean up any resources +they may have allocated when such a thread exists. This can be achieved through +the usage of the AddEnvironmentCleanupHook() function:

      +
      void AddEnvironmentCleanupHook(v8::Isolate* isolate,
      +                               void (*fun)(void* arg),
      +                               void* arg);
      +

      This function adds a hook that will run before a given Node.js instance shuts +down. If necessary, such hooks can be removed before they are run using +RemoveEnvironmentCleanupHook(), which has the same signature. Callbacks are +run in last-in first-out order.

      +

      If necessary, there is an additional pair of AddEnvironmentCleanupHook() +and RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a +callback function. This can be used for shutting down asynchronous resources, +such as any libuv handles registered by the addon.

      +

      The following addon.cc uses AddEnvironmentCleanupHook:

      +
      // addon.cc
      +#include <assert.h>
      +#include <stdlib.h>
      +#include <node.h>
      +
      +using node::AddEnvironmentCleanupHook;
      +using v8::HandleScope;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::Object;
      +
      +// Note: In a real-world application, do not rely on static/global data.
      +static char cookie[] = "yum yum";
      +static int cleanup_cb1_called = 0;
      +static int cleanup_cb2_called = 0;
      +
      +static void cleanup_cb1(void* arg) {
      +  Isolate* isolate = static_cast<Isolate*>(arg);
      +  HandleScope scope(isolate);
      +  Local<Object> obj = Object::New(isolate);
      +  assert(!obj.IsEmpty());  // assert VM is still alive
      +  assert(obj->IsObject());
      +  cleanup_cb1_called++;
      +}
      +
      +static void cleanup_cb2(void* arg) {
      +  assert(arg == static_cast<void*>(cookie));
      +  cleanup_cb2_called++;
      +}
      +
      +static void sanity_check(void*) {
      +  assert(cleanup_cb1_called == 1);
      +  assert(cleanup_cb2_called == 1);
      +}
      +
      +// Initialize this addon to be context-aware.
      +NODE_MODULE_INIT(/* exports, module, context */) {
      +  Isolate* isolate = context->GetIsolate();
      +
      +  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
      +  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
      +  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
      +}
      +

      Test in JavaScript by running:

      +
      // test.js
      +require('./build/Release/addon');
      +

      Building#

      +

      Once the source code has been written, it must be compiled into the binary +addon.node file. To do so, create a file called binding.gyp in the +top-level of the project describing the build configuration of the module +using a JSON-like format. This file is used by node-gyp, a tool written +specifically to compile Node.js addons.

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [ "hello.cc" ]
      +    }
      +  ]
      +}
      +

      A version of the node-gyp utility is bundled and distributed with +Node.js as part of npm. This version is not made directly available for +developers to use and is intended only to support the ability to use the +npm install command to compile and install addons. Developers who wish to +use node-gyp directly can install it using the command +npm install -g node-gyp. See the node-gyp installation instructions for +more information, including platform-specific requirements.

      +

      Once the binding.gyp file has been created, use node-gyp configure to +generate the appropriate project build files for the current platform. This +will generate either a Makefile (on Unix platforms) or a vcxproj file +(on Windows) in the build/ directory.

      +

      Next, invoke the node-gyp build command to generate the compiled addon.node +file. This will be put into the build/Release/ directory.

      +

      When using npm install to install a Node.js addon, npm uses its own bundled +version of node-gyp to perform this same set of actions, generating a +compiled version of the addon for the user's platform on demand.

      +

      Once built, the binary addon can be used from within Node.js by pointing +require() to the built addon.node module:

      +
      // hello.js
      +const addon = require('./build/Release/addon');
      +
      +console.log(addon.hello());
      +// Prints: 'world'
      +

      Because the exact path to the compiled addon binary can vary depending on how +it is compiled (i.e. sometimes it may be in ./build/Debug/), addons can use +the bindings package to load the compiled module.

      +

      While the bindings package implementation is more sophisticated in how it +locates addon modules, it is essentially using a try…catch pattern similar to:

      +
      try {
      +  return require('./build/Release/addon.node');
      +} catch (err) {
      +  return require('./build/Debug/addon.node');
      +}
      +

      Linking to libraries included with Node.js#

      +

      Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All +addons are required to link to V8 and may link to any of the other dependencies +as well. Typically, this is as simple as including the appropriate +#include <...> statements (e.g. #include <v8.h>) and node-gyp will locate +the appropriate headers automatically. However, there are a few caveats to be +aware of:

      +
        +
      • +

        When node-gyp runs, it will detect the specific release version of Node.js +and download either the full source tarball or just the headers. If the full +source is downloaded, addons will have complete access to the full set of +Node.js dependencies. However, if only the Node.js headers are downloaded, then +only the symbols exported by Node.js will be available.

        +
      • +
      • +

        node-gyp can be run using the --nodedir flag pointing at a local Node.js +source image. Using this option, the addon will have access to the full set of +dependencies.

        +
      • +
      +

      Loading addons using require()#

      +

      The filename extension of the compiled addon binary is .node (as opposed +to .dll or .so). The require() function is written to look for +files with the .node file extension and initialize those as dynamically-linked +libraries.

      +

      When calling require(), the .node extension can usually be +omitted and Node.js will still find and initialize the addon. One caveat, +however, is that Node.js will first attempt to locate and load modules or +JavaScript files that happen to share the same base name. For instance, if +there is a file addon.js in the same directory as the binary addon.node, +then require('addon') will give precedence to the addon.js file +and load it instead.

      +

      Native abstractions for Node.js#

      +

      Each of the examples illustrated in this document directly use the +Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed +dramatically from one V8 release to the next (and one major Node.js release to +the next). With each change, addons may need to be updated and recompiled in +order to continue functioning. The Node.js release schedule is designed to +minimize the frequency and impact of such changes but there is little that +Node.js can do to ensure stability of the V8 APIs.

      +

      The Native Abstractions for Node.js (or nan) provide a set of tools that +addon developers are recommended to use to keep compatibility between past and +future releases of V8 and Node.js. See the nan examples for an +illustration of how it can be used.

      +

      N-API#

      +

      Stability: 2 - Stable

      +

      N-API is an API for building native addons. It is independent from +the underlying JavaScript runtime (e.g. V8) and is maintained as part of +Node.js itself. This API will be Application Binary Interface (ABI) stable +across versions of Node.js. It is intended to insulate addons from +changes in the underlying JavaScript engine and allow modules +compiled for one version to run on later versions of Node.js without +recompilation. Addons are built/packaged with the same approach/tools +outlined in this document (node-gyp, etc.). The only difference is the +set of APIs that are used by the native code. Instead of using the V8 +or Native Abstractions for Node.js APIs, the functions available +in the N-API are used.

      +

      Creating and maintaining an addon that benefits from the ABI stability +provided by N-API carries with it certain +implementation considerations.

      +

      To use N-API in the above "Hello world" example, replace the content of +hello.cc with the following. All other instructions remain the same.

      +
      // hello.cc using N-API
      +#include <node_api.h>
      +
      +namespace demo {
      +
      +napi_value Method(napi_env env, napi_callback_info args) {
      +  napi_value greeting;
      +  napi_status status;
      +
      +  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
      +  if (status != napi_ok) return nullptr;
      +  return greeting;
      +}
      +
      +napi_value init(napi_env env, napi_value exports) {
      +  napi_status status;
      +  napi_value fn;
      +
      +  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
      +  if (status != napi_ok) return nullptr;
      +
      +  status = napi_set_named_property(env, exports, "hello", fn);
      +  if (status != napi_ok) return nullptr;
      +  return exports;
      +}
      +
      +NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
      +
      +}  // namespace demo
      +

      The functions available and how to use them are documented in +C/C++ addons with N-API.

      +

      Addon examples#

      +

      Following are some example addons intended to help developers get started. The +examples use the V8 APIs. Refer to the online V8 reference +for help with the various V8 calls, and V8's Embedder's Guide for an +explanation of several concepts used such as handles, scopes, function +templates, etc.

      +

      Each of these examples using the following binding.gyp file:

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [ "addon.cc" ]
      +    }
      +  ]
      +}
      +

      In cases where there is more than one .cc file, simply add the additional +filename to the sources array:

      +
      "sources": ["addon.cc", "myexample.cc"]
      +

      Once the binding.gyp file is ready, the example addons can be configured and +built using node-gyp:

      +
      $ node-gyp configure build
      +

      Function arguments#

      +

      Addons will typically expose objects and functions that can be accessed from +JavaScript running within Node.js. When functions are invoked from JavaScript, +the input arguments and return value must be mapped to and from the C/C++ +code.

      +

      The following example illustrates how to read function arguments passed from +JavaScript and how to return a result:

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Exception;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Number;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +// This is the implementation of the "add" method
      +// Input arguments are passed using the
      +// const FunctionCallbackInfo<Value>& args struct
      +void Add(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  // Check the number of arguments passed.
      +  if (args.Length() < 2) {
      +    // Throw an Error that is passed back to JavaScript
      +    isolate->ThrowException(Exception::TypeError(
      +        String::NewFromUtf8(isolate,
      +                            "Wrong number of arguments",
      +                            NewStringType::kNormal).ToLocalChecked()));
      +    return;
      +  }
      +
      +  // Check the argument types
      +  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
      +    isolate->ThrowException(Exception::TypeError(
      +        String::NewFromUtf8(isolate,
      +                            "Wrong arguments",
      +                            NewStringType::kNormal).ToLocalChecked()));
      +    return;
      +  }
      +
      +  // Perform the operation
      +  double value =
      +      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();
      +  Local<Number> num = Number::New(isolate, value);
      +
      +  // Set the return value (using the passed in
      +  // FunctionCallbackInfo<Value>&)
      +  args.GetReturnValue().Set(num);
      +}
      +
      +void Init(Local<Object> exports) {
      +  NODE_SET_METHOD(exports, "add", Add);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      Once compiled, the example addon can be required and used from within Node.js:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +console.log('This should be eight:', addon.add(3, 5));
      +

      Callbacks#

      +

      It is common practice within addons to pass JavaScript functions to a C++ +function and execute them from there. The following example illustrates how +to invoke such callbacks:

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Null;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void RunCallback(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<Function> cb = Local<Function>::Cast(args[0]);
      +  const unsigned argc = 1;
      +  Local<Value> argv[argc] = {
      +      String::NewFromUtf8(isolate,
      +                          "hello world",
      +                          NewStringType::kNormal).ToLocalChecked() };
      +  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
      +}
      +
      +void Init(Local<Object> exports, Local<Object> module) {
      +  NODE_SET_METHOD(module, "exports", RunCallback);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      This example uses a two-argument form of Init() that receives the full +module object as the second argument. This allows the addon to completely +overwrite exports with a single function instead of adding the function as a +property of exports.

      +

      To test it, run the following JavaScript:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +addon((msg) => {
      +  console.log(msg);
      +// Prints: 'hello world'
      +});
      +

      In this example, the callback function is invoked synchronously.

      +

      Object factory#

      +

      Addons can create and return new objects from within a C++ function as +illustrated in the following example. An object is created and returned with a +property msg that echoes the string passed to createObject():

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void CreateObject(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  Local<Object> obj = Object::New(isolate);
      +  obj->Set(context,
      +           String::NewFromUtf8(isolate,
      +                               "msg",
      +                               NewStringType::kNormal).ToLocalChecked(),
      +                               args[0]->ToString(context).ToLocalChecked())
      +           .FromJust();
      +
      +  args.GetReturnValue().Set(obj);
      +}
      +
      +void Init(Local<Object> exports, Local<Object> module) {
      +  NODE_SET_METHOD(module, "exports", CreateObject);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      To test it in JavaScript:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const obj1 = addon('hello');
      +const obj2 = addon('world');
      +console.log(obj1.msg, obj2.msg);
      +// Prints: 'hello world'
      +

      Function factory#

      +

      Another common scenario is creating JavaScript functions that wrap C++ +functions and returning those back to JavaScript:

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void MyFunction(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  args.GetReturnValue().Set(String::NewFromUtf8(
      +      isolate, "hello world", NewStringType::kNormal).ToLocalChecked());
      +}
      +
      +void CreateFunction(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
      +  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();
      +
      +  // omit this to make it anonymous
      +  fn->SetName(String::NewFromUtf8(
      +      isolate, "theFunction", NewStringType::kNormal).ToLocalChecked());
      +
      +  args.GetReturnValue().Set(fn);
      +}
      +
      +void Init(Local<Object> exports, Local<Object> module) {
      +  NODE_SET_METHOD(module, "exports", CreateFunction);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      To test:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const fn = addon();
      +console.log(fn());
      +// Prints: 'hello world'
      +

      Wrapping C++ objects#

      +

      It is also possible to wrap C++ objects/classes in a way that allows new +instances to be created using the JavaScript new operator:

      +
      // addon.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::Local;
      +using v8::Object;
      +
      +void InitAll(Local<Object> exports) {
      +  MyObject::Init(exports);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
      +
      +}  // namespace demo
      +

      Then, in myobject.h, the wrapper class inherits from node::ObjectWrap:

      +
      // myobject.h
      +#ifndef MYOBJECT_H
      +#define MYOBJECT_H
      +
      +#include <node.h>
      +#include <node_object_wrap.h>
      +
      +namespace demo {
      +
      +class MyObject : public node::ObjectWrap {
      + public:
      +  static void Init(v8::Local<v8::Object> exports);
      +
      + private:
      +  explicit MyObject(double value = 0);
      +  ~MyObject();
      +
      +  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
      +
      +  double value_;
      +};
      +
      +}  // namespace demo
      +
      +#endif
      +

      In myobject.cc, implement the various methods that are to be exposed. +Below, the method plusOne() is exposed by adding it to the constructor's +prototype:

      +
      // myobject.cc
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Number;
      +using v8::Object;
      +using v8::ObjectTemplate;
      +using v8::String;
      +using v8::Value;
      +
      +MyObject::MyObject(double value) : value_(value) {
      +}
      +
      +MyObject::~MyObject() {
      +}
      +
      +void MyObject::Init(Local<Object> exports) {
      +  Isolate* isolate = exports->GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);
      +  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()
      +  Local<Object> addon_data =
      +      addon_data_tpl->NewInstance(context).ToLocalChecked();
      +
      +  // Prepare constructor template
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);
      +  tpl->SetClassName(String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
      +  tpl->InstanceTemplate()->SetInternalFieldCount(1);
      +
      +  // Prototype
      +  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
      +
      +  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();
      +  addon_data->SetInternalField(0, constructor);
      +  exports->Set(context, String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked(),
      +               constructor).FromJust();
      +}
      +
      +void MyObject::New(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  if (args.IsConstructCall()) {
      +    // Invoked as constructor: `new MyObject(...)`
      +    double value = args[0]->IsUndefined() ?
      +        0 : args[0]->NumberValue(context).FromMaybe(0);
      +    MyObject* obj = new MyObject(value);
      +    obj->Wrap(args.This());
      +    args.GetReturnValue().Set(args.This());
      +  } else {
      +    // Invoked as plain function `MyObject(...)`, turn into construct call.
      +    const int argc = 1;
      +    Local<Value> argv[argc] = { args[0] };
      +    Local<Function> cons =
      +        args.Data().As<Object>()->GetInternalField(0).As<Function>();
      +    Local<Object> result =
      +        cons->NewInstance(context, argc, argv).ToLocalChecked();
      +    args.GetReturnValue().Set(result);
      +  }
      +}
      +
      +void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
      +  obj->value_ += 1;
      +
      +  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
      +}
      +
      +}  // namespace demo
      +

      To build this example, the myobject.cc file must be added to the +binding.gyp:

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [
      +        "addon.cc",
      +        "myobject.cc"
      +      ]
      +    }
      +  ]
      +}
      +

      Test it with:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const obj = new addon.MyObject(10);
      +console.log(obj.plusOne());
      +// Prints: 11
      +console.log(obj.plusOne());
      +// Prints: 12
      +console.log(obj.plusOne());
      +// Prints: 13
      +

      The destructor for a wrapper object will run when the object is +garbage-collected. For destructor testing, there are command-line flags that +can be used to make it possible to force garbage collection. These flags are +provided by the underlying V8 JavaScript engine. They are subject to change +or removal at any time. They are not documented by Node.js or V8, and they +should never be used outside of testing.

      +

      Factory of wrapped objects#

      +

      Alternatively, it is possible to use a factory pattern to avoid explicitly +creating object instances using the JavaScript new operator:

      +
      const obj = addon.createObject();
      +// instead of:
      +// const obj = new addon.Object();
      +

      First, the createObject() method is implemented in addon.cc:

      +
      // addon.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void CreateObject(const FunctionCallbackInfo<Value>& args) {
      +  MyObject::NewInstance(args);
      +}
      +
      +void InitAll(Local<Object> exports, Local<Object> module) {
      +  MyObject::Init(exports->GetIsolate());
      +
      +  NODE_SET_METHOD(module, "exports", CreateObject);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
      +
      +}  // namespace demo
      +

      In myobject.h, the static method NewInstance() is added to handle +instantiating the object. This method takes the place of using new in +JavaScript:

      +
      // myobject.h
      +#ifndef MYOBJECT_H
      +#define MYOBJECT_H
      +
      +#include <node.h>
      +#include <node_object_wrap.h>
      +
      +namespace demo {
      +
      +class MyObject : public node::ObjectWrap {
      + public:
      +  static void Init(v8::Isolate* isolate);
      +  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
      +
      + private:
      +  explicit MyObject(double value = 0);
      +  ~MyObject();
      +
      +  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static v8::Global<v8::Function> constructor;
      +  double value_;
      +};
      +
      +}  // namespace demo
      +
      +#endif
      +

      The implementation in myobject.cc is similar to the previous example:

      +
      // myobject.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using node::AddEnvironmentCleanupHook;
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Global;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Number;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +// Warning! This is not thread-safe, this addon cannot be used for worker
      +// threads.
      +Global<Function> MyObject::constructor;
      +
      +MyObject::MyObject(double value) : value_(value) {
      +}
      +
      +MyObject::~MyObject() {
      +}
      +
      +void MyObject::Init(Isolate* isolate) {
      +  // Prepare constructor template
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
      +  tpl->SetClassName(String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
      +  tpl->InstanceTemplate()->SetInternalFieldCount(1);
      +
      +  // Prototype
      +  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
      +
      +  Local<Context> context = isolate->GetCurrentContext();
      +  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
      +
      +  AddEnvironmentCleanupHook(isolate, [](void*) {
      +    constructor.Reset();
      +  }, nullptr);
      +}
      +
      +void MyObject::New(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  if (args.IsConstructCall()) {
      +    // Invoked as constructor: `new MyObject(...)`
      +    double value = args[0]->IsUndefined() ?
      +        0 : args[0]->NumberValue(context).FromMaybe(0);
      +    MyObject* obj = new MyObject(value);
      +    obj->Wrap(args.This());
      +    args.GetReturnValue().Set(args.This());
      +  } else {
      +    // Invoked as plain function `MyObject(...)`, turn into construct call.
      +    const int argc = 1;
      +    Local<Value> argv[argc] = { args[0] };
      +    Local<Function> cons = Local<Function>::New(isolate, constructor);
      +    Local<Object> instance =
      +        cons->NewInstance(context, argc, argv).ToLocalChecked();
      +    args.GetReturnValue().Set(instance);
      +  }
      +}
      +
      +void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  const unsigned argc = 1;
      +  Local<Value> argv[argc] = { args[0] };
      +  Local<Function> cons = Local<Function>::New(isolate, constructor);
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<Object> instance =
      +      cons->NewInstance(context, argc, argv).ToLocalChecked();
      +
      +  args.GetReturnValue().Set(instance);
      +}
      +
      +void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
      +  obj->value_ += 1;
      +
      +  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
      +}
      +
      +}  // namespace demo
      +

      Once again, to build this example, the myobject.cc file must be added to the +binding.gyp:

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [
      +        "addon.cc",
      +        "myobject.cc"
      +      ]
      +    }
      +  ]
      +}
      +

      Test it with:

      +
      // test.js
      +const createObject = require('./build/Release/addon');
      +
      +const obj = createObject(10);
      +console.log(obj.plusOne());
      +// Prints: 11
      +console.log(obj.plusOne());
      +// Prints: 12
      +console.log(obj.plusOne());
      +// Prints: 13
      +
      +const obj2 = createObject(20);
      +console.log(obj2.plusOne());
      +// Prints: 21
      +console.log(obj2.plusOne());
      +// Prints: 22
      +console.log(obj2.plusOne());
      +// Prints: 23
      +

      Passing wrapped objects around#

      +

      In addition to wrapping and returning C++ objects, it is possible to pass +wrapped objects around by unwrapping them with the Node.js helper function +node::ObjectWrap::Unwrap. The following examples shows a function add() +that can take two MyObject objects as input arguments:

      +
      // addon.cc
      +#include <node.h>
      +#include <node_object_wrap.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::Number;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void CreateObject(const FunctionCallbackInfo<Value>& args) {
      +  MyObject::NewInstance(args);
      +}
      +
      +void Add(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
      +      args[0]->ToObject(context).ToLocalChecked());
      +  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
      +      args[1]->ToObject(context).ToLocalChecked());
      +
      +  double sum = obj1->value() + obj2->value();
      +  args.GetReturnValue().Set(Number::New(isolate, sum));
      +}
      +
      +void InitAll(Local<Object> exports) {
      +  MyObject::Init(exports->GetIsolate());
      +
      +  NODE_SET_METHOD(exports, "createObject", CreateObject);
      +  NODE_SET_METHOD(exports, "add", Add);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
      +
      +}  // namespace demo
      +

      In myobject.h, a new public method is added to allow access to private values +after unwrapping the object.

      +
      // myobject.h
      +#ifndef MYOBJECT_H
      +#define MYOBJECT_H
      +
      +#include <node.h>
      +#include <node_object_wrap.h>
      +
      +namespace demo {
      +
      +class MyObject : public node::ObjectWrap {
      + public:
      +  static void Init(v8::Isolate* isolate);
      +  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  inline double value() const { return value_; }
      +
      + private:
      +  explicit MyObject(double value = 0);
      +  ~MyObject();
      +
      +  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static v8::Global<v8::Function> constructor;
      +  double value_;
      +};
      +
      +}  // namespace demo
      +
      +#endif
      +

      The implementation of myobject.cc is similar to before:

      +
      // myobject.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using node::AddEnvironmentCleanupHook;
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Global;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +// Warning! This is not thread-safe, this addon cannot be used for worker
      +// threads.
      +Global<Function> MyObject::constructor;
      +
      +MyObject::MyObject(double value) : value_(value) {
      +}
      +
      +MyObject::~MyObject() {
      +}
      +
      +void MyObject::Init(Isolate* isolate) {
      +  // Prepare constructor template
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
      +  tpl->SetClassName(String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
      +  tpl->InstanceTemplate()->SetInternalFieldCount(1);
      +
      +  Local<Context> context = isolate->GetCurrentContext();
      +  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
      +
      +  AddEnvironmentCleanupHook(isolate, [](void*) {
      +    constructor.Reset();
      +  }, nullptr);
      +}
      +
      +void MyObject::New(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  if (args.IsConstructCall()) {
      +    // Invoked as constructor: `new MyObject(...)`
      +    double value = args[0]->IsUndefined() ?
      +        0 : args[0]->NumberValue(context).FromMaybe(0);
      +    MyObject* obj = new MyObject(value);
      +    obj->Wrap(args.This());
      +    args.GetReturnValue().Set(args.This());
      +  } else {
      +    // Invoked as plain function `MyObject(...)`, turn into construct call.
      +    const int argc = 1;
      +    Local<Value> argv[argc] = { args[0] };
      +    Local<Function> cons = Local<Function>::New(isolate, constructor);
      +    Local<Object> instance =
      +        cons->NewInstance(context, argc, argv).ToLocalChecked();
      +    args.GetReturnValue().Set(instance);
      +  }
      +}
      +
      +void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  const unsigned argc = 1;
      +  Local<Value> argv[argc] = { args[0] };
      +  Local<Function> cons = Local<Function>::New(isolate, constructor);
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<Object> instance =
      +      cons->NewInstance(context, argc, argv).ToLocalChecked();
      +
      +  args.GetReturnValue().Set(instance);
      +}
      +
      +}  // namespace demo
      +

      Test it with:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const obj1 = addon.createObject(10);
      +const obj2 = addon.createObject(20);
      +const result = addon.add(obj1, obj2);
      +
      +console.log(result);
      +// Prints: 30
      + + + + + + diff --git a/doc/api/addons.json b/doc/api/addons.json new file mode 100644 index 0000000000000000000000000000000000000000..12a6f6e724675af93d2f07aa5a7e21c260adcfc5 --- /dev/null +++ b/doc/api/addons.json @@ -0,0 +1,145 @@ +{ + "type": "module", + "source": "doc/api/addons.md", + "introduced_in": "v0.10.0", + "miscs": [ + { + "textRaw": "C++ addons", + "name": "C++ addons", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      Addons are dynamically-linked shared objects written in C++. The\nrequire() function can load addons as ordinary Node.js modules.\nAddons provide an interface between JavaScript and C/C++ libraries.

      \n

      There are three options for implementing addons: N-API, nan, or direct\nuse of internal V8, libuv and Node.js libraries. Unless there is a need for\ndirect access to functionality which is not exposed by N-API, use N-API.\nRefer to C/C++ addons with N-API for more information on N-API.

      \n

      When not using N-API, implementing addons is complicated,\ninvolving knowledge of several components and APIs:

      \n
        \n
      • \n

        V8: the C++ library Node.js uses to provide the\nJavaScript implementation. V8 provides the mechanisms for creating objects,\ncalling functions, etc. V8's API is documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node.js source\ntree), which is also available online.

        \n
      • \n
      • \n

        libuv: The C library that implements the Node.js event loop, its worker\nthreads and all of the asynchronous behaviors of the platform. It also\nserves as a cross-platform abstraction library, giving easy, POSIX-like\naccess across all major operating systems to many common system tasks, such\nas interacting with the filesystem, sockets, timers, and system events. libuv\nalso provides a pthreads-like threading abstraction that may be used to\npower more sophisticated asynchronous addons that need to move beyond the\nstandard event loop. Addon authors are encouraged to think about how to\navoid blocking the event loop with I/O or other time-intensive tasks by\noff-loading work via libuv to non-blocking system operations, worker threads\nor a custom use of libuv's threads.

        \n
      • \n
      • \n

        Internal Node.js libraries. Node.js itself exports C++ APIs that addons can\nuse, the most important of which is the node::ObjectWrap class.

        \n
      • \n
      • \n

        Node.js includes other statically linked libraries including OpenSSL. These\nother libraries are located in the deps/ directory in the Node.js source\ntree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully\nre-exported by Node.js and may be used to various extents by addons. See\nLinking to libraries included with Node.js for additional information.

        \n
      • \n
      \n

      All of the following examples are available for download and may\nbe used as the starting-point for an addon.

      ", + "miscs": [ + { + "textRaw": "Hello world", + "name": "hello_world", + "desc": "

      This \"Hello world\" example is a simple addon, written in C++, that is the\nequivalent of the following JavaScript code:

      \n
      module.exports.hello = () => 'world';\n
      \n

      First, create the file hello.cc:

      \n
      // hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid Method(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"hello\", Method);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n\n}  // namespace demo\n
      \n

      All Node.js addons must export an initialization function following\nthe pattern:

      \n
      void Initialize(Local<Object> exports);\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n
      \n

      There is no semi-colon after NODE_MODULE as it's not a function (see\nnode.h).

      \n

      The module_name must match the filename of the final binary (excluding\nthe .node suffix).

      \n

      In the hello.cc example, then, the initialization function is Initialize\nand the addon module name is addon.

      \n

      When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as\nthe first parameter of NODE_MODULE() will ensure that the name of the final\nbinary will be passed to NODE_MODULE().

      ", + "modules": [ + { + "textRaw": "Context-aware addons", + "name": "context-aware_addons", + "desc": "

      There are environments in which Node.js addons may need to be loaded multiple\ntimes in multiple contexts. For example, the Electron runtime runs multiple\ninstances of Node.js in a single process. Each instance will have its own\nrequire() cache, and thus each instance will need a native addon to behave\ncorrectly when loaded via require(). From the addon's perspective, this means\nthat it must support multiple initializations.

      \n

      A context-aware addon can be constructed by using the macro\nNODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js\nwill expect to find when it loads an addon. An addon can thus be initialized as\nin the following example:

      \n
      using namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local<Object> exports,\n                        Local<Value> module,\n                        Local<Context> context) {\n  /* Perform addon initialization steps here. */\n}\n
      \n

      Another option is to use the macro NODE_MODULE_INIT(), which will also\nconstruct a context-aware addon. Unlike NODE_MODULE(), which is used to\nconstruct an addon around a given addon initializer function,\nNODE_MODULE_INIT() serves as the declaration of such an initializer to be\nfollowed by a function body.

      \n

      The following three variables may be used inside the function body following an\ninvocation of NODE_MODULE_INIT():

      \n
        \n
      • Local<Object> exports,
      • \n
      • Local<Value> module, and
      • \n
      • Local<Context> context
      • \n
      \n

      The choice to build a context-aware addon carries with it the responsibility of\ncarefully managing global static data. Since the addon may be loaded multiple\ntimes, potentially even from different threads, any global static data stored\nin the addon must be properly protected, and must not contain any persistent\nreferences to JavaScript objects. The reason for this is that JavaScript\nobjects are only valid in one context, and will likely cause a crash when\naccessed from the wrong context or from a different thread than the one on which\nthey were created.

      \n

      The context-aware addon can be structured to avoid global static data by\nperforming the following steps:

      \n
        \n
      • Define a class which will hold per-addon-instance data and which has a static\nmember of the form\n
        static void DeleteInstance(void* data) {\n  // Cast `data` to an instance of the class and delete it.\n}\n
        \n
      • \n
      • Heap-allocate an instance of this class in the addon initializer. This can be\naccomplished using the new keyword.
      • \n
      • Call node::AddEnvironmentCleanupHook(), passing it the above-created\ninstance and a pointer to DeleteInstance(). This will ensure the instance is\ndeleted when the environment is torn down.
      • \n
      • Store the instance of the class in a v8::External, and
      • \n
      • Pass the v8::External to all methods exposed to JavaScript by passing it\nto v8::FunctionTemplate::New() or v8::Function::New() which creates the\nnative-backed JavaScript functions. The third parameter of\nv8::FunctionTemplate::New() or v8::Function::New() accepts the\nv8::External and makes it available in the native callback using the\nv8::FunctionCallbackInfo::Data() method.
      • \n
      \n

      This will ensure that the per-addon-instance data reaches each binding that can\nbe called from JavaScript. The per-addon-instance data must also be passed into\nany asynchronous callbacks the addon may create.

      \n

      The following example illustrates the implementation of a context-aware addon:

      \n
      #include <node.h>\n\nusing namespace v8;\n\nclass AddonData {\n public:\n  explicit AddonData(Isolate* isolate):\n      call_count(0) {\n    // Ensure this per-addon-instance data is deleted at environment cleanup.\n    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);\n  }\n\n  // Per-addon data.\n  int call_count;\n\n  static void DeleteInstance(void* data) {\n    delete static_cast<AddonData*>(data);\n  }\n};\n\nstatic void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {\n  // Retrieve the per-addon-instance data.\n  AddonData* data =\n      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());\n  data->call_count++;\n  info.GetReturnValue().Set((double)data->call_count);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = context->GetIsolate();\n\n  // Create a new instance of `AddonData` for this instance of the addon and\n  // tie its life cycle to that of the Node.js environment.\n  AddonData* data = new AddonData(isolate);\n\n  // Wrap the data in a `v8::External` so we can pass it to the method we\n  // expose.\n  Local<External> external = External::New(isolate, data);\n\n  // Expose the method `Method` to JavaScript, and make sure it receives the\n  // per-addon-instance data we created above by passing `external` as the\n  // third parameter to the `FunctionTemplate` constructor.\n  exports->Set(context,\n               String::NewFromUtf8(isolate, \"method\", NewStringType::kNormal)\n                  .ToLocalChecked(),\n               FunctionTemplate::New(isolate, Method, external)\n                  ->GetFunction(context).ToLocalChecked()).FromJust();\n}\n
      ", + "modules": [ + { + "textRaw": "Worker support", + "name": "worker_support", + "meta": { + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34572", + "description": "Cleanup hooks may now be asynchronous." + } + ] + }, + "desc": "

      In order to be loaded from multiple Node.js environments,\nsuch as a main thread and a Worker thread, an add-on needs to either:

      \n
        \n
      • Be an N-API addon, or
      • \n
      • Be declared as context-aware using NODE_MODULE_INIT() as described above
      • \n
      \n

      In order to support Worker threads, addons need to clean up any resources\nthey may have allocated when such a thread exists. This can be achieved through\nthe usage of the AddEnvironmentCleanupHook() function:

      \n
      void AddEnvironmentCleanupHook(v8::Isolate* isolate,\n                               void (*fun)(void* arg),\n                               void* arg);\n
      \n

      This function adds a hook that will run before a given Node.js instance shuts\ndown. If necessary, such hooks can be removed before they are run using\nRemoveEnvironmentCleanupHook(), which has the same signature. Callbacks are\nrun in last-in first-out order.

      \n

      If necessary, there is an additional pair of AddEnvironmentCleanupHook()\nand RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a\ncallback function. This can be used for shutting down asynchronous resources,\nsuch as any libuv handles registered by the addon.

      \n

      The following addon.cc uses AddEnvironmentCleanupHook:

      \n
      // addon.cc\n#include <assert.h>\n#include <stdlib.h>\n#include <node.h>\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\n// Note: In a real-world application, do not rely on static/global data.\nstatic char cookie[] = \"yum yum\";\nstatic int cleanup_cb1_called = 0;\nstatic int cleanup_cb2_called = 0;\n\nstatic void cleanup_cb1(void* arg) {\n  Isolate* isolate = static_cast<Isolate*>(arg);\n  HandleScope scope(isolate);\n  Local<Object> obj = Object::New(isolate);\n  assert(!obj.IsEmpty());  // assert VM is still alive\n  assert(obj->IsObject());\n  cleanup_cb1_called++;\n}\n\nstatic void cleanup_cb2(void* arg) {\n  assert(arg == static_cast<void*>(cookie));\n  cleanup_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n  assert(cleanup_cb1_called == 1);\n  assert(cleanup_cb2_called == 1);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = context->GetIsolate();\n\n  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);\n}\n
      \n

      Test in JavaScript by running:

      \n
      // test.js\nrequire('./build/Release/addon');\n
      ", + "type": "module", + "displayName": "Worker support" + } + ], + "type": "module", + "displayName": "Context-aware addons" + }, + { + "textRaw": "Building", + "name": "building", + "desc": "

      Once the source code has been written, it must be compiled into the binary\naddon.node file. To do so, create a file called binding.gyp in the\ntop-level of the project describing the build configuration of the module\nusing a JSON-like format. This file is used by node-gyp, a tool written\nspecifically to compile Node.js addons.

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}\n
      \n

      A version of the node-gyp utility is bundled and distributed with\nNode.js as part of npm. This version is not made directly available for\ndevelopers to use and is intended only to support the ability to use the\nnpm install command to compile and install addons. Developers who wish to\nuse node-gyp directly can install it using the command\nnpm install -g node-gyp. See the node-gyp installation instructions for\nmore information, including platform-specific requirements.

      \n

      Once the binding.gyp file has been created, use node-gyp configure to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory.

      \n

      Next, invoke the node-gyp build command to generate the compiled addon.node\nfile. This will be put into the build/Release/ directory.

      \n

      When using npm install to install a Node.js addon, npm uses its own bundled\nversion of node-gyp to perform this same set of actions, generating a\ncompiled version of the addon for the user's platform on demand.

      \n

      Once built, the binary addon can be used from within Node.js by pointing\nrequire() to the built addon.node module:

      \n
      // hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n
      \n

      Because the exact path to the compiled addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in ./build/Debug/), addons can use\nthe bindings package to load the compiled module.

      \n

      While the bindings package implementation is more sophisticated in how it\nlocates addon modules, it is essentially using a try…catch pattern similar to:

      \n
      try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n
      ", + "type": "module", + "displayName": "Building" + }, + { + "textRaw": "Linking to libraries included with Node.js", + "name": "linking_to_libraries_included_with_node.js", + "desc": "

      Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All\naddons are required to link to V8 and may link to any of the other dependencies\nas well. Typically, this is as simple as including the appropriate\n#include <...> statements (e.g. #include <v8.h>) and node-gyp will locate\nthe appropriate headers automatically. However, there are a few caveats to be\naware of:

      \n
        \n
      • \n

        When node-gyp runs, it will detect the specific release version of Node.js\nand download either the full source tarball or just the headers. If the full\nsource is downloaded, addons will have complete access to the full set of\nNode.js dependencies. However, if only the Node.js headers are downloaded, then\nonly the symbols exported by Node.js will be available.

        \n
      • \n
      • \n

        node-gyp can be run using the --nodedir flag pointing at a local Node.js\nsource image. Using this option, the addon will have access to the full set of\ndependencies.

        \n
      • \n
      ", + "type": "module", + "displayName": "Linking to libraries included with Node.js" + }, + { + "textRaw": "Loading addons using `require()`", + "name": "loading_addons_using_`require()`", + "desc": "

      The filename extension of the compiled addon binary is .node (as opposed\nto .dll or .so). The require() function is written to look for\nfiles with the .node file extension and initialize those as dynamically-linked\nlibraries.

      \n

      When calling require(), the .node extension can usually be\nomitted and Node.js will still find and initialize the addon. One caveat,\nhowever, is that Node.js will first attempt to locate and load modules or\nJavaScript files that happen to share the same base name. For instance, if\nthere is a file addon.js in the same directory as the binary addon.node,\nthen require('addon') will give precedence to the addon.js file\nand load it instead.

      ", + "type": "module", + "displayName": "Loading addons using `require()`" + } + ], + "type": "misc", + "displayName": "Hello world" + }, + { + "textRaw": "Native abstractions for Node.js", + "name": "native_abstractions_for_node.js", + "desc": "

      Each of the examples illustrated in this document directly use the\nNode.js and V8 APIs for implementing addons. The V8 API can, and has, changed\ndramatically from one V8 release to the next (and one major Node.js release to\nthe next). With each change, addons may need to be updated and recompiled in\norder to continue functioning. The Node.js release schedule is designed to\nminimize the frequency and impact of such changes but there is little that\nNode.js can do to ensure stability of the V8 APIs.

      \n

      The Native Abstractions for Node.js (or nan) provide a set of tools that\naddon developers are recommended to use to keep compatibility between past and\nfuture releases of V8 and Node.js. See the nan examples for an\nillustration of how it can be used.

      ", + "type": "misc", + "displayName": "Native abstractions for Node.js" + }, + { + "textRaw": "N-API", + "name": "n-api", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      N-API is an API for building native addons. It is independent from\nthe underlying JavaScript runtime (e.g. V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross versions of Node.js. It is intended to insulate addons from\nchanges in the underlying JavaScript engine and allow modules\ncompiled for one version to run on later versions of Node.js without\nrecompilation. Addons are built/packaged with the same approach/tools\noutlined in this document (node-gyp, etc.). The only difference is the\nset of APIs that are used by the native code. Instead of using the V8\nor Native Abstractions for Node.js APIs, the functions available\nin the N-API are used.

      \n

      Creating and maintaining an addon that benefits from the ABI stability\nprovided by N-API carries with it certain\nimplementation considerations.

      \n

      To use N-API in the above \"Hello world\" example, replace the content of\nhello.cc with the following. All other instructions remain the same.

      \n
      // hello.cc using N-API\n#include <node_api.h>\n\nnamespace demo {\n\nnapi_value Method(napi_env env, napi_callback_info args) {\n  napi_value greeting;\n  napi_status status;\n\n  status = napi_create_string_utf8(env, \"world\", NAPI_AUTO_LENGTH, &greeting);\n  if (status != napi_ok) return nullptr;\n  return greeting;\n}\n\nnapi_value init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_value fn;\n\n  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);\n  if (status != napi_ok) return nullptr;\n\n  status = napi_set_named_property(env, exports, \"hello\", fn);\n  if (status != napi_ok) return nullptr;\n  return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, init)\n\n}  // namespace demo\n
      \n

      The functions available and how to use them are documented in\nC/C++ addons with N-API.

      ", + "type": "misc", + "displayName": "N-API" + }, + { + "textRaw": "Addon examples", + "name": "addon_examples", + "desc": "

      Following are some example addons intended to help developers get started. The\nexamples use the V8 APIs. Refer to the online V8 reference\nfor help with the various V8 calls, and V8's Embedder's Guide for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.

      \n

      Each of these examples using the following binding.gyp file:

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}\n
      \n

      In cases where there is more than one .cc file, simply add the additional\nfilename to the sources array:

      \n
      \"sources\": [\"addon.cc\", \"myexample.cc\"]\n
      \n

      Once the binding.gyp file is ready, the example addons can be configured and\nbuilt using node-gyp:

      \n
      $ node-gyp configure build\n
      ", + "modules": [ + { + "textRaw": "Function arguments", + "name": "function_arguments", + "desc": "

      Addons will typically expose objects and functions that can be accessed from\nJavaScript running within Node.js. When functions are invoked from JavaScript,\nthe input arguments and return value must be mapped to and from the C/C++\ncode.

      \n

      The following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the \"add\" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  // Check the number of arguments passed.\n  if (args.Length() < 2) {\n    // Throw an Error that is passed back to JavaScript\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong number of arguments\",\n                            NewStringType::kNormal).ToLocalChecked()));\n    return;\n  }\n\n  // Check the argument types\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong arguments\",\n                            NewStringType::kNormal).ToLocalChecked()));\n    return;\n  }\n\n  // Perform the operation\n  double value =\n      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();\n  Local<Number> num = Number::New(isolate, value);\n\n  // Set the return value (using the passed in\n  // FunctionCallbackInfo<Value>&)\n  args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      Once compiled, the example addon can be required and used from within Node.js:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n
      ", + "type": "module", + "displayName": "Function arguments" + }, + { + "textRaw": "Callbacks", + "name": "callbacks", + "desc": "

      It is common practice within addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = {\n      String::NewFromUtf8(isolate,\n                          \"hello world\",\n                          NewStringType::kNormal).ToLocalChecked() };\n  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      This example uses a two-argument form of Init() that receives the full\nmodule object as the second argument. This allows the addon to completely\noverwrite exports with a single function instead of adding the function as a\nproperty of exports.

      \n

      To test it, run the following JavaScript:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg);\n// Prints: 'hello world'\n});\n
      \n

      In this example, the callback function is invoked synchronously.

      ", + "type": "module", + "displayName": "Callbacks" + }, + { + "textRaw": "Object factory", + "name": "object_factory", + "desc": "

      Addons can create and return new objects from within a C++ function as\nillustrated in the following example. An object is created and returned with a\nproperty msg that echoes the string passed to createObject():

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<Object> obj = Object::New(isolate);\n  obj->Set(context,\n           String::NewFromUtf8(isolate,\n                               \"msg\",\n                               NewStringType::kNormal).ToLocalChecked(),\n                               args[0]->ToString(context).ToLocalChecked())\n           .FromJust();\n\n  args.GetReturnValue().Set(obj);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      To test it in JavaScript:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'\n
      ", + "type": "module", + "displayName": "Object factory" + }, + { + "textRaw": "Function factory", + "name": "function_factory", + "desc": "

      Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"hello world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();\n\n  // omit this to make it anonymous\n  fn->SetName(String::NewFromUtf8(\n      isolate, \"theFunction\", NewStringType::kNormal).ToLocalChecked());\n\n  args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      To test:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n
      ", + "type": "module", + "displayName": "Function factory" + }, + { + "textRaw": "Wrapping C++ objects", + "name": "wrapping_c++_objects", + "desc": "

      It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript new operator:

      \n
      // addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
      \n

      Then, in myobject.h, the wrapper class inherits from node::ObjectWrap:

      \n
      // myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Local<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
      \n

      In myobject.cc, implement the various methods that are to be exposed.\nBelow, the method plusOne() is exposed by adding it to the constructor's\nprototype:

      \n
      // myobject.cc\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n  Isolate* isolate = exports->GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);\n  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()\n  Local<Object> addon_data =\n      addon_data_tpl->NewInstance(context).ToLocalChecked();\n\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();\n  addon_data->SetInternalField(0, constructor);\n  exports->Set(context, String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked(),\n               constructor).FromJust();\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons =\n        args.Data().As<Object>()->GetInternalField(0).As<Function>();\n    Local<Object> result =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(result);\n  }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
      \n

      To build this example, the myobject.cc file must be added to the\nbinding.gyp:

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
      \n

      Test it with:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n
      \n

      The destructor for a wrapper object will run when the object is\ngarbage-collected. For destructor testing, there are command-line flags that\ncan be used to make it possible to force garbage collection. These flags are\nprovided by the underlying V8 JavaScript engine. They are subject to change\nor removal at any time. They are not documented by Node.js or V8, and they\nshould never be used outside of testing.

      ", + "type": "module", + "displayName": "Wrapping C++ objects" + }, + { + "textRaw": "Factory of wrapped objects", + "name": "factory_of_wrapped_objects", + "desc": "

      Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript new operator:

      \n
      const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n
      \n

      First, the createObject() method is implemented in addon.cc:

      \n
      // addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n  MyObject::Init(exports->GetIsolate());\n\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
      \n

      In myobject.h, the static method NewInstance() is added to handle\ninstantiating the object. This method takes the place of using new in\nJavaScript:

      \n
      // myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Isolate* isolate);\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
      \n

      The implementation in myobject.cc is similar to the previous example:

      \n
      // myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
      \n

      Once again, to build this example, the myobject.cc file must be added to the\nbinding.gyp:

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
      \n

      Test it with:

      \n
      // test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23\n
      ", + "type": "module", + "displayName": "Factory of wrapped objects" + }, + { + "textRaw": "Passing wrapped objects around", + "name": "passing_wrapped_objects_around", + "desc": "

      In addition to wrapping and returning C++ objects, it is possible to pass\nwrapped objects around by unwrapping them with the Node.js helper function\nnode::ObjectWrap::Unwrap. The following examples shows a function add()\nthat can take two MyObject objects as input arguments:

      \n
      // addon.cc\n#include <node.h>\n#include <node_object_wrap.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject(context).ToLocalChecked());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject(context).ToLocalChecked());\n\n  double sum = obj1->value() + obj2->value();\n  args.GetReturnValue().Set(Number::New(isolate, sum));\n}\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports->GetIsolate());\n\n  NODE_SET_METHOD(exports, \"createObject\", CreateObject);\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
      \n

      In myobject.h, a new public method is added to allow access to private values\nafter unwrapping the object.

      \n
      // myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Isolate* isolate);\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n  inline double value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
      \n

      The implementation of myobject.cc is similar to before:

      \n
      // myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo\n
      \n

      Test it with:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30\n
      ", + "type": "module", + "displayName": "Passing wrapped objects around" + } + ], + "type": "misc", + "displayName": "Addon examples" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/all.html b/doc/api/all.html new file mode 100644 index 0000000000000000000000000000000000000000..7dcf5e1f6549abaa7a5125b4ee146e18a1ca9522 --- /dev/null +++ b/doc/api/all.html @@ -0,0 +1,64117 @@ + + + + + + + Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + + +
      + +
      +

      About this documentation#

      + + +

      Welcome to the official API reference documentation for Node.js!

      +

      Node.js is a JavaScript runtime built on the V8 JavaScript engine.

      +

      Contributing#

      +

      Report errors in this documentation in the issue tracker. See +the contributing guide for directions on how to submit pull requests.

      +

      Stability index#

      + +

      Throughout the documentation are indications of a section's stability. Some APIs +are so proven and so relied upon that they are unlikely to ever change at all. +Others are brand new and experimental, or known to be hazardous.

      +

      The stability indices are as follows:

      +

      Stability: 0 - Deprecated. The feature may emit warnings. Backward +compatibility is not guaranteed.

      + +

      Stability: 1 - Experimental. The feature is not subject to +Semantic Versioning rules. Non-backward compatible changes or removal may +occur in any future release. Use of the feature is not recommended in +production environments.

      + +

      Stability: 2 - Stable. Compatibility with the npm ecosystem is a high +priority.

      +

      Use caution when making use of Experimental features, particularly within +modules. Users may not be aware that experimental features are being used. +Bugs or behavior changes may surprise users when Experimental API +modifications occur. To avoid surprises, use of an Experimental feature may need +a command-line flag. Experimental features may also emit a warning.

      +

      JSON output#

      + +

      Every .html document has a corresponding .json document. This is for IDEs +and other utilities that consume the documentation.

      +

      System calls and man pages#

      +

      Node.js functions which wrap a system call will document that. The docs link +to the corresponding man pages which describe how the system call works.

      +

      Most Unix system calls have Windows analogues. Still, behavior differences may +be unavoidable.

      +

      Usage and example#

      +

      Usage#

      + + +

      node [options] [V8 options] [script.js | -e "script" | - ] [arguments]

      +

      Please see the Command Line Options document for more information.

      +

      Example#

      +

      An example of a web server written with Node.js which responds with +'Hello, World!':

      +

      Commands in this document start with $ or > to replicate how they would +appear in a user's terminal. Do not include the $ and > characters. They are +there to show the start of each command.

      +

      Lines that don’t start with $ or > character show the output of the previous +command.

      +

      First, make sure to have downloaded and installed Node.js. See this guide +for further install information.

      +

      Now, create an empty project folder called projects, then navigate into it.

      +

      Linux and Mac:

      +
      $ mkdir ~/projects
      +$ cd ~/projects
      +

      Windows CMD:

      +
      > mkdir %USERPROFILE%\projects
      +> cd %USERPROFILE%\projects
      +

      Windows PowerShell:

      +
      > mkdir $env:USERPROFILE\projects
      +> cd $env:USERPROFILE\projects
      +

      Next, create a new source file in the projects +folder and call it hello-world.js.

      +

      Open hello-world.js in any preferred text editor and +paste in the following content:

      +
      const http = require('http');
      +
      +const hostname = '127.0.0.1';
      +const port = 3000;
      +
      +const server = http.createServer((req, res) => {
      +  res.statusCode = 200;
      +  res.setHeader('Content-Type', 'text/plain');
      +  res.end('Hello, World!\n');
      +});
      +
      +server.listen(port, hostname, () => {
      +  console.log(`Server running at http://${hostname}:${port}/`);
      +});
      +

      Save the file, go back to the terminal window, and enter the following command:

      +
      $ node hello-world.js
      +

      Output like this should appear in the terminal:

      +
      Server running at http://127.0.0.1:3000/
      +

      Now, open any preferred web browser and visit http://127.0.0.1:3000.

      +

      If the browser displays the string Hello, World!, that indicates +the server is working.

      +

      Assert#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/assert.js

      +

      The assert module provides a set of assertion functions for verifying +invariants.

      +

      Strict assertion mode#

      + +

      In strict assertion mode, non-strict methods behave like their corresponding +strict methods. For example, assert.deepEqual() will behave like +assert.deepStrictEqual().

      +

      In strict assertion mode, error messages for objects display a diff. In legacy +assertion mode, error messages for objects display the objects, often truncated.

      +

      To use strict assertion mode:

      +
      const assert = require('assert').strict;
      +

      Example error diff:

      +
      const assert = require('assert').strict;
      +
      +assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected ... Lines skipped
      +//
      +//   [
      +//     [
      +// ...
      +//       2,
      +// +     3
      +// -     '3'
      +//     ],
      +// ...
      +//     5
      +//   ]
      +

      To deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS +environment variables. This will also deactivate the colors in the REPL. For +more on color support in terminal environments, read the tty +getColorDepth() documentation.

      +

      Legacy assertion mode#

      +

      Legacy assertion mode uses the Abstract Equality Comparison in:

      + +

      To use legacy assertion mode:

      +
      const assert = require('assert');
      +

      Whenever possible, use the strict assertion mode instead. Otherwise, the +Abstract Equality Comparison may cause surprising results. This is +especially true for assert.deepEqual(), where the comparison rules are +lax:

      +
      // WARNING: This does not throw an AssertionError!
      +assert.deepEqual(/a/gi, new Date());
      +

      Class: assert.AssertionError[src]#

      + +

      Indicates the failure of an assertion. All errors thrown by the assert module +will be instances of the AssertionError class.

      +

      new assert.AssertionError(options)#

      + +
        +
      • options <Object> +
          +
        • message <string> If provided, the error message is set to this value.
        • +
        • actual <any> The actual property on the error instance.
        • +
        • expected <any> The expected property on the error instance.
        • +
        • operator <string> The operator property on the error instance.
        • +
        • stackStartFn <Function> If provided, the generated stack trace omits +frames before this function.
        • +
        +
      • +
      +

      A subclass of Error that indicates the failure of an assertion.

      +

      All instances contain the built-in Error properties (message and name) +and:

      +
        +
      • actual <any> Set to the actual argument for methods such as +assert.strictEqual().
      • +
      • expected <any> Set to the expected value for methods such as +assert.strictEqual().
      • +
      • generatedMessage <boolean> Indicates if the message was auto-generated +(true) or not.
      • +
      • code <string> Value is always ERR_ASSERTION to show that the error is an +assertion error.
      • +
      • operator <string> Set to the passed in operator value.
      • +
      +
      const assert = require('assert');
      +
      +// Generate an AssertionError to compare the error message later:
      +const { message } = new assert.AssertionError({
      +  actual: 1,
      +  expected: 2,
      +  operator: 'strictEqual'
      +});
      +
      +// Verify error output:
      +try {
      +  assert.strictEqual(1, 2);
      +} catch (err) {
      +  assert(err instanceof assert.AssertionError);
      +  assert.strictEqual(err.message, message);
      +  assert.strictEqual(err.name, 'AssertionError');
      +  assert.strictEqual(err.actual, 1);
      +  assert.strictEqual(err.expected, 2);
      +  assert.strictEqual(err.code, 'ERR_ASSERTION');
      +  assert.strictEqual(err.operator, 'strictEqual');
      +  assert.strictEqual(err.generatedMessage, true);
      +}
      +

      Class: assert.CallTracker#

      + +

      Stability: 1 - Experimental

      +

      This feature is currently experimental and behavior might still change.

      +

      ### new assert.CallTracker()

      + +

      Creates a new CallTracker object which can be used to track if functions +were called a specific number of times. The tracker.verify() must be called +for the verification to take place. The usual pattern would be to call it in a +process.on('exit') handler.

      +
      const assert = require('assert');
      +
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +// callsfunc() must be called exactly 1 time before tracker.verify().
      +const callsfunc = tracker.calls(func, 1);
      +
      +callsfunc();
      +
      +// Calls tracker.verify() and verifies if all tracker.calls() functions have
      +// been called exact times.
      +process.on('exit', () => {
      +  tracker.verify();
      +});
      +

      tracker.calls([fn][, exact])#

      + + +

      The wrapper function is expected to be called exactly exact times. If the +function has not been called exactly exact times when +tracker.verify() is called, then tracker.verify() will throw an +error.

      +
      const assert = require('assert');
      +
      +// Creates call tracker.
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +// Returns a function that wraps func() that must be called exact times
      +// before tracker.verify().
      +const callsfunc = tracker.calls(func);
      +

      tracker.report()#

      + +
        +
      • Returns: <Array> of objects containing information about the wrapper functions +returned by tracker.calls().
      • +
      • Object <Object> +
          +
        • message <string>
        • +
        • actual <number> The actual number of times the function was called.
        • +
        • expected <number> The number of times the function was expected to be +called.
        • +
        • operator <string> The name of the function that is wrapped.
        • +
        • stack <Object> A stack trace of the function.
        • +
        +
      • +
      +

      The arrays contains information about the expected and actual number of calls of +the functions that have not been called the expected number of times.

      +
      const assert = require('assert');
      +
      +// Creates call tracker.
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +function foo() {}
      +
      +// Returns a function that wraps func() that must be called exact times
      +// before tracker.verify().
      +const callsfunc = tracker.calls(func, 2);
      +
      +// Returns an array containing information on callsfunc()
      +tracker.report();
      +// [
      +//  {
      +//    message: 'Expected the func function to be executed 2 time(s) but was
      +//    executed 0 time(s).',
      +//    actual: 0,
      +//    expected: 2,
      +//    operator: 'func',
      +//    stack: stack trace
      +//  }
      +// ]
      +

      tracker.verify()#

      + +

      Iterates through the list of functions passed to +tracker.calls() and will throw an error for functions that +have not been called the expected number of times.

      +
      const assert = require('assert');
      +
      +// Creates call tracker.
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +// Returns a function that wraps func() that must be called exact times
      +// before tracker.verify().
      +const callsfunc = tracker.calls(func, 2);
      +
      +callsfunc();
      +
      +// Will throw an error since callsfunc() was only called once.
      +tracker.verify();
      +

      assert(value[, message])#

      + + +

      An alias of assert.ok().

      +

      assert.deepEqual(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.deepStrictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.deepStrictEqual() instead.

      +

      Tests for deep equality between the actual and expected parameters. Consider +using assert.deepStrictEqual() instead. assert.deepEqual() can have +surprising results.

      +

      Deep equality means that the enumerable "own" properties of child objects +are also recursively evaluated by the following rules.

      +

      Comparison details#

      +
        +
      • Primitive values are compared with the Abstract Equality Comparison +( == ).
      • +
      • Type tags of objects should be the same.
      • +
      • Only enumerable "own" properties are considered.
      • +
      • Error names and messages are always compared, even if these are not +enumerable properties.
      • +
      • Object wrappers are compared both as objects and unwrapped values.
      • +
      • Object properties are compared unordered.
      • +
      • Map keys and Set items are compared unordered.
      • +
      • Recursion stops when both sides differ or both sides encounter a circular +reference.
      • +
      • Implementation does not test the [[Prototype]] of +objects.
      • +
      • Symbol properties are not compared.
      • +
      • WeakMap and WeakSet comparison does not rely on their values.
      • +
      +

      The following example does not throw an AssertionError because the +primitives are considered equal by the Abstract Equality Comparison +( == ).

      +
      // WARNING: This does not throw an AssertionError!
      +assert.deepEqual('+00000000', false);
      +

      "Deep" equality means that the enumerable "own" properties of child objects +are evaluated also:

      +
      const assert = require('assert');
      +
      +const obj1 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj2 = {
      +  a: {
      +    b: 2
      +  }
      +};
      +const obj3 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj4 = Object.create(obj1);
      +
      +assert.deepEqual(obj1, obj1);
      +// OK
      +
      +// Values of b are different:
      +assert.deepEqual(obj1, obj2);
      +// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
      +
      +assert.deepEqual(obj1, obj3);
      +// OK
      +
      +// Prototypes are ignored:
      +assert.deepEqual(obj1, obj4);
      +// AssertionError: { a: { b: 1 } } deepEqual {}
      +

      If the values are not equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.deepStrictEqual(actual, expected[, message])#

      + + +

      Tests for deep equality between the actual and expected parameters. +"Deep" equality means that the enumerable "own" properties of child objects +are recursively evaluated also by the following rules.

      +

      Comparison details#

      + +
      const assert = require('assert').strict;
      +
      +// This fails because 1 !== '1'.
      +assert.deepStrictEqual({ a: 1 }, { a: '1' });
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +//   {
      +// +   a: 1
      +// -   a: '1'
      +//   }
      +
      +// The following objects don't have own properties
      +const date = new Date();
      +const object = {};
      +const fakeDate = {};
      +Object.setPrototypeOf(fakeDate, Date.prototype);
      +
      +// Different [[Prototype]]:
      +assert.deepStrictEqual(object, fakeDate);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + {}
      +// - Date {}
      +
      +// Different type tags:
      +assert.deepStrictEqual(date, fakeDate);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + 2018-04-26T00:49:08.604Z
      +// - Date {}
      +
      +assert.deepStrictEqual(NaN, NaN);
      +// OK, because of the SameValue comparison
      +
      +// Different unwrapped numbers:
      +assert.deepStrictEqual(new Number(1), new Number(2));
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + [Number: 1]
      +// - [Number: 2]
      +
      +assert.deepStrictEqual(new String('foo'), Object('foo'));
      +// OK because the object and the string are identical when unwrapped.
      +
      +assert.deepStrictEqual(-0, -0);
      +// OK
      +
      +// Different zeros using the SameValue Comparison:
      +assert.deepStrictEqual(0, -0);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + 0
      +// - -0
      +
      +const symbol1 = Symbol();
      +const symbol2 = Symbol();
      +assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
      +// OK, because it is the same symbol on both objects.
      +
      +assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
      +// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
      +//
      +// {
      +//   [Symbol()]: 1
      +// }
      +
      +const weakMap1 = new WeakMap();
      +const weakMap2 = new WeakMap([[{}, {}]]);
      +const weakMap3 = new WeakMap();
      +weakMap3.unequal = true;
      +
      +assert.deepStrictEqual(weakMap1, weakMap2);
      +// OK, because it is impossible to compare the entries
      +
      +// Fails because weakMap3 has a property that weakMap1 does not contain:
      +assert.deepStrictEqual(weakMap1, weakMap3);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +//   WeakMap {
      +// +   [items unknown]
      +// -   [items unknown],
      +// -   unequal: true
      +//   }
      +

      If the values are not equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.doesNotMatch(string, regexp[, message])#

      + + +

      Stability: 1 - Experimental

      +

      Expects the string input not to match the regular expression.

      +

      This feature is currently experimental and the name might change or it might be +completely removed again.

      +
      const assert = require('assert').strict;
      +
      +assert.doesNotMatch('I will fail', /fail/);
      +// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
      +
      +assert.doesNotMatch(123, /pass/);
      +// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
      +
      +assert.doesNotMatch('I will pass', /different/);
      +// OK
      +

      If the values do match, or if the string argument is of another type than +string, an AssertionError is thrown with a message property set equal +to the value of the message parameter. If the message parameter is +undefined, a default error message is assigned. If the message parameter is an +instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.doesNotReject(asyncFn[, error][, message])#

      + + +

      Awaits the asyncFn promise or, if asyncFn is a function, immediately +calls the function and awaits the returned promise to complete. It will then +check that the promise is not rejected.

      +

      If asyncFn is a function and it throws an error synchronously, +assert.doesNotReject() will return a rejected Promise with that error. If +the function does not return a promise, assert.doesNotReject() will return a +rejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases +the error handler is skipped.

      +

      Using assert.doesNotReject() is actually not useful because there is little +benefit in catching a rejection and then rejecting it again. Instead, consider +adding a comment next to the specific code path that should not reject and keep +error messages as expressive as possible.

      +

      If specified, error can be a Class, RegExp or a validation +function. See assert.throws() for more details.

      +

      Besides the async nature to await the completion behaves identically to +assert.doesNotThrow().

      + +
      (async () => {
      +  await assert.doesNotReject(
      +    async () => {
      +      throw new TypeError('Wrong value');
      +    },
      +    SyntaxError
      +  );
      +})();
      + +
      assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
      +  .then(() => {
      +    // ...
      +  });
      +

      assert.doesNotThrow(fn[, error][, message])#

      + + +

      Asserts that the function fn does not throw an error.

      +

      Using assert.doesNotThrow() is actually not useful because there +is no benefit in catching an error and then rethrowing it. Instead, consider +adding a comment next to the specific code path that should not throw and keep +error messages as expressive as possible.

      +

      When assert.doesNotThrow() is called, it will immediately call the fn +function.

      +

      If an error is thrown and it is the same type as that specified by the error +parameter, then an AssertionError is thrown. If the error is of a +different type, or if the error parameter is undefined, the error is +propagated back to the caller.

      +

      If specified, error can be a Class, RegExp or a validation +function. See assert.throws() for more details.

      +

      The following, for instance, will throw the TypeError because there is no +matching error type in the assertion:

      + +
      assert.doesNotThrow(
      +  () => {
      +    throw new TypeError('Wrong value');
      +  },
      +  SyntaxError
      +);
      +

      However, the following will result in an AssertionError with the message +'Got unwanted exception...':

      + +
      assert.doesNotThrow(
      +  () => {
      +    throw new TypeError('Wrong value');
      +  },
      +  TypeError
      +);
      +

      If an AssertionError is thrown and a value is provided for the message +parameter, the value of message will be appended to the AssertionError +message:

      + +
      assert.doesNotThrow(
      +  () => {
      +    throw new TypeError('Wrong value');
      +  },
      +  /Wrong value/,
      +  'Whoops'
      +);
      +// Throws: AssertionError: Got unwanted exception: Whoops
      +

      assert.equal(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.strictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.strictEqual() instead.

      +

      Tests shallow, coercive equality between the actual and expected parameters +using the Abstract Equality Comparison ( == ).

      +
      const assert = require('assert');
      +
      +assert.equal(1, 1);
      +// OK, 1 == 1
      +assert.equal(1, '1');
      +// OK, 1 == '1'
      +
      +assert.equal(1, 2);
      +// AssertionError: 1 == 2
      +assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
      +// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
      +

      If the values are not equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.fail([message])#

      + + +

      Throws an AssertionError with the provided error message or a default +error message. If the message parameter is an instance of an Error then +it will be thrown instead of the AssertionError.

      +
      const assert = require('assert').strict;
      +
      +assert.fail();
      +// AssertionError [ERR_ASSERTION]: Failed
      +
      +assert.fail('boom');
      +// AssertionError [ERR_ASSERTION]: boom
      +
      +assert.fail(new TypeError('need array'));
      +// TypeError: need array
      +

      Using assert.fail() with more than two arguments is possible but deprecated. +See below for further details.

      +

      assert.fail(actual, expected[, message[, operator[, stackStartFn]]])#

      + +

      Stability: 0 - Deprecated: Use assert.fail([message]) or other assert +functions instead.

      + +

      If message is falsy, the error message is set as the values of actual and +expected separated by the provided operator. If just the two actual and +expected arguments are provided, operator will default to '!='. If +message is provided as third argument it will be used as the error message and +the other arguments will be stored as properties on the thrown object. If +stackStartFn is provided, all stack frames above that function will be +removed from stacktrace (see Error.captureStackTrace). If no arguments are +given, the default message Failed will be used.

      +
      const assert = require('assert').strict;
      +
      +assert.fail('a', 'b');
      +// AssertionError [ERR_ASSERTION]: 'a' != 'b'
      +
      +assert.fail(1, 2, undefined, '>');
      +// AssertionError [ERR_ASSERTION]: 1 > 2
      +
      +assert.fail(1, 2, 'fail');
      +// AssertionError [ERR_ASSERTION]: fail
      +
      +assert.fail(1, 2, 'whoops', '>');
      +// AssertionError [ERR_ASSERTION]: whoops
      +
      +assert.fail(1, 2, new TypeError('need array'));
      +// TypeError: need array
      +

      In the last three cases actual, expected, and operator have no +influence on the error message.

      +

      Example use of stackStartFn for truncating the exception's stacktrace:

      +
      function suppressFrame() {
      +  assert.fail('a', 'b', undefined, '!==', suppressFrame);
      +}
      +suppressFrame();
      +// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
      +//     at repl:1:1
      +//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
      +//     ...
      +

      assert.ifError(value)#

      + + +

      Throws value if value is not undefined or null. This is useful when +testing the error argument in callbacks. The stack trace contains all frames +from the error passed to ifError() including the potential new frames for +ifError() itself.

      +
      const assert = require('assert').strict;
      +
      +assert.ifError(null);
      +// OK
      +assert.ifError(0);
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
      +assert.ifError('error');
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
      +assert.ifError(new Error());
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
      +
      +// Create some random error frames.
      +let err;
      +(function errorFrame() {
      +  err = new Error('test error');
      +})();
      +
      +(function ifErrorFrame() {
      +  assert.ifError(err);
      +})();
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
      +//     at ifErrorFrame
      +//     at errorFrame
      +

      assert.match(string, regexp[, message])#

      + + +

      Stability: 1 - Experimental

      +

      Expects the string input to match the regular expression.

      +

      This feature is currently experimental and the name might change or it might be +completely removed again.

      +
      const assert = require('assert').strict;
      +
      +assert.match('I will fail', /pass/);
      +// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
      +
      +assert.match(123, /pass/);
      +// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
      +
      +assert.match('I will pass', /pass/);
      +// OK
      +

      If the values do not match, or if the string argument is of another type than +string, an AssertionError is thrown with a message property set equal +to the value of the message parameter. If the message parameter is +undefined, a default error message is assigned. If the message parameter is an +instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.notDeepEqual(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.notDeepStrictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.notDeepStrictEqual() instead.

      +

      Tests for any deep inequality. Opposite of assert.deepEqual().

      +
      const assert = require('assert');
      +
      +const obj1 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj2 = {
      +  a: {
      +    b: 2
      +  }
      +};
      +const obj3 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj4 = Object.create(obj1);
      +
      +assert.notDeepEqual(obj1, obj1);
      +// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
      +
      +assert.notDeepEqual(obj1, obj2);
      +// OK
      +
      +assert.notDeepEqual(obj1, obj3);
      +// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
      +
      +assert.notDeepEqual(obj1, obj4);
      +// OK
      +

      If the values are deeply equal, an AssertionError is thrown with a +message property set equal to the value of the message parameter. If the +message parameter is undefined, a default error message is assigned. If the +message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.notDeepStrictEqual(actual, expected[, message])#

      + + +

      Tests for deep strict inequality. Opposite of assert.deepStrictEqual().

      +
      const assert = require('assert').strict;
      +
      +assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
      +// OK
      +

      If the values are deeply and strictly equal, an AssertionError is thrown +with a message property set equal to the value of the message parameter. If +the message parameter is undefined, a default error message is assigned. If +the message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.notEqual(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.notStrictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.notStrictEqual() instead.

      +

      Tests shallow, coercive inequality with the Abstract Equality Comparison +( != ).

      +
      const assert = require('assert');
      +
      +assert.notEqual(1, 2);
      +// OK
      +
      +assert.notEqual(1, 1);
      +// AssertionError: 1 != 1
      +
      +assert.notEqual(1, '1');
      +// AssertionError: 1 != '1'
      +

      If the values are equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.notStrictEqual(actual, expected[, message])#

      + + +

      Tests strict inequality between the actual and expected parameters as +determined by the SameValue Comparison.

      +
      const assert = require('assert').strict;
      +
      +assert.notStrictEqual(1, 2);
      +// OK
      +
      +assert.notStrictEqual(1, 1);
      +// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
      +//
      +// 1
      +
      +assert.notStrictEqual(1, '1');
      +// OK
      +

      If the values are strictly equal, an AssertionError is thrown with a +message property set equal to the value of the message parameter. If the +message parameter is undefined, a default error message is assigned. If the +message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.ok(value[, message])#

      + + +

      Tests if value is truthy. It is equivalent to +assert.equal(!!value, true, message).

      +

      If value is not truthy, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError. +If no arguments are passed in at all message will be set to the string: +'No value argument passed to `assert.ok()`'.

      +

      Be aware that in the repl the error message will be different to the one +thrown in a file! See below for further details.

      +
      const assert = require('assert').strict;
      +
      +assert.ok(true);
      +// OK
      +assert.ok(1);
      +// OK
      +
      +assert.ok();
      +// AssertionError: No value argument passed to `assert.ok()`
      +
      +assert.ok(false, 'it\'s false');
      +// AssertionError: it's false
      +
      +// In the repl:
      +assert.ok(typeof 123 === 'string');
      +// AssertionError: false == true
      +
      +// In a file (e.g. test.js):
      +assert.ok(typeof 123 === 'string');
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert.ok(typeof 123 === 'string')
      +
      +assert.ok(false);
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert.ok(false)
      +
      +assert.ok(0);
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert.ok(0)
      +
      +// Using `assert()` works the same:
      +assert(0);
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert(0)
      +

      assert.rejects(asyncFn[, error][, message])#

      + + +

      Awaits the asyncFn promise or, if asyncFn is a function, immediately +calls the function and awaits the returned promise to complete. It will then +check that the promise is rejected.

      +

      If asyncFn is a function and it throws an error synchronously, +assert.rejects() will return a rejected Promise with that error. If the +function does not return a promise, assert.rejects() will return a rejected +Promise with an ERR_INVALID_RETURN_VALUE error. In both cases the error +handler is skipped.

      +

      Besides the async nature to await the completion behaves identically to +assert.throws().

      +

      If specified, error can be a Class, RegExp, a validation function, +an object where each property will be tested for, or an instance of error where +each property will be tested for including the non-enumerable message and +name properties.

      +

      If specified, message will be the message provided by the AssertionError +if the asyncFn fails to reject.

      +
      (async () => {
      +  await assert.rejects(
      +    async () => {
      +      throw new TypeError('Wrong value');
      +    },
      +    {
      +      name: 'TypeError',
      +      message: 'Wrong value'
      +    }
      +  );
      +})();
      +
      (async () => {
      +  await assert.rejects(
      +    async () => {
      +      throw new TypeError('Wrong value');
      +    },
      +    (err) => {
      +      assert.strictEqual(err.name, 'TypeError');
      +      assert.strictEqual(err.message, 'Wrong value');
      +      return true;
      +    }
      +  );
      +})();
      +
      assert.rejects(
      +  Promise.reject(new Error('Wrong value')),
      +  Error
      +).then(() => {
      +  // ...
      +});
      +

      error cannot be a string. If a string is provided as the second +argument, then error is assumed to be omitted and the string will be used for +message instead. This can lead to easy-to-miss mistakes. Please read the +example in assert.throws() carefully if using a string as the second +argument gets considered.

      +

      assert.strictEqual(actual, expected[, message])#

      + + +

      Tests strict equality between the actual and expected parameters as +determined by the SameValue Comparison.

      +
      const assert = require('assert').strict;
      +
      +assert.strictEqual(1, 2);
      +// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
      +//
      +// 1 !== 2
      +
      +assert.strictEqual(1, 1);
      +// OK
      +
      +assert.strictEqual('Hello foobar', 'Hello World!');
      +// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
      +// + actual - expected
      +//
      +// + 'Hello foobar'
      +// - 'Hello World!'
      +//          ^
      +
      +const apples = 1;
      +const oranges = 2;
      +assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
      +// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
      +
      +assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
      +// TypeError: Inputs are not identical
      +

      If the values are not strictly equal, an AssertionError is thrown with a +message property set equal to the value of the message parameter. If the +message parameter is undefined, a default error message is assigned. If the +message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.throws(fn[, error][, message])#

      + + +

      Expects the function fn to throw an error.

      +

      If specified, error can be a Class, RegExp, a validation function, +a validation object where each property will be tested for strict deep equality, +or an instance of error where each property will be tested for strict deep +equality including the non-enumerable message and name properties. When +using an object, it is also possible to use a regular expression, when +validating against a string property. See below for examples.

      +

      If specified, message will be appended to the message provided by the +AssertionError if the fn call fails to throw or in case the error validation +fails.

      +

      Custom validation object/error instance:

      +
      const err = new TypeError('Wrong value');
      +err.code = 404;
      +err.foo = 'bar';
      +err.info = {
      +  nested: true,
      +  baz: 'text'
      +};
      +err.reg = /abc/i;
      +
      +assert.throws(
      +  () => {
      +    throw err;
      +  },
      +  {
      +    name: 'TypeError',
      +    message: 'Wrong value',
      +    info: {
      +      nested: true,
      +      baz: 'text'
      +    }
      +    // Only properties on the validation object will be tested for.
      +    // Using nested objects requires all properties to be present. Otherwise
      +    // the validation is going to fail.
      +  }
      +);
      +
      +// Using regular expressions to validate error properties:
      +assert.throws(
      +  () => {
      +    throw err;
      +  },
      +  {
      +    // The `name` and `message` properties are strings and using regular
      +    // expressions on those will match against the string. If they fail, an
      +    // error is thrown.
      +    name: /^TypeError$/,
      +    message: /Wrong/,
      +    foo: 'bar',
      +    info: {
      +      nested: true,
      +      // It is not possible to use regular expressions for nested properties!
      +      baz: 'text'
      +    },
      +    // The `reg` property contains a regular expression and only if the
      +    // validation object contains an identical regular expression, it is going
      +    // to pass.
      +    reg: /abc/i
      +  }
      +);
      +
      +// Fails due to the different `message` and `name` properties:
      +assert.throws(
      +  () => {
      +    const otherErr = new Error('Not found');
      +    // Copy all enumerable properties from `err` to `otherErr`.
      +    for (const [key, value] of Object.entries(err)) {
      +      otherErr[key] = value;
      +    }
      +    throw otherErr;
      +  },
      +  // The error's `message` and `name` properties will also be checked when using
      +  // an error as validation object.
      +  err
      +);
      +

      Validate instanceof using constructor:

      +
      assert.throws(
      +  () => {
      +    throw new Error('Wrong value');
      +  },
      +  Error
      +);
      +

      Validate error message using RegExp:

      +

      Using a regular expression runs .toString on the error object, and will +therefore also include the error name.

      +
      assert.throws(
      +  () => {
      +    throw new Error('Wrong value');
      +  },
      +  /^Error: Wrong value$/
      +);
      +

      Custom error validation:

      +

      The function must return true to indicate all internal validations passed. +It will otherwise fail with an AssertionError.

      +
      assert.throws(
      +  () => {
      +    throw new Error('Wrong value');
      +  },
      +  (err) => {
      +    assert(err instanceof Error);
      +    assert(/value/.test(err));
      +    // Avoid returning anything from validation functions besides `true`.
      +    // Otherwise, it's not clear what part of the validation failed. Instead,
      +    // throw an error about the specific validation that failed (as done in this
      +    // example) and add as much helpful debugging information to that error as
      +    // possible.
      +    return true;
      +  },
      +  'unexpected error'
      +);
      +

      error cannot be a string. If a string is provided as the second +argument, then error is assumed to be omitted and the string will be used for +message instead. This can lead to easy-to-miss mistakes. Using the same +message as the thrown error message is going to result in an +ERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using +a string as the second argument gets considered:

      + +
      function throwingFirst() {
      +  throw new Error('First');
      +}
      +
      +function throwingSecond() {
      +  throw new Error('Second');
      +}
      +
      +function notThrowing() {}
      +
      +// The second argument is a string and the input function threw an Error.
      +// The first case will not throw as it does not match for the error message
      +// thrown by the input function!
      +assert.throws(throwingFirst, 'Second');
      +// In the next example the message has no benefit over the message from the
      +// error and since it is not clear if the user intended to actually match
      +// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
      +assert.throws(throwingSecond, 'Second');
      +// TypeError [ERR_AMBIGUOUS_ARGUMENT]
      +
      +// The string is only used (as message) in case the function does not throw:
      +assert.throws(notThrowing, 'Second');
      +// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
      +
      +// If it was intended to match for the error message do this instead:
      +// It does not throw because the error messages match.
      +assert.throws(throwingSecond, /Second$/);
      +
      +// If the error message does not match, an AssertionError is thrown.
      +assert.throws(throwingFirst, /Second$/);
      +// AssertionError [ERR_ASSERTION]
      +

      Due to the confusing error-prone notation, avoid a string as the second +argument.

      +

      Async hooks#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/async_hooks.js

      +

      The async_hooks module provides an API to track asynchronous resources. It +can be accessed using:

      +
      const async_hooks = require('async_hooks');
      +

      Terminology#

      +

      An asynchronous resource represents an object with an associated callback. +This callback may be called multiple times, for example, the 'connection' +event in net.createServer(), or just a single time like in fs.open(). +A resource can also be closed before the callback is called. AsyncHook does +not explicitly distinguish between these different cases but will represent them +as the abstract concept that is a resource.

      +

      If Workers are used, each thread has an independent async_hooks +interface, and each thread will use a new set of async IDs.

      +

      Public API#

      +

      Overview#

      +

      Following is a simple overview of the public API.

      +
      const async_hooks = require('async_hooks');
      +
      +// Return the ID of the current execution context.
      +const eid = async_hooks.executionAsyncId();
      +
      +// Return the ID of the handle responsible for triggering the callback of the
      +// current execution scope to call.
      +const tid = async_hooks.triggerAsyncId();
      +
      +// Create a new AsyncHook instance. All of these callbacks are optional.
      +const asyncHook =
      +    async_hooks.createHook({ init, before, after, destroy, promiseResolve });
      +
      +// Allow callbacks of this AsyncHook instance to call. This is not an implicit
      +// action after running the constructor, and must be explicitly run to begin
      +// executing callbacks.
      +asyncHook.enable();
      +
      +// Disable listening for new asynchronous events.
      +asyncHook.disable();
      +
      +//
      +// The following are the callbacks that can be passed to createHook().
      +//
      +
      +// init is called during object construction. The resource may not have
      +// completed construction when this callback runs, therefore all fields of the
      +// resource referenced by "asyncId" may not have been populated.
      +function init(asyncId, type, triggerAsyncId, resource) { }
      +
      +// Before is called just before the resource's callback is called. It can be
      +// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
      +// time for requests (e.g. FSReqCallback).
      +function before(asyncId) { }
      +
      +// After is called just after the resource's callback has finished.
      +function after(asyncId) { }
      +
      +// Destroy is called when the resource is destroyed.
      +function destroy(asyncId) { }
      +
      +// promiseResolve is called only for promise resources, when the
      +// `resolve` function passed to the `Promise` constructor is invoked
      +// (either directly or through other means of resolving a promise).
      +function promiseResolve(asyncId) { }
      +

      async_hooks.createHook(callbacks)#

      + + +

      Registers functions to be called for different lifetime events of each async +operation.

      +

      The callbacks init()/before()/after()/destroy() are called for the +respective asynchronous event during a resource's lifetime.

      +

      All callbacks are optional. For example, if only resource cleanup needs to +be tracked, then only the destroy callback needs to be passed. The +specifics of all functions that can be passed to callbacks is in the +Hook Callbacks section.

      +
      const async_hooks = require('async_hooks');
      +
      +const asyncHook = async_hooks.createHook({
      +  init(asyncId, type, triggerAsyncId, resource) { },
      +  destroy(asyncId) { }
      +});
      +

      The callbacks will be inherited via the prototype chain:

      +
      class MyAsyncCallbacks {
      +  init(asyncId, type, triggerAsyncId, resource) { }
      +  destroy(asyncId) {}
      +}
      +
      +class MyAddedCallbacks extends MyAsyncCallbacks {
      +  before(asyncId) { }
      +  after(asyncId) { }
      +}
      +
      +const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
      +
      Error handling#
      +

      If any AsyncHook callbacks throw, the application will print the stack trace +and exit. The exit path does follow that of an uncaught exception, but +all 'uncaughtException' listeners are removed, thus forcing the process to +exit. The 'exit' callbacks will still be called unless the application is run +with --abort-on-uncaught-exception, in which case a stack trace will be +printed and the application exits, leaving a core file.

      +

      The reason for this error handling behavior is that these callbacks are running +at potentially volatile points in an object's lifetime, for example during +class construction and destruction. Because of this, it is deemed necessary to +bring down the process quickly in order to prevent an unintentional abort in the +future. This is subject to change in the future if a comprehensive analysis is +performed to ensure an exception can follow the normal control flow without +unintentional side effects.

      +
      Printing in AsyncHooks callbacks#
      +

      Because printing to the console is an asynchronous operation, console.log() +will cause the AsyncHooks callbacks to be called. Using console.log() or +similar asynchronous operations inside an AsyncHooks callback function will thus +cause an infinite recursion. An easy solution to this when debugging is to use a +synchronous logging operation such as fs.writeFileSync(file, msg, flag). +This will print to the file and will not invoke AsyncHooks recursively because +it is synchronous.

      +
      const fs = require('fs');
      +const util = require('util');
      +
      +function debug(...args) {
      +  // Use a function like this one when debugging inside an AsyncHooks callback
      +  fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
      +}
      +

      If an asynchronous operation is needed for logging, it is possible to keep +track of what caused the asynchronous operation using the information +provided by AsyncHooks itself. The logging should then be skipped when +it was the logging itself that caused AsyncHooks callback to call. By +doing this the otherwise infinite recursion is broken.

      +

      Class: AsyncHook#

      +

      The class AsyncHook exposes an interface for tracking lifetime events +of asynchronous operations.

      +

      asyncHook.enable()#

      + +

      Enable the callbacks for a given AsyncHook instance. If no callbacks are +provided enabling is a noop.

      +

      The AsyncHook instance is disabled by default. If the AsyncHook instance +should be enabled immediately after creation, the following pattern can be used.

      +
      const async_hooks = require('async_hooks');
      +
      +const hook = async_hooks.createHook(callbacks).enable();
      +

      asyncHook.disable()#

      + +

      Disable the callbacks for a given AsyncHook instance from the global pool of +AsyncHook callbacks to be executed. Once a hook has been disabled it will not +be called again until enabled.

      +

      For API consistency disable() also returns the AsyncHook instance.

      +

      Hook callbacks#

      +

      Key events in the lifetime of asynchronous events have been categorized into +four areas: instantiation, before/after the callback is called, and when the +instance is destroyed.

      +
      init(asyncId, type, triggerAsyncId, resource)#
      +
        +
      • asyncId <number> A unique ID for the async resource.
      • +
      • type <string> The type of the async resource.
      • +
      • triggerAsyncId <number> The unique ID of the async resource in whose +execution context this async resource was created.
      • +
      • resource <Object> Reference to the resource representing the async +operation, needs to be released during destroy.
      • +
      +

      Called when a class is constructed that has the possibility to emit an +asynchronous event. This does not mean the instance must call +before/after before destroy is called, only that the possibility +exists.

      +

      This behavior can be observed by doing something like opening a resource then +closing it before the resource can be used. The following snippet demonstrates +this.

      +
      require('net').createServer().listen(function() { this.close(); });
      +// OR
      +clearTimeout(setTimeout(() => {}, 10));
      +

      Every new resource is assigned an ID that is unique within the scope of the +current Node.js instance.

      +
      type#
      +

      The type is a string identifying the type of resource that caused +init to be called. Generally, it will correspond to the name of the +resource's constructor.

      +
      FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
      +HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
      +SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
      +TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
      +RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
      +

      There is also the PROMISE resource type, which is used to track Promise +instances and asynchronous work scheduled by them.

      +

      Users are able to define their own type when using the public embedder API.

      +

      It is possible to have type name collisions. Embedders are encouraged to use +unique prefixes, such as the npm package name, to prevent collisions when +listening to the hooks.

      +
      triggerAsyncId#
      +

      triggerAsyncId is the asyncId of the resource that caused (or "triggered") +the new resource to initialize and that caused init to call. This is different +from async_hooks.executionAsyncId() that only shows when a resource was +created, while triggerAsyncId shows why a resource was created.

      +

      The following is a simple demonstration of triggerAsyncId:

      +
      async_hooks.createHook({
      +  init(asyncId, type, triggerAsyncId) {
      +    const eid = async_hooks.executionAsyncId();
      +    fs.writeSync(
      +      process.stdout.fd,
      +      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
      +  }
      +}).enable();
      +
      +require('net').createServer((conn) => {}).listen(8080);
      +

      Output when hitting the server with nc localhost 8080:

      +
      TCPSERVERWRAP(5): trigger: 1 execution: 1
      +TCPWRAP(7): trigger: 5 execution: 0
      +

      The TCPSERVERWRAP is the server which receives the connections.

      +

      The TCPWRAP is the new connection from the client. When a new +connection is made, the TCPWrap instance is immediately constructed. This +happens outside of any JavaScript stack. (An executionAsyncId() of 0 means +that it is being executed from C++ with no JavaScript stack above it.) With only +that information, it would be impossible to link resources together in +terms of what caused them to be created, so triggerAsyncId is given the task +of propagating what resource is responsible for the new resource's existence.

      +
      resource#
      +

      resource is an object that represents the actual async resource that has +been initialized. This can contain useful information that can vary based on +the value of type. For instance, for the GETADDRINFOREQWRAP resource type, +resource provides the host name used when looking up the IP address for the +host in net.Server.listen(). The API for accessing this information is +not supported, but using the Embedder API, users can provide +and document their own resource objects. For example, such a resource object +could contain the SQL query being executed.

      +

      In the case of Promises, the resource object will have an +isChainedPromise property, set to true if the promise has a parent promise, +and false otherwise. For example, in the case of b = a.then(handler), a is +considered a parent Promise of b. Here, b is considered a chained promise.

      +

      In some cases the resource object is reused for performance reasons, it is +thus not safe to use it as a key in a WeakMap or add properties to it.

      +
      Asynchronous context example#
      +

      The following is an example with additional information about the calls to +init between the before and after calls, specifically what the +callback to listen() will look like. The output formatting is slightly more +elaborate to make calling context easier to see.

      +
      let indent = 0;
      +async_hooks.createHook({
      +  init(asyncId, type, triggerAsyncId) {
      +    const eid = async_hooks.executionAsyncId();
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(
      +      process.stdout.fd,
      +      `${indentStr}${type}(${asyncId}):` +
      +      ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
      +  },
      +  before(asyncId) {
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(process.stdout.fd, `${indentStr}before:  ${asyncId}\n`);
      +    indent += 2;
      +  },
      +  after(asyncId) {
      +    indent -= 2;
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(process.stdout.fd, `${indentStr}after:  ${asyncId}\n`);
      +  },
      +  destroy(asyncId) {
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(process.stdout.fd, `${indentStr}destroy:  ${asyncId}\n`);
      +  },
      +}).enable();
      +
      +require('net').createServer(() => {}).listen(8080, () => {
      +  // Let's wait 10ms before logging the server started.
      +  setTimeout(() => {
      +    console.log('>>>', async_hooks.executionAsyncId());
      +  }, 10);
      +});
      +

      Output from only starting the server:

      +
      TCPSERVERWRAP(5): trigger: 1 execution: 1
      +TickObject(6): trigger: 5 execution: 1
      +before:  6
      +  Timeout(7): trigger: 6 execution: 6
      +after:   6
      +destroy: 6
      +before:  7
      +>>> 7
      +  TickObject(8): trigger: 7 execution: 7
      +after:   7
      +before:  8
      +after:   8
      +

      As illustrated in the example, executionAsyncId() and execution each specify +the value of the current execution context; which is delineated by calls to +before and after.

      +

      Only using execution to graph resource allocation results in the following:

      +
        root(1)
      +     ^
      +     |
      +TickObject(6)
      +     ^
      +     |
      + Timeout(7)
      +

      The TCPSERVERWRAP is not part of this graph, even though it was the reason for +console.log() being called. This is because binding to a port without a host +name is a synchronous operation, but to maintain a completely asynchronous +API the user's callback is placed in a process.nextTick(). Which is why +TickObject is present in the output and is a 'parent' for .listen() +callback.

      +

      The graph only shows when a resource was created, not why, so to track +the why use triggerAsyncId. Which can be represented with the following +graph:

      +
       bootstrap(1)
      +     |
      +     Ë…
      +TCPSERVERWRAP(5)
      +     |
      +     Ë…
      + TickObject(6)
      +     |
      +     Ë…
      +  Timeout(7)
      +
      before(asyncId)#
      + +

      When an asynchronous operation is initiated (such as a TCP server receiving a +new connection) or completes (such as writing data to disk) a callback is +called to notify the user. The before callback is called just before said +callback is executed. asyncId is the unique identifier assigned to the +resource about to execute the callback.

      +

      The before callback will be called 0 to N times. The before callback +will typically be called 0 times if the asynchronous operation was cancelled +or, for example, if no connections are received by a TCP server. Persistent +asynchronous resources like a TCP server will typically call the before +callback multiple times, while other operations like fs.open() will call +it only once.

      +
      after(asyncId)#
      + +

      Called immediately after the callback specified in before is completed.

      +

      If an uncaught exception occurs during execution of the callback, then after +will run after the 'uncaughtException' event is emitted or a domain's +handler runs.

      +
      destroy(asyncId)#
      + +

      Called after the resource corresponding to asyncId is destroyed. It is also +called asynchronously from the embedder API emitDestroy().

      +

      Some resources depend on garbage collection for cleanup, so if a reference is +made to the resource object passed to init it is possible that destroy +will never be called, causing a memory leak in the application. If the resource +does not depend on garbage collection, then this will not be an issue.

      +
      promiseResolve(asyncId)#
      + + +

      Called when the resolve function passed to the Promise constructor is +invoked (either directly or through other means of resolving a promise).

      +

      resolve() does not do any observable synchronous work.

      +

      The Promise is not necessarily fulfilled or rejected at this point if the +Promise was resolved by assuming the state of another Promise.

      +
      new Promise((resolve) => resolve(true)).then((a) => {});
      +

      calls the following callbacks:

      +
      init for PROMISE with id 5, trigger id: 1
      +  promise resolve 5      # corresponds to resolve(true)
      +init for PROMISE with id 6, trigger id: 5  # the Promise returned by then()
      +  before 6               # the then() callback is entered
      +  promise resolve 6      # the then() callback resolves the promise by returning
      +  after 6
      +

      async_hooks.executionAsyncResource()#

      + +
        +
      • Returns: <Object> The resource representing the current execution. +Useful to store data within the resource.
      • +
      +

      Resource objects returned by executionAsyncResource() are most often internal +Node.js handle objects with undocumented APIs. Using any functions or properties +on the object is likely to crash your application and should be avoided.

      +

      Using executionAsyncResource() in the top-level execution context will +return an empty object as there is no handle or request object to use, +but having an object representing the top-level can be helpful.

      +
      const { open } = require('fs');
      +const { executionAsyncId, executionAsyncResource } = require('async_hooks');
      +
      +console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
      +open(__filename, 'r', (err, fd) => {
      +  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
      +});
      +

      This can be used to implement continuation local storage without the +use of a tracking Map to store the metadata:

      +
      const { createServer } = require('http');
      +const {
      +  executionAsyncId,
      +  executionAsyncResource,
      +  createHook
      +} = require('async_hooks');
      +const sym = Symbol('state'); // Private symbol to avoid pollution
      +
      +createHook({
      +  init(asyncId, type, triggerAsyncId, resource) {
      +    const cr = executionAsyncResource();
      +    if (cr) {
      +      resource[sym] = cr[sym];
      +    }
      +  }
      +}).enable();
      +
      +const server = createServer((req, res) => {
      +  executionAsyncResource()[sym] = { state: req.url };
      +  setTimeout(function() {
      +    res.end(JSON.stringify(executionAsyncResource()[sym]));
      +  }, 100);
      +}).listen(3000);
      +

      async_hooks.executionAsyncId()#

      + +
        +
      • Returns: <number> The asyncId of the current execution context. Useful to +track when something calls.
      • +
      +
      const async_hooks = require('async_hooks');
      +
      +console.log(async_hooks.executionAsyncId());  // 1 - bootstrap
      +fs.open(path, 'r', (err, fd) => {
      +  console.log(async_hooks.executionAsyncId());  // 6 - open()
      +});
      +

      The ID returned from executionAsyncId() is related to execution timing, not +causality (which is covered by triggerAsyncId()):

      +
      const server = net.createServer((conn) => {
      +  // Returns the ID of the server, not of the new connection, because the
      +  // callback runs in the execution scope of the server's MakeCallback().
      +  async_hooks.executionAsyncId();
      +
      +}).listen(port, () => {
      +  // Returns the ID of a TickObject (i.e. process.nextTick()) because all
      +  // callbacks passed to .listen() are wrapped in a nextTick().
      +  async_hooks.executionAsyncId();
      +});
      +

      Promise contexts may not get precise executionAsyncIds by default. +See the section on promise execution tracking.

      +

      async_hooks.triggerAsyncId()#

      +
        +
      • Returns: <number> The ID of the resource responsible for calling the callback +that is currently being executed.
      • +
      +
      const server = net.createServer((conn) => {
      +  // The resource that caused (or triggered) this callback to be called
      +  // was that of the new connection. Thus the return value of triggerAsyncId()
      +  // is the asyncId of "conn".
      +  async_hooks.triggerAsyncId();
      +
      +}).listen(port, () => {
      +  // Even though all callbacks passed to .listen() are wrapped in a nextTick()
      +  // the callback itself exists because the call to the server's .listen()
      +  // was made. So the return value would be the ID of the server.
      +  async_hooks.triggerAsyncId();
      +});
      +

      Promise contexts may not get valid triggerAsyncIds by default. See +the section on promise execution tracking.

      +

      Promise execution tracking#

      +

      By default, promise executions are not assigned asyncIds due to the relatively +expensive nature of the promise introspection API provided by +V8. This means that programs using promises or async/await will not get +correct execution and trigger ids for promise callback contexts by default.

      +
      const ah = require('async_hooks');
      +Promise.resolve(1729).then(() => {
      +  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
      +});
      +// produces:
      +// eid 1 tid 0
      +

      Observe that the then() callback claims to have executed in the context of the +outer scope even though there was an asynchronous hop involved. Also, +the triggerAsyncId value is 0, which means that we are missing context about +the resource that caused (triggered) the then() callback to be executed.

      +

      Installing async hooks via async_hooks.createHook enables promise execution +tracking:

      +
      const ah = require('async_hooks');
      +ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
      +Promise.resolve(1729).then(() => {
      +  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
      +});
      +// produces:
      +// eid 7 tid 6
      +

      In this example, adding any actual hook function enabled the tracking of +promises. There are two promises in the example above; the promise created by +Promise.resolve() and the promise returned by the call to then(). In the +example above, the first promise got the asyncId 6 and the latter got +asyncId 7. During the execution of the then() callback, we are executing +in the context of promise with asyncId 7. This promise was triggered by +async resource 6.

      +

      Another subtlety with promises is that before and after callbacks are run +only on chained promises. That means promises not created by then()/catch() +will not have the before and after callbacks fired on them. For more details +see the details of the V8 PromiseHooks API.

      +

      JavaScript embedder API#

      +

      Library developers that handle their own asynchronous resources performing tasks +like I/O, connection pooling, or managing callback queues may use the +AsyncResource JavaScript API so that all the appropriate callbacks are called.

      +

      Class: AsyncResource#

      +

      The class AsyncResource is designed to be extended by the embedder's async +resources. Using this, users can easily trigger the lifetime events of their +own resources.

      +

      The init hook will trigger when an AsyncResource is instantiated.

      +

      The following is an overview of the AsyncResource API.

      +
      const { AsyncResource, executionAsyncId } = require('async_hooks');
      +
      +// AsyncResource() is meant to be extended. Instantiating a
      +// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
      +// async_hook.executionAsyncId() is used.
      +const asyncResource = new AsyncResource(
      +  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
      +);
      +
      +// Run a function in the execution context of the resource. This will
      +// * establish the context of the resource
      +// * trigger the AsyncHooks before callbacks
      +// * call the provided function `fn` with the supplied arguments
      +// * trigger the AsyncHooks after callbacks
      +// * restore the original execution context
      +asyncResource.runInAsyncScope(fn, thisArg, ...args);
      +
      +// Call AsyncHooks destroy callbacks.
      +asyncResource.emitDestroy();
      +
      +// Return the unique ID assigned to the AsyncResource instance.
      +asyncResource.asyncId();
      +
      +// Return the trigger ID for the AsyncResource instance.
      +asyncResource.triggerAsyncId();
      +

      new AsyncResource(type[, options])#

      +
        +
      • type <string> The type of async event.
      • +
      • options <Object> +
          +
        • triggerAsyncId <number> The ID of the execution context that created this +async event. Default: executionAsyncId().
        • +
        • requireManualDestroy <boolean> If set to true, disables emitDestroy +when the object is garbage collected. This usually does not need to be set +(even if emitDestroy is called manually), unless the resource's asyncId +is retrieved and the sensitive API's emitDestroy is called with it. +When set to false, the emitDestroy call on garbage collection +will only take place if there is at least one active destroy hook. +Default: false.
        • +
        +
      • +
      +

      Example usage:

      +
      class DBQuery extends AsyncResource {
      +  constructor(db) {
      +    super('DBQuery');
      +    this.db = db;
      +  }
      +
      +  getInfo(query, callback) {
      +    this.db.get(query, (err, data) => {
      +      this.runInAsyncScope(callback, null, err, data);
      +    });
      +  }
      +
      +  close() {
      +    this.db = null;
      +    this.emitDestroy();
      +  }
      +}
      +

      Static method: AsyncResource.bind(fn[, type])#

      + +
        +
      • fn <Function> The function to bind to the current execution context.
      • +
      • type <string> An optional name to associate with the underlying +AsyncResource.
      • +
      +

      Binds the given function to the current execution context.

      +

      The returned function will have an asyncResource property referencing +the AsyncResource to which the function is bound.

      +

      asyncResource.bind(fn)#

      + +
        +
      • fn <Function> The function to bind to the current AsyncResource.
      • +
      +

      Binds the given function to execute to this AsyncResource's scope.

      +

      The returned function will have an asyncResource property referencing +the AsyncResource to which the function is bound.

      +

      asyncResource.runInAsyncScope(fn[, thisArg, ...args])#

      + +
        +
      • fn <Function> The function to call in the execution context of this async +resource.
      • +
      • thisArg <any> The receiver to be used for the function call.
      • +
      • ...args <any> Optional arguments to pass to the function.
      • +
      +

      Call the provided function with the provided arguments in the execution context +of the async resource. This will establish the context, trigger the AsyncHooks +before callbacks, call the function, trigger the AsyncHooks after callbacks, and +then restore the original execution context.

      +

      asyncResource.emitDestroy()#

      + +

      Call all destroy hooks. This should only ever be called once. An error will +be thrown if it is called more than once. This must be manually called. If +the resource is left to be collected by the GC then the destroy hooks will +never be called.

      +

      asyncResource.asyncId()#

      +
        +
      • Returns: <number> The unique asyncId assigned to the resource.
      • +
      +

      asyncResource.triggerAsyncId()#

      +
        +
      • Returns: <number> The same triggerAsyncId that is passed to the +AsyncResource constructor.
      • +
      +

      +

      Using AsyncResource for a Worker thread pool#

      +

      The following example shows how to use the AsyncResource class to properly +provide async tracking for a Worker pool. Other resource pools, such as +database connection pools, can follow a similar model.

      +

      Assuming that the task is adding two numbers, using a file named +task_processor.js with the following content:

      +
      const { parentPort } = require('worker_threads');
      +parentPort.on('message', (task) => {
      +  parentPort.postMessage(task.a + task.b);
      +});
      +

      a Worker pool around it could use the following structure:

      +
      const { AsyncResource } = require('async_hooks');
      +const { EventEmitter } = require('events');
      +const path = require('path');
      +const { Worker } = require('worker_threads');
      +
      +const kTaskInfo = Symbol('kTaskInfo');
      +const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
      +
      +class WorkerPoolTaskInfo extends AsyncResource {
      +  constructor(callback) {
      +    super('WorkerPoolTaskInfo');
      +    this.callback = callback;
      +  }
      +
      +  done(err, result) {
      +    this.runInAsyncScope(this.callback, null, err, result);
      +    this.emitDestroy();  // `TaskInfo`s are used only once.
      +  }
      +}
      +
      +class WorkerPool extends EventEmitter {
      +  constructor(numThreads) {
      +    super();
      +    this.numThreads = numThreads;
      +    this.workers = [];
      +    this.freeWorkers = [];
      +
      +    for (let i = 0; i < numThreads; i++)
      +      this.addNewWorker();
      +  }
      +
      +  addNewWorker() {
      +    const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));
      +    worker.on('message', (result) => {
      +      // In case of success: Call the callback that was passed to `runTask`,
      +      // remove the `TaskInfo` associated with the Worker, and mark it as free
      +      // again.
      +      worker[kTaskInfo].done(null, result);
      +      worker[kTaskInfo] = null;
      +      this.freeWorkers.push(worker);
      +      this.emit(kWorkerFreedEvent);
      +    });
      +    worker.on('error', (err) => {
      +      // In case of an uncaught exception: Call the callback that was passed to
      +      // `runTask` with the error.
      +      if (worker[kTaskInfo])
      +        worker[kTaskInfo].done(err, null);
      +      else
      +        this.emit('error', err);
      +      // Remove the worker from the list and start a new Worker to replace the
      +      // current one.
      +      this.workers.splice(this.workers.indexOf(worker), 1);
      +      this.addNewWorker();
      +    });
      +    this.workers.push(worker);
      +    this.freeWorkers.push(worker);
      +    this.emit(kWorkerFreedEvent);
      +  }
      +
      +  runTask(task, callback) {
      +    if (this.freeWorkers.length === 0) {
      +      // No free threads, wait until a worker thread becomes free.
      +      this.once(kWorkerFreedEvent, () => this.runTask(task, callback));
      +      return;
      +    }
      +
      +    const worker = this.freeWorkers.pop();
      +    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
      +    worker.postMessage(task);
      +  }
      +
      +  close() {
      +    for (const worker of this.workers) worker.terminate();
      +  }
      +}
      +
      +module.exports = WorkerPool;
      +

      Without the explicit tracking added by the WorkerPoolTaskInfo objects, +it would appear that the callbacks are associated with the individual Worker +objects. However, the creation of the Workers is not associated with the +creation of the tasks and does not provide information about when tasks +were scheduled.

      +

      This pool could be used as follows:

      +
      const WorkerPool = require('./worker_pool.js');
      +const os = require('os');
      +
      +const pool = new WorkerPool(os.cpus().length);
      +
      +let finished = 0;
      +for (let i = 0; i < 10; i++) {
      +  pool.runTask({ a: 42, b: 100 }, (err, result) => {
      +    console.log(i, err, result);
      +    if (++finished === 10)
      +      pool.close();
      +  });
      +}
      +

      Integrating AsyncResource with EventEmitter#

      +

      Event listeners triggered by an EventEmitter may be run in a different +execution context than the one that was active when eventEmitter.on() was +called.

      +

      The following example shows how to use the AsyncResource class to properly +associate an event listener with the correct execution context. The same +approach can be applied to a Stream or a similar event-driven class.

      +
      const { createServer } = require('http');
      +const { AsyncResource, executionAsyncId } = require('async_hooks');
      +
      +const server = createServer((req, res) => {
      +  req.on('close', AsyncResource.bind(() => {
      +    // Execution context is bound to the current outer scope.
      +  }));
      +  req.on('close', () => {
      +    // Execution context is bound to the scope that caused 'close' to emit.
      +  });
      +  res.end();
      +}).listen(3000);
      +

      Class: AsyncLocalStorage#

      + +

      This class is used to create asynchronous state within callbacks and promise +chains. It allows storing data throughout the lifetime of a web request +or any other asynchronous duration. It is similar to thread-local storage +in other languages.

      +

      The following example uses AsyncLocalStorage to build a simple logger +that assigns IDs to incoming HTTP requests and includes them in messages +logged within each request.

      +
      const http = require('http');
      +const { AsyncLocalStorage } = require('async_hooks');
      +
      +const asyncLocalStorage = new AsyncLocalStorage();
      +
      +function logWithId(msg) {
      +  const id = asyncLocalStorage.getStore();
      +  console.log(`${id !== undefined ? id : '-'}:`, msg);
      +}
      +
      +let idSeq = 0;
      +http.createServer((req, res) => {
      +  asyncLocalStorage.run(idSeq++, () => {
      +    logWithId('start');
      +    // Imagine any chain of async operations here
      +    setImmediate(() => {
      +      logWithId('finish');
      +      res.end();
      +    });
      +  });
      +}).listen(8080);
      +
      +http.get('http://localhost:8080');
      +http.get('http://localhost:8080');
      +// Prints:
      +//   0: start
      +//   1: start
      +//   0: finish
      +//   1: finish
      +

      When having multiple instances of AsyncLocalStorage, they are independent +from each other. It is safe to instantiate this class multiple times.

      +

      new AsyncLocalStorage()#

      + +

      Creates a new instance of AsyncLocalStorage. Store is only provided within a +run method call.

      +

      asyncLocalStorage.disable()#

      + +

      This method disables the instance of AsyncLocalStorage. All subsequent calls +to asyncLocalStorage.getStore() will return undefined until +asyncLocalStorage.run() is called again.

      +

      When calling asyncLocalStorage.disable(), all current contexts linked to the +instance will be exited.

      +

      Calling asyncLocalStorage.disable() is required before the +asyncLocalStorage can be garbage collected. This does not apply to stores +provided by the asyncLocalStorage, as those objects are garbage collected +along with the corresponding async resources.

      +

      This method is to be used when the asyncLocalStorage is not in use anymore +in the current process.

      +

      asyncLocalStorage.getStore()#

      + + +

      This method returns the current store. +If this method is called outside of an asynchronous context initialized by +calling asyncLocalStorage.run, it will return undefined.

      +

      asyncLocalStorage.enterWith(store)#

      + + +

      Calling asyncLocalStorage.enterWith(store) will transition into the context +for the remainder of the current synchronous execution and will persist +through any following asynchronous calls.

      +

      Example:

      +
      const store = { id: 1 };
      +asyncLocalStorage.enterWith(store);
      +asyncLocalStorage.getStore(); // Returns the store object
      +someAsyncOperation(() => {
      +  asyncLocalStorage.getStore(); // Returns the same object
      +});
      +

      This transition will continue for the entire synchronous execution. +This means that if, for example, the context is entered within an event +handler subsequent event handlers will also run within that context unless +specifically bound to another context with an AsyncResource.

      +
      const store = { id: 1 };
      +
      +emitter.on('my-event', () => {
      +  asyncLocalStorage.enterWith(store);
      +});
      +emitter.on('my-event', () => {
      +  asyncLocalStorage.getStore(); // Returns the same object
      +});
      +
      +asyncLocalStorage.getStore(); // Returns undefined
      +emitter.emit('my-event');
      +asyncLocalStorage.getStore(); // Returns the same object
      +

      asyncLocalStorage.run(store, callback[, ...args])#

      + + +

      This methods runs a function synchronously within a context and return its +return value. The store is not accessible outside of the callback function or +the asynchronous operations created within the callback.

      +

      Optionally, arguments can be passed to the function. They will be passed to +the callback function.

      +

      If the callback function throws an error, it will be thrown by run too. +The stacktrace will not be impacted by this call and the context will +be exited.

      +

      Example:

      +
      const store = { id: 2 };
      +try {
      +  asyncLocalStorage.run(store, () => {
      +    asyncLocalStorage.getStore(); // Returns the store object
      +    throw new Error();
      +  });
      +} catch (e) {
      +  asyncLocalStorage.getStore(); // Returns undefined
      +  // The error will be caught here
      +}
      +

      asyncLocalStorage.exit(callback[, ...args])#

      + + +

      This methods runs a function synchronously outside of a context and return its +return value. The store is not accessible within the callback function or +the asynchronous operations created within the callback.

      +

      Optionally, arguments can be passed to the function. They will be passed to +the callback function.

      +

      If the callback function throws an error, it will be thrown by exit too. +The stacktrace will not be impacted by this call and +the context will be re-entered.

      +

      Example:

      +
      // Within a call to run
      +try {
      +  asyncLocalStorage.getStore(); // Returns the store object or value
      +  asyncLocalStorage.exit(() => {
      +    asyncLocalStorage.getStore(); // Returns undefined
      +    throw new Error();
      +  });
      +} catch (e) {
      +  asyncLocalStorage.getStore(); // Returns the same object or value
      +  // The error will be caught here
      +}
      +

      Usage with async/await#

      +

      If, within an async function, only one await call is to run within a context, +the following pattern should be used:

      +
      async function fn() {
      +  await asyncLocalStorage.run(new Map(), () => {
      +    asyncLocalStorage.getStore().set('key', value);
      +    return foo(); // The return value of foo will be awaited
      +  });
      +}
      +

      In this example, the store is only available in the callback function and the +functions called by foo. Outside of run, calling getStore will return +undefined.

      +

      Troubleshooting#

      +

      In most cases your application or library code should have no issues with +AsyncLocalStorage. But in rare cases you may face situations when the +current store is lost in one of asynchronous operations. In those cases, +consider the following options.

      +

      If your code is callback-based, it is enough to promisify it with +util.promisify(), so it starts working with native promises.

      +

      If you need to keep using callback-based API, or your code assumes +a custom thenable implementation, use the AsyncResource class +to associate the asynchronous operation with the correct execution context.

      +

      Buffer#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/buffer.js

      +

      Buffer objects are used to represent a fixed-length sequence of bytes. Many +Node.js APIs support Buffers.

      +

      The Buffer class is a subclass of JavaScript's Uint8Array class and +extends it with methods that cover additional use cases. Node.js APIs accept +plain Uint8Arrays wherever Buffers are supported as well.

      +

      The Buffer class is within the global scope, making it unlikely that one +would need to ever use require('buffer').Buffer.

      +
      // Creates a zero-filled Buffer of length 10.
      +const buf1 = Buffer.alloc(10);
      +
      +// Creates a Buffer of length 10,
      +// filled with bytes which all have the value `1`.
      +const buf2 = Buffer.alloc(10, 1);
      +
      +// Creates an uninitialized buffer of length 10.
      +// This is faster than calling Buffer.alloc() but the returned
      +// Buffer instance might contain old data that needs to be
      +// overwritten using fill(), write(), or other functions that fill the Buffer's
      +// contents.
      +const buf3 = Buffer.allocUnsafe(10);
      +
      +// Creates a Buffer containing the bytes [1, 2, 3].
      +const buf4 = Buffer.from([1, 2, 3]);
      +
      +// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
      +// are all truncated using `(value & 255)` to fit into the range 0–255.
      +const buf5 = Buffer.from([257, 257.5, -255, '1']);
      +
      +// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
      +// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
      +// [116, 195, 169, 115, 116] (in decimal notation)
      +const buf6 = Buffer.from('tést');
      +
      +// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
      +const buf7 = Buffer.from('tést', 'latin1');
      +

      Buffers and character encodings#

      + +

      When converting between Buffers and strings, a character encoding may be +specified. If no character encoding is specified, UTF-8 will be used as the +default.

      +
      const buf = Buffer.from('hello world', 'utf8');
      +
      +console.log(buf.toString('hex'));
      +// Prints: 68656c6c6f20776f726c64
      +console.log(buf.toString('base64'));
      +// Prints: aGVsbG8gd29ybGQ=
      +
      +console.log(Buffer.from('fhqwhgads', 'utf8'));
      +// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
      +console.log(Buffer.from('fhqwhgads', 'utf16le'));
      +// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
      +

      The character encodings currently supported by Node.js are the following:

      +
        +
      • +

        'utf8': Multi-byte encoded Unicode characters. Many web pages and other +document formats use UTF-8. This is the default character encoding. +When decoding a Buffer into a string that does not exclusively contain +valid UTF-8 data, the Unicode replacement character U+FFFD � will be used +to represent those errors.

        +
      • +
      • +

        'utf16le': Multi-byte encoded Unicode characters. Unlike 'utf8', each +character in the string will be encoded using either 2 or 4 bytes. +Node.js only supports the little-endian variant of UTF-16.

        +
      • +
      • +

        'latin1': Latin-1 stands for ISO-8859-1. This character encoding only +supports the Unicode characters from U+0000 to U+00FF. Each character is +encoded using a single byte. Characters that do not fit into that range are +truncated and will be mapped to characters in that range.

        +
      • +
      +

      Converting a Buffer into a string using one of the above is referred to as +decoding, and converting a string into a Buffer is referred to as encoding.

      +

      Node.js also supports the following two binary-to-text encodings. For +binary-to-text encodings, the naming convention is reversed: Converting a +Buffer into a string is typically referred to as encoding, and converting a +string into a Buffer as decoding.

      +
        +
      • +

        'base64': Base64 encoding. When creating a Buffer from a string, +this encoding will also correctly accept "URL and Filename Safe Alphabet" as +specified in RFC 4648, Section 5. Whitespace characters such as spaces, +tabs, and new lines contained within the base64-encoded string are ignored.

        +
      • +
      • +

        'hex': Encode each byte as two hexadecimal characters. Data truncation +may occur when decoding strings that do exclusively contain valid hexadecimal +characters. See below for an example.

        +
      • +
      +

      The following legacy character encodings are also supported:

      +
        +
      • +

        'ascii': For 7-bit ASCII data only. When encoding a string into a +Buffer, this is equivalent to using 'latin1'. When decoding a Buffer +into a string, using this encoding will additionally unset the highest bit of +each byte before decoding as 'latin1'. +Generally, there should be no reason to use this encoding, as 'utf8' +(or, if the data is known to always be ASCII-only, 'latin1') will be a +better choice when encoding or decoding ASCII-only text. It is only provided +for legacy compatibility.

        +
      • +
      • +

        'binary': Alias for 'latin1'. See binary strings for more background +on this topic. The name of this encoding can be very misleading, as all of the +encodings listed here convert between strings and binary data. For converting +between strings and Buffers, typically 'utf-8' is the right choice.

        +
      • +
      • +

        'ucs2': Alias of 'utf16le'. UCS-2 used to refer to a variant of UTF-16 +that did not support characters that had code points larger than U+FFFF. +In Node.js, these code points are always supported.

        +
      • +
      +
      Buffer.from('1ag', 'hex');
      +// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
      +// ('g') encountered.
      +
      +Buffer.from('1a7g', 'hex');
      +// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
      +
      +Buffer.from('1634', 'hex');
      +// Prints <Buffer 16 34>, all data represented.
      +

      Modern Web browsers follow the WHATWG Encoding Standard which aliases +both 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing +something like http.get(), if the returned charset is one of those listed in +the WHATWG specification it is possible that the server actually returned +'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode +the characters.

      +

      Buffers and TypedArrays#

      + +

      Buffer instances are also JavaScript Uint8Array and TypedArray +instances. All TypedArray methods are available on Buffers. There are, +however, subtle incompatibilities between the Buffer API and the +TypedArray API.

      +

      In particular:

      +
        +
      • While TypedArray#slice() creates a copy of part of the TypedArray, +Buffer#slice() creates a view over the existing Buffer +without copying. This behavior can be surprising, and only exists for legacy +compatibility. TypedArray#subarray() can be used to achieve the behavior +of Buffer#slice() on both Buffers and other +TypedArrays.
      • +
      • buf.toString() is incompatible with its TypedArray equivalent.
      • +
      • A number of methods, e.g. buf.indexOf(), support additional arguments.
      • +
      +

      There are two ways to create new TypedArray instances from a Buffer:

      +
        +
      • Passing a Buffer to a TypedArray constructor will copy the Buffers +contents, interpreted as an array of integers, and not as a byte sequence +of the target type.
      • +
      +
      const buf = Buffer.from([1, 2, 3, 4]);
      +const uint32array = new Uint32Array(buf);
      +
      +console.log(uint32array);
      +
      +// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
      +
        +
      • Passing the Buffers underlying ArrayBuffer will create a +TypedArray that shares its memory with the Buffer.
      • +
      +
      const buf = Buffer.from('hello', 'utf16le');
      +const uint16arr = new Uint16Array(
      +  buf.buffer,
      +  buf.byteOffset,
      +  buf.length / Uint16Array.BYTES_PER_ELEMENT);
      +
      +console.log(uint16array);
      +
      +// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
      +

      It is possible to create a new Buffer that shares the same allocated +memory as a TypedArray instance by using the TypedArray object’s +.buffer property in the same way. Buffer.from() +behaves like new Uint8Array() in this context.

      +
      const arr = new Uint16Array(2);
      +
      +arr[0] = 5000;
      +arr[1] = 4000;
      +
      +// Copies the contents of `arr`.
      +const buf1 = Buffer.from(arr);
      +
      +// Shares memory with `arr`.
      +const buf2 = Buffer.from(arr.buffer);
      +
      +console.log(buf1);
      +// Prints: <Buffer 88 a0>
      +console.log(buf2);
      +// Prints: <Buffer 88 13 a0 0f>
      +
      +arr[1] = 6000;
      +
      +console.log(buf1);
      +// Prints: <Buffer 88 a0>
      +console.log(buf2);
      +// Prints: <Buffer 88 13 70 17>
      +

      When creating a Buffer using a TypedArray's .buffer, it is +possible to use only a portion of the underlying ArrayBuffer by passing in +byteOffset and length parameters.

      +
      const arr = new Uint16Array(20);
      +const buf = Buffer.from(arr.buffer, 0, 16);
      +
      +console.log(buf.length);
      +// Prints: 16
      +

      The Buffer.from() and TypedArray.from() have different signatures and +implementations. Specifically, the TypedArray variants accept a second +argument that is a mapping function that is invoked on every element of the +typed array:

      +
        +
      • TypedArray.from(source[, mapFn[, thisArg]])
      • +
      +

      The Buffer.from() method, however, does not support the use of a mapping +function:

      + +

      Buffers and iteration#

      +

      Buffer instances can be iterated over using for..of syntax:

      +
      const buf = Buffer.from([1, 2, 3]);
      +
      +for (const b of buf) {
      +  console.log(b);
      +}
      +// Prints:
      +//   1
      +//   2
      +//   3
      +

      Additionally, the buf.values(), buf.keys(), and +buf.entries() methods can be used to create iterators.

      +

      Class: Buffer#

      +

      The Buffer class is a global type for dealing with binary data directly. +It can be constructed in a variety of ways.

      +

      Static method: Buffer.alloc(size[, fill[, encoding]])#

      + + +

      Allocates a new Buffer of size bytes. If fill is undefined, the +Buffer will be zero-filled.

      +
      const buf = Buffer.alloc(5);
      +
      +console.log(buf);
      +// Prints: <Buffer 00 00 00 00 00>
      +

      If size is larger than +buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE +is thrown.

      +

      If fill is specified, the allocated Buffer will be initialized by calling +buf.fill(fill).

      +
      const buf = Buffer.alloc(5, 'a');
      +
      +console.log(buf);
      +// Prints: <Buffer 61 61 61 61 61>
      +

      If both fill and encoding are specified, the allocated Buffer will be +initialized by calling buf.fill(fill, encoding).

      +
      const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
      +
      +console.log(buf);
      +// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
      +

      Calling Buffer.alloc() can be measurably slower than the alternative +Buffer.allocUnsafe() but ensures that the newly created Buffer instance +contents will never contain sensitive data from previous allocations, including +data that might not have been allocated for Buffers.

      +

      A TypeError will be thrown if size is not a number.

      +

      Static method: Buffer.allocUnsafe(size)#

      + +
        +
      • size <integer> The desired length of the new Buffer.
      • +
      +

      Allocates a new Buffer of size bytes. If size is larger than +buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE +is thrown.

      +

      The underlying memory for Buffer instances created in this way is not +initialized. The contents of the newly created Buffer are unknown and +may contain sensitive data. Use Buffer.alloc() instead to initialize +Buffer instances with zeroes.

      +
      const buf = Buffer.allocUnsafe(10);
      +
      +console.log(buf);
      +// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
      +
      +buf.fill(0);
      +
      +console.log(buf);
      +// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
      +

      A TypeError will be thrown if size is not a number.

      +

      The Buffer module pre-allocates an internal Buffer instance of +size Buffer.poolSize that is used as a pool for the fast allocation of new +Buffer instances created using Buffer.allocUnsafe(), +Buffer.from(array), Buffer.concat(), and the deprecated +new Buffer(size) constructor only when size is less than or equal +to Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).

      +

      Use of this pre-allocated internal memory pool is a key difference between +calling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill). +Specifically, Buffer.alloc(size, fill) will never use the internal Buffer +pool, while Buffer.allocUnsafe(size).fill(fill) will use the internal +Buffer pool if size is less than or equal to half Buffer.poolSize. The +difference is subtle but can be important when an application requires the +additional performance that Buffer.allocUnsafe() provides.

      +

      Static method: Buffer.allocUnsafeSlow(size)#

      + +
        +
      • size <integer> The desired length of the new Buffer.
      • +
      +

      Allocates a new Buffer of size bytes. If size is larger than +buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE +is thrown. A zero-length Buffer is created if size is 0.

      +

      The underlying memory for Buffer instances created in this way is not +initialized. The contents of the newly created Buffer are unknown and +may contain sensitive data. Use buf.fill(0) to initialize +such Buffer instances with zeroes.

      +

      When using Buffer.allocUnsafe() to allocate new Buffer instances, +allocations under 4KB are sliced from a single pre-allocated Buffer. This +allows applications to avoid the garbage collection overhead of creating many +individually allocated Buffer instances. This approach improves both +performance and memory usage by eliminating the need to track and clean up as +many individual ArrayBuffer objects.

      +

      However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and +then copying out the relevant bits.

      +
      // Need to keep around a few small chunks of memory.
      +const store = [];
      +
      +socket.on('readable', () => {
      +  let data;
      +  while (null !== (data = readable.read())) {
      +    // Allocate for retained data.
      +    const sb = Buffer.allocUnsafeSlow(10);
      +
      +    // Copy the data into the new allocation.
      +    data.copy(sb, 0, 0, 10);
      +
      +    store.push(sb);
      +  }
      +});
      +

      A TypeError will be thrown if size is not a number.

      +

      Static method: Buffer.byteLength(string[, encoding])#

      + + +

      Returns the byte length of a string when encoded using encoding. +This is not the same as String.prototype.length, which does not account +for the encoding that is used to convert the string into bytes.

      +

      For 'base64' and 'hex', this function assumes valid input. For strings that +contain non-base64/hex-encoded data (e.g. whitespace), the return value might be +greater than the length of a Buffer created from the string.

      +
      const str = '\u00bd + \u00bc = \u00be';
      +
      +console.log(`${str}: ${str.length} characters, ` +
      +            `${Buffer.byteLength(str, 'utf8')} bytes`);
      +// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
      +

      When string is a Buffer/DataView/TypedArray/ArrayBuffer/ +SharedArrayBuffer, the byte length as reported by .byteLength +is returned.

      +

      Static method: Buffer.compare(buf1, buf2)#

      + + +

      Compares buf1 to buf2, typically for the purpose of sorting arrays of +Buffer instances. This is equivalent to calling +buf1.compare(buf2).

      +
      const buf1 = Buffer.from('1234');
      +const buf2 = Buffer.from('0123');
      +const arr = [buf1, buf2];
      +
      +console.log(arr.sort(Buffer.compare));
      +// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
      +// (This result is equal to: [buf2, buf1].)
      +

      Static method: Buffer.concat(list[, totalLength])#

      + + +

      Returns a new Buffer which is the result of concatenating all the Buffer +instances in the list together.

      +

      If the list has no items, or if the totalLength is 0, then a new zero-length +Buffer is returned.

      +

      If totalLength is not provided, it is calculated from the Buffer instances +in list by adding their lengths.

      +

      If totalLength is provided, it is coerced to an unsigned integer. If the +combined length of the Buffers in list exceeds totalLength, the result is +truncated to totalLength.

      +
      // Create a single `Buffer` from a list of three `Buffer` instances.
      +
      +const buf1 = Buffer.alloc(10);
      +const buf2 = Buffer.alloc(14);
      +const buf3 = Buffer.alloc(18);
      +const totalLength = buf1.length + buf2.length + buf3.length;
      +
      +console.log(totalLength);
      +// Prints: 42
      +
      +const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
      +
      +console.log(bufA);
      +// Prints: <Buffer 00 00 00 00 ...>
      +console.log(bufA.length);
      +// Prints: 42
      +

      Buffer.concat() may also use the internal Buffer pool like +Buffer.allocUnsafe() does.

      +

      Static method: Buffer.from(array)#

      + + +

      Allocates a new Buffer using an array of bytes in the range 0 – 255. +Array entries outside that range will be truncated to fit into it.

      +
      // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
      +const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
      +

      A TypeError will be thrown if array is not an Array or another type +appropriate for Buffer.from() variants.

      +

      Buffer.from(array) and Buffer.from(string) may also use the internal +Buffer pool like Buffer.allocUnsafe() does.

      +

      Static method: Buffer.from(arrayBuffer[, byteOffset[, length]])#

      + + +

      This creates a view of the ArrayBuffer without copying the underlying +memory. For example, when passed a reference to the .buffer property of a +TypedArray instance, the newly created Buffer will share the same +allocated memory as the TypedArray.

      +
      const arr = new Uint16Array(2);
      +
      +arr[0] = 5000;
      +arr[1] = 4000;
      +
      +// Shares memory with `arr`.
      +const buf = Buffer.from(arr.buffer);
      +
      +console.log(buf);
      +// Prints: <Buffer 88 13 a0 0f>
      +
      +// Changing the original Uint16Array changes the Buffer also.
      +arr[1] = 6000;
      +
      +console.log(buf);
      +// Prints: <Buffer 88 13 70 17>
      +

      The optional byteOffset and length arguments specify a memory range within +the arrayBuffer that will be shared by the Buffer.

      +
      const ab = new ArrayBuffer(10);
      +const buf = Buffer.from(ab, 0, 2);
      +
      +console.log(buf.length);
      +// Prints: 2
      +

      A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a +SharedArrayBuffer or another type appropriate for Buffer.from() +variants.

      +

      Static method: Buffer.from(buffer)#

      + + +

      Copies the passed buffer data onto a new Buffer instance.

      +
      const buf1 = Buffer.from('buffer');
      +const buf2 = Buffer.from(buf1);
      +
      +buf1[0] = 0x61;
      +
      +console.log(buf1.toString());
      +// Prints: auffer
      +console.log(buf2.toString());
      +// Prints: buffer
      +

      A TypeError will be thrown if buffer is not a Buffer or another type +appropriate for Buffer.from() variants.

      +

      Static method: Buffer.from(object[, offsetOrEncoding[, length]])#

      + + +

      For objects whose valueOf() function returns a value not strictly equal to +object, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

      +
      const buf = Buffer.from(new String('this is a test'));
      +// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
      +

      For objects that support Symbol.toPrimitive, returns +Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).

      +
      class Foo {
      +  [Symbol.toPrimitive]() {
      +    return 'this is a test';
      +  }
      +}
      +
      +const buf = Buffer.from(new Foo(), 'utf8');
      +// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
      +

      A TypeError will be thrown if object does not have the mentioned methods or +is not of another type appropriate for Buffer.from() variants.

      +

      Static method: Buffer.from(string[, encoding])#

      + +
        +
      • string <string> A string to encode.
      • +
      • encoding <string> The encoding of string. Default: 'utf8'.
      • +
      +

      Creates a new Buffer containing string. The encoding parameter identifies +the character encoding to be used when converting string into bytes.

      +
      const buf1 = Buffer.from('this is a tést');
      +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
      +
      +console.log(buf1.toString());
      +// Prints: this is a tést
      +console.log(buf2.toString());
      +// Prints: this is a tést
      +console.log(buf1.toString('latin1'));
      +// Prints: this is a tést
      +

      A TypeError will be thrown if string is not a string or another type +appropriate for Buffer.from() variants.

      +

      Static method: Buffer.isBuffer(obj)#

      + + +

      Returns true if obj is a Buffer, false otherwise.

      +

      Static method: Buffer.isEncoding(encoding)#

      + + +

      Returns true if encoding is the name of a supported character encoding, +or false otherwise.

      +
      console.log(Buffer.isEncoding('utf-8'));
      +// Prints: true
      +
      +console.log(Buffer.isEncoding('hex'));
      +// Prints: true
      +
      +console.log(Buffer.isEncoding('utf/8'));
      +// Prints: false
      +
      +console.log(Buffer.isEncoding(''));
      +// Prints: false
      +

      Class property: Buffer.poolSize#

      + + +

      This is the size (in bytes) of pre-allocated internal Buffer instances used +for pooling. This value may be modified.

      +

      buf[index]#

      + + +

      The index operator [index] can be used to get and set the octet at position +index in buf. The values refer to individual bytes, so the legal value +range is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).

      +

      This operator is inherited from Uint8Array, so its behavior on out-of-bounds +access is the same as Uint8Array. In other words, buf[index] returns +undefined when index is negative or greater or equal to buf.length, and +buf[index] = value does not modify the buffer if index is negative or +>= buf.length.

      +
      // Copy an ASCII string into a `Buffer` one byte at a time.
      +// (This only works for ASCII-only strings. In general, one should use
      +// `Buffer.from()` to perform this conversion.)
      +
      +const str = 'Node.js';
      +const buf = Buffer.allocUnsafe(str.length);
      +
      +for (let i = 0; i < str.length; i++) {
      +  buf[i] = str.charCodeAt(i);
      +}
      +
      +console.log(buf.toString('utf8'));
      +// Prints: Node.js
      +

      buf.buffer#

      +
        +
      • <ArrayBuffer> The underlying ArrayBuffer object based on which this Buffer +object is created.
      • +
      +

      This ArrayBuffer is not guaranteed to correspond exactly to the original +Buffer. See the notes on buf.byteOffset for details.

      +
      const arrayBuffer = new ArrayBuffer(16);
      +const buffer = Buffer.from(arrayBuffer);
      +
      +console.log(buffer.buffer === arrayBuffer);
      +// Prints: true
      +

      buf.byteOffset#

      +
        +
      • <integer> The byteOffset of the Buffers underlying ArrayBuffer object.
      • +
      +

      When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length), +or sometimes when allocating a Buffer smaller than Buffer.poolSize, the +buffer does not start from a zero offset on the underlying ArrayBuffer.

      +

      This can cause problems when accessing the underlying ArrayBuffer directly +using buf.buffer, as other parts of the ArrayBuffer may be unrelated +to the Buffer object itself.

      +

      A common issue when creating a TypedArray object that shares its memory with +a Buffer is that in this case one needs to specify the byteOffset correctly:

      +
      // Create a buffer smaller than `Buffer.poolSize`.
      +const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
      +
      +// When casting the Node.js Buffer to an Int8Array, use the byteOffset
      +// to refer only to the part of `nodeBuffer.buffer` that contains the memory
      +// for `nodeBuffer`.
      +new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
      +

      buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])#

      + +
        +
      • target <Buffer> | <Uint8Array> A Buffer or Uint8Array with which to +compare buf.
      • +
      • targetStart <integer> The offset within target at which to begin +comparison. Default: 0.
      • +
      • targetEnd <integer> The offset within target at which to end comparison +(not inclusive). Default: target.length.
      • +
      • sourceStart <integer> The offset within buf at which to begin comparison. +Default: 0.
      • +
      • sourceEnd <integer> The offset within buf at which to end comparison +(not inclusive). Default: buf.length.
      • +
      • Returns: <integer>
      • +
      +

      Compares buf with target and returns a number indicating whether buf +comes before, after, or is the same as target in sort order. +Comparison is based on the actual sequence of bytes in each Buffer.

      +
        +
      • 0 is returned if target is the same as buf
      • +
      • 1 is returned if target should come before buf when sorted.
      • +
      • -1 is returned if target should come after buf when sorted.
      • +
      +
      const buf1 = Buffer.from('ABC');
      +const buf2 = Buffer.from('BCD');
      +const buf3 = Buffer.from('ABCD');
      +
      +console.log(buf1.compare(buf1));
      +// Prints: 0
      +console.log(buf1.compare(buf2));
      +// Prints: -1
      +console.log(buf1.compare(buf3));
      +// Prints: -1
      +console.log(buf2.compare(buf1));
      +// Prints: 1
      +console.log(buf2.compare(buf3));
      +// Prints: 1
      +console.log([buf1, buf2, buf3].sort(Buffer.compare));
      +// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
      +// (This result is equal to: [buf1, buf3, buf2].)
      +

      The optional targetStart, targetEnd, sourceStart, and sourceEnd +arguments can be used to limit the comparison to specific ranges within target +and buf respectively.

      +
      const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
      +const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
      +
      +console.log(buf1.compare(buf2, 5, 9, 0, 4));
      +// Prints: 0
      +console.log(buf1.compare(buf2, 0, 6, 4));
      +// Prints: -1
      +console.log(buf1.compare(buf2, 5, 6, 5));
      +// Prints: 1
      +

      ERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0, +targetEnd > target.byteLength, or sourceEnd > source.byteLength.

      +

      buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])#

      + +
        +
      • target <Buffer> | <Uint8Array> A Buffer or Uint8Array to copy into.
      • +
      • targetStart <integer> The offset within target at which to begin +writing. Default: 0.
      • +
      • sourceStart <integer> The offset within buf from which to begin copying. +Default: 0.
      • +
      • sourceEnd <integer> The offset within buf at which to stop copying (not +inclusive). Default: buf.length.
      • +
      • Returns: <integer> The number of bytes copied.
      • +
      +

      Copies data from a region of buf to a region in target, even if the target +memory region overlaps with buf.

      +

      TypedArray#set() performs the same operation, and is available for all +TypedArrays, including Node.js Buffers, although it takes different +function arguments.

      +
      // Create two `Buffer` instances.
      +const buf1 = Buffer.allocUnsafe(26);
      +const buf2 = Buffer.allocUnsafe(26).fill('!');
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf1[i] = i + 97;
      +}
      +
      +// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
      +buf1.copy(buf2, 8, 16, 20);
      +// This is equivalent to:
      +// buf2.set(buf1.subarray(16, 20), 8);
      +
      +console.log(buf2.toString('ascii', 0, 25));
      +// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
      +
      // Create a `Buffer` and copy data from one region to an overlapping region
      +// within the same `Buffer`.
      +
      +const buf = Buffer.allocUnsafe(26);
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf[i] = i + 97;
      +}
      +
      +buf.copy(buf, 0, 4, 10);
      +
      +console.log(buf.toString());
      +// Prints: efghijghijklmnopqrstuvwxyz
      +

      buf.entries()#

      + + +

      Creates and returns an iterator of [index, byte] pairs from the contents +of buf.

      +
      // Log the entire contents of a `Buffer`.
      +
      +const buf = Buffer.from('buffer');
      +
      +for (const pair of buf.entries()) {
      +  console.log(pair);
      +}
      +// Prints:
      +//   [0, 98]
      +//   [1, 117]
      +//   [2, 102]
      +//   [3, 102]
      +//   [4, 101]
      +//   [5, 114]
      +

      buf.equals(otherBuffer)#

      + + +

      Returns true if both buf and otherBuffer have exactly the same bytes, +false otherwise. Equivalent to +buf.compare(otherBuffer) === 0.

      +
      const buf1 = Buffer.from('ABC');
      +const buf2 = Buffer.from('414243', 'hex');
      +const buf3 = Buffer.from('ABCD');
      +
      +console.log(buf1.equals(buf2));
      +// Prints: true
      +console.log(buf1.equals(buf3));
      +// Prints: false
      +

      buf.fill(value[, offset[, end]][, encoding])#

      + + +

      Fills buf with the specified value. If the offset and end are not given, +the entire buf will be filled:

      +
      // Fill a `Buffer` with the ASCII character 'h'.
      +
      +const b = Buffer.allocUnsafe(50).fill('h');
      +
      +console.log(b.toString());
      +// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      +

      value is coerced to a uint32 value if it is not a string, Buffer, or +integer. If the resulting integer is greater than 255 (decimal), buf will be +filled with value & 255.

      +

      If the final write of a fill() operation falls on a multi-byte character, +then only the bytes of that character that fit into buf are written:

      +
      // Fill a `Buffer` with character that takes up two bytes in UTF-8.
      +
      +console.log(Buffer.allocUnsafe(5).fill('\u0222'));
      +// Prints: <Buffer c8 a2 c8 a2 c8>
      +

      If value contains invalid characters, it is truncated; if no valid +fill data remains, an exception is thrown:

      +
      const buf = Buffer.allocUnsafe(5);
      +
      +console.log(buf.fill('a'));
      +// Prints: <Buffer 61 61 61 61 61>
      +console.log(buf.fill('aazz', 'hex'));
      +// Prints: <Buffer aa aa aa aa aa>
      +console.log(buf.fill('zz', 'hex'));
      +// Throws an exception.
      +

      buf.includes(value[, byteOffset][, encoding])#

      + +
        +
      • value <string> | <Buffer> | <Uint8Array> | <integer> What to search for.
      • +
      • byteOffset <integer> Where to begin searching in buf. If negative, then +offset is calculated from the end of buf. Default: 0.
      • +
      • encoding <string> If value is a string, this is its encoding. +Default: 'utf8'.
      • +
      • Returns: <boolean> true if value was found in buf, false otherwise.
      • +
      +

      Equivalent to buf.indexOf() !== -1.

      +
      const buf = Buffer.from('this is a buffer');
      +
      +console.log(buf.includes('this'));
      +// Prints: true
      +console.log(buf.includes('is'));
      +// Prints: true
      +console.log(buf.includes(Buffer.from('a buffer')));
      +// Prints: true
      +console.log(buf.includes(97));
      +// Prints: true (97 is the decimal ASCII value for 'a')
      +console.log(buf.includes(Buffer.from('a buffer example')));
      +// Prints: false
      +console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
      +// Prints: true
      +console.log(buf.includes('this', 4));
      +// Prints: false
      +

      buf.indexOf(value[, byteOffset][, encoding])#

      + +
        +
      • value <string> | <Buffer> | <Uint8Array> | <integer> What to search for.
      • +
      • byteOffset <integer> Where to begin searching in buf. If negative, then +offset is calculated from the end of buf. Default: 0.
      • +
      • encoding <string> If value is a string, this is the encoding used to +determine the binary representation of the string that will be searched for in +buf. Default: 'utf8'.
      • +
      • Returns: <integer> The index of the first occurrence of value in buf, or +-1 if buf does not contain value.
      • +
      +

      If value is:

      +
        +
      • a string, value is interpreted according to the character encoding in +encoding.
      • +
      • a Buffer or Uint8Array, value will be used in its entirety. +To compare a partial Buffer, use buf.slice().
      • +
      • a number, value will be interpreted as an unsigned 8-bit integer +value between 0 and 255.
      • +
      +
      const buf = Buffer.from('this is a buffer');
      +
      +console.log(buf.indexOf('this'));
      +// Prints: 0
      +console.log(buf.indexOf('is'));
      +// Prints: 2
      +console.log(buf.indexOf(Buffer.from('a buffer')));
      +// Prints: 8
      +console.log(buf.indexOf(97));
      +// Prints: 8 (97 is the decimal ASCII value for 'a')
      +console.log(buf.indexOf(Buffer.from('a buffer example')));
      +// Prints: -1
      +console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
      +// Prints: 8
      +
      +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
      +
      +console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
      +// Prints: 4
      +console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
      +// Prints: 6
      +

      If value is not a string, number, or Buffer, this method will throw a +TypeError. If value is a number, it will be coerced to a valid byte value, +an integer between 0 and 255.

      +

      If byteOffset is not a number, it will be coerced to a number. If the result +of coercion is NaN or 0, then the entire buffer will be searched. This +behavior matches String#indexOf().

      +
      const b = Buffer.from('abcdef');
      +
      +// Passing a value that's a number, but not a valid byte.
      +// Prints: 2, equivalent to searching for 99 or 'c'.
      +console.log(b.indexOf(99.9));
      +console.log(b.indexOf(256 + 99));
      +
      +// Passing a byteOffset that coerces to NaN or 0.
      +// Prints: 1, searching the whole buffer.
      +console.log(b.indexOf('b', undefined));
      +console.log(b.indexOf('b', {}));
      +console.log(b.indexOf('b', null));
      +console.log(b.indexOf('b', []));
      +

      If value is an empty string or empty Buffer and byteOffset is less +than buf.length, byteOffset will be returned. If value is empty and +byteOffset is at least buf.length, buf.length will be returned.

      +

      buf.keys()#

      + + +

      Creates and returns an iterator of buf keys (indices).

      +
      const buf = Buffer.from('buffer');
      +
      +for (const key of buf.keys()) {
      +  console.log(key);
      +}
      +// Prints:
      +//   0
      +//   1
      +//   2
      +//   3
      +//   4
      +//   5
      +

      buf.lastIndexOf(value[, byteOffset][, encoding])#

      + +
        +
      • value <string> | <Buffer> | <Uint8Array> | <integer> What to search for.
      • +
      • byteOffset <integer> Where to begin searching in buf. If negative, then +offset is calculated from the end of buf. Default: +buf.length - 1.
      • +
      • encoding <string> If value is a string, this is the encoding used to +determine the binary representation of the string that will be searched for in +buf. Default: 'utf8'.
      • +
      • Returns: <integer> The index of the last occurrence of value in buf, or +-1 if buf does not contain value.
      • +
      +

      Identical to buf.indexOf(), except the last occurrence of value is found +rather than the first occurrence.

      +
      const buf = Buffer.from('this buffer is a buffer');
      +
      +console.log(buf.lastIndexOf('this'));
      +// Prints: 0
      +console.log(buf.lastIndexOf('buffer'));
      +// Prints: 17
      +console.log(buf.lastIndexOf(Buffer.from('buffer')));
      +// Prints: 17
      +console.log(buf.lastIndexOf(97));
      +// Prints: 15 (97 is the decimal ASCII value for 'a')
      +console.log(buf.lastIndexOf(Buffer.from('yolo')));
      +// Prints: -1
      +console.log(buf.lastIndexOf('buffer', 5));
      +// Prints: 5
      +console.log(buf.lastIndexOf('buffer', 4));
      +// Prints: -1
      +
      +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
      +
      +console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
      +// Prints: 6
      +console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
      +// Prints: 4
      +

      If value is not a string, number, or Buffer, this method will throw a +TypeError. If value is a number, it will be coerced to a valid byte value, +an integer between 0 and 255.

      +

      If byteOffset is not a number, it will be coerced to a number. Any arguments +that coerce to NaN, like {} or undefined, will search the whole buffer. +This behavior matches String#lastIndexOf().

      +
      const b = Buffer.from('abcdef');
      +
      +// Passing a value that's a number, but not a valid byte.
      +// Prints: 2, equivalent to searching for 99 or 'c'.
      +console.log(b.lastIndexOf(99.9));
      +console.log(b.lastIndexOf(256 + 99));
      +
      +// Passing a byteOffset that coerces to NaN.
      +// Prints: 1, searching the whole buffer.
      +console.log(b.lastIndexOf('b', undefined));
      +console.log(b.lastIndexOf('b', {}));
      +
      +// Passing a byteOffset that coerces to 0.
      +// Prints: -1, equivalent to passing 0.
      +console.log(b.lastIndexOf('b', null));
      +console.log(b.lastIndexOf('b', []));
      +

      If value is an empty string or empty Buffer, byteOffset will be returned.

      +

      buf.length#

      + + +

      Returns the number of bytes in buf.

      +
      // Create a `Buffer` and write a shorter string to it using UTF-8.
      +
      +const buf = Buffer.alloc(1234);
      +
      +console.log(buf.length);
      +// Prints: 1234
      +
      +buf.write('some string', 0, 'utf8');
      +
      +console.log(buf.length);
      +// Prints: 1234
      +

      buf.parent#

      + +

      Stability: 0 - Deprecated: Use buf.buffer instead.

      +

      The buf.parent property is a deprecated alias for buf.buffer.

      +

      buf.readBigInt64BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads a signed, big-endian 64-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed +values.

      +

      buf.readBigInt64LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads a signed, little-endian 64-bit integer from buf at the specified +offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed +values.

      +

      buf.readBigUInt64BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads an unsigned, big-endian 64-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
      +
      +console.log(buf.readBigUInt64BE(0));
      +// Prints: 4294967295n
      +

      buf.readBigUInt64LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads an unsigned, little-endian 64-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
      +
      +console.log(buf.readBigUInt64LE(0));
      +// Prints: 18446744069414584320n
      +

      buf.readDoubleBE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 64-bit, big-endian double from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
      +
      +console.log(buf.readDoubleBE(0));
      +// Prints: 8.20788039913184e-304
      +

      buf.readDoubleLE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 64-bit, little-endian double from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
      +
      +console.log(buf.readDoubleLE(0));
      +// Prints: 5.447603722011605e-270
      +console.log(buf.readDoubleLE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readFloatBE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 32-bit, big-endian float from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4]);
      +
      +console.log(buf.readFloatBE(0));
      +// Prints: 2.387939260590663e-38
      +

      buf.readFloatLE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 32-bit, little-endian float from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4]);
      +
      +console.log(buf.readFloatLE(0));
      +// Prints: 1.539989614439558e-36
      +console.log(buf.readFloatLE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readInt8([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed 8-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([-1, 5]);
      +
      +console.log(buf.readInt8(0));
      +// Prints: -1
      +console.log(buf.readInt8(1));
      +// Prints: 5
      +console.log(buf.readInt8(2));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readInt16BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, big-endian 16-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 5]);
      +
      +console.log(buf.readInt16BE(0));
      +// Prints: 5
      +

      buf.readInt16LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, little-endian 16-bit integer from buf at the specified +offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 5]);
      +
      +console.log(buf.readInt16LE(0));
      +// Prints: 1280
      +console.log(buf.readInt16LE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readInt32BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, big-endian 32-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 0, 0, 5]);
      +
      +console.log(buf.readInt32BE(0));
      +// Prints: 5
      +

      buf.readInt32LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, little-endian 32-bit integer from buf at the specified +offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 0, 0, 5]);
      +
      +console.log(buf.readInt32LE(0));
      +// Prints: 83886080
      +console.log(buf.readInt32LE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readIntBE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as a big-endian, two's complement signed value +supporting up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readIntBE(0, 6).toString(16));
      +// Prints: 1234567890ab
      +console.log(buf.readIntBE(1, 6).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +console.log(buf.readIntBE(1, 0).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readIntLE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as a little-endian, two's complement signed value +supporting up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readIntLE(0, 6).toString(16));
      +// Prints: -546f87a9cbee
      +

      buf.readUInt8([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned 8-bit integer from buf at the specified offset.

      +
      const buf = Buffer.from([1, -2]);
      +
      +console.log(buf.readUInt8(0));
      +// Prints: 1
      +console.log(buf.readUInt8(1));
      +// Prints: 254
      +console.log(buf.readUInt8(2));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUInt16BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, big-endian 16-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56]);
      +
      +console.log(buf.readUInt16BE(0).toString(16));
      +// Prints: 1234
      +console.log(buf.readUInt16BE(1).toString(16));
      +// Prints: 3456
      +

      buf.readUInt16LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, little-endian 16-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56]);
      +
      +console.log(buf.readUInt16LE(0).toString(16));
      +// Prints: 3412
      +console.log(buf.readUInt16LE(1).toString(16));
      +// Prints: 5634
      +console.log(buf.readUInt16LE(2).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUInt32BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, big-endian 32-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
      +
      +console.log(buf.readUInt32BE(0).toString(16));
      +// Prints: 12345678
      +

      buf.readUInt32LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, little-endian 32-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
      +
      +console.log(buf.readUInt32LE(0).toString(16));
      +// Prints: 78563412
      +console.log(buf.readUInt32LE(1).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUIntBE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as an unsigned big-endian integer supporting +up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readUIntBE(0, 6).toString(16));
      +// Prints: 1234567890ab
      +console.log(buf.readUIntBE(1, 6).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUIntLE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as an unsigned, little-endian integer supporting +up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readUIntLE(0, 6).toString(16));
      +// Prints: ab9078563412
      +

      buf.subarray([start[, end]])#

      + + +

      Returns a new Buffer that references the same memory as the original, but +offset and cropped by the start and end indices.

      +

      Specifying end greater than buf.length will return the same result as +that of end equal to buf.length.

      +

      This method is inherited from TypedArray#subarray().

      +

      Modifying the new Buffer slice will modify the memory in the original Buffer +because the allocated memory of the two objects overlap.

      +
      // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
      +// from the original `Buffer`.
      +
      +const buf1 = Buffer.allocUnsafe(26);
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf1[i] = i + 97;
      +}
      +
      +const buf2 = buf1.subarray(0, 3);
      +
      +console.log(buf2.toString('ascii', 0, buf2.length));
      +// Prints: abc
      +
      +buf1[0] = 33;
      +
      +console.log(buf2.toString('ascii', 0, buf2.length));
      +// Prints: !bc
      +

      Specifying negative indexes causes the slice to be generated relative to the +end of buf rather than the beginning.

      +
      const buf = Buffer.from('buffer');
      +
      +console.log(buf.subarray(-6, -1).toString());
      +// Prints: buffe
      +// (Equivalent to buf.subarray(0, 5).)
      +
      +console.log(buf.subarray(-6, -2).toString());
      +// Prints: buff
      +// (Equivalent to buf.subarray(0, 4).)
      +
      +console.log(buf.subarray(-5, -2).toString());
      +// Prints: uff
      +// (Equivalent to buf.subarray(1, 4).)
      +

      buf.slice([start[, end]])#

      + + +

      Returns a new Buffer that references the same memory as the original, but +offset and cropped by the start and end indices.

      +

      This is the same behavior as buf.subarray().

      +

      This method is not compatible with the Uint8Array.prototype.slice(), +which is a superclass of Buffer. To copy the slice, use +Uint8Array.prototype.slice().

      +
      const buf = Buffer.from('buffer');
      +
      +const copiedBuf = Uint8Array.prototype.slice.call(buf);
      +copiedBuf[0]++;
      +console.log(copiedBuf.toString());
      +// Prints: cuffer
      +
      +console.log(buf.toString());
      +// Prints: buffer
      +

      buf.swap16()#

      + +
        +
      • Returns: <Buffer> A reference to buf.
      • +
      +

      Interprets buf as an array of unsigned 16-bit integers and swaps the +byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length +is not a multiple of 2.

      +
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
      +
      +console.log(buf1);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +
      +buf1.swap16();
      +
      +console.log(buf1);
      +// Prints: <Buffer 02 01 04 03 06 05 08 07>
      +
      +const buf2 = Buffer.from([0x1, 0x2, 0x3]);
      +
      +buf2.swap16();
      +// Throws ERR_INVALID_BUFFER_SIZE.
      +

      One convenient use of buf.swap16() is to perform a fast in-place conversion +between UTF-16 little-endian and UTF-16 big-endian:

      +
      const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
      +buf.swap16(); // Convert to big-endian UTF-16 text.
      +

      buf.swap32()#

      + +
        +
      • Returns: <Buffer> A reference to buf.
      • +
      +

      Interprets buf as an array of unsigned 32-bit integers and swaps the +byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length +is not a multiple of 4.

      +
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
      +
      +console.log(buf1);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +
      +buf1.swap32();
      +
      +console.log(buf1);
      +// Prints: <Buffer 04 03 02 01 08 07 06 05>
      +
      +const buf2 = Buffer.from([0x1, 0x2, 0x3]);
      +
      +buf2.swap32();
      +// Throws ERR_INVALID_BUFFER_SIZE.
      +

      buf.swap64()#

      + +
        +
      • Returns: <Buffer> A reference to buf.
      • +
      +

      Interprets buf as an array of 64-bit numbers and swaps byte order in-place. +Throws ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.

      +
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
      +
      +console.log(buf1);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +
      +buf1.swap64();
      +
      +console.log(buf1);
      +// Prints: <Buffer 08 07 06 05 04 03 02 01>
      +
      +const buf2 = Buffer.from([0x1, 0x2, 0x3]);
      +
      +buf2.swap64();
      +// Throws ERR_INVALID_BUFFER_SIZE.
      +

      buf.toJSON()#

      + + +

      Returns a JSON representation of buf. JSON.stringify() implicitly calls +this function when stringifying a Buffer instance.

      +

      Buffer.from() accepts objects in the format returned from this method. +In particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

      +
      const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
      +const json = JSON.stringify(buf);
      +
      +console.log(json);
      +// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
      +
      +const copy = JSON.parse(json, (key, value) => {
      +  return value && value.type === 'Buffer' ?
      +    Buffer.from(value) :
      +    value;
      +});
      +
      +console.log(copy);
      +// Prints: <Buffer 01 02 03 04 05>
      +

      buf.toString([encoding[, start[, end]]])#

      + +
        +
      • encoding <string> The character encoding to use. Default: 'utf8'.
      • +
      • start <integer> The byte offset to start decoding at. Default: 0.
      • +
      • end <integer> The byte offset to stop decoding at (not inclusive). +Default: buf.length.
      • +
      • Returns: <string>
      • +
      +

      Decodes buf to a string according to the specified character encoding in +encoding. start and end may be passed to decode only a subset of buf.

      +

      If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, +then each invalid byte is replaced with the replacement character U+FFFD.

      +

      The maximum length of a string instance (in UTF-16 code units) is available +as buffer.constants.MAX_STRING_LENGTH.

      +
      const buf1 = Buffer.allocUnsafe(26);
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf1[i] = i + 97;
      +}
      +
      +console.log(buf1.toString('utf8'));
      +// Prints: abcdefghijklmnopqrstuvwxyz
      +console.log(buf1.toString('utf8', 0, 5));
      +// Prints: abcde
      +
      +const buf2 = Buffer.from('tést');
      +
      +console.log(buf2.toString('hex'));
      +// Prints: 74c3a97374
      +console.log(buf2.toString('utf8', 0, 3));
      +// Prints: té
      +console.log(buf2.toString(undefined, 0, 3));
      +// Prints: té
      +

      buf.values()#

      + + +

      Creates and returns an iterator for buf values (bytes). This function is +called automatically when a Buffer is used in a for..of statement.

      +
      const buf = Buffer.from('buffer');
      +
      +for (const value of buf.values()) {
      +  console.log(value);
      +}
      +// Prints:
      +//   98
      +//   117
      +//   102
      +//   102
      +//   101
      +//   114
      +
      +for (const value of buf) {
      +  console.log(value);
      +}
      +// Prints:
      +//   98
      +//   117
      +//   102
      +//   102
      +//   101
      +//   114
      +

      buf.write(string[, offset[, length]][, encoding])#

      + +
        +
      • string <string> String to write to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write string. +Default: 0.
      • +
      • length <integer> Maximum number of bytes to write (written bytes will not +exceed buf.length - offset). Default: buf.length - offset.
      • +
      • encoding <string> The character encoding of string. Default: 'utf8'.
      • +
      • Returns: <integer> Number of bytes written.
      • +
      +

      Writes string to buf at offset according to the character encoding in +encoding. The length parameter is the number of bytes to write. If buf did +not contain enough space to fit the entire string, only part of string will be +written. However, partially encoded characters will not be written.

      +
      const buf = Buffer.alloc(256);
      +
      +const len = buf.write('\u00bd + \u00bc = \u00be', 0);
      +
      +console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
      +// Prints: 12 bytes: ½ + ¼ = ¾
      +
      +const buffer = Buffer.alloc(10);
      +
      +const length = buffer.write('abcd', 8);
      +
      +console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
      +// Prints: 2 bytes : ab
      +

      buf.writeBigInt64BE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian.

      +

      value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigInt64BE(0x0102030405060708n, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +

      buf.writeBigInt64LE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian.

      +

      value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigInt64LE(0x0102030405060708n, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 08 07 06 05 04 03 02 01>
      +

      buf.writeBigUInt64BE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer de ca fa fe ca ce fa de>
      +

      buf.writeBigUInt64LE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer de fa ce ca fe fa ca de>
      +

      buf.writeDoubleBE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a JavaScript number. Behavior is undefined when value is anything +other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeDoubleBE(123.456, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
      +

      buf.writeDoubleLE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a JavaScript number. Behavior is undefined when value is anything +other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeDoubleLE(123.456, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
      +

      buf.writeFloatBE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. Behavior is +undefined when value is anything other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeFloatBE(0xcafebabe, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 4f 4a fe bb>
      +
      +

      buf.writeFloatLE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. Behavior is +undefined when value is anything other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeFloatLE(0xcafebabe, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer bb fe 4a 4f>
      +

      buf.writeInt8(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset. value must be a valid +signed 8-bit integer. Behavior is undefined when value is anything other than +a signed 8-bit integer.

      +

      value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(2);
      +
      +buf.writeInt8(2, 0);
      +buf.writeInt8(-2, 1);
      +
      +console.log(buf);
      +// Prints: <Buffer 02 fe>
      +

      buf.writeInt16BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid signed 16-bit integer. Behavior is undefined when value is +anything other than a signed 16-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(2);
      +
      +buf.writeInt16BE(0x0102, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 01 02>
      +

      buf.writeInt16LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid signed 16-bit integer. Behavior is undefined when value is +anything other than a signed 16-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(2);
      +
      +buf.writeInt16LE(0x0304, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 04 03>
      +

      buf.writeInt32BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid signed 32-bit integer. Behavior is undefined when value is +anything other than a signed 32-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeInt32BE(0x01020304, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 01 02 03 04>
      +

      buf.writeInt32LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid signed 32-bit integer. Behavior is undefined when value is +anything other than a signed 32-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeInt32LE(0x05060708, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 08 07 06 05>
      +

      buf.writeIntBE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when +value is anything other than a signed integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeIntBE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer 12 34 56 78 90 ab>
      +
      +

      buf.writeIntLE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined +when value is anything other than a signed integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeIntLE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer ab 90 78 56 34 12>
      +

      buf.writeUInt8(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset. value must be a +valid unsigned 8-bit integer. Behavior is undefined when value is anything +other than an unsigned 8-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt8(0x3, 0);
      +buf.writeUInt8(0x4, 1);
      +buf.writeUInt8(0x23, 2);
      +buf.writeUInt8(0x42, 3);
      +
      +console.log(buf);
      +// Prints: <Buffer 03 04 23 42>
      +

      buf.writeUInt16BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid unsigned 16-bit integer. Behavior is undefined when value +is anything other than an unsigned 16-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt16BE(0xdead, 0);
      +buf.writeUInt16BE(0xbeef, 2);
      +
      +console.log(buf);
      +// Prints: <Buffer de ad be ef>
      +

      buf.writeUInt16LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid unsigned 16-bit integer. Behavior is undefined when value is +anything other than an unsigned 16-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt16LE(0xdead, 0);
      +buf.writeUInt16LE(0xbeef, 2);
      +
      +console.log(buf);
      +// Prints: <Buffer ad de ef be>
      +

      buf.writeUInt32BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid unsigned 32-bit integer. Behavior is undefined when value +is anything other than an unsigned 32-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt32BE(0xfeedface, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer fe ed fa ce>
      +

      buf.writeUInt32LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid unsigned 32-bit integer. Behavior is undefined when value is +anything other than an unsigned 32-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt32LE(0xfeedface, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer ce fa ed fe>
      +

      buf.writeUIntBE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined +when value is anything other than an unsigned integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeUIntBE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer 12 34 56 78 90 ab>
      +

      buf.writeUIntLE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined +when value is anything other than an unsigned integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeUIntLE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer ab 90 78 56 34 12>
      +

      new Buffer(array)#

      + +

      Stability: 0 - Deprecated: Use Buffer.from(array) instead.

      + +

      See Buffer.from(array).

      +

      new Buffer(arrayBuffer[, byteOffset[, length]])#

      + +

      + +

      See +Buffer.from(arrayBuffer[, byteOffset[, length]]).

      +

      new Buffer(buffer)#

      + +

      Stability: 0 - Deprecated: Use Buffer.from(buffer) instead.

      + +

      See Buffer.from(buffer).

      +

      new Buffer(size)#

      + +

      Stability: 0 - Deprecated: Use Buffer.alloc() instead (also see +Buffer.allocUnsafe()).

      +
        +
      • size <integer> The desired length of the new Buffer.
      • +
      +

      See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the +constructor is equivalent to Buffer.alloc().

      +

      new Buffer(string[, encoding])#

      + +

      Stability: 0 - Deprecated: +Use Buffer.from(string[, encoding]) instead.

      +
        +
      • string <string> String to encode.
      • +
      • encoding <string> The encoding of string. Default: 'utf8'.
      • +
      +

      See Buffer.from(string[, encoding]).

      +

      buffer module APIs#

      +

      While, the Buffer object is available as a global, there are additional +Buffer-related APIs that are available only via the buffer module +accessed using require('buffer').

      +

      buffer.INSPECT_MAX_BYTES#

      + + +

      Returns the maximum number of bytes that will be returned when +buf.inspect() is called. This can be overridden by user modules. See +util.inspect() for more details on buf.inspect() behavior.

      +

      buffer.kMaxLength#

      + +
        +
      • <integer> The largest size allowed for a single Buffer instance.
      • +
      +

      An alias for buffer.constants.MAX_LENGTH.

      +

      buffer.transcode(source, fromEnc, toEnc)#

      + + +

      Re-encodes the given Buffer or Uint8Array instance from one character +encoding to another. Returns a new Buffer instance.

      +

      Throws if the fromEnc or toEnc specify invalid character encodings or if +conversion from fromEnc to toEnc is not permitted.

      +

      Encodings supported by buffer.transcode() are: 'ascii', 'utf8', +'utf16le', 'ucs2', 'latin1', and 'binary'.

      +

      The transcoding process will use substitution characters if a given byte +sequence cannot be adequately represented in the target encoding. For instance:

      +
      const buffer = require('buffer');
      +
      +const newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');
      +console.log(newBuf.toString('ascii'));
      +// Prints: '?'
      +

      Because the Euro (€) sign is not representable in US-ASCII, it is replaced +with ? in the transcoded Buffer.

      +

      Class: SlowBuffer#

      + +

      Stability: 0 - Deprecated: Use Buffer.allocUnsafeSlow() instead.

      +

      See Buffer.allocUnsafeSlow(). This was never a class in the sense that +the constructor always returned a Buffer instance, rather than a SlowBuffer +instance.

      +

      new SlowBuffer(size)#

      + +

      Stability: 0 - Deprecated: Use Buffer.allocUnsafeSlow() instead.

      +
        +
      • size <integer> The desired length of the new SlowBuffer.
      • +
      +

      See Buffer.allocUnsafeSlow().

      +

      Buffer constants#

      + +

      buffer.constants.MAX_LENGTH#

      + +
        +
      • <integer> The largest size allowed for a single Buffer instance.
      • +
      +

      On 32-bit architectures, this value currently is 230 - 1 (~1GB). +On 64-bit architectures, this value currently is 231 - 1 (~2GB).

      +

      This value is also available as buffer.kMaxLength.

      +

      buffer.constants.MAX_STRING_LENGTH#

      + +
        +
      • <integer> The largest length allowed for a single string instance.
      • +
      +

      Represents the largest length that a string primitive can have, counted +in UTF-16 code units.

      +

      This value may depend on the JS engine that is being used.

      +

      Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe()#

      +

      In versions of Node.js prior to 6.0.0, Buffer instances were created using the +Buffer constructor function, which allocates the returned Buffer +differently based on what arguments are provided:

      +
        +
      • Passing a number as the first argument to Buffer() (e.g. new Buffer(10)) +allocates a new Buffer object of the specified size. Prior to Node.js 8.0.0, +the memory allocated for such Buffer instances is not initialized and +can contain sensitive data. Such Buffer instances must be subsequently +initialized by using either buf.fill(0) or by writing to the +entire Buffer before reading data from the Buffer. +While this behavior is intentional to improve performance, +development experience has demonstrated that a more explicit distinction is +required between creating a fast-but-uninitialized Buffer versus creating a +slower-but-safer Buffer. Since Node.js 8.0.0, Buffer(num) and new Buffer(num) return a Buffer with initialized memory.
      • +
      • Passing a string, array, or Buffer as the first argument copies the +passed object's data into the Buffer.
      • +
      • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer +that shares allocated memory with the given array buffer.
      • +
      +

      Because the behavior of new Buffer() is different depending on the type of the +first argument, security and reliability issues can be inadvertently introduced +into applications when argument validation or Buffer initialization is not +performed.

      +

      For example, if an attacker can cause an application to receive a number where +a string is expected, the application may call new Buffer(100) +instead of new Buffer("100"), leading it to allocate a 100 byte buffer instead +of allocating a 3 byte buffer with content "100". This is commonly possible +using JSON API calls. Since JSON distinguishes between numeric and string types, +it allows injection of numbers where a naively written application that does not +validate its input sufficiently might expect to always receive a string. +Before Node.js 8.0.0, the 100 byte buffer might contain +arbitrary pre-existing in-memory data, so may be used to expose in-memory +secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot +occur because the data is zero-filled. However, other attacks are still +possible, such as causing very large buffers to be allocated by the server, +leading to performance degradation or crashing on memory exhaustion.

      +

      To make the creation of Buffer instances more reliable and less error-prone, +the various forms of the new Buffer() constructor have been deprecated +and replaced by separate Buffer.from(), Buffer.alloc(), and +Buffer.allocUnsafe() methods.

      +

      Developers should migrate all existing uses of the new Buffer() constructors +to one of these new APIs.

      + +

      Buffer instances returned by Buffer.allocUnsafe() and +Buffer.from(array) may be allocated off a shared internal memory pool +if size is less than or equal to half Buffer.poolSize. Instances +returned by Buffer.allocUnsafeSlow() never use the shared internal +memory pool.

      +

      The --zero-fill-buffers command line option#

      + +

      Node.js can be started using the --zero-fill-buffers command line option to +cause all newly-allocated Buffer instances to be zero-filled upon creation by +default. Without the option, buffers created with Buffer.allocUnsafe(), +Buffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled. +Use of this flag can have a measurable negative impact on performance. Use the +--zero-fill-buffers option only when necessary to enforce that newly allocated +Buffer instances cannot contain old data that is potentially sensitive.

      +
      $ node --zero-fill-buffers
      +> Buffer.allocUnsafe(5);
      +<Buffer 00 00 00 00 00>
      +

      What makes Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() "unsafe"?#

      +

      When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the +segment of allocated memory is uninitialized (it is not zeroed-out). While +this design makes the allocation of memory quite fast, the allocated segment of +memory might contain old data that is potentially sensitive. Using a Buffer +created by Buffer.allocUnsafe() without completely overwriting the +memory can allow this old data to be leaked when the Buffer memory is read.

      +

      While there are clear performance advantages to using +Buffer.allocUnsafe(), extra care must be taken in order to avoid +introducing security vulnerabilities into an application.

      +

      C++ addons#

      + + +

      Addons are dynamically-linked shared objects written in C++. The +require() function can load addons as ordinary Node.js modules. +Addons provide an interface between JavaScript and C/C++ libraries.

      +

      There are three options for implementing addons: N-API, nan, or direct +use of internal V8, libuv and Node.js libraries. Unless there is a need for +direct access to functionality which is not exposed by N-API, use N-API. +Refer to C/C++ addons with N-API for more information on N-API.

      +

      When not using N-API, implementing addons is complicated, +involving knowledge of several components and APIs:

      +
        +
      • +

        V8: the C++ library Node.js uses to provide the +JavaScript implementation. V8 provides the mechanisms for creating objects, +calling functions, etc. V8's API is documented mostly in the +v8.h header file (deps/v8/include/v8.h in the Node.js source +tree), which is also available online.

        +
      • +
      • +

        libuv: The C library that implements the Node.js event loop, its worker +threads and all of the asynchronous behaviors of the platform. It also +serves as a cross-platform abstraction library, giving easy, POSIX-like +access across all major operating systems to many common system tasks, such +as interacting with the filesystem, sockets, timers, and system events. libuv +also provides a pthreads-like threading abstraction that may be used to +power more sophisticated asynchronous addons that need to move beyond the +standard event loop. Addon authors are encouraged to think about how to +avoid blocking the event loop with I/O or other time-intensive tasks by +off-loading work via libuv to non-blocking system operations, worker threads +or a custom use of libuv's threads.

        +
      • +
      • +

        Internal Node.js libraries. Node.js itself exports C++ APIs that addons can +use, the most important of which is the node::ObjectWrap class.

        +
      • +
      • +

        Node.js includes other statically linked libraries including OpenSSL. These +other libraries are located in the deps/ directory in the Node.js source +tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully +re-exported by Node.js and may be used to various extents by addons. See +Linking to libraries included with Node.js for additional information.

        +
      • +
      +

      All of the following examples are available for download and may +be used as the starting-point for an addon.

      +

      Hello world#

      +

      This "Hello world" example is a simple addon, written in C++, that is the +equivalent of the following JavaScript code:

      +
      module.exports.hello = () => 'world';
      +

      First, create the file hello.cc:

      +
      // hello.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void Method(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  args.GetReturnValue().Set(String::NewFromUtf8(
      +      isolate, "world", NewStringType::kNormal).ToLocalChecked());
      +}
      +
      +void Initialize(Local<Object> exports) {
      +  NODE_SET_METHOD(exports, "hello", Method);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
      +
      +}  // namespace demo
      +

      All Node.js addons must export an initialization function following +the pattern:

      +
      void Initialize(Local<Object> exports);
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
      +

      There is no semi-colon after NODE_MODULE as it's not a function (see +node.h).

      +

      The module_name must match the filename of the final binary (excluding +the .node suffix).

      +

      In the hello.cc example, then, the initialization function is Initialize +and the addon module name is addon.

      +

      When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as +the first parameter of NODE_MODULE() will ensure that the name of the final +binary will be passed to NODE_MODULE().

      +

      Context-aware addons#

      +

      There are environments in which Node.js addons may need to be loaded multiple +times in multiple contexts. For example, the Electron runtime runs multiple +instances of Node.js in a single process. Each instance will have its own +require() cache, and thus each instance will need a native addon to behave +correctly when loaded via require(). From the addon's perspective, this means +that it must support multiple initializations.

      +

      A context-aware addon can be constructed by using the macro +NODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js +will expect to find when it loads an addon. An addon can thus be initialized as +in the following example:

      +
      using namespace v8;
      +
      +extern "C" NODE_MODULE_EXPORT void
      +NODE_MODULE_INITIALIZER(Local<Object> exports,
      +                        Local<Value> module,
      +                        Local<Context> context) {
      +  /* Perform addon initialization steps here. */
      +}
      +

      Another option is to use the macro NODE_MODULE_INIT(), which will also +construct a context-aware addon. Unlike NODE_MODULE(), which is used to +construct an addon around a given addon initializer function, +NODE_MODULE_INIT() serves as the declaration of such an initializer to be +followed by a function body.

      +

      The following three variables may be used inside the function body following an +invocation of NODE_MODULE_INIT():

      +
        +
      • Local<Object> exports,
      • +
      • Local<Value> module, and
      • +
      • Local<Context> context
      • +
      +

      The choice to build a context-aware addon carries with it the responsibility of +carefully managing global static data. Since the addon may be loaded multiple +times, potentially even from different threads, any global static data stored +in the addon must be properly protected, and must not contain any persistent +references to JavaScript objects. The reason for this is that JavaScript +objects are only valid in one context, and will likely cause a crash when +accessed from the wrong context or from a different thread than the one on which +they were created.

      +

      The context-aware addon can be structured to avoid global static data by +performing the following steps:

      +
        +
      • Define a class which will hold per-addon-instance data and which has a static +member of the form +
        static void DeleteInstance(void* data) {
        +  // Cast `data` to an instance of the class and delete it.
        +}
        +
      • +
      • Heap-allocate an instance of this class in the addon initializer. This can be +accomplished using the new keyword.
      • +
      • Call node::AddEnvironmentCleanupHook(), passing it the above-created +instance and a pointer to DeleteInstance(). This will ensure the instance is +deleted when the environment is torn down.
      • +
      • Store the instance of the class in a v8::External, and
      • +
      • Pass the v8::External to all methods exposed to JavaScript by passing it +to v8::FunctionTemplate::New() or v8::Function::New() which creates the +native-backed JavaScript functions. The third parameter of +v8::FunctionTemplate::New() or v8::Function::New() accepts the +v8::External and makes it available in the native callback using the +v8::FunctionCallbackInfo::Data() method.
      • +
      +

      This will ensure that the per-addon-instance data reaches each binding that can +be called from JavaScript. The per-addon-instance data must also be passed into +any asynchronous callbacks the addon may create.

      +

      The following example illustrates the implementation of a context-aware addon:

      +
      #include <node.h>
      +
      +using namespace v8;
      +
      +class AddonData {
      + public:
      +  explicit AddonData(Isolate* isolate):
      +      call_count(0) {
      +    // Ensure this per-addon-instance data is deleted at environment cleanup.
      +    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
      +  }
      +
      +  // Per-addon data.
      +  int call_count;
      +
      +  static void DeleteInstance(void* data) {
      +    delete static_cast<AddonData*>(data);
      +  }
      +};
      +
      +static void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
      +  // Retrieve the per-addon-instance data.
      +  AddonData* data =
      +      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());
      +  data->call_count++;
      +  info.GetReturnValue().Set((double)data->call_count);
      +}
      +
      +// Initialize this addon to be context-aware.
      +NODE_MODULE_INIT(/* exports, module, context */) {
      +  Isolate* isolate = context->GetIsolate();
      +
      +  // Create a new instance of `AddonData` for this instance of the addon and
      +  // tie its life cycle to that of the Node.js environment.
      +  AddonData* data = new AddonData(isolate);
      +
      +  // Wrap the data in a `v8::External` so we can pass it to the method we
      +  // expose.
      +  Local<External> external = External::New(isolate, data);
      +
      +  // Expose the method `Method` to JavaScript, and make sure it receives the
      +  // per-addon-instance data we created above by passing `external` as the
      +  // third parameter to the `FunctionTemplate` constructor.
      +  exports->Set(context,
      +               String::NewFromUtf8(isolate, "method", NewStringType::kNormal)
      +                  .ToLocalChecked(),
      +               FunctionTemplate::New(isolate, Method, external)
      +                  ->GetFunction(context).ToLocalChecked()).FromJust();
      +}
      +

      Worker support#

      + +

      In order to be loaded from multiple Node.js environments, +such as a main thread and a Worker thread, an add-on needs to either:

      +
        +
      • Be an N-API addon, or
      • +
      • Be declared as context-aware using NODE_MODULE_INIT() as described above
      • +
      +

      In order to support Worker threads, addons need to clean up any resources +they may have allocated when such a thread exists. This can be achieved through +the usage of the AddEnvironmentCleanupHook() function:

      +
      void AddEnvironmentCleanupHook(v8::Isolate* isolate,
      +                               void (*fun)(void* arg),
      +                               void* arg);
      +

      This function adds a hook that will run before a given Node.js instance shuts +down. If necessary, such hooks can be removed before they are run using +RemoveEnvironmentCleanupHook(), which has the same signature. Callbacks are +run in last-in first-out order.

      +

      If necessary, there is an additional pair of AddEnvironmentCleanupHook() +and RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a +callback function. This can be used for shutting down asynchronous resources, +such as any libuv handles registered by the addon.

      +

      The following addon.cc uses AddEnvironmentCleanupHook:

      +
      // addon.cc
      +#include <assert.h>
      +#include <stdlib.h>
      +#include <node.h>
      +
      +using node::AddEnvironmentCleanupHook;
      +using v8::HandleScope;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::Object;
      +
      +// Note: In a real-world application, do not rely on static/global data.
      +static char cookie[] = "yum yum";
      +static int cleanup_cb1_called = 0;
      +static int cleanup_cb2_called = 0;
      +
      +static void cleanup_cb1(void* arg) {
      +  Isolate* isolate = static_cast<Isolate*>(arg);
      +  HandleScope scope(isolate);
      +  Local<Object> obj = Object::New(isolate);
      +  assert(!obj.IsEmpty());  // assert VM is still alive
      +  assert(obj->IsObject());
      +  cleanup_cb1_called++;
      +}
      +
      +static void cleanup_cb2(void* arg) {
      +  assert(arg == static_cast<void*>(cookie));
      +  cleanup_cb2_called++;
      +}
      +
      +static void sanity_check(void*) {
      +  assert(cleanup_cb1_called == 1);
      +  assert(cleanup_cb2_called == 1);
      +}
      +
      +// Initialize this addon to be context-aware.
      +NODE_MODULE_INIT(/* exports, module, context */) {
      +  Isolate* isolate = context->GetIsolate();
      +
      +  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
      +  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
      +  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
      +}
      +

      Test in JavaScript by running:

      +
      // test.js
      +require('./build/Release/addon');
      +

      Building#

      +

      Once the source code has been written, it must be compiled into the binary +addon.node file. To do so, create a file called binding.gyp in the +top-level of the project describing the build configuration of the module +using a JSON-like format. This file is used by node-gyp, a tool written +specifically to compile Node.js addons.

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [ "hello.cc" ]
      +    }
      +  ]
      +}
      +

      A version of the node-gyp utility is bundled and distributed with +Node.js as part of npm. This version is not made directly available for +developers to use and is intended only to support the ability to use the +npm install command to compile and install addons. Developers who wish to +use node-gyp directly can install it using the command +npm install -g node-gyp. See the node-gyp installation instructions for +more information, including platform-specific requirements.

      +

      Once the binding.gyp file has been created, use node-gyp configure to +generate the appropriate project build files for the current platform. This +will generate either a Makefile (on Unix platforms) or a vcxproj file +(on Windows) in the build/ directory.

      +

      Next, invoke the node-gyp build command to generate the compiled addon.node +file. This will be put into the build/Release/ directory.

      +

      When using npm install to install a Node.js addon, npm uses its own bundled +version of node-gyp to perform this same set of actions, generating a +compiled version of the addon for the user's platform on demand.

      +

      Once built, the binary addon can be used from within Node.js by pointing +require() to the built addon.node module:

      +
      // hello.js
      +const addon = require('./build/Release/addon');
      +
      +console.log(addon.hello());
      +// Prints: 'world'
      +

      Because the exact path to the compiled addon binary can vary depending on how +it is compiled (i.e. sometimes it may be in ./build/Debug/), addons can use +the bindings package to load the compiled module.

      +

      While the bindings package implementation is more sophisticated in how it +locates addon modules, it is essentially using a try…catch pattern similar to:

      +
      try {
      +  return require('./build/Release/addon.node');
      +} catch (err) {
      +  return require('./build/Debug/addon.node');
      +}
      +

      Linking to libraries included with Node.js#

      +

      Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All +addons are required to link to V8 and may link to any of the other dependencies +as well. Typically, this is as simple as including the appropriate +#include <...> statements (e.g. #include <v8.h>) and node-gyp will locate +the appropriate headers automatically. However, there are a few caveats to be +aware of:

      +
        +
      • +

        When node-gyp runs, it will detect the specific release version of Node.js +and download either the full source tarball or just the headers. If the full +source is downloaded, addons will have complete access to the full set of +Node.js dependencies. However, if only the Node.js headers are downloaded, then +only the symbols exported by Node.js will be available.

        +
      • +
      • +

        node-gyp can be run using the --nodedir flag pointing at a local Node.js +source image. Using this option, the addon will have access to the full set of +dependencies.

        +
      • +
      +

      Loading addons using require()#

      +

      The filename extension of the compiled addon binary is .node (as opposed +to .dll or .so). The require() function is written to look for +files with the .node file extension and initialize those as dynamically-linked +libraries.

      +

      When calling require(), the .node extension can usually be +omitted and Node.js will still find and initialize the addon. One caveat, +however, is that Node.js will first attempt to locate and load modules or +JavaScript files that happen to share the same base name. For instance, if +there is a file addon.js in the same directory as the binary addon.node, +then require('addon') will give precedence to the addon.js file +and load it instead.

      +

      Native abstractions for Node.js#

      +

      Each of the examples illustrated in this document directly use the +Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed +dramatically from one V8 release to the next (and one major Node.js release to +the next). With each change, addons may need to be updated and recompiled in +order to continue functioning. The Node.js release schedule is designed to +minimize the frequency and impact of such changes but there is little that +Node.js can do to ensure stability of the V8 APIs.

      +

      The Native Abstractions for Node.js (or nan) provide a set of tools that +addon developers are recommended to use to keep compatibility between past and +future releases of V8 and Node.js. See the nan examples for an +illustration of how it can be used.

      +

      N-API#

      +

      Stability: 2 - Stable

      +

      N-API is an API for building native addons. It is independent from +the underlying JavaScript runtime (e.g. V8) and is maintained as part of +Node.js itself. This API will be Application Binary Interface (ABI) stable +across versions of Node.js. It is intended to insulate addons from +changes in the underlying JavaScript engine and allow modules +compiled for one version to run on later versions of Node.js without +recompilation. Addons are built/packaged with the same approach/tools +outlined in this document (node-gyp, etc.). The only difference is the +set of APIs that are used by the native code. Instead of using the V8 +or Native Abstractions for Node.js APIs, the functions available +in the N-API are used.

      +

      Creating and maintaining an addon that benefits from the ABI stability +provided by N-API carries with it certain +implementation considerations.

      +

      To use N-API in the above "Hello world" example, replace the content of +hello.cc with the following. All other instructions remain the same.

      +
      // hello.cc using N-API
      +#include <node_api.h>
      +
      +namespace demo {
      +
      +napi_value Method(napi_env env, napi_callback_info args) {
      +  napi_value greeting;
      +  napi_status status;
      +
      +  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
      +  if (status != napi_ok) return nullptr;
      +  return greeting;
      +}
      +
      +napi_value init(napi_env env, napi_value exports) {
      +  napi_status status;
      +  napi_value fn;
      +
      +  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
      +  if (status != napi_ok) return nullptr;
      +
      +  status = napi_set_named_property(env, exports, "hello", fn);
      +  if (status != napi_ok) return nullptr;
      +  return exports;
      +}
      +
      +NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
      +
      +}  // namespace demo
      +

      The functions available and how to use them are documented in +C/C++ addons with N-API.

      +

      Addon examples#

      +

      Following are some example addons intended to help developers get started. The +examples use the V8 APIs. Refer to the online V8 reference +for help with the various V8 calls, and V8's Embedder's Guide for an +explanation of several concepts used such as handles, scopes, function +templates, etc.

      +

      Each of these examples using the following binding.gyp file:

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [ "addon.cc" ]
      +    }
      +  ]
      +}
      +

      In cases where there is more than one .cc file, simply add the additional +filename to the sources array:

      +
      "sources": ["addon.cc", "myexample.cc"]
      +

      Once the binding.gyp file is ready, the example addons can be configured and +built using node-gyp:

      +
      $ node-gyp configure build
      +

      Function arguments#

      +

      Addons will typically expose objects and functions that can be accessed from +JavaScript running within Node.js. When functions are invoked from JavaScript, +the input arguments and return value must be mapped to and from the C/C++ +code.

      +

      The following example illustrates how to read function arguments passed from +JavaScript and how to return a result:

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Exception;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Number;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +// This is the implementation of the "add" method
      +// Input arguments are passed using the
      +// const FunctionCallbackInfo<Value>& args struct
      +void Add(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  // Check the number of arguments passed.
      +  if (args.Length() < 2) {
      +    // Throw an Error that is passed back to JavaScript
      +    isolate->ThrowException(Exception::TypeError(
      +        String::NewFromUtf8(isolate,
      +                            "Wrong number of arguments",
      +                            NewStringType::kNormal).ToLocalChecked()));
      +    return;
      +  }
      +
      +  // Check the argument types
      +  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
      +    isolate->ThrowException(Exception::TypeError(
      +        String::NewFromUtf8(isolate,
      +                            "Wrong arguments",
      +                            NewStringType::kNormal).ToLocalChecked()));
      +    return;
      +  }
      +
      +  // Perform the operation
      +  double value =
      +      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();
      +  Local<Number> num = Number::New(isolate, value);
      +
      +  // Set the return value (using the passed in
      +  // FunctionCallbackInfo<Value>&)
      +  args.GetReturnValue().Set(num);
      +}
      +
      +void Init(Local<Object> exports) {
      +  NODE_SET_METHOD(exports, "add", Add);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      Once compiled, the example addon can be required and used from within Node.js:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +console.log('This should be eight:', addon.add(3, 5));
      +

      Callbacks#

      +

      It is common practice within addons to pass JavaScript functions to a C++ +function and execute them from there. The following example illustrates how +to invoke such callbacks:

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Null;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void RunCallback(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<Function> cb = Local<Function>::Cast(args[0]);
      +  const unsigned argc = 1;
      +  Local<Value> argv[argc] = {
      +      String::NewFromUtf8(isolate,
      +                          "hello world",
      +                          NewStringType::kNormal).ToLocalChecked() };
      +  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
      +}
      +
      +void Init(Local<Object> exports, Local<Object> module) {
      +  NODE_SET_METHOD(module, "exports", RunCallback);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      This example uses a two-argument form of Init() that receives the full +module object as the second argument. This allows the addon to completely +overwrite exports with a single function instead of adding the function as a +property of exports.

      +

      To test it, run the following JavaScript:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +addon((msg) => {
      +  console.log(msg);
      +// Prints: 'hello world'
      +});
      +

      In this example, the callback function is invoked synchronously.

      +

      Object factory#

      +

      Addons can create and return new objects from within a C++ function as +illustrated in the following example. An object is created and returned with a +property msg that echoes the string passed to createObject():

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void CreateObject(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  Local<Object> obj = Object::New(isolate);
      +  obj->Set(context,
      +           String::NewFromUtf8(isolate,
      +                               "msg",
      +                               NewStringType::kNormal).ToLocalChecked(),
      +                               args[0]->ToString(context).ToLocalChecked())
      +           .FromJust();
      +
      +  args.GetReturnValue().Set(obj);
      +}
      +
      +void Init(Local<Object> exports, Local<Object> module) {
      +  NODE_SET_METHOD(module, "exports", CreateObject);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      To test it in JavaScript:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const obj1 = addon('hello');
      +const obj2 = addon('world');
      +console.log(obj1.msg, obj2.msg);
      +// Prints: 'hello world'
      +

      Function factory#

      +

      Another common scenario is creating JavaScript functions that wrap C++ +functions and returning those back to JavaScript:

      +
      // addon.cc
      +#include <node.h>
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void MyFunction(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  args.GetReturnValue().Set(String::NewFromUtf8(
      +      isolate, "hello world", NewStringType::kNormal).ToLocalChecked());
      +}
      +
      +void CreateFunction(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
      +  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();
      +
      +  // omit this to make it anonymous
      +  fn->SetName(String::NewFromUtf8(
      +      isolate, "theFunction", NewStringType::kNormal).ToLocalChecked());
      +
      +  args.GetReturnValue().Set(fn);
      +}
      +
      +void Init(Local<Object> exports, Local<Object> module) {
      +  NODE_SET_METHOD(module, "exports", CreateFunction);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
      +
      +}  // namespace demo
      +

      To test:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const fn = addon();
      +console.log(fn());
      +// Prints: 'hello world'
      +

      Wrapping C++ objects#

      +

      It is also possible to wrap C++ objects/classes in a way that allows new +instances to be created using the JavaScript new operator:

      +
      // addon.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::Local;
      +using v8::Object;
      +
      +void InitAll(Local<Object> exports) {
      +  MyObject::Init(exports);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
      +
      +}  // namespace demo
      +

      Then, in myobject.h, the wrapper class inherits from node::ObjectWrap:

      +
      // myobject.h
      +#ifndef MYOBJECT_H
      +#define MYOBJECT_H
      +
      +#include <node.h>
      +#include <node_object_wrap.h>
      +
      +namespace demo {
      +
      +class MyObject : public node::ObjectWrap {
      + public:
      +  static void Init(v8::Local<v8::Object> exports);
      +
      + private:
      +  explicit MyObject(double value = 0);
      +  ~MyObject();
      +
      +  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
      +
      +  double value_;
      +};
      +
      +}  // namespace demo
      +
      +#endif
      +

      In myobject.cc, implement the various methods that are to be exposed. +Below, the method plusOne() is exposed by adding it to the constructor's +prototype:

      +
      // myobject.cc
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Number;
      +using v8::Object;
      +using v8::ObjectTemplate;
      +using v8::String;
      +using v8::Value;
      +
      +MyObject::MyObject(double value) : value_(value) {
      +}
      +
      +MyObject::~MyObject() {
      +}
      +
      +void MyObject::Init(Local<Object> exports) {
      +  Isolate* isolate = exports->GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);
      +  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()
      +  Local<Object> addon_data =
      +      addon_data_tpl->NewInstance(context).ToLocalChecked();
      +
      +  // Prepare constructor template
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);
      +  tpl->SetClassName(String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
      +  tpl->InstanceTemplate()->SetInternalFieldCount(1);
      +
      +  // Prototype
      +  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
      +
      +  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();
      +  addon_data->SetInternalField(0, constructor);
      +  exports->Set(context, String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked(),
      +               constructor).FromJust();
      +}
      +
      +void MyObject::New(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  if (args.IsConstructCall()) {
      +    // Invoked as constructor: `new MyObject(...)`
      +    double value = args[0]->IsUndefined() ?
      +        0 : args[0]->NumberValue(context).FromMaybe(0);
      +    MyObject* obj = new MyObject(value);
      +    obj->Wrap(args.This());
      +    args.GetReturnValue().Set(args.This());
      +  } else {
      +    // Invoked as plain function `MyObject(...)`, turn into construct call.
      +    const int argc = 1;
      +    Local<Value> argv[argc] = { args[0] };
      +    Local<Function> cons =
      +        args.Data().As<Object>()->GetInternalField(0).As<Function>();
      +    Local<Object> result =
      +        cons->NewInstance(context, argc, argv).ToLocalChecked();
      +    args.GetReturnValue().Set(result);
      +  }
      +}
      +
      +void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
      +  obj->value_ += 1;
      +
      +  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
      +}
      +
      +}  // namespace demo
      +

      To build this example, the myobject.cc file must be added to the +binding.gyp:

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [
      +        "addon.cc",
      +        "myobject.cc"
      +      ]
      +    }
      +  ]
      +}
      +

      Test it with:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const obj = new addon.MyObject(10);
      +console.log(obj.plusOne());
      +// Prints: 11
      +console.log(obj.plusOne());
      +// Prints: 12
      +console.log(obj.plusOne());
      +// Prints: 13
      +

      The destructor for a wrapper object will run when the object is +garbage-collected. For destructor testing, there are command-line flags that +can be used to make it possible to force garbage collection. These flags are +provided by the underlying V8 JavaScript engine. They are subject to change +or removal at any time. They are not documented by Node.js or V8, and they +should never be used outside of testing.

      +

      Factory of wrapped objects#

      +

      Alternatively, it is possible to use a factory pattern to avoid explicitly +creating object instances using the JavaScript new operator:

      +
      const obj = addon.createObject();
      +// instead of:
      +// const obj = new addon.Object();
      +

      First, the createObject() method is implemented in addon.cc:

      +
      // addon.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void CreateObject(const FunctionCallbackInfo<Value>& args) {
      +  MyObject::NewInstance(args);
      +}
      +
      +void InitAll(Local<Object> exports, Local<Object> module) {
      +  MyObject::Init(exports->GetIsolate());
      +
      +  NODE_SET_METHOD(module, "exports", CreateObject);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
      +
      +}  // namespace demo
      +

      In myobject.h, the static method NewInstance() is added to handle +instantiating the object. This method takes the place of using new in +JavaScript:

      +
      // myobject.h
      +#ifndef MYOBJECT_H
      +#define MYOBJECT_H
      +
      +#include <node.h>
      +#include <node_object_wrap.h>
      +
      +namespace demo {
      +
      +class MyObject : public node::ObjectWrap {
      + public:
      +  static void Init(v8::Isolate* isolate);
      +  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
      +
      + private:
      +  explicit MyObject(double value = 0);
      +  ~MyObject();
      +
      +  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static v8::Global<v8::Function> constructor;
      +  double value_;
      +};
      +
      +}  // namespace demo
      +
      +#endif
      +

      The implementation in myobject.cc is similar to the previous example:

      +
      // myobject.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using node::AddEnvironmentCleanupHook;
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Global;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Number;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +// Warning! This is not thread-safe, this addon cannot be used for worker
      +// threads.
      +Global<Function> MyObject::constructor;
      +
      +MyObject::MyObject(double value) : value_(value) {
      +}
      +
      +MyObject::~MyObject() {
      +}
      +
      +void MyObject::Init(Isolate* isolate) {
      +  // Prepare constructor template
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
      +  tpl->SetClassName(String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
      +  tpl->InstanceTemplate()->SetInternalFieldCount(1);
      +
      +  // Prototype
      +  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
      +
      +  Local<Context> context = isolate->GetCurrentContext();
      +  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
      +
      +  AddEnvironmentCleanupHook(isolate, [](void*) {
      +    constructor.Reset();
      +  }, nullptr);
      +}
      +
      +void MyObject::New(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  if (args.IsConstructCall()) {
      +    // Invoked as constructor: `new MyObject(...)`
      +    double value = args[0]->IsUndefined() ?
      +        0 : args[0]->NumberValue(context).FromMaybe(0);
      +    MyObject* obj = new MyObject(value);
      +    obj->Wrap(args.This());
      +    args.GetReturnValue().Set(args.This());
      +  } else {
      +    // Invoked as plain function `MyObject(...)`, turn into construct call.
      +    const int argc = 1;
      +    Local<Value> argv[argc] = { args[0] };
      +    Local<Function> cons = Local<Function>::New(isolate, constructor);
      +    Local<Object> instance =
      +        cons->NewInstance(context, argc, argv).ToLocalChecked();
      +    args.GetReturnValue().Set(instance);
      +  }
      +}
      +
      +void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  const unsigned argc = 1;
      +  Local<Value> argv[argc] = { args[0] };
      +  Local<Function> cons = Local<Function>::New(isolate, constructor);
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<Object> instance =
      +      cons->NewInstance(context, argc, argv).ToLocalChecked();
      +
      +  args.GetReturnValue().Set(instance);
      +}
      +
      +void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
      +  obj->value_ += 1;
      +
      +  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
      +}
      +
      +}  // namespace demo
      +

      Once again, to build this example, the myobject.cc file must be added to the +binding.gyp:

      +
      {
      +  "targets": [
      +    {
      +      "target_name": "addon",
      +      "sources": [
      +        "addon.cc",
      +        "myobject.cc"
      +      ]
      +    }
      +  ]
      +}
      +

      Test it with:

      +
      // test.js
      +const createObject = require('./build/Release/addon');
      +
      +const obj = createObject(10);
      +console.log(obj.plusOne());
      +// Prints: 11
      +console.log(obj.plusOne());
      +// Prints: 12
      +console.log(obj.plusOne());
      +// Prints: 13
      +
      +const obj2 = createObject(20);
      +console.log(obj2.plusOne());
      +// Prints: 21
      +console.log(obj2.plusOne());
      +// Prints: 22
      +console.log(obj2.plusOne());
      +// Prints: 23
      +

      Passing wrapped objects around#

      +

      In addition to wrapping and returning C++ objects, it is possible to pass +wrapped objects around by unwrapping them with the Node.js helper function +node::ObjectWrap::Unwrap. The following examples shows a function add() +that can take two MyObject objects as input arguments:

      +
      // addon.cc
      +#include <node.h>
      +#include <node_object_wrap.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using v8::Context;
      +using v8::FunctionCallbackInfo;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::Number;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +void CreateObject(const FunctionCallbackInfo<Value>& args) {
      +  MyObject::NewInstance(args);
      +}
      +
      +void Add(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
      +      args[0]->ToObject(context).ToLocalChecked());
      +  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
      +      args[1]->ToObject(context).ToLocalChecked());
      +
      +  double sum = obj1->value() + obj2->value();
      +  args.GetReturnValue().Set(Number::New(isolate, sum));
      +}
      +
      +void InitAll(Local<Object> exports) {
      +  MyObject::Init(exports->GetIsolate());
      +
      +  NODE_SET_METHOD(exports, "createObject", CreateObject);
      +  NODE_SET_METHOD(exports, "add", Add);
      +}
      +
      +NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
      +
      +}  // namespace demo
      +

      In myobject.h, a new public method is added to allow access to private values +after unwrapping the object.

      +
      // myobject.h
      +#ifndef MYOBJECT_H
      +#define MYOBJECT_H
      +
      +#include <node.h>
      +#include <node_object_wrap.h>
      +
      +namespace demo {
      +
      +class MyObject : public node::ObjectWrap {
      + public:
      +  static void Init(v8::Isolate* isolate);
      +  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  inline double value() const { return value_; }
      +
      + private:
      +  explicit MyObject(double value = 0);
      +  ~MyObject();
      +
      +  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
      +  static v8::Global<v8::Function> constructor;
      +  double value_;
      +};
      +
      +}  // namespace demo
      +
      +#endif
      +

      The implementation of myobject.cc is similar to before:

      +
      // myobject.cc
      +#include <node.h>
      +#include "myobject.h"
      +
      +namespace demo {
      +
      +using node::AddEnvironmentCleanupHook;
      +using v8::Context;
      +using v8::Function;
      +using v8::FunctionCallbackInfo;
      +using v8::FunctionTemplate;
      +using v8::Global;
      +using v8::Isolate;
      +using v8::Local;
      +using v8::NewStringType;
      +using v8::Object;
      +using v8::String;
      +using v8::Value;
      +
      +// Warning! This is not thread-safe, this addon cannot be used for worker
      +// threads.
      +Global<Function> MyObject::constructor;
      +
      +MyObject::MyObject(double value) : value_(value) {
      +}
      +
      +MyObject::~MyObject() {
      +}
      +
      +void MyObject::Init(Isolate* isolate) {
      +  // Prepare constructor template
      +  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
      +  tpl->SetClassName(String::NewFromUtf8(
      +      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
      +  tpl->InstanceTemplate()->SetInternalFieldCount(1);
      +
      +  Local<Context> context = isolate->GetCurrentContext();
      +  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
      +
      +  AddEnvironmentCleanupHook(isolate, [](void*) {
      +    constructor.Reset();
      +  }, nullptr);
      +}
      +
      +void MyObject::New(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +  Local<Context> context = isolate->GetCurrentContext();
      +
      +  if (args.IsConstructCall()) {
      +    // Invoked as constructor: `new MyObject(...)`
      +    double value = args[0]->IsUndefined() ?
      +        0 : args[0]->NumberValue(context).FromMaybe(0);
      +    MyObject* obj = new MyObject(value);
      +    obj->Wrap(args.This());
      +    args.GetReturnValue().Set(args.This());
      +  } else {
      +    // Invoked as plain function `MyObject(...)`, turn into construct call.
      +    const int argc = 1;
      +    Local<Value> argv[argc] = { args[0] };
      +    Local<Function> cons = Local<Function>::New(isolate, constructor);
      +    Local<Object> instance =
      +        cons->NewInstance(context, argc, argv).ToLocalChecked();
      +    args.GetReturnValue().Set(instance);
      +  }
      +}
      +
      +void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
      +  Isolate* isolate = args.GetIsolate();
      +
      +  const unsigned argc = 1;
      +  Local<Value> argv[argc] = { args[0] };
      +  Local<Function> cons = Local<Function>::New(isolate, constructor);
      +  Local<Context> context = isolate->GetCurrentContext();
      +  Local<Object> instance =
      +      cons->NewInstance(context, argc, argv).ToLocalChecked();
      +
      +  args.GetReturnValue().Set(instance);
      +}
      +
      +}  // namespace demo
      +

      Test it with:

      +
      // test.js
      +const addon = require('./build/Release/addon');
      +
      +const obj1 = addon.createObject(10);
      +const obj2 = addon.createObject(20);
      +const result = addon.add(obj1, obj2);
      +
      +console.log(result);
      +// Prints: 30
      +

      N-API#

      + + +

      Stability: 2 - Stable

      +

      N-API (pronounced N as in the letter, followed by API) +is an API for building native Addons. It is independent from +the underlying JavaScript runtime (for example, V8) and is maintained as part of +Node.js itself. This API will be Application Binary Interface (ABI) stable +across versions of Node.js. It is intended to insulate Addons from +changes in the underlying JavaScript engine and allow modules +compiled for one major version to run on later major versions of Node.js without +recompilation. The ABI Stability guide provides a more in-depth explanation.

      +

      Addons are built/packaged with the same approach/tools outlined in the section +titled C++ Addons. The only difference is the set of APIs that are used by +the native code. Instead of using the V8 or Native Abstractions for Node.js +APIs, the functions available in the N-API are used.

      +

      APIs exposed by N-API are generally used to create and manipulate +JavaScript values. Concepts and operations generally map to ideas specified +in the ECMA-262 Language Specification. The APIs have the following +properties:

      +
        +
      • All N-API calls return a status code of type napi_status. This +status indicates whether the API call succeeded or failed.
      • +
      • The API's return value is passed via an out parameter.
      • +
      • All JavaScript values are abstracted behind an opaque type named +napi_value.
      • +
      • In case of an error status code, additional information can be obtained +using napi_get_last_error_info. More information can be found in the error +handling section Error handling.
      • +
      +

      The N-API is a C API that ensures ABI stability across Node.js versions +and different compiler levels. A C++ API can be easier to use. +To support using C++, the project maintains a +C++ wrapper module called node-addon-api. +This wrapper provides an inlineable C++ API. Binaries built +with node-addon-api will depend on the symbols for the N-API C-based +functions exported by Node.js. node-addon-api is a more +efficient way to write code that calls N-API. Take, for example, the +following node-addon-api code. The first section shows the +node-addon-api code and the second section shows what actually gets +used in the addon.

      +
      Object obj = Object::New(env);
      +obj["foo"] = String::New(env, "bar");
      +
      napi_status status;
      +napi_value object, string;
      +status = napi_create_object(env, &object);
      +if (status != napi_ok) {
      +  napi_throw_error(env, ...);
      +  return;
      +}
      +
      +status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string);
      +if (status != napi_ok) {
      +  napi_throw_error(env, ...);
      +  return;
      +}
      +
      +status = napi_set_named_property(env, object, "foo", string);
      +if (status != napi_ok) {
      +  napi_throw_error(env, ...);
      +  return;
      +}
      +

      The end result is that the addon only uses the exported C APIs. As a result, +it still gets the benefits of the ABI stability provided by the C API.

      +

      When using node-addon-api instead of the C APIs, start with the API docs +for node-addon-api.

      +

      The N-API Resource offers an +excellent orientation and tips for developers just getting started with N-API +and node-addon-api.

      +

      Implications of ABI stability#

      +

      Although N-API provides an ABI stability guarantee, other parts of Node.js do +not, and any external libraries used from the addon may not. In particular, +none of the following APIs provide an ABI stability guarantee across major +versions:

      +
        +
      • +

        the Node.js C++ APIs available via any of

        +
        #include <node.h>
        +#include <node_buffer.h>
        +#include <node_version.h>
        +#include <node_object_wrap.h>
        +
      • +
      • +

        the libuv APIs which are also included with Node.js and available via

        +
        #include <uv.h>
        +
      • +
      • +

        the V8 API available via

        +
        #include <v8.h>
        +
      • +
      +

      Thus, for an addon to remain ABI-compatible across Node.js major versions, it +must use N-API exclusively by restricting itself to using

      +
      #include <node_api.h>
      +

      and by checking, for all external libraries that it uses, that the external +library makes ABI stability guarantees similar to N-API.

      +

      Building#

      +

      Unlike modules written in JavaScript, developing and deploying Node.js +native addons using N-API requires an additional set of tools. Besides the +basic tools required to develop for Node.js, the native addon developer +requires a toolchain that can compile C and C++ code into a binary. In +addition, depending upon how the native addon is deployed, the user of +the native addon will also need to have a C/C++ toolchain installed.

      +

      For Linux developers, the necessary C/C++ toolchain packages are readily +available. GCC is widely used in the Node.js community to build and +test across a variety of platforms. For many developers, the LLVM +compiler infrastructure is also a good choice.

      +

      For Mac developers, Xcode offers all the required compiler tools. +However, it is not necessary to install the entire Xcode IDE. The following +command installs the necessary toolchain:

      +
      xcode-select --install
      +

      For Windows developers, Visual Studio offers all the required compiler +tools. However, it is not necessary to install the entire Visual Studio +IDE. The following command installs the necessary toolchain:

      +
      npm install --global windows-build-tools
      +

      The sections below describe the additional tools available for developing +and deploying Node.js native addons.

      +

      Build tools#

      +

      Both the tools listed here require that users of the native +addon have a C/C++ toolchain installed in order to successfully install +the native addon.

      +

      node-gyp#

      +

      node-gyp is a build system based on Google's GYP tool and comes +bundled with npm. GYP, and therefore node-gyp, requires that Python be +installed.

      +

      Historically, node-gyp has been the tool of choice for building native +addons. It has widespread adoption and documentation. However, some +developers have run into limitations in node-gyp.

      +

      CMake.js#

      +

      CMake.js is an alternative build system based on CMake.

      +

      CMake.js is a good choice for projects that already use CMake or for +developers affected by limitations in node-gyp.

      +

      Uploading precompiled binaries#

      +

      The three tools listed here permit native addon developers and maintainers +to create and upload binaries to public or private servers. These tools are +typically integrated with CI/CD build systems like Travis CI and +AppVeyor to build and upload binaries for a variety of platforms and +architectures. These binaries are then available for download by users who +do not need to have a C/C++ toolchain installed.

      +

      node-pre-gyp#

      +

      node-pre-gyp is a tool based on node-gyp that adds the ability to +upload binaries to a server of the developer's choice. node-pre-gyp has +particularly good support for uploading binaries to Amazon S3.

      +

      prebuild#

      +

      prebuild is a tool that supports builds using either node-gyp or +CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild +uploads binaries only to GitHub releases. prebuild is a good choice for +GitHub projects using CMake.js.

      +

      prebuildify#

      +

      prebuildify is a tool based on node-gyp. The advantage of prebuildify is +that the built binaries are bundled with the native module when it's +uploaded to npm. The binaries are downloaded from npm and are immediately +available to the module user when the native module is installed.

      +

      Usage#

      +

      In order to use the N-API functions, include the file node_api.h which is +located in the src directory in the node development tree:

      +
      #include <node_api.h>
      +

      This will opt into the default NAPI_VERSION for the given release of Node.js. +In order to ensure compatibility with specific versions of N-API, the version +can be specified explicitly when including the header:

      +
      #define NAPI_VERSION 3
      +#include <node_api.h>
      +

      This restricts the N-API surface to just the functionality that was available in +the specified (and earlier) versions.

      +

      Some of the N-API surface is experimental and requires explicit opt-in:

      +
      #define NAPI_EXPERIMENTAL
      +#include <node_api.h>
      +

      In this case the entire API surface, including any experimental APIs, will be +available to the module code.

      +

      N-API version matrix#

      +

      N-API versions are additive and versioned independently from Node.js. +Version 4 is an extension to version 3 in that it has all of the APIs +from version 3 with some additions. This means that it is not necessary +to recompile for new versions of Node.js which are +listed as supporting a later version.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      123456
      v6.xv6.14.2*
      v8.xv8.0.0*v8.10.0*v8.11.2v8.16.0
      v9.xv9.0.0*v9.3.0*v9.11.0*
      v10.xv10.0.0v10.0.0v10.0.0v10.16.0v10.17.0v10.20.0
      v11.xv11.0.0v11.0.0v11.0.0v11.8.0
      v12.xv12.0.0v12.0.0v12.0.0v12.0.0v12.11.0v12.17.0
      v13.xv13.0.0v13.0.0v13.0.0v13.0.0v13.0.0
      v14.xv14.0.0v14.0.0v14.0.0v14.0.0v14.0.0v14.0.0
      +

      * Indicates that the N-API version was released as experimental

      +

      Each API documented for N-API will have a header named added in:, and APIs +which are stable will have the additional header N-API version:. +APIs are directly usable when using a Node.js version which supports +the N-API version shown in N-API version: or higher. +When using a Node.js version that does not support the +N-API version: listed or if there is no N-API version: listed, +then the API will only be available if +#define NAPI_EXPERIMENTAL precedes the inclusion of node_api.h +or js_native_api.h. If an API appears not to be available on +a version of Node.js which is later than the one shown in added in: then +this is most likely the reason for the apparent absence.

      +

      The N-APIs associated strictly with accessing ECMAScript features from native +code can be found separately in js_native_api.h and js_native_api_types.h. +The APIs defined in these headers are included in node_api.h and +node_api_types.h. The headers are structured in this way in order to allow +implementations of N-API outside of Node.js. For those implementations the +Node.js specific APIs may not be applicable.

      +

      The Node.js-specific parts of an addon can be separated from the code that +exposes the actual functionality to the JavaScript environment so that the +latter may be used with multiple implementations of N-API. In the example below, +addon.c and addon.h refer only to js_native_api.h. This ensures that +addon.c can be reused to compile against either the Node.js implementation of +N-API or any implementation of N-API outside of Node.js.

      +

      addon_node.c is a separate file that contains the Node.js specific entry point +to the addon and which instantiates the addon by calling into addon.c when the +addon is loaded into a Node.js environment.

      +
      // addon.h
      +#ifndef _ADDON_H_
      +#define _ADDON_H_
      +#include <js_native_api.h>
      +napi_value create_addon(napi_env env);
      +#endif  // _ADDON_H_
      +
      // addon.c
      +#include "addon.h"
      +
      +#define NAPI_CALL(env, call)                                      \
      +  do {                                                            \
      +    napi_status status = (call);                                  \
      +    if (status != napi_ok) {                                      \
      +      const napi_extended_error_info* error_info = NULL;          \
      +      napi_get_last_error_info((env), &error_info);               \
      +      bool is_pending;                                            \
      +      napi_is_exception_pending((env), &is_pending);              \
      +      if (!is_pending) {                                          \
      +        const char* message = (error_info->error_message == NULL) \
      +            ? "empty error message"                               \
      +            : error_info->error_message;                          \
      +        napi_throw_error((env), NULL, message);                   \
      +        return NULL;                                              \
      +      }                                                           \
      +    }                                                             \
      +  } while(0)
      +
      +static napi_value
      +DoSomethingUseful(napi_env env, napi_callback_info info) {
      +  // Do something useful.
      +  return NULL;
      +}
      +
      +napi_value create_addon(napi_env env) {
      +  napi_value result;
      +  NAPI_CALL(env, napi_create_object(env, &result));
      +
      +  napi_value exported_function;
      +  NAPI_CALL(env, napi_create_function(env,
      +                                      "doSomethingUseful",
      +                                      NAPI_AUTO_LENGTH,
      +                                      DoSomethingUseful,
      +                                      NULL,
      +                                      &exported_function));
      +
      +  NAPI_CALL(env, napi_set_named_property(env,
      +                                         result,
      +                                         "doSomethingUseful",
      +                                         exported_function));
      +
      +  return result;
      +}
      +
      // addon_node.c
      +#include <node_api.h>
      +#include "addon.h"
      +
      +NAPI_MODULE_INIT() {
      +  // This function body is expected to return a `napi_value`.
      +  // The variables `napi_env env` and `napi_value exports` may be used within
      +  // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.
      +  return create_addon(env);
      +}
      +

      Environment life cycle APIs#

      +

      Section 8.7 of the ECMAScript Language Specification defines the concept +of an "Agent" as a self-contained environment in which JavaScript code runs. +Multiple such Agents may be started and terminated either concurrently or in +sequence by the process.

      +

      A Node.js environment corresponds to an ECMAScript Agent. In the main process, +an environment is created at startup, and additional environments can be created +on separate threads to serve as worker threads. When Node.js is embedded in +another application, the main thread of the application may also construct and +destroy a Node.js environment multiple times during the life cycle of the +application process such that each Node.js environment created by the +application may, in turn, during its life cycle create and destroy additional +environments as worker threads.

      +

      From the perspective of a native addon this means that the bindings it provides +may be called multiple times, from multiple contexts, and even concurrently from +multiple threads.

      +

      Native addons may need to allocate global state which they use during +their entire life cycle such that the state must be unique to each instance of +the addon.

      +

      To this end, N-API provides a way to allocate data such that its life cycle is +tied to the life cycle of the Agent.

      +

      napi_set_instance_data#

      + +
      napi_status napi_set_instance_data(napi_env env,
      +                                   void* data,
      +                                   napi_finalize finalize_cb,
      +                                   void* finalize_hint);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] data: The data item to make available to bindings of this instance.
      • +
      • [in] finalize_cb: The function to call when the environment is being torn +down. The function receives data so that it might free it. +napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API associates data with the currently running Agent. data can later +be retrieved using napi_get_instance_data(). Any existing data associated with +the currently running Agent which was set by means of a previous call to +napi_set_instance_data() will be overwritten. If a finalize_cb was provided +by the previous call, it will not be called.

      +

      napi_get_instance_data#

      + +
      napi_status napi_get_instance_data(napi_env env,
      +                                   void** data);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [out] data: The data item that was previously associated with the currently +running Agent by a call to napi_set_instance_data().
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API retrieves data that was previously associated with the currently +running Agent via napi_set_instance_data(). If no data is set, the call will +succeed and data will be set to NULL.

      +

      Basic N-API data types#

      +

      N-API exposes the following fundamental datatypes as abstractions that are +consumed by the various APIs. These APIs should be treated as opaque, +introspectable only with other N-API calls.

      +

      napi_status#

      + +

      Integral status code indicating the success or failure of a N-API call. +Currently, the following status codes are supported.

      +
      typedef enum {
      +  napi_ok,
      +  napi_invalid_arg,
      +  napi_object_expected,
      +  napi_string_expected,
      +  napi_name_expected,
      +  napi_function_expected,
      +  napi_number_expected,
      +  napi_boolean_expected,
      +  napi_array_expected,
      +  napi_generic_failure,
      +  napi_pending_exception,
      +  napi_cancelled,
      +  napi_escape_called_twice,
      +  napi_handle_scope_mismatch,
      +  napi_callback_scope_mismatch,
      +  napi_queue_full,
      +  napi_closing,
      +  napi_bigint_expected,
      +  napi_date_expected,
      +  napi_arraybuffer_expected,
      +  napi_detachable_arraybuffer_expected,
      +} napi_status;
      +

      If additional information is required upon an API returning a failed status, +it can be obtained by calling napi_get_last_error_info.

      +

      napi_extended_error_info#

      + +
      typedef struct {
      +  const char* error_message;
      +  void* engine_reserved;
      +  uint32_t engine_error_code;
      +  napi_status error_code;
      +} napi_extended_error_info;
      +
        +
      • error_message: UTF8-encoded string containing a VM-neutral description of +the error.
      • +
      • engine_reserved: Reserved for VM-specific error details. This is currently +not implemented for any VM.
      • +
      • engine_error_code: VM-specific error code. This is currently +not implemented for any VM.
      • +
      • error_code: The N-API status code that originated with the last error.
      • +
      +

      See the Error handling section for additional information.

      +

      napi_env#

      +

      napi_env is used to represent a context that the underlying N-API +implementation can use to persist VM-specific state. This structure is passed +to native functions when they're invoked, and it must be passed back when +making N-API calls. Specifically, the same napi_env that was passed in when +the initial native function was called must be passed to any subsequent +nested N-API calls. Caching the napi_env for the purpose of general reuse, +and passing the napi_env between instances of the same addon running on +different Worker threads is not allowed. The napi_env becomes invalid +when an instance of a native addon is unloaded. Notification of this event is +delivered through the callbacks given to napi_add_env_cleanup_hook and +napi_set_instance_data.

      +

      napi_value#

      +

      This is an opaque pointer that is used to represent a JavaScript value.

      +

      napi_threadsafe_function#

      + +

      This is an opaque pointer that represents a JavaScript function which can be +called asynchronously from multiple threads via +napi_call_threadsafe_function().

      +

      napi_threadsafe_function_release_mode#

      + +

      A value to be given to napi_release_threadsafe_function() to indicate whether +the thread-safe function is to be closed immediately (napi_tsfn_abort) or +merely released (napi_tsfn_release) and thus available for subsequent use via +napi_acquire_threadsafe_function() and napi_call_threadsafe_function().

      +
      typedef enum {
      +  napi_tsfn_release,
      +  napi_tsfn_abort
      +} napi_threadsafe_function_release_mode;
      +

      napi_threadsafe_function_call_mode#

      + +

      A value to be given to napi_call_threadsafe_function() to indicate whether +the call should block whenever the queue associated with the thread-safe +function is full.

      +
      typedef enum {
      +  napi_tsfn_nonblocking,
      +  napi_tsfn_blocking
      +} napi_threadsafe_function_call_mode;
      +

      N-API memory management types#

      +

      napi_handle_scope#

      +

      This is an abstraction used to control and modify the lifetime of objects +created within a particular scope. In general, N-API values are created within +the context of a handle scope. When a native method is called from +JavaScript, a default handle scope will exist. If the user does not explicitly +create a new handle scope, N-API values will be created in the default handle +scope. For any invocations of code outside the execution of a native method +(for instance, during a libuv callback invocation), the module is required to +create a scope before invoking any functions that can result in the creation +of JavaScript values.

      +

      Handle scopes are created using napi_open_handle_scope and are destroyed +using napi_close_handle_scope. Closing the scope can indicate to the GC +that all napi_values created during the lifetime of the handle scope are no +longer referenced from the current stack frame.

      +

      For more details, review the Object lifetime management.

      +

      napi_escapable_handle_scope#

      + +

      Escapable handle scopes are a special type of handle scope to return values +created within a particular handle scope to a parent scope.

      +

      napi_ref#

      + +

      This is the abstraction to use to reference a napi_value. This allows for +users to manage the lifetimes of JavaScript values, including defining their +minimum lifetimes explicitly.

      +

      For more details, review the Object lifetime management.

      +

      napi_type_tag#

      + +

      A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID +with which JavaScript objects can be "tagged" in order to ensure that they are +of a certain type. This is a stronger check than napi_instanceof, because +the latter can report a false positive if the object's prototype has been +manipulated. Type-tagging is most useful in conjunction with napi_wrap +because it ensures that the pointer retrieved from a wrapped object can be +safely cast to the native type corresponding to the type tag that had been +previously applied to the JavaScript object.

      +
      typedef struct {
      +  uint64_t lower;
      +  uint64_t upper;
      +} napi_type_tag;
      +

      napi_async_cleanup_hook_handle#

      + +

      An opaque value returned by napi_add_async_cleanup_hook. It must be passed +to napi_remove_async_cleanup_hook when the chain of asynchronous cleanup +events completes.

      +

      N-API callback types#

      +

      napi_callback_info#

      + +

      Opaque datatype that is passed to a callback function. It can be used for +getting additional information about the context in which the callback was +invoked.

      +

      napi_callback#

      + +

      Function pointer type for user-provided native functions which are to be +exposed to JavaScript via N-API. Callback functions should satisfy the +following signature:

      +
      typedef napi_value (*napi_callback)(napi_env, napi_callback_info);
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside a napi_callback is not necessary.

      +

      napi_finalize#

      + +

      Function pointer type for add-on provided functions that allow the user to be +notified when externally-owned data is ready to be cleaned up because the +object with which it was associated with, has been garbage-collected. The user +must provide a function satisfying the following signature which would get +called upon the object's collection. Currently, napi_finalize can be used for +finding out when objects that have external data are collected.

      +
      typedef void (*napi_finalize)(napi_env env,
      +                              void* finalize_data,
      +                              void* finalize_hint);
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside the function body is not necessary.

      +

      napi_async_execute_callback#

      + +

      Function pointer used with functions that support asynchronous +operations. Callback functions must satisfy the following signature:

      +
      typedef void (*napi_async_execute_callback)(napi_env env, void* data);
      +

      Implementations of this function must avoid making N-API calls that execute +JavaScript or interact with JavaScript objects. N-API calls should be in the +napi_async_complete_callback instead. Do not use the napi_env parameter as +it will likely result in execution of JavaScript.

      +

      napi_async_complete_callback#

      + +

      Function pointer used with functions that support asynchronous +operations. Callback functions must satisfy the following signature:

      +
      typedef void (*napi_async_complete_callback)(napi_env env,
      +                                             napi_status status,
      +                                             void* data);
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside the function body is not necessary.

      +

      napi_threadsafe_function_call_js#

      + +

      Function pointer used with asynchronous thread-safe function calls. The callback +will be called on the main thread. Its purpose is to use a data item arriving +via the queue from one of the secondary threads to construct the parameters +necessary for a call into JavaScript, usually via napi_call_function, and then +make the call into JavaScript.

      +

      The data arriving from the secondary thread via the queue is given in the data +parameter and the JavaScript function to call is given in the js_callback +parameter.

      +

      N-API sets up the environment prior to calling this callback, so it is +sufficient to call the JavaScript function via napi_call_function rather than +via napi_make_callback.

      +

      Callback functions must satisfy the following signature:

      +
      typedef void (*napi_threadsafe_function_call_js)(napi_env env,
      +                                                 napi_value js_callback,
      +                                                 void* context,
      +                                                 void* data);
      +
        +
      • [in] env: The environment to use for API calls, or NULL if the thread-safe +function is being torn down and data may need to be freed.
      • +
      • [in] js_callback: The JavaScript function to call, or NULL if the +thread-safe function is being torn down and data may need to be freed. It +may also be NULL if the thread-safe function was created without +js_callback.
      • +
      • [in] context: The optional data with which the thread-safe function was +created.
      • +
      • [in] data: Data created by the secondary thread. It is the responsibility of +the callback to convert this native data to JavaScript values (with N-API +functions) that can be passed as parameters when js_callback is invoked. +This pointer is managed entirely by the threads and this callback. Thus this +callback should free the data.
      • +
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside the function body is not necessary.

      +

      napi_async_cleanup_hook#

      + +

      Function pointer used with napi_add_async_cleanup_hook. It will be called +when the environment is being torn down.

      +

      Callback functions must satisfy the following signature:

      +
      typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,
      +                                        void* data);
      + +

      The body of the function should initiate the asynchronous cleanup actions at the +end of which handle must be passed in a call to +napi_remove_async_cleanup_hook.

      +

      Error handling#

      +

      N-API uses both return values and JavaScript exceptions for error handling. +The following sections explain the approach for each case.

      +

      Return values#

      +

      All of the N-API functions share the same error handling pattern. The +return type of all API functions is napi_status.

      +

      The return value will be napi_ok if the request was successful and +no uncaught JavaScript exception was thrown. If an error occurred AND +an exception was thrown, the napi_status value for the error +will be returned. If an exception was thrown, and no error occurred, +napi_pending_exception will be returned.

      +

      In cases where a return value other than napi_ok or +napi_pending_exception is returned, napi_is_exception_pending +must be called to check if an exception is pending. +See the section on exceptions for more details.

      +

      The full set of possible napi_status values is defined +in napi_api_types.h.

      +

      The napi_status return value provides a VM-independent representation of +the error which occurred. In some cases it is useful to be able to get +more detailed information, including a string representing the error as well as +VM (engine)-specific information.

      +

      In order to retrieve this information napi_get_last_error_info +is provided which returns a napi_extended_error_info structure. +The format of the napi_extended_error_info structure is as follows:

      + +
      typedef struct napi_extended_error_info {
      +  const char* error_message;
      +  void* engine_reserved;
      +  uint32_t engine_error_code;
      +  napi_status error_code;
      +};
      +
        +
      • error_message: Textual representation of the error that occurred.
      • +
      • engine_reserved: Opaque handle reserved for engine use only.
      • +
      • engine_error_code: VM specific error code.
      • +
      • error_code: n-api status code for the last error.
      • +
      +

      napi_get_last_error_info returns the information for the last +N-API call that was made.

      +

      Do not rely on the content or format of any of the extended information as it +is not subject to SemVer and may change at any time. It is intended only for +logging purposes.

      +

      napi_get_last_error_info#

      + +
      napi_status
      +napi_get_last_error_info(napi_env env,
      +                         const napi_extended_error_info** result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: The napi_extended_error_info structure with more +information about the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API retrieves a napi_extended_error_info structure with information +about the last error that occurred.

      +

      The content of the napi_extended_error_info returned is only valid up until +an n-api function is called on the same env.

      +

      Do not rely on the content or format of any of the extended information as it +is not subject to SemVer and may change at any time. It is intended only for +logging purposes.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Exceptions#

      +

      Any N-API function call may result in a pending JavaScript exception. This is +the case for any of the API functions, even those that may not cause the +execution of JavaScript.

      +

      If the napi_status returned by a function is napi_ok then no +exception is pending and no additional action is required. If the +napi_status returned is anything other than napi_ok or +napi_pending_exception, in order to try to recover and continue +instead of simply returning immediately, napi_is_exception_pending +must be called in order to determine if an exception is pending or not.

      +

      In many cases when an N-API function is called and an exception is +already pending, the function will return immediately with a +napi_status of napi_pending_exception. However, this is not the case +for all functions. N-API allows a subset of the functions to be +called to allow for some minimal cleanup before returning to JavaScript. +In that case, napi_status will reflect the status for the function. It +will not reflect previous pending exceptions. To avoid confusion, check +the error status after every function call.

      +

      When an exception is pending one of two approaches can be employed.

      +

      The first approach is to do any appropriate cleanup and then return so that +execution will return to JavaScript. As part of the transition back to +JavaScript, the exception will be thrown at the point in the JavaScript +code where the native method was invoked. The behavior of most N-API calls +is unspecified while an exception is pending, and many will simply return +napi_pending_exception, so do as little as possible and then return to +JavaScript where the exception can be handled.

      +

      The second approach is to try to handle the exception. There will be cases +where the native code can catch the exception, take the appropriate action, +and then continue. This is only recommended in specific cases +where it is known that the exception can be safely handled. In these +cases napi_get_and_clear_last_exception can be used to get and +clear the exception. On success, result will contain the handle to +the last JavaScript Object thrown. If it is determined, after +retrieving the exception, the exception cannot be handled after all +it can be re-thrown it with napi_throw where error is the +JavaScript Error object to be thrown.

      +

      The following utility functions are also available in case native code +needs to throw an exception or determine if a napi_value is an instance +of a JavaScript Error object: napi_throw_error, +napi_throw_type_error, napi_throw_range_error and +napi_is_error.

      +

      The following utility functions are also available in case native +code needs to create an Error object: napi_create_error, +napi_create_type_error, and napi_create_range_error, +where result is the napi_value that refers to the newly created +JavaScript Error object.

      +

      The Node.js project is adding error codes to all of the errors +generated internally. The goal is for applications to use these +error codes for all error checking. The associated error messages +will remain, but will only be meant to be used for logging and +display with the expectation that the message can change without +SemVer applying. In order to support this model with N-API, both +in internal functionality and for module specific functionality +(as its good practice), the throw_ and create_ functions +take an optional code parameter which is the string for the code +to be added to the error object. If the optional parameter is NULL +then no code will be associated with the error. If a code is provided, +the name associated with the error is also updated to be:

      +
      originalName [code]
      +

      where originalName is the original name associated with the error +and code is the code that was provided. For example, if the code +is 'ERR_ERROR_1' and a TypeError is being created the name will be:

      +
      TypeError [ERR_ERROR_1]
      +

      napi_throw#

      + +
      NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] error: The JavaScript value to be thrown.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws the JavaScript value provided.

      +

      napi_throw_error#

      + +
      NAPI_EXTERN napi_status napi_throw_error(napi_env env,
      +                                         const char* code,
      +                                         const char* msg);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional error code to be set on the error.
      • +
      • [in] msg: C string representing the text to be associated with the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws a JavaScript Error with the text provided.

      +

      napi_throw_type_error#

      + +
      NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,
      +                                              const char* code,
      +                                              const char* msg);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional error code to be set on the error.
      • +
      • [in] msg: C string representing the text to be associated with the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws a JavaScript TypeError with the text provided.

      +

      napi_throw_range_error#

      + +
      NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,
      +                                               const char* code,
      +                                               const char* msg);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional error code to be set on the error.
      • +
      • [in] msg: C string representing the text to be associated with the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws a JavaScript RangeError with the text provided.

      +

      napi_is_error#

      + +
      NAPI_EXTERN napi_status napi_is_error(napi_env env,
      +                                      napi_value value,
      +                                      bool* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The napi_value to be checked.
      • +
      • [out] result: Boolean value that is set to true if napi_value represents +an error, false otherwise.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API queries a napi_value to check if it represents an error object.

      +

      napi_create_error#

      + +
      NAPI_EXTERN napi_status napi_create_error(napi_env env,
      +                                          napi_value code,
      +                                          napi_value msg,
      +                                          napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional napi_value with the string for the error code to be +associated with the error.
      • +
      • [in] msg: napi_value that references a JavaScript String to be used as +the message for the Error.
      • +
      • [out] result: napi_value representing the error created.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns a JavaScript Error with the text provided.

      +

      napi_create_type_error#

      + +
      NAPI_EXTERN napi_status napi_create_type_error(napi_env env,
      +                                               napi_value code,
      +                                               napi_value msg,
      +                                               napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional napi_value with the string for the error code to be +associated with the error.
      • +
      • [in] msg: napi_value that references a JavaScript String to be used as +the message for the Error.
      • +
      • [out] result: napi_value representing the error created.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns a JavaScript TypeError with the text provided.

      +

      napi_create_range_error#

      + +
      NAPI_EXTERN napi_status napi_create_range_error(napi_env env,
      +                                                napi_value code,
      +                                                napi_value msg,
      +                                                napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional napi_value with the string for the error code to be +associated with the error.
      • +
      • [in] msg: napi_value that references a JavaScript String to be used as +the message for the Error.
      • +
      • [out] result: napi_value representing the error created.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns a JavaScript RangeError with the text provided.

      +

      napi_get_and_clear_last_exception#

      + +
      napi_status napi_get_and_clear_last_exception(napi_env env,
      +                                              napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: The exception if one is pending, NULL otherwise.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_is_exception_pending#

      + +
      napi_status napi_is_exception_pending(napi_env env, bool* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: Boolean value that is set to true if an exception is pending.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_fatal_exception#

      + +
      napi_status napi_fatal_exception(napi_env env, napi_value err);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] err: The error that is passed to 'uncaughtException'.
      • +
      +

      Trigger an 'uncaughtException' in JavaScript. Useful if an async +callback throws an exception with no way to recover.

      +

      Fatal errors#

      +

      In the event of an unrecoverable error in a native module, a fatal error can be +thrown to immediately terminate the process.

      +

      napi_fatal_error#

      + +
      NAPI_NO_RETURN void napi_fatal_error(const char* location,
      +                                                 size_t location_len,
      +                                                 const char* message,
      +                                                 size_t message_len);
      +
        +
      • [in] location: Optional location at which the error occurred.
      • +
      • [in] location_len: The length of the location in bytes, or +NAPI_AUTO_LENGTH if it is null-terminated.
      • +
      • [in] message: The message associated with the error.
      • +
      • [in] message_len: The length of the message in bytes, or NAPI_AUTO_LENGTH +if it is null-terminated.
      • +
      +

      The function call does not return, the process will be terminated.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Object lifetime management#

      +

      As N-API calls are made, handles to objects in the heap for the underlying +VM may be returned as napi_values. These handles must hold the +objects 'live' until they are no longer required by the native code, +otherwise the objects could be collected before the native code was +finished using them.

      +

      As object handles are returned they are associated with a +'scope'. The lifespan for the default scope is tied to the lifespan +of the native method call. The result is that, by default, handles +remain valid and the objects associated with these handles will be +held live for the lifespan of the native method call.

      +

      In many cases, however, it is necessary that the handles remain valid for +either a shorter or longer lifespan than that of the native method. +The sections which follow describe the N-API functions that can be used +to change the handle lifespan from the default.

      +

      Making handle lifespan shorter than that of the native method#

      +

      It is often necessary to make the lifespan of handles shorter than +the lifespan of a native method. For example, consider a native method +that has a loop which iterates through the elements in a large array:

      +
      for (int i = 0; i < 1000000; i++) {
      +  napi_value result;
      +  napi_status status = napi_get_element(env, object, i, &result);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +  // do something with element
      +}
      +

      This would result in a large number of handles being created, consuming +substantial resources. In addition, even though the native code could only +use the most recent handle, all of the associated objects would also be +kept alive since they all share the same scope.

      +

      To handle this case, N-API provides the ability to establish a new 'scope' to +which newly created handles will be associated. Once those handles +are no longer required, the scope can be 'closed' and any handles associated +with the scope are invalidated. The methods available to open/close scopes are +napi_open_handle_scope and napi_close_handle_scope.

      +

      N-API only supports a single nested hierarchy of scopes. There is only one +active scope at any time, and all new handles will be associated with that +scope while it is active. Scopes must be closed in the reverse order from +which they are opened. In addition, all scopes created within a native method +must be closed before returning from that method.

      +

      Taking the earlier example, adding calls to napi_open_handle_scope and +napi_close_handle_scope would ensure that at most a single handle +is valid throughout the execution of the loop:

      +
      for (int i = 0; i < 1000000; i++) {
      +  napi_handle_scope scope;
      +  napi_status status = napi_open_handle_scope(env, &scope);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +  napi_value result;
      +  status = napi_get_element(env, object, i, &result);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +  // do something with element
      +  status = napi_close_handle_scope(env, scope);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +}
      +

      When nesting scopes, there are cases where a handle from an +inner scope needs to live beyond the lifespan of that scope. N-API supports an +'escapable scope' in order to support this case. An escapable scope +allows one handle to be 'promoted' so that it 'escapes' the +current scope and the lifespan of the handle changes from the current +scope to that of the outer scope.

      +

      The methods available to open/close escapable scopes are +napi_open_escapable_handle_scope and +napi_close_escapable_handle_scope.

      +

      The request to promote a handle is made through napi_escape_handle which +can only be called once.

      +

      napi_open_handle_scope#

      + +
      NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,
      +                                               napi_handle_scope* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing the new scope.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API opens a new scope.

      +

      napi_close_handle_scope#

      + +
      NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,
      +                                                napi_handle_scope scope);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: napi_value representing the scope to be closed.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API closes the scope passed in. Scopes must be closed in the +reverse order from which they were created.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_open_escapable_handle_scope#

      + +
      NAPI_EXTERN napi_status
      +    napi_open_escapable_handle_scope(napi_env env,
      +                                     napi_handle_scope* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing the new scope.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API opens a new scope from which one object can be promoted +to the outer scope.

      +

      napi_close_escapable_handle_scope#

      + +
      NAPI_EXTERN napi_status
      +    napi_close_escapable_handle_scope(napi_env env,
      +                                      napi_handle_scope scope);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: napi_value representing the scope to be closed.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API closes the scope passed in. Scopes must be closed in the +reverse order from which they were created.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_escape_handle#

      + +
      napi_status napi_escape_handle(napi_env env,
      +                               napi_escapable_handle_scope scope,
      +                               napi_value escapee,
      +                               napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: napi_value representing the current scope.
      • +
      • [in] escapee: napi_value representing the JavaScript Object to be +escaped.
      • +
      • [out] result: napi_value representing the handle to the escaped Object +in the outer scope.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API promotes the handle to the JavaScript object so that it is valid +for the lifetime of the outer scope. It can only be called once per scope. +If it is called more than once an error will be returned.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      References to objects with a lifespan longer than that of the native method#

      +

      In some cases an addon will need to be able to create and reference objects +with a lifespan longer than that of a single native method invocation. For +example, to create a constructor and later use that constructor +in a request to creates instances, it must be possible to reference +the constructor object across many different instance creation requests. This +would not be possible with a normal handle returned as a napi_value as +described in the earlier section. The lifespan of a normal handle is +managed by scopes and all scopes must be closed before the end of a native +method.

      +

      N-API provides methods to create persistent references to an object. +Each persistent reference has an associated count with a value of 0 +or higher. The count determines if the reference will keep +the corresponding object live. References with a count of 0 do not +prevent the object from being collected and are often called 'weak' +references. Any count greater than 0 will prevent the object +from being collected.

      +

      References can be created with an initial reference count. The count can +then be modified through napi_reference_ref and +napi_reference_unref. If an object is collected while the count +for a reference is 0, all subsequent calls to +get the object associated with the reference napi_get_reference_value +will return NULL for the returned napi_value. An attempt to call +napi_reference_ref for a reference whose object has been collected +will result in an error.

      +

      References must be deleted once they are no longer required by the addon. When +a reference is deleted it will no longer prevent the corresponding object from +being collected. Failure to delete a persistent reference will result in +a 'memory leak' with both the native memory for the persistent reference and +the corresponding object on the heap being retained forever.

      +

      There can be multiple persistent references created which refer to the same +object, each of which will either keep the object live or not based on its +individual count.

      +

      napi_create_reference#

      + +
      NAPI_EXTERN napi_status napi_create_reference(napi_env env,
      +                                              napi_value value,
      +                                              uint32_t initial_refcount,
      +                                              napi_ref* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing the Object to which we want a +reference.
      • +
      • [in] initial_refcount: Initial reference count for the new reference.
      • +
      • [out] result: napi_ref pointing to the new reference.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API create a new reference with the specified reference count +to the Object passed in.

      +

      napi_delete_reference#

      + +
      NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref to be deleted.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API deletes the reference passed in.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_reference_ref#

      + +
      NAPI_EXTERN napi_status napi_reference_ref(napi_env env,
      +                                           napi_ref ref,
      +                                           uint32_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref for which the reference count will be incremented.
      • +
      • [out] result: The new reference count.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API increments the reference count for the reference +passed in and returns the resulting reference count.

      +

      napi_reference_unref#

      + +
      NAPI_EXTERN napi_status napi_reference_unref(napi_env env,
      +                                             napi_ref ref,
      +                                             uint32_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref for which the reference count will be decremented.
      • +
      • [out] result: The new reference count.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API decrements the reference count for the reference +passed in and returns the resulting reference count.

      +

      napi_get_reference_value#

      + +
      NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,
      +                                                 napi_ref ref,
      +                                                 napi_value* result);
      +

      the napi_value passed in or out of these methods is a handle to the +object to which the reference is related.

      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref for which we requesting the corresponding Object.
      • +
      • [out] result: The napi_value for the Object referenced by the +napi_ref.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      If still valid, this API returns the napi_value representing the +JavaScript Object associated with the napi_ref. Otherwise, result +will be NULL.

      +

      Cleanup on exit of the current Node.js instance#

      +

      While a Node.js process typically releases all its resources when exiting, +embedders of Node.js, or future Worker support, may require addons to register +clean-up hooks that will be run once the current Node.js instance exits.

      +

      N-API provides functions for registering and un-registering such callbacks. +When those callbacks are run, all resources that are being held by the addon +should be freed up.

      +

      napi_add_env_cleanup_hook#

      + +
      NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,
      +                                                  void (*fun)(void* arg),
      +                                                  void* arg);
      +

      Registers fun as a function to be run with the arg parameter once the +current Node.js environment exits.

      +

      A function can safely be specified multiple times with different +arg values. In that case, it will be called multiple times as well. +Providing the same fun and arg values multiple times is not allowed +and will lead the process to abort.

      +

      The hooks will be called in reverse order, i.e. the most recently added one +will be called first.

      +

      Removing this hook can be done by using napi_remove_env_cleanup_hook. +Typically, that happens when the resource for which this hook was added +is being torn down anyway.

      +

      For asynchronous cleanup, napi_add_async_cleanup_hook is available.

      +

      napi_remove_env_cleanup_hook#

      + +
      NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,
      +                                                     void (*fun)(void* arg),
      +                                                     void* arg);
      +

      Unregisters fun as a function to be run with the arg parameter once the +current Node.js environment exits. Both the argument and the function value +need to be exact matches.

      +

      The function must have originally been registered +with napi_add_env_cleanup_hook, otherwise the process will abort.

      +

      napi_add_async_cleanup_hook#

      + +
      NAPI_EXTERN napi_status napi_add_async_cleanup_hook(
      +    napi_env env,
      +    napi_async_cleanup_hook hook,
      +    void* arg,
      +    napi_async_cleanup_hook_handle* remove_handle);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] hook: The function pointer to call at environment teardown.
      • +
      • [in] arg: The pointer to pass to hook when it gets called.
      • +
      • [out] remove_handle: Optional handle that refers to the asynchronous cleanup +hook.
      • +
      +

      Registers hook, which is a function of type napi_async_cleanup_hook, as +a function to be run with the remove_handle and arg parameters once the +current Node.js environment exits.

      +

      Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.

      +

      Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.

      +

      If remove_handle is not NULL, an opaque value will be stored in it +that must later be passed to napi_remove_async_cleanup_hook, +regardless of whether the hook has already been invoked. +Typically, that happens when the resource for which this hook was added +is being torn down anyway.

      +

      napi_remove_async_cleanup_hook#

      + +
      NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(
      +    napi_async_cleanup_hook_handle remove_handle);
      + +

      Unregisters the cleanup hook corresponding to remove_handle. This will prevent +the hook from being executed, unless it has already started executing. +This must be called on any napi_async_cleanup_hook_handle value obtained +from napi_add_async_cleanup_hook.

      +

      Module registration#

      +

      N-API modules are registered in a manner similar to other modules +except that instead of using the NODE_MODULE macro the following +is used:

      +
      NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
      +

      The next difference is the signature for the Init method. For a N-API +module it is as follows:

      +
      napi_value Init(napi_env env, napi_value exports);
      +

      The return value from Init is treated as the exports object for the module. +The Init method is passed an empty object via the exports parameter as a +convenience. If Init returns NULL, the parameter passed as exports is +exported by the module. N-API modules cannot modify the module object but can +specify anything as the exports property of the module.

      +

      To add the method hello as a function so that it can be called as a method +provided by the addon:

      +
      napi_value Init(napi_env env, napi_value exports) {
      +  napi_status status;
      +  napi_property_descriptor desc = {
      +    "hello",
      +    NULL,
      +    Method,
      +    NULL,
      +    NULL,
      +    NULL,
      +    napi_writable | napi_enumerable | napi_configurable,
      +    NULL
      +  };
      +  status = napi_define_properties(env, exports, 1, &desc);
      +  if (status != napi_ok) return NULL;
      +  return exports;
      +}
      +

      To set a function to be returned by the require() for the addon:

      +
      napi_value Init(napi_env env, napi_value exports) {
      +  napi_value method;
      +  napi_status status;
      +  status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method);
      +  if (status != napi_ok) return NULL;
      +  return method;
      +}
      +

      To define a class so that new instances can be created (often used with +Object wrap):

      +
      // NOTE: partial example, not all referenced code is included
      +napi_value Init(napi_env env, napi_value exports) {
      +  napi_status status;
      +  napi_property_descriptor properties[] = {
      +    { "value", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL },
      +    DECLARE_NAPI_METHOD("plusOne", PlusOne),
      +    DECLARE_NAPI_METHOD("multiply", Multiply),
      +  };
      +
      +  napi_value cons;
      +  status =
      +      napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_create_reference(env, cons, 1, &constructor);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_set_named_property(env, exports, "MyObject", cons);
      +  if (status != napi_ok) return NULL;
      +
      +  return exports;
      +}
      +

      If the module will be loaded multiple times during the lifetime of the Node.js +process, use the NAPI_MODULE_INIT macro to initialize the module:

      +
      NAPI_MODULE_INIT() {
      +  napi_value answer;
      +  napi_status result;
      +
      +  status = napi_create_int64(env, 42, &answer);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_set_named_property(env, exports, "answer", answer);
      +  if (status != napi_ok) return NULL;
      +
      +  return exports;
      +}
      +

      This macro includes NAPI_MODULE, and declares an Init function with a +special name and with visibility beyond the addon. This will allow Node.js to +initialize the module even if it is loaded multiple times.

      +

      There are a few design considerations when declaring a module that may be loaded +multiple times. The documentation of context-aware addons provides more +details.

      +

      The variables env and exports will be available inside the function body +following the macro invocation.

      +

      For more details on setting properties on objects, see the section on +Working with JavaScript properties.

      +

      For more details on building addon modules in general, refer to the existing +API.

      +

      Working with JavaScript values#

      +

      N-API exposes a set of APIs to create all types of JavaScript values. +Some of these types are documented under Section 6 +of the ECMAScript Language Specification.

      +

      Fundamentally, these APIs are used to do one of the following:

      +
        +
      1. Create a new JavaScript object
      2. +
      3. Convert from a primitive C type to an N-API value
      4. +
      5. Convert from N-API value to a primitive C type
      6. +
      7. Get global instances including undefined and null
      8. +
      +

      N-API values are represented by the type napi_value. +Any N-API call that requires a JavaScript value takes in a napi_value. +In some cases, the API does check the type of the napi_value up-front. +However, for better performance, it's better for the caller to make sure that +the napi_value in question is of the JavaScript type expected by the API.

      +

      Enum types#

      +

      napi_key_collection_mode#

      + +
      typedef enum {
      +  napi_key_include_prototypes,
      +  napi_key_own_only
      +} napi_key_collection_mode;
      +

      Describes the Keys/Properties filter enums:

      +

      napi_key_collection_mode limits the range of collected properties.

      +

      napi_key_own_only limits the collected properties to the given +object only. napi_key_include_prototypes will include all keys +of the objects's prototype chain as well.

      +

      napi_key_filter#

      + +
      typedef enum {
      +  napi_key_all_properties = 0,
      +  napi_key_writable = 1,
      +  napi_key_enumerable = 1 << 1,
      +  napi_key_configurable = 1 << 2,
      +  napi_key_skip_strings = 1 << 3,
      +  napi_key_skip_symbols = 1 << 4
      +} napi_key_filter;
      +

      Property filter bits. They can be or'ed to build a composite filter.

      +

      napi_key_conversion#

      + +
      typedef enum {
      +  napi_key_keep_numbers,
      +  napi_key_numbers_to_strings
      +} napi_key_conversion;
      +

      napi_key_numbers_to_strings will convert integer indices to +strings. napi_key_keep_numbers will return numbers for integer +indices.

      +

      napi_valuetype#

      +
      typedef enum {
      +  // ES6 types (corresponds to typeof)
      +  napi_undefined,
      +  napi_null,
      +  napi_boolean,
      +  napi_number,
      +  napi_string,
      +  napi_symbol,
      +  napi_object,
      +  napi_function,
      +  napi_external,
      +  napi_bigint,
      +} napi_valuetype;
      +

      Describes the type of a napi_value. This generally corresponds to the types +described in Section 6.1 of the ECMAScript Language Specification. +In addition to types in that section, napi_valuetype can also represent +Functions and Objects with external data.

      +

      A JavaScript value of type napi_external appears in JavaScript as a plain +object such that no properties can be set on it, and no prototype.

      +

      napi_typedarray_type#

      +
      typedef enum {
      +  napi_int8_array,
      +  napi_uint8_array,
      +  napi_uint8_clamped_array,
      +  napi_int16_array,
      +  napi_uint16_array,
      +  napi_int32_array,
      +  napi_uint32_array,
      +  napi_float32_array,
      +  napi_float64_array,
      +  napi_bigint64_array,
      +  napi_biguint64_array,
      +} napi_typedarray_type;
      +

      This represents the underlying binary scalar datatype of the TypedArray. +Elements of this enum correspond to +Section 22.2 of the ECMAScript Language Specification.

      +

      Object creation functions#

      +

      napi_create_array#

      + +
      napi_status napi_create_array(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [out] result: A napi_value representing a JavaScript Array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript Array type. +JavaScript arrays are described in +Section 22.1 of the ECMAScript Language Specification.

      +

      napi_create_array_with_length#

      + +
      napi_status napi_create_array_with_length(napi_env env,
      +                                          size_t length,
      +                                          napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: The initial length of the Array.
      • +
      • [out] result: A napi_value representing a JavaScript Array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript Array type. +The Array's length property is set to the passed-in length parameter. +However, the underlying buffer is not guaranteed to be pre-allocated by the VM +when the array is created. That behavior is left to the underlying VM +implementation. If the buffer must be a contiguous block of memory that can be +directly read and/or written via C, consider using +napi_create_external_arraybuffer.

      +

      JavaScript arrays are described in +Section 22.1 of the ECMAScript Language Specification.

      +

      napi_create_arraybuffer#

      + +
      napi_status napi_create_arraybuffer(napi_env env,
      +                                    size_t byte_length,
      +                                    void** data,
      +                                    napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: The length in bytes of the array buffer to create.
      • +
      • [out] data: Pointer to the underlying byte buffer of the ArrayBuffer.
      • +
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer. +ArrayBuffers are used to represent fixed-length binary data buffers. They are +normally used as a backing-buffer for TypedArray objects. +The ArrayBuffer allocated will have an underlying byte buffer whose size is +determined by the length parameter that's passed in. +The underlying buffer is optionally returned back to the caller in case the +caller wants to directly manipulate the buffer. This buffer can only be +written to directly from native code. To write to this buffer from JavaScript, +a typed array or DataView object would need to be created.

      +

      JavaScript ArrayBuffer objects are described in +Section 24.1 of the ECMAScript Language Specification.

      +

      napi_create_buffer#

      + +
      napi_status napi_create_buffer(napi_env env,
      +                               size_t size,
      +                               void** data,
      +                               napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] size: Size in bytes of the underlying buffer.
      • +
      • [out] data: Raw pointer to the underlying buffer.
      • +
      • [out] result: A napi_value representing a node::Buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a node::Buffer object. While this is still a +fully-supported data structure, in most cases using a TypedArray will suffice.

      +

      napi_create_buffer_copy#

      + +
      napi_status napi_create_buffer_copy(napi_env env,
      +                                    size_t length,
      +                                    const void* data,
      +                                    void** result_data,
      +                                    napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] size: Size in bytes of the input buffer (should be the same as the size +of the new buffer).
      • +
      • [in] data: Raw pointer to the underlying buffer to copy from.
      • +
      • [out] result_data: Pointer to the new Buffer's underlying data buffer.
      • +
      • [out] result: A napi_value representing a node::Buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a node::Buffer object and initializes it with data copied +from the passed-in buffer. While this is still a fully-supported data +structure, in most cases using a TypedArray will suffice.

      +

      napi_create_date#

      + +
      napi_status napi_create_date(napi_env env,
      +                             double time,
      +                             napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] time: ECMAScript time value in milliseconds since 01 January, 1970 UTC.
      • +
      • [out] result: A napi_value representing a JavaScript Date.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API does not observe leap seconds; they are ignored, as +ECMAScript aligns with POSIX time specification.

      +

      This API allocates a JavaScript Date object.

      +

      JavaScript Date objects are described in +Section 20.3 of the ECMAScript Language Specification.

      +

      napi_create_external#

      + +
      napi_status napi_create_external(napi_env env,
      +                                 void* data,
      +                                 napi_finalize finalize_cb,
      +                                 void* finalize_hint,
      +                                 napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] data: Raw pointer to the external data.
      • +
      • [in] finalize_cb: Optional callback to call when the external value is being +collected. napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      • [out] result: A napi_value representing an external value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a JavaScript value with external data attached to it. This +is used to pass external data through JavaScript code, so it can be retrieved +later by native code using napi_get_value_external.

      +

      The API adds a napi_finalize callback which will be called when the JavaScript +object just created is ready for garbage collection. It is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the object created by the API can be used with napi_wrap().
      • +
      +

      The created value is not an object, and therefore does not support additional +properties. It is considered a distinct value type: calling napi_typeof() with +an external value yields napi_external.

      +

      napi_create_external_arraybuffer#

      + +
      napi_status
      +napi_create_external_arraybuffer(napi_env env,
      +                                 void* external_data,
      +                                 size_t byte_length,
      +                                 napi_finalize finalize_cb,
      +                                 void* finalize_hint,
      +                                 napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] external_data: Pointer to the underlying byte buffer of the +ArrayBuffer.
      • +
      • [in] byte_length: The length in bytes of the underlying buffer.
      • +
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being +collected. napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer. +The underlying byte buffer of the ArrayBuffer is externally allocated and +managed. The caller must ensure that the byte buffer remains valid until the +finalize callback is called.

      +

      The API adds a napi_finalize callback which will be called when the JavaScript +object just created is ready for garbage collection. It is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the object created by the API can be used with napi_wrap().
      • +
      +

      JavaScript ArrayBuffers are described in +Section 24.1 of the ECMAScript Language Specification.

      +

      napi_create_external_buffer#

      + +
      napi_status napi_create_external_buffer(napi_env env,
      +                                        size_t length,
      +                                        void* data,
      +                                        napi_finalize finalize_cb,
      +                                        void* finalize_hint,
      +                                        napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: Size in bytes of the input buffer (should be the same as the +size of the new buffer).
      • +
      • [in] data: Raw pointer to the underlying buffer to expose to JavaScript.
      • +
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being +collected. napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      • [out] result: A napi_value representing a node::Buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a node::Buffer object and initializes it with data +backed by the passed in buffer. While this is still a fully-supported data +structure, in most cases using a TypedArray will suffice.

      +

      The API adds a napi_finalize callback which will be called when the JavaScript +object just created is ready for garbage collection. It is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the object created by the API can be used with napi_wrap().
      • +
      +

      For Node.js >=4 Buffers are Uint8Arrays.

      +

      napi_create_object#

      + +
      napi_status napi_create_object(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: A napi_value representing a JavaScript Object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a default JavaScript Object. +It is the equivalent of doing new Object() in JavaScript.

      +

      The JavaScript Object type is described in Section 6.1.7 of the +ECMAScript Language Specification.

      +

      napi_create_symbol#

      + +
      napi_status napi_create_symbol(napi_env env,
      +                               napi_value description,
      +                               napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] description: Optional napi_value which refers to a JavaScript +String to be set as the description for the symbol.
      • +
      • [out] result: A napi_value representing a JavaScript Symbol.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript Symbol object from a UTF8-encoded C string.

      +

      The JavaScript Symbol type is described in Section 19.4 +of the ECMAScript Language Specification.

      +

      napi_create_typedarray#

      + +
      napi_status napi_create_typedarray(napi_env env,
      +                                   napi_typedarray_type type,
      +                                   size_t length,
      +                                   napi_value arraybuffer,
      +                                   size_t byte_offset,
      +                                   napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] type: Scalar datatype of the elements within the TypedArray.
      • +
      • [in] length: Number of elements in the TypedArray.
      • +
      • [in] arraybuffer: ArrayBuffer underlying the typed array.
      • +
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to +start projecting the TypedArray.
      • +
      • [out] result: A napi_value representing a JavaScript TypedArray.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript TypedArray object over an existing +ArrayBuffer. TypedArray objects provide an array-like view over an +underlying data buffer where each element has the same underlying binary scalar +datatype.

      +

      It's required that (length * size_of_element) + byte_offset should +be <= the size in bytes of the array passed in. If not, a RangeError exception +is raised.

      +

      JavaScript TypedArray objects are described in +Section 22.2 of the ECMAScript Language Specification.

      +

      napi_create_dataview#

      + +
      napi_status napi_create_dataview(napi_env env,
      +                                 size_t byte_length,
      +                                 napi_value arraybuffer,
      +                                 size_t byte_offset,
      +                                 napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: Number of elements in the DataView.
      • +
      • [in] arraybuffer: ArrayBuffer underlying the DataView.
      • +
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to +start projecting the DataView.
      • +
      • [out] result: A napi_value representing a JavaScript DataView.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript DataView object over an existing ArrayBuffer. +DataView objects provide an array-like view over an underlying data buffer, +but one which allows items of different size and type in the ArrayBuffer.

      +

      It is required that byte_length + byte_offset is less than or equal to the +size in bytes of the array passed in. If not, a RangeError exception is +raised.

      +

      JavaScript DataView objects are described in +Section 24.3 of the ECMAScript Language Specification.

      +

      Functions to convert from C types to N-API#

      +

      napi_create_int32#

      + +
      napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C int32_t type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in +Section 6.1.6 of the ECMAScript Language Specification.

      +

      napi_create_uint32#

      + +
      napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C uint32_t type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in +Section 6.1.6 of the ECMAScript Language Specification.

      +

      napi_create_int64#

      + +
      napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C int64_t type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in Section 6.1.6 +of the ECMAScript Language Specification. Note the complete range of int64_t +cannot be represented with full precision in JavaScript. Integer values +outside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) - +Number.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.

      +

      napi_create_double#

      + +
      napi_status napi_create_double(napi_env env, double value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Double-precision value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C double type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in +Section 6.1.6 of the ECMAScript Language Specification.

      +

      napi_create_bigint_int64#

      + +
      napi_status napi_create_bigint_int64(napi_env env,
      +                                     int64_t value,
      +                                     napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript BigInt.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts the C int64_t type to the JavaScript BigInt type.

      +

      napi_create_bigint_uint64#

      + +
      napi_status napi_create_bigint_uint64(napi_env env,
      +                                      uint64_t value,
      +                                      napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript BigInt.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts the C uint64_t type to the JavaScript BigInt type.

      +

      napi_create_bigint_words#

      + +
      napi_status napi_create_bigint_words(napi_env env,
      +                                     int sign_bit,
      +                                     size_t word_count,
      +                                     const uint64_t* words,
      +                                     napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] sign_bit: Determines if the resulting BigInt will be positive or +negative.
      • +
      • [in] word_count: The length of the words array.
      • +
      • [in] words: An array of uint64_t little-endian 64-bit words.
      • +
      • [out] result: A napi_value representing a JavaScript BigInt.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts an array of unsigned 64-bit words into a single BigInt +value.

      +

      The resulting BigInt is calculated as: (–1)sign_bit (words[0] +× (264)0 + words[1] × (264)1 + …)

      +

      napi_create_string_latin1#

      + +
      napi_status napi_create_string_latin1(napi_env env,
      +                                      const char* str,
      +                                      size_t length,
      +                                      napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] str: Character buffer representing an ISO-8859-1-encoded string.
      • +
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it +is null-terminated.
      • +
      • [out] result: A napi_value representing a JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript String object from an ISO-8859-1-encoded C +string. The native string is copied.

      +

      The JavaScript String type is described in +Section 6.1.4 of the ECMAScript Language Specification.

      +

      napi_create_string_utf16#

      + +
      napi_status napi_create_string_utf16(napi_env env,
      +                                     const char16_t* str,
      +                                     size_t length,
      +                                     napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] str: Character buffer representing a UTF16-LE-encoded string.
      • +
      • [in] length: The length of the string in two-byte code units, or +NAPI_AUTO_LENGTH if it is null-terminated.
      • +
      • [out] result: A napi_value representing a JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript String object from a UTF16-LE-encoded C string. +The native string is copied.

      +

      The JavaScript String type is described in +Section 6.1.4 of the ECMAScript Language Specification.

      +

      napi_create_string_utf8#

      + +
      napi_status napi_create_string_utf8(napi_env env,
      +                                    const char* str,
      +                                    size_t length,
      +                                    napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] str: Character buffer representing a UTF8-encoded string.
      • +
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it +is null-terminated.
      • +
      • [out] result: A napi_value representing a JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript String object from a UTF8-encoded C string. +The native string is copied.

      +

      The JavaScript String type is described in +Section 6.1.4 of the ECMAScript Language Specification.

      +

      Functions to convert from N-API to C types#

      +

      napi_get_array_length#

      + +
      napi_status napi_get_array_length(napi_env env,
      +                                  napi_value value,
      +                                  uint32_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing the JavaScript Array whose length is +being queried.
      • +
      • [out] result: uint32 representing length of the array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the length of an array.

      +

      Array length is described in Section 22.1.4.1 of the ECMAScript Language +Specification.

      +

      napi_get_arraybuffer_info#

      + +
      napi_status napi_get_arraybuffer_info(napi_env env,
      +                                      napi_value arraybuffer,
      +                                      void** data,
      +                                      size_t* byte_length)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] arraybuffer: napi_value representing the ArrayBuffer being queried.
      • +
      • [out] data: The underlying data buffer of the ArrayBuffer. If byte_length +is 0, this may be NULL or any other pointer value.
      • +
      • [out] byte_length: Length in bytes of the underlying data buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to retrieve the underlying data buffer of an ArrayBuffer and +its length.

      +

      WARNING: Use caution while using this API. The lifetime of the underlying data +buffer is managed by the ArrayBuffer even after it's returned. A +possible safe way to use this API is in conjunction with +napi_create_reference, which can be used to guarantee control over the +lifetime of the ArrayBuffer. It's also safe to use the returned data buffer +within the same callback as long as there are no calls to other APIs that might +trigger a GC.

      +

      napi_get_buffer_info#

      + +
      napi_status napi_get_buffer_info(napi_env env,
      +                                 napi_value value,
      +                                 void** data,
      +                                 size_t* length)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing the node::Buffer being queried.
      • +
      • [out] data: The underlying data buffer of the node::Buffer. +If length is 0, this may be NULL or any other pointer value.
      • +
      • [out] length: Length in bytes of the underlying data buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to retrieve the underlying data buffer of a node::Buffer +and it's length.

      +

      Warning: Use caution while using this API since the underlying data buffer's +lifetime is not guaranteed if it's managed by the VM.

      +

      napi_get_prototype#

      + +
      napi_status napi_get_prototype(napi_env env,
      +                               napi_value object,
      +                               napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] object: napi_value representing JavaScript Object whose prototype +to return. This returns the equivalent of Object.getPrototypeOf (which is +not the same as the function's prototype property).
      • +
      • [out] result: napi_value representing prototype of the given object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      napi_get_typedarray_info#

      + +
      napi_status napi_get_typedarray_info(napi_env env,
      +                                     napi_value typedarray,
      +                                     napi_typedarray_type* type,
      +                                     size_t* length,
      +                                     void** data,
      +                                     napi_value* arraybuffer,
      +                                     size_t* byte_offset)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] typedarray: napi_value representing the TypedArray whose +properties to query.
      • +
      • [out] type: Scalar datatype of the elements within the TypedArray.
      • +
      • [out] length: The number of elements in the TypedArray.
      • +
      • [out] data: The data buffer underlying the TypedArray adjusted by +the byte_offset value so that it points to the first element in the +TypedArray. If the length of the array is 0, this may be NULL or +any other pointer value.
      • +
      • [out] arraybuffer: The ArrayBuffer underlying the TypedArray.
      • +
      • [out] byte_offset: The byte offset within the underlying native array +at which the first element of the arrays is located. The value for the data +parameter has already been adjusted so that data points to the first element +in the array. Therefore, the first byte of the native array would be at +data - byte_offset.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns various properties of a typed array.

      +

      Warning: Use caution while using this API since the underlying data buffer +is managed by the VM.

      +

      napi_get_dataview_info#

      + +
      napi_status napi_get_dataview_info(napi_env env,
      +                                   napi_value dataview,
      +                                   size_t* byte_length,
      +                                   void** data,
      +                                   napi_value* arraybuffer,
      +                                   size_t* byte_offset)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] dataview: napi_value representing the DataView whose +properties to query.
      • +
      • [out] byte_length: Number of bytes in the DataView.
      • +
      • [out] data: The data buffer underlying the DataView. +If byte_length is 0, this may be NULL or any other pointer value.
      • +
      • [out] arraybuffer: ArrayBuffer underlying the DataView.
      • +
      • [out] byte_offset: The byte offset within the data buffer from which +to start projecting the DataView.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns various properties of a DataView.

      +

      napi_get_date_value#

      + +
      napi_status napi_get_date_value(napi_env env,
      +                                napi_value value,
      +                                double* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing a JavaScript Date.
      • +
      • [out] result: Time value as a double represented as milliseconds since +midnight at the beginning of 01 January, 1970 UTC.
      • +
      +

      This API does not observe leap seconds; they are ignored, as +ECMAScript aligns with POSIX time specification.

      +

      Returns napi_ok if the API succeeded. If a non-date napi_value is passed +in it returns napi_date_expected.

      +

      This API returns the C double primitive of time value for the given JavaScript +Date.

      +

      napi_get_value_bool#

      + +
      napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Boolean.
      • +
      • [out] result: C boolean primitive equivalent of the given JavaScript +Boolean.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-boolean napi_value is +passed in it returns napi_boolean_expected.

      +

      This API returns the C boolean primitive equivalent of the given JavaScript +Boolean.

      +

      napi_get_value_double#

      + +
      napi_status napi_get_value_double(napi_env env,
      +                                  napi_value value,
      +                                  double* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C double primitive equivalent of the given JavaScript +Number.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value is passed +in it returns napi_number_expected.

      +

      This API returns the C double primitive equivalent of the given JavaScript +Number.

      +

      napi_get_value_bigint_int64#

      + +
      napi_status napi_get_value_bigint_int64(napi_env env,
      +                                        napi_value value,
      +                                        int64_t* result,
      +                                        bool* lossless);
      +
        +
      • [in] env: The environment that the API is invoked under
      • +
      • [in] value: napi_value representing JavaScript BigInt.
      • +
      • [out] result: C int64_t primitive equivalent of the given JavaScript +BigInt.
      • +
      • [out] lossless: Indicates whether the BigInt value was converted +losslessly.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it +returns napi_bigint_expected.

      +

      This API returns the C int64_t primitive equivalent of the given JavaScript +BigInt. If needed it will truncate the value, setting lossless to false.

      +

      napi_get_value_bigint_uint64#

      + +
      napi_status napi_get_value_bigint_uint64(napi_env env,
      +                                        napi_value value,
      +                                        uint64_t* result,
      +                                        bool* lossless);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript BigInt.
      • +
      • [out] result: C uint64_t primitive equivalent of the given JavaScript +BigInt.
      • +
      • [out] lossless: Indicates whether the BigInt value was converted +losslessly.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it +returns napi_bigint_expected.

      +

      This API returns the C uint64_t primitive equivalent of the given JavaScript +BigInt. If needed it will truncate the value, setting lossless to false.

      +

      napi_get_value_bigint_words#

      + +
      napi_status napi_get_value_bigint_words(napi_env env,
      +                                        napi_value value,
      +                                        int* sign_bit,
      +                                        size_t* word_count,
      +                                        uint64_t* words);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript BigInt.
      • +
      • [out] sign_bit: Integer representing if the JavaScript BigInt is positive +or negative.
      • +
      • [in/out] word_count: Must be initialized to the length of the words +array. Upon return, it will be set to the actual number of words that +would be needed to store this BigInt.
      • +
      • [out] words: Pointer to a pre-allocated 64-bit word array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts a single BigInt value into a sign bit, 64-bit little-endian +array, and the number of elements in the array. sign_bit and words may be +both set to NULL, in order to get only word_count.

      +

      napi_get_value_external#

      + +
      napi_status napi_get_value_external(napi_env env,
      +                                    napi_value value,
      +                                    void** result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript external value.
      • +
      • [out] result: Pointer to the data wrapped by the JavaScript external value.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-external napi_value is +passed in it returns napi_invalid_arg.

      +

      This API retrieves the external data pointer that was previously passed to +napi_create_external().

      +

      napi_get_value_int32#

      + +
      napi_status napi_get_value_int32(napi_env env,
      +                                 napi_value value,
      +                                 int32_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C int32 primitive equivalent of the given JavaScript +Number.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value +is passed in napi_number_expected.

      +

      This API returns the C int32 primitive equivalent +of the given JavaScript Number.

      +

      If the number exceeds the range of the 32 bit integer, then the result is +truncated to the equivalent of the bottom 32 bits. This can result in a large +positive number becoming a negative number if the value is > 231 - 1.

      +

      Non-finite number values (NaN, +Infinity, or -Infinity) set the +result to zero.

      +

      napi_get_value_int64#

      + +
      napi_status napi_get_value_int64(napi_env env,
      +                                 napi_value value,
      +                                 int64_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C int64 primitive equivalent of the given JavaScript +Number.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value +is passed in it returns napi_number_expected.

      +

      This API returns the C int64 primitive equivalent of the given JavaScript +Number.

      +

      Number values outside the range of Number.MIN_SAFE_INTEGER +-(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose +precision.

      +

      Non-finite number values (NaN, +Infinity, or -Infinity) set the +result to zero.

      +

      napi_get_value_string_latin1#

      + +
      napi_status napi_get_value_string_latin1(napi_env env,
      +                                         napi_value value,
      +                                         char* buf,
      +                                         size_t bufsize,
      +                                         size_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript string.
      • +
      • [in] buf: Buffer to write the ISO-8859-1-encoded string into. If NULL is +passed in, the length of the string (in bytes) is returned.
      • +
      • [in] bufsize: Size of the destination buffer. When this value is +insufficient, the returned string will be truncated.
      • +
      • [out] result: Number of bytes copied into the buffer, excluding the null +terminator.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-String napi_value +is passed in it returns napi_string_expected.

      +

      This API returns the ISO-8859-1-encoded string corresponding the value passed +in.

      +

      napi_get_value_string_utf8#

      + +
      napi_status napi_get_value_string_utf8(napi_env env,
      +                                       napi_value value,
      +                                       char* buf,
      +                                       size_t bufsize,
      +                                       size_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript string.
      • +
      • [in] buf: Buffer to write the UTF8-encoded string into. If NULL is passed +in, the length of the string (in bytes) is returned.
      • +
      • [in] bufsize: Size of the destination buffer. When this value is +insufficient, the returned string will be truncated.
      • +
      • [out] result: Number of bytes copied into the buffer, excluding the null +terminator.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-String napi_value +is passed in it returns napi_string_expected.

      +

      This API returns the UTF8-encoded string corresponding the value passed in.

      +

      napi_get_value_string_utf16#

      + +
      napi_status napi_get_value_string_utf16(napi_env env,
      +                                        napi_value value,
      +                                        char16_t* buf,
      +                                        size_t bufsize,
      +                                        size_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript string.
      • +
      • [in] buf: Buffer to write the UTF16-LE-encoded string into. If NULL is +passed in, the length of the string (in 2-byte code units) is returned.
      • +
      • [in] bufsize: Size of the destination buffer. When this value is +insufficient, the returned string will be truncated.
      • +
      • [out] result: Number of 2-byte code units copied into the buffer, excluding +the null terminator.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-String napi_value +is passed in it returns napi_string_expected.

      +

      This API returns the UTF16-encoded string corresponding the value passed in.

      +

      napi_get_value_uint32#

      + +
      napi_status napi_get_value_uint32(napi_env env,
      +                                  napi_value value,
      +                                  uint32_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C primitive equivalent of the given napi_value as a +uint32_t.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value +is passed in it returns napi_number_expected.

      +

      This API returns the C primitive equivalent of the given napi_value as a +uint32_t.

      +

      Functions to get global instances#

      +

      napi_get_boolean#

      + +
      napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The value of the boolean to retrieve.
      • +
      • [out] result: napi_value representing JavaScript Boolean singleton to +retrieve.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to return the JavaScript singleton object that is used to +represent the given boolean value.

      +

      napi_get_global#

      + +
      napi_status napi_get_global(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing JavaScript global object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the global object.

      +

      napi_get_null#

      + +
      napi_status napi_get_null(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing JavaScript null object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the null object.

      +

      napi_get_undefined#

      + +
      napi_status napi_get_undefined(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing JavaScript Undefined value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the Undefined object.

      +

      Working with JavaScript values and abstract operations#

      +

      N-API exposes a set of APIs to perform some abstract operations on JavaScript +values. Some of these operations are documented under Section 7 +of the ECMAScript Language Specification.

      +

      These APIs support doing one of the following:

      +
        +
      1. Coerce JavaScript values to specific JavaScript types (such as Number or +String).
      2. +
      3. Check the type of a JavaScript value.
      4. +
      5. Check for equality between two JavaScript values.
      6. +
      +

      napi_coerce_to_bool#

      + +
      napi_status napi_coerce_to_bool(napi_env env,
      +                                napi_value value,
      +                                napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript Boolean.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToBoolean() as defined in +Section 7.1.2 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_coerce_to_number#

      + +
      napi_status napi_coerce_to_number(napi_env env,
      +                                  napi_value value,
      +                                  napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToNumber() as defined in +Section 7.1.3 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_coerce_to_object#

      + +
      napi_status napi_coerce_to_object(napi_env env,
      +                                  napi_value value,
      +                                  napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript Object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToObject() as defined in +Section 7.1.13 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_coerce_to_string#

      + +
      napi_status napi_coerce_to_string(napi_env env,
      +                                  napi_value value,
      +                                  napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToString() as defined in +Section 7.1.13 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_typeof#

      + +
      napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value whose type to query.
      • +
      • [out] result: The type of the JavaScript value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +
        +
      • napi_invalid_arg if the type of value is not a known ECMAScript type and +value is not an External value.
      • +
      +

      This API represents behavior similar to invoking the typeof Operator on +the object as defined in Section 12.5.5 of the ECMAScript Language +Specification. However, there are some differences:

      +
        +
      1. It has support for detecting an External value.
      2. +
      3. It detects null as a separate type, while ECMAScript typeof would detect +object.
      4. +
      +

      If value has a type that is invalid, an error is returned.

      +

      napi_instanceof#

      + +
      napi_status napi_instanceof(napi_env env,
      +                            napi_value object,
      +                            napi_value constructor,
      +                            bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] object: The JavaScript value to check.
      • +
      • [in] constructor: The JavaScript function object of the constructor function +to check against.
      • +
      • [out] result: Boolean that is set to true if object instanceof constructor +is true.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API represents invoking the instanceof Operator on the object as +defined in Section 12.10.4 of the ECMAScript Language Specification.

      +

      napi_is_array#

      + +
      napi_status napi_is_array(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given object is an array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API represents invoking the IsArray operation on the object +as defined in Section 7.2.2 of the ECMAScript Language Specification.

      +

      napi_is_arraybuffer#

      + +
      napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given object is an ArrayBuffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is an array buffer.

      +

      napi_is_buffer#

      + +
      napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a node::Buffer +object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a buffer.

      +

      napi_is_date#

      + +
      napi_status napi_is_date(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a JavaScript Date +object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a date.

      +

      napi_is_error#

      + +
      napi_status napi_is_error(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents an Error object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is an Error.

      +

      napi_is_typedarray#

      + +
      napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a TypedArray.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a typed array.

      +

      napi_is_dataview#

      + +
      napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a DataView.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a DataView.

      +

      napi_strict_equals#

      + +
      napi_status napi_strict_equals(napi_env env,
      +                               napi_value lhs,
      +                               napi_value rhs,
      +                               bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] lhs: The JavaScript value to check.
      • +
      • [in] rhs: The JavaScript value to check against.
      • +
      • [out] result: Whether the two napi_value objects are equal.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API represents the invocation of the Strict Equality algorithm as +defined in Section 7.2.14 of the ECMAScript Language Specification.

      +

      napi_detach_arraybuffer#

      + +
      napi_status napi_detach_arraybuffer(napi_env env,
      +                                    napi_value arraybuffer)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] arraybuffer: The JavaScript ArrayBuffer to be detached.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is +passed in it returns napi_detachable_arraybuffer_expected.

      +

      Generally, an ArrayBuffer is non-detachable if it has been detached before. +The engine may impose additional conditions on whether an ArrayBuffer is +detachable. For example, V8 requires that the ArrayBuffer be external, +that is, created with napi_create_external_arraybuffer.

      +

      This API represents the invocation of the ArrayBuffer detach operation as +defined in Section 24.1.1.3 of the ECMAScript Language Specification.

      +

      napi_is_detached_arraybuffer#

      + +
      napi_status napi_is_detached_arraybuffer(napi_env env,
      +                                         napi_value arraybuffer,
      +                                         bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] arraybuffer: The JavaScript ArrayBuffer to be checked.
      • +
      • [out] result: Whether the arraybuffer is detached.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      The ArrayBuffer is considered detached if its internal data is null.

      +

      This API represents the invocation of the ArrayBuffer IsDetachedBuffer +operation as defined in Section 24.1.1.2 of the ECMAScript Language +Specification.

      +

      Working with JavaScript properties#

      +

      N-API exposes a set of APIs to get and set properties on JavaScript +objects. Some of these types are documented under Section 7 of the +ECMAScript Language Specification.

      +

      Properties in JavaScript are represented as a tuple of a key and a value. +Fundamentally, all property keys in N-API can be represented in one of the +following forms:

      +
        +
      • Named: a simple UTF8-encoded string
      • +
      • Integer-Indexed: an index value represented by uint32_t
      • +
      • JavaScript value: these are represented in N-API by napi_value. This can +be a napi_value representing a String, Number, or Symbol.
      • +
      +

      N-API values are represented by the type napi_value. +Any N-API call that requires a JavaScript value takes in a napi_value. +However, it's the caller's responsibility to make sure that the +napi_value in question is of the JavaScript type expected by the API.

      +

      The APIs documented in this section provide a simple interface to +get and set properties on arbitrary JavaScript objects represented by +napi_value.

      +

      For instance, consider the following JavaScript code snippet:

      +
      const obj = {};
      +obj.myProp = 123;
      +

      The equivalent can be done using N-API values with the following snippet:

      +
      napi_status status = napi_generic_failure;
      +
      +// const obj = {}
      +napi_value obj, value;
      +status = napi_create_object(env, &obj);
      +if (status != napi_ok) return status;
      +
      +// Create a napi_value for 123
      +status = napi_create_int32(env, 123, &value);
      +if (status != napi_ok) return status;
      +
      +// obj.myProp = 123
      +status = napi_set_named_property(env, obj, "myProp", value);
      +if (status != napi_ok) return status;
      +

      Indexed properties can be set in a similar manner. Consider the following +JavaScript snippet:

      +
      const arr = [];
      +arr[123] = 'hello';
      +

      The equivalent can be done using N-API values with the following snippet:

      +
      napi_status status = napi_generic_failure;
      +
      +// const arr = [];
      +napi_value arr, value;
      +status = napi_create_array(env, &arr);
      +if (status != napi_ok) return status;
      +
      +// Create a napi_value for 'hello'
      +status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value);
      +if (status != napi_ok) return status;
      +
      +// arr[123] = 'hello';
      +status = napi_set_element(env, arr, 123, value);
      +if (status != napi_ok) return status;
      +

      Properties can be retrieved using the APIs described in this section. +Consider the following JavaScript snippet:

      +
      const arr = [];
      +const value = arr[123];
      +

      The following is the approximate equivalent of the N-API counterpart:

      +
      napi_status status = napi_generic_failure;
      +
      +// const arr = []
      +napi_value arr, value;
      +status = napi_create_array(env, &arr);
      +if (status != napi_ok) return status;
      +
      +// const value = arr[123]
      +status = napi_get_element(env, arr, 123, &value);
      +if (status != napi_ok) return status;
      +

      Finally, multiple properties can also be defined on an object for performance +reasons. Consider the following JavaScript:

      +
      const obj = {};
      +Object.defineProperties(obj, {
      +  'foo': { value: 123, writable: true, configurable: true, enumerable: true },
      +  'bar': { value: 456, writable: true, configurable: true, enumerable: true }
      +});
      +

      The following is the approximate equivalent of the N-API counterpart:

      +
      napi_status status = napi_status_generic_failure;
      +
      +// const obj = {};
      +napi_value obj;
      +status = napi_create_object(env, &obj);
      +if (status != napi_ok) return status;
      +
      +// Create napi_values for 123 and 456
      +napi_value fooValue, barValue;
      +status = napi_create_int32(env, 123, &fooValue);
      +if (status != napi_ok) return status;
      +status = napi_create_int32(env, 456, &barValue);
      +if (status != napi_ok) return status;
      +
      +// Set the properties
      +napi_property_descriptor descriptors[] = {
      +  { "foo", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL },
      +  { "bar", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL }
      +}
      +status = napi_define_properties(env,
      +                                obj,
      +                                sizeof(descriptors) / sizeof(descriptors[0]),
      +                                descriptors);
      +if (status != napi_ok) return status;
      +

      Structures#

      +

      napi_property_attributes#

      + +
      typedef enum {
      +  napi_default = 0,
      +  napi_writable = 1 << 0,
      +  napi_enumerable = 1 << 1,
      +  napi_configurable = 1 << 2,
      +
      +  // Used with napi_define_class to distinguish static properties
      +  // from instance properties. Ignored by napi_define_properties.
      +  napi_static = 1 << 10,
      +
      +  // Default for class methods.
      +  napi_default_method = napi_writable | napi_configurable,
      +
      +  // Default for object properties, like in JS obj[prop].
      +  napi_default_property = napi_writable |
      +                          napi_enumerable |
      +                          napi_configurable,
      +} napi_property_attributes;
      +

      napi_property_attributes are flags used to control the behavior of properties +set on a JavaScript object. Other than napi_static they correspond to the +attributes listed in Section 6.1.7.1 +of the ECMAScript Language Specification. +They can be one or more of the following bitflags:

      +
        +
      • napi_default: No explicit attributes are set on the property. By default, a +property is read only, not enumerable and not configurable.
      • +
      • napi_writable: The property is writable.
      • +
      • napi_enumerable: The property is enumerable.
      • +
      • napi_configurable: The property is configurable as defined in +Section 6.1.7.1 of the ECMAScript Language Specification.
      • +
      • napi_static: The property will be defined as a static property on a class as +opposed to an instance property, which is the default. This is used only by +napi_define_class. It is ignored by napi_define_properties.
      • +
      • napi_default_method: The property is configureable, writeable but not +enumerable like a method in a JS class.
      • +
      • napi_default_property: The property is writable, enumerable and configurable +like a property set via JS code obj.key = value.
      • +
      +

      napi_property_descriptor#

      +
      typedef struct {
      +  // One of utf8name or name should be NULL.
      +  const char* utf8name;
      +  napi_value name;
      +
      +  napi_callback method;
      +  napi_callback getter;
      +  napi_callback setter;
      +  napi_value value;
      +
      +  napi_property_attributes attributes;
      +  void* data;
      +} napi_property_descriptor;
      +
        +
      • utf8name: Optional String describing the key for the property, +encoded as UTF8. One of utf8name or name must be provided for the +property.
      • +
      • name: Optional napi_value that points to a JavaScript string or symbol +to be used as the key for the property. One of utf8name or name must +be provided for the property.
      • +
      • value: The value that's retrieved by a get access of the property if the +property is a data property. If this is passed in, set getter, setter, +method and data to NULL (since these members won't be used).
      • +
      • getter: A function to call when a get access of the property is performed. +If this is passed in, set value and method to NULL (since these members +won't be used). The given function is called implicitly by the runtime when +the property is accessed from JavaScript code (or if a get on the property is +performed using a N-API call). napi_callback provides more details.
      • +
      • setter: A function to call when a set access of the property is performed. +If this is passed in, set value and method to NULL (since these members +won't be used). The given function is called implicitly by the runtime when +the property is set from JavaScript code (or if a set on the property is +performed using a N-API call). napi_callback provides more details.
      • +
      • method: Set this to make the property descriptor object's value +property to be a JavaScript function represented by method. If this is +passed in, set value, getter and setter to NULL (since these members +won't be used). napi_callback provides more details.
      • +
      • attributes: The attributes associated with the particular property. See +napi_property_attributes.
      • +
      • data: The callback data passed into method, getter and setter if this +function is invoked.
      • +
      +

      Functions#

      +

      napi_get_property_names#

      + +
      napi_status napi_get_property_names(napi_env env,
      +                                    napi_value object,
      +                                    napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the properties.
      • +
      • [out] result: A napi_value representing an array of JavaScript values +that represent the property names of the object. The API can be used to +iterate over result using napi_get_array_length +and napi_get_element.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the names of the enumerable properties of object as an array +of strings. The properties of object whose key is a symbol will not be +included.

      +

      napi_get_all_property_names#

      + +
      napi_get_all_property_names(napi_env env,
      +                            napi_value object,
      +                            napi_key_collection_mode key_mode,
      +                            napi_key_filter key_filter,
      +                            napi_key_conversion key_conversion,
      +                            napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the properties.
      • +
      • [in] key_mode: Whether to retrieve prototype properties as well.
      • +
      • [in] key_filter: Which properties to retrieve +(enumerable/readable/writable).
      • +
      • [in] key_conversion: Whether to convert numbered property keys to strings.
      • +
      • [out] result: A napi_value representing an array of JavaScript values +that represent the property names of the object. napi_get_array_length and +napi_get_element can be used to iterate over result.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an array containing the names of the available properties +of this object.

      +

      napi_set_property#

      + +
      napi_status napi_set_property(napi_env env,
      +                              napi_value object,
      +                              napi_value key,
      +                              napi_value value);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object on which to set the property.
      • +
      • [in] key: The name of the property to set.
      • +
      • [in] value: The property value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API set a property on the Object passed in.

      +

      napi_get_property#

      + +
      napi_status napi_get_property(napi_env env,
      +                              napi_value object,
      +                              napi_value key,
      +                              napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the property.
      • +
      • [in] key: The name of the property to retrieve.
      • +
      • [out] result: The value of the property.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API gets the requested property from the Object passed in.

      +

      napi_has_property#

      + +
      napi_status napi_has_property(napi_env env,
      +                              napi_value object,
      +                              napi_value key,
      +                              bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] key: The name of the property whose existence to check.
      • +
      • [out] result: Whether the property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in has the named property.

      +

      napi_delete_property#

      + +
      napi_status napi_delete_property(napi_env env,
      +                                 napi_value object,
      +                                 napi_value key,
      +                                 bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] key: The name of the property to delete.
      • +
      • [out] result: Whether the property deletion succeeded or not. result can +optionally be ignored by passing NULL.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API attempts to delete the key own property from object.

      +

      napi_has_own_property#

      + +
      napi_status napi_has_own_property(napi_env env,
      +                                  napi_value object,
      +                                  napi_value key,
      +                                  bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] key: The name of the own property whose existence to check.
      • +
      • [out] result: Whether the own property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in has the named own property. key must +be a string or a Symbol, or an error will be thrown. N-API will not perform +any conversion between data types.

      +

      napi_set_named_property#

      + +
      napi_status napi_set_named_property(napi_env env,
      +                                    napi_value object,
      +                                    const char* utf8Name,
      +                                    napi_value value);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object on which to set the property.
      • +
      • [in] utf8Name: The name of the property to set.
      • +
      • [in] value: The property value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is equivalent to calling napi_set_property with a napi_value +created from the string passed in as utf8Name.

      +

      napi_get_named_property#

      + +
      napi_status napi_get_named_property(napi_env env,
      +                                    napi_value object,
      +                                    const char* utf8Name,
      +                                    napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the property.
      • +
      • [in] utf8Name: The name of the property to get.
      • +
      • [out] result: The value of the property.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is equivalent to calling napi_get_property with a napi_value +created from the string passed in as utf8Name.

      +

      napi_has_named_property#

      + +
      napi_status napi_has_named_property(napi_env env,
      +                                    napi_value object,
      +                                    const char* utf8Name,
      +                                    bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] utf8Name: The name of the property whose existence to check.
      • +
      • [out] result: Whether the property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is equivalent to calling napi_has_property with a napi_value +created from the string passed in as utf8Name.

      +

      napi_set_element#

      + +
      napi_status napi_set_element(napi_env env,
      +                             napi_value object,
      +                             uint32_t index,
      +                             napi_value value);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to set the properties.
      • +
      • [in] index: The index of the property to set.
      • +
      • [in] value: The property value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API sets and element on the Object passed in.

      +

      napi_get_element#

      + +
      napi_status napi_get_element(napi_env env,
      +                             napi_value object,
      +                             uint32_t index,
      +                             napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the property.
      • +
      • [in] index: The index of the property to get.
      • +
      • [out] result: The value of the property.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API gets the element at the requested index.

      +

      napi_has_element#

      + +
      napi_status napi_has_element(napi_env env,
      +                             napi_value object,
      +                             uint32_t index,
      +                             bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] index: The index of the property whose existence to check.
      • +
      • [out] result: Whether the property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns if the Object passed in has an element at the +requested index.

      +

      napi_delete_element#

      + +
      napi_status napi_delete_element(napi_env env,
      +                                napi_value object,
      +                                uint32_t index,
      +                                bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] index: The index of the property to delete.
      • +
      • [out] result: Whether the element deletion succeeded or not. result can +optionally be ignored by passing NULL.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API attempts to delete the specified index from object.

      +

      napi_define_properties#

      + +
      napi_status napi_define_properties(napi_env env,
      +                                   napi_value object,
      +                                   size_t property_count,
      +                                   const napi_property_descriptor* properties);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the properties.
      • +
      • [in] property_count: The number of elements in the properties array.
      • +
      • [in] properties: The array of property descriptors.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method allows the efficient definition of multiple properties on a given +object. The properties are defined using property descriptors (see +napi_property_descriptor). Given an array of such property descriptors, +this API will set the properties on the object one at a time, as defined by +DefineOwnProperty() (described in Section 9.1.6 of the ECMA-262 +specification).

      +

      napi_object_freeze#

      + +
      napi_status napi_object_freeze(napi_env env,
      +                               napi_value object);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to freeze.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method freezes a given object. This prevents new properties from +being added to it, existing properties from being removed, prevents +changing the enumerability, configurability, or writability of existing +properties, and prevents the values of existing properties from being changed. +It also prevents the object's prototype from being changed. This is described +in Section 19.1.2.6 of the +ECMA-262 specification.

      +

      napi_object_seal#

      + +
      napi_status napi_object_seal(napi_env env,
      +                             napi_value object);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to seal.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method seals a given object. This prevents new properties from being +added to it, as well as marking all existing properties as non-configurable. +This is described in Section 19.1.2.20 +of the ECMA-262 specification.

      +

      Working with JavaScript functions#

      +

      N-API provides a set of APIs that allow JavaScript code to +call back into native code. N-API APIs that support calling back +into native code take in a callback functions represented by +the napi_callback type. When the JavaScript VM calls back to +native code, the napi_callback function provided is invoked. The APIs +documented in this section allow the callback function to do the +following:

      +
        +
      • Get information about the context in which the callback was invoked.
      • +
      • Get the arguments passed into the callback.
      • +
      • Return a napi_value back from the callback.
      • +
      +

      Additionally, N-API provides a set of functions which allow calling +JavaScript functions from native code. One can either call a function +like a regular JavaScript function call, or as a constructor +function.

      +

      Any non-NULL data which is passed to this API via the data field of the +napi_property_descriptor items can be associated with object and freed +whenever object is garbage-collected by passing both object and the data to +napi_add_finalizer.

      +

      napi_call_function#

      + +
      NAPI_EXTERN napi_status napi_call_function(napi_env env,
      +                                           napi_value recv,
      +                                           napi_value func,
      +                                           size_t argc,
      +                                           const napi_value* argv,
      +                                           napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] recv: The this object passed to the called function.
      • +
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • +
      • [in] argc: The count of elements in the argv array.
      • +
      • [in] argv: Array of napi_values representing JavaScript values passed in +as arguments to the function.
      • +
      • [out] result: napi_value representing the JavaScript object returned.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method allows a JavaScript function object to be called from a native +add-on. This is the primary mechanism of calling back from the add-on's +native code into JavaScript. For the special case of calling into JavaScript +after an async operation, see napi_make_callback.

      +

      A sample use case might look as follows. Consider the following JavaScript +snippet:

      +
      function AddTwo(num) {
      +  return num + 2;
      +}
      +

      Then, the above function can be invoked from a native add-on using the +following code:

      +
      // Get the function named "AddTwo" on the global object
      +napi_value global, add_two, arg;
      +napi_status status = napi_get_global(env, &global);
      +if (status != napi_ok) return;
      +
      +status = napi_get_named_property(env, global, "AddTwo", &add_two);
      +if (status != napi_ok) return;
      +
      +// const arg = 1337
      +status = napi_create_int32(env, 1337, &arg);
      +if (status != napi_ok) return;
      +
      +napi_value* argv = &arg;
      +size_t argc = 1;
      +
      +// AddTwo(arg);
      +napi_value return_val;
      +status = napi_call_function(env, global, add_two, argc, argv, &return_val);
      +if (status != napi_ok) return;
      +
      +// Convert the result back to a native type
      +int32_t result;
      +status = napi_get_value_int32(env, return_val, &result);
      +if (status != napi_ok) return;
      +

      napi_create_function#

      + +
      napi_status napi_create_function(napi_env env,
      +                                 const char* utf8name,
      +                                 size_t length,
      +                                 napi_callback cb,
      +                                 void* data,
      +                                 napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] utf8Name: The name of the function encoded as UTF8. This is visible +within JavaScript as the new function object's name property.
      • +
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH if +it is null-terminated.
      • +
      • [in] cb: The native function which should be called when this function +object is invoked. napi_callback provides more details.
      • +
      • [in] data: User-provided data context. This will be passed back into the +function when invoked later.
      • +
      • [out] result: napi_value representing the JavaScript function object for +the newly created function.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allows an add-on author to create a function object in native code. +This is the primary mechanism to allow calling into the add-on's native code +from JavaScript.

      +

      The newly created function is not automatically visible from script after this +call. Instead, a property must be explicitly set on any object that is visible +to JavaScript, in order for the function to be accessible from script.

      +

      In order to expose a function as part of the +add-on's module exports, set the newly created function on the exports +object. A sample module might look as follows:

      +
      napi_value SayHello(napi_env env, napi_callback_info info) {
      +  printf("Hello\n");
      +  return NULL;
      +}
      +
      +napi_value Init(napi_env env, napi_value exports) {
      +  napi_status status;
      +
      +  napi_value fn;
      +  status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_set_named_property(env, exports, "sayHello", fn);
      +  if (status != napi_ok) return NULL;
      +
      +  return exports;
      +}
      +
      +NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
      +

      Given the above code, the add-on can be used from JavaScript as follows:

      +
      const myaddon = require('./addon');
      +myaddon.sayHello();
      +

      The string passed to require() is the name of the target in binding.gyp +responsible for creating the .node file.

      +

      Any non-NULL data which is passed to this API via the data parameter can +be associated with the resulting JavaScript function (which is returned in the +result parameter) and freed whenever the function is garbage-collected by +passing both the JavaScript function and the data to napi_add_finalizer.

      +

      JavaScript Functions are described in Section 19.2 of the ECMAScript +Language Specification.

      +

      napi_get_cb_info#

      + +
      napi_status napi_get_cb_info(napi_env env,
      +                             napi_callback_info cbinfo,
      +                             size_t* argc,
      +                             napi_value* argv,
      +                             napi_value* thisArg,
      +                             void** data)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] cbinfo: The callback info passed into the callback function.
      • +
      • [in-out] argc: Specifies the size of the provided argv array and receives +the actual count of arguments.
      • +
      • [out] argv: Buffer to which the napi_value representing the arguments are +copied. If there are more arguments than the provided count, only the +requested number of arguments are copied. If there are fewer arguments +provided than claimed, the rest of argv is filled with napi_value values +that represent undefined.
      • +
      • [out] this: Receives the JavaScript this argument for the call.
      • +
      • [out] data: Receives the data pointer for the callback.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is used within a callback function to retrieve details about the +call like the arguments and the this pointer from a given callback info.

      +

      napi_get_new_target#

      + +
      napi_status napi_get_new_target(napi_env env,
      +                                napi_callback_info cbinfo,
      +                                napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] cbinfo: The callback info passed into the callback function.
      • +
      • [out] result: The new.target of the constructor call.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the new.target of the constructor call. If the current +callback is not a constructor call, the result is NULL.

      +

      napi_new_instance#

      + +
      napi_status napi_new_instance(napi_env env,
      +                              napi_value cons,
      +                              size_t argc,
      +                              napi_value* argv,
      +                              napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] cons: napi_value representing the JavaScript function to be invoked +as a constructor.
      • +
      • [in] argc: The count of elements in the argv array.
      • +
      • [in] argv: Array of JavaScript values as napi_value representing the +arguments to the constructor.
      • +
      • [out] result: napi_value representing the JavaScript object returned, +which in this case is the constructed object.
      • +
      +

      This method is used to instantiate a new JavaScript value using a given +napi_value that represents the constructor for the object. For example, +consider the following snippet:

      +
      function MyObject(param) {
      +  this.param = param;
      +}
      +
      +const arg = 'hello';
      +const value = new MyObject(arg);
      +

      The following can be approximated in N-API using the following snippet:

      +
      // Get the constructor function MyObject
      +napi_value global, constructor, arg, value;
      +napi_status status = napi_get_global(env, &global);
      +if (status != napi_ok) return;
      +
      +status = napi_get_named_property(env, global, "MyObject", &constructor);
      +if (status != napi_ok) return;
      +
      +// const arg = "hello"
      +status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg);
      +if (status != napi_ok) return;
      +
      +napi_value* argv = &arg;
      +size_t argc = 1;
      +
      +// const value = new MyObject(arg)
      +status = napi_new_instance(env, constructor, argc, argv, &value);
      +

      Returns napi_ok if the API succeeded.

      +

      Object wrap#

      +

      N-API offers a way to "wrap" C++ classes and instances so that the class +constructor and methods can be called from JavaScript.

      +
        +
      1. The napi_define_class API defines a JavaScript class with constructor, +static properties and methods, and instance properties and methods that +correspond to the C++ class.
      2. +
      3. When JavaScript code invokes the constructor, the constructor callback +uses napi_wrap to wrap a new C++ instance in a JavaScript object, +then returns the wrapper object.
      4. +
      5. When JavaScript code invokes a method or property accessor on the class, +the corresponding napi_callback C++ function is invoked. For an instance +callback, napi_unwrap obtains the C++ instance that is the target of +the call.
      6. +
      +

      For wrapped objects it may be difficult to distinguish between a function +called on a class prototype and a function called on an instance of a class. +A common pattern used to address this problem is to save a persistent +reference to the class constructor for later instanceof checks.

      +
      napi_value MyClass_constructor = NULL;
      +status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);
      +assert(napi_ok == status);
      +bool is_instance = false;
      +status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);
      +assert(napi_ok == status);
      +if (is_instance) {
      +  // napi_unwrap() ...
      +} else {
      +  // otherwise...
      +}
      +

      The reference must be freed once it is no longer needed.

      +

      There are occasions where napi_instanceof() is insufficient for ensuring that +a JavaScript object is a wrapper for a certain native type. This is the case +especially when wrapped JavaScript objects are passed back into the addon via +static methods rather than as the this value of prototype methods. In such +cases there is a chance that they may be unwrapped incorrectly.

      +
      const myAddon = require('./build/Release/my_addon.node');
      +
      +// `openDatabase()` returns a JavaScript object that wraps a native database
      +// handle.
      +const dbHandle = myAddon.openDatabase();
      +
      +// `query()` returns a JavaScript object that wraps a native query handle.
      +const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!');
      +
      +// There is an accidental error in the line below. The first parameter to
      +// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not
      +// the query handle (`query`), so the correct condition for the while-loop
      +// should be
      +//
      +// myAddon.queryHasRecords(dbHandle, queryHandle)
      +//
      +while (myAddon.queryHasRecords(queryHandle, dbHandle)) {
      +  // retrieve records
      +}
      +

      In the above example myAddon.queryHasRecords() is a method that accepts two +arguments. The first is a database handle and the second is a query handle. +Internally, it unwraps the first argument and casts the resulting pointer to a +native database handle. It then unwraps the second argument and casts the +resulting pointer to a query handle. If the arguments are passed in the wrong +order, the casts will work, however, there is a good chance that the underlying +database operation will fail, or will even cause an invalid memory access.

      +

      To ensure that the pointer retrieved from the first argument is indeed a pointer +to a database handle and, similarly, that the pointer retrieved from the second +argument is indeed a pointer to a query handle, the implementation of +queryHasRecords() has to perform a type validation. Retaining the JavaScript +class constructor from which the database handle was instantiated and the +constructor from which the query handle was instantiated in napi_refs can +help, because napi_instanceof() can then be used to ensure that the instances +passed into queryHashRecords() are indeed of the correct type.

      +

      Unfortunately, napi_instanceof() does not protect against prototype +manipulation. For example, the prototype of the database handle instance can be +set to the prototype of the constructor for query handle instances. In this +case, the database handle instance can appear as a query handle instance, and it +will pass the napi_instanceof() test for a query handle instance, while still +containing a pointer to a database handle.

      +

      To this end, N-API provides type-tagging capabilities.

      +

      A type tag is a 128-bit integer unique to the addon. N-API provides the +napi_type_tag structure for storing a type tag. When such a value is passed +along with a JavaScript object stored in a napi_value to +napi_type_tag_object(), the JavaScript object will be "marked" with the +type tag. The "mark" is invisible on the JavaScript side. When a JavaScript +object arrives into a native binding, napi_check_object_type_tag() can be used +along with the original type tag to determine whether the JavaScript object was +previously "marked" with the type tag. This creates a type-checking capability +of a higher fidelity than napi_instanceof() can provide, because such type- +tagging survives prototype manipulation and addon unloading/reloading.

      +

      Continuing the above example, the following skeleton addon implementation +illustrates the use of napi_type_tag_object() and +napi_check_object_type_tag().

      +
      // This value is the type tag for a database handle. The command
      +//
      +//   uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/'
      +//
      +// can be used to obtain the two values with which to initialize the structure.
      +static const napi_type_tag DatabaseHandleTypeTag = {
      +  0x1edf75a38336451d, 0xa5ed9ce2e4c00c38
      +};
      +
      +// This value is the type tag for a query handle.
      +static const napi_type_tag QueryHandleTypeTag = {
      +  0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a
      +};
      +
      +static napi_value
      +openDatabase(napi_env env, napi_callback_info info) {
      +  napi_status status;
      +  napi_value result;
      +
      +  // Perform the underlying action which results in a database handle.
      +  DatabaseHandle* dbHandle = open_database();
      +
      +  // Create a new, empty JS object.
      +  status = napi_create_object(env, &result);
      +  if (status != napi_ok) return NULL;
      +
      +  // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.
      +  status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);
      +  if (status != napi_ok) return NULL;
      +
      +  // Store the pointer to the `DatabaseHandle` structure inside the JS object.
      +  status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL);
      +  if (status != napi_ok) return NULL;
      +
      +  return result;
      +}
      +
      +// Later when we receive a JavaScript object purporting to be a database handle
      +// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a
      +// handle.
      +
      +static napi_value
      +query(napi_env env, napi_callback_info info) {
      +  napi_status status;
      +  size_t argc = 2;
      +  napi_value argv[2];
      +  bool is_db_handle;
      +
      +  status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
      +  if (status != napi_ok) return NULL;
      +
      +  // Check that the object passed as the first parameter has the previously
      +  // applied tag.
      +  status = napi_check_object_type_tag(env,
      +                                      argv[0],
      +                                      &DatabaseHandleTypeTag,
      +                                      &is_db_handle);
      +  if (status != napi_ok) return NULL;
      +
      +  // Throw a `TypeError` if it doesn't.
      +  if (!is_db_handle) {
      +    // Throw a TypeError.
      +    return NULL;
      +  }
      +}
      +

      napi_define_class#

      + +
      napi_status napi_define_class(napi_env env,
      +                              const char* utf8name,
      +                              size_t length,
      +                              napi_callback constructor,
      +                              void* data,
      +                              size_t property_count,
      +                              const napi_property_descriptor* properties,
      +                              napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] utf8name: Name of the JavaScript constructor function; this is +not required to be the same as the C++ class name, though it is recommended +for clarity.
      • +
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH +if it is null-terminated.
      • +
      • [in] constructor: Callback function that handles constructing instances +of the class. This should be a static method on the class, not an actual +C++ constructor function. napi_callback provides more details.
      • +
      • [in] data: Optional data to be passed to the constructor callback as +the data property of the callback info.
      • +
      • [in] property_count: Number of items in the properties array argument.
      • +
      • [in] properties: Array of property descriptors describing static and +instance data properties, accessors, and methods on the class +See napi_property_descriptor.
      • +
      • [out] result: A napi_value representing the constructor function for +the class.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Defines a JavaScript class that corresponds to a C++ class, including:

      +
        +
      • A JavaScript constructor function that has the class name and invokes the +provided C++ constructor callback.
      • +
      • Properties on the constructor function corresponding to static data +properties, accessors, and methods of the C++ class (defined by +property descriptors with the napi_static attribute).
      • +
      • Properties on the constructor function's prototype object corresponding to +non-static data properties, accessors, and methods of the C++ class +(defined by property descriptors without the napi_static attribute).
      • +
      +

      The C++ constructor callback should be a static method on the class that calls +the actual class constructor, then wraps the new C++ instance in a JavaScript +object, and returns the wrapper object. See napi_wrap() for details.

      +

      The JavaScript constructor function returned from napi_define_class is +often saved and used later, to construct new instances of the class from native +code, and/or check whether provided values are instances of the class. In that +case, to prevent the function value from being garbage-collected, create a +persistent reference to it using napi_create_reference and ensure the +reference count is kept >= 1.

      +

      Any non-NULL data which is passed to this API via the data parameter or via +the data field of the napi_property_descriptor array items can be associated +with the resulting JavaScript constructor (which is returned in the result +parameter) and freed whenever the class is garbage-collected by passing both +the JavaScript function and the data to napi_add_finalizer.

      +

      napi_wrap#

      + +
      napi_status napi_wrap(napi_env env,
      +                      napi_value js_object,
      +                      void* native_object,
      +                      napi_finalize finalize_cb,
      +                      void* finalize_hint,
      +                      napi_ref* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object that will be the wrapper for the +native object.
      • +
      • [in] native_object: The native instance that will be wrapped in the +JavaScript object.
      • +
      • [in] finalize_cb: Optional native callback that can be used to free the +native instance when the JavaScript object is ready for garbage-collection. +napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional contextual hint that is passed to the +finalize callback.
      • +
      • [out] result: Optional reference to the wrapped object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Wraps a native instance in a JavaScript object. The native instance can be +retrieved later using napi_unwrap().

      +

      When JavaScript code invokes a constructor for a class that was defined using +napi_define_class(), the napi_callback for the constructor is invoked. +After constructing an instance of the native class, the callback must then call +napi_wrap() to wrap the newly constructed instance in the already-created +JavaScript object that is the this argument to the constructor callback. +(That this object was created from the constructor function's prototype, +so it already has definitions of all the instance properties and methods.)

      +

      Typically when wrapping a class instance, a finalize callback should be +provided that simply deletes the native instance that is received as the data +argument to the finalize callback.

      +

      The optional returned reference is initially a weak reference, meaning it +has a reference count of 0. Typically this reference count would be incremented +temporarily during async operations that require the instance to remain valid.

      +

      Caution: The optional returned reference (if obtained) should be deleted via +napi_delete_reference ONLY in response to the finalize callback +invocation. If it is deleted before then, then the finalize callback may never +be invoked. Therefore, when obtaining a reference a finalize callback is also +required in order to enable correct disposal of the reference.

      +

      Calling napi_wrap() a second time on an object will return an error. To +associate another native instance with the object, use napi_remove_wrap() +first.

      +

      napi_unwrap#

      + +
      napi_status napi_unwrap(napi_env env,
      +                        napi_value js_object,
      +                        void** result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The object associated with the native instance.
      • +
      • [out] result: Pointer to the wrapped native instance.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Retrieves a native instance that was previously wrapped in a JavaScript +object using napi_wrap().

      +

      When JavaScript code invokes a method or property accessor on the class, the +corresponding napi_callback is invoked. If the callback is for an instance +method or accessor, then the this argument to the callback is the wrapper +object; the wrapped C++ instance that is the target of the call can be obtained +then by calling napi_unwrap() on the wrapper object.

      +

      napi_remove_wrap#

      + +
      napi_status napi_remove_wrap(napi_env env,
      +                             napi_value js_object,
      +                             void** result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The object associated with the native instance.
      • +
      • [out] result: Pointer to the wrapped native instance.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Retrieves a native instance that was previously wrapped in the JavaScript +object js_object using napi_wrap() and removes the wrapping. If a finalize +callback was associated with the wrapping, it will no longer be called when the +JavaScript object becomes garbage-collected.

      +

      napi_type_tag_object#

      + +
      napi_status napi_type_tag_object(napi_env env,
      +                                 napi_value js_object,
      +                                 const napi_type_tag* type_tag);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object to be marked.
      • +
      • [in] type_tag: The tag with which the object is to be marked.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Associates the value of the type_tag pointer with the JavaScript object. +napi_check_object_type_tag() can then be used to compare the tag that was +attached to the object with one owned by the addon to ensure that the object +has the right type.

      +

      If the object already has an associated type tag, this API will return +napi_invalid_arg.

      +

      napi_check_object_type_tag#

      + +
      napi_status napi_check_object_type_tag(napi_env env,
      +                                       napi_value js_object,
      +                                       const napi_type_tag* type_tag,
      +                                       bool* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object whose type tag to examine.
      • +
      • [in] type_tag: The tag with which to compare any tag found on the object.
      • +
      • [out] result: Whether the type tag given matched the type tag on the +object. false is also returned if no type tag was found on the object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Compares the pointer given as type_tag with any that can be found on +js_object. If no tag is found on js_object or, if a tag is found but it does +not match type_tag, then result is set to false. If a tag is found and it +matches type_tag, then result is set to true.

      +

      napi_add_finalizer#

      + +
      napi_status napi_add_finalizer(napi_env env,
      +                               napi_value js_object,
      +                               void* native_object,
      +                               napi_finalize finalize_cb,
      +                               void* finalize_hint,
      +                               napi_ref* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object to which the native data will be +attached.
      • +
      • [in] native_object: The native data that will be attached to the JavaScript +object.
      • +
      • [in] finalize_cb: Native callback that will be used to free the +native data when the JavaScript object is ready for garbage-collection. +napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional contextual hint that is passed to the +finalize callback.
      • +
      • [out] result: Optional reference to the JavaScript object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Adds a napi_finalize callback which will be called when the JavaScript object +in js_object is ready for garbage collection. This API is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the API can be called multiple times with different data items in order to +attach each of them to the JavaScript object, and
      • +
      • the object manipulated by the API can be used with napi_wrap().
      • +
      +

      Caution: The optional returned reference (if obtained) should be deleted via +napi_delete_reference ONLY in response to the finalize callback +invocation. If it is deleted before then, then the finalize callback may never +be invoked. Therefore, when obtaining a reference a finalize callback is also +required in order to enable correct disposal of the reference.

      +

      Simple asynchronous operations#

      +

      Addon modules often need to leverage async helpers from libuv as part of their +implementation. This allows them to schedule work to be executed asynchronously +so that their methods can return in advance of the work being completed. This +allows them to avoid blocking overall execution of the Node.js application.

      +

      N-API provides an ABI-stable interface for these +supporting functions which covers the most common asynchronous use cases.

      +

      N-API defines the napi_async_work structure which is used to manage +asynchronous workers. Instances are created/deleted with +napi_create_async_work and napi_delete_async_work.

      +

      The execute and complete callbacks are functions that will be +invoked when the executor is ready to execute and when it completes its +task respectively.

      +

      The execute function should avoid making any N-API calls +that could result in the execution of JavaScript or interaction with +JavaScript objects. Most often, any code that needs to make N-API +calls should be made in complete callback instead. +Avoid using the napi_env parameter in the execute callback as +it will likely execute JavaScript.

      +

      These functions implement the following interfaces:

      +
      typedef void (*napi_async_execute_callback)(napi_env env,
      +                                            void* data);
      +typedef void (*napi_async_complete_callback)(napi_env env,
      +                                             napi_status status,
      +                                             void* data);
      +

      When these methods are invoked, the data parameter passed will be the +addon-provided void* data that was passed into the +napi_create_async_work call.

      +

      Once created the async worker can be queued +for execution using the napi_queue_async_work function:

      +
      napi_status napi_queue_async_work(napi_env env,
      +                                  napi_async_work work);
      +

      napi_cancel_async_work can be used if the work needs +to be cancelled before the work has started execution.

      +

      After calling napi_cancel_async_work, the complete callback +will be invoked with a status value of napi_cancelled. +The work should not be deleted before the complete +callback invocation, even when it was cancelled.

      +

      napi_create_async_work#

      + +
      napi_status napi_create_async_work(napi_env env,
      +                                   napi_value async_resource,
      +                                   napi_value async_resource_name,
      +                                   napi_async_execute_callback execute,
      +                                   napi_async_complete_callback complete,
      +                                   void* data,
      +                                   napi_async_work* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_resource: An optional object associated with the async work +that will be passed to possible async_hooks init hooks.
      • +
      • [in] async_resource_name: Identifier for the kind of resource that is being +provided for diagnostic information exposed by the async_hooks API.
      • +
      • [in] execute: The native function which should be called to execute the +logic asynchronously. The given function is called from a worker pool thread +and can execute in parallel with the main event loop thread.
      • +
      • [in] complete: The native function which will be called when the +asynchronous logic is completed or is cancelled. The given function is called +from the main event loop thread. napi_async_complete_callback provides +more details.
      • +
      • [in] data: User-provided data context. This will be passed back into the +execute and complete functions.
      • +
      • [out] result: napi_async_work* which is the handle to the newly created +async work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a work object that is used to execute logic asynchronously. +It should be freed using napi_delete_async_work once the work is no longer +required.

      +

      async_resource_name should be a null-terminated, UTF-8-encoded string.

      +

      The async_resource_name identifier is provided by the user and should be +representative of the type of async work being performed. It is also recommended +to apply namespacing to the identifier, e.g. by including the module name. See +the async_hooks documentation for more information.

      +

      napi_delete_async_work#

      + +
      napi_status napi_delete_async_work(napi_env env,
      +                                   napi_async_work work);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] work: The handle returned by the call to napi_create_async_work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API frees a previously allocated work object.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_queue_async_work#

      + +
      napi_status napi_queue_async_work(napi_env env,
      +                                  napi_async_work work);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] work: The handle returned by the call to napi_create_async_work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API requests that the previously allocated work be scheduled +for execution. Once it returns successfully, this API must not be called again +with the same napi_async_work item or the result will be undefined.

      +

      napi_cancel_async_work#

      + +
      napi_status napi_cancel_async_work(napi_env env,
      +                                   napi_async_work work);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] work: The handle returned by the call to napi_create_async_work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API cancels queued work if it has not yet +been started. If it has already started executing, it cannot be +cancelled and napi_generic_failure will be returned. If successful, +the complete callback will be invoked with a status value of +napi_cancelled. The work should not be deleted before the complete +callback invocation, even if it has been successfully cancelled.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Custom asynchronous operations#

      +

      The simple asynchronous work APIs above may not be appropriate for every +scenario. When using any other asynchronous mechanism, the following APIs +are necessary to ensure an asynchronous operation is properly tracked by +the runtime.

      +

      napi_async_init#

      + +
      napi_status napi_async_init(napi_env env,
      +                            napi_value async_resource,
      +                            napi_value async_resource_name,
      +                            napi_async_context* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_resource: Object associated with the async work +that will be passed to possible async_hooks init hooks. +In order to retain ABI compatibility with previous versions, +passing NULL for async_resource will not result in an error, however, +this will result incorrect operation of async hooks for the +napi_async_context created. Potential issues include +loss of async context when using the AsyncLocalStorage API.
      • +
      • [in] async_resource_name: Identifier for the kind of resource +that is being provided for diagnostic information exposed by the +async_hooks API.
      • +
      • [out] result: The initialized async context.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      napi_async_destroy#

      + +
      napi_status napi_async_destroy(napi_env env,
      +                               napi_async_context async_context);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_context: The async context to be destroyed.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_make_callback#

      + +
      NAPI_EXTERN napi_status napi_make_callback(napi_env env,
      +                                           napi_async_context async_context,
      +                                           napi_value recv,
      +                                           napi_value func,
      +                                           size_t argc,
      +                                           const napi_value* argv,
      +                                           napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_context: Context for the async operation that is +invoking the callback. This should normally be a value previously +obtained from napi_async_init. However NULL is also allowed, +which indicates the current async context (if any) is to be used +for the callback.
      • +
      • [in] recv: The this object passed to the called function.
      • +
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • +
      • [in] argc: The count of elements in the argv array.
      • +
      • [in] argv: Array of JavaScript values as napi_value representing the +arguments to the function.
      • +
      • [out] result: napi_value representing the JavaScript object returned.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method allows a JavaScript function object to be called from a native +add-on. This API is similar to napi_call_function. However, it is used to call +from native code back into JavaScript after returning from an async +operation (when there is no other script on the stack). It is a fairly simple +wrapper around node::MakeCallback.

      +

      Note it is not necessary to use napi_make_callback from within a +napi_async_complete_callback; in that situation the callback's async +context has already been set up, so a direct call to napi_call_function +is sufficient and appropriate. Use of the napi_make_callback function +may be required when implementing custom async behavior that does not use +napi_create_async_work.

      +

      Any process.nextTicks or Promises scheduled on the microtask queue by +JavaScript during the callback are ran before returning back to C/C++.

      +

      napi_open_callback_scope#

      + +
      NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,
      +                                                 napi_value resource_object,
      +                                                 napi_async_context context,
      +                                                 napi_callback_scope* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] resource_object: An object associated with the async work +that will be passed to possible async_hooks init hooks.
      • +
      • [in] context: Context for the async operation that is invoking the callback. +This should be a value previously obtained from napi_async_init.
      • +
      • [out] result: The newly created scope.
      • +
      +

      There are cases (for example, resolving promises) where it is +necessary to have the equivalent of the scope associated with a callback +in place when making certain N-API calls. If there is no other script on +the stack the napi_open_callback_scope and +napi_close_callback_scope functions can be used to open/close +the required scope.

      +

      napi_close_callback_scope#

      + +
      NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,
      +                                                  napi_callback_scope scope)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: The scope to be closed.
      • +
      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Version management#

      +

      napi_get_node_version#

      + +
      typedef struct {
      +  uint32_t major;
      +  uint32_t minor;
      +  uint32_t patch;
      +  const char* release;
      +} napi_node_version;
      +
      +napi_status napi_get_node_version(napi_env env,
      +                                  const napi_node_version** version);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] version: A pointer to version information for Node.js itself.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This function fills the version struct with the major, minor, and patch +version of Node.js that is currently running, and the release field with the +value of process.release.name.

      +

      The returned buffer is statically allocated and does not need to be freed.

      +

      napi_get_version#

      + +
      napi_status napi_get_version(napi_env env,
      +                             uint32_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: The highest version of N-API supported.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the highest N-API version supported by the +Node.js runtime. N-API is planned to be additive such that +newer releases of Node.js may support additional API functions. +In order to allow an addon to use a newer function when running with +versions of Node.js that support it, while providing +fallback behavior when running with Node.js versions that don't +support it:

      +
        +
      • Call napi_get_version() to determine if the API is available.
      • +
      • If available, dynamically load a pointer to the function using uv_dlsym().
      • +
      • Use the dynamically loaded pointer to invoke the function.
      • +
      • If the function is not available, provide an alternate implementation +that does not use the function.
      • +
      +

      Memory management#

      +

      napi_adjust_external_memory#

      + +
      NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,
      +                                                    int64_t change_in_bytes,
      +                                                    int64_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] change_in_bytes: The change in externally allocated memory that is kept +alive by JavaScript objects.
      • +
      • [out] result: The adjusted value
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This function gives V8 an indication of the amount of externally allocated +memory that is kept alive by JavaScript objects (i.e. a JavaScript object +that points to its own memory allocated by a native module). Registering +externally allocated memory will trigger global garbage collections more +often than it would otherwise.

      +

      Promises#

      +

      N-API provides facilities for creating Promise objects as described in +Section 25.4 of the ECMA specification. It implements promises as a pair of +objects. When a promise is created by napi_create_promise(), a "deferred" +object is created and returned alongside the Promise. The deferred object is +bound to the created Promise and is the only means to resolve or reject the +Promise using napi_resolve_deferred() or napi_reject_deferred(). The +deferred object that is created by napi_create_promise() is freed by +napi_resolve_deferred() or napi_reject_deferred(). The Promise object may +be returned to JavaScript where it can be used in the usual fashion.

      +

      For example, to create a promise and pass it to an asynchronous worker:

      +
      napi_deferred deferred;
      +napi_value promise;
      +napi_status status;
      +
      +// Create the promise.
      +status = napi_create_promise(env, &deferred, &promise);
      +if (status != napi_ok) return NULL;
      +
      +// Pass the deferred to a function that performs an asynchronous action.
      +do_something_asynchronous(deferred);
      +
      +// Return the promise to JS
      +return promise;
      +

      The above function do_something_asynchronous() would perform its asynchronous +action and then it would resolve or reject the deferred, thereby concluding the +promise and freeing the deferred:

      +
      napi_deferred deferred;
      +napi_value undefined;
      +napi_status status;
      +
      +// Create a value with which to conclude the deferred.
      +status = napi_get_undefined(env, &undefined);
      +if (status != napi_ok) return NULL;
      +
      +// Resolve or reject the promise associated with the deferred depending on
      +// whether the asynchronous action succeeded.
      +if (asynchronous_action_succeeded) {
      +  status = napi_resolve_deferred(env, deferred, undefined);
      +} else {
      +  status = napi_reject_deferred(env, deferred, undefined);
      +}
      +if (status != napi_ok) return NULL;
      +
      +// At this point the deferred has been freed, so we should assign NULL to it.
      +deferred = NULL;
      +

      napi_create_promise#

      + +
      napi_status napi_create_promise(napi_env env,
      +                                napi_deferred* deferred,
      +                                napi_value* promise);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] deferred: A newly created deferred object which can later be passed to +napi_resolve_deferred() or napi_reject_deferred() to resolve resp. reject +the associated promise.
      • +
      • [out] promise: The JavaScript promise associated with the deferred object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a deferred object and a JavaScript promise.

      +

      napi_resolve_deferred#

      + +
      napi_status napi_resolve_deferred(napi_env env,
      +                                  napi_deferred deferred,
      +                                  napi_value resolution);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] deferred: The deferred object whose associated promise to resolve.
      • +
      • [in] resolution: The value with which to resolve the promise.
      • +
      +

      This API resolves a JavaScript promise by way of the deferred object +with which it is associated. Thus, it can only be used to resolve JavaScript +promises for which the corresponding deferred object is available. This +effectively means that the promise must have been created using +napi_create_promise() and the deferred object returned from that call must +have been retained in order to be passed to this API.

      +

      The deferred object is freed upon successful completion.

      +

      napi_reject_deferred#

      + +
      napi_status napi_reject_deferred(napi_env env,
      +                                 napi_deferred deferred,
      +                                 napi_value rejection);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] deferred: The deferred object whose associated promise to resolve.
      • +
      • [in] rejection: The value with which to reject the promise.
      • +
      +

      This API rejects a JavaScript promise by way of the deferred object +with which it is associated. Thus, it can only be used to reject JavaScript +promises for which the corresponding deferred object is available. This +effectively means that the promise must have been created using +napi_create_promise() and the deferred object returned from that call must +have been retained in order to be passed to this API.

      +

      The deferred object is freed upon successful completion.

      +

      napi_is_promise#

      + +
      napi_status napi_is_promise(napi_env env,
      +                            napi_value value,
      +                            bool* is_promise);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The value to examine
      • +
      • [out] is_promise: Flag indicating whether promise is a native promise +object (that is, a promise object created by the underlying engine).
      • +
      +

      Script execution#

      +

      N-API provides an API for executing a string containing JavaScript using the +underlying JavaScript engine.

      +

      napi_run_script#

      + +
      NAPI_EXTERN napi_status napi_run_script(napi_env env,
      +                                        napi_value script,
      +                                        napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] script: A JavaScript string containing the script to execute.
      • +
      • [out] result: The value resulting from having executed the script.
      • +
      +

      This function executes a string of JavaScript code and returns its result with +the following caveats:

      +
        +
      • Unlike eval, this function does not allow the script to access the current +lexical scope, and therefore also does not allow to access the +module scope, meaning that pseudo-globals such as require will not be +available.
      • +
      • The script can access the global scope. Function and var declarations +in the script will be added to the global object. Variable declarations +made using let and const will be visible globally, but will not be added +to the global object.
      • +
      • The value of this is global within the script.
      • +
      +

      libuv event loop#

      +

      N-API provides a function for getting the current event loop associated with +a specific napi_env.

      +

      napi_get_uv_event_loop#

      + +
      NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,
      +                                               struct uv_loop_s** loop);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] loop: The current libuv loop instance.
      • +
      +

      Asynchronous thread-safe function calls#

      +

      JavaScript functions can normally only be called from a native addon's main +thread. If an addon creates additional threads, then N-API functions that +require a napi_env, napi_value, or napi_ref must not be called from those +threads.

      +

      When an addon has additional threads and JavaScript functions need to be invoked +based on the processing completed by those threads, those threads must +communicate with the addon's main thread so that the main thread can invoke the +JavaScript function on their behalf. The thread-safe function APIs provide an +easy way to do this.

      +

      These APIs provide the type napi_threadsafe_function as well as APIs to +create, destroy, and call objects of this type. +napi_create_threadsafe_function() creates a persistent reference to a +napi_value that holds a JavaScript function which can be called from multiple +threads. The calls happen asynchronously. This means that values with which the +JavaScript callback is to be called will be placed in a queue, and, for each +value in the queue, a call will eventually be made to the JavaScript function.

      +

      Upon creation of a napi_threadsafe_function a napi_finalize callback can be +provided. This callback will be invoked on the main thread when the thread-safe +function is about to be destroyed. It receives the context and the finalize data +given during construction, and provides an opportunity for cleaning up after the +threads e.g. by calling uv_thread_join(). Aside from the main loop thread, +no threads should be using the thread-safe function after the finalize callback +completes.

      +

      The context given during the call to napi_create_threadsafe_function() can +be retrieved from any thread with a call to +napi_get_threadsafe_function_context().

      +

      Calling a thread-safe function#

      +

      napi_call_threadsafe_function() can be used for initiating a call into +JavaScript. napi_call_threadsafe_function() accepts a parameter which controls +whether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API +behaves non-blockingly, returning napi_queue_full if the queue was full, +preventing data from being successfully added to the queue. If set to +napi_tsfn_blocking, the API blocks until space becomes available in the queue. +napi_call_threadsafe_function() never blocks if the thread-safe function was +created with a maximum queue size of 0.

      +

      The actual call into JavaScript is controlled by the callback given via the +call_js_cb parameter. call_js_cb is invoked on the main thread once for each +value that was placed into the queue by a successful call to +napi_call_threadsafe_function(). If such a callback is not given, a default +callback will be used, and the resulting JavaScript call will have no arguments. +The call_js_cb callback receives the JavaScript function to call as a +napi_value in its parameters, as well as the void* context pointer used when +creating the napi_threadsafe_function, and the next data pointer that was +created by one of the secondary threads. The callback can then use an API such +as napi_call_function() to call into JavaScript.

      +

      The callback may also be invoked with env and call_js_cb both set to NULL +to indicate that calls into JavaScript are no longer possible, while items +remain in the queue that may need to be freed. This normally occurs when the +Node.js process exits while there is a thread-safe function still active.

      +

      It is not necessary to call into JavaScript via napi_make_callback() because +N-API runs call_js_cb in a context appropriate for callbacks.

      +

      Reference counting of thread-safe functions#

      +

      Threads can be added to and removed from a napi_threadsafe_function object +during its existence. Thus, in addition to specifying an initial number of +threads upon creation, napi_acquire_threadsafe_function can be called to +indicate that a new thread will start making use of the thread-safe function. +Similarly, napi_release_threadsafe_function can be called to indicate that an +existing thread will stop making use of the thread-safe function.

      +

      napi_threadsafe_function objects are destroyed when every thread which uses +the object has called napi_release_threadsafe_function() or has received a +return status of napi_closing in response to a call to +napi_call_threadsafe_function. The queue is emptied before the +napi_threadsafe_function is destroyed. napi_release_threadsafe_function() +should be the last API call made in conjunction with a given +napi_threadsafe_function, because after the call completes, there is no +guarantee that the napi_threadsafe_function is still allocated. For the same +reason, do not use a thread-safe function +after receiving a return value of napi_closing in response to a call to +napi_call_threadsafe_function. Data associated with the +napi_threadsafe_function can be freed in its napi_finalize callback which +was passed to napi_create_threadsafe_function(). The parameter +initial_thread_count of napi_create_threadsafe_function marks the initial +number of aquisitions of the thread-safe functions, instead of calling +napi_acquire_threadsafe_function multiple times at creation.

      +

      Once the number of threads making use of a napi_threadsafe_function reaches +zero, no further threads can start making use of it by calling +napi_acquire_threadsafe_function(). In fact, all subsequent API calls +associated with it, except napi_release_threadsafe_function(), will return an +error value of napi_closing.

      +

      The thread-safe function can be "aborted" by giving a value of napi_tsfn_abort +to napi_release_threadsafe_function(). This will cause all subsequent APIs +associated with the thread-safe function except +napi_release_threadsafe_function() to return napi_closing even before its +reference count reaches zero. In particular, napi_call_threadsafe_function() +will return napi_closing, thus informing the threads that it is no longer +possible to make asynchronous calls to the thread-safe function. This can be +used as a criterion for terminating the thread. Upon receiving a return value +of napi_closing from napi_call_threadsafe_function() a thread must not use +the thread-safe function anymore because it is no longer guaranteed to +be allocated.

      +

      Deciding whether to keep the process running#

      +

      Similarly to libuv handles, thread-safe functions can be "referenced" and +"unreferenced". A "referenced" thread-safe function will cause the event loop on +the thread on which it is created to remain alive until the thread-safe function +is destroyed. In contrast, an "unreferenced" thread-safe function will not +prevent the event loop from exiting. The APIs napi_ref_threadsafe_function and +napi_unref_threadsafe_function exist for this purpose.

      +

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as +able to be destroyed nor does napi_ref_threadsafe_function prevent it from +being destroyed.

      +

      napi_create_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_create_threadsafe_function(napi_env env,
      +                                napi_value func,
      +                                napi_value async_resource,
      +                                napi_value async_resource_name,
      +                                size_t max_queue_size,
      +                                size_t initial_thread_count,
      +                                void* thread_finalize_data,
      +                                napi_finalize thread_finalize_cb,
      +                                void* context,
      +                                napi_threadsafe_function_call_js call_js_cb,
      +                                napi_threadsafe_function* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] func: An optional JavaScript function to call from another thread. It +must be provided if NULL is passed to call_js_cb.
      • +
      • [in] async_resource: An optional object associated with the async work that +will be passed to possible async_hooks init hooks.
      • +
      • [in] async_resource_name: A JavaScript string to provide an identifier for +the kind of resource that is being provided for diagnostic information exposed +by the async_hooks API.
      • +
      • [in] max_queue_size: Maximum size of the queue. 0 for no limit.
      • +
      • [in] initial_thread_count: The initial number of acquisitions, i.e. the +initial number of threads, including the main thread, which will be making use +of this function.
      • +
      • [in] thread_finalize_data: Optional data to be passed to thread_finalize_cb.
      • +
      • [in] thread_finalize_cb: Optional function to call when the +napi_threadsafe_function is being destroyed.
      • +
      • [in] context: Optional data to attach to the resulting +napi_threadsafe_function.
      • +
      • [in] call_js_cb: Optional callback which calls the JavaScript function in +response to a call on a different thread. This callback will be called on the +main thread. If not given, the JavaScript function will be called with no +parameters and with undefined as its this value. +napi_threadsafe_function_call_js provides more details.
      • +
      • [out] result: The asynchronous thread-safe JavaScript function.
      • +
      +

      napi_get_threadsafe_function_context#

      + +
      NAPI_EXTERN napi_status
      +napi_get_threadsafe_function_context(napi_threadsafe_function func,
      +                                     void** result);
      +
        +
      • [in] func: The thread-safe function for which to retrieve the context.
      • +
      • [out] result: The location where to store the context.
      • +
      +

      This API may be called from any thread which makes use of func.

      +

      napi_call_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_call_threadsafe_function(napi_threadsafe_function func,
      +                              void* data,
      +                              napi_threadsafe_function_call_mode is_blocking);
      +
        +
      • [in] func: The asynchronous thread-safe JavaScript function to invoke.
      • +
      • [in] data: Data to send into JavaScript via the callback call_js_cb +provided during the creation of the thread-safe JavaScript function.
      • +
      • [in] is_blocking: Flag whose value can be either napi_tsfn_blocking to +indicate that the call should block if the queue is full or +napi_tsfn_nonblocking to indicate that the call should return immediately +with a status of napi_queue_full whenever the queue is full.
      • +
      +

      This API will return napi_closing if napi_release_threadsafe_function() was +called with abort set to napi_tsfn_abort from any thread. The value is only +added to the queue if the API returns napi_ok.

      +

      This API may be called from any thread which makes use of func.

      +

      napi_acquire_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_acquire_threadsafe_function(napi_threadsafe_function func);
      +
        +
      • [in] func: The asynchronous thread-safe JavaScript function to start making +use of.
      • +
      +

      A thread should call this API before passing func to any other thread-safe +function APIs to indicate that it will be making use of func. This prevents +func from being destroyed when all other threads have stopped making use of +it.

      +

      This API may be called from any thread which will start making use of func.

      +

      napi_release_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_release_threadsafe_function(napi_threadsafe_function func,
      +                                 napi_threadsafe_function_release_mode mode);
      +
        +
      • [in] func: The asynchronous thread-safe JavaScript function whose reference +count to decrement.
      • +
      • [in] mode: Flag whose value can be either napi_tsfn_release to indicate +that the current thread will make no further calls to the thread-safe +function, or napi_tsfn_abort to indicate that in addition to the current +thread, no other thread should make any further calls to the thread-safe +function. If set to napi_tsfn_abort, further calls to +napi_call_threadsafe_function() will return napi_closing, and no further +values will be placed in the queue.
      • +
      +

      A thread should call this API when it stops making use of func. Passing func +to any thread-safe APIs after having called this API has undefined results, as +func may have been destroyed.

      +

      This API may be called from any thread which will stop making use of func.

      +

      napi_ref_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] func: The thread-safe function to reference.
      • +
      +

      This API is used to indicate that the event loop running on the main thread +should not exit until func has been destroyed. Similar to uv_ref it is +also idempotent.

      +

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as +able to be destroyed nor does napi_ref_threadsafe_function prevent it from +being destroyed. napi_acquire_threadsafe_function and +napi_release_threadsafe_function are available for that purpose.

      +

      This API may only be called from the main thread.

      +

      napi_unref_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] func: The thread-safe function to unreference.
      • +
      +

      This API is used to indicate that the event loop running on the main thread +may exit before func is destroyed. Similar to uv_unref it is also +idempotent.

      +

      This API may only be called from the main thread.

      +

      Miscellaneous utilities#

      +

      node_api_get_module_file_name#

      + +

      Stability: 1 - Experimental

      +
      NAPI_EXTERN napi_status
      +node_api_get_module_file_name(napi_env env, const char** result);
      +
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: A URL containing the absolute path of the +location from which the add-on was loaded. For a file on the local +file system it will start with file://. The string is null-terminated and +owned by env and must thus not be modified or freed.
      • +
      +

      result may be an empty string if the add-on loading process fails to establish +the add-on's file name during loading.

      +

      C++ Embedder API#

      + +

      Node.js provides a number of C++ APIs that can be used to execute JavaScript +in a Node.js environment from other C++ software.

      +

      The documentation for these APIs can be found in src/node.h in the Node.js +source tree. In addition to the APIs exposed by Node.js, some required concepts +are provided by the V8 embedder API.

      +

      Because using Node.js as an embedded library is different from writing code +that is executed by Node.js, breaking changes do not follow typical Node.js +deprecation policy and may occur on each semver-major release without prior +warning.

      +

      Example embedding application#

      +

      The following sections will provide an overview over how to use these APIs +to create an application from scratch that will perform the equivalent of +node -e <code>, i.e. that will take a piece of JavaScript and run it in +a Node.js-specific environment.

      +

      The full code can be found in the Node.js source tree.

      +

      Setting up per-process state#

      +

      Node.js requires some per-process state management in order to run:

      +
        +
      • Arguments parsing for Node.js CLI options,
      • +
      • V8 per-process requirements, such as a v8::Platform instance.
      • +
      +

      The following example shows how these can be set up. Some class names are from +the node and v8 C++ namespaces, respectively.

      +
      int main(int argc, char** argv) {
      +  argv = uv_setup_args(argc, argv);
      +  std::vector<std::string> args(argv, argv + argc);
      +  std::vector<std::string> exec_args;
      +  std::vector<std::string> errors;
      +  // Parse Node.js CLI options, and print any errors that have occurred while
      +  // trying to parse them.
      +  int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);
      +  for (const std::string& error : errors)
      +    fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
      +  if (exit_code != 0) {
      +    return exit_code;
      +  }
      +
      +  // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way
      +  // to create a v8::Platform instance that Node.js can use when creating
      +  // Worker threads. When no `MultiIsolatePlatform` instance is present,
      +  // Worker threads are disabled.
      +  std::unique_ptr<MultiIsolatePlatform> platform =
      +      MultiIsolatePlatform::Create(4);
      +  V8::InitializePlatform(platform.get());
      +  V8::Initialize();
      +
      +  // See below for the contents of this function.
      +  int ret = RunNodeInstance(platform.get(), args, exec_args);
      +
      +  V8::Dispose();
      +  V8::ShutdownPlatform();
      +  return ret;
      +}
      +

      Per-instance state#

      +

      Node.js has a concept of a “Node.js instanceâ€, that is commonly being referred +to as node::Environment. Each node::Environment is associated with:

      +
        +
      • Exactly one v8::Isolate, i.e. one JS Engine instance,
      • +
      • Exactly one uv_loop_t, i.e. one event loop, and
      • +
      • A number of v8::Contexts, but exactly one main v8::Context.
      • +
      • One node::IsolateData instance that contains information that could be +shared by multiple node::Environments that use the same v8::Isolate. +Currently, no testing if performed for this scenario.
      • +
      +

      In order to set up a v8::Isolate, an v8::ArrayBuffer::Allocator needs +to be provided. One possible choice is the default Node.js allocator, which +can be created through node::ArrayBufferAllocator::Create(). Using the Node.js +allocator allows minor performance optimizations when addons use the Node.js +C++ Buffer API, and is required in order to track ArrayBuffer memory in +process.memoryUsage().

      +

      Additionally, each v8::Isolate that is used for a Node.js instance needs to +be registered and unregistered with the MultiIsolatePlatform instance, if one +is being used, in order for the platform to know which event loop to use +for tasks scheduled by the v8::Isolate.

      +

      The node::NewIsolate() helper function creates a v8::Isolate, +sets it up with some Node.js-specific hooks (e.g. the Node.js error handler), +and registers it with the platform automatically.

      +
      int RunNodeInstance(MultiIsolatePlatform* platform,
      +                    const std::vector<std::string>& args,
      +                    const std::vector<std::string>& exec_args) {
      +  int exit_code = 0;
      +  // Set up a libuv event loop.
      +  uv_loop_t loop;
      +  int ret = uv_loop_init(&loop);
      +  if (ret != 0) {
      +    fprintf(stderr, "%s: Failed to initialize loop: %s\n",
      +            args[0].c_str(),
      +            uv_err_name(ret));
      +    return 1;
      +  }
      +
      +  std::shared_ptr<ArrayBufferAllocator> allocator =
      +      ArrayBufferAllocator::Create();
      +
      +  Isolate* isolate = NewIsolate(allocator, &loop, platform);
      +  if (isolate == nullptr) {
      +    fprintf(stderr, "%s: Failed to initialize V8 Isolate\n", args[0].c_str());
      +    return 1;
      +  }
      +
      +  {
      +    Locker locker(isolate);
      +    Isolate::Scope isolate_scope(isolate);
      +
      +    // Create a node::IsolateData instance that will later be released using
      +    // node::FreeIsolateData().
      +    std::unique_ptr<IsolateData, decltype(&node::FreeIsolateData)> isolate_data(
      +        node::CreateIsolateData(isolate, &loop, platform, allocator.get()),
      +        node::FreeIsolateData);
      +
      +    // Set up a new v8::Context.
      +    HandleScope handle_scope(isolate);
      +    Local<Context> context = node::NewContext(isolate);
      +    if (context.IsEmpty()) {
      +      fprintf(stderr, "%s: Failed to initialize V8 Context\n", args[0].c_str());
      +      return 1;
      +    }
      +
      +    // The v8::Context needs to be entered when node::CreateEnvironment() and
      +    // node::LoadEnvironment() are being called.
      +    Context::Scope context_scope(context);
      +
      +    // Create a node::Environment instance that will later be released using
      +    // node::FreeEnvironment().
      +    std::unique_ptr<Environment, decltype(&node::FreeEnvironment)> env(
      +        node::CreateEnvironment(isolate_data.get(), context, args, exec_args),
      +        node::FreeEnvironment);
      +
      +    // Set up the Node.js instance for execution, and run code inside of it.
      +    // There is also a variant that takes a callback and provides it with
      +    // the `require` and `process` objects, so that it can manually compile
      +    // and run scripts as needed.
      +    // The `require` function inside this script does *not* access the file
      +    // system, and can only load built-in Node.js modules.
      +    // `module.createRequire()` is being used to create one that is able to
      +    // load files from the disk, and uses the standard CommonJS file loader
      +    // instead of the internal-only `require` function.
      +    MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(
      +        env.get(),
      +        "const publicRequire ="
      +        "  require('module').createRequire(process.cwd() + '/');"
      +        "globalThis.require = publicRequire;"
      +        "require('vm').runInThisContext(process.argv[1]);");
      +
      +    if (loadenv_ret.IsEmpty())  // There has been a JS exception.
      +      return 1;
      +
      +    {
      +      // SealHandleScope protects against handle leaks from callbacks.
      +      SealHandleScope seal(isolate);
      +      bool more;
      +      do {
      +        uv_run(&loop, UV_RUN_DEFAULT);
      +
      +        // V8 tasks on background threads may end up scheduling new tasks in the
      +        // foreground, which in turn can keep the event loop going. For example,
      +        // WebAssembly.compile() may do so.
      +        platform->DrainTasks(isolate);
      +
      +        // If there are new tasks, continue.
      +        more = uv_loop_alive(&loop);
      +        if (more) continue;
      +
      +        // node::EmitBeforeExit() is used to emit the 'beforeExit' event on
      +        // the `process` object.
      +        node::EmitBeforeExit(env.get());
      +
      +        // 'beforeExit' can also schedule new work that keeps the event loop
      +        // running.
      +        more = uv_loop_alive(&loop);
      +      } while (more == true);
      +    }
      +
      +    // node::EmitExit() returns the current exit code.
      +    exit_code = node::EmitExit(env.get());
      +
      +    // node::Stop() can be used to explicitly stop the event loop and keep
      +    // further JavaScript from running. It can be called from any thread,
      +    // and will act like worker.terminate() if called from another thread.
      +    node::Stop(env.get());
      +  }
      +
      +  // Unregister the Isolate with the platform and add a listener that is called
      +  // when the Platform is done cleaning up any state it had associated with
      +  // the Isolate.
      +  bool platform_finished = false;
      +  platform->AddIsolateFinishedCallback(isolate, [](void* data) {
      +    *static_cast<bool*>(data) = true;
      +  }, &platform_finished);
      +  platform->UnregisterIsolate(isolate);
      +  isolate->Dispose();
      +
      +  // Wait until the platform has cleaned up all relevant resources.
      +  while (!platform_finished)
      +    uv_run(&loop, UV_RUN_ONCE);
      +  int err = uv_loop_close(&loop);
      +  assert(err == 0);
      +
      +  return exit_code;
      +}
      +

      Child process#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/child_process.js

      +

      The child_process module provides the ability to spawn child processes in +a manner that is similar, but not identical, to popen(3). This capability +is primarily provided by the child_process.spawn() function:

      +
      const { spawn } = require('child_process');
      +const ls = spawn('ls', ['-lh', '/usr']);
      +
      +ls.stdout.on('data', (data) => {
      +  console.log(`stdout: ${data}`);
      +});
      +
      +ls.stderr.on('data', (data) => {
      +  console.error(`stderr: ${data}`);
      +});
      +
      +ls.on('close', (code) => {
      +  console.log(`child process exited with code ${code}`);
      +});
      +

      By default, pipes for stdin, stdout, and stderr are established between +the parent Node.js process and the spawned child. These pipes have +limited (and platform-specific) capacity. If the child process writes to +stdout in excess of that limit without the output being captured, the child +process will block waiting for the pipe buffer to accept more data. This is +identical to the behavior of pipes in the shell. Use the { stdio: 'ignore' } +option if the output will not be consumed.

      +

      The command lookup will be performed using options.env.PATH environment +variable if passed in options object, otherwise process.env.PATH will be +used. To account for the fact that Windows environment variables are +case-insensitive Node.js will lexicographically sort all env keys and choose +the first one case-insensitively matching PATH to perform command lookup. +This may lead to issues on Windows when passing objects to env option that +have multiple variants of PATH variable.

      +

      The child_process.spawn() method spawns the child process asynchronously, +without blocking the Node.js event loop. The child_process.spawnSync() +function provides equivalent functionality in a synchronous manner that blocks +the event loop until the spawned process either exits or is terminated.

      +

      For convenience, the child_process module provides a handful of synchronous +and asynchronous alternatives to child_process.spawn() and +child_process.spawnSync(). Each of these alternatives are implemented on +top of child_process.spawn() or child_process.spawnSync().

      + +

      For certain use cases, such as automating shell scripts, the +synchronous counterparts may be more convenient. In many cases, however, +the synchronous methods can have significant impact on performance due to +stalling the event loop while spawned processes complete.

      +

      Asynchronous process creation#

      +

      The child_process.spawn(), child_process.fork(), child_process.exec(), +and child_process.execFile() methods all follow the idiomatic asynchronous +programming pattern typical of other Node.js APIs.

      +

      Each of the methods returns a ChildProcess instance. These objects +implement the Node.js EventEmitter API, allowing the parent process to +register listener functions that are called when certain events occur during +the life cycle of the child process.

      +

      The child_process.exec() and child_process.execFile() methods +additionally allow for an optional callback function to be specified that is +invoked when the child process terminates.

      +

      Spawning .bat and .cmd files on Windows#

      +

      The importance of the distinction between child_process.exec() and +child_process.execFile() can vary based on platform. On Unix-type +operating systems (Unix, Linux, macOS) child_process.execFile() can be +more efficient because it does not spawn a shell by default. On Windows, +however, .bat and .cmd files are not executable on their own without a +terminal, and therefore cannot be launched using child_process.execFile(). +When running on Windows, .bat and .cmd files can be invoked using +child_process.spawn() with the shell option set, with +child_process.exec(), or by spawning cmd.exe and passing the .bat or +.cmd file as an argument (which is what the shell option and +child_process.exec() do). In any case, if the script filename contains +spaces it needs to be quoted.

      +
      // On Windows Only...
      +const { spawn } = require('child_process');
      +const bat = spawn('cmd.exe', ['/c', 'my.bat']);
      +
      +bat.stdout.on('data', (data) => {
      +  console.log(data.toString());
      +});
      +
      +bat.stderr.on('data', (data) => {
      +  console.error(data.toString());
      +});
      +
      +bat.on('exit', (code) => {
      +  console.log(`Child exited with code ${code}`);
      +});
      +
      // OR...
      +const { exec, spawn } = require('child_process');
      +exec('my.bat', (err, stdout, stderr) => {
      +  if (err) {
      +    console.error(err);
      +    return;
      +  }
      +  console.log(stdout);
      +});
      +
      +// Script with spaces in the filename:
      +const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
      +// or:
      +exec('"my script.cmd" a b', (err, stdout, stderr) => {
      +  // ...
      +});
      +

      child_process.exec(command[, options][, callback])#

      + + +

      Spawns a shell then executes the command within that shell, buffering any +generated output. The command string passed to the exec function is processed +directly by the shell and special characters (vary based on +shell) +need to be dealt with accordingly:

      +
      exec('"/path/to/test file/test.sh" arg1 arg2');
      +// Double quotes are used so that the space in the path is not interpreted as
      +// a delimiter of multiple arguments.
      +
      +exec('echo "The \\$HOME variable is $HOME"');
      +// The $HOME variable is escaped in the first instance, but not in the second.
      +

      Never pass unsanitized user input to this function. Any input containing shell +metacharacters may be used to trigger arbitrary command execution.

      +

      If a callback function is provided, it is called with the arguments +(error, stdout, stderr). On success, error will be null. On error, +error will be an instance of Error. The error.code property will be +the exit code of the process. By convention, any exit code other than 0 +indicates an error. error.signal will be the signal that terminated the +process.

      +

      The stdout and stderr arguments passed to the callback will contain the +stdout and stderr output of the child process. By default, Node.js will decode +the output as UTF-8 and pass strings to the callback. The encoding option +can be used to specify the character encoding used to decode the stdout and +stderr output. If encoding is 'buffer', or an unrecognized character +encoding, Buffer objects will be passed to the callback instead.

      +
      const { exec } = require('child_process');
      +exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
      +  if (error) {
      +    console.error(`exec error: ${error}`);
      +    return;
      +  }
      +  console.log(`stdout: ${stdout}`);
      +  console.error(`stderr: ${stderr}`);
      +});
      +

      If timeout is greater than 0, the parent will send the signal +identified by the killSignal property (the default is 'SIGTERM') if the +child runs longer than timeout milliseconds.

      +

      Unlike the exec(3) POSIX system call, child_process.exec() does not replace +the existing process and uses a shell to execute the command.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with stdout and stderr properties. The returned +ChildProcess instance is attached to the Promise as a child property. In +case of an error (including any error resulting in an exit code other than 0), a +rejected promise is returned, with the same error object given in the +callback, but with two additional properties stdout and stderr.

      +
      const util = require('util');
      +const exec = util.promisify(require('child_process').exec);
      +
      +async function lsExample() {
      +  const { stdout, stderr } = await exec('ls');
      +  console.log('stdout:', stdout);
      +  console.error('stderr:', stderr);
      +}
      +lsExample();
      +

      child_process.execFile(file[, args][, options][, callback])#

      + +
        +
      • file <string> The name or path of the executable file to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • encoding <string> Default: 'utf8'
        • +
        • timeout <number> Default: 0
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated and any output is +truncated. See caveat at maxBuffer and Unicode. +Default: 1024 * 1024.
        • +
        • killSignal <string> | <integer> Default: 'SIGTERM'
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. Default: false.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        +
      • +
      • callback <Function> Called with the output when process terminates. + +
      • +
      • Returns: <ChildProcess>
      • +
      +

      The child_process.execFile() function is similar to child_process.exec() +except that it does not spawn a shell by default. Rather, the specified +executable file is spawned directly as a new process making it slightly more +efficient than child_process.exec().

      +

      The same options as child_process.exec() are supported. Since a shell is +not spawned, behaviors such as I/O redirection and file globbing are not +supported.

      +
      const { execFile } = require('child_process');
      +const child = execFile('node', ['--version'], (error, stdout, stderr) => {
      +  if (error) {
      +    throw error;
      +  }
      +  console.log(stdout);
      +});
      +

      The stdout and stderr arguments passed to the callback will contain the +stdout and stderr output of the child process. By default, Node.js will decode +the output as UTF-8 and pass strings to the callback. The encoding option +can be used to specify the character encoding used to decode the stdout and +stderr output. If encoding is 'buffer', or an unrecognized character +encoding, Buffer objects will be passed to the callback instead.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with stdout and stderr properties. The returned +ChildProcess instance is attached to the Promise as a child property. In +case of an error (including any error resulting in an exit code other than 0), a +rejected promise is returned, with the same error object given in the +callback, but with two additional properties stdout and stderr.

      +
      const util = require('util');
      +const execFile = util.promisify(require('child_process').execFile);
      +async function getVersion() {
      +  const { stdout } = await execFile('node', ['--version']);
      +  console.log(stdout);
      +}
      +getVersion();
      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      child_process.fork(modulePath[, args][, options])#

      + +
        +
      • modulePath <string> The module to run in the child.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • detached <boolean> Prepare child to run independently of its parent +process. Specific behavior depends on the platform, see +options.detached).
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • execPath <string> Executable used to create the child process.
        • +
        • execArgv <string[]> List of string arguments passed to the executable. +Default: process.execArgv.
        • +
        • serialization <string> Specify the kind of serialization used for sending +messages between processes. Possible values are 'json' and 'advanced'. +See Advanced serialization for more details. Default: 'json'.
        • +
        • silent <boolean> If true, stdin, stdout, and stderr of the child will be +piped to the parent, otherwise they will be inherited from the parent, see +the 'pipe' and 'inherit' options for child_process.spawn()'s +stdio for more details. Default: false.
        • +
        • stdio <Array> | <string> See child_process.spawn()'s stdio. +When this option is provided, it overrides silent. If the array variant +is used, it must contain exactly one item with value 'ipc' or an error +will be thrown. For instance [0, 1, 2, 'ipc'].
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. Default: false.
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        +
      • +
      • Returns: <ChildProcess>
      • +
      +

      The child_process.fork() method is a special case of +child_process.spawn() used specifically to spawn new Node.js processes. +Like child_process.spawn(), a ChildProcess object is returned. The +returned ChildProcess will have an additional communication channel +built-in that allows messages to be passed back and forth between the parent and +child. See subprocess.send() for details.

      +

      Keep in mind that spawned Node.js child processes are +independent of the parent with exception of the IPC communication channel +that is established between the two. Each process has its own memory, with +their own V8 instances. Because of the additional resource allocations +required, spawning a large number of child Node.js processes is not +recommended.

      +

      By default, child_process.fork() will spawn new Node.js instances using the +process.execPath of the parent process. The execPath property in the +options object allows for an alternative execution path to be used.

      +

      Node.js processes launched with a custom execPath will communicate with the +parent process using the file descriptor (fd) identified using the +environment variable NODE_CHANNEL_FD on the child process.

      +

      Unlike the fork(2) POSIX system call, child_process.fork() does not clone the +current process.

      +

      The shell option available in child_process.spawn() is not supported by +child_process.fork() and will be ignored if set.

      +

      child_process.spawn(command[, args][, options])#

      + +
        +
      • command <string> The command to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • argv0 <string> Explicitly set the value of argv[0] sent to the child +process. This will be set to command if not specified.
        • +
        • stdio <Array> | <string> Child's stdio configuration (see +options.stdio).
        • +
        • detached <boolean> Prepare child to run independently of its parent +process. Specific behavior depends on the platform, see +options.detached).
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • serialization <string> Specify the kind of serialization used for sending +messages between processes. Possible values are 'json' and 'advanced'. +See Advanced serialization for more details. Default: 'json'.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. This is set to true automatically +when shell is specified and is CMD. Default: false.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      • Returns: <ChildProcess>
      • +
      +

      The child_process.spawn() method spawns a new process using the given +command, with command line arguments in args. If omitted, args defaults +to an empty array.

      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      A third argument may be used to specify additional options, with these defaults:

      +
      const defaults = {
      +  cwd: undefined,
      +  env: process.env
      +};
      +

      Use cwd to specify the working directory from which the process is spawned. +If not given, the default is to inherit the current working directory.

      +

      Use env to specify environment variables that will be visible to the new +process, the default is process.env.

      +

      undefined values in env will be ignored.

      +

      Example of running ls -lh /usr, capturing stdout, stderr, and the +exit code:

      +
      const { spawn } = require('child_process');
      +const ls = spawn('ls', ['-lh', '/usr']);
      +
      +ls.stdout.on('data', (data) => {
      +  console.log(`stdout: ${data}`);
      +});
      +
      +ls.stderr.on('data', (data) => {
      +  console.error(`stderr: ${data}`);
      +});
      +
      +ls.on('close', (code) => {
      +  console.log(`child process exited with code ${code}`);
      +});
      +

      Example: A very elaborate way to run ps ax | grep ssh

      +
      const { spawn } = require('child_process');
      +const ps = spawn('ps', ['ax']);
      +const grep = spawn('grep', ['ssh']);
      +
      +ps.stdout.on('data', (data) => {
      +  grep.stdin.write(data);
      +});
      +
      +ps.stderr.on('data', (data) => {
      +  console.error(`ps stderr: ${data}`);
      +});
      +
      +ps.on('close', (code) => {
      +  if (code !== 0) {
      +    console.log(`ps process exited with code ${code}`);
      +  }
      +  grep.stdin.end();
      +});
      +
      +grep.stdout.on('data', (data) => {
      +  console.log(data.toString());
      +});
      +
      +grep.stderr.on('data', (data) => {
      +  console.error(`grep stderr: ${data}`);
      +});
      +
      +grep.on('close', (code) => {
      +  if (code !== 0) {
      +    console.log(`grep process exited with code ${code}`);
      +  }
      +});
      +

      Example of checking for failed spawn:

      +
      const { spawn } = require('child_process');
      +const subprocess = spawn('bad_command');
      +
      +subprocess.on('error', (err) => {
      +  console.error('Failed to start subprocess.');
      +});
      +

      Certain platforms (macOS, Linux) will use the value of argv[0] for the process +title while others (Windows, SunOS) will use command.

      +

      Node.js currently overwrites argv[0] with process.execPath on startup, so +process.argv[0] in a Node.js child process will not match the argv0 +parameter passed to spawn from the parent, retrieve it with the +process.argv0 property instead.

      +

      options.detached#

      + +

      On Windows, setting options.detached to true makes it possible for the +child process to continue running after the parent exits. The child will have +its own console window. Once enabled for a child process, it cannot be +disabled.

      +

      On non-Windows platforms, if options.detached is set to true, the child +process will be made the leader of a new process group and session. Child +processes may continue running after the parent exits regardless of whether +they are detached or not. See setsid(2) for more information.

      +

      By default, the parent will wait for the detached child to exit. To prevent the +parent from waiting for a given subprocess to exit, use the +subprocess.unref() method. Doing so will cause the parent's event loop to not +include the child in its reference count, allowing the parent to exit +independently of the child, unless there is an established IPC channel between +the child and the parent.

      +

      When using the detached option to start a long-running process, the process +will not stay running in the background after the parent exits unless it is +provided with a stdio configuration that is not connected to the parent. +If the parent's stdio is inherited, the child will remain attached to the +controlling terminal.

      +

      Example of a long-running process, by detaching and also ignoring its parent +stdio file descriptors, in order to ignore the parent's termination:

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn(process.argv[0], ['child_program.js'], {
      +  detached: true,
      +  stdio: 'ignore'
      +});
      +
      +subprocess.unref();
      +

      Alternatively one can redirect the child process' output into files:

      +
      const fs = require('fs');
      +const { spawn } = require('child_process');
      +const out = fs.openSync('./out.log', 'a');
      +const err = fs.openSync('./out.log', 'a');
      +
      +const subprocess = spawn('prg', [], {
      +  detached: true,
      +  stdio: [ 'ignore', out, err ]
      +});
      +
      +subprocess.unref();
      +

      options.stdio#

      + +

      The options.stdio option is used to configure the pipes that are established +between the parent and child process. By default, the child's stdin, stdout, +and stderr are redirected to corresponding subprocess.stdin, +subprocess.stdout, and subprocess.stderr streams on the +ChildProcess object. This is equivalent to setting the options.stdio +equal to ['pipe', 'pipe', 'pipe'].

      +

      For convenience, options.stdio may be one of the following strings:

      +
        +
      • 'pipe': equivalent to ['pipe', 'pipe', 'pipe'] (the default)
      • +
      • 'ignore': equivalent to ['ignore', 'ignore', 'ignore']
      • +
      • 'inherit': equivalent to ['inherit', 'inherit', 'inherit'] or [0, 1, 2]
      • +
      +

      Otherwise, the value of options.stdio is an array where each index corresponds +to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout, +and stderr, respectively. Additional fds can be specified to create additional +pipes between the parent and child. The value is one of the following:

      +
        +
      1. +

        'pipe': Create a pipe between the child process and the parent process. +The parent end of the pipe is exposed to the parent as a property on the +child_process object as subprocess.stdio[fd]. Pipes +created for fds 0, 1, and 2 are also available as subprocess.stdin, +subprocess.stdout and subprocess.stderr, respectively.

        +
      2. +
      3. +

        'ipc': Create an IPC channel for passing messages/file descriptors +between parent and child. A ChildProcess may have at most one IPC +stdio file descriptor. Setting this option enables the +subprocess.send() method. If the child is a Node.js process, the +presence of an IPC channel will enable process.send() and +process.disconnect() methods, as well as 'disconnect' and +'message' events within the child.

        +

        Accessing the IPC channel fd in any way other than process.send() +or using the IPC channel with a child process that is not a Node.js instance +is not supported.

        +
      4. +
      5. +

        'ignore': Instructs Node.js to ignore the fd in the child. While Node.js +will always open fds 0, 1, and 2 for the processes it spawns, setting the fd +to 'ignore' will cause Node.js to open /dev/null and attach it to the +child's fd.

        +
      6. +
      7. +

        'inherit': Pass through the corresponding stdio stream to/from the +parent process. In the first three positions, this is equivalent to +process.stdin, process.stdout, and process.stderr, respectively. In +any other position, equivalent to 'ignore'.

        +
      8. +
      9. +

        <Stream> object: Share a readable or writable stream that refers to a tty, +file, socket, or a pipe with the child process. The stream's underlying +file descriptor is duplicated in the child process to the fd that +corresponds to the index in the stdio array. The stream must have an +underlying descriptor (file streams do not until the 'open' event has +occurred).

        +
      10. +
      11. +

        Positive integer: The integer value is interpreted as a file descriptor +that is currently open in the parent process. It is shared with the child +process, similar to how <Stream> objects can be shared. Passing sockets +is not supported on Windows.

        +
      12. +
      13. +

        null, undefined: Use default value. For stdio fds 0, 1, and 2 (in other +words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the +default is 'ignore'.

        +
      14. +
      +
      const { spawn } = require('child_process');
      +
      +// Child will use parent's stdios.
      +spawn('prg', [], { stdio: 'inherit' });
      +
      +// Spawn child sharing only stderr.
      +spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
      +
      +// Open an extra fd=4, to interact with programs presenting a
      +// startd-style interface.
      +spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
      +

      It is worth noting that when an IPC channel is established between the +parent and child processes, and the child is a Node.js process, the child +is launched with the IPC channel unreferenced (using unref()) until the +child registers an event handler for the 'disconnect' event +or the 'message' event. This allows the child to exit +normally without the process being held open by the open IPC channel.

      +

      On Unix-like operating systems, the child_process.spawn() method +performs memory operations synchronously before decoupling the event loop +from the child. Applications with a large memory footprint may find frequent +child_process.spawn() calls to be a bottleneck. For more information, +see V8 issue 7381.

      +

      See also: child_process.exec() and child_process.fork().

      +

      Synchronous process creation#

      +

      The child_process.spawnSync(), child_process.execSync(), and +child_process.execFileSync() methods are synchronous and will block the +Node.js event loop, pausing execution of any additional code until the spawned +process exits.

      +

      Blocking calls like these are mostly useful for simplifying general-purpose +scripting tasks and for simplifying the loading/processing of application +configuration at startup.

      +

      child_process.execFileSync(file[, args][, options])#

      + +
        +
      • file <string> The name or path of the executable file to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • input <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed +as stdin to the spawned process. Supplying this value will override +stdio[0].
        • +
        • stdio <string> | <Array> Child's stdio configuration. stderr by default will +be output to the parent process' stderr unless stdio is specified. +Default: 'pipe'.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • timeout <number> In milliseconds the maximum amount of time the process +is allowed to run. Default: undefined.
        • +
        • killSignal <string> | <integer> The signal value to be used when the spawned +process will be killed. Default: 'SIGTERM'.
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated. See caveat at +maxBuffer and Unicode. Default: 1024 * 1024.
        • +
        • encoding <string> The encoding used for all stdio inputs and outputs. +Default: 'buffer'.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        +
      • +
      • Returns: <Buffer> | <string> The stdout from the command.
      • +
      +

      The child_process.execFileSync() method is generally identical to +child_process.execFile() with the exception that the method will not +return until the child process has fully closed. When a timeout has been +encountered and killSignal is sent, the method won't return until the process +has completely exited.

      +

      If the child process intercepts and handles the SIGTERM signal and +does not exit, the parent process will still wait until the child process has +exited.

      +

      If the process times out or has a non-zero exit code, this method will throw an +Error that will include the full result of the underlying +child_process.spawnSync().

      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      child_process.execSync(command[, options])#

      + +
        +
      • command <string> The command to run.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • input <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed +as stdin to the spawned process. Supplying this value will override +stdio[0].
        • +
        • stdio <string> | <Array> Child's stdio configuration. stderr by default will +be output to the parent process' stderr unless stdio is specified. +Default: 'pipe'.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • shell <string> Shell to execute the command with. See +Shell requirements and Default Windows shell. Default: +'/bin/sh' on Unix, process.env.ComSpec on Windows.
        • +
        • uid <number> Sets the user identity of the process. (See setuid(2)).
        • +
        • gid <number> Sets the group identity of the process. (See setgid(2)).
        • +
        • timeout <number> In milliseconds the maximum amount of time the process +is allowed to run. Default: undefined.
        • +
        • killSignal <string> | <integer> The signal value to be used when the spawned +process will be killed. Default: 'SIGTERM'.
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated and any output is +truncated. See caveat at maxBuffer and Unicode. +Default: 1024 * 1024.
        • +
        • encoding <string> The encoding used for all stdio inputs and outputs. +Default: 'buffer'.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      • Returns: <Buffer> | <string> The stdout from the command.
      • +
      +

      The child_process.execSync() method is generally identical to +child_process.exec() with the exception that the method will not return +until the child process has fully closed. When a timeout has been encountered +and killSignal is sent, the method won't return until the process has +completely exited. If the child process intercepts and handles the SIGTERM +signal and doesn't exit, the parent process will wait until the child process +has exited.

      +

      If the process times out or has a non-zero exit code, this method will throw. +The Error object will contain the entire result from +child_process.spawnSync().

      +

      Never pass unsanitized user input to this function. Any input containing shell +metacharacters may be used to trigger arbitrary command execution.

      +

      child_process.spawnSync(command[, args][, options])#

      + +
        +
      • command <string> The command to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • input <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed +as stdin to the spawned process. Supplying this value will override +stdio[0].
        • +
        • argv0 <string> Explicitly set the value of argv[0] sent to the child +process. This will be set to command if not specified.
        • +
        • stdio <string> | <Array> Child's stdio configuration.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • timeout <number> In milliseconds the maximum amount of time the process +is allowed to run. Default: undefined.
        • +
        • killSignal <string> | <integer> The signal value to be used when the spawned +process will be killed. Default: 'SIGTERM'.
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated and any output is +truncated. See caveat at maxBuffer and Unicode. +Default: 1024 * 1024.
        • +
        • encoding <string> The encoding used for all stdio inputs and outputs. +Default: 'buffer'.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. This is set to true automatically +when shell is specified and is CMD. Default: false.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      • Returns: <Object> +
          +
        • pid <number> Pid of the child process.
        • +
        • output <Array> Array of results from stdio output.
        • +
        • stdout <Buffer> | <string> The contents of output[1].
        • +
        • stderr <Buffer> | <string> The contents of output[2].
        • +
        • status <number> | <null> The exit code of the subprocess, or null if the +subprocess terminated due to a signal.
        • +
        • signal <string> | <null> The signal used to kill the subprocess, or null if +the subprocess did not terminate due to a signal.
        • +
        • error <Error> The error object if the child process failed or timed out.
        • +
        +
      • +
      +

      The child_process.spawnSync() method is generally identical to +child_process.spawn() with the exception that the function will not return +until the child process has fully closed. When a timeout has been encountered +and killSignal is sent, the method won't return until the process has +completely exited. If the process intercepts and handles the SIGTERM signal +and doesn't exit, the parent process will wait until the child process has +exited.

      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      Class: ChildProcess#

      + + +

      Instances of the ChildProcess represent spawned child processes.

      +

      Instances of ChildProcess are not intended to be created directly. Rather, +use the child_process.spawn(), child_process.exec(), +child_process.execFile(), or child_process.fork() methods to create +instances of ChildProcess.

      +

      Event: 'close'#

      + +
        +
      • code <number> The exit code if the child exited on its own.
      • +
      • signal <string> The signal by which the child process was terminated.
      • +
      +

      The 'close' event is emitted when the stdio streams of a child process have +been closed. This is distinct from the 'exit' event, since multiple +processes might share the same stdio streams.

      +
      const { spawn } = require('child_process');
      +const ls = spawn('ls', ['-lh', '/usr']);
      +
      +ls.stdout.on('data', (data) => {
      +  console.log(`stdout: ${data}`);
      +});
      +
      +ls.on('close', (code) => {
      +  console.log(`child process close all stdio with code ${code}`);
      +});
      +
      +ls.on('exit', (code) => {
      +  console.log(`child process exited with code ${code}`);
      +});
      +

      Event: 'disconnect'#

      + +

      The 'disconnect' event is emitted after calling the +subprocess.disconnect() method in parent process or +process.disconnect() in child process. After disconnecting it is no longer +possible to send or receive messages, and the subprocess.connected +property is false.

      +

      Event: 'error'#

      + +

      The 'error' event is emitted whenever:

      +
        +
      1. The process could not be spawned, or
      2. +
      3. The process could not be killed, or
      4. +
      5. Sending a message to the child process failed.
      6. +
      +

      The 'exit' event may or may not fire after an error has occurred. When +listening to both the 'exit' and 'error' events, guard +against accidentally invoking handler functions multiple times.

      +

      See also subprocess.kill() and subprocess.send().

      +

      Event: 'exit'#

      + +
        +
      • code <number> The exit code if the child exited on its own.
      • +
      • signal <string> The signal by which the child process was terminated.
      • +
      +

      The 'exit' event is emitted after the child process ends. If the process +exited, code is the final exit code of the process, otherwise null. If the +process terminated due to receipt of a signal, signal is the string name of +the signal, otherwise null. One of the two will always be non-null.

      +

      When the 'exit' event is triggered, child process stdio streams might still be +open.

      +

      Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js +processes will not terminate immediately due to receipt of those signals. +Rather, Node.js will perform a sequence of cleanup actions and then will +re-raise the handled signal.

      +

      See waitpid(2).

      +

      Event: 'message'#

      + + +

      The 'message' event is triggered when a child process uses +process.send() to send messages.

      +

      The message goes through serialization and parsing. The resulting +message might not be the same as what is originally sent.

      +

      If the serialization option was set to 'advanced' used when spawning the +child process, the message argument can contain data that JSON is not able +to represent. +See Advanced serialization for more details.

      +

      subprocess.channel#

      + +
        +
      • <Object> A pipe representing the IPC channel to the child process.
      • +
      +

      The subprocess.channel property is a reference to the child's IPC channel. If +no IPC channel currently exists, this property is undefined.

      +

      subprocess.connected#

      + +
        +
      • <boolean> Set to false after subprocess.disconnect() is called.
      • +
      +

      The subprocess.connected property indicates whether it is still possible to +send and receive messages from a child process. When subprocess.connected is +false, it is no longer possible to send or receive messages.

      +

      subprocess.disconnect()#

      + +

      Closes the IPC channel between parent and child, allowing the child to exit +gracefully once there are no other connections keeping it alive. After calling +this method the subprocess.connected and process.connected properties in +both the parent and child (respectively) will be set to false, and it will be +no longer possible to pass messages between the processes.

      +

      The 'disconnect' event will be emitted when there are no messages in the +process of being received. This will most often be triggered immediately after +calling subprocess.disconnect().

      +

      When the child process is a Node.js instance (e.g. spawned using +child_process.fork()), the process.disconnect() method can be invoked +within the child process to close the IPC channel as well.

      +

      subprocess.exitCode#

      + +

      The subprocess.exitCode property indicates the exit code of the child process. +If the child process is still running, the field will be null.

      +

      subprocess.kill([signal])#

      + + +

      The subprocess.kill() method sends a signal to the child process. If no +argument is given, the process will be sent the 'SIGTERM' signal. See +signal(7) for a list of available signals. This function returns true if +kill(2) succeeds, and false otherwise.

      +
      const { spawn } = require('child_process');
      +const grep = spawn('grep', ['ssh']);
      +
      +grep.on('close', (code, signal) => {
      +  console.log(
      +    `child process terminated due to receipt of signal ${signal}`);
      +});
      +
      +// Send SIGHUP to process.
      +grep.kill('SIGHUP');
      +

      The ChildProcess object may emit an 'error' event if the signal +cannot be delivered. Sending a signal to a child process that has already exited +is not an error but may have unforeseen consequences. Specifically, if the +process identifier (PID) has been reassigned to another process, the signal will +be delivered to that process instead which can have unexpected results.

      +

      While the function is called kill, the signal delivered to the child process +may not actually terminate the process.

      +

      See kill(2) for reference.

      +

      On Linux, child processes of child processes will not be terminated +when attempting to kill their parent. This is likely to happen when running a +new process in a shell or with the use of the shell option of ChildProcess:

      +
      'use strict';
      +const { spawn } = require('child_process');
      +
      +const subprocess = spawn(
      +  'sh',
      +  [
      +    '-c',
      +    `node -e "setInterval(() => {
      +      console.log(process.pid, 'is alive')
      +    }, 500);"`
      +  ], {
      +    stdio: ['inherit', 'inherit', 'inherit']
      +  }
      +);
      +
      +setTimeout(() => {
      +  subprocess.kill(); // Does not terminate the Node.js process in the shell.
      +}, 2000);
      +

      subprocess.killed#

      + +
        +
      • <boolean> Set to true after subprocess.kill() is used to successfully +send a signal to the child process.
      • +
      +

      The subprocess.killed property indicates whether the child process +successfully received a signal from subprocess.kill(). The killed property +does not indicate that the child process has been terminated.

      +

      subprocess.pid#

      + + +

      Returns the process identifier (PID) of the child process.

      +
      const { spawn } = require('child_process');
      +const grep = spawn('grep', ['ssh']);
      +
      +console.log(`Spawned child pid: ${grep.pid}`);
      +grep.stdin.end();
      +

      subprocess.ref()#

      + +

      Calling subprocess.ref() after making a call to subprocess.unref() will +restore the removed reference count for the child process, forcing the parent +to wait for the child to exit before exiting itself.

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn(process.argv[0], ['child_program.js'], {
      +  detached: true,
      +  stdio: 'ignore'
      +});
      +
      +subprocess.unref();
      +subprocess.ref();
      +

      subprocess.send(message[, sendHandle[, options]][, callback])#

      + +
        +
      • message <Object>
      • +
      • sendHandle <Handle>
      • +
      • options <Object> The options argument, if present, is an object used to +parameterize the sending of certain types of handles. options supports +the following properties: +
          +
        • keepOpen <boolean> A value that can be used when passing instances of +net.Socket. When true, the socket is kept open in the sending process. +Default: false.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <boolean>
      • +
      +

      When an IPC channel has been established between the parent and child ( +i.e. when using child_process.fork()), the subprocess.send() method can +be used to send messages to the child process. When the child process is a +Node.js instance, these messages can be received via the 'message' event.

      +

      The message goes through serialization and parsing. The resulting +message might not be the same as what is originally sent.

      +

      For example, in the parent script:

      +
      const cp = require('child_process');
      +const n = cp.fork(`${__dirname}/sub.js`);
      +
      +n.on('message', (m) => {
      +  console.log('PARENT got message:', m);
      +});
      +
      +// Causes the child to print: CHILD got message: { hello: 'world' }
      +n.send({ hello: 'world' });
      +

      And then the child script, 'sub.js' might look like this:

      +
      process.on('message', (m) => {
      +  console.log('CHILD got message:', m);
      +});
      +
      +// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
      +process.send({ foo: 'bar', baz: NaN });
      +

      Child Node.js processes will have a process.send() method of their own +that allows the child to send messages back to the parent.

      +

      There is a special case when sending a {cmd: 'NODE_foo'} message. Messages +containing a NODE_ prefix in the cmd property are reserved for use within +Node.js core and will not be emitted in the child's 'message' +event. Rather, such messages are emitted using the +'internalMessage' event and are consumed internally by Node.js. +Applications should avoid using such messages or listening for +'internalMessage' events as it is subject to change without notice.

      +

      The optional sendHandle argument that may be passed to subprocess.send() is +for passing a TCP server or socket object to the child process. The child will +receive the object as the second argument passed to the callback function +registered on the 'message' event. Any data that is received +and buffered in the socket will not be sent to the child.

      +

      The optional callback is a function that is invoked after the message is +sent but before the child may have received it. The function is called with a +single argument: null on success, or an Error object on failure.

      +

      If no callback function is provided and the message cannot be sent, an +'error' event will be emitted by the ChildProcess object. This can +happen, for instance, when the child process has already exited.

      +

      subprocess.send() will return false if the channel has closed or when the +backlog of unsent messages exceeds a threshold that makes it unwise to send +more. Otherwise, the method returns true. The callback function can be +used to implement flow control.

      +

      Example: sending a server object#

      +

      The sendHandle argument can be used, for instance, to pass the handle of +a TCP server object to the child process as illustrated in the example below:

      +
      const subprocess = require('child_process').fork('subprocess.js');
      +
      +// Open up the server object and send the handle.
      +const server = require('net').createServer();
      +server.on('connection', (socket) => {
      +  socket.end('handled by parent');
      +});
      +server.listen(1337, () => {
      +  subprocess.send('server', server);
      +});
      +

      The child would then receive the server object as:

      +
      process.on('message', (m, server) => {
      +  if (m === 'server') {
      +    server.on('connection', (socket) => {
      +      socket.end('handled by child');
      +    });
      +  }
      +});
      +

      Once the server is now shared between the parent and child, some connections +can be handled by the parent and some by the child.

      +

      While the example above uses a server created using the net module, dgram +module servers use exactly the same workflow with the exceptions of listening on +a 'message' event instead of 'connection' and using server.bind() instead +of server.listen(). This is, however, currently only supported on Unix +platforms.

      +

      Example: sending a socket object#

      +

      Similarly, the sendHandler argument can be used to pass the handle of a +socket to the child process. The example below spawns two children that each +handle connections with "normal" or "special" priority:

      +
      const { fork } = require('child_process');
      +const normal = fork('subprocess.js', ['normal']);
      +const special = fork('subprocess.js', ['special']);
      +
      +// Open up the server and send sockets to child. Use pauseOnConnect to prevent
      +// the sockets from being read before they are sent to the child process.
      +const server = require('net').createServer({ pauseOnConnect: true });
      +server.on('connection', (socket) => {
      +
      +  // If this is special priority...
      +  if (socket.remoteAddress === '74.125.127.100') {
      +    special.send('socket', socket);
      +    return;
      +  }
      +  // This is normal priority.
      +  normal.send('socket', socket);
      +});
      +server.listen(1337);
      +

      The subprocess.js would receive the socket handle as the second argument +passed to the event callback function:

      +
      process.on('message', (m, socket) => {
      +  if (m === 'socket') {
      +    if (socket) {
      +      // Check that the client socket exists.
      +      // It is possible for the socket to be closed between the time it is
      +      // sent and the time it is received in the child process.
      +      socket.end(`Request handled with ${process.argv[2]} priority`);
      +    }
      +  }
      +});
      +

      Do not use .maxConnections on a socket that has been passed to a subprocess. +The parent cannot track when the socket is destroyed.

      +

      Any 'message' handlers in the subprocess should verify that socket exists, +as the connection may have been closed during the time it takes to send the +connection to the child.

      +

      subprocess.signalCode#

      + +

      The subprocess.signalCode property indicates the signal number received by +the child process if any, else null.

      +

      subprocess.spawnargs#

      + +

      The subprocess.spawnargs property represents the full list of command line +arguments the child process was launched with.

      +

      subprocess.spawnfile#

      + +

      The subprocess.spawnfile property indicates the executable file name of +the child process that is launched.

      +

      For child_process.fork(), its value will be equal to +process.execPath. +For child_process.spawn(), its value will be the name of +the executable file. +For child_process.exec(), its value will be the name of the shell +in which the child process is launched.

      +

      subprocess.stderr#

      + + +

      A Readable Stream that represents the child process's stderr.

      +

      If the child was spawned with stdio[2] set to anything other than 'pipe', +then this will be null.

      +

      subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will +refer to the same value.

      +

      subprocess.stdin#

      + + +

      A Writable Stream that represents the child process's stdin.

      +

      If a child process waits to read all of its input, the child will not continue +until this stream has been closed via end().

      +

      If the child was spawned with stdio[0] set to anything other than 'pipe', +then this will be null.

      +

      subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will +refer to the same value.

      +

      subprocess.stdio#

      + + +

      A sparse array of pipes to the child process, corresponding with positions in +the stdio option passed to child_process.spawn() that have been set +to the value 'pipe'. subprocess.stdio[0], subprocess.stdio[1], and +subprocess.stdio[2] are also available as subprocess.stdin, +subprocess.stdout, and subprocess.stderr, respectively.

      +

      In the following example, only the child's fd 1 (stdout) is configured as a +pipe, so only the parent's subprocess.stdio[1] is a stream, all other values +in the array are null.

      +
      const assert = require('assert');
      +const fs = require('fs');
      +const child_process = require('child_process');
      +
      +const subprocess = child_process.spawn('ls', {
      +  stdio: [
      +    0, // Use parent's stdin for child.
      +    'pipe', // Pipe child's stdout to parent.
      +    fs.openSync('err.out', 'w') // Direct child's stderr to a file.
      +  ]
      +});
      +
      +assert.strictEqual(subprocess.stdio[0], null);
      +assert.strictEqual(subprocess.stdio[0], subprocess.stdin);
      +
      +assert(subprocess.stdout);
      +assert.strictEqual(subprocess.stdio[1], subprocess.stdout);
      +
      +assert.strictEqual(subprocess.stdio[2], null);
      +assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
      +

      subprocess.stdout#

      + + +

      A Readable Stream that represents the child process's stdout.

      +

      If the child was spawned with stdio[1] set to anything other than 'pipe', +then this will be null.

      +

      subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will +refer to the same value.

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn('ls');
      +
      +subprocess.stdout.on('data', (data) => {
      +  console.log(`Received chunk ${data}`);
      +});
      +

      subprocess.unref()#

      + +

      By default, the parent will wait for the detached child to exit. To prevent the +parent from waiting for a given subprocess to exit, use the +subprocess.unref() method. Doing so will cause the parent's event loop to not +include the child in its reference count, allowing the parent to exit +independently of the child, unless there is an established IPC channel between +the child and the parent.

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn(process.argv[0], ['child_program.js'], {
      +  detached: true,
      +  stdio: 'ignore'
      +});
      +
      +subprocess.unref();
      +

      maxBuffer and Unicode#

      +

      The maxBuffer option specifies the largest number of bytes allowed on stdout +or stderr. If this value is exceeded, then the child process is terminated. +This impacts output that includes multibyte character encodings such as UTF-8 or +UTF-16. For instance, console.log('中文测试') will send 13 UTF-8 encoded bytes +to stdout although there are only 4 characters.

      +

      Shell requirements#

      +

      The shell should understand the -c switch. If the shell is 'cmd.exe', it +should understand the /d /s /c switches and command line parsing should be +compatible.

      +

      Default Windows shell#

      +

      Although Microsoft specifies %COMSPEC% must contain the path to +'cmd.exe' in the root environment, child processes are not always subject to +the same requirement. Thus, in child_process functions where a shell can be +spawned, 'cmd.exe' is used as a fallback if process.env.ComSpec is +unavailable.

      +

      Advanced serialization#

      + +

      Child processes support a serialization mechanism for IPC that is based on the +serialization API of the v8 module, based on the +HTML structured clone algorithm. This is generally more powerful and +supports more built-in JavaScript object types, such as BigInt, Map +and Set, ArrayBuffer and TypedArray, Buffer, Error, RegExp etc.

      +

      However, this format is not a full superset of JSON, and e.g. properties set on +objects of such built-in types will not be passed on through the serialization +step. Additionally, performance may not be equivalent to that of JSON, depending +on the structure of the passed data. +Therefore, this feature requires opting in by setting the +serialization option to 'advanced' when calling child_process.spawn() +or child_process.fork().

      +

      Cluster#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/cluster.js

      +

      A single instance of Node.js runs in a single thread. To take advantage of +multi-core systems, the user will sometimes want to launch a cluster of Node.js +processes to handle the load.

      +

      The cluster module allows easy creation of child processes that all share +server ports.

      +
      const cluster = require('cluster');
      +const http = require('http');
      +const numCPUs = require('os').cpus().length;
      +
      +if (cluster.isMaster) {
      +  console.log(`Master ${process.pid} is running`);
      +
      +  // Fork workers.
      +  for (let i = 0; i < numCPUs; i++) {
      +    cluster.fork();
      +  }
      +
      +  cluster.on('exit', (worker, code, signal) => {
      +    console.log(`worker ${worker.process.pid} died`);
      +  });
      +} else {
      +  // Workers can share any TCP connection
      +  // In this case it is an HTTP server
      +  http.createServer((req, res) => {
      +    res.writeHead(200);
      +    res.end('hello world\n');
      +  }).listen(8000);
      +
      +  console.log(`Worker ${process.pid} started`);
      +}
      +

      Running Node.js will now share port 8000 between the workers:

      +
      $ node server.js
      +Master 3596 is running
      +Worker 4324 started
      +Worker 4520 started
      +Worker 6056 started
      +Worker 5644 started
      +

      On Windows, it is not yet possible to set up a named pipe server in a worker.

      +

      How it works#

      + +

      The worker processes are spawned using the child_process.fork() method, +so that they can communicate with the parent via IPC and pass server +handles back and forth.

      +

      The cluster module supports two methods of distributing incoming +connections.

      +

      The first one (and the default one on all platforms except Windows), +is the round-robin approach, where the master process listens on a +port, accepts new connections and distributes them across the workers +in a round-robin fashion, with some built-in smarts to avoid +overloading a worker process.

      +

      The second approach is where the master process creates the listen +socket and sends it to interested workers. The workers then accept +incoming connections directly.

      +

      The second approach should, in theory, give the best performance. +In practice however, distribution tends to be very unbalanced due +to operating system scheduler vagaries. Loads have been observed +where over 70% of all connections ended up in just two processes, +out of a total of eight.

      +

      Because server.listen() hands off most of the work to the master +process, there are three cases where the behavior between a normal +Node.js process and a cluster worker differs:

      +
        +
      1. server.listen({fd: 7}) Because the message is passed to the master, +file descriptor 7 in the parent will be listened on, and the +handle passed to the worker, rather than listening to the worker's +idea of what the number 7 file descriptor references.
      2. +
      3. server.listen(handle) Listening on handles explicitly will cause +the worker to use the supplied handle, rather than talk to the master +process.
      4. +
      5. server.listen(0) Normally, this will cause servers to listen on a +random port. However, in a cluster, each worker will receive the +same "random" port each time they do listen(0). In essence, the +port is random the first time, but predictable thereafter. To listen +on a unique port, generate a port number based on the cluster worker ID.
      6. +
      +

      Node.js does not provide routing logic. It is, therefore important to design an +application such that it does not rely too heavily on in-memory data objects for +things like sessions and login.

      +

      Because workers are all separate processes, they can be killed or +re-spawned depending on a program's needs, without affecting other +workers. As long as there are some workers still alive, the server will +continue to accept connections. If no workers are alive, existing connections +will be dropped and new connections will be refused. Node.js does not +automatically manage the number of workers, however. It is the application's +responsibility to manage the worker pool based on its own needs.

      +

      Although a primary use case for the cluster module is networking, it can +also be used for other use cases requiring worker processes.

      +

      Class: Worker#

      + + +

      A Worker object contains all public information and method about a worker. +In the master it can be obtained using cluster.workers. In a worker +it can be obtained using cluster.worker.

      +

      Event: 'disconnect'#

      + +

      Similar to the cluster.on('disconnect') event, but specific to this worker.

      +
      cluster.fork().on('disconnect', () => {
      +  // Worker has disconnected
      +});
      +

      Event: 'error'#

      + +

      This event is the same as the one provided by child_process.fork().

      +

      Within a worker, process.on('error') may also be used.

      +

      Event: 'exit'#

      + +
        +
      • code <number> The exit code, if it exited normally.
      • +
      • signal <string> The name of the signal (e.g. 'SIGHUP') that caused +the process to be killed.
      • +
      +

      Similar to the cluster.on('exit') event, but specific to this worker.

      +
      const worker = cluster.fork();
      +worker.on('exit', (code, signal) => {
      +  if (signal) {
      +    console.log(`worker was killed by signal: ${signal}`);
      +  } else if (code !== 0) {
      +    console.log(`worker exited with error code: ${code}`);
      +  } else {
      +    console.log('worker success!');
      +  }
      +});
      +

      Event: 'listening'#

      + + +

      Similar to the cluster.on('listening') event, but specific to this worker.

      +
      cluster.fork().on('listening', (address) => {
      +  // Worker is listening
      +});
      +

      It is not emitted in the worker.

      +

      Event: 'message'#

      + + +

      Similar to the 'message' event of cluster, but specific to this worker.

      +

      Within a worker, process.on('message') may also be used.

      +

      See process event: 'message'.

      +

      Here is an example using the message system. It keeps a count in the master +process of the number of HTTP requests received by the workers:

      +
      const cluster = require('cluster');
      +const http = require('http');
      +
      +if (cluster.isMaster) {
      +
      +  // Keep track of http requests
      +  let numReqs = 0;
      +  setInterval(() => {
      +    console.log(`numReqs = ${numReqs}`);
      +  }, 1000);
      +
      +  // Count requests
      +  function messageHandler(msg) {
      +    if (msg.cmd && msg.cmd === 'notifyRequest') {
      +      numReqs += 1;
      +    }
      +  }
      +
      +  // Start workers and listen for messages containing notifyRequest
      +  const numCPUs = require('os').cpus().length;
      +  for (let i = 0; i < numCPUs; i++) {
      +    cluster.fork();
      +  }
      +
      +  for (const id in cluster.workers) {
      +    cluster.workers[id].on('message', messageHandler);
      +  }
      +
      +} else {
      +
      +  // Worker processes have a http server.
      +  http.Server((req, res) => {
      +    res.writeHead(200);
      +    res.end('hello world\n');
      +
      +    // Notify master about the request
      +    process.send({ cmd: 'notifyRequest' });
      +  }).listen(8000);
      +}
      +

      Event: 'online'#

      + +

      Similar to the cluster.on('online') event, but specific to this worker.

      +
      cluster.fork().on('online', () => {
      +  // Worker is online
      +});
      +

      It is not emitted in the worker.

      +

      worker.disconnect()#

      + + +

      In a worker, this function will close all servers, wait for the 'close' event +on those servers, and then disconnect the IPC channel.

      +

      In the master, an internal message is sent to the worker causing it to call +.disconnect() on itself.

      +

      Causes .exitedAfterDisconnect to be set.

      +

      After a server is closed, it will no longer accept new connections, +but connections may be accepted by any other listening worker. Existing +connections will be allowed to close as usual. When no more connections exist, +see server.close(), the IPC channel to the worker will close allowing it +to die gracefully.

      +

      The above applies only to server connections, client connections are not +automatically closed by workers, and disconnect does not wait for them to close +before exiting.

      +

      In a worker, process.disconnect exists, but it is not this function; +it is disconnect().

      +

      Because long living server connections may block workers from disconnecting, it +may be useful to send a message, so application specific actions may be taken to +close them. It also may be useful to implement a timeout, killing a worker if +the 'disconnect' event has not been emitted after some time.

      +
      if (cluster.isMaster) {
      +  const worker = cluster.fork();
      +  let timeout;
      +
      +  worker.on('listening', (address) => {
      +    worker.send('shutdown');
      +    worker.disconnect();
      +    timeout = setTimeout(() => {
      +      worker.kill();
      +    }, 2000);
      +  });
      +
      +  worker.on('disconnect', () => {
      +    clearTimeout(timeout);
      +  });
      +
      +} else if (cluster.isWorker) {
      +  const net = require('net');
      +  const server = net.createServer((socket) => {
      +    // Connections never end
      +  });
      +
      +  server.listen(8000);
      +
      +  process.on('message', (msg) => {
      +    if (msg === 'shutdown') {
      +      // Initiate graceful close of any connections to server
      +    }
      +  });
      +}
      +

      worker.exitedAfterDisconnect#

      + + +

      This property is true if the worker exited due to .kill() or +.disconnect(). If the worker exited any other way, it is false. If the +worker has not exited, it is undefined.

      +

      The boolean worker.exitedAfterDisconnect allows distinguishing between +voluntary and accidental exit, the master may choose not to respawn a worker +based on this value.

      +
      cluster.on('exit', (worker, code, signal) => {
      +  if (worker.exitedAfterDisconnect === true) {
      +    console.log('Oh, it was just voluntary – no need to worry');
      +  }
      +});
      +
      +// kill worker
      +worker.kill();
      +

      worker.id#

      + + +

      Each new worker is given its own unique id, this id is stored in the +id.

      +

      While a worker is alive, this is the key that indexes it in +cluster.workers.

      +

      worker.isConnected()#

      + +

      This function returns true if the worker is connected to its master via its +IPC channel, false otherwise. A worker is connected to its master after it +has been created. It is disconnected after the 'disconnect' event is emitted.

      +

      worker.isDead()#

      + +

      This function returns true if the worker's process has terminated (either +because of exiting or being signaled). Otherwise, it returns false.

      +
      const cluster = require('cluster');
      +const http = require('http');
      +const numCPUs = require('os').cpus().length;
      +
      +if (cluster.isMaster) {
      +  console.log(`Master ${process.pid} is running`);
      +
      +  // Fork workers.
      +  for (let i = 0; i < numCPUs; i++) {
      +    cluster.fork();
      +  }
      +
      +  cluster.on('fork', (worker) => {
      +    console.log('worker is dead:', worker.isDead());
      +  });
      +
      +  cluster.on('exit', (worker, code, signal) => {
      +    console.log('worker is dead:', worker.isDead());
      +  });
      +} else {
      +  // Workers can share any TCP connection. In this case, it is an HTTP server.
      +  http.createServer((req, res) => {
      +    res.writeHead(200);
      +    res.end(`Current process\n ${process.pid}`);
      +    process.kill(process.pid);
      +  }).listen(8000);
      +}
      +

      worker.kill([signal])#

      + +
        +
      • signal <string> Name of the kill signal to send to the worker +process. Default: 'SIGTERM'
      • +
      +

      This function will kill the worker. In the master, it does this by disconnecting +the worker.process, and once disconnected, killing with signal. In the +worker, it does it by disconnecting the channel, and then exiting with code 0.

      +

      Because kill() attempts to gracefully disconnect the worker process, it is +susceptible to waiting indefinitely for the disconnect to complete. For example, +if the worker enters an infinite loop, a graceful disconnect will never occur. +If the graceful disconnect behavior is not needed, use worker.process.kill().

      +

      Causes .exitedAfterDisconnect to be set.

      +

      This method is aliased as worker.destroy() for backward compatibility.

      +

      In a worker, process.kill() exists, but it is not this function; +it is kill().

      +

      worker.process#

      + + +

      All workers are created using child_process.fork(), the returned object +from this function is stored as .process. In a worker, the global process +is stored.

      +

      See: Child Process module.

      +

      Workers will call process.exit(0) if the 'disconnect' event occurs +on process and .exitedAfterDisconnect is not true. This protects against +accidental disconnection.

      +

      worker.send(message[, sendHandle[, options]][, callback])#

      + +
        +
      • message <Object>
      • +
      • sendHandle <Handle>
      • +
      • options <Object> The options argument, if present, is an object used to +parameterize the sending of certain types of handles. options supports +the following properties: +
          +
        • keepOpen <boolean> A value that can be used when passing instances of +net.Socket. When true, the socket is kept open in the sending process. +Default: false.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <boolean>
      • +
      +

      Send a message to a worker or master, optionally with a handle.

      +

      In the master this sends a message to a specific worker. It is identical to +ChildProcess.send().

      +

      In a worker this sends a message to the master. It is identical to +process.send().

      +

      This example will echo back all messages from the master:

      +
      if (cluster.isMaster) {
      +  const worker = cluster.fork();
      +  worker.send('hi there');
      +
      +} else if (cluster.isWorker) {
      +  process.on('message', (msg) => {
      +    process.send(msg);
      +  });
      +}
      +

      Event: 'disconnect'#

      + + +

      Emitted after the worker IPC channel has disconnected. This can occur when a +worker exits gracefully, is killed, or is disconnected manually (such as with +worker.disconnect()).

      +

      There may be a delay between the 'disconnect' and 'exit' events. These +events can be used to detect if the process is stuck in a cleanup or if there +are long-living connections.

      +
      cluster.on('disconnect', (worker) => {
      +  console.log(`The worker #${worker.id} has disconnected`);
      +});
      +

      Event: 'exit'#

      + +
        +
      • worker <cluster.Worker>
      • +
      • code <number> The exit code, if it exited normally.
      • +
      • signal <string> The name of the signal (e.g. 'SIGHUP') that caused +the process to be killed.
      • +
      +

      When any of the workers die the cluster module will emit the 'exit' event.

      +

      This can be used to restart the worker by calling .fork() again.

      +
      cluster.on('exit', (worker, code, signal) => {
      +  console.log('worker %d died (%s). restarting...',
      +              worker.process.pid, signal || code);
      +  cluster.fork();
      +});
      +

      See child_process event: 'exit'.

      +

      Event: 'fork'#

      + + +

      When a new worker is forked the cluster module will emit a 'fork' event. +This can be used to log worker activity, and create a custom timeout.

      +
      const timeouts = [];
      +function errorMsg() {
      +  console.error('Something must be wrong with the connection ...');
      +}
      +
      +cluster.on('fork', (worker) => {
      +  timeouts[worker.id] = setTimeout(errorMsg, 2000);
      +});
      +cluster.on('listening', (worker, address) => {
      +  clearTimeout(timeouts[worker.id]);
      +});
      +cluster.on('exit', (worker, code, signal) => {
      +  clearTimeout(timeouts[worker.id]);
      +  errorMsg();
      +});
      +

      Event: 'listening'#

      + + +

      After calling listen() from a worker, when the 'listening' event is emitted +on the server a 'listening' event will also be emitted on cluster in the +master.

      +

      The event handler is executed with two arguments, the worker contains the +worker object and the address object contains the following connection +properties: address, port and addressType. This is very useful if the +worker is listening on more than one address.

      +
      cluster.on('listening', (worker, address) => {
      +  console.log(
      +    `A worker is now connected to ${address.address}:${address.port}`);
      +});
      +

      The addressType is one of:

      +
        +
      • 4 (TCPv4)
      • +
      • 6 (TCPv6)
      • +
      • -1 (Unix domain socket)
      • +
      • 'udp4' or 'udp6' (UDP v4 or v6)
      • +
      +

      Event: 'message'#

      + + +

      Emitted when the cluster master receives a message from any worker.

      +

      See child_process event: 'message'.

      +

      Event: 'online'#

      + + +

      After forking a new worker, the worker should respond with an online message. +When the master receives an online message it will emit this event. +The difference between 'fork' and 'online' is that fork is emitted when the +master forks a worker, and 'online' is emitted when the worker is running.

      +
      cluster.on('online', (worker) => {
      +  console.log('Yay, the worker responded after it was forked');
      +});
      +

      Event: 'setup'#

      + + +

      Emitted every time .setupMaster() is called.

      +

      The settings object is the cluster.settings object at the time +.setupMaster() was called and is advisory only, since multiple calls to +.setupMaster() can be made in a single tick.

      +

      If accuracy is important, use cluster.settings.

      +

      cluster.disconnect([callback])#

      + +
        +
      • callback <Function> Called when all workers are disconnected and handles are +closed.
      • +
      +

      Calls .disconnect() on each worker in cluster.workers.

      +

      When they are disconnected all internal handles will be closed, allowing the +master process to die gracefully if no other event is waiting.

      +

      The method takes an optional callback argument which will be called when +finished.

      +

      This can only be called from the master process.

      +

      cluster.fork([env])#

      + + +

      Spawn a new worker process.

      +

      This can only be called from the master process.

      +

      cluster.isMaster#

      + + +

      True if the process is a master. This is determined +by the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is +undefined, then isMaster is true.

      +

      cluster.isWorker#

      + + +

      True if the process is not a master (it is the negation of cluster.isMaster).

      +

      cluster.schedulingPolicy#

      + +

      The scheduling policy, either cluster.SCHED_RR for round-robin or +cluster.SCHED_NONE to leave it to the operating system. This is a +global setting and effectively frozen once either the first worker is spawned, +or .setupMaster() is called, whichever comes first.

      +

      SCHED_RR is the default on all operating systems except Windows. +Windows will change to SCHED_RR once libuv is able to effectively +distribute IOCP handles without incurring a large performance hit.

      +

      cluster.schedulingPolicy can also be set through the +NODE_CLUSTER_SCHED_POLICY environment variable. Valid +values are 'rr' and 'none'.

      +

      cluster.settings#

      + +
        +
      • <Object> +
          +
        • execArgv <string[]> List of string arguments passed to the Node.js +executable. Default: process.execArgv.
        • +
        • exec <string> File path to worker file. Default: process.argv[1].
        • +
        • args <string[]> String arguments passed to worker. +Default: process.argv.slice(2).
        • +
        • cwd <string> Current working directory of the worker process. Default: +undefined (inherits from parent process).
        • +
        • serialization <string> Specify the kind of serialization used for sending +messages between processes. Possible values are 'json' and 'advanced'. +See Advanced serialization for child_process for more details. +Default: false.
        • +
        • silent <boolean> Whether or not to send output to parent's stdio. +Default: false.
        • +
        • stdio <Array> Configures the stdio of forked processes. Because the +cluster module relies on IPC to function, this configuration must contain an +'ipc' entry. When this option is provided, it overrides silent.
        • +
        • uid <number> Sets the user identity of the process. (See setuid(2).)
        • +
        • gid <number> Sets the group identity of the process. (See setgid(2).)
        • +
        • inspectPort <number> | <Function> Sets inspector port of worker. +This can be a number, or a function that takes no arguments and returns a +number. By default each worker gets its own port, incremented from the +master's process.debugPort.
        • +
        • windowsHide <boolean> Hide the forked processes console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      +

      After calling .setupMaster() (or .fork()) this settings object will +contain the settings, including the default values.

      +

      This object is not intended to be changed or set manually.

      +

      cluster.setupMaster([settings])#

      + + +

      setupMaster is used to change the default 'fork' behavior. Once called, +the settings will be present in cluster.settings.

      +

      Any settings changes only affect future calls to .fork() and have no +effect on workers that are already running.

      +

      The only attribute of a worker that cannot be set via .setupMaster() is +the env passed to .fork().

      +

      The defaults above apply to the first call only; the defaults for later +calls are the current values at the time of cluster.setupMaster() is called.

      +
      const cluster = require('cluster');
      +cluster.setupMaster({
      +  exec: 'worker.js',
      +  args: ['--use', 'https'],
      +  silent: true
      +});
      +cluster.fork(); // https worker
      +cluster.setupMaster({
      +  exec: 'worker.js',
      +  args: ['--use', 'http']
      +});
      +cluster.fork(); // http worker
      +

      This can only be called from the master process.

      +

      cluster.worker#

      + + +

      A reference to the current worker object. Not available in the master process.

      +
      const cluster = require('cluster');
      +
      +if (cluster.isMaster) {
      +  console.log('I am master');
      +  cluster.fork();
      +  cluster.fork();
      +} else if (cluster.isWorker) {
      +  console.log(`I am worker #${cluster.worker.id}`);
      +}
      +

      cluster.workers#

      + + +

      A hash that stores the active worker objects, keyed by id field. Makes it +easy to loop through all the workers. It is only available in the master +process.

      +

      A worker is removed from cluster.workers after the worker has disconnected +and exited. The order between these two events cannot be determined in +advance. However, it is guaranteed that the removal from the cluster.workers +list happens before last 'disconnect' or 'exit' event is emitted.

      +
      // Go through all workers
      +function eachWorker(callback) {
      +  for (const id in cluster.workers) {
      +    callback(cluster.workers[id]);
      +  }
      +}
      +eachWorker((worker) => {
      +  worker.send('big announcement to all workers');
      +});
      +

      Using the worker's unique id is the easiest way to locate the worker.

      +
      socket.on('data', (id) => {
      +  const worker = cluster.workers[id];
      +});
      +

      Command line options#

      + + +

      Node.js comes with a variety of CLI options. These options expose built-in +debugging, multiple ways to execute scripts, and other helpful runtime options.

      +

      To view this documentation as a manual page in a terminal, run man node.

      +

      Synopsis#

      +

      node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]

      +

      node inspect [script.js | -e "script" | <host>:<port>] …

      +

      node --v8-options

      +

      Execute without arguments to start the REPL.

      +

      For more info about node inspect, please see the debugger documentation.

      +

      Options#

      + +

      All options, including V8 options, allow words to be separated by both +dashes (-) or underscores (_).

      +

      For example, --pending-deprecation is equivalent to --pending_deprecation.

      +

      If an option that takes a single value, for example --max-http-header-size, +is passed more than once, then the last passed value will be used. Options +from the command line take precedence over options passed through the +NODE_OPTIONS environment variable.

      +

      -#

      + +

      Alias for stdin. Analogous to the use of - in other command line utilities, +meaning that the script will be read from stdin, and the rest of the options +are passed to that script.

      +

      --#

      + +

      Indicate the end of node options. Pass the rest of the arguments to the script. +If no script filename or eval/print script is supplied prior to this, then +the next argument will be used as a script filename.

      +

      --abort-on-uncaught-exception#

      + +

      Aborting instead of exiting causes a core file to be generated for post-mortem +analysis using a debugger (such as lldb, gdb, and mdb).

      +

      If this flag is passed, the behavior can still be set to not abort through +process.setUncaughtExceptionCaptureCallback() (and through usage of the +domain module that uses it).

      +

      --completion-bash#

      + +

      Print source-able bash completion script for Node.js.

      +
      $ node --completion-bash > node_bash_completion
      +$ source node_bash_completion
      +

      --conditions=condition#

      + +

      Stability: 1 - Experimental

      +

      Enable experimental support for custom conditional exports resolution +conditions.

      +

      Any number of custom string condition names are permitted.

      +

      The default Node.js conditions of "node", "default", "import", and +"require" will always apply as defined.

      +

      --cpu-prof#

      + +

      Stability: 1 - Experimental

      +

      Starts the V8 CPU profiler on start up, and writes the CPU profile to disk +before exit.

      +

      If --cpu-prof-dir is not specified, the generated profile will be placed +in the current working directory.

      +

      If --cpu-prof-name is not specified, the generated profile will be +named CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.

      +
      $ node --cpu-prof index.js
      +$ ls *.cpuprofile
      +CPU.20190409.202950.15293.0.0.cpuprofile
      +

      --cpu-prof-dir#

      + +

      Stability: 1 - Experimental

      +

      Specify the directory where the CPU profiles generated by --cpu-prof will +be placed.

      +

      The default value is controlled by the +--diagnostic-dir command line option.

      +

      --cpu-prof-interval#

      + +

      Stability: 1 - Experimental

      +

      Specify the sampling interval in microseconds for the CPU profiles generated +by --cpu-prof. The default is 1000 microseconds.

      +

      --cpu-prof-name#

      + +

      Stability: 1 - Experimental

      +

      Specify the file name of the CPU profile generated by --cpu-prof.

      +

      --diagnostic-dir=directory#

      +

      Set the directory to which all diagnostic output files will be written to. +Defaults to current working directory.

      +

      Affects the default output directory of:

      + +

      --disable-proto=mode#

      + +

      Disable the Object.prototype.__proto__ property. If mode is delete, the +property will be removed entirely. If mode is throw, accesses to the +property will throw an exception with the code ERR_PROTO_ACCESS.

      +

      --disallow-code-generation-from-strings#

      + +

      Make built-in language features like eval and new Function that generate +code from strings throw an exception instead. This does not affect the Node.js +vm module.

      +

      --enable-fips#

      + +

      Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with +./configure --openssl-fips.)

      +

      --enable-source-maps#

      + +

      Stability: 1 - Experimental

      +

      Enable experimental Source Map v3 support for stack traces.

      +

      Currently, overriding Error.prepareStackTrace is ignored when the +--enable-source-maps flag is set.

      +

      --experimental-import-meta-resolve#

      + +

      Enable experimental import.meta.resolve() support.

      +

      --experimental-json-modules#

      + +

      Enable experimental JSON support for the ES Module loader.

      +

      --experimental-loader=module#

      + +

      Specify the module of a custom experimental ECMAScript Module loader. +module may be either a path to a file, or an ECMAScript Module name.

      +

      --experimental-modules#

      + +

      Enable latest experimental modules features (deprecated).

      +

      --experimental-policy#

      + +

      Use the specified file as a security policy.

      +

      --experimental-repl-await#

      + +

      Enable experimental top-level await keyword support in REPL.

      +

      --experimental-specifier-resolution=mode#

      + +

      Sets the resolution algorithm for resolving ES module specifiers. Valid options +are explicit and node.

      +

      The default is explicit, which requires providing the full path to a +module. The node mode will enable support for optional file extensions and +the ability to import a directory that has an index file.

      +

      Please see customizing ESM specifier resolution for example usage.

      +

      --experimental-vm-modules#

      + +

      Enable experimental ES Module support in the vm module.

      +

      --experimental-wasi-unstable-preview1#

      + +

      Enable experimental WebAssembly System Interface (WASI) support.

      +

      --experimental-wasm-modules#

      + +

      --force-context-aware#

      + +

      Disable loading native addons that are not context-aware.

      +

      Enable experimental WebAssembly module support.

      +

      --force-fips#

      + +

      Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) +(Same requirements as --enable-fips.)

      +

      --frozen-intrinsics#

      + +

      Stability: 1 - Experimental

      +

      Enable experimental frozen intrinsics like Array and Object.

      +

      Support is currently only provided for the root context and no guarantees are +currently provided that global.Array is indeed the default intrinsic +reference. Code may break under this flag.

      +

      --require runs prior to freezing intrinsics in order to allow polyfills to +be added.

      +

      --heapsnapshot-signal=signal#

      + +

      Enables a signal handler that causes the Node.js process to write a heap dump +when the specified signal is received. signal must be a valid signal name. +Disabled by default.

      +
      $ node --heapsnapshot-signal=SIGUSR2 index.js &
      +$ ps aux
      +USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
      +node         1  5.5  6.1 787252 247004 ?       Ssl  16:43   0:02 node --heapsnapshot-signal=SIGUSR2 index.js
      +$ kill -USR2 1
      +$ ls
      +Heap.20190718.133405.15554.0.001.heapsnapshot
      +

      --heap-prof#

      + +

      Stability: 1 - Experimental

      +

      Starts the V8 heap profiler on start up, and writes the heap profile to disk +before exit.

      +

      If --heap-prof-dir is not specified, the generated profile will be placed +in the current working directory.

      +

      If --heap-prof-name is not specified, the generated profile will be +named Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.

      +
      $ node --heap-prof index.js
      +$ ls *.heapprofile
      +Heap.20190409.202950.15293.0.001.heapprofile
      +

      --heap-prof-dir#

      + +

      Stability: 1 - Experimental

      +

      Specify the directory where the heap profiles generated by --heap-prof will +be placed.

      +

      The default value is controlled by the +--diagnostic-dir command line option.

      +

      --heap-prof-interval#

      + +

      Stability: 1 - Experimental

      +

      Specify the average sampling interval in bytes for the heap profiles generated +by --heap-prof. The default is 512 * 1024 bytes.

      +

      --heap-prof-name#

      + +

      Stability: 1 - Experimental

      +

      Specify the file name of the heap profile generated by --heap-prof.

      +

      --http-parser=library#

      + +

      Chooses an HTTP parser library. Available values are:

      + +

      The default is llhttp, unless otherwise specified when building Node.js.

      +

      The legacy HTTP parser is deprecated and will emit a deprecation warning.

      +

      This flag exists to aid in experimentation with the internal implementation of +the Node.js http parser. +This flag is likely to become a no-op and removed at some point in the future.

      +

      --http-server-default-timeout=milliseconds#

      + +

      Overrides the default value of http, https and http2 server socket +timeout. Setting the value to 0 disables server socket timeout. Unless +provided, http server sockets timeout after 120s (2 minutes). Programmatic +setting of the timeout takes precedence over the value set through this +flag.

      +

      --icu-data-dir=file#

      + +

      Specify ICU data load path. (Overrides NODE_ICU_DATA.)

      +

      --input-type=type#

      + +

      This configures Node.js to interpret string input as CommonJS or as an ES +module. String input is input via --eval, --print, or STDIN.

      +

      Valid values are "commonjs" and "module". The default is "commonjs".

      +

      --inspect-brk[=[host:]port]#

      + +

      Activate inspector on host:port and break at start of user script. +Default host:port is 127.0.0.1:9229.

      +

      --inspect-port=[host:]port#

      + +

      Set the host:port to be used when the inspector is activated. +Useful when activating the inspector by sending the SIGUSR1 signal.

      +

      Default host is 127.0.0.1.

      +

      See the security warning below regarding the host +parameter usage.

      +

      --inspect[=[host:]port]#

      + +

      Activate inspector on host:port. Default is 127.0.0.1:9229.

      +

      V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug +and profile Node.js instances. The tools attach to Node.js instances via a +tcp port and communicate using the Chrome DevTools Protocol.

      +

      +

      Warning: binding inspector to a public IP:port combination is insecure#

      +

      Binding the inspector to a public IP (including 0.0.0.0) with an open port is +insecure, as it allows external hosts to connect to the inspector and perform +a remote code execution attack.

      +

      If specifying a host, make sure that either:

      +
        +
      • The host is not accessible from public networks.
      • +
      • A firewall disallows unwanted connections on the port.
      • +
      +

      More specifically, --inspect=0.0.0.0 is insecure if the port (9229 by +default) is not firewall-protected.

      +

      See the debugging security implications section for more information.

      +

      --inspect-publish-uid=stderr,http#

      +

      Specify ways of the inspector web socket url exposure.

      +

      By default inspector websocket url is available in stderr and under /json/list +endpoint on http://host:port/json/list.

      +

      --insecure-http-parser#

      + +

      Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow +interoperability with non-conformant HTTP implementations. It may also allow +request smuggling and other HTTP attacks that rely on invalid headers being +accepted. Avoid using this option.

      +

      --jitless#

      + +

      Disable runtime allocation of executable memory. This may be +required on some platforms for security reasons. It can also reduce attack +surface on other platforms, but the performance impact may be severe.

      +

      This flag is inherited from V8 and is subject to change upstream. It may +disappear in a non-semver-major release.

      +

      --max-http-header-size=size#

      + +

      Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB.

      +

      --napi-modules#

      + +

      This option is a no-op. It is kept for compatibility.

      +

      --no-deprecation#

      + +

      Silence deprecation warnings.

      +

      --no-force-async-hooks-checks#

      + +

      Disables runtime checks for async_hooks. These will still be enabled +dynamically when async_hooks is enabled.

      +

      --no-warnings#

      + +

      Silence all process warnings (including deprecations).

      +

      --openssl-config=file#

      + +

      Load an OpenSSL configuration file on startup. Among other uses, this can be +used to enable FIPS-compliant crypto if Node.js is built with +./configure --openssl-fips.

      +

      --pending-deprecation#

      + +

      Emit pending deprecation warnings.

      +

      Pending deprecations are generally identical to a runtime deprecation with the +notable exception that they are turned off by default and will not be emitted +unless either the --pending-deprecation command line flag, or the +NODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations +are used to provide a kind of selective "early warning" mechanism that +developers may leverage to detect deprecated API usage.

      +

      --policy-integrity=sri#

      + +

      Stability: 1 - Experimental

      +

      Instructs Node.js to error prior to running any code if the policy does not have +the specified integrity. It expects a Subresource Integrity string as a +parameter.

      +

      --preserve-symlinks#

      + +

      Instructs the module loader to preserve symbolic links when resolving and +caching modules.

      +

      By default, when Node.js loads a module from a path that is symbolically linked +to a different on-disk location, Node.js will dereference the link and use the +actual on-disk "real path" of the module as both an identifier and as a root +path to locate other dependency modules. In most cases, this default behavior +is acceptable. However, when using symbolically linked peer dependencies, as +illustrated in the example below, the default behavior causes an exception to +be thrown if moduleA attempts to require moduleB as a peer dependency:

      +
      {appDir}
      + ├── app
      + │   ├── index.js
      + │   └── node_modules
      + │       ├── moduleA -> {appDir}/moduleA
      + │       └── moduleB
      + │           ├── index.js
      + │           └── package.json
      + └── moduleA
      +     ├── index.js
      +     └── package.json
      +

      The --preserve-symlinks command line flag instructs Node.js to use the +symlink path for modules as opposed to the real path, allowing symbolically +linked peer dependencies to be found.

      +

      Note, however, that using --preserve-symlinks can have other side effects. +Specifically, symbolically linked native modules can fail to load if those +are linked from more than one location in the dependency tree (Node.js would +see those as two separate modules and would attempt to load the module multiple +times, causing an exception to be thrown).

      +

      The --preserve-symlinks flag does not apply to the main module, which allows +node --preserve-symlinks node_module/.bin/<foo> to work. To apply the same +behavior for the main module, also use --preserve-symlinks-main.

      +

      --preserve-symlinks-main#

      + +

      Instructs the module loader to preserve symbolic links when resolving and +caching the main module (require.main).

      +

      This flag exists so that the main module can be opted-in to the same behavior +that --preserve-symlinks gives to all other imports; they are separate flags, +however, for backward compatibility with older Node.js versions.

      +

      --preserve-symlinks-main does not imply --preserve-symlinks; it +is expected that --preserve-symlinks-main will be used in addition to +--preserve-symlinks when it is not desirable to follow symlinks before +resolving relative paths.

      +

      See --preserve-symlinks for more information.

      +

      --prof#

      + +

      Generate V8 profiler output.

      +

      --prof-process#

      + +

      Process V8 profiler output generated using the V8 option --prof.

      +

      --redirect-warnings=file#

      + +

      Write process warnings to the given file instead of printing to stderr. The +file will be created if it does not exist, and will be appended to if it does. +If an error occurs while attempting to write the warning to the file, the +warning will be written to stderr instead.

      +

      The file name may be an absolute path. If it is not, the default directory it +will be written to is controlled by the +--diagnostic-dir command line option.

      +

      --report-compact#

      + +

      Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption.

      +

      --report-dir=directory, report-directory=directory#

      + +

      Location at which the report will be generated.

      +

      --report-filename=filename#

      + +

      Name of the file to which the report will be written.

      +

      --report-on-fatalerror#

      + +

      Enables the report to be triggered on fatal errors (internal errors within +the Node.js runtime such as out of memory) that lead to termination of the +application. Useful to inspect various diagnostic data elements such as heap, +stack, event loop state, resource consumption etc. to reason about the fatal +error.

      +

      --report-on-signal#

      + +

      Enables report to be generated upon receiving the specified (or predefined) +signal to the running Node.js process. The signal to trigger the report is +specified through --report-signal.

      +

      --report-signal=signal#

      + +

      Sets or resets the signal for report generation (not supported on Windows). +Default signal is SIGUSR2.

      +

      --report-uncaught-exception#

      + +

      Enables report to be generated on uncaught exceptions. Useful when inspecting +the JavaScript stack in conjunction with native stack and other runtime +environment data.

      +

      --throw-deprecation#

      + +

      Throw errors for deprecations.

      +

      --title=title#

      + +

      Set process.title on startup.

      +

      --tls-cipher-list=list#

      + +

      Specify an alternative default TLS cipher list. Requires Node.js to be built +with crypto support (default).

      +

      --tls-keylog=file#

      + +

      Log TLS key material to a file. The key material is in NSS SSLKEYLOGFILE +format and can be used by software (such as Wireshark) to decrypt the TLS +traffic.

      +

      --tls-max-v1.2#

      + +

      Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for +TLSv1.3.

      +

      --tls-max-v1.3#

      + +

      Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support +for TLSv1.3.

      +

      --tls-min-v1.0#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with +old TLS clients or servers.

      +

      --tls-min-v1.1#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility +with old TLS clients or servers.

      +

      --tls-min-v1.2#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.2'. This is the default for +12.x and later, but the option is supported for compatibility with older Node.js +versions.

      +

      --tls-min-v1.3#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support +for TLSv1.2, which is not as secure as TLSv1.3.

      +

      --trace-deprecation#

      + +

      Print stack traces for deprecations.

      +

      --trace-event-categories#

      + +

      A comma separated list of categories that should be traced when trace event +tracing is enabled using --trace-events-enabled.

      +

      --trace-event-file-pattern#

      + +

      Template string specifying the filepath for the trace event data, it +supports ${rotation} and ${pid}.

      +

      --trace-events-enabled#

      + +

      Enables the collection of trace event tracing information.

      +

      --trace-exit#

      + +

      Prints a stack trace whenever an environment is exited proactively, +i.e. invoking process.exit().

      +

      --trace-sigint#

      + +

      Prints a stack trace on SIGINT.

      +

      --trace-sync-io#

      + +

      Prints a stack trace whenever synchronous I/O is detected after the first turn +of the event loop.

      +

      --trace-tls#

      + +

      Prints TLS packet trace information to stderr. This can be used to debug TLS +connection problems.

      +

      --trace-uncaught#

      + +

      Print stack traces for uncaught exceptions; usually, the stack trace associated +with the creation of an Error is printed, whereas this makes Node.js also +print the stack trace associated with throwing the value (which does not need +to be an Error instance).

      +

      Enabling this option may affect garbage collection behavior negatively.

      +

      --trace-warnings#

      + +

      Print stack traces for process warnings (including deprecations).

      +

      --track-heap-objects#

      + +

      Track heap object allocations for heap snapshots.

      +

      --unhandled-rejections=mode#

      + +

      By default all unhandled rejections trigger a warning plus a deprecation warning +for the very first unhandled rejection in case no unhandledRejection hook +is used.

      +

      Using this flag allows to change what should happen when an unhandled rejection +occurs. One of three modes can be chosen:

      +
        +
      • strict: Raise the unhandled rejection as an uncaught exception.
      • +
      • warn: Always trigger a warning, no matter if the unhandledRejection +hook is set or not but do not print the deprecation warning.
      • +
      • none: Silence all warnings.
      • +
      +

      --use-bundled-ca, --use-openssl-ca#

      + +

      Use bundled Mozilla CA store as supplied by current Node.js version +or use OpenSSL's default CA store. The default store is selectable +at build-time.

      +

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store +that is fixed at release time. It is identical on all supported platforms.

      +

      Using OpenSSL store allows for external modifications of the store. For most +Linux and BSD distributions, this store is maintained by the distribution +maintainers and system administrators. OpenSSL CA store location is dependent on +configuration of the OpenSSL library but this can be altered at runtime using +environment variables.

      +

      See SSL_CERT_DIR and SSL_CERT_FILE.

      +

      --use-largepages=mode#

      + +

      Re-map the Node.js static code to large memory pages at startup. If supported on +the target system, this will cause the Node.js static code to be moved onto 2 +MiB pages instead of 4 KiB pages.

      +

      The following values are valid for mode:

      +
        +
      • off: No mapping will be attempted. This is the default.
      • +
      • on: If supported by the OS, mapping will be attempted. Failure to map will +be ignored and a message will be printed to standard error.
      • +
      • silent: If supported by the OS, mapping will be attempted. Failure to map +will be ignored and will not be reported.
      • +
      +

      --v8-options#

      + +

      Print V8 command line options.

      +

      --v8-pool-size=num#

      + +

      Set V8's thread pool size which will be used to allocate background jobs.

      +

      If set to 0 then V8 will choose an appropriate size of the thread pool based +on the number of online processors.

      +

      If the value provided is larger than V8's maximum, then the largest value +will be chosen.

      +

      --zero-fill-buffers#

      + +

      Automatically zero-fills all newly allocated Buffer and SlowBuffer +instances.

      +

      -c, --check#

      + +

      Syntax check the script without executing.

      +

      -e, --eval "script"#

      + +

      Evaluate the following argument as JavaScript. The modules which are +predefined in the REPL can also be used in script.

      +

      On Windows, using cmd.exe a single quote will not work correctly because it +only recognizes double " for quoting. In Powershell or Git bash, both ' +and " are usable.

      +

      -h, --help#

      + +

      Print node command line options. +The output of this option is less detailed than this document.

      +

      -i, --interactive#

      + +

      Opens the REPL even if stdin does not appear to be a terminal.

      +

      -p, --print "script"#

      + +

      Identical to -e but prints the result.

      +

      -r, --require module#

      + +

      Preload the specified module at startup.

      +

      Follows require()'s module resolution +rules. module may be either a path to a file, or a node module name.

      +

      -v, --version#

      + +

      Print node's version.

      +

      Environment variables#

      +

      NODE_DEBUG=module[,…]#

      + +

      ','-separated list of core modules that should print debug information.

      +

      NODE_DEBUG_NATIVE=module[,…]#

      +

      ','-separated list of core C++ modules that should print debug information.

      +

      NODE_DISABLE_COLORS=1#

      + +

      When set, colors will not be used in the REPL.

      +

      NODE_EXTRA_CA_CERTS=file#

      + +

      When set, the well known "root" CAs (like VeriSign) will be extended with the +extra certificates in file. The file should consist of one or more trusted +certificates in PEM format. A message will be emitted (once) with +process.emitWarning() if the file is missing or +malformed, but any errors are otherwise ignored.

      +

      Neither the well known nor extra certificates are used when the ca +options property is explicitly specified for a TLS or HTTPS client or server.

      +

      This environment variable is ignored when node runs as setuid root or +has Linux file capabilities set.

      +

      NODE_ICU_DATA=file#

      + +

      Data path for ICU (Intl object) data. Will extend linked-in data when compiled +with small-icu support.

      +

      NODE_NO_WARNINGS=1#

      + +

      When set to 1, process warnings are silenced.

      +

      NODE_OPTIONS=options...#

      + +

      A space-separated list of command line options. options... are interpreted +before command line options, so command line options will override or +compound after anything in options.... Node.js will exit with an error if +an option that is not allowed in the environment is used, such as -p or a +script file.

      +

      In case an option value happens to contain a space (for example a path listed +in --require), it must be escaped using double quotes. For example:

      +
      NODE_OPTIONS='--require "./my path/file.js"'
      +

      A singleton flag passed as a command line option will override the same flag +passed into NODE_OPTIONS:

      +
      # The inspector will be available on port 5555
      +NODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555
      +

      A flag that can be passed multiple times will be treated as if its +NODE_OPTIONS instances were passed first, and then its command line +instances afterwards:

      +
      NODE_OPTIONS='--require "./a.js"' node --require "./b.js"
      +# is equivalent to:
      +node --require "./a.js" --require "./b.js"
      +

      Node.js options that are allowed are:

      + +
        +
      • --conditions
      • +
      • --diagnostic-dir
      • +
      • --disable-proto
      • +
      • --enable-fips
      • +
      • --enable-source-maps
      • +
      • --experimental-import-meta-resolve
      • +
      • --experimental-json-modules
      • +
      • --experimental-loader
      • +
      • --experimental-modules
      • +
      • --experimental-policy
      • +
      • --experimental-repl-await
      • +
      • --experimental-specifier-resolution
      • +
      • --experimental-vm-modules
      • +
      • --experimental-wasi-unstable-preview1
      • +
      • --experimental-wasm-modules
      • +
      • --force-context-aware
      • +
      • --force-fips
      • +
      • --frozen-intrinsics
      • +
      • --heapsnapshot-signal
      • +
      • --http-parser
      • +
      • --http-server-default-timeout
      • +
      • --icu-data-dir
      • +
      • --input-type
      • +
      • --insecure-http-parser
      • +
      • --inspect-brk
      • +
      • --inspect-port, --debug-port
      • +
      • --inspect-publish-uid
      • +
      • --inspect
      • +
      • --max-http-header-size
      • +
      • --napi-modules
      • +
      • --no-deprecation
      • +
      • --no-force-async-hooks-checks
      • +
      • --no-warnings
      • +
      • --openssl-config
      • +
      • --pending-deprecation
      • +
      • --policy-integrity
      • +
      • --preserve-symlinks-main
      • +
      • --preserve-symlinks
      • +
      • --prof-process
      • +
      • --redirect-warnings
      • +
      • --report-compact
      • +
      • --report-dir, --report-directory
      • +
      • --report-filename
      • +
      • --report-on-fatalerror
      • +
      • --report-on-signal
      • +
      • --report-signal
      • +
      • --report-uncaught-exception
      • +
      • --require, -r
      • +
      • --throw-deprecation
      • +
      • --title
      • +
      • --tls-cipher-list
      • +
      • --tls-keylog
      • +
      • --tls-max-v1.2
      • +
      • --tls-max-v1.3
      • +
      • --tls-min-v1.0
      • +
      • --tls-min-v1.1
      • +
      • --tls-min-v1.2
      • +
      • --tls-min-v1.3
      • +
      • --trace-deprecation
      • +
      • --trace-event-categories
      • +
      • --trace-event-file-pattern
      • +
      • --trace-events-enabled
      • +
      • --trace-exit
      • +
      • --trace-sigint
      • +
      • --trace-sync-io
      • +
      • --trace-tls
      • +
      • --trace-uncaught
      • +
      • --trace-warnings
      • +
      • --track-heap-objects
      • +
      • --unhandled-rejections
      • +
      • --use-bundled-ca
      • +
      • --use-largepages
      • +
      • --use-openssl-ca
      • +
      • --v8-pool-size
      • +
      • --zero-fill-buffers + +
      • +
      +

      V8 options that are allowed are:

      + +
        +
      • --abort-on-uncaught-exception
      • +
      • --disallow-code-generation-from-strings
      • +
      • --huge-max-old-generation-size
      • +
      • --interpreted-frames-native-stack
      • +
      • --jitless
      • +
      • --max-old-space-size
      • +
      • --perf-basic-prof-only-functions
      • +
      • --perf-basic-prof
      • +
      • --perf-prof-unwinding-info
      • +
      • --perf-prof
      • +
      • --stack-trace-limit + +
      • +
      +

      --perf-basic-prof-only-functions, --perf-basic-prof, +--perf-prof-unwinding-info, and --perf-prof are only available on Linux.

      +

      NODE_PATH=path[:…]#

      + +

      ':'-separated list of directories prefixed to the module search path.

      +

      On Windows, this is a ';'-separated list instead.

      +

      NODE_PENDING_DEPRECATION=1#

      + +

      When set to 1, emit pending deprecation warnings.

      +

      Pending deprecations are generally identical to a runtime deprecation with the +notable exception that they are turned off by default and will not be emitted +unless either the --pending-deprecation command line flag, or the +NODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations +are used to provide a kind of selective "early warning" mechanism that +developers may leverage to detect deprecated API usage.

      +

      NODE_PENDING_PIPE_INSTANCES=instances#

      +

      Set the number of pending pipe instance handles when the pipe server is waiting +for connections. This setting applies to Windows only.

      +

      NODE_PRESERVE_SYMLINKS=1#

      + +

      When set to 1, instructs the module loader to preserve symbolic links when +resolving and caching modules.

      +

      NODE_REDIRECT_WARNINGS=file#

      + +

      When set, process warnings will be emitted to the given file instead of +printing to stderr. The file will be created if it does not exist, and will be +appended to if it does. If an error occurs while attempting to write the +warning to the file, the warning will be written to stderr instead. This is +equivalent to using the --redirect-warnings=file command-line flag.

      +

      NODE_REPL_HISTORY=file#

      + +

      Path to the file used to store the persistent REPL history. The default path is +~/.node_repl_history, which is overridden by this variable. Setting the value +to an empty string ('' or ' ') disables persistent REPL history.

      +

      NODE_REPL_EXTERNAL_MODULE=file#

      + +

      Path to a Node.js module which will be loaded in place of the built-in REPL. +Overriding this value to an empty string ('') will use the built-in REPL.

      +

      NODE_TLS_REJECT_UNAUTHORIZED=value#

      +

      If value equals '0', certificate validation is disabled for TLS connections. +This makes TLS, and HTTPS by extension, insecure. The use of this environment +variable is strongly discouraged.

      +

      NODE_V8_COVERAGE=dir#

      +

      When set, Node.js will begin outputting V8 JavaScript code coverage and +Source Map data to the directory provided as an argument (coverage +information is written as JSON to files with a coverage prefix).

      +

      NODE_V8_COVERAGE will automatically propagate to subprocesses, making it +easier to instrument applications that call the child_process.spawn() family +of functions. NODE_V8_COVERAGE can be set to an empty string, to prevent +propagation.

      +

      Coverage output#

      +

      Coverage is output as an array of ScriptCoverage objects on the top-level +key result:

      +
      {
      +  "result": [
      +    {
      +      "scriptId": "67",
      +      "url": "internal/tty.js",
      +      "functions": []
      +    }
      +  ]
      +}
      +

      Source map cache#

      +

      Stability: 1 - Experimental

      +

      If found, source map data is appended to the top-level key source-map-cache +on the JSON coverage object.

      +

      source-map-cache is an object with keys representing the files source maps +were extracted from, and values which include the raw source-map URL +(in the key url), the parsed Source Map v3 information (in the key data), +and the line lengths of the source file (in the key lineLengths).

      +
      {
      +  "result": [
      +    {
      +      "scriptId": "68",
      +      "url": "file:///absolute/path/to/source.js",
      +      "functions": []
      +    }
      +  ],
      +  "source-map-cache": {
      +    "file:///absolute/path/to/source.js": {
      +      "url": "./path-to-map.json",
      +      "data": {
      +        "version": 3,
      +        "sources": [
      +          "file:///absolute/path/to/original.js"
      +        ],
      +        "names": [
      +          "Foo",
      +          "console",
      +          "info"
      +        ],
      +        "mappings": "MAAMA,IACJC,YAAaC",
      +        "sourceRoot": "./"
      +      },
      +      "lineLengths": [
      +        13,
      +        62,
      +        38,
      +        27
      +      ]
      +    }
      +  }
      +}
      +

      OPENSSL_CONF=file#

      + +

      Load an OpenSSL configuration file on startup. Among other uses, this can be +used to enable FIPS-compliant crypto if Node.js is built with ./configure --openssl-fips.

      +

      If the --openssl-config command line option is used, the environment +variable is ignored.

      +

      SSL_CERT_DIR=dir#

      + +

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory +containing trusted certificates.

      +

      Be aware that unless the child environment is explicitly set, this environment +variable will be inherited by any child processes, and if they use OpenSSL, it +may cause them to trust the same CAs as node.

      +

      SSL_CERT_FILE=file#

      + +

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file +containing trusted certificates.

      +

      Be aware that unless the child environment is explicitly set, this environment +variable will be inherited by any child processes, and if they use OpenSSL, it +may cause them to trust the same CAs as node.

      +

      UV_THREADPOOL_SIZE=size#

      +

      Set the number of threads used in libuv's threadpool to size threads.

      +

      Asynchronous system APIs are used by Node.js whenever possible, but where they +do not exist, libuv's threadpool is used to create asynchronous node APIs based +on synchronous system APIs. Node.js APIs that use the threadpool are:

      +
        +
      • all fs APIs, other than the file watcher APIs and those that are explicitly +synchronous
      • +
      • asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(), +crypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
      • +
      • dns.lookup()
      • +
      • all zlib APIs, other than those that are explicitly synchronous
      • +
      +

      Because libuv's threadpool has a fixed size, it means that if for whatever +reason any of these APIs takes a long time, other (seemingly unrelated) APIs +that run in libuv's threadpool will experience degraded performance. In order to +mitigate this issue, one potential solution is to increase the size of libuv's +threadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value +greater than 4 (its current default value). For more information, see the +libuv threadpool documentation.

      +

      Useful V8 options#

      +

      V8 has its own set of CLI options. Any V8 CLI option that is provided to node +will be passed on to V8 to handle. V8's options have no stability guarantee. +The V8 team themselves don't consider them to be part of their formal API, +and reserve the right to change them at any time. Likewise, they are not +covered by the Node.js stability guarantees. Many of the V8 +options are of interest only to V8 developers. Despite this, there is a small +set of V8 options that are widely applicable to Node.js, and they are +documented here:

      +

      --max-old-space-size=SIZE (in megabytes)#

      +

      Sets the max memory size of V8's old memory section. As memory +consumption approaches the limit, V8 will spend more time on +garbage collection in an effort to free unused memory.

      +

      On a machine with 2GB of memory, consider setting this to +1536 (1.5GB) to leave some memory for other uses and avoid swapping.

      +
      $ node --max-old-space-size=1536 index.js
      +

      Console#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/console.js

      +

      The console module provides a simple debugging console that is similar to the +JavaScript console mechanism provided by web browsers.

      +

      The module exports two specific components:

      +
        +
      • A Console class with methods such as console.log(), console.error() and +console.warn() that can be used to write to any Node.js stream.
      • +
      • A global console instance configured to write to process.stdout and +process.stderr. The global console can be used without calling +require('console').
      • +
      +

      Warning: The global console object's methods are neither consistently +synchronous like the browser APIs they resemble, nor are they consistently +asynchronous like all other Node.js streams. See the note on process I/O for +more information.

      +

      Example using the global console:

      +
      console.log('hello world');
      +// Prints: hello world, to stdout
      +console.log('hello %s', 'world');
      +// Prints: hello world, to stdout
      +console.error(new Error('Whoops, something bad happened'));
      +// Prints: [Error: Whoops, something bad happened], to stderr
      +
      +const name = 'Will Robinson';
      +console.warn(`Danger ${name}! Danger!`);
      +// Prints: Danger Will Robinson! Danger!, to stderr
      +

      Example using the Console class:

      +
      const out = getStreamSomehow();
      +const err = getStreamSomehow();
      +const myConsole = new console.Console(out, err);
      +
      +myConsole.log('hello world');
      +// Prints: hello world, to out
      +myConsole.log('hello %s', 'world');
      +// Prints: hello world, to out
      +myConsole.error(new Error('Whoops, something bad happened'));
      +// Prints: [Error: Whoops, something bad happened], to err
      +
      +const name = 'Will Robinson';
      +myConsole.warn(`Danger ${name}! Danger!`);
      +// Prints: Danger Will Robinson! Danger!, to err
      +

      Class: Console#

      + + +

      The Console class can be used to create a simple logger with configurable +output streams and can be accessed using either require('console').Console +or console.Console (or their destructured counterparts):

      +
      const { Console } = require('console');
      +
      const { Console } = console;
      +

      new Console(stdout[, stderr][, ignoreErrors])#

      +

      new Console(options)#

      + +
        +
      • options <Object> +
          +
        • stdout <stream.Writable>
        • +
        • stderr <stream.Writable>
        • +
        • ignoreErrors <boolean> Ignore errors when writing to the underlying +streams. Default: true.
        • +
        • colorMode <boolean> | <string> Set color support for this Console instance. +Setting to true enables coloring while inspecting values. Setting to +false disables coloring while inspecting values. Setting to +'auto' makes color support depend on the value of the isTTY property +and the value returned by getColorDepth() on the respective stream. This +option can not be used, if inspectOptions.colors is set as well. +Default: 'auto'.
        • +
        • inspectOptions <Object> Specifies options that are passed along to +util.inspect().
        • +
        • groupIndentation <number> Set group indentation. +Default: 2.
        • +
        +
      • +
      +

      Creates a new Console with one or two writable stream instances. stdout is a +writable stream to print log or info output. stderr is used for warning or +error output. If stderr is not provided, stdout is used for stderr.

      +
      const output = fs.createWriteStream('./stdout.log');
      +const errorOutput = fs.createWriteStream('./stderr.log');
      +// Custom simple logger
      +const logger = new Console({ stdout: output, stderr: errorOutput });
      +// use it like console
      +const count = 5;
      +logger.log('count: %d', count);
      +// In stdout.log: count 5
      +

      The global console is a special Console whose output is sent to +process.stdout and process.stderr. It is equivalent to calling:

      +
      new Console({ stdout: process.stdout, stderr: process.stderr });
      +

      console.assert(value[, ...message])#

      + +
        +
      • value <any> The value tested for being truthy.
      • +
      • ...message <any> All arguments besides value are used as error message.
      • +
      +

      console.assert() writes a message if value is falsy or omitted. It only +writes a message and does not otherwise affect execution. The output always +starts with "Assertion failed". If provided, message is formatted using +util.format().

      +

      If value is truthy, nothing happens.

      +
      console.assert(true, 'does nothing');
      +
      +console.assert(false, 'Whoops %s work', 'didn\'t');
      +// Assertion failed: Whoops didn't work
      +
      +console.assert();
      +// Assertion failed
      +

      console.clear()#

      + +

      When stdout is a TTY, calling console.clear() will attempt to clear the +TTY. When stdout is not a TTY, this method does nothing.

      +

      The specific operation of console.clear() can vary across operating systems +and terminal types. For most Linux operating systems, console.clear() +operates similarly to the clear shell command. On Windows, console.clear() +will clear only the output in the current terminal viewport for the Node.js +binary.

      +

      console.count([label])#

      + +
        +
      • label <string> The display label for the counter. Default: 'default'.
      • +
      +

      Maintains an internal counter specific to label and outputs to stdout the +number of times console.count() has been called with the given label.

      + +
      > console.count()
      +default: 1
      +undefined
      +> console.count('default')
      +default: 2
      +undefined
      +> console.count('abc')
      +abc: 1
      +undefined
      +> console.count('xyz')
      +xyz: 1
      +undefined
      +> console.count('abc')
      +abc: 2
      +undefined
      +> console.count()
      +default: 3
      +undefined
      +>
      +

      console.countReset([label])#

      + +
        +
      • label <string> The display label for the counter. Default: 'default'.
      • +
      +

      Resets the internal counter specific to label.

      + +
      > console.count('abc');
      +abc: 1
      +undefined
      +> console.countReset('abc');
      +undefined
      +> console.count('abc');
      +abc: 1
      +undefined
      +>
      +

      console.debug(data[, ...args])#

      + + +

      The console.debug() function is an alias for console.log().

      +

      console.dir(obj[, options])#

      + +
        +
      • obj <any>
      • +
      • options <Object> +
          +
        • showHidden <boolean> If true then the object's non-enumerable and symbol +properties will be shown too. Default: false.
        • +
        • depth <number> Tells util.inspect() how many times to recurse while +formatting the object. This is useful for inspecting large complicated +objects. To make it recurse indefinitely, pass null. Default: 2.
        • +
        • colors <boolean> If true, then the output will be styled with ANSI color +codes. Colors are customizable; +see customizing util.inspect() colors. Default: false.
        • +
        +
      • +
      +

      Uses util.inspect() on obj and prints the resulting string to stdout. +This function bypasses any custom inspect() function defined on obj.

      +

      console.dirxml(...data)#

      + + +

      This method calls console.log() passing it the arguments received. +This method does not produce any XML formatting.

      +

      console.error([data][, ...args])#

      + + +

      Prints to stderr with newline. Multiple arguments can be passed, with the +first used as the primary message and all additional used as substitution +values similar to printf(3) (the arguments are all passed to +util.format()).

      +
      const code = 5;
      +console.error('error #%d', code);
      +// Prints: error #5, to stderr
      +console.error('error', code);
      +// Prints: error 5, to stderr
      +

      If formatting elements (e.g. %d) are not found in the first string then +util.inspect() is called on each argument and the resulting string +values are concatenated. See util.format() for more information.

      +

      console.group([...label])#

      + + +

      Increases indentation of subsequent lines by spaces for groupIndentation +length.

      +

      If one or more labels are provided, those are printed first without the +additional indentation.

      +

      console.groupCollapsed()#

      + +

      An alias for console.group().

      +

      console.groupEnd()#

      + +

      Decreases indentation of subsequent lines by spaces for groupIndentation +length.

      +

      console.info([data][, ...args])#

      + + +

      The console.info() function is an alias for console.log().

      +

      console.log([data][, ...args])#

      + + +

      Prints to stdout with newline. Multiple arguments can be passed, with the +first used as the primary message and all additional used as substitution +values similar to printf(3) (the arguments are all passed to +util.format()).

      +
      const count = 5;
      +console.log('count: %d', count);
      +// Prints: count: 5, to stdout
      +console.log('count:', count);
      +// Prints: count: 5, to stdout
      +

      See util.format() for more information.

      +

      console.table(tabularData[, properties])#

      + +
        +
      • tabularData <any>
      • +
      • properties <string[]> Alternate properties for constructing the table.
      • +
      +

      Try to construct a table with the columns of the properties of tabularData +(or use properties) and rows of tabularData and log it. Falls back to just +logging the argument if it can’t be parsed as tabular.

      +
      // These can't be parsed as tabular data
      +console.table(Symbol());
      +// Symbol()
      +
      +console.table(undefined);
      +// undefined
      +
      +console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
      +// ┌─────────┬─────┬─────â”
      +// │ (index) │  a  │  b  │
      +// ├─────────┼─────┼─────┤
      +// │    0    │  1  │ 'Y' │
      +// │    1    │ 'Z' │  2  │
      +// └─────────┴─────┴─────┘
      +
      +console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
      +// ┌─────────┬─────â”
      +// │ (index) │  a  │
      +// ├─────────┼─────┤
      +// │    0    │  1  │
      +// │    1    │ 'Z' │
      +// └─────────┴─────┘
      +

      console.time([label])#

      + + +

      Starts a timer that can be used to compute the duration of an operation. Timers +are identified by a unique label. Use the same label when calling +console.timeEnd() to stop the timer and output the elapsed time in +milliseconds to stdout. Timer durations are accurate to the sub-millisecond.

      +

      console.timeEnd([label])#

      + + +

      Stops a timer that was previously started by calling console.time() and +prints the result to stdout:

      +
      console.time('100-elements');
      +for (let i = 0; i < 100; i++) {}
      +console.timeEnd('100-elements');
      +// prints 100-elements: 225.438ms
      +

      console.timeLog([label][, ...data])#

      + + +

      For a timer that was previously started by calling console.time(), prints +the elapsed time and other data arguments to stdout:

      +
      console.time('process');
      +const value = expensiveProcess1(); // Returns 42
      +console.timeLog('process', value);
      +// Prints "process: 365.227ms 42".
      +doExpensiveProcess2(value);
      +console.timeEnd('process');
      +

      console.trace([message][, ...args])#

      + + +

      Prints to stderr the string 'Trace: ', followed by the util.format() +formatted message and stack trace to the current position in the code.

      +
      console.trace('Show me');
      +// Prints: (stack trace will vary based on where trace is called)
      +//  Trace: Show me
      +//    at repl:2:9
      +//    at REPLServer.defaultEval (repl.js:248:27)
      +//    at bound (domain.js:287:14)
      +//    at REPLServer.runBound [as eval] (domain.js:300:12)
      +//    at REPLServer.<anonymous> (repl.js:412:12)
      +//    at emitOne (events.js:82:20)
      +//    at REPLServer.emit (events.js:169:7)
      +//    at REPLServer.Interface._onLine (readline.js:210:10)
      +//    at REPLServer.Interface._line (readline.js:549:8)
      +//    at REPLServer.Interface._ttyWrite (readline.js:826:14)
      +

      console.warn([data][, ...args])#

      + + +

      The console.warn() function is an alias for console.error().

      +

      Inspector only methods#

      +

      The following methods are exposed by the V8 engine in the general API but do +not display anything unless used in conjunction with the inspector +(--inspect flag).

      +

      console.profile([label])#

      + + +

      This method does not display anything unless used in the inspector. The +console.profile() method starts a JavaScript CPU profile with an optional +label until console.profileEnd() is called. The profile is then added to +the Profile panel of the inspector.

      +
      console.profile('MyLabel');
      +// Some code
      +console.profileEnd('MyLabel');
      +// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
      +

      console.profileEnd([label])#

      + + +

      This method does not display anything unless used in the inspector. Stops the +current JavaScript CPU profiling session if one has been started and prints +the report to the Profiles panel of the inspector. See +console.profile() for an example.

      +

      If this method is called without a label, the most recently started profile is +stopped.

      +

      console.timeStamp([label])#

      + + +

      This method does not display anything unless used in the inspector. The +console.timeStamp() method adds an event with the label 'label' to the +Timeline panel of the inspector.

      +

      Crypto#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/crypto.js

      +

      The crypto module provides cryptographic functionality that includes a set of +wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

      +

      Use require('crypto') to access this module.

      +
      const crypto = require('crypto');
      +
      +const secret = 'abcdefg';
      +const hash = crypto.createHmac('sha256', secret)
      +                   .update('I love cupcakes')
      +                   .digest('hex');
      +console.log(hash);
      +// Prints:
      +//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
      +

      Determining if crypto support is unavailable#

      +

      It is possible for Node.js to be built without including support for the +crypto module. In such cases, calling require('crypto') will result in an +error being thrown.

      +
      let crypto;
      +try {
      +  crypto = require('crypto');
      +} catch (err) {
      +  console.log('crypto support is disabled!');
      +}
      +

      Class: Certificate#

      + +

      SPKAC is a Certificate Signing Request mechanism originally implemented by +Netscape and was specified formally as part of HTML5's keygen element.

      +

      <keygen> is deprecated since HTML 5.2 and new projects +should not use this element anymore.

      +

      The crypto module provides the Certificate class for working with SPKAC +data. The most common usage is handling output generated by the HTML5 +<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.

      +

      Certificate.exportChallenge(spkac)#

      + + +
      const { Certificate } = require('crypto');
      +const spkac = getSpkacSomehow();
      +const challenge = Certificate.exportChallenge(spkac);
      +console.log(challenge.toString('utf8'));
      +// Prints: the challenge as a UTF8 string
      +

      Certificate.exportPublicKey(spkac[, encoding])#

      + + +
      const { Certificate } = require('crypto');
      +const spkac = getSpkacSomehow();
      +const publicKey = Certificate.exportPublicKey(spkac);
      +console.log(publicKey);
      +// Prints: the public key as <Buffer ...>
      +

      Certificate.verifySpkac(spkac)#

      + + +
      const { Certificate } = require('crypto');
      +const spkac = getSpkacSomehow();
      +console.log(Certificate.verifySpkac(Buffer.from(spkac)));
      +// Prints: true or false
      +

      Legacy API#

      +

      As a still supported legacy interface, it is possible to create new instances of +the crypto.Certificate class as illustrated in the examples below.

      +

      new crypto.Certificate()#

      +

      Instances of the Certificate class can be created using the new keyword +or by calling crypto.Certificate() as a function:

      +
      const crypto = require('crypto');
      +
      +const cert1 = new crypto.Certificate();
      +const cert2 = crypto.Certificate();
      +

      certificate.exportChallenge(spkac)#

      + + +
      const cert = require('crypto').Certificate();
      +const spkac = getSpkacSomehow();
      +const challenge = cert.exportChallenge(spkac);
      +console.log(challenge.toString('utf8'));
      +// Prints: the challenge as a UTF8 string
      +

      certificate.exportPublicKey(spkac)#

      + + +
      const cert = require('crypto').Certificate();
      +const spkac = getSpkacSomehow();
      +const publicKey = cert.exportPublicKey(spkac);
      +console.log(publicKey);
      +// Prints: the public key as <Buffer ...>
      +

      certificate.verifySpkac(spkac)#

      + + +
      const cert = require('crypto').Certificate();
      +const spkac = getSpkacSomehow();
      +console.log(cert.verifySpkac(Buffer.from(spkac)));
      +// Prints: true or false
      +

      Class: Cipher#

      + + +

      Instances of the Cipher class are used to encrypt data. The class can be +used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where plain unencrypted +data is written to produce encrypted data on the readable side, or
      • +
      • Using the cipher.update() and cipher.final() methods to produce +the encrypted data.
      • +
      +

      The crypto.createCipher() or crypto.createCipheriv() methods are +used to create Cipher instances. Cipher objects are not to be created +directly using the new keyword.

      +

      Example: Using Cipher objects as streams:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Key length is dependent on the algorithm. In this case for aes192, it is
      +// 24 bytes (192 bits).
      +// Use async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
      +// shown here.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const cipher = crypto.createCipheriv(algorithm, key, iv);
      +
      +let encrypted = '';
      +cipher.on('readable', () => {
      +  let chunk;
      +  while (null !== (chunk = cipher.read())) {
      +    encrypted += chunk.toString('hex');
      +  }
      +});
      +cipher.on('end', () => {
      +  console.log(encrypted);
      +  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
      +});
      +
      +cipher.write('some clear text data');
      +cipher.end();
      +

      Example: Using Cipher and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
      +// shown here.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const cipher = crypto.createCipheriv(algorithm, key, iv);
      +
      +const input = fs.createReadStream('test.js');
      +const output = fs.createWriteStream('test.enc');
      +
      +input.pipe(cipher).pipe(output);
      +

      Example: Using the cipher.update() and cipher.final() methods:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// Use `crypto.randomBytes` to generate a random iv instead of the static iv
      +// shown here.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const cipher = crypto.createCipheriv(algorithm, key, iv);
      +
      +let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
      +encrypted += cipher.final('hex');
      +console.log(encrypted);
      +// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
      +

      cipher.final([outputEncoding])#

      + +
        +
      • outputEncoding <string> The encoding of the return value.
      • +
      • Returns: <Buffer> | <string> Any remaining enciphered contents. +If outputEncoding is specified, a string is +returned. If an outputEncoding is not provided, a Buffer is returned.
      • +
      +

      Once the cipher.final() method has been called, the Cipher object can no +longer be used to encrypt data. Attempts to call cipher.final() more than +once will result in an error being thrown.

      +

      cipher.setAAD(buffer[, options])#

      + + +

      When using an authenticated encryption mode (GCM, CCM and OCB are +currently supported), the cipher.setAAD() method sets the value used for the +additional authenticated data (AAD) input parameter.

      +

      The options argument is optional for GCM and OCB. When using CCM, the +plaintextLength option must be specified and its value must match the length +of the plaintext in bytes. See CCM mode.

      +

      The cipher.setAAD() method must be called before cipher.update().

      +

      cipher.getAuthTag()#

      + +
        +
      • Returns: <Buffer> When using an authenticated encryption mode (GCM, CCM +and OCB are currently supported), the cipher.getAuthTag() method returns a +Buffer containing the authentication tag that has been computed from +the given data.
      • +
      +

      The cipher.getAuthTag() method should only be called after encryption has +been completed using the cipher.final() method.

      +

      cipher.setAutoPadding([autoPadding])#

      + + +

      When using block encryption algorithms, the Cipher class will automatically +add padding to the input data to the appropriate block size. To disable the +default padding call cipher.setAutoPadding(false).

      +

      When autoPadding is false, the length of the entire input data must be a +multiple of the cipher's block size or cipher.final() will throw an error. +Disabling automatic padding is useful for non-standard padding, for instance +using 0x0 instead of PKCS padding.

      +

      The cipher.setAutoPadding() method must be called before +cipher.final().

      +

      cipher.update(data[, inputEncoding][, outputEncoding])#

      + + +

      Updates the cipher with data. If the inputEncoding argument is given, +the data +argument is a string using the specified encoding. If the inputEncoding +argument is not given, data must be a Buffer, TypedArray, or +DataView. If data is a Buffer, TypedArray, or DataView, then +inputEncoding is ignored.

      +

      The outputEncoding specifies the output format of the enciphered +data. If the outputEncoding +is specified, a string using the specified encoding is returned. If no +outputEncoding is provided, a Buffer is returned.

      +

      The cipher.update() method can be called multiple times with new data until +cipher.final() is called. Calling cipher.update() after +cipher.final() will result in an error being thrown.

      +

      Class: Decipher#

      + + +

      Instances of the Decipher class are used to decrypt data. The class can be +used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where plain encrypted +data is written to produce unencrypted data on the readable side, or
      • +
      • Using the decipher.update() and decipher.final() methods to +produce the unencrypted data.
      • +
      +

      The crypto.createDecipher() or crypto.createDecipheriv() methods are +used to create Decipher instances. Decipher objects are not to be created +directly using the new keyword.

      +

      Example: Using Decipher objects as streams:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Key length is dependent on the algorithm. In this case for aes192, it is
      +// 24 bytes (192 bits).
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// The IV is usually passed along with the ciphertext.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const decipher = crypto.createDecipheriv(algorithm, key, iv);
      +
      +let decrypted = '';
      +decipher.on('readable', () => {
      +  while (null !== (chunk = decipher.read())) {
      +    decrypted += chunk.toString('utf8');
      +  }
      +});
      +decipher.on('end', () => {
      +  console.log(decrypted);
      +  // Prints: some clear text data
      +});
      +
      +// Encrypted with same algorithm, key and iv.
      +const encrypted =
      +  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
      +decipher.write(encrypted, 'hex');
      +decipher.end();
      +

      Example: Using Decipher and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// The IV is usually passed along with the ciphertext.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const decipher = crypto.createDecipheriv(algorithm, key, iv);
      +
      +const input = fs.createReadStream('test.enc');
      +const output = fs.createWriteStream('test.js');
      +
      +input.pipe(decipher).pipe(output);
      +

      Example: Using the decipher.update() and decipher.final() methods:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// The IV is usually passed along with the ciphertext.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const decipher = crypto.createDecipheriv(algorithm, key, iv);
      +
      +// Encrypted using same algorithm, key and iv.
      +const encrypted =
      +  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
      +let decrypted = decipher.update(encrypted, 'hex', 'utf8');
      +decrypted += decipher.final('utf8');
      +console.log(decrypted);
      +// Prints: some clear text data
      +

      decipher.final([outputEncoding])#

      + +
        +
      • outputEncoding <string> The encoding of the return value.
      • +
      • Returns: <Buffer> | <string> Any remaining deciphered contents. +If outputEncoding is specified, a string is +returned. If an outputEncoding is not provided, a Buffer is returned.
      • +
      +

      Once the decipher.final() method has been called, the Decipher object can +no longer be used to decrypt data. Attempts to call decipher.final() more +than once will result in an error being thrown.

      +

      decipher.setAAD(buffer[, options])#

      + + +

      When using an authenticated encryption mode (GCM, CCM and OCB are +currently supported), the decipher.setAAD() method sets the value used for the +additional authenticated data (AAD) input parameter.

      +

      The options argument is optional for GCM. When using CCM, the +plaintextLength option must be specified and its value must match the length +of the ciphertext in bytes. See CCM mode.

      +

      The decipher.setAAD() method must be called before decipher.update().

      +

      decipher.setAuthTag(buffer)#

      + + +

      When using an authenticated encryption mode (GCM, CCM and OCB are +currently supported), the decipher.setAuthTag() method is used to pass in the +received authentication tag. If no tag is provided, or if the cipher text +has been tampered with, decipher.final() will throw, indicating that the +cipher text should be discarded due to failed authentication. If the tag length +is invalid according to NIST SP 800-38D or does not match the value of the +authTagLength option, decipher.setAuthTag() will throw an error.

      +

      The decipher.setAuthTag() method must be called before decipher.update() +for CCM mode or before decipher.final() for GCM and OCB modes. +decipher.setAuthTag() can only be called once.

      +

      decipher.setAutoPadding([autoPadding])#

      + + +

      When data has been encrypted without standard block padding, calling +decipher.setAutoPadding(false) will disable automatic padding to prevent +decipher.final() from checking for and removing padding.

      +

      Turning auto padding off will only work if the input data's length is a +multiple of the ciphers block size.

      +

      The decipher.setAutoPadding() method must be called before +decipher.final().

      +

      decipher.update(data[, inputEncoding][, outputEncoding])#

      + + +

      Updates the decipher with data. If the inputEncoding argument is given, +the data +argument is a string using the specified encoding. If the inputEncoding +argument is not given, data must be a Buffer. If data is a +Buffer then inputEncoding is ignored.

      +

      The outputEncoding specifies the output format of the enciphered +data. If the outputEncoding +is specified, a string using the specified encoding is returned. If no +outputEncoding is provided, a Buffer is returned.

      +

      The decipher.update() method can be called multiple times with new data until +decipher.final() is called. Calling decipher.update() after +decipher.final() will result in an error being thrown.

      +

      Class: DiffieHellman#

      + +

      The DiffieHellman class is a utility for creating Diffie-Hellman key +exchanges.

      +

      Instances of the DiffieHellman class can be created using the +crypto.createDiffieHellman() function.

      +
      const crypto = require('crypto');
      +const assert = require('assert');
      +
      +// Generate Alice's keys...
      +const alice = crypto.createDiffieHellman(2048);
      +const aliceKey = alice.generateKeys();
      +
      +// Generate Bob's keys...
      +const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
      +const bobKey = bob.generateKeys();
      +
      +// Exchange and generate the secret...
      +const aliceSecret = alice.computeSecret(bobKey);
      +const bobSecret = bob.computeSecret(aliceKey);
      +
      +// OK
      +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
      +

      diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#

      + + +

      Computes the shared secret using otherPublicKey as the other +party's public key and returns the computed shared secret. The supplied +key is interpreted using the specified inputEncoding, and secret is +encoded using specified outputEncoding. +If the inputEncoding is not +provided, otherPublicKey is expected to be a Buffer, +TypedArray, or DataView.

      +

      If outputEncoding is given a string is returned; otherwise, a +Buffer is returned.

      +

      diffieHellman.generateKeys([encoding])#

      + + +

      Generates private and public Diffie-Hellman key values, and returns +the public key in the specified encoding. This key should be +transferred to the other party. +If encoding is provided a string is returned; otherwise a +Buffer is returned.

      +

      diffieHellman.getGenerator([encoding])#

      + + +

      Returns the Diffie-Hellman generator in the specified encoding. +If encoding is provided a string is +returned; otherwise a Buffer is returned.

      +

      diffieHellman.getPrime([encoding])#

      + + +

      Returns the Diffie-Hellman prime in the specified encoding. +If encoding is provided a string is +returned; otherwise a Buffer is returned.

      +

      diffieHellman.getPrivateKey([encoding])#

      + + +

      Returns the Diffie-Hellman private key in the specified encoding. +If encoding is provided a +string is returned; otherwise a Buffer is returned.

      +

      diffieHellman.getPublicKey([encoding])#

      + + +

      Returns the Diffie-Hellman public key in the specified encoding. +If encoding is provided a +string is returned; otherwise a Buffer is returned.

      +

      diffieHellman.setPrivateKey(privateKey[, encoding])#

      + + +

      Sets the Diffie-Hellman private key. If the encoding argument is provided, +privateKey is expected +to be a string. If no encoding is provided, privateKey is expected +to be a Buffer, TypedArray, or DataView.

      +

      diffieHellman.setPublicKey(publicKey[, encoding])#

      + + +

      Sets the Diffie-Hellman public key. If the encoding argument is provided, +publicKey is expected +to be a string. If no encoding is provided, publicKey is expected +to be a Buffer, TypedArray, or DataView.

      +

      diffieHellman.verifyError#

      + +

      A bit field containing any warnings and/or errors resulting from a check +performed during initialization of the DiffieHellman object.

      +

      The following values are valid for this property (as defined in constants +module):

      +
        +
      • DH_CHECK_P_NOT_SAFE_PRIME
      • +
      • DH_CHECK_P_NOT_PRIME
      • +
      • DH_UNABLE_TO_CHECK_GENERATOR
      • +
      • DH_NOT_SUITABLE_GENERATOR
      • +
      +

      Class: DiffieHellmanGroup#

      + +

      The DiffieHellmanGroup class takes a well-known modp group as its argument but +otherwise works the same as DiffieHellman.

      +
      const name = 'modp1';
      +const dh = crypto.createDiffieHellmanGroup(name);
      +

      name is taken from RFC 2412 (modp1 and 2) and RFC 3526:

      +
      $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
      +modp1  #  768 bits
      +modp2  # 1024 bits
      +modp5  # 1536 bits
      +modp14 # 2048 bits
      +modp15 # etc.
      +modp16
      +modp17
      +modp18
      +

      Class: ECDH#

      + +

      The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) +key exchanges.

      +

      Instances of the ECDH class can be created using the +crypto.createECDH() function.

      +
      const crypto = require('crypto');
      +const assert = require('assert');
      +
      +// Generate Alice's keys...
      +const alice = crypto.createECDH('secp521r1');
      +const aliceKey = alice.generateKeys();
      +
      +// Generate Bob's keys...
      +const bob = crypto.createECDH('secp521r1');
      +const bobKey = bob.generateKeys();
      +
      +// Exchange and generate the secret...
      +const aliceSecret = alice.computeSecret(bobKey);
      +const bobSecret = bob.computeSecret(aliceKey);
      +
      +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
      +// OK
      +

      Static method: ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])#

      + + +

      Converts the EC Diffie-Hellman public key specified by key and curve to the +format specified by format. The format argument specifies point encoding +and can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is +interpreted using the specified inputEncoding, and the returned key is encoded +using the specified outputEncoding.

      +

      Use crypto.getCurves() to obtain a list of available curve names. +On recent OpenSSL releases, openssl ecparam -list_curves will also display +the name and description of each available elliptic curve.

      +

      If format is not specified the point will be returned in 'uncompressed' +format.

      +

      If the inputEncoding is not provided, key is expected to be a Buffer, +TypedArray, or DataView.

      +

      Example (uncompressing a key):

      +
      const { createECDH, ECDH } = require('crypto');
      +
      +const ecdh = createECDH('secp256k1');
      +ecdh.generateKeys();
      +
      +const compressedKey = ecdh.getPublicKey('hex', 'compressed');
      +
      +const uncompressedKey = ECDH.convertKey(compressedKey,
      +                                        'secp256k1',
      +                                        'hex',
      +                                        'hex',
      +                                        'uncompressed');
      +
      +// The converted key and the uncompressed public key should be the same
      +console.log(uncompressedKey === ecdh.getPublicKey('hex'));
      +

      ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#

      + + +

      Computes the shared secret using otherPublicKey as the other +party's public key and returns the computed shared secret. The supplied +key is interpreted using specified inputEncoding, and the returned secret +is encoded using the specified outputEncoding. +If the inputEncoding is not +provided, otherPublicKey is expected to be a Buffer, TypedArray, or +DataView.

      +

      If outputEncoding is given a string will be returned; otherwise a +Buffer is returned.

      +

      ecdh.computeSecret will throw an +ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey +lies outside of the elliptic curve. Since otherPublicKey is +usually supplied from a remote user over an insecure network, +be sure to handle this exception accordingly.

      +

      ecdh.generateKeys([encoding[, format]])#

      + + +

      Generates private and public EC Diffie-Hellman key values, and returns +the public key in the specified format and encoding. This key should be +transferred to the other party.

      +

      The format argument specifies point encoding and can be 'compressed' or +'uncompressed'. If format is not specified, the point will be returned in +'uncompressed' format.

      +

      If encoding is provided a string is returned; otherwise a Buffer +is returned.

      +

      ecdh.getPrivateKey([encoding])#

      + + +

      If encoding is specified, a string is returned; otherwise a Buffer is +returned.

      +

      ecdh.getPublicKey([encoding][, format])#

      + + +

      The format argument specifies point encoding and can be 'compressed' or +'uncompressed'. If format is not specified the point will be returned in +'uncompressed' format.

      +

      If encoding is specified, a string is returned; otherwise a Buffer is +returned.

      +

      ecdh.setPrivateKey(privateKey[, encoding])#

      + + +

      Sets the EC Diffie-Hellman private key. +If encoding is provided, privateKey is expected +to be a string; otherwise privateKey is expected to be a Buffer, +TypedArray, or DataView.

      +

      If privateKey is not valid for the curve specified when the ECDH object was +created, an error is thrown. Upon setting the private key, the associated +public point (key) is also generated and set in the ECDH object.

      +

      ecdh.setPublicKey(publicKey[, encoding])#

      + +

      Stability: 0 - Deprecated

      + +

      Sets the EC Diffie-Hellman public key. +If encoding is provided publicKey is expected to +be a string; otherwise a Buffer, TypedArray, or DataView is expected.

      +

      There is not normally a reason to call this method because ECDH +only requires a private key and the other party's public key to compute the +shared secret. Typically either ecdh.generateKeys() or +ecdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method +attempts to generate the public point/key associated with the private key being +set.

      +

      Example (obtaining a shared secret):

      +
      const crypto = require('crypto');
      +const alice = crypto.createECDH('secp256k1');
      +const bob = crypto.createECDH('secp256k1');
      +
      +// This is a shortcut way of specifying one of Alice's previous private
      +// keys. It would be unwise to use such a predictable private key in a real
      +// application.
      +alice.setPrivateKey(
      +  crypto.createHash('sha256').update('alice', 'utf8').digest()
      +);
      +
      +// Bob uses a newly generated cryptographically strong
      +// pseudorandom key pair
      +bob.generateKeys();
      +
      +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
      +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
      +
      +// aliceSecret and bobSecret should be the same shared secret value
      +console.log(aliceSecret === bobSecret);
      +

      Class: Hash#

      + + +

      The Hash class is a utility for creating hash digests of data. It can be +used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where data is written +to produce a computed hash digest on the readable side, or
      • +
      • Using the hash.update() and hash.digest() methods to produce the +computed hash.
      • +
      +

      The crypto.createHash() method is used to create Hash instances. Hash +objects are not to be created directly using the new keyword.

      +

      Example: Using Hash objects as streams:

      +
      const crypto = require('crypto');
      +const hash = crypto.createHash('sha256');
      +
      +hash.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = hash.read();
      +  if (data) {
      +    console.log(data.toString('hex'));
      +    // Prints:
      +    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
      +  }
      +});
      +
      +hash.write('some data to hash');
      +hash.end();
      +

      Example: Using Hash and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +const hash = crypto.createHash('sha256');
      +
      +const input = fs.createReadStream('test.js');
      +input.pipe(hash).pipe(process.stdout);
      +

      Example: Using the hash.update() and hash.digest() methods:

      +
      const crypto = require('crypto');
      +const hash = crypto.createHash('sha256');
      +
      +hash.update('some data to hash');
      +console.log(hash.digest('hex'));
      +// Prints:
      +//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
      +

      hash.copy([options])#

      + + +

      Creates a new Hash object that contains a deep copy of the internal state +of the current Hash object.

      +

      The optional options argument controls stream behavior. For XOF hash +functions such as 'shake256', the outputLength option can be used to +specify the desired output length in bytes.

      +

      An error is thrown when an attempt is made to copy the Hash object after +its hash.digest() method has been called.

      +
      // Calculate a rolling hash.
      +const crypto = require('crypto');
      +const hash = crypto.createHash('sha256');
      +
      +hash.update('one');
      +console.log(hash.copy().digest('hex'));
      +
      +hash.update('two');
      +console.log(hash.copy().digest('hex'));
      +
      +hash.update('three');
      +console.log(hash.copy().digest('hex'));
      +
      +// Etc.
      +

      hash.digest([encoding])#

      + + +

      Calculates the digest of all of the data passed to be hashed (using the +hash.update() method). +If encoding is provided a string will be returned; otherwise +a Buffer is returned.

      +

      The Hash object can not be used again after hash.digest() method has been +called. Multiple calls will cause an error to be thrown.

      +

      hash.update(data[, inputEncoding])#

      + + +

      Updates the hash content with the given data, the encoding of which +is given in inputEncoding. +If encoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      Class: Hmac#

      + + +

      The Hmac class is a utility for creating cryptographic HMAC digests. It can +be used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where data is written +to produce a computed HMAC digest on the readable side, or
      • +
      • Using the hmac.update() and hmac.digest() methods to produce the +computed HMAC digest.
      • +
      +

      The crypto.createHmac() method is used to create Hmac instances. Hmac +objects are not to be created directly using the new keyword.

      +

      Example: Using Hmac objects as streams:

      +
      const crypto = require('crypto');
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +hmac.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = hmac.read();
      +  if (data) {
      +    console.log(data.toString('hex'));
      +    // Prints:
      +    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
      +  }
      +});
      +
      +hmac.write('some data to hash');
      +hmac.end();
      +

      Example: Using Hmac and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +const input = fs.createReadStream('test.js');
      +input.pipe(hmac).pipe(process.stdout);
      +

      Example: Using the hmac.update() and hmac.digest() methods:

      +
      const crypto = require('crypto');
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +hmac.update('some data to hash');
      +console.log(hmac.digest('hex'));
      +// Prints:
      +//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
      +

      hmac.digest([encoding])#

      + + +

      Calculates the HMAC digest of all of the data passed using hmac.update(). +If encoding is +provided a string is returned; otherwise a Buffer is returned;

      +

      The Hmac object can not be used again after hmac.digest() has been +called. Multiple calls to hmac.digest() will result in an error being thrown.

      +

      hmac.update(data[, inputEncoding])#

      + + +

      Updates the Hmac content with the given data, the encoding of which +is given in inputEncoding. +If encoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      Class: KeyObject#

      + +

      Node.js uses a KeyObject class to represent a symmetric or asymmetric key, +and each kind of key exposes different functions. The +crypto.createSecretKey(), crypto.createPublicKey() and +crypto.createPrivateKey() methods are used to create KeyObject +instances. KeyObject objects are not to be created directly using the new +keyword.

      +

      Most applications should consider using the new KeyObject API instead of +passing keys as strings or Buffers due to improved security features.

      +

      KeyObject instances can be passed to other threads via postMessage(). +The receiver obtains a cloned KeyObject, and the KeyObject does not need to +be listed in the transferList argument.

      +

      keyObject.asymmetricKeyType#

      + + +

      For asymmetric keys, this property represents the type of the key. Supported key +types are:

      +
        +
      • 'rsa' (OID 1.2.840.113549.1.1.1)
      • +
      • 'rsa-pss' (OID 1.2.840.113549.1.1.10)
      • +
      • 'dsa' (OID 1.2.840.10040.4.1)
      • +
      • 'ec' (OID 1.2.840.10045.2.1)
      • +
      • 'x25519' (OID 1.3.101.110)
      • +
      • 'x448' (OID 1.3.101.111)
      • +
      • 'ed25519' (OID 1.3.101.112)
      • +
      • 'ed448' (OID 1.3.101.113)
      • +
      • 'dh' (OID 1.2.840.113549.1.3.1)
      • +
      +

      This property is undefined for unrecognized KeyObject types and symmetric +keys.

      +

      keyObject.export([options])#

      + + +

      For symmetric keys, this function allocates a Buffer containing the key +material and ignores any options.

      +

      For asymmetric keys, the options parameter is used to determine the export +format.

      +

      For public keys, the following encoding options can be used:

      +
        +
      • type: <string> Must be one of 'pkcs1' (RSA only) or 'spki'.
      • +
      • format: <string> Must be 'pem' or 'der'.
      • +
      +

      For private keys, the following encoding options can be used:

      +
        +
      • type: <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or +'sec1' (EC only).
      • +
      • format: <string> Must be 'pem' or 'der'.
      • +
      • cipher: <string> If specified, the private key will be encrypted with + the given cipher and passphrase using PKCS#5 v2.0 password based +encryption.
      • +
      • passphrase: <string> | <Buffer> The passphrase to use for encryption, see +cipher.
      • +
      +

      When PEM encoding was selected, the result will be a string, otherwise it will +be a buffer containing the data encoded as DER.

      +

      PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of +the cipher and format options. The PKCS#8 type can be used with any +format to encrypt any key algorithm (RSA, EC, or DH) by specifying a +cipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher +when the PEM format is used. For maximum compatibility, use PKCS#8 for +encrypted private keys. Since PKCS#8 defines its own +encryption mechanism, PEM-level encryption is not supported when encrypting +a PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for +PKCS#1 and SEC1 encryption.

      +

      keyObject.symmetricKeySize#

      + + +

      For secret keys, this property represents the size of the key in bytes. This +property is undefined for asymmetric keys.

      +

      keyObject.type#

      + + +

      Depending on the type of this KeyObject, this property is either +'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys +or 'private' for private (asymmetric) keys.

      +

      Class: Sign#

      + + +

      The Sign class is a utility for generating signatures. It can be used in one +of two ways:

      +
        +
      • As a writable stream, where data to be signed is written and the +sign.sign() method is used to generate and return the signature, or
      • +
      • Using the sign.update() and sign.sign() methods to produce the +signature.
      • +
      +

      The crypto.createSign() method is used to create Sign instances. The +argument is the string name of the hash function to use. Sign objects are not +to be created directly using the new keyword.

      +

      Example: Using Sign and Verify objects as streams:

      +
      const crypto = require('crypto');
      +
      +const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
      +  namedCurve: 'sect239k1'
      +});
      +
      +const sign = crypto.createSign('SHA256');
      +sign.write('some data to sign');
      +sign.end();
      +const signature = sign.sign(privateKey, 'hex');
      +
      +const verify = crypto.createVerify('SHA256');
      +verify.write('some data to sign');
      +verify.end();
      +console.log(verify.verify(publicKey, signature, 'hex'));
      +// Prints: true
      +

      Example: Using the sign.update() and verify.update() methods:

      +
      const crypto = require('crypto');
      +
      +const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
      +  modulusLength: 2048,
      +});
      +
      +const sign = crypto.createSign('SHA256');
      +sign.update('some data to sign');
      +sign.end();
      +const signature = sign.sign(privateKey);
      +
      +const verify = crypto.createVerify('SHA256');
      +verify.update('some data to sign');
      +verify.end();
      +console.log(verify.verify(publicKey, signature));
      +// Prints: true
      +

      sign.sign(privateKey[, outputEncoding])#

      + + +

      Calculates the signature on all the data passed through using either +sign.update() or sign.write().

      +

      If privateKey is not a KeyObject, this function behaves as if +privateKey had been passed to crypto.createPrivateKey(). If it is an +object, the following additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to sign the message as specified in section 3.1 of RFC 4055, unless +an MGF1 hash function has been specified as part of the key in compliance with +section 3.3 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the +maximum permissible value.

        +
      • +
      +

      If outputEncoding is provided a string is returned; otherwise a Buffer +is returned.

      +

      The Sign object can not be again used after sign.sign() method has been +called. Multiple calls to sign.sign() will result in an error being thrown.

      +

      sign.update(data[, inputEncoding])#

      + + +

      Updates the Sign content with the given data, the encoding of which +is given in inputEncoding. +If encoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      Class: Verify#

      + + +

      The Verify class is a utility for verifying signatures. It can be used in one +of two ways:

      +
        +
      • As a writable stream where written data is used to validate against the +supplied signature, or
      • +
      • Using the verify.update() and verify.verify() methods to verify +the signature.
      • +
      +

      The crypto.createVerify() method is used to create Verify instances. +Verify objects are not to be created directly using the new keyword.

      +

      See Sign for examples.

      +

      verify.update(data[, inputEncoding])#

      + + +

      Updates the Verify content with the given data, the encoding of which +is given in inputEncoding. +If inputEncoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      verify.verify(object, signature[, signatureEncoding])#

      + + +

      Verifies the provided data using the given object and signature.

      +

      If object is not a KeyObject, this function behaves as if +object had been passed to crypto.createPublicKey(). If it is an +object, the following additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to verify the message as specified in section 3.1 of RFC 4055, unless +an MGF1 hash function has been specified as part of the key in compliance with +section 3.3 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be +determined automatically.

        +
      • +
      +

      The signature argument is the previously calculated signature for the data, in +the signatureEncoding. +If a signatureEncoding is specified, the signature is expected to be a +string; otherwise signature is expected to be a Buffer, +TypedArray, or DataView.

      +

      The verify object can not be used again after verify.verify() has been +called. Multiple calls to verify.verify() will result in an error being +thrown.

      +

      Because public keys can be derived from private keys, a private key may +be passed instead of a public key.

      +

      crypto module methods and properties#

      +

      crypto.constants#

      + +
        +
      • Returns: <Object> An object containing commonly used constants for crypto and +security related operations. The specific constants currently defined are +described in Crypto constants.
      • +
      +

      crypto.DEFAULT_ENCODING#

      + +

      Stability: 0 - Deprecated

      +

      The default encoding to use for functions that can take either strings +or buffers. The default value is 'buffer', which makes methods +default to Buffer objects.

      +

      The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility +with legacy programs that expect 'latin1' to be the default encoding.

      +

      New applications should expect the default to be 'buffer'.

      +

      This property is deprecated.

      +

      crypto.fips#

      + +

      Stability: 0 - Deprecated

      +

      Property for checking and controlling whether a FIPS compliant crypto provider +is currently in use. Setting to true requires a FIPS build of Node.js.

      +

      This property is deprecated. Please use crypto.setFips() and +crypto.getFips() instead.

      +

      crypto.createCipher(algorithm, password[, options])#

      + +

      Stability: 0 - Deprecated: Use crypto.createCipheriv() instead.

      + +

      Creates and returns a Cipher object that uses the given algorithm and +password.

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength +option is not required but can be used to set the length of the authentication +tag that will be returned by getAuthTag() and defaults to 16 bytes.

      +

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On +recent OpenSSL releases, openssl list -cipher-algorithms +(openssl list-cipher-algorithms for older versions of OpenSSL) will +display the available cipher algorithms.

      +

      The password is used to derive the cipher key and initialization vector (IV). +The value must be either a 'latin1' encoded string, a Buffer, a +TypedArray, or a DataView.

      +

      The implementation of crypto.createCipher() derives keys using the OpenSSL +function EVP_BytesToKey with the digest algorithm set to MD5, one +iteration, and no salt. The lack of salt allows dictionary attacks as the same +password always creates the same key. The low iteration count and +non-cryptographically secure hash algorithm allow passwords to be tested very +rapidly.

      +

      In line with OpenSSL's recommendation to use a more modern algorithm instead of +EVP_BytesToKey it is recommended that developers derive a key and IV on +their own using crypto.scrypt() and to use crypto.createCipheriv() +to create the Cipher object. Users should not use ciphers with counter mode +(e.g. CTR, GCM, or CCM) in crypto.createCipher(). A warning is emitted when +they are used in order to avoid the risk of IV reuse that causes +vulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting +Adversaries for details.

      +

      crypto.createCipheriv(algorithm, key, iv[, options])#

      + + +

      Creates and returns a Cipher object, with the given algorithm, key and +initialization vector (iv).

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength +option is not required but can be used to set the length of the authentication +tag that will be returned by getAuthTag() and defaults to 16 bytes.

      +

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On +recent OpenSSL releases, openssl list -cipher-algorithms +(openssl list-cipher-algorithms for older versions of OpenSSL) will +display the available cipher algorithms.

      +

      The key is the raw key used by the algorithm and iv is an +initialization vector. Both arguments must be 'utf8' encoded strings, +Buffers, TypedArray, or DataViews. The key may optionally be +a KeyObject of type secret. If the cipher does not need +an initialization vector, iv may be null.

      +

      Initialization vectors should be unpredictable and unique; ideally, they will be +cryptographically random. They do not have to be secret: IVs are typically just +added to ciphertext messages unencrypted. It may sound contradictory that +something has to be unpredictable and unique, but does not have to be secret; +remember that an attacker must not be able to predict ahead of time what a +given IV will be.

      +

      crypto.createDecipher(algorithm, password[, options])#

      + +

      Stability: 0 - Deprecated: Use crypto.createDecipheriv() instead.

      + +

      Creates and returns a Decipher object that uses the given algorithm and +password (key).

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode.

      +

      The implementation of crypto.createDecipher() derives keys using the OpenSSL +function EVP_BytesToKey with the digest algorithm set to MD5, one +iteration, and no salt. The lack of salt allows dictionary attacks as the same +password always creates the same key. The low iteration count and +non-cryptographically secure hash algorithm allow passwords to be tested very +rapidly.

      +

      In line with OpenSSL's recommendation to use a more modern algorithm instead of +EVP_BytesToKey it is recommended that developers derive a key and IV on +their own using crypto.scrypt() and to use crypto.createDecipheriv() +to create the Decipher object.

      +

      crypto.createDecipheriv(algorithm, key, iv[, options])#

      + + +

      Creates and returns a Decipher object that uses the given algorithm, key +and initialization vector (iv).

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength +option is not required but can be used to restrict accepted authentication tags +to those with the specified length.

      +

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On +recent OpenSSL releases, openssl list -cipher-algorithms +(openssl list-cipher-algorithms for older versions of OpenSSL) will +display the available cipher algorithms.

      +

      The key is the raw key used by the algorithm and iv is an +initialization vector. Both arguments must be 'utf8' encoded strings, +Buffers, TypedArray, or DataViews. The key may optionally be +a KeyObject of type secret. If the cipher does not need +an initialization vector, iv may be null.

      +

      Initialization vectors should be unpredictable and unique; ideally, they will be +cryptographically random. They do not have to be secret: IVs are typically just +added to ciphertext messages unencrypted. It may sound contradictory that +something has to be unpredictable and unique, but does not have to be secret; +remember that an attacker must not be able to predict ahead of time what a given +IV will be.

      +

      crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])#

      + + +

      Creates a DiffieHellman key exchange object using the supplied prime and an +optional specific generator.

      +

      The generator argument can be a number, string, or Buffer. If +generator is not specified, the value 2 is used.

      +

      If primeEncoding is specified, prime is expected to be a string; otherwise +a Buffer, TypedArray, or DataView is expected.

      +

      If generatorEncoding is specified, generator is expected to be a string; +otherwise a number, Buffer, TypedArray, or DataView is expected.

      +

      crypto.createDiffieHellman(primeLength[, generator])#

      + + +

      Creates a DiffieHellman key exchange object and generates a prime of +primeLength bits using an optional specific numeric generator. +If generator is not specified, the value 2 is used.

      +

      crypto.createDiffieHellmanGroup(name)#

      + + +

      An alias for crypto.getDiffieHellman()

      +

      crypto.createECDH(curveName)#

      + + +

      Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a +predefined curve specified by the curveName string. Use +crypto.getCurves() to obtain a list of available curve names. On recent +OpenSSL releases, openssl ecparam -list_curves will also display the name +and description of each available elliptic curve.

      +

      crypto.createHash(algorithm[, options])#

      + + +

      Creates and returns a Hash object that can be used to generate hash digests +using the given algorithm. Optional options argument controls stream +behavior. For XOF hash functions such as 'shake256', the outputLength option +can be used to specify the desired output length in bytes.

      +

      The algorithm is dependent on the available algorithms supported by the +version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. +On recent releases of OpenSSL, openssl list -digest-algorithms +(openssl list-message-digest-algorithms for older versions of OpenSSL) will +display the available digest algorithms.

      +

      Example: generating the sha256 sum of a file

      +
      const filename = process.argv[2];
      +const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const hash = crypto.createHash('sha256');
      +
      +const input = fs.createReadStream(filename);
      +input.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = input.read();
      +  if (data)
      +    hash.update(data);
      +  else {
      +    console.log(`${hash.digest('hex')} ${filename}`);
      +  }
      +});
      +

      crypto.createHmac(algorithm, key[, options])#

      + + +

      Creates and returns an Hmac object that uses the given algorithm and key. +Optional options argument controls stream behavior.

      +

      The algorithm is dependent on the available algorithms supported by the +version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. +On recent releases of OpenSSL, openssl list -digest-algorithms +(openssl list-message-digest-algorithms for older versions of OpenSSL) will +display the available digest algorithms.

      +

      The key is the HMAC key used to generate the cryptographic HMAC hash. If it is +a KeyObject, its type must be secret.

      +

      Example: generating the sha256 HMAC of a file

      +
      const filename = process.argv[2];
      +const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +const input = fs.createReadStream(filename);
      +input.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = input.read();
      +  if (data)
      +    hmac.update(data);
      +  else {
      +    console.log(`${hmac.digest('hex')} ${filename}`);
      +  }
      +});
      +

      crypto.createPrivateKey(key)#

      + + +

      Creates and returns a new key object containing a private key. If key is a +string or Buffer, format is assumed to be 'pem'; otherwise, key +must be an object with the properties described above.

      +

      If the private key is encrypted, a passphrase must be specified. The length +of the passphrase is limited to 1024 bytes.

      +

      crypto.createPublicKey(key)#

      + + +

      Creates and returns a new key object containing a public key. If key is a +string or Buffer, format is assumed to be 'pem'; if key is a KeyObject +with type 'private', the public key is derived from the given private key; +otherwise, key must be an object with the properties described above.

      +

      If the format is 'pem', the 'key' may also be an X.509 certificate.

      +

      Because public keys can be derived from private keys, a private key may be +passed instead of a public key. In that case, this function behaves as if +crypto.createPrivateKey() had been called, except that the type of the +returned KeyObject will be 'public' and that the private key cannot be +extracted from the returned KeyObject. Similarly, if a KeyObject with type +'private' is given, a new KeyObject with type 'public' will be returned +and it will be impossible to extract the private key from the returned object.

      +

      crypto.createSecretKey(key)#

      + + +

      Creates and returns a new key object containing a secret key for symmetric +encryption or Hmac.

      +

      crypto.createSign(algorithm[, options])#

      + + +

      Creates and returns a Sign object that uses the given algorithm. Use +crypto.getHashes() to obtain the names of the available digest algorithms. +Optional options argument controls the stream.Writable behavior.

      +

      In some cases, a Sign instance can be created using the name of a signature +algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use +the corresponding digest algorithm. This does not work for all signature +algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest +algorithm names.

      +

      crypto.createVerify(algorithm[, options])#

      + + +

      Creates and returns a Verify object that uses the given algorithm. +Use crypto.getHashes() to obtain an array of names of the available +signing algorithms. Optional options argument controls the +stream.Writable behavior.

      +

      In some cases, a Verify instance can be created using the name of a signature +algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use +the corresponding digest algorithm. This does not work for all signature +algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest +algorithm names.

      +

      crypto.diffieHellman(options)#

      + + +

      Computes the Diffie-Hellman secret based on a privateKey and a publicKey. +Both keys must have the same asymmetricKeyType, which must be one of 'dh' +(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).

      +

      crypto.generateKeyPair(type, options, callback)#

      + + +

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported.

      +

      If a publicKeyEncoding or privateKeyEncoding was specified, this function +behaves as if keyObject.export() had been called on its result. Otherwise, +the respective part of the key is returned as a KeyObject.

      +

      It is recommended to encode public keys as 'spki' and private keys as +'pkcs8' with encryption for long-term storage:

      +
      const { generateKeyPair } = require('crypto');
      +generateKeyPair('rsa', {
      +  modulusLength: 4096,
      +  publicKeyEncoding: {
      +    type: 'spki',
      +    format: 'pem'
      +  },
      +  privateKeyEncoding: {
      +    type: 'pkcs8',
      +    format: 'pem',
      +    cipher: 'aes-256-cbc',
      +    passphrase: 'top secret'
      +  }
      +}, (err, publicKey, privateKey) => {
      +  // Handle errors and use the generated key pair.
      +});
      +

      On completion, callback will be called with err set to undefined and +publicKey / privateKey representing the generated key pair.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with publicKey and privateKey properties.

      +

      crypto.generateKeyPairSync(type, options)#

      + + +

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported.

      +

      If a publicKeyEncoding or privateKeyEncoding was specified, this function +behaves as if keyObject.export() had been called on its result. Otherwise, +the respective part of the key is returned as a KeyObject.

      +

      When encoding public keys, it is recommended to use 'spki'. When encoding +private keys, it is recommended to use 'pkcs8' with a strong passphrase, +and to keep the passphrase confidential.

      +
      const { generateKeyPairSync } = require('crypto');
      +const { publicKey, privateKey } = generateKeyPairSync('rsa', {
      +  modulusLength: 4096,
      +  publicKeyEncoding: {
      +    type: 'spki',
      +    format: 'pem'
      +  },
      +  privateKeyEncoding: {
      +    type: 'pkcs8',
      +    format: 'pem',
      +    cipher: 'aes-256-cbc',
      +    passphrase: 'top secret'
      +  }
      +});
      +

      The return value { publicKey, privateKey } represents the generated key pair. +When PEM encoding was selected, the respective key will be a string, otherwise +it will be a buffer containing the data encoded as DER.

      +

      crypto.getCiphers()#

      + +
        +
      • Returns: <string[]> An array with the names of the supported cipher +algorithms.
      • +
      +
      const ciphers = crypto.getCiphers();
      +console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
      +

      crypto.getCurves()#

      + +
        +
      • Returns: <string[]> An array with the names of the supported elliptic curves.
      • +
      +
      const curves = crypto.getCurves();
      +console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
      +

      crypto.getDiffieHellman(groupName)#

      + + +

      Creates a predefined DiffieHellmanGroup key exchange object. The +supported groups are: 'modp1', 'modp2', 'modp5' (defined in +RFC 2412, but see Caveats) and 'modp14', 'modp15', +'modp16', 'modp17', 'modp18' (defined in RFC 3526). The +returned object mimics the interface of objects created by +crypto.createDiffieHellman(), but will not allow changing +the keys (with diffieHellman.setPublicKey(), for example). The +advantage of using this method is that the parties do not have to +generate nor exchange a group modulus beforehand, saving both processor +and communication time.

      +

      Example (obtaining a shared secret):

      +
      const crypto = require('crypto');
      +const alice = crypto.getDiffieHellman('modp14');
      +const bob = crypto.getDiffieHellman('modp14');
      +
      +alice.generateKeys();
      +bob.generateKeys();
      +
      +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
      +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
      +
      +/* aliceSecret and bobSecret should be the same */
      +console.log(aliceSecret === bobSecret);
      +

      crypto.getFips()#

      + +
        +
      • Returns: <number> 1 if and only if a FIPS compliant crypto provider is +currently in use, 0 otherwise. A future semver-major release may change +the return type of this API to a <boolean>.
      • +
      +

      crypto.getHashes()#

      + +
        +
      • Returns: <string[]> An array of the names of the supported hash algorithms, +such as 'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.
      • +
      +
      const hashes = crypto.getHashes();
      +console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
      +

      crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)#

      + + +

      Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) +implementation. A selected HMAC digest algorithm specified by digest is +applied to derive a key of the requested byte length (keylen) from the +password, salt and iterations.

      +

      The supplied callback function is called with two arguments: err and +derivedKey. If an error occurs while deriving the key, err will be set; +otherwise err will be null. By default, the successfully generated +derivedKey will be passed to the callback as a Buffer. An error will be +thrown if any of the input arguments specify invalid values or types.

      +

      If digest is null, 'sha1' will be used. This behavior is deprecated, +please specify a digest explicitly.

      +

      The iterations argument must be a number set as high as possible. The +higher the number of iterations, the more secure the derived key will be, +but will take a longer amount of time to complete.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +
      const crypto = require('crypto');
      +crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
      +});
      +

      The crypto.DEFAULT_ENCODING property can be used to change the way the +derivedKey is passed to the callback. This property, however, has been +deprecated and use should be avoided.

      +
      const crypto = require('crypto');
      +crypto.DEFAULT_ENCODING = 'hex';
      +crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey);  // '3745e48...aa39b34'
      +});
      +

      An array of supported digest functions can be retrieved using +crypto.getHashes().

      +

      This API uses libuv's threadpool, which can have surprising and +negative performance implications for some applications; see the +UV_THREADPOOL_SIZE documentation for more information.

      +

      crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)#

      + + +

      Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) +implementation. A selected HMAC digest algorithm specified by digest is +applied to derive a key of the requested byte length (keylen) from the +password, salt and iterations.

      +

      If an error occurs an Error will be thrown, otherwise the derived key will be +returned as a Buffer.

      +

      If digest is null, 'sha1' will be used. This behavior is deprecated, +please specify a digest explicitly.

      +

      The iterations argument must be a number set as high as possible. The +higher the number of iterations, the more secure the derived key will be, +but will take a longer amount of time to complete.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +
      const crypto = require('crypto');
      +const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
      +console.log(key.toString('hex'));  // '3745e48...08d59ae'
      +

      The crypto.DEFAULT_ENCODING property may be used to change the way the +derivedKey is returned. This property, however, is deprecated and use +should be avoided.

      +
      const crypto = require('crypto');
      +crypto.DEFAULT_ENCODING = 'hex';
      +const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
      +console.log(key);  // '3745e48...aa39b34'
      +

      An array of supported digest functions can be retrieved using +crypto.getHashes().

      +

      crypto.privateDecrypt(privateKey, buffer)#

      + + +

      Decrypts buffer with privateKey. buffer was previously encrypted using +the corresponding public key, for example using crypto.publicEncrypt().

      +

      If privateKey is not a KeyObject, this function behaves as if +privateKey had been passed to crypto.createPrivateKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_OAEP_PADDING.

      +

      crypto.privateEncrypt(privateKey, buffer)#

      + + +

      Encrypts buffer with privateKey. The returned data can be decrypted using +the corresponding public key, for example using crypto.publicDecrypt().

      +

      If privateKey is not a KeyObject, this function behaves as if +privateKey had been passed to crypto.createPrivateKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_PADDING.

      +

      crypto.publicDecrypt(key, buffer)#

      + + +

      Decrypts buffer with key.buffer was previously encrypted using +the corresponding private key, for example using crypto.privateEncrypt().

      +

      If key is not a KeyObject, this function behaves as if +key had been passed to crypto.createPublicKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_PADDING.

      +

      Because RSA public keys can be derived from private keys, a private key may +be passed instead of a public key.

      +

      crypto.publicEncrypt(key, buffer)#

      + + +

      Encrypts the content of buffer with key and returns a new +Buffer with encrypted content. The returned data can be decrypted using +the corresponding private key, for example using crypto.privateDecrypt().

      +

      If key is not a KeyObject, this function behaves as if +key had been passed to crypto.createPublicKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_OAEP_PADDING.

      +

      Because RSA public keys can be derived from private keys, a private key may +be passed instead of a public key.

      +

      crypto.randomBytes(size[, callback])#

      + + +

      Generates cryptographically strong pseudo-random data. The size argument +is a number indicating the number of bytes to generate.

      +

      If a callback function is provided, the bytes are generated asynchronously +and the callback function is invoked with two arguments: err and buf. +If an error occurs, err will be an Error object; otherwise it is null. The +buf argument is a Buffer containing the generated bytes.

      +
      // Asynchronous
      +const crypto = require('crypto');
      +crypto.randomBytes(256, (err, buf) => {
      +  if (err) throw err;
      +  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
      +});
      +

      If the callback function is not provided, the random bytes are generated +synchronously and returned as a Buffer. An error will be thrown if +there is a problem generating the bytes.

      +
      // Synchronous
      +const buf = crypto.randomBytes(256);
      +console.log(
      +  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
      +

      The crypto.randomBytes() method will not complete until there is +sufficient entropy available. +This should normally never take longer than a few milliseconds. The only time +when generating the random bytes may conceivably block for a longer period of +time is right after boot, when the whole system is still low on entropy.

      +

      This API uses libuv's threadpool, which can have surprising and +negative performance implications for some applications; see the +UV_THREADPOOL_SIZE documentation for more information.

      +

      The asynchronous version of crypto.randomBytes() is carried out in a single +threadpool request. To minimize threadpool task length variation, partition +large randomBytes requests when doing so as part of fulfilling a client +request.

      +

      crypto.randomFillSync(buffer[, offset][, size])#

      + + +

      Synchronous version of crypto.randomFill().

      +
      const buf = Buffer.alloc(10);
      +console.log(crypto.randomFillSync(buf).toString('hex'));
      +
      +crypto.randomFillSync(buf, 5);
      +console.log(buf.toString('hex'));
      +
      +// The above is equivalent to the following:
      +crypto.randomFillSync(buf, 5, 5);
      +console.log(buf.toString('hex'));
      +

      Any TypedArray or DataView instance may be passed as buffer.

      +
      const a = new Uint32Array(10);
      +console.log(Buffer.from(crypto.randomFillSync(a).buffer,
      +                        a.byteOffset, a.byteLength).toString('hex'));
      +
      +const b = new Float64Array(10);
      +console.log(Buffer.from(crypto.randomFillSync(b).buffer,
      +                        b.byteOffset, b.byteLength).toString('hex'));
      +
      +const c = new DataView(new ArrayBuffer(10));
      +console.log(Buffer.from(crypto.randomFillSync(c).buffer,
      +                        c.byteOffset, c.byteLength).toString('hex'));
      +

      crypto.randomFill(buffer[, offset][, size], callback)#

      + + +

      This function is similar to crypto.randomBytes() but requires the first +argument to be a Buffer that will be filled. It also +requires that a callback is passed in.

      +

      If the callback function is not provided, an error will be thrown.

      +
      const buf = Buffer.alloc(10);
      +crypto.randomFill(buf, (err, buf) => {
      +  if (err) throw err;
      +  console.log(buf.toString('hex'));
      +});
      +
      +crypto.randomFill(buf, 5, (err, buf) => {
      +  if (err) throw err;
      +  console.log(buf.toString('hex'));
      +});
      +
      +// The above is equivalent to the following:
      +crypto.randomFill(buf, 5, 5, (err, buf) => {
      +  if (err) throw err;
      +  console.log(buf.toString('hex'));
      +});
      +

      Any TypedArray or DataView instance may be passed as buffer.

      +
      const a = new Uint32Array(10);
      +crypto.randomFill(a, (err, buf) => {
      +  if (err) throw err;
      +  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
      +    .toString('hex'));
      +});
      +
      +const b = new Float64Array(10);
      +crypto.randomFill(b, (err, buf) => {
      +  if (err) throw err;
      +  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
      +    .toString('hex'));
      +});
      +
      +const c = new DataView(new ArrayBuffer(10));
      +crypto.randomFill(c, (err, buf) => {
      +  if (err) throw err;
      +  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
      +    .toString('hex'));
      +});
      +

      This API uses libuv's threadpool, which can have surprising and +negative performance implications for some applications; see the +UV_THREADPOOL_SIZE documentation for more information.

      +

      The asynchronous version of crypto.randomFill() is carried out in a single +threadpool request. To minimize threadpool task length variation, partition +large randomFill requests when doing so as part of fulfilling a client +request.

      +

      crypto.randomInt([min, ]max[, callback])#

      + +
        +
      • min <integer> Start of random range (inclusive). Default: 0.
      • +
      • max <integer> End of random range (exclusive).
      • +
      • callback <Function> function(err, n) {}.
      • +
      +

      Return a random integer n such that min <= n < max. This +implementation avoids modulo bias.

      +

      The range (max - min) must be less than 248. min and max must +be safe integers.

      +

      If the callback function is not provided, the random integer is +generated synchronously.

      +
      // Asynchronous
      +crypto.randomInt(3, (err, n) => {
      +  if (err) throw err;
      +  console.log(`Random number chosen from (0, 1, 2): ${n}`);
      +});
      +
      // Synchronous
      +const n = crypto.randomInt(3);
      +console.log(`Random number chosen from (0, 1, 2): ${n}`);
      +
      // With `min` argument
      +const n = crypto.randomInt(1, 7);
      +console.log(`The dice rolled: ${n}`);
      +

      crypto.scrypt(password, salt, keylen[, options], callback)#

      + + +

      Provides an asynchronous scrypt implementation. Scrypt is a password-based +key derivation function that is designed to be expensive computationally and +memory-wise in order to make brute-force attacks unrewarding.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +

      The callback function is called with two arguments: err and derivedKey. +err is an exception object when key derivation fails, otherwise err is +null. derivedKey is passed to the callback as a Buffer.

      +

      An exception is thrown when any of the input arguments specify invalid values +or types.

      +
      const crypto = require('crypto');
      +// Using the factory defaults.
      +crypto.scrypt('secret', 'salt', 64, (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
      +});
      +// Using a custom N parameter. Must be a power of two.
      +crypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
      +});
      +

      crypto.scryptSync(password, salt, keylen[, options])#

      + + +

      Provides a synchronous scrypt implementation. Scrypt is a password-based +key derivation function that is designed to be expensive computationally and +memory-wise in order to make brute-force attacks unrewarding.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +

      An exception is thrown when key derivation fails, otherwise the derived key is +returned as a Buffer.

      +

      An exception is thrown when any of the input arguments specify invalid values +or types.

      +
      const crypto = require('crypto');
      +// Using the factory defaults.
      +const key1 = crypto.scryptSync('secret', 'salt', 64);
      +console.log(key1.toString('hex'));  // '3745e48...08d59ae'
      +// Using a custom N parameter. Must be a power of two.
      +const key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 });
      +console.log(key2.toString('hex'));  // '3745e48...aa39b34'
      +

      crypto.setEngine(engine[, flags])#

      + + +

      Load and set the engine for some or all OpenSSL functions (selected by flags).

      +

      engine could be either an id or a path to the engine's shared library.

      +

      The optional flags argument uses ENGINE_METHOD_ALL by default. The flags +is a bit field taking one of or a mix of the following flags (defined in +crypto.constants):

      +
        +
      • crypto.constants.ENGINE_METHOD_RSA
      • +
      • crypto.constants.ENGINE_METHOD_DSA
      • +
      • crypto.constants.ENGINE_METHOD_DH
      • +
      • crypto.constants.ENGINE_METHOD_RAND
      • +
      • crypto.constants.ENGINE_METHOD_EC
      • +
      • crypto.constants.ENGINE_METHOD_CIPHERS
      • +
      • crypto.constants.ENGINE_METHOD_DIGESTS
      • +
      • crypto.constants.ENGINE_METHOD_PKEY_METHS
      • +
      • crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
      • +
      • crypto.constants.ENGINE_METHOD_ALL
      • +
      • crypto.constants.ENGINE_METHOD_NONE
      • +
      +

      The flags below are deprecated in OpenSSL-1.1.0.

      +
        +
      • crypto.constants.ENGINE_METHOD_ECDH
      • +
      • crypto.constants.ENGINE_METHOD_ECDSA
      • +
      • crypto.constants.ENGINE_METHOD_STORE
      • +
      +

      crypto.setFips(bool)#

      + + +

      Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. +Throws an error if FIPS mode is not available.

      +

      crypto.sign(algorithm, data, key)#

      + + +

      Calculates and returns the signature for data using the given private key and +algorithm. If algorithm is null or undefined, then the algorithm is +dependent upon the key type (especially Ed25519 and Ed448).

      +

      If key is not a KeyObject, this function behaves as if key had been +passed to crypto.createPrivateKey(). If it is an object, the following +additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to sign the message as specified in section 3.1 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the +maximum permissible value.

        +
      • +
      +

      crypto.timingSafeEqual(a, b)#

      + + +

      This function is based on a constant-time algorithm. +Returns true if a is equal to b, without leaking timing information that +would allow an attacker to guess one of the values. This is suitable for +comparing HMAC digests or secret values like authentication cookies or +capability urls.

      +

      a and b must both be Buffers, TypedArrays, or DataViews, and they +must have the same length.

      +

      Use of crypto.timingSafeEqual does not guarantee that the surrounding code +is timing-safe. Care should be taken to ensure that the surrounding code does +not introduce timing vulnerabilities.

      +

      crypto.verify(algorithm, data, key, signature)#

      + + +

      Verifies the given signature for data using the given key and algorithm. If +algorithm is null or undefined, then the algorithm is dependent upon the +key type (especially Ed25519 and Ed448).

      +

      If key is not a KeyObject, this function behaves as if key had been +passed to crypto.createPublicKey(). If it is an object, the following +additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to sign the message as specified in section 3.1 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the +maximum permissible value.

        +
      • +
      +

      The signature argument is the previously calculated signature for the data.

      +

      Because public keys can be derived from private keys, a private key or a public +key may be passed for key.

      +

      Notes#

      +

      Legacy Streams API (prior to Node.js 0.10)#

      +

      The Crypto module was added to Node.js before there was the concept of a +unified Stream API, and before there were Buffer objects for handling +binary data. As such, the many of the crypto defined classes have methods not +typically found on other Node.js classes that implement the streams +API (e.g. update(), final(), or digest()). Also, many methods accepted +and returned 'latin1' encoded strings by default rather than Buffers. This +default was changed after Node.js v0.8 to use Buffer objects by default +instead.

      +

      Recent ECDH changes#

      +

      Usage of ECDH with non-dynamically generated key pairs has been simplified. +Now, ecdh.setPrivateKey() can be called with a preselected private key +and the associated public point (key) will be computed and stored in the object. +This allows code to only store and provide the private part of the EC key pair. +ecdh.setPrivateKey() now also validates that the private key is valid for +the selected curve.

      +

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the +API is not useful. Either a previously stored private key should be set, which +automatically generates the associated public key, or ecdh.generateKeys() +should be called. The main drawback of using ecdh.setPublicKey() is that +it can be used to put the ECDH key pair into an inconsistent state.

      +

      Support for weak or compromised algorithms#

      +

      The crypto module still supports some algorithms which are already +compromised and are not currently recommended for use. The API also allows +the use of ciphers and hashes with a small key size that are too weak for safe +use.

      +

      Users should take full responsibility for selecting the crypto +algorithm and key size according to their security requirements.

      +

      Based on the recommendations of NIST SP 800-131A:

      +
        +
      • MD5 and SHA-1 are no longer acceptable where collision resistance is +required such as digital signatures.
      • +
      • The key used with RSA, DSA, and DH algorithms is recommended to have +at least 2048 bits and that of the curve of ECDSA and ECDH at least +224 bits, to be safe to use for several years.
      • +
      • The DH groups of modp1, modp2 and modp5 have a key size +smaller than 2048 bits and are not recommended.
      • +
      +

      See the reference for other recommendations and details.

      +

      CCM mode#

      +

      CCM is one of the supported AEAD algorithms. Applications which use this +mode must adhere to certain restrictions when using the cipher API:

      +
        +
      • The authentication tag length must be specified during cipher creation by +setting the authTagLength option and must be one of 4, 6, 8, 10, 12, 14 or +16 bytes.
      • +
      • The length of the initialization vector (nonce) N must be between 7 and 13 +bytes (7 ≤ N ≤ 13).
      • +
      • The length of the plaintext is limited to 2 ** (8 * (15 - N)) bytes.
      • +
      • When decrypting, the authentication tag must be set via setAuthTag() before +calling update(). +Otherwise, decryption will fail and final() will throw an error in +compliance with section 2.6 of RFC 3610.
      • +
      • Using stream methods such as write(data), end(data) or pipe() in CCM +mode might fail as CCM cannot handle more than one chunk of data per instance.
      • +
      • When passing additional authenticated data (AAD), the length of the actual +message in bytes must be passed to setAAD() via the plaintextLength +option. +Many crypto libraries include the authentication tag in the ciphertext, +which means that they produce ciphertexts of the length +plaintextLength + authTagLength. Node.js does not include the authentication +tag, so the ciphertext length is always plaintextLength. +This is not necessary if no AAD is used.
      • +
      • As CCM processes the whole message at once, update() can only be called +once.
      • +
      • Even though calling update() is sufficient to encrypt/decrypt the message, +applications must call final() to compute or verify the +authentication tag.
      • +
      +
      const crypto = require('crypto');
      +
      +const key = 'keykeykeykeykeykeykeykey';
      +const nonce = crypto.randomBytes(12);
      +
      +const aad = Buffer.from('0123456789', 'hex');
      +
      +const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {
      +  authTagLength: 16
      +});
      +const plaintext = 'Hello world';
      +cipher.setAAD(aad, {
      +  plaintextLength: Buffer.byteLength(plaintext)
      +});
      +const ciphertext = cipher.update(plaintext, 'utf8');
      +cipher.final();
      +const tag = cipher.getAuthTag();
      +
      +// Now transmit { ciphertext, nonce, tag }.
      +
      +const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {
      +  authTagLength: 16
      +});
      +decipher.setAuthTag(tag);
      +decipher.setAAD(aad, {
      +  plaintextLength: ciphertext.length
      +});
      +const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
      +
      +try {
      +  decipher.final();
      +} catch (err) {
      +  console.error('Authentication failed!');
      +  return;
      +}
      +
      +console.log(receivedPlaintext);
      +

      Crypto constants#

      +

      The following constants exported by crypto.constants apply to various uses of +the crypto, tls, and https modules and are generally specific to OpenSSL.

      +

      OpenSSL options#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. See + https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html + for detail.
      SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode + for TLS v1.3
      SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched + clients or servers. See + https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CIPHER_SERVER_PREFERENCEAttempts to use the server's preferences instead of the client's when + selecting a cipher. Behavior depends on protocol version. See + https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER.
      SSL_OP_COOKIE_EXCHANGEInstructs OpenSSL to turn on cookie exchange.
      SSL_OP_CRYPTOPRO_TLSEXT_BUGInstructs OpenSSL to add server-hello extension from an early version + of the cryptopro draft.
      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability + workaround added in OpenSSL 0.9.6d.
      SSL_OP_EPHEMERAL_RSAInstructs OpenSSL to always use the tmp_rsa key when performing RSA + operations.
      SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
      SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
      SSL_OP_MICROSOFT_SESS_ID_BUG
      SSL_OP_MSIE_SSLV2_RSA_PADDINGInstructs OpenSSL to disable the workaround for a man-in-the-middle + protocol-version vulnerability in the SSL 2.0 server implementation.
      SSL_OP_NETSCAPE_CA_DN_BUG
      SSL_OP_NETSCAPE_CHALLENGE_BUG
      SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
      SSL_OP_NO_COMPRESSIONInstructs OpenSSL to disable support for SSL/TLS compression.
      SSL_OP_NO_ENCRYPT_THEN_MACInstructs OpenSSL to disable encrypt-then-MAC.
      SSL_OP_NO_QUERY_MTU
      SSL_OP_NO_RENEGOTIATIONInstructs OpenSSL to disable renegotiation.
      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATIONInstructs OpenSSL to always start a new session when performing + renegotiation.
      SSL_OP_NO_SSLv2Instructs OpenSSL to turn off SSL v2
      SSL_OP_NO_SSLv3Instructs OpenSSL to turn off SSL v3
      SSL_OP_NO_TICKETInstructs OpenSSL to disable use of RFC4507bis tickets.
      SSL_OP_NO_TLSv1Instructs OpenSSL to turn off TLS v1
      SSL_OP_NO_TLSv1_1Instructs OpenSSL to turn off TLS v1.1
      SSL_OP_NO_TLSv1_2Instructs OpenSSL to turn off TLS v1.2
      SSL_OP_NO_TLSv1_3Instructs OpenSSL to turn off TLS v1.3
      SSL_OP_PKCS1_CHECK_1
      SSL_OP_PKCS1_CHECK_2
      SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20Poly1305 + when client does. + This option has no effect if + SSL_OP_CIPHER_SERVER_PREFERENCE + is not enabled.
      SSL_OP_SINGLE_DH_USEInstructs OpenSSL to always create a new key when using + temporary/ephemeral DH parameters.
      SSL_OP_SINGLE_ECDH_USEInstructs OpenSSL to always create a new key when using + temporary/ephemeral ECDH parameters.
      SSL_OP_SSLEAY_080_CLIENT_DH_BUG
      SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
      SSL_OP_TLS_BLOCK_PADDING_BUG
      SSL_OP_TLS_D5_BUG
      SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.
      +

      OpenSSL engine constants#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      ENGINE_METHOD_RSALimit engine usage to RSA
      ENGINE_METHOD_DSALimit engine usage to DSA
      ENGINE_METHOD_DHLimit engine usage to DH
      ENGINE_METHOD_RANDLimit engine usage to RAND
      ENGINE_METHOD_ECLimit engine usage to EC
      ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
      ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
      ENGINE_METHOD_PKEY_METHSLimit engine usage to PKEY_METHDS
      ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
      ENGINE_METHOD_ALL
      ENGINE_METHOD_NONE
      +

      Other OpenSSL constants#

      +

      See the list of SSL OP Flags for details.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      DH_CHECK_P_NOT_SAFE_PRIME
      DH_CHECK_P_NOT_PRIME
      DH_UNABLE_TO_CHECK_GENERATOR
      DH_NOT_SUITABLE_GENERATOR
      ALPN_ENABLED
      RSA_PKCS1_PADDING
      RSA_SSLV23_PADDING
      RSA_NO_PADDING
      RSA_PKCS1_OAEP_PADDING
      RSA_X931_PADDING
      RSA_PKCS1_PSS_PADDING
      RSA_PSS_SALTLEN_DIGESTSets the salt length for RSA_PKCS1_PSS_PADDING to the + digest size when signing or verifying.
      RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the + maximum permissible value when signing data.
      RSA_PSS_SALTLEN_AUTOCauses the salt length for RSA_PKCS1_PSS_PADDING to be + determined automatically when verifying a signature.
      POINT_CONVERSION_COMPRESSED
      POINT_CONVERSION_UNCOMPRESSED
      POINT_CONVERSION_HYBRID
      +

      Node.js crypto constants#

      + + + + + + + + + + + + + +
      ConstantDescription
      defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
      defaultCipherListSpecifies the active default cipher list used by the current Node.js + process.
      +

      Debugger#

      + +

      Stability: 2 - Stable

      + +

      Node.js includes an out-of-process debugging utility accessible via a +V8 Inspector and built-in debugging client. To use it, start Node.js +with the inspect argument followed by the path to the script to debug; a +prompt will be displayed indicating successful launch of the debugger:

      +
      $ node inspect myscript.js
      +< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
      +< For help, see: https://nodejs.org/en/docs/inspector
      +< Debugger attached.
      +Break on start in myscript.js:1
      +> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
      +  2 setTimeout(() => {
      +  3   console.log('world');
      +debug>
      +

      The Node.js debugger client is not a full-featured debugger, but simple step and +inspection are possible.

      +

      Inserting the statement debugger; into the source code of a script will +enable a breakpoint at that position in the code:

      + +
      // myscript.js
      +global.x = 5;
      +setTimeout(() => {
      +  debugger;
      +  console.log('world');
      +}, 1000);
      +console.log('hello');
      +

      Once the debugger is run, a breakpoint will occur at line 3:

      +
      $ node inspect myscript.js
      +< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
      +< For help, see: https://nodejs.org/en/docs/inspector
      +< Debugger attached.
      +Break on start in myscript.js:1
      +> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
      +  2 setTimeout(() => {
      +  3   debugger;
      +debug> cont
      +< hello
      +break in myscript.js:3
      +  1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
      +  2 setTimeout(() => {
      +> 3   debugger;
      +  4   console.log('world');
      +  5 }, 1000);
      +debug> next
      +break in myscript.js:4
      +  2 setTimeout(() => {
      +  3   debugger;
      +> 4   console.log('world');
      +  5 }, 1000);
      +  6 console.log('hello');
      +debug> repl
      +Press Ctrl + C to leave debug repl
      +> x
      +5
      +> 2 + 2
      +4
      +debug> next
      +< world
      +break in myscript.js:5
      +  3   debugger;
      +  4   console.log('world');
      +> 5 }, 1000);
      +  6 console.log('hello');
      +  7
      +debug> .exit
      +

      The repl command allows code to be evaluated remotely. The next command +steps to the next line. Type help to see what other commands are available.

      +

      Pressing enter without typing a command will repeat the previous debugger +command.

      +

      Watchers#

      +

      It is possible to watch expression and variable values while debugging. On +every breakpoint, each expression from the watchers list will be evaluated +in the current context and displayed immediately before the breakpoint's +source code listing.

      +

      To begin watching an expression, type watch('my_expression'). The command +watchers will print the active watchers. To remove a watcher, type +unwatch('my_expression').

      +

      Command reference#

      +

      Stepping#

      +
        +
      • cont, c: Continue execution
      • +
      • next, n: Step next
      • +
      • step, s: Step in
      • +
      • out, o: Step out
      • +
      • pause: Pause running code (like pause button in Developer Tools)
      • +
      +

      Breakpoints#

      +
        +
      • setBreakpoint(), sb(): Set breakpoint on current line
      • +
      • setBreakpoint(line), sb(line): Set breakpoint on specific line
      • +
      • setBreakpoint('fn()'), sb(...): Set breakpoint on a first statement in +functions body
      • +
      • setBreakpoint('script.js', 1), sb(...): Set breakpoint on first line of +script.js
      • +
      • clearBreakpoint('script.js', 1), cb(...): Clear breakpoint in script.js +on line 1
      • +
      +

      It is also possible to set a breakpoint in a file (module) that +is not loaded yet:

      +
      $ node inspect main.js
      +< Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd
      +< For help, see: https://nodejs.org/en/docs/inspector
      +< Debugger attached.
      +Break on start in main.js:1
      +> 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js');
      +  2 mod.hello();
      +  3 mod.hello();
      +debug> setBreakpoint('mod.js', 22)
      +Warning: script 'mod.js' was not loaded yet.
      +debug> c
      +break in mod.js:22
      + 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
      + 21
      +>22 exports.hello = function() {
      + 23   return 'hello from module';
      + 24 };
      +debug>
      +

      Information#

      +
        +
      • backtrace, bt: Print backtrace of current execution frame
      • +
      • list(5): List scripts source code with 5 line context (5 lines before and +after)
      • +
      • watch(expr): Add expression to watch list
      • +
      • unwatch(expr): Remove expression from watch list
      • +
      • watchers: List all watchers and their values (automatically listed on each +breakpoint)
      • +
      • repl: Open debugger's repl for evaluation in debugging script's context
      • +
      • exec expr: Execute an expression in debugging script's context
      • +
      +

      Execution control#

      +
        +
      • run: Run script (automatically runs on debugger's start)
      • +
      • restart: Restart script
      • +
      • kill: Kill script
      • +
      +

      Various#

      +
        +
      • scripts: List all loaded scripts
      • +
      • version: Display V8's version
      • +
      +

      Advanced usage#

      +

      V8 inspector integration for Node.js#

      +

      V8 Inspector integration allows attaching Chrome DevTools to Node.js +instances for debugging and profiling. It uses the +Chrome DevTools Protocol.

      +

      V8 Inspector can be enabled by passing the --inspect flag when starting a +Node.js application. It is also possible to supply a custom port with that flag, +e.g. --inspect=9222 will accept DevTools connections on port 9222.

      +

      To break on the first line of the application code, pass the --inspect-brk +flag instead of --inspect.

      +
      $ node --inspect index.js
      +Debugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
      +For help, see: https://nodejs.org/en/docs/inspector
      +

      (In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29 +at the end of the URL is generated on the fly, it varies in different +debugging sessions.)

      +

      If the Chrome browser is older than 66.0.3345.0, +use inspector.html instead of js_app.html in the above URL.

      +

      Chrome DevTools doesn't support debugging worker threads yet. +ndb can be used to debug them.

      +

      Deprecated APIs#

      + + +

      Node.js may deprecate APIs for any of the following reasons:

      +
        +
      • Use of the API is unsafe.
      • +
      • An improved alternative API is available.
      • +
      • Breaking changes to the API are expected in a future major release.
      • +
      +

      Node.js utilizes three kinds of Deprecations:

      +
        +
      • Documentation-only
      • +
      • Runtime
      • +
      • End-of-Life
      • +
      +

      A Documentation-only deprecation is one that is expressed only within the +Node.js API docs. These generate no side-effects while running Node.js. +Some Documentation-only deprecations trigger a runtime warning when launched +with --pending-deprecation flag (or its alternative, +NODE_PENDING_DEPRECATION=1 environment variable), similarly to Runtime +deprecations below. Documentation-only deprecations that support that flag +are explicitly labeled as such in the +list of Deprecated APIs.

      +

      A Runtime deprecation will, by default, generate a process warning that will +be printed to stderr the first time the deprecated API is used. When the +--throw-deprecation command-line flag is used, a Runtime deprecation will +cause an error to be thrown.

      +

      An End-of-Life deprecation is used when functionality is or will soon be removed +from Node.js.

      +

      Revoking deprecations#

      +

      Occasionally, the deprecation of an API may be reversed. In such situations, +this document will be updated with information relevant to the decision. +However, the deprecation identifier will not be modified.

      +

      List of deprecated APIs#

      +

      +

      DEP0001: http.OutgoingMessage.prototype.flush#

      + +

      Type: Runtime

      +

      The OutgoingMessage.prototype.flush() method is deprecated. Use +OutgoingMessage.prototype.flushHeaders() instead.

      +

      +

      DEP0002: require('_linklist')#

      + +

      Type: End-of-Life

      +

      The _linklist module is deprecated. Please use a userland alternative.

      +

      +

      DEP0003: _writableState.buffer#

      + +

      Type: Runtime

      +

      The _writableState.buffer property is deprecated. Use the +_writableState.getBuffer() method instead.

      +

      +

      DEP0004: CryptoStream.prototype.readyState#

      + +

      Type: End-of-Life

      +

      The CryptoStream.prototype.readyState property was removed.

      +

      +

      DEP0005: Buffer() constructor#

      + +

      Type: Runtime (supports --pending-deprecation)

      +

      The Buffer() function and new Buffer() constructor are deprecated due to +API usability issues that can lead to accidental security issues.

      +

      As an alternative, use one of the following methods of constructing Buffer +objects:

      + +

      Without --pending-deprecation, runtime warnings occur only for code not in +node_modules. This means there will not be deprecation warnings for +Buffer() usage in dependencies. With --pending-deprecation, a runtime +warning results no matter where the Buffer() usage occurs.

      +

      +

      DEP0006: child_process options.customFds#

      + +

      Type: End-of-Life

      +

      Within the child_process module's spawn(), fork(), and exec() +methods, the options.customFds option is deprecated. The options.stdio +option should be used instead.

      +

      +

      DEP0007: Replace cluster worker.suicide with worker.exitedAfterDisconnect#

      + +

      Type: End-of-Life

      +

      In an earlier version of the Node.js cluster, a boolean property with the name +suicide was added to the Worker object. The intent of this property was to +provide an indication of how and why the Worker instance exited. In Node.js +6.0.0, the old property was deprecated and replaced with a new +worker.exitedAfterDisconnect property. The old property name did not +precisely describe the actual semantics and was unnecessarily emotion-laden.

      +

      +

      DEP0008: require('constants')#

      + +

      Type: Documentation-only

      +

      The constants module is deprecated. When requiring access to constants +relevant to specific Node.js builtin modules, developers should instead refer +to the constants property exposed by the relevant module. For instance, +require('fs').constants and require('os').constants.

      +

      +

      DEP0009: crypto.pbkdf2 without digest#

      + +

      Type: Runtime

      +

      Use of the crypto.pbkdf2() API without specifying a digest was deprecated +in Node.js 6.0 because the method defaulted to using the non-recommended +'SHA1' digest. Previously, a deprecation warning was printed. Starting in +Node.js 8.0.0, calling crypto.pbkdf2() or crypto.pbkdf2Sync() with +digest set to undefined will throw a TypeError.

      +

      Beginning in Node.js v11.0.0, calling these functions with digest set to +null will print a deprecation warning to align with the behavior when digest +is undefined.

      +

      +

      DEP0010: crypto.createCredentials#

      + +

      Type: End-of-Life

      +

      The crypto.createCredentials() API was removed. Please use +tls.createSecureContext() instead.

      +

      +

      DEP0011: crypto.Credentials#

      + +

      Type: End-of-Life

      +

      The crypto.Credentials class was removed. Please use tls.SecureContext +instead.

      +

      +

      DEP0012: Domain.dispose#

      + +

      Type: End-of-Life

      +

      Domain.dispose() has been removed. Recover from failed I/O actions +explicitly via error event handlers set on the domain instead.

      +

      +

      DEP0013: fs asynchronous function without callback#

      + +

      Type: End-of-Life

      +

      Calling an asynchronous function without a callback throws a TypeError +in Node.js 10.0.0 onwards. See https://github.com/nodejs/node/pull/12562.

      +

      +

      DEP0014: fs.read legacy String interface#

      + +

      Type: End-of-Life

      +

      The fs.read() legacy String interface is deprecated. Use the Buffer +API as mentioned in the documentation instead.

      +

      +

      DEP0015: fs.readSync legacy String interface#

      + +

      Type: End-of-Life

      +

      The fs.readSync() legacy String interface is deprecated. Use the +Buffer API as mentioned in the documentation instead.

      +

      +

      DEP0016: GLOBAL/root#

      + +

      Type: Runtime

      +

      The GLOBAL and root aliases for the global property are deprecated +and should no longer be used.

      +

      +

      DEP0017: Intl.v8BreakIterator#

      + +

      Type: End-of-Life

      +

      Intl.v8BreakIterator was a non-standard extension and has been removed. +See Intl.Segmenter.

      +

      +

      DEP0018: Unhandled promise rejections#

      + +

      Type: Runtime

      +

      Unhandled promise rejections are deprecated. In the future, promise rejections +that are not handled will terminate the Node.js process with a non-zero exit +code.

      +

      +

      DEP0019: require('.') resolved outside directory#

      + +

      Type: End-of-Life

      +

      In certain cases, require('.') could resolve outside the package directory. +This behavior has been removed.

      +

      +

      DEP0020: Server.connections#

      + +

      Type: Runtime

      +

      The Server.connections property is deprecated. Please use the +Server.getConnections() method instead.

      +

      +

      DEP0021: Server.listenFD#

      + +

      Type: End-of-Life

      +

      The Server.listenFD() method was deprecated and removed. Please use +Server.listen({fd: <number>}) instead.

      +

      +

      DEP0022: os.tmpDir()#

      + +

      Type: Runtime

      +

      The os.tmpDir() API is deprecated. Please use os.tmpdir() instead.

      +

      +

      DEP0023: os.getNetworkInterfaces()#

      + +

      Type: End-of-Life

      +

      The os.getNetworkInterfaces() method is deprecated. Please use the +os.networkInterfaces() method instead.

      +

      +

      DEP0024: REPLServer.prototype.convertToContext()#

      + +

      Type: End-of-Life

      +

      The REPLServer.prototype.convertToContext() API has been removed.

      +

      +

      DEP0025: require('sys')#

      + +

      Type: Runtime

      +

      The sys module is deprecated. Please use the util module instead.

      +

      +

      DEP0026: util.print()#

      + +

      Type: End-of-Life

      +

      util.print() has been removed. Please use console.log() instead.

      +

      +

      DEP0027: util.puts()#

      + +

      Type: End-of-Life

      +

      util.puts() has been removed. Please use console.log() instead.

      +

      +

      DEP0028: util.debug()#

      + +

      Type: End-of-Life

      +

      util.debug() has been removed. Please use console.error() instead.

      +

      +

      DEP0029: util.error()#

      + +

      Type: End-of-Life

      +

      util.error() has been removed. Please use console.error() instead.

      +

      +

      DEP0030: SlowBuffer#

      + +

      Type: Documentation-only

      +

      The SlowBuffer class is deprecated. Please use +Buffer.allocUnsafeSlow(size) instead.

      +

      +

      DEP0031: ecdh.setPublicKey()#

      + +

      Type: Documentation-only

      +

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the +API is not useful.

      +

      +

      DEP0032: domain module#

      + +

      Type: Documentation-only

      +

      The domain module is deprecated and should not be used.

      +

      +

      DEP0033: EventEmitter.listenerCount()#

      + +

      Type: Documentation-only

      +

      The EventEmitter.listenerCount(emitter, eventName) API is +deprecated. Please use emitter.listenerCount(eventName) instead.

      +

      +

      DEP0034: fs.exists(path, callback)#

      + +

      Type: Documentation-only

      +

      The fs.exists(path, callback) API is deprecated. Please use +fs.stat() or fs.access() instead.

      +

      +

      DEP0035: fs.lchmod(path, mode, callback)#

      + +

      Type: Documentation-only

      +

      The fs.lchmod(path, mode, callback) API is deprecated.

      +

      +

      DEP0036: fs.lchmodSync(path, mode)#

      + +

      Type: Documentation-only

      +

      The fs.lchmodSync(path, mode) API is deprecated.

      +

      +

      DEP0037: fs.lchown(path, uid, gid, callback)#

      + +

      Type: Deprecation revoked

      +

      The fs.lchown(path, uid, gid, callback) API was deprecated. The +deprecation was revoked because the requisite supporting APIs were added in +libuv.

      +

      +

      DEP0038: fs.lchownSync(path, uid, gid)#

      + +

      Type: Deprecation revoked

      +

      The fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was +revoked because the requisite supporting APIs were added in libuv.

      +

      +

      DEP0039: require.extensions#

      + +

      Type: Documentation-only

      +

      The require.extensions property is deprecated.

      +

      +

      DEP0040: punycode module#

      + +

      Type: Documentation-only

      +

      The punycode module is deprecated. Please use a userland alternative +instead.

      +

      +

      DEP0041: NODE_REPL_HISTORY_FILE environment variable#

      + +

      Type: End-of-Life

      +

      The NODE_REPL_HISTORY_FILE environment variable was removed. Please use +NODE_REPL_HISTORY instead.

      +

      +

      DEP0042: tls.CryptoStream#

      + +

      Type: End-of-Life

      +

      The tls.CryptoStream class was removed. Please use +tls.TLSSocket instead.

      +

      +

      DEP0043: tls.SecurePair#

      + +

      Type: Documentation-only

      +

      The tls.SecurePair class is deprecated. Please use +tls.TLSSocket instead.

      +

      +

      DEP0044: util.isArray()#

      + +

      Type: Documentation-only

      +

      The util.isArray() API is deprecated. Please use Array.isArray() +instead.

      +

      +

      DEP0045: util.isBoolean()#

      + +

      Type: Documentation-only

      +

      The util.isBoolean() API is deprecated.

      +

      +

      DEP0046: util.isBuffer()#

      + +

      Type: Documentation-only

      +

      The util.isBuffer() API is deprecated. Please use +Buffer.isBuffer() instead.

      +

      +

      DEP0047: util.isDate()#

      + +

      Type: Documentation-only

      +

      The util.isDate() API is deprecated.

      +

      +

      DEP0048: util.isError()#

      + +

      Type: Documentation-only

      +

      The util.isError() API is deprecated.

      +

      +

      DEP0049: util.isFunction()#

      + +

      Type: Documentation-only

      +

      The util.isFunction() API is deprecated.

      +

      +

      DEP0050: util.isNull()#

      + +

      Type: Documentation-only

      +

      The util.isNull() API is deprecated.

      +

      +

      DEP0051: util.isNullOrUndefined()#

      + +

      Type: Documentation-only

      +

      The util.isNullOrUndefined() API is deprecated.

      +

      +

      DEP0052: util.isNumber()#

      + +

      Type: Documentation-only

      +

      The util.isNumber() API is deprecated.

      +

      +

      DEP0053 util.isObject()#

      + +

      Type: Documentation-only

      +

      The util.isObject() API is deprecated.

      +

      +

      DEP0054: util.isPrimitive()#

      + +

      Type: Documentation-only

      +

      The util.isPrimitive() API is deprecated.

      +

      +

      DEP0055: util.isRegExp()#

      + +

      Type: Documentation-only

      +

      The util.isRegExp() API is deprecated.

      +

      +

      DEP0056: util.isString()#

      + +

      Type: Documentation-only

      +

      The util.isString() API is deprecated.

      +

      +

      DEP0057: util.isSymbol()#

      + +

      Type: Documentation-only

      +

      The util.isSymbol() API is deprecated.

      +

      +

      DEP0058: util.isUndefined()#

      + +

      Type: Documentation-only

      +

      The util.isUndefined() API is deprecated.

      +

      +

      DEP0059: util.log()#

      + +

      Type: Documentation-only

      +

      The util.log() API is deprecated.

      +

      +

      DEP0060: util._extend()#

      + +

      Type: Documentation-only

      +

      The util._extend() API is deprecated.

      +

      +

      DEP0061: fs.SyncWriteStream#

      + +

      Type: End-of-Life

      +

      The fs.SyncWriteStream class was never intended to be a publicly accessible +API and has been removed. No alternative API is available. Please use a userland +alternative.

      +

      +

      DEP0062: node --debug#

      + +

      Type: End-of-Life

      +

      --debug activates the legacy V8 debugger interface, which was removed as +of V8 5.8. It is replaced by Inspector which is activated with --inspect +instead.

      +

      +

      DEP0063: ServerResponse.prototype.writeHeader()#

      + +

      Type: Documentation-only

      +

      The http module ServerResponse.prototype.writeHeader() API is +deprecated. Please use ServerResponse.prototype.writeHead() instead.

      +

      The ServerResponse.prototype.writeHeader() method was never documented as an +officially supported API.

      +

      +

      DEP0064: tls.createSecurePair()#

      + +

      Type: Runtime

      +

      The tls.createSecurePair() API was deprecated in documentation in Node.js +0.11.3. Users should use tls.Socket instead.

      +

      +

      DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic#

      + +

      Type: End-of-Life

      +

      The repl module's REPL_MODE_MAGIC constant, used for replMode option, has +been removed. Its behavior has been functionally identical to that of +REPL_MODE_SLOPPY since Node.js 6.0.0, when V8 5.0 was imported. Please use +REPL_MODE_SLOPPY instead.

      +

      The NODE_REPL_MODE environment variable is used to set the underlying +replMode of an interactive node session. Its value, magic, is also +removed. Please use sloppy instead.

      +

      +

      DEP0066: OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames#

      + +

      Type: Runtime

      +

      The http module OutgoingMessage.prototype._headers and +OutgoingMessage.prototype._headerNames properties are deprecated. Use one of +the public methods (e.g. OutgoingMessage.prototype.getHeader(), +OutgoingMessage.prototype.getHeaders(), +OutgoingMessage.prototype.getHeaderNames(), +OutgoingMessage.prototype.hasHeader(), +OutgoingMessage.prototype.removeHeader(), +OutgoingMessage.prototype.setHeader()) for working with outgoing headers.

      +

      The OutgoingMessage.prototype._headers and +OutgoingMessage.prototype._headerNames properties were never documented as +officially supported properties.

      +

      +

      DEP0067: OutgoingMessage.prototype._renderHeaders#

      + +

      Type: Documentation-only

      +

      The http module OutgoingMessage.prototype._renderHeaders() API is +deprecated.

      +

      The OutgoingMessage.prototype._renderHeaders property was never documented as +an officially supported API.

      +

      +

      DEP0068: node debug#

      + +

      Type: Runtime

      +

      node debug corresponds to the legacy CLI debugger which has been replaced with +a V8-inspector based CLI debugger available through node inspect.

      +

      +

      DEP0069: vm.runInDebugContext(string)#

      + +

      Type: End-of-Life

      +

      DebugContext has been removed in V8 and is not available in Node.js 10+.

      +

      DebugContext was an experimental API.

      +

      +

      DEP0070: async_hooks.currentId()#

      + +

      Type: End-of-Life

      +

      async_hooks.currentId() was renamed to async_hooks.executionAsyncId() for +clarity.

      +

      This change was made while async_hooks was an experimental API.

      +

      +

      DEP0071: async_hooks.triggerId()#

      + +

      Type: End-of-Life

      +

      async_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for +clarity.

      +

      This change was made while async_hooks was an experimental API.

      +

      +

      DEP0072: async_hooks.AsyncResource.triggerId()#

      + +

      Type: End-of-Life

      +

      async_hooks.AsyncResource.triggerId() was renamed to +async_hooks.AsyncResource.triggerAsyncId() for clarity.

      +

      This change was made while async_hooks was an experimental API.

      +

      +

      DEP0073: Several internal properties of net.Server#

      + +

      Type: End-of-Life

      +

      Accessing several internal, undocumented properties of net.Server instances +with inappropriate names is deprecated.

      +

      As the original API was undocumented and not generally useful for non-internal +code, no replacement API is provided.

      +

      +

      DEP0074: REPLServer.bufferedCommand#

      + +

      Type: Runtime

      +

      The REPLServer.bufferedCommand property was deprecated in favor of +REPLServer.clearBufferedCommand().

      +

      +

      DEP0075: REPLServer.parseREPLKeyword()#

      + +

      Type: Runtime

      +

      REPLServer.parseREPLKeyword() was removed from userland visibility.

      +

      +

      DEP0076: tls.parseCertString()#

      + +

      Type: Runtime

      +

      tls.parseCertString() is a trivial parsing helper that was made public by +mistake. This function can usually be replaced with:

      +
      const querystring = require('querystring');
      +querystring.parse(str, '\n', '=');
      +

      This function is not completely equivalent to querystring.parse(). One +difference is that querystring.parse() does url decoding:

      +
      > querystring.parse('%E5%A5%BD=1', '\n', '=');
      +{ '好': '1' }
      +> tls.parseCertString('%E5%A5%BD=1');
      +{ '%E5%A5%BD': '1' }
      +

      +

      DEP0077: Module._debug()#

      + +

      Type: Runtime

      +

      Module._debug() is deprecated.

      +

      The Module._debug() function was never documented as an officially +supported API.

      +

      +

      DEP0078: REPLServer.turnOffEditorMode()#

      + +

      Type: Runtime

      +

      REPLServer.turnOffEditorMode() was removed from userland visibility.

      +

      +

      DEP0079: Custom inspection function on objects via .inspect()#

      + +

      Type: End-of-Life

      +

      Using a property named inspect on an object to specify a custom inspection +function for util.inspect() is deprecated. Use util.inspect.custom +instead. For backward compatibility with Node.js prior to version 6.4.0, both +may be specified.

      +

      +

      DEP0080: path._makeLong()#

      + +

      Type: Documentation-only

      +

      The internal path._makeLong() was not intended for public use. However, +userland modules have found it useful. The internal API is deprecated +and replaced with an identical, public path.toNamespacedPath() method.

      +

      +

      DEP0081: fs.truncate() using a file descriptor#

      + +

      Type: Runtime

      +

      fs.truncate() fs.truncateSync() usage with a file descriptor is +deprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with +file descriptors.

      +

      +

      DEP0082: REPLServer.prototype.memory()#

      + +

      Type: Runtime

      +

      REPLServer.prototype.memory() is only necessary for the internal mechanics of +the REPLServer itself. Do not use this function.

      +

      +

      DEP0083: Disabling ECDH by setting ecdhCurve to false#

      + +

      Type: End-of-Life.

      +

      The ecdhCurve option to tls.createSecureContext() and tls.TLSSocket could +be set to false to disable ECDH entirely on the server only. This mode was +deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with +the client and is now unsupported. Use the ciphers parameter instead.

      +

      +

      DEP0084: requiring bundled internal dependencies#

      + +

      Type: End-of-Life

      +

      Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for +internal usage were mistakenly exposed to user code through require(). These +modules were:

      +
        +
      • v8/tools/codemap
      • +
      • v8/tools/consarray
      • +
      • v8/tools/csvparser
      • +
      • v8/tools/logreader
      • +
      • v8/tools/profile_view
      • +
      • v8/tools/profile
      • +
      • v8/tools/SourceMap
      • +
      • v8/tools/splaytree
      • +
      • v8/tools/tickprocessor-driver
      • +
      • v8/tools/tickprocessor
      • +
      • node-inspect/lib/_inspect (from 7.6.0)
      • +
      • node-inspect/lib/internal/inspect_client (from 7.6.0)
      • +
      • node-inspect/lib/internal/inspect_repl (from 7.6.0)
      • +
      +

      The v8/* modules do not have any exports, and if not imported in a specific +order would in fact throw errors. As such there are virtually no legitimate use +cases for importing them through require().

      +

      On the other hand, node-inspect may be installed locally through a package +manager, as it is published on the npm registry under the same name. No source +code modification is necessary if that is done.

      +

      +

      DEP0085: AsyncHooks sensitive API#

      + +

      Type: End-of-Life

      +

      The AsyncHooks sensitive API was never documented and had various minor issues. +Use the AsyncResource API instead. See +https://github.com/nodejs/node/issues/15572.

      +

      +

      DEP0086: Remove runInAsyncIdScope#

      + +

      Type: End-of-Life

      +

      runInAsyncIdScope doesn't emit the 'before' or 'after' event and can thus +cause a lot of issues. See https://github.com/nodejs/node/issues/14328.

      +

      +

      DEP0089: require('assert')#

      + +

      Type: Deprecation revoked

      +

      Importing assert directly was not recommended as the exposed functions use +loose equality checks. The deprecation was revoked because use of the assert +module is not discouraged, and the deprecation caused developer confusion.

      +

      +

      DEP0090: Invalid GCM authentication tag lengths#

      + +

      Type: End-of-Life

      +

      Node.js used to support all GCM authentication tag lengths which are accepted by +OpenSSL when calling decipher.setAuthTag(). Beginning with Node.js +v11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32 +bits are allowed. Authentication tags of other lengths are invalid per +NIST SP 800-38D.

      +

      +

      DEP0091: crypto.DEFAULT_ENCODING#

      + +

      Type: Runtime

      +

      The crypto.DEFAULT_ENCODING property is deprecated.

      +

      +

      DEP0092: Top-level this bound to module.exports#

      + +

      Type: Documentation-only

      +

      Assigning properties to the top-level this as an alternative +to module.exports is deprecated. Developers should use exports +or module.exports instead.

      +

      +

      DEP0093: crypto.fips is deprecated and replaced.#

      + +

      Type: Documentation-only

      +

      The crypto.fips property is deprecated. Please use crypto.setFips() +and crypto.getFips() instead.

      +

      +

      DEP0094: Using assert.fail() with more than one argument.#

      + +

      Type: Runtime

      +

      Using assert.fail() with more than one argument is deprecated. Use +assert.fail() with only one argument or use a different assert module +method.

      +

      +

      DEP0095: timers.enroll()#

      + +

      Type: Runtime

      +

      timers.enroll() is deprecated. Please use the publicly documented +setTimeout() or setInterval() instead.

      +

      +

      DEP0096: timers.unenroll()#

      + +

      Type: Runtime

      +

      timers.unenroll() is deprecated. Please use the publicly documented +clearTimeout() or clearInterval() instead.

      +

      +

      DEP0097: MakeCallback with domain property#

      + +

      Type: Runtime

      +

      Users of MakeCallback that add the domain property to carry context, +should start using the async_context variant of MakeCallback or +CallbackScope, or the high-level AsyncResource class.

      +

      +

      DEP0098: AsyncHooks embedder AsyncResource.emitBefore and AsyncResource.emitAfter APIs#

      + +

      Type: End-of-Life

      +

      The embedded API provided by AsyncHooks exposes .emitBefore() and +.emitAfter() methods which are very easy to use incorrectly which can lead +to unrecoverable errors.

      +

      Use asyncResource.runInAsyncScope() API instead which provides a much +safer, and more convenient, alternative. See +https://github.com/nodejs/node/pull/18513.

      +

      +

      DEP0099: Async context-unaware node::MakeCallback C++ APIs#

      + +

      Type: Compile-time

      +

      Certain versions of node::MakeCallback APIs available to native modules are +deprecated. Please use the versions of the API that accept an async_context +parameter.

      +

      +

      DEP0100: process.assert()#

      + +

      Type: Runtime

      +

      process.assert() is deprecated. Please use the assert module instead.

      +

      This was never a documented feature.

      +

      +

      DEP0101: --with-lttng#

      + +

      Type: End-of-Life

      +

      The --with-lttng compile-time option has been removed.

      +

      +

      DEP0102: Using noAssert in Buffer#(read|write) operations.#

      + +

      Type: End-of-Life

      +

      Using the noAssert argument has no functionality anymore. All input is going +to be verified, no matter if it is set to true or not. Skipping the verification +could lead to hard to find errors and crashes.

      +

      +

      DEP0103: process.binding('util').is[...] typechecks#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      Using process.binding() in general should be avoided. The type checking +methods in particular can be replaced by using util.types.

      +

      This deprecation has been superseded by the deprecation of the +process.binding() API (DEP0111).

      +

      +

      DEP0104: process.env string coercion#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      When assigning a non-string property to process.env, the assigned value is +implicitly converted to a string. This behavior is deprecated if the assigned +value is not a string, boolean, or number. In the future, such assignment may +result in a thrown error. Please convert the property to a string before +assigning it to process.env.

      +

      +

      DEP0105: decipher.finaltol#

      + +

      Type: End-of-Life

      +

      decipher.finaltol() has never been documented and was an alias for +decipher.final(). This API has been removed, and it is recommended to use +decipher.final() instead.

      +

      +

      DEP0106: crypto.createCipher and crypto.createDecipher#

      + +

      Type: Runtime

      +

      Using crypto.createCipher() and crypto.createDecipher() should be +avoided as they use a weak key derivation function (MD5 with no salt) and static +initialization vectors. It is recommended to derive a key using +crypto.pbkdf2() or crypto.scrypt() and to use +crypto.createCipheriv() and crypto.createDecipheriv() to obtain the +Cipher and Decipher objects respectively.

      +

      +

      DEP0107: tls.convertNPNProtocols()#

      + +

      Type: End-of-Life

      +

      This was an undocumented helper function not intended for use outside Node.js +core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.

      +

      +

      DEP0108: zlib.bytesRead#

      + +

      Type: Runtime

      +

      Deprecated alias for zlib.bytesWritten. This original name was chosen +because it also made sense to interpret the value as the number of bytes +read by the engine, but is inconsistent with other streams in Node.js that +expose values under these names.

      +

      +

      DEP0109: http, https, and tls support for invalid URLs#

      + +

      Type: Runtime

      +

      Some previously supported (but strictly invalid) URLs were accepted through the +http.request(), http.get(), https.request(), +https.get(), and tls.checkServerIdentity() APIs because those were +accepted by the legacy url.parse() API. The mentioned APIs now use the WHATWG +URL parser that requires strictly valid URLs. Passing an invalid URL is +deprecated and support will be removed in the future.

      +

      +

      DEP0110: vm.Script cached data#

      + +

      Type: Documentation-only

      +

      The produceCachedData option is deprecated. Use +script.createCachedData() instead.

      +

      +

      DEP0111: process.binding()#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      process.binding() is for use by Node.js internal code only.

      +

      +

      DEP0112: dgram private APIs#

      + +

      Type: Runtime

      +

      The dgram module previously contained several APIs that were never meant to +accessed outside of Node.js core: Socket.prototype._handle, +Socket.prototype._receiving, Socket.prototype._bindState, +Socket.prototype._queue, Socket.prototype._reuseAddr, +Socket.prototype._healthCheck(), Socket.prototype._stopReceiving(), and +dgram._createSocketHandle().

      +

      +

      DEP0113: Cipher.setAuthTag(), Decipher.getAuthTag()#

      + +

      Type: End-of-Life

      +

      Cipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They +were never documented and would throw when called.

      +

      +

      DEP0114: crypto._toBuf()#

      + +

      Type: End-of-Life

      +

      The crypto._toBuf() function was not designed to be used by modules outside +of Node.js core and was removed.

      +

      +

      DEP0115: crypto.prng(), crypto.pseudoRandomBytes(), crypto.rng()#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      In recent versions of Node.js, there is no difference between +crypto.randomBytes() and crypto.pseudoRandomBytes(). The latter is +deprecated along with the undocumented aliases crypto.prng() and +crypto.rng() in favor of crypto.randomBytes() and may be removed in a +future release.

      +

      +

      DEP0116: Legacy URL API#

      + +

      Type: Documentation-only

      +

      The Legacy URL API is deprecated. This includes url.format(), +url.parse(), url.resolve(), and the legacy urlObject. Please +use the WHATWG URL API instead.

      +

      +

      DEP0117: Native crypto handles#

      + +

      Type: End-of-Life

      +

      Previous versions of Node.js exposed handles to internal native objects through +the _handle property of the Cipher, Decipher, DiffieHellman, +DiffieHellmanGroup, ECDH, Hash, Hmac, Sign, and Verify classes. +The _handle property has been removed because improper use of the native +object can lead to crashing the application.

      +

      +

      DEP0118: dns.lookup() support for a falsy host name#

      + +

      Type: Runtime

      +

      Previous versions of Node.js supported dns.lookup() with a falsy host name +like dns.lookup(false) due to backward compatibility. +This behavior is undocumented and is thought to be unused in real world apps. +It will become an error in future versions of Node.js.

      +

      +

      DEP0119: process.binding('uv').errname() private API#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      process.binding('uv').errname() is deprecated. Please use +util.getSystemErrorName() instead.

      +

      +

      DEP0120: Windows Performance Counter support#

      + +

      Type: End-of-Life

      +

      Windows Performance Counter support has been removed from Node.js. The +undocumented COUNTER_NET_SERVER_CONNECTION(), +COUNTER_NET_SERVER_CONNECTION_CLOSE(), COUNTER_HTTP_SERVER_REQUEST(), +COUNTER_HTTP_SERVER_RESPONSE(), COUNTER_HTTP_CLIENT_REQUEST(), and +COUNTER_HTTP_CLIENT_RESPONSE() functions have been deprecated.

      +

      +

      DEP0121: net._setSimultaneousAccepts()#

      + +

      Type: Runtime

      +

      The undocumented net._setSimultaneousAccepts() function was originally +intended for debugging and performance tuning when using the child_process +and cluster modules on Windows. The function is not generally useful and +is being removed. See discussion here: +https://github.com/nodejs/node/issues/18391

      +

      +

      DEP0122: tls Server.prototype.setOptions()#

      + +

      Type: Runtime

      +

      Please use Server.prototype.setSecureContext() instead.

      +

      +

      DEP0123: setting the TLS ServerName to an IP address#

      + +

      Type: Runtime

      +

      Setting the TLS ServerName to an IP address is not permitted by +RFC 6066. This will be ignored in a future version.

      +

      +

      DEP0124: using REPLServer.rli#

      + +

      Type: Runtime

      +

      This property is a reference to the instance itself.

      +

      +

      DEP0125: require('_stream_wrap')#

      + +

      Type: Runtime

      +

      The _stream_wrap module is deprecated.

      +

      +

      DEP0126: timers.active()#

      + +

      Type: Runtime

      +

      The previously undocumented timers.active() is deprecated. +Please use the publicly documented timeout.refresh() instead. +If re-referencing the timeout is necessary, timeout.ref() can be used +with no performance impact since Node.js 10.

      +

      +

      DEP0127: timers._unrefActive()#

      + +

      Type: Runtime

      +

      The previously undocumented and "private" timers._unrefActive() is deprecated. +Please use the publicly documented timeout.refresh() instead. +If unreferencing the timeout is necessary, timeout.unref() can be used +with no performance impact since Node.js 10.

      +

      +

      DEP0128: modules with an invalid main entry and an index.js file#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      Modules that have an invalid main entry (e.g., ./does-not-exist.js) and +also have an index.js file in the top level directory will resolve the +index.js file. That is deprecated and is going to throw an error in future +Node.js versions.

      +

      +

      DEP0129: ChildProcess._channel#

      + +

      Type: Documentation-only

      +

      The _channel property of child process objects returned by spawn() and +similar functions is not intended for public use. Use ChildProcess.channel +instead.

      +

      +

      DEP0130: Module.createRequireFromPath()#

      + +

      Type: Documentation-only

      +

      Module.createRequireFromPath() is deprecated. Please use module.createRequire() instead.

      +

      +

      DEP0131: Legacy HTTP parser#

      + +

      Type: Runtime

      +

      The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0, +is deprecated. This deprecation applies to users of the +--http-parser=legacy command-line flag.

      +

      +

      DEP0132: worker.terminate() with callback#

      + +

      Type: Runtime

      +

      Passing a callback to worker.terminate() is deprecated. Use the returned +Promise instead, or a listener to the worker’s 'exit' event.

      +

      +

      DEP0133: http connection#

      + +

      Type: Documentation-only

      +

      Prefer response.socket over response.connection and +request.socket over request.connection.

      +

      +

      DEP0134: process._tickCallback#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      The process._tickCallback property was never documented as +an officially supported API.

      +

      +

      DEP0136: http finished#

      + +

      Type: Documentation-only

      +

      response.finished indicates whether response.end() has been +called, not whether 'finish' has been emitted and the underlying data +is flushed.

      +

      Use response.writableFinished or response.writableEnded +accordingly instead to avoid the ambigiuty.

      +

      To maintain existing behaviour response.finished should be replaced with +response.writableEnded.

      +

      +

      DEP0139: process.umask() with no arguments#

      + +

      Type: Documentation-only

      +

      Calling process.umask() with no argument causes the process-wide umask to be +written twice. This introduces a race condition between threads, and is a +potential security vulnerability. There is no safe, cross-platform alternative +API.

      +

      +

      DEP0144: module.parent#

      + +

      Type: Documentation-only

      +

      A CommonJS module can access the first module that required it using +module.parent. This feature is deprecated because it does not work +consistently in the presence of ECMAScript modules and because it gives an +inaccurate representation of the CommonJS module graph.

      +

      Some modules use it to check if they are the entry point of the current process. +Instead, it is recommended to compare require.main and module:

      +
      if (require.main === module) {
      +  // Code section that will run only if current file is the entry point.
      +}
      +

      When looking for the CommonJS modules that have required the current one, +require.cache and module.children can be used:

      +
      const moduleParents = Object.values(require.cache)
      +  .filter((m) => m.children.includes(module));
      +

      DNS#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/dns.js

      +

      The dns module enables name resolution. For example, use it to look up IP +addresses of host names.

      +

      Although named for the Domain Name System (DNS), it does not always use the +DNS protocol for lookups. dns.lookup() uses the operating system +facilities to perform name resolution. It may not need to perform any network +communication. To perform name resolution the way other applications on the same +system do, use dns.lookup().

      +
      const dns = require('dns');
      +
      +dns.lookup('example.org', (err, address, family) => {
      +  console.log('address: %j family: IPv%s', address, family);
      +});
      +// address: "93.184.216.34" family: IPv4
      +

      All other functions in the dns module connect to an actual DNS server to +perform name resolution. They will always use the network to perform DNS +queries. These functions do not use the same set of configuration files used by +dns.lookup() (e.g. /etc/hosts). Use these functions to always perform +DNS queries, bypassing other name-resolution facilities.

      +
      const dns = require('dns');
      +
      +dns.resolve4('archive.org', (err, addresses) => {
      +  if (err) throw err;
      +
      +  console.log(`addresses: ${JSON.stringify(addresses)}`);
      +
      +  addresses.forEach((a) => {
      +    dns.reverse(a, (err, hostnames) => {
      +      if (err) {
      +        throw err;
      +      }
      +      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
      +    });
      +  });
      +});
      +

      See the Implementation considerations section for more information.

      +

      Class: dns.Resolver#

      + +

      An independent resolver for DNS requests.

      +

      Creating a new resolver uses the default server settings. Setting +the servers used for a resolver using +resolver.setServers() does not affect +other resolvers:

      +
      const { Resolver } = require('dns');
      +const resolver = new Resolver();
      +resolver.setServers(['4.4.4.4']);
      +
      +// This request will use the server at 4.4.4.4, independent of global settings.
      +resolver.resolve4('example.org', (err, addresses) => {
      +  // ...
      +});
      +

      The following methods from the dns module are available:

      + +

      Resolver([options])#

      + +

      Create a new resolver.

      +
        +
      • options <Object> +
          +
        • timeout <integer> Query timeout in milliseconds, or -1 to use the +default timeout.
        • +
        +
      • +
      +

      resolver.cancel()#

      + +

      Cancel all outstanding DNS queries made by this resolver. The corresponding +callbacks will be called with an error with code ECANCELLED.

      +

      dns.getServers()#

      + + +

      Returns an array of IP address strings, formatted according to RFC 5952, +that are currently configured for DNS resolution. A string will include a port +section if a custom port is used.

      + +
      [
      +  '4.4.4.4',
      +  '2001:4860:4860::8888',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]
      +

      dns.lookup(hostname[, options], callback)#

      + +
        +
      • hostname <string>
      • +
      • options <integer> | <Object> +
          +
        • family <integer> The record family. Must be 4, 6, or 0. The value +0 indicates that IPv4 and IPv6 addresses are both returned. Default: +0.
        • +
        • hints <number> One or more supported getaddrinfo flags. Multiple +flags may be passed by bitwise ORing their values.
        • +
        • all <boolean> When true, the callback returns all resolved addresses in +an array. Otherwise, returns a single address. Default: false.
        • +
        • verbatim <boolean> When true, the callback receives IPv4 and IPv6 +addresses in the order the DNS resolver returned them. When false, +IPv4 addresses are placed before IPv6 addresses. +Default: currently false (addresses are reordered) but this is +expected to change in the not too distant future. +New code should use { verbatim: true }.
        • +
        +
      • +
      • callback <Function> +
          +
        • err <Error>
        • +
        • address <string> A string representation of an IPv4 or IPv6 address.
        • +
        • family <integer> 4 or 6, denoting the family of address, or 0 if +the address is not an IPv4 or IPv6 address. 0 is a likely indicator of a +bug in the name resolution service used by the operating system.
        • +
        +
      • +
      +

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or +AAAA (IPv6) record. All option properties are optional. If options is an +integer, then it must be 4 or 6 – if options is not provided, then IPv4 +and IPv6 addresses are both returned if found.

      +

      With the all option set to true, the arguments for callback change to +(err, addresses), with addresses being an array of objects with the +properties address and family.

      +

      On error, err is an Error object, where err.code is the error code. +Keep in mind that err.code will be set to 'ENOTFOUND' not only when +the host name does not exist but also when the lookup fails in other ways +such as no available file descriptors.

      +

      dns.lookup() does not necessarily have anything to do with the DNS protocol. +The implementation uses an operating system facility that can associate names +with addresses, and vice versa. This implementation can have subtle but +important consequences on the behavior of any Node.js program. Please take some +time to consult the Implementation considerations section before using +dns.lookup().

      +

      Example usage:

      +
      const dns = require('dns');
      +const options = {
      +  family: 6,
      +  hints: dns.ADDRCONFIG | dns.V4MAPPED,
      +};
      +dns.lookup('example.com', options, (err, address, family) =>
      +  console.log('address: %j family: IPv%s', address, family));
      +// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
      +
      +// When options.all is true, the result will be an Array.
      +options.all = true;
      +dns.lookup('example.com', options, (err, addresses) =>
      +  console.log('addresses: %j', addresses));
      +// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
      +

      If this method is invoked as its util.promisify()ed version, and all +is not set to true, it returns a Promise for an Object with address and +family properties.

      +

      Supported getaddrinfo flags#

      + +

      The following flags can be passed as hints to dns.lookup().

      +
        +
      • dns.ADDRCONFIG: Limits returned address types to the types of non-loopback +addresses configured on the system. For example, IPv4 addresses are only +returned if the current system has at least one IPv4 address configured.
      • +
      • dns.V4MAPPED: If the IPv6 family was specified, but no IPv6 addresses were +found, then return IPv4 mapped IPv6 addresses. It is not supported +on some operating systems (e.g FreeBSD 10.1).
      • +
      • dns.ALL: If dns.V4MAPPED is specified, return resolved IPv6 addresses as +well as IPv4 mapped IPv6 addresses.
      • +
      +

      dns.lookupService(address, port, callback)#

      + + +

      Resolves the given address and port into a host name and service using +the operating system's underlying getnameinfo implementation.

      +

      If address is not a valid IP address, a TypeError will be thrown. +The port will be coerced to a number. If it is not a legal port, a TypeError +will be thrown.

      +

      On an error, err is an Error object, where err.code is the error code.

      +
      const dns = require('dns');
      +dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
      +  console.log(hostname, service);
      +  // Prints: localhost ssh
      +});
      +

      If this method is invoked as its util.promisify()ed version, it returns a +Promise for an Object with hostname and service properties.

      +

      dns.resolve(hostname[, rrtype], callback)#

      + + +

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array +of the resource records. The callback function has arguments +(err, records). When successful, records will be an array of resource +records. The type and structure of individual results varies based on rrtype:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dns.resolve4()
      'AAAA'IPv6 addresses<string>dns.resolve6()
      'ANY'any records<Object>dns.resolveAny()
      'CNAME'canonical name records<string>dns.resolveCname()
      'MX'mail exchange records<Object>dns.resolveMx()
      'NAPTR'name authority pointer records<Object>dns.resolveNaptr()
      'NS'name server records<string>dns.resolveNs()
      'PTR'pointer records<string>dns.resolvePtr()
      'SOA'start of authority records<Object>dns.resolveSoa()
      'SRV'service records<Object>dns.resolveSrv()
      'TXT'text records<string[]>dns.resolveTxt()
      +

      On error, err is an Error object, where err.code is one of the +DNS error codes.

      +

      dns.resolve4(hostname[, options], callback)#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the callback receives an array of +{ address: '1.2.3.4', ttl: 60 } objects rather than an array of strings, +with the TTL expressed in seconds.
        • +
        +
      • +
      • callback <Function> + +
      • +
      +

      Uses the DNS protocol to resolve a IPv4 addresses (A records) for the +hostname. The addresses argument passed to the callback function +will contain an array of IPv4 addresses (e.g. +['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      +

      dns.resolve6(hostname[, options], callback)#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the callback receives an array of +{ address: '0:1:2:3:4:5:6:7', ttl: 60 } objects rather than an array of +strings, with the TTL expressed in seconds.
        • +
        +
      • +
      • callback <Function> + +
      • +
      +

      Uses the DNS protocol to resolve a IPv6 addresses (AAAA records) for the +hostname. The addresses argument passed to the callback function +will contain an array of IPv6 addresses.

      +

      dns.resolveAny(hostname, callback)#

      + +

      Uses the DNS protocol to resolve all records (also known as ANY or * query). +The ret argument passed to the callback function will be an array containing +various types of records. Each object has a property type that indicates the +type of the current record. And depending on the type, additional properties +will be present on the object:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dns.resolveMx()
      'NAPTR'Refer to dns.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dns.resolveSoa()
      'SRV'Refer to dns.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      +

      Here is an example of the ret object passed to the callback:

      + +
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },
      +  { type: 'CNAME', value: 'example.com' },
      +  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
      +  { type: 'NS', value: 'ns1.example.com' },
      +  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
      +  { type: 'SOA',
      +    nsname: 'ns1.example.com',
      +    hostmaster: 'admin.example.com',
      +    serial: 156696742,
      +    refresh: 900,
      +    retry: 900,
      +    expire: 1800,
      +    minttl: 60 } ]
      +

      DNS server operators may choose not to respond to ANY +queries. It may be better to call individual methods like dns.resolve4(), +dns.resolveMx(), and so on. For more details, see RFC 8482.

      +

      dns.resolveCname(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve CNAME records for the hostname. The +addresses argument passed to the callback function +will contain an array of canonical name records available for the hostname +(e.g. ['bar.example.com']).

      +

      dns.resolveMx(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve mail exchange records (MX records) for the +hostname. The addresses argument passed to the callback function will +contain an array of objects containing both a priority and exchange +property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).

      +

      dns.resolveNaptr(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve regular expression based records (NAPTR +records) for the hostname. The addresses argument passed to the callback +function will contain an array of objects with the following properties:

      +
        +
      • flags
      • +
      • service
      • +
      • regexp
      • +
      • replacement
      • +
      • order
      • +
      • preference
      • +
      + +
      {
      +  flags: 's',
      +  service: 'SIP+D2U',
      +  regexp: '',
      +  replacement: '_sip._udp.example.com',
      +  order: 30,
      +  preference: 100
      +}
      +

      dns.resolveNs(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve name server records (NS records) for the +hostname. The addresses argument passed to the callback function will +contain an array of name server records available for hostname +(e.g. ['ns1.example.com', 'ns2.example.com']).

      +

      dns.resolvePtr(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve pointer records (PTR records) for the +hostname. The addresses argument passed to the callback function will +be an array of strings containing the reply records.

      +

      dns.resolveSoa(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve a start of authority record (SOA record) for +the hostname. The address argument passed to the callback function will +be an object with the following properties:

      +
        +
      • nsname
      • +
      • hostmaster
      • +
      • serial
      • +
      • refresh
      • +
      • retry
      • +
      • expire
      • +
      • minttl
      • +
      + +
      {
      +  nsname: 'ns.example.com',
      +  hostmaster: 'root.example.com',
      +  serial: 2013101809,
      +  refresh: 10000,
      +  retry: 2400,
      +  expire: 604800,
      +  minttl: 3600
      +}
      +

      dns.resolveSrv(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve service records (SRV records) for the +hostname. The addresses argument passed to the callback function will +be an array of objects with the following properties:

      +
        +
      • priority
      • +
      • weight
      • +
      • port
      • +
      • name
      • +
      + +
      {
      +  priority: 10,
      +  weight: 5,
      +  port: 21223,
      +  name: 'service.example.com'
      +}
      +

      dns.resolveTxt(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve text queries (TXT records) for the +hostname. The records argument passed to the callback function is a +two-dimensional array of the text records available for hostname (e.g. +[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of +one record. Depending on the use case, these could be either joined together or +treated separately.

      +

      dns.reverse(ip, callback)#

      + + +

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an +array of host names.

      +

      On error, err is an Error object, where err.code is +one of the DNS error codes.

      +

      dns.setServers(servers)#

      + + +

      Sets the IP address and port of servers to be used when performing DNS +resolution. The servers argument is an array of RFC 5952 formatted +addresses. If the port is the IANA default DNS port (53) it can be omitted.

      +
      dns.setServers([
      +  '4.4.4.4',
      +  '[2001:4860:4860::8888]',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]);
      +

      An error will be thrown if an invalid address is provided.

      +

      The dns.setServers() method must not be called while a DNS query is in +progress.

      +

      The dns.setServers() method affects only dns.resolve(), +dns.resolve*() and dns.reverse() (and specifically not +dns.lookup()).

      +

      This method works much like +resolve.conf. +That is, if attempting to resolve with the first server provided results in a +NOTFOUND error, the resolve() method will not attempt to resolve with +subsequent servers provided. Fallback DNS servers will only be used if the +earlier ones time out or result in some other error.

      +

      DNS promises API#

      +

      The dns.promises API provides an alternative set of asynchronous DNS methods +that return Promise objects rather than using callbacks. The API is accessible +via require('dns').promises.

      +

      Class: dnsPromises.Resolver#

      + +

      An independent resolver for DNS requests.

      +

      Creating a new resolver uses the default server settings. Setting +the servers used for a resolver using +resolver.setServers() does not affect +other resolvers:

      +
      const { Resolver } = require('dns').promises;
      +const resolver = new Resolver();
      +resolver.setServers(['4.4.4.4']);
      +
      +// This request will use the server at 4.4.4.4, independent of global settings.
      +resolver.resolve4('example.org').then((addresses) => {
      +  // ...
      +});
      +
      +// Alternatively, the same code can be written using async-await style.
      +(async function() {
      +  const addresses = await resolver.resolve4('example.org');
      +})();
      +

      The following methods from the dnsPromises API are available:

      + +

      dnsPromises.getServers()#

      + + +

      Returns an array of IP address strings, formatted according to RFC 5952, +that are currently configured for DNS resolution. A string will include a port +section if a custom port is used.

      + +
      [
      +  '4.4.4.4',
      +  '2001:4860:4860::8888',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]
      +

      dnsPromises.lookup(hostname[, options])#

      + +
        +
      • hostname <string>
      • +
      • options <integer> | <Object> +
          +
        • family <integer> The record family. Must be 4, 6, or 0. The value +0 indicates that IPv4 and IPv6 addresses are both returned. Default: +0.
        • +
        • hints <number> One or more supported getaddrinfo flags. Multiple +flags may be passed by bitwise ORing their values.
        • +
        • all <boolean> When true, the Promise is resolved with all addresses in +an array. Otherwise, returns a single address. Default: false.
        • +
        • verbatim <boolean> When true, the Promise is resolved with IPv4 and +IPv6 addresses in the order the DNS resolver returned them. When false, +IPv4 addresses are placed before IPv6 addresses. +Default: currently false (addresses are reordered) but this is +expected to change in the not too distant future. +New code should use { verbatim: true }.
        • +
        +
      • +
      +

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or +AAAA (IPv6) record. All option properties are optional. If options is an +integer, then it must be 4 or 6 – if options is not provided, then IPv4 +and IPv6 addresses are both returned if found.

      +

      With the all option set to true, the Promise is resolved with addresses +being an array of objects with the properties address and family.

      +

      On error, the Promise is rejected with an Error object, where err.code +is the error code. +Keep in mind that err.code will be set to 'ENOTFOUND' not only when +the host name does not exist but also when the lookup fails in other ways +such as no available file descriptors.

      +

      dnsPromises.lookup() does not necessarily have anything to do with the DNS +protocol. The implementation uses an operating system facility that can +associate names with addresses, and vice versa. This implementation can have +subtle but important consequences on the behavior of any Node.js program. Please +take some time to consult the Implementation considerations section before +using dnsPromises.lookup().

      +

      Example usage:

      +
      const dns = require('dns');
      +const dnsPromises = dns.promises;
      +const options = {
      +  family: 6,
      +  hints: dns.ADDRCONFIG | dns.V4MAPPED,
      +};
      +
      +dnsPromises.lookup('example.com', options).then((result) => {
      +  console.log('address: %j family: IPv%s', result.address, result.family);
      +  // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
      +});
      +
      +// When options.all is true, the result will be an Array.
      +options.all = true;
      +dnsPromises.lookup('example.com', options).then((result) => {
      +  console.log('addresses: %j', result);
      +  // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
      +});
      +

      dnsPromises.lookupService(address, port)#

      + + +

      Resolves the given address and port into a host name and service using +the operating system's underlying getnameinfo implementation.

      +

      If address is not a valid IP address, a TypeError will be thrown. +The port will be coerced to a number. If it is not a legal port, a TypeError +will be thrown.

      +

      On error, the Promise is rejected with an Error object, where err.code +is the error code.

      +
      const dnsPromises = require('dns').promises;
      +dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
      +  console.log(result.hostname, result.service);
      +  // Prints: localhost ssh
      +});
      +

      dnsPromises.resolve(hostname[, rrtype])#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • rrtype <string> Resource record type. Default: 'A'.
      • +
      +

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array +of the resource records. When successful, the Promise is resolved with an +array of resource records. The type and structure of individual results vary +based on rrtype:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dnsPromises.resolve4()
      'AAAA'IPv6 addresses<string>dnsPromises.resolve6()
      'ANY'any records<Object>dnsPromises.resolveAny()
      'CNAME'canonical name records<string>dnsPromises.resolveCname()
      'MX'mail exchange records<Object>dnsPromises.resolveMx()
      'NAPTR'name authority pointer records<Object>dnsPromises.resolveNaptr()
      'NS'name server records<string>dnsPromises.resolveNs()
      'PTR'pointer records<string>dnsPromises.resolvePtr()
      'SOA'start of authority records<Object>dnsPromises.resolveSoa()
      'SRV'service records<Object>dnsPromises.resolveSrv()
      'TXT'text records<string[]>dnsPromises.resolveTxt()
      +

      On error, the Promise is rejected with an Error object, where err.code +is one of the DNS error codes.

      +

      dnsPromises.resolve4(hostname[, options])#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the Promise is resolved with an array of +{ address: '1.2.3.4', ttl: 60 } objects rather than an array of strings, +with the TTL expressed in seconds.
        • +
        +
      • +
      +

      Uses the DNS protocol to resolve IPv4 addresses (A records) for the +hostname. On success, the Promise is resolved with an array of IPv4 +addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      +

      dnsPromises.resolve6(hostname[, options])#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the Promise is resolved with an array of +{ address: '0:1:2:3:4:5:6:7', ttl: 60 } objects rather than an array of +strings, with the TTL expressed in seconds.
        • +
        +
      • +
      +

      Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the +hostname. On success, the Promise is resolved with an array of IPv6 +addresses.

      +

      dnsPromises.resolveAny(hostname)#

      + + +

      Uses the DNS protocol to resolve all records (also known as ANY or * query). +On success, the Promise is resolved with an array containing various types of +records. Each object has a property type that indicates the type of the +current record. And depending on the type, additional properties will be +present on the object:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dnsPromises.resolveMx()
      'NAPTR'Refer to dnsPromises.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dnsPromises.resolveSoa()
      'SRV'Refer to dnsPromises.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      +

      Here is an example of the result object:

      + +
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },
      +  { type: 'CNAME', value: 'example.com' },
      +  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
      +  { type: 'NS', value: 'ns1.example.com' },
      +  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
      +  { type: 'SOA',
      +    nsname: 'ns1.example.com',
      +    hostmaster: 'admin.example.com',
      +    serial: 156696742,
      +    refresh: 900,
      +    retry: 900,
      +    expire: 1800,
      +    minttl: 60 } ]
      +

      dnsPromises.resolveCname(hostname)#

      + + +

      Uses the DNS protocol to resolve CNAME records for the hostname. On success, +the Promise is resolved with an array of canonical name records available for +the hostname (e.g. ['bar.example.com']).

      +

      dnsPromises.resolveMx(hostname)#

      + + +

      Uses the DNS protocol to resolve mail exchange records (MX records) for the +hostname. On success, the Promise is resolved with an array of objects +containing both a priority and exchange property (e.g. +[{priority: 10, exchange: 'mx.example.com'}, ...]).

      +

      dnsPromises.resolveNaptr(hostname)#

      + + +

      Uses the DNS protocol to resolve regular expression based records (NAPTR +records) for the hostname. On success, the Promise is resolved with an array +of objects with the following properties:

      +
        +
      • flags
      • +
      • service
      • +
      • regexp
      • +
      • replacement
      • +
      • order
      • +
      • preference
      • +
      + +
      {
      +  flags: 's',
      +  service: 'SIP+D2U',
      +  regexp: '',
      +  replacement: '_sip._udp.example.com',
      +  order: 30,
      +  preference: 100
      +}
      +

      dnsPromises.resolveNs(hostname)#

      + + +

      Uses the DNS protocol to resolve name server records (NS records) for the +hostname. On success, the Promise is resolved with an array of name server +records available for hostname (e.g. +['ns1.example.com', 'ns2.example.com']).

      +

      dnsPromises.resolvePtr(hostname)#

      + + +

      Uses the DNS protocol to resolve pointer records (PTR records) for the +hostname. On success, the Promise is resolved with an array of strings +containing the reply records.

      +

      dnsPromises.resolveSoa(hostname)#

      + + +

      Uses the DNS protocol to resolve a start of authority record (SOA record) for +the hostname. On success, the Promise is resolved with an object with the +following properties:

      +
        +
      • nsname
      • +
      • hostmaster
      • +
      • serial
      • +
      • refresh
      • +
      • retry
      • +
      • expire
      • +
      • minttl
      • +
      + +
      {
      +  nsname: 'ns.example.com',
      +  hostmaster: 'root.example.com',
      +  serial: 2013101809,
      +  refresh: 10000,
      +  retry: 2400,
      +  expire: 604800,
      +  minttl: 3600
      +}
      +

      dnsPromises.resolveSrv(hostname)#

      + + +

      Uses the DNS protocol to resolve service records (SRV records) for the +hostname. On success, the Promise is resolved with an array of objects with +the following properties:

      +
        +
      • priority
      • +
      • weight
      • +
      • port
      • +
      • name
      • +
      + +
      {
      +  priority: 10,
      +  weight: 5,
      +  port: 21223,
      +  name: 'service.example.com'
      +}
      +

      dnsPromises.resolveTxt(hostname)#

      + + +

      Uses the DNS protocol to resolve text queries (TXT records) for the +hostname. On success, the Promise is resolved with a two-dimensional array +of the text records available for hostname (e.g. +[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of +one record. Depending on the use case, these could be either joined together or +treated separately.

      +

      dnsPromises.reverse(ip)#

      + + +

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an +array of host names.

      +

      On error, the Promise is rejected with an Error object, where err.code +is one of the DNS error codes.

      +

      dnsPromises.setServers(servers)#

      + + +

      Sets the IP address and port of servers to be used when performing DNS +resolution. The servers argument is an array of RFC 5952 formatted +addresses. If the port is the IANA default DNS port (53) it can be omitted.

      +
      dnsPromises.setServers([
      +  '4.4.4.4',
      +  '[2001:4860:4860::8888]',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]);
      +

      An error will be thrown if an invalid address is provided.

      +

      The dnsPromises.setServers() method must not be called while a DNS query is in +progress.

      +

      This method works much like +resolve.conf. +That is, if attempting to resolve with the first server provided results in a +NOTFOUND error, the resolve() method will not attempt to resolve with +subsequent servers provided. Fallback DNS servers will only be used if the +earlier ones time out or result in some other error.

      +

      Error codes#

      +

      Each DNS query can return one of the following error codes:

      +
        +
      • dns.NODATA: DNS server returned answer with no data.
      • +
      • dns.FORMERR: DNS server claims query was misformatted.
      • +
      • dns.SERVFAIL: DNS server returned general failure.
      • +
      • dns.NOTFOUND: Domain name not found.
      • +
      • dns.NOTIMP: DNS server does not implement requested operation.
      • +
      • dns.REFUSED: DNS server refused query.
      • +
      • dns.BADQUERY: Misformatted DNS query.
      • +
      • dns.BADNAME: Misformatted host name.
      • +
      • dns.BADFAMILY: Unsupported address family.
      • +
      • dns.BADRESP: Misformatted DNS reply.
      • +
      • dns.CONNREFUSED: Could not contact DNS servers.
      • +
      • dns.TIMEOUT: Timeout while contacting DNS servers.
      • +
      • dns.EOF: End of file.
      • +
      • dns.FILE: Error reading file.
      • +
      • dns.NOMEM: Out of memory.
      • +
      • dns.DESTRUCTION: Channel is being destroyed.
      • +
      • dns.BADSTR: Misformatted string.
      • +
      • dns.BADFLAGS: Illegal flags specified.
      • +
      • dns.NONAME: Given host name is not numeric.
      • +
      • dns.BADHINTS: Illegal hints flags specified.
      • +
      • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
      • +
      • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
      • +
      • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
      • +
      • dns.CANCELLED: DNS query cancelled.
      • +
      +

      Implementation considerations#

      +

      Although dns.lookup() and the various dns.resolve*()/dns.reverse() +functions have the same goal of associating a network name with a network +address (or vice versa), their behavior is quite different. These differences +can have subtle but significant consequences on the behavior of Node.js +programs.

      +

      dns.lookup()#

      +

      Under the hood, dns.lookup() uses the same operating system facilities +as most other programs. For instance, dns.lookup() will almost always +resolve a given name the same way as the ping command. On most POSIX-like +operating systems, the behavior of the dns.lookup() function can be +modified by changing settings in nsswitch.conf(5) and/or resolv.conf(5), +but changing these files will change the behavior of all other +programs running on the same operating system.

      +

      Though the call to dns.lookup() will be asynchronous from JavaScript's +perspective, it is implemented as a synchronous call to getaddrinfo(3) that runs +on libuv's threadpool. This can have surprising negative performance +implications for some applications, see the UV_THREADPOOL_SIZE +documentation for more information.

      +

      Various networking APIs will call dns.lookup() internally to resolve +host names. If that is an issue, consider resolving the host name to an address +using dns.resolve() and using the address instead of a host name. Also, some +networking APIs (such as socket.connect() and dgram.createSocket()) +allow the default resolver, dns.lookup(), to be replaced.

      +

      dns.resolve(), dns.resolve*() and dns.reverse()#

      +

      These functions are implemented quite differently than dns.lookup(). They +do not use getaddrinfo(3) and they always perform a DNS query on the +network. This network communication is always done asynchronously, and does not +use libuv's threadpool.

      +

      As a result, these functions cannot have the same negative impact on other +processing that happens on libuv's threadpool that dns.lookup() can have.

      +

      They do not use the same set of configuration files than what dns.lookup() +uses. For instance, they do not use the configuration from /etc/hosts.

      +

      Domain#

      + + +

      Stability: 0 - Deprecated

      +

      Source Code: lib/domain.js

      +

      This module is pending deprecation. Once a replacement API has been +finalized, this module will be fully deprecated. Most developers should +not have cause to use this module. Users who absolutely must have +the functionality that domains provide may rely on it for the time being +but should expect to have to migrate to a different solution +in the future.

      +

      Domains provide a way to handle multiple different IO operations as a +single group. If any of the event emitters or callbacks registered to a +domain emit an 'error' event, or throw an error, then the domain object +will be notified, rather than losing the context of the error in the +process.on('uncaughtException') handler, or causing the program to +exit immediately with an error code.

      +

      Warning: Don't ignore errors!#

      + +

      Domain error handlers are not a substitute for closing down a +process when an error occurs.

      +

      By the very nature of how throw works in JavaScript, there is almost +never any way to safely "pick up where it left off", without leaking +references, or creating some other sort of undefined brittle state.

      +

      The safest way to respond to a thrown error is to shut down the +process. Of course, in a normal web server, there may be many +open connections, and it is not reasonable to abruptly shut those down +because an error was triggered by someone else.

      +

      The better approach is to send an error response to the request that +triggered the error, while letting the others finish in their normal +time, and stop listening for new requests in that worker.

      +

      In this way, domain usage goes hand-in-hand with the cluster module, +since the master process can fork a new worker when a worker +encounters an error. For Node.js programs that scale to multiple +machines, the terminating proxy or service registry can take note of +the failure, and react accordingly.

      +

      For example, this is not a good idea:

      +
      // XXX WARNING! BAD IDEA!
      +
      +const d = require('domain').create();
      +d.on('error', (er) => {
      +  // The error won't crash the process, but what it does is worse!
      +  // Though we've prevented abrupt process restarting, we are leaking
      +  // resources like crazy if this ever happens.
      +  // This is no better than process.on('uncaughtException')!
      +  console.log(`error, but oh well ${er.message}`);
      +});
      +d.run(() => {
      +  require('http').createServer((req, res) => {
      +    handleRequest(req, res);
      +  }).listen(PORT);
      +});
      +

      By using the context of a domain, and the resilience of separating our +program into multiple worker processes, we can react more +appropriately, and handle errors with much greater safety.

      +
      // Much better!
      +
      +const cluster = require('cluster');
      +const PORT = +process.env.PORT || 1337;
      +
      +if (cluster.isMaster) {
      +  // A more realistic scenario would have more than 2 workers,
      +  // and perhaps not put the master and worker in the same file.
      +  //
      +  // It is also possible to get a bit fancier about logging, and
      +  // implement whatever custom logic is needed to prevent DoS
      +  // attacks and other bad behavior.
      +  //
      +  // See the options in the cluster documentation.
      +  //
      +  // The important thing is that the master does very little,
      +  // increasing our resilience to unexpected errors.
      +
      +  cluster.fork();
      +  cluster.fork();
      +
      +  cluster.on('disconnect', (worker) => {
      +    console.error('disconnect!');
      +    cluster.fork();
      +  });
      +
      +} else {
      +  // the worker
      +  //
      +  // This is where we put our bugs!
      +
      +  const domain = require('domain');
      +
      +  // See the cluster documentation for more details about using
      +  // worker processes to serve requests. How it works, caveats, etc.
      +
      +  const server = require('http').createServer((req, res) => {
      +    const d = domain.create();
      +    d.on('error', (er) => {
      +      console.error(`error ${er.stack}`);
      +
      +      // We're in dangerous territory!
      +      // By definition, something unexpected occurred,
      +      // which we probably didn't want.
      +      // Anything can happen now! Be very careful!
      +
      +      try {
      +        // Make sure we close down within 30 seconds
      +        const killtimer = setTimeout(() => {
      +          process.exit(1);
      +        }, 30000);
      +        // But don't keep the process open just for that!
      +        killtimer.unref();
      +
      +        // Stop taking new requests.
      +        server.close();
      +
      +        // Let the master know we're dead. This will trigger a
      +        // 'disconnect' in the cluster master, and then it will fork
      +        // a new worker.
      +        cluster.worker.disconnect();
      +
      +        // Try to send an error to the request that triggered the problem
      +        res.statusCode = 500;
      +        res.setHeader('content-type', 'text/plain');
      +        res.end('Oops, there was a problem!\n');
      +      } catch (er2) {
      +        // Oh well, not much we can do at this point.
      +        console.error(`Error sending 500! ${er2.stack}`);
      +      }
      +    });
      +
      +    // Because req and res were created before this domain existed,
      +    // we need to explicitly add them.
      +    // See the explanation of implicit vs explicit binding below.
      +    d.add(req);
      +    d.add(res);
      +
      +    // Now run the handler function in the domain.
      +    d.run(() => {
      +      handleRequest(req, res);
      +    });
      +  });
      +  server.listen(PORT);
      +}
      +
      +// This part is not important. Just an example routing thing.
      +// Put fancy application logic here.
      +function handleRequest(req, res) {
      +  switch (req.url) {
      +    case '/error':
      +      // We do some async stuff, and then...
      +      setTimeout(() => {
      +        // Whoops!
      +        flerb.bark();
      +      }, timeout);
      +      break;
      +    default:
      +      res.end('ok');
      +  }
      +}
      +

      Additions to Error objects#

      + +

      Any time an Error object is routed through a domain, a few extra fields +are added to it.

      +
        +
      • error.domain The domain that first handled the error.
      • +
      • error.domainEmitter The event emitter that emitted an 'error' event +with the error object.
      • +
      • error.domainBound The callback function which was bound to the +domain, and passed an error as its first argument.
      • +
      • error.domainThrown A boolean indicating whether the error was +thrown, emitted, or passed to a bound callback function.
      • +
      +

      Implicit binding#

      + +

      If domains are in use, then all new EventEmitter objects (including +Stream objects, requests, responses, etc.) will be implicitly bound to +the active domain at the time of their creation.

      +

      Additionally, callbacks passed to lowlevel event loop requests (such as +to fs.open(), or other callback-taking methods) will automatically be +bound to the active domain. If they throw, then the domain will catch +the error.

      +

      In order to prevent excessive memory usage, Domain objects themselves +are not implicitly added as children of the active domain. If they +were, then it would be too easy to prevent request and response objects +from being properly garbage collected.

      +

      To nest Domain objects as children of a parent Domain they must be +explicitly added.

      +

      Implicit binding routes thrown errors and 'error' events to the +Domain's 'error' event, but does not register the EventEmitter on the +Domain. +Implicit binding only takes care of thrown errors and 'error' events.

      +

      Explicit binding#

      + +

      Sometimes, the domain in use is not the one that ought to be used for a +specific event emitter. Or, the event emitter could have been created +in the context of one domain, but ought to instead be bound to some +other domain.

      +

      For example, there could be one domain in use for an HTTP server, but +perhaps we would like to have a separate domain to use for each request.

      +

      That is possible via explicit binding.

      +
      // Create a top-level domain for the server
      +const domain = require('domain');
      +const http = require('http');
      +const serverDomain = domain.create();
      +
      +serverDomain.run(() => {
      +  // Server is created in the scope of serverDomain
      +  http.createServer((req, res) => {
      +    // Req and res are also created in the scope of serverDomain
      +    // however, we'd prefer to have a separate domain for each request.
      +    // create it first thing, and add req and res to it.
      +    const reqd = domain.create();
      +    reqd.add(req);
      +    reqd.add(res);
      +    reqd.on('error', (er) => {
      +      console.error('Error', er, req.url);
      +      try {
      +        res.writeHead(500);
      +        res.end('Error occurred, sorry.');
      +      } catch (er2) {
      +        console.error('Error sending 500', er2, req.url);
      +      }
      +    });
      +  }).listen(1337);
      +});
      +

      domain.create()#

      + +

      Class: Domain#

      + +

      The Domain class encapsulates the functionality of routing errors and +uncaught exceptions to the active Domain object.

      +

      To handle the errors that it catches, listen to its 'error' event.

      +

      domain.members#

      + +

      An array of timers and event emitters that have been explicitly added +to the domain.

      +

      domain.add(emitter)#

      + +

      Explicitly adds an emitter to the domain. If any event handlers called by +the emitter throw an error, or if the emitter emits an 'error' event, it +will be routed to the domain's 'error' event, just like with implicit +binding.

      +

      This also works with timers that are returned from setInterval() and +setTimeout(). If their callback function throws, it will be caught by +the domain 'error' handler.

      +

      If the Timer or EventEmitter was already bound to a domain, it is removed +from that one, and bound to this one instead.

      +

      domain.bind(callback)#

      + +

      The returned function will be a wrapper around the supplied callback +function. When the returned function is called, any errors that are +thrown will be routed to the domain's 'error' event.

      +
      const d = domain.create();
      +
      +function readSomeFile(filename, cb) {
      +  fs.readFile(filename, 'utf8', d.bind((er, data) => {
      +    // If this throws, it will also be passed to the domain.
      +    return cb(er, data ? JSON.parse(data) : null);
      +  }));
      +}
      +
      +d.on('error', (er) => {
      +  // An error occurred somewhere. If we throw it now, it will crash the program
      +  // with the normal line number and stack message.
      +});
      +

      domain.enter()#

      +

      The enter() method is plumbing used by the run(), bind(), and +intercept() methods to set the active domain. It sets domain.active and +process.domain to the domain, and implicitly pushes the domain onto the domain +stack managed by the domain module (see domain.exit() for details on the +domain stack). The call to enter() delimits the beginning of a chain of +asynchronous calls and I/O operations bound to a domain.

      +

      Calling enter() changes only the active domain, and does not alter the domain +itself. enter() and exit() can be called an arbitrary number of times on a +single domain.

      +

      domain.exit()#

      +

      The exit() method exits the current domain, popping it off the domain stack. +Any time execution is going to switch to the context of a different chain of +asynchronous calls, it's important to ensure that the current domain is exited. +The call to exit() delimits either the end of or an interruption to the chain +of asynchronous calls and I/O operations bound to a domain.

      +

      If there are multiple, nested domains bound to the current execution context, +exit() will exit any domains nested within this domain.

      +

      Calling exit() changes only the active domain, and does not alter the domain +itself. enter() and exit() can be called an arbitrary number of times on a +single domain.

      +

      domain.intercept(callback)#

      + +

      This method is almost identical to domain.bind(callback). However, in +addition to catching thrown errors, it will also intercept Error +objects sent as the first argument to the function.

      +

      In this way, the common if (err) return callback(err); pattern can be replaced +with a single error handler in a single place.

      +
      const d = domain.create();
      +
      +function readSomeFile(filename, cb) {
      +  fs.readFile(filename, 'utf8', d.intercept((data) => {
      +    // Note, the first argument is never passed to the
      +    // callback since it is assumed to be the 'Error' argument
      +    // and thus intercepted by the domain.
      +
      +    // If this throws, it will also be passed to the domain
      +    // so the error-handling logic can be moved to the 'error'
      +    // event on the domain instead of being repeated throughout
      +    // the program.
      +    return cb(null, JSON.parse(data));
      +  }));
      +}
      +
      +d.on('error', (er) => {
      +  // An error occurred somewhere. If we throw it now, it will crash the program
      +  // with the normal line number and stack message.
      +});
      +

      domain.remove(emitter)#

      + +

      The opposite of domain.add(emitter). Removes domain handling from the +specified emitter.

      +

      domain.run(fn[, ...args])#

      + +

      Run the supplied function in the context of the domain, implicitly +binding all event emitters, timers, and lowlevel requests that are +created in that context. Optionally, arguments can be passed to +the function.

      +

      This is the most basic way to use a domain.

      +
      const domain = require('domain');
      +const fs = require('fs');
      +const d = domain.create();
      +d.on('error', (er) => {
      +  console.error('Caught error!', er);
      +});
      +d.run(() => {
      +  process.nextTick(() => {
      +    setTimeout(() => { // Simulating some various async stuff
      +      fs.open('non-existent file', 'r', (er, fd) => {
      +        if (er) throw er;
      +        // proceed...
      +      });
      +    }, 100);
      +  });
      +});
      +

      In this example, the d.on('error') handler will be triggered, rather +than crashing the program.

      +

      Domains and promises#

      +

      As of Node.js 8.0.0, the handlers of promises are run inside the domain in +which the call to .then() or .catch() itself was made:

      +
      const d1 = domain.create();
      +const d2 = domain.create();
      +
      +let p;
      +d1.run(() => {
      +  p = Promise.resolve(42);
      +});
      +
      +d2.run(() => {
      +  p.then((v) => {
      +    // running in d2
      +  });
      +});
      +

      A callback may be bound to a specific domain using domain.bind(callback):

      +
      const d1 = domain.create();
      +const d2 = domain.create();
      +
      +let p;
      +d1.run(() => {
      +  p = Promise.resolve(42);
      +});
      +
      +d2.run(() => {
      +  p.then(p.domain.bind((v) => {
      +    // running in d1
      +  }));
      +});
      +

      Domains will not interfere with the error handling mechanisms for +promises. In other words, no 'error' event will be emitted for unhandled +Promise rejections.

      +

      Errors#

      + + +

      Applications running in Node.js will generally experience four categories of +errors:

      +
        +
      • Standard JavaScript errors such as <EvalError>, <SyntaxError>, <RangeError>, +<ReferenceError>, <TypeError>, and <URIError>.
      • +
      • System errors triggered by underlying operating system constraints such +as attempting to open a file that does not exist or attempting to send data +over a closed socket.
      • +
      • User-specified errors triggered by application code.
      • +
      • AssertionErrors are a special class of error that can be triggered when +Node.js detects an exceptional logic violation that should never occur. These +are raised typically by the assert module.
      • +
      +

      All JavaScript and system errors raised by Node.js inherit from, or are +instances of, the standard JavaScript <Error> class and are guaranteed +to provide at least the properties available on that class.

      +

      Error propagation and interception#

      + +

      Node.js supports several mechanisms for propagating and handling errors that +occur while an application is running. How these errors are reported and +handled depends entirely on the type of Error and the style of the API that is +called.

      +

      All JavaScript errors are handled as exceptions that immediately generate +and throw an error using the standard JavaScript throw mechanism. These +are handled using the try…catch construct provided by the +JavaScript language.

      +
      // Throws with a ReferenceError because z is not defined.
      +try {
      +  const m = 1;
      +  const n = m + z;
      +} catch (err) {
      +  // Handle the error here.
      +}
      +

      Any use of the JavaScript throw mechanism will raise an exception that +must be handled using try…catch or the Node.js process will exit +immediately.

      +

      With few exceptions, Synchronous APIs (any blocking method that does not +accept a callback function, such as fs.readFileSync), will use throw +to report errors.

      +

      Errors that occur within Asynchronous APIs may be reported in multiple ways:

      +
        +
      • Most asynchronous methods that accept a callback function will accept an +Error object passed as the first argument to that function. If that first +argument is not null and is an instance of Error, then an error occurred +that should be handled.
      • +
      + +
      const fs = require('fs');
      +fs.readFile('a file that does not exist', (err, data) => {
      +  if (err) {
      +    console.error('There was an error reading the file!', err);
      +    return;
      +  }
      +  // Otherwise handle the data
      +});
      +
        +
      • +

        When an asynchronous method is called on an object that is an +EventEmitter, errors can be routed to that object's 'error' event.

        +
        const net = require('net');
        +const connection = net.connect('localhost');
        +
        +// Adding an 'error' event handler to a stream:
        +connection.on('error', (err) => {
        +  // If the connection is reset by the server, or if it can't
        +  // connect at all, or on any sort of error encountered by
        +  // the connection, the error will be sent here.
        +  console.error(err);
        +});
        +
        +connection.pipe(process.stdout);
        +
      • +
      • +

        A handful of typically asynchronous methods in the Node.js API may still +use the throw mechanism to raise exceptions that must be handled using +try…catch. There is no comprehensive list of such methods; please +refer to the documentation of each method to determine the appropriate +error handling mechanism required.

        +
      • +
      +

      The use of the 'error' event mechanism is most common for stream-based +and event emitter-based APIs, which themselves represent a series of +asynchronous operations over time (as opposed to a single operation that may +pass or fail).

      +

      For all EventEmitter objects, if an 'error' event handler is not +provided, the error will be thrown, causing the Node.js process to report an +uncaught exception and crash unless either: The domain module is +used appropriately or a handler has been registered for the +'uncaughtException' event.

      +
      const EventEmitter = require('events');
      +const ee = new EventEmitter();
      +
      +setImmediate(() => {
      +  // This will crash the process because no 'error' event
      +  // handler has been added.
      +  ee.emit('error', new Error('This will crash'));
      +});
      +

      Errors generated in this way cannot be intercepted using try…catch as +they are thrown after the calling code has already exited.

      +

      Developers must refer to the documentation for each method to determine +exactly how errors raised by those methods are propagated.

      +

      Error-first callbacks#

      + +

      Most asynchronous methods exposed by the Node.js core API follow an idiomatic +pattern referred to as an error-first callback. With this pattern, a callback +function is passed to the method as an argument. When the operation either +completes or an error is raised, the callback function is called with the +Error object (if any) passed as the first argument. If no error was raised, +the first argument will be passed as null.

      +
      const fs = require('fs');
      +
      +function errorFirstCallback(err, data) {
      +  if (err) {
      +    console.error('There was an error', err);
      +    return;
      +  }
      +  console.log(data);
      +}
      +
      +fs.readFile('/some/file/that/does-not-exist', errorFirstCallback);
      +fs.readFile('/some/file/that/does-exist', errorFirstCallback);
      +

      The JavaScript try…catch mechanism cannot be used to intercept errors +generated by asynchronous APIs. A common mistake for beginners is to try to +use throw inside an error-first callback:

      +
      // THIS WILL NOT WORK:
      +const fs = require('fs');
      +
      +try {
      +  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
      +    // Mistaken assumption: throwing here...
      +    if (err) {
      +      throw err;
      +    }
      +  });
      +} catch (err) {
      +  // This will not catch the throw!
      +  console.error(err);
      +}
      +

      This will not work because the callback function passed to fs.readFile() is +called asynchronously. By the time the callback has been called, the +surrounding code, including the try…catch block, will have already exited. +Throwing an error inside the callback can crash the Node.js process in most +cases. If domains are enabled, or a handler has been registered with +process.on('uncaughtException'), such errors can be intercepted.

      +

      Class: Error#

      + +

      A generic JavaScript <Error> object that does not denote any specific +circumstance of why the error occurred. Error objects capture a "stack trace" +detailing the point in the code at which the Error was instantiated, and may +provide a text description of the error.

      +

      All errors generated by Node.js, including all system and JavaScript errors, +will either be instances of, or inherit from, the Error class.

      +

      new Error(message)#

      + +

      Creates a new Error object and sets the error.message property to the +provided text message. If an object is passed as message, the text message +is generated by calling message.toString(). The error.stack property will +represent the point in the code at which new Error() was called. Stack traces +are dependent on V8's stack trace API. Stack traces extend only to either +(a) the beginning of synchronous code execution, or (b) the number of frames +given by the property Error.stackTraceLimit, whichever is smaller.

      +

      Error.captureStackTrace(targetObject[, constructorOpt])#

      + +

      Creates a .stack property on targetObject, which when accessed returns +a string representing the location in the code at which +Error.captureStackTrace() was called.

      +
      const myObject = {};
      +Error.captureStackTrace(myObject);
      +myObject.stack;  // Similar to `new Error().stack`
      +

      The first line of the trace will be prefixed with +${myObject.name}: ${myObject.message}.

      +

      The optional constructorOpt argument accepts a function. If given, all frames +above constructorOpt, including constructorOpt, will be omitted from the +generated stack trace.

      +

      The constructorOpt argument is useful for hiding implementation +details of error generation from the user. For instance:

      +
      function MyError() {
      +  Error.captureStackTrace(this, MyError);
      +}
      +
      +// Without passing MyError to captureStackTrace, the MyError
      +// frame would show up in the .stack property. By passing
      +// the constructor, we omit that frame, and retain all frames below it.
      +new MyError().stack;
      +

      Error.stackTraceLimit#

      + +

      The Error.stackTraceLimit property specifies the number of stack frames +collected by a stack trace (whether generated by new Error().stack or +Error.captureStackTrace(obj)).

      +

      The default value is 10 but may be set to any valid JavaScript number. Changes +will affect any stack trace captured after the value has been changed.

      +

      If set to a non-number value, or set to a negative number, stack traces will +not capture any frames.

      +

      error.code#

      + +

      The error.code property is a string label that identifies the kind of error. +error.code is the most stable way to identify an error. It will only change +between major versions of Node.js. In contrast, error.message strings may +change between any versions of Node.js. See Node.js error codes for details +about specific codes.

      +

      error.message#

      + +

      The error.message property is the string description of the error as set by +calling new Error(message). The message passed to the constructor will also +appear in the first line of the stack trace of the Error, however changing +this property after the Error object is created may not change the first +line of the stack trace (for example, when error.stack is read before this +property is changed).

      +
      const err = new Error('The message');
      +console.error(err.message);
      +// Prints: The message
      +

      error.stack#

      + +

      The error.stack property is a string describing the point in the code at which +the Error was instantiated.

      +
      Error: Things keep happening!
      +   at /home/gbusey/file.js:525:2
      +   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
      +   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
      +   at increaseSynergy (/home/gbusey/actors.js:701:6)
      +

      The first line is formatted as <error class name>: <error message>, and +is followed by a series of stack frames (each line beginning with "at "). +Each frame describes a call site within the code that lead to the error being +generated. V8 attempts to display a name for each function (by variable name, +function name, or object method name), but occasionally it will not be able to +find a suitable name. If V8 cannot determine a name for the function, only +location information will be displayed for that frame. Otherwise, the +determined function name will be displayed with location information appended +in parentheses.

      +

      Frames are only generated for JavaScript functions. If, for example, execution +synchronously passes through a C++ addon function called cheetahify which +itself calls a JavaScript function, the frame representing the cheetahify call +will not be present in the stack traces:

      +
      const cheetahify = require('./native-binding.node');
      +
      +function makeFaster() {
      +  // `cheetahify()` *synchronously* calls speedy.
      +  cheetahify(function speedy() {
      +    throw new Error('oh no!');
      +  });
      +}
      +
      +makeFaster();
      +// will throw:
      +//   /home/gbusey/file.js:6
      +//       throw new Error('oh no!');
      +//           ^
      +//   Error: oh no!
      +//       at speedy (/home/gbusey/file.js:6:11)
      +//       at makeFaster (/home/gbusey/file.js:5:3)
      +//       at Object.<anonymous> (/home/gbusey/file.js:10:1)
      +//       at Module._compile (module.js:456:26)
      +//       at Object.Module._extensions..js (module.js:474:10)
      +//       at Module.load (module.js:356:32)
      +//       at Function.Module._load (module.js:312:12)
      +//       at Function.Module.runMain (module.js:497:10)
      +//       at startup (node.js:119:16)
      +//       at node.js:906:3
      +

      The location information will be one of:

      +
        +
      • native, if the frame represents a call internal to V8 (as in [].forEach).
      • +
      • plain-filename.js:line:column, if the frame represents a call internal +to Node.js.
      • +
      • /absolute/path/to/file.js:line:column, if the frame represents a call in +a user program, or its dependencies.
      • +
      +

      The string representing the stack trace is lazily generated when the +error.stack property is accessed.

      +

      The number of frames captured by the stack trace is bounded by the smaller of +Error.stackTraceLimit or the number of available frames on the current event +loop tick.

      +

      Class: AssertionError#

      + +

      Indicates the failure of an assertion. For details, see +Class: assert.AssertionError.

      +

      Class: RangeError#

      + +

      Indicates that a provided argument was not within the set or range of +acceptable values for a function; whether that is a numeric range, or +outside the set of options for a given function parameter.

      +
      require('net').connect(-1);
      +// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"
      +

      Node.js will generate and throw RangeError instances immediately as a form +of argument validation.

      +

      Class: ReferenceError#

      + +

      Indicates that an attempt is being made to access a variable that is not +defined. Such errors commonly indicate typos in code, or an otherwise broken +program.

      +

      While client code may generate and propagate these errors, in practice, only V8 +will do so.

      +
      doesNotExist;
      +// Throws ReferenceError, doesNotExist is not a variable in this program.
      +

      Unless an application is dynamically generating and running code, +ReferenceError instances indicate a bug in the code or its dependencies.

      +

      Class: SyntaxError#

      + +

      Indicates that a program is not valid JavaScript. These errors may only be +generated and propagated as a result of code evaluation. Code evaluation may +happen as a result of eval, Function, require, or vm. These errors +are almost always indicative of a broken program.

      +
      try {
      +  require('vm').runInThisContext('binary ! isNotOk');
      +} catch (err) {
      +  // 'err' will be a SyntaxError.
      +}
      +

      SyntaxError instances are unrecoverable in the context that created them – +they may only be caught by other contexts.

      +

      Class: SystemError#

      + +

      Node.js generates system errors when exceptions occur within its runtime +environment. These usually occur when an application violates an operating +system constraint. For example, a system error will occur if an application +attempts to read a file that does not exist.

      +
        +
      • address <string> If present, the address to which a network connection +failed
      • +
      • code <string> The string error code
      • +
      • dest <string> If present, the file path destination when reporting a file +system error
      • +
      • errno <number> | <string> The system-provided error number
      • +
      • info <Object> If present, extra details about the error condition
      • +
      • message <string> A system-provided human-readable description of the error
      • +
      • path <string> If present, the file path when reporting a file system error
      • +
      • port <number> If present, the network connection port that is not available
      • +
      • syscall <string> The name of the system call that triggered the error
      • +
      +

      error.address#

      + +

      If present, error.address is a string describing the address to which a +network connection failed.

      +

      error.code#

      + +

      The error.code property is a string representing the error code.

      +

      error.dest#

      + +

      If present, error.dest is the file path destination when reporting a file +system error.

      +

      error.errno#

      + +

      The error.errno property is a number or a string. If it is a number, it is a +negative value which corresponds to the error code defined in +libuv Error handling. See the libuv errno.h header file +(deps/uv/include/uv/errno.h in the Node.js source tree) for details. In case +of a string, it is the same as error.code.

      +

      error.info#

      + +

      If present, error.info is an object with details about the error condition.

      +

      error.message#

      + +

      error.message is a system-provided human-readable description of the error.

      +

      error.path#

      + +

      If present, error.path is a string containing a relevant invalid pathname.

      +

      error.port#

      + +

      If present, error.port is the network connection port that is not available.

      +

      error.syscall#

      + +

      The error.syscall property is a string describing the syscall that failed.

      +

      Common system errors#

      +

      This is a list of system errors commonly-encountered when writing a Node.js +program. For a comprehensive list, see the errno(3) man page.

      +
        +
      • +

        EACCES (Permission denied): An attempt was made to access a file in a way +forbidden by its file access permissions.

        +
      • +
      • +

        EADDRINUSE (Address already in use): An attempt to bind a server +(net, http, or https) to a local address failed due to +another server on the local system already occupying that address.

        +
      • +
      • +

        ECONNREFUSED (Connection refused): No connection could be made because the +target machine actively refused it. This usually results from trying to +connect to a service that is inactive on the foreign host.

        +
      • +
      • +

        ECONNRESET (Connection reset by peer): A connection was forcibly closed by +a peer. This normally results from a loss of the connection on the remote +socket due to a timeout or reboot. Commonly encountered via the http +and net modules.

        +
      • +
      • +

        EEXIST (File exists): An existing file was the target of an operation that +required that the target not exist.

        +
      • +
      • +

        EISDIR (Is a directory): An operation expected a file, but the given +pathname was a directory.

        +
      • +
      • +

        EMFILE (Too many open files in system): Maximum number of +file descriptors allowable on the system has been reached, and +requests for another descriptor cannot be fulfilled until at least one +has been closed. This is encountered when opening many files at once in +parallel, especially on systems (in particular, macOS) where there is a low +file descriptor limit for processes. To remedy a low limit, run +ulimit -n 2048 in the same shell that will run the Node.js process.

        +
      • +
      • +

        ENOENT (No such file or directory): Commonly raised by fs operations +to indicate that a component of the specified pathname does not exist. No +entity (file or directory) could be found by the given path.

        +
      • +
      • +

        ENOTDIR (Not a directory): A component of the given pathname existed, but +was not a directory as expected. Commonly raised by fs.readdir.

        +
      • +
      • +

        ENOTEMPTY (Directory not empty): A directory with entries was the target +of an operation that requires an empty directory, usually fs.unlink.

        +
      • +
      • +

        ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either +EAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

        +
      • +
      • +

        EPERM (Operation not permitted): An attempt was made to perform an +operation that requires elevated privileges.

        +
      • +
      • +

        EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is +no process to read the data. Commonly encountered at the net and +http layers, indicative that the remote side of the stream being +written to has been closed.

        +
      • +
      • +

        ETIMEDOUT (Operation timed out): A connect or send request failed because +the connected party did not properly respond after a period of time. Usually +encountered by http or net. Often a sign that a socket.end() +was not properly called.

        +
      • +
      +

      Class: TypeError#

      + +

      Indicates that a provided argument is not an allowable type. For example, +passing a function to a parameter which expects a string would be a TypeError.

      +
      require('url').parse(() => { });
      +// Throws TypeError, since it expected a string.
      +

      Node.js will generate and throw TypeError instances immediately as a form +of argument validation.

      +

      Exceptions vs. errors#

      + +

      A JavaScript exception is a value that is thrown as a result of an invalid +operation or as the target of a throw statement. While it is not required +that these values are instances of Error or classes which inherit from +Error, all exceptions thrown by Node.js or the JavaScript runtime will be +instances of Error.

      +

      Some exceptions are unrecoverable at the JavaScript layer. Such exceptions +will always cause the Node.js process to crash. Examples include assert() +checks or abort() calls in the C++ layer.

      +

      OpenSSL errors#

      +

      Errors originating in crypto or tls are of class Error, and in addition to +the standard .code and .message properties, may have some additional +OpenSSL-specific properties.

      +

      error.opensslErrorStack#

      +

      An array of errors that can give context to where in the OpenSSL library an +error originates from.

      +

      error.function#

      +

      The OpenSSL function the error originates in.

      +

      error.library#

      +

      The OpenSSL library the error originates in.

      +

      error.reason#

      +

      A human-readable string describing the reason for the error.

      +

      +

      Node.js error codes#

      +

      +

      ERR_AMBIGUOUS_ARGUMENT#

      +

      A function argument is being used in a way that suggests that the function +signature may be misunderstood. This is thrown by the assert module when the +message parameter in assert.throws(block, message) matches the error message +thrown by block because that usage suggests that the user believes message +is the expected message rather than the message the AssertionError will +display if block does not throw.

      +

      +

      ERR_ARG_NOT_ITERABLE#

      +

      An iterable argument (i.e. a value that works with for...of loops) was +required, but not provided to a Node.js API.

      +

      +

      ERR_ASSERTION#

      +

      A special type of error that can be triggered whenever Node.js detects an +exceptional logic violation that should never occur. These are raised typically +by the assert module.

      +

      +

      ERR_ASYNC_CALLBACK#

      +

      An attempt was made to register something that is not a function as an +AsyncHooks callback.

      +

      +

      ERR_ASYNC_TYPE#

      +

      The type of an asynchronous resource was invalid. Users are also able +to define their own types if using the public embedder API.

      +

      +

      ERR_BROTLI_COMPRESSION_FAILED#

      +

      Data passed to a Brotli stream was not successfully compressed.

      +

      +

      ERR_BROTLI_INVALID_PARAM#

      +

      An invalid parameter key was passed during construction of a Brotli stream.

      +

      +

      ERR_BUFFER_CONTEXT_NOT_AVAILABLE#

      +

      An attempt was made to create a Node.js Buffer instance from addon or embedder +code, while in a JS engine Context that is not associated with a Node.js +instance. The data passed to the Buffer method will have been released +by the time the method returns.

      +

      When encountering this error, a possible alternative to creating a Buffer +instance is to create a normal Uint8Array, which only differs in the +prototype of the resulting object. Uint8Arrays are generally accepted in all +Node.js core APIs where Buffers are; they are available in all Contexts.

      +

      +

      ERR_BUFFER_OUT_OF_BOUNDS#

      +

      An operation outside the bounds of a Buffer was attempted.

      +

      +

      ERR_BUFFER_TOO_LARGE#

      +

      An attempt has been made to create a Buffer larger than the maximum allowed +size.

      +

      +

      ERR_CANNOT_WATCH_SIGINT#

      +

      Node.js was unable to watch for the SIGINT signal.

      +

      +

      ERR_CHILD_CLOSED_BEFORE_REPLY#

      +

      A child process was closed before the parent received a reply.

      +

      +

      ERR_CHILD_PROCESS_IPC_REQUIRED#

      +

      Used when a child process is being forked without specifying an IPC channel.

      +

      +

      ERR_CHILD_PROCESS_STDIO_MAXBUFFER#

      +

      Used when the main process is trying to read data from the child process's +STDERR/STDOUT, and the data's length is longer than the maxBuffer option.

      +

      +

      ERR_CONSOLE_WRITABLE_STREAM#

      +

      Console was instantiated without stdout stream, or Console has a +non-writable stdout or stderr stream.

      +

      +

      ERR_CONSTRUCT_CALL_REQUIRED#

      +

      A constructor for a class was called without new.

      +

      +

      ERR_CONSTRUCT_CALL_INVALID#

      + +

      A class constructor was called that is not callable.

      +

      +

      ERR_CPU_USAGE#

      +

      The native call from process.cpuUsage could not be processed.

      +

      +

      ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED#

      +

      A client certificate engine was requested that is not supported by the version +of OpenSSL being used.

      +

      +

      ERR_CRYPTO_ECDH_INVALID_FORMAT#

      +

      An invalid value for the format argument was passed to the crypto.ECDH() +class getPublicKey() method.

      +

      +

      ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY#

      +

      An invalid value for the key argument has been passed to the +crypto.ECDH() class computeSecret() method. It means that the public +key lies outside of the elliptic curve.

      +

      +

      ERR_CRYPTO_ENGINE_UNKNOWN#

      +

      An invalid crypto engine identifier was passed to +require('crypto').setEngine().

      +

      +

      ERR_CRYPTO_FIPS_FORCED#

      +

      The --force-fips command-line argument was used but there was an attempt +to enable or disable FIPS mode in the crypto module.

      +

      +

      ERR_CRYPTO_FIPS_UNAVAILABLE#

      +

      An attempt was made to enable or disable FIPS mode, but FIPS mode was not +available.

      +

      +

      ERR_CRYPTO_HASH_FINALIZED#

      +

      hash.digest() was called multiple times. The hash.digest() method must +be called no more than one time per instance of a Hash object.

      +

      +

      ERR_CRYPTO_HASH_UPDATE_FAILED#

      +

      hash.update() failed for any reason. This should rarely, if ever, happen.

      +

      +

      ERR_CRYPTO_INCOMPATIBLE_KEY#

      +

      The given crypto keys are incompatible with the attempted operation.

      +

      +

      ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS#

      +

      The selected public or private key encoding is incompatible with other options.

      +

      +

      ERR_CRYPTO_INVALID_DIGEST#

      +

      An invalid crypto digest algorithm was specified.

      +

      +

      ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE#

      +

      The given crypto key object's type is invalid for the attempted operation.

      +

      +

      ERR_CRYPTO_INVALID_STATE#

      +

      A crypto method was used on an object that was in an invalid state. For +instance, calling cipher.getAuthTag() before calling cipher.final().

      +

      +

      ERR_CRYPTO_PBKDF2_ERROR#

      +

      The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide +more details and therefore neither does Node.js.

      +

      +

      ERR_CRYPTO_SCRYPT_INVALID_PARAMETER#

      +

      One or more crypto.scrypt() or crypto.scryptSync() parameters are +outside their legal range.

      +

      +

      ERR_CRYPTO_SCRYPT_NOT_SUPPORTED#

      +

      Node.js was compiled without scrypt support. Not possible with the official +release binaries but can happen with custom builds, including distro builds.

      +

      +

      ERR_CRYPTO_SIGN_KEY_REQUIRED#

      +

      A signing key was not provided to the sign.sign() method.

      +

      +

      ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH#

      +

      crypto.timingSafeEqual() was called with Buffer, TypedArray, or +DataView arguments of different lengths.

      +

      +

      ERR_CRYPTO_UNKNOWN_CIPHER#

      +

      An unknown cipher was specified.

      +

      +

      ERR_CRYPTO_UNKNOWN_DH_GROUP#

      +

      An unknown Diffie-Hellman group name was given. See +crypto.getDiffieHellman() for a list of valid group names.

      +

      +

      ERR_DIR_CLOSED#

      +

      The fs.Dir was previously closed.

      +

      +

      ERR_DIR_CONCURRENT_OPERATION#

      + +

      A synchronous read or close call was attempted on an fs.Dir which has +ongoing asynchronous operations.

      +

      +

      ERR_DNS_SET_SERVERS_FAILED#

      +

      c-ares failed to set the DNS server.

      +

      +

      ERR_DOMAIN_CALLBACK_NOT_AVAILABLE#

      +

      The domain module was not usable since it could not establish the required +error handling hooks, because +process.setUncaughtExceptionCaptureCallback() had been called at an +earlier point in time.

      +

      +

      ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE#

      +

      process.setUncaughtExceptionCaptureCallback() could not be called +because the domain module has been loaded at an earlier point in time.

      +

      The stack trace is extended to include the point in time at which the +domain module had been loaded.

      +

      +

      ERR_ENCODING_INVALID_ENCODED_DATA#

      +

      Data provided to TextDecoder() API was invalid according to the encoding +provided.

      +

      +

      ERR_ENCODING_NOT_SUPPORTED#

      +

      Encoding provided to TextDecoder() API was not one of the +WHATWG Supported Encodings.

      +

      +

      ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE#

      +

      The JS execution context is not associated with a Node.js environment. +This may occur when Node.js is used as an embedded library and some hooks +for the JS engine are not set up properly.

      +

      +

      ERR_FALSY_VALUE_REJECTION#

      +

      A Promise that was callbackified via util.callbackify() was rejected with a +falsy value.

      +

      +

      ERR_FS_FILE_TOO_LARGE#

      +

      An attempt has been made to read a file whose size is larger than the maximum +allowed size for a Buffer.

      +

      +

      ERR_FS_INVALID_SYMLINK_TYPE#

      +

      An invalid symlink type was passed to the fs.symlink() or +fs.symlinkSync() methods.

      +

      +

      ERR_HTTP_HEADERS_SENT#

      +

      An attempt was made to add more headers after the headers had already been sent.

      +

      +

      ERR_HTTP_INVALID_HEADER_VALUE#

      +

      An invalid HTTP header value was specified.

      +

      +

      ERR_HTTP_INVALID_STATUS_CODE#

      +

      Status code was outside the regular status code range (100-999).

      +

      +

      ERR_HTTP_TRAILER_INVALID#

      +

      The Trailer header was set even though the transfer encoding does not support +that.

      +

      +

      ERR_HTTP2_ALTSVC_INVALID_ORIGIN#

      +

      HTTP/2 ALTSVC frames require a valid origin.

      +

      +

      ERR_HTTP2_ALTSVC_LENGTH#

      +

      HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

      +

      +

      ERR_HTTP2_CONNECT_AUTHORITY#

      +

      For HTTP/2 requests using the CONNECT method, the :authority pseudo-header +is required.

      +

      +

      ERR_HTTP2_CONNECT_PATH#

      +

      For HTTP/2 requests using the CONNECT method, the :path pseudo-header is +forbidden.

      +

      +

      ERR_HTTP2_CONNECT_SCHEME#

      +

      For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is +forbidden.

      +

      +

      ERR_HTTP2_ERROR#

      +

      A non-specific HTTP/2 error has occurred.

      +

      +

      ERR_HTTP2_GOAWAY_SESSION#

      +

      New HTTP/2 Streams may not be opened after the Http2Session has received a +GOAWAY frame from the connected peer.

      +

      +

      ERR_HTTP2_HEADERS_AFTER_RESPOND#

      +

      An additional headers was specified after an HTTP/2 response was initiated.

      +

      +

      ERR_HTTP2_HEADERS_SENT#

      +

      An attempt was made to send multiple response headers.

      +

      +

      ERR_HTTP2_HEADER_SINGLE_VALUE#

      +

      Multiple values were provided for an HTTP/2 header field that was required to +have only a single value.

      +

      +

      ERR_HTTP2_INFO_STATUS_NOT_ALLOWED#

      +

      Informational HTTP status codes (1xx) may not be set as the response status +code on HTTP/2 responses.

      +

      +

      ERR_HTTP2_INVALID_CONNECTION_HEADERS#

      +

      HTTP/1 connection specific headers are forbidden to be used in HTTP/2 +requests and responses.

      +

      +

      ERR_HTTP2_INVALID_HEADER_VALUE#

      +

      An invalid HTTP/2 header value was specified.

      +

      +

      ERR_HTTP2_INVALID_INFO_STATUS#

      +

      An invalid HTTP informational status code has been specified. Informational +status codes must be an integer between 100 and 199 (inclusive).

      +

      +

      ERR_HTTP2_INVALID_ORIGIN#

      +

      HTTP/2 ORIGIN frames require a valid origin.

      +

      +

      ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH#

      +

      Input Buffer and Uint8Array instances passed to the +http2.getUnpackedSettings() API must have a length that is a multiple of +six.

      +

      +

      ERR_HTTP2_INVALID_PSEUDOHEADER#

      +

      Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme, +and :method) may be used.

      +

      +

      ERR_HTTP2_INVALID_SESSION#

      +

      An action was performed on an Http2Session object that had already been +destroyed.

      +

      +

      ERR_HTTP2_INVALID_SETTING_VALUE#

      +

      An invalid value has been specified for an HTTP/2 setting.

      +

      +

      ERR_HTTP2_INVALID_STREAM#

      +

      An operation was performed on a stream that had already been destroyed.

      +

      +

      ERR_HTTP2_MAX_PENDING_SETTINGS_ACK#

      +

      Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is +required to send an acknowledgment that it has received and applied the new +SETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may +be sent at any given time. This error code is used when that limit has been +reached.

      +

      +

      ERR_HTTP2_NESTED_PUSH#

      +

      An attempt was made to initiate a new push stream from within a push stream. +Nested push streams are not permitted.

      +

      +

      ERR_HTTP2_NO_SOCKET_MANIPULATION#

      +

      An attempt was made to directly manipulate (read, write, pause, resume, etc.) a +socket attached to an Http2Session.

      +

      +

      ERR_HTTP2_ORIGIN_LENGTH#

      +

      HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

      +

      +

      ERR_HTTP2_OUT_OF_STREAMS#

      +

      The number of streams created on a single HTTP/2 session reached the maximum +limit.

      +

      +

      ERR_HTTP2_PAYLOAD_FORBIDDEN#

      +

      A message payload was specified for an HTTP response code for which a payload is +forbidden.

      +

      +

      ERR_HTTP2_PING_CANCEL#

      +

      An HTTP/2 ping was canceled.

      +

      +

      ERR_HTTP2_PING_LENGTH#

      +

      HTTP/2 ping payloads must be exactly 8 bytes in length.

      +

      +

      ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED#

      +

      An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header +key names that begin with the : prefix.

      +

      +

      ERR_HTTP2_PUSH_DISABLED#

      +

      An attempt was made to create a push stream, which had been disabled by the +client.

      +

      +

      ERR_HTTP2_SEND_FILE#

      +

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to +send a directory.

      +

      +

      ERR_HTTP2_SEND_FILE_NOSEEK#

      +

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to +send something other than a regular file, but offset or length options were +provided.

      +

      +

      ERR_HTTP2_SESSION_ERROR#

      +

      The Http2Session closed with a non-zero error code.

      +

      +

      ERR_HTTP2_SETTINGS_CANCEL#

      +

      The Http2Session settings canceled.

      +

      +

      ERR_HTTP2_SOCKET_BOUND#

      +

      An attempt was made to connect a Http2Session object to a net.Socket or +tls.TLSSocket that had already been bound to another Http2Session object.

      +

      +

      ERR_HTTP2_SOCKET_UNBOUND#

      +

      An attempt was made to use the socket property of an Http2Session that +has already been closed.

      +

      +

      ERR_HTTP2_STATUS_101#

      +

      Use of the 101 Informational status code is forbidden in HTTP/2.

      +

      +

      ERR_HTTP2_STATUS_INVALID#

      +

      An invalid HTTP status code has been specified. Status codes must be an integer +between 100 and 599 (inclusive).

      +

      +

      ERR_HTTP2_STREAM_CANCEL#

      +

      An Http2Stream was destroyed before any data was transmitted to the connected +peer.

      +

      +

      ERR_HTTP2_STREAM_ERROR#

      +

      A non-zero error code was been specified in an RST_STREAM frame.

      +

      +

      ERR_HTTP2_STREAM_SELF_DEPENDENCY#

      +

      When setting the priority for an HTTP/2 stream, the stream may be marked as +a dependency for a parent stream. This error code is used when an attempt is +made to mark a stream and dependent of itself.

      +

      +

      ERR_HTTP2_TRAILERS_ALREADY_SENT#

      +

      Trailing headers have already been sent on the Http2Stream.

      +

      +

      ERR_HTTP2_TRAILERS_NOT_READY#

      +

      The http2stream.sendTrailers() method cannot be called until after the +'wantTrailers' event is emitted on an Http2Stream object. The +'wantTrailers' event will only be emitted if the waitForTrailers option +is set for the Http2Stream.

      +

      +

      ERR_HTTP2_UNSUPPORTED_PROTOCOL#

      +

      http2.connect() was passed a URL that uses any protocol other than http: or +https:.

      +

      +

      ERR_INTERNAL_ASSERTION#

      +

      There was a bug in Node.js or incorrect usage of Node.js internals. +To fix the error, open an issue at https://github.com/nodejs/node/issues.

      +

      +

      ERR_INCOMPATIBLE_OPTION_PAIR#

      +

      An option pair is incompatible with each other and cannot be used at the same +time.

      +

      +

      ERR_INPUT_TYPE_NOT_ALLOWED#

      +

      Stability: 1 - Experimental

      +

      The --input-type flag was used to attempt to execute a file. This flag can +only be used with input via --eval, --print or STDIN.

      +

      +

      ERR_INSPECTOR_ALREADY_ACTIVATED#

      +

      While using the inspector module, an attempt was made to activate the +inspector when it already started to listen on a port. Use inspector.close() +before activating it on a different address.

      +

      +

      ERR_INSPECTOR_ALREADY_CONNECTED#

      +

      While using the inspector module, an attempt was made to connect when the +inspector was already connected.

      +

      +

      ERR_INSPECTOR_CLOSED#

      +

      While using the inspector module, an attempt was made to use the inspector +after the session had already closed.

      +

      +

      ERR_INSPECTOR_COMMAND#

      +

      An error occurred while issuing a command via the inspector module.

      +

      +

      ERR_INSPECTOR_NOT_ACTIVE#

      +

      The inspector is not active when inspector.waitForDebugger() is called.

      +

      +

      ERR_INSPECTOR_NOT_AVAILABLE#

      +

      The inspector module is not available for use.

      +

      +

      ERR_INSPECTOR_NOT_CONNECTED#

      +

      While using the inspector module, an attempt was made to use the inspector +before it was connected.

      +

      +

      ERR_INSPECTOR_NOT_WORKER#

      +

      An API was called on the main thread that can only be used from +the worker thread.

      +

      +

      ERR_INVALID_ADDRESS_FAMILY#

      +

      The provided address family is not understood by the Node.js API.

      +

      +

      ERR_INVALID_ARG_TYPE#

      +

      An argument of the wrong type was passed to a Node.js API.

      +

      +

      ERR_INVALID_ARG_VALUE#

      +

      An invalid or unsupported value was passed for a given argument.

      +

      +

      ERR_INVALID_ASYNC_ID#

      +

      An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id +less than -1 should never happen.

      +

      +

      ERR_INVALID_BUFFER_SIZE#

      +

      A swap was performed on a Buffer but its size was not compatible with the +operation.

      +

      +

      ERR_INVALID_CALLBACK#

      +

      A callback function was required but was not been provided to a Node.js API.

      +

      +

      ERR_INVALID_CHAR#

      +

      Invalid characters were detected in headers.

      +

      +

      ERR_INVALID_CURSOR_POS#

      +

      A cursor on a given stream cannot be moved to a specified row without a +specified column.

      +

      +

      ERR_INVALID_FD#

      +

      A file descriptor ('fd') was not valid (e.g. it was a negative value).

      +

      +

      ERR_INVALID_FD_TYPE#

      +

      A file descriptor ('fd') type was not valid.

      +

      +

      ERR_INVALID_FILE_URL_HOST#

      +

      A Node.js API that consumes file: URLs (such as certain functions in the +fs module) encountered a file URL with an incompatible host. This +situation can only occur on Unix-like systems where only localhost or an empty +host is supported.

      +

      +

      ERR_INVALID_FILE_URL_PATH#

      +

      A Node.js API that consumes file: URLs (such as certain functions in the +fs module) encountered a file URL with an incompatible path. The exact +semantics for determining whether a path can be used is platform-dependent.

      +

      +

      ERR_INVALID_HANDLE_TYPE#

      +

      An attempt was made to send an unsupported "handle" over an IPC communication +channel to a child process. See subprocess.send() and process.send() +for more information.

      +

      +

      ERR_INVALID_HTTP_TOKEN#

      +

      An invalid HTTP token was supplied.

      +

      +

      ERR_INVALID_IP_ADDRESS#

      +

      An IP address is not valid.

      +

      +

      ERR_INVALID_MODULE_SPECIFIER#

      +

      The imported module string is an invalid URL, package name, or package subpath +specifier.

      +

      +

      ERR_INVALID_OPT_VALUE#

      +

      An invalid or unexpected value was passed in an options object.

      +

      +

      ERR_INVALID_OPT_VALUE_ENCODING#

      +

      An invalid or unknown file encoding was passed.

      +

      +

      ERR_INVALID_PACKAGE_CONFIG#

      +

      An invalid package.json file was found which failed parsing.

      +

      +

      ERR_INVALID_PACKAGE_TARGET#

      +

      The package.json "exports" field contains an invalid target mapping +value for the attempted module resolution.

      +

      +

      ERR_INVALID_PERFORMANCE_MARK#

      +

      While using the Performance Timing API (perf_hooks), a performance mark is +invalid.

      +

      +

      ERR_INVALID_PROTOCOL#

      +

      An invalid options.protocol was passed to http.request().

      +

      +

      ERR_INVALID_REPL_EVAL_CONFIG#

      +

      Both breakEvalOnSigint and eval options were set in the REPL config, +which is not supported.

      +

      +

      ERR_INVALID_REPL_INPUT#

      +

      The input may not be used in the REPL. All prohibited inputs are +documented in the REPL's documentation.

      +

      +

      ERR_INVALID_RETURN_PROPERTY#

      +

      Thrown in case a function option does not provide a valid value for one of its +returned object properties on execution.

      +

      +

      ERR_INVALID_RETURN_PROPERTY_VALUE#

      +

      Thrown in case a function option does not provide an expected value +type for one of its returned object properties on execution.

      +

      +

      ERR_INVALID_RETURN_VALUE#

      +

      Thrown in case a function option does not return an expected value +type on execution, such as when a function is expected to return a promise.

      +

      +

      ERR_INVALID_SYNC_FORK_INPUT#

      +

      A Buffer, TypedArray, DataView or string was provided as stdio input to +an asynchronous fork. See the documentation for the child_process module +for more information.

      +

      +

      ERR_INVALID_THIS#

      +

      A Node.js API function was called with an incompatible this value.

      +
      const urlSearchParams = new URLSearchParams('foo=bar&baz=new');
      +
      +const buf = Buffer.alloc(1);
      +urlSearchParams.has.call(buf, 'foo');
      +// Throws a TypeError with code 'ERR_INVALID_THIS'
      +

      +

      ERR_INVALID_TRANSFER_OBJECT#

      +

      An invalid transfer object was passed to postMessage().

      +

      +

      ERR_INVALID_TUPLE#

      +

      An element in the iterable provided to the WHATWG +URLSearchParams constructor did not +represent a [name, value] tuple – that is, if an element is not iterable, or +does not consist of exactly two elements.

      +

      +

      ERR_INVALID_URI#

      +

      An invalid URI was passed.

      +

      +

      ERR_INVALID_URL#

      +

      An invalid URL was passed to the WHATWG +URL constructor to be parsed. The thrown error object +typically has an additional property 'input' that contains the URL that failed +to parse.

      +

      +

      ERR_INVALID_URL_SCHEME#

      +

      An attempt was made to use a URL of an incompatible scheme (protocol) for a +specific purpose. It is only used in the WHATWG URL API support in the +fs module (which only accepts URLs with 'file' scheme), but may be used +in other Node.js APIs as well in the future.

      +

      +

      ERR_IPC_CHANNEL_CLOSED#

      +

      An attempt was made to use an IPC communication channel that was already closed.

      +

      +

      ERR_IPC_DISCONNECTED#

      +

      An attempt was made to disconnect an IPC communication channel that was already +disconnected. See the documentation for the child_process module +for more information.

      +

      +

      ERR_IPC_ONE_PIPE#

      +

      An attempt was made to create a child Node.js process using more than one IPC +communication channel. See the documentation for the child_process module +for more information.

      +

      +

      ERR_IPC_SYNC_FORK#

      +

      An attempt was made to open an IPC communication channel with a synchronously +forked Node.js process. See the documentation for the child_process module +for more information.

      +

      +

      ERR_MANIFEST_ASSERT_INTEGRITY#

      +

      An attempt was made to load a resource, but the resource did not match the +integrity defined by the policy manifest. See the documentation for policy +manifests for more information.

      +

      +

      ERR_MANIFEST_DEPENDENCY_MISSING#

      +

      An attempt was made to load a resource, but the resource was not listed as a +dependency from the location that attempted to load it. See the documentation +for policy manifests for more information.

      +

      +

      ERR_MANIFEST_INTEGRITY_MISMATCH#

      +

      An attempt was made to load a policy manifest, but the manifest had multiple +entries for a resource which did not match each other. Update the manifest +entries to match in order to resolve this error. See the documentation for +policy manifests for more information.

      +

      +

      ERR_MANIFEST_INVALID_RESOURCE_FIELD#

      +

      A policy manifest resource had an invalid value for one of its fields. Update +the manifest entry to match in order to resolve this error. See the +documentation for policy manifests for more information.

      +

      +

      ERR_MANIFEST_PARSE_POLICY#

      +

      An attempt was made to load a policy manifest, but the manifest was unable to +be parsed. See the documentation for policy manifests for more information.

      +

      +

      ERR_MANIFEST_TDZ#

      +

      An attempt was made to read from a policy manifest, but the manifest +initialization has not yet taken place. This is likely a bug in Node.js.

      +

      +

      ERR_MANIFEST_UNKNOWN_ONERROR#

      +

      A policy manifest was loaded, but had an unknown value for its "onerror" +behavior. See the documentation for policy manifests for more information.

      +

      +

      ERR_MEMORY_ALLOCATION_FAILED#

      +

      An attempt was made to allocate memory (usually in the C++ layer) but it +failed.

      +

      +

      ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE#

      + +

      A message posted to a MessagePort could not be deserialized in the target +vm Context. Not all Node.js objects can be successfully instantiated in +any context at this time, and attempting to transfer them using postMessage() +can fail on the receiving side in that case.

      +

      +

      ERR_METHOD_NOT_IMPLEMENTED#

      +

      A method is required but not implemented.

      +

      +

      ERR_MISSING_ARGS#

      +

      A required argument of a Node.js API was not passed. This is only used for +strict compliance with the API specification (which in some cases may accept +func(undefined) but not func()). In most native Node.js APIs, +func(undefined) and func() are treated identically, and the +ERR_INVALID_ARG_TYPE error code may be used instead.

      +

      +

      ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK#

      +

      Stability: 1 - Experimental

      +

      An ES Module loader hook specified format: 'dynamic' but did not provide +a dynamicInstantiate hook.

      +

      +

      ERR_MISSING_OPTION#

      +

      For APIs that accept options objects, some options might be mandatory. This code +is thrown if a required option is missing.

      +

      +

      ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST#

      +

      An object that needs to be explicitly listed in the transferList argument +was found in the object passed to a postMessage() call, but not provided in +the transferList for that call. Usually, this is a MessagePort.

      +

      +

      ERR_MISSING_PASSPHRASE#

      +

      An attempt was made to read an encrypted key without specifying a passphrase.

      +

      +

      ERR_MISSING_PLATFORM_FOR_WORKER#

      +

      The V8 platform used by this instance of Node.js does not support creating +Workers. This is caused by lack of embedder support for Workers. In particular, +this error will not occur with standard builds of Node.js.

      +

      +

      ERR_MODULE_NOT_FOUND#

      +

      Stability: 1 - Experimental

      +

      An ES Module could not be resolved.

      +

      +

      ERR_MULTIPLE_CALLBACK#

      +

      A callback was called more than once.

      +

      A callback is almost always meant to only be called once as the query +can either be fulfilled or rejected but not both at the same time. The latter +would be possible by calling a callback more than once.

      +

      +

      ERR_NAPI_CONS_FUNCTION#

      +

      While using N-API, a constructor passed was not a function.

      +

      +

      ERR_NAPI_INVALID_DATAVIEW_ARGS#

      +

      While calling napi_create_dataview(), a given offset was outside the bounds +of the dataview or offset + length was larger than a length of given buffer.

      +

      +

      ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT#

      +

      While calling napi_create_typedarray(), the provided offset was not a +multiple of the element size.

      +

      +

      ERR_NAPI_INVALID_TYPEDARRAY_LENGTH#

      +

      While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.

      +

      +

      ERR_NAPI_TSFN_CALL_JS#

      +

      An error occurred while invoking the JavaScript portion of the thread-safe +function.

      +

      +

      ERR_NAPI_TSFN_GET_UNDEFINED#

      +

      An error occurred while attempting to retrieve the JavaScript undefined +value.

      +

      +

      ERR_NAPI_TSFN_START_IDLE_LOOP#

      +

      On the main thread, values are removed from the queue associated with the +thread-safe function in an idle loop. This error indicates that an error +has occurred when attempting to start the loop.

      +

      +

      ERR_NAPI_TSFN_STOP_IDLE_LOOP#

      +

      Once no more items are left in the queue, the idle loop must be suspended. This +error indicates that the idle loop has failed to stop.

      +

      +

      ERR_NO_CRYPTO#

      +

      An attempt was made to use crypto features while Node.js was not compiled with +OpenSSL crypto support.

      +

      +

      ERR_NO_ICU#

      +

      An attempt was made to use features that require ICU, but Node.js was not +compiled with ICU support.

      +

      +

      ERR_NON_CONTEXT_AWARE_DISABLED#

      +

      A non-context-aware native addon was loaded in a process that disallows them.

      +

      +

      ERR_OUT_OF_RANGE#

      +

      A given value is out of the accepted range.

      +

      +

      ERR_PACKAGE_IMPORT_NOT_DEFINED#

      +

      The package.json "imports" field does not define the given internal +package specifier mapping.

      +

      +

      ERR_PACKAGE_PATH_NOT_EXPORTED#

      +

      The package.json "exports" field does not export the requested subpath. +Because exports are encapsulated, private internal modules that are not exported +cannot be imported through the package resolution, unless using an absolute URL.

      +

      +

      ERR_PROTO_ACCESS#

      +

      Accessing Object.prototype.__proto__ has been forbidden using +--disable-proto=throw. Object.getPrototypeOf and +Object.setPrototypeOf should be used to get and set the prototype of an +object.

      +

      +

      ERR_REQUIRE_ESM#

      +

      Stability: 1 - Experimental

      +

      An attempt was made to require() an ES Module.

      +

      +

      ERR_SCRIPT_EXECUTION_INTERRUPTED#

      +

      Script execution was interrupted by SIGINT (For example, +Ctrl+C was pressed.)

      +

      +

      ERR_SCRIPT_EXECUTION_TIMEOUT#

      +

      Script execution timed out, possibly due to bugs in the script being executed.

      +

      +

      ERR_SERVER_ALREADY_LISTEN#

      +

      The server.listen() method was called while a net.Server was already +listening. This applies to all instances of net.Server, including HTTP, HTTPS, +and HTTP/2 Server instances.

      +

      +

      ERR_SERVER_NOT_RUNNING#

      +

      The server.close() method was called when a net.Server was not +running. This applies to all instances of net.Server, including HTTP, HTTPS, +and HTTP/2 Server instances.

      +

      +

      ERR_SOCKET_ALREADY_BOUND#

      +

      An attempt was made to bind a socket that has already been bound.

      +

      +

      ERR_SOCKET_BAD_BUFFER_SIZE#

      +

      An invalid (negative) size was passed for either the recvBufferSize or +sendBufferSize options in dgram.createSocket().

      +

      +

      ERR_SOCKET_BAD_PORT#

      +

      An API function expecting a port >= 0 and < 65536 received an invalid value.

      +

      +

      ERR_SOCKET_BAD_TYPE#

      +

      An API function expecting a socket type (udp4 or udp6) received an invalid +value.

      +

      +

      ERR_SOCKET_BUFFER_SIZE#

      +

      While using dgram.createSocket(), the size of the receive or send Buffer +could not be determined.

      +

      +

      ERR_SOCKET_CANNOT_SEND#

      +

      Data could be sent on a socket.

      +

      +

      ERR_SOCKET_CLOSED#

      +

      An attempt was made to operate on an already closed socket.

      +

      +

      ERR_SOCKET_DGRAM_IS_CONNECTED#

      +

      A dgram.connect() call was made on an already connected socket.

      +

      +

      ERR_SOCKET_DGRAM_NOT_CONNECTED#

      +

      A dgram.disconnect() or dgram.remoteAddress() call was made on a +disconnected socket.

      +

      +

      ERR_SOCKET_DGRAM_NOT_RUNNING#

      +

      A call was made and the UDP subsystem was not running.

      +

      +

      ERR_SRI_PARSE#

      +

      A string was provided for a Subresource Integrity check, but was unable to be +parsed. Check the format of integrity attributes by looking at the +Subresource Integrity specification.

      +

      +

      ERR_STREAM_CANNOT_PIPE#

      +

      An attempt was made to call stream.pipe() on a Writable stream.

      +

      +

      ERR_STREAM_DESTROYED#

      +

      A stream method was called that cannot complete because the stream was +destroyed using stream.destroy().

      +

      +

      ERR_STREAM_NULL_VALUES#

      +

      An attempt was made to call stream.write() with a null chunk.

      +

      +

      ERR_STREAM_PREMATURE_CLOSE#

      +

      An error returned by stream.finished() and stream.pipeline(), when a stream +or a pipeline ends non gracefully with no explicit error.

      +

      +

      ERR_STREAM_PUSH_AFTER_EOF#

      +

      An attempt was made to call stream.push() after a null(EOF) had been +pushed to the stream.

      +

      +

      ERR_STREAM_UNSHIFT_AFTER_END_EVENT#

      +

      An attempt was made to call stream.unshift() after the 'end' event was +emitted.

      +

      +

      ERR_STREAM_WRAP#

      +

      Prevents an abort if a string decoder was set on the Socket or if the decoder +is in objectMode.

      +
      const Socket = require('net').Socket;
      +const instance = new Socket();
      +
      +instance.setEncoding('utf8');
      +

      +

      ERR_STREAM_WRITE_AFTER_END#

      +

      An attempt was made to call stream.write() after stream.end() has been +called.

      +

      +

      ERR_STRING_TOO_LONG#

      +

      An attempt has been made to create a string longer than the maximum allowed +length.

      +

      +

      ERR_SYNTHETIC#

      +

      An artificial error object used to capture the call stack for diagnostic +reports.

      +

      +

      ERR_SYSTEM_ERROR#

      +

      An unspecified or non-specific system error has occurred within the Node.js +process. The error object will have an err.info object property with +additional details.

      +

      +

      ERR_TLS_CERT_ALTNAME_INVALID#

      +

      While using TLS, the host name/IP of the peer did not match any of the +subjectAltNames in its certificate.

      +

      +

      ERR_TLS_DH_PARAM_SIZE#

      +

      While using TLS, the parameter offered for the Diffie-Hellman (DH) +key-agreement protocol is too small. By default, the key length must be greater +than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly +recommended to use 2048 bits or larger for stronger security.

      +

      +

      ERR_TLS_HANDSHAKE_TIMEOUT#

      +

      A TLS/SSL handshake timed out. In this case, the server must also abort the +connection.

      +

      +

      ERR_TLS_INVALID_CONTEXT#

      + +

      The context must be a SecureContext.

      +

      +

      ERR_TLS_INVALID_STATE#

      + +

      The TLS socket must be connected and securily established. Ensure the 'secure' +event is emitted before continuing.

      +

      +

      ERR_TLS_INVALID_PROTOCOL_METHOD#

      +

      The specified secureProtocol method is invalid. It is either unknown, or +disabled because it is insecure.

      +

      +

      ERR_TLS_INVALID_PROTOCOL_VERSION#

      +

      Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.

      +

      +

      ERR_TLS_PROTOCOL_VERSION_CONFLICT#

      +

      Attempting to set a TLS protocol minVersion or maxVersion conflicts with an +attempt to set the secureProtocol explicitly. Use one mechanism or the other.

      +

      +

      ERR_TLS_RENEGOTIATION_DISABLED#

      +

      An attempt was made to renegotiate TLS on a socket instance with TLS disabled.

      +

      +

      ERR_TLS_REQUIRED_SERVER_NAME#

      +

      While using TLS, the server.addContext() method was called without providing +a host name in the first parameter.

      +

      +

      ERR_TLS_SESSION_ATTACK#

      +

      An excessive amount of TLS renegotiations is detected, which is a potential +vector for denial-of-service attacks.

      +

      +

      ERR_TLS_SNI_FROM_SERVER#

      +

      An attempt was made to issue Server Name Indication from a TLS server-side +socket, which is only valid from a client.

      +

      +

      ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED#

      +

      Failed to set PSK identity hint. Hint may be too long.

      +

      +

      ERR_TRACE_EVENTS_CATEGORY_REQUIRED#

      +

      The trace_events.createTracing() method requires at least one trace event +category.

      +

      +

      ERR_TRACE_EVENTS_UNAVAILABLE#

      +

      The trace_events module could not be loaded because Node.js was compiled with +the --without-v8-platform flag.

      +

      +

      ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER#

      +

      A SharedArrayBuffer whose memory is not managed by the JavaScript engine +or by Node.js was encountered during serialization. Such a SharedArrayBuffer +cannot be serialized.

      +

      This can only happen when native addons create SharedArrayBuffers in +"externalized" mode, or put existing SharedArrayBuffer into externalized mode.

      +

      +

      ERR_TRANSFORM_ALREADY_TRANSFORMING#

      +

      A Transform stream finished while it was still transforming.

      +

      +

      ERR_TRANSFORM_WITH_LENGTH_0#

      +

      A Transform stream finished with data still in the write buffer.

      +

      +

      ERR_TTY_INIT_FAILED#

      +

      The initialization of a TTY failed due to a system error.

      +

      +

      ERR_UNAVAILABLE_DURING_EXIT#

      +

      Function was called within a process.on('exit') handler that shouldn't be +called within process.on('exit') handler.

      +

      +

      ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET#

      +

      process.setUncaughtExceptionCaptureCallback() was called twice, +without first resetting the callback to null.

      +

      This error is designed to prevent accidentally overwriting a callback registered +from another module.

      +

      +

      ERR_UNESCAPED_CHARACTERS#

      +

      A string that contained unescaped characters was received.

      +

      +

      ERR_UNHANDLED_ERROR#

      +

      An unhandled error occurred (for instance, when an 'error' event is emitted +by an EventEmitter but an 'error' handler is not registered).

      +

      +

      ERR_UNKNOWN_BUILTIN_MODULE#

      +

      Used to identify a specific kind of internal Node.js error that should not +typically be triggered by user code. Instances of this error point to an +internal bug within the Node.js binary itself.

      +

      +

      ERR_UNKNOWN_CREDENTIAL#

      +

      A Unix group or user identifier that does not exist was passed.

      +

      +

      ERR_UNKNOWN_ENCODING#

      +

      An invalid or unknown encoding option was passed to an API.

      +

      +

      ERR_UNKNOWN_FILE_EXTENSION#

      +

      Stability: 1 - Experimental

      +

      An attempt was made to load a module with an unknown or unsupported file +extension.

      +

      +

      ERR_UNKNOWN_MODULE_FORMAT#

      +

      Stability: 1 - Experimental

      +

      An attempt was made to load a module with an unknown or unsupported format.

      +

      +

      ERR_UNKNOWN_SIGNAL#

      +

      An invalid or unknown process signal was passed to an API expecting a valid +signal (such as subprocess.kill()).

      +

      +

      ERR_UNSUPPORTED_DIR_IMPORT#

      +

      import a directory URL is unsupported. Instead, +self-reference a package using its name and define a custom subpath in +the "exports" field of the package.json file.

      + +
      import './'; // unsupported
      +import './index.js'; // supported
      +import 'package-name'; // supported
      +

      +

      ERR_UNSUPPORTED_ESM_URL_SCHEME#

      +

      import with URL schemes other than file and data is unsupported.

      +

      +

      ERR_VALID_PERFORMANCE_ENTRY_TYPE#

      +

      While using the Performance Timing API (perf_hooks), no valid performance +entry types were found.

      +

      +

      ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING#

      +

      A dynamic import callback was not specified.

      +

      +

      ERR_VM_MODULE_ALREADY_LINKED#

      +

      The module attempted to be linked is not eligible for linking, because of one of +the following reasons:

      +
        +
      • It has already been linked (linkingStatus is 'linked')
      • +
      • It is being linked (linkingStatus is 'linking')
      • +
      • Linking has failed for this module (linkingStatus is 'errored')
      • +
      +

      +

      ERR_VM_MODULE_CACHED_DATA_REJECTED#

      +

      The cachedData option passed to a module constructor is invalid.

      +

      +

      ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA#

      +

      Cached data cannot be created for modules which have already been evaluated.

      +

      +

      ERR_VM_MODULE_DIFFERENT_CONTEXT#

      +

      The module being returned from the linker function is from a different context +than the parent module. Linked modules must share the same context.

      +

      +

      ERR_VM_MODULE_LINKING_ERRORED#

      +

      The linker function returned a module for which linking has failed.

      +

      +

      ERR_VM_MODULE_NOT_MODULE#

      +

      The fulfilled value of a linking promise is not a vm.Module object.

      +

      +

      ERR_VM_MODULE_STATUS#

      +

      The current module's status does not allow for this operation. The specific +meaning of the error depends on the specific function.

      +

      +

      ERR_WASI_ALREADY_STARTED#

      +

      The WASI instance has already started.

      +

      +

      ERR_WASI_NOT_STARTED#

      +

      The WASI instance has not been started.

      +

      +

      ERR_WORKER_INIT_FAILED#

      +

      The Worker initialization failed.

      +

      +

      ERR_WORKER_INVALID_EXEC_ARGV#

      +

      The execArgv option passed to the Worker constructor contains +invalid flags.

      +

      +

      ERR_WORKER_NOT_RUNNING#

      +

      An operation failed because the Worker instance is not currently running.

      +

      +

      ERR_WORKER_OUT_OF_MEMORY#

      +

      The Worker instance terminated because it reached its memory limit.

      +

      +

      ERR_WORKER_PATH#

      +

      The path for the main script of a worker is neither an absolute path +nor a relative path starting with ./ or ../.

      +

      +

      ERR_WORKER_UNSERIALIZABLE_ERROR#

      +

      All attempts at serializing an uncaught exception from a worker thread failed.

      +

      +

      ERR_WORKER_UNSUPPORTED_EXTENSION#

      +

      The pathname used for the main script of a worker has an +unknown file extension.

      +

      +

      ERR_WORKER_UNSUPPORTED_OPERATION#

      +

      The requested functionality is not supported in worker threads.

      +

      +

      ERR_ZLIB_INITIALIZATION_FAILED#

      +

      Creation of a zlib object failed due to incorrect configuration.

      +

      +

      HPE_HEADER_OVERFLOW#

      + +

      Too much HTTP header data was received. In order to protect against malicious or +malconfigured clients, if more than 8KB of HTTP header data is received then +HTTP parsing will abort without a request or response object being created, and +an Error with this code will be emitted.

      +

      +

      HPE_UNEXPECTED_CONTENT_LENGTH#

      +

      Server is sending both a Content-Length header and Transfer-Encoding: chunked.

      +

      Transfer-Encoding: chunked allows the server to maintain an HTTP persistent +connection for dynamically generated content. +In this case, the Content-Length HTTP header cannot be used.

      +

      Use Content-Length or Transfer-Encoding: chunked.

      +

      +

      MODULE_NOT_FOUND#

      + +

      A module file could not be resolved while attempting a require() or +import operation.

      +

      Legacy Node.js error codes#

      +

      Stability: 0 - Deprecated. These error codes are either inconsistent, or have +been removed.

      +

      +

      ERR_CANNOT_TRANSFER_OBJECT#

      + +

      The value passed to postMessage() contained an object that is not supported +for transferring.

      +

      +

      ERR_CLOSED_MESSAGE_PORT#

      + +

      There was an attempt to use a MessagePort instance in a closed +state, usually after .close() has been called.

      +

      +

      ERR_CRYPTO_HASH_DIGEST_NO_UTF16#

      + +

      The UTF-16 encoding was used with hash.digest(). While the +hash.digest() method does allow an encoding argument to be passed in, +causing the method to return a string rather than a Buffer, the UTF-16 +encoding (e.g. ucs or utf16le) is not supported.

      +

      +

      ERR_HTTP2_FRAME_ERROR#

      + +

      Used when a failure occurs sending an individual frame on the HTTP/2 +session.

      +

      +

      ERR_HTTP2_HEADERS_OBJECT#

      + +

      Used when an HTTP/2 Headers Object is expected.

      +

      +

      ERR_HTTP2_HEADER_REQUIRED#

      + +

      Used when a required header is missing in an HTTP/2 message.

      +

      +

      ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND#

      + +

      HTTP/2 informational headers must only be sent prior to calling the +Http2Stream.prototype.respond() method.

      +

      +

      ERR_HTTP2_STREAM_CLOSED#

      + +

      Used when an action has been performed on an HTTP/2 Stream that has already +been closed.

      +

      +

      ERR_HTTP_INVALID_CHAR#

      + +

      Used when an invalid character is found in an HTTP response status message +(reason phrase).

      +

      +

      ERR_INDEX_OUT_OF_RANGE#

      + +

      A given index was out of the accepted range (e.g. negative offsets).

      +

      +

      ERR_NAPI_CONS_PROTOTYPE_OBJECT#

      + +

      Used by the N-API when Constructor.prototype is not an object.

      +

      +

      ERR_NO_LONGER_SUPPORTED#

      +

      A Node.js API was called in an unsupported manner, such as +Buffer.write(string, encoding, offset[, length]).

      +

      +

      ERR_OUTOFMEMORY#

      + +

      Used generically to identify that an operation caused an out of memory +condition.

      +

      +

      ERR_PARSE_HISTORY_DATA#

      + +

      The repl module was unable to parse data from the REPL history file.

      +

      +

      ERR_STDERR_CLOSE#

      + +

      An attempt was made to close the process.stderr stream. By design, Node.js +does not allow stdout or stderr streams to be closed by user code.

      +

      +

      ERR_STDOUT_CLOSE#

      + +

      An attempt was made to close the process.stdout stream. By design, Node.js +does not allow stdout or stderr streams to be closed by user code.

      +

      +

      ERR_STREAM_READ_NOT_IMPLEMENTED#

      + +

      Used when an attempt is made to use a readable stream that has not implemented +readable._read().

      +

      +

      ERR_TLS_RENEGOTIATION_FAILED#

      + +

      Used when a TLS renegotiation request has failed in a non-specific way.

      +

      +

      ERR_UNKNOWN_BUILTIN_MODULE#

      + +

      The 'ERR_UNKNOWN_BUILTIN_MODULE' error code is used to identify a specific +kind of internal Node.js error that should not typically be triggered by user +code. Instances of this error point to an internal bug within the Node.js +binary itself.

      +

      +

      ERR_UNKNOWN_STDIN_TYPE#

      + +

      An attempt was made to launch a Node.js process with an unknown stdin file +type. This error is usually an indication of a bug within Node.js itself, +although it is possible for user code to trigger it.

      +

      +

      ERR_UNKNOWN_STREAM_TYPE#

      + +

      An attempt was made to launch a Node.js process with an unknown stdout or +stderr file type. This error is usually an indication of a bug within Node.js +itself, although it is possible for user code to trigger it.

      +

      +

      ERR_V8BREAKITERATOR#

      +

      The V8 BreakIterator API was used but the full ICU data set is not installed.

      +

      +

      ERR_VALUE_OUT_OF_RANGE#

      + +

      Used when a given value is out of the accepted range.

      +

      +

      ERR_VM_MODULE_NOT_LINKED#

      +

      The module must be successfully linked before instantiation.

      +

      +

      ERR_ZLIB_BINDING_CLOSED#

      + +

      Used when an attempt is made to use a zlib object after it has already been +closed.

      +

      Events#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/events.js

      +

      Much of the Node.js core API is built around an idiomatic asynchronous +event-driven architecture in which certain kinds of objects (called "emitters") +emit named events that cause Function objects ("listeners") to be called.

      +

      For instance: a net.Server object emits an event each time a peer +connects to it; a fs.ReadStream emits an event when the file is opened; +a stream emits an event whenever data is available to be read.

      +

      All objects that emit events are instances of the EventEmitter class. These +objects expose an eventEmitter.on() function that allows one or more +functions to be attached to named events emitted by the object. Typically, +event names are camel-cased strings but any valid JavaScript property key +can be used.

      +

      When the EventEmitter object emits an event, all of the functions attached +to that specific event are called synchronously. Any values returned by the +called listeners are ignored and will be discarded.

      +

      The following example shows a simple EventEmitter instance with a single +listener. The eventEmitter.on() method is used to register listeners, while +the eventEmitter.emit() method is used to trigger the event.

      +
      const EventEmitter = require('events');
      +
      +class MyEmitter extends EventEmitter {}
      +
      +const myEmitter = new MyEmitter();
      +myEmitter.on('event', () => {
      +  console.log('an event occurred!');
      +});
      +myEmitter.emit('event');
      +

      Passing arguments and this to listeners#

      +

      The eventEmitter.emit() method allows an arbitrary set of arguments to be +passed to the listener functions. Keep in mind that when +an ordinary listener function is called, the standard this keyword +is intentionally set to reference the EventEmitter instance to which the +listener is attached.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', function(a, b) {
      +  console.log(a, b, this, this === myEmitter);
      +  // Prints:
      +  //   a b MyEmitter {
      +  //     domain: null,
      +  //     _events: { event: [Function] },
      +  //     _eventsCount: 1,
      +  //     _maxListeners: undefined } true
      +});
      +myEmitter.emit('event', 'a', 'b');
      +

      It is possible to use ES6 Arrow Functions as listeners, however, when doing so, +the this keyword will no longer reference the EventEmitter instance:

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', (a, b) => {
      +  console.log(a, b, this);
      +  // Prints: a b {}
      +});
      +myEmitter.emit('event', 'a', 'b');
      +

      Asynchronous vs. synchronous#

      +

      The EventEmitter calls all listeners synchronously in the order in which +they were registered. This ensures the proper sequencing of +events and helps avoid race conditions and logic errors. When appropriate, +listener functions can switch to an asynchronous mode of operation using +the setImmediate() or process.nextTick() methods:

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', (a, b) => {
      +  setImmediate(() => {
      +    console.log('this happens asynchronously');
      +  });
      +});
      +myEmitter.emit('event', 'a', 'b');
      +

      Handling events only once#

      +

      When a listener is registered using the eventEmitter.on() method, that +listener will be invoked every time the named event is emitted.

      +
      const myEmitter = new MyEmitter();
      +let m = 0;
      +myEmitter.on('event', () => {
      +  console.log(++m);
      +});
      +myEmitter.emit('event');
      +// Prints: 1
      +myEmitter.emit('event');
      +// Prints: 2
      +

      Using the eventEmitter.once() method, it is possible to register a listener +that is called at most once for a particular event. Once the event is emitted, +the listener is unregistered and then called.

      +
      const myEmitter = new MyEmitter();
      +let m = 0;
      +myEmitter.once('event', () => {
      +  console.log(++m);
      +});
      +myEmitter.emit('event');
      +// Prints: 1
      +myEmitter.emit('event');
      +// Ignored
      +

      Error events#

      +

      When an error occurs within an EventEmitter instance, the typical action is +for an 'error' event to be emitted. These are treated as special cases +within Node.js.

      +

      If an EventEmitter does not have at least one listener registered for the +'error' event, and an 'error' event is emitted, the error is thrown, a +stack trace is printed, and the Node.js process exits.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.emit('error', new Error('whoops!'));
      +// Throws and crashes Node.js
      +

      To guard against crashing the Node.js process the domain module can be +used. (Note, however, that the domain module is deprecated.)

      +

      As a best practice, listeners should always be added for the 'error' events.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('error', (err) => {
      +  console.error('whoops! there was an error');
      +});
      +myEmitter.emit('error', new Error('whoops!'));
      +// Prints: whoops! there was an error
      +

      It is possible to monitor 'error' events without consuming the emitted error +by installing a listener using the symbol errorMonitor.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on(EventEmitter.errorMonitor, (err) => {
      +  MyMonitoringTool.log(err);
      +});
      +myEmitter.emit('error', new Error('whoops!'));
      +// Still throws and crashes Node.js
      +

      Capture rejections of promises#

      +

      Stability: 1 - captureRejections is experimental.

      +

      Using async functions with event handlers is problematic, because it +can lead to an unhandled rejection in case of a thrown exception:

      +
      const ee = new EventEmitter();
      +ee.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +

      The captureRejections option in the EventEmitter constructor or the global +setting change this behavior, installing a .then(undefined, handler) +handler on the Promise. This handler routes the exception +asynchronously to the Symbol.for('nodejs.rejection') method +if there is one, or to 'error' event handler if there is none.

      +
      const ee1 = new EventEmitter({ captureRejections: true });
      +ee1.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +
      +ee1.on('error', console.log);
      +
      +const ee2 = new EventEmitter({ captureRejections: true });
      +ee2.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +
      +ee2[Symbol.for('nodejs.rejection')] = console.log;
      +

      Setting EventEmitter.captureRejections = true will change the default for all +new instances of EventEmitter.

      +
      EventEmitter.captureRejections = true;
      +const ee1 = new EventEmitter();
      +ee1.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +
      +ee1.on('error', console.log);
      +

      The 'error' events that are generated by the captureRejections behavior +do not have a catch handler to avoid infinite error loops: the +recommendation is to not use async functions as 'error' event handlers.

      +

      Class: EventEmitter#

      + +

      The EventEmitter class is defined and exposed by the events module:

      +
      const EventEmitter = require('events');
      +

      All EventEmitters emit the event 'newListener' when new listeners are +added and 'removeListener' when existing listeners are removed.

      +

      It supports the following option:

      + +

      Event: 'newListener'#

      + + +

      The EventEmitter instance will emit its own 'newListener' event before +a listener is added to its internal array of listeners.

      +

      Listeners registered for the 'newListener' event will be passed the event +name and a reference to the listener being added.

      +

      The fact that the event is triggered before adding the listener has a subtle +but important side effect: any additional listeners registered to the same +name within the 'newListener' callback will be inserted before the +listener that is in the process of being added.

      +
      const myEmitter = new MyEmitter();
      +// Only do this once so we don't loop forever
      +myEmitter.once('newListener', (event, listener) => {
      +  if (event === 'event') {
      +    // Insert a new listener in front
      +    myEmitter.on('event', () => {
      +      console.log('B');
      +    });
      +  }
      +});
      +myEmitter.on('event', () => {
      +  console.log('A');
      +});
      +myEmitter.emit('event');
      +// Prints:
      +//   B
      +//   A
      +

      Event: 'removeListener'#

      + + +

      The 'removeListener' event is emitted after the listener is removed.

      +

      EventEmitter.listenerCount(emitter, eventName)#

      + +

      Stability: 0 - Deprecated: Use emitter.listenerCount() instead.

      + +

      A class method that returns the number of listeners for the given eventName +registered on the given emitter.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', () => {});
      +myEmitter.on('event', () => {});
      +console.log(EventEmitter.listenerCount(myEmitter, 'event'));
      +// Prints: 2
      +

      EventEmitter.defaultMaxListeners#

      + +

      By default, a maximum of 10 listeners can be registered for any single +event. This limit can be changed for individual EventEmitter instances +using the emitter.setMaxListeners(n) method. To change the default +for all EventEmitter instances, the EventEmitter.defaultMaxListeners +property can be used. If this value is not a positive number, a TypeError +will be thrown.

      +

      Take caution when setting the EventEmitter.defaultMaxListeners because the +change affects all EventEmitter instances, including those created before +the change is made. However, calling emitter.setMaxListeners(n) still has +precedence over EventEmitter.defaultMaxListeners.

      +

      This is not a hard limit. The EventEmitter instance will allow +more listeners to be added but will output a trace warning to stderr indicating +that a "possible EventEmitter memory leak" has been detected. For any single +EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() +methods can be used to temporarily avoid this warning:

      +
      emitter.setMaxListeners(emitter.getMaxListeners() + 1);
      +emitter.once('event', () => {
      +  // do stuff
      +  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
      +});
      +

      The --trace-warnings command line flag can be used to display the +stack trace for such warnings.

      +

      The emitted warning can be inspected with process.on('warning') and will +have the additional emitter, type and count properties, referring to +the event emitter instance, the event’s name and the number of attached +listeners, respectively. +Its name property is set to 'MaxListenersExceededWarning'.

      +

      EventEmitter.errorMonitor#

      + +

      This symbol shall be used to install a listener for only monitoring 'error' +events. Listeners installed using this symbol are called before the regular +'error' listeners are called.

      +

      Installing a listener using this symbol does not change the behavior once an +'error' event is emitted, therefore the process will still crash if no +regular 'error' listener is installed.

      +

      emitter.addListener(eventName, listener)#

      + + +

      Alias for emitter.on(eventName, listener).

      +

      emitter.emit(eventName[, ...args])#

      + + +

      Synchronously calls each of the listeners registered for the event named +eventName, in the order they were registered, passing the supplied arguments +to each.

      +

      Returns true if the event had listeners, false otherwise.

      +
      const EventEmitter = require('events');
      +const myEmitter = new EventEmitter();
      +
      +// First listener
      +myEmitter.on('event', function firstListener() {
      +  console.log('Helloooo! first listener');
      +});
      +// Second listener
      +myEmitter.on('event', function secondListener(arg1, arg2) {
      +  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      +});
      +// Third listener
      +myEmitter.on('event', function thirdListener(...args) {
      +  const parameters = args.join(', ');
      +  console.log(`event with parameters ${parameters} in third listener`);
      +});
      +
      +console.log(myEmitter.listeners('event'));
      +
      +myEmitter.emit('event', 1, 2, 3, 4, 5);
      +
      +// Prints:
      +// [
      +//   [Function: firstListener],
      +//   [Function: secondListener],
      +//   [Function: thirdListener]
      +// ]
      +// Helloooo! first listener
      +// event with parameters 1, 2 in second listener
      +// event with parameters 1, 2, 3, 4, 5 in third listener
      +

      emitter.eventNames()#

      + + +

      Returns an array listing the events for which the emitter has registered +listeners. The values in the array will be strings or Symbols.

      +
      const EventEmitter = require('events');
      +const myEE = new EventEmitter();
      +myEE.on('foo', () => {});
      +myEE.on('bar', () => {});
      +
      +const sym = Symbol('symbol');
      +myEE.on(sym, () => {});
      +
      +console.log(myEE.eventNames());
      +// Prints: [ 'foo', 'bar', Symbol(symbol) ]
      +

      emitter.getMaxListeners()#

      + + +

      Returns the current max listener value for the EventEmitter which is either +set by emitter.setMaxListeners(n) or defaults to +EventEmitter.defaultMaxListeners.

      +

      emitter.listenerCount(eventName)#

      + + +

      Returns the number of listeners listening to the event named eventName.

      +

      emitter.listeners(eventName)#

      + + +

      Returns a copy of the array of listeners for the event named eventName.

      +
      server.on('connection', (stream) => {
      +  console.log('someone connected!');
      +});
      +console.log(util.inspect(server.listeners('connection')));
      +// Prints: [ [Function] ]
      +

      emitter.off(eventName, listener)#

      + + +

      Alias for emitter.removeListener().

      +

      emitter.on(eventName, listener)#

      + + +

      Adds the listener function to the end of the listeners array for the +event named eventName. No checks are made to see if the listener has +already been added. Multiple calls passing the same combination of eventName +and listener will result in the listener being added, and called, multiple +times.

      +
      server.on('connection', (stream) => {
      +  console.log('someone connected!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      By default, event listeners are invoked in the order they are added. The +emitter.prependListener() method can be used as an alternative to add the +event listener to the beginning of the listeners array.

      +
      const myEE = new EventEmitter();
      +myEE.on('foo', () => console.log('a'));
      +myEE.prependListener('foo', () => console.log('b'));
      +myEE.emit('foo');
      +// Prints:
      +//   b
      +//   a
      +

      emitter.once(eventName, listener)#

      + + +

      Adds a one-time listener function for the event named eventName. The +next time eventName is triggered, this listener is removed and then invoked.

      +
      server.once('connection', (stream) => {
      +  console.log('Ah, we have our first user!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      By default, event listeners are invoked in the order they are added. The +emitter.prependOnceListener() method can be used as an alternative to add the +event listener to the beginning of the listeners array.

      +
      const myEE = new EventEmitter();
      +myEE.once('foo', () => console.log('a'));
      +myEE.prependOnceListener('foo', () => console.log('b'));
      +myEE.emit('foo');
      +// Prints:
      +//   b
      +//   a
      +

      emitter.prependListener(eventName, listener)#

      + + +

      Adds the listener function to the beginning of the listeners array for the +event named eventName. No checks are made to see if the listener has +already been added. Multiple calls passing the same combination of eventName +and listener will result in the listener being added, and called, multiple +times.

      +
      server.prependListener('connection', (stream) => {
      +  console.log('someone connected!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.prependOnceListener(eventName, listener)#

      + + +

      Adds a one-time listener function for the event named eventName to the +beginning of the listeners array. The next time eventName is triggered, this +listener is removed, and then invoked.

      +
      server.prependOnceListener('connection', (stream) => {
      +  console.log('Ah, we have our first user!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.removeAllListeners([eventName])#

      + + +

      Removes all listeners, or those of the specified eventName.

      +

      It is bad practice to remove listeners added elsewhere in the code, +particularly when the EventEmitter instance was created by some other +component or module (e.g. sockets or file streams).

      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.removeListener(eventName, listener)#

      + + +

      Removes the specified listener from the listener array for the event named +eventName.

      +
      const callback = (stream) => {
      +  console.log('someone connected!');
      +};
      +server.on('connection', callback);
      +// ...
      +server.removeListener('connection', callback);
      +

      removeListener() will remove, at most, one instance of a listener from the +listener array. If any single listener has been added multiple times to the +listener array for the specified eventName, then removeListener() must be +called multiple times to remove each instance.

      +

      Once an event has been emitted, all listeners attached to it at the +time of emitting will be called in order. This implies that any +removeListener() or removeAllListeners() calls after emitting and +before the last listener finishes execution will not remove them from +emit() in progress. Subsequent events will behave as expected.

      +
      const myEmitter = new MyEmitter();
      +
      +const callbackA = () => {
      +  console.log('A');
      +  myEmitter.removeListener('event', callbackB);
      +};
      +
      +const callbackB = () => {
      +  console.log('B');
      +};
      +
      +myEmitter.on('event', callbackA);
      +
      +myEmitter.on('event', callbackB);
      +
      +// callbackA removes listener callbackB but it will still be called.
      +// Internal listener array at time of emit [callbackA, callbackB]
      +myEmitter.emit('event');
      +// Prints:
      +//   A
      +//   B
      +
      +// callbackB is now removed.
      +// Internal listener array [callbackA]
      +myEmitter.emit('event');
      +// Prints:
      +//   A
      +

      Because listeners are managed using an internal array, calling this will +change the position indices of any listener registered after the listener +being removed. This will not impact the order in which listeners are called, +but it means that any copies of the listener array as returned by +the emitter.listeners() method will need to be recreated.

      +

      When a single function has been added as a handler multiple times for a single +event (as in the example below), removeListener() will remove the most +recently added instance. In the example the once('ping') +listener is removed:

      +
      const ee = new EventEmitter();
      +
      +function pong() {
      +  console.log('pong');
      +}
      +
      +ee.on('ping', pong);
      +ee.once('ping', pong);
      +ee.removeListener('ping', pong);
      +
      +ee.emit('ping');
      +ee.emit('ping');
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.setMaxListeners(n)#

      + + +

      By default EventEmitters will print a warning if more than 10 listeners are +added for a particular event. This is a useful default that helps finding +memory leaks. The emitter.setMaxListeners() method allows the limit to be +modified for this specific EventEmitter instance. The value can be set to +Infinity (or 0) to indicate an unlimited number of listeners.

      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.rawListeners(eventName)#

      + + +

      Returns a copy of the array of listeners for the event named eventName, +including any wrappers (such as those created by .once()).

      +
      const emitter = new EventEmitter();
      +emitter.once('log', () => console.log('log once'));
      +
      +// Returns a new Array with a function `onceWrapper` which has a property
      +// `listener` which contains the original listener bound above
      +const listeners = emitter.rawListeners('log');
      +const logFnWrapper = listeners[0];
      +
      +// Logs "log once" to the console and does not unbind the `once` event
      +logFnWrapper.listener();
      +
      +// Logs "log once" to the console and removes the listener
      +logFnWrapper();
      +
      +emitter.on('log', () => console.log('log persistently'));
      +// Will return a new Array with a single function bound by `.on()` above
      +const newListeners = emitter.rawListeners('log');
      +
      +// Logs "log persistently" twice
      +newListeners[0]();
      +emitter.emit('log');
      +

      emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])#

      + +

      Stability: 1 - captureRejections is experimental.

      + +

      The Symbol.for('nodejs.rejection') method is called in case a +promise rejection happens when emitting an event and +captureRejections is enabled on the emitter. +It is possible to use events.captureRejectionSymbol in +place of Symbol.for('nodejs.rejection').

      +
      const { EventEmitter, captureRejectionSymbol } = require('events');
      +
      +class MyClass extends EventEmitter {
      +  constructor() {
      +    super({ captureRejections: true });
      +  }
      +
      +  [captureRejectionSymbol](err, event, ...args) {
      +    console.log('rejection happened for', event, 'with', err, ...args);
      +    this.destroy(err);
      +  }
      +
      +  destroy(err) {
      +    // Tear the resource down here.
      +  }
      +}
      +

      events.once(emitter, name)#

      + + +

      Creates a Promise that is fulfilled when the EventEmitter emits the given +event or that is rejected if the EventEmitter emits 'error' while waiting. +The Promise will resolve with an array of all the arguments emitted to the +given event.

      +

      This method is intentionally generic and works with the web platform +EventTarget interface, which has no special +'error' event semantics and does not listen to the 'error' event.

      +
      const { once, EventEmitter } = require('events');
      +
      +async function run() {
      +  const ee = new EventEmitter();
      +
      +  process.nextTick(() => {
      +    ee.emit('myevent', 42);
      +  });
      +
      +  const [value] = await once(ee, 'myevent');
      +  console.log(value);
      +
      +  const err = new Error('kaboom');
      +  process.nextTick(() => {
      +    ee.emit('error', err);
      +  });
      +
      +  try {
      +    await once(ee, 'myevent');
      +  } catch (err) {
      +    console.log('error happened', err);
      +  }
      +}
      +
      +run();
      +

      The special handling of the 'error' event is only used when events.once() +is used to wait for another event. If events.once() is used to wait for the +'error' event itself, then it is treated as any other kind of event without +special handling:

      +
      const { EventEmitter, once } = require('events');
      +
      +const ee = new EventEmitter();
      +
      +once(ee, 'error')
      +  .then(([err]) => console.log('ok', err.message))
      +  .catch((err) => console.log('error', err.message));
      +
      +ee.emit('error', new Error('boom'));
      +
      +// Prints: ok boom
      +

      Awaiting multiple events emitted on process.nextTick()#

      +

      There is an edge case worth noting when using the events.once() function +to await multiple events emitted on in the same batch of process.nextTick() +operations, or whenever multiple events are emitted synchronously. Specifically, +because the process.nextTick() queue is drained before the Promise microtask +queue, and because EventEmitter emits all events synchronously, it is possible +for events.once() to miss an event.

      +
      const { EventEmitter, once } = require('events');
      +
      +const myEE = new EventEmitter();
      +
      +async function foo() {
      +  await once(myEE, 'bar');
      +  console.log('bar');
      +
      +  // This Promise will never resolve because the 'foo' event will
      +  // have already been emitted before the Promise is created.
      +  await once(myEE, 'foo');
      +  console.log('foo');
      +}
      +
      +process.nextTick(() => {
      +  myEE.emit('bar');
      +  myEE.emit('foo');
      +});
      +
      +foo().then(() => console.log('done'));
      +

      To catch both events, create each of the Promises before awaiting either +of them, then it becomes possible to use Promise.all(), Promise.race(), +or Promise.allSettled():

      +
      const { EventEmitter, once } = require('events');
      +
      +const myEE = new EventEmitter();
      +
      +async function foo() {
      +  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);
      +  console.log('foo', 'bar');
      +}
      +
      +process.nextTick(() => {
      +  myEE.emit('bar');
      +  myEE.emit('foo');
      +});
      +
      +foo().then(() => console.log('done'));
      +

      events.captureRejections#

      + +

      Stability: 1 - captureRejections is experimental.

      +

      Value: <boolean>

      +

      Change the default captureRejections option on all new EventEmitter objects.

      +

      events.captureRejectionSymbol#

      + +

      Stability: 1 - captureRejections is experimental.

      +

      Value: Symbol.for('nodejs.rejection')

      +

      See how to write a custom rejection handler.

      +

      events.on(emitter, eventName)[src]#

      + + +
      const { on, EventEmitter } = require('events');
      +
      +(async () => {
      +  const ee = new EventEmitter();
      +
      +  // Emit later on
      +  process.nextTick(() => {
      +    ee.emit('foo', 'bar');
      +    ee.emit('foo', 42);
      +  });
      +
      +  for await (const event of on(ee, 'foo')) {
      +    // The execution of this inner block is synchronous and it
      +    // processes one event at a time (even with await). Do not use
      +    // if concurrent execution is required.
      +    console.log(event); // prints ['bar'] [42]
      +  }
      +  // Unreachable here
      +})();
      +

      Returns an AsyncIterator that iterates eventName events. It will throw +if the EventEmitter emits 'error'. It removes all listeners when +exiting the loop. The value returned by each iteration is an array +composed of the emitted event arguments.

      +

      File system#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/fs.js

      +

      The fs module enables interacting with the file system in a +way modeled on standard POSIX functions.

      +

      To use this module:

      +
      const fs = require('fs');
      +

      All file system operations have synchronous, callback, and promise-based +forms.

      +

      Synchronous example#

      +

      The synchronous form blocks the Node.js event loop and further JavaScript +execution until the operation is complete. Exceptions are thrown immediately +and can be handled using try…catch, or can be allowed to bubble up.

      +
      const fs = require('fs');
      +
      +try {
      +  fs.unlinkSync('/tmp/hello');
      +  console.log('successfully deleted /tmp/hello');
      +} catch (err) {
      +  // handle the error
      +}
      +

      Callback example#

      +

      The callback form takes a completion callback function as its last +argument and invokes the operation asynchronously. The arguments passed to +the completion callback depend on the method, but the first argument is always +reserved for an exception. If the operation is completed successfully, then +the first argument is null or undefined.

      +
      const fs = require('fs');
      +
      +fs.unlink('/tmp/hello', (err) => {
      +  if (err) throw err;
      +  console.log('successfully deleted /tmp/hello');
      +});
      +

      Promise example#

      +

      Promise-based operations return a Promise that is resolved when the +asynchronous operation is complete.

      +
      const fs = require('fs').promises;
      +
      +(async function(path) {
      +  try {
      +    await fs.unlink(path);
      +    console.log(`successfully deleted ${path}`);
      +  } catch (error) {
      +    console.error('there was an error:', error.message);
      +  }
      +})('/tmp/hello');
      +

      Ordering of callback and promise-based operations#

      +

      There is no guaranteed ordering when using either the callback or +promise-based methods. For example, the following is prone to error +because the fs.stat() operation might complete before the fs.rename() +operation:

      +
      fs.rename('/tmp/hello', '/tmp/world', (err) => {
      +  if (err) throw err;
      +  console.log('renamed complete');
      +});
      +fs.stat('/tmp/world', (err, stats) => {
      +  if (err) throw err;
      +  console.log(`stats: ${JSON.stringify(stats)}`);
      +});
      +

      To correctly order the operations, move the fs.stat() call into the callback +of the fs.rename() operation:

      +
      fs.rename('/tmp/hello', '/tmp/world', (err) => {
      +  if (err) throw err;
      +  fs.stat('/tmp/world', (err, stats) => {
      +    if (err) throw err;
      +    console.log(`stats: ${JSON.stringify(stats)}`);
      +  });
      +});
      +

      Or, use the promise-based API:

      +
      const fs = require('fs').promises;
      +
      +(async function(from, to) {
      +  try {
      +    await fs.rename(from, to);
      +    const stats = await fs.stat(to);
      +    console.log(`stats: ${JSON.stringify(stats)}`);
      +  } catch (error) {
      +    console.error('there was an error:', error.message);
      +  }
      +})('/tmp/hello', '/tmp/world');
      +

      File paths#

      +

      Most fs operations accept filepaths that may be specified in the form of +a string, a Buffer, or a URL object using the file: protocol.

      +

      String form paths are interpreted as UTF-8 character sequences identifying +the absolute or relative filename. Relative paths will be resolved relative +to the current working directory as determined by calling process.cwd().

      +

      Example using an absolute path on POSIX:

      +
      const fs = require('fs');
      +
      +fs.open('/open/some/file.txt', 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.close(fd, (err) => {
      +    if (err) throw err;
      +  });
      +});
      +

      Example using a relative path on POSIX (relative to process.cwd()):

      +
      fs.open('file.txt', 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.close(fd, (err) => {
      +    if (err) throw err;
      +  });
      +});
      +

      Paths specified using a Buffer are useful primarily on certain POSIX +operating systems that treat file paths as opaque byte sequences. On such +systems, it is possible for a single file path to contain sub-sequences that +use multiple character encodings. As with string paths, Buffer paths may +be relative or absolute:

      +

      Example using an absolute path on POSIX:

      +
      fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.close(fd, (err) => {
      +    if (err) throw err;
      +  });
      +});
      +

      On Windows, Node.js follows the concept of per-drive working directory. This +behavior can be observed when using a drive path without a backslash. For +example fs.readdirSync('C:\\') can potentially return a different result than +fs.readdirSync('C:'). For more information, see +this MSDN page.

      +

      URL object support#

      + +

      For most fs module functions, the path or filename argument may be passed +as a WHATWG URL object. Only URL objects using the file: protocol +are supported.

      +
      const fs = require('fs');
      +const fileUrl = new URL('file:///tmp/hello');
      +
      +fs.readFileSync(fileUrl);
      +

      file: URLs are always absolute paths.

      +

      Using WHATWG URL objects might introduce platform-specific behaviors.

      +

      On Windows, file: URLs with a host name convert to UNC paths, while file: +URLs with drive letters convert to local absolute paths. file: URLs without a +host name nor a drive letter will result in a throw:

      +
      // On Windows :
      +
      +// - WHATWG file URLs with hostname convert to UNC path
      +// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
      +fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
      +
      +// - WHATWG file URLs with drive letters convert to absolute path
      +// file:///C:/tmp/hello => C:\tmp\hello
      +fs.readFileSync(new URL('file:///C:/tmp/hello'));
      +
      +// - WHATWG file URLs without hostname must have a drive letters
      +fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
      +fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
      +// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
      +

      file: URLs with drive letters must use : as a separator just after +the drive letter. Using another separator will result in a throw.

      +

      On all other platforms, file: URLs with a host name are unsupported and will +result in a throw:

      +
      // On other platforms:
      +
      +// - WHATWG file URLs with hostname are unsupported
      +// file://hostname/p/a/t/h/file => throw!
      +fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
      +// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
      +
      +// - WHATWG file URLs convert to absolute path
      +// file:///tmp/hello => /tmp/hello
      +fs.readFileSync(new URL('file:///tmp/hello'));
      +

      A file: URL having encoded slash characters will result in a throw on all +platforms:

      +
      // On Windows
      +fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
      +fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
      +/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
      +\ or / characters */
      +
      +// On POSIX
      +fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
      +fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
      +/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
      +/ characters */
      +

      On Windows, file: URLs having encoded backslash will result in a throw:

      +
      // On Windows
      +fs.readFileSync(new URL('file:///C:/path/%5C'));
      +fs.readFileSync(new URL('file:///C:/path/%5c'));
      +/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
      +\ or / characters */
      +

      File descriptors#

      +

      On POSIX systems, for every process, the kernel maintains a table of currently +open files and resources. Each open file is assigned a simple numeric +identifier called a file descriptor. At the system-level, all file system +operations use these file descriptors to identify and track each specific +file. Windows systems use a different but conceptually similar mechanism for +tracking resources. To simplify things for users, Node.js abstracts away the +specific differences between operating systems and assigns all open files a +numeric file descriptor.

      +

      The fs.open() method is used to allocate a new file descriptor. Once +allocated, the file descriptor may be used to read data from, write data to, +or request information about the file.

      +
      fs.open('/open/some/file.txt', 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.fstat(fd, (err, stat) => {
      +    if (err) throw err;
      +    // use stat
      +
      +    // always close the file descriptor!
      +    fs.close(fd, (err) => {
      +      if (err) throw err;
      +    });
      +  });
      +});
      +

      Most operating systems limit the number of file descriptors that may be open +at any given time so it is critical to close the descriptor when operations +are completed. Failure to do so will result in a memory leak that will +eventually cause an application to crash.

      +

      Threadpool usage#

      +

      All file system APIs except fs.FSWatcher() and those that are explicitly +synchronous use libuv's threadpool, which can have surprising and negative +performance implications for some applications. See the +UV_THREADPOOL_SIZE documentation for more information.

      +

      Class: fs.Dir#

      + +

      A class representing a directory stream.

      +

      Created by fs.opendir(), fs.opendirSync(), or +fsPromises.opendir().

      +
      const fs = require('fs');
      +
      +async function print(path) {
      +  const dir = await fs.promises.opendir(path);
      +  for await (const dirent of dir) {
      +    console.log(dirent.name);
      +  }
      +}
      +print('./').catch(console.error);
      +

      dir.close()#

      + + +

      Asynchronously close the directory's underlying resource handle. +Subsequent reads will result in errors.

      +

      A Promise is returned that will be resolved after the resource has been +closed.

      +

      dir.close(callback)#

      + + +

      Asynchronously close the directory's underlying resource handle. +Subsequent reads will result in errors.

      +

      The callback will be called after the resource handle has been closed.

      +

      dir.closeSync()#

      + +

      Synchronously close the directory's underlying resource handle. +Subsequent reads will result in errors.

      +

      dir.path#

      + + +

      The read-only path of this directory as was provided to fs.opendir(), +fs.opendirSync(), or fsPromises.opendir().

      +

      dir.read()#

      + + +

      Asynchronously read the next directory entry via readdir(3) as an +fs.Dirent.

      +

      After the read is completed, a Promise is returned that will be resolved with +an fs.Dirent, or null if there are no more directory entries to read.

      +

      Directory entries returned by this function are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      dir.read(callback)#

      + + +

      Asynchronously read the next directory entry via readdir(3) as an +fs.Dirent.

      +

      After the read is completed, the callback will be called with an +fs.Dirent, or null if there are no more directory entries to read.

      +

      Directory entries returned by this function are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      dir.readSync()#

      + + +

      Synchronously read the next directory entry via readdir(3) as an +fs.Dirent.

      +

      If there are no more directory entries to read, null will be returned.

      +

      Directory entries returned by this function are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      dir[Symbol.asyncIterator]()#

      + + +

      Asynchronously iterates over the directory via readdir(3) until all entries have +been read.

      +

      Entries returned by the async iterator are always an fs.Dirent. +The null case from dir.read() is handled internally.

      +

      See fs.Dir for an example.

      +

      Directory entries returned by this iterator are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      Class: fs.Dirent#

      + +

      A representation of a directory entry, which can be a file or a subdirectory +within the directory, as returned by reading from an fs.Dir. The +directory entry is a combination of the file name and file type pairs.

      +

      Additionally, when fs.readdir() or fs.readdirSync() is called with +the withFileTypes option set to true, the resulting array is filled with +fs.Dirent objects, rather than strings or Buffers.

      +

      dirent.isBlockDevice()#

      + + +

      Returns true if the fs.Dirent object describes a block device.

      +

      dirent.isCharacterDevice()#

      + + +

      Returns true if the fs.Dirent object describes a character device.

      +

      dirent.isDirectory()#

      + + +

      Returns true if the fs.Dirent object describes a file system +directory.

      +

      dirent.isFIFO()#

      + + +

      Returns true if the fs.Dirent object describes a first-in-first-out +(FIFO) pipe.

      +

      dirent.isFile()#

      + + +

      Returns true if the fs.Dirent object describes a regular file.

      +

      dirent.isSocket()#

      + + +

      Returns true if the fs.Dirent object describes a socket.

      +

      dirent.isSymbolicLink()#

      + + +

      Returns true if the fs.Dirent object describes a symbolic link.

      +

      dirent.name#

      + + +

      The file name that this fs.Dirent object refers to. The type of this +value is determined by the options.encoding passed to fs.readdir() or +fs.readdirSync().

      +

      Class: fs.FSWatcher#

      + + +

      A successful call to fs.watch() method will return a new fs.FSWatcher +object.

      +

      All fs.FSWatcher objects emit a 'change' event whenever a specific watched +file is modified.

      +

      Event: 'change'#

      + +
        +
      • eventType <string> The type of change event that has occurred
      • +
      • filename <string> | <Buffer> The filename that changed (if relevant/available)
      • +
      +

      Emitted when something changes in a watched directory or file. +See more details in fs.watch().

      +

      The filename argument may not be provided depending on operating system +support. If filename is provided, it will be provided as a Buffer if +fs.watch() is called with its encoding option set to 'buffer', otherwise +filename will be a UTF-8 string.

      +
      // Example when handled through fs.watch() listener
      +fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
      +  if (filename) {
      +    console.log(filename);
      +    // Prints: <Buffer ...>
      +  }
      +});
      +

      Event: 'close'#

      + +

      Emitted when the watcher stops watching for changes. The closed +fs.FSWatcher object is no longer usable in the event handler.

      +

      Event: 'error'#

      + + +

      Emitted when an error occurs while watching the file. The errored +fs.FSWatcher object is no longer usable in the event handler.

      +

      watcher.close()#

      + +

      Stop watching for changes on the given fs.FSWatcher. Once stopped, the +fs.FSWatcher object is no longer usable.

      +

      watcher.ref()#

      + + +

      When called, requests that the Node.js event loop not exit so long as the +FSWatcher is active. Calling watcher.ref() multiple times will have +no effect.

      +

      By default, all FSWatcher objects are "ref'ed", making it normally +unnecessary to call watcher.ref() unless watcher.unref() had been +called previously.

      +

      watcher.unref()#

      + + +

      When called, the active FSWatcher object will not require the Node.js +event loop to remain active. If there is no other activity keeping the +event loop running, the process may exit before the FSWatcher object's +callback is invoked. Calling watcher.unref() multiple times will have +no effect.

      +

      Class: fs.StatWatcher#

      + + +

      A successful call to fs.watchFile() method will return a new fs.StatWatcher +object.

      +

      watcher.ref()#

      + + +

      When called, requests that the Node.js event loop not exit so long as the +StatWatcher is active. Calling watcher.ref() multiple times will have +no effect.

      +

      By default, all StatWatcher objects are "ref'ed", making it normally +unnecessary to call watcher.ref() unless watcher.unref() had been +called previously.

      +

      watcher.unref()#

      + + +

      When called, the active StatWatcher object will not require the Node.js +event loop to remain active. If there is no other activity keeping the +event loop running, the process may exit before the StatWatcher object's +callback is invoked. Calling watcher.unref() multiple times will have +no effect.

      +

      Class: fs.ReadStream#

      + + +

      Instances of fs.ReadStream are created and returned using the +fs.createReadStream() function.

      +

      Event: 'close'#

      + +

      Emitted when the fs.ReadStream's underlying file descriptor has been closed.

      +

      Event: 'open'#

      + +
        +
      • fd <integer> Integer file descriptor used by the ReadStream.
      • +
      +

      Emitted when the fs.ReadStream's file descriptor has been opened.

      +

      Event: 'ready'#

      + +

      Emitted when the fs.ReadStream is ready to be used.

      +

      Fires immediately after 'open'.

      +

      readStream.bytesRead#

      + + +

      The number of bytes that have been read so far.

      +

      readStream.path#

      + + +

      The path to the file the stream is reading from as specified in the first +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 Buffer.

      +

      readStream.pending#

      + + +

      This property is true if the underlying file has not been opened yet, +i.e. before the 'ready' event is emitted.

      +

      Class: fs.Stats#

      + +

      A fs.Stats object provides information about a file.

      +

      Objects returned from fs.stat(), fs.lstat() and fs.fstat() and +their synchronous counterparts are of this type. +If bigint in the options passed to those methods is true, the numeric values +will be bigint instead of number, and the object will contain additional +nanosecond-precision properties suffixed with Ns.

      +
      Stats {
      +  dev: 2114,
      +  ino: 48064969,
      +  mode: 33188,
      +  nlink: 1,
      +  uid: 85,
      +  gid: 100,
      +  rdev: 0,
      +  size: 527,
      +  blksize: 4096,
      +  blocks: 8,
      +  atimeMs: 1318289051000.1,
      +  mtimeMs: 1318289051000.1,
      +  ctimeMs: 1318289051000.1,
      +  birthtimeMs: 1318289051000.1,
      +  atime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
      +

      bigint version:

      +
      BigIntStats {
      +  dev: 2114n,
      +  ino: 48064969n,
      +  mode: 33188n,
      +  nlink: 1n,
      +  uid: 85n,
      +  gid: 100n,
      +  rdev: 0n,
      +  size: 527n,
      +  blksize: 4096n,
      +  blocks: 8n,
      +  atimeMs: 1318289051000n,
      +  mtimeMs: 1318289051000n,
      +  ctimeMs: 1318289051000n,
      +  birthtimeMs: 1318289051000n,
      +  atimeNs: 1318289051000000000n,
      +  mtimeNs: 1318289051000000000n,
      +  ctimeNs: 1318289051000000000n,
      +  birthtimeNs: 1318289051000000000n,
      +  atime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
      +

      stats.isBlockDevice()#

      + + +

      Returns true if the fs.Stats object describes a block device.

      +

      stats.isCharacterDevice()#

      + + +

      Returns true if the fs.Stats object describes a character device.

      +

      stats.isDirectory()#

      + + +

      Returns true if the fs.Stats object describes a file system directory.

      +

      stats.isFIFO()#

      + + +

      Returns true if the fs.Stats object describes a first-in-first-out (FIFO) +pipe.

      +

      stats.isFile()#

      + + +

      Returns true if the fs.Stats object describes a regular file.

      +

      stats.isSocket()#

      + + +

      Returns true if the fs.Stats object describes a socket.

      +

      stats.isSymbolicLink()#

      + + +

      Returns true if the fs.Stats object describes a symbolic link.

      +

      This method is only valid when using fs.lstat().

      +

      stats.dev#

      + +

      The numeric identifier of the device containing the file.

      +

      stats.ino#

      + +

      The file system specific "Inode" number for the file.

      +

      stats.mode#

      + +

      A bit-field describing the file type and mode.

      +

      stats.nlink#

      + +

      The number of hard-links that exist for the file.

      +

      stats.uid#

      + +

      The numeric user identifier of the user that owns the file (POSIX).

      +

      stats.gid#

      + +

      The numeric group identifier of the group that owns the file (POSIX).

      +

      stats.rdev#

      + +

      A numeric device identifier if the file represents a device.

      +

      stats.size#

      + +

      The size of the file in bytes.

      +

      stats.blksize#

      + +

      The file system block size for i/o operations.

      +

      stats.blocks#

      + +

      The number of blocks allocated for this file.

      +

      stats.atimeMs#

      + + +

      The timestamp indicating the last time this file was accessed expressed in +milliseconds since the POSIX Epoch.

      +

      stats.mtimeMs#

      + + +

      The timestamp indicating the last time this file was modified expressed in +milliseconds since the POSIX Epoch.

      +

      stats.ctimeMs#

      + + +

      The timestamp indicating the last time the file status was changed expressed +in milliseconds since the POSIX Epoch.

      +

      stats.birthtimeMs#

      + + +

      The timestamp indicating the creation time of this file expressed in +milliseconds since the POSIX Epoch.

      +

      stats.atimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the last time this file was accessed expressed in +nanoseconds since the POSIX Epoch.

      +

      stats.mtimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the last time this file was modified expressed in +nanoseconds since the POSIX Epoch.

      +

      stats.ctimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the last time the file status was changed expressed +in nanoseconds since the POSIX Epoch.

      +

      stats.birthtimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the creation time of this file expressed in +nanoseconds since the POSIX Epoch.

      +

      stats.atime#

      + + +

      The timestamp indicating the last time this file was accessed.

      +

      stats.mtime#

      + + +

      The timestamp indicating the last time this file was modified.

      +

      stats.ctime#

      + + +

      The timestamp indicating the last time the file status was changed.

      +

      stats.birthtime#

      + + +

      The timestamp indicating the creation time of this file.

      +

      Stat time values#

      +

      The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are +numeric values that hold the corresponding times in milliseconds. Their +precision is platform specific. When bigint: true is passed into the +method that generates the object, the properties will be bigints, +otherwise they will be numbers.

      +

      The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are +bigints that hold the corresponding times in nanoseconds. They are +only present when bigint: true is passed into the method that generates +the object. Their precision is platform specific.

      +

      atime, mtime, ctime, and birthtime are +Date object alternate representations of the various times. The +Date and number values are not connected. Assigning a new number value, or +mutating the Date value, will not be reflected in the corresponding alternate +representation.

      +

      The times in the stat object have the following semantics:

      +
        +
      • atime "Access Time": Time when file data last accessed. Changed +by the mknod(2), utimes(2), and read(2) system calls.
      • +
      • mtime "Modified Time": Time when file data last modified. +Changed by the mknod(2), utimes(2), and write(2) system calls.
      • +
      • ctime "Change Time": Time when file status was last changed +(inode data modification). Changed by the chmod(2), chown(2), +link(2), mknod(2), rename(2), unlink(2), utimes(2), +read(2), and write(2) system calls.
      • +
      • birthtime "Birth Time": Time of file creation. Set once when the +file is created. On filesystems where birthtime is not available, +this field may instead hold either the ctime or +1970-01-01T00:00Z (ie, Unix epoch timestamp 0). This value may be greater +than atime or mtime in this case. On Darwin and other FreeBSD variants, +also set if the atime is explicitly set to an earlier value than the current +birthtime using the utimes(2) system call.
      • +
      +

      Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As +of 0.12, ctime is not "creation time", and on Unix systems, it never was.

      +

      Class: fs.WriteStream#

      + + +

      Instances of fs.WriteStream are created and returned using the +fs.createWriteStream() function.

      +

      Event: 'close'#

      + +

      Emitted when the WriteStream's underlying file descriptor has been closed.

      +

      Event: 'open'#

      + +
        +
      • fd <integer> Integer file descriptor used by the WriteStream.
      • +
      +

      Emitted when the WriteStream's file is opened.

      +

      Event: 'ready'#

      + +

      Emitted when the fs.WriteStream is ready to be used.

      +

      Fires immediately after 'open'.

      +

      writeStream.bytesWritten#

      + +

      The number of bytes written so far. Does not include data that is still queued +for writing.

      +

      writeStream.path#

      + +

      The path to the file the stream is writing to as specified in the first +argument to fs.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 Buffer.

      +

      writeStream.pending#

      + + +

      This property is true if the underlying file has not been opened yet, +i.e. before the 'ready' event is emitted.

      +

      fs.access(path[, mode], callback)#

      + + +

      Tests a user's permissions for the file or directory specified by path. +The mode argument is an optional integer that specifies the accessibility +checks to be performed. Check File access constants for possible values +of mode. It is possible to create a mask consisting of the bitwise OR of +two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      +

      The final argument, callback, is a callback function that is invoked with +a possible error argument. If any of the accessibility checks fail, the error +argument will be an Error object. The following examples check if +package.json exists, and if it is readable or writable.

      +
      const file = 'package.json';
      +
      +// Check if the file exists in the current directory.
      +fs.access(file, fs.constants.F_OK, (err) => {
      +  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
      +});
      +
      +// Check if the file is readable.
      +fs.access(file, fs.constants.R_OK, (err) => {
      +  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
      +});
      +
      +// Check if the file is writable.
      +fs.access(file, fs.constants.W_OK, (err) => {
      +  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
      +});
      +
      +// Check if the file exists in the current directory, and if it is writable.
      +fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
      +  if (err) {
      +    console.error(
      +      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
      +  } else {
      +    console.log(`${file} exists, and it is writable`);
      +  }
      +});
      +

      Do not use fs.access() to check for the accessibility of a file before calling +fs.open(), fs.readFile() or fs.writeFile(). Doing +so introduces a race condition, since other processes may change the file's +state between the two calls. Instead, user code should open/read/write the +file directly and handle the error raised if the file is not accessible.

      +

      write (NOT RECOMMENDED)

      +
      fs.access('myfile', (err) => {
      +  if (!err) {
      +    console.error('myfile already exists');
      +    return;
      +  }
      +
      +  fs.open('myfile', 'wx', (err, fd) => {
      +    if (err) throw err;
      +    writeMyData(fd);
      +  });
      +});
      +

      write (RECOMMENDED)

      +
      fs.open('myfile', 'wx', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'EEXIST') {
      +      console.error('myfile already exists');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  writeMyData(fd);
      +});
      +

      read (NOT RECOMMENDED)

      +
      fs.access('myfile', (err) => {
      +  if (err) {
      +    if (err.code === 'ENOENT') {
      +      console.error('myfile does not exist');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  fs.open('myfile', 'r', (err, fd) => {
      +    if (err) throw err;
      +    readMyData(fd);
      +  });
      +});
      +

      read (RECOMMENDED)

      +
      fs.open('myfile', 'r', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'ENOENT') {
      +      console.error('myfile does not exist');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  readMyData(fd);
      +});
      +

      The "not recommended" examples above check for accessibility and then use the +file; the "recommended" examples are better because they use the file directly +and handle the error, if any.

      +

      In general, check for the accessibility of a file only if the file will not be +used directly, for example when its accessibility is a signal from another +process.

      +

      On Windows, access-control policies (ACLs) on a directory may limit access to +a file or directory. The fs.access() function, however, does not check the +ACL and therefore may report that a path is accessible even if the ACL restricts +the user from reading or writing to it.

      +

      fs.accessSync(path[, mode])#

      + + +

      Synchronously tests a user's permissions for the file or directory specified +by path. The mode argument is an optional integer that specifies the +accessibility checks to be performed. Check File access constants for +possible values of mode. It is possible to create a mask consisting of +the bitwise OR of two or more values +(e.g. fs.constants.W_OK | fs.constants.R_OK).

      +

      If any of the accessibility checks fail, an Error will be thrown. Otherwise, +the method will return undefined.

      +
      try {
      +  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
      +  console.log('can read/write');
      +} catch (err) {
      +  console.error('no access!');
      +}
      +

      fs.appendFile(path, data[, options], callback)#

      + + +

      Asynchronously append data to a file, creating the file if it does not yet +exist. data can be a string or a Buffer.

      +
      fs.appendFile('message.txt', 'data to append', (err) => {
      +  if (err) throw err;
      +  console.log('The "data to append" was appended to file!');
      +});
      +

      If options is a string, then it specifies the encoding:

      +
      fs.appendFile('message.txt', 'data to append', 'utf8', callback);
      +

      The path may be specified as a numeric file descriptor that has been opened +for appending (using fs.open() or fs.openSync()). The file descriptor will +not be closed automatically.

      +
      fs.open('message.txt', 'a', (err, fd) => {
      +  if (err) throw err;
      +  fs.appendFile(fd, 'data to append', 'utf8', (err) => {
      +    fs.close(fd, (err) => {
      +      if (err) throw err;
      +    });
      +    if (err) throw err;
      +  });
      +});
      +

      fs.appendFileSync(path, data[, options])#

      + + +

      Synchronously append data to a file, creating the file if it does not yet +exist. data can be a string or a Buffer.

      +
      try {
      +  fs.appendFileSync('message.txt', 'data to append');
      +  console.log('The "data to append" was appended to file!');
      +} catch (err) {
      +  /* Handle the error */
      +}
      +

      If options is a string, then it specifies the encoding:

      +
      fs.appendFileSync('message.txt', 'data to append', 'utf8');
      +

      The path may be specified as a numeric file descriptor that has been opened +for appending (using fs.open() or fs.openSync()). The file descriptor will +not be closed automatically.

      +
      let fd;
      +
      +try {
      +  fd = fs.openSync('message.txt', 'a');
      +  fs.appendFileSync(fd, 'data to append', 'utf8');
      +} catch (err) {
      +  /* Handle the error */
      +} finally {
      +  if (fd !== undefined)
      +    fs.closeSync(fd);
      +}
      +

      fs.chmod(path, mode, callback)#

      + + +

      Asynchronously changes the permissions of a file. No arguments other than a +possible exception are given to the completion callback.

      +

      See also: chmod(2).

      +
      fs.chmod('my_file.txt', 0o775, (err) => {
      +  if (err) throw err;
      +  console.log('The permissions for file "my_file.txt" have been changed!');
      +});
      +

      File modes#

      +

      The mode argument used in both the fs.chmod() and fs.chmodSync() +methods is a numeric bitmask created using a logical OR of the following +constants:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantOctalDescription
      fs.constants.S_IRUSR0o400read by owner
      fs.constants.S_IWUSR0o200write by owner
      fs.constants.S_IXUSR0o100execute/search by owner
      fs.constants.S_IRGRP0o40read by group
      fs.constants.S_IWGRP0o20write by group
      fs.constants.S_IXGRP0o10execute/search by group
      fs.constants.S_IROTH0o4read by others
      fs.constants.S_IWOTH0o2write by others
      fs.constants.S_IXOTH0o1execute/search by others
      +

      An easier method of constructing the mode is to use a sequence of three +octal digits (e.g. 765). The left-most digit (7 in the example), specifies +the permissions for the file owner. The middle digit (6 in the example), +specifies permissions for the group. The right-most digit (5 in the example), +specifies the permissions for others.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      NumberDescription
      7read, write, and execute
      6read and write
      5read and execute
      4read only
      3write and execute
      2write only
      1execute only
      0no permission
      +

      For example, the octal value 0o765 means:

      +
        +
      • The owner may read, write and execute the file.
      • +
      • The group may read and write the file.
      • +
      • Others may read and execute the file.
      • +
      +

      When using raw numbers where file modes are expected, any value larger than +0o777 may result in platform-specific behaviors that are not supported to work +consistently. Therefore constants like S_ISVTX, S_ISGID or S_ISUID are not +exposed in fs.constants.

      +

      Caveats: on Windows only the write permission can be changed, and the +distinction among the permissions of group, owner or others is not +implemented.

      +

      fs.chmodSync(path, mode)#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.chmod().

      +

      See also: chmod(2).

      +

      fs.chown(path, uid, gid, callback)#

      + + +

      Asynchronously changes owner and group of a file. No arguments other than a +possible exception are given to the completion callback.

      +

      See also: chown(2).

      +

      fs.chownSync(path, uid, gid)#

      + + +

      Synchronously changes owner and group of a file. Returns undefined. +This is the synchronous version of fs.chown().

      +

      See also: chown(2).

      +

      fs.close(fd, callback)#

      + + +

      Asynchronous close(2). No arguments other than a possible exception are given +to the completion callback.

      +

      Calling fs.close() on any file descriptor (fd) that is currently in use +through any other fs operation may lead to undefined behavior.

      +

      fs.closeSync(fd)#

      + + +

      Synchronous close(2). Returns undefined.

      +

      Calling fs.closeSync() on any file descriptor (fd) that is currently in use +through any other fs operation may lead to undefined behavior.

      +

      fs.constants#

      + +

      Returns an object containing commonly used constants for file system +operations. The specific constants currently defined are described in +FS constants.

      +

      fs.copyFile(src, dest[, flags], callback)#

      + + +

      Asynchronously copies src to dest. By default, dest is overwritten if it +already exists. No arguments other than a possible exception are given to the +callback function. Node.js makes no guarantees about the atomicity of the copy +operation. If an error occurs after the destination file has been opened for +writing, Node.js will attempt to remove the destination.

      +

      flags is an optional integer that specifies the behavior +of the copy operation. It is possible to create a mask consisting of the bitwise +OR of two or more values (e.g. +fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      +
        +
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already +exists.
      • +
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a +copy-on-write reflink. If the platform does not support copy-on-write, then a +fallback copy mechanism is used.
      • +
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to +create a copy-on-write reflink. If the platform does not support copy-on-write, +then the operation will fail.
      • +
      +
      const fs = require('fs');
      +
      +// destination.txt will be created or overwritten by default.
      +fs.copyFile('source.txt', 'destination.txt', (err) => {
      +  if (err) throw err;
      +  console.log('source.txt was copied to destination.txt');
      +});
      +

      If the third argument is a number, then it specifies flags:

      +
      const fs = require('fs');
      +const { COPYFILE_EXCL } = fs.constants;
      +
      +// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
      +fs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback);
      +

      fs.copyFileSync(src, dest[, flags])#

      + + +

      Synchronously copies src to dest. By default, dest is overwritten if it +already exists. Returns undefined. Node.js makes no guarantees about the +atomicity of the copy operation. If an error occurs after the destination file +has been opened for writing, Node.js will attempt to remove the destination.

      +

      flags is an optional integer that specifies the behavior +of the copy operation. It is possible to create a mask consisting of the bitwise +OR of two or more values (e.g. +fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      +
        +
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already +exists.
      • +
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a +copy-on-write reflink. If the platform does not support copy-on-write, then a +fallback copy mechanism is used.
      • +
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to +create a copy-on-write reflink. If the platform does not support copy-on-write, +then the operation will fail.
      • +
      +
      const fs = require('fs');
      +
      +// destination.txt will be created or overwritten by default.
      +fs.copyFileSync('source.txt', 'destination.txt');
      +console.log('source.txt was copied to destination.txt');
      +

      If the third argument is a number, then it specifies flags:

      +
      const fs = require('fs');
      +const { COPYFILE_EXCL } = fs.constants;
      +
      +// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
      +fs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL);
      +

      fs.createReadStream(path[, options])#

      + + +

      Unlike the 16 kb default highWaterMark for a readable stream, the stream +returned by this method has a default highWaterMark of 64 kb.

      +

      options can include start and end values to read a range of bytes from +the file instead of the entire file. Both start and end are inclusive and +start counting at 0, allowed values are in the +[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is +omitted or undefined, fs.createReadStream() reads sequentially from the +current file position. The encoding can be any one of those accepted by +Buffer.

      +

      If fd is specified, ReadStream will ignore the path argument and will use +the specified file descriptor. This means that no 'open' event will be +emitted. fd should be blocking; non-blocking fds should be passed to +net.Socket.

      +

      If fd points to a character device that only supports blocking reads +(such as keyboard or sound card), read operations do not finish until data is +available. This can prevent the process from exiting and the stream from +closing naturally.

      +

      By default, the stream will not emit a 'close' event after it has been +destroyed. This is the opposite of the default for other Readable streams. +Set the emitClose option to true to change this behavior.

      +

      By providing the fs option, it is possible to override the corresponding fs +implementations for open, read, and close. When providing the fs option, +overrides for open, read, and close are required.

      +
      const fs = require('fs');
      +// Create a stream from some character device.
      +const stream = fs.createReadStream('/dev/input/event0');
      +setTimeout(() => {
      +  stream.close(); // This may not close the stream.
      +  // Artificially marking end-of-stream, as if the underlying resource had
      +  // indicated end-of-file by itself, allows the stream to close.
      +  // This does not cancel pending read operations, and if there is such an
      +  // operation, the process may still not be able to exit successfully
      +  // until it finishes.
      +  stream.push(null);
      +  stream.read(0);
      +}, 100);
      +

      If autoClose is false, then the file descriptor won't be closed, even if +there's an error. It is the application's responsibility to close it and make +sure there's no file descriptor leak. If autoClose is set to true (default +behavior), on 'error' or 'end' the file descriptor will be closed +automatically.

      +

      mode sets the file mode (permission and sticky bits), but only if the +file was created.

      +

      An example to read the last 10 bytes of a file which is 100 bytes long:

      +
      fs.createReadStream('sample.txt', { start: 90, end: 99 });
      +

      If options is a string, then it specifies the encoding.

      +

      fs.createWriteStream(path[, options])#

      + + +

      options may also include a start option to allow writing data at +some position past the beginning of the file, allowed values are in the +[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather +than replacing it may require a flags mode of r+ rather than the +default mode w. The encoding can be any one of those accepted by +Buffer.

      +

      If autoClose is set to true (default behavior) on 'error' or 'finish' +the file descriptor will be closed automatically. If autoClose is false, +then the file descriptor won't be closed, even if there's an error. +It is the application's responsibility to close it and make sure there's no +file descriptor leak.

      +

      By default, the stream will not emit a 'close' event after it has been +destroyed. This is the opposite of the default for other Writable streams. +Set the emitClose option to true to change this behavior.

      +

      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 performance as some optimizations (_writev()) +will be disabled. When providing the fs option, overrides for open, +close, and at least one of write and writev are required.

      +

      Like ReadStream, if fd is specified, WriteStream will ignore the +path argument and will use the specified file descriptor. This means that no +'open' event will be emitted. fd should be blocking; non-blocking fds +should be passed to net.Socket.

      +

      If options is a string, then it specifies the encoding.

      +

      fs.exists(path, callback)#

      + +

      Stability: 0 - Deprecated: Use fs.stat() or fs.access() instead.

      + +

      Test whether or not the given path exists by checking with the file system. +Then call the callback argument with either true or false:

      +
      fs.exists('/etc/passwd', (exists) => {
      +  console.log(exists ? 'it\'s there' : 'no passwd!');
      +});
      +

      The parameters for this callback are not consistent with other Node.js +callbacks. Normally, the first parameter to a Node.js callback is an err +parameter, optionally followed by other parameters. The fs.exists() callback +has only one boolean parameter. This is one reason fs.access() is recommended +instead of fs.exists().

      +

      Using fs.exists() to check for the existence of a file before calling +fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing +so introduces a race condition, since other processes may change the file's +state between the two calls. Instead, user code should open/read/write the +file directly and handle the error raised if the file does not exist.

      +

      write (NOT RECOMMENDED)

      +
      fs.exists('myfile', (exists) => {
      +  if (exists) {
      +    console.error('myfile already exists');
      +  } else {
      +    fs.open('myfile', 'wx', (err, fd) => {
      +      if (err) throw err;
      +      writeMyData(fd);
      +    });
      +  }
      +});
      +

      write (RECOMMENDED)

      +
      fs.open('myfile', 'wx', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'EEXIST') {
      +      console.error('myfile already exists');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  writeMyData(fd);
      +});
      +

      read (NOT RECOMMENDED)

      +
      fs.exists('myfile', (exists) => {
      +  if (exists) {
      +    fs.open('myfile', 'r', (err, fd) => {
      +      if (err) throw err;
      +      readMyData(fd);
      +    });
      +  } else {
      +    console.error('myfile does not exist');
      +  }
      +});
      +

      read (RECOMMENDED)

      +
      fs.open('myfile', 'r', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'ENOENT') {
      +      console.error('myfile does not exist');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  readMyData(fd);
      +});
      +

      The "not recommended" examples above check for existence and then use the +file; the "recommended" examples are better because they use the file directly +and handle the error, if any.

      +

      In general, check for the existence of a file only if the file won’t be +used directly, for example when its existence is a signal from another +process.

      +

      fs.existsSync(path)#

      + + +

      Returns true if the path exists, false otherwise.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.exists().

      +

      fs.exists() is deprecated, but fs.existsSync() is not. The callback +parameter to fs.exists() accepts parameters that are inconsistent with other +Node.js callbacks. fs.existsSync() does not use a callback.

      +
      if (fs.existsSync('/etc/passwd')) {
      +  console.log('The path exists.');
      +}
      +

      fs.fchmod(fd, mode, callback)#

      + + +

      Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback.

      +

      fs.fchmodSync(fd, mode)#

      + + +

      Synchronous fchmod(2). Returns undefined.

      +

      fs.fchown(fd, uid, gid, callback)#

      + + +

      Asynchronous fchown(2). No arguments other than a possible exception are given +to the completion callback.

      +

      fs.fchownSync(fd, uid, gid)#

      + + +

      Synchronous fchown(2). Returns undefined.

      +

      fs.fdatasync(fd, callback)#

      + + +

      Asynchronous fdatasync(2). No arguments other than a possible exception are +given to the completion callback.

      +

      fs.fdatasyncSync(fd)#

      + + +

      Synchronous fdatasync(2). Returns undefined.

      +

      fs.fstat(fd[, options], callback)#

      + + +

      Asynchronous fstat(2). The callback gets two arguments (err, stats) where +stats is an fs.Stats object. fstat() is identical to stat(), +except that the file to be stat-ed is specified by the file descriptor fd.

      +

      fs.fstatSync(fd[, options])#

      + + +

      Synchronous fstat(2).

      +

      fs.fsync(fd, callback)#

      + + +

      Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback.

      +

      fs.fsyncSync(fd)#

      + + +

      Synchronous fsync(2). Returns undefined.

      +

      fs.ftruncate(fd[, len], callback)#

      + + +

      Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback.

      +

      If the file referred to by the file descriptor was larger than len bytes, only +the first len bytes will be retained in the file.

      +

      For example, the following program retains only the first four bytes of the +file:

      +
      console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +// get the file descriptor of the file to be truncated
      +const fd = fs.openSync('temp.txt', 'r+');
      +
      +// Truncate the file to first four bytes
      +fs.ftruncate(fd, 4, (err) => {
      +  assert.ifError(err);
      +  console.log(fs.readFileSync('temp.txt', 'utf8'));
      +});
      +// Prints: Node
      +

      If the file previously was shorter than len bytes, it is extended, and the +extended part is filled with null bytes ('\0'):

      +
      console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +// get the file descriptor of the file to be truncated
      +const fd = fs.openSync('temp.txt', 'r+');
      +
      +// Truncate the file to 10 bytes, whereas the actual size is 7 bytes
      +fs.ftruncate(fd, 10, (err) => {
      +  assert.ifError(err);
      +  console.log(fs.readFileSync('temp.txt'));
      +});
      +// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>
      +// ('Node.js\0\0\0' in UTF8)
      +

      The last three bytes are null bytes ('\0'), to compensate the over-truncation.

      +

      fs.ftruncateSync(fd[, len])#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.ftruncate().

      +

      fs.futimes(fd, atime, mtime, callback)#

      + + +

      Change the file system timestamps of the object referenced by the supplied file +descriptor. See fs.utimes().

      +

      This function does not work on AIX versions before 7.1, it will return the +error UV_ENOSYS.

      +

      fs.futimesSync(fd, atime, mtime)#

      + + +

      Synchronous version of fs.futimes(). Returns undefined.

      +

      fs.lchmod(path, mode, callback)#

      + + +

      Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback.

      +

      Only available on macOS.

      +

      fs.lchmodSync(path, mode)#

      + + +

      Synchronous lchmod(2). Returns undefined.

      +

      fs.lchown(path, uid, gid, callback)#

      + + +

      Asynchronous lchown(2). No arguments other than a possible exception are given +to the completion callback.

      +

      fs.lchownSync(path, uid, gid)#

      + + +

      Synchronous lchown(2). Returns undefined.

      +

      fs.lutimes(path, atime, mtime, callback)#

      + + +

      Changes the access and modification times of a file in the same way as +fs.utimes(), with the difference that if the path refers to a symbolic +link, then the link is not dereferenced: instead, the timestamps of the +symbolic link itself are changed.

      +

      No arguments other than a possible exception are given to the completion +callback.

      +

      fs.lutimesSync(path, atime, mtime)#

      + + +

      Change the file system timestamps of the symbolic link referenced by path. +Returns undefined, or throws an exception when parameters are incorrect or +the operation fails. This is the synchronous version of fs.lutimes().

      +

      fs.link(existingPath, newPath, callback)#

      + + +

      Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback.

      +

      fs.linkSync(existingPath, newPath)#

      + + +

      Synchronous link(2). Returns undefined.

      +

      fs.lstat(path[, options], callback)#

      + + +

      Asynchronous lstat(2). 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 link, then the link itself is stat-ed, +not the file that it refers to.

      +

      fs.lstatSync(path[, options])#

      + + +

      Synchronous lstat(2).

      +

      fs.mkdir(path[, options], callback)#

      + + +

      Asynchronously creates a directory.

      +

      The callback is given a possible exception and, if recursive is true, the +first directory path created, (err, [path]).

      +

      The optional options argument can be an integer specifying mode (permission +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 exists results in an error only +when recursive is false.

      +
      // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
      +fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
      +  if (err) throw err;
      +});
      +

      On Windows, using fs.mkdir() on the root directory even with recursion will +result in an error:

      +
      fs.mkdir('/', { recursive: true }, (err) => {
      +  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
      +});
      +

      See also: mkdir(2).

      +

      fs.mkdirSync(path[, options])#

      + + +

      Synchronously creates a directory. Returns undefined, or if recursive is +true, the first directory path created. +This is the synchronous version of fs.mkdir().

      +

      See also: mkdir(2).

      +

      fs.mkdtemp(prefix[, options], callback)#

      + + +

      Creates a unique temporary directory.

      +

      Generates six random characters to be appended behind a required +prefix to create a unique temporary directory. Due to platform +inconsistencies, avoid trailing X characters in prefix. Some platforms, +notably the BSDs, can return more than six random characters, and replace +trailing X characters in prefix with random characters.

      +

      The created directory path is passed as a string to the callback's second +parameter.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use.

      +
      fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
      +  if (err) throw err;
      +  console.log(directory);
      +  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
      +});
      +

      The fs.mkdtemp() method will append the six randomly selected characters +directly to the prefix string. For instance, given a directory /tmp, if the +intention is to create a temporary directory within /tmp, the prefix +must end with a trailing platform-specific path separator +(require('path').sep).

      +
      // The parent directory for the new temporary directory
      +const tmpDir = os.tmpdir();
      +
      +// This method is *INCORRECT*:
      +fs.mkdtemp(tmpDir, (err, directory) => {
      +  if (err) throw err;
      +  console.log(directory);
      +  // Will print something similar to `/tmpabc123`.
      +  // A new temporary directory is created at the file system root
      +  // rather than *within* the /tmp directory.
      +});
      +
      +// This method is *CORRECT*:
      +const { sep } = require('path');
      +fs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
      +  if (err) throw err;
      +  console.log(directory);
      +  // Will print something similar to `/tmp/abc123`.
      +  // A new temporary directory is created within
      +  // the /tmp directory.
      +});
      +

      fs.mkdtempSync(prefix[, options])#

      + + +

      Returns the created directory path.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.mkdtemp().

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use.

      +

      fs.open(path[, flags[, mode]], callback)#

      + + +

      Asynchronous file open. See open(2).

      +

      mode sets the file mode (permission and sticky bits), but only if the file was +created. On Windows, only the write permission can be manipulated; see +fs.chmod().

      +

      The callback gets two arguments (err, fd).

      +

      Some characters (< > : " / \ | ? *) are reserved under Windows as documented +by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains +a colon, Node.js will open a file system stream, as described by +this MSDN page.

      +

      Functions based on fs.open() exhibit this behavior as well: +fs.writeFile(), fs.readFile(), etc.

      +

      fs.opendir(path[, options], callback)#

      + + +

      Asynchronously open a directory. See opendir(3).

      +

      Creates an fs.Dir, which contains all further functions for reading from +and cleaning up the directory.

      +

      The encoding option sets the encoding for the path while opening the +directory and subsequent read operations.

      +

      fs.opendirSync(path[, options])#

      + +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • encoding <string> | <null> Default: 'utf8'
        • +
        • bufferSize <number> Number of directory entries that are buffered +internally when reading from the directory. Higher values lead to better +performance but higher memory usage. Default: 32
        • +
        +
      • +
      • Returns: <fs.Dir>
      • +
      +

      Synchronously open a directory. See opendir(3).

      +

      Creates an fs.Dir, which contains all further functions for reading from +and cleaning up the directory.

      +

      The encoding option sets the encoding for the path while opening the +directory and subsequent read operations.

      +

      fs.openSync(path[, flags, mode])#

      + + +

      Returns an integer representing the file descriptor.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.open().

      +

      fs.read(fd, buffer, offset, length, position, callback)#

      + + +

      Read data from the file specified by fd.

      +

      buffer is the buffer that the data (read from the fd) will be written to.

      +

      offset is the offset in the buffer to start writing at.

      +

      length is an integer specifying the number of bytes to read.

      +

      position is an argument specifying where to begin reading from in the file. +If position is null, data will be read from the current file position, +and the file position will be updated. +If position is an integer, the file position will remain unchanged.

      +

      The callback is given the three arguments, (err, bytesRead, buffer).

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with bytesRead and buffer properties.

      +

      fs.read(fd, [options,] callback)#

      + + +

      Similar to the above fs.read function, this version takes an optional options object. +If no options object is specified, it will default with the above values.

      +

      fs.readdir(path[, options], callback)#

      + + +

      Asynchronous readdir(3). 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 '..'.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the filenames passed to the callback. If the encoding is set to 'buffer', +the filenames returned will be passed as Buffer objects.

      +

      If options.withFileTypes is set to true, the files array will contain +fs.Dirent objects.

      +

      fs.readdirSync(path[, options])#

      + + +

      Synchronous readdir(3).

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the filenames returned. If the encoding is set to 'buffer', +the filenames returned will be passed as Buffer objects.

      +

      If options.withFileTypes is set to true, the result will contain +fs.Dirent objects.

      +

      fs.readFile(path[, options], callback)#

      + + +

      Asynchronously reads the entire contents of a file.

      +
      fs.readFile('/etc/passwd', (err, data) => {
      +  if (err) throw err;
      +  console.log(data);
      +});
      +

      The callback is passed two arguments (err, data), where data is the +contents of the file.

      +

      If no encoding is specified, then the raw buffer is returned.

      +

      If options is a string, then it specifies the encoding:

      +
      fs.readFile('/etc/passwd', 'utf8', callback);
      +

      When the path is a directory, the behavior of fs.readFile() and +fs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an +error will be returned. On FreeBSD, a representation of the directory's contents +will be returned.

      +
      // macOS, Linux, and Windows
      +fs.readFile('<directory>', (err, data) => {
      +  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
      +});
      +
      +//  FreeBSD
      +fs.readFile('<directory>', (err, data) => {
      +  // => null, <data>
      +});
      +

      The fs.readFile() function buffers the entire file. To minimize memory costs, +when possible prefer streaming via fs.createReadStream().

      +

      File descriptors#

      +
        +
      1. Any specified file descriptor has to support reading.
      2. +
      3. If a file descriptor is specified as the path, it will not be closed +automatically.
      4. +
      5. The reading will begin at the current position. For example, if the file +already had 'Hello World' and six bytes are read with the file descriptor, +the call to fs.readFile() with the same file descriptor, would give +'World', rather than 'Hello World'.
      6. +
      +

      fs.readFileSync(path[, options])#

      + + +

      Returns the contents of the path.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.readFile().

      +

      If the encoding option is specified then this function returns a +string. Otherwise it returns a buffer.

      +

      Similar to fs.readFile(), when the path is a directory, the behavior of +fs.readFileSync() is platform-specific.

      +
      // macOS, Linux, and Windows
      +fs.readFileSync('<directory>');
      +// => [Error: EISDIR: illegal operation on a directory, read <directory>]
      +
      +//  FreeBSD
      +fs.readFileSync('<directory>'); // => <data>
      +

      fs.readlink(path[, options], callback)#

      + + +

      Asynchronous readlink(2). The callback gets two arguments (err, linkString).

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the link path passed to the callback. If the encoding is set to 'buffer', +the link path returned will be passed as a Buffer object.

      +

      fs.readlinkSync(path[, options])#

      + + +

      Synchronous readlink(2). Returns the symbolic link's string value.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the link path returned. If the encoding is set to 'buffer', +the link path returned will be passed as a Buffer object.

      +

      fs.readSync(fd, buffer, offset, length, position)#

      + + +

      Returns the number of bytesRead.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.read().

      +

      fs.readSync(fd, buffer, [options])#

      + + +

      Returns the number of bytesRead.

      +

      Similar to the above fs.readSync function, this version takes an optional options object. +If no options object is specified, it will default with the above values.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.read().

      +

      fs.readv(fd, buffers[, position], callback)#

      + + +

      Read from a file specified by fd and write to an array of ArrayBufferViews +using readv().

      +

      position is the offset from the beginning of the file from where data +should be read. If typeof position !== 'number', the data will be read +from the current position.

      +

      The callback will be given three arguments: err, bytesRead, and +buffers. bytesRead is how many bytes were read from the file.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with bytesRead and buffers properties.

      +

      fs.readvSync(fd, buffers[, position])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.readv().

      +

      fs.realpath(path[, options], callback)#

      + + +

      Asynchronously computes the canonical pathname by resolving ., .. and +symbolic links.

      +

      A canonical pathname is not necessarily unique. Hard links and bind mounts can +expose a file system entity through many pathnames.

      +

      This function behaves like realpath(3), with some exceptions:

      +
        +
      1. +

        No case conversion is performed on case-insensitive file systems.

        +
      2. +
      3. +

        The maximum number of symbolic links is platform-independent and generally +(much) higher than what the native realpath(3) implementation supports.

        +
      4. +
      +

      The callback gets two arguments (err, resolvedPath). May use process.cwd +to resolve relative paths.

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path passed to the callback. If the encoding is set to 'buffer', +the path returned will be passed as a Buffer object.

      +

      If path resolves to a socket or a pipe, the function will return a system +dependent name for that object.

      +

      fs.realpath.native(path[, options], callback)#

      + + +

      Asynchronous realpath(3).

      +

      The callback gets two arguments (err, resolvedPath).

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path passed to the callback. If the encoding is set to 'buffer', +the path returned will be passed as a Buffer object.

      +

      On Linux, when Node.js is linked against musl libc, the procfs file system must +be mounted on /proc in order for this function to work. Glibc does not have +this restriction.

      +

      fs.realpathSync(path[, options])#

      + + +

      Returns the resolved pathname.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.realpath().

      +

      fs.realpathSync.native(path[, options])#

      + + +

      Synchronous realpath(3).

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path returned. If the encoding is set to 'buffer', +the path returned will be passed as a Buffer object.

      +

      On Linux, when Node.js is linked against musl libc, the procfs file system must +be mounted on /proc in order for this function to work. Glibc does not have +this restriction.

      +

      fs.rename(oldPath, newPath, callback)#

      + + +

      Asynchronously rename file at oldPath to the pathname provided +as newPath. In the case that newPath already exists, it will +be overwritten. If there is a directory at newPath, an error will +be raised instead. No arguments other than a possible exception are +given to the completion callback.

      +

      See also: rename(2).

      +
      fs.rename('oldFile.txt', 'newFile.txt', (err) => {
      +  if (err) throw err;
      +  console.log('Rename complete!');
      +});
      +

      fs.renameSync(oldPath, newPath)#

      + + +

      Synchronous rename(2). Returns undefined.

      +

      fs.rmdir(path[, options], callback)#

      + +

      Stability: 1 - Recursive removal is experimental.

      +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or +EPERM error is encountered, Node.js will retry the operation with a linear +backoff wait of retryDelay ms longer on each try. This option represents the +number of retries. This option is ignored if the recursive option is not +true. Default: 0.
        • +
        • recursive <boolean> If true, perform a recursive directory removal. In +recursive mode, errors are not reported if path does not exist, and +operations are retried on failure. Default: false.
        • +
        • retryDelay <integer> The amount of time in milliseconds to wait between +retries. This option is ignored if the recursive option is not true. +Default: 100.
        • +
        +
      • +
      • callback <Function> + +
      • +
      +

      Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback.

      +

      Using fs.rmdir() on a file (not a directory) results in an ENOENT error on +Windows and an ENOTDIR error on POSIX.

      +

      fs.rmdirSync(path[, options])#

      + +

      Stability: 1 - Recursive removal is experimental.

      +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or +EPERM error is encountered, Node.js will retry the operation with a linear +backoff wait of retryDelay ms longer on each try. This option represents the +number of retries. This option is ignored if the recursive option is not +true. Default: 0.
        • +
        • recursive <boolean> If true, perform a recursive directory removal. In +recursive mode, errors are not reported if path does not exist, and +operations are retried on failure. Default: false.
        • +
        • retryDelay <integer> The amount of time in milliseconds to wait between +retries. This option is ignored if the recursive option is not true. +Default: 100.
        • +
        +
      • +
      +

      Synchronous rmdir(2). Returns undefined.

      +

      Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error +on Windows and an ENOTDIR error on POSIX.

      +

      fs.stat(path[, options], callback)#

      + + +

      Asynchronous stat(2). The callback gets two arguments (err, stats) where +stats is an fs.Stats object.

      +

      In case of an error, the err.code will be one of Common System Errors.

      +

      Using fs.stat() to check for the existence of a file before calling +fs.open(), fs.readFile() or fs.writeFile() is not recommended. +Instead, user code should open/read/write the file directly and handle the +error raised if the file is not available.

      +

      To check if a file exists without manipulating it afterwards, fs.access() +is recommended.

      +

      For example, given the following directory structure:

      +
      - txtDir
      +-- file.txt
      +- app.js
      +

      The next program will check for the stats of the given paths:

      +
      const fs = require('fs');
      +
      +const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
      +
      +for (let i = 0; i < pathsToCheck.length; i++) {
      +  fs.stat(pathsToCheck[i], function(err, stats) {
      +    console.log(stats.isDirectory());
      +    console.log(stats);
      +  });
      +}
      +

      The resulting output will resemble:

      +
      true
      +Stats {
      +  dev: 16777220,
      +  mode: 16877,
      +  nlink: 3,
      +  uid: 501,
      +  gid: 20,
      +  rdev: 0,
      +  blksize: 4096,
      +  ino: 14214262,
      +  size: 96,
      +  blocks: 0,
      +  atimeMs: 1561174653071.963,
      +  mtimeMs: 1561174614583.3518,
      +  ctimeMs: 1561174626623.5366,
      +  birthtimeMs: 1561174126937.2893,
      +  atime: 2019-06-22T03:37:33.072Z,
      +  mtime: 2019-06-22T03:36:54.583Z,
      +  ctime: 2019-06-22T03:37:06.624Z,
      +  birthtime: 2019-06-22T03:28:46.937Z
      +}
      +false
      +Stats {
      +  dev: 16777220,
      +  mode: 33188,
      +  nlink: 1,
      +  uid: 501,
      +  gid: 20,
      +  rdev: 0,
      +  blksize: 4096,
      +  ino: 14214074,
      +  size: 8,
      +  blocks: 8,
      +  atimeMs: 1561174616618.8555,
      +  mtimeMs: 1561174614584,
      +  ctimeMs: 1561174614583.8145,
      +  birthtimeMs: 1561174007710.7478,
      +  atime: 2019-06-22T03:36:56.619Z,
      +  mtime: 2019-06-22T03:36:54.584Z,
      +  ctime: 2019-06-22T03:36:54.584Z,
      +  birthtime: 2019-06-22T03:26:47.711Z
      +}
      +

      fs.statSync(path[, options])#

      + + +

      Synchronous stat(2).

      +

      fs.symlink(target, path[, type], callback)#

      + + +

      Asynchronous symlink(2) which creates the link called path pointing to +target. No arguments other than a possible exception are given to the +completion callback.

      +

      The type argument is only available on Windows and ignored on other platforms. +It can be set to 'dir', 'file', or 'junction'. If the type argument is +not set, Node.js will autodetect target type and use 'file' or 'dir'. If +the target does not exist, 'file' will be used. Windows junction points +require the destination path to be absolute. When using 'junction', the +target argument will automatically be normalized to absolute path.

      +

      Relative targets are relative to the link’s parent directory.

      +
      fs.symlink('./mew', './example/mewtwo', callback);
      +

      The above example creates a symbolic link mewtwo in the example which points +to mew in the same directory:

      +
      $ tree example/
      +example/
      +├── mew
      +└── mewtwo -> ./mew
      +

      fs.symlinkSync(target, path[, type])#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.symlink().

      +

      fs.truncate(path[, len], callback)#

      + + +

      Asynchronous truncate(2). No arguments other than a possible exception are +given to the completion callback. A file descriptor can also be passed as the +first argument. In this case, fs.ftruncate() is called.

      +

      Passing a file descriptor is deprecated and may result in an error being thrown +in the future.

      +

      fs.truncateSync(path[, len])#

      + + +

      Synchronous truncate(2). Returns undefined. A file descriptor can also be +passed as the first argument. In this case, fs.ftruncateSync() is called.

      +

      Passing a file descriptor is deprecated and may result in an error being thrown +in the future.

      +

      fs.unlink(path, callback)#

      + + +

      Asynchronously removes a file or symbolic link. No arguments other than a +possible exception are given to the completion callback.

      +
      // Assuming that 'path/file.txt' is a regular file.
      +fs.unlink('path/file.txt', (err) => {
      +  if (err) throw err;
      +  console.log('path/file.txt was deleted');
      +});
      +

      fs.unlink() will not work on a directory, empty or otherwise. To remove a +directory, use fs.rmdir().

      +

      See also: unlink(2).

      +

      fs.unlinkSync(path)#

      + + +

      Synchronous unlink(2). Returns undefined.

      +

      fs.unwatchFile(filename[, listener])#

      + + +

      Stop watching for changes on filename. If listener is specified, only that +particular listener is removed. Otherwise, all listeners are removed, +effectively stopping watching of filename.

      +

      Calling fs.unwatchFile() with a filename that is not being watched is a +no-op, not an error.

      +

      Using fs.watch() is more efficient than fs.watchFile() and +fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() +and fs.unwatchFile() when possible.

      +

      fs.utimes(path, atime, mtime, callback)#

      + + +

      Change the file system timestamps of the object referenced by path.

      +

      The atime and mtime arguments follow these rules:

      +
        +
      • Values can be either numbers representing Unix epoch time in seconds, +Dates, or a numeric string like '123456789.0'.
      • +
      • If the value can not be converted to a number, or is NaN, Infinity or +-Infinity, an Error will be thrown.
      • +
      +

      fs.utimesSync(path, atime, mtime)#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.utimes().

      +

      fs.watch(filename[, options][, listener])#

      + +
        +
      • filename <string> | <Buffer> | <URL>
      • +
      • options <string> | <Object> +
          +
        • persistent <boolean> Indicates whether the process should continue to run +as long as files are being watched. Default: true.
        • +
        • recursive <boolean> Indicates whether all subdirectories should be +watched, or only the current directory. This applies when a directory is +specified, and only on supported platforms (See Caveats). Default: +false.
        • +
        • encoding <string> Specifies the character encoding to be used for the + filename passed to the listener. Default: 'utf8'.
        • +
        +
      • +
      • listener <Function> | <undefined> Default: undefined + +
      • +
      • Returns: <fs.FSWatcher>
      • +
      +

      Watch for changes on filename, where filename is either a file or a +directory.

      +

      The second argument is optional. If options is provided as a string, it +specifies the encoding. Otherwise options should be passed as an object.

      +

      The listener callback gets two arguments (eventType, filename). eventType +is either 'rename' or 'change', and filename is the name of the file +which triggered the event.

      +

      On most platforms, 'rename' is emitted whenever a filename appears or +disappears in the directory.

      +

      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.

      +

      Caveats#

      + +

      The fs.watch API is not 100% consistent across platforms, and is +unavailable in some situations.

      +

      The recursive option is only supported on macOS and Windows.

      +

      On Windows, no events will be emitted if the watched directory is moved or +renamed. An EPERM error is reported when the watched directory is deleted.

      +

      Availability#

      + +

      This feature depends on the underlying operating system providing a way +to be notified of filesystem changes.

      +
        +
      • On Linux systems, this uses inotify(7).
      • +
      • On BSD systems, this uses kqueue(2).
      • +
      • On macOS, this uses kqueue(2) for files and FSEvents for +directories.
      • +
      • On SunOS systems (including Solaris and SmartOS), this uses event ports.
      • +
      • On Windows systems, this feature depends on ReadDirectoryChangesW.
      • +
      • On Aix systems, this feature depends on AHAFS, which must be enabled.
      • +
      • On IBM i systems, this feature is not supported.
      • +
      +

      If the underlying functionality is not available for some reason, then +fs.watch() will not be able to function and may thrown an exception. +For example, watching files or directories can be unreliable, and in some +cases impossible, on network file systems (NFS, SMB, etc) or host file systems +when using virtualization software such as Vagrant or Docker.

      +

      It is still possible to use fs.watchFile(), which uses stat polling, but +this method is slower and less reliable.

      +

      Inodes#

      + +

      On Linux and macOS systems, fs.watch() resolves the path to an inode and +watches the inode. If the watched path is deleted and recreated, it is assigned +a new inode. The watch will emit an event for the delete but will continue +watching the original inode. Events for the new inode will not be emitted. +This is expected behavior.

      +

      AIX files retain the same inode for the lifetime of a file. Saving and closing a +watched file on AIX will result in two notifications (one for adding new +content, and one for truncation).

      +

      Filename argument#

      + +

      Providing filename argument in the callback is only supported on Linux, +macOS, Windows, and AIX. Even on supported platforms, filename is not always +guaranteed to be provided. Therefore, don't assume that filename argument is +always provided in the callback, and have some fallback logic if it is null.

      +
      fs.watch('somedir', (eventType, filename) => {
      +  console.log(`event type is: ${eventType}`);
      +  if (filename) {
      +    console.log(`filename provided: ${filename}`);
      +  } else {
      +    console.log('filename not provided');
      +  }
      +});
      +

      fs.watchFile(filename[, options], listener)#

      + + +

      Watch for changes on filename. The callback listener will be called each +time the file is accessed.

      +

      The options argument may be omitted. If provided, it should be an object. The +options object may contain a boolean named persistent that indicates +whether the process should continue to run as long as files are being watched. +The options object may specify an interval property indicating how often the +target should be polled in milliseconds.

      +

      The listener gets two arguments the current stat object and the previous +stat object:

      +
      fs.watchFile('message.text', (curr, prev) => {
      +  console.log(`the current mtime is: ${curr.mtime}`);
      +  console.log(`the previous mtime was: ${prev.mtime}`);
      +});
      +

      These stat objects are instances of fs.Stat. If the bigint option is true, +the numeric values in these objects are specified as BigInts.

      +

      To be notified when the file was modified, not just accessed, it is necessary +to compare curr.mtime and prev.mtime.

      +

      When an fs.watchFile operation results in an ENOENT error, it +will invoke the listener once, with all the fields zeroed (or, for dates, the +Unix Epoch). If the file is created later on, the listener will be called +again, with the latest stat objects. This is a change in functionality since +v0.10.

      +

      Using fs.watch() is more efficient than fs.watchFile and +fs.unwatchFile. fs.watch should be used instead of fs.watchFile and +fs.unwatchFile when possible.

      +

      When a file being watched by fs.watchFile() disappears and reappears, +then the contents of previous in the second callback event (the file's +reappearance) will be the same as the contents of previous in the first +callback event (its disappearance).

      +

      This happens when:

      +
        +
      • the file is deleted, followed by a restore
      • +
      • the file is renamed and then renamed a second time back to its original name
      • +
      +

      fs.write(fd, buffer[, offset[, length[, position]]], callback)#

      + + +

      Write buffer to the file specified by fd.

      +

      offset determines the part of the buffer to be written, and length is +an integer specifying the number of bytes to write.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position. See pwrite(2).

      +

      The callback will be given three arguments (err, bytesWritten, buffer) where +bytesWritten specifies how many bytes were written from buffer.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with bytesWritten and buffer properties.

      +

      It is unsafe to use fs.write() multiple times on the same file without waiting +for the callback. For this scenario, fs.createWriteStream() is +recommended.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      fs.write(fd, string[, position[, encoding]], callback)#

      + + +

      Write string to the file specified by fd. If string is not a string, then +the value will be coerced to one.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If typeof position !== 'number' the data will be written at +the current position. See pwrite(2).

      +

      encoding is the expected string encoding.

      +

      The callback will receive the arguments (err, written, string) where written +specifies how many bytes the passed string required to be written. Bytes +written is not necessarily the same as string characters written. See +Buffer.byteLength.

      +

      It is unsafe to use fs.write() multiple times on the same file without waiting +for the callback. For this scenario, fs.createWriteStream() is +recommended.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      On Windows, if the file descriptor is connected to the console (e.g. fd == 1 +or stdout) a string containing non-ASCII characters will not be rendered +properly by default, regardless of the encoding used. +It is possible to configure the console to render UTF-8 properly by changing the +active codepage with the chcp 65001 command. See the chcp docs for more +details.

      +

      fs.writeFile(file, data[, options], callback)#

      + + +

      When file is a filename, asynchronously writes data to the file, replacing the +file if it already exists. data can be a string or a buffer.

      +

      When file is a file descriptor, the behavior is similar to calling +fs.write() directly (which is recommended). See the notes below on using +a file descriptor.

      +

      The encoding option is ignored if data is a buffer.

      +
      const data = new Uint8Array(Buffer.from('Hello Node.js'));
      +fs.writeFile('message.txt', data, (err) => {
      +  if (err) throw err;
      +  console.log('The file has been saved!');
      +});
      +

      If options is a string, then it specifies the encoding:

      +
      fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
      +

      It is unsafe to use fs.writeFile() multiple times on the same file without +waiting for the callback. For this scenario, fs.createWriteStream() is +recommended.

      +

      Using fs.writeFile() with file descriptors#

      +

      When file is a file descriptor, the behavior is almost identical to directly +calling fs.write() like:

      +
      fs.write(fd, Buffer.from(data, options.encoding), callback);
      +

      The difference from directly calling fs.write() is that under some unusual +conditions, fs.write() may write only part of the buffer and will need to be +retried to write the remaining data, whereas fs.writeFile() will retry until +the data is entirely written (or an error occurs).

      +

      The implications of this are a common source of confusion. In +the file descriptor case, the file is not replaced! The data is not necessarily +written to the beginning of the file, and the file's original data may remain +before and/or after the newly written data.

      +

      For example, if fs.writeFile() is called twice in a row, first to write the +string 'Hello', then to write the string ', World', the file would contain +'Hello, World', and might contain some of the file's original data (depending +on the size of the original file, and the position of the file descriptor). If +a file name had been used instead of a descriptor, the file would be guaranteed +to contain only ', World'.

      +

      fs.writeFileSync(file, data[, options])#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.writeFile().

      +

      fs.writeSync(fd, buffer[, offset[, length[, position]]])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.write(fd, buffer...).

      +

      fs.writeSync(fd, string[, position[, encoding]])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.write(fd, string...).

      +

      fs.writev(fd, buffers[, position], callback)#

      + + +

      Write an array of ArrayBufferViews to the file specified by fd using +writev().

      +

      position is the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position.

      +

      The callback will be given three arguments: err, bytesWritten, and +buffers. bytesWritten is how many bytes were written from buffers.

      +

      If this method is util.promisify()ed, it returns a Promise for an +Object with bytesWritten and buffers properties.

      +

      It is unsafe to use fs.writev() multiple times on the same file without +waiting for the callback. For this scenario, use fs.createWriteStream().

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      fs.writevSync(fd, buffers[, position])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.writev().

      +

      fs Promises API#

      +

      The fs.promises API provides an alternative set of asynchronous file system +methods that return Promise objects rather than using callbacks. The +API is accessible via require('fs').promises.

      +

      Class: FileHandle#

      + +

      A FileHandle object is a wrapper for a numeric file descriptor. +Instances of FileHandle are distinct from numeric file descriptors +in that they provide an object oriented API for working with files.

      +

      If a FileHandle is not closed using the +filehandle.close() method, it might automatically close the file descriptor +and will emit a process warning, thereby helping to prevent memory leaks. +Please do not rely on this behavior because it is unreliable and +the file may not be closed. Instead, always explicitly close FileHandles. +Node.js may change this behavior in the future.

      +

      Instances of the FileHandle object are created internally by the +fsPromises.open() method.

      +

      Unlike the callback-based API (fs.fstat(), fs.fchown(), fs.fchmod(), and +so on), a numeric file descriptor is not used by the promise-based API. Instead, +the promise-based API uses the FileHandle class in order to help avoid +accidental leaking of unclosed file descriptors after a Promise is resolved or +rejected.

      +

      filehandle.appendFile(data, options)#

      + + +

      Alias of filehandle.writeFile().

      +

      When operating on file handles, the mode cannot be changed from what it was set +to with fsPromises.open(). Therefore, this is equivalent to +filehandle.writeFile().

      +

      filehandle.chmod(mode)#

      + + +

      Modifies the permissions on the file. The Promise is resolved with no +arguments upon success.

      +

      filehandle.chown(uid, gid)#

      + + +

      Changes the ownership of the file then resolves the Promise with no arguments +upon success.

      +

      filehandle.close()#

      + +
        +
      • Returns: <Promise> A Promise that will be resolved once the underlying +file descriptor is closed, or will be rejected if an error occurs while +closing.
      • +
      +

      Closes the file descriptor.

      +
      const fsPromises = require('fs').promises;
      +async function openAndClose() {
      +  let filehandle;
      +  try {
      +    filehandle = await fsPromises.open('thefile.txt', 'r');
      +  } finally {
      +    if (filehandle !== undefined)
      +      await filehandle.close();
      +  }
      +}
      +

      filehandle.datasync()#

      + + +

      Asynchronous fdatasync(2). The Promise is resolved with no arguments upon +success.

      +

      filehandle.fd#

      + +
        +
      • <number> The numeric file descriptor managed by the FileHandle object.
      • +
      +

      filehandle.read(buffer, offset, length, position)#

      + + +

      Read data from the file.

      +

      buffer is the buffer that the data will be written to.

      +

      offset is the offset in the buffer to start writing at.

      +

      length is an integer specifying the number of bytes to read.

      +

      position is an argument specifying where to begin reading from in the file. +If position is null, data will be read from the current file position, +and the file position will be updated. +If position is an integer, the file position will remain unchanged.

      +

      Following successful read, the Promise is resolved with an object with a +bytesRead property specifying the number of bytes read, and a buffer +property that is a reference to the passed in buffer argument.

      +

      filehandle.read(options)#

      + + +

      filehandle.readFile(options)#

      + + +

      Asynchronously reads the entire contents of a file.

      +

      The Promise is resolved with the contents of the file. If no encoding is +specified (using options.encoding), the data is returned as a Buffer +object. Otherwise, the data will be a string.

      +

      If options is a string, then it specifies the encoding.

      +

      The FileHandle has to support reading.

      +

      If one or more filehandle.read() calls are made on a file handle and then a +filehandle.readFile() call is made, the data will be read from the current +position till the end of the file. It doesn't always read from the beginning +of the file.

      +

      filehandle.readv(buffers[, position])#

      + + +

      Read from a file and write to an array of ArrayBufferViews

      +

      The Promise is resolved with an object containing a bytesRead property +identifying the number of bytes read, and a buffers property containing +a reference to the buffers input.

      +

      position is the offset from the beginning of the file where this data +should be read from. If typeof position !== 'number', the data will be read +from the current position.

      +

      filehandle.stat([options])#

      + + +

      Retrieves the fs.Stats for the file.

      +

      filehandle.sync()#

      + + +

      Asynchronous fsync(2). The Promise is resolved with no arguments upon +success.

      +

      filehandle.truncate(len)#

      + + +

      Truncates the file then resolves the Promise with no arguments upon success.

      +

      If the file was larger than len bytes, only the first len bytes will be +retained in the file.

      +

      For example, the following program retains only the first four bytes of the +file:

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +
      +console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +async function doTruncate() {
      +  let filehandle = null;
      +  try {
      +    filehandle = await fsPromises.open('temp.txt', 'r+');
      +    await filehandle.truncate(4);
      +  } finally {
      +    if (filehandle) {
      +      // Close the file if it is opened.
      +      await filehandle.close();
      +    }
      +  }
      +  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node
      +}
      +
      +doTruncate().catch(console.error);
      +

      If the file previously was shorter than len bytes, it is extended, and the +extended part is filled with null bytes ('\0'):

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +
      +console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +async function doTruncate() {
      +  let filehandle = null;
      +  try {
      +    filehandle = await fsPromises.open('temp.txt', 'r+');
      +    await filehandle.truncate(10);
      +  } finally {
      +    if (filehandle) {
      +      // Close the file if it is opened.
      +      await filehandle.close();
      +    }
      +  }
      +  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\0\0\0
      +}
      +
      +doTruncate().catch(console.error);
      +

      The last three bytes are null bytes ('\0'), to compensate the over-truncation.

      +

      filehandle.utimes(atime, mtime)#

      + + +

      Change the file system timestamps of the object referenced by the FileHandle +then resolves the Promise with no arguments upon success.

      +

      This function does not work on AIX versions before 7.1, it will resolve the +Promise with an error using code UV_ENOSYS.

      +

      filehandle.write(buffer[, offset[, length[, position]]])#

      + + +

      Write buffer to the file.

      +

      The Promise is resolved with an object containing a bytesWritten property +identifying the number of bytes written, and a buffer property containing +a reference to the buffer written.

      +

      offset determines the part of the buffer to be written, and length is +an integer specifying the number of bytes to write.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position. See pwrite(2).

      +

      It is unsafe to use filehandle.write() multiple times on the same file +without waiting for the Promise to be resolved (or rejected). For this +scenario, use fs.createWriteStream().

      +

      On Linux, positional writes do not work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      filehandle.write(string[, position[, encoding]])#

      + + +

      Write string to the file. If string is not a string, then +the value will be coerced to one.

      +

      The Promise is resolved with an object containing a bytesWritten property +identifying the number of bytes written, and a buffer property containing +a reference to the string written.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If the type of position is not a number the data +will be written at the current position. See pwrite(2).

      +

      encoding is the expected string encoding.

      +

      It is unsafe to use filehandle.write() multiple times on the same file +without waiting for the Promise to be resolved (or rejected). For this +scenario, use fs.createWriteStream().

      +

      On Linux, positional writes do not work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      filehandle.writeFile(data, options)#

      + + +

      Asynchronously writes data to a file, replacing the file if it already exists. +data can be a string or a buffer. The Promise will be resolved with no +arguments upon success.

      +

      The encoding option is ignored if data is a buffer.

      +

      If options is a string, then it specifies the encoding.

      +

      The FileHandle has to support writing.

      +

      It is unsafe to use filehandle.writeFile() multiple times on the same file +without waiting for the Promise to be resolved (or rejected).

      +

      If one or more filehandle.write() calls are made on a file handle and then a +filehandle.writeFile() call is made, the data will be written from the +current position till the end of the file. It doesn't always write from the +beginning of the file.

      +

      filehandle.writev(buffers[, position])#

      + + +

      Write an array of ArrayBufferViews to the file.

      +

      The Promise is resolved with an object containing a bytesWritten property +identifying the number of bytes written, and a buffers property containing +a reference to the buffers input.

      +

      position is the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position.

      +

      It is unsafe to call writev() multiple times on the same file without waiting +for the previous operation to complete.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      fsPromises.access(path[, mode])#

      + + +

      Tests a user's permissions for the file or directory specified by path. +The mode argument is an optional integer that specifies the accessibility +checks to be performed. Check File access constants for possible values +of mode. It is possible to create a mask consisting of the bitwise OR of +two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      +

      If the accessibility check is successful, the Promise is resolved with no +value. If any of the accessibility checks fail, the Promise is rejected +with an Error object. The following example checks if the file +/etc/passwd can be read and written by the current process.

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +
      +fsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK)
      +  .then(() => console.log('can access'))
      +  .catch(() => console.error('cannot access'));
      +

      Using fsPromises.access() to check for the accessibility of a file before +calling fsPromises.open() is not recommended. Doing so introduces a race +condition, since other processes may change the file's state between the two +calls. Instead, user code should open/read/write the file directly and handle +the error raised if the file is not accessible.

      +

      fsPromises.appendFile(path, data[, options])#

      + + +

      Asynchronously append data to a file, creating the file if it does not yet +exist. data can be a string or a Buffer. The Promise will be +resolved with no arguments upon success.

      +

      If options is a string, then it specifies the encoding.

      +

      The path may be specified as a FileHandle that has been opened +for appending (using fsPromises.open()).

      +

      fsPromises.chmod(path, mode)#

      + + +

      Changes the permissions of a file then resolves the Promise with no +arguments upon succces.

      +

      fsPromises.chown(path, uid, gid)#

      + + +

      Changes the ownership of a file then resolves the Promise with no arguments +upon success.

      +

      fsPromises.copyFile(src, dest[, flags])#

      + + +

      Asynchronously copies src to dest. By default, dest is overwritten if it +already exists. The Promise will be resolved with no arguments upon success.

      +

      Node.js makes no guarantees about the atomicity of the copy operation. If an +error occurs after the destination file has been opened for writing, Node.js +will attempt to remove the destination.

      +

      flags is an optional integer that specifies the behavior +of the copy operation. It is possible to create a mask consisting of the bitwise +OR of two or more values (e.g. +fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      +
        +
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already +exists.
      • +
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a +copy-on-write reflink. If the platform does not support copy-on-write, then a +fallback copy mechanism is used.
      • +
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to +create a copy-on-write reflink. If the platform does not support copy-on-write, +then the operation will fail.
      • +
      +
      const fsPromises = require('fs').promises;
      +
      +// destination.txt will be created or overwritten by default.
      +fsPromises.copyFile('source.txt', 'destination.txt')
      +  .then(() => console.log('source.txt was copied to destination.txt'))
      +  .catch(() => console.log('The file could not be copied'));
      +

      If the third argument is a number, then it specifies flags:

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +const { COPYFILE_EXCL } = fs.constants;
      +
      +// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
      +fsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL)
      +  .then(() => console.log('source.txt was copied to destination.txt'))
      +  .catch(() => console.log('The file could not be copied'));
      +

      fsPromises.lchmod(path, mode)#

      + + +

      Changes the permissions on a symbolic link then resolves the Promise with +no arguments upon success. This method is only implemented on macOS.

      +

      fsPromises.lchown(path, uid, gid)#

      + + +

      Changes the ownership on a symbolic link then resolves the Promise with +no arguments upon success.

      +

      fsPromises.lutimes(path, atime, mtime)#

      + + +

      Changes the access and modification times of a file in the same way as +fsPromises.utimes(), with the difference that if the path refers to a +symbolic link, then the link is not dereferenced: instead, the timestamps of +the symbolic link itself are changed.

      +

      Upon success, the Promise is resolved without arguments.

      +

      fsPromises.link(existingPath, newPath)#

      + + +

      Asynchronous link(2). The Promise is resolved with no arguments upon success.

      +

      fsPromises.lstat(path[, options])#

      + + +

      Asynchronous lstat(2). The Promise is resolved with the fs.Stats object +for the given symbolic link path.

      +

      fsPromises.mkdir(path[, options])#

      + + +

      Asynchronously creates a directory then resolves the Promise with either no +arguments, or the first directory path created if recursive is true.

      +

      The optional options argument can be an integer specifying mode (permission +and sticky bits), or an object with a mode property and a recursive +property indicating whether parent directories should be created. Calling +fsPromises.mkdir() when path is a directory that exists results in a +rejection only when recursive is false.

      +

      fsPromises.mkdtemp(prefix[, options])#

      + + +

      Creates a unique temporary directory and resolves the Promise with the created +directory path. A unique directory name is generated by appending six random +characters to the end of the provided prefix. Due to platform +inconsistencies, avoid trailing X characters in prefix. Some platforms, +notably the BSDs, can return more than six random characters, and replace +trailing X characters in prefix with random characters.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use.

      +
      fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))
      +  .catch(console.error);
      +

      The fsPromises.mkdtemp() method will append the six randomly selected +characters directly to the prefix string. For instance, given a directory +/tmp, if the intention is to create a temporary directory within /tmp, the +prefix must end with a trailing platform-specific path separator +(require('path').sep).

      +

      fsPromises.open(path, flags[, mode])#

      + + +

      Asynchronous file open that returns a Promise that, when resolved, yields a +FileHandle object. See open(2).

      +

      mode sets the file mode (permission and sticky bits), but only if the file was +created.

      +

      Some characters (< > : " / \ | ? *) are reserved under Windows as documented +by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains +a colon, Node.js will open a file system stream, as described by +this MSDN page.

      +

      fsPromises.opendir(path[, options])#

      + + +

      Asynchronously open a directory. See opendir(3).

      +

      Creates an fs.Dir, which contains all further functions for reading from +and cleaning up the directory.

      +

      The encoding option sets the encoding for the path while opening the +directory and subsequent read operations.

      +

      Example using async iteration:

      +
      const fs = require('fs');
      +
      +async function print(path) {
      +  const dir = await fs.promises.opendir(path);
      +  for await (const dirent of dir) {
      +    console.log(dirent.name);
      +  }
      +}
      +print('./').catch(console.error);
      +

      fsPromises.readdir(path[, options])#

      + + +

      Reads the contents of a directory then resolves the Promise with an array +of the names of the files in the directory excluding '.' and '..'.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the filenames. If the encoding is set to 'buffer', the filenames returned +will be passed as Buffer objects.

      +

      If options.withFileTypes is set to true, the resolved array will contain +fs.Dirent objects.

      +
      const fs = require('fs');
      +
      +async function print(path) {
      +  const files = await fs.promises.readdir(path);
      +  for (const file of files) {
      +    console.log(file);
      +  }
      +}
      +print('./').catch(console.error);
      +

      fsPromises.readFile(path[, options])#

      + + +

      Asynchronously reads the entire contents of a file.

      +

      The Promise is resolved with the contents of the file. If no encoding is +specified (using options.encoding), the data is returned as a Buffer +object. Otherwise, the data will be a string.

      +

      If options is a string, then it specifies the encoding.

      +

      When the path is a directory, the behavior of fsPromises.readFile() is +platform-specific. On macOS, Linux, and Windows, the promise will be rejected +with an error. On FreeBSD, a representation of the directory's contents will be +returned.

      +

      Any specified FileHandle has to support reading.

      +

      fsPromises.readlink(path[, options])#

      + + +

      Asynchronous readlink(2). The Promise is resolved with the linkString upon +success.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the link path returned. If the encoding is set to 'buffer', the link path +returned will be passed as a Buffer object.

      +

      fsPromises.realpath(path[, options])#

      + + +

      Determines the actual location of path using the same semantics as the +fs.realpath.native() function then resolves the Promise with the resolved +path.

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path. If the encoding is set to 'buffer', the path returned will be +passed as a Buffer object.

      +

      On Linux, when Node.js is linked against musl libc, the procfs file system must +be mounted on /proc in order for this function to work. Glibc does not have +this restriction.

      +

      fsPromises.rename(oldPath, newPath)#

      + + +

      Renames oldPath to newPath and resolves the Promise with no arguments +upon success.

      +

      fsPromises.rmdir(path[, options])#

      + +

      Stability: 1 - Recursive removal is experimental.

      +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or +EPERM error is encountered, Node.js will retry the operation with a linear +backoff wait of retryDelay ms longer on each try. This option represents the +number of retries. This option is ignored if the recursive option is not +true. Default: 0.
        • +
        • recursive <boolean> If true, perform a recursive directory removal. In +recursive mode, errors are not reported if path does not exist, and +operations are retried on failure. Default: false.
        • +
        • retryDelay <integer> The amount of time in milliseconds to wait between +retries. This option is ignored if the recursive option is not true. +Default: 100.
        • +
        +
      • +
      • Returns: <Promise>
      • +
      +

      Removes the directory identified by path then resolves the Promise with +no arguments upon success.

      +

      Using fsPromises.rmdir() on a file (not a directory) results in the +Promise being rejected with an ENOENT error on Windows and an ENOTDIR +error on POSIX.

      +

      fsPromises.stat(path[, options])#

      + + +

      The Promise is resolved with the fs.Stats object for the given path.

      +

      fsPromises.symlink(target, path[, type])#

      + + +

      Creates a symbolic link then resolves the Promise with no arguments upon +success.

      +

      The type argument is only used on Windows platforms and can be one of 'dir', +'file', or 'junction'. Windows junction points require the destination path +to be absolute. When using 'junction', the target argument will +automatically be normalized to absolute path.

      +

      fsPromises.truncate(path[, len])#

      + + +

      Truncates the path then resolves the Promise with no arguments upon +success. The path must be a string or Buffer.

      +

      fsPromises.unlink(path)#

      + + +

      Asynchronous unlink(2). The Promise is resolved with no arguments upon +success.

      +

      fsPromises.utimes(path, atime, mtime)#

      + + +

      Change the file system timestamps of the object referenced by path then +resolves the Promise with no arguments upon success.

      +

      The atime and mtime arguments follow these rules:

      +
        +
      • Values can be either numbers representing Unix epoch time, Dates, or a +numeric string like '123456789.0'.
      • +
      • If the value can not be converted to a number, or is NaN, Infinity or +-Infinity, an Error will be thrown.
      • +
      +

      fsPromises.writeFile(file, data[, options])#

      + + +

      Asynchronously writes data to a file, replacing the file if it already exists. +data can be a string or a buffer. The Promise will be resolved with no +arguments upon success.

      +

      The encoding option is ignored if data is a buffer.

      +

      If options is a string, then it specifies the encoding.

      +

      Any specified FileHandle has to support writing.

      +

      It is unsafe to use fsPromises.writeFile() multiple times on the same file +without waiting for the Promise to be resolved (or rejected).

      +

      FS constants#

      +

      The following constants are exported by fs.constants.

      +

      Not every constant will be available on every operating system.

      +

      To use more than one constant, use the bitwise OR | operator.

      +

      Example:

      +
      const fs = require('fs');
      +
      +const {
      +  O_RDWR,
      +  O_CREAT,
      +  O_EXCL
      +} = fs.constants;
      +
      +fs.open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
      +  // ...
      +});
      +

      File access constants#

      +

      The following constants are meant for use with fs.access().

      + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      F_OKFlag indicating that the file is visible to the calling process. + This is useful for determining if a file exists, but says nothing + about rwx permissions. Default if no mode is specified.
      R_OKFlag indicating that the file can be read by the calling process.
      W_OKFlag indicating that the file can be written by the calling + process.
      X_OKFlag indicating that the file can be executed by the calling + process. This has no effect on Windows + (will behave like fs.constants.F_OK).
      +

      File copy constants#

      +

      The following constants are meant for use with fs.copyFile().

      + + + + + + + + + + + + + + + + + +
      ConstantDescription
      COPYFILE_EXCLIf present, the copy operation will fail with an error if the + destination path already exists.
      COPYFILE_FICLONEIf present, the copy operation will attempt to create a + copy-on-write reflink. If the underlying platform does not support + copy-on-write, then a fallback copy mechanism is used.
      COPYFILE_FICLONE_FORCEIf present, the copy operation will attempt to create a + copy-on-write reflink. If the underlying platform does not support + copy-on-write, then the operation will fail with an error.
      +

      File open constants#

      +

      The following constants are meant for use with fs.open().

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      O_RDONLYFlag indicating to open a file for read-only access.
      O_WRONLYFlag indicating to open a file for write-only access.
      O_RDWRFlag indicating to open a file for read-write access.
      O_CREATFlag indicating to create the file if it does not already exist.
      O_EXCLFlag indicating that opening a file should fail if the + O_CREAT flag is set and the file already exists.
      O_NOCTTYFlag indicating that if path identifies a terminal device, opening the + path shall not cause that terminal to become the controlling terminal for + the process (if the process does not already have one).
      O_TRUNCFlag 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.
      O_APPENDFlag indicating that data will be appended to the end of the file.
      O_DIRECTORYFlag indicating that the open should fail if the path is not a + directory.
      O_NOATIMEFlag indicating reading accesses to the file system will no longer + result in an update to the atime information associated with + the file. This flag is available on Linux operating systems only.
      O_NOFOLLOWFlag indicating that the open should fail if the path is a symbolic + link.
      O_SYNCFlag indicating that the file is opened for synchronized I/O with write + operations waiting for file integrity.
      O_DSYNCFlag indicating that the file is opened for synchronized I/O with write + operations waiting for data integrity.
      O_SYMLINKFlag indicating to open the symbolic link itself rather than the + resource it is pointing to.
      O_DIRECTWhen set, an attempt will be made to minimize caching effects of file + I/O.
      O_NONBLOCKFlag indicating to open the file in nonblocking mode when possible.
      UV_FS_O_FILEMAPWhen set, a memory file mapping is used to access the file. This flag + is available on Windows operating systems only. On other operating systems, + this flag is ignored.
      +

      File type constants#

      +

      The following constants are meant for use with the fs.Stats object's +mode property for determining a file's type.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      S_IFMTBit mask used to extract the file type code.
      S_IFREGFile type constant for a regular file.
      S_IFDIRFile type constant for a directory.
      S_IFCHRFile type constant for a character-oriented device file.
      S_IFBLKFile type constant for a block-oriented device file.
      S_IFIFOFile type constant for a FIFO/pipe.
      S_IFLNKFile type constant for a symbolic link.
      S_IFSOCKFile type constant for a socket.
      +

      File mode constants#

      +

      The following constants are meant for use with the fs.Stats object's +mode property for determining the access permissions for a file.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      S_IRWXUFile mode indicating readable, writable, and executable by owner.
      S_IRUSRFile mode indicating readable by owner.
      S_IWUSRFile mode indicating writable by owner.
      S_IXUSRFile mode indicating executable by owner.
      S_IRWXGFile mode indicating readable, writable, and executable by group.
      S_IRGRPFile mode indicating readable by group.
      S_IWGRPFile mode indicating writable by group.
      S_IXGRPFile mode indicating executable by group.
      S_IRWXOFile mode indicating readable, writable, and executable by others.
      S_IROTHFile mode indicating readable by others.
      S_IWOTHFile mode indicating writable by others.
      S_IXOTHFile mode indicating executable by others.
      +

      File system flags#

      +

      The following flags are available wherever the flag option takes a +string.

      +
        +
      • +

        'a': Open file for appending. +The file is created if it does not exist.

        +
      • +
      • +

        'ax': Like 'a' but fails if the path exists.

        +
      • +
      • +

        'a+': Open file for reading and appending. +The file is created if it does not exist.

        +
      • +
      • +

        'ax+': Like 'a+' but fails if the path exists.

        +
      • +
      • +

        'as': Open file for appending in synchronous mode. +The file is created if it does not exist.

        +
      • +
      • +

        'as+': Open file for reading and appending in synchronous mode. +The file is created if it does not exist.

        +
      • +
      • +

        'r': Open file for reading. +An exception occurs if the file does not exist.

        +
      • +
      • +

        'r+': Open file for reading and writing. +An exception occurs if the file does not exist.

        +
      • +
      • +

        'rs+': Open file for reading and writing in synchronous mode. Instructs +the operating system to bypass the local file system cache.

        +

        This is primarily useful for opening files on NFS mounts as it allows +skipping the potentially stale local cache. It has a very real impact on +I/O performance so using this flag is not recommended unless it is needed.

        +

        This doesn't turn fs.open() or fsPromises.open() into a synchronous +blocking call. If synchronous operation is desired, something like +fs.openSync() should be used.

        +
      • +
      • +

        'w': Open file for writing. +The file is created (if it does not exist) or truncated (if it exists).

        +
      • +
      • +

        'wx': Like 'w' but fails if the path exists.

        +
      • +
      • +

        'w+': Open file for reading and writing. +The file is created (if it does not exist) or truncated (if it exists).

        +
      • +
      • +

        'wx+': Like 'w+' but fails if the path exists.

        +
      • +
      +

      flag can also be a number as documented by open(2); commonly used constants +are available from fs.constants. On Windows, flags are translated to +their equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE, +or O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.

      +

      The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to +return an error if the path already exists. On POSIX, if the path is a symbolic +link, using O_EXCL returns an error even if the link is to a path that does +not exist. The exclusive flag may or may not work with network file systems.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      Modifying a file rather than replacing it may require a flags mode of 'r+' +rather than the default mode 'w'.

      +

      The behavior of some flags are platform-specific. As such, opening a directory +on macOS and Linux with the 'a+' flag, as in the example below, will return an +error. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle +will be returned.

      +
      // macOS and Linux
      +fs.open('<directory>', 'a+', (err, fd) => {
      +  // => [Error: EISDIR: illegal operation on a directory, open <directory>]
      +});
      +
      +// Windows and FreeBSD
      +fs.open('<directory>', 'a+', (err, fd) => {
      +  // => null, <fd>
      +});
      +

      On Windows, opening an existing hidden file using the 'w' flag (either +through fs.open() or fs.writeFile() or fsPromises.open()) will fail with +EPERM. Existing hidden files can be opened for writing with the 'r+' flag.

      +

      A call to fs.ftruncate() or filehandle.truncate() can be used to reset +the file contents.

      +

      Global objects#

      + + +

      These objects are available in all modules. The following variables may appear +to be global but are not. They exist only in the scope of modules, see the +module system documentation:

      + +

      The objects listed here are specific to Node.js. There are built-in objects +that are part of the JavaScript language itself, which are also globally +accessible.

      +

      Class: Buffer#

      + + + +

      Used to handle binary data. See the buffer section.

      +

      __dirname#

      +

      This variable may appear to be global but is not. See __dirname.

      +

      __filename#

      +

      This variable may appear to be global but is not. See __filename.

      +

      clearImmediate(immediateObject)#

      + + +

      clearImmediate is described in the timers section.

      +

      clearInterval(intervalObject)#

      + + +

      clearInterval is described in the timers section.

      +

      clearTimeout(timeoutObject)#

      + + +

      clearTimeout is described in the timers section.

      +

      console#

      + + + +

      Used to print to stdout and stderr. See the console section.

      +

      exports#

      +

      This variable may appear to be global but is not. See exports.

      +

      global#

      + + +
        +
      • <Object> The global namespace object.
      • +
      +

      In browsers, the top-level scope is the global scope. This means that +within the browser var something will define a new global variable. In +Node.js this is different. The top-level scope is not the global scope; +var something inside a Node.js module will be local to that module.

      +

      module#

      +

      This variable may appear to be global but is not. See module.

      +

      process#

      + + + +

      The process object. See the process object section.

      +

      queueMicrotask(callback)#

      + + + +

      The queueMicrotask() method queues a microtask to invoke callback. If +callback throws an exception, the process object 'uncaughtException' +event will be emitted.

      +

      The microtask queue is managed by V8 and may be used in a similar manner to +the process.nextTick() queue, which is managed by Node.js. The +process.nextTick() queue is always processed before the microtask queue +within each turn of the Node.js event loop.

      +
      // Here, `queueMicrotask()` is used to ensure the 'load' event is always
      +// emitted asynchronously, and therefore consistently. Using
      +// `process.nextTick()` here would result in the 'load' event always emitting
      +// before any other promise jobs.
      +
      +DataHandler.prototype.load = async function load(key) {
      +  const hit = this._cache.get(url);
      +  if (hit !== undefined) {
      +    queueMicrotask(() => {
      +      this.emit('load', hit);
      +    });
      +    return;
      +  }
      +
      +  const data = await fetchData(key);
      +  this._cache.set(url, data);
      +  this.emit('load', data);
      +};
      +

      require()#

      +

      This variable may appear to be global but is not. See require().

      +

      setImmediate(callback[, ...args])#

      + + +

      setImmediate is described in the timers section.

      +

      setInterval(callback, delay[, ...args])#

      + + +

      setInterval is described in the timers section.

      +

      setTimeout(callback, delay[, ...args])#

      + + +

      setTimeout is described in the timers section.

      +

      TextDecoder#

      + + +

      The WHATWG TextDecoder class. See the TextDecoder section.

      +

      TextEncoder#

      + + +

      The WHATWG TextEncoder class. See the TextEncoder section.

      +

      URL#

      + + +

      The WHATWG URL class. See the URL section.

      +

      URLSearchParams#

      + + +

      The WHATWG URLSearchParams class. See the URLSearchParams section.

      +

      WebAssembly#

      + + + +

      The object that acts as the namespace for all W3C +WebAssembly related functionality. See the +Mozilla Developer Network for usage and compatibility.

      +

      HTTP#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/http.js

      +

      To use the HTTP server and client one must require('http').

      +

      The HTTP interfaces in Node.js are designed to support many features +of the protocol which have been traditionally difficult to use. +In particular, large, possibly chunk-encoded, messages. The interface is +careful to never buffer entire requests or responses, so the +user is able to stream data.

      +

      HTTP message headers are represented by an object like this:

      + +
      { 'content-length': '123',
      +  'content-type': 'text/plain',
      +  'connection': 'keep-alive',
      +  'host': 'mysite.com',
      +  'accept': '*/*' }
      +

      Keys are lowercased. Values are not modified.

      +

      In order to support the full spectrum of possible HTTP applications, the Node.js +HTTP API is very low-level. It deals with stream handling and message +parsing only. It parses a message into headers and body but it does not +parse the actual headers or the body.

      +

      See message.headers for details on how duplicate headers are handled.

      +

      The raw headers as they were received are retained in the rawHeaders +property, which is an array of [key, value, key2, value2, ...]. For +example, the previous message header object might have a rawHeaders +list like the following:

      + +
      [ 'ConTent-Length', '123456',
      +  'content-LENGTH', '123',
      +  'content-type', 'text/plain',
      +  'CONNECTION', 'keep-alive',
      +  'Host', 'mysite.com',
      +  'accepT', '*/*' ]
      +

      Class: http.Agent#

      + +

      An Agent is responsible for managing connection persistence +and reuse for HTTP clients. It maintains a queue of pending requests +for a given host and port, reusing a single socket connection for each +until the queue is empty, at which time the socket is either destroyed +or put into a pool where it is kept to be used again for requests to the +same host and port. Whether it is destroyed or pooled depends on the +keepAlive option.

      +

      Pooled connections have TCP Keep-Alive enabled for them, but servers may +still close idle connections, in which case they will be removed from the +pool and a new connection will be made when a new HTTP request is made for +that host and port. Servers may also refuse to allow multiple requests +over the same connection, in which case the connection will have to be +remade for every request and cannot be pooled. The Agent will still make +the requests to that server, but each one will occur over a new connection.

      +

      When a connection is closed by the client or the server, it is removed +from the pool. Any unused sockets in the pool will be unrefed so as not +to keep the Node.js process running when there are no outstanding requests. +(see socket.unref()).

      +

      It is good practice, to destroy() an Agent instance when it is no +longer in use, because unused sockets consume OS resources.

      +

      Sockets are removed from an agent when the socket emits either +a 'close' event or an 'agentRemove' event. When intending to keep one +HTTP request open for a long time without keeping it in the agent, something +like the following may be done:

      +
      http.get(options, (res) => {
      +  // Do stuff
      +}).on('socket', (socket) => {
      +  socket.emit('agentRemove');
      +});
      +

      An agent may also be used for an individual request. By providing +{agent: false} as an option to the http.get() or http.request() +functions, a one-time use Agent with default options will be used +for the client connection.

      +

      agent:false:

      +
      http.get({
      +  hostname: 'localhost',
      +  port: 80,
      +  path: '/',
      +  agent: false  // Create a new agent just for this one request
      +}, (res) => {
      +  // Do stuff with response
      +});
      +

      new Agent([options])#

      + +
        +
      • options <Object> Set of configurable options to set on the agent. +Can have the following fields: +
          +
        • keepAlive <boolean> Keep sockets around even when there are no +outstanding requests, so they can be used for future requests without +having to reestablish a TCP connection. Not to be confused with the +keep-alive value of the Connection header. The Connection: keep-alive +header is always sent when using an agent except when the Connection +header is explicitly specified or when the keepAlive and maxSockets +options are respectively set to false and Infinity, in which case +Connection: close will be used. Default: false.
        • +
        • keepAliveMsecs <number> When using the keepAlive option, specifies +the initial delay +for TCP Keep-Alive packets. Ignored when the +keepAlive option is false or undefined. Default: 1000.
        • +
        • maxSockets <number> Maximum number of sockets to allow per +host. Each request will use a new socket until the maximum is reached. +Default: Infinity.
        • +
        • maxTotalSockets <number> Maximum number of sockets allowed for +all hosts in total. Each request will use a new socket +until the maximum is reached. +Default: Infinity.
        • +
        • maxFreeSockets <number> Maximum number of sockets to leave open +in a free state. Only relevant if keepAlive is set to true. +Default: 256.
        • +
        • scheduling <string> Scheduling strategy to apply when picking +the next free socket to use. It can be 'fifo' or 'lifo'. +The main difference between the two scheduling strategies is that 'lifo' +selects the most recently used socket, while 'fifo' selects +the least recently used socket. +In case of a low rate of request per second, the 'lifo' scheduling +will lower the risk of picking a socket that might have been closed +by the server due to inactivity. +In case of a high rate of request per second, +the 'fifo' scheduling will maximize the number of open sockets, +while the 'lifo' scheduling will keep it as low as possible. +Default: 'fifo'.
        • +
        • timeout <number> Socket timeout in milliseconds. +This will set the timeout when the socket is created.
        • +
        +
      • +
      +

      options in socket.connect() are also supported.

      +

      The default http.globalAgent that is used by http.request() has all +of these values set to their respective defaults.

      +

      To configure any of them, a custom http.Agent instance must be created.

      +
      const http = require('http');
      +const keepAliveAgent = new http.Agent({ keepAlive: true });
      +options.agent = keepAliveAgent;
      +http.request(options, onResponseCallback);
      +

      agent.createConnection(options[, callback])#

      + + +

      Produces a socket/stream to be used for HTTP requests.

      +

      By default, this function is the same as net.createConnection(). However, +custom agents may override this method in case greater flexibility is desired.

      +

      A socket/stream can be supplied in one of two ways: by returning the +socket/stream from this function, or by passing the socket/stream to callback.

      +

      This method is guaranteed to return an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      callback has a signature of (err, stream).

      +

      agent.keepSocketAlive(socket)#

      + + +

      Called when socket is detached from a request and could be persisted by the +Agent. Default behavior is to:

      +
      socket.setKeepAlive(true, this.keepAliveMsecs);
      +socket.unref();
      +return true;
      +

      This method can be overridden by a particular Agent subclass. If this +method returns a falsy value, the socket will be destroyed instead of persisting +it for use with the next request.

      +

      The socket argument can be an instance of <net.Socket>, a subclass of +<stream.Duplex>.

      +

      agent.reuseSocket(socket, request)#

      + + +

      Called when socket is attached to request after being persisted because of +the keep-alive options. Default behavior is to:

      +
      socket.ref();
      +

      This method can be overridden by a particular Agent subclass.

      +

      The socket argument can be an instance of <net.Socket>, a subclass of +<stream.Duplex>.

      +

      agent.destroy()#

      + +

      Destroy any sockets that are currently in use by the agent.

      +

      It is usually not necessary to do this. However, if using an +agent with keepAlive enabled, then it is best to explicitly shut down +the agent when it will no longer be used. Otherwise, +sockets may hang open for quite a long time before the server +terminates them.

      +

      agent.freeSockets#

      + + +

      An object which contains arrays of sockets currently awaiting use by +the agent when keepAlive is enabled. Do not modify.

      +

      Sockets in the freeSockets list will be automatically destroyed and +removed from the array on 'timeout'.

      +

      agent.getName(options)#

      + +
        +
      • options <Object> A set of options providing information for name generation +
          +
        • host <string> A domain name or IP address of the server to issue the +request to
        • +
        • port <number> Port of remote server
        • +
        • localAddress <string> Local interface to bind for network connections +when issuing the request
        • +
        • family <integer> Must be 4 or 6 if this doesn't equal undefined.
        • +
        +
      • +
      • Returns: <string>
      • +
      +

      Get a unique name for a set of request options, to determine whether a +connection can be reused. For an HTTP agent, this returns +host:port:localAddress or host:port:localAddress:family. For an HTTPS agent, +the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options +that determine socket reusability.

      +

      agent.maxFreeSockets#

      + + +

      By default set to 256. For agents with keepAlive enabled, this +sets the maximum number of sockets that will be left open in the free +state.

      +

      agent.maxSockets#

      + + +

      By default set to Infinity. Determines how many concurrent sockets the agent +can have open per origin. Origin is the returned value of agent.getName().

      +

      agent.maxTotalSockets#

      + + +

      By default set to Infinity. Determines how many concurrent sockets the agent +can have open. Unlike maxSockets, this parameter applies across all origins.

      +

      agent.requests#

      + + +

      An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify.

      +

      agent.sockets#

      + + +

      An object which contains arrays of sockets currently in use by the +agent. Do not modify.

      +

      Class: http.ClientRequest#

      + + +

      This object is created internally and returned from http.request(). It +represents an in-progress request whose header has already been queued. The +header is still mutable using the setHeader(name, value), +getHeader(name), removeHeader(name) API. The actual header will +be sent along with the first data chunk or when calling request.end().

      +

      To get the response, add a listener for 'response' to the request object. +'response' will be emitted from the request object when the response +headers have been received. The 'response' event is executed with one +argument which is an instance of http.IncomingMessage.

      +

      During the 'response' event, one can add listeners to the +response object; particularly to listen for the 'data' event.

      +

      If no 'response' handler is added, then the response will be +entirely discarded. However, if a 'response' event handler is added, +then the data from the response object must be consumed, either by +calling response.read() whenever there is a 'readable' event, or +by adding a 'data' handler, or by calling the .resume() method. +Until the data is consumed, the 'end' event will not fire. Also, until +the data is read it will consume memory that can eventually lead to a +'process out of memory' error.

      +

      Unlike the request object, if the response closes prematurely, the +response object does not emit an 'error' event but instead emits the +'aborted' event.

      +

      Node.js does not check whether Content-Length and the length of the +body which has been transmitted are equal or not.

      +

      Event: 'abort'#

      + +

      Emitted when the request has been aborted by the client. This event is only +emitted on the first call to abort().

      +

      Event: 'connect'#

      + + +

      Emitted each time a server responds to a request with a CONNECT method. If +this event is not being listened for, clients receiving a CONNECT method will +have their connections closed.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      A client and server pair demonstrating how to listen for the 'connect' event:

      +
      const http = require('http');
      +const net = require('net');
      +const { URL } = require('url');
      +
      +// Create an HTTP tunneling proxy
      +const proxy = http.createServer((req, res) => {
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('okay');
      +});
      +proxy.on('connect', (req, clientSocket, head) => {
      +  // Connect to an origin server
      +  const { port, hostname } = new URL(`http://${req.url}`);
      +  const serverSocket = net.connect(port || 80, hostname, () => {
      +    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
      +                    'Proxy-agent: Node.js-Proxy\r\n' +
      +                    '\r\n');
      +    serverSocket.write(head);
      +    serverSocket.pipe(clientSocket);
      +    clientSocket.pipe(serverSocket);
      +  });
      +});
      +
      +// Now that proxy is running
      +proxy.listen(1337, '127.0.0.1', () => {
      +
      +  // Make a request to a tunneling proxy
      +  const options = {
      +    port: 1337,
      +    host: '127.0.0.1',
      +    method: 'CONNECT',
      +    path: 'www.google.com:80'
      +  };
      +
      +  const req = http.request(options);
      +  req.end();
      +
      +  req.on('connect', (res, socket, head) => {
      +    console.log('got connected!');
      +
      +    // Make a request over an HTTP tunnel
      +    socket.write('GET / HTTP/1.1\r\n' +
      +                 'Host: www.google.com:80\r\n' +
      +                 'Connection: close\r\n' +
      +                 '\r\n');
      +    socket.on('data', (chunk) => {
      +      console.log(chunk.toString());
      +    });
      +    socket.on('end', () => {
      +      proxy.close();
      +    });
      +  });
      +});
      +

      Event: 'continue'#

      + +

      Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body.

      +

      Event: 'information'#

      + + +

      Emitted when the server sends a 1xx intermediate response (excluding 101 +Upgrade). The listeners of this event will receive an object containing the +HTTP version, status code, status message, key-value headers object, +and array with the raw header names followed by their respective values.

      +
      const http = require('http');
      +
      +const options = {
      +  host: '127.0.0.1',
      +  port: 8080,
      +  path: '/length_request'
      +};
      +
      +// Make a request
      +const req = http.request(options);
      +req.end();
      +
      +req.on('information', (info) => {
      +  console.log(`Got information prior to main response: ${info.statusCode}`);
      +});
      +

      101 Upgrade statuses do not fire this event due to their break from the +traditional HTTP request/response chain, such as web sockets, in-place TLS +upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the +'upgrade' event instead.

      +

      Event: 'response'#

      + + +

      Emitted when a response is received to this request. This event is emitted only +once.

      +

      Event: 'socket'#

      + + +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      Event: 'timeout'#

      + +

      Emitted when the underlying socket times out from inactivity. This only notifies +that the socket has been idle. The request must be aborted manually.

      +

      See also: request.setTimeout().

      +

      Event: 'upgrade'#

      + + +

      Emitted each time a server responds to a request with an upgrade. If this +event is not being listened for and the response status code is 101 Switching +Protocols, clients receiving an upgrade header will have their connections +closed.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      A client server pair demonstrating how to listen for the 'upgrade' event.

      +
      const http = require('http');
      +
      +// Create an HTTP server
      +const server = http.createServer((req, res) => {
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('okay');
      +});
      +server.on('upgrade', (req, socket, head) => {
      +  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
      +               'Upgrade: WebSocket\r\n' +
      +               'Connection: Upgrade\r\n' +
      +               '\r\n');
      +
      +  socket.pipe(socket); // echo back
      +});
      +
      +// Now that server is running
      +server.listen(1337, '127.0.0.1', () => {
      +
      +  // make a request
      +  const options = {
      +    port: 1337,
      +    host: '127.0.0.1',
      +    headers: {
      +      'Connection': 'Upgrade',
      +      'Upgrade': 'websocket'
      +    }
      +  };
      +
      +  const req = http.request(options);
      +  req.end();
      +
      +  req.on('upgrade', (res, socket, upgradeHead) => {
      +    console.log('got upgraded!');
      +    socket.end();
      +    process.exit(0);
      +  });
      +});
      +

      request.abort()#

      + +

      Marks the request as aborting. Calling this will cause remaining data +in the response to be dropped and the socket to be destroyed.

      +

      request.aborted#

      + + +

      The request.aborted property will be true if the request has +been aborted.

      +

      request.connection#

      + + +

      See request.socket.

      +

      request.end([data[, encoding]][, callback])#

      + + +

      Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating '0\r\n\r\n'.

      +

      If data is specified, it is equivalent to calling +request.write(data, encoding) followed by request.end(callback).

      +

      If callback is specified, it will be called when the request stream +is finished.

      +

      request.finished#

      + +

      + +

      The request.finished property will be true if request.end() +has been called. request.end() will automatically be called if the +request was initiated via http.get().

      +

      request.flushHeaders()#

      + +

      Flushes the request headers.

      +

      For efficiency reasons, Node.js normally buffers the request headers until +request.end() is called or the first chunk of request data is written. It +then tries to pack the request headers and data into a single TCP packet.

      +

      That's usually desired (it saves a TCP round-trip), but not when the first +data is not sent until possibly much later. request.flushHeaders() bypasses +the optimization and kickstarts the request.

      +

      request.getHeader(name)#

      + + +

      Reads out a header on the request. The name is case-insensitive. +The type of the return value depends on the arguments provided to +request.setHeader().

      +
      request.setHeader('content-type', 'text/html');
      +request.setHeader('Content-Length', Buffer.byteLength(body));
      +request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
      +const contentType = request.getHeader('Content-Type');
      +// 'contentType' is 'text/html'
      +const contentLength = request.getHeader('Content-Length');
      +// 'contentLength' is of type number
      +const cookie = request.getHeader('Cookie');
      +// 'cookie' is of type string[]
      +

      request.maxHeadersCount#

      + +

      Limits maximum response headers count. If set to 0, no limit will be applied.

      +

      request.path#

      + + +

      request.method#

      + + +

      request.host#

      + + +

      request.protocol#

      + + +

      request.removeHeader(name)#

      + + +

      Removes a header that's already defined into headers object.

      +
      request.removeHeader('Content-Type');
      +

      request.reusedSocket#

      + +
        +
      • <boolean> Whether the request is send through a reused socket.
      • +
      +

      When sending request through a keep-alive enabled agent, the underlying socket +might be reused. But if server closes connection at unfortunate time, client +may run into a 'ECONNRESET' error.

      +
      const http = require('http');
      +
      +// Server has a 5 seconds keep-alive timeout by default
      +http
      +  .createServer((req, res) => {
      +    res.write('hello\n');
      +    res.end();
      +  })
      +  .listen(3000);
      +
      +setInterval(() => {
      +  // Adapting a keep-alive agent
      +  http.get('http://localhost:3000', { agent }, (res) => {
      +    res.on('data', (data) => {
      +      // Do nothing
      +    });
      +  });
      +}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
      +

      By marking a request whether it reused socket or not, we can do +automatic error retry base on it.

      +
      const http = require('http');
      +const agent = new http.Agent({ keepAlive: true });
      +
      +function retriableRequest() {
      +  const req = http
      +    .get('http://localhost:3000', { agent }, (res) => {
      +      // ...
      +    })
      +    .on('error', (err) => {
      +      // Check if retry is needed
      +      if (req.reusedSocket && err.code === 'ECONNRESET') {
      +        retriableRequest();
      +      }
      +    });
      +}
      +
      +retriableRequest();
      +

      request.setHeader(name, value)#

      + + +

      Sets a single header value for headers object. If this header already exists in +the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name. Non-string values will be +stored without modification. Therefore, request.getHeader() may return +non-string values. However, the non-string values will be converted to strings +for network transmission.

      +
      request.setHeader('Content-Type', 'application/json');
      +

      or

      +
      request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
      +

      request.setNoDelay([noDelay])#

      + + +

      Once a socket is assigned to this request and is connected +socket.setNoDelay() will be called.

      +

      request.setSocketKeepAlive([enable][, initialDelay])#

      + + +

      Once a socket is assigned to this request and is connected +socket.setKeepAlive() will be called.

      +

      request.setTimeout(timeout[, callback])#

      + +
        +
      • timeout <number> Milliseconds before a request times out.
      • +
      • callback <Function> Optional function to be called when a timeout occurs. +Same as binding to the 'timeout' event.
      • +
      • Returns: <http.ClientRequest>
      • +
      +

      Once a socket is assigned to this request and is connected +socket.setTimeout() will be called.

      +

      request.socket#

      + + +

      Reference to the underlying socket. Usually users will not want to access +this property. In particular, the socket will not emit 'readable' events +because of how the protocol parser attaches to the socket. The socket +may also be accessed via request.connection.

      +
      const http = require('http');
      +const options = {
      +  host: 'www.google.com',
      +};
      +const req = http.get(options);
      +req.end();
      +req.once('response', (res) => {
      +  const ip = req.socket.localAddress;
      +  const port = req.socket.localPort;
      +  console.log(`Your IP address is ${ip} and your source port is ${port}.`);
      +  // Consume response object
      +});
      +

      This property is guaranteed to be an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specified a socket +type other than <net.Socket>.

      +

      request.writableEnded#

      + + +

      Is true after request.end() has been called. This property +does not indicate whether the data has been flushed, for this use +request.writableFinished instead.

      +

      request.writableFinished#

      + + +

      Is true if all data has been flushed to the underlying system, immediately +before the 'finish' event is emitted.

      +

      request.write(chunk[, encoding][, callback])#

      + + +

      Sends a chunk of the body. By calling this method +many times, a request body can be sent to a +server. In that case, it is suggested to use the +['Transfer-Encoding', 'chunked'] header line when +creating the request.

      +

      The encoding argument is optional and only applies when chunk is a string. +Defaults to 'utf8'.

      +

      The callback argument is optional and will be called when this chunk of data +is flushed, but only if the chunk is non-empty.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is free again.

      +

      When write function is called with empty string or buffer, it does +nothing and waits for more input.

      +

      Class: http.Server#

      + + +

      Event: 'checkContinue'#

      + + +

      Emitted each time a request with an HTTP Expect: 100-continue is received. +If this event is not listened for, the server will automatically respond +with a 100 Continue as appropriate.

      +

      Handling this event involves calling response.writeContinue() if the +client should continue to send the request body, or generating an appropriate +HTTP response (e.g. 400 Bad Request) if the client should not continue to send +the request body.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'checkExpectation'#

      + + +

      Emitted each time a request with an HTTP Expect header is received, where the +value is not 100-continue. If this event is not listened for, the server will +automatically respond with a 417 Expectation Failed as appropriate.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'clientError'#

      + + +

      If a client connection emits an 'error' event, it will be forwarded here. +Listener of this event is responsible for closing/destroying the underlying +socket. For example, one may wish to more gracefully close the socket with a +custom HTTP response instead of abruptly severing the connection.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      Default behavior is to try close the socket with a HTTP '400 Bad Request', +or a HTTP '431 Request Header Fields Too Large' in the case of a +HPE_HEADER_OVERFLOW error. If the socket is not writable or has already +written data it is immediately destroyed.

      +

      socket is the net.Socket object that the error originated from.

      +
      const http = require('http');
      +
      +const server = http.createServer((req, res) => {
      +  res.end();
      +});
      +server.on('clientError', (err, socket) => {
      +  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
      +});
      +server.listen(8000);
      +

      When the 'clientError' event occurs, there is no request or response +object, so any HTTP response sent, including response headers and payload, +must be written directly to the socket object. Care must be taken to +ensure the response is a properly formatted HTTP response message.

      +

      err is an instance of Error with two extra columns:

      +
        +
      • bytesParsed: the bytes count of request packet that Node.js may have parsed +correctly;
      • +
      • rawPacket: the raw packet of current request.
      • +
      +

      In some cases, the client has already received the response and/or the socket +has already been destroyed, like in case of ECONNRESET errors. Before +trying to send data to the socket, it is better to check that it is still +writable.

      +
      server.on('clientError', (err, socket) => {
      +  if (err.code === 'ECONNRESET' || !socket.writable) {
      +    return;
      +  }
      +
      +  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
      +});
      +

      Event: 'close'#

      + +

      Emitted when the server closes.

      +

      Event: 'connect'#

      + + +

      Emitted each time a client requests an HTTP CONNECT method. If this event is +not listened for, then clients requesting a CONNECT method will have their +connections closed.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      After this event is emitted, the request's socket will not have a 'data' +event listener, meaning it will need to be bound in order to handle data +sent to the server on that socket.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established. socket is +typically an object of type net.Socket. Usually users will not want to +access this event. In particular, the socket will not emit 'readable' events +because of how the protocol parser attaches to the socket. The socket can +also be accessed at request.connection.

      +

      This event can also be explicitly emitted by users to inject connections +into the HTTP server. In that case, any Duplex stream can be passed.

      +

      If socket.setTimeout() is called here, the timeout will be replaced with +server.keepAliveTimeout when the socket has served a request (if +server.keepAliveTimeout is non-zero).

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      Event: 'request'#

      + + +

      Emitted each time there is a request. There may be multiple requests +per connection (in the case of HTTP Keep-Alive connections).

      +

      Event: 'upgrade'#

      + + +

      Emitted each time a client requests an HTTP upgrade. Listening to this event +is optional and clients cannot insist on a protocol change.

      +

      After this event is emitted, the request's socket will not have a 'data' +event listener, meaning it will need to be bound in order to handle data +sent to the server on that socket.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      server.close([callback])#

      + + +

      Stops the server from accepting new connections. See net.Server.close().

      +

      server.headersTimeout#

      + + +

      Limit the amount of time the parser will wait to receive the complete HTTP +headers.

      +

      In case of inactivity, the rules defined in server.timeout apply. However, +that inactivity based timeout would still allow the connection to be kept open +if the headers are being sent very slowly (by default, up to a byte per 2 +minutes). In order to prevent this, whenever header data arrives an additional +check is made that more than server.headersTimeout milliseconds has not +passed since the connection was established. If the check fails, a 'timeout' +event is emitted on the server object, and (by default) the socket is destroyed. +See server.timeout for more information on how timeout behavior can be +customized.

      +

      A value of 0 will disable the HTTP headers timeout check.

      +

      server.listen()#

      +

      Starts the HTTP server listening for connections. +This method is identical to server.listen() from net.Server.

      +

      server.listening#

      + +
        +
      • <boolean> Indicates whether or not the server is listening for connections.
      • +
      +

      server.maxHeadersCount#

      + + +

      Limits maximum incoming headers count. If set to 0, no limit will be applied.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      Sets the timeout value for sockets, and emits a 'timeout' event on +the Server object, passing the socket as an argument, if a timeout +occurs.

      +

      If there is a 'timeout' event listener on the Server object, then it +will be called with the timed-out socket as an argument.

      +

      By default, the Server's timeout value is 2 minutes, and sockets are +destroyed automatically if they time out. However, if a callback is assigned +to the Server's 'timeout' event, timeouts must be handled explicitly.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      server.timeout#

      + +
        +
      • <number> Timeout in milliseconds. Default: 120000 (2 minutes).
      • +
      +

      The number of milliseconds of inactivity before a socket is presumed +to have timed out.

      +

      A value of 0 will disable the timeout behavior on incoming connections.

      +

      The socket timeout logic is set up on connection, so changing this +value only affects new connections to the server, not any existing connections.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      server.keepAliveTimeout#

      + +
        +
      • <number> Timeout in milliseconds. Default: 5000 (5 seconds).
      • +
      +

      The number of milliseconds of inactivity a server needs to wait for additional +incoming data, after it has finished writing the last response, before a socket +will be destroyed. If the server receives new data before the keep-alive +timeout has fired, it will reset the regular inactivity timeout, i.e., +server.timeout.

      +

      A value of 0 will disable the keep-alive timeout behavior on incoming +connections. +A value of 0 makes the http server behave similarly to Node.js versions prior +to 8.0.0, which did not have a keep-alive timeout.

      +

      The socket timeout logic is set up on connection, so changing this value only +affects new connections to the server, not any existing connections.

      +

      Class: http.ServerResponse#

      + + +

      This object is created internally by an HTTP server, not by the user. It is +passed as the second parameter to the 'request' event.

      +

      Event: 'close'#

      + +

      Indicates that the the response is completed, or its underlying connection was +terminated prematurely (before the response completion).

      +

      Event: 'finish'#

      + +

      Emitted when the response has been sent. More specifically, this event is +emitted when the last segment of the response headers and body have been +handed off to the operating system for transmission over the network. It +does not imply that the client has received anything yet.

      +

      response.addTrailers(headers)#

      + + +

      This method adds HTTP trailing headers (a header but at the end of the +message) to the response.

      +

      Trailers will only be emitted if chunked encoding is used for the +response; if it is not (e.g. if the request was HTTP/1.0), they will +be silently discarded.

      +

      HTTP requires the Trailer header to be sent in order to +emit trailers, with a list of the header fields in its value. E.g.,

      +
      response.writeHead(200, { 'Content-Type': 'text/plain',
      +                          'Trailer': 'Content-MD5' });
      +response.write(fileData);
      +response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
      +response.end();
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.connection#

      + + +

      See response.socket.

      +

      response.cork()#

      + +

      See writable.cork().

      +

      response.end([data[, encoding]][, callback])#

      + + +

      This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, response.end(), MUST be called on each response.

      +

      If data is specified, it is similar in effect to calling +response.write(data, encoding) followed by response.end(callback).

      +

      If callback is specified, it will be called when the response stream +is finished.

      +

      response.finished#

      + +

      + +

      The response.finished property will be true if response.end() +has been called.

      +

      response.flushHeaders()#

      + +

      Flushes the response headers. See also: request.flushHeaders().

      +

      response.getHeader(name)#

      + + +

      Reads out a header that's already been queued but not sent to the client. +The name is case-insensitive. The type of the return value depends +on the arguments provided to response.setHeader().

      +
      response.setHeader('Content-Type', 'text/html');
      +response.setHeader('Content-Length', Buffer.byteLength(body));
      +response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
      +const contentType = response.getHeader('content-type');
      +// contentType is 'text/html'
      +const contentLength = response.getHeader('Content-Length');
      +// contentLength is of type number
      +const setCookie = response.getHeader('set-cookie');
      +// setCookie is of type string[]
      +

      response.getHeaderNames()#

      + + +

      Returns an array containing the unique names of the current outgoing headers. +All header names are lowercase.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headerNames = response.getHeaderNames();
      +// headerNames === ['foo', 'set-cookie']
      +

      response.getHeaders()#

      + + +

      Returns a shallow copy of the current outgoing headers. Since a shallow copy +is used, array values may be mutated without additional calls to various +header-related http module methods. The keys of the returned object are the +header names and the values are the respective header values. All header names +are lowercase.

      +

      The object returned by the response.getHeaders() method does not +prototypically inherit from the JavaScript Object. This means that typical +Object methods such as obj.toString(), obj.hasOwnProperty(), and others +are not defined and will not work.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headers = response.getHeaders();
      +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      +

      response.hasHeader(name)#

      + + +

      Returns true if the header identified by name is currently set in the +outgoing headers. The header name matching is case-insensitive.

      +
      const hasContentType = response.hasHeader('content-type');
      +

      response.headersSent#

      + + +

      Boolean (read-only). True if headers were sent, false otherwise.

      +

      response.removeHeader(name)#

      + + +

      Removes a header that's queued for implicit sending.

      +
      response.removeHeader('Content-Encoding');
      +

      response.sendDate#

      + + +

      When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true.

      +

      This should only be disabled for testing; HTTP requires the Date header +in responses.

      +

      response.setHeader(name, value)#

      + + +

      Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name. Non-string values will be +stored without modification. Therefore, response.getHeader() may return +non-string values. However, the non-string values will be converted to strings +for network transmission.

      +
      response.setHeader('Content-Type', 'text/html');
      +

      or

      +
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +
      // Returns content-type = text/plain
      +const server = http.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('ok');
      +});
      +

      If response.writeHead() method is called and this method has not been +called, it will directly write the supplied header values onto the network +channel without caching internally, and the response.getHeader() on the +header will not yield the expected result. If progressive population of headers +is desired with potential future retrieval and modification, use +response.setHeader() instead of response.writeHead().

      +

      response.setTimeout(msecs[, callback])#

      + + +

      Sets the Socket's timeout value to msecs. If a callback is +provided, then it is added as a listener on the 'timeout' event on +the response object.

      +

      If no 'timeout' listener is added to the request, the response, or +the server, then sockets are destroyed when they time out. If a handler is +assigned to the request, the response, or the server's 'timeout' events, +timed out sockets must be handled explicitly.

      +

      response.socket#

      + + +

      Reference to the underlying socket. Usually users will not want to access +this property. In particular, the socket will not emit 'readable' events +because of how the protocol parser attaches to the socket. After +response.end(), the property is nulled. The socket may also be accessed +via response.connection.

      +
      const http = require('http');
      +const server = http.createServer((req, res) => {
      +  const ip = res.socket.remoteAddress;
      +  const port = res.socket.remotePort;
      +  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
      +}).listen(3000);
      +

      This property is guaranteed to be an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specified a socket +type other than <net.Socket>.

      +

      response.statusCode#

      + + +

      When using implicit headers (not calling response.writeHead() explicitly), +this property controls the status code that will be sent to the client when +the headers get flushed.

      +
      response.statusCode = 404;
      +

      After response header was sent to the client, this property indicates the +status code which was sent out.

      +

      response.statusMessage#

      + + +

      When using implicit headers (not calling response.writeHead() explicitly), +this property controls the status message that will be sent to the client when +the headers get flushed. If this is left as undefined then the standard +message for the status code will be used.

      +
      response.statusMessage = 'Not found';
      +

      After response header was sent to the client, this property indicates the +status message which was sent out.

      +

      response.uncork()#

      + +

      See writable.uncork().

      +

      response.writableEnded#

      + + +

      Is true after response.end() has been called. This property +does not indicate whether the data has been flushed, for this use +response.writableFinished instead.

      +

      response.writableFinished#

      + + +

      Is true if all data has been flushed to the underlying system, immediately +before the 'finish' event is emitted.

      +

      response.write(chunk[, encoding][, callback])#

      + + +

      If this method is called and response.writeHead() has not been called, +it will switch to implicit header mode and flush the implicit headers.

      +

      This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body.

      +

      In the http module, the response body is omitted when the +request is a HEAD request. Similarly, the 204 and 304 responses +must not include a message body.

      +

      chunk can be a string or a buffer. If chunk is a string, +the second parameter specifies how to encode it into a byte stream. +callback will be called when this chunk of data is flushed.

      +

      This is the raw HTTP body and has nothing to do with higher-level multi-part +body encodings that may be used.

      +

      The first time response.write() is called, it will send the buffered +header information and the first chunk of the body to the client. The second +time response.write() is called, Node.js assumes data will be streamed, +and sends the new data separately. That is, the response is buffered up to the +first chunk of the body.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is free again.

      +

      response.writeContinue()#

      + +

      Sends a HTTP/1.1 100 Continue message to the client, indicating that +the request body should be sent. See the 'checkContinue' event on +Server.

      +

      response.writeHead(statusCode[, statusMessage][, headers])#

      + + +

      Sends a response header to the request. The status code is a 3-digit HTTP +status code, like 404. The last argument, headers, are the response headers. +Optionally one can give a human-readable statusMessage as the second +argument.

      +

      Returns a reference to the ServerResponse, so that calls can be chained.

      +
      const body = 'hello world';
      +response
      +  .writeHead(200, {
      +    'Content-Length': Buffer.byteLength(body),
      +    'Content-Type': 'text/plain'
      +  })
      +  .end(body);
      +

      This method must only be called once on a message and it must +be called before response.end() is called.

      +

      If response.write() or response.end() are called before calling +this, the implicit/mutable headers will be calculated and call this function.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +

      If this method is called and response.setHeader() has not been called, +it will directly write the supplied header values onto the network channel +without caching internally, and the response.getHeader() on the header +will not yield the expected result. If progressive population of headers is +desired with potential future retrieval and modification, use +response.setHeader() instead.

      +
      // Returns content-type = text/plain
      +const server = http.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('ok');
      +});
      +

      Content-Length is given in bytes, not characters. Use +Buffer.byteLength() to determine the length of the body in bytes. Node.js +does not check whether Content-Length and the length of the body which has +been transmitted are equal or not.

      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.writeProcessing()#

      + +

      Sends a HTTP/1.1 102 Processing message to the client, indicating that +the request body should be sent.

      +

      Class: http.IncomingMessage#

      + + +

      An IncomingMessage object is created by http.Server or +http.ClientRequest and passed as the first argument to the 'request' +and 'response' event respectively. It may be used to access response +status, headers and data.

      +

      Event: 'aborted'#

      + +

      Emitted when the request has been aborted.

      +

      Event: 'close'#

      + +

      Indicates that the underlying connection was closed.

      +

      message.aborted#

      + + +

      The message.aborted property will be true if the request has +been aborted.

      +

      message.complete#

      + + +

      The message.complete property will be true if a complete HTTP message has +been received and successfully parsed.

      +

      This property is particularly useful as a means of determining if a client or +server fully transmitted a message before a connection was terminated:

      +
      const req = http.request({
      +  host: '127.0.0.1',
      +  port: 8080,
      +  method: 'POST'
      +}, (res) => {
      +  res.resume();
      +  res.on('end', () => {
      +    if (!res.complete)
      +      console.error(
      +        'The connection was terminated while the message was still being sent');
      +  });
      +});
      +

      message.destroy([error])#

      + + +

      Calls destroy() on the socket that received the IncomingMessage. If error +is provided, an 'error' event is emitted on the socket and error is passed +as an argument to any listeners on the event.

      +

      message.headers#

      + + +

      The request/response headers object.

      +

      Key-value pairs of header names and values. Header names are lower-cased.

      +
      // Prints something like:
      +//
      +// { 'user-agent': 'curl/7.22.0',
      +//   host: '127.0.0.1:8000',
      +//   accept: '*/*' }
      +console.log(request.headers);
      +

      Duplicates in raw headers are handled in the following ways, depending on the +header name:

      +
        +
      • Duplicates of age, authorization, content-length, content-type, +etag, expires, from, host, if-modified-since, if-unmodified-since, +last-modified, location, max-forwards, proxy-authorization, referer, +retry-after, server, or user-agent are discarded.
      • +
      • set-cookie is always an array. Duplicates are added to the array.
      • +
      • For duplicate cookie headers, the values are joined together with '; '.
      • +
      • For all other headers, the values are joined together with ', '.
      • +
      +

      message.httpVersion#

      + + +

      In case of server request, the HTTP version sent by the client. In the case of +client response, the HTTP version of the connected-to server. +Probably either '1.1' or '1.0'.

      +

      Also message.httpVersionMajor is the first integer and +message.httpVersionMinor is the second.

      +

      message.method#

      + + +

      Only valid for request obtained from http.Server.

      +

      The request method as a string. Read only. Examples: 'GET', 'DELETE'.

      +

      message.rawHeaders#

      + + +

      The raw request/response headers list exactly as they were received.

      +

      The keys and values are in the same list. It is not a +list of tuples. So, the even-numbered offsets are key values, and the +odd-numbered offsets are the associated values.

      +

      Header names are not lowercased, and duplicates are not merged.

      +
      // Prints something like:
      +//
      +// [ 'user-agent',
      +//   'this is invalid because there can be only one',
      +//   'User-Agent',
      +//   'curl/7.22.0',
      +//   'Host',
      +//   '127.0.0.1:8000',
      +//   'ACCEPT',
      +//   '*/*' ]
      +console.log(request.rawHeaders);
      +

      message.rawTrailers#

      + + +

      The raw request/response trailer keys and values exactly as they were +received. Only populated at the 'end' event.

      +

      message.setTimeout(msecs[, callback])#

      + + +

      Calls message.connection.setTimeout(msecs, callback).

      +

      message.socket#

      + + +

      The net.Socket object associated with the connection.

      +

      With HTTPS support, use request.socket.getPeerCertificate() to obtain the +client's authentication details.

      +

      This property is guaranteed to be an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specified a socket +type other than <net.Socket>.

      +

      message.statusCode#

      + + +

      Only valid for response obtained from http.ClientRequest.

      +

      The 3-digit HTTP response status code. E.G. 404.

      +

      message.statusMessage#

      + + +

      Only valid for response obtained from http.ClientRequest.

      +

      The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

      +

      message.trailers#

      + + +

      The request/response trailers object. Only populated at the 'end' event.

      +

      message.url#

      + + +

      Only valid for request obtained from http.Server.

      +

      Request URL string. This contains only the URL that is present in the actual +HTTP request. Take the following request:

      +
      GET /status?name=ryan HTTP/1.1
      +Accept: text/plain
      +

      To parse the URL into its parts:

      +
      new URL(request.url, `http://${request.headers.host}`);
      +

      When request.url is '/status?name=ryan' and +request.headers.host is 'localhost:3000':

      +
      $ node
      +> new URL(request.url, `http://${request.headers.host}`)
      +URL {
      +  href: 'http://localhost:3000/status?name=ryan',
      +  origin: 'http://localhost:3000',
      +  protocol: 'http:',
      +  username: '',
      +  password: '',
      +  host: 'localhost:3000',
      +  hostname: 'localhost',
      +  port: '3000',
      +  pathname: '/status',
      +  search: '?name=ryan',
      +  searchParams: URLSearchParams { 'name' => 'ryan' },
      +  hash: ''
      +}
      +

      http.METHODS#

      + + +

      A list of the HTTP methods that are supported by the parser.

      +

      http.STATUS_CODES#

      + + +

      A collection of all the standard HTTP response status codes, and the +short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

      +

      http.createServer([options][, requestListener])#

      + +
        +
      • +

        options <Object>

        +
          +
        • IncomingMessage <http.IncomingMessage> Specifies the IncomingMessage +class to be used. Useful for extending the original IncomingMessage. +Default: IncomingMessage.
        • +
        • ServerResponse <http.ServerResponse> Specifies the ServerResponse class +to be used. Useful for extending the original ServerResponse. Default: +ServerResponse.
        • +
        • insecureHTTPParser <boolean> Use an insecure HTTP parser that accepts +invalid HTTP headers when true. Using the insecure parser should be +avoided. See --insecure-http-parser for more information. +Default: false
        • +
        +
      • +
      • +

        requestListener <Function>

        +
      • +
      • +

        Returns: <http.Server>

        +
      • +
      +

      Returns a new instance of http.Server.

      +

      The requestListener is a function which is automatically +added to the 'request' event.

      +

      http.get(options[, callback])#

      +

      http.get(url[, options][, callback])#

      + + +

      Since most requests are GET requests without bodies, Node.js provides this +convenience method. The only difference between this method and +http.request() is that it sets the method to GET and calls req.end() +automatically. The callback must take care to consume the response +data for reasons stated in http.ClientRequest section.

      +

      The callback is invoked with a single argument that is an instance of +http.IncomingMessage.

      +

      JSON fetching example:

      +
      http.get('http://nodejs.org/dist/index.json', (res) => {
      +  const { statusCode } = res;
      +  const contentType = res.headers['content-type'];
      +
      +  let error;
      +  // Any 2xx status code signals a successful response but
      +  // here we're only checking for 200.
      +  if (statusCode !== 200) {
      +    error = new Error('Request Failed.\n' +
      +                      `Status Code: ${statusCode}`);
      +  } else if (!/^application\/json/.test(contentType)) {
      +    error = new Error('Invalid content-type.\n' +
      +                      `Expected application/json but received ${contentType}`);
      +  }
      +  if (error) {
      +    console.error(error.message);
      +    // Consume response data to free up memory
      +    res.resume();
      +    return;
      +  }
      +
      +  res.setEncoding('utf8');
      +  let rawData = '';
      +  res.on('data', (chunk) => { rawData += chunk; });
      +  res.on('end', () => {
      +    try {
      +      const parsedData = JSON.parse(rawData);
      +      console.log(parsedData);
      +    } catch (e) {
      +      console.error(e.message);
      +    }
      +  });
      +}).on('error', (e) => {
      +  console.error(`Got error: ${e.message}`);
      +});
      +

      http.globalAgent#

      + + +

      Global instance of Agent which is used as the default for all HTTP client +requests.

      +

      http.maxHeaderSize#

      + + +

      Read-only property specifying the maximum allowed size of HTTP headers in bytes. +Defaults to 8KB. Configurable using the --max-http-header-size CLI option.

      +

      http.request(options[, callback])#

      +

      http.request(url[, options][, callback])#

      + +
        +
      • url <string> | <URL>
      • +
      • options <Object> +
          +
        • agent <http.Agent> | <boolean> Controls Agent behavior. Possible +values: +
            +
          • undefined (default): use http.globalAgent for this host and port.
          • +
          • Agent object: explicitly use the passed in Agent.
          • +
          • false: causes a new Agent with default values to be used.
          • +
          +
        • +
        • auth <string> Basic authentication i.e. 'user:password' to compute an +Authorization header.
        • +
        • createConnection <Function> A function that produces a socket/stream to +use for the request when the agent option is not used. This can be used to +avoid creating a custom Agent class just to override the default +createConnection function. See agent.createConnection() for more +details. Any Duplex stream is a valid return value.
        • +
        • defaultPort <number> Default port for the protocol. Default: +agent.defaultPort if an Agent is used, else undefined.
        • +
        • family <number> IP address family to use when resolving host or +hostname. Valid values are 4 or 6. When unspecified, both IP v4 and +v6 will be used.
        • +
        • headers <Object> An object containing request headers.
        • +
        • host <string> A domain name or IP address of the server to issue the +request to. Default: 'localhost'.
        • +
        • hostname <string> Alias for host. To support url.parse(), +hostname will be used if both host and hostname are specified.
        • +
        • insecureHTTPParser <boolean> Use an insecure HTTP parser that accepts +invalid HTTP headers when true. Using the insecure parser should be +avoided. See --insecure-http-parser for more information. +Default: false
        • +
        • localAddress <string> Local interface to bind for network connections.
        • +
        • lookup <Function> Custom lookup function. Default: dns.lookup().
        • +
        • method <string> A string specifying the HTTP request method. Default: +'GET'.
        • +
        • path <string> Request path. Should include query string if any. +E.G. '/index.html?page=12'. An exception is thrown when the request path +contains illegal characters. Currently, only spaces are rejected but that +may change in the future. Default: '/'.
        • +
        • port <number> Port of remote server. Default: defaultPort if set, +else 80.
        • +
        • protocol <string> Protocol to use. Default: 'http:'.
        • +
        • setHost <boolean>: Specifies whether or not to automatically add the +Host header. Defaults to true.
        • +
        • socketPath <string> Unix Domain Socket (cannot be used if one of host +or port is specified, those specify a TCP Socket).
        • +
        • timeout <number>: A number specifying the socket timeout in milliseconds. +This will set the timeout before the socket is connected.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <http.ClientRequest>
      • +
      +

      Node.js maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests.

      +

      url can be a string or a URL object. If url is a +string, it is automatically parsed with new URL(). If it is a URL +object, it will be automatically converted to an ordinary options object.

      +

      If both url and options are specified, the objects are merged, with the +options properties taking precedence.

      +

      The optional callback parameter will be added as a one-time listener for +the 'response' event.

      +

      http.request() returns an instance of the http.ClientRequest +class. The ClientRequest instance is a writable stream. If one needs to +upload a file with a POST request, then write to the ClientRequest object.

      +
      const postData = querystring.stringify({
      +  'msg': 'Hello World!'
      +});
      +
      +const options = {
      +  hostname: 'www.google.com',
      +  port: 80,
      +  path: '/upload',
      +  method: 'POST',
      +  headers: {
      +    'Content-Type': 'application/x-www-form-urlencoded',
      +    'Content-Length': Buffer.byteLength(postData)
      +  }
      +};
      +
      +const req = http.request(options, (res) => {
      +  console.log(`STATUS: ${res.statusCode}`);
      +  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      +  res.setEncoding('utf8');
      +  res.on('data', (chunk) => {
      +    console.log(`BODY: ${chunk}`);
      +  });
      +  res.on('end', () => {
      +    console.log('No more data in response.');
      +  });
      +});
      +
      +req.on('error', (e) => {
      +  console.error(`problem with request: ${e.message}`);
      +});
      +
      +// Write data to request body
      +req.write(postData);
      +req.end();
      +

      In the example req.end() was called. With http.request() one +must always call req.end() to signify the end of the request - +even if there is no data being written to the request body.

      +

      If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an 'error' event is emitted +on the returned request object. As with all 'error' events, if no listeners +are registered the error will be thrown.

      +

      There are a few special headers that should be noted.

      +
        +
      • +

        Sending a 'Connection: keep-alive' will notify Node.js that the connection to +the server should be persisted until the next request.

        +
      • +
      • +

        Sending a 'Content-Length' header will disable the default chunked encoding.

        +
      • +
      • +

        Sending an 'Expect' header will immediately send the request headers. +Usually, when sending 'Expect: 100-continue', both a timeout and a listener +for the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more +information.

        +
      • +
      • +

        Sending an Authorization header will override using the auth option +to compute basic authentication.

        +
      • +
      +

      Example using a URL as options:

      +
      const options = new URL('http://abc:xyz@example.com');
      +
      +const req = http.request(options, (res) => {
      +  // ...
      +});
      +

      In a successful request, the following events will be emitted in the following +order:

      +
        +
      • 'socket'
      • +
      • 'response' +
          +
        • 'data' any number of times, on the res object +('data' will not be emitted at all if the response body is empty, for +instance, in most redirects)
        • +
        • 'end' on the res object
        • +
        +
      • +
      • 'close'
      • +
      +

      In the case of a connection error, the following events will be emitted:

      +
        +
      • 'socket'
      • +
      • 'error'
      • +
      • 'close'
      • +
      +

      If req.abort() is called before the connection succeeds, the following events +will be emitted in the following order:

      +
        +
      • 'socket'
      • +
      • (req.abort() called here)
      • +
      • 'abort'
      • +
      • 'error' with an error with message 'Error: socket hang up' and code +'ECONNRESET'
      • +
      • 'close'
      • +
      +

      If req.abort() is called after the response is received, the following events +will be emitted in the following order:

      +
        +
      • 'socket'
      • +
      • 'response' +
          +
        • 'data' any number of times, on the res object
        • +
        +
      • +
      • (req.abort() called here)
      • +
      • 'abort'
      • +
      • 'aborted' on the res object
      • +
      • 'close'
      • +
      • 'end' on the res object
      • +
      • 'close' on the res object
      • +
      +

      Setting the timeout option or using the setTimeout() function will +not abort the request or do anything besides add a 'timeout' event.

      +

      HTTP/2#

      + + +

      Stability: 2 - Stable

      +

      Source Code: lib/http2.js

      +

      The http2 module provides an implementation of the HTTP/2 protocol. It +can be accessed using:

      +
      const http2 = require('http2');
      +

      Core API#

      +

      The Core API provides a low-level interface designed specifically around +support for HTTP/2 protocol features. It is specifically not designed for +compatibility with the existing HTTP/1 module API. However, +the Compatibility API is.

      +

      The http2 Core API is much more symmetric between client and server than the +http API. For instance, most events, like 'error', 'connect' and +'stream', can be emitted either by client-side code or server-side code.

      +

      Server-side example#

      +

      The following illustrates a simple HTTP/2 server using the Core API. +Since there are no browsers known that support +unencrypted HTTP/2, the use of +http2.createSecureServer() is necessary when communicating +with browser clients.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const server = http2.createSecureServer({
      +  key: fs.readFileSync('localhost-privkey.pem'),
      +  cert: fs.readFileSync('localhost-cert.pem')
      +});
      +server.on('error', (err) => console.error(err));
      +
      +server.on('stream', (stream, headers) => {
      +  // stream is a Duplex
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(8443);
      +

      To generate the certificate and key for this example, run:

      +
      openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
      +  -keyout localhost-privkey.pem -out localhost-cert.pem
      +

      Client-side example#

      +

      The following illustrates an HTTP/2 client:

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +const client = http2.connect('https://localhost:8443', {
      +  ca: fs.readFileSync('localhost-cert.pem')
      +});
      +client.on('error', (err) => console.error(err));
      +
      +const req = client.request({ ':path': '/' });
      +
      +req.on('response', (headers, flags) => {
      +  for (const name in headers) {
      +    console.log(`${name}: ${headers[name]}`);
      +  }
      +});
      +
      +req.setEncoding('utf8');
      +let data = '';
      +req.on('data', (chunk) => { data += chunk; });
      +req.on('end', () => {
      +  console.log(`\n${data}`);
      +  client.close();
      +});
      +req.end();
      +

      Class: Http2Session#

      + + +

      Instances of the http2.Http2Session class represent an active communications +session between an HTTP/2 client and server. Instances of this class are not +intended to be constructed directly by user code.

      +

      Each Http2Session instance will exhibit slightly different behaviors +depending on whether it is operating as a server or a client. The +http2session.type property can be used to determine the mode in which an +Http2Session is operating. On the server side, user code should rarely +have occasion to work with the Http2Session object directly, with most +actions typically taken through interactions with either the Http2Server or +Http2Stream objects.

      +

      User code will not create Http2Session instances directly. Server-side +Http2Session instances are created by the Http2Server instance when a +new HTTP/2 connection is received. Client-side Http2Session instances are +created using the http2.connect() method.

      +

      Http2Session and sockets#

      +

      Every Http2Session instance is associated with exactly one net.Socket or +tls.TLSSocket when it is created. When either the Socket or the +Http2Session are destroyed, both will be destroyed.

      +

      Because of the specific serialization and processing requirements imposed +by the HTTP/2 protocol, it is not recommended for user code to read data from +or write data to a Socket instance bound to a Http2Session. Doing so can +put the HTTP/2 session into an indeterminate state causing the session and +the socket to become unusable.

      +

      Once a Socket has been bound to an Http2Session, user code should rely +solely on the API of the Http2Session.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted once the Http2Session has been destroyed. Its +listener does not expect any arguments.

      +

      Event: 'connect'#

      + + +

      The 'connect' event is emitted once the Http2Session has been successfully +connected to the remote peer and communication may begin.

      +

      User code will typically not listen for this event directly.

      +

      Event: 'error'#

      + + +

      The 'error' event is emitted when an error occurs during the processing of +an Http2Session.

      +

      Event: 'frameError'#

      + +
        +
      • type <integer> The frame type.
      • +
      • code <integer> The error code.
      • +
      • id <integer> The stream id (or 0 if the frame isn't associated with a +stream).
      • +
      +

      The 'frameError' event is emitted when an error occurs while attempting to +send a frame on the session. If the frame that could not be sent is associated +with a specific Http2Stream, an attempt to emit a 'frameError' event on the +Http2Stream is made.

      +

      If the 'frameError' event is associated with a stream, the stream will be +closed and destroyed immediately following the 'frameError' event. If the +event is not associated with a stream, the Http2Session will be shut down +immediately following the 'frameError' event.

      +

      Event: 'goaway'#

      + +
        +
      • errorCode <number> The HTTP/2 error code specified in the GOAWAY frame.
      • +
      • lastStreamID <number> The ID of the last stream the remote peer successfully +processed (or 0 if no ID is specified).
      • +
      • opaqueData <Buffer> If additional opaque data was included in the GOAWAY +frame, a Buffer instance will be passed containing that data.
      • +
      +

      The 'goaway' event is emitted when a GOAWAY frame is received.

      +

      The Http2Session instance will be shut down automatically when the 'goaway' +event is emitted.

      +

      Event: 'localSettings'#

      + + +

      The 'localSettings' event is emitted when an acknowledgment SETTINGS frame +has been received.

      +

      When using http2session.settings() to submit new settings, the modified +settings do not take effect until the 'localSettings' event is emitted.

      +
      session.settings({ enablePush: false });
      +
      +session.on('localSettings', (settings) => {
      +  /* Use the new settings */
      +});
      +

      Event: 'ping'#

      + +
        +
      • payload <Buffer> The PING frame 8-byte payload
      • +
      +

      The 'ping' event is emitted whenever a PING frame is received from the +connected peer.

      +

      Event: 'remoteSettings'#

      + + +

      The 'remoteSettings' event is emitted when a new SETTINGS frame is received +from the connected peer.

      +
      session.on('remoteSettings', (settings) => {
      +  /* Use the new settings */
      +});
      +

      Event: 'stream'#

      + +
        +
      • stream <Http2Stream> A reference to the stream
      • +
      • headers <HTTP/2 Headers Object> An object describing the headers
      • +
      • flags <number> The associated numeric flags
      • +
      • rawHeaders <Array> An array containing the raw header names followed by +their respective values.
      • +
      +

      The 'stream' event is emitted when a new Http2Stream is created.

      +
      const http2 = require('http2');
      +session.on('stream', (stream, headers, flags) => {
      +  const method = headers[':method'];
      +  const path = headers[':path'];
      +  // ...
      +  stream.respond({
      +    ':status': 200,
      +    'content-type': 'text/plain; charset=utf-8'
      +  });
      +  stream.write('hello ');
      +  stream.end('world');
      +});
      +

      On the server side, user code will typically not listen for this event directly, +and would instead register a handler for the 'stream' event emitted by the +net.Server or tls.Server instances returned by http2.createServer() and +http2.createSecureServer(), respectively, as in the example below:

      +
      const http2 = require('http2');
      +
      +// Create an unencrypted HTTP/2 server
      +const server = http2.createServer();
      +
      +server.on('stream', (stream, headers) => {
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.on('error', (error) => console.error(error));
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(80);
      +

      Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, +a network error will destroy each individual stream and must be handled on the +stream level, as shown above.

      +

      Event: 'timeout'#

      + +

      After the http2session.setTimeout() method is used to set the timeout period +for this Http2Session, the 'timeout' event is emitted if there is no +activity on the Http2Session after the configured number of milliseconds. +Its listener does not expect any arguments.

      +
      session.setTimeout(2000);
      +session.on('timeout', () => { /* .. */ });
      +

      http2session.alpnProtocol#

      + + +

      Value will be undefined if the Http2Session is not yet connected to a +socket, h2c if the Http2Session is not connected to a TLSSocket, or +will return the value of the connected TLSSocket's own alpnProtocol +property.

      +

      http2session.close([callback])#

      + + +

      Gracefully closes the Http2Session, allowing any existing streams to +complete on their own and preventing new Http2Stream instances from being +created. Once closed, http2session.destroy() might be called if there +are no open Http2Stream instances.

      +

      If specified, the callback function is registered as a handler for the +'close' event.

      +

      http2session.closed#

      + + +

      Will be true if this Http2Session instance has been closed, otherwise +false.

      +

      http2session.connecting#

      + + +

      Will be true if this Http2Session instance is still connecting, will be set +to false before emitting connect event and/or calling the http2.connect +callback.

      +

      http2session.destroy([error][, code])#

      + +
        +
      • error <Error> An Error object if the Http2Session is being destroyed +due to an error.
      • +
      • code <number> The HTTP/2 error code to send in the final GOAWAY frame. +If unspecified, and error is not undefined, the default is INTERNAL_ERROR, +otherwise defaults to NO_ERROR.
      • +
      +

      Immediately terminates the Http2Session and the associated net.Socket or +tls.TLSSocket.

      +

      Once destroyed, the Http2Session will emit the 'close' event. If error +is not undefined, an 'error' event will be emitted immediately before the +'close' event.

      +

      If there are any remaining open Http2Streams associated with the +Http2Session, those will also be destroyed.

      +

      http2session.destroyed#

      + + +

      Will be true if this Http2Session instance has been destroyed and must no +longer be used, otherwise false.

      +

      http2session.encrypted#

      + + +

      Value is undefined if the Http2Session session socket has not yet been +connected, true if the Http2Session is connected with a TLSSocket, +and false if the Http2Session is connected to any other kind of socket +or stream.

      +

      http2session.goaway([code[, lastStreamID[, opaqueData]]])#

      + +
        +
      • code <number> An HTTP/2 error code
      • +
      • lastStreamID <number> The numeric ID of the last processed Http2Stream
      • +
      • opaqueData <Buffer> | <TypedArray> | <DataView> A TypedArray or DataView +instance containing additional data to be carried within the GOAWAY frame.
      • +
      +

      Transmits a GOAWAY frame to the connected peer without shutting down the +Http2Session.

      +

      http2session.localSettings#

      + + +

      A prototype-less object describing the current local settings of this +Http2Session. The local settings are local to this Http2Session instance.

      +

      http2session.originSet#

      + + +

      If the Http2Session is connected to a TLSSocket, the originSet property +will return an Array of origins for which the Http2Session may be +considered authoritative.

      +

      The originSet property is only available when using a secure TLS connection.

      +

      http2session.pendingSettingsAck#

      + + +

      Indicates whether the Http2Session is currently waiting for acknowledgment of +a sent SETTINGS frame. Will be true after calling the +http2session.settings() method. Will be false once all sent SETTINGS +frames have been acknowledged.

      +

      http2session.ping([payload, ]callback)#

      + + +

      Sends a PING frame to the connected HTTP/2 peer. A callback function must +be provided. The method will return true if the PING was sent, false +otherwise.

      +

      The maximum number of outstanding (unacknowledged) pings is determined by the +maxOutstandingPings configuration option. The default maximum is 10.

      +

      If provided, the payload must be a Buffer, TypedArray, or DataView +containing 8 bytes of data that will be transmitted with the PING and +returned with the ping acknowledgment.

      +

      The callback will be invoked with three arguments: an error argument that will +be null if the PING was successfully acknowledged, a duration argument +that reports the number of milliseconds elapsed since the ping was sent and the +acknowledgment was received, and a Buffer containing the 8-byte PING +payload.

      +
      session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
      +  if (!err) {
      +    console.log(`Ping acknowledged in ${duration} milliseconds`);
      +    console.log(`With payload '${payload.toString()}'`);
      +  }
      +});
      +

      If the payload argument is not specified, the default payload will be the +64-bit timestamp (little endian) marking the start of the PING duration.

      +

      http2session.ref()#

      + +

      Calls ref() on this Http2Session +instance's underlying net.Socket.

      +

      http2session.remoteSettings#

      + + +

      A prototype-less object describing the current remote settings of this +Http2Session. The remote settings are set by the connected HTTP/2 peer.

      +

      http2session.setTimeout(msecs, callback)#

      + + +

      Used to set a callback function that is called when there is no activity on +the Http2Session after msecs milliseconds. The given callback is +registered as a listener on the 'timeout' event.

      +

      http2session.socket#

      + + +

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but +limits available methods to ones safe to use with HTTP/2.

      +

      destroy, emit, end, pause, read, resume, and write will throw +an error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See +Http2Session and Sockets for more information.

      +

      setTimeout method will be called on this Http2Session.

      +

      All other interactions will be routed directly to the socket.

      +

      http2session.state#

      + +

      Provides miscellaneous information about the current state of the +Http2Session.

      +
        +
      • <Object> +
          +
        • effectiveLocalWindowSize <number> The current local (receive) +flow control window size for the Http2Session.
        • +
        • effectiveRecvDataLength <number> The current number of bytes +that have been received since the last flow control WINDOW_UPDATE.
        • +
        • nextStreamID <number> The numeric identifier to be used the +next time a new Http2Stream is created by this Http2Session.
        • +
        • localWindowSize <number> The number of bytes that the remote peer can +send without receiving a WINDOW_UPDATE.
        • +
        • lastProcStreamID <number> The numeric id of the Http2Stream +for which a HEADERS or DATA frame was most recently received.
        • +
        • remoteWindowSize <number> The number of bytes that this Http2Session +may send without receiving a WINDOW_UPDATE.
        • +
        • outboundQueueSize <number> The number of frames currently within the +outbound queue for this Http2Session.
        • +
        • deflateDynamicTableSize <number> The current size in bytes of the +outbound header compression state table.
        • +
        • inflateDynamicTableSize <number> The current size in bytes of the +inbound header compression state table.
        • +
        +
      • +
      +

      An object describing the current status of this Http2Session.

      +

      http2session.settings([settings][, callback])#

      + + +

      Updates the current local settings for this Http2Session and sends a new +SETTINGS frame to the connected HTTP/2 peer.

      +

      Once called, the http2session.pendingSettingsAck property will be true +while the session is waiting for the remote peer to acknowledge the new +settings.

      +

      The new settings will not become effective until the SETTINGS acknowledgment +is received and the 'localSettings' event is emitted. It is possible to send +multiple SETTINGS frames while acknowledgment is still pending.

      +

      http2session.type#

      + + +

      The http2session.type will be equal to +http2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a +server, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a +client.

      +

      http2session.unref()#

      + +

      Calls unref() on this Http2Session +instance's underlying net.Socket.

      +

      Class: ServerHttp2Session#

      + + +

      serverhttp2session.altsvc(alt, originOrStream)#

      + +
        +
      • alt <string> A description of the alternative service configuration as +defined by RFC 7838.
      • +
      • originOrStream <number> | <string> | <URL> | <Object> Either a URL string specifying +the origin (or an Object with an origin property) or the numeric +identifier of an active Http2Stream as given by the http2stream.id +property.
      • +
      +

      Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

      +
      const http2 = require('http2');
      +
      +const server = http2.createServer();
      +server.on('session', (session) => {
      +  // Set altsvc for origin https://example.org:80
      +  session.altsvc('h2=":8000"', 'https://example.org:80');
      +});
      +
      +server.on('stream', (stream) => {
      +  // Set altsvc for a specific stream
      +  stream.session.altsvc('h2=":8000"', stream.id);
      +});
      +

      Sending an ALTSVC frame with a specific stream ID indicates that the alternate +service is associated with the origin of the given Http2Stream.

      +

      The alt and origin string must contain only ASCII bytes and are +strictly interpreted as a sequence of ASCII bytes. The special value 'clear' +may be passed to clear any previously set alternative service for a given +domain.

      +

      When a string is passed for the originOrStream argument, it will be parsed as +a URL and the origin will be derived. For instance, the origin for the +HTTP URL 'https://example.org/foo/bar' is the ASCII string +'https://example.org'. An error will be thrown if either the given string +cannot be parsed as a URL or if a valid origin cannot be derived.

      +

      A URL object, or any object with an origin property, may be passed as +originOrStream, in which case the value of the origin property will be +used. The value of the origin property must be a properly serialized +ASCII origin.

      +

      Specifying alternative services#

      +

      The format of the alt parameter is strictly defined by RFC 7838 as an +ASCII string containing a comma-delimited list of "alternative" protocols +associated with a specific host and port.

      +

      For example, the value 'h2="example.org:81"' indicates that the HTTP/2 +protocol is available on the host 'example.org' on TCP/IP port 81. The +host and port must be contained within the quote (") characters.

      +

      Multiple alternatives may be specified, for instance: 'h2="example.org:81", h2=":82"'.

      +

      The protocol identifier ('h2' in the examples) may be any valid +ALPN Protocol ID.

      +

      The syntax of these values is not validated by the Node.js implementation and +are passed through as provided by the user or received from the peer.

      +

      serverhttp2session.origin(...origins)#

      + + +

      Submits an ORIGIN frame (as defined by RFC 8336) to the connected client +to advertise the set of origins for which the server is capable of providing +authoritative responses.

      +
      const http2 = require('http2');
      +const options = getSecureOptionsSomehow();
      +const server = http2.createSecureServer(options);
      +server.on('stream', (stream) => {
      +  stream.respond();
      +  stream.end('ok');
      +});
      +server.on('session', (session) => {
      +  session.origin('https://example.com', 'https://example.org');
      +});
      +

      When a string is passed as an origin, it will be parsed as a URL and the +origin will be derived. For instance, the origin for the HTTP URL +'https://example.org/foo/bar' is the ASCII string +'https://example.org'. An error will be thrown if either the given string +cannot be parsed as a URL or if a valid origin cannot be derived.

      +

      A URL object, or any object with an origin property, may be passed as +an origin, in which case the value of the origin property will be +used. The value of the origin property must be a properly serialized +ASCII origin.

      +

      Alternatively, the origins option may be used when creating a new HTTP/2 +server using the http2.createSecureServer() method:

      +
      const http2 = require('http2');
      +const options = getSecureOptionsSomehow();
      +options.origins = ['https://example.com', 'https://example.org'];
      +const server = http2.createSecureServer(options);
      +server.on('stream', (stream) => {
      +  stream.respond();
      +  stream.end('ok');
      +});
      +

      Class: ClientHttp2Session#

      + + +

      Event: 'altsvc'#

      + + +

      The 'altsvc' event is emitted whenever an ALTSVC frame is received by +the client. The event is emitted with the ALTSVC value, origin, and stream +ID. If no origin is provided in the ALTSVC frame, origin will +be an empty string.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://example.org');
      +
      +client.on('altsvc', (alt, origin, streamId) => {
      +  console.log(alt);
      +  console.log(origin);
      +  console.log(streamId);
      +});
      +

      Event: 'origin'#

      + + +

      The 'origin' event is emitted whenever an ORIGIN frame is received by +the client. The event is emitted with an array of origin strings. The +http2session.originSet will be updated to include the received +origins.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://example.org');
      +
      +client.on('origin', (origins) => {
      +  for (let n = 0; n < origins.length; n++)
      +    console.log(origins[n]);
      +});
      +

      The 'origin' event is only emitted when using a secure TLS connection.

      +

      clienthttp2session.request(headers[, options])#

      + +
        +
      • +

        headers <HTTP/2 Headers Object>

        +
      • +
      • +

        options <Object>

        +
          +
        • endStream <boolean> true if the Http2Stream writable side should +be closed initially, such as when sending a GET request that should not +expect a payload body.
        • +
        • exclusive <boolean> When true and parent identifies a parent Stream, +the created stream is made the sole direct dependency of the parent, with +all other existing dependents made a dependent of the newly created stream. +Default: false.
        • +
        • parent <number> Specifies the numeric identifier of a stream the newly +created stream is dependent on.
        • +
        • weight <number> Specifies the relative dependency of a stream in relation +to other streams with the same parent. The value is a number between 1 +and 256 (inclusive).
        • +
        • waitForTrailers <boolean> When true, the Http2Stream will emit the +'wantTrailers' event after the final DATA frame has been sent.
        • +
        +
      • +
      • +

        Returns: <ClientHttp2Stream>

        +
      • +
      +

      For HTTP/2 Client Http2Session instances only, the http2session.request() +creates and returns an Http2Stream instance that can be used to send an +HTTP/2 request to the connected server.

      +

      This method is only available if http2session.type is equal to +http2.constants.NGHTTP2_SESSION_CLIENT.

      +
      const http2 = require('http2');
      +const clientSession = http2.connect('https://localhost:1234');
      +const {
      +  HTTP2_HEADER_PATH,
      +  HTTP2_HEADER_STATUS
      +} = http2.constants;
      +
      +const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
      +req.on('response', (headers) => {
      +  console.log(headers[HTTP2_HEADER_STATUS]);
      +  req.on('data', (chunk) => { /* .. */ });
      +  req.on('end', () => { /* .. */ });
      +});
      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +is emitted immediately after queuing the last chunk of payload data to be sent. +The http2stream.sendTrailers() method can then be called to send trailing +headers to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +

      The :method and :path pseudo-headers are not specified within headers, +they respectively default to:

      +
        +
      • :method = 'GET'
      • +
      • :path = /
      • +
      +

      Class: Http2Stream#

      + + +

      Each instance of the Http2Stream class represents a bidirectional HTTP/2 +communications stream over an Http2Session instance. Any single Http2Session +may have up to 231-1 Http2Stream instances over its lifetime.

      +

      User code will not construct Http2Stream instances directly. Rather, these +are created, managed, and provided to user code through the Http2Session +instance. On the server, Http2Stream instances are created either in response +to an incoming HTTP request (and handed off to user code via the 'stream' +event), or in response to a call to the http2stream.pushStream() method. +On the client, Http2Stream instances are created and returned when either the +http2session.request() method is called, or in response to an incoming +'push' event.

      +

      The Http2Stream class is a base for the ServerHttp2Stream and +ClientHttp2Stream classes, each of which is used specifically by either +the Server or Client side, respectively.

      +

      All Http2Stream instances are Duplex streams. The Writable side of the +Duplex is used to send data to the connected peer, while the Readable side +is used to receive data sent by the connected peer.

      +

      The default text character encoding for all Http2Streams is UTF-8. As a best +practice, it is recommended that when using an Http2Stream to send text, +the 'content-type' header should be set and should identify the character +encoding used.

      +
      stream.respond({
      +  'content-type': 'text/html; charset=utf-8',
      +  ':status': 200
      +});
      +

      Http2Stream Lifecycle#

      +
      Creation#
      +

      On the server side, instances of ServerHttp2Stream are created either +when:

      +
        +
      • A new HTTP/2 HEADERS frame with a previously unused stream ID is received;
      • +
      • The http2stream.pushStream() method is called.
      • +
      +

      On the client side, instances of ClientHttp2Stream are created when the +http2session.request() method is called.

      +

      On the client, the Http2Stream instance returned by http2session.request() +may not be immediately ready for use if the parent Http2Session has not yet +been fully established. In such cases, operations called on the Http2Stream +will be buffered until the 'ready' event is emitted. User code should rarely, +if ever, need to handle the 'ready' event directly. The ready status of an +Http2Stream can be determined by checking the value of http2stream.id. If +the value is undefined, the stream is not yet ready for use.

      +
      Destruction#
      +

      All Http2Stream instances are destroyed either when:

      +
        +
      • An RST_STREAM frame for the stream is received by the connected peer, +and (for client streams only) pending data has been read.
      • +
      • The http2stream.close() method is called, and (for client streams only) +pending data has been read.
      • +
      • The http2stream.destroy() or http2session.destroy() methods are called.
      • +
      +

      When an Http2Stream instance is destroyed, an attempt will be made to send an +RST_STREAM frame to the connected peer.

      +

      When the Http2Stream instance is destroyed, the 'close' event will +be emitted. Because Http2Stream is an instance of stream.Duplex, the +'end' event will also be emitted if the stream data is currently flowing. +The 'error' event may also be emitted if http2stream.destroy() was called +with an Error passed as the first argument.

      +

      After the Http2Stream has been destroyed, the http2stream.destroyed +property will be true and the http2stream.rstCode property will specify the +RST_STREAM error code. The Http2Stream instance is no longer usable once +destroyed.

      +

      Event: 'aborted'#

      + +

      The 'aborted' event is emitted whenever a Http2Stream instance is +abnormally aborted in mid-communication. +Its listener does not expect any arguments.

      +

      The 'aborted' event will only be emitted if the Http2Stream writable side +has not been ended.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted when the Http2Stream is destroyed. Once +this event is emitted, the Http2Stream instance is no longer usable.

      +

      The HTTP/2 error code used when closing the stream can be retrieved using +the http2stream.rstCode property. If the code is any value other than +NGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.

      +

      Event: 'error'#

      + + +

      The 'error' event is emitted when an error occurs during the processing of +an Http2Stream.

      +

      Event: 'frameError'#

      + +
        +
      • type <integer> The frame type.
      • +
      • code <integer> The error code.
      • +
      • id <integer> The stream id (or 0 if the frame isn't associated with a +stream).
      • +
      +

      The 'frameError' event is emitted when an error occurs while attempting to +send a frame. When invoked, the handler function will receive an integer +argument identifying the frame type, and an integer argument identifying the +error code. The Http2Stream instance will be destroyed immediately after the +'frameError' event is emitted.

      +

      Event: 'ready'#

      + +

      The 'ready' event is emitted when the Http2Stream has been opened, has +been assigned an id, and can be used. The listener does not expect any +arguments.

      +

      Event: 'timeout'#

      + +

      The 'timeout' event is emitted after no activity is received for this +Http2Stream within the number of milliseconds set using +http2stream.setTimeout(). +Its listener does not expect any arguments.

      +

      Event: 'trailers'#

      + + +

      The 'trailers' event is emitted when a block of headers associated with +trailing header fields is received. The listener callback is passed the +HTTP/2 Headers Object and flags associated with the headers.

      +

      This event might not be emitted if http2stream.end() is called +before trailers are received and the incoming data is not being read or +listened for.

      +
      stream.on('trailers', (headers, flags) => {
      +  console.log(headers);
      +});
      +

      Event: 'wantTrailers'#

      + +

      The 'wantTrailers' event is emitted when the Http2Stream has queued the +final DATA frame to be sent on a frame and the Http2Stream is ready to send +trailing headers. When initiating a request or response, the waitForTrailers +option must be set for this event to be emitted.

      +

      http2stream.aborted#

      + + +

      Set to true if the Http2Stream instance was aborted abnormally. When set, +the 'aborted' event will have been emitted.

      +

      http2stream.bufferSize#

      + + +

      This property shows the number of characters currently buffered to be written. +See net.Socket.bufferSize for details.

      +

      http2stream.close(code[, callback])#

      + +
        +
      • code <number> Unsigned 32-bit integer identifying the error code. +Default: http2.constants.NGHTTP2_NO_ERROR (0x00).
      • +
      • callback <Function> An optional function registered to listen for the +'close' event.
      • +
      +

      Closes the Http2Stream instance by sending an RST_STREAM frame to the +connected HTTP/2 peer.

      +

      http2stream.closed#

      + + +

      Set to true if the Http2Stream instance has been closed.

      +

      http2stream.destroyed#

      + + +

      Set to true if the Http2Stream instance has been destroyed and is no longer +usable.

      +

      http2stream.endAfterHeaders#

      + + +

      Set the true if the END_STREAM flag was set in the request or response +HEADERS frame received, indicating that no additional data should be received +and the readable side of the Http2Stream will be closed.

      +

      http2stream.id#

      + + +

      The numeric stream identifier of this Http2Stream instance. Set to undefined +if the stream identifier has not yet been assigned.

      +

      http2stream.pending#

      + + +

      Set to true if the Http2Stream instance has not yet been assigned a +numeric stream identifier.

      +

      http2stream.priority(options)#

      + +
        +
      • options <Object> +
          +
        • exclusive <boolean> When true and parent identifies a parent Stream, +this stream is made the sole direct dependency of the parent, with +all other existing dependents made a dependent of this stream. Default: +false.
        • +
        • parent <number> Specifies the numeric identifier of a stream this stream +is dependent on.
        • +
        • weight <number> Specifies the relative dependency of a stream in relation +to other streams with the same parent. The value is a number between 1 +and 256 (inclusive).
        • +
        • silent <boolean> When true, changes the priority locally without +sending a PRIORITY frame to the connected peer.
        • +
        +
      • +
      +

      Updates the priority for this Http2Stream instance.

      +

      http2stream.rstCode#

      + + +

      Set to the RST_STREAM error code reported when the Http2Stream is +destroyed after either receiving an RST_STREAM frame from the connected peer, +calling http2stream.close(), or http2stream.destroy(). Will be +undefined if the Http2Stream has not been closed.

      +

      http2stream.sentHeaders#

      + + +

      An object containing the outbound headers sent for this Http2Stream.

      +

      http2stream.sentInfoHeaders#

      + + +

      An array of objects containing the outbound informational (additional) headers +sent for this Http2Stream.

      +

      http2stream.sentTrailers#

      + + +

      An object containing the outbound trailers sent for this HttpStream.

      +

      http2stream.session#

      + + +

      A reference to the Http2Session instance that owns this Http2Stream. The +value will be undefined after the Http2Stream instance is destroyed.

      +

      http2stream.setTimeout(msecs, callback)#

      + + +
      const http2 = require('http2');
      +const client = http2.connect('http://example.org:8000');
      +const { NGHTTP2_CANCEL } = http2.constants;
      +const req = client.request({ ':path': '/' });
      +
      +// Cancel the stream if there's no activity after 5 seconds
      +req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
      +

      http2stream.state#

      + +

      Provides miscellaneous information about the current state of the +Http2Stream.

      +
        +
      • <Object> +
          +
        • localWindowSize <number> The number of bytes the connected peer may send +for this Http2Stream without receiving a WINDOW_UPDATE.
        • +
        • state <number> A flag indicating the low-level current state of the +Http2Stream as determined by nghttp2.
        • +
        • localClose <number> 1 if this Http2Stream has been closed locally.
        • +
        • remoteClose <number> 1 if this Http2Stream has been closed +remotely.
        • +
        • sumDependencyWeight <number> The sum weight of all Http2Stream +instances that depend on this Http2Stream as specified using +PRIORITY frames.
        • +
        • weight <number> The priority weight of this Http2Stream.
        • +
        +
      • +
      +

      A current state of this Http2Stream.

      +

      http2stream.sendTrailers(headers)#

      + + +

      Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method +will cause the Http2Stream to be immediately closed and must only be +called after the 'wantTrailers' event has been emitted. When sending a +request or sending a response, the options.waitForTrailers option must be set +in order to keep the Http2Stream open after the final DATA frame so that +trailers can be sent.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond(undefined, { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ xyz: 'abc' });
      +  });
      +  stream.end('Hello World');
      +});
      +

      The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header +fields (e.g. ':method', ':path', etc).

      +

      Class: ClientHttp2Stream#

      + + +

      The ClientHttp2Stream class is an extension of Http2Stream that is +used exclusively on HTTP/2 Clients. Http2Stream instances on the client +provide events such as 'response' and 'push' that are only relevant on +the client.

      +

      Event: 'continue'#

      + +

      Emitted when the server sends a 100 Continue status, usually because +the request contained Expect: 100-continue. This is an instruction that +the client should send the request body.

      +

      Event: 'headers'#

      + +

      The 'headers' event is emitted when an additional block of headers is received +for a stream, such as when a block of 1xx informational headers is received. +The listener callback is passed the HTTP/2 Headers Object and flags +associated with the headers.

      +
      stream.on('headers', (headers, flags) => {
      +  console.log(headers);
      +});
      +

      Event: 'push'#

      + +

      The 'push' event is emitted when response headers for a Server Push stream +are received. The listener callback is passed the HTTP/2 Headers Object and +flags associated with the headers.

      +
      stream.on('push', (headers, flags) => {
      +  console.log(headers);
      +});
      +

      Event: 'response'#

      + +

      The 'response' event is emitted when a response HEADERS frame has been +received for this stream from the connected HTTP/2 server. The listener is +invoked with two arguments: an Object containing the received +HTTP/2 Headers Object, and flags associated with the headers.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://localhost');
      +const req = client.request({ ':path': '/' });
      +req.on('response', (headers, flags) => {
      +  console.log(headers[':status']);
      +});
      +

      Class: ServerHttp2Stream#

      + + +

      The ServerHttp2Stream class is an extension of Http2Stream that is +used exclusively on HTTP/2 Servers. Http2Stream instances on the server +provide additional methods such as http2stream.pushStream() and +http2stream.respond() that are only relevant on the server.

      +

      http2stream.additionalHeaders(headers)#

      + + +

      Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

      +

      http2stream.headersSent#

      + + +

      True if headers were sent, false otherwise (read-only).

      +

      http2stream.pushAllowed#

      + + +

      Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote +client's most recent SETTINGS frame. Will be true if the remote peer +accepts push streams, false otherwise. Settings are the same for every +Http2Stream in the same Http2Session.

      +

      http2stream.pushStream(headers[, options], callback)#

      + +
        +
      • headers <HTTP/2 Headers Object>
      • +
      • options <Object> +
          +
        • exclusive <boolean> When true and parent identifies a parent Stream, +the created stream is made the sole direct dependency of the parent, with +all other existing dependents made a dependent of the newly created stream. +Default: false.
        • +
        • parent <number> Specifies the numeric identifier of a stream the newly +created stream is dependent on.
        • +
        +
      • +
      • callback <Function> Callback that is called once the push stream has been +initiated. + +
      • +
      +

      Initiates a push stream. The callback is invoked with the new Http2Stream +instance created for the push stream passed as the second argument, or an +Error passed as the first argument.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond({ ':status': 200 });
      +  stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
      +    if (err) throw err;
      +    pushStream.respond({ ':status': 200 });
      +    pushStream.end('some pushed data');
      +  });
      +  stream.end('some data');
      +});
      +

      Setting the weight of a push stream is not allowed in the HEADERS frame. Pass +a weight value to http2stream.priority with the silent option set to +true to enable server-side bandwidth balancing between concurrent streams.

      +

      Calling http2stream.pushStream() from within a pushed stream is not permitted +and will throw an error.

      +

      http2stream.respond([headers[, options]])#

      + +
        +
      • headers <HTTP/2 Headers Object>
      • +
      • options <Object> +
          +
        • endStream <boolean> Set to true to indicate that the response will not +include payload data.
        • +
        • waitForTrailers <boolean> When true, the Http2Stream will emit the +'wantTrailers' event after the final DATA frame has been sent.
        • +
        +
      • +
      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond({ ':status': 200 });
      +  stream.end('some data');
      +});
      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +will be emitted immediately after queuing the last chunk of payload data to be +sent. The http2stream.sendTrailers() method can then be used to sent trailing +header fields to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond({ ':status': 200 }, { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ ABC: 'some value to send' });
      +  });
      +  stream.end('some data');
      +});
      +

      http2stream.respondWithFD(fd[, headers[, options]])#

      + + +

      Initiates a response whose data is read from the given file descriptor. No +validation is performed on the given file descriptor. If an error occurs while +attempting to read data using the file descriptor, the Http2Stream will be +closed using an RST_STREAM frame using the standard INTERNAL_ERROR code.

      +

      When used, the Http2Stream object's Duplex interface will be closed +automatically.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  const fd = fs.openSync('/some/file', 'r');
      +
      +  const stat = fs.fstatSync(fd);
      +  const headers = {
      +    'content-length': stat.size,
      +    'last-modified': stat.mtime.toUTCString(),
      +    'content-type': 'text/plain; charset=utf-8'
      +  };
      +  stream.respondWithFD(fd, headers);
      +  stream.on('close', () => fs.closeSync(fd));
      +});
      +

      The optional options.statCheck function may be specified to give user code +an opportunity to set additional content headers based on the fs.Stat details +of the given fd. If the statCheck function is provided, the +http2stream.respondWithFD() method will perform an fs.fstat() call to +collect details on the provided file descriptor.

      +

      The offset and length options may be used to limit the response to a +specific range subset. This can be used, for instance, to support HTTP Range +requests.

      +

      The file descriptor or FileHandle is not closed when the stream is closed, +so it will need to be closed manually once it is no longer needed. +Using the same file descriptor concurrently for multiple streams +is not supported and may result in data loss. Re-using a file descriptor +after a stream has finished is supported.

      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +will be emitted immediately after queuing the last chunk of payload data to be +sent. The http2stream.sendTrailers() method can then be used to sent trailing +header fields to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  const fd = fs.openSync('/some/file', 'r');
      +
      +  const stat = fs.fstatSync(fd);
      +  const headers = {
      +    'content-length': stat.size,
      +    'last-modified': stat.mtime.toUTCString(),
      +    'content-type': 'text/plain; charset=utf-8'
      +  };
      +  stream.respondWithFD(fd, headers, { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ ABC: 'some value to send' });
      +  });
      +
      +  stream.on('close', () => fs.closeSync(fd));
      +});
      +

      http2stream.respondWithFile(path[, headers[, options]])#

      + + +

      Sends a regular file as the response. The path must specify a regular file +or an 'error' event will be emitted on the Http2Stream object.

      +

      When used, the Http2Stream object's Duplex interface will be closed +automatically.

      +

      The optional options.statCheck function may be specified to give user code +an opportunity to set additional content headers based on the fs.Stat details +of the given file:

      +

      If an error occurs while attempting to read the file data, the Http2Stream +will be closed using an RST_STREAM frame using the standard INTERNAL_ERROR +code. If the onError callback is defined, then it will be called. Otherwise +the stream will be destroyed.

      +

      Example using a file path:

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  function statCheck(stat, headers) {
      +    headers['last-modified'] = stat.mtime.toUTCString();
      +  }
      +
      +  function onError(err) {
      +    if (err.code === 'ENOENT') {
      +      stream.respond({ ':status': 404 });
      +    } else {
      +      stream.respond({ ':status': 500 });
      +    }
      +    stream.end();
      +  }
      +
      +  stream.respondWithFile('/some/file',
      +                         { 'content-type': 'text/plain; charset=utf-8' },
      +                         { statCheck, onError });
      +});
      +

      The options.statCheck function may also be used to cancel the send operation +by returning false. For instance, a conditional request may check the stat +results to determine if the file has been modified to return an appropriate +304 response:

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  function statCheck(stat, headers) {
      +    // Check the stat here...
      +    stream.respond({ ':status': 304 });
      +    return false; // Cancel the send operation
      +  }
      +  stream.respondWithFile('/some/file',
      +                         { 'content-type': 'text/plain; charset=utf-8' },
      +                         { statCheck });
      +});
      +

      The content-length header field will be automatically set.

      +

      The offset and length options may be used to limit the response to a +specific range subset. This can be used, for instance, to support HTTP Range +requests.

      +

      The options.onError function may also be used to handle all the errors +that could happen before the delivery of the file is initiated. The +default behavior is to destroy the stream.

      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +will be emitted immediately after queuing the last chunk of payload data to be +sent. The http2stream.sendTrailers() method can then be used to sent trailing +header fields to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respondWithFile('/some/file',
      +                         { 'content-type': 'text/plain; charset=utf-8' },
      +                         { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ ABC: 'some value to send' });
      +  });
      +});
      +

      Class: Http2Server#

      + + +

      Instances of Http2Server are created using the http2.createServer() +function. The Http2Server class is not exported directly by the http2 +module.

      +

      Event: 'checkContinue'#

      + + +

      If a 'request' listener is registered or http2.createServer() is +supplied a callback function, the 'checkContinue' event is emitted each time +a request with an HTTP Expect: 100-continue is received. If this event is +not listened for, the server will automatically respond with a status +100 Continue as appropriate.

      +

      Handling this event involves calling response.writeContinue() if the +client should continue to send the request body, or generating an appropriate +HTTP response (e.g. 400 Bad Request) if the client should not continue to send +the request body.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established. socket is +typically an object of type net.Socket. Usually users will not want to +access this event.

      +

      This event can also be explicitly emitted by users to inject connections +into the HTTP server. In that case, any Duplex stream can be passed.

      +

      Event: 'request'#

      + + +

      Emitted each time there is a request. There may be multiple requests +per session. See the Compatibility API.

      +

      Event: 'session'#

      + +

      The 'session' event is emitted when a new Http2Session is created by the +Http2Server.

      +

      Event: 'sessionError'#

      + +

      The 'sessionError' event is emitted when an 'error' event is emitted by +an Http2Session object associated with the Http2Server.

      +

      Event: 'stream'#

      + +

      The 'stream' event is emitted when a 'stream' event has been emitted by +an Http2Session associated with the server.

      +
      const http2 = require('http2');
      +const {
      +  HTTP2_HEADER_METHOD,
      +  HTTP2_HEADER_PATH,
      +  HTTP2_HEADER_STATUS,
      +  HTTP2_HEADER_CONTENT_TYPE
      +} = http2.constants;
      +
      +const server = http2.createServer();
      +server.on('stream', (stream, headers, flags) => {
      +  const method = headers[HTTP2_HEADER_METHOD];
      +  const path = headers[HTTP2_HEADER_PATH];
      +  // ...
      +  stream.respond({
      +    [HTTP2_HEADER_STATUS]: 200,
      +    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
      +  });
      +  stream.write('hello ');
      +  stream.end('world');
      +});
      +

      Event: 'timeout'#

      + +

      The 'timeout' event is emitted when there is no activity on the Server for +a given number of milliseconds set using http2server.setTimeout(). +Default: 2 minutes.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      server.close([callback])#

      + + +

      Stops the server from establishing new sessions. This does not prevent new +request streams from being created due to the persistent nature of HTTP/2 +sessions. To gracefully shut down the server, call http2session.close() on +all active sessions.

      +

      If callback is provided, it is not invoked until all active sessions have been +closed, although the server has already stopped allowing new sessions. See +net.Server.close() for more details.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      Used to set the timeout value for http2 server requests, +and sets a callback function that is called when there is no activity +on the Http2Server after msecs milliseconds.

      +

      The given callback is registered as a listener on the 'timeout' event.

      +

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK +error will be thrown.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      Class: Http2SecureServer#

      + + +

      Instances of Http2SecureServer are created using the +http2.createSecureServer() function. The Http2SecureServer class is not +exported directly by the http2 module.

      +

      Event: 'checkContinue'#

      + + +

      If a 'request' listener is registered or http2.createSecureServer() +is supplied a callback function, the 'checkContinue' event is emitted each +time a request with an HTTP Expect: 100-continue is received. If this event +is not listened for, the server will automatically respond with a status +100 Continue as appropriate.

      +

      Handling this event involves calling response.writeContinue() if the +client should continue to send the request body, or generating an appropriate +HTTP response (e.g. 400 Bad Request) if the client should not continue to send +the request body.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established, before the TLS +handshake begins. socket is typically an object of type net.Socket. +Usually users will not want to access this event.

      +

      This event can also be explicitly emitted by users to inject connections +into the HTTP server. In that case, any Duplex stream can be passed.

      +

      Event: 'request'#

      + + +

      Emitted each time there is a request. There may be multiple requests +per session. See the Compatibility API.

      +

      Event: 'session'#

      + +

      The 'session' event is emitted when a new Http2Session is created by the +Http2SecureServer.

      +

      Event: 'sessionError'#

      + +

      The 'sessionError' event is emitted when an 'error' event is emitted by +an Http2Session object associated with the Http2SecureServer.

      +

      Event: 'stream'#

      + +

      The 'stream' event is emitted when a 'stream' event has been emitted by +an Http2Session associated with the server.

      +
      const http2 = require('http2');
      +const {
      +  HTTP2_HEADER_METHOD,
      +  HTTP2_HEADER_PATH,
      +  HTTP2_HEADER_STATUS,
      +  HTTP2_HEADER_CONTENT_TYPE
      +} = http2.constants;
      +
      +const options = getOptionsSomehow();
      +
      +const server = http2.createSecureServer(options);
      +server.on('stream', (stream, headers, flags) => {
      +  const method = headers[HTTP2_HEADER_METHOD];
      +  const path = headers[HTTP2_HEADER_PATH];
      +  // ...
      +  stream.respond({
      +    [HTTP2_HEADER_STATUS]: 200,
      +    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
      +  });
      +  stream.write('hello ');
      +  stream.end('world');
      +});
      +

      Event: 'timeout'#

      + +

      The 'timeout' event is emitted when there is no activity on the Server for +a given number of milliseconds set using http2secureServer.setTimeout(). +Default: 2 minutes.

      +

      Event: 'unknownProtocol'#

      + +

      The 'unknownProtocol' event is emitted when a connecting client fails to +negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler +receives the socket for handling. If no listener is registered for this event, +the connection is terminated. A timeout may be specified using the +'unknownProtocolTimeout' option passed to http2.createSecureServer(). +See the Compatibility API.

      +

      server.close([callback])#

      + + +

      Stops the server from establishing new sessions. This does not prevent new +request streams from being created due to the persistent nature of HTTP/2 +sessions. To gracefully shut down the server, call http2session.close() on +all active sessions.

      +

      If callback is provided, it is not invoked until all active sessions have been +closed, although the server has already stopped allowing new sessions. See +tls.Server.close() for more details.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      Used to set the timeout value for http2 secure server requests, +and sets a callback function that is called when there is no activity +on the Http2SecureServer after msecs milliseconds.

      +

      The given callback is registered as a listener on the 'timeout' event.

      +

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK +error will be thrown.

      +

      http2.createServer(options[, onRequestHandler])#

      + +
        +
      • options <Object> +
          +
        • maxDeflateDynamicTableSize <number> Sets the maximum dynamic table size +for deflating header fields. Default: 4Kib.
        • +
        • maxSettings <number> Sets the maximum number of settings entries per +SETTINGS frame. The minimum value allowed is 1. Default: 32.
        • +
        • maxSessionMemory<number> Sets the maximum memory that the Http2Session +is permitted to use. The value is expressed in terms of number of megabytes, +e.g. 1 equal 1 megabyte. The minimum value allowed is 1. +This is a credit based limit, existing Http2Streams may cause this +limit to be exceeded, but new Http2Stream instances will be rejected +while this limit is exceeded. The current number of Http2Stream sessions, +the current memory use of the header compression tables, current data +queued to be sent, and unacknowledged PING and SETTINGS frames are all +counted towards the current limit. Default: 10.
        • +
        • maxHeaderListPairs <number> Sets the maximum number of header entries. +This is similar to http.Server#maxHeadersCount or +http.ClientRequest#maxHeadersCount. The minimum value is 4. +Default: 128.
        • +
        • maxOutstandingPings <number> Sets the maximum number of outstanding, +unacknowledged pings. Default: 10.
        • +
        • maxSendHeaderBlockLength <number> Sets the maximum allowed size for a +serialized, compressed block of headers. Attempts to send headers that +exceed this limit will result in a 'frameError' event being emitted +and the stream being closed and destroyed.
        • +
        • paddingStrategy <number> The strategy used for determining the amount of +padding to use for HEADERS and DATA frames. Default: +http2.constants.PADDING_STRATEGY_NONE. Value may be one of: +
            +
          • http2.constants.PADDING_STRATEGY_NONE: Specifies that no padding is +to be applied.
          • +
          • http2.constants.PADDING_STRATEGY_MAX: Specifies that the maximum +amount of padding, as determined by the internal implementation, is to +be applied.
          • +
          • http2.constants.PADDING_STRATEGY_CALLBACK: Specifies that the user +provided options.selectPadding() callback is to be used to determine +the amount of padding.
          • +
          • http2.constants.PADDING_STRATEGY_ALIGNED: Will attempt to apply +enough padding to ensure that the total frame length, including the +9-byte header, is a multiple of 8. For each frame, however, there is a +maximum allowed number of padding bytes that is determined by current +flow control state and settings. If this maximum is less than the +calculated amount needed to ensure alignment, the maximum will be used +and the total frame length will not necessarily be aligned at 8 bytes.
          • +
          +
        • +
        • peerMaxConcurrentStreams <number> Sets the maximum number of concurrent +streams for the remote peer as if a SETTINGS frame had been received. Will +be overridden if the remote peer sets its own value for +maxConcurrentStreams. Default: 100.
        • +
        • maxSessionInvalidFrames <integer> Sets the maximum number of invalid +frames that will be tolerated before the session is closed. +Default: 1000.
        • +
        • maxSessionRejectedStreams <integer> Sets the maximum number of rejected +upon creation streams that will be tolerated before the session is closed. +Each rejection is associated with an NGHTTP2_ENHANCE_YOUR_CALM +error that should tell the peer to not open any more streams, continuing +to open streams is therefore regarded as a sign of a misbehaving peer. +Default: 100.
        • +
        • selectPadding <Function> When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, provides the callback function +used to determine the padding. See Using options.selectPadding().
        • +
        • settings <HTTP/2 Settings Object> The initial settings to send to the +remote peer upon connection.
        • +
        • Http1IncomingMessage <http.IncomingMessage> Specifies the +IncomingMessage class to used for HTTP/1 fallback. Useful for extending +the original http.IncomingMessage. Default: http.IncomingMessage.
        • +
        • Http1ServerResponse <http.ServerResponse> Specifies the ServerResponse +class to used for HTTP/1 fallback. Useful for extending the original +http.ServerResponse. Default: http.ServerResponse.
        • +
        • Http2ServerRequest <http2.Http2ServerRequest> Specifies the +Http2ServerRequest class to use. +Useful for extending the original Http2ServerRequest. +Default: Http2ServerRequest.
        • +
        • Http2ServerResponse <http2.Http2ServerResponse> Specifies the +Http2ServerResponse class to use. +Useful for extending the original Http2ServerResponse. +Default: Http2ServerResponse.
        • +
        • unknownProtocolTimeout <number> Specifies a timeout in milliseconds that +a server should wait when an 'unknownProtocol' is emitted. If the +socket has not been destroyed by that time the server will destroy it. +Default: 10000.
        • +
        • ...: Any net.createServer() option can be provided.
        • +
        +
      • +
      • onRequestHandler <Function> See Compatibility API
      • +
      • Returns: <Http2Server>
      • +
      +

      Returns a net.Server instance that creates and manages Http2Session +instances.

      +

      Since there are no browsers known that support +unencrypted HTTP/2, the use of +http2.createSecureServer() is necessary when communicating +with browser clients.

      +
      const http2 = require('http2');
      +
      +// Create an unencrypted HTTP/2 server.
      +// Since there are no browsers known that support
      +// unencrypted HTTP/2, the use of `http2.createSecureServer()`
      +// is necessary when communicating with browser clients.
      +const server = http2.createServer();
      +
      +server.on('stream', (stream, headers) => {
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(80);
      +

      http2.createSecureServer(options[, onRequestHandler])#

      + +
        +
      • options <Object> +
          +
        • allowHTTP1 <boolean> Incoming client connections that do not support +HTTP/2 will be downgraded to HTTP/1.x when set to true. +See the 'unknownProtocol' event. See ALPN negotiation. +Default: false.
        • +
        • maxDeflateDynamicTableSize <number> Sets the maximum dynamic table size +for deflating header fields. Default: 4Kib.
        • +
        • maxSettings <number> Sets the maximum number of settings entries per +SETTINGS frame. The minimum value allowed is 1. Default: 32.
        • +
        • maxSessionMemory<number> Sets the maximum memory that the Http2Session +is permitted to use. The value is expressed in terms of number of megabytes, +e.g. 1 equal 1 megabyte. The minimum value allowed is 1. This is a +credit based limit, existing Http2Streams may cause this +limit to be exceeded, but new Http2Stream instances will be rejected +while this limit is exceeded. The current number of Http2Stream sessions, +the current memory use of the header compression tables, current data +queued to be sent, and unacknowledged PING and SETTINGS frames are all +counted towards the current limit. Default: 10.
        • +
        • maxHeaderListPairs <number> Sets the maximum number of header entries. +This is similar to http.Server#maxHeadersCount or +http.ClientRequest#maxHeadersCount. The minimum value is 4. +Default: 128.
        • +
        • maxOutstandingPings <number> Sets the maximum number of outstanding, +unacknowledged pings. Default: 10.
        • +
        • maxSendHeaderBlockLength <number> Sets the maximum allowed size for a +serialized, compressed block of headers. Attempts to send headers that +exceed this limit will result in a 'frameError' event being emitted +and the stream being closed and destroyed.
        • +
        • paddingStrategy <number> Strategy used for determining the amount of +padding to use for HEADERS and DATA frames. Default: +http2.constants.PADDING_STRATEGY_NONE. Value may be one of: +
            +
          • http2.constants.PADDING_STRATEGY_NONE: Specifies that no padding is +to be applied.
          • +
          • http2.constants.PADDING_STRATEGY_MAX: Specifies that the maximum +amount of padding, as determined by the internal implementation, is to +be applied.
          • +
          • http2.constants.PADDING_STRATEGY_CALLBACK: Specifies that the user +provided options.selectPadding() callback is to be used to determine +the amount of padding.
          • +
          • http2.constants.PADDING_STRATEGY_ALIGNED: Will attempt to apply +enough padding to ensure that the total frame length, including the +9-byte header, is a multiple of 8. For each frame, however, there is a +maximum allowed number of padding bytes that is determined by current +flow control state and settings. If this maximum is less than the +calculated amount needed to ensure alignment, the maximum will be used +and the total frame length will not necessarily be aligned at 8 bytes.
          • +
          +
        • +
        • peerMaxConcurrentStreams <number> Sets the maximum number of concurrent +streams for the remote peer as if a SETTINGS frame had been received. Will +be overridden if the remote peer sets its own value for +maxConcurrentStreams. Default: 100.
        • +
        • maxSessionInvalidFrames <integer> Sets the maximum number of invalid +frames that will be tolerated before the session is closed. +Default: 1000.
        • +
        • maxSessionRejectedStreams <integer> Sets the maximum number of rejected +upon creation streams that will be tolerated before the session is closed. +Each rejection is associated with an NGHTTP2_ENHANCE_YOUR_CALM +error that should tell the peer to not open any more streams, continuing +to open streams is therefore regarded as a sign of a misbehaving peer. +Default: 100.
        • +
        • selectPadding <Function> When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, provides the callback function +used to determine the padding. See Using options.selectPadding().
        • +
        • settings <HTTP/2 Settings Object> The initial settings to send to the +remote peer upon connection.
        • +
        • ...: Any tls.createServer() options can be provided. For +servers, the identity options (pfx or key/cert) are usually required.
        • +
        • origins <string[]> An array of origin strings to send within an ORIGIN +frame immediately following creation of a new server Http2Session.
        • +
        • unknownProtocolTimeout <number> Specifies a timeout in milliseconds that +a server should wait when an 'unknownProtocol' event is emitted. If +the socket has not been destroyed by that time the server will destroy it. +Default: 10000.
        • +
        +
      • +
      • onRequestHandler <Function> See Compatibility API
      • +
      • Returns: <Http2SecureServer>
      • +
      +

      Returns a tls.Server instance that creates and manages Http2Session +instances.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const options = {
      +  key: fs.readFileSync('server-key.pem'),
      +  cert: fs.readFileSync('server-cert.pem')
      +};
      +
      +// Create a secure HTTP/2 server
      +const server = http2.createSecureServer(options);
      +
      +server.on('stream', (stream, headers) => {
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(80);
      +

      http2.connect(authority[, options][, listener])#

      + +
        +
      • authority <string> | <URL> The remote HTTP/2 server to connect to. This must +be in the form of a minimal, valid URL with the http:// or https:// +prefix, host name, and IP port (if a non-default port is used). Userinfo +(user ID and password), path, querystring, and fragment details in the +URL will be ignored.
      • +
      • options <Object> +
          +
        • maxDeflateDynamicTableSize <number> Sets the maximum dynamic table size +for deflating header fields. Default: 4Kib.
        • +
        • maxSettings <number> Sets the maximum number of settings entries per +SETTINGS frame. The minimum value allowed is 1. Default: 32.
        • +
        • maxSessionMemory<number> Sets the maximum memory that the Http2Session +is permitted to use. The value is expressed in terms of number of megabytes, +e.g. 1 equal 1 megabyte. The minimum value allowed is 1. +This is a credit based limit, existing Http2Streams may cause this +limit to be exceeded, but new Http2Stream instances will be rejected +while this limit is exceeded. The current number of Http2Stream sessions, +the current memory use of the header compression tables, current data +queued to be sent, and unacknowledged PING and SETTINGS frames are all +counted towards the current limit. Default: 10.
        • +
        • maxHeaderListPairs <number> Sets the maximum number of header entries. +This is similar to http.Server#maxHeadersCount or +http.ClientRequest#maxHeadersCount. The minimum value is 1. +Default: 128.
        • +
        • maxOutstandingPings <number> Sets the maximum number of outstanding, +unacknowledged pings. Default: 10.
        • +
        • maxReservedRemoteStreams <number> Sets the maximum number of reserved push +streams the client will accept at any given time. Once the current number of +currently reserved push streams exceeds reaches this limit, new push streams +sent by the server will be automatically rejected. The minimum allowed value +is 0. The maximum allowed value is 232-1. A negative value sets +this option to the maximum allowed value. Default: 200.
        • +
        • maxSendHeaderBlockLength <number> Sets the maximum allowed size for a +serialized, compressed block of headers. Attempts to send headers that +exceed this limit will result in a 'frameError' event being emitted +and the stream being closed and destroyed.
        • +
        • paddingStrategy <number> Strategy used for determining the amount of +padding to use for HEADERS and DATA frames. Default: +http2.constants.PADDING_STRATEGY_NONE. Value may be one of: +
            +
          • http2.constants.PADDING_STRATEGY_NONE: Specifies that no padding is +to be applied.
          • +
          • http2.constants.PADDING_STRATEGY_MAX: Specifies that the maximum +amount of padding, as determined by the internal implementation, is to +be applied.
          • +
          • http2.constants.PADDING_STRATEGY_CALLBACK: Specifies that the user +provided options.selectPadding() callback is to be used to determine +the amount of padding.
          • +
          • http2.constants.PADDING_STRATEGY_ALIGNED: Will attempt to apply +enough padding to ensure that the total frame length, including the +9-byte header, is a multiple of 8. For each frame, however, there is a +maximum allowed number of padding bytes that is determined by current +flow control state and settings. If this maximum is less than the +calculated amount needed to ensure alignment, the maximum will be used +and the total frame length will not necessarily be aligned at 8 bytes.
          • +
          +
        • +
        • peerMaxConcurrentStreams <number> Sets the maximum number of concurrent +streams for the remote peer as if a SETTINGS frame had been received. Will +be overridden if the remote peer sets its own value for +maxConcurrentStreams. Default: 100.
        • +
        • selectPadding <Function> When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, provides the callback function +used to determine the padding. See Using options.selectPadding().
        • +
        • protocol <string> The protocol to connect with, if not set in the +authority. Value may be either 'http:' or 'https:'. Default: +'https:'
        • +
        • settings <HTTP/2 Settings Object> The initial settings to send to the +remote peer upon connection.
        • +
        • createConnection <Function> An optional callback that receives the URL +instance passed to connect and the options object, and returns any +Duplex stream that is to be used as the connection for this session.
        • +
        • ...: Any net.connect() or tls.connect() options can be provided.
        • +
        • unknownProtocolTimeout <number> Specifies a timeout in milliseconds that +a server should wait when an 'unknownProtocol' event is emitted. If +the socket has not been destroyed by that time the server will destroy it. +Default: 10000.
        • +
        +
      • +
      • listener <Function> Will be registered as a one-time listener of the +'connect' event.
      • +
      • Returns: <ClientHttp2Session>
      • +
      +

      Returns a ClientHttp2Session instance.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://localhost:1234');
      +
      +/* Use the client */
      +
      +client.close();
      +

      http2.constants#

      + +

      Error codes for RST_STREAM and GOAWAY#

      +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ValueNameConstant
      0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
      0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
      0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
      0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
      0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
      0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
      0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
      0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
      0x08Cancelhttp2.constants.NGHTTP2_CANCEL
      0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
      0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
      0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
      0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
      0x0dHTTP/1.1 Requiredhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED
      +

      The 'timeout' event is emitted when there is no activity on the Server for +a given number of milliseconds set using http2server.setTimeout().

      +

      http2.getDefaultSettings()#

      + + +

      Returns an object containing the default settings for an Http2Session +instance. This method returns a new object instance every time it is called +so instances returned may be safely modified for use.

      +

      http2.getPackedSettings([settings])#

      + + +

      Returns a Buffer instance containing serialized representation of the given +HTTP/2 settings as specified in the HTTP/2 specification. This is intended +for use with the HTTP2-Settings header field.

      +
      const http2 = require('http2');
      +
      +const packed = http2.getPackedSettings({ enablePush: false });
      +
      +console.log(packed.toString('base64'));
      +// Prints: AAIAAAAA
      +

      http2.getUnpackedSettings(buf)#

      + + +

      Returns a HTTP/2 Settings Object containing the deserialized settings from +the given Buffer as generated by http2.getPackedSettings().

      +

      Headers object#

      +

      Headers are represented as own-properties on JavaScript objects. The property +keys will be serialized to lower-case. Property values should be strings (if +they are not they will be coerced to strings) or an Array of strings (in order +to send more than one value per header field).

      +
      const headers = {
      +  ':status': '200',
      +  'content-type': 'text-plain',
      +  'ABC': ['has', 'more', 'than', 'one', 'value']
      +};
      +
      +stream.respond(headers);
      +

      Header objects passed to callback functions will have a null prototype. This +means that normal JavaScript object methods such as +Object.prototype.toString() and Object.prototype.hasOwnProperty() will +not work.

      +

      For incoming headers:

      +
        +
      • The :status header is converted to number.
      • +
      • Duplicates of :status, :method, :authority, :scheme, :path, +:protocol, age, authorization, access-control-allow-credentials, +access-control-max-age, access-control-request-method, content-encoding, +content-language, content-length, content-location, content-md5, +content-range, content-type, date, dnt, etag, expires, from, +if-match, if-modified-since, if-none-match, if-range, +if-unmodified-since, last-modified, location, max-forwards, +proxy-authorization, range, referer,retry-after, tk, +upgrade-insecure-requests, user-agent or x-content-type-options are +discarded.
      • +
      • set-cookie is always an array. Duplicates are added to the array.
      • +
      • For duplicate cookie headers, the values are joined together with '; '.
      • +
      • For all other headers, the values are joined together with ', '.
      • +
      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream, headers) => {
      +  console.log(headers[':path']);
      +  console.log(headers.ABC);
      +});
      +

      Settings object#

      + +

      The http2.getDefaultSettings(), http2.getPackedSettings(), +http2.createServer(), http2.createSecureServer(), +http2session.settings(), http2session.localSettings, and +http2session.remoteSettings APIs either return or receive as input an +object that defines configuration settings for an Http2Session object. +These objects are ordinary JavaScript objects containing the following +properties.

      +
        +
      • headerTableSize <number> Specifies the maximum number of bytes used for +header compression. The minimum allowed value is 0. The maximum allowed value +is 232-1. Default: 4096.
      • +
      • enablePush <boolean> Specifies true if HTTP/2 Push Streams are to be +permitted on the Http2Session instances. Default: true.
      • +
      • initialWindowSize <number> Specifies the sender's initial window size in +bytes for stream-level flow control. The minimum allowed value is 0. The +maximum allowed value is 232-1. Default: 65535.
      • +
      • maxFrameSize <number> Specifies the size in bytes of the largest frame +payload. The minimum allowed value is 16,384. The maximum allowed value is +224-1. Default: 16384.
      • +
      • maxConcurrentStreams <number> Specifies the maximum number of concurrent +streams permitted on an Http2Session. There is no default value which +implies, at least theoretically, 232-1 streams may be open +concurrently at any given time in an Http2Session. The minimum value +is 0. The maximum allowed value is 232-1. Default: +4294967295.
      • +
      • maxHeaderListSize <number> Specifies the maximum size (uncompressed octets) +of header list that will be accepted. The minimum allowed value is 0. The +maximum allowed value is 232-1. Default: 65535.
      • +
      • maxHeaderSize <number> Alias for maxHeaderListSize.
      • +
      • enableConnectProtocol<boolean> Specifies true if the "Extended Connect +Protocol" defined by RFC 8441 is to be enabled. This setting is only +meaningful if sent by the server. Once the enableConnectProtocol setting +has been enabled for a given Http2Session, it cannot be disabled. +Default: false.
      • +
      +

      All additional properties on the settings object are ignored.

      +

      Using options.selectPadding()#

      +

      When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, the HTTP/2 implementation will +consult the options.selectPadding() callback function, if provided, to +determine the specific amount of padding to use per HEADERS and DATA frame.

      +

      The options.selectPadding() function receives two numeric arguments, +frameLen and maxFrameLen and must return a number N such that +frameLen <= N <= maxFrameLen.

      +
      const http2 = require('http2');
      +const server = http2.createServer({
      +  paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK,
      +  selectPadding(frameLen, maxFrameLen) {
      +    return maxFrameLen;
      +  }
      +});
      +

      The options.selectPadding() function is invoked once for every HEADERS and +DATA frame. This has a definite noticeable impact on performance.

      +

      Error handling#

      +

      There are several types of error conditions that may arise when using the +http2 module:

      +

      Validation errors occur when an incorrect argument, option, or setting value is +passed in. These will always be reported by a synchronous throw.

      +

      State errors occur when an action is attempted at an incorrect time (for +instance, attempting to send data on a stream after it has closed). These will +be reported using either a synchronous throw or via an 'error' event on +the Http2Stream, Http2Session or HTTP/2 Server objects, depending on where +and when the error occurs.

      +

      Internal errors occur when an HTTP/2 session fails unexpectedly. These will be +reported via an 'error' event on the Http2Session or HTTP/2 Server objects.

      +

      Protocol errors occur when various HTTP/2 protocol constraints are violated. +These will be reported using either a synchronous throw or via an 'error' +event on the Http2Stream, Http2Session or HTTP/2 Server objects, depending +on where and when the error occurs.

      +

      Invalid character handling in header names and values#

      +

      The HTTP/2 implementation applies stricter handling of invalid characters in +HTTP header names and values than the HTTP/1 implementation.

      +

      Header field names are case-insensitive and are transmitted over the wire +strictly as lower-case strings. The API provided by Node.js allows header +names to be set as mixed-case strings (e.g. Content-Type) but will convert +those to lower-case (e.g. content-type) upon transmission.

      +

      Header field-names must only contain one or more of the following ASCII +characters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +, +-, ., ^, _, ` (backtick), |, and ~.

      +

      Using invalid characters within an HTTP header field name will cause the +stream to be closed with a protocol error being reported.

      +

      Header field values are handled with more leniency but should not contain +new-line or carriage return characters and should be limited to US-ASCII +characters, per the requirements of the HTTP specification.

      +

      Push streams on the client#

      +

      To receive pushed streams on the client, set a listener for the 'stream' +event on the ClientHttp2Session:

      +
      const http2 = require('http2');
      +
      +const client = http2.connect('http://localhost');
      +
      +client.on('stream', (pushedStream, requestHeaders) => {
      +  pushedStream.on('push', (responseHeaders) => {
      +    // Process response headers
      +  });
      +  pushedStream.on('data', (chunk) => { /* handle pushed data */ });
      +});
      +
      +const req = client.request({ ':path': '/' });
      +

      Supporting the CONNECT method#

      +

      The CONNECT method is used to allow an HTTP/2 server to be used as a proxy +for TCP/IP connections.

      +

      A simple TCP Server:

      +
      const net = require('net');
      +
      +const server = net.createServer((socket) => {
      +  let name = '';
      +  socket.setEncoding('utf8');
      +  socket.on('data', (chunk) => name += chunk);
      +  socket.on('end', () => socket.end(`hello ${name}`));
      +});
      +
      +server.listen(8000);
      +

      An HTTP/2 CONNECT proxy:

      +
      const http2 = require('http2');
      +const { NGHTTP2_REFUSED_STREAM } = http2.constants;
      +const net = require('net');
      +
      +const proxy = http2.createServer();
      +proxy.on('stream', (stream, headers) => {
      +  if (headers[':method'] !== 'CONNECT') {
      +    // Only accept CONNECT requests
      +    stream.close(NGHTTP2_REFUSED_STREAM);
      +    return;
      +  }
      +  const auth = new URL(`tcp://${headers[':authority']}`);
      +  // It's a very good idea to verify that hostname and port are
      +  // things this proxy should be connecting to.
      +  const socket = net.connect(auth.port, auth.hostname, () => {
      +    stream.respond();
      +    socket.pipe(stream);
      +    stream.pipe(socket);
      +  });
      +  socket.on('error', (error) => {
      +    stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);
      +  });
      +});
      +
      +proxy.listen(8001);
      +

      An HTTP/2 CONNECT client:

      +
      const http2 = require('http2');
      +
      +const client = http2.connect('http://localhost:8001');
      +
      +// Must not specify the ':path' and ':scheme' headers
      +// for CONNECT requests or an error will be thrown.
      +const req = client.request({
      +  ':method': 'CONNECT',
      +  ':authority': `localhost:${port}`
      +});
      +
      +req.on('response', (headers) => {
      +  console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);
      +});
      +let data = '';
      +req.setEncoding('utf8');
      +req.on('data', (chunk) => data += chunk);
      +req.on('end', () => {
      +  console.log(`The server says: ${data}`);
      +  client.close();
      +});
      +req.end('Jane');
      +

      The extended CONNECT protocol#

      +

      RFC 8441 defines an "Extended CONNECT Protocol" extension to HTTP/2 that +may be used to bootstrap the use of an Http2Stream using the CONNECT +method as a tunnel for other communication protocols (such as WebSockets).

      +

      The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using +the enableConnectProtocol setting:

      +
      const http2 = require('http2');
      +const settings = { enableConnectProtocol: true };
      +const server = http2.createServer({ settings });
      +

      Once the client receives the SETTINGS frame from the server indicating that +the extended CONNECT may be used, it may send CONNECT requests that use the +':protocol' HTTP/2 pseudo-header:

      +
      const http2 = require('http2');
      +const client = http2.connect('http://localhost:8080');
      +client.on('remoteSettings', (settings) => {
      +  if (settings.enableConnectProtocol) {
      +    const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });
      +    // ...
      +  }
      +});
      +

      Compatibility API#

      +

      The Compatibility API has the goal of providing a similar developer experience +of HTTP/1 when using HTTP/2, making it possible to develop applications +that support both HTTP/1 and HTTP/2. This API targets only the +public API of the HTTP/1. However many modules use internal +methods or state, and those are not supported as it is a completely +different implementation.

      +

      The following example creates an HTTP/2 server using the compatibility +API:

      +
      const http2 = require('http2');
      +const server = http2.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      +  res.end('ok');
      +});
      +

      In order to create a mixed HTTPS and HTTP/2 server, refer to the +ALPN negotiation section. +Upgrading from non-tls HTTP/1 servers is not supported.

      +

      The HTTP/2 compatibility API is composed of Http2ServerRequest and +Http2ServerResponse. They aim at API compatibility with HTTP/1, but +they do not hide the differences between the protocols. As an example, +the status message for HTTP codes is ignored.

      +

      ALPN negotiation#

      +

      ALPN negotiation allows supporting both HTTPS and HTTP/2 over +the same socket. The req and res objects can be either HTTP/1 or +HTTP/2, and an application must restrict itself to the public API of +HTTP/1, and detect if it is possible to use the more advanced +features of HTTP/2.

      +

      The following example creates a server that supports both protocols:

      +
      const { createSecureServer } = require('http2');
      +const { readFileSync } = require('fs');
      +
      +const cert = readFileSync('./cert.pem');
      +const key = readFileSync('./key.pem');
      +
      +const server = createSecureServer(
      +  { cert, key, allowHTTP1: true },
      +  onRequest
      +).listen(4443);
      +
      +function onRequest(req, res) {
      +  // Detects if it is a HTTPS request or HTTP/2
      +  const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?
      +    req.stream.session : req;
      +  res.writeHead(200, { 'content-type': 'application/json' });
      +  res.end(JSON.stringify({
      +    alpnProtocol,
      +    httpVersion: req.httpVersion
      +  }));
      +}
      +

      The 'request' event works identically on both HTTPS and +HTTP/2.

      +

      Class: http2.Http2ServerRequest#

      + + +

      A Http2ServerRequest object is created by http2.Server or +http2.SecureServer and passed as the first argument to the +'request' event. It may be used to access a request status, headers, and +data.

      +

      Event: 'aborted'#

      + +

      The 'aborted' event is emitted whenever a Http2ServerRequest instance is +abnormally aborted in mid-communication.

      +

      The 'aborted' event will only be emitted if the Http2ServerRequest writable +side has not been ended.

      +

      Event: 'close'#

      + +

      Indicates that the underlying Http2Stream was closed. +Just like 'end', this event occurs only once per response.

      +

      request.aborted#

      + + +

      The request.aborted property will be true if the request has +been aborted.

      +

      request.authority#

      + + +

      The request authority pseudo header field. It can also be accessed via +req.headers[':authority'].

      +

      request.complete#

      + + +

      The request.complete property will be true if the request has +been completed, aborted, or destroyed.

      +

      request.destroy([error])#

      + + +

      Calls destroy() on the Http2Stream that received +the Http2ServerRequest. If error is provided, an 'error' event +is emitted and error is passed as an argument to any listeners on the event.

      +

      It does nothing if the stream was already destroyed.

      +

      request.headers#

      + + +

      The request/response headers object.

      +

      Key-value pairs of header names and values. Header names are lower-cased.

      +
      // Prints something like:
      +//
      +// { 'user-agent': 'curl/7.22.0',
      +//   host: '127.0.0.1:8000',
      +//   accept: '*/*' }
      +console.log(request.headers);
      +

      See HTTP/2 Headers Object.

      +

      In HTTP/2, the request path, host name, protocol, and method are represented as +special headers prefixed with the : character (e.g. ':path'). These special +headers will be included in the request.headers object. Care must be taken not +to inadvertently modify these special headers or errors may occur. For instance, +removing all headers from the request will cause errors to occur:

      +
      removeAllHeaders(request.headers);
      +assert(request.url);   // Fails because the :path header has been removed
      +

      request.httpVersion#

      + + +

      In case of server request, the HTTP version sent by the client. In the case of +client response, the HTTP version of the connected-to server. Returns +'2.0'.

      +

      Also message.httpVersionMajor is the first integer and +message.httpVersionMinor is the second.

      +

      request.method#

      + + +

      The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

      +

      request.rawHeaders#

      + + +

      The raw request/response headers list exactly as they were received.

      +

      The keys and values are in the same list. It is not a +list of tuples. So, the even-numbered offsets are key values, and the +odd-numbered offsets are the associated values.

      +

      Header names are not lowercased, and duplicates are not merged.

      +
      // Prints something like:
      +//
      +// [ 'user-agent',
      +//   'this is invalid because there can be only one',
      +//   'User-Agent',
      +//   'curl/7.22.0',
      +//   'Host',
      +//   '127.0.0.1:8000',
      +//   'ACCEPT',
      +//   '*/*' ]
      +console.log(request.rawHeaders);
      +

      request.rawTrailers#

      + + +

      The raw request/response trailer keys and values exactly as they were +received. Only populated at the 'end' event.

      +

      request.scheme#

      + + +

      The request scheme pseudo header field indicating the scheme +portion of the target URL.

      +

      request.setTimeout(msecs, callback)#

      + + +

      Sets the Http2Stream's timeout value to msecs. If a callback is +provided, then it is added as a listener on the 'timeout' event on +the response object.

      +

      If no 'timeout' listener is added to the request, the response, or +the server, then Http2Streams are destroyed when they time out. If a +handler is assigned to the request, the response, or the server's 'timeout' +events, timed out sockets must be handled explicitly.

      +

      request.socket#

      + + +

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but +applies getters, setters, and methods based on HTTP/2 logic.

      +

      destroyed, readable, and writable properties will be retrieved from and +set on request.stream.

      +

      destroy, emit, end, on and once methods will be called on +request.stream.

      +

      setTimeout method will be called on request.stream.session.

      +

      pause, read, resume, and write will throw an error with code +ERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for +more information.

      +

      All other interactions will be routed directly to the socket. With TLS support, +use request.socket.getPeerCertificate() to obtain the client's +authentication details.

      +

      request.stream#

      + + +

      The Http2Stream object backing the request.

      +

      request.trailers#

      + + +

      The request/response trailers object. Only populated at the 'end' event.

      +

      request.url#

      + + +

      Request URL string. This contains only the URL that is present in the actual +HTTP request. If the request is:

      +
      GET /status?name=ryan HTTP/1.1
      +Accept: text/plain
      +

      Then request.url will be:

      + +
      '/status?name=ryan'
      +

      To parse the url into its parts, require('url').parse(request.url) +can be used:

      +
      $ node
      +> require('url').parse('/status?name=ryan')
      +Url {
      +  protocol: null,
      +  slashes: null,
      +  auth: null,
      +  host: null,
      +  port: null,
      +  hostname: null,
      +  hash: null,
      +  search: '?name=ryan',
      +  query: 'name=ryan',
      +  pathname: '/status',
      +  path: '/status?name=ryan',
      +  href: '/status?name=ryan' }
      +

      To obtain the parameters from the query string, use the +require('querystring').parse() function or pass +true as the second argument to require('url').parse().

      +
      $ node
      +> require('url').parse('/status?name=ryan', true)
      +Url {
      +  protocol: null,
      +  slashes: null,
      +  auth: null,
      +  host: null,
      +  port: null,
      +  hostname: null,
      +  hash: null,
      +  search: '?name=ryan',
      +  query: { name: 'ryan' },
      +  pathname: '/status',
      +  path: '/status?name=ryan',
      +  href: '/status?name=ryan' }
      +

      Class: http2.Http2ServerResponse#

      + + +

      This object is created internally by an HTTP server, not by the user. It is +passed as the second parameter to the 'request' event.

      +

      Event: 'close'#

      + +

      Indicates that the underlying Http2Stream was terminated before +response.end() was called or able to flush.

      +

      Event: 'finish'#

      + +

      Emitted when the response has been sent. More specifically, this event is +emitted when the last segment of the response headers and body have been +handed off to the HTTP/2 multiplexing for transmission over the network. It +does not imply that the client has received anything yet.

      +

      After this event, no more events will be emitted on the response object.

      +

      response.addTrailers(headers)#

      + + +

      This method adds HTTP trailing headers (a header but at the end of the +message) to the response.

      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.connection#

      + + +

      See response.socket.

      +

      response.end([data[, encoding]][, callback])#

      + + +

      This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, response.end(), MUST be called on each response.

      +

      If data is specified, it is equivalent to calling +response.write(data, encoding) followed by response.end(callback).

      +

      If callback is specified, it will be called when the response stream +is finished.

      +

      response.finished#

      + +

      + +

      Boolean value that indicates whether the response has completed. Starts +as false. After response.end() executes, the value will be true.

      +

      response.getHeader(name)#

      + + +

      Reads out a header that has already been queued but not sent to the client. +The name is case-insensitive.

      +
      const contentType = response.getHeader('content-type');
      +

      response.getHeaderNames()#

      + + +

      Returns an array containing the unique names of the current outgoing headers. +All header names are lowercase.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headerNames = response.getHeaderNames();
      +// headerNames === ['foo', 'set-cookie']
      +

      response.getHeaders()#

      + + +

      Returns a shallow copy of the current outgoing headers. Since a shallow copy +is used, array values may be mutated without additional calls to various +header-related http module methods. The keys of the returned object are the +header names and the values are the respective header values. All header names +are lowercase.

      +

      The object returned by the response.getHeaders() method does not +prototypically inherit from the JavaScript Object. This means that typical +Object methods such as obj.toString(), obj.hasOwnProperty(), and others +are not defined and will not work.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headers = response.getHeaders();
      +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      +

      response.hasHeader(name)#

      + + +

      Returns true if the header identified by name is currently set in the +outgoing headers. The header name matching is case-insensitive.

      +
      const hasContentType = response.hasHeader('content-type');
      +

      response.headersSent#

      + + +

      True if headers were sent, false otherwise (read-only).

      +

      response.removeHeader(name)#

      + + +

      Removes a header that has been queued for implicit sending.

      +
      response.removeHeader('Content-Encoding');
      +

      response.sendDate#

      + + +

      When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true.

      +

      This should only be disabled for testing; HTTP requires the Date header +in responses.

      +

      response.setHeader(name, value)#

      + + +

      Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name.

      +
      response.setHeader('Content-Type', 'text/html; charset=utf-8');
      +

      or

      +
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +
      // Returns content-type = text/plain
      +const server = http2.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html; charset=utf-8');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      +  res.end('ok');
      +});
      +

      response.setTimeout(msecs[, callback])#

      + + +

      Sets the Http2Stream's timeout value to msecs. If a callback is +provided, then it is added as a listener on the 'timeout' event on +the response object.

      +

      If no 'timeout' listener is added to the request, the response, or +the server, then Http2Streams are destroyed when they time out. If a +handler is assigned to the request, the response, or the server's 'timeout' +events, timed out sockets must be handled explicitly.

      +

      response.socket#

      + + +

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but +applies getters, setters, and methods based on HTTP/2 logic.

      +

      destroyed, readable, and writable properties will be retrieved from and +set on response.stream.

      +

      destroy, emit, end, on and once methods will be called on +response.stream.

      +

      setTimeout method will be called on response.stream.session.

      +

      pause, read, resume, and write will throw an error with code +ERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for +more information.

      +

      All other interactions will be routed directly to the socket.

      +
      const http2 = require('http2');
      +const server = http2.createServer((req, res) => {
      +  const ip = req.socket.remoteAddress;
      +  const port = req.socket.remotePort;
      +  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
      +}).listen(3000);
      +

      response.statusCode#

      + + +

      When using implicit headers (not calling response.writeHead() explicitly), +this property controls the status code that will be sent to the client when +the headers get flushed.

      +
      response.statusCode = 404;
      +

      After response header was sent to the client, this property indicates the +status code which was sent out.

      +

      response.statusMessage#

      + + +

      Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns +an empty string.

      +

      response.stream#

      + + +

      The Http2Stream object backing the response.

      +

      response.writableEnded#

      + + +

      Is true after response.end() has been called. This property +does not indicate whether the data has been flushed, for this use +writable.writableFinished instead.

      +

      response.write(chunk[, encoding][, callback])#

      + + +

      If this method is called and response.writeHead() has not been called, +it will switch to implicit header mode and flush the implicit headers.

      +

      This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body.

      +

      In the http module, the response body is omitted when the +request is a HEAD request. Similarly, the 204 and 304 responses +must not include a message body.

      +

      chunk can be a string or a buffer. If chunk is a string, +the second parameter specifies how to encode it into a byte stream. +By default the encoding is 'utf8'. callback will be called when this chunk +of data is flushed.

      +

      This is the raw HTTP body and has nothing to do with higher-level multi-part +body encodings that may be used.

      +

      The first time response.write() is called, it will send the buffered +header information and the first chunk of the body to the client. The second +time response.write() is called, Node.js assumes data will be streamed, +and sends the new data separately. That is, the response is buffered up to the +first chunk of the body.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is free again.

      +

      response.writeContinue()#

      + +

      Sends a status 100 Continue to the client, indicating that the request body +should be sent. See the 'checkContinue' event on Http2Server and +Http2SecureServer.

      +

      response.writeHead(statusCode[, statusMessage][, headers])#

      + + +

      Sends a response header to the request. The status code is a 3-digit HTTP +status code, like 404. The last argument, headers, are the response headers.

      +

      Returns a reference to the Http2ServerResponse, so that calls can be chained.

      +

      For compatibility with HTTP/1, a human-readable statusMessage may be +passed as the second argument. However, because the statusMessage has no +meaning within HTTP/2, the argument will have no effect and a process warning +will be emitted.

      +
      const body = 'hello world';
      +response.writeHead(200, {
      +  'Content-Length': Buffer.byteLength(body),
      +  'Content-Type': 'text/plain; charset=utf-8' });
      +

      Content-Length is given in bytes not characters. The +Buffer.byteLength() API may be used to determine the number of bytes in a +given encoding. On outbound messages, Node.js does not check if Content-Length +and the length of the body being transmitted are equal or not. However, when +receiving messages, Node.js will automatically reject messages when the +Content-Length does not match the actual payload size.

      +

      This method may be called at most one time on a message before +response.end() is called.

      +

      If response.write() or response.end() are called before calling +this, the implicit/mutable headers will be calculated and call this function.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +
      // Returns content-type = text/plain
      +const server = http2.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html; charset=utf-8');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      +  res.end('ok');
      +});
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.createPushResponse(headers, callback)#

      + +
        +
      • headers <HTTP/2 Headers Object> An object describing the headers
      • +
      • callback <Function> Called once http2stream.pushStream() is finished, +or either when the attempt to create the pushed Http2Stream has failed or +has been rejected, or the state of Http2ServerRequest is closed prior to +calling the http2stream.pushStream() method + +
      • +
      +

      Call http2stream.pushStream() with the given headers, and wrap the +given Http2Stream on a newly created Http2ServerResponse as the callback +parameter if successful. When Http2ServerRequest is closed, the callback is +called with an error ERR_HTTP2_INVALID_STREAM.

      +

      Collecting HTTP/2 performance metrics#

      +

      The Performance Observer API can be used to collect basic performance +metrics for each Http2Session and Http2Stream instance.

      +
      const { PerformanceObserver } = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((items) => {
      +  const entry = items.getEntries()[0];
      +  console.log(entry.entryType);  // prints 'http2'
      +  if (entry.name === 'Http2Session') {
      +    // Entry contains statistics about the Http2Session
      +  } else if (entry.name === 'Http2Stream') {
      +    // Entry contains statistics about the Http2Stream
      +  }
      +});
      +obs.observe({ entryTypes: ['http2'] });
      +

      The entryType property of the PerformanceEntry will be equal to 'http2'.

      +

      The name property of the PerformanceEntry will be equal to either +'Http2Stream' or 'Http2Session'.

      +

      If name is equal to Http2Stream, the PerformanceEntry will contain the +following additional properties:

      +
        +
      • bytesRead <number> The number of DATA frame bytes received for this +Http2Stream.
      • +
      • bytesWritten <number> The number of DATA frame bytes sent for this +Http2Stream.
      • +
      • id <number> The identifier of the associated Http2Stream
      • +
      • timeToFirstByte <number> The number of milliseconds elapsed between the +PerformanceEntry startTime and the reception of the first DATA frame.
      • +
      • timeToFirstByteSent <number> The number of milliseconds elapsed between +the PerformanceEntry startTime and sending of the first DATA frame.
      • +
      • timeToFirstHeader <number> The number of milliseconds elapsed between the +PerformanceEntry startTime and the reception of the first header.
      • +
      +

      If name is equal to Http2Session, the PerformanceEntry will contain the +following additional properties:

      +
        +
      • bytesRead <number> The number of bytes received for this Http2Session.
      • +
      • bytesWritten <number> The number of bytes sent for this Http2Session.
      • +
      • framesReceived <number> The number of HTTP/2 frames received by the +Http2Session.
      • +
      • framesSent <number> The number of HTTP/2 frames sent by the Http2Session.
      • +
      • maxConcurrentStreams <number> The maximum number of streams concurrently +open during the lifetime of the Http2Session.
      • +
      • pingRTT <number> The number of milliseconds elapsed since the transmission +of a PING frame and the reception of its acknowledgment. Only present if +a PING frame has been sent on the Http2Session.
      • +
      • streamAverageDuration <number> The average duration (in milliseconds) for +all Http2Stream instances.
      • +
      • streamCount <number> The number of Http2Stream instances processed by +the Http2Session.
      • +
      • type <string> Either 'server' or 'client' to identify the type of +Http2Session.
      • +
      +

      HTTPS#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/https.js

      +

      HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a +separate module.

      +

      Class: https.Agent#

      + +

      An Agent object for HTTPS similar to http.Agent. See +https.request() for more information.

      +

      new Agent([options])#

      + +
        +
      • +

        options <Object> Set of configurable options to set on the agent. +Can have the same fields as for http.Agent(options), and

        +
          +
        • +

          maxCachedSessions <number> maximum number of TLS cached sessions. +Use 0 to disable TLS session caching. Default: 100.

          +
        • +
        • +

          servername <string> the value of +Server Name Indication extension to be sent to the server. Use +empty string '' to disable sending the extension. +Default: host name of the target server, unless the target server +is specified using an IP address, in which case the default is '' (no +extension).

          +

          See Session Resumption for information about TLS session reuse.

          +
        • +
        +
      • +
      +

      Event: 'keylog'#

      + +
        +
      • line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.
      • +
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance on which it was +generated.
      • +
      +

      The keylog event is emitted when key material is generated or received by a +connection managed by this agent (typically before handshake has completed, but +not necessarily). This keying material can be stored for debugging, as it +allows captured TLS traffic to be decrypted. It may be emitted multiple times +for each socket.

      +

      A typical use case is to append received lines to a common text file, which is +later used by software (such as Wireshark) to decrypt the traffic:

      +
      // ...
      +https.globalAgent.on('keylog', (line, tlsSocket) => {
      +  fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });
      +});
      +

      Class: https.Server#

      + + +

      See http.Server for more information.

      +

      server.close([callback])#

      + + +

      See server.close() from the HTTP module for details.

      +

      server.headersTimeout#

      + + +

      See http.Server#headersTimeout.

      +

      server.listen()#

      +

      Starts the HTTPS server listening for encrypted connections. +This method is identical to server.listen() from net.Server.

      +

      server.maxHeadersCount#

      + +

      See http.Server#maxHeadersCount.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      See http.Server#setTimeout().

      +

      server.timeout#

      + +
        +
      • <number> Default: 120000 (2 minutes)
      • +
      +

      See http.Server#timeout.

      +

      server.keepAliveTimeout#

      + + +

      See http.Server#keepAliveTimeout.

      +

      https.createServer([options][, requestListener])#

      + + +
      // curl -k https://localhost:8000/
      +const https = require('https');
      +const fs = require('fs');
      +
      +const options = {
      +  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      +  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
      +};
      +
      +https.createServer(options, (req, res) => {
      +  res.writeHead(200);
      +  res.end('hello world\n');
      +}).listen(8000);
      +

      Or

      +
      const https = require('https');
      +const fs = require('fs');
      +
      +const options = {
      +  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
      +  passphrase: 'sample'
      +};
      +
      +https.createServer(options, (req, res) => {
      +  res.writeHead(200);
      +  res.end('hello world\n');
      +}).listen(8000);
      +

      https.get(options[, callback])#

      +

      https.get(url[, options][, callback])#

      + + +

      Like http.get() but for HTTPS.

      +

      options can be an object, a string, or a URL object. If options is a +string, it is automatically parsed with new URL(). If it is a URL +object, it will be automatically converted to an ordinary options object.

      +
      const https = require('https');
      +
      +https.get('https://encrypted.google.com/', (res) => {
      +  console.log('statusCode:', res.statusCode);
      +  console.log('headers:', res.headers);
      +
      +  res.on('data', (d) => {
      +    process.stdout.write(d);
      +  });
      +
      +}).on('error', (e) => {
      +  console.error(e);
      +});
      +

      https.globalAgent#

      + +

      Global instance of https.Agent for all HTTPS client requests.

      +

      https.request(options[, callback])#

      +

      https.request(url[, options][, callback])#

      + + +

      Makes a request to a secure web server.

      +

      The following additional options from tls.connect() are also accepted: +ca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve, +honorCipherOrder, key, passphrase, pfx, rejectUnauthorized, +secureOptions, secureProtocol, servername, sessionIdContext.

      +

      options can be an object, a string, or a URL object. If options is a +string, it is automatically parsed with new URL(). If it is a URL +object, it will be automatically converted to an ordinary options object.

      +
      const https = require('https');
      +
      +const options = {
      +  hostname: 'encrypted.google.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET'
      +};
      +
      +const req = https.request(options, (res) => {
      +  console.log('statusCode:', res.statusCode);
      +  console.log('headers:', res.headers);
      +
      +  res.on('data', (d) => {
      +    process.stdout.write(d);
      +  });
      +});
      +
      +req.on('error', (e) => {
      +  console.error(e);
      +});
      +req.end();
      +

      Example using options from tls.connect():

      +
      const options = {
      +  hostname: 'encrypted.google.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET',
      +  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      +  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
      +};
      +options.agent = new https.Agent(options);
      +
      +const req = https.request(options, (res) => {
      +  // ...
      +});
      +

      Alternatively, opt out of connection pooling by not using an Agent.

      +
      const options = {
      +  hostname: 'encrypted.google.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET',
      +  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      +  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
      +  agent: false
      +};
      +
      +const req = https.request(options, (res) => {
      +  // ...
      +});
      +

      Example using a URL as options:

      +
      const options = new URL('https://abc:xyz@example.com');
      +
      +const req = https.request(options, (res) => {
      +  // ...
      +});
      +

      Example pinning on certificate fingerprint, or the public key (similar to +pin-sha256):

      +
      const tls = require('tls');
      +const https = require('https');
      +const crypto = require('crypto');
      +
      +function sha256(s) {
      +  return crypto.createHash('sha256').update(s).digest('base64');
      +}
      +const options = {
      +  hostname: 'github.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET',
      +  checkServerIdentity: function(host, cert) {
      +    // Make sure the certificate is issued to the host we are connected to
      +    const err = tls.checkServerIdentity(host, cert);
      +    if (err) {
      +      return err;
      +    }
      +
      +    // Pin the public key, similar to HPKP pin-sha25 pinning
      +    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
      +    if (sha256(cert.pubkey) !== pubkey256) {
      +      const msg = 'Certificate verification error: ' +
      +        `The public key of '${cert.subject.CN}' ` +
      +        'does not match our pinned fingerprint';
      +      return new Error(msg);
      +    }
      +
      +    // Pin the exact certificate, rather than the pub key
      +    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
      +      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
      +    if (cert.fingerprint256 !== cert256) {
      +      const msg = 'Certificate verification error: ' +
      +        `The certificate of '${cert.subject.CN}' ` +
      +        'does not match our pinned fingerprint';
      +      return new Error(msg);
      +    }
      +
      +    // This loop is informational only.
      +    // Print the certificate and public key fingerprints of all certs in the
      +    // chain. Its common to pin the public key of the issuer on the public
      +    // internet, while pinning the public key of the service in sensitive
      +    // environments.
      +    do {
      +      console.log('Subject Common Name:', cert.subject.CN);
      +      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);
      +
      +      hash = crypto.createHash('sha256');
      +      console.log('  Public key ping-sha256:', sha256(cert.pubkey));
      +
      +      lastprint256 = cert.fingerprint256;
      +      cert = cert.issuerCertificate;
      +    } while (cert.fingerprint256 !== lastprint256);
      +
      +  },
      +};
      +
      +options.agent = new https.Agent(options);
      +const req = https.request(options, (res) => {
      +  console.log('All OK. Server matched our pinned cert or public key');
      +  console.log('statusCode:', res.statusCode);
      +  // Print the HPKP values
      +  console.log('headers:', res.headers['public-key-pins']);
      +
      +  res.on('data', (d) => {});
      +});
      +
      +req.on('error', (e) => {
      +  console.error(e.message);
      +});
      +req.end();
      +

      Outputs for example:

      +
      Subject Common Name: github.com
      +  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
      +  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
      +Subject Common Name: DigiCert SHA2 Extended Validation Server CA
      +  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
      +  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
      +Subject Common Name: DigiCert High Assurance EV Root CA
      +  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
      +  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
      +All OK. Server matched our pinned cert or public key
      +statusCode: 200
      +headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
      +

      Inspector#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/inspector.js

      +

      The inspector module provides an API for interacting with the V8 inspector.

      +

      It can be accessed using:

      +
      const inspector = require('inspector');
      +

      inspector.close()#

      +

      Deactivate the inspector. Blocks until there are no active connections.

      +

      inspector.console#

      +
        +
      • <Object> An object to send messages to the remote inspector console.
      • +
      +
      require('inspector').console.log('a message');
      +

      The inspector console does not have API parity with Node.js +console.

      +

      inspector.open([port[, host[, wait]]])#

      +
        +
      • port <number> Port to listen on for inspector connections. Optional. +Default: what was specified on the CLI.
      • +
      • host <string> Host to listen on for inspector connections. Optional. +Default: what was specified on the CLI.
      • +
      • wait <boolean> Block until a client has connected. Optional. +Default: false.
      • +
      +

      Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programmatically after node has +started.

      +

      If wait is true, will block until a client has connected to the inspect port +and flow control has been passed to the debugger client.

      +

      See the security warning regarding the host +parameter usage.

      +

      inspector.url()#

      + +

      Return the URL of the active inspector, or undefined if there is none.

      +
      $ node --inspect -p 'inspector.url()'
      +Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
      +For help see https://nodejs.org/en/docs/inspector
      +ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
      +
      +$ node --inspect=localhost:3000 -p 'inspector.url()'
      +Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
      +For help see https://nodejs.org/en/docs/inspector
      +ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
      +
      +$ node -p 'inspector.url()'
      +undefined
      +

      inspector.waitForDebugger()#

      + +

      Blocks until a client (existing or connected later) has sent +Runtime.runIfWaitingForDebugger command.

      +

      An exception will be thrown if there is no active inspector.

      +

      Class: inspector.Session#

      + +

      The inspector.Session is used for dispatching messages to the V8 inspector +back-end and receiving message responses and notifications.

      +

      new inspector.Session()#

      + +

      Create a new instance of the inspector.Session class. The inspector session +needs to be connected through session.connect() before the messages +can be dispatched to the inspector backend.

      +

      Event: 'inspectorNotification'#

      + +
        +
      • <Object> The notification message object
      • +
      +

      Emitted when any notification from the V8 Inspector is received.

      +
      session.on('inspectorNotification', (message) => console.log(message.method));
      +// Debugger.paused
      +// Debugger.resumed
      +

      It is also possible to subscribe only to notifications with specific method:

      +

      Event: <inspector-protocol-method>;#

      + +
        +
      • <Object> The notification message object
      • +
      +

      Emitted when an inspector notification is received that has its method field set +to the <inspector-protocol-method> value.

      +

      The following snippet installs a listener on the 'Debugger.paused' +event, and prints the reason for program suspension whenever program +execution is suspended (through breakpoints, for example):

      +
      session.on('Debugger.paused', ({ params }) => {
      +  console.log(params.hitBreakpoints);
      +});
      +// [ '/the/file/that/has/the/breakpoint.js:11:0' ]
      +

      session.connect()#

      + +

      Connects a session to the inspector back-end.

      +

      session.connectToMainThread()#

      + +

      Connects a session to the main thread inspector back-end. An exception will +be thrown if this API was not called on a Worker thread.

      +

      session.disconnect()#

      + +

      Immediately close the session. All pending message callbacks will be called +with an error. session.connect() will need to be called to be able to send +messages again. Reconnected session will lose all inspector state, such as +enabled agents or configured breakpoints.

      +

      session.post(method[, params][, callback])#

      + + +

      Posts a message to the inspector back-end. callback will be notified when +a response is received. callback is a function that accepts two optional +arguments: error and message-specific result.

      +
      session.post('Runtime.evaluate', { expression: '2 + 2' },
      +             (error, { result }) => console.log(result));
      +// Output: { type: 'number', value: 4, description: '4' }
      +

      The latest version of the V8 inspector protocol is published on the +Chrome DevTools Protocol Viewer.

      +

      Node.js inspector supports all the Chrome DevTools Protocol domains declared +by V8. Chrome DevTools Protocol domain provides an interface for interacting +with one of the runtime agents used to inspect the application state and listen +to the run-time events.

      +

      Example usage#

      +

      Apart from the debugger, various V8 Profilers are available through the DevTools +protocol.

      +

      CPU profiler#

      +

      Here's an example showing how to use the CPU Profiler:

      +
      const inspector = require('inspector');
      +const fs = require('fs');
      +const session = new inspector.Session();
      +session.connect();
      +
      +session.post('Profiler.enable', () => {
      +  session.post('Profiler.start', () => {
      +    // Invoke business logic under measurement here...
      +
      +    // some time later...
      +    session.post('Profiler.stop', (err, { profile }) => {
      +      // Write profile to disk, upload, etc.
      +      if (!err) {
      +        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
      +      }
      +    });
      +  });
      +});
      +

      Heap profiler#

      +

      Here's an example showing how to use the Heap Profiler:

      +
      const inspector = require('inspector');
      +const fs = require('fs');
      +const session = new inspector.Session();
      +
      +const fd = fs.openSync('profile.heapsnapshot', 'w');
      +
      +session.connect();
      +
      +session.on('HeapProfiler.addHeapSnapshotChunk', (m) => {
      +  fs.writeSync(fd, m.params.chunk);
      +});
      +
      +session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
      +  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);
      +  session.disconnect();
      +  fs.closeSync(fd);
      +});
      +

      Internationalization support#

      + + +

      Node.js has many features that make it easier to write internationalized +programs. Some of them are:

      + +

      Node.js (and its underlying V8 engine) uses ICU to implement these features +in native C/C++ code. However, some of them require a very large ICU data file +in order to support all locales of the world. Because it is expected that most +Node.js users will make use of only a small portion of ICU functionality, only +a subset of the full ICU data set is provided by Node.js by default. Several +options are provided for customizing and expanding the ICU data set either when +building or running Node.js.

      +

      Options for building Node.js#

      +

      To control how ICU is used in Node.js, four configure options are available +during compilation. Additional details on how to compile Node.js are documented +in BUILDING.md.

      +
        +
      • --with-intl=none/--without-intl
      • +
      • --with-intl=system-icu
      • +
      • --with-intl=small-icu (default)
      • +
      • --with-intl=full-icu
      • +
      +

      An overview of available Node.js and JavaScript features for each configure +option:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      nonesystem-icusmall-icufull-icu
      String.prototype.normalize()none (function is no-op)fullfullfull
      String.prototype.to*Case()fullfullfullfull
      Intlnone (object does not exist)partial/full (depends on OS)partial (English-only)full
      String.prototype.localeCompare()partial (not locale-aware)fullfullfull
      String.prototype.toLocale*Case()partial (not locale-aware)fullfullfull
      Number.prototype.toLocaleString()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      Date.prototype.toLocale*String()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      WHATWG URL Parserpartial (no IDN support)fullfullfull
      require('buffer').transcode()none (function does not exist)fullfullfull
      REPLpartial (inaccurate line editing)fullfullfull
      require('util').TextDecoderpartial (basic encodings support)partial/full (depends on OS)partial (Unicode-only)full
      RegExp Unicode Property Escapesnone (invalid RegExp error)fullfullfull
      +

      The "(not locale-aware)" designation denotes that the function carries out its +operation just like the non-Locale version of the function, if one +exists. For example, under none mode, Date.prototype.toLocaleString()'s +operation is identical to that of Date.prototype.toString().

      +

      Disable all internationalization features (none)#

      +

      If this option is chosen, most internationalization features mentioned above +will be unavailable in the resulting node binary.

      +

      Build with a pre-installed ICU (system-icu)#

      +

      Node.js can link against an ICU build already installed on the system. In fact, +most Linux distributions already come with ICU installed, and this option would +make it possible to reuse the same set of data used by other components in the +OS.

      +

      Functionalities that only require the ICU library itself, such as +String.prototype.normalize() and the WHATWG URL parser, are fully +supported under system-icu. Features that require ICU locale data in +addition, such as Intl.DateTimeFormat may be fully or partially +supported, depending on the completeness of the ICU data installed on the +system.

      +

      Embed a limited set of ICU data (small-icu)#

      +

      This option makes the resulting binary link against the ICU library statically, +and includes a subset of ICU data (typically only the English locale) within +the node executable.

      +

      Functionalities that only require the ICU library itself, such as +String.prototype.normalize() and the WHATWG URL parser, are fully +supported under small-icu. Features that require ICU locale data in addition, +such as Intl.DateTimeFormat, generally only work with the English locale:

      +
      const january = new Date(9e8);
      +const english = new Intl.DateTimeFormat('en', { month: 'long' });
      +const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
      +
      +console.log(english.format(january));
      +// Prints "January"
      +console.log(spanish.format(january));
      +// Prints "M01" on small-icu
      +// Should print "enero"
      +

      This mode provides a good balance between features and binary size, and it is +the default behavior if no --with-intl flag is passed. The official binaries +are also built in this mode.

      +

      Providing ICU data at runtime#

      +

      If the small-icu option is used, one can still provide additional locale data +at runtime so that the JS methods would work for all ICU locales. Assuming the +data file is stored at /some/directory, it can be made available to ICU +through either:

      +
        +
      • +

        The NODE_ICU_DATA environment variable:

        +
        env NODE_ICU_DATA=/some/directory node
        +
      • +
      • +

        The --icu-data-dir CLI parameter:

        +
        node --icu-data-dir=/some/directory
        +
      • +
      +

      (If both are specified, the --icu-data-dir CLI parameter takes precedence.)

      +

      ICU is able to automatically find and load a variety of data formats, but the +data must be appropriate for the ICU version, and the file correctly named. +The most common name for the data file is icudt6X[bl].dat, where 6X denotes +the intended ICU version, and b or l indicates the system's endianness. +Check "ICU Data" article in the ICU User Guide for other supported formats +and more details on ICU data in general.

      +

      The full-icu npm module can greatly simplify ICU data installation by +detecting the ICU version of the running node executable and downloading the +appropriate data file. After installing the module through npm i full-icu, +the data file will be available at ./node_modules/full-icu. This path can be +then passed either to NODE_ICU_DATA or --icu-data-dir as shown above to +enable full Intl support.

      +

      Embed the entire ICU (full-icu)#

      +

      This option makes the resulting binary link against ICU statically and include +a full set of ICU data. A binary created this way has no further external +dependencies and supports all locales, but might be rather large. See +BUILDING.md on how to compile a binary using this mode.

      +

      Detecting internationalization support#

      +

      To verify that ICU is enabled at all (system-icu, small-icu, or +full-icu), simply checking the existence of Intl should suffice:

      +
      const hasICU = typeof Intl === 'object';
      +

      Alternatively, checking for process.versions.icu, a property defined only +when ICU is enabled, works too:

      +
      const hasICU = typeof process.versions.icu === 'string';
      +

      To check for support for a non-English locale (i.e. full-icu or +system-icu), Intl.DateTimeFormat can be a good distinguishing factor:

      +
      const hasFullICU = (() => {
      +  try {
      +    const january = new Date(9e8);
      +    const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
      +    return spanish.format(january) === 'enero';
      +  } catch (err) {
      +    return false;
      +  }
      +})();
      +

      For more verbose tests for Intl support, the following resources may be found +to be helpful:

      +
        +
      • btest402: Generally used to check whether Node.js with Intl support is +built correctly.
      • +
      • Test262: ECMAScript's official conformance test suite includes a section +dedicated to ECMA-402.
      • +
      +

      Modules: CommonJS modules#

      + +

      Stability: 2 - Stable

      + +

      In the Node.js module system, each file is treated as a separate module. For +example, consider a file named foo.js:

      +
      const circle = require('./circle.js');
      +console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
      +

      On the first line, foo.js loads the module circle.js that is in the same +directory as foo.js.

      +

      Here are the contents of circle.js:

      +
      const { PI } = Math;
      +
      +exports.area = (r) => PI * r ** 2;
      +
      +exports.circumference = (r) => 2 * PI * r;
      +

      The module circle.js has exported the functions area() and +circumference(). Functions and objects are added to the root of a module +by specifying additional properties on the special exports object.

      +

      Variables local to the module will be private, because the module is wrapped +in a function by Node.js (see module wrapper). +In this example, the variable PI is private to circle.js.

      +

      The module.exports property can be assigned a new value (such as a function +or object).

      +

      Below, bar.js makes use of the square module, which exports a Square class:

      +
      const Square = require('./square.js');
      +const mySquare = new Square(2);
      +console.log(`The area of mySquare is ${mySquare.area()}`);
      +

      The square module is defined in square.js:

      +
      // Assigning to exports will not modify module, must use module.exports
      +module.exports = class Square {
      +  constructor(width) {
      +    this.width = width;
      +  }
      +
      +  area() {
      +    return this.width ** 2;
      +  }
      +};
      +

      The module system is implemented in the require('module') module.

      +

      Accessing the main module#

      + +

      When a file is run directly from Node.js, require.main is set to its +module. That means that it is possible to determine whether a file has been +run directly by testing require.main === module.

      +

      For a file foo.js, this will be true if run via node foo.js, but +false if run by require('./foo').

      +

      Because module provides a filename property (normally equivalent to +__filename), the entry point of the current application can be obtained +by checking require.main.filename.

      +

      Addenda: Package manager tips#

      + +

      The semantics of the Node.js require() function were designed to be general +enough to support reasonable directory structures. Package manager programs +such as dpkg, rpm, and npm will hopefully find it possible to build +native packages from Node.js modules without modification.

      +

      Below we give a suggested directory structure that could work:

      +

      Let's say that we wanted to have the folder at +/usr/lib/node/<some-package>/<some-version> hold the contents of a +specific version of a package.

      +

      Packages can depend on one another. In order to install package foo, it +may be necessary to install a specific version of package bar. The bar +package may itself have dependencies, and in some cases, these may even collide +or form cyclic dependencies.

      +

      Because Node.js looks up the realpath of any modules it loads (that is, it +resolves symlinks) and then looks for their dependencies in node_modules folders, +this situation can be resolved with the following architecture:

      +
        +
      • /usr/lib/node/foo/1.2.3/: Contents of the foo package, version 1.2.3.
      • +
      • /usr/lib/node/bar/4.3.2/: Contents of the bar package that foo depends +on.
      • +
      • /usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to +/usr/lib/node/bar/4.3.2/.
      • +
      • /usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages that +bar depends on.
      • +
      +

      Thus, even if a cycle is encountered, or if there are dependency +conflicts, every module will be able to get a version of its dependency +that it can use.

      +

      When the code in the foo package does require('bar'), it will get the +version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. +Then, when the code in the bar package calls require('quux'), it'll get +the version that is symlinked into +/usr/lib/node/bar/4.3.2/node_modules/quux.

      +

      Furthermore, to make the module lookup process even more optimal, rather +than putting packages directly in /usr/lib/node, we could put them in +/usr/lib/node_modules/<name>/<version>. Then Node.js will not bother +looking for missing dependencies in /usr/node_modules or /node_modules.

      +

      In order to make modules available to the Node.js REPL, it might be useful to +also add the /usr/lib/node_modules folder to the $NODE_PATH environment +variable. Since the module lookups using node_modules folders are all +relative, and based on the real path of the files making the calls to +require(), the packages themselves can be anywhere.

      +

      Addenda: The .mjs extension#

      +

      It is not possible to require() files that have the .mjs extension. +Attempting to do so will throw an error. The .mjs extension is +reserved for ECMAScript Modules which cannot be loaded via require(). +See ECMAScript Modules for more details.

      +

      All together...#

      + +

      To get the exact filename that will be loaded when require() is called, use +the require.resolve() function.

      +

      Putting together all of the above, here is the high-level algorithm +in pseudocode of what require() does:

      +
      require(X) from module at path Y
      +1. If X is a core module,
      +   a. return the core module
      +   b. STOP
      +2. If X begins with '/'
      +   a. set Y to be the filesystem root
      +3. If X begins with './' or '/' or '../'
      +   a. LOAD_AS_FILE(Y + X)
      +   b. LOAD_AS_DIRECTORY(Y + X)
      +   c. THROW "not found"
      +4. If X begins with '#'
      +   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
      +5. LOAD_PACKAGE_SELF(X, dirname(Y))
      +6. LOAD_NODE_MODULES(X, dirname(Y))
      +7. THROW "not found"
      +
      +LOAD_AS_FILE(X)
      +1. If X is a file, load X as its file extension format. STOP
      +2. If X.js is a file, load X.js as JavaScript text. STOP
      +3. If X.json is a file, parse X.json to a JavaScript Object. STOP
      +4. If X.node is a file, load X.node as binary addon. STOP
      +
      +LOAD_INDEX(X)
      +1. If X/index.js is a file, load X/index.js as JavaScript text. STOP
      +2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
      +3. If X/index.node is a file, load X/index.node as binary addon. STOP
      +
      +LOAD_AS_DIRECTORY(X)
      +1. If X/package.json is a file,
      +   a. Parse X/package.json, and look for "main" field.
      +   b. If "main" is a falsy value, GOTO 2.
      +   c. let M = X + (json main field)
      +   d. LOAD_AS_FILE(M)
      +   e. LOAD_INDEX(M)
      +   f. LOAD_INDEX(X) DEPRECATED
      +   g. THROW "not found"
      +2. LOAD_INDEX(X)
      +
      +LOAD_NODE_MODULES(X, START)
      +1. let DIRS = NODE_MODULES_PATHS(START)
      +2. for each DIR in DIRS:
      +   a. LOAD_PACKAGE_EXPORTS(X, DIR)
      +   b. LOAD_AS_FILE(DIR/X)
      +   c. LOAD_AS_DIRECTORY(DIR/X)
      +
      +NODE_MODULES_PATHS(START)
      +1. let PARTS = path split(START)
      +2. let I = count of PARTS - 1
      +3. let DIRS = [GLOBAL_FOLDERS]
      +4. while I >= 0,
      +   a. if PARTS[I] = "node_modules" CONTINUE
      +   b. DIR = path join(PARTS[0 .. I] + "node_modules")
      +   c. DIRS = DIRS + DIR
      +   d. let I = I - 1
      +5. return DIRS
      +
      +LOAD_PACKAGE_IMPORTS(X, DIR)
      +1. Find the closest package scope SCOPE to DIR.
      +2. If no scope was found, return.
      +3. If the SCOPE/package.json "imports" is null or undefined, return.
      +4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
      +  ["node", "require"]) defined in the ESM resolver.
      +5. RESOLVE_ESM_MATCH(MATCH).
      +
      +LOAD_PACKAGE_EXPORTS(X, DIR)
      +1. Try to interpret X as a combination of NAME and SUBPATH where the name
      +   may have a @scope/ prefix and the subpath begins with a slash (`/`).
      +2. If X does not match this pattern or DIR/NAME/package.json is not a file,
      +   return.
      +3. Parse DIR/NAME/package.json, and look for "exports" field.
      +4. If "exports" is null or undefined, return.
      +5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
      +   `package.json` "exports", ["node", "require"]) defined in the ESM resolver.
      +6. RESOLVE_ESM_MATCH(MATCH)
      +
      +LOAD_PACKAGE_SELF(X, DIR)
      +1. Find the closest package scope SCOPE to DIR.
      +2. If no scope was found, return.
      +3. If the SCOPE/package.json "exports" is null or undefined, return.
      +4. If the SCOPE/package.json "name" is not the first segment of X, return.
      +5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
      +   "." + X.slice("name".length), `package.json` "exports", ["node", "require"])
      +   defined in the ESM resolver.
      +6. RESOLVE_ESM_MATCH(MATCH)
      +
      +RESOLVE_ESM_MATCH(MATCH)
      +1. let { RESOLVED, EXACT } = MATCH
      +2. let RESOLVED_PATH = fileURLToPath(RESOLVED)
      +3. If EXACT is true,
      +   a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
      +      format. STOP
      +4. Otherwise, if EXACT is false,
      +   a. LOAD_AS_FILE(RESOLVED_PATH)
      +   b. LOAD_AS_DIRECTORY(RESOLVED_PATH)
      +5. THROW "not found"
      +

      Caching#

      + +

      Modules are cached after the first time they are loaded. This means (among other +things) that every call to require('foo') will get exactly the same object +returned, if it would resolve to the same file.

      +

      Provided require.cache is not modified, multiple calls to require('foo') +will not cause the module code to be executed multiple times. This is an +important feature. With it, "partially done" objects can be returned, thus +allowing transitive dependencies to be loaded even when they would cause cycles.

      +

      To have a module execute code multiple times, export a function, and call that +function.

      +

      Module caching caveats#

      + +

      Modules are cached based on their resolved filename. Since modules may resolve +to a different filename based on the location of the calling module (loading +from node_modules folders), it is not a guarantee that require('foo') will +always return the exact same object, if it would resolve to different files.

      +

      Additionally, on case-insensitive file systems or operating systems, different +resolved filenames can point to the same file, but the cache will still treat +them as different modules and will reload the file multiple times. For example, +require('./foo') and require('./FOO') return two different objects, +irrespective of whether or not ./foo and ./FOO are the same file.

      +

      Core modules#

      + +

      Node.js has several modules compiled into the binary. These modules are +described in greater detail elsewhere in this documentation.

      +

      The core modules are defined within the Node.js source and are located in the +lib/ folder.

      +

      Core modules are always preferentially loaded if their identifier is +passed to require(). For instance, require('http') will always +return the built in HTTP module, even if there is a file by that name.

      +

      Cycles#

      + +

      When there are circular require() calls, a module might not have finished +executing when it is returned.

      +

      Consider this situation:

      +

      a.js:

      +
      console.log('a starting');
      +exports.done = false;
      +const b = require('./b.js');
      +console.log('in a, b.done = %j', b.done);
      +exports.done = true;
      +console.log('a done');
      +

      b.js:

      +
      console.log('b starting');
      +exports.done = false;
      +const a = require('./a.js');
      +console.log('in b, a.done = %j', a.done);
      +exports.done = true;
      +console.log('b done');
      +

      main.js:

      +
      console.log('main starting');
      +const a = require('./a.js');
      +const b = require('./b.js');
      +console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
      +

      When main.js loads a.js, then a.js in turn loads b.js. At that +point, b.js tries to load a.js. In order to prevent an infinite +loop, an unfinished copy of the a.js exports object is returned to the +b.js module. b.js then finishes loading, and its exports object is +provided to the a.js module.

      +

      By the time main.js has loaded both modules, they're both finished. +The output of this program would thus be:

      +
      $ node main.js
      +main starting
      +a starting
      +b starting
      +in b, a.done = false
      +b done
      +in a, b.done = true
      +a done
      +in main, a.done = true, b.done = true
      +

      Careful planning is required to allow cyclic module dependencies to work +correctly within an application.

      +

      File modules#

      + +

      If the exact filename is not found, then Node.js will attempt to load the +required filename with the added extensions: .js, .json, and finally +.node.

      +

      .js files are interpreted as JavaScript text files, and .json files are +parsed as JSON text files. .node files are interpreted as compiled addon +modules loaded with process.dlopen().

      +

      A required module prefixed with '/' is an absolute path to the file. For +example, require('/home/marco/foo.js') will load the file at +/home/marco/foo.js.

      +

      A required module prefixed with './' is relative to the file calling +require(). That is, circle.js must be in the same directory as foo.js for +require('./circle') to find it.

      +

      Without a leading '/', './', or '../' to indicate a file, the module must +either be a core module or is loaded from a node_modules folder.

      +

      If the given path does not exist, require() will throw an Error with its +code property set to 'MODULE_NOT_FOUND'.

      +

      Folders as modules#

      + +

      It is convenient to organize programs and libraries into self-contained +directories, and then provide a single entry point to those directories. +There are three ways in which a folder may be passed to require() as +an argument.

      +

      The first is to create a package.json file in the root of the folder, +which specifies a main module. An example package.json file might +look like this:

      +
      { "name" : "some-library",
      +  "main" : "./lib/some-library.js" }
      +

      If this was in a folder at ./some-library, then +require('./some-library') would attempt to load +./some-library/lib/some-library.js.

      +

      This is the extent of the awareness of package.json files within Node.js.

      +

      If there is no package.json file present in the directory, or if the +"main" entry is missing or cannot be resolved, then Node.js +will attempt to load an index.js or index.node file out of that +directory. For example, if there was no package.json file in the previous +example, then require('./some-library') would attempt to load:

      +
        +
      • ./some-library/index.js
      • +
      • ./some-library/index.node
      • +
      +

      If these attempts fail, then Node.js will report the entire module as missing +with the default error:

      +
      Error: Cannot find module 'some-library'
      +

      Loading from node_modules folders#

      + +

      If the module identifier passed to require() is not a +core module, and does not begin with '/', '../', or +'./', then Node.js starts at the parent directory of the current module, and +adds /node_modules, and attempts to load the module from that location. +Node.js will not append node_modules to a path already ending in +node_modules.

      +

      If it is not found there, then it moves to the parent directory, and so +on, until the root of the file system is reached.

      +

      For example, if the file at '/home/ry/projects/foo.js' called +require('bar.js'), then Node.js would look in the following locations, in +this order:

      +
        +
      • /home/ry/projects/node_modules/bar.js
      • +
      • /home/ry/node_modules/bar.js
      • +
      • /home/node_modules/bar.js
      • +
      • /node_modules/bar.js
      • +
      +

      This allows programs to localize their dependencies, so that they do not +clash.

      +

      It is possible to require specific files or sub modules distributed with a +module by including a path suffix after the module name. For instance +require('example-module/path/to/file') would resolve path/to/file +relative to where example-module is located. The suffixed path follows the +same module resolution semantics.

      +

      Loading from the global folders#

      + +

      If the NODE_PATH environment variable is set to a colon-delimited list +of absolute paths, then Node.js will search those paths for modules if they +are not found elsewhere.

      +

      On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

      +

      NODE_PATH was originally created to support loading modules from +varying paths before the current module resolution algorithm was defined.

      +

      NODE_PATH is still supported, but is less necessary now that the Node.js +ecosystem has settled on a convention for locating dependent modules. +Sometimes deployments that rely on NODE_PATH show surprising behavior +when people are unaware that NODE_PATH must be set. Sometimes a +module's dependencies change, causing a different version (or even a +different module) to be loaded as the NODE_PATH is searched.

      +

      Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

      +
        +
      • 1: $HOME/.node_modules
      • +
      • 2: $HOME/.node_libraries
      • +
      • 3: $PREFIX/lib/node
      • +
      +

      Where $HOME is the user's home directory, and $PREFIX is the Node.js +configured node_prefix.

      +

      These are mostly for historic reasons.

      +

      It is strongly encouraged to place dependencies in the local node_modules +folder. These will be loaded faster, and more reliably.

      +

      The module wrapper#

      + +

      Before a module's code is executed, Node.js will wrap it with a function +wrapper that looks like the following:

      +
      (function(exports, require, module, __filename, __dirname) {
      +// Module code actually lives in here
      +});
      +

      By doing this, Node.js achieves a few things:

      +
        +
      • It keeps top-level variables (defined with var, const or let) scoped to +the module rather than the global object.
      • +
      • It helps to provide some global-looking variables that are actually specific +to the module, such as: +
          +
        • The module and exports objects that the implementor can use to export +values from the module.
        • +
        • The convenience variables __filename and __dirname, containing the +module's absolute filename and directory path.
        • +
        +
      • +
      +

      The module scope#

      +

      __dirname#

      + + + +

      The directory name of the current module. This is the same as the +path.dirname() of the __filename.

      +

      Example: running node example.js from /Users/mjr

      +
      console.log(__dirname);
      +// Prints: /Users/mjr
      +console.log(path.dirname(__filename));
      +// Prints: /Users/mjr
      +

      __filename#

      + + + +

      The file name of the current module. This is the current module file's absolute +path with symlinks resolved.

      +

      For a main program this is not necessarily the same as the file name used in the +command line.

      +

      See __dirname for the directory name of the current module.

      +

      Examples:

      +

      Running node example.js from /Users/mjr

      +
      console.log(__filename);
      +// Prints: /Users/mjr/example.js
      +console.log(__dirname);
      +// Prints: /Users/mjr
      +

      Given two modules: a and b, where b is a dependency of +a and there is a directory structure of:

      +
        +
      • /Users/mjr/app/a.js
      • +
      • /Users/mjr/app/node_modules/b/b.js
      • +
      +

      References to __filename within b.js will return +/Users/mjr/app/node_modules/b/b.js while references to __filename within +a.js will return /Users/mjr/app/a.js.

      +

      exports#

      + + + +

      A reference to the module.exports that is shorter to type. +See the section about the exports shortcut for details on when to use +exports and when to use module.exports.

      +

      module#

      + + + +

      A reference to the current module, see the section about the +module object. In particular, module.exports is used for defining what +a module exports and makes available through require().

      +

      require(id)#

      + + +
        +
      • id <string> module name or path
      • +
      • Returns: <any> exported module content
      • +
      +

      Used to import modules, JSON, and local files. Modules can be imported +from node_modules. Local modules and JSON files can be imported using +a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be +resolved against the directory named by __dirname (if defined) or +the current working directory. The relative paths of POSIX style are resolved +in an OS independent fashion, meaning that the examples above will work on +Windows in the same way they would on Unix systems.

      +
      // Importing a local module with a path relative to the `__dirname` or current
      +// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
      +const myLocalModule = require('./path/myLocalModule');
      +
      +// Importing a JSON file:
      +const jsonData = require('./path/filename.json');
      +
      +// Importing a module from node_modules or Node.js built-in module:
      +const crypto = require('crypto');
      +

      require.cache#

      + + +

      Modules are cached in this object when they are required. By deleting a key +value from this object, the next require will reload the module. +This does not apply to native addons, for which reloading will result in an +error.

      +

      Adding or replacing entries is also possible. This cache is checked before +native modules and if a name matching a native module is added to the cache, +no require call is +going to receive the native module anymore. Use with care!

      +

      require.extensions#

      + +

      Stability: 0 - Deprecated

      + +

      Instruct require on how to handle certain file extensions.

      +

      Process files with the extension .sjs as .js:

      +
      require.extensions['.sjs'] = require.extensions['.js'];
      +

      Deprecated. In the past, this list has been used to load non-JavaScript +modules into Node.js by compiling them on-demand. However, in practice, there +are much better ways to do this, such as loading modules via some other Node.js +program, or compiling them to JavaScript ahead of time.

      +

      Avoid using require.extensions. Use could cause subtle bugs and resolving the +extensions gets slower with each registered extension.

      +

      require.main#

      + + +

      The Module object representing the entry script loaded when the Node.js +process launched. +See "Accessing the main module".

      +

      In entry.js script:

      +
      console.log(require.main);
      +
      node entry.js
      + +
      Module {
      +  id: '.',
      +  path: '/absolute/path/to',
      +  exports: {},
      +  parent: null,
      +  filename: '/absolute/path/to/entry.js',
      +  loaded: false,
      +  children: [],
      +  paths:
      +   [ '/absolute/path/to/node_modules',
      +     '/absolute/path/node_modules',
      +     '/absolute/node_modules',
      +     '/node_modules' ] }
      +

      require.resolve(request[, options])#

      + +
        +
      • request <string> The module path to resolve.
      • +
      • options <Object> +
          +
        • paths <string[]> Paths to resolve module location from. If present, these +paths are used instead of the default resolution paths, with the exception +of GLOBAL_FOLDERS like $HOME/.node_modules, which are always +included. Each of these paths is used as a starting point for +the module resolution algorithm, meaning that the node_modules hierarchy +is checked from this location.
        • +
        +
      • +
      • Returns: <string>
      • +
      +

      Use the internal require() machinery to look up the location of a module, +but rather than loading the module, just return the resolved filename.

      +

      If the module can not be found, a MODULE_NOT_FOUND error is thrown.

      +
      require.resolve.paths(request)#
      + + +

      Returns an array containing the paths searched during resolution of request or +null if the request string references a core module, for example http or +fs.

      +

      The module object#

      + + + + +

      In each module, the module free variable is a reference to the object +representing the current module. For convenience, module.exports is +also accessible via the exports module-global. module is not actually +a global but rather local to each module.

      +

      module.children#

      + + +

      The module objects required for the first time by this one.

      +

      module.exports#

      + + +

      The module.exports object is created by the Module system. Sometimes this is +not acceptable; many want their module to be an instance of some class. To do +this, assign the desired export object to module.exports. Assigning +the desired object to exports will simply rebind the local exports variable, +which is probably not what is desired.

      +

      For example, suppose we were making a module called a.js:

      +
      const EventEmitter = require('events');
      +
      +module.exports = new EventEmitter();
      +
      +// Do some work, and after some time emit
      +// the 'ready' event from the module itself.
      +setTimeout(() => {
      +  module.exports.emit('ready');
      +}, 1000);
      +

      Then in another file we could do:

      +
      const a = require('./a');
      +a.on('ready', () => {
      +  console.log('module "a" is ready');
      +});
      +

      Assignment to module.exports must be done immediately. It cannot be +done in any callbacks. This does not work:

      +

      x.js:

      +
      setTimeout(() => {
      +  module.exports = { a: 'hello' };
      +}, 0);
      +

      y.js:

      +
      const x = require('./x');
      +console.log(x.a);
      +

      exports shortcut#

      + +

      The exports variable is available within a module's file-level scope, and is +assigned the value of module.exports before the module is evaluated.

      +

      It allows a shortcut, so that module.exports.f = ... can be written more +succinctly as exports.f = .... However, be aware that like any variable, if a +new value is assigned to exports, it is no longer bound to module.exports:

      +
      module.exports.hello = true; // Exported from require of module
      +exports = { hello: false };  // Not exported, only available in the module
      +

      When the module.exports property is being completely replaced by a new +object, it is common to also reassign exports:

      + +
      module.exports = exports = function Constructor() {
      +  // ... etc.
      +};
      +

      To illustrate the behavior, imagine this hypothetical implementation of +require(), which is quite similar to what is actually done by require():

      +
      function require(/* ... */) {
      +  const module = { exports: {} };
      +  ((module, exports) => {
      +    // Module code here. In this example, define a function.
      +    function someFunc() {}
      +    exports = someFunc;
      +    // At this point, exports is no longer a shortcut to module.exports, and
      +    // this module will still export an empty default object.
      +    module.exports = someFunc;
      +    // At this point, the module will now export someFunc, instead of the
      +    // default object.
      +  })(module, module.exports);
      +  return module.exports;
      +}
      +

      module.filename#

      + + +

      The fully resolved filename of the module.

      +

      module.id#

      + + +

      The identifier for the module. Typically this is the fully resolved +filename.

      +

      module.loaded#

      + + +

      Whether or not the module is done loading, or is in the process of +loading.

      +

      module.parent#

      + +

      Stability: 0 - Deprecated: Please use require.main and +module.children instead.

      + +

      The module that first required this one, or null if the current module is the +entry point of the current process, or undefined if the module was loaded by +something that is not a CommonJS module (E.G.: REPL or import).

      +

      module.path#

      + + +

      The directory name of the module. This is usually the same as the +path.dirname() of the module.id.

      +

      module.paths#

      + + +

      The search paths for the module.

      +

      module.require(id)#

      + + +

      The module.require() method provides a way to load a module as if +require() was called from the original module.

      +

      In order to do this, it is necessary to get a reference to the module object. +Since require() returns the module.exports, and the module is typically +only available within a specific module's code, it must be explicitly exported +in order to be used.

      +

      The Module object#

      +

      This section was moved to +Modules: module core module.

      + + +

      Source map v3 support#

      +

      This section was moved to +Modules: module core module.

      + + +

      Modules: ECMAScript modules#

      + + + +

      Stability: 2 - Stable

      +

      Introduction#

      + +

      ECMAScript modules are the official standard format to package JavaScript +code for reuse. Modules are defined using a variety of import and +export statements.

      +

      The following example of an ES module exports a function:

      +
      // addTwo.mjs
      +function addTwo(num) {
      +  return num + 2;
      +}
      +
      +export { addTwo };
      +

      The following example of an ES module imports the function from addTwo.mjs:

      +
      // app.mjs
      +import { addTwo } from './addTwo.mjs';
      +
      +// Prints: 6
      +console.log(addTwo(4));
      +

      Node.js fully supports ECMAScript modules as they are currently specified and +provides interoperability between them and its original module format, +CommonJS.

      + +

      + +

      +

      Enabling#

      + +

      Node.js treats JavaScript code as CommonJS modules by default. +Authors can tell Node.js to treat JavaScript code as ECMAScript modules +via the .mjs file extension, the package.json "type" field, or the +--input-type flag. See +Modules: Packages for more +details.

      + +

      + + + + + + + + + + + + +

      +

      Packages#

      +

      This section was moved to Modules: Packages.

      +

      import Specifiers#

      +

      Terminology#

      +

      The specifier of an import statement is the string after the from keyword, +e.g. 'path' in import { sep } from 'path'. Specifiers are also used in +export from statements, and as the argument to an import() expression.

      +

      There are four types of specifiers:

      +
        +
      • +

        Bare specifiers like 'some-package'. They refer to an entry point of a +package by the package name.

        +
      • +
      • +

        Deep import specifiers like 'some-package/lib/shuffle.mjs'. They refer to +a path within a package prefixed by the package name.

        +
      • +
      • +

        Relative specifiers like './startup.js' or '../config.mjs'. They refer +to a path relative to the location of the importing file.

        +
      • +
      • +

        Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer +directly and explicitly to a full path.

        +
      • +
      +

      Bare specifiers, and the bare specifier portion of deep import specifiers, are +strings; but everything else in a specifier is a URL.

      +

      file:, node:, and data: URLs are supported. A specifier like +'https://example.com/app.js' may be supported by browsers but it is not +supported in Node.js.

      +

      Specifiers may not begin with / or //. These are reserved for potential +future use. The root of the current volume may be referenced via file:///.

      +

      node: Imports#

      + +

      node: URLs are supported as a means to load Node.js builtin modules. This +URL scheme allows for builtin modules to be referenced by valid absolute URL +strings.

      +
      import fs from 'node:fs/promises';
      +

      data: Imports#

      + +

      data: URLs are supported for importing with the following MIME types:

      +
        +
      • text/javascript for ES Modules
      • +
      • application/json for JSON
      • +
      • application/wasm for Wasm
      • +
      +

      data: URLs only resolve Bare specifiers for builtin modules +and Absolute specifiers. Resolving +Relative specifiers does not work because data: is not a +special scheme. For example, attempting to load ./foo +from data:text/javascript,import "./foo"; fails to resolve because there +is no concept of relative resolution for data: URLs. An example of a data: +URLs being used is:

      +
      import 'data:text/javascript,console.log("hello!");';
      +import _ from 'data:application/json,"world!"';
      +

      import.meta#

      + +

      The import.meta metaproperty is an Object that contains the following +property:

      +
        +
      • url <string> The absolute file: URL of the module.
      • +
      +

      Differences between ES modules and CommonJS#

      +

      Mandatory file extensions#

      +

      A file extension must be provided when using the import keyword. Directory +indexes (e.g. './startup/index.js') must also be fully specified.

      +

      This behavior matches how import behaves in browser environments, assuming a +typically configured server.

      +

      No NODE_PATH#

      +

      NODE_PATH is not part of resolving import specifiers. Please use symlinks +if this behavior is desired.

      +

      No require, exports, module.exports, __filename, __dirname#

      +

      These CommonJS variables are not available in ES modules.

      +

      require can be imported into an ES module using module.createRequire().

      +

      Equivalents of __filename and __dirname can be created inside of each file +via import.meta.url.

      +
      import { fileURLToPath } from 'url';
      +import { dirname } from 'path';
      +
      +const __filename = fileURLToPath(import.meta.url);
      +const __dirname = dirname(__filename);
      +

      No require.resolve#

      +

      Former use cases relying on require.resolve to determine the resolved path +of a module can be supported via import.meta.resolve, which is experimental +and supported via the --experimental-import-meta-resolve flag:

      +
      (async () => {
      +  const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
      +})();
      +

      import.meta.resolve also accepts a second argument which is the parent module +from which to resolve from:

      +
      (async () => {
      +  // Equivalent to import.meta.resolve('./dep')
      +  await import.meta.resolve('./dep', import.meta.url);
      +})();
      +

      This function is asynchronous because the ES module resolver in Node.js is +asynchronous. With the introduction of Top-Level Await, these use cases +will be easier as they won't require an async function wrapper.

      +

      No require.extensions#

      +

      require.extensions is not used by import. The expectation is that loader +hooks can provide this workflow in the future.

      +

      No require.cache#

      +

      require.cache is not used by import. It has a separate cache.

      +

      URL-based paths#

      +

      ES modules are resolved and cached based upon +URL semantics. This means that files containing +special characters such as # and ? need to be escaped.

      +

      Modules are loaded multiple times if the import specifier used to resolve +them has a different query or fragment.

      +
      import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1"
      +import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2"
      +

      For now, only modules using the file: protocol can be loaded.

      +

      Interoperability with CommonJS#

      +

      require#

      +

      require always treats the files it references as CommonJS. This applies +whether require is used the traditional way within a CommonJS environment, or +in an ES module environment using module.createRequire().

      +

      To include an ES module into CommonJS, use import().

      +

      import statements#

      +

      An import statement can reference an ES module or a CommonJS module. +import statements are permitted only in ES modules. For similar functionality +in CommonJS, see import().

      +

      When importing CommonJS modules, the +module.exports object is provided as the default export. Named exports may be +available, provided by static analysis as a convenience for better ecosystem +compatibility.

      +

      Additional experimental flags are available for importing +Wasm modules or +JSON modules. For importing native modules or +JSON modules unflagged, see module.createRequire().

      +

      The specifier of an import statement (the string after the from keyword) +can either be an URL-style relative path like './file.mjs' or a package name +like 'fs'.

      +

      Like in CommonJS, files within packages can be accessed by appending a path to +the package name; unless the package’s package.json contains an +"exports" field, in which case files within packages need to be accessed +via the path defined in "exports".

      +
      import { sin, cos } from 'geometry/trigonometry-functions.mjs';
      +

      import() expressions#

      +

      Dynamic import() is supported in both CommonJS and ES modules. It can be +used to include ES module files from CommonJS code.

      +

      CommonJS Namespaces#

      +

      CommonJS modules consist of a module.exports object which can be of any type.

      +

      When importing a CommonJS module, it can be reliably imported using the ES +module default import or its corresponding sugar syntax:

      + +
      import { default as cjs } from 'cjs';
      +
      +// The following import statement is "syntax sugar" (equivalent but sweeter)
      +// for `{ default as cjsSugar }` in the above import statement:
      +import cjsSugar from 'cjs';
      +
      +console.log(cjs);
      +console.log(cjs === cjsSugar);
      +// Prints:
      +//   <module.exports>
      +//   true
      +

      The ECMAScript Module Namespace representation of a CommonJS module is always +a namespace with a default export key pointing to the CommonJS +module.exports value.

      +

      This Module Namespace Exotic Object can be directly observed either when using +import * as m from 'cjs' or a dynamic import:

      + +
      import * as m from 'cjs';
      +console.log(m);
      +console.log(m === await import('cjs'));
      +// Prints:
      +//   [Module] { default: <module.exports> }
      +//   true
      +

      For better compatibility with existing usage in the JS ecosystem, Node.js +in addition attempts to determine the CommonJS named exports of every imported +CommonJS module to provide them as separate ES module exports using a static +analysis process.

      +

      For example, consider a CommonJS module written:

      +
      // cjs.cjs
      +exports.name = 'exported';
      +

      The preceding module supports named imports in ES modules:

      + +
      import { name } from './cjs.cjs';
      +console.log(name);
      +// Prints: 'exported'
      +
      +import cjs from './cjs.cjs';
      +console.log(cjs);
      +// Prints: { name: 'exported' }
      +
      +import * as m from './cjs.cjs';
      +console.log(m);
      +// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }
      +

      As can be seen from the last example of the Module Namespace Exotic Object being +logged, the name export is copied off of the module.exports object and set +directly on the ES module namespace when the module is imported.

      +

      Live binding updates or new exports added to module.exports are not detected +for these named exports.

      +

      The detection of named exports is based on common syntax patterns but does not +always correctly detect named exports. In these cases, using the default +import form described above can be a better option.

      +

      Named exports detection covers many common export patterns, reexport patterns +and build tool and transpiler outputs. See cjs-module-lexer for the exact +semantics implemented.

      +

      Builtin modules#

      +

      Core modules provide named exports of their public API. A +default export is also provided which is the value of the CommonJS exports. +The default export can be used for, among other things, modifying the named +exports. Named exports of builtin modules are updated only by calling +module.syncBuiltinESMExports().

      +
      import EventEmitter from 'events';
      +const e = new EventEmitter();
      +
      import { readFile } from 'fs';
      +readFile('./foo.txt', (err, source) => {
      +  if (err) {
      +    console.error(err);
      +  } else {
      +    console.log(source);
      +  }
      +});
      +
      import fs, { readFileSync } from 'fs';
      +import { syncBuiltinESMExports } from 'module';
      +
      +fs.readFileSync = () => Buffer.from('Hello, ESM');
      +syncBuiltinESMExports();
      +
      +fs.readFileSync === readFileSync;
      +

      CommonJS, JSON, and native modules#

      +

      CommonJS, JSON, and native modules can be used with +module.createRequire().

      +
      // cjs.cjs
      +module.exports = 'cjs';
      +
      +// esm.mjs
      +import { createRequire } from 'module';
      +
      +const require = createRequire(import.meta.url);
      +
      +const cjs = require('./cjs.cjs');
      +cjs === 'cjs'; // true
      +

      Experimental JSON modules#

      +

      Currently importing JSON modules are only supported in the commonjs mode +and are loaded using the CJS loader. WHATWG JSON modules specification are +still being standardized, and are experimentally supported by including the +additional flag --experimental-json-modules when running Node.js.

      +

      When the --experimental-json-modules flag is included, both the +commonjs and module mode use the new experimental JSON +loader. The imported JSON only exposes a default. There is no +support for named exports. A cache entry is created in the CommonJS +cache to avoid duplication. The same object is returned in +CommonJS if the JSON module has already been imported from the +same path.

      +

      Assuming an index.mjs with

      + +
      import packageConfig from './package.json';
      +

      The --experimental-json-modules flag is needed for the module +to work.

      +
      node index.mjs # fails
      +node --experimental-json-modules index.mjs # works
      +

      Experimental Wasm modules#

      +

      Importing Web Assembly modules is supported under the +--experimental-wasm-modules flag, allowing any .wasm files to be +imported as normal modules while also supporting their module imports.

      +

      This integration is in line with the +ES Module Integration Proposal for Web Assembly.

      +

      For example, an index.mjs containing:

      +
      import * as M from './module.wasm';
      +console.log(M);
      +

      executed under:

      +
      node --experimental-wasm-modules index.mjs
      +

      would provide the exports interface for the instantiation of module.wasm.

      +

      Experimental loaders#

      +

      Note: This API is currently being redesigned and will still change.

      + +

      To customize the default module resolution, loader hooks can optionally be +provided via a --experimental-loader ./loader-name.mjs argument to Node.js.

      +

      When hooks are used they only apply to ES module loading and not to any +CommonJS modules loaded.

      +

      Hooks#

      +

      resolve(specifier, context, defaultResolve)#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The resolve hook returns the resolved file URL for a given module specifier +and parent URL. The module specifier is the string in an import statement or +import() expression, and the parent URL is the URL of the module that imported +this one, or undefined if this is the main entry point for the application.

      +

      The conditions property on the context is an array of conditions for +Conditional exports that apply to this resolution request. They can be used +for looking up conditional mappings elsewhere or to modify the list when calling +the default resolution logic.

      +

      The current package exports conditions are always in +the context.conditions array passed into the hook. To guarantee default +Node.js module specifier resolution behavior when calling defaultResolve, the +context.conditions array passed to it must include all elements of the +context.conditions array originally passed into the resolve hook.

      +
      /**
      + * @param {string} specifier
      + * @param {{
      + *   conditions: !Array<string>,
      + *   parentURL: !(string | undefined),
      + * }} context
      + * @param {Function} defaultResolve
      + * @returns {Promise<{ url: string }>}
      + */
      +export async function resolve(specifier, context, defaultResolve) {
      +  const { parentURL = null } = context;
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all specifiers, do some custom logic for resolving.
      +    // Always return an object of the form {url: <string>}.
      +    return {
      +      url: parentURL ?
      +        new URL(specifier, parentURL).href :
      +        new URL(specifier).href,
      +    };
      +  }
      +  if (Math.random() < 0.5) { // Another condition.
      +    // When calling `defaultResolve`, the arguments can be modified. In this
      +    // case it's adding another value for matching conditional exports.
      +    return defaultResolve(specifier, {
      +      ...context,
      +      conditions: [...context.conditions, 'another-condition'],
      +    });
      +  }
      +  // Defer to Node.js for all other specifiers.
      +  return defaultResolve(specifier, context, defaultResolve);
      +}
      +

      getFormat(url, context, defaultGetFormat)#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The getFormat hook provides a way to define a custom method of determining how +a URL should be interpreted. The format returned also affects what the +acceptable forms of source values are for a module when parsing. This can be one +of the following:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      formatDescriptionAcceptable Types For source Returned by getSource or transformSource
      'builtin'Load a Node.js builtin moduleNot applicable
      'dynamic'Use a dynamic instantiate hookNot applicable
      'commonjs'Load a Node.js CommonJS moduleNot applicable
      'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
      'module'Load an ES module{ string, ArrayBuffer, TypedArray }
      'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
      +

      Note: These types all correspond to classes defined in ECMAScript.

      + +

      Note: If the source value of a text-based format (i.e., 'json', 'module') is +not a string, it is converted to a string using util.TextDecoder.

      +
      /**
      + * @param {string} url
      + * @param {Object} context (currently empty)
      + * @param {Function} defaultGetFormat
      + * @returns {Promise<{ format: string }>}
      + */
      +export async function getFormat(url, context, defaultGetFormat) {
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all URLs, do some custom logic for determining format.
      +    // Always return an object of the form {format: <string>}, where the
      +    // format is one of the strings in the preceding table.
      +    return {
      +      format: 'module',
      +    };
      +  }
      +  // Defer to Node.js for all other URLs.
      +  return defaultGetFormat(url, context, defaultGetFormat);
      +}
      +

      getSource(url, context, defaultGetSource)#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The getSource hook provides a way to define a custom method for retrieving +the source code of an ES module specifier. This would allow a loader to +potentially avoid reading files from disk.

      +
      /**
      + * @param {string} url
      + * @param {{ format: string }} context
      + * @param {Function} defaultGetSource
      + * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
      + */
      +export async function getSource(url, context, defaultGetSource) {
      +  const { format } = context;
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all URLs, do some custom logic for retrieving the source.
      +    // Always return an object of the form {source: <string|buffer>}.
      +    return {
      +      source: '...',
      +    };
      +  }
      +  // Defer to Node.js for all other URLs.
      +  return defaultGetSource(url, context, defaultGetSource);
      +}
      +

      transformSource(source, context, defaultTransformSource)#

      +
      NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js
      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The transformSource hook provides a way to modify the source code of a loaded +ES module file after the source string has been loaded but before Node.js has +done anything with it.

      +

      If this hook is used to convert unknown-to-Node.js file types into executable +JavaScript, a resolve hook is also necessary in order to register any +unknown-to-Node.js file extensions. See the transpiler loader example below.

      +
      /**
      + * @param {!(string | SharedArrayBuffer | Uint8Array)} source
      + * @param {{
      + *   format: string,
      + *   url: string,
      + * }} context
      + * @param {Function} defaultTransformSource
      + * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
      + */
      +export async function transformSource(source, context, defaultTransformSource) {
      +  const { url, format } = context;
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all URLs, do some custom logic for modifying the source.
      +    // Always return an object of the form {source: <string|buffer>}.
      +    return {
      +      source: '...',
      +    };
      +  }
      +  // Defer to Node.js for all other sources.
      +  return defaultTransformSource(source, context, defaultTransformSource);
      +}
      +

      getGlobalPreloadCode()#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      Sometimes it might be necessary to run some code inside of the same global scope +that the application runs in. This hook allows the return of a string that is +run as sloppy-mode script on startup.

      +

      Similar to how CommonJS wrappers work, the code runs in an implicit function +scope. The only argument is a require-like function that can be used to load +builtins like "fs": getBuiltin(request: string).

      +

      If the code needs more advanced require features, it has to construct +its own require using module.createRequire().

      +
      /**
      + * @returns {string} Code to run before application startup
      + */
      +export function getGlobalPreloadCode() {
      +  return `\
      +globalThis.someInjectedProperty = 42;
      +console.log('I just set some globals!');
      +
      +const { createRequire } = getBuiltin('module');
      +
      +const require = createRequire(process.cwd() + '/<preload>');
      +// [...]
      +`;
      +}
      +

      dynamicInstantiate hook#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      +

      To create a custom dynamic module that doesn't correspond to one of the +existing format interpretations, the dynamicInstantiate hook can be used. +This hook is called only for modules that return format: 'dynamic' from +the getFormat hook.

      +
      /**
      + * @param {string} url
      + * @returns {object} response
      + * @returns {array} response.exports
      + * @returns {function} response.execute
      + */
      +export async function dynamicInstantiate(url) {
      +  return {
      +    exports: ['customExportName'],
      +    execute: (exports) => {
      +      // Get and set functions provided for pre-allocated export names
      +      exports.customExportName.set('value');
      +    }
      +  };
      +}
      +

      With the list of module exports provided upfront, the execute function will +then be called at the exact point of module evaluation order for that module +in the import tree.

      +

      Examples#

      +

      The various loader hooks can be used together to accomplish wide-ranging +customizations of Node.js’ code loading and evaluation behaviors.

      +

      HTTPS loader#

      +

      In current Node.js, specifiers starting with https:// are unsupported. The +loader below registers hooks to enable rudimentary support for such specifiers. +While this may seem like a significant improvement to Node.js core +functionality, there are substantial downsides to actually using this loader: +performance is much slower than loading files from disk, there is no caching, +and there is no security.

      +
      // https-loader.mjs
      +import { get } from 'https';
      +
      +export function resolve(specifier, context, defaultResolve) {
      +  const { parentURL = null } = context;
      +
      +  // Normally Node.js would error on specifiers starting with 'https://', so
      +  // this hook intercepts them and converts them into absolute URLs to be
      +  // passed along to the later hooks below.
      +  if (specifier.startsWith('https://')) {
      +    return {
      +      url: specifier
      +    };
      +  } else if (parentURL && parentURL.startsWith('https://')) {
      +    return {
      +      url: new URL(specifier, parentURL).href
      +    };
      +  }
      +
      +  // Let Node.js handle all other specifiers.
      +  return defaultResolve(specifier, context, defaultResolve);
      +}
      +
      +export function getFormat(url, context, defaultGetFormat) {
      +  // This loader assumes all network-provided JavaScript is ES module code.
      +  if (url.startsWith('https://')) {
      +    return {
      +      format: 'module'
      +    };
      +  }
      +
      +  // Let Node.js handle all other URLs.
      +  return defaultGetFormat(url, context, defaultGetFormat);
      +}
      +
      +export function getSource(url, context, defaultGetSource) {
      +  // For JavaScript to be loaded over the network, we need to fetch and
      +  // return it.
      +  if (url.startsWith('https://')) {
      +    return new Promise((resolve, reject) => {
      +      get(url, (res) => {
      +        let data = '';
      +        res.on('data', (chunk) => data += chunk);
      +        res.on('end', () => resolve({ source: data }));
      +      }).on('error', (err) => reject(err));
      +    });
      +  }
      +
      +  // Let Node.js handle all other URLs.
      +  return defaultGetSource(url, context, defaultGetSource);
      +}
      +
      // main.mjs
      +import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
      +
      +console.log(VERSION);
      +

      With the preceding loader, running +node --experimental-loader ./https-loader.mjs ./main.mjs +prints the current version of CoffeeScript per the module at the URL in +main.mjs.

      +

      Transpiler loader#

      +

      Sources that are in formats Node.js doesn’t understand can be converted into +JavaScript using the transformSource hook. Before that hook gets called, +however, other hooks need to tell Node.js not to throw an error on unknown file +types; and to tell Node.js how to load this new file type.

      +

      This is less performant than transpiling source files before running +Node.js; a transpiler loader should only be used for development and testing +purposes.

      +
      // coffeescript-loader.mjs
      +import { URL, pathToFileURL } from 'url';
      +import CoffeeScript from 'coffeescript';
      +
      +const baseURL = pathToFileURL(`${process.cwd()}/`).href;
      +
      +// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.
      +const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;
      +
      +export function resolve(specifier, context, defaultResolve) {
      +  const { parentURL = baseURL } = context;
      +
      +  // Node.js normally errors on unknown file extensions, so return a URL for
      +  // specifiers ending in the CoffeeScript file extensions.
      +  if (extensionsRegex.test(specifier)) {
      +    return {
      +      url: new URL(specifier, parentURL).href
      +    };
      +  }
      +
      +  // Let Node.js handle all other specifiers.
      +  return defaultResolve(specifier, context, defaultResolve);
      +}
      +
      +export function getFormat(url, context, defaultGetFormat) {
      +  // Now that we patched resolve to let CoffeeScript URLs through, we need to
      +  // tell Node.js what format such URLs should be interpreted as. For the
      +  // purposes of this loader, all CoffeeScript URLs are ES modules.
      +  if (extensionsRegex.test(url)) {
      +    return {
      +      format: 'module'
      +    };
      +  }
      +
      +  // Let Node.js handle all other URLs.
      +  return defaultGetFormat(url, context, defaultGetFormat);
      +}
      +
      +export function transformSource(source, context, defaultTransformSource) {
      +  const { url, format } = context;
      +
      +  if (extensionsRegex.test(url)) {
      +    return {
      +      source: CoffeeScript.compile(source, { bare: true })
      +    };
      +  }
      +
      +  // Let Node.js handle all other sources.
      +  return defaultTransformSource(source, context, defaultTransformSource);
      +}
      +
      # main.coffee
      +import { scream } from './scream.coffee'
      +console.log scream 'hello, world'
      +
      +import { version } from 'process'
      +console.log "Brought to you by Node.js version #{version}"
      +
      # scream.coffee
      +export scream = (str) -> str.toUpperCase()
      +

      With the preceding loader, running +node --experimental-loader ./coffeescript-loader.mjs main.coffee +causes main.coffee to be turned into JavaScript after its source code is +loaded from disk but before Node.js executes it; and so on for any .coffee, +.litcoffee or .coffee.md files referenced via import statements of any +loaded file.

      +

      Resolution algorithm#

      +

      Features#

      +

      The resolver has the following properties:

      +
        +
      • FileURL-based resolution as is used by ES modules
      • +
      • Support for builtin module loading
      • +
      • Relative and absolute URL resolution
      • +
      • No default extensions
      • +
      • No folder mains
      • +
      • Bare specifier package resolution lookup through node_modules
      • +
      +

      Resolver algorithm#

      +

      The algorithm to load an ES module specifier is given through the +ESM_RESOLVE method below. It returns the resolved URL for a +module specifier relative to a parentURL.

      +

      The algorithm to determine the module format of a resolved URL is +provided by ESM_FORMAT, which returns the unique module +format for any file. The "module" format is returned for an ECMAScript +Module, while the "commonjs" format is used to indicate loading through the +legacy CommonJS loader. Additional formats such as "addon" can be extended in +future updates.

      +

      In the following algorithms, all subroutine errors are propagated as errors +of these top-level routines unless stated otherwise.

      +

      defaultConditions is the conditional environment name array, +["node", "import"].

      +

      The resolver can throw the following errors:

      +
        +
      • Invalid Module Specifier: Module specifier is an invalid URL, package name +or package subpath specifier.
      • +
      • Invalid Package Configuration: package.json configuration is invalid or +contains an invalid configuration.
      • +
      • Invalid Package Target: Package exports or imports define a target module +for the package that is an invalid type or string target.
      • +
      • Package Path Not Exported: Package exports do not define or permit a target +subpath in the package for the given module.
      • +
      • Package Import Not Defined: Package imports do not define the specifier.
      • +
      • Module Not Found: The package or module requested does not exist.
      • +
      +

      Resolver Algorithm Specification#

      +

      ESM_RESOLVE(specifier, parentURL)

      +
      +
        +
      1. Let resolved be undefined.
      2. +
      3. If specifier is a valid URL, then +
          +
        1. Set resolved to the result of parsing and reserializing +specifier as a URL.
        2. +
        +
      4. +
      5. Otherwise, if specifier starts with "/", "./" or "../", then +
          +
        1. Set resolved to the URL resolution of specifier relative to +parentURL.
        2. +
        +
      6. +
      7. Otherwise, if specifier starts with "#", then +
          +
        1. Set resolved to the destructured value of the result of +PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, +defaultConditions).
        2. +
        +
      8. +
      9. Otherwise, +
          +
        1. Note: specifier is now a bare specifier.
        2. +
        3. Set resolved the result of +PACKAGE_RESOLVE(specifier, parentURL).
        4. +
        +
      10. +
      11. If resolved contains any percent encodings of "/" or "\" ("%2f" +and "%5C" respectively), then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      12. +
      13. If the file at resolved is a directory, then +
          +
        1. Throw an Unsupported Directory Import error.
        2. +
        +
      14. +
      15. If the file at resolved does not exist, then +
          +
        1. Throw a Module Not Found error.
        2. +
        +
      16. +
      17. Set resolved to the real path of resolved.
      18. +
      19. Let format be the result of ESM_FORMAT(resolved).
      20. +
      21. Load resolved as module format, format.
      22. +
      23. Return resolved.
      24. +
      +
      +

      PACKAGE_RESOLVE(packageSpecifier, parentURL)

      +
      +
        +
      1. Let packageName be undefined.
      2. +
      3. If packageSpecifier is an empty string, then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      4. +
      5. If packageSpecifier does not start with "@", then +
          +
        1. Set packageName to the substring of packageSpecifier until the first +"/" separator or the end of the string.
        2. +
        +
      6. +
      7. Otherwise, +
          +
        1. If packageSpecifier does not contain a "/" separator, then +
            +
          1. Throw an Invalid Module Specifier error.
          2. +
          +
        2. +
        3. Set packageName to the substring of packageSpecifier +until the second "/" separator or the end of the string.
        4. +
        +
      8. +
      9. If packageName starts with "." or contains "\" or "%", then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      10. +
      11. Let packageSubpath be "." concatenated with the substring of +packageSpecifier from the position at the length of packageName.
      12. +
      13. Let selfUrl be the result of +PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
      14. +
      15. If selfUrl is not undefined, return selfUrl.
      16. +
      17. If packageSubpath is "." and packageName is a Node.js builtin +module, then +
          +
        1. Return the string "node:" concatenated with packageSpecifier.
        2. +
        +
      18. +
      19. While parentURL is not the file system root, +
          +
        1. Let packageURL be the URL resolution of "node_modules/" +concatenated with packageSpecifier, relative to parentURL.
        2. +
        3. Set parentURL to the parent folder URL of parentURL.
        4. +
        5. If the folder at packageURL does not exist, then +
            +
          1. Set parentURL to the parent URL path of parentURL.
          2. +
          3. Continue the next loop iteration.
          4. +
          +
        6. +
        7. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        8. +
        9. If pjson is not null and pjson.exports is not null or +undefined, then +
            +
          1. Let exports be pjson.exports.
          2. +
          3. Return the resolved destructured value of the result of +PACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath, +pjson.exports, defaultConditions).
          4. +
          +
        10. +
        11. Otherwise, if packageSubpath is equal to ".", then +
            +
          1. Return the result applying the legacy LOAD_AS_DIRECTORY +CommonJS resolver to packageURL, throwing a Module Not Found +error for no resolution.
          2. +
          +
        12. +
        13. Otherwise, +
            +
          1. Return the URL resolution of packageSubpath in packageURL.
          2. +
          +
        14. +
        +
      20. +
      21. Throw a Module Not Found error.
      22. +
      +
      +

      PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

      +
      +
        +
      1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      2. +
      3. If packageURL is null, then +
          +
        1. Return undefined.
        2. +
        +
      4. +
      5. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
      6. +
      7. If pjson is null or if pjson.exports is null or +undefined, then +
          +
        1. Return undefined.
        2. +
        +
      8. +
      9. If pjson.name is equal to packageName, then +
          +
        1. Return the resolved destructured value of the result of +PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports, +defaultConditions).
        2. +
        +
      10. +
      11. Otherwise, return undefined.
      12. +
      +
      +

      PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

      +
      +
        +
      1. If exports is an Object with both a key starting with "." and a key not +starting with ".", throw an Invalid Package Configuration error.
      2. +
      3. If subpath is equal to ".", then +
          +
        1. Let mainExport be undefined.
        2. +
        3. If exports is a String or Array, or an Object containing no keys +starting with ".", then +
            +
          1. Set mainExport to exports.
          2. +
          +
        4. +
        5. Otherwise if exports is an Object containing a "." property, then +
            +
          1. Set mainExport to exports["."].
          2. +
          +
        6. +
        7. If mainExport is not undefined, then +
            +
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, mainExport, "", false, false, +conditions).
          2. +
          3. If resolved is not null or undefined, then +
              +
            1. Return resolved.
            2. +
            +
          4. +
          +
        8. +
        +
      4. +
      5. Otherwise, if exports is an Object and all keys of exports start with +".", then +
          +
        1. Let matchKey be the string "./" concatenated with subpath.
        2. +
        3. Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( +matchKey, exports, packageURL, false, conditions).
        4. +
        5. If resolvedMatch.resolve is not null or undefined, then +
            +
          1. Return resolvedMatch.
          2. +
          +
        6. +
        +
      6. +
      7. Throw a Package Path Not Exported error.
      8. +
      +
      +

      PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

      +
      +
        +
      1. Assert: specifier begins with "#".
      2. +
      3. If specifier is exactly equal to "#" or starts with "#/", then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      4. +
      5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      6. +
      7. If packageURL is not null, then +
          +
        1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        2. +
        3. If pjson.imports is a non-null Object, then +
            +
          1. Let resolvedMatch be the result of +PACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports, +packageURL, true, conditions).
          2. +
          3. If resolvedMatch.resolve is not null or undefined, then +
              +
            1. Return resolvedMatch.
            2. +
            +
          4. +
          +
        4. +
        +
      8. +
      9. Throw a Package Import Not Defined error.
      10. +
      +
      +

      PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, +isImports, conditions)

      +
      +
        +
      1. If matchKey is a key of matchObj, and does not end in "*", then +
          +
        1. Let target be the value of matchObj[matchKey].
        2. +
        3. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, target, "", false, isImports, conditions).
        4. +
        5. Return the object { resolved, exact: true }.
        6. +
        +
      2. +
      3. Let expansionKeys be the list of keys of matchObj ending in "/" +or "*", sorted by length descending.
      4. +
      5. For each key expansionKey in expansionKeys, do +
          +
        1. If expansionKey ends in "*" and matchKey starts with but is +not equal to the substring of expansionKey excluding the last "*" +character, then +
            +
          1. Let target be the value of matchObj[expansionKey].
          2. +
          3. Let subpath be the substring of matchKey starting at the +index of the length of expansionKey minus one.
          4. +
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, target, subpath, true, isImports, +conditions).
          6. +
          7. Return the object { resolved, exact: true }.
          8. +
          +
        2. +
        3. If matchKey starts with expansionKey, then +
            +
          1. Let target be the value of matchObj[expansionKey].
          2. +
          3. Let subpath be the substring of matchKey starting at the +index of the length of expansionKey.
          4. +
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, target, subpath, false, isImports, +conditions).
          6. +
          7. Return the object { resolved, exact: false }.
          8. +
          +
        4. +
        +
      6. +
      7. Return the object { resolved: null, exact: true }.
      8. +
      +
      +

      PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern, +internal, conditions)

      +
      +
        +
      1. If target is a String, then +
          +
        1. If pattern is false, subpath has non-zero length and target +does not end with "/", throw an Invalid Module Specifier error.
        2. +
        3. If target does not start with "./", then +
            +
          1. If internal is true and target does not start with "../" or +"/" and is not a valid URL, then +
              +
            1. If pattern is true, then +
                +
              1. Return PACKAGE_RESOLVE(target with every instance of +"*" replaced by subpath, packageURL + "/")_.
              2. +
              +
            2. +
            3. Return PACKAGE_RESOLVE(target + subpath, +packageURL + "/")_.
            4. +
            +
          2. +
          3. Otherwise, throw an Invalid Package Target error.
          4. +
          +
        4. +
        5. If target split on "/" or "\" contains any ".", ".." or +"node_modules" segments after the first segment, throw an +Invalid Package Target error.
        6. +
        7. Let resolvedTarget be the URL resolution of the concatenation of +packageURL and target.
        8. +
        9. Assert: resolvedTarget is contained in packageURL.
        10. +
        11. If subpath split on "/" or "\" contains any ".", ".." or +"node_modules" segments, throw an Invalid Module Specifier error.
        12. +
        13. If pattern is true, then +
            +
          1. Return the URL resolution of resolvedTarget with every instance of +"*" replaced with subpath.
          2. +
          +
        14. +
        15. Otherwise, +
            +
          1. Return the URL resolution of the concatenation of subpath and +resolvedTarget.
          2. +
          +
        16. +
        +
      2. +
      3. Otherwise, if target is a non-null Object, then +
          +
        1. If exports contains any index property keys, as defined in ECMA-262 +6.1.7 Array Index, throw an Invalid Package Configuration error.
        2. +
        3. For each property p of target, in object insertion order as, +
            +
          1. If p equals "default" or conditions contains an entry for p, +then +
              +
            1. Let targetValue be the value of the p property in target.
            2. +
            3. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, targetValue, subpath, pattern, internal, +conditions).
            4. +
            5. If resolved is equal to undefined, continue the loop.
            6. +
            7. Return resolved.
            8. +
            +
          2. +
          +
        4. +
        5. Return undefined.
        6. +
        +
      4. +
      5. Otherwise, if target is an Array, then +
          +
        1. If _target.length is zero, return null.
        2. +
        3. For each item targetValue in target, do +
            +
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, targetValue, subpath, pattern, internal, +conditions), continuing the loop on any Invalid Package Target +error.
          2. +
          3. If resolved is undefined, continue the loop.
          4. +
          5. Return resolved.
          6. +
          +
        4. +
        5. Return or throw the last fallback resolution null return or error.
        6. +
        +
      6. +
      7. Otherwise, if target is null, return null.
      8. +
      9. Otherwise throw an Invalid Package Target error.
      10. +
      +
      +

      ESM_FORMAT(url)

      +
      +
        +
      1. Assert: url corresponds to an existing file.
      2. +
      3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
      4. +
      5. If url ends in ".mjs", then +
          +
        1. Return "module".
        2. +
        +
      6. +
      7. If url ends in ".cjs", then +
          +
        1. Return "commonjs".
        2. +
        +
      8. +
      9. If pjson?.type exists and is "module", then +
          +
        1. If url ends in ".js", then +
            +
          1. Return "module".
          2. +
          +
        2. +
        3. Throw an Unsupported File Extension error.
        4. +
        +
      10. +
      11. Otherwise, +
          +
        1. Throw an Unsupported File Extension error.
        2. +
        +
      12. +
      +
      +

      READ_PACKAGE_SCOPE(url)

      +
      +
        +
      1. Let scopeURL be url.
      2. +
      3. While scopeURL is not the file system root, +
          +
        1. Set scopeURL to the parent URL of scopeURL.
        2. +
        3. If scopeURL ends in a "node_modules" path segment, return null.
        4. +
        5. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
        6. +
        7. If pjson is not null, then +
            +
          1. Return pjson.
          2. +
          +
        8. +
        +
      4. +
      5. Return null.
      6. +
      +
      +

      READ_PACKAGE_JSON(packageURL)

      +
      +
        +
      1. Let pjsonURL be the resolution of "package.json" within packageURL.
      2. +
      3. If the file at pjsonURL does not exist, then +
          +
        1. Return null.
        2. +
        +
      4. +
      5. If the file at packageURL does not parse as valid JSON, then +
          +
        1. Throw an Invalid Package Configuration error.
        2. +
        +
      6. +
      7. Return the parsed JSON source of the file at pjsonURL.
      8. +
      +
      +

      Customizing ESM specifier resolution algorithm#

      +

      The current specifier resolution does not support all default behavior of +the CommonJS loader. One of the behavior differences is automatic resolution +of file extensions and the ability to import directories that have an index +file.

      +

      The --experimental-specifier-resolution=[mode] flag can be used to customize +the extension resolution algorithm. The default mode is explicit, which +requires the full path to a module be provided to the loader. To enable the +automatic extension resolution and importing from directories that include an +index file use the node mode.

      +
      $ node index.mjs
      +success!
      +$ node index # Failure!
      +Error: Cannot find module
      +$ node --experimental-specifier-resolution=node index
      +success!
      + +

      Modules: module API#

      + +

      The Module object#

      + +

      Provides general utility methods when interacting with instances of +Module, the module variable often seen in CommonJS modules. Accessed +via import 'module' or require('module').

      +

      module.builtinModules#

      + + +

      A list of the names of all modules provided by Node.js. Can be used to verify +if a module is maintained by a third party or not.

      +

      module in this context isn't the same object that's provided +by the module wrapper. To access it, require the Module module:

      +
      // module.mjs
      +// In an ECMAScript module
      +import { builtinModules as builtin } from 'module';
      +
      // module.cjs
      +// In a CommonJS module
      +const builtin = require('module').builtinModules;
      +

      module.createRequire(filename)#

      + +
        +
      • filename <string> | <URL> Filename to be used to construct the require +function. Must be a file URL object, file URL string, or absolute path +string.
      • +
      • Returns: <require> Require function
      • +
      +
      import { createRequire } from 'module';
      +const require = createRequire(import.meta.url);
      +
      +// sibling-module.js is a CommonJS module.
      +const siblingModule = require('./sibling-module');
      +

      module.createRequireFromPath(filename)#

      + +

      Stability: 0 - Deprecated: Please use createRequire() instead.

      +
        +
      • filename <string> Filename to be used to construct the relative require +function.
      • +
      • Returns: <require> Require function
      • +
      +
      const { createRequireFromPath } = require('module');
      +const requireUtil = createRequireFromPath('../src/utils/');
      +
      +// Require `../src/utils/some-tool`
      +requireUtil('./some-tool');
      +

      module.syncBuiltinESMExports()#

      + +

      The module.syncBuiltinESMExports() method updates all the live bindings for +builtin ES Modules to match the properties of the CommonJS exports. It +does not add or remove exported names from the ES Modules.

      +
      const fs = require('fs');
      +const { syncBuiltinESMExports } = require('module');
      +
      +fs.readFile = null;
      +
      +delete fs.readFileSync;
      +
      +fs.newAPI = function newAPI() {
      +  // ...
      +};
      +
      +syncBuiltinESMExports();
      +
      +import('fs').then((esmFS) => {
      +  assert.strictEqual(esmFS.readFile, null);
      +  assert.strictEqual('readFileSync' in fs, true);
      +  assert.strictEqual(esmFS.newAPI, undefined);
      +});
      +

      Source map v3 support#

      + +

      Stability: 1 - Experimental

      +

      Helpers for interacting with the source map cache. This cache is +populated when source map parsing is enabled and +source map include directives are found in a modules' footer.

      +

      To enable source map parsing, Node.js must be run with the flag +--enable-source-maps, or with code coverage enabled by setting +NODE_V8_COVERAGE=dir.

      +
      // module.mjs
      +// In an ECMAScript module
      +import { findSourceMap, SourceMap } from 'module';
      +
      // module.cjs
      +// In a CommonJS module
      +const { findSourceMap, SourceMap } = require('module');
      +

      module.findSourceMap(path[, error])#

      + + +

      path is the resolved path for the file for which a corresponding source map +should be fetched.

      +

      The error instance should be passed as the second parameter to findSourceMap +in exceptional flows, such as when an overridden +Error.prepareStackTrace(error, trace) is invoked. Modules are not added to +the module cache until they are successfully loaded. In these cases, source maps +are associated with the error instance along with the path.

      +

      Class: module.SourceMap#

      + +

      new SourceMap(payload)#

      + +

      Creates a new sourceMap instance.

      +

      payload is an object with keys matching the Source map v3 format:

      + +

      sourceMap.payload#

      + +

      Getter for the payload used to construct the SourceMap instance.

      +

      sourceMap.findEntry(lineNumber, columnNumber)#

      + +

      Given a line number and column number in the generated source file, returns +an object representing the position in the original file. The object returned +consists of the following keys:

      + +

      Modules: Packages#

      + + +

      Introduction#

      +

      A package is a folder tree described by a package.json file. The package +consists of the folder containing the package.json file and all subfolders +until the next folder containing another package.json file, or a folder +named node_modules.

      +

      This page provides guidance for package authors writing package.json files +along with a reference for the package.json fields defined by Node.js.

      +

      Determining module system#

      +

      Node.js will treat the following as ES modules when passed to node as the +initial input, or when referenced by import statements within ES module code:

      +
        +
      • +

        Files ending in .mjs.

        +
      • +
      • +

        Files ending in .js when the nearest parent package.json file contains a +top-level "type" field with a value of "module".

        +
      • +
      • +

        Strings passed in as an argument to --eval, or piped to node via STDIN, +with the flag --input-type=module.

        +
      • +
      +

      Node.js will treat as CommonJS all other forms of input, such as .js files +where the nearest parent package.json file contains no top-level "type" +field, or string input without the flag --input-type. This behavior is to +preserve backward compatibility. However, now that Node.js supports both +CommonJS and ES modules, it is best to be explicit whenever possible. Node.js +will treat the following as CommonJS when passed to node as the initial input, +or when referenced by import statements within ES module code:

      +
        +
      • +

        Files ending in .cjs.

        +
      • +
      • +

        Files ending in .js when the nearest parent package.json file contains a +top-level field "type" with a value of "commonjs".

        +
      • +
      • +

        Strings passed in as an argument to --eval or --print, or piped to node +via STDIN, with the flag --input-type=commonjs.

        +
      • +
      +

      Package authors should include the "type" field, even in packages where +all sources are CommonJS. Being explicit about the type of the package will +future-proof the package in case the default type of Node.js ever changes, and +it will also make things easier for build tools and loaders to determine how the +files in the package should be interpreted.

      +

      package.json and file extensions#

      +

      Within a package, the package.json "type" field defines how +Node.js should interpret .js files. If a package.json file does not have a +"type" field, .js files are treated as CommonJS.

      +

      A package.json "type" value of "module" tells Node.js to interpret .js +files within that package as using ES module syntax.

      +

      The "type" field applies not only to initial entry points (node my-app.js) +but also to files referenced by import statements and import() expressions.

      +
      // my-app.js, treated as an ES module because there is a package.json
      +// file in the same folder with "type": "module".
      +
      +import './startup/init.js';
      +// Loaded as ES module since ./startup contains no package.json file,
      +// and therefore inherits the "type" value from one level up.
      +
      +import 'commonjs-package';
      +// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
      +// lacks a "type" field or contains "type": "commonjs".
      +
      +import './node_modules/commonjs-package/index.js';
      +// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
      +// lacks a "type" field or contains "type": "commonjs".
      +

      Files ending with .mjs are always loaded as ES modules regardless of +the nearest parent package.json.

      +

      Files ending with .cjs are always loaded as CommonJS regardless of the +nearest parent package.json.

      +
      import './legacy-file.cjs';
      +// Loaded as CommonJS since .cjs is always loaded as CommonJS.
      +
      +import 'commonjs-package/src/index.mjs';
      +// Loaded as ES module since .mjs is always loaded as ES module.
      +

      The .mjs and .cjs extensions can be used to mix types within the same +package:

      +
        +
      • +

        Within a "type": "module" package, Node.js can be instructed to +interpret a particular file as CommonJS by naming it with a .cjs +extension (since both .js and .mjs files are treated as ES modules within +a "module" package).

        +
      • +
      • +

        Within a "type": "commonjs" package, Node.js can be instructed to +interpret a particular file as an ES module by naming it with an .mjs +extension (since both .js and .cjs files are treated as CommonJS within a +"commonjs" package).

        +
      • +
      +

      --input-type flag#

      +

      Strings passed in as an argument to --eval (or -e), or piped to node via +STDIN, are treated as ES modules when the --input-type=module flag +is set.

      +
      node --input-type=module --eval "import { sep } from 'path'; console.log(sep);"
      +
      +echo "import { sep } from 'path'; console.log(sep);" | node --input-type=module
      +

      For completeness there is also --input-type=commonjs, for explicitly running +string input as CommonJS. This is the default behavior if --input-type is +unspecified.

      +

      Package entry points#

      +

      In a package’s package.json file, two fields can define entry points for a +package: "main" and "exports". The "main" field is supported +in all versions of Node.js, but its capabilities are limited: it only defines +the main entry point of the package.

      +

      The "exports" field provides an alternative to "main" where the +package main entry point can be defined while also encapsulating the package, +preventing any other entry points besides those defined in "exports". +This encapsulation allows module authors to define a public interface for +their package.

      +

      If both "exports" and "main" are defined, the "exports" field +takes precedence over "main". "exports" are not specific to ES +modules or CommonJS; "main" is overridden by "exports" if it +exists. As such "main" cannot be used as a fallback for CommonJS but it +can be used as a fallback for legacy versions of Node.js that do not support the +"exports" field.

      +

      Conditional exports can be used within "exports" to define different +package entry points per environment, including whether the package is +referenced via require or via import. For more information about supporting +both CommonJS and ES Modules in a single package please consult +the dual CommonJS/ES module packages section.

      +

      Warning: Introducing the "exports" field prevents consumers of a +package from using any entry points that are not defined, including the +package.json (e.g. require('your-package/package.json'). This will +likely be a breaking change.

      +

      To make the introduction of "exports" non-breaking, ensure that every +previously supported entry point is exported. It is best to explicitly specify +entry points so that the package’s public API is well-defined. For example, +a project that previous exported main, lib, +feature, and the package.json could use the following package.exports:

      +
      {
      +  "name": "my-mod",
      +  "exports": {
      +    ".": "./lib/index.js",
      +    "./lib": "./lib/index.js",
      +    "./lib/index": "./lib/index.js",
      +    "./lib/index.js": "./lib/index.js",
      +    "./feature": "./feature/index.js",
      +    "./feature/index.js": "./feature/index.js",
      +    "./package.json": "./package.json"
      +  }
      +}
      +

      Alternatively a project could choose to export entire folders:

      +
      {
      +  "name": "my-mod",
      +  "exports": {
      +    ".": "./lib/index.js",
      +    "./lib": "./lib/index.js",
      +    "./lib/*": "./lib/*.js",
      +    "./feature": "./feature/index.js",
      +    "./feature/*": "./feature/*.js",
      +    "./package.json": "./package.json"
      +  }
      +}
      +

      As a last resort, package encapsulation can be disabled entirely by creating an +export for the root of the package "./*": "./*". This exposes every file +in the package at the cost of disabling the encapsulation and potential tooling +benefits this provides. As the ES Module loader in Node.js enforces the use of +the full specifier path, exporting the root rather than being explicit +about entry is less expressive than either of the prior examples. Not only +is encapsulation lost but module consumers are unable to +import feature from 'my-mod/feature' as they need to provide the full +path import feature from 'my-mod/feature/index.js.

      +

      Main entry point export#

      +

      To set the main entry point for a package, it is advisable to define both +"exports" and "main" in the package’s package.json file:

      +
      {
      +  "main": "./main.js",
      +  "exports": "./main.js"
      +}
      +

      When the "exports" field is defined, all subpaths of the package are +encapsulated and no longer available to importers. For example, +require('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED +error.

      +

      This encapsulation of exports provides more reliable guarantees +about package interfaces for tools and when handling semver upgrades for a +package. It is not a strong encapsulation since a direct require of any +absolute subpath of the package such as +require('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.

      +

      Subpath exports#

      +

      Stability: 1 - Experimental

      +

      When using the "exports" field, custom subpaths can be defined along +with the main entry point by treating the main entry point as the +"." subpath:

      +
      {
      +  "main": "./main.js",
      +  "exports": {
      +    ".": "./main.js",
      +    "./submodule": "./src/submodule.js"
      +  }
      +}
      +

      Now only the defined subpath in "exports" can be imported by a consumer:

      +
      import submodule from 'es-module-package/submodule';
      +// Loads ./node_modules/es-module-package/src/submodule.js
      +

      While other subpaths will error:

      +
      import submodule from 'es-module-package/private-module.js';
      +// Throws ERR_PACKAGE_PATH_NOT_EXPORTED
      +

      Subpath imports#

      +

      Stability: 1 - Experimental

      +

      In addition to the "exports" field, it is possible to define internal +package import maps that only apply to import specifiers from within the package +itself.

      +

      Entries in the imports field must always start with # to ensure they are +disambiguated from package specifiers.

      +

      For example, the imports field can be used to gain the benefits of conditional +exports for internal modules:

      +
      // package.json
      +{
      +  "imports": {
      +    "#dep": {
      +      "node": "dep-node-native",
      +      "default": "./dep-polyfill.js"
      +    }
      +  },
      +  "dependencies": {
      +    "dep-node-native": "^1.0.0"
      +  }
      +}
      +

      where import '#dep' does not get the resolution of the external package +dep-node-native (including its exports in turn), and instead gets the local +file ./dep-polyfill.js relative to the package in other environments.

      +

      Unlike the "exports" field, the "imports" field permits mapping to external +packages.

      +

      The resolution rules for the imports field are otherwise +analogous to the exports field.

      +

      Subpath patterns#

      +

      Stability: 1 - Experimental

      +

      For packages with a small number of exports or imports, we recommend +explicitly listing each exports subpath entry. But for packages that have +large numbers of subpaths, this might cause package.json bloat and +maintenance issues.

      +

      For these use cases, subpath export patterns can be used instead:

      +
      // ./node_modules/es-module-package/package.json
      +{
      +  "exports": {
      +    "./features/*": "./src/features/*.js"
      +  },
      +  "imports": {
      +    "#internal/*": "./src/internal/*.js"
      +  }
      +}
      +

      The left hand matching pattern must always end in *. All instances of * on +the right hand side will then be replaced with this value, including if it +contains any / separators.

      +
      import featureX from 'es-module-package/features/x';
      +// Loads ./node_modules/es-module-package/src/features/x.js
      +
      +import featureY from 'es-module-package/features/y/y';
      +// Loads ./node_modules/es-module-package/src/features/y/y.js
      +
      +import internalZ from '#internal/z';
      +// Loads ./node_modules/es-module-package/src/internal/z.js
      +

      This is a direct static replacement without any special handling for file +extensions. In the previous example, pkg/features/x.json would be resolved to +./src/features/x.json.js in the mapping.

      +

      The property of exports being statically enumerable is maintained with exports +patterns since the individual exports for a package can be determined by +treating the right hand side target pattern as a ** glob against the list of +files within the package. Because node_modules paths are forbidden in exports +targets, this expansion is dependent on only the files of the package itself.

      +

      Exports sugar#

      +

      Stability: 1 - Experimental

      +

      If the "." export is the only export, the "exports" field provides sugar +for this case being the direct "exports" field value.

      +

      If the "." export has a fallback array or string value, then the +"exports" field can be set to this value directly.

      +
      {
      +  "exports": {
      +    ".": "./main.js"
      +  }
      +}
      +

      can be written:

      +
      {
      +  "exports": "./main.js"
      +}
      +

      Conditional exports#

      +

      Stability: 1 - Experimental

      +

      Conditional exports provide a way to map to different paths depending on +certain conditions. They are supported for both CommonJS and ES module imports.

      +

      For example, a package that wants to provide different ES module exports for +require() and import can be written:

      +
      // package.json
      +{
      +  "main": "./main-require.cjs",
      +  "exports": {
      +    "import": "./main-module.js",
      +    "require": "./main-require.cjs"
      +  },
      +  "type": "module"
      +}
      +

      Node.js supports the following conditions out of the box:

      +
        +
      • "import" - matches when the package is loaded via import or +import(), or via any top-level import or resolve operation by the +ECMAScript module loader. Applies regardless of the module format of the +target file. Always mutually exclusive with "require".
      • +
      • "require" - matches when the package is loaded via require(). The +referenced file should be loadable with require() although the condition +matches regardless of the module format of the target file. Expected +formats include CommonJS, JSON, and native addons but not ES modules as +require() doesn't support them. Always mutually exclusive with +"import".
      • +
      • "node" - matches for any Node.js environment. Can be a CommonJS or ES +module file. This condition should always come after "import" or +"require".
      • +
      • "default" - the generic fallback that always matches. Can be a CommonJS +or ES module file. This condition should always come last.
      • +
      +

      Within the "exports" object, key order is significant. During condition +matching, earlier entries have higher priority and take precedence over later +entries. The general rule is that conditions should be from most specific to +least specific in object order.

      +

      Other conditions such as "browser", "electron", "deno", "react-native", +etc., are unknown to Node.js, and thus ignored. Runtimes or tools other than +Node.js can use them at their discretion. Further restrictions, definitions, or +guidance on condition names might occur in the future.

      +

      Using the "import" and "require" conditions can lead to some hazards, +which are further explained in the dual CommonJS/ES module packages section.

      +

      Conditional exports can also be extended to exports subpaths, for example:

      +
      {
      +  "main": "./main.js",
      +  "exports": {
      +    ".": "./main.js",
      +    "./feature": {
      +      "node": "./feature-node.js",
      +      "default": "./feature.js"
      +    }
      +  }
      +}
      +

      Defines a package where require('pkg/feature') and import 'pkg/feature' +could provide different implementations between Node.js and other JS +environments.

      +

      When using environment branches, always include a "default" condition where +possible. Providing a "default" condition ensures that any unknown JS +environments are able to use this universal implementation, which helps avoid +these JS environments from having to pretend to be existing environments in +order to support packages with conditional exports. For this reason, using +"node" and "default" condition branches is usually preferable to using +"node" and "browser" condition branches.

      +

      Nested conditions#

      +

      Stability: 1 - Experimental

      +

      In addition to direct mappings, Node.js also supports nested condition objects.

      +

      For example, to define a package that only has dual mode entry points for +use in Node.js but not the browser:

      +
      {
      +  "main": "./main.js",
      +  "exports": {
      +    "node": {
      +      "import": "./feature-node.mjs",
      +      "require": "./feature-node.cjs"
      +    },
      +    "default": "./feature.mjs",
      +  }
      +}
      +

      Conditions continue to be matched in order as with flat conditions. If +a nested conditional does not have any mapping it will continue checking +the remaining conditions of the parent condition. In this way nested +conditions behave analogously to nested JavaScript if statements.

      +

      Resolving user conditions#

      +

      When running Node.js, custom user conditions can be added with the +--conditions flag:

      +
      node --conditions=development main.js
      +

      which would then resolve the "development" condition in package imports and +exports, while resolving the existing "node", "default", "import", and +"require" conditions as appropriate.

      +

      Any number of custom conditions can be set with repeat flags.

      +

      Self-referencing a package using its name#

      +

      Within a package, the values defined in the package’s +package.json "exports" field can be referenced via the package’s name. +For example, assuming the package.json is:

      +
      // package.json
      +{
      +  "name": "a-package",
      +  "exports": {
      +    ".": "./main.mjs",
      +    "./foo": "./foo.js"
      +  }
      +}
      +

      Then any module in that package can reference an export in the package itself:

      +
      // ./a-module.mjs
      +import { something } from 'a-package'; // Imports "something" from ./main.mjs.
      +

      Self-referencing is available only if package.json has "exports", and +will allow importing only what that "exports" (in the package.json) +allows. So the code below, given the previous package, will generate a runtime +error:

      +
      // ./another-module.mjs
      +
      +// Imports "another" from ./m.mjs. Fails because
      +// the "package.json" "exports" field
      +// does not provide an export named "./m.mjs".
      +import { another } from 'a-package/m.mjs';
      +

      Self-referencing is also available when using require, both in an ES module, +and in a CommonJS one. For example, this code will also work:

      +
      // ./a-module.js
      +const { something } = require('a-package/foo'); // Loads from ./foo.js.
      +

      Dual CommonJS/ES module packages#

      +

      Prior to the introduction of support for ES modules in Node.js, it was a common +pattern for package authors to include both CommonJS and ES module JavaScript +sources in their package, with package.json "main" specifying the +CommonJS entry point and package.json "module" specifying the ES module +entry point. +This enabled Node.js to run the CommonJS entry point while build tools such as +bundlers used the ES module entry point, since Node.js ignored (and still +ignores) the top-level "module" field.

      +

      Node.js can now run ES module entry points, and a package can contain both +CommonJS and ES module entry points (either via separate specifiers such as +'pkg' and 'pkg/es-module', or both at the same specifier via Conditional +exports). Unlike in the scenario where "module" is only used by bundlers, +or ES module files are transpiled into CommonJS on the fly before evaluation by +Node.js, the files referenced by the ES module entry point are evaluated as ES +modules.

      +

      Dual package hazard#

      +

      When an application is using a package that provides both CommonJS and ES module +sources, there is a risk of certain bugs if both versions of the package get +loaded. This potential comes from the fact that the pkgInstance created by +const pkgInstance = require('pkg') is not the same as the pkgInstance +created by import pkgInstance from 'pkg' (or an alternative main path like +'pkg/module'). This is the “dual package hazard,†where two versions of the +same package can be loaded within the same runtime environment. While it is +unlikely that an application or package would intentionally load both versions +directly, it is common for an application to load one version while a dependency +of the application loads the other version. This hazard can happen because +Node.js supports intermixing CommonJS and ES modules, and can lead to unexpected +behavior.

      +

      If the package main export is a constructor, an instanceof comparison of +instances created by the two versions returns false, and if the export is an +object, properties added to one (like pkgInstance.foo = 3) are not present on +the other. This differs from how import and require statements work in +all-CommonJS or all-ES module environments, respectively, and therefore is +surprising to users. It also differs from the behavior users are familiar with +when using transpilation via tools like Babel or esm.

      +

      Writing dual packages while avoiding or minimizing hazards#

      +

      First, the hazard described in the previous section occurs when a package +contains both CommonJS and ES module sources and both sources are provided for +use in Node.js, either via separate main entry points or exported paths. A +package might instead be written where any version of Node.js receives only +CommonJS sources, and any separate ES module sources the package might contain +are intended only for other environments such as browsers. Such a package +would be usable by any version of Node.js, since import can refer to CommonJS +files; but it would not provide any of the advantages of using ES module syntax.

      +

      A package might also switch from CommonJS to ES module syntax in a breaking +change version bump. This has the disadvantage that the +newest version of the package would only be usable in ES module-supporting +versions of Node.js.

      +

      Every pattern has tradeoffs, but there are two broad approaches that satisfy the +following conditions:

      +
        +
      1. The package is usable via both require and import.
      2. +
      3. The package is usable in both current Node.js and older versions of Node.js +that lack support for ES modules.
      4. +
      5. The package main entry point, e.g. 'pkg' can be used by both require to +resolve to a CommonJS file and by import to resolve to an ES module file. +(And likewise for exported paths, e.g. 'pkg/feature'.)
      6. +
      7. The package provides named exports, e.g. import { name } from 'pkg' rather +than import pkg from 'pkg'; pkg.name.
      8. +
      9. The package is potentially usable in other ES module environments such as +browsers.
      10. +
      11. The hazards described in the previous section are avoided or minimized.
      12. +
      +

      Approach #1: Use an ES module wrapper#

      +

      Write the package in CommonJS or transpile ES module sources into CommonJS, and +create an ES module wrapper file that defines the named exports. Using +Conditional exports, the ES module wrapper is used for import and the +CommonJS entry point for require.

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    "import": "./wrapper.mjs",
      +    "require": "./index.cjs"
      +  }
      +}
      +

      The preceding example uses explicit extensions .mjs and .cjs. +If your files use the .js extension, "type": "module" will cause such files +to be treated as ES modules, just as "type": "commonjs" would cause them +to be treated as CommonJS. +See Enabling.

      +
      // ./node_modules/pkg/index.cjs
      +exports.name = 'value';
      +
      // ./node_modules/pkg/wrapper.mjs
      +import cjsModule from './index.cjs';
      +export const name = cjsModule.name;
      +

      In this example, the name from import { name } from 'pkg' is the same +singleton as the name from const { name } = require('pkg'). Therefore === +returns true when comparing the two names and the divergent specifier hazard +is avoided.

      +

      If the module is not simply a list of named exports, but rather contains a +unique function or object export like module.exports = function () { ... }, +or if support in the wrapper for the import pkg from 'pkg' pattern is desired, +then the wrapper would instead be written to export the default optionally +along with any named exports as well:

      +
      import cjsModule from './index.cjs';
      +export const name = cjsModule.name;
      +export default cjsModule;
      +

      This approach is appropriate for any of the following use cases:

      +
        +
      • The package is currently written in CommonJS and the author would prefer not +to refactor it into ES module syntax, but wishes to provide named exports for +ES module consumers.
      • +
      • The package has other packages that depend on it, and the end user might +install both this package and those other packages. For example a utilities +package is used directly in an application, and a utilities-plus package +adds a few more functions to utilities. Because the wrapper exports +underlying CommonJS files, it doesn’t matter if utilities-plus is written in +CommonJS or ES module syntax; it will work either way.
      • +
      • The package stores internal state, and the package author would prefer not to +refactor the package to isolate its state management. See the next section.
      • +
      +

      A variant of this approach not requiring conditional exports for consumers could +be to add an export, e.g. "./module", to point to an all-ES module-syntax +version of the package. This could be used via import 'pkg/module' by users +who are certain that the CommonJS version will not be loaded anywhere in the +application, such as by dependencies; or if the CommonJS version can be loaded +but doesn’t affect the ES module version (for example, because the package is +stateless):

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    ".": "./index.cjs",
      +    "./module": "./wrapper.mjs"
      +  }
      +}
      +

      Approach #2: Isolate state#

      +

      A package.json file can define the separate CommonJS and ES module entry +points directly:

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    "import": "./index.mjs",
      +    "require": "./index.cjs"
      +  }
      +}
      +

      This can be done if both the CommonJS and ES module versions of the package are +equivalent, for example because one is the transpiled output of the other; and +the package’s management of state is carefully isolated (or the package is +stateless).

      +

      The reason that state is an issue is because both the CommonJS and ES module +versions of the package might get used within an application; for example, the +user’s application code could import the ES module version while a dependency +requires the CommonJS version. If that were to occur, two copies of the +package would be loaded in memory and therefore two separate states would be +present. This would likely cause hard-to-troubleshoot bugs.

      +

      Aside from writing a stateless package (if JavaScript’s Math were a package, +for example, it would be stateless as all of its methods are static), there are +some ways to isolate state so that it’s shared between the potentially loaded +CommonJS and ES module instances of the package:

      +
        +
      1. +

        If possible, contain all state within an instantiated object. JavaScript’s +Date, for example, needs to be instantiated to contain state; if it were a +package, it would be used like this:

        +
        import Date from 'date';
        +const someDate = new Date();
        +// someDate contains state; Date does not
        +

        The new keyword isn’t required; a package’s function can return a new +object, or modify a passed-in object, to keep the state external to the +package.

        +
      2. +
      3. +

        Isolate the state in one or more CommonJS files that are shared between the +CommonJS and ES module versions of the package. For example, if the CommonJS +and ES module entry points are index.cjs and index.mjs, respectively:

        +
        // ./node_modules/pkg/index.cjs
        +const state = require('./state.cjs');
        +module.exports.state = state;
        +
        // ./node_modules/pkg/index.mjs
        +import state from './state.cjs';
        +export {
        +  state
        +};
        +

        Even if pkg is used via both require and import in an application (for +example, via import in application code and via require by a dependency) +each reference of pkg will contain the same state; and modifying that +state from either module system will apply to both.

        +
      4. +
      +

      Any plugins that attach to the package’s singleton would need to separately +attach to both the CommonJS and ES module singletons.

      +

      This approach is appropriate for any of the following use cases:

      +
        +
      • The package is currently written in ES module syntax and the package author +wants that version to be used wherever such syntax is supported.
      • +
      • The package is stateless or its state can be isolated without too much +difficulty.
      • +
      • The package is unlikely to have other public packages that depend on it, or if +it does, the package is stateless or has state that need not be shared between +dependencies or with the overall application.
      • +
      +

      Even with isolated state, there is still the cost of possible extra code +execution between the CommonJS and ES module versions of a package.

      +

      As with the previous approach, a variant of this approach not requiring +conditional exports for consumers could be to add an export, e.g. +"./module", to point to an all-ES module-syntax version of the package:

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    ".": "./index.cjs",
      +    "./module": "./index.mjs"
      +  }
      +}
      +

      Node.js package.json field definitions#

      +

      This section describes the fields used by the Node.js runtime. Other tools (such +as npm) use +additional fields which are ignored by Node.js and not documented here.

      +

      The following fields in package.json files are used in Node.js:

      +
        +
      • "name" - Relevant when using named imports within a package. Also used +by package managers as the name of the package.
      • +
      • "type" - The package type determining whether to load .js files as +CommonJS or ES modules.
      • +
      • "exports" - Package exports and conditional exports. When present, +limits which submodules can be loaded from within the package.
      • +
      • "main" - The default module when loading the package, if exports is not +specified, and in versions of Node.js prior to the introduction of exports.
      • +
      • "imports" - Package imports, for use by modules within the package +itself.
      • +
      +

      "name"#

      + + +
      {
      +  "name": "package-name"
      +}
      +

      The "name" field defines your package’s name. Publishing to the +npm registry requires a name that satisfies +certain requirements.

      +

      The "name" field can be used in addition to the "exports" field to +self-reference a package using its name.

      +

      "type"#

      + + +

      The "type" field defines the module format that Node.js uses for all +.js files that have that package.json file as their nearest parent.

      +

      Files ending with .js are loaded as ES modules when the nearest parent +package.json file contains a top-level field "type" with a value of +"module".

      +

      The nearest parent package.json is defined as the first package.json found +when searching in the current folder, that folder’s parent, and so on up +until a node_modules folder or the volume root is reached.

      +
      // package.json
      +{
      +  "type": "module"
      +}
      +
      # In same folder as preceding package.json
      +node my-app.js # Runs as ES module
      +

      If the nearest parent package.json lacks a "type" field, or contains +"type": "commonjs", .js files are treated as CommonJS. If the volume +root is reached and no package.json is found, .js files are treated as +CommonJS.

      +

      import statements of .js files are treated as ES modules if the nearest +parent package.json contains "type": "module".

      +
      // my-app.js, part of the same example as above
      +import './startup.js'; // Loaded as ES module because of package.json
      +

      Regardless of the value of the "type" field, .mjs files are always treated +as ES modules and .cjs files are always treated as CommonJS.

      +

      "exports"#

      + + +
      {
      +  "exports": "./index.js"
      +}
      +

      The "exports" field allows defining the entry points of a package when +imported by name loaded either via a node_modules lookup or a +self-reference to its own name. It is supported in Node.js 12+ as an +alternative to the "main" that can support defining subpath exports +and conditional exports while encapsulating internal unexported modules.

      +

      Conditional Exports can also be used within "exports" to define different +package entry points per environment, including whether the package is +referenced via require or via import.

      +

      All paths defined in the "exports" must be relative file URLs starting with +./.

      +

      "main"#

      + + +
      {
      +  "main": "./main.js"
      +}
      +

      The "main" field defines the script that is used when the package directory +is loaded via require(). Its value +is interpreted as a path.

      +
      require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.
      +

      When a package has an "exports" field, this will take precedence over the +"main" field when importing the package by name.

      +

      "imports"#

      + +

      Stability: 1 - Experimental

      + +
      // package.json
      +{
      +  "imports": {
      +    "#dep": {
      +      "node": "dep-node-native",
      +      "default": "./dep-polyfill.js"
      +    }
      +  },
      +  "dependencies": {
      +    "dep-node-native": "^1.0.0"
      +  }
      +}
      +

      Entries in the imports field must be strings starting with #.

      +

      Import maps permit mapping to external packages.

      +

      This field defines subpath imports for the current package.

      +

      Net#

      + + +

      Stability: 2 - Stable

      +

      Source Code: lib/net.js

      +

      The net module provides an asynchronous network API for creating stream-based +TCP or IPC servers (net.createServer()) and clients +(net.createConnection()).

      +

      It can be accessed using:

      +
      const net = require('net');
      +

      IPC support#

      +

      The net module supports IPC with named pipes on Windows, and Unix domain +sockets on other operating systems.

      +

      Identifying paths for IPC connections#

      +

      net.connect(), net.createConnection(), server.listen() and +socket.connect() take a path parameter to identify IPC endpoints.

      +

      On Unix, the local domain is also known as the Unix domain. The path is a +filesystem pathname. It gets truncated to an OS-dependent length of +sizeof(sockaddr_un.sun_path) - 1. Typical values are 107 bytes on Linux and +103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, +it will unlink the Unix domain socket as well. For example, +net.createServer() may create a Unix domain socket and +server.close() will unlink it. But if a user creates the Unix domain +socket outside of these abstractions, the user will need to remove it. The same +applies when a Node.js API creates a Unix domain socket but the program then +crashes. In short, a Unix domain socket will be visible in the filesystem and +will persist until unlinked.

      +

      On Windows, the local domain is implemented using a named pipe. The path must +refer to an entry in \\?\pipe\ or \\.\pipe\. Any characters are permitted, +but the latter may do some processing of pipe names, such as resolving .. +sequences. Despite how it might look, the pipe namespace is flat. Pipes will +not persist. They are removed when the last reference to them is closed. +Unlike Unix domain sockets, Windows will close and remove the pipe when the +owning process exits.

      +

      JavaScript string escaping requires paths to be specified with extra backslash +escaping such as:

      +
      net.createServer().listen(
      +  path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
      +

      Class: net.Server#

      + + +

      This class is used to create a TCP or IPC server.

      +

      new net.Server([options][, connectionListener])#

      + +

      net.Server is an EventEmitter with the following events:

      +

      Event: 'close'#

      + +

      Emitted when the server closes. If connections exist, this +event is not emitted until all connections are ended.

      +

      Event: 'connection'#

      + + +

      Emitted when a new connection is made. socket is an instance of +net.Socket.

      +

      Event: 'error'#

      + + +

      Emitted when an error occurs. Unlike net.Socket, the 'close' +event will not be emitted directly following this event unless +server.close() is manually called. See the example in discussion of +server.listen().

      +

      Event: 'listening'#

      + +

      Emitted when the server has been bound after calling server.listen().

      +

      server.address()#

      + + +

      Returns the bound address, the address family name, and port of the server +as reported by the operating system if listening on an IP socket +(useful to find which port was assigned when getting an OS-assigned address): +{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      +

      For a server listening on a pipe or Unix domain socket, the name is returned +as a string.

      +
      const server = net.createServer((socket) => {
      +  socket.end('goodbye\n');
      +}).on('error', (err) => {
      +  // Handle errors here.
      +  throw err;
      +});
      +
      +// Grab an arbitrary unused port.
      +server.listen(() => {
      +  console.log('opened server on', server.address());
      +});
      +

      server.address() returns null before the 'listening' event has been +emitted or after calling server.close().

      +

      server.close([callback])#

      + + +

      Stops the server from accepting new connections and keeps existing +connections. This function is asynchronous, the server is finally closed +when all connections are ended and the server emits a 'close' event. +The optional callback will be called once the 'close' event occurs. Unlike +that event, it will be called with an Error as its only argument if the server +was not open when it was closed.

      +

      server.connections#

      + +

      Stability: 0 - Deprecated: Use server.getConnections() instead.

      + +

      The number of concurrent connections on the server.

      +

      This becomes null when sending a socket to a child with +child_process.fork(). To poll forks and get current number of active +connections, use asynchronous server.getConnections() instead.

      +

      server.getConnections(callback)#

      + + +

      Asynchronously get the number of concurrent connections on the server. Works +when sockets were sent to forks.

      +

      Callback should take two arguments err and count.

      +

      server.listen()#

      +

      Start a server listening for connections. A net.Server can be a TCP or +an IPC server depending on what it listens to.

      +

      Possible signatures:

      + +

      This function is asynchronous. When the server starts listening, the +'listening' event will be emitted. The last parameter callback +will be added as a listener for the 'listening' event.

      +

      All listen() methods can take a backlog parameter to specify the maximum +length of the queue of pending connections. The actual length will be determined +by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn +on Linux. The default value of this parameter is 511 (not 512).

      +

      All net.Socket are set to SO_REUSEADDR (see socket(7) for +details).

      +

      The server.listen() method can be called again if and only if there was an +error during the first server.listen() call or server.close() has been +called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      +

      One of the most common errors raised when listening is EADDRINUSE. +This happens when another server is already listening on the requested +port/path/handle. One way to handle this would be to retry +after a certain amount of time:

      +
      server.on('error', (e) => {
      +  if (e.code === 'EADDRINUSE') {
      +    console.log('Address in use, retrying...');
      +    setTimeout(() => {
      +      server.close();
      +      server.listen(PORT, HOST);
      +    }, 1000);
      +  }
      +});
      +

      server.listen(handle[, backlog][, callback])#

      + + +

      Start a server listening for connections on a given handle that has +already been bound to a port, a Unix domain socket, or a Windows named pipe.

      +

      The handle object can be either a server, a socket (anything with an +underlying _handle member), or an object with an fd member that is a +valid file descriptor.

      +

      Listening on a file descriptor is not supported on Windows.

      +

      server.listen(options[, callback])#

      + + +

      If port is specified, it behaves the same as + +server.listen([port[, host[, backlog]]][, callback]). +Otherwise, if path is specified, it behaves the same as +server.listen(path[, backlog][, callback]). +If none of them is specified, an error will be thrown.

      +

      If exclusive is false (default), then cluster workers will use the same +underlying handle, allowing connection handling duties to be shared. When +exclusive is true, the handle is not shared, and attempted port sharing +results in an error. An example which listens on an exclusive port is +shown below.

      +
      server.listen({
      +  host: 'localhost',
      +  port: 80,
      +  exclusive: true
      +});
      +

      Starting an IPC server as root may cause the server path to be inaccessible for +unprivileged users. Using readableAll and writableAll will make the server +accessible for all users.

      +

      server.listen(path[, backlog][, callback])#

      + + +

      Start an IPC server listening for connections on the given path.

      +

      server.listen([port[, host[, backlog]]][, callback])#

      + + +

      Start a TCP server listening for connections on the given port and host.

      +

      If port is omitted or is 0, the operating system will assign an arbitrary +unused port, which can be retrieved by using server.address().port +after the 'listening' event has been emitted.

      +

      If host is omitted, the server will accept connections on the +unspecified IPv6 address (::) when IPv6 is available, or the +unspecified IPv4 address (0.0.0.0) otherwise.

      +

      In most operating systems, listening to the unspecified IPv6 address (::) +may cause the net.Server to also listen on the unspecified IPv4 address +(0.0.0.0).

      +

      server.listening#

      + +
        +
      • <boolean> Indicates whether or not the server is listening for connections.
      • +
      +

      server.maxConnections#

      + + +

      Set this property to reject connections when the server's connection count gets +high.

      +

      It is not recommended to use this option once a socket has been sent to a child +with child_process.fork().

      +

      server.ref()#

      + + +

      Opposite of unref(), calling ref() on a previously unrefed server will +not let the program exit if it's the only server left (the default behavior). +If the server is refed calling ref() again will have no effect.

      +

      server.unref()#

      + + +

      Calling unref() on a server will allow the program to exit if this is the only +active server in the event system. If the server is already unrefed calling +unref() again will have no effect.

      +

      Class: net.Socket#

      + + +

      This class is an abstraction of a TCP socket or a streaming IPC endpoint +(uses named pipes on Windows, and Unix domain sockets otherwise). It is also +an EventEmitter.

      +

      A net.Socket can be created by the user and used directly to interact with +a server. For example, it is returned by net.createConnection(), +so the user can use it to talk to the server.

      +

      It can also be created by Node.js and passed to the user when a connection +is received. For example, it is passed to the listeners of a +'connection' event emitted on a net.Server, so the user can use +it to interact with the client.

      +

      new net.Socket([options])#

      + +
        +
      • options <Object> Available options are: +
          +
        • fd <number> If specified, wrap around an existing socket with +the given file descriptor, otherwise a new socket will be created.
        • +
        • allowHalfOpen <boolean> Indicates whether half-opened TCP connections +are allowed. See net.createServer() and the 'end' event +for details. Default: false.
        • +
        • readable <boolean> Allow reads on the socket when an fd is passed, +otherwise ignored. Default: false.
        • +
        • writable <boolean> Allow writes on the socket when an fd is passed, +otherwise ignored. Default: false.
        • +
        +
      • +
      • Returns: <net.Socket>
      • +
      +

      Creates a new socket object.

      +

      The newly created socket can be either a TCP socket or a streaming IPC +endpoint, depending on what it connect() to.

      +

      Event: 'close'#

      + +
        +
      • hadError <boolean> true if the socket had a transmission error.
      • +
      +

      Emitted once the socket is fully closed. The argument hadError is a boolean +which says if the socket was closed due to a transmission error.

      +

      Event: 'connect'#

      + +

      Emitted when a socket connection is successfully established. +See net.createConnection().

      +

      Event: 'data'#

      + + +

      Emitted when data is received. The argument data will be a Buffer or +String. Encoding of data is set by socket.setEncoding().

      +

      The data will be lost if there is no listener when a Socket +emits a 'data' event.

      +

      Event: 'drain'#

      + +

      Emitted when the write buffer becomes empty. Can be used to throttle uploads.

      +

      See also: the return values of socket.write().

      +

      Event: 'end'#

      + +

      Emitted when the other end of the socket sends a FIN packet, thus ending the +readable side of the socket.

      +

      By default (allowHalfOpen is false) the socket will send a FIN packet +back and destroy its file descriptor once it has written out its pending +write queue. However, if allowHalfOpen is set to true, the socket will +not automatically end() its writable side, allowing the +user to write arbitrary amounts of data. The user must call +end() explicitly to close the connection (i.e. sending a +FIN packet back).

      +

      Event: 'error'#

      + + +

      Emitted when an error occurs. The 'close' event will be called directly +following this event.

      +

      Event: 'lookup'#

      + +

      Emitted after resolving the host name but before connecting. +Not applicable to Unix sockets.

      + +

      Event: 'ready'#

      + +

      Emitted when a socket is ready to be used.

      +

      Triggered immediately after 'connect'.

      +

      Event: 'timeout'#

      + +

      Emitted if the socket times out from inactivity. This is only to notify that +the socket has been idle. The user must manually close the connection.

      +

      See also: socket.setTimeout().

      +

      socket.address()#

      + + +

      Returns the bound address, the address family name and port of the +socket as reported by the operating system: +{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

      +

      socket.bufferSize#

      + + +

      This property shows the number of characters buffered for writing. The buffer +may contain strings whose length after encoding is not yet known. So this number +is only an approximation of the number of bytes in the buffer.

      +

      net.Socket has the property that socket.write() always works. This is to +help users get up and running quickly. The computer cannot always keep up +with the amount of data that is written to a socket. The network connection +simply might be too slow. Node.js will internally queue up the data written to a +socket and send it out over the wire when it is possible.

      +

      The consequence of this internal buffering is that memory may grow. +Users who experience large or growing bufferSize should attempt to +"throttle" the data flows in their program with +socket.pause() and socket.resume().

      +

      socket.bytesRead#

      + + +

      The amount of received bytes.

      +

      socket.bytesWritten#

      + + +

      The amount of bytes sent.

      +

      socket.connect()#

      +

      Initiate a connection on a given socket.

      +

      Possible signatures:

      + +

      This function is asynchronous. When the connection is established, the +'connect' event will be emitted. If there is a problem connecting, +instead of a 'connect' event, an 'error' event will be emitted with +the error passed to the 'error' listener. +The last parameter connectListener, if supplied, will be added as a listener +for the 'connect' event once.

      +

      This function should only be used for reconnecting a socket after +'close' has been emitted or otherwise it may lead to undefined +behavior.

      +

      socket.connect(options[, connectListener])#

      + + +

      Initiate a connection on a given socket. Normally this method is not needed, +the socket should be created and opened with net.createConnection(). Use +this only when implementing a custom Socket.

      +

      For TCP connections, available options are:

      +
        +
      • port <number> Required. Port the socket should connect to.
      • +
      • host <string> Host the socket should connect to. Default: 'localhost'.
      • +
      • localAddress <string> Local address the socket should connect from.
      • +
      • localPort <number> Local port the socket should connect from.
      • +
      • family <number>: Version of IP stack. Must be 4, 6, or 0. The value +0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.
      • +
      • hints <number> Optional dns.lookup() hints.
      • +
      • lookup <Function> Custom lookup function. Default: dns.lookup().
      • +
      +

      For IPC connections, available options are:

      + +

      For both types, available options include:

      +
        +
      • onread <Object> If specified, incoming data is stored in a single buffer +and passed to the supplied callback when data arrives on the socket. +This will cause the streaming functionality to not provide any data. +The socket will emit events like 'error', 'end', and 'close' +as usual. Methods like pause() and resume() will also behave as +expected. +
          +
        • buffer <Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to +use for storing incoming data or a function that returns such.
        • +
        • callback <Function> This function is called for every chunk of incoming +data. Two arguments are passed to it: the number of bytes written to +buffer and a reference to buffer. Return false from this function to +implicitly pause() the socket. This function will be executed in the +global context.
        • +
        +
      • +
      +

      Following is an example of a client using the onread option:

      +
      const net = require('net');
      +net.connect({
      +  port: 80,
      +  onread: {
      +    // Reuses a 4KiB Buffer for every read from the socket.
      +    buffer: Buffer.alloc(4 * 1024),
      +    callback: function(nread, buf) {
      +      // Received data is available in `buf` from 0 to `nread`.
      +      console.log(buf.toString('utf8', 0, nread));
      +    }
      +  }
      +});
      +

      socket.connect(path[, connectListener])#

      + +

      Initiate an IPC connection on the given socket.

      +

      Alias to +socket.connect(options[, connectListener]) +called with { path: path } as options.

      +

      socket.connect(port[, host][, connectListener])#

      + + +

      Initiate a TCP connection on the given socket.

      +

      Alias to +socket.connect(options[, connectListener]) +called with {port: port, host: host} as options.

      +

      socket.connecting#

      + + +

      If true, +socket.connect(options[, connectListener]) was +called and has not yet finished. It will stay true until the socket becomes +connected, then it is set to false and the 'connect' event is emitted. Note +that the +socket.connect(options[, connectListener]) +callback is a listener for the 'connect' event.

      +

      socket.destroy([error])#

      + + +

      Ensures that no more I/O activity happens on this socket. +Destroys the stream and closes the connection.

      +

      See writable.destroy() for further details.

      +

      socket.destroyed#

      +
        +
      • <boolean> Indicates if the connection is destroyed or not. Once a +connection is destroyed no further data can be transferred using it.
      • +
      +

      See writable.destroyed for further details.

      +

      socket.end([data[, encoding]][, callback])#

      + + +

      Half-closes the socket. i.e., it sends a FIN packet. It is possible the +server will still send some data.

      +

      See writable.end() for further details.

      +

      socket.localAddress#

      + + +

      The string representation of the local IP address the remote client is +connecting on. For example, in a server listening on '0.0.0.0', if a client +connects on '192.168.1.1', the value of socket.localAddress would be +'192.168.1.1'.

      +

      socket.localPort#

      + + +

      The numeric representation of the local port. For example, 80 or 21.

      +

      socket.pause()#

      + +

      Pauses the reading of data. That is, 'data' events will not be emitted. +Useful to throttle back an upload.

      +

      socket.pending#

      + + +

      This is true if the socket is not connected yet, either because .connect() +has not yet been called or because it is still in the process of connecting +(see socket.connecting).

      +

      socket.ref()#

      + + +

      Opposite of unref(), calling ref() on a previously unrefed socket will +not let the program exit if it's the only socket left (the default behavior). +If the socket is refed calling ref again will have no effect.

      +

      socket.remoteAddress#

      + + +

      The string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if +the socket is destroyed (for example, if the client disconnected).

      +

      socket.remoteFamily#

      + + +

      The string representation of the remote IP family. 'IPv4' or 'IPv6'.

      +

      socket.remotePort#

      + + +

      The numeric representation of the remote port. For example, 80 or 21.

      +

      socket.resume()#

      + +

      Resumes reading after a call to socket.pause().

      +

      socket.setEncoding([encoding])#

      + + +

      Set the encoding for the socket as a Readable Stream. See +readable.setEncoding() for more information.

      +

      socket.setKeepAlive([enable][, initialDelay])#

      + + +

      Enable/disable keep-alive functionality, and optionally set the initial +delay before the first keepalive probe is sent on an idle socket.

      +

      Set initialDelay (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting 0 for +initialDelay will leave the value unchanged from the default +(or previous) setting.

      +

      socket.setNoDelay([noDelay])#

      + + +

      Enable/disable the use of Nagle's algorithm.

      +

      When a TCP connection is created, it will have Nagle's algorithm enabled.

      +

      Nagle's algorithm delays data before it is sent via the network. It attempts +to optimize throughput at the expense of latency.

      +

      Passing true for noDelay or not passing an argument will disable Nagle's +algorithm for the socket. Passing false for noDelay will enable Nagle's +algorithm.

      +

      socket.setTimeout(timeout[, callback])#

      + + +

      Sets the socket to timeout after timeout milliseconds of inactivity on +the socket. By default net.Socket do not have a timeout.

      +

      When an idle timeout is triggered the socket will receive a 'timeout' +event but the connection will not be severed. The user must manually call +socket.end() or socket.destroy() to end the connection.

      +
      socket.setTimeout(3000);
      +socket.on('timeout', () => {
      +  console.log('socket timeout');
      +  socket.end();
      +});
      +

      If timeout is 0, then the existing idle timeout is disabled.

      +

      The optional callback parameter will be added as a one-time listener for the +'timeout' event.

      +

      socket.unref()#

      + + +

      Calling unref() on a socket will allow the program to exit if this is the only +active socket in the event system. If the socket is already unrefed calling +unref() again will have no effect.

      +

      socket.write(data[, encoding][, callback])#

      + + +

      Sends data on the socket. The second parameter specifies the encoding in the +case of a string. It defaults to UTF8 encoding.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is again free.

      +

      The optional callback parameter will be executed when the data is finally +written out, which may not be immediately.

      +

      See Writable stream write() method for more +information.

      +

      net.connect()#

      +

      Aliases to +net.createConnection().

      +

      Possible signatures:

      + +

      net.connect(options[, connectListener])#

      + + +

      Alias to +net.createConnection(options[, connectListener]).

      +

      net.connect(path[, connectListener])#

      + + +

      Alias to +net.createConnection(path[, connectListener]).

      +

      net.connect(port[, host][, connectListener])#

      + + +

      Alias to +net.createConnection(port[, host][, connectListener]).

      +

      net.createConnection()#

      +

      A factory function, which creates a new net.Socket, +immediately initiates connection with socket.connect(), +then returns the net.Socket that starts the connection.

      +

      When the connection is established, a 'connect' event will be emitted +on the returned socket. The last parameter connectListener, if supplied, +will be added as a listener for the 'connect' event once.

      +

      Possible signatures:

      + +

      The net.connect() function is an alias to this function.

      +

      net.createConnection(options[, connectListener])#

      + + +

      For available options, see +new net.Socket([options]) +and socket.connect(options[, connectListener]).

      +

      Additional options:

      + +

      Following is an example of a client of the echo server described +in the net.createServer() section:

      +
      const net = require('net');
      +const client = net.createConnection({ port: 8124 }, () => {
      +  // 'connect' listener.
      +  console.log('connected to server!');
      +  client.write('world!\r\n');
      +});
      +client.on('data', (data) => {
      +  console.log(data.toString());
      +  client.end();
      +});
      +client.on('end', () => {
      +  console.log('disconnected from server');
      +});
      +

      To connect on the socket /tmp/echo.sock:

      +
      const client = net.createConnection({ path: '/tmp/echo.sock' });
      +

      net.createConnection(path[, connectListener])#

      + + +

      Initiates an IPC connection.

      +

      This function creates a new net.Socket with all options set to default, +immediately initiates connection with +socket.connect(path[, connectListener]), +then returns the net.Socket that starts the connection.

      +

      net.createConnection(port[, host][, connectListener])#

      + + +

      Initiates a TCP connection.

      +

      This function creates a new net.Socket with all options set to default, +immediately initiates connection with +socket.connect(port[, host][, connectListener]), +then returns the net.Socket that starts the connection.

      +

      net.createServer([options][, connectionListener])#

      + +
        +
      • options <Object> +
          +
        • allowHalfOpen <boolean> Indicates whether half-opened TCP +connections are allowed. Default: false.
        • +
        • pauseOnConnect <boolean> Indicates whether the socket should be +paused on incoming connections. Default: false.
        • +
        +
      • +
      • connectionListener <Function> Automatically set as a listener for the +'connection' event.
      • +
      • Returns: <net.Server>
      • +
      +

      Creates a new TCP or IPC server.

      +

      If allowHalfOpen is set to true, when the other end of the socket +sends a FIN packet, the server will only send a FIN packet back when +socket.end() is explicitly called, until then the connection is +half-closed (non-readable but still writable). See 'end' event +and RFC 1122 (section 4.2.2.13) for more information.

      +

      If pauseOnConnect is set to true, then the socket associated with each +incoming connection will be paused, and no data will be read from its handle. +This allows connections to be passed between processes without any data being +read by the original process. To begin reading data from a paused socket, call +socket.resume().

      +

      The server can be a TCP server or an IPC server, depending on what it +listen() to.

      +

      Here is an example of an TCP echo server which listens for connections +on port 8124:

      +
      const net = require('net');
      +const server = net.createServer((c) => {
      +  // 'connection' listener.
      +  console.log('client connected');
      +  c.on('end', () => {
      +    console.log('client disconnected');
      +  });
      +  c.write('hello\r\n');
      +  c.pipe(c);
      +});
      +server.on('error', (err) => {
      +  throw err;
      +});
      +server.listen(8124, () => {
      +  console.log('server bound');
      +});
      +

      Test this by using telnet:

      +
      $ telnet localhost 8124
      +

      To listen on the socket /tmp/echo.sock:

      +
      server.listen('/tmp/echo.sock', () => {
      +  console.log('server bound');
      +});
      +

      Use nc to connect to a Unix domain socket server:

      +
      $ nc -U /tmp/echo.sock
      +

      net.isIP(input)#

      + + +

      Tests if input is an IP address. Returns 0 for invalid strings, +returns 4 for IP version 4 addresses, and returns 6 for IP version 6 +addresses.

      +

      net.isIPv4(input)#

      + + +

      Returns true if input is a version 4 IP address, otherwise returns false.

      +

      net.isIPv6(input)#

      + + +

      Returns true if input is a version 6 IP address, otherwise returns false.

      +

      OS#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/os.js

      +

      The os module provides operating system-related utility methods and +properties. It can be accessed using:

      +
      const os = require('os');
      +

      os.EOL#

      + + +

      The operating system-specific end-of-line marker.

      +
        +
      • \n on POSIX
      • +
      • \r\n on Windows
      • +
      +

      os.arch()#

      + + +

      Returns the operating system CPU architecture for which the Node.js binary was +compiled. Possible values are 'arm', 'arm64', 'ia32', 'mips', +'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

      +

      The return value is equivalent to process.arch.

      +

      os.constants#

      + + +

      Contains commonly used operating system-specific constants for error codes, +process signals, and so on. The specific constants defined are described in +OS constants.

      +

      os.cpus()#

      + + +

      Returns an array of objects containing information about each logical CPU core.

      +

      The properties included on each object include:

      +
        +
      • model <string>
      • +
      • speed <number> (in MHz)
      • +
      • times <Object> +
          +
        • user <number> The number of milliseconds the CPU has spent in user mode.
        • +
        • nice <number> The number of milliseconds the CPU has spent in nice mode.
        • +
        • sys <number> The number of milliseconds the CPU has spent in sys mode.
        • +
        • idle <number> The number of milliseconds the CPU has spent in idle mode.
        • +
        • irq <number> The number of milliseconds the CPU has spent in irq mode.
        • +
        +
      • +
      + +
      [
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 252020,
      +      nice: 0,
      +      sys: 30340,
      +      idle: 1070356870,
      +      irq: 0
      +    }
      +  },
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 306960,
      +      nice: 0,
      +      sys: 26980,
      +      idle: 1071569080,
      +      irq: 0
      +    }
      +  },
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 248450,
      +      nice: 0,
      +      sys: 21750,
      +      idle: 1070919370,
      +      irq: 0
      +    }
      +  },
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 256880,
      +      nice: 0,
      +      sys: 19430,
      +      idle: 1070905480,
      +      irq: 20
      +    }
      +  }
      +]
      +

      nice values are POSIX-only. On Windows, the nice values of all processors +are always 0.

      +

      os.endianness()#

      + + +

      Returns a string identifying the endianness of the CPU for which the Node.js +binary was compiled.

      +

      Possible values are 'BE' for big endian and 'LE' for little endian.

      +

      os.freemem()#

      + + +

      Returns the amount of free system memory in bytes as an integer.

      +

      os.getPriority([pid])#

      + +
        +
      • pid <integer> The process ID to retrieve scheduling priority for. +Default 0.
      • +
      • Returns: <integer>
      • +
      +

      Returns the scheduling priority for the process specified by pid. If pid is +not provided or is 0, the priority of the current process is returned.

      +

      os.homedir()#

      + + +

      Returns the string path of the current user's home directory.

      +

      On POSIX, it uses the $HOME environment variable if defined. Otherwise it +uses the effective UID to look up the user's home directory.

      +

      On Windows, it uses the USERPROFILE environment variable if defined. +Otherwise it uses the path to the profile directory of the current user.

      +

      os.hostname()#

      + + +

      Returns the host name of the operating system as a string.

      +

      os.loadavg()#

      + + +

      Returns an array containing the 1, 5, and 15 minute load averages.

      +

      The load average is a measure of system activity calculated by the operating +system and expressed as a fractional number.

      +

      The load average is a Unix-specific concept. On Windows, the return value is +always [0, 0, 0].

      +

      os.networkInterfaces()#

      + + +

      Returns an object containing network interfaces that have been assigned a +network address.

      +

      Each key on the returned object identifies a network interface. The associated +value is an array of objects that each describe an assigned network address.

      +

      The properties available on the assigned network address object include:

      +
        +
      • address <string> The assigned IPv4 or IPv6 address
      • +
      • netmask <string> The IPv4 or IPv6 network mask
      • +
      • family <string> Either IPv4 or IPv6
      • +
      • mac <string> The MAC address of the network interface
      • +
      • internal <boolean> true if the network interface is a loopback or +similar interface that is not remotely accessible; otherwise false
      • +
      • scopeid <number> The numeric IPv6 scope ID (only specified when family +is IPv6)
      • +
      • cidr <string> The assigned IPv4 or IPv6 address with the routing prefix +in CIDR notation. If the netmask is invalid, this property is set +to null.
      • +
      + +
      {
      +  lo: [
      +    {
      +      address: '127.0.0.1',
      +      netmask: '255.0.0.0',
      +      family: 'IPv4',
      +      mac: '00:00:00:00:00:00',
      +      internal: true,
      +      cidr: '127.0.0.1/8'
      +    },
      +    {
      +      address: '::1',
      +      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      +      family: 'IPv6',
      +      mac: '00:00:00:00:00:00',
      +      scopeid: 0,
      +      internal: true,
      +      cidr: '::1/128'
      +    }
      +  ],
      +  eth0: [
      +    {
      +      address: '192.168.1.108',
      +      netmask: '255.255.255.0',
      +      family: 'IPv4',
      +      mac: '01:02:03:0a:0b:0c',
      +      internal: false,
      +      cidr: '192.168.1.108/24'
      +    },
      +    {
      +      address: 'fe80::a00:27ff:fe4e:66a1',
      +      netmask: 'ffff:ffff:ffff:ffff::',
      +      family: 'IPv6',
      +      mac: '01:02:03:0a:0b:0c',
      +      scopeid: 1,
      +      internal: false,
      +      cidr: 'fe80::a00:27ff:fe4e:66a1/64'
      +    }
      +  ]
      +}
      +

      os.platform()#

      + + +

      Returns a string identifying the operating system platform. The value is set +at compile time. Possible values are 'aix', 'darwin', 'freebsd', +'linux', 'openbsd', 'sunos', and 'win32'.

      +

      The return value is equivalent to process.platform.

      +

      The value 'android' may also be returned if Node.js is built on the Android +operating system. Android support is experimental.

      +

      os.release()#

      + + +

      Returns the operating system as a string.

      +

      On POSIX systems, the operating system release is determined by calling +uname(3). On Windows, GetVersionExW() is used. See +https://en.wikipedia.org/wiki/Uname#Examples for more information.

      +

      os.setPriority([pid, ]priority)#

      + +
        +
      • pid <integer> The process ID to set scheduling priority for. +Default 0.
      • +
      • priority <integer> The scheduling priority to assign to the process.
      • +
      +

      Attempts to set the scheduling priority for the process specified by pid. If +pid is not provided or is 0, the process ID of the current process is used.

      +

      The priority input must be an integer between -20 (high priority) and 19 +(low priority). Due to differences between Unix priority levels and Windows +priority classes, priority is mapped to one of six priority constants in +os.constants.priority. When retrieving a process priority level, this range +mapping may cause the return value to be slightly different on Windows. To avoid +confusion, set priority to one of the priority constants.

      +

      On Windows, setting priority to PRIORITY_HIGHEST requires elevated user +privileges. Otherwise the set priority will be silently reduced to +PRIORITY_HIGH.

      +

      os.tmpdir()#

      + + +

      Returns the operating system's default directory for temporary files as a +string.

      +

      os.totalmem()#

      + + +

      Returns the total amount of system memory in bytes as an integer.

      +

      os.type()#

      + + +

      Returns the operating system name as returned by uname(3). For example, it +returns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows.

      +

      See https://en.wikipedia.org/wiki/Uname#Examples for additional information +about the output of running uname(3) on various operating systems.

      +

      os.uptime()#

      + + +

      Returns the system uptime in number of seconds.

      +

      os.userInfo([options])#

      + +
        +
      • options <Object> +
          +
        • encoding <string> Character encoding used to interpret resulting strings. +If encoding is set to 'buffer', the username, shell, and homedir +values will be Buffer instances. Default: 'utf8'.
        • +
        +
      • +
      • Returns: <Object>
      • +
      +

      Returns information about the currently effective user. On POSIX platforms, +this is typically a subset of the password file. The returned object includes +the username, uid, gid, shell, and homedir. On Windows, the uid and +gid fields are -1, and shell is null.

      +

      The value of homedir returned by os.userInfo() is provided by the operating +system. This differs from the result of os.homedir(), which queries +environment variables for the home directory before falling back to the +operating system response.

      +

      Throws a SystemError if a user has no username or homedir.

      +

      os.version()#

      + + +

      Returns a string identifying the kernel version.

      +

      On POSIX systems, the operating system release is determined by calling +uname(3). On Windows, RtlGetVersion() is used, and if it is not +available, GetVersionExW() will be used. See +https://en.wikipedia.org/wiki/Uname#Examples for more information.

      +

      OS constants#

      +

      The following constants are exported by os.constants.

      +

      Not all constants will be available on every operating system.

      +

      Signal constants#

      + +

      The following signal constants are exported by os.constants.signals.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      SIGHUPSent to indicate when a controlling terminal is closed or a parent + process exits.
      SIGINTSent to indicate when a user wishes to interrupt a process + ((Ctrl+C)).
      SIGQUITSent to indicate when a user wishes to terminate a process and perform a + core dump.
      SIGILLSent to a process to notify that it has attempted to perform an illegal, + malformed, unknown, or privileged instruction.
      SIGTRAPSent to a process when an exception has occurred.
      SIGABRTSent to a process to request that it abort.
      SIGIOTSynonym for SIGABRT
      SIGBUSSent to a process to notify that it has caused a bus error.
      SIGFPESent to a process to notify that it has performed an illegal arithmetic + operation.
      SIGKILLSent to a process to terminate it immediately.
      SIGUSR1 SIGUSR2Sent to a process to identify user-defined conditions.
      SIGSEGVSent to a process to notify of a segmentation fault.
      SIGPIPESent to a process when it has attempted to write to a disconnected + pipe.
      SIGALRMSent to a process when a system timer elapses.
      SIGTERMSent to a process to request termination.
      SIGCHLDSent to a process when a child process terminates.
      SIGSTKFLTSent to a process to indicate a stack fault on a coprocessor.
      SIGCONTSent to instruct the operating system to continue a paused process.
      SIGSTOPSent to instruct the operating system to halt a process.
      SIGTSTPSent to a process to request it to stop.
      SIGBREAKSent to indicate when a user wishes to interrupt a process.
      SIGTTINSent to a process when it reads from the TTY while in the + background.
      SIGTTOUSent to a process when it writes to the TTY while in the + background.
      SIGURGSent to a process when a socket has urgent data to read.
      SIGXCPUSent to a process when it has exceeded its limit on CPU usage.
      SIGXFSZSent to a process when it grows a file larger than the maximum + allowed.
      SIGVTALRMSent to a process when a virtual timer has elapsed.
      SIGPROFSent to a process when a system timer has elapsed.
      SIGWINCHSent to a process when the controlling terminal has changed its + size.
      SIGIOSent to a process when I/O is available.
      SIGPOLLSynonym for SIGIO
      SIGLOSTSent to a process when a file lock has been lost.
      SIGPWRSent to a process to notify of a power failure.
      SIGINFOSynonym for SIGPWR
      SIGSYSSent to a process to notify of a bad argument.
      SIGUNUSEDSynonym for SIGSYS
      +

      Error constants#

      +

      The following error constants are exported by os.constants.errno.

      +

      POSIX error constants#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      E2BIGIndicates that the list of arguments is longer than expected.
      EACCESIndicates that the operation did not have sufficient permissions.
      EADDRINUSEIndicates that the network address is already in use.
      EADDRNOTAVAILIndicates that the network address is currently unavailable for + use.
      EAFNOSUPPORTIndicates that the network address family is not supported.
      EAGAINIndicates that there is no data available and to try the + operation again later.
      EALREADYIndicates that the socket already has a pending connection in + progress.
      EBADFIndicates that a file descriptor is not valid.
      EBADMSGIndicates an invalid data message.
      EBUSYIndicates that a device or resource is busy.
      ECANCELEDIndicates that an operation was canceled.
      ECHILDIndicates that there are no child processes.
      ECONNABORTEDIndicates that the network connection has been aborted.
      ECONNREFUSEDIndicates that the network connection has been refused.
      ECONNRESETIndicates that the network connection has been reset.
      EDEADLKIndicates that a resource deadlock has been avoided.
      EDESTADDRREQIndicates that a destination address is required.
      EDOMIndicates that an argument is out of the domain of the function.
      EDQUOTIndicates that the disk quota has been exceeded.
      EEXISTIndicates that the file already exists.
      EFAULTIndicates an invalid pointer address.
      EFBIGIndicates that the file is too large.
      EHOSTUNREACHIndicates that the host is unreachable.
      EIDRMIndicates that the identifier has been removed.
      EILSEQIndicates an illegal byte sequence.
      EINPROGRESSIndicates that an operation is already in progress.
      EINTRIndicates that a function call was interrupted.
      EINVALIndicates that an invalid argument was provided.
      EIOIndicates an otherwise unspecified I/O error.
      EISCONNIndicates that the socket is connected.
      EISDIRIndicates that the path is a directory.
      ELOOPIndicates too many levels of symbolic links in a path.
      EMFILEIndicates that there are too many open files.
      EMLINKIndicates that there are too many hard links to a file.
      EMSGSIZEIndicates that the provided message is too long.
      EMULTIHOPIndicates that a multihop was attempted.
      ENAMETOOLONGIndicates that the filename is too long.
      ENETDOWNIndicates that the network is down.
      ENETRESETIndicates that the connection has been aborted by the network.
      ENETUNREACHIndicates that the network is unreachable.
      ENFILEIndicates too many open files in the system.
      ENOBUFSIndicates that no buffer space is available.
      ENODATAIndicates that no message is available on the stream head read + queue.
      ENODEVIndicates that there is no such device.
      ENOENTIndicates that there is no such file or directory.
      ENOEXECIndicates an exec format error.
      ENOLCKIndicates that there are no locks available.
      ENOLINKIndications that a link has been severed.
      ENOMEMIndicates that there is not enough space.
      ENOMSGIndicates that there is no message of the desired type.
      ENOPROTOOPTIndicates that a given protocol is not available.
      ENOSPCIndicates that there is no space available on the device.
      ENOSRIndicates that there are no stream resources available.
      ENOSTRIndicates that a given resource is not a stream.
      ENOSYSIndicates that a function has not been implemented.
      ENOTCONNIndicates that the socket is not connected.
      ENOTDIRIndicates that the path is not a directory.
      ENOTEMPTYIndicates that the directory is not empty.
      ENOTSOCKIndicates that the given item is not a socket.
      ENOTSUPIndicates that a given operation is not supported.
      ENOTTYIndicates an inappropriate I/O control operation.
      ENXIOIndicates no such device or address.
      EOPNOTSUPPIndicates that an operation is not supported on the socket. Although + ENOTSUP and EOPNOTSUPP have the same value + on Linux, according to POSIX.1 these error values should be distinct.)
      EOVERFLOWIndicates that a value is too large to be stored in a given data + type.
      EPERMIndicates that the operation is not permitted.
      EPIPEIndicates a broken pipe.
      EPROTOIndicates a protocol error.
      EPROTONOSUPPORTIndicates that a protocol is not supported.
      EPROTOTYPEIndicates the wrong type of protocol for a socket.
      ERANGEIndicates that the results are too large.
      EROFSIndicates that the file system is read only.
      ESPIPEIndicates an invalid seek operation.
      ESRCHIndicates that there is no such process.
      ESTALEIndicates that the file handle is stale.
      ETIMEIndicates an expired timer.
      ETIMEDOUTIndicates that the connection timed out.
      ETXTBSYIndicates that a text file is busy.
      EWOULDBLOCKIndicates that the operation would block.
      EXDEVIndicates an improper link. +
      +

      Windows-specific error constants#

      +

      The following error codes are specific to the Windows operating system.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      WSAEINTRIndicates an interrupted function call.
      WSAEBADFIndicates an invalid file handle.
      WSAEACCESIndicates insufficient permissions to complete the operation.
      WSAEFAULTIndicates an invalid pointer address.
      WSAEINVALIndicates that an invalid argument was passed.
      WSAEMFILEIndicates that there are too many open files.
      WSAEWOULDBLOCKIndicates that a resource is temporarily unavailable.
      WSAEINPROGRESSIndicates that an operation is currently in progress.
      WSAEALREADYIndicates that an operation is already in progress.
      WSAENOTSOCKIndicates that the resource is not a socket.
      WSAEDESTADDRREQIndicates that a destination address is required.
      WSAEMSGSIZEIndicates that the message size is too long.
      WSAEPROTOTYPEIndicates the wrong protocol type for the socket.
      WSAENOPROTOOPTIndicates a bad protocol option.
      WSAEPROTONOSUPPORTIndicates that the protocol is not supported.
      WSAESOCKTNOSUPPORTIndicates that the socket type is not supported.
      WSAEOPNOTSUPPIndicates that the operation is not supported.
      WSAEPFNOSUPPORTIndicates that the protocol family is not supported.
      WSAEAFNOSUPPORTIndicates that the address family is not supported.
      WSAEADDRINUSEIndicates that the network address is already in use.
      WSAEADDRNOTAVAILIndicates that the network address is not available.
      WSAENETDOWNIndicates that the network is down.
      WSAENETUNREACHIndicates that the network is unreachable.
      WSAENETRESETIndicates that the network connection has been reset.
      WSAECONNABORTEDIndicates that the connection has been aborted.
      WSAECONNRESETIndicates that the connection has been reset by the peer.
      WSAENOBUFSIndicates that there is no buffer space available.
      WSAEISCONNIndicates that the socket is already connected.
      WSAENOTCONNIndicates that the socket is not connected.
      WSAESHUTDOWNIndicates that data cannot be sent after the socket has been + shutdown.
      WSAETOOMANYREFSIndicates that there are too many references.
      WSAETIMEDOUTIndicates that the connection has timed out.
      WSAECONNREFUSEDIndicates that the connection has been refused.
      WSAELOOPIndicates that a name cannot be translated.
      WSAENAMETOOLONGIndicates that a name was too long.
      WSAEHOSTDOWNIndicates that a network host is down.
      WSAEHOSTUNREACHIndicates that there is no route to a network host.
      WSAENOTEMPTYIndicates that the directory is not empty.
      WSAEPROCLIMIndicates that there are too many processes.
      WSAEUSERSIndicates that the user quota has been exceeded.
      WSAEDQUOTIndicates that the disk quota has been exceeded.
      WSAESTALEIndicates a stale file handle reference.
      WSAEREMOTEIndicates that the item is remote.
      WSASYSNOTREADYIndicates that the network subsystem is not ready.
      WSAVERNOTSUPPORTEDIndicates that the winsock.dll version is out of + range.
      WSANOTINITIALISEDIndicates that successful WSAStartup has not yet been performed.
      WSAEDISCONIndicates that a graceful shutdown is in progress.
      WSAENOMOREIndicates that there are no more results.
      WSAECANCELLEDIndicates that an operation has been canceled.
      WSAEINVALIDPROCTABLEIndicates that the procedure call table is invalid.
      WSAEINVALIDPROVIDERIndicates an invalid service provider.
      WSAEPROVIDERFAILEDINITIndicates that the service provider failed to initialized.
      WSASYSCALLFAILUREIndicates a system call failure.
      WSASERVICE_NOT_FOUNDIndicates that a service was not found.
      WSATYPE_NOT_FOUNDIndicates that a class type was not found.
      WSA_E_NO_MOREIndicates that there are no more results.
      WSA_E_CANCELLEDIndicates that the call was canceled.
      WSAEREFUSEDIndicates that a database query was refused.
      +

      dlopen constants#

      +

      If available on the operating system, the following constants +are exported in os.constants.dlopen. See dlopen(3) for detailed +information.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      RTLD_LAZYPerform lazy binding. Node.js sets this flag by default.
      RTLD_NOWResolve all undefined symbols in the library before dlopen(3) + returns.
      RTLD_GLOBALSymbols defined by the library will be made available for symbol + resolution of subsequently loaded libraries.
      RTLD_LOCALThe converse of RTLD_GLOBAL. This is the default behavior + if neither flag is specified.
      RTLD_DEEPBINDMake a self-contained library use its own symbols in preference to + symbols from previously loaded libraries.
      +

      Priority constants#

      + +

      The following process scheduling constants are exported by +os.constants.priority.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      PRIORITY_LOWThe lowest process scheduling priority. This corresponds to + IDLE_PRIORITY_CLASS on Windows, and a nice value of + 19 on all other platforms.
      PRIORITY_BELOW_NORMALThe process scheduling priority above PRIORITY_LOW and + below PRIORITY_NORMAL. This corresponds to + BELOW_NORMAL_PRIORITY_CLASS on Windows, and a nice value of + 10 on all other platforms.
      PRIORITY_NORMALThe default process scheduling priority. This corresponds to + NORMAL_PRIORITY_CLASS on Windows, and a nice value of + 0 on all other platforms.
      PRIORITY_ABOVE_NORMALThe process scheduling priority above PRIORITY_NORMAL and + below PRIORITY_HIGH. This corresponds to + ABOVE_NORMAL_PRIORITY_CLASS on Windows, and a nice value of + -7 on all other platforms.
      PRIORITY_HIGHThe process scheduling priority above PRIORITY_ABOVE_NORMAL + and below PRIORITY_HIGHEST. This corresponds to + HIGH_PRIORITY_CLASS on Windows, and a nice value of + -14 on all other platforms.
      PRIORITY_HIGHESTThe highest process scheduling priority. This corresponds to + REALTIME_PRIORITY_CLASS on Windows, and a nice value of + -20 on all other platforms.
      +

      libuv constants#

      + + + + + + + + + +
      ConstantDescription
      UV_UDP_REUSEADDR
      +

      Path#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/path.js

      +

      The path module provides utilities for working with file and directory paths. +It can be accessed using:

      +
      const path = require('path');
      +

      Windows vs. POSIX#

      +

      The default operation of the path module varies based on the operating system +on which a Node.js application is running. Specifically, when running on a +Windows operating system, the path module will assume that Windows-style +paths are being used.

      +

      So using path.basename() might yield different results on POSIX and Windows:

      +

      On POSIX:

      +
      path.basename('C:\\temp\\myfile.html');
      +// Returns: 'C:\\temp\\myfile.html'
      +

      On Windows:

      +
      path.basename('C:\\temp\\myfile.html');
      +// Returns: 'myfile.html'
      +

      To achieve consistent results when working with Windows file paths on any +operating system, use path.win32:

      +

      On POSIX and Windows:

      +
      path.win32.basename('C:\\temp\\myfile.html');
      +// Returns: 'myfile.html'
      +

      To achieve consistent results when working with POSIX file paths on any +operating system, use path.posix:

      +

      On POSIX and Windows:

      +
      path.posix.basename('/tmp/myfile.html');
      +// Returns: 'myfile.html'
      +

      On Windows Node.js follows the concept of per-drive working directory. +This behavior can be observed when using a drive path without a backslash. For +example, path.resolve('C:\\') can potentially return a different result than +path.resolve('C:'). For more information, see +this MSDN page.

      +

      path.basename(path[, ext])#

      + + +

      The path.basename() method returns the last portion of a path, similar to +the Unix basename command. Trailing directory separators are ignored, see +path.sep.

      +
      path.basename('/foo/bar/baz/asdf/quux.html');
      +// Returns: 'quux.html'
      +
      +path.basename('/foo/bar/baz/asdf/quux.html', '.html');
      +// Returns: 'quux'
      +

      Although Windows usually treats file names, including file extensions, in a +case-insensitive manner, this function does not. For example, C:\\foo.html and +C:\\foo.HTML refer to the same file, but basename treats the extension as a +case-sensitive string:

      +
      path.win32.basename('C:\\foo.html', '.html');
      +// Returns: 'foo'
      +
      +path.win32.basename('C:\\foo.HTML', '.html');
      +// Returns: 'foo.HTML'
      +

      A TypeError is thrown if path is not a string or if ext is given +and is not a string.

      +

      path.delimiter#

      + + +

      Provides the platform-specific path delimiter:

      +
        +
      • ; for Windows
      • +
      • : for POSIX
      • +
      +

      For example, on POSIX:

      +
      console.log(process.env.PATH);
      +// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
      +
      +process.env.PATH.split(path.delimiter);
      +// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
      +

      On Windows:

      +
      console.log(process.env.PATH);
      +// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
      +
      +process.env.PATH.split(path.delimiter);
      +// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
      +

      path.dirname(path)#

      + + +

      The path.dirname() method returns the directory name of a path, similar to +the Unix dirname command. Trailing directory separators are ignored, see +path.sep.

      +
      path.dirname('/foo/bar/baz/asdf/quux');
      +// Returns: '/foo/bar/baz/asdf'
      +

      A TypeError is thrown if path is not a string.

      +

      path.extname(path)#

      + + +

      The path.extname() method returns the extension of the path, from the last +occurrence of the . (period) character to end of string in the last portion of +the path. If there is no . in the last portion of the path, or if +there are no . characters other than the first character of +the basename of path (see path.basename()) , an empty string is returned.

      +
      path.extname('index.html');
      +// Returns: '.html'
      +
      +path.extname('index.coffee.md');
      +// Returns: '.md'
      +
      +path.extname('index.');
      +// Returns: '.'
      +
      +path.extname('index');
      +// Returns: ''
      +
      +path.extname('.index');
      +// Returns: ''
      +
      +path.extname('.index.md');
      +// Returns: '.md'
      +

      A TypeError is thrown if path is not a string.

      +

      path.format(pathObject)#

      + + +

      The path.format() method returns a path string from an object. This is the +opposite of path.parse().

      +

      When providing properties to the pathObject remember that there are +combinations where one property has priority over another:

      +
        +
      • pathObject.root is ignored if pathObject.dir is provided
      • +
      • pathObject.ext and pathObject.name are ignored if pathObject.base exists
      • +
      +

      For example, on POSIX:

      +
      // If `dir`, `root` and `base` are provided,
      +// `${dir}${path.sep}${base}`
      +// will be returned. `root` is ignored.
      +path.format({
      +  root: '/ignored',
      +  dir: '/home/user/dir',
      +  base: 'file.txt'
      +});
      +// Returns: '/home/user/dir/file.txt'
      +
      +// `root` will be used if `dir` is not specified.
      +// If only `root` is provided or `dir` is equal to `root` then the
      +// platform separator will not be included. `ext` will be ignored.
      +path.format({
      +  root: '/',
      +  base: 'file.txt',
      +  ext: 'ignored'
      +});
      +// Returns: '/file.txt'
      +
      +// `name` + `ext` will be used if `base` is not specified.
      +path.format({
      +  root: '/',
      +  name: 'file',
      +  ext: '.txt'
      +});
      +// Returns: '/file.txt'
      +

      On Windows:

      +
      path.format({
      +  dir: 'C:\\path\\dir',
      +  base: 'file.txt'
      +});
      +// Returns: 'C:\\path\\dir\\file.txt'
      +

      path.isAbsolute(path)#

      + + +

      The path.isAbsolute() method determines if path is an absolute path.

      +

      If the given path is a zero-length string, false will be returned.

      +

      For example, on POSIX:

      +
      path.isAbsolute('/foo/bar'); // true
      +path.isAbsolute('/baz/..');  // true
      +path.isAbsolute('qux/');     // false
      +path.isAbsolute('.');        // false
      +

      On Windows:

      +
      path.isAbsolute('//server');    // true
      +path.isAbsolute('\\\\server');  // true
      +path.isAbsolute('C:/foo/..');   // true
      +path.isAbsolute('C:\\foo\\..'); // true
      +path.isAbsolute('bar\\baz');    // false
      +path.isAbsolute('bar/baz');     // false
      +path.isAbsolute('.');           // false
      +

      A TypeError is thrown if path is not a string.

      +

      path.join([...paths])#

      + + +

      The path.join() method joins all given path segments together using the +platform-specific separator as a delimiter, then normalizes the resulting path.

      +

      Zero-length path segments are ignored. If the joined path string is a +zero-length string then '.' will be returned, representing the current +working directory.

      +
      path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
      +// Returns: '/foo/bar/baz/asdf'
      +
      +path.join('foo', {}, 'bar');
      +// Throws 'TypeError: Path must be a string. Received {}'
      +

      A TypeError is thrown if any of the path segments is not a string.

      +

      path.normalize(path)#

      + + +

      The path.normalize() method normalizes the given path, resolving '..' and +'.' segments.

      +

      When multiple, sequential path segment separation characters are found (e.g. +/ on POSIX and either \ or / on Windows), they are replaced by a single +instance of the platform-specific path segment separator (/ on POSIX and +\ on Windows). Trailing separators are preserved.

      +

      If the path is a zero-length string, '.' is returned, representing the +current working directory.

      +

      For example, on POSIX:

      +
      path.normalize('/foo/bar//baz/asdf/quux/..');
      +// Returns: '/foo/bar/baz/asdf'
      +

      On Windows:

      +
      path.normalize('C:\\temp\\\\foo\\bar\\..\\');
      +// Returns: 'C:\\temp\\foo\\'
      +

      Since Windows recognizes multiple path separators, both separators will be +replaced by instances of the Windows preferred separator (\):

      +
      path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
      +// Returns: 'C:\\temp\\foo\\bar'
      +

      A TypeError is thrown if path is not a string.

      +

      path.parse(path)#

      + + +

      The path.parse() method returns an object whose properties represent +significant elements of the path. Trailing directory separators are ignored, +see path.sep.

      +

      The returned object will have the following properties:

      + +

      For example, on POSIX:

      +
      path.parse('/home/user/dir/file.txt');
      +// Returns:
      +// { root: '/',
      +//   dir: '/home/user/dir',
      +//   base: 'file.txt',
      +//   ext: '.txt',
      +//   name: 'file' }
      +
      ┌─────────────────────┬────────────â”
      +│          dir        │    base    │
      +├──────┬              ├──────┬─────┤
      +│ root │              │ name │ ext │
      +"  /    home/user/dir / file  .txt "
      +└──────┴──────────────┴──────┴─────┘
      +(All spaces in the "" line should be ignored. They are purely for formatting.)
      +

      On Windows:

      +
      path.parse('C:\\path\\dir\\file.txt');
      +// Returns:
      +// { root: 'C:\\',
      +//   dir: 'C:\\path\\dir',
      +//   base: 'file.txt',
      +//   ext: '.txt',
      +//   name: 'file' }
      +
      ┌─────────────────────┬────────────â”
      +│          dir        │    base    │
      +├──────┬              ├──────┬─────┤
      +│ root │              │ name │ ext │
      +" C:\      path\dir   \ file  .txt "
      +└──────┴──────────────┴──────┴─────┘
      +(All spaces in the "" line should be ignored. They are purely for formatting.)
      +

      A TypeError is thrown if path is not a string.

      +

      path.posix#

      + + +

      The path.posix property provides access to POSIX specific implementations +of the path methods.

      +

      path.relative(from, to)#

      + + +

      The path.relative() method returns the relative path from from to to based +on the current working directory. If from and to each resolve to the same +path (after calling path.resolve() on each), a zero-length string is returned.

      +

      If a zero-length string is passed as from or to, the current working +directory will be used instead of the zero-length strings.

      +

      For example, on POSIX:

      +
      path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
      +// Returns: '../../impl/bbb'
      +

      On Windows:

      +
      path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
      +// Returns: '..\\..\\impl\\bbb'
      +

      A TypeError is thrown if either from or to is not a string.

      +

      path.resolve([...paths])#

      + + +

      The path.resolve() method resolves a sequence of paths or path segments into +an absolute path.

      +

      The given sequence of paths is processed from right to left, with each +subsequent path prepended until an absolute path is constructed. +For instance, given the sequence of path segments: /foo, /bar, baz, +calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz +because 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.

      +

      If, after processing all given path segments, an absolute path has not yet +been generated, the current working directory is used.

      +

      The resulting path is normalized and trailing slashes are removed unless the +path is resolved to the root directory.

      +

      Zero-length path segments are ignored.

      +

      If no path segments are passed, path.resolve() will return the absolute path +of the current working directory.

      +
      path.resolve('/foo/bar', './baz');
      +// Returns: '/foo/bar/baz'
      +
      +path.resolve('/foo/bar', '/tmp/file/');
      +// Returns: '/tmp/file'
      +
      +path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
      +// If the current working directory is /home/myself/node,
      +// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
      +

      A TypeError is thrown if any of the arguments is not a string.

      +

      path.sep#

      + + +

      Provides the platform-specific path segment separator:

      +
        +
      • \ on Windows
      • +
      • / on POSIX
      • +
      +

      For example, on POSIX:

      +
      'foo/bar/baz'.split(path.sep);
      +// Returns: ['foo', 'bar', 'baz']
      +

      On Windows:

      +
      'foo\\bar\\baz'.split(path.sep);
      +// Returns: ['foo', 'bar', 'baz']
      +

      On Windows, both the forward slash (/) and backward slash (\) are accepted +as path segment separators; however, the path methods only add backward +slashes (\).

      +

      path.toNamespacedPath(path)#

      + + +

      On Windows systems only, returns an equivalent namespace-prefixed path for +the given path. If path is not a string, path will be returned without +modifications.

      +

      This method is meaningful only on Windows systems. On POSIX systems, the +method is non-operational and always returns path without modifications.

      +

      path.win32#

      + + +

      The path.win32 property provides access to Windows-specific implementations +of the path methods.

      +

      Performance measurement APIs#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/perf_hooks.js

      +

      This module provides an implementation of a subset of the W3C +Web Performance APIs as well as additional APIs for +Node.js-specific performance measurements.

      +

      Node.js supports the following Web Performance APIs:

      + +
      const { PerformanceObserver, performance } = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((items) => {
      +  console.log(items.getEntries()[0].duration);
      +  performance.clearMarks();
      +});
      +obs.observe({ entryTypes: ['measure'] });
      +performance.measure('Start to Now');
      +
      +performance.mark('A');
      +doSomeLongRunningProcess(() => {
      +  performance.measure('A to Now', 'A');
      +
      +  performance.mark('B');
      +  performance.measure('A to B', 'A', 'B');
      +});
      +

      perf_hooks.performance#

      + +

      An object that can be used to collect performance metrics from the current +Node.js instance. It is similar to window.performance in browsers.

      +

      performance.clearMarks([name])#

      + + +

      If name is not provided, removes all PerformanceMark objects from the +Performance Timeline. If name is provided, removes only the named mark.

      +

      performance.eventLoopUtilization([utilization1[, utilization2]])#

      + +
        +
      • utilization1 <Object> The result of a previous call to + eventLoopUtilization().
      • +
      • utilization2 <Object> The result of a previous call to + eventLoopUtilization() prior to utilization1.
      • +
      • Returns <Object> + +
      • +
      +

      The eventLoopUtilization() method returns an object that contains the +cumulative duration of time the event loop has been both idle and active as a +high resolution milliseconds timer. The utilization value is the calculated +Event Loop Utilization (ELU).

      +

      If bootstrapping has not yet finished on the main thread the properties have +the value of 0. The ELU is immediately available on Worker threads since +bootstrap happens within the event loop.

      +

      Both utilization1 and utilization2 are optional parameters.

      +

      If utilization1 is passed, then the delta between the current call's active +and idle times, as well as the corresponding utilization value are +calculated and returned (similar to process.hrtime()).

      +

      If utilization1 and utilization2 are both passed, then the delta is +calculated between the two arguments. This is a convenience option because, +unlike process.hrtime(), calculating the ELU is more complex than a +single subtraction.

      +

      ELU is similar to CPU utilization, except that it only measures event loop +statistics and not CPU usage. It represents the percentage of time the event +loop has spent outside the event loop's event provider (e.g. epoll_wait). +No other CPU idle time is taken into consideration. The following is an example +of how a mostly idle process will have a high ELU.

      +
      'use strict';
      +const { eventLoopUtilization } = require('perf_hooks').performance;
      +const { spawnSync } = require('child_process');
      +
      +setImmediate(() => {
      +  const elu = eventLoopUtilization();
      +  spawnSync('sleep', ['5']);
      +  console.log(eventLoopUtilization(elu).utilization);
      +});
      +

      Although the CPU is mostly idle while running this script, the value of +utilization is 1. This is because the call to +child_process.spawnSync() blocks the event loop from proceeding.

      +

      Passing in a user-defined object instead of the result of a previous call to +eventLoopUtilization() will lead to undefined behavior. The return values +are not guaranteed to reflect any correct state of the event loop.

      +

      performance.mark([name])#

      + + +

      Creates a new PerformanceMark entry in the Performance Timeline. A +PerformanceMark is a subclass of PerformanceEntry whose +performanceEntry.entryType is always 'mark', and whose +performanceEntry.duration is always 0. Performance marks are used +to mark specific significant moments in the Performance Timeline.

      +

      performance.measure(name[, startMark[, endMark]])#

      + + +

      Creates a new PerformanceMeasure entry in the Performance Timeline. A +PerformanceMeasure is a subclass of PerformanceEntry whose +performanceEntry.entryType is always 'measure', and whose +performanceEntry.duration measures the number of milliseconds elapsed since +startMark and endMark.

      +

      The startMark argument may identify any existing PerformanceMark in the +Performance Timeline, or may identify any of the timestamp properties +provided by the PerformanceNodeTiming class. If the named startMark does +not exist, then startMark is set to timeOrigin by default.

      +

      The optional endMark argument must identify any existing PerformanceMark +in the Performance Timeline or any of the timestamp properties provided by the +PerformanceNodeTiming class. endMark will be performance.now() +if no parameter is passed, otherwise if the named endMark does not exist, an +error will be thrown.

      +

      performance.nodeTiming#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      An instance of the PerformanceNodeTiming class that provides performance +metrics for specific Node.js operational milestones.

      +

      performance.now()#

      + + +

      Returns the current high resolution millisecond timestamp, where 0 represents +the start of the current node process.

      +

      performance.timeOrigin#

      + + +

      The timeOrigin specifies the high resolution millisecond timestamp at +which the current node process began, measured in Unix time.

      +

      performance.timerify(fn)#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      Wraps a function within a new function that measures the running time of the +wrapped function. A PerformanceObserver must be subscribed to the 'function' +event type in order for the timing details to be accessed.

      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +function someFunction() {
      +  console.log('hello world');
      +}
      +
      +const wrapped = performance.timerify(someFunction);
      +
      +const obs = new PerformanceObserver((list) => {
      +  console.log(list.getEntries()[0].duration);
      +  obs.disconnect();
      +});
      +obs.observe({ entryTypes: ['function'] });
      +
      +// A performance timeline entry will be created
      +wrapped();
      +

      performance.eventLoopUtilization([util1][,util2])#

      + +
        +
      • util1 <Object> The result of a previous call to eventLoopUtilization()
      • +
      • util2 <Object> The result of a previous call to eventLoopUtilization() +prior to util1
      • +
      • Returns <Object> + +
      • +
      +

      The eventLoopUtilization() method returns an object that contains the +cumulative duration of time the event loop has been both idle and active as a +high resolution milliseconds timer. The utilization value is the calculated +Event Loop Utilization (ELU). If bootstrapping has not yet finished, the +properties have the value of 0.

      +

      util1 and util2 are optional parameters.

      +

      If util1 is passed then the delta between the current call's active and +idle times are calculated and returned (similar to process.hrtime()). +Likewise the adjusted utilization value is calculated.

      +

      If util1 and util2 are both passed then the calculation adjustments are +done between the two arguments. This is a convenience option because unlike +process.hrtime() additional work is done to calculate the ELU.

      +

      ELU is similar to CPU utilization except that it is calculated using high +precision wall-clock time. It represents the percentage of time the event loop +has spent outside the event loop's event provider (e.g. epoll_wait). No other +CPU idle time is taken into consideration. The following is an example of how +a mostly idle process will have a high ELU.

      + +
      'use strict';
      +const { eventLoopUtilization } = require('perf_hooks').performance;
      +const { spawnSync } = require('child_process');
      +
      +setImmediate(() => {
      +  const elu = eventLoopUtilization();
      +  spawnSync('sleep', ['5']);
      +  console.log(eventLoopUtilization(elu).utilization);
      +});
      +

      Although the CPU is mostly idle while running this script, the value of +utilization is 1. This is because the call to child_process.spawnSync() +blocks the event loop from proceeding.

      +

      Passing in a user-defined object instead of the result of a previous call to +eventLoopUtilization() will lead to undefined behavior. The return values +are not guaranteed to reflect any correct state of the event loop.

      +

      Class: PerformanceEntry#

      + +

      performanceEntry.duration#

      + + +

      The total number of milliseconds elapsed for this entry. This value will not +be meaningful for all Performance Entry types.

      +

      performanceEntry.name#

      + + +

      The name of the performance entry.

      +

      performanceEntry.startTime#

      + + +

      The high resolution millisecond timestamp marking the starting time of the +Performance Entry.

      +

      performanceEntry.entryType#

      + + +

      The type of the performance entry. It may be one of:

      +
        +
      • 'node' (Node.js only)
      • +
      • 'mark' (available on the Web)
      • +
      • 'measure' (available on the Web)
      • +
      • 'gc' (Node.js only)
      • +
      • 'function' (Node.js only)
      • +
      • 'http2' (Node.js only)
      • +
      • 'http' (Node.js only)
      • +
      +

      performanceEntry.kind#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      When performanceEntry.entryType is equal to 'gc', the performance.kind +property identifies the type of garbage collection operation that occurred. +The value may be one of:

      +
        +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
      • +
      +

      performanceEntry.flags#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      When performanceEntry.entryType is equal to 'gc', the performance.flags +property contains additional information about garbage collection operation. +The value may be one of:

      +
        +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
      • +
      +

      Class: PerformanceNodeTiming extends PerformanceEntry#

      + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      Provides timing details for Node.js itself. The constructor of this class +is not exposed to users.

      +

      performanceNodeTiming.bootstrapComplete#

      + + +

      The high resolution millisecond timestamp at which the Node.js process +completed bootstrapping. If bootstrapping has not yet finished, the property +has the value of -1.

      +

      performanceNodeTiming.environment#

      + + +

      The high resolution millisecond timestamp at which the Node.js environment was +initialized.

      +

      performanceNodeTiming.loopExit#

      + + +

      The high resolution millisecond timestamp at which the Node.js event loop +exited. If the event loop has not yet exited, the property has the value of -1. +It can only have a value of not -1 in a handler of the 'exit' event.

      +

      performanceNodeTiming.loopStart#

      + + +

      The high resolution millisecond timestamp at which the Node.js event loop +started. If the event loop has not yet started (e.g., in the first tick of the +main script), the property has the value of -1.

      +

      performanceNodeTiming.nodeStart#

      + + +

      The high resolution millisecond timestamp at which the Node.js process was +initialized.

      +

      performanceNodeTiming.v8Start#

      + + +

      The high resolution millisecond timestamp at which the V8 platform was +initialized.

      +

      performanceNodeTiming.idleTime#

      + + +

      The high resolution millisecond timestamp of the amount of time the event loop +has been idle within the event loop's event provider (e.g. epoll_wait). This +does not take CPU usage into consideration. If the event loop has not yet +started (e.g., in the first tick of the main script), the property has the +value of 0.

      +

      Class: perf_hooks.PerformanceObserver#

      +

      new PerformanceObserver(callback)#

      + + +

      PerformanceObserver objects provide notifications when new +PerformanceEntry instances have been added to the Performance Timeline.

      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  console.log(list.getEntries());
      +  observer.disconnect();
      +});
      +obs.observe({ entryTypes: ['mark'], buffered: true });
      +
      +performance.mark('test');
      +

      Because PerformanceObserver instances introduce their own additional +performance overhead, instances should not be left subscribed to notifications +indefinitely. Users should disconnect observers as soon as they are no +longer needed.

      +

      The callback is invoked when a PerformanceObserver is +notified about new PerformanceEntry instances. The callback receives a +PerformanceObserverEntryList instance and a reference to the +PerformanceObserver.

      +

      performanceObserver.disconnect()#

      + +

      Disconnects the PerformanceObserver instance from all notifications.

      +

      performanceObserver.observe(options)#

      + +
        +
      • options <Object> +
          +
        • entryTypes <string[]> An array of strings identifying the types of +PerformanceEntry instances the observer is interested in. If not +provided an error will be thrown.
        • +
        • buffered <boolean> If true, the notification callback will be +called using setImmediate() and multiple PerformanceEntry instance +notifications will be buffered internally. If false, notifications will +be immediate and synchronous. Default: false.
        • +
        +
      • +
      +

      Subscribes the PerformanceObserver instance to notifications of new +PerformanceEntry instances identified by options.entryTypes.

      +

      When options.buffered is false, the callback will be invoked once for +every PerformanceEntry instance:

      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  // Called three times synchronously. `list` contains one item.
      +});
      +obs.observe({ entryTypes: ['mark'] });
      +
      +for (let n = 0; n < 3; n++)
      +  performance.mark(`test${n}`);
      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  // Called once. `list` contains three items.
      +});
      +obs.observe({ entryTypes: ['mark'], buffered: true });
      +
      +for (let n = 0; n < 3; n++)
      +  performance.mark(`test${n}`);
      +

      Class: PerformanceObserverEntryList#

      + +

      The PerformanceObserverEntryList class is used to provide access to the +PerformanceEntry instances passed to a PerformanceObserver. +The constructor of this class is not exposed to users.

      +

      performanceObserverEntryList.getEntries()#

      + + +

      Returns a list of PerformanceEntry objects in chronological order +with respect to performanceEntry.startTime.

      +

      performanceObserverEntryList.getEntriesByName(name[, type])#

      + + +

      Returns a list of PerformanceEntry objects in chronological order +with respect to performanceEntry.startTime whose performanceEntry.name is +equal to name, and optionally, whose performanceEntry.entryType is equal to +type.

      +

      performanceObserverEntryList.getEntriesByType(type)#

      + + +

      Returns a list of PerformanceEntry objects in chronological order +with respect to performanceEntry.startTime whose performanceEntry.entryType +is equal to type.

      +

      perf_hooks.monitorEventLoopDelay([options])#

      + +
        +
      • options <Object> +
          +
        • resolution <number> The sampling rate in milliseconds. Must be greater +than zero. Default: 10.
        • +
        +
      • +
      • Returns: <Histogram>
      • +
      +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      Creates a Histogram object that samples and reports the event loop delay +over time. The delays will be reported in nanoseconds.

      +

      Using a timer to detect approximate event loop delay works because the +execution of timers is tied specifically to the lifecycle of the libuv +event loop. That is, a delay in the loop will cause a delay in the execution +of the timer, and those delays are specifically what this API is intended to +detect.

      +
      const { monitorEventLoopDelay } = require('perf_hooks');
      +const h = monitorEventLoopDelay({ resolution: 20 });
      +h.enable();
      +// Do something.
      +h.disable();
      +console.log(h.min);
      +console.log(h.max);
      +console.log(h.mean);
      +console.log(h.stddev);
      +console.log(h.percentiles);
      +console.log(h.percentile(50));
      +console.log(h.percentile(99));
      +

      Class: Histogram#

      + +

      Tracks the event loop delay at a given sampling rate. The constructor of +this class not exposed to users.

      +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      histogram.disable()#

      + + +

      Disables the event loop delay sample timer. Returns true if the timer was +stopped, false if it was already stopped.

      +

      histogram.enable()#

      + + +

      Enables the event loop delay sample timer. Returns true if the timer was +started, false if it was already started.

      +

      histogram.exceeds#

      + + +

      The number of times the event loop delay exceeded the maximum 1 hour event +loop delay threshold.

      +

      histogram.max#

      + + +

      The maximum recorded event loop delay.

      +

      histogram.mean#

      + + +

      The mean of the recorded event loop delays.

      +

      histogram.min#

      + + +

      The minimum recorded event loop delay.

      +

      histogram.percentile(percentile)#

      + +
        +
      • percentile <number> A percentile value between 1 and 100.
      • +
      • Returns: <number>
      • +
      +

      Returns the value at the given percentile.

      +

      histogram.percentiles#

      + + +

      Returns a Map object detailing the accumulated percentile distribution.

      +

      histogram.reset()#

      + +

      Resets the collected histogram data.

      +

      histogram.stddev#

      + + +

      The standard deviation of the recorded event loop delays.

      +

      Examples#

      +

      Measuring the duration of async operations#

      +

      The following example uses the Async Hooks and Performance APIs to measure +the actual duration of a Timeout operation (including the amount of time it took +to execute the callback).

      +
      'use strict';
      +const async_hooks = require('async_hooks');
      +const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const set = new Set();
      +const hook = async_hooks.createHook({
      +  init(id, type) {
      +    if (type === 'Timeout') {
      +      performance.mark(`Timeout-${id}-Init`);
      +      set.add(id);
      +    }
      +  },
      +  destroy(id) {
      +    if (set.has(id)) {
      +      set.delete(id);
      +      performance.mark(`Timeout-${id}-Destroy`);
      +      performance.measure(`Timeout-${id}`,
      +                          `Timeout-${id}-Init`,
      +                          `Timeout-${id}-Destroy`);
      +    }
      +  }
      +});
      +hook.enable();
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  console.log(list.getEntries()[0]);
      +  performance.clearMarks();
      +  observer.disconnect();
      +});
      +obs.observe({ entryTypes: ['measure'], buffered: true });
      +
      +setTimeout(() => {}, 1000);
      +

      Measuring how long it takes to load dependencies#

      +

      The following example measures the duration of require() operations to load +dependencies:

      + +
      'use strict';
      +const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +const mod = require('module');
      +
      +// Monkey patch the require function
      +mod.Module.prototype.require =
      +  performance.timerify(mod.Module.prototype.require);
      +require = performance.timerify(require);
      +
      +// Activate the observer
      +const obs = new PerformanceObserver((list) => {
      +  const entries = list.getEntries();
      +  entries.forEach((entry) => {
      +    console.log(`require('${entry[0]}')`, entry.duration);
      +  });
      +  obs.disconnect();
      +});
      +obs.observe({ entryTypes: ['function'], buffered: true });
      +
      +require('some-module');
      +

      Policies#

      + + +

      Stability: 1 - Experimental

      + +

      Node.js contains experimental support for creating policies on loading code.

      +

      Policies are a security feature intended to allow guarantees +about what code Node.js is able to load. The use of policies assumes +safe practices for the policy files such as ensuring that policy +files cannot be overwritten by the Node.js application by using +file permissions.

      +

      A best practice would be to ensure that the policy manifest is read only for +the running Node.js application, and that the file cannot be changed +by the running Node.js application in any way. A typical setup would be to +create the policy file as a different user id than the one running Node.js +and granting read permissions to the user id running Node.js.

      +

      Enabling#

      + +

      The --experimental-policy flag can be used to enable features for policies +when loading modules.

      +

      Once this has been set, all modules must conform to a policy manifest file +passed to the flag:

      +
      node --experimental-policy=policy.json app.js
      +

      The policy manifest will be used to enforce constraints on code loaded by +Node.js.

      +

      To mitigate tampering with policy files on disk, an integrity for +the policy file itself may be provided via --policy-integrity. +This allows running node and asserting the policy file contents +even if the file is changed on disk.

      +
      node --experimental-policy=policy.json --policy-integrity="sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0" app.js
      +

      Features#

      +

      Error behavior#

      +

      When a policy check fails, Node.js by default will throw an error. +It is possible to change the error behavior to one of a few possibilities +by defining an "onerror" field in a policy manifest. The following values are +available to change the behavior:

      +
        +
      • "exit": will exit the process immediately. +No cleanup code will be allowed to run.
      • +
      • "log": will log the error at the site of the failure.
      • +
      • "throw": will throw a JS error at the site of the failure. This is the +default.
      • +
      +
      {
      +  "onerror": "log",
      +  "resources": {
      +    "./app/checked.js": {
      +      "integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
      +    }
      +  }
      +}
      +

      Integrity checks#

      +

      Policy files must use integrity checks with Subresource Integrity strings +compatible with the browser +integrity attribute +associated with absolute URLs.

      +

      When using require() all resources involved in loading are checked for +integrity if a policy manifest has been specified. If a resource does not match +the integrity listed in the manifest, an error will be thrown.

      +

      An example policy file that would allow loading a file checked.js:

      +
      {
      +  "resources": {
      +    "./app/checked.js": {
      +      "integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
      +    }
      +  }
      +}
      +

      Each resource listed in the policy manifest can be of one the following +formats to determine its location:

      +
        +
      1. A relative url string to a resource from the manifest such as ./resource.js, ../resource.js, or /resource.js.
      2. +
      3. A complete url string to a resource such as file:///resource.js.
      4. +
      +

      When loading resources the entire URL must match including search parameters +and hash fragment. ./a.js?b will not be used when attempting to load +./a.js and vice versa.

      +

      To generate integrity strings, a script such as +printf "sha384-$(cat checked.js | openssl dgst -sha384 -binary | base64)" +can be used.

      +

      Integrity can be specified as the boolean value true to accept any +body for the resource which can be useful for local development. It is not +recommended in production since it would allow unexpected alteration of +resources to be considered valid.

      +

      Dependency redirection#

      +

      An application may need to ship patched versions of modules or to prevent +modules from allowing all modules access to all other modules. Redirection +can be used by intercepting attempts to load the modules wishing to be +replaced.

      +
      {
      +  "builtins": [],
      +  "resources": {
      +    "./app/checked.js": {
      +      "dependencies": {
      +        "fs": true,
      +        "os": "./app/node_modules/alt-os"
      +      }
      +    }
      +  }
      +}
      +

      The dependencies are keyed by the requested string specifier and have values +of either true or a string pointing to a module that will be resolved.

      +

      The specifier string does not perform any searching and must match exactly +what is provided to the require(). Therefore, multiple specifiers may be +needed in the policy if require() uses multiple different strings to point +to the same module (such as excluding the extension).

      +

      If the value of the redirection is true the default searching algorithms will +be used to find the module.

      +

      If the value of the redirection is a string, it will be resolved relative to +the manifest and then immediately be used without searching.

      +

      Any specifier string that is require()ed and not listed in the dependencies +will result in an error according to the policy.

      +

      Redirection will not prevent access to APIs through means such as direct access +to require.cache and/or through module.constructor which allow access to +loading modules. Policy redirection only affect specifiers to require(). +Other means such as to prevent undesired access to APIs through variables are +necessary to lock down that path of loading modules.

      +

      A boolean value of true for the dependencies map can be specified to allow a +module to load any specifier without redirection. This can be useful for local +development and may have some valid usage in production, but should be used +only with care after auditing a module to ensure its behavior is valid.

      +

      Example: Patched dependency#

      +

      Redirected dependencies can provide attenuated or modified functionality as fits +the application. For example, log data about timing of function durations by +wrapping the original:

      +
      const original = require('fn');
      +module.exports = function fn(...args) {
      +  console.time();
      +  try {
      +    return new.target ?
      +      Reflect.construct(original, args) :
      +      Reflect.apply(original, this, args);
      +  } finally {
      +    console.timeEnd();
      +  }
      +};
      +

      Process#

      + + +

      Source Code: lib/process.js

      +

      The process object is a global that provides information about, and control +over, the current Node.js process. As a global, it is always available to +Node.js applications without using require(). It can also be explicitly +accessed using require():

      +
      const process = require('process');
      +

      Process events#

      +

      The process object is an instance of EventEmitter.

      +

      Event: 'beforeExit'#

      + +

      The 'beforeExit' event is emitted when Node.js empties its event loop and has +no additional work to schedule. Normally, the Node.js process will exit when +there is no work scheduled, but a listener registered on the 'beforeExit' +event can make asynchronous calls, and thereby cause the Node.js process to +continue.

      +

      The listener callback function is invoked with the value of +process.exitCode passed as the only argument.

      +

      The 'beforeExit' event is not emitted for conditions causing explicit +termination, such as calling process.exit() or uncaught exceptions.

      +

      The 'beforeExit' should not be used as an alternative to the 'exit' event +unless the intention is to schedule additional work.

      +
      process.on('beforeExit', (code) => {
      +  console.log('Process beforeExit event with code: ', code);
      +});
      +
      +process.on('exit', (code) => {
      +  console.log('Process exit event with code: ', code);
      +});
      +
      +console.log('This message is displayed first.');
      +
      +// Prints:
      +// This message is displayed first.
      +// Process beforeExit event with code: 0
      +// Process exit event with code: 0
      +

      Event: 'disconnect'#

      + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the 'disconnect' event will be emitted when +the IPC channel is closed.

      +

      Event: 'exit'#

      + + +

      The 'exit' event is emitted when the Node.js process is about to exit as a +result of either:

      +
        +
      • The process.exit() method being called explicitly;
      • +
      • The Node.js event loop no longer having any additional work to perform.
      • +
      +

      There is no way to prevent the exiting of the event loop at this point, and once +all 'exit' listeners have finished running the Node.js process will terminate.

      +

      The listener callback function is invoked with the exit code specified either +by the process.exitCode property, or the exitCode argument passed to the +process.exit() method.

      +
      process.on('exit', (code) => {
      +  console.log(`About to exit with code: ${code}`);
      +});
      +

      Listener functions must only perform synchronous operations. The Node.js +process will exit immediately after calling the 'exit' event listeners +causing any additional work still queued in the event loop to be abandoned. +In the following example, for instance, the timeout will never occur:

      +
      process.on('exit', (code) => {
      +  setTimeout(() => {
      +    console.log('This will not run');
      +  }, 0);
      +});
      +

      Event: 'message'#

      + + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the 'message' event is emitted whenever a +message sent by a parent process using childprocess.send() is received by +the child process.

      +

      The message goes through serialization and parsing. The resulting message might +not be the same as what is originally sent.

      +

      If the serialization option was set to advanced used when spawning the +process, the message argument can contain data that JSON is not able +to represent. +See Advanced serialization for child_process for more details.

      +

      Event: 'multipleResolves'#

      + +
        +
      • type <string> The resolution type. One of 'resolve' or 'reject'.
      • +
      • promise <Promise> The promise that resolved or rejected more than once.
      • +
      • value <any> The value with which the promise was either resolved or +rejected after the original resolve.
      • +
      +

      The 'multipleResolves' event is emitted whenever a Promise has been either:

      +
        +
      • Resolved more than once.
      • +
      • Rejected more than once.
      • +
      • Rejected after resolve.
      • +
      • Resolved after reject.
      • +
      +

      This is useful for tracking potential errors in an application while using the +Promise constructor, as multiple resolutions are silently swallowed. However, +the occurrence of this event does not necessarily indicate an error. For +example, Promise.race() can trigger a 'multipleResolves' event.

      +
      process.on('multipleResolves', (type, promise, reason) => {
      +  console.error(type, promise, reason);
      +  setImmediate(() => process.exit(1));
      +});
      +
      +async function main() {
      +  try {
      +    return await new Promise((resolve, reject) => {
      +      resolve('First call');
      +      resolve('Swallowed resolve');
      +      reject(new Error('Swallowed reject'));
      +    });
      +  } catch {
      +    throw new Error('Failed');
      +  }
      +}
      +
      +main().then(console.log);
      +// resolve: Promise { 'First call' } 'Swallowed resolve'
      +// reject: Promise { 'First call' } Error: Swallowed reject
      +//     at Promise (*)
      +//     at new Promise (<anonymous>)
      +//     at main (*)
      +// First call
      +

      Event: 'rejectionHandled'#

      + +
        +
      • promise <Promise> The late handled promise.
      • +
      +

      The 'rejectionHandled' event is emitted whenever a Promise has been rejected +and an error handler was attached to it (using promise.catch(), for +example) later than one turn of the Node.js event loop.

      +

      The Promise object would have previously been emitted in an +'unhandledRejection' event, but during the course of processing gained a +rejection handler.

      +

      There is no notion of a top level for a Promise chain at which rejections can +always be handled. Being inherently asynchronous in nature, a Promise +rejection can be handled at a future point in time, possibly much later than +the event loop turn it takes for the 'unhandledRejection' event to be emitted.

      +

      Another way of stating this is that, unlike in synchronous code where there is +an ever-growing list of unhandled exceptions, with Promises there can be a +growing-and-shrinking list of unhandled rejections.

      +

      In synchronous code, the 'uncaughtException' event is emitted when the list of +unhandled exceptions grows.

      +

      In asynchronous code, the 'unhandledRejection' event is emitted when the list +of unhandled rejections grows, and the 'rejectionHandled' event is emitted +when the list of unhandled rejections shrinks.

      +
      const unhandledRejections = new Map();
      +process.on('unhandledRejection', (reason, promise) => {
      +  unhandledRejections.set(promise, reason);
      +});
      +process.on('rejectionHandled', (promise) => {
      +  unhandledRejections.delete(promise);
      +});
      +

      In this example, the unhandledRejections Map will grow and shrink over time, +reflecting rejections that start unhandled and then become handled. It is +possible to record such errors in an error log, either periodically (which is +likely best for long-running application) or upon process exit (which is likely +most convenient for scripts).

      +

      Event: 'uncaughtException'#

      + +
        +
      • err <Error> The uncaught exception.
      • +
      • origin <string> Indicates if the exception originates from an unhandled +rejection or from an synchronous error. Can either be 'uncaughtException' or +'unhandledRejection'. The latter is only used in conjunction with the +--unhandled-rejections flag set to strict and an unhandled rejection.
      • +
      +

      The 'uncaughtException' event is emitted when an uncaught JavaScript +exception bubbles all the way back to the event loop. By default, Node.js +handles such exceptions by printing the stack trace to stderr and exiting +with code 1, overriding any previously set process.exitCode. +Adding a handler for the 'uncaughtException' event overrides this default +behavior. Alternatively, change the process.exitCode in the +'uncaughtException' handler which will result in the process exiting with the +provided exit code. Otherwise, in the presence of such handler the process will +exit with 0.

      +
      process.on('uncaughtException', (err, origin) => {
      +  fs.writeSync(
      +    process.stderr.fd,
      +    `Caught exception: ${err}\n` +
      +    `Exception origin: ${origin}`
      +  );
      +});
      +
      +setTimeout(() => {
      +  console.log('This will still run.');
      +}, 500);
      +
      +// Intentionally cause an exception, but don't catch it.
      +nonexistentFunc();
      +console.log('This will not run.');
      +

      It is possible to monitor 'uncaughtException' events without overriding the +default behavior to exit the process by installing a +'uncaughtExceptionMonitor' listener.

      +

      Warning: Using 'uncaughtException' correctly#

      +

      'uncaughtException' is a crude mechanism for exception handling +intended to be used only as a last resort. The event should not be used as +an equivalent to On Error Resume Next. Unhandled exceptions inherently mean +that an application is in an undefined state. Attempting to resume application +code without properly recovering from the exception can cause additional +unforeseen and unpredictable issues.

      +

      Exceptions thrown from within the event handler will not be caught. Instead the +process will exit with a non-zero exit code and the stack trace will be printed. +This is to avoid infinite recursion.

      +

      Attempting to resume normally after an uncaught exception can be similar to +pulling out the power cord when upgrading a computer. Nine out of ten +times, nothing happens. But the tenth time, the system becomes corrupted.

      +

      The correct use of 'uncaughtException' is to perform synchronous cleanup +of allocated resources (e.g. file descriptors, handles, etc) before shutting +down the process. It is not safe to resume normal operation after +'uncaughtException'.

      +

      To restart a crashed application in a more reliable way, whether +'uncaughtException' is emitted or not, an external monitor should be employed +in a separate process to detect application failures and recover or restart as +needed.

      +

      Event: 'uncaughtExceptionMonitor'#

      + +
        +
      • err <Error> The uncaught exception.
      • +
      • origin <string> Indicates if the exception originates from an unhandled +rejection or from synchronous errors. Can either be 'uncaughtException' or +'unhandledRejection'.
      • +
      +

      The 'uncaughtExceptionMonitor' event is emitted before an +'uncaughtException' event is emitted or a hook installed via +process.setUncaughtExceptionCaptureCallback() is called.

      +

      Installing an 'uncaughtExceptionMonitor' listener does not change the behavior +once an 'uncaughtException' event is emitted. The process will +still crash if no 'uncaughtException' listener is installed.

      +
      process.on('uncaughtExceptionMonitor', (err, origin) => {
      +  MyMonitoringTool.logSync(err, origin);
      +});
      +
      +// Intentionally cause an exception, but don't catch it.
      +nonexistentFunc();
      +// Still crashes Node.js
      +

      Event: 'unhandledRejection'#

      + +
        +
      • reason <Error> | <any> The object with which the promise was rejected +(typically an Error object).
      • +
      • promise <Promise> The rejected promise.
      • +
      +

      The 'unhandledRejection' event is emitted whenever a Promise is rejected and +no error handler is attached to the promise within a turn of the event loop. +When programming with Promises, exceptions are encapsulated as "rejected +promises". Rejections can be caught and handled using promise.catch() and +are propagated through a Promise chain. The 'unhandledRejection' event is +useful for detecting and keeping track of promises that were rejected whose +rejections have not yet been handled.

      +
      process.on('unhandledRejection', (reason, promise) => {
      +  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
      +  // Application specific logging, throwing an error, or other logic here
      +});
      +
      +somePromise.then((res) => {
      +  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
      +}); // No `.catch()` or `.then()`
      +

      The following will also trigger the 'unhandledRejection' event to be +emitted:

      +
      function SomeResource() {
      +  // Initially set the loaded status to a rejected promise
      +  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
      +}
      +
      +const resource = new SomeResource();
      +// no .catch or .then on resource.loaded for at least a turn
      +

      In this example case, it is possible to track the rejection as a developer error +as would typically be the case for other 'unhandledRejection' events. To +address such failures, a non-operational +.catch(() => { }) handler may be attached to +resource.loaded, which would prevent the 'unhandledRejection' event from +being emitted.

      +

      Event: 'warning'#

      + +
        +
      • warning <Error> Key properties of the warning are: +
          +
        • name <string> The name of the warning. Default: 'Warning'.
        • +
        • message <string> A system-provided description of the warning.
        • +
        • stack <string> A stack trace to the location in the code where the warning +was issued.
        • +
        +
      • +
      +

      The 'warning' event is emitted whenever Node.js emits a process warning.

      +

      A process warning is similar to an error in that it describes exceptional +conditions that are being brought to the user's attention. However, warnings +are not part of the normal Node.js and JavaScript error handling flow. +Node.js can emit warnings whenever it detects bad coding practices that could +lead to sub-optimal application performance, bugs, or security vulnerabilities.

      +
      process.on('warning', (warning) => {
      +  console.warn(warning.name);    // Print the warning name
      +  console.warn(warning.message); // Print the warning message
      +  console.warn(warning.stack);   // Print the stack trace
      +});
      +

      By default, Node.js will print process warnings to stderr. The --no-warnings +command-line option can be used to suppress the default console output but the +'warning' event will still be emitted by the process object.

      +

      The following example illustrates the warning that is printed to stderr when +too many listeners have been added to an event:

      +
      $ node
      +> events.defaultMaxListeners = 1;
      +> process.on('foo', () => {});
      +> process.on('foo', () => {});
      +> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak
      +detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit
      +

      In contrast, the following example turns off the default warning output and +adds a custom handler to the 'warning' event:

      +
      $ node --no-warnings
      +> const p = process.on('warning', (warning) => console.warn('Do not do that!'));
      +> events.defaultMaxListeners = 1;
      +> process.on('foo', () => {});
      +> process.on('foo', () => {});
      +> Do not do that!
      +

      The --trace-warnings command-line option can be used to have the default +console output for warnings include the full stack trace of the warning.

      +

      Launching Node.js using the --throw-deprecation command line flag will +cause custom deprecation warnings to be thrown as exceptions.

      +

      Using the --trace-deprecation command line flag will cause the custom +deprecation to be printed to stderr along with the stack trace.

      +

      Using the --no-deprecation command line flag will suppress all reporting +of the custom deprecation.

      +

      The *-deprecation command line flags only affect warnings that use the name +'DeprecationWarning'.

      +

      Emitting custom warnings#

      +

      See the process.emitWarning() method for issuing +custom or application-specific warnings.

      +

      Signal events#

      + + +

      Signal events will be emitted when the Node.js process receives a signal. Please +refer to signal(7) for a listing of standard POSIX signal names such as +'SIGINT', 'SIGHUP', etc.

      +

      Signals are not available on Worker threads.

      +

      The signal handler will receive the signal's name ('SIGINT', +'SIGTERM', etc.) as the first argument.

      +

      The name of each event will be the uppercase common name for the signal (e.g. +'SIGINT' for SIGINT signals).

      +
      // Begin reading from stdin so the process does not exit.
      +process.stdin.resume();
      +
      +process.on('SIGINT', () => {
      +  console.log('Received SIGINT. Press Control-D to exit.');
      +});
      +
      +// Using a single function to handle multiple signals
      +function handle(signal) {
      +  console.log(`Received ${signal}`);
      +}
      +
      +process.on('SIGINT', handle);
      +process.on('SIGTERM', handle);
      +
        +
      • 'SIGUSR1' is reserved by Node.js to start the debugger. It's possible to +install a listener but doing so might interfere with the debugger.
      • +
      • 'SIGTERM' and 'SIGINT' have default handlers on non-Windows platforms that +reset the terminal mode before exiting with code 128 + signal number. If one +of these signals has a listener installed, its default behavior will be +removed (Node.js will no longer exit).
      • +
      • 'SIGPIPE' is ignored by default. It can have a listener installed.
      • +
      • 'SIGHUP' is generated on Windows when the console window is closed, and on +other platforms under various similar conditions. See signal(7). It can have a +listener installed, however Node.js will be unconditionally terminated by +Windows about 10 seconds later. On non-Windows platforms, the default +behavior of SIGHUP is to terminate Node.js, but once a listener has been +installed its default behavior will be removed.
      • +
      • 'SIGTERM' is not supported on Windows, it can be listened on.
      • +
      • 'SIGINT' from the terminal is supported on all platforms, and can usually be +generated with Ctrl+C (though this may be configurable). +It is not generated when terminal raw mode is enabled and +Ctrl+C is used.
      • +
      • 'SIGBREAK' is delivered on Windows when Ctrl+Break is +pressed. On non-Windows platforms, it can be listened on, but there is no way +to send or generate it.
      • +
      • 'SIGWINCH' is delivered when the console has been resized. On Windows, this +will only happen on write to the console when the cursor is being moved, or +when a readable tty is used in raw mode.
      • +
      • 'SIGKILL' cannot have a listener installed, it will unconditionally +terminate Node.js on all platforms.
      • +
      • 'SIGSTOP' cannot have a listener installed.
      • +
      • 'SIGBUS', 'SIGFPE', 'SIGSEGV' and 'SIGILL', when not raised + artificially using kill(2), inherently leave the process in a state from + which it is not safe to attempt to call JS listeners. Doing so might lead to + the process hanging in an endless loop, since listeners attached using + process.on() are called asynchronously and therefore unable to correct the +underlying problem.
      • +
      • 0 can be sent to test for the existence of a process, it has no effect if +the process exists, but will throw an error if the process does not exist.
      • +
      +

      Windows does not support signals so has no equivalent to termination by signal, +but Node.js offers some emulation with process.kill(), and +subprocess.kill():

      +
        +
      • Sending SIGINT, SIGTERM, and SIGKILL will cause the unconditional +termination of the target process, and afterwards, subprocess will report that +the process was terminated by signal.
      • +
      • Sending signal 0 can be used as a platform independent way to test for the +existence of a process.
      • +
      +

      process.abort()#

      + +

      The process.abort() method causes the Node.js process to exit immediately and +generate a core file.

      +

      This feature is not available in Worker threads.

      +

      process.allowedNodeEnvironmentFlags#

      + + +

      The process.allowedNodeEnvironmentFlags property is a special, +read-only Set of flags allowable within the NODE_OPTIONS +environment variable.

      +

      process.allowedNodeEnvironmentFlags extends Set, but overrides +Set.prototype.has to recognize several different possible flag +representations. process.allowedNodeEnvironmentFlags.has() will +return true in the following cases:

      +
        +
      • Flags may omit leading single (-) or double (--) dashes; e.g., +inspect-brk for --inspect-brk, or r for -r.
      • +
      • Flags passed through to V8 (as listed in --v8-options) may replace +one or more non-leading dashes for an underscore, or vice-versa; +e.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof, +etc.
      • +
      • Flags may contain one or more equals (=) characters; all +characters after and including the first equals will be ignored; +e.g., --stack-trace-limit=100.
      • +
      • Flags must be allowable within NODE_OPTIONS.
      • +
      +

      When iterating over process.allowedNodeEnvironmentFlags, flags will +appear only once; each will begin with one or more dashes. Flags +passed through to V8 will contain underscores instead of non-leading +dashes:

      +
      process.allowedNodeEnvironmentFlags.forEach((flag) => {
      +  // -r
      +  // --inspect-brk
      +  // --abort_on_uncaught_exception
      +  // ...
      +});
      +

      The methods add(), clear(), and delete() of +process.allowedNodeEnvironmentFlags do nothing, and will fail +silently.

      +

      If Node.js was compiled without NODE_OPTIONS support (shown in +process.config), process.allowedNodeEnvironmentFlags will +contain what would have been allowable.

      +

      process.arch#

      + + +

      The operating system CPU architecture for which the Node.js binary was compiled. +Possible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc', +'ppc64', 's390', 's390x', 'x32', and 'x64'.

      +
      console.log(`This processor architecture is ${process.arch}`);
      +

      process.argv#

      + + +

      The process.argv property returns an array containing the command line +arguments passed when the Node.js process was launched. The first element will +be process.execPath. See process.argv0 if access to the original value +of argv[0] is needed. The second element will be the path to the JavaScript +file being executed. The remaining elements will be any additional command line +arguments.

      +

      For example, assuming the following script for process-args.js:

      +
      // print process.argv
      +process.argv.forEach((val, index) => {
      +  console.log(`${index}: ${val}`);
      +});
      +

      Launching the Node.js process as:

      +
      $ node process-args.js one two=three four
      +

      Would generate the output:

      +
      0: /usr/local/bin/node
      +1: /Users/mjr/work/node/process-args.js
      +2: one
      +3: two=three
      +4: four
      +

      process.argv0#

      + + +

      The process.argv0 property stores a read-only copy of the original value of +argv[0] passed when Node.js starts.

      +
      $ bash -c 'exec -a customArgv0 ./node'
      +> process.argv[0]
      +'/Volumes/code/external/node/out/Release/node'
      +> process.argv0
      +'customArgv0'
      +

      process.channel#

      + + +

      If the Node.js process was spawned with an IPC channel (see the +Child Process documentation), the process.channel +property is a reference to the IPC channel. If no IPC channel exists, this +property is undefined.

      +

      process.chdir(directory)#

      + + +

      The process.chdir() method changes the current working directory of the +Node.js process or throws an exception if doing so fails (for instance, if +the specified directory does not exist).

      +
      console.log(`Starting directory: ${process.cwd()}`);
      +try {
      +  process.chdir('/tmp');
      +  console.log(`New directory: ${process.cwd()}`);
      +} catch (err) {
      +  console.error(`chdir: ${err}`);
      +}
      +

      This feature is not available in Worker threads.

      +

      process.config#

      + + +

      The process.config property returns an Object containing the JavaScript +representation of the configure options used to compile the current Node.js +executable. This is the same as the config.gypi file that was produced when +running the ./configure script.

      +

      An example of the possible output looks like:

      + +
      {
      +  target_defaults:
      +   { cflags: [],
      +     default_configuration: 'Release',
      +     defines: [],
      +     include_dirs: [],
      +     libraries: [] },
      +  variables:
      +   {
      +     host_arch: 'x64',
      +     napi_build_version: 5,
      +     node_install_npm: 'true',
      +     node_prefix: '',
      +     node_shared_cares: 'false',
      +     node_shared_http_parser: 'false',
      +     node_shared_libuv: 'false',
      +     node_shared_zlib: 'false',
      +     node_use_dtrace: 'false',
      +     node_use_openssl: 'true',
      +     node_shared_openssl: 'false',
      +     strict_aliasing: 'true',
      +     target_arch: 'x64',
      +     v8_use_snapshot: 1
      +   }
      +}
      +

      The process.config property is not read-only and there are existing +modules in the ecosystem that are known to extend, modify, or entirely replace +the value of process.config.

      +

      process.connected#

      + + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the process.connected property will return +true so long as the IPC channel is connected and will return false after +process.disconnect() is called.

      +

      Once process.connected is false, it is no longer possible to send messages +over the IPC channel using process.send().

      +

      process.cpuUsage([previousValue])#

      + + +

      The process.cpuUsage() method returns the user and system CPU time usage of +the current process, in an object with properties user and system, whose +values are microsecond values (millionth of a second). These values measure time +spent in user and system code respectively, and may end up being greater than +actual elapsed time if multiple CPU cores are performing work for this process.

      +

      The result of a previous call to process.cpuUsage() can be passed as the +argument to the function, to get a diff reading.

      +
      const startUsage = process.cpuUsage();
      +// { user: 38579, system: 6986 }
      +
      +// spin the CPU for 500 milliseconds
      +const now = Date.now();
      +while (Date.now() - now < 500);
      +
      +console.log(process.cpuUsage(startUsage));
      +// { user: 514883, system: 11226 }
      +

      process.cwd()#

      + + +

      The process.cwd() method returns the current working directory of the Node.js +process.

      +
      console.log(`Current directory: ${process.cwd()}`);
      +

      process.debugPort#

      + + +

      The port used by the Node.js debugger when enabled.

      +
      process.debugPort = 5858;
      +

      process.disconnect()#

      + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the process.disconnect() method will close the +IPC channel to the parent process, allowing the child process to exit gracefully +once there are no other connections keeping it alive.

      +

      The effect of calling process.disconnect() is the same as calling +ChildProcess.disconnect() from the parent process.

      +

      If the Node.js process was not spawned with an IPC channel, +process.disconnect() will be undefined.

      +

      process.dlopen(module, filename[, flags])#

      + + +

      The process.dlopen() method allows to dynamically load shared +objects. It is primarily used by require() to load +C++ Addons, and should not be used directly, except in special +cases. In other words, require() should be preferred over +process.dlopen(), unless there are specific reasons.

      +

      The flags argument is an integer that allows to specify dlopen +behavior. See the os.constants.dlopen documentation for details.

      +

      If there are specific reasons to use process.dlopen() (for instance, +to specify dlopen flags), it's often useful to use require.resolve() +to look up the module's path.

      +

      An important drawback when calling process.dlopen() is that the module +instance must be passed. Functions exported by the C++ Addon will be accessible +via module.exports.

      +

      The example below shows how to load a C++ Addon, named as binding, +that exports a foo function. All the symbols will be loaded before +the call returns, by passing the RTLD_NOW constant. In this example +the constant is assumed to be available.

      +
      const os = require('os');
      +process.dlopen(module, require.resolve('binding'),
      +               os.constants.dlopen.RTLD_NOW);
      +module.exports.foo();
      +

      process.emitWarning(warning[, options])#

      + +
        +
      • warning <string> | <Error> The warning to emit.
      • +
      • options <Object> +
          +
        • type <string> When warning is a String, type is the name to use +for the type of warning being emitted. Default: 'Warning'.
        • +
        • code <string> A unique identifier for the warning instance being emitted.
        • +
        • ctor <Function> When warning is a String, ctor is an optional +function used to limit the generated stack trace. Default: +process.emitWarning.
        • +
        • detail <string> Additional text to include with the error.
        • +
        +
      • +
      +

      The process.emitWarning() method can be used to emit custom or application +specific process warnings. These can be listened for by adding a handler to the +'warning' event.

      +
      // Emit a warning with a code and additional detail.
      +process.emitWarning('Something happened!', {
      +  code: 'MY_WARNING',
      +  detail: 'This is some additional information'
      +});
      +// Emits:
      +// (node:56338) [MY_WARNING] Warning: Something happened!
      +// This is some additional information
      +

      In this example, an Error object is generated internally by +process.emitWarning() and passed through to the +'warning' handler.

      +
      process.on('warning', (warning) => {
      +  console.warn(warning.name);    // 'Warning'
      +  console.warn(warning.message); // 'Something happened!'
      +  console.warn(warning.code);    // 'MY_WARNING'
      +  console.warn(warning.stack);   // Stack trace
      +  console.warn(warning.detail);  // 'This is some additional information'
      +});
      +

      If warning is passed as an Error object, the options argument is ignored.

      +

      process.emitWarning(warning[, type[, code]][, ctor])#

      + +
        +
      • warning <string> | <Error> The warning to emit.
      • +
      • type <string> When warning is a String, type is the name to use +for the type of warning being emitted. Default: 'Warning'.
      • +
      • code <string> A unique identifier for the warning instance being emitted.
      • +
      • ctor <Function> When warning is a String, ctor is an optional +function used to limit the generated stack trace. Default: +process.emitWarning.
      • +
      +

      The process.emitWarning() method can be used to emit custom or application +specific process warnings. These can be listened for by adding a handler to the +'warning' event.

      +
      // Emit a warning using a string.
      +process.emitWarning('Something happened!');
      +// Emits: (node: 56338) Warning: Something happened!
      +
      // Emit a warning using a string and a type.
      +process.emitWarning('Something Happened!', 'CustomWarning');
      +// Emits: (node:56338) CustomWarning: Something Happened!
      +
      process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
      +// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
      +

      In each of the previous examples, an Error object is generated internally by +process.emitWarning() and passed through to the 'warning' +handler.

      +
      process.on('warning', (warning) => {
      +  console.warn(warning.name);
      +  console.warn(warning.message);
      +  console.warn(warning.code);
      +  console.warn(warning.stack);
      +});
      +

      If warning is passed as an Error object, it will be passed through to the +'warning' event handler unmodified (and the optional type, +code and ctor arguments will be ignored):

      +
      // Emit a warning using an Error object.
      +const myWarning = new Error('Something happened!');
      +// Use the Error name property to specify the type name
      +myWarning.name = 'CustomWarning';
      +myWarning.code = 'WARN001';
      +
      +process.emitWarning(myWarning);
      +// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
      +

      A TypeError is thrown if warning is anything other than a string or Error +object.

      +

      While process warnings use Error objects, the process warning +mechanism is not a replacement for normal error handling mechanisms.

      +

      The following additional handling is implemented if the warning type is +'DeprecationWarning':

      +
        +
      • If the --throw-deprecation command-line flag is used, the deprecation +warning is thrown as an exception rather than being emitted as an event.
      • +
      • If the --no-deprecation command-line flag is used, the deprecation +warning is suppressed.
      • +
      • If the --trace-deprecation command-line flag is used, the deprecation +warning is printed to stderr along with the full stack trace.
      • +
      +

      Avoiding duplicate warnings#

      +

      As a best practice, warnings should be emitted only once per process. To do +so, it is recommended to place the emitWarning() behind a simple boolean +flag as illustrated in the example below:

      +
      function emitMyWarning() {
      +  if (!emitMyWarning.warned) {
      +    emitMyWarning.warned = true;
      +    process.emitWarning('Only warn once!');
      +  }
      +}
      +emitMyWarning();
      +// Emits: (node: 56339) Warning: Only warn once!
      +emitMyWarning();
      +// Emits nothing
      +

      process.env#

      + + +

      The process.env property returns an object containing the user environment. +See environ(7).

      +

      An example of this object looks like:

      + +
      {
      +  TERM: 'xterm-256color',
      +  SHELL: '/usr/local/bin/bash',
      +  USER: 'maciej',
      +  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
      +  PWD: '/Users/maciej',
      +  EDITOR: 'vim',
      +  SHLVL: '1',
      +  HOME: '/Users/maciej',
      +  LOGNAME: 'maciej',
      +  _: '/usr/local/bin/node'
      +}
      +

      It is possible to modify this object, but such modifications will not be +reflected outside the Node.js process, or (unless explicitly requested) +to other Worker threads. +In other words, the following example would not work:

      +
      $ node -e 'process.env.foo = "bar"' && echo $foo
      +

      While the following will:

      +
      process.env.foo = 'bar';
      +console.log(process.env.foo);
      +

      Assigning a property on process.env will implicitly convert the value +to a string. This behavior is deprecated. Future versions of Node.js may +throw an error when the value is not a string, number, or boolean.

      +
      process.env.test = null;
      +console.log(process.env.test);
      +// => 'null'
      +process.env.test = undefined;
      +console.log(process.env.test);
      +// => 'undefined'
      +

      Use delete to delete a property from process.env.

      +
      process.env.TEST = 1;
      +delete process.env.TEST;
      +console.log(process.env.TEST);
      +// => undefined
      +

      On Windows operating systems, environment variables are case-insensitive.

      +
      process.env.TEST = 1;
      +console.log(process.env.test);
      +// => 1
      +

      Unless explicitly specified when creating a Worker instance, +each Worker thread has its own copy of process.env, based on its +parent thread’s process.env, or whatever was specified as the env option +to the Worker constructor. Changes to process.env will not be visible +across Worker threads, and only the main thread can make changes that +are visible to the operating system or to native add-ons.

      +

      process.execArgv#

      + + +

      The process.execArgv property returns the set of Node.js-specific command-line +options passed when the Node.js process was launched. These options do not +appear in the array returned by the process.argv property, and do not +include the Node.js executable, the name of the script, or any options following +the script name. These options are useful in order to spawn child processes with +the same execution environment as the parent.

      +
      $ node --harmony script.js --version
      +

      Results in process.execArgv:

      + +
      ['--harmony']
      +

      And process.argv:

      + +
      ['/usr/local/bin/node', 'script.js', '--version']
      +

      process.execPath#

      + + +

      The process.execPath property returns the absolute pathname of the executable +that started the Node.js process. Symbolic links, if any, are resolved.

      + +
      '/usr/local/bin/node'
      +

      process.exit([code])#

      + +
        +
      • code <integer> The exit code. Default: 0.
      • +
      +

      The process.exit() method instructs Node.js to terminate the process +synchronously with an exit status of code. If code is omitted, exit uses +either the 'success' code 0 or the value of process.exitCode if it has been +set. Node.js will not terminate until all the 'exit' event listeners are +called.

      +

      To exit with a 'failure' code:

      +
      process.exit(1);
      +

      The shell that executed Node.js should see the exit code as 1.

      +

      Calling process.exit() will force the process to exit as quickly as possible +even if there are still asynchronous operations pending that have not yet +completed fully, including I/O operations to process.stdout and +process.stderr.

      +

      In most situations, it is not actually necessary to call process.exit() +explicitly. The Node.js process will exit on its own if there is no additional +work pending in the event loop. The process.exitCode property can be set to +tell the process which exit code to use when the process exits gracefully.

      +

      For instance, the following example illustrates a misuse of the +process.exit() method that could lead to data printed to stdout being +truncated and lost:

      +
      // This is an example of what *not* to do:
      +if (someConditionNotMet()) {
      +  printUsageToStdout();
      +  process.exit(1);
      +}
      +

      The reason this is problematic is because writes to process.stdout in Node.js +are sometimes asynchronous and may occur over multiple ticks of the Node.js +event loop. Calling process.exit(), however, forces the process to exit +before those additional writes to stdout can be performed.

      +

      Rather than calling process.exit() directly, the code should set the +process.exitCode and allow the process to exit naturally by avoiding +scheduling any additional work for the event loop:

      +
      // How to properly set the exit code while letting
      +// the process exit gracefully.
      +if (someConditionNotMet()) {
      +  printUsageToStdout();
      +  process.exitCode = 1;
      +}
      +

      If it is necessary to terminate the Node.js process due to an error condition, +throwing an uncaught error and allowing the process to terminate accordingly +is safer than calling process.exit().

      +

      In Worker threads, this function stops the current thread rather +than the current process.

      +

      process.exitCode#

      + + +

      A number which will be the process exit code, when the process either +exits gracefully, or is exited via process.exit() without specifying +a code.

      +

      Specifying a code to process.exit(code) will override any +previous setting of process.exitCode.

      +

      process.getegid()#

      + +

      The process.getegid() method returns the numerical effective group identity +of the Node.js process. (See getegid(2).)

      +
      if (process.getegid) {
      +  console.log(`Current gid: ${process.getegid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.geteuid()#

      + + +

      The process.geteuid() method returns the numerical effective user identity of +the process. (See geteuid(2).)

      +
      if (process.geteuid) {
      +  console.log(`Current uid: ${process.geteuid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.getgid()#

      + + +

      The process.getgid() method returns the numerical group identity of the +process. (See getgid(2).)

      +
      if (process.getgid) {
      +  console.log(`Current gid: ${process.getgid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.getgroups()#

      + + +

      The process.getgroups() method returns an array with the supplementary group +IDs. POSIX leaves it unspecified if the effective group ID is included but +Node.js ensures it always is.

      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.getuid()#

      + + +

      The process.getuid() method returns the numeric user identity of the process. +(See getuid(2).)

      +
      if (process.getuid) {
      +  console.log(`Current uid: ${process.getuid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.hasUncaughtExceptionCaptureCallback()#

      + + +

      Indicates whether a callback has been set using +process.setUncaughtExceptionCaptureCallback().

      +

      process.hrtime([time])#

      + + +

      This is the legacy version of process.hrtime.bigint() +before bigint was introduced in JavaScript.

      +

      The process.hrtime() method returns the current high-resolution real time +in a [seconds, nanoseconds] tuple Array, where nanoseconds is the +remaining part of the real time that can't be represented in second precision.

      +

      time is an optional parameter that must be the result of a previous +process.hrtime() call to diff with the current time. If the parameter +passed in is not a tuple Array, a TypeError will be thrown. Passing in a +user-defined array instead of the result of a previous call to +process.hrtime() will lead to undefined behavior.

      +

      These times are relative to an arbitrary time in the +past, and not related to the time of day and therefore not subject to clock +drift. The primary use is for measuring performance between intervals:

      +
      const NS_PER_SEC = 1e9;
      +const time = process.hrtime();
      +// [ 1800216, 25 ]
      +
      +setTimeout(() => {
      +  const diff = process.hrtime(time);
      +  // [ 1, 552 ]
      +
      +  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
      +  // Benchmark took 1000000552 nanoseconds
      +}, 1000);
      +

      process.hrtime.bigint()#

      + + +

      The bigint version of the process.hrtime() method returning the +current high-resolution real time in nanoseconds as a bigint.

      +

      Unlike process.hrtime(), it does not support an additional time +argument since the difference can just be computed directly +by subtraction of the two bigints.

      +
      const start = process.hrtime.bigint();
      +// 191051479007711n
      +
      +setTimeout(() => {
      +  const end = process.hrtime.bigint();
      +  // 191052633396993n
      +
      +  console.log(`Benchmark took ${end - start} nanoseconds`);
      +  // Benchmark took 1154389282 nanoseconds
      +}, 1000);
      +

      process.initgroups(user, extraGroup)#

      + + +

      The process.initgroups() method reads the /etc/group file and initializes +the group access list, using all groups of which the user is a member. This is +a privileged operation that requires that the Node.js process either have root +access or the CAP_SETGID capability.

      +

      Use care when dropping privileges:

      +
      console.log(process.getgroups());         // [ 0 ]
      +process.initgroups('nodeuser', 1000);     // switch user
      +console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
      +process.setgid(1000);                     // drop root gid
      +console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.kill(pid[, signal])#

      + +
        +
      • pid <number> A process ID
      • +
      • signal <string> | <number> The signal to send, either as a string or number. +Default: 'SIGTERM'.
      • +
      +

      The process.kill() method sends the signal to the process identified by +pid.

      +

      Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events +and kill(2) for more information.

      +

      This method will throw an error if the target pid does not exist. As a special +case, a signal of 0 can be used to test for the existence of a process. +Windows platforms will throw an error if the pid is used to kill a process +group.

      +

      Even though the name of this function is process.kill(), it is really just a +signal sender, like the kill system call. The signal sent may do something +other than kill the target process.

      +
      process.on('SIGHUP', () => {
      +  console.log('Got SIGHUP signal.');
      +});
      +
      +setTimeout(() => {
      +  console.log('Exiting.');
      +  process.exit(0);
      +}, 100);
      +
      +process.kill(process.pid, 'SIGHUP');
      +

      When SIGUSR1 is received by a Node.js process, Node.js will start the +debugger. See Signal Events.

      +

      process.mainModule#

      + + +

      The process.mainModule property provides an alternative way of retrieving +require.main. The difference is that if the main module changes at +runtime, require.main may still refer to the original main module in +modules that were required before the change occurred. Generally, it's +safe to assume that the two refer to the same module.

      +

      As with require.main, process.mainModule will be undefined if there +is no entry script.

      +

      process.memoryUsage()#

      + + +

      The process.memoryUsage() method returns an object describing the memory usage +of the Node.js process measured in bytes.

      +

      For example, the code:

      +
      console.log(process.memoryUsage());
      +

      Will generate:

      + +
      {
      +  rss: 4935680,
      +  heapTotal: 1826816,
      +  heapUsed: 650472,
      +  external: 49879,
      +  arrayBuffers: 9386
      +}
      +
        +
      • heapTotal and heapUsed refer to V8's memory usage.
      • +
      • external refers to the memory usage of C++ objects bound to JavaScript +objects managed by V8.
      • +
      • rss, Resident Set Size, is the amount of space occupied in the main +memory device (that is a subset of the total allocated memory) for the +process, including all C++ and JavaScript objects and code.
      • +
      • arrayBuffers refers to memory allocated for ArrayBuffers and +SharedArrayBuffers, including all Node.js Buffers. +This is also included in the external value. When Node.js is used as an +embedded library, this value may be 0 because allocations for ArrayBuffers +may not be tracked in that case.
      • +
      +

      When using Worker threads, rss will be a value that is valid for the +entire process, while the other fields will only refer to the current thread.

      +

      process.nextTick(callback[, ...args])#

      + +
        +
      • callback <Function>
      • +
      • ...args <any> Additional arguments to pass when invoking the callback
      • +
      +

      process.nextTick() adds callback to the "next tick queue". This queue is +fully drained after the current operation on the JavaScript stack runs to +completion and before the event loop is allowed to continue. It's possible to +create an infinite loop if one were to recursively call process.nextTick(). +See the Event Loop guide for more background.

      +
      console.log('start');
      +process.nextTick(() => {
      +  console.log('nextTick callback');
      +});
      +console.log('scheduled');
      +// Output:
      +// start
      +// scheduled
      +// nextTick callback
      +

      This is important when developing APIs in order to give users the opportunity +to assign event handlers after an object has been constructed but before any +I/O has occurred:

      +
      function MyThing(options) {
      +  this.setupOptions(options);
      +
      +  process.nextTick(() => {
      +    this.startDoingStuff();
      +  });
      +}
      +
      +const thing = new MyThing();
      +thing.getReadyForStuff();
      +
      +// thing.startDoingStuff() gets called now, not before.
      +

      It is very important for APIs to be either 100% synchronous or 100% +asynchronous. Consider this example:

      +
      // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
      +function maybeSync(arg, cb) {
      +  if (arg) {
      +    cb();
      +    return;
      +  }
      +
      +  fs.stat('file', cb);
      +}
      +

      This API is hazardous because in the following case:

      +
      const maybeTrue = Math.random() > 0.5;
      +
      +maybeSync(maybeTrue, () => {
      +  foo();
      +});
      +
      +bar();
      +

      It is not clear whether foo() or bar() will be called first.

      +

      The following approach is much better:

      +
      function definitelyAsync(arg, cb) {
      +  if (arg) {
      +    process.nextTick(cb);
      +    return;
      +  }
      +
      +  fs.stat('file', cb);
      +}
      +

      process.noDeprecation#

      + + +

      The process.noDeprecation property indicates whether the --no-deprecation +flag is set on the current Node.js process. See the documentation for +the 'warning' event and the +emitWarning() method for more information about this +flag's behavior.

      +

      process.pid#

      + + +

      The process.pid property returns the PID of the process.

      +
      console.log(`This process is pid ${process.pid}`);
      +

      process.platform#

      + + +

      The process.platform property returns a string identifying the operating +system platform on which the Node.js process is running.

      +

      Currently possible values are:

      +
        +
      • 'aix'
      • +
      • 'darwin'
      • +
      • 'freebsd'
      • +
      • 'linux'
      • +
      • 'openbsd'
      • +
      • 'sunos'
      • +
      • 'win32'
      • +
      +
      console.log(`This platform is ${process.platform}`);
      +

      The value 'android' may also be returned if the Node.js is built on the +Android operating system. However, Android support in Node.js +is experimental.

      +

      process.ppid#

      + + +

      The process.ppid property returns the PID of the parent of the +current process.

      +
      console.log(`The parent process is pid ${process.ppid}`);
      +

      process.release#

      + + +

      The process.release property returns an Object containing metadata related +to the current release, including URLs for the source tarball and headers-only +tarball.

      +

      process.release contains the following properties:

      +
        +
      • name <string> A value that will always be 'node' for Node.js. For +legacy io.js releases, this will be 'io.js'.
      • +
      • sourceUrl <string> an absolute URL pointing to a .tar.gz file containing +the source code of the current release.
      • +
      • headersUrl<string> an absolute URL pointing to a .tar.gz file containing +only the source header files for the current release. This file is +significantly smaller than the full source file and can be used for compiling +Node.js native add-ons.
      • +
      • libUrl <string> an absolute URL pointing to a node.lib file matching the +architecture and version of the current release. This file is used for +compiling Node.js native add-ons. This property is only present on Windows +builds of Node.js and will be missing on all other platforms.
      • +
      • lts <string> a string label identifying the LTS label for this release. +This property only exists for LTS releases and is undefined for all other +release types, including Current releases. +Valid values include the LTS Release Codenames (including those +that are no longer supported). A non-exhaustive example of +these codenames includes: +
          +
        • 'Dubnium' for the 10.x LTS line beginning with 10.13.0.
        • +
        • 'Erbium' for the 12.x LTS line beginning with 12.13.0. +For other LTS Release Codenames, see Node.js Changelog Archive
        • +
        +
      • +
      + +
      {
      +  name: 'node',
      +  lts: 'Erbium',
      +  sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz',
      +  headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz',
      +  libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib'
      +}
      +

      In custom builds from non-release versions of the source tree, only the +name property may be present. The additional properties should not be +relied upon to exist.

      +

      process.report#

      + + +

      process.report is an object whose methods are used to generate diagnostic +reports for the current process. Additional documentation is available in the +report documentation.

      +

      process.report.compact#

      + + +

      Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption.

      +
      console.log(`Reports are compact? ${process.report.compact}`);
      +

      process.report.directory#

      + + +

      Directory where the report is written. The default value is the empty string, +indicating that reports are written to the current working directory of the +Node.js process.

      +
      console.log(`Report directory is ${process.report.directory}`);
      +

      process.report.filename#

      + + +

      Filename where the report is written. If set to the empty string, the output +filename will be comprised of a timestamp, PID, and sequence number. The default +value is the empty string.

      +
      console.log(`Report filename is ${process.report.filename}`);
      +

      process.report.getReport([err])#

      + +
        +
      • err <Error> A custom error used for reporting the JavaScript stack.
      • +
      • Returns: <Object>
      • +
      +

      Returns a JavaScript Object representation of a diagnostic report for the +running process. The report's JavaScript stack trace is taken from err, if +present.

      +
      const data = process.report.getReport();
      +console.log(data.header.nodeJsVersion);
      +
      +// Similar to process.report.writeReport()
      +const fs = require('fs');
      +fs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8');
      +

      Additional documentation is available in the report documentation.

      +

      process.report.reportOnFatalError#

      + +

      Stability: 1 - Experimental

      + +

      If true, a diagnostic report is generated on fatal errors, such as out of +memory errors or failed C++ assertions.

      +
      console.log(`Report on fatal error: ${process.report.reportOnFatalError}`);
      +

      process.report.reportOnSignal#

      + + +

      If true, a diagnostic report is generated when the process receives the +signal specified by process.report.signal.

      +
      console.log(`Report on signal: ${process.report.reportOnSignal}`);
      +

      process.report.reportOnUncaughtException#

      + + +

      If true, a diagnostic report is generated on uncaught exception.

      +
      console.log(`Report on exception: ${process.report.reportOnUncaughtException}`);
      +

      process.report.signal#

      + + +

      The signal used to trigger the creation of a diagnostic report. Defaults to +'SIGUSR2'.

      +
      console.log(`Report signal: ${process.report.signal}`);
      +

      process.report.writeReport([filename][, err])#

      + +
        +
      • +

        filename <string> Name of the file where the report is written. This +should be a relative path, that will be appended to the directory specified in +process.report.directory, or the current working directory of the Node.js +process, if unspecified.

        +
      • +
      • +

        err <Error> A custom error used for reporting the JavaScript stack.

        +
      • +
      • +

        Returns: <string> Returns the filename of the generated report.

        +
      • +
      +

      Writes a diagnostic report to a file. If filename is not provided, the default +filename includes the date, time, PID, and a sequence number. The report's +JavaScript stack trace is taken from err, if present.

      +
      process.report.writeReport();
      +

      Additional documentation is available in the report documentation.

      +

      process.resourceUsage()#

      + +
        +
      • Returns: <Object> the resource usage for the current process. All of these +values come from the uv_getrusage call which returns +a uv_rusage_t struct. +
          +
        • userCPUTime <integer> maps to ru_utime computed in microseconds. +It is the same value as process.cpuUsage().user.
        • +
        • systemCPUTime <integer> maps to ru_stime computed in microseconds. +It is the same value as process.cpuUsage().system.
        • +
        • maxRSS <integer> maps to ru_maxrss which is the maximum resident set +size used in kilobytes.
        • +
        • sharedMemorySize <integer> maps to ru_ixrss but is not supported by +any platform.
        • +
        • unsharedDataSize <integer> maps to ru_idrss but is not supported by +any platform.
        • +
        • unsharedStackSize <integer> maps to ru_isrss but is not supported by +any platform.
        • +
        • minorPageFault <integer> maps to ru_minflt which is the number of +minor page faults for the process, see +this article for more details.
        • +
        • majorPageFault <integer> maps to ru_majflt which is the number of +major page faults for the process, see +this article for more details. This field is not +supported on Windows.
        • +
        • swappedOut <integer> maps to ru_nswap but is not supported by any +platform.
        • +
        • fsRead <integer> maps to ru_inblock which is the number of times the +file system had to perform input.
        • +
        • fsWrite <integer> maps to ru_oublock which is the number of times the +file system had to perform output.
        • +
        • ipcSent <integer> maps to ru_msgsnd but is not supported by any +platform.
        • +
        • ipcReceived <integer> maps to ru_msgrcv but is not supported by any +platform.
        • +
        • signalsCount <integer> maps to ru_nsignals but is not supported by any +platform.
        • +
        • voluntaryContextSwitches <integer> maps to ru_nvcsw which is the +number of times a CPU context switch resulted due to a process voluntarily +giving up the processor before its time slice was completed (usually to +await availability of a resource). This field is not supported on Windows.
        • +
        • involuntaryContextSwitches <integer> maps to ru_nivcsw which is the +number of times a CPU context switch resulted due to a higher priority +process becoming runnable or because the current process exceeded its +time slice. This field is not supported on Windows.
        • +
        +
      • +
      +
      console.log(process.resourceUsage());
      +/*
      +  Will output:
      +  {
      +    userCPUTime: 82872,
      +    systemCPUTime: 4143,
      +    maxRSS: 33164,
      +    sharedMemorySize: 0,
      +    unsharedDataSize: 0,
      +    unsharedStackSize: 0,
      +    minorPageFault: 2469,
      +    majorPageFault: 0,
      +    swappedOut: 0,
      +    fsRead: 0,
      +    fsWrite: 8,
      +    ipcSent: 0,
      +    ipcReceived: 0,
      +    signalsCount: 0,
      +    voluntaryContextSwitches: 79,
      +    involuntaryContextSwitches: 1
      +  }
      +*/
      +

      process.send(message[, sendHandle[, options]][, callback])#

      + +
        +
      • message <Object>
      • +
      • sendHandle <net.Server> | <net.Socket>
      • +
      • options <Object> used to parameterize the sending of certain types of +handles.options supports the following properties: +
          +
        • keepOpen <boolean> A value that can be used when passing instances of +net.Socket. When true, the socket is kept open in the sending process. +Default: false.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <boolean>
      • +
      +

      If Node.js is spawned with an IPC channel, the process.send() method can be +used to send messages to the parent process. Messages will be received as a +'message' event on the parent's ChildProcess object.

      +

      If Node.js was not spawned with an IPC channel, process.send will be +undefined.

      +

      The message goes through serialization and parsing. The resulting message might +not be the same as what is originally sent.

      +

      process.setegid(id)#

      + + +

      The process.setegid() method sets the effective group identity of the process. +(See setegid(2).) The id can be passed as either a numeric ID or a group +name string. If a group name is specified, this method blocks while resolving +the associated a numeric ID.

      +
      if (process.getegid && process.setegid) {
      +  console.log(`Current gid: ${process.getegid()}`);
      +  try {
      +    process.setegid(501);
      +    console.log(`New gid: ${process.getegid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set gid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.seteuid(id)#

      + + +

      The process.seteuid() method sets the effective user identity of the process. +(See seteuid(2).) The id can be passed as either a numeric ID or a username +string. If a username is specified, the method blocks while resolving the +associated numeric ID.

      +
      if (process.geteuid && process.seteuid) {
      +  console.log(`Current uid: ${process.geteuid()}`);
      +  try {
      +    process.seteuid(501);
      +    console.log(`New uid: ${process.geteuid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set uid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setgid(id)#

      + + +

      The process.setgid() method sets the group identity of the process. (See +setgid(2).) The id can be passed as either a numeric ID or a group name +string. If a group name is specified, this method blocks while resolving the +associated numeric ID.

      +
      if (process.getgid && process.setgid) {
      +  console.log(`Current gid: ${process.getgid()}`);
      +  try {
      +    process.setgid(501);
      +    console.log(`New gid: ${process.getgid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set gid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setgroups(groups)#

      + + +

      The process.setgroups() method sets the supplementary group IDs for the +Node.js process. This is a privileged operation that requires the Node.js +process to have root or the CAP_SETGID capability.

      +

      The groups array can contain numeric group IDs, group names or both.

      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setuid(id)#

      + + +

      The process.setuid(id) method sets the user identity of the process. (See +setuid(2).) The id can be passed as either a numeric ID or a username string. +If a username is specified, the method blocks while resolving the associated +numeric ID.

      +
      if (process.getuid && process.setuid) {
      +  console.log(`Current uid: ${process.getuid()}`);
      +  try {
      +    process.setuid(501);
      +    console.log(`New uid: ${process.getuid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set uid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setUncaughtExceptionCaptureCallback(fn)#

      + + +

      The process.setUncaughtExceptionCaptureCallback() function sets a function +that will be invoked when an uncaught exception occurs, which will receive the +exception value itself as its first argument.

      +

      If such a function is set, the 'uncaughtException' event will +not be emitted. If --abort-on-uncaught-exception was passed from the +command line or set through v8.setFlagsFromString(), the process will +not abort.

      +

      To unset the capture function, +process.setUncaughtExceptionCaptureCallback(null) may be used. Calling this +method with a non-null argument while another capture function is set will +throw an error.

      +

      Using this function is mutually exclusive with using the deprecated +domain built-in module.

      +

      process.stderr#

      + +

      The process.stderr property returns a stream connected to +stderr (fd 2). It is a net.Socket (which is a Duplex +stream) unless fd 2 refers to a file, in which case it is +a Writable stream.

      +

      process.stderr differs from other Node.js streams in important ways. See +note on process I/O for more information.

      +

      process.stderr.fd#

      + +

      This property refers to the value of underlying file descriptor of +process.stderr. The value is fixed at 2. In Worker threads, +this field does not exist.

      +

      process.stdin#

      + +

      The process.stdin property returns a stream connected to +stdin (fd 0). It is a net.Socket (which is a Duplex +stream) unless fd 0 refers to a file, in which case it is +a Readable stream.

      +

      For details of how to read from stdin see readable.read().

      +

      As a Duplex stream, process.stdin can also be used in "old" mode that +is compatible with scripts written for Node.js prior to v0.10. +For more information see Stream compatibility.

      +

      In "old" streams mode the stdin stream is paused by default, so one +must call process.stdin.resume() to read from it. Note also that calling +process.stdin.resume() itself would switch stream to "old" mode.

      +

      process.stdin.fd#

      + +

      This property refers to the value of underlying file descriptor of +process.stdin. The value is fixed at 0. In Worker threads, +this field does not exist.

      +

      process.stdout#

      + +

      The process.stdout property returns a stream connected to +stdout (fd 1). It is a net.Socket (which is a Duplex +stream) unless fd 1 refers to a file, in which case it is +a Writable stream.

      +

      For example, to copy process.stdin to process.stdout:

      +
      process.stdin.pipe(process.stdout);
      +

      process.stdout differs from other Node.js streams in important ways. See +note on process I/O for more information.

      +

      process.stdout.fd#

      + +

      This property refers to the value of underlying file descriptor of +process.stdout. The value is fixed at 1. In Worker threads, +this field does not exist.

      +

      A note on process I/O#

      +

      process.stdout and process.stderr differ from other Node.js streams in +important ways:

      +
        +
      1. They are used internally by console.log() and console.error(), +respectively.
      2. +
      3. Writes may be synchronous depending on what the stream is connected to +and whether the system is Windows or POSIX: +
          +
        • Files: synchronous on Windows and POSIX
        • +
        • TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
        • +
        • Pipes (and sockets): synchronous on Windows, asynchronous on POSIX
        • +
        +
      4. +
      +

      These behaviors are partly for historical reasons, as changing them would +create backward incompatibility, but they are also expected by some users.

      +

      Synchronous writes avoid problems such as output written with console.log() or +console.error() being unexpectedly interleaved, or not written at all if +process.exit() is called before an asynchronous write completes. See +process.exit() for more information.

      +

      Warning: Synchronous writes block the event loop until the write has +completed. This can be near instantaneous in the case of output to a file, but +under high system load, pipes that are not being read at the receiving end, or +with slow terminals or file systems, its possible for the event loop to be +blocked often enough and long enough to have severe negative performance +impacts. This may not be a problem when writing to an interactive terminal +session, but consider this particularly careful when doing production logging to +the process output streams.

      +

      To check if a stream is connected to a TTY context, check the isTTY +property.

      +

      For instance:

      +
      $ node -p "Boolean(process.stdin.isTTY)"
      +true
      +$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
      +false
      +$ node -p "Boolean(process.stdout.isTTY)"
      +true
      +$ node -p "Boolean(process.stdout.isTTY)" | cat
      +false
      +

      See the TTY documentation for more information.

      +

      process.throwDeprecation#

      + + +

      The initial value of process.throwDeprecation indicates whether the +--throw-deprecation flag is set on the current Node.js process. +process.throwDeprecation is mutable, so whether or not deprecation +warnings result in errors may be altered at runtime. See the +documentation for the 'warning' event and the +emitWarning() method for more information.

      +
      $ node --throw-deprecation -p "process.throwDeprecation"
      +true
      +$ node -p "process.throwDeprecation"
      +undefined
      +$ node
      +> process.emitWarning('test', 'DeprecationWarning');
      +undefined
      +> (node:26598) DeprecationWarning: test
      +> process.throwDeprecation = true;
      +true
      +> process.emitWarning('test', 'DeprecationWarning');
      +Thrown:
      +[DeprecationWarning: test] { name: 'DeprecationWarning' }
      +

      process.title#

      + + +

      The process.title property returns the current process title (i.e. returns +the current value of ps). Assigning a new value to process.title modifies +the current value of ps.

      +

      When a new value is assigned, different platforms will impose different maximum +length restrictions on the title. Usually such restrictions are quite limited. +For instance, on Linux and macOS, process.title is limited to the size of the +binary name plus the length of the command line arguments because setting the +process.title overwrites the argv memory of the process. Node.js v0.8 +allowed for longer process title strings by also overwriting the environ +memory but that was potentially insecure and confusing in some (rather obscure) +cases.

      +

      Assigning a value to process.title might not result in an accurate label +within process manager applications such as macOS Activity Monitor or Windows +Services Manager.

      +

      process.traceDeprecation#

      + + +

      The process.traceDeprecation property indicates whether the +--trace-deprecation flag is set on the current Node.js process. See the +documentation for the 'warning' event and the +emitWarning() method for more information about this +flag's behavior.

      +

      process.umask()#

      + +

      Stability: 0 - Deprecated. Calling process.umask() with no argument causes +the process-wide umask to be written twice. This introduces a race condition +between threads, and is a potential security vulnerability. There is no safe, +cross-platform alternative API.

      +

      process.umask() returns the Node.js process's file mode creation mask. Child +processes inherit the mask from the parent process.

      +

      process.umask(mask)#

      + + +

      process.umask(mask) sets the Node.js process's file mode creation mask. Child +processes inherit the mask from the parent process. Returns the previous mask.

      +
      const newmask = 0o022;
      +const oldmask = process.umask(newmask);
      +console.log(
      +  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
      +);
      +

      In Worker threads, process.umask(mask) will throw an exception.

      +

      process.uptime()#

      + + +

      The process.uptime() method returns the number of seconds the current Node.js +process has been running.

      +

      The return value includes fractions of a second. Use Math.floor() to get whole +seconds.

      +

      process.version#

      + + +

      The process.version property contains the Node.js version string.

      +
      console.log(`Version: ${process.version}`);
      +// Version: v14.8.0
      +

      To get the version string without the prepended v, use +process.versions.node.

      +

      process.versions#

      + + +

      The process.versions property returns an object listing the version strings of +Node.js and its dependencies. process.versions.modules indicates the current +ABI version, which is increased whenever a C++ API changes. Node.js will refuse +to load modules that were compiled against a different module ABI version.

      +
      console.log(process.versions);
      +

      Will generate an object similar to:

      +
      { node: '11.13.0',
      +  v8: '7.0.276.38-node.18',
      +  uv: '1.27.0',
      +  zlib: '1.2.11',
      +  brotli: '1.0.7',
      +  ares: '1.15.0',
      +  modules: '67',
      +  nghttp2: '1.34.0',
      +  napi: '4',
      +  llhttp: '1.1.1',
      +  http_parser: '2.8.0',
      +  openssl: '1.1.1b',
      +  cldr: '34.0',
      +  icu: '63.1',
      +  tz: '2018e',
      +  unicode: '11.0' }
      +

      Exit codes#

      +

      Node.js will normally exit with a 0 status code when no more async +operations are pending. The following status codes are used in other +cases:

      +
        +
      • 1 Uncaught Fatal Exception: There was an uncaught exception, +and it was not handled by a domain or an 'uncaughtException' event +handler.
      • +
      • 2: Unused (reserved by Bash for builtin misuse)
      • +
      • 3 Internal JavaScript Parse Error: The JavaScript source code +internal in the Node.js bootstrapping process caused a parse error. This +is extremely rare, and generally can only happen during development +of Node.js itself.
      • +
      • 4 Internal JavaScript Evaluation Failure: The JavaScript +source code internal in the Node.js bootstrapping process failed to +return a function value when evaluated. This is extremely rare, and +generally can only happen during development of Node.js itself.
      • +
      • 5 Fatal Error: There was a fatal unrecoverable error in V8. +Typically a message will be printed to stderr with the prefix FATAL ERROR.
      • +
      • 6 Non-function Internal Exception Handler: There was an +uncaught exception, but the internal fatal exception handler +function was somehow set to a non-function, and could not be called.
      • +
      • 7 Internal Exception Handler Run-Time Failure: There was an +uncaught exception, and the internal fatal exception handler +function itself threw an error while attempting to handle it. This +can happen, for example, if an 'uncaughtException' or +domain.on('error') handler throws an error.
      • +
      • 8: Unused. In previous versions of Node.js, exit code 8 sometimes +indicated an uncaught exception.
      • +
      • 9 Invalid Argument: Either an unknown option was specified, +or an option requiring a value was provided without a value.
      • +
      • 10 Internal JavaScript Run-Time Failure: The JavaScript +source code internal in the Node.js bootstrapping process threw an error +when the bootstrapping function was called. This is extremely rare, +and generally can only happen during development of Node.js itself.
      • +
      • 12 Invalid Debug Argument: The --inspect and/or --inspect-brk +options were set, but the port number chosen was invalid or unavailable.
      • +
      • >128 Signal Exits: If Node.js receives a fatal signal such as +SIGKILL or SIGHUP, then its exit code will be 128 plus the +value of the signal code. This is a standard POSIX practice, since +exit codes are defined to be 7-bit integers, and signal exits set +the high-order bit, and then contain the value of the signal code. +For example, signal SIGABRT has value 6, so the expected exit +code will be 128 + 6, or 134.
      • +
      +

      Punycode#

      + + +

      Stability: 0 - Deprecated

      +

      Source Code: lib/punycode.js

      +

      The version of the punycode module bundled in Node.js is being deprecated. +In a future major version of Node.js this module will be removed. Users +currently depending on the punycode module should switch to using the +userland-provided Punycode.js module instead.

      +

      The punycode module is a bundled version of the Punycode.js module. It +can be accessed using:

      +
      const punycode = require('punycode');
      +

      Punycode is a character encoding scheme defined by RFC 3492 that is +primarily intended for use in Internationalized Domain Names. Because host +names in URLs are limited to ASCII characters only, Domain Names that contain +non-ASCII characters must be converted into ASCII using the Punycode scheme. +For instance, the Japanese character that translates into the English word, +'example' is '例'. The Internationalized Domain Name, '例.com' (equivalent +to 'example.com') is represented by Punycode as the ASCII string +'xn--fsq.com'.

      +

      The punycode module provides a simple implementation of the Punycode standard.

      +

      The punycode module is a third-party dependency used by Node.js and +made available to developers as a convenience. Fixes or other modifications to +the module must be directed to the Punycode.js project.

      +

      punycode.decode(string)#

      + + +

      The punycode.decode() method converts a Punycode string of ASCII-only +characters to the equivalent string of Unicode codepoints.

      +
      punycode.decode('maana-pta'); // 'mañana'
      +punycode.decode('--dqo34k'); // '☃-⌘'
      +

      punycode.encode(string)#

      + + +

      The punycode.encode() method converts a string of Unicode codepoints to a +Punycode string of ASCII-only characters.

      +
      punycode.encode('mañana'); // 'maana-pta'
      +punycode.encode('☃-⌘'); // '--dqo34k'
      +

      punycode.toASCII(domain)#

      + + +

      The punycode.toASCII() method converts a Unicode string representing an +Internationalized Domain Name to Punycode. Only the non-ASCII parts of the +domain name will be converted. Calling punycode.toASCII() on a string that +already only contains ASCII characters will have no effect.

      +
      // encode domain names
      +punycode.toASCII('mañana.com');  // 'xn--maana-pta.com'
      +punycode.toASCII('☃-⌘.com');   // 'xn----dqo34k.com'
      +punycode.toASCII('example.com'); // 'example.com'
      +

      punycode.toUnicode(domain)#

      + + +

      The punycode.toUnicode() method converts a string representing a domain name +containing Punycode encoded characters into Unicode. Only the Punycode +encoded parts of the domain name are be converted.

      +
      // decode domain names
      +punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
      +punycode.toUnicode('xn----dqo34k.com');  // '☃-⌘.com'
      +punycode.toUnicode('example.com');       // 'example.com'
      +

      punycode.ucs2#

      + +

      punycode.ucs2.decode(string)#

      + + +

      The punycode.ucs2.decode() method returns an array containing the numeric +codepoint values of each Unicode symbol in the string.

      +
      punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]
      +// surrogate pair for U+1D306 tetragram for centre:
      +punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
      +

      punycode.ucs2.encode(codePoints)#

      + + +

      The punycode.ucs2.encode() method returns a string based on an array of +numeric code point values.

      +
      punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'
      +punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
      +

      punycode.version#

      + + +

      Returns a string identifying the current Punycode.js version number.

      +

      Query string#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/querystring.js

      +

      The querystring module provides utilities for parsing and formatting URL +query strings. It can be accessed using:

      +
      const querystring = require('querystring');
      +

      querystring.decode()#

      + +

      The querystring.decode() function is an alias for querystring.parse().

      +

      querystring.encode()#

      + +

      The querystring.encode() function is an alias for querystring.stringify().

      +

      querystring.escape(str)#

      + + +

      The querystring.escape() method performs URL percent-encoding on the given +str in a manner that is optimized for the specific requirements of URL +query strings.

      +

      The querystring.escape() method is used by querystring.stringify() and is +generally not expected to be used directly. It is exported primarily to allow +application code to provide a replacement percent-encoding implementation if +necessary by assigning querystring.escape to an alternative function.

      +

      querystring.parse(str[, sep[, eq[, options]]])#

      + +
        +
      • str <string> The URL query string to parse
      • +
      • sep <string> The substring used to delimit key and value pairs in the +query string. Default: '&'.
      • +
      • eq <string>. The substring used to delimit keys and values in the +query string. Default: '='.
      • +
      • options <Object> +
          +
        • decodeURIComponent <Function> The function to use when decoding +percent-encoded characters in the query string. Default: +querystring.unescape().
        • +
        • maxKeys <number> Specifies the maximum number of keys to parse. +Specify 0 to remove key counting limitations. Default: 1000.
        • +
        +
      • +
      +

      The querystring.parse() method parses a URL query string (str) into a +collection of key and value pairs.

      +

      For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:

      + +
      {
      +  foo: 'bar',
      +  abc: ['xyz', '123']
      +}
      +

      The object returned by the querystring.parse() method does not +prototypically inherit from the JavaScript Object. This means that typical +Object methods such as obj.toString(), obj.hasOwnProperty(), and others +are not defined and will not work.

      +

      By default, percent-encoded characters within the query string will be assumed +to use UTF-8 encoding. If an alternative character encoding is used, then an +alternative decodeURIComponent option will need to be specified:

      +
      // Assuming gbkDecodeURIComponent function already exists...
      +
      +querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
      +                  { decodeURIComponent: gbkDecodeURIComponent });
      +

      querystring.stringify(obj[, sep[, eq[, options]]])#

      + +
        +
      • obj <Object> The object to serialize into a URL query string
      • +
      • sep <string> The substring used to delimit key and value pairs in the +query string. Default: '&'.
      • +
      • eq <string>. The substring used to delimit keys and values in the +query string. Default: '='.
      • +
      • options +
          +
        • encodeURIComponent <Function> The function to use when converting +URL-unsafe characters to percent-encoding in the query string. Default: +querystring.escape().
        • +
        +
      • +
      +

      The querystring.stringify() method produces a URL query string from a +given obj by iterating through the object's "own properties".

      +

      It serializes the following types of values passed in obj: +<string> | <number> | <boolean> | <string[]> | <number[]> | <boolean[]> +Any other input values will be coerced to empty strings.

      +
      querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
      +// Returns 'foo=bar&baz=qux&baz=quux&corge='
      +
      +querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
      +// Returns 'foo:bar;baz:qux'
      +

      By default, characters requiring percent-encoding within the query string will +be encoded as UTF-8. If an alternative encoding is required, then an alternative +encodeURIComponent option will need to be specified:

      +
      // Assuming gbkEncodeURIComponent function already exists,
      +
      +querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
      +                      { encodeURIComponent: gbkEncodeURIComponent });
      +

      querystring.unescape(str)#

      + + +

      The querystring.unescape() method performs decoding of URL percent-encoded +characters on the given str.

      +

      The querystring.unescape() method is used by querystring.parse() and is +generally not expected to be used directly. It is exported primarily to allow +application code to provide a replacement decoding implementation if +necessary by assigning querystring.unescape to an alternative function.

      +

      By default, the querystring.unescape() method will attempt to use the +JavaScript built-in decodeURIComponent() method to decode. If that fails, +a safer equivalent that does not throw on malformed URLs will be used.

      +

      Readline#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/readline.js

      +

      The readline module provides an interface for reading data from a Readable +stream (such as process.stdin) one line at a time. It can be accessed +using:

      +
      const readline = require('readline');
      +

      The following simple example illustrates the basic use of the readline module.

      +
      const readline = require('readline');
      +
      +const rl = readline.createInterface({
      +  input: process.stdin,
      +  output: process.stdout
      +});
      +
      +rl.question('What do you think of Node.js? ', (answer) => {
      +  // TODO: Log the answer in a database
      +  console.log(`Thank you for your valuable feedback: ${answer}`);
      +
      +  rl.close();
      +});
      +

      Once this code is invoked, the Node.js application will not terminate until the +readline.Interface is closed because the interface waits for data to be +received on the input stream.

      +

      Class: Interface#

      + + +

      Instances of the readline.Interface class are constructed using the +readline.createInterface() method. Every instance is associated with a +single input Readable stream and a single output Writable stream. +The output stream is used to print prompts for user input that arrives on, +and is read from, the input stream.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted when one of the following occur:

      +
        +
      • The rl.close() method is called and the readline.Interface instance has +relinquished control over the input and output streams;
      • +
      • The input stream receives its 'end' event;
      • +
      • The input stream receives <ctrl>-D to signal end-of-transmission (EOT);
      • +
      • The input stream receives <ctrl>-C to signal SIGINT and there is no +'SIGINT' event listener registered on the readline.Interface instance.
      • +
      +

      The listener function is called without passing any arguments.

      +

      The readline.Interface instance is finished once the 'close' event is +emitted.

      +

      Event: 'line'#

      + +

      The 'line' event is emitted whenever the input stream receives an +end-of-line input (\n, \r, or \r\n). This usually occurs when the user +presses the <Enter>, or <Return> keys.

      +

      The listener function is called with a string containing the single line of +received input.

      +
      rl.on('line', (input) => {
      +  console.log(`Received: ${input}`);
      +});
      +

      Event: 'pause'#

      + +

      The 'pause' event is emitted when one of the following occur:

      +
        +
      • The input stream is paused.
      • +
      • The input stream is not paused and receives the 'SIGCONT' event. (See +events 'SIGTSTP' and 'SIGCONT'.)
      • +
      +

      The listener function is called without passing any arguments.

      +
      rl.on('pause', () => {
      +  console.log('Readline paused.');
      +});
      +

      Event: 'resume'#

      + +

      The 'resume' event is emitted whenever the input stream is resumed.

      +

      The listener function is called without passing any arguments.

      +
      rl.on('resume', () => {
      +  console.log('Readline resumed.');
      +});
      +

      Event: 'SIGCONT'#

      + +

      The 'SIGCONT' event is emitted when a Node.js process previously moved into +the background using <ctrl>-Z (i.e. SIGTSTP) is then brought back to the +foreground using fg(1p).

      +

      If the input stream was paused before the SIGTSTP request, this event will +not be emitted.

      +

      The listener function is invoked without passing any arguments.

      +
      rl.on('SIGCONT', () => {
      +  // `prompt` will automatically resume the stream
      +  rl.prompt();
      +});
      +

      The 'SIGCONT' event is not supported on Windows.

      +

      Event: 'SIGINT'#

      + +

      The 'SIGINT' event is emitted whenever the input stream receives a +<ctrl>-C input, known typically as SIGINT. If there are no 'SIGINT' event +listeners registered when the input stream receives a SIGINT, the 'pause' +event will be emitted.

      +

      The listener function is invoked without passing any arguments.

      +
      rl.on('SIGINT', () => {
      +  rl.question('Are you sure you want to exit? ', (answer) => {
      +    if (answer.match(/^y(es)?$/i)) rl.pause();
      +  });
      +});
      +

      Event: 'SIGTSTP'#

      + +

      The 'SIGTSTP' event is emitted when the input stream receives a <ctrl>-Z +input, typically known as SIGTSTP. If there are no 'SIGTSTP' event listeners +registered when the input stream receives a SIGTSTP, the Node.js process +will be sent to the background.

      +

      When the program is resumed using fg(1p), the 'pause' and 'SIGCONT' events +will be emitted. These can be used to resume the input stream.

      +

      The 'pause' and 'SIGCONT' events will not be emitted if the input was +paused before the process was sent to the background.

      +

      The listener function is invoked without passing any arguments.

      +
      rl.on('SIGTSTP', () => {
      +  // This will override SIGTSTP and prevent the program from going to the
      +  // background.
      +  console.log('Caught SIGTSTP.');
      +});
      +

      The 'SIGTSTP' event is not supported on Windows.

      +

      rl.close()#

      + +

      The rl.close() method closes the readline.Interface instance and +relinquishes control over the input and output streams. When called, +the 'close' event will be emitted.

      +

      Calling rl.close() does not immediately stop other events (including 'line') +from being emitted by the readline.Interface instance.

      +

      rl.pause()#

      + +

      The rl.pause() method pauses the input stream, allowing it to be resumed +later if necessary.

      +

      Calling rl.pause() does not immediately pause other events (including +'line') from being emitted by the readline.Interface instance.

      +

      rl.prompt([preserveCursor])#

      + +
        +
      • preserveCursor <boolean> If true, prevents the cursor placement from +being reset to 0.
      • +
      +

      The rl.prompt() method writes the readline.Interface instances configured +prompt to a new line in output in order to provide a user with a new +location at which to provide input.

      +

      When called, rl.prompt() will resume the input stream if it has been +paused.

      +

      If the readline.Interface was created with output set to null or +undefined the prompt is not written.

      +

      rl.question(query, callback)#

      + +
        +
      • query <string> A statement or query to write to output, prepended to the +prompt.
      • +
      • callback <Function> A callback function that is invoked with the user's +input in response to the query.
      • +
      +

      The rl.question() method displays the query by writing it to the output, +waits for user input to be provided on input, then invokes the callback +function passing the provided input as the first argument.

      +

      When called, rl.question() will resume the input stream if it has been +paused.

      +

      If the readline.Interface was created with output set to null or +undefined the query is not written.

      +

      Example usage:

      +
      rl.question('What is your favorite food? ', (answer) => {
      +  console.log(`Oh, so your favorite food is ${answer}`);
      +});
      +

      The callback function passed to rl.question() does not follow the typical +pattern of accepting an Error object or null as the first argument. +The callback is called with the provided answer as the only argument.

      +

      rl.resume()#

      + +

      The rl.resume() method resumes the input stream if it has been paused.

      +

      rl.setPrompt(prompt)#

      + + +

      The rl.setPrompt() method sets the prompt that will be written to output +whenever rl.prompt() is called.

      +

      rl.write(data[, key])#

      + + +

      The rl.write() method will write either data or a key sequence identified +by key to the output. The key argument is supported only if output is +a TTY text terminal. See TTY keybindings for a list of key +combinations.

      +

      If key is specified, data is ignored.

      +

      When called, rl.write() will resume the input stream if it has been +paused.

      +

      If the readline.Interface was created with output set to null or +undefined the data and key are not written.

      +
      rl.write('Delete this!');
      +// Simulate Ctrl+u to delete the line written previously
      +rl.write(null, { ctrl: true, name: 'u' });
      +

      The rl.write() method will write the data to the readline Interface's +input as if it were provided by the user.

      +

      rl[Symbol.asyncIterator]()#

      + + +

      Create an AsyncIterator object that iterates through each line in the input +stream as a string. This method allows asynchronous iteration of +readline.Interface objects through for await...of loops.

      +

      Errors in the input stream are not forwarded.

      +

      If the loop is terminated with break, throw, or return, +rl.close() will be called. In other words, iterating over a +readline.Interface will always consume the input stream fully.

      +

      Performance is not on par with the traditional 'line' event API. Use 'line' +instead for performance-sensitive applications.

      +
      async function processLineByLine() {
      +  const rl = readline.createInterface({
      +    // ...
      +  });
      +
      +  for await (const line of rl) {
      +    // Each line in the readline input will be successively available here as
      +    // `line`.
      +  }
      +}
      +

      rl.line#

      + + +

      The current input data being processed by node.

      +

      This can be used when collecting input from a TTY stream to retrieve the +current value that has been processed thus far, prior to the line event +being emitted. Once the line event has been emitted, this property will +be an empty string.

      +

      Be aware that modifying the value during the instance runtime may have +unintended consequences if rl.cursor is not also controlled.

      +

      If not using a TTY stream for input, use the 'line' event.

      +

      One possible use case would be as follows:

      +
      const values = ['lorem ipsum', 'dolor sit amet'];
      +const rl = readline.createInterface(process.stdin);
      +const showResults = debounce(() => {
      +  console.log(
      +    '\n',
      +    values.filter((val) => val.startsWith(rl.line)).join(' ')
      +  );
      +}, 300);
      +process.stdin.on('keypress', (c, k) => {
      +  showResults();
      +});
      +

      rl.cursor#

      + + +

      The cursor position relative to rl.line.

      +

      This will track where the current cursor lands in the input string, when +reading input from a TTY stream. The position of cursor determines the +portion of the input string that will be modified as input is processed, +as well as the column where the terminal caret will be rendered.

      +

      rl.getCursorPos()#

      + +
        +
      • Returns: <Object> +
          +
        • rows <number> the row of the prompt the cursor currently lands on
        • +
        • cols <number> the screen column the cursor currently lands on
        • +
        +
      • +
      +

      Returns the real position of the cursor in relation to the input +prompt + string. Long input (wrapping) strings, as well as multiple +line prompts are included in the calculations.

      +

      readline.clearLine(stream, dir[, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • dir <number> +
          +
        • -1: to the left from cursor
        • +
        • 1: to the right from cursor
        • +
        • 0: the entire line
        • +
        +
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.clearLine() method clears current line of given TTY stream +in a specified direction identified by dir.

      +

      readline.clearScreenDown(stream[, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.clearScreenDown() method clears the given TTY stream from +the current position of the cursor down.

      +

      readline.createInterface(options)#

      + +
        +
      • options <Object> +
          +
        • input <stream.Readable> The Readable stream to listen to. This option +is required.
        • +
        • output <stream.Writable> The Writable stream to write readline data +to.
        • +
        • completer <Function> An optional function used for Tab autocompletion.
        • +
        • terminal <boolean> true if the input and output streams should be +treated like a TTY, and have ANSI/VT100 escape codes written to it. +Default: checking isTTY on the output stream upon instantiation.
        • +
        • historySize <number> Maximum number of history lines retained. To disable +the history set this value to 0. This option makes sense only if +terminal is set to true by the user or by an internal output check, +otherwise the history caching mechanism is not initialized at all. +Default: 30.
        • +
        • prompt <string> The prompt string to use. Default: '> '.
        • +
        • crlfDelay <number> If the delay between \r and \n exceeds +crlfDelay milliseconds, both \r and \n will be treated as separate +end-of-line input. crlfDelay will be coerced to a number no less than +100. It can be set to Infinity, in which case \r followed by \n +will always be considered a single newline (which may be reasonable for +reading files with \r\n line delimiter). Default: 100.
        • +
        • removeHistoryDuplicates <boolean> If true, when a new input line added +to the history list duplicates an older one, this removes the older line +from the list. Default: false.
        • +
        • escapeCodeTimeout <number> The duration readline will wait for a +character (when reading an ambiguous key sequence in milliseconds one that +can both form a complete key sequence using the input read so far and can +take additional input to complete a longer key sequence). +Default: 500.
        • +
        +
      • +
      +

      The readline.createInterface() method creates a new readline.Interface +instance.

      +
      const readline = require('readline');
      +const rl = readline.createInterface({
      +  input: process.stdin,
      +  output: process.stdout
      +});
      +

      Once the readline.Interface instance is created, the most common case is to +listen for the 'line' event:

      +
      rl.on('line', (line) => {
      +  console.log(`Received: ${line}`);
      +});
      +

      If terminal is true for this instance then the output stream will get +the best compatibility if it defines an output.columns property and emits +a 'resize' event on the output if or when the columns ever change +(process.stdout does this automatically when it is a TTY).

      +

      Use of the completer function#

      +

      The completer function takes the current line entered by the user +as an argument, and returns an Array with 2 entries:

      +
        +
      • An Array with matching entries for the completion.
      • +
      • The substring that was used for the matching.
      • +
      +

      For instance: [[substr1, substr2, ...], originalsubstring].

      +
      function completer(line) {
      +  const completions = '.help .error .exit .quit .q'.split(' ');
      +  const hits = completions.filter((c) => c.startsWith(line));
      +  // Show all completions if none found
      +  return [hits.length ? hits : completions, line];
      +}
      +

      The completer function can be called asynchronously if it accepts two +arguments:

      +
      function completer(linePartial, callback) {
      +  callback(null, [['123'], linePartial]);
      +}
      +

      readline.cursorTo(stream, x[, y][, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • x <number>
      • +
      • y <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.cursorTo() method moves cursor to the specified position in a +given TTY stream.

      +

      readline.emitKeypressEvents(stream[, interface])#

      + + +

      The readline.emitKeypressEvents() method causes the given Readable +stream to begin emitting 'keypress' events corresponding to received input.

      +

      Optionally, interface specifies a readline.Interface instance for which +autocompletion is disabled when copy-pasted input is detected.

      +

      If the stream is a TTY, then it must be in raw mode.

      +

      This is automatically called by any readline instance on its input if the +input is a terminal. Closing the readline instance does not stop +the input from emitting 'keypress' events.

      +
      readline.emitKeypressEvents(process.stdin);
      +if (process.stdin.isTTY)
      +  process.stdin.setRawMode(true);
      +

      readline.moveCursor(stream, dx, dy[, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • dx <number>
      • +
      • dy <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.moveCursor() method moves the cursor relative to its current +position in a given TTY stream.

      +

      Example: Tiny CLI#

      +

      The following example illustrates the use of readline.Interface class to +implement a small command-line interface:

      +
      const readline = require('readline');
      +const rl = readline.createInterface({
      +  input: process.stdin,
      +  output: process.stdout,
      +  prompt: 'OHAI> '
      +});
      +
      +rl.prompt();
      +
      +rl.on('line', (line) => {
      +  switch (line.trim()) {
      +    case 'hello':
      +      console.log('world!');
      +      break;
      +    default:
      +      console.log(`Say what? I might have heard '${line.trim()}'`);
      +      break;
      +  }
      +  rl.prompt();
      +}).on('close', () => {
      +  console.log('Have a great day!');
      +  process.exit(0);
      +});
      +

      Example: Read file stream line-by-Line#

      +

      A common use case for readline is to consume an input file one line at a +time. The easiest way to do so is leveraging the fs.ReadStream API as +well as a for await...of loop:

      +
      const fs = require('fs');
      +const readline = require('readline');
      +
      +async function processLineByLine() {
      +  const fileStream = fs.createReadStream('input.txt');
      +
      +  const rl = readline.createInterface({
      +    input: fileStream,
      +    crlfDelay: Infinity
      +  });
      +  // Note: we use the crlfDelay option to recognize all instances of CR LF
      +  // ('\r\n') in input.txt as a single line break.
      +
      +  for await (const line of rl) {
      +    // Each line in input.txt will be successively available here as `line`.
      +    console.log(`Line from file: ${line}`);
      +  }
      +}
      +
      +processLineByLine();
      +

      Alternatively, one could use the 'line' event:

      +
      const fs = require('fs');
      +const readline = require('readline');
      +
      +const rl = readline.createInterface({
      +  input: fs.createReadStream('sample.txt'),
      +  crlfDelay: Infinity
      +});
      +
      +rl.on('line', (line) => {
      +  console.log(`Line from file: ${line}`);
      +});
      +

      Currently, for await...of loop can be a bit slower. If async / await +flow and speed are both essential, a mixed approach can be applied:

      +
      const { once } = require('events');
      +const { createReadStream } = require('fs');
      +const { createInterface } = require('readline');
      +
      +(async function processLineByLine() {
      +  try {
      +    const rl = createInterface({
      +      input: createReadStream('big-file.txt'),
      +      crlfDelay: Infinity
      +    });
      +
      +    rl.on('line', (line) => {
      +      // Process the line.
      +    });
      +
      +    await once(rl, 'close');
      +
      +    console.log('File processed.');
      +  } catch (err) {
      +    console.error(err);
      +  }
      +})();
      +

      TTY keybindings#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      KeybindingsDescriptionNotes
      ctrl + shift + backspaceDelete line leftDoesn't work on Linux, Mac and Windows
      ctrl + shift + deleteDelete line rightDoesn't work on Mac
      ctrl + cEmit SIGINT or close the readline instance
      ctrl + hDelete left
      ctrl + dDelete right or close the readline instance in case the current line is empty / EOFDoesn't work on Windows
      ctrl + uDelete from the current position to the line start
      ctrl + kDelete from the current position to the end of line
      ctrl + aGo to start of line
      ctrl + eGo to to end of line
      ctrl + bBack one character
      ctrl + fForward one character
      ctrl + lClear screen
      ctrl + nNext history item
      ctrl + pPrevious history item
      ctrl + zMoves running process into background. Type + fg and press enter + to return.Doesn't work on Windows
      ctrl + w or ctrl + + backspaceDelete backward to a word boundaryctrl + backspace Doesn't + work on Linux, Mac and Windows
      ctrl + deleteDelete forward to a word boundaryDoesn't work on Mac
      ctrl + left or + meta + bWord leftctrl + left Doesn't work + on Mac
      ctrl + right or + meta + fWord rightctrl + right Doesn't work + on Mac
      meta + d or meta + + deleteDelete word rightmeta + delete Doesn't work + on windows
      meta + backspaceDelete word leftDoesn't work on Mac
      +

      REPL#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/repl.js

      +

      The repl module provides a Read-Eval-Print-Loop (REPL) implementation that +is available both as a standalone program or includible in other applications. +It can be accessed using:

      +
      const repl = require('repl');
      +

      Design and features#

      +

      The repl module exports the repl.REPLServer class. While running, +instances of repl.REPLServer will accept individual lines of user input, +evaluate those according to a user-defined evaluation function, then output the +result. Input and output may be from stdin and stdout, respectively, or may +be connected to any Node.js stream.

      +

      Instances of repl.REPLServer support automatic completion of inputs, +completion preview, simplistic Emacs-style line editing, multi-line inputs, +ZSH-like reverse-i-search, ZSH-like substring-based history search, +ANSI-styled output, saving and restoring current REPL session state, error +recovery, and customizable evaluation functions. Terminals that do not support +ANSI styles and Emacs-style line editing automatically fall back to a limited +feature set.

      +

      Commands and special keys#

      +

      The following special commands are supported by all REPL instances:

      +
        +
      • .break: When in the process of inputting a multi-line expression, entering +the .break command (or pressing the <ctrl>-C key combination) will abort +further input or processing of that expression.
      • +
      • .clear: Resets the REPL context to an empty object and clears any +multi-line expression being input.
      • +
      • .exit: Close the I/O stream, causing the REPL to exit.
      • +
      • .help: Show this list of special commands.
      • +
      • .save: Save the current REPL session to a file: +> .save ./file/to/save.js
      • +
      • .load: Load a file into the current REPL session. +> .load ./file/to/load.js
      • +
      • .editor: Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel).
      • +
      +
      > .editor
      +// Entering editor mode (^D to finish, ^C to cancel)
      +function welcome(name) {
      +  return `Hello ${name}!`;
      +}
      +
      +welcome('Node.js User');
      +
      +// ^D
      +'Hello Node.js User!'
      +>
      +

      The following key combinations in the REPL have these special effects:

      +
        +
      • <ctrl>-C: When pressed once, has the same effect as the .break command. +When pressed twice on a blank line, has the same effect as the .exit +command.
      • +
      • <ctrl>-D: Has the same effect as the .exit command.
      • +
      • <tab>: When pressed on a blank line, displays global and local (scope) +variables. When pressed while entering other input, displays relevant +autocompletion options.
      • +
      +

      For key bindings related to the reverse-i-search, see reverse-i-search. +For all other key bindings, see TTY keybindings.

      +

      Default evaluation#

      +

      By default, all instances of repl.REPLServer use an evaluation function +that evaluates JavaScript expressions and provides access to Node.js built-in +modules. This default behavior can be overridden by passing in an alternative +evaluation function when the repl.REPLServer instance is created.

      +

      JavaScript expressions#

      +

      The default evaluator supports direct evaluation of JavaScript expressions:

      +
      > 1 + 1
      +2
      +> const m = 2
      +undefined
      +> m + 1
      +3
      +

      Unless otherwise scoped within blocks or functions, variables declared +either implicitly or using the const, let, or var keywords +are declared at the global scope.

      +

      Global and local scope#

      +

      The default evaluator provides access to any variables that exist in the global +scope. It is possible to expose a variable to the REPL explicitly by assigning +it to the context object associated with each REPLServer:

      +
      const repl = require('repl');
      +const msg = 'message';
      +
      +repl.start('> ').context.m = msg;
      +

      Properties in the context object appear as local within the REPL:

      +
      $ node repl_test.js
      +> m
      +'message'
      +

      Context properties are not read-only by default. To specify read-only globals, +context properties must be defined using Object.defineProperty():

      +
      const repl = require('repl');
      +const msg = 'message';
      +
      +const r = repl.start('> ');
      +Object.defineProperty(r.context, 'm', {
      +  configurable: false,
      +  enumerable: true,
      +  value: msg
      +});
      +

      Accessing core Node.js modules#

      +

      The default evaluator will automatically load Node.js core modules into the +REPL environment when used. For instance, unless otherwise declared as a +global or scoped variable, the input fs will be evaluated on-demand as +global.fs = require('fs').

      +
      > fs.createReadStream('./some/file');
      +

      Global uncaught exceptions#

      + +

      The REPL uses the domain module to catch all uncaught exceptions for that +REPL session.

      +

      This use of the domain module in the REPL has these side effects:

      + +

      As standalone program:

      +
      process.on('uncaughtException', () => console.log('Uncaught'));
      +
      +throw new Error('foobar');
      +// Uncaught
      +

      When used in another application:

      +
      process.on('uncaughtException', () => console.log('Uncaught'));
      +// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`
      +// cannot be used in the REPL
      +
      +throw new Error('foobar');
      +// Thrown:
      +// Error: foobar
      +

      Assignment of the _ (underscore) variable#

      + +

      The default evaluator will, by default, assign the result of the most recently +evaluated expression to the special variable _ (underscore). +Explicitly setting _ to a value will disable this behavior.

      +
      > [ 'a', 'b', 'c' ]
      +[ 'a', 'b', 'c' ]
      +> _.length
      +3
      +> _ += 1
      +Expression assignment to _ now disabled.
      +4
      +> 1 + 1
      +2
      +> _
      +4
      +

      Similarly, _error will refer to the last seen error, if there was any. +Explicitly setting _error to a value will disable this behavior.

      +
      > throw new Error('foo');
      +Error: foo
      +> _error.message
      +'foo'
      +

      await keyword#

      +

      With the --experimental-repl-await command line option specified, +experimental support for the await keyword is enabled.

      +
      > await Promise.resolve(123)
      +123
      +> await Promise.reject(new Error('REPL await'))
      +Error: REPL await
      +    at repl:1:45
      +> const timeout = util.promisify(setTimeout);
      +undefined
      +> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
      +1002
      +undefined
      +

      Reverse-i-search#

      + +

      The REPL supports bi-directional reverse-i-search similar to ZSH. It is +triggered with <ctrl> + R to search backward and <ctrl> + S to search +forward.

      +

      Duplicated history entires will be skipped.

      +

      Entries are accepted as soon as any button is pressed that doesn't correspond +with the reverse search. Cancelling is possible by pressing escape or +<ctrl> + C.

      +

      Changing the direction immediately searches for the next entry in the expected +direction from the current position on.

      +

      Custom evaluation functions#

      +

      When a new repl.REPLServer is created, a custom evaluation function may be +provided. This can be used, for instance, to implement fully customized REPL +applications.

      +

      The following illustrates a hypothetical example of a REPL that performs +translation of text from one language to another:

      +
      const repl = require('repl');
      +const { Translator } = require('translator');
      +
      +const myTranslator = new Translator('en', 'fr');
      +
      +function myEval(cmd, context, filename, callback) {
      +  callback(null, myTranslator.translate(cmd));
      +}
      +
      +repl.start({ prompt: '> ', eval: myEval });
      +

      Recoverable errors#

      +

      As a user is typing input into the REPL prompt, pressing the <enter> key will +send the current line of input to the eval function. In order to support +multi-line input, the eval function can return an instance of repl.Recoverable +to the provided callback function:

      +
      function myEval(cmd, context, filename, callback) {
      +  let result;
      +  try {
      +    result = vm.runInThisContext(cmd);
      +  } catch (e) {
      +    if (isRecoverableError(e)) {
      +      return callback(new repl.Recoverable(e));
      +    }
      +  }
      +  callback(null, result);
      +}
      +
      +function isRecoverableError(error) {
      +  if (error.name === 'SyntaxError') {
      +    return /^(Unexpected end of input|Unexpected token)/.test(error.message);
      +  }
      +  return false;
      +}
      +

      Customizing REPL output#

      +

      By default, repl.REPLServer instances format output using the +util.inspect() method before writing the output to the provided Writable +stream (process.stdout by default). The showProxy inspection option is set +to true by default and the colors option is set to true depending on the +REPL's useColors option.

      +

      The useColors boolean option can be specified at construction to instruct the +default writer to use ANSI style codes to colorize the output from the +util.inspect() method.

      +

      If the REPL is run as standalone program, it is also possible to change the +REPL's inspection defaults from inside the REPL by using the +inspect.replDefaults property which mirrors the defaultOptions from +util.inspect().

      +
      > util.inspect.replDefaults.compact = false;
      +false
      +> [1]
      +[
      +  1
      +]
      +>
      +

      To fully customize the output of a repl.REPLServer instance pass in a new +function for the writer option on construction. The following example, for +instance, simply converts any input text to upper case:

      +
      const repl = require('repl');
      +
      +const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });
      +
      +function myEval(cmd, context, filename, callback) {
      +  callback(null, cmd);
      +}
      +
      +function myWriter(output) {
      +  return output.toUpperCase();
      +}
      +

      Class: REPLServer#

      + + +

      Instances of repl.REPLServer are created using the repl.start() method +or directly using the JavaScript new keyword.

      +
      const repl = require('repl');
      +
      +const options = { useColors: true };
      +
      +const firstInstance = repl.start(options);
      +const secondInstance = new repl.REPLServer(options);
      +

      Event: 'exit'#

      + +

      The 'exit' event is emitted when the REPL is exited either by receiving the +.exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, +or by pressing <ctrl>-D to signal 'end' on the input stream. The listener +callback is invoked without any arguments.

      +
      replServer.on('exit', () => {
      +  console.log('Received "exit" event from repl!');
      +  process.exit();
      +});
      +

      Event: 'reset'#

      + +

      The 'reset' event is emitted when the REPL's context is reset. This occurs +whenever the .clear command is received as input unless the REPL is using +the default evaluator and the repl.REPLServer instance was created with the +useGlobal option set to true. The listener callback will be called with a +reference to the context object as the only argument.

      +

      This can be used primarily to re-initialize REPL context to some pre-defined +state:

      +
      const repl = require('repl');
      +
      +function initializeContext(context) {
      +  context.m = 'test';
      +}
      +
      +const r = repl.start({ prompt: '> ' });
      +initializeContext(r.context);
      +
      +r.on('reset', initializeContext);
      +

      When this code is executed, the global 'm' variable can be modified but then +reset to its initial value using the .clear command:

      +
      $ ./node example.js
      +> m
      +'test'
      +> m = 1
      +1
      +> m
      +1
      +> .clear
      +Clearing context...
      +> m
      +'test'
      +>
      +

      replServer.defineCommand(keyword, cmd)#

      + +
        +
      • keyword <string> The command keyword (without a leading . character).
      • +
      • cmd <Object> | <Function> The function to invoke when the command is processed.
      • +
      +

      The replServer.defineCommand() method is used to add new .-prefixed commands +to the REPL instance. Such commands are invoked by typing a . followed by the +keyword. The cmd is either a Function or an Object with the following +properties:

      +
        +
      • help <string> Help text to be displayed when .help is entered (Optional).
      • +
      • action <Function> The function to execute, optionally accepting a single +string argument.
      • +
      +

      The following example shows two new commands added to the REPL instance:

      +
      const repl = require('repl');
      +
      +const replServer = repl.start({ prompt: '> ' });
      +replServer.defineCommand('sayhello', {
      +  help: 'Say hello',
      +  action(name) {
      +    this.clearBufferedCommand();
      +    console.log(`Hello, ${name}!`);
      +    this.displayPrompt();
      +  }
      +});
      +replServer.defineCommand('saybye', function saybye() {
      +  console.log('Goodbye!');
      +  this.close();
      +});
      +

      The new commands can then be used from within the REPL instance:

      +
      > .sayhello Node.js User
      +Hello, Node.js User!
      +> .saybye
      +Goodbye!
      +

      replServer.displayPrompt([preserveCursor])#

      + + +

      The replServer.displayPrompt() method readies the REPL instance for input +from the user, printing the configured prompt to a new line in the output +and resuming the input to accept new input.

      +

      When multi-line input is being entered, an ellipsis is printed rather than the +'prompt'.

      +

      When preserveCursor is true, the cursor placement will not be reset to 0.

      +

      The replServer.displayPrompt method is primarily intended to be called from +within the action function for commands registered using the +replServer.defineCommand() method.

      +

      replServer.clearBufferedCommand()#

      + +

      The replServer.clearBufferedCommand() method clears any command that has been +buffered but not yet executed. This method is primarily intended to be +called from within the action function for commands registered using the +replServer.defineCommand() method.

      +

      replServer.parseREPLKeyword(keyword[, rest])#

      + +

      Stability: 0 - Deprecated.

      +
        +
      • keyword <string> the potential keyword to parse and execute
      • +
      • rest <any> any parameters to the keyword command
      • +
      • Returns: <boolean>
      • +
      +

      An internal method used to parse and execute REPLServer keywords. +Returns true if keyword is a valid keyword, otherwise false.

      +

      replServer.setupHistory(historyPath, callback)#

      + + +

      Initializes a history log file for the REPL instance. When executing the +Node.js binary and using the command line REPL, a history file is initialized +by default. However, this is not the case when creating a REPL +programmatically. Use this method to initialize a history log file when working +with REPL instances programmatically.

      +

      repl.start([options])#

      + +
        +
      • options <Object> | <string> +
          +
        • prompt <string> The input prompt to display. Default: '> ' +(with a trailing space).
        • +
        • input <stream.Readable> The Readable stream from which REPL input will +be read. Default: process.stdin.
        • +
        • output <stream.Writable> The Writable stream to which REPL output will +be written. Default: process.stdout.
        • +
        • terminal <boolean> If true, specifies that the output should be +treated as a TTY terminal. +Default: checking the value of the isTTY property on the output +stream upon instantiation.
        • +
        • eval <Function> The function to be used when evaluating each given line +of input. Default: an async wrapper for the JavaScript eval() +function. An eval function can error with repl.Recoverable to indicate +the input was incomplete and prompt for additional lines.
        • +
        • useColors <boolean> If true, specifies that the default writer +function should include ANSI color styling to REPL output. If a custom +writer function is provided then this has no effect. Default: checking +color support on the output stream if the REPL instance's terminal value +is true.
        • +
        • useGlobal <boolean> If true, specifies that the default evaluation +function will use the JavaScript global as the context as opposed to +creating a new separate context for the REPL instance. The node CLI REPL +sets this value to true. Default: false.
        • +
        • ignoreUndefined <boolean> If true, specifies that the default writer +will not output the return value of a command if it evaluates to +undefined. Default: false.
        • +
        • writer <Function> The function to invoke to format the output of each + command before writing to output. Default: util.inspect().
        • +
        • completer <Function> An optional function used for custom Tab auto + completion. See readline.InterfaceCompleter for an example.
        • +
        • replMode <symbol> A flag that specifies whether the default evaluator +executes all JavaScript commands in strict mode or default (sloppy) mode. +Acceptable values are: +
            +
          • repl.REPL_MODE_SLOPPY to evaluate expressions in sloppy mode.
          • +
          • repl.REPL_MODE_STRICT to evaluate expressions in strict mode. This is +equivalent to prefacing every repl statement with 'use strict'.
          • +
          +
        • +
        • breakEvalOnSigint <boolean> Stop evaluating the current piece of code when +SIGINT is received, such as when Ctrl+C is pressed. This cannot be used +together with a custom eval function. Default: false.
        • +
        • preview <boolean> Defines if the repl prints autocomplete and output +previews or not. Default: true with the default eval function and +false in case a custom eval function is used. If terminal is falsy, then +there are no previews and the value of preview has no effect.
        • +
        +
      • +
      • Returns: <repl.REPLServer>
      • +
      +

      The repl.start() method creates and starts a repl.REPLServer instance.

      +

      If options is a string, then it specifies the input prompt:

      +
      const repl = require('repl');
      +
      +// a Unix style prompt
      +repl.start('$ ');
      +

      The Node.js REPL#

      +

      Node.js itself uses the repl module to provide its own interactive interface +for executing JavaScript. This can be used by executing the Node.js binary +without passing any arguments (or by passing the -i argument):

      +
      $ node
      +> const a = [1, 2, 3];
      +undefined
      +> a
      +[ 1, 2, 3 ]
      +> a.forEach((v) => {
      +...   console.log(v);
      +...   });
      +1
      +2
      +3
      +

      Environment variable options#

      +

      Various behaviors of the Node.js REPL can be customized using the following +environment variables:

      +
        +
      • NODE_REPL_HISTORY: When a valid path is given, persistent REPL history +will be saved to the specified file rather than .node_repl_history in the +user's home directory. Setting this value to '' (an empty string) will +disable persistent REPL history. Whitespace will be trimmed from the value. +On Windows platforms environment variables with empty values are invalid so +set this variable to one or more spaces to disable persistent REPL history.
      • +
      • NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be +persisted if history is available. Must be a positive number. +Default: 1000.
      • +
      • NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default: +'sloppy', which will allow non-strict mode code to be run.
      • +
      +

      Persistent history#

      +

      By default, the Node.js REPL will persist history between node REPL sessions +by saving inputs to a .node_repl_history file located in the user's home +directory. This can be disabled by setting the environment variable +NODE_REPL_HISTORY=''.

      +

      Using the Node.js REPL with advanced line-editors#

      +

      For advanced line-editors, start Node.js with the environment variable +NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical +terminal settings, which will allow use with rlwrap.

      +

      For example, the following can be added to a .bashrc file:

      +
      alias node="env NODE_NO_READLINE=1 rlwrap node"
      +

      Starting multiple REPL instances against a single running instance#

      +

      It is possible to create and run multiple REPL instances against a single +running instance of Node.js that share a single global object but have +separate I/O interfaces.

      +

      The following example, for instance, provides separate REPLs on stdin, a Unix +socket, and a TCP socket:

      +
      const net = require('net');
      +const repl = require('repl');
      +let connections = 0;
      +
      +repl.start({
      +  prompt: 'Node.js via stdin> ',
      +  input: process.stdin,
      +  output: process.stdout
      +});
      +
      +net.createServer((socket) => {
      +  connections += 1;
      +  repl.start({
      +    prompt: 'Node.js via Unix socket> ',
      +    input: socket,
      +    output: socket
      +  }).on('exit', () => {
      +    socket.end();
      +  });
      +}).listen('/tmp/node-repl-sock');
      +
      +net.createServer((socket) => {
      +  connections += 1;
      +  repl.start({
      +    prompt: 'Node.js via TCP socket> ',
      +    input: socket,
      +    output: socket
      +  }).on('exit', () => {
      +    socket.end();
      +  });
      +}).listen(5001);
      +

      Running this application from the command line will start a REPL on stdin. +Other REPL clients may connect through the Unix socket or TCP socket. telnet, +for instance, is useful for connecting to TCP sockets, while socat can be used +to connect to both Unix and TCP sockets.

      +

      By starting a REPL from a Unix socket-based server instead of stdin, it is +possible to connect to a long-running Node.js process without restarting it.

      +

      For an example of running a "full-featured" (terminal) REPL over +a net.Server and net.Socket instance, see: +https://gist.github.com/TooTallNate/2209310.

      +

      For an example of running a REPL instance over curl(1), see: +https://gist.github.com/TooTallNate/2053342.

      +

      Diagnostic report#

      + + +

      Stability: 2 - Stable

      + +

      Delivers a JSON-formatted diagnostic summary, written to a file.

      +

      The report is intended for development, test and production use, to capture +and preserve information for problem determination. It includes JavaScript +and native stack traces, heap statistics, platform information, resource +usage etc. With the report option enabled, diagnostic reports can be triggered +on unhandled exceptions, fatal errors and user signals, in addition to +triggering programmatically through API calls.

      +

      A complete example report that was generated on an uncaught exception +is provided below for reference.

      +
      {
      +  "header": {
      +    "reportVersion": 1,
      +    "event": "exception",
      +    "trigger": "Exception",
      +    "filename": "report.20181221.005011.8974.0.001.json",
      +    "dumpEventTime": "2018-12-21T00:50:11Z",
      +    "dumpEventTimeStamp": "1545371411331",
      +    "processId": 8974,
      +    "cwd": "/home/nodeuser/project/node",
      +    "commandLine": [
      +      "/home/nodeuser/project/node/out/Release/node",
      +      "--report-uncaught-exception",
      +      "/home/nodeuser/project/node/test/report/test-exception.js",
      +      "child"
      +    ],
      +    "nodejsVersion": "v12.0.0-pre",
      +    "glibcVersionRuntime": "2.17",
      +    "glibcVersionCompiler": "2.17",
      +    "wordSize": "64 bit",
      +    "arch": "x64",
      +    "platform": "linux",
      +    "componentVersions": {
      +      "node": "12.0.0-pre",
      +      "v8": "7.1.302.28-node.5",
      +      "uv": "1.24.1",
      +      "zlib": "1.2.11",
      +      "ares": "1.15.0",
      +      "modules": "68",
      +      "nghttp2": "1.34.0",
      +      "napi": "3",
      +      "llhttp": "1.0.1",
      +      "http_parser": "2.8.0",
      +      "openssl": "1.1.0j"
      +    },
      +    "release": {
      +      "name": "node"
      +    },
      +    "osName": "Linux",
      +    "osRelease": "3.10.0-862.el7.x86_64",
      +    "osVersion": "#1 SMP Wed Mar 21 18:14:51 EDT 2018",
      +    "osMachine": "x86_64",
      +    "cpus": [
      +      {
      +        "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
      +        "speed": 2700,
      +        "user": 88902660,
      +        "nice": 0,
      +        "sys": 50902570,
      +        "idle": 241732220,
      +        "irq": 0
      +      },
      +      {
      +        "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
      +        "speed": 2700,
      +        "user": 88902660,
      +        "nice": 0,
      +        "sys": 50902570,
      +        "idle": 241732220,
      +        "irq": 0
      +      }
      +    ],
      +    "networkInterfaces": [
      +      {
      +        "name": "en0",
      +        "internal": false,
      +        "mac": "13:10:de:ad:be:ef",
      +        "address": "10.0.0.37",
      +        "netmask": "255.255.255.0",
      +        "family": "IPv4"
      +      }
      +    ],
      +    "host": "test_machine"
      +  },
      +  "javascriptStack": {
      +    "message": "Error: *** test-exception.js: throwing uncaught Error",
      +    "stack": [
      +      "at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)",
      +      "at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)",
      +      "at Module._compile (internal/modules/cjs/loader.js:718:30)",
      +      "at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)",
      +      "at Module.load (internal/modules/cjs/loader.js:617:32)",
      +      "at tryModuleLoad (internal/modules/cjs/loader.js:560:12)",
      +      "at Function.Module._load (internal/modules/cjs/loader.js:552:3)",
      +      "at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)",
      +      "at executeUserCode (internal/bootstrap/node.js:332:15)"
      +    ]
      +  },
      +  "nativeStack": [
      +    {
      +      "pc": "0x000055b57f07a9ef",
      +      "symbol": "report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57f07cf03",
      +      "symbol": "report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57f1bccfd",
      +      "symbol": " [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57f1be048",
      +      "symbol": "v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57feeda0e",
      +      "symbol": " [./node]"
      +    }
      +  ],
      +  "javascriptHeap": {
      +    "totalMemory": 6127616,
      +    "totalCommittedMemory": 4357352,
      +    "usedMemory": 3221136,
      +    "availableMemory": 1521370240,
      +    "memoryLimit": 1526909922,
      +    "heapSpaces": {
      +      "read_only_space": {
      +        "memorySize": 524288,
      +        "committedMemory": 39208,
      +        "capacity": 515584,
      +        "used": 30504,
      +        "available": 485080
      +      },
      +      "new_space": {
      +        "memorySize": 2097152,
      +        "committedMemory": 2019312,
      +        "capacity": 1031168,
      +        "used": 985496,
      +        "available": 45672
      +      },
      +      "old_space": {
      +        "memorySize": 2273280,
      +        "committedMemory": 1769008,
      +        "capacity": 1974640,
      +        "used": 1725488,
      +        "available": 249152
      +      },
      +      "code_space": {
      +        "memorySize": 696320,
      +        "committedMemory": 184896,
      +        "capacity": 152128,
      +        "used": 152128,
      +        "available": 0
      +      },
      +      "map_space": {
      +        "memorySize": 536576,
      +        "committedMemory": 344928,
      +        "capacity": 327520,
      +        "used": 327520,
      +        "available": 0
      +      },
      +      "large_object_space": {
      +        "memorySize": 0,
      +        "committedMemory": 0,
      +        "capacity": 1520590336,
      +        "used": 0,
      +        "available": 1520590336
      +      },
      +      "new_large_object_space": {
      +        "memorySize": 0,
      +        "committedMemory": 0,
      +        "capacity": 0,
      +        "used": 0,
      +        "available": 0
      +      }
      +    }
      +  },
      +  "resourceUsage": {
      +    "userCpuSeconds": 0.069595,
      +    "kernelCpuSeconds": 0.019163,
      +    "cpuConsumptionPercent": 0.000000,
      +    "maxRss": 18079744,
      +    "pageFaults": {
      +      "IORequired": 0,
      +      "IONotRequired": 4610
      +    },
      +    "fsActivity": {
      +      "reads": 0,
      +      "writes": 0
      +    }
      +  },
      +  "uvthreadResourceUsage": {
      +    "userCpuSeconds": 0.068457,
      +    "kernelCpuSeconds": 0.019127,
      +    "cpuConsumptionPercent": 0.000000,
      +    "fsActivity": {
      +      "reads": 0,
      +      "writes": 0
      +    }
      +  },
      +  "libuv": [
      +    {
      +      "type": "async",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x0000000102910900",
      +      "details": ""
      +    },
      +    {
      +      "type": "timer",
      +      "is_active": false,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfeab0",
      +      "repeat": 0,
      +      "firesInMsFromNow": 94403548320796,
      +      "expired": true
      +    },
      +    {
      +      "type": "check",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfeb48"
      +    },
      +    {
      +      "type": "idle",
      +      "is_active": false,
      +      "is_referenced": true,
      +      "address": "0x00007fff5fbfebc0"
      +    },
      +    {
      +      "type": "prepare",
      +      "is_active": false,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfec38"
      +    },
      +    {
      +      "type": "check",
      +      "is_active": false,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfecb0"
      +    },
      +    {
      +      "type": "async",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x000000010188f2e0"
      +    },
      +    {
      +      "type": "tty",
      +      "is_active": false,
      +      "is_referenced": true,
      +      "address": "0x000055b581db0e18",
      +      "width": 204,
      +      "height": 55,
      +      "fd": 17,
      +      "writeQueueSize": 0,
      +      "readable": true,
      +      "writable": true
      +    },
      +    {
      +      "type": "signal",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x000055b581d80010",
      +      "signum": 28,
      +      "signal": "SIGWINCH"
      +    },
      +    {
      +      "type": "tty",
      +      "is_active": true,
      +      "is_referenced": true,
      +      "address": "0x000055b581df59f8",
      +      "width": 204,
      +      "height": 55,
      +      "fd": 19,
      +      "writeQueueSize": 0,
      +      "readable": true,
      +      "writable": true
      +    },
      +    {
      +      "type": "loop",
      +      "is_active": true,
      +      "address": "0x000055fc7b2cb180"
      +    }
      +  ],
      +  "workers": [],
      +  "environmentVariables": {
      +    "REMOTEHOST": "REMOVED",
      +    "MANPATH": "/opt/rh/devtoolset-3/root/usr/share/man:",
      +    "XDG_SESSION_ID": "66126",
      +    "HOSTNAME": "test_machine",
      +    "HOST": "test_machine",
      +    "TERM": "xterm-256color",
      +    "SHELL": "/bin/csh",
      +    "SSH_CLIENT": "REMOVED",
      +    "PERL5LIB": "/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl",
      +    "OLDPWD": "/home/nodeuser/project/node/src",
      +    "JAVACONFDIRS": "/opt/rh/devtoolset-3/root/etc/java:/etc/java",
      +    "SSH_TTY": "/dev/pts/0",
      +    "PCP_DIR": "/opt/rh/devtoolset-3/root",
      +    "GROUP": "normaluser",
      +    "USER": "nodeuser",
      +    "LD_LIBRARY_PATH": "/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib",
      +    "HOSTTYPE": "x86_64-linux",
      +    "XDG_CONFIG_DIRS": "/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg",
      +    "MAIL": "/var/spool/mail/nodeuser",
      +    "PATH": "/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin",
      +    "PWD": "/home/nodeuser/project/node",
      +    "LANG": "en_US.UTF-8",
      +    "PS1": "\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] >  ",
      +    "SHLVL": "2",
      +    "HOME": "/home/nodeuser",
      +    "OSTYPE": "linux",
      +    "VENDOR": "unknown",
      +    "PYTHONPATH": "/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages",
      +    "MACHTYPE": "x86_64",
      +    "LOGNAME": "nodeuser",
      +    "XDG_DATA_DIRS": "/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share",
      +    "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
      +    "INFOPATH": "/opt/rh/devtoolset-3/root/usr/share/info",
      +    "XDG_RUNTIME_DIR": "/run/user/50141",
      +    "_": "./node"
      +  },
      +  "userLimits": {
      +    "core_file_size_blocks": {
      +      "soft": "",
      +      "hard": "unlimited"
      +    },
      +    "data_seg_size_kbytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "file_size_blocks": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "max_locked_memory_bytes": {
      +      "soft": "unlimited",
      +      "hard": 65536
      +    },
      +    "max_memory_size_kbytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "open_files": {
      +      "soft": "unlimited",
      +      "hard": 4096
      +    },
      +    "stack_size_bytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "cpu_time_seconds": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "max_user_processes": {
      +      "soft": "unlimited",
      +      "hard": 4127290
      +    },
      +    "virtual_memory_kbytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    }
      +  },
      +  "sharedObjects": [
      +    "/lib64/libdl.so.2",
      +    "/lib64/librt.so.1",
      +    "/lib64/libstdc++.so.6",
      +    "/lib64/libm.so.6",
      +    "/lib64/libgcc_s.so.1",
      +    "/lib64/libpthread.so.0",
      +    "/lib64/libc.so.6",
      +    "/lib64/ld-linux-x86-64.so.2"
      +  ]
      +}
      +

      Usage#

      +
      node --report-uncaught-exception --report-on-signal \
      +--report-on-fatalerror app.js
      +
        +
      • +

        --report-uncaught-exception Enables report to be generated on +un-caught exceptions. Useful when inspecting JavaScript stack in conjunction +with native stack and other runtime environment data.

        +
      • +
      • +

        --report-on-signal Enables report to be generated upon receiving +the specified (or predefined) signal to the running Node.js process. (See below +on how to modify the signal that triggers the report.) Default signal is SIGUSR2. +Useful when a report needs to be triggered from another program. +Application monitors may leverage this feature to collect report at regular +intervals and plot rich set of internal runtime data to their views.

        +
      • +
      +

      Signal based report generation is not supported in Windows.

      +

      Under normal circumstances, there is no need to modify the report triggering +signal. However, if SIGUSR2 is already used for other purposes, then this +flag helps to change the signal for report generation and preserve the original +meaning of SIGUSR2 for the said purposes.

      +
        +
      • +

        --report-on-fatalerror Enables the report to be triggered on +fatal errors (internal errors within the Node.js runtime, such as out of memory) +that leads to termination of the application. Useful to inspect various +diagnostic data elements such as heap, stack, event loop state, resource +consumption etc. to reason about the fatal error.

        +
      • +
      • +

        --report-compact Write reports in a compact format, single-line JSON, more +easily consumable by log processing systems than the default multi-line format +designed for human consumption.

        +
      • +
      • +

        --report-directory Location at which the report will be +generated.

        +
      • +
      • +

        --report-filename Name of the file to which the report will be +written.

        +
      • +
      • +

        --report-signal Sets or resets the signal for report generation +(not supported on Windows). Default signal is SIGUSR2.

        +
      • +
      +

      A report can also be triggered via an API call from a JavaScript application:

      +
      process.report.writeReport();
      +

      This function takes an optional additional argument filename, which is +the name of a file into which the report is written.

      +
      process.report.writeReport('./foo.json');
      +

      This function takes an optional additional argument err which is an Error +object that will be used as the context for the JavaScript stack printed in the +report. When using report to handle errors in a callback or an exception +handler, this allows the report to include the location of the original error as +well as where it was handled.

      +
      try {
      +  process.chdir('/non-existent-path');
      +} catch (err) {
      +  process.report.writeReport(err);
      +}
      +// Any other code
      +

      If both filename and error object are passed to writeReport() the +error object must be the second parameter.

      +
      try {
      +  process.chdir('/non-existent-path');
      +} catch (err) {
      +  process.report.writeReport(filename, err);
      +}
      +// Any other code
      +

      The content of the diagnostic report can be returned as a JavaScript Object +via an API call from a JavaScript application:

      +
      const report = process.report.getReport();
      +console.log(typeof report === 'object'); // true
      +
      +// Similar to process.report.writeReport() output
      +console.log(JSON.stringify(report, null, 2));
      +

      This function takes an optional additional argument err, which is an Error +object that will be used as the context for the JavaScript stack printed in the +report.

      +
      const report = process.report.getReport(new Error('custom error'));
      +console.log(typeof report === 'object'); // true
      +

      The API versions are useful when inspecting the runtime state from within +the application, in expectation of self-adjusting the resource consumption, +load balancing, monitoring etc.

      +

      The content of the report consists of a header section containing the event +type, date, time, PID and Node.js version, sections containing JavaScript and +native stack traces, a section containing V8 heap information, a section +containing libuv handle information and an OS platform information section +showing CPU and memory usage and system limits. An example report can be +triggered using the Node.js REPL:

      +
      $ node
      +> process.report.writeReport();
      +Writing Node.js report to file: report.20181126.091102.8480.0.001.json
      +Node.js report completed
      +>
      +

      When a report is written, start and end messages are issued to stderr +and the filename of the report is returned to the caller. The default filename +includes the date, time, PID and a sequence number. The sequence number helps +in associating the report dump with the runtime state if generated multiple +times for the same Node.js process.

      +

      Configuration#

      +

      Additional runtime configuration of report generation is available via +the following properties of process.report:

      +

      reportOnFatalError triggers diagnostic reporting on fatal errors when true. +Defaults to false.

      +

      reportOnSignal triggers diagnostic reporting on signal when true. This is +not supported on Windows. Defaults to false.

      +

      reportOnUncaughtException triggers diagnostic reporting on uncaught exception +when true. Defaults to false.

      +

      signal specifies the POSIX signal identifier that will be used +to intercept external triggers for report generation. Defaults to +'SIGUSR2'.

      +

      filename specifies the name of the output file in the file system. +Special meaning is attached to stdout and stderr. Usage of these +will result in report being written to the associated standard streams. +In cases where standard streams are used, the value in directory is ignored. +URLs are not supported. Defaults to a composite filename that contains +timestamp, PID and sequence number.

      +

      directory specifies the filesystem directory where the report will be written. +URLs are not supported. Defaults to the current working directory of the +Node.js process.

      +
      // Trigger report only on uncaught exceptions.
      +process.report.reportOnFatalError = false;
      +process.report.reportOnSignal = false;
      +process.report.reportOnUncaughtException = true;
      +
      +// Trigger report for both internal errors as well as external signal.
      +process.report.reportOnFatalError = true;
      +process.report.reportOnSignal = true;
      +process.report.reportOnUncaughtException = false;
      +
      +// Change the default signal to 'SIGQUIT' and enable it.
      +process.report.reportOnFatalError = false;
      +process.report.reportOnUncaughtException = false;
      +process.report.reportOnSignal = true;
      +process.report.signal = 'SIGQUIT';
      +

      Configuration on module initialization is also available via +environment variables:

      +
      NODE_OPTIONS="--report-uncaught-exception \
      +  --report-on-fatalerror --report-on-signal \
      +  --report-signal=SIGUSR2  --report-filename=./report.json \
      +  --report-directory=/home/nodeuser"
      +

      Specific API documentation can be found under +process API documentation section.

      +

      Interaction with workers#

      + +

      Worker threads can create reports in the same way that the main thread +does.

      +

      Reports will include information on any Workers that are children of the current +thread as part of the workers section, with each Worker generating a report +in the standard report format.

      +

      The thread which is generating the report will wait for the reports from Worker +threads to finish. However, the latency for this will usually be low, as both +running JavaScript and the event loop are interrupted to generate the report.

      +

      Stream[src]#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/stream.js

      +

      A stream is an abstract interface for working with streaming data in Node.js. +The stream module provides an API for implementing the stream interface.

      +

      There are many stream objects provided by Node.js. For instance, a +request to an HTTP server and process.stdout +are both stream instances.

      +

      Streams can be readable, writable, or both. All streams are instances of +EventEmitter.

      +

      To access the stream module:

      +
      const stream = require('stream');
      +

      The stream module is useful for creating new types of stream instances. It is +usually not necessary to use the stream module to consume streams.

      +

      Organization of this document#

      +

      This document contains two primary sections and a third section for notes. The +first section explains how to use existing streams within an application. The +second section explains how to create new types of streams.

      +

      Types of streams#

      +

      There are four fundamental stream types within Node.js:

      + +

      Additionally, this module includes the utility functions +stream.pipeline(), stream.finished() and +stream.Readable.from().

      +

      Object mode#

      +

      All streams created by Node.js APIs operate exclusively on strings and Buffer +(or Uint8Array) objects. It is possible, however, for stream implementations +to work with other types of JavaScript values (with the exception of null, +which serves a special purpose within streams). Such streams are considered to +operate in "object mode".

      +

      Stream instances are switched into object mode using the objectMode option +when the stream is created. Attempting to switch an existing stream into +object mode is not safe.

      +

      Buffering#

      + +

      Both Writable and Readable streams will store data in an internal +buffer that can be retrieved using writable.writableBuffer or +readable.readableBuffer, respectively.

      +

      The amount of data potentially buffered depends on the highWaterMark option +passed into the stream's constructor. For normal streams, the highWaterMark +option specifies a total number of bytes. For streams operating +in object mode, the highWaterMark specifies a total number of objects.

      +

      Data is buffered in Readable streams when the implementation calls +stream.push(chunk). If the consumer of the Stream does not +call stream.read(), the data will sit in the internal +queue until it is consumed.

      +

      Once the total size of the internal read buffer reaches the threshold specified +by highWaterMark, the stream will temporarily stop reading data from the +underlying resource until the data currently buffered can be consumed (that is, +the stream will stop calling the internal readable._read() method that is +used to fill the read buffer).

      +

      Data is buffered in Writable streams when the +writable.write(chunk) method is called repeatedly. While the +total size of the internal write buffer is below the threshold set by +highWaterMark, calls to writable.write() will return true. Once +the size of the internal buffer reaches or exceeds the highWaterMark, false +will be returned.

      +

      A key goal of the stream API, particularly the stream.pipe() method, +is to limit the buffering of data to acceptable levels such that sources and +destinations of differing speeds will not overwhelm the available memory.

      +

      The highWaterMark option is a threshold, not a limit: it dictates the amount +of data that a stream buffers before it stops asking for more data. It does not +enforce a strict memory limitation in general. Specific stream implementations +may choose to enforce stricter limits but doing so is optional.

      +

      Because Duplex and Transform streams are both Readable and +Writable, each maintains two separate internal buffers used for reading and +writing, allowing each side to operate independently of the other while +maintaining an appropriate and efficient flow of data. For example, +net.Socket instances are Duplex streams whose Readable side allows +consumption of data received from the socket and whose Writable side allows +writing data to the socket. Because data may be written to the socket at a +faster or slower rate than data is received, each side should +operate (and buffer) independently of the other.

      +

      API for stream consumers#

      + +

      Almost all Node.js applications, no matter how simple, use streams in some +manner. The following is an example of using streams in a Node.js application +that implements an HTTP server:

      +
      const http = require('http');
      +
      +const server = http.createServer((req, res) => {
      +  // `req` is an http.IncomingMessage, which is a readable stream.
      +  // `res` is an http.ServerResponse, which is a writable stream.
      +
      +  let body = '';
      +  // Get the data as utf8 strings.
      +  // If an encoding is not set, Buffer objects will be received.
      +  req.setEncoding('utf8');
      +
      +  // Readable streams emit 'data' events once a listener is added.
      +  req.on('data', (chunk) => {
      +    body += chunk;
      +  });
      +
      +  // The 'end' event indicates that the entire body has been received.
      +  req.on('end', () => {
      +    try {
      +      const data = JSON.parse(body);
      +      // Write back something interesting to the user:
      +      res.write(typeof data);
      +      res.end();
      +    } catch (er) {
      +      // uh oh! bad json!
      +      res.statusCode = 400;
      +      return res.end(`error: ${er.message}`);
      +    }
      +  });
      +});
      +
      +server.listen(1337);
      +
      +// $ curl localhost:1337 -d "{}"
      +// object
      +// $ curl localhost:1337 -d "\"foo\""
      +// string
      +// $ curl localhost:1337 -d "not json"
      +// error: Unexpected token o in JSON at position 1
      +

      Writable streams (such as res in the example) expose methods such as +write() and end() that are used to write data onto the stream.

      +

      Readable streams use the EventEmitter API for notifying application +code when data is available to be read off the stream. That available data can +be read from the stream in multiple ways.

      +

      Both Writable and Readable streams use the EventEmitter API in +various ways to communicate the current state of the stream.

      +

      Duplex and Transform streams are both Writable and +Readable.

      +

      Applications that are either writing data to or consuming data from a stream +are not required to implement the stream interfaces directly and will generally +have no reason to call require('stream').

      +

      Developers wishing to implement new types of streams should refer to the +section API for stream implementers.

      +

      Writable streams#

      +

      Writable streams are an abstraction for a destination to which data is +written.

      +

      Examples of Writable streams include:

      + +

      Some of these examples are actually Duplex streams that implement the +Writable interface.

      +

      All Writable streams implement the interface defined by the +stream.Writable class.

      +

      While specific instances of Writable streams may differ in various ways, +all Writable streams follow the same fundamental usage pattern as illustrated +in the example below:

      +
      const myStream = getWritableStreamSomehow();
      +myStream.write('some data');
      +myStream.write('some more data');
      +myStream.end('done writing data');
      +

      Class: stream.Writable#

      + + +
      Event: 'close'#
      + +

      The 'close' event is emitted when the stream and any of its underlying +resources (a file descriptor, for example) have been closed. The event indicates +that no more events will be emitted, and no further computation will occur.

      +

      A Writable stream will always emit the 'close' event if it is +created with the emitClose option.

      +
      Event: 'drain'#
      + +

      If a call to stream.write(chunk) returns false, the +'drain' event will be emitted when it is appropriate to resume writing data +to the stream.

      +
      // Write the data to the supplied writable stream one million times.
      +// Be attentive to back-pressure.
      +function writeOneMillionTimes(writer, data, encoding, callback) {
      +  let i = 1000000;
      +  write();
      +  function write() {
      +    let ok = true;
      +    do {
      +      i--;
      +      if (i === 0) {
      +        // Last time!
      +        writer.write(data, encoding, callback);
      +      } else {
      +        // See if we should continue, or wait.
      +        // Don't pass the callback, because we're not done yet.
      +        ok = writer.write(data, encoding);
      +      }
      +    } while (i > 0 && ok);
      +    if (i > 0) {
      +      // Had to stop early!
      +      // Write some more once it drains.
      +      writer.once('drain', write);
      +    }
      +  }
      +}
      +
      Event: 'error'#
      + + +

      The 'error' event is emitted if an error occurred while writing or piping +data. The listener callback is passed a single Error argument when called.

      +

      The stream is not closed when the 'error' event is emitted unless the +autoDestroy option was set to true when creating the +stream.

      +
      Event: 'finish'#
      + +

      The 'finish' event is emitted after the stream.end() method +has been called, and all data has been flushed to the underlying system.

      +
      const writer = getWritableStreamSomehow();
      +for (let i = 0; i < 100; i++) {
      +  writer.write(`hello, #${i}!\n`);
      +}
      +writer.on('finish', () => {
      +  console.log('All writes are now complete.');
      +});
      +writer.end('This is the end\n');
      +
      Event: 'pipe'#
      + + +

      The 'pipe' event is emitted when the stream.pipe() method is called on +a readable stream, adding this writable to its set of destinations.

      +
      const writer = getWritableStreamSomehow();
      +const reader = getReadableStreamSomehow();
      +writer.on('pipe', (src) => {
      +  console.log('Something is piping into the writer.');
      +  assert.equal(src, reader);
      +});
      +reader.pipe(writer);
      +
      Event: 'unpipe'#
      + + +

      The 'unpipe' event is emitted when the stream.unpipe() method is called +on a Readable stream, removing this Writable from its set of +destinations.

      +

      This is also emitted in case this Writable stream emits an error when a +Readable stream pipes into it.

      +
      const writer = getWritableStreamSomehow();
      +const reader = getReadableStreamSomehow();
      +writer.on('unpipe', (src) => {
      +  console.log('Something has stopped piping into the writer.');
      +  assert.equal(src, reader);
      +});
      +reader.pipe(writer);
      +reader.unpipe(writer);
      +
      writable.cork()#
      + +

      The writable.cork() method forces all written data to be buffered in memory. +The buffered data will be flushed when either the stream.uncork() or +stream.end() methods are called.

      +

      The primary intent of writable.cork() is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, writable.cork() +buffers all the chunks until writable.uncork() is called, which will pass them +all to writable._writev(), if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of writable.cork() without implementing +writable._writev() may have an adverse effect on throughput.

      +

      See also: writable.uncork(), writable._writev().

      +
      writable.destroy([error])#
      + +
        +
      • error <Error> Optional, an error to emit with 'error' event.
      • +
      • Returns: <this>
      • +
      +

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' +event (unless emitClose is set to false). After this call, the writable +stream has ended and subsequent calls to write() or end() will result in +an ERR_STREAM_DESTROYED error. +This is a destructive and immediate way to destroy a stream. Previous calls to +write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. +Use end() instead of destroy if data should flush before close, or wait for +the 'drain' event before destroying the stream. +Implementors should not override this method, +but instead implement writable._destroy().

      +
      writable.destroyed#
      + + +

      Is true after writable.destroy() has been called.

      +
      writable.end([chunk[, encoding]][, callback])#
      + +
        +
      • chunk <string> | <Buffer> | <Uint8Array> | <any> Optional data to write. For streams +not operating in object mode, chunk must be a string, Buffer or +Uint8Array. For object mode streams, chunk may be any JavaScript value +other than null.
      • +
      • encoding <string> The encoding if chunk is a string
      • +
      • callback <Function> Optional callback for when the stream is finished
      • +
      • Returns: <this>
      • +
      +

      Calling the writable.end() method signals that no more data will be written +to the Writable. The optional chunk and encoding arguments allow one +final additional chunk of data to be written immediately before closing the +stream. If provided, the optional callback function is attached as a listener +for the 'finish' event.

      +

      Calling the stream.write() method after calling +stream.end() will raise an error.

      +
      // Write 'hello, ' and then end with 'world!'.
      +const fs = require('fs');
      +const file = fs.createWriteStream('example.txt');
      +file.write('hello, ');
      +file.end('world!');
      +// Writing more now is not allowed!
      +
      writable.setDefaultEncoding(encoding)#
      + + +

      The writable.setDefaultEncoding() method sets the default encoding for a +Writable stream.

      +
      writable.uncork()#
      + +

      The writable.uncork() method flushes all data buffered since +stream.cork() was called.

      +

      When using writable.cork() and writable.uncork() to manage the buffering +of writes to a stream, it is recommended that calls to writable.uncork() be +deferred using process.nextTick(). Doing so allows batching of all +writable.write() calls that occur within a given Node.js event loop phase.

      +
      stream.cork();
      +stream.write('some ');
      +stream.write('data ');
      +process.nextTick(() => stream.uncork());
      +

      If the writable.cork() method is called multiple times on a stream, the +same number of calls to writable.uncork() must be called to flush the buffered +data.

      +
      stream.cork();
      +stream.write('some ');
      +stream.cork();
      +stream.write('data ');
      +process.nextTick(() => {
      +  stream.uncork();
      +  // The data will not be flushed until uncork() is called a second time.
      +  stream.uncork();
      +});
      +

      See also: writable.cork().

      +
      writable.writable#
      + + +

      Is true if it is safe to call writable.write().

      +
      writable.writableEnded#
      + + +

      Is true after writable.end() has been called. This property +does not indicate whether the data has been flushed, for this use +writable.writableFinished instead.

      +
      writable.writableCorked#
      + + +

      Number of times writable.uncork() needs to be +called in order to fully uncork the stream.

      +
      writable.writableFinished#
      + + +

      Is set to true immediately before the 'finish' event is emitted.

      +
      writable.writableHighWaterMark#
      + + +

      Return the value of highWaterMark passed when constructing this +Writable.

      +
      writable.writableLength#
      + + +

      This property contains the number of bytes (or objects) in the queue +ready to be written. The value provides introspection data regarding +the status of the highWaterMark.

      +
      writable.writableObjectMode#
      + + +

      Getter for the property objectMode of a given Writable stream.

      +
      writable.write(chunk[, encoding][, callback])#
      + +
        +
      • chunk <string> | <Buffer> | <Uint8Array> | <any> Optional data to write. For streams +not operating in object mode, chunk must be a string, Buffer or +Uint8Array. For object mode streams, chunk may be any JavaScript value +other than null.
      • +
      • encoding <string> The encoding, if chunk is a string. Default: 'utf8'
      • +
      • callback <Function> Callback for when this chunk of data is flushed
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to +wait for the 'drain' event to be emitted before continuing to write +additional data; otherwise true.
      • +
      +

      The writable.write() method writes some data to the stream, and calls the +supplied callback once the data has been fully handled. If an error +occurs, the callback may or may not be called with the error as its +first argument. To reliably detect write errors, add a listener for the +'error' event.

      +

      The return value is true if the internal buffer is less than the +highWaterMark configured when the stream was created after admitting chunk. +If false is returned, further attempts to write data to the stream should +stop until the 'drain' event is emitted.

      +

      While a stream is not draining, calls to write() will buffer chunk, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the 'drain' event will be emitted. +It is recommended that once write() returns false, no more chunks be written +until the 'drain' event is emitted. While calling write() on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability.

      +

      Writing data while the stream is not draining is particularly +problematic for a Transform, because the Transform streams are paused +by default until they are piped or a 'data' or 'readable' event handler +is added.

      +

      If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a Readable and use +stream.pipe(). However, if calling write() is preferred, it is +possible to respect backpressure and avoid memory issues using the +'drain' event:

      +
      function write(data, cb) {
      +  if (!stream.write(data)) {
      +    stream.once('drain', cb);
      +  } else {
      +    process.nextTick(cb);
      +  }
      +}
      +
      +// Wait for cb to be called before doing any other write.
      +write('hello', () => {
      +  console.log('Write completed, do more writes now.');
      +});
      +

      A Writable stream in object mode will always ignore the encoding argument.

      +

      Readable streams#

      +

      Readable streams are an abstraction for a source from which data is +consumed.

      +

      Examples of Readable streams include:

      + +

      All Readable streams implement the interface defined by the +stream.Readable class.

      +

      Two reading modes#

      +

      Readable streams effectively operate in one of two modes: flowing and +paused. These modes are separate from object mode. +A Readable stream can be in object mode or not, regardless of whether +it is in flowing mode or paused mode.

      +
        +
      • +

        In flowing mode, data is read from the underlying system automatically +and provided to an application as quickly as possible using events via the +EventEmitter interface.

        +
      • +
      • +

        In paused mode, the stream.read() method must be called +explicitly to read chunks of data from the stream.

        +
      • +
      +

      All Readable streams begin in paused mode but can be switched to flowing +mode in one of the following ways:

      + +

      The Readable can switch back to paused mode using one of the following:

      +
        +
      • If there are no pipe destinations, by calling the +stream.pause() method.
      • +
      • If there are pipe destinations, by removing all pipe destinations. +Multiple pipe destinations may be removed by calling the +stream.unpipe() method.
      • +
      +

      The important concept to remember is that a Readable will not generate data +until a mechanism for either consuming or ignoring that data is provided. If +the consuming mechanism is disabled or taken away, the Readable will attempt +to stop generating the data.

      +

      For backward compatibility reasons, removing 'data' event handlers will +not automatically pause the stream. Also, if there are piped destinations, +then calling stream.pause() will not guarantee that the +stream will remain paused once those destinations drain and ask for more data.

      +

      If a Readable is switched into flowing mode and there are no consumers +available to handle the data, that data will be lost. This can occur, for +instance, when the readable.resume() method is called without a listener +attached to the 'data' event, or when a 'data' event handler is removed +from the stream.

      +

      Adding a 'readable' event handler automatically makes the stream +stop flowing, and the data has to be consumed via +readable.read(). If the 'readable' event handler is +removed, then the stream will start flowing again if there is a +'data' event handler.

      +

      Three states#

      +

      The "two modes" of operation for a Readable stream are a simplified +abstraction for the more complicated internal state management that is happening +within the Readable stream implementation.

      +

      Specifically, at any given point in time, every Readable is in one of three +possible states:

      +
        +
      • readable.readableFlowing === null
      • +
      • readable.readableFlowing === false
      • +
      • readable.readableFlowing === true
      • +
      +

      When readable.readableFlowing is null, no mechanism for consuming the +stream's data is provided. Therefore, the stream will not generate data. +While in this state, attaching a listener for the 'data' event, calling the +readable.pipe() method, or calling the readable.resume() method will switch +readable.readableFlowing to true, causing the Readable to begin actively +emitting events as data is generated.

      +

      Calling readable.pause(), readable.unpipe(), or receiving backpressure +will cause the readable.readableFlowing to be set as false, +temporarily halting the flowing of events but not halting the generation of +data. While in this state, attaching a listener for the 'data' event +will not switch readable.readableFlowing to true.

      +
      const { PassThrough, Writable } = require('stream');
      +const pass = new PassThrough();
      +const writable = new Writable();
      +
      +pass.pipe(writable);
      +pass.unpipe(writable);
      +// readableFlowing is now false.
      +
      +pass.on('data', (chunk) => { console.log(chunk.toString()); });
      +pass.write('ok');  // Will not emit 'data'.
      +pass.resume();     // Must be called to make stream emit 'data'.
      +

      While readable.readableFlowing is false, data may be accumulating +within the stream's internal buffer.

      +

      Choose one API style#

      +

      The Readable stream API evolved across multiple Node.js versions and provides +multiple methods of consuming stream data. In general, developers should choose +one of the methods of consuming data and should never use multiple methods +to consume data from a single stream. Specifically, using a combination +of on('data'), on('readable'), pipe(), or async iterators could +lead to unintuitive behavior.

      +

      Use of the readable.pipe() method is recommended for most users as it has been +implemented to provide the easiest way of consuming stream data. Developers that +require more fine-grained control over the transfer and generation of data can +use the EventEmitter and readable.on('readable')/readable.read() +or the readable.pause()/readable.resume() APIs.

      +

      Class: stream.Readable#

      + + +
      Event: 'close'#
      + +

      The 'close' event is emitted when the stream and any of its underlying +resources (a file descriptor, for example) have been closed. The event indicates +that no more events will be emitted, and no further computation will occur.

      +

      A Readable stream will always emit the 'close' event if it is +created with the emitClose option.

      +
      Event: 'data'#
      + +
        +
      • chunk <Buffer> | <string> | <any> The chunk of data. For streams that are not +operating in object mode, the chunk will be either a string or Buffer. +For streams that are in object mode, the chunk can be any JavaScript value +other than null.
      • +
      +

      The 'data' event is emitted whenever the stream is relinquishing ownership of +a chunk of data to a consumer. This may occur whenever the stream is switched +in flowing mode by calling readable.pipe(), readable.resume(), or by +attaching a listener callback to the 'data' event. The 'data' event will +also be emitted whenever the readable.read() method is called and a chunk of +data is available to be returned.

      +

      Attaching a 'data' event listener to a stream that has not been explicitly +paused will switch the stream into flowing mode. Data will then be passed as +soon as it is available.

      +

      The listener callback will be passed the chunk of data as a string if a default +encoding has been specified for the stream using the +readable.setEncoding() method; otherwise the data will be passed as a +Buffer.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('data', (chunk) => {
      +  console.log(`Received ${chunk.length} bytes of data.`);
      +});
      +
      Event: 'end'#
      + +

      The 'end' event is emitted when there is no more data to be consumed from +the stream.

      +

      The 'end' event will not be emitted unless the data is completely +consumed. This can be accomplished by switching the stream into flowing mode, +or by calling stream.read() repeatedly until all data has been +consumed.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('data', (chunk) => {
      +  console.log(`Received ${chunk.length} bytes of data.`);
      +});
      +readable.on('end', () => {
      +  console.log('There will be no more data.');
      +});
      +
      Event: 'error'#
      + + +

      The 'error' event may be emitted by a Readable implementation at any time. +Typically, this may occur if the underlying stream is unable to generate data +due to an underlying internal failure, or when a stream implementation attempts +to push an invalid chunk of data.

      +

      The listener callback will be passed a single Error object.

      +
      Event: 'pause'#
      + +

      The 'pause' event is emitted when stream.pause() is called +and readableFlowing is not false.

      +
      Event: 'readable'#
      + +

      The 'readable' event is emitted when there is data available to be read from +the stream. In some cases, attaching a listener for the 'readable' event will +cause some amount of data to be read into an internal buffer.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('readable', function() {
      +  // There is some data to read now.
      +  let data;
      +
      +  while (data = this.read()) {
      +    console.log(data);
      +  }
      +});
      +

      The 'readable' event will also be emitted once the end of the stream data +has been reached but before the 'end' event is emitted.

      +

      Effectively, the 'readable' event indicates that the stream has new +information: either new data is available or the end of the stream has been +reached. In the former case, stream.read() will return the +available data. In the latter case, stream.read() will return +null. For instance, in the following example, foo.txt is an empty file:

      +
      const fs = require('fs');
      +const rr = fs.createReadStream('foo.txt');
      +rr.on('readable', () => {
      +  console.log(`readable: ${rr.read()}`);
      +});
      +rr.on('end', () => {
      +  console.log('end');
      +});
      +

      The output of running this script is:

      +
      $ node test.js
      +readable: null
      +end
      +

      In general, the readable.pipe() and 'data' event mechanisms are easier to +understand than the 'readable' event. However, handling 'readable' might +result in increased throughput.

      +

      If both 'readable' and 'data' are used at the same time, 'readable' +takes precedence in controlling the flow, i.e. 'data' will be emitted +only when stream.read() is called. The +readableFlowing property would become false. +If there are 'data' listeners when 'readable' is removed, the stream +will start flowing, i.e. 'data' events will be emitted without calling +.resume().

      +
      Event: 'resume'#
      + +

      The 'resume' event is emitted when stream.resume() is +called and readableFlowing is not true.

      +
      readable.destroy([error])#
      + +
        +
      • error <Error> Error which will be passed as payload in 'error' event
      • +
      • Returns: <this>
      • +
      +

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' +event (unless emitClose is set to false). After this call, the readable +stream will release any internal resources and subsequent calls to push() +will be ignored. +Implementors should not override this method, but instead implement +readable._destroy().

      +
      readable.destroyed#
      + + +

      Is true after readable.destroy() has been called.

      +
      readable.isPaused()#
      + + +

      The readable.isPaused() method returns the current operating state of the +Readable. This is used primarily by the mechanism that underlies the +readable.pipe() method. In most typical cases, there will be no reason to +use this method directly.

      +
      const readable = new stream.Readable();
      +
      +readable.isPaused(); // === false
      +readable.pause();
      +readable.isPaused(); // === true
      +readable.resume();
      +readable.isPaused(); // === false
      +
      readable.pause()#
      + + +

      The readable.pause() method will cause a stream in flowing mode to stop +emitting 'data' events, switching out of flowing mode. Any data that +becomes available will remain in the internal buffer.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('data', (chunk) => {
      +  console.log(`Received ${chunk.length} bytes of data.`);
      +  readable.pause();
      +  console.log('There will be no additional data for 1 second.');
      +  setTimeout(() => {
      +    console.log('Now data will start flowing again.');
      +    readable.resume();
      +  }, 1000);
      +});
      +

      The readable.pause() method has no effect if there is a 'readable' +event listener.

      +
      readable.pipe(destination[, options])#
      + + +

      The readable.pipe() method attaches a Writable stream to the readable, +causing it to switch automatically into flowing mode and push all of its data +to the attached Writable. The flow of data will be automatically managed +so that the destination Writable stream is not overwhelmed by a faster +Readable stream.

      +

      The following example pipes all of the data from the readable into a file +named file.txt:

      +
      const fs = require('fs');
      +const readable = getReadableStreamSomehow();
      +const writable = fs.createWriteStream('file.txt');
      +// All the data from readable goes into 'file.txt'.
      +readable.pipe(writable);
      +

      It is possible to attach multiple Writable streams to a single Readable +stream.

      +

      The readable.pipe() method returns a reference to the destination stream +making it possible to set up chains of piped streams:

      +
      const fs = require('fs');
      +const r = fs.createReadStream('file.txt');
      +const z = zlib.createGzip();
      +const w = fs.createWriteStream('file.txt.gz');
      +r.pipe(z).pipe(w);
      +

      By default, stream.end() is called on the destination Writable +stream when the source Readable stream emits 'end', so that the +destination is no longer writable. To disable this default behavior, the end +option can be passed as false, causing the destination stream to remain open:

      +
      reader.pipe(writer, { end: false });
      +reader.on('end', () => {
      +  writer.end('Goodbye\n');
      +});
      +

      One important caveat is that if the Readable stream emits an error during +processing, the Writable destination is not closed automatically. If an +error occurs, it will be necessary to manually close each stream in order +to prevent memory leaks.

      +

      The process.stderr and process.stdout Writable streams are never +closed until the Node.js process exits, regardless of the specified options.

      +
      readable.read([size])#
      + + +

      The readable.read() method pulls some data out of the internal buffer and +returns it. If no data available to be read, null is returned. By default, +the data will be returned as a Buffer object unless an encoding has been +specified using the readable.setEncoding() method or the stream is operating +in object mode.

      +

      The optional size argument specifies a specific number of bytes to read. If +size bytes are not available to be read, null will be returned unless +the stream has ended, in which case all of the data remaining in the internal +buffer will be returned.

      +

      If the size argument is not specified, all of the data contained in the +internal buffer will be returned.

      +

      The size argument must be less than or equal to 1 GB.

      +

      The readable.read() method should only be called on Readable streams +operating in paused mode. In flowing mode, readable.read() is called +automatically until the internal buffer is fully drained.

      +
      const readable = getReadableStreamSomehow();
      +
      +// 'readable' may be triggered multiple times as data is buffered in
      +readable.on('readable', () => {
      +  let chunk;
      +  console.log('Stream is readable (new data received in buffer)');
      +  // Use a loop to make sure we read all currently available data
      +  while (null !== (chunk = readable.read())) {
      +    console.log(`Read ${chunk.length} bytes of data...`);
      +  }
      +});
      +
      +// 'end' will be triggered once when there is no more data available
      +readable.on('end', () => {
      +  console.log('Reached end of stream.');
      +});
      +

      Each call to readable.read() returns a chunk of data, or null. The chunks +are not concatenated. A while loop is necessary to consume all data +currently in the buffer. When reading a large file .read() may return null, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new 'readable' event will be emitted +when there is more data in the buffer. Finally the 'end' event will be +emitted when there is no more data to come.

      +

      Therefore to read a file's whole contents from a readable, it is necessary +to collect chunks across multiple 'readable' events:

      +
      const chunks = [];
      +
      +readable.on('readable', () => {
      +  let chunk;
      +  while (null !== (chunk = readable.read())) {
      +    chunks.push(chunk);
      +  }
      +});
      +
      +readable.on('end', () => {
      +  const content = chunks.join('');
      +});
      +

      A Readable stream in object mode will always return a single item from +a call to readable.read(size), regardless of the value of the +size argument.

      +

      If the readable.read() method returns a chunk of data, a 'data' event will +also be emitted.

      +

      Calling stream.read([size]) after the 'end' event has +been emitted will return null. No runtime error will be raised.

      +
      readable.readable#
      + + +

      Is true if it is safe to call readable.read().

      +
      readable.readableEncoding#
      + + +

      Getter for the property encoding of a given Readable stream. The encoding +property can be set using the readable.setEncoding() method.

      +
      readable.readableEnded#
      + + +

      Becomes true when 'end' event is emitted.

      +
      readable.readableFlowing#
      + + +

      This property reflects the current state of a Readable stream as described +in the Three states section.

      +
      readable.readableHighWaterMark#
      + + +

      Returns the value of highWaterMark passed when constructing this +Readable.

      +
      readable.readableLength#
      + + +

      This property contains the number of bytes (or objects) in the queue +ready to be read. The value provides introspection data regarding +the status of the highWaterMark.

      +
      readable.readableObjectMode#
      + + +

      Getter for the property objectMode of a given Readable stream.

      +
      readable.resume()#
      + + +

      The readable.resume() method causes an explicitly paused Readable stream to +resume emitting 'data' events, switching the stream into flowing mode.

      +

      The readable.resume() method can be used to fully consume the data from a +stream without actually processing any of that data:

      +
      getReadableStreamSomehow()
      +  .resume()
      +  .on('end', () => {
      +    console.log('Reached the end, but did not read anything.');
      +  });
      +

      The readable.resume() method has no effect if there is a 'readable' +event listener.

      +
      readable.setEncoding(encoding)#
      + + +

      The readable.setEncoding() method sets the character encoding for +data read from the Readable stream.

      +

      By default, no encoding is assigned and stream data will be returned as +Buffer objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as Buffer +objects. For instance, calling readable.setEncoding('utf8') will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling +readable.setEncoding('hex') will cause the data to be encoded in hexadecimal +string format.

      +

      The Readable stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as Buffer objects.

      +
      const readable = getReadableStreamSomehow();
      +readable.setEncoding('utf8');
      +readable.on('data', (chunk) => {
      +  assert.equal(typeof chunk, 'string');
      +  console.log('Got %d characters of string data:', chunk.length);
      +});
      +
      readable.unpipe([destination])#
      + + +

      The readable.unpipe() method detaches a Writable stream previously attached +using the stream.pipe() method.

      +

      If the destination is not specified, then all pipes are detached.

      +

      If the destination is specified, but no pipe is set up for it, then +the method does nothing.

      +
      const fs = require('fs');
      +const readable = getReadableStreamSomehow();
      +const writable = fs.createWriteStream('file.txt');
      +// All the data from readable goes into 'file.txt',
      +// but only for the first second.
      +readable.pipe(writable);
      +setTimeout(() => {
      +  console.log('Stop writing to file.txt.');
      +  readable.unpipe(writable);
      +  console.log('Manually close the file stream.');
      +  writable.end();
      +}, 1000);
      +
      readable.unshift(chunk[, encoding])#
      + +
        +
      • chunk <Buffer> | <Uint8Array> | <string> | <null> | <any> Chunk of data to unshift onto the +read queue. For streams not operating in object mode, chunk must be a +string, Buffer, Uint8Array or null. For object mode streams, chunk +may be any JavaScript value.
      • +
      • encoding <string> Encoding of string chunks. Must be a valid +Buffer encoding, such as 'utf8' or 'ascii'.
      • +
      +

      Passing chunk as null signals the end of the stream (EOF) and behaves the +same as readable.push(null), after which no more data can be written. The EOF +signal is put at the end of the buffer and any buffered data will still be +flushed.

      +

      The readable.unshift() method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party.

      +

      The stream.unshift(chunk) method cannot be called after the 'end' event +has been emitted or a runtime error will be thrown.

      +

      Developers using stream.unshift() often should consider switching to +use of a Transform stream instead. See the API for stream implementers +section for more information.

      +
      // Pull off a header delimited by \n\n.
      +// Use unshift() if we get too much.
      +// Call the callback with (error, header, stream).
      +const { StringDecoder } = require('string_decoder');
      +function parseHeader(stream, callback) {
      +  stream.on('error', callback);
      +  stream.on('readable', onReadable);
      +  const decoder = new StringDecoder('utf8');
      +  let header = '';
      +  function onReadable() {
      +    let chunk;
      +    while (null !== (chunk = stream.read())) {
      +      const str = decoder.write(chunk);
      +      if (str.match(/\n\n/)) {
      +        // Found the header boundary.
      +        const split = str.split(/\n\n/);
      +        header += split.shift();
      +        const remaining = split.join('\n\n');
      +        const buf = Buffer.from(remaining, 'utf8');
      +        stream.removeListener('error', callback);
      +        // Remove the 'readable' listener before unshifting.
      +        stream.removeListener('readable', onReadable);
      +        if (buf.length)
      +          stream.unshift(buf);
      +        // Now the body of the message can be read from the stream.
      +        callback(null, header, stream);
      +      } else {
      +        // Still reading the header.
      +        header += str;
      +      }
      +    }
      +  }
      +}
      +

      Unlike stream.push(chunk), stream.unshift(chunk) will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if readable.unshift() is called during a +read (i.e. from within a stream._read() implementation on a +custom stream). Following the call to readable.unshift() with an immediate +stream.push('') will reset the reading state appropriately, +however it is best to simply avoid calling readable.unshift() while in the +process of performing a read.

      +
      readable.wrap(stream)#
      + + +

      Prior to Node.js 0.10, streams did not implement the entire stream module API +as it is currently defined. (See Compatibility for more information.)

      +

      When using an older Node.js library that emits 'data' events and has a +stream.pause() method that is advisory only, the +readable.wrap() method can be used to create a Readable stream that uses +the old stream as its data source.

      +

      It will rarely be necessary to use readable.wrap() but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries.

      +
      const { OldReader } = require('./old-api-module.js');
      +const { Readable } = require('stream');
      +const oreader = new OldReader();
      +const myReader = new Readable().wrap(oreader);
      +
      +myReader.on('readable', () => {
      +  myReader.read(); // etc.
      +});
      +
      readable[Symbol.asyncIterator]()#
      + + +
      const fs = require('fs');
      +
      +async function print(readable) {
      +  readable.setEncoding('utf8');
      +  let data = '';
      +  for await (const chunk of readable) {
      +    data += chunk;
      +  }
      +  console.log(data);
      +}
      +
      +print(fs.createReadStream('file')).catch(console.error);
      +

      If the loop terminates with a break or a throw, the stream will be +destroyed. In other terms, iterating over a stream will consume the stream +fully. The stream will be read in chunks of size equal to the highWaterMark +option. In the code example above, data will be in a single chunk if the file +has less then 64KB of data because no highWaterMark option is provided to +fs.createReadStream().

      +

      Duplex and transform streams#

      +

      Class: stream.Duplex#

      + + +

      Duplex streams are streams that implement both the Readable and +Writable interfaces.

      +

      Examples of Duplex streams include:

      + +

      Class: stream.Transform#

      + + +

      Transform streams are Duplex streams where the output is in some way +related to the input. Like all Duplex streams, Transform streams +implement both the Readable and Writable interfaces.

      +

      Examples of Transform streams include:

      + +
      transform.destroy([error])#
      + + +

      Destroy the stream, and optionally emit an 'error' event. After this call, the +transform stream would release any internal resources. +Implementors should not override this method, but instead implement +readable._destroy(). +The default implementation of _destroy() for Transform also emit 'close' +unless emitClose is set in false.

      +

      stream.finished(stream[, options], callback)#

      + +
        +
      • stream <Stream> A readable and/or writable stream.
      • +
      • options <Object> +
          +
        • error <boolean> If set to false, then a call to emit('error', err) is +not treated as finished. Default: true.
        • +
        • readable <boolean> When set to false, the callback will be called when +the stream ends even though the stream might still be readable. +Default: true.
        • +
        • writable <boolean> When set to false, the callback will be called when +the stream ends even though the stream might still be writable. +Default: true.
        • +
        +
      • +
      • callback <Function> A callback function that takes an optional error +argument.
      • +
      • Returns: <Function> A cleanup function which removes all registered +listeners.
      • +
      +

      A function to get notified when a stream is no longer readable, writable +or has experienced an error or a premature close event.

      +
      const { finished } = require('stream');
      +
      +const rs = fs.createReadStream('archive.tar');
      +
      +finished(rs, (err) => {
      +  if (err) {
      +    console.error('Stream failed.', err);
      +  } else {
      +    console.log('Stream is done reading.');
      +  }
      +});
      +
      +rs.resume(); // Drain the stream.
      +

      Especially useful in error handling scenarios where a stream is destroyed +prematurely (like an aborted HTTP request), and will not emit 'end' +or 'finish'.

      +

      The finished API is promisify-able as well;

      +
      const finished = util.promisify(stream.finished);
      +
      +const rs = fs.createReadStream('archive.tar');
      +
      +async function run() {
      +  await finished(rs);
      +  console.log('Stream is done reading.');
      +}
      +
      +run().catch(console.error);
      +rs.resume(); // Drain the stream.
      +

      stream.finished() leaves dangling event listeners (in particular +'error', 'end', 'finish' and 'close') after callback has been +invoked. The reason for this is so that unexpected 'error' events (due to +incorrect stream implementations) do not cause unexpected crashes. +If this is unwanted behavior then the returned cleanup function needs to be +invoked in the callback:

      +
      const cleanup = finished(rs, (err) => {
      +  cleanup();
      +  // ...
      +});
      +

      stream.pipeline(...streams, callback)#

      + +
        +
      • ...streams <Stream> Two or more streams to pipe between.
      • +
      • callback <Function> Called when the pipeline is fully done. + +
      • +
      +

      A module method to pipe between streams forwarding errors and properly cleaning +up and provide a callback when the pipeline is complete.

      +
      const { pipeline } = require('stream');
      +const fs = require('fs');
      +const zlib = require('zlib');
      +
      +// Use the pipeline API to easily pipe a series of streams
      +// together and get notified when the pipeline is fully done.
      +
      +// A pipeline to gzip a potentially huge tar file efficiently:
      +
      +pipeline(
      +  fs.createReadStream('archive.tar'),
      +  zlib.createGzip(),
      +  fs.createWriteStream('archive.tar.gz'),
      +  (err) => {
      +    if (err) {
      +      console.error('Pipeline failed.', err);
      +    } else {
      +      console.log('Pipeline succeeded.');
      +    }
      +  }
      +);
      +

      The pipeline API is promisify-able as well:

      +
      const pipeline = util.promisify(stream.pipeline);
      +
      +async function run() {
      +  await pipeline(
      +    fs.createReadStream('archive.tar'),
      +    zlib.createGzip(),
      +    fs.createWriteStream('archive.tar.gz')
      +  );
      +  console.log('Pipeline succeeded.');
      +}
      +
      +run().catch(console.error);
      +

      stream.pipeline() will call stream.destroy(err) on all streams except:

      +
        +
      • Readable streams which have emitted 'end' or 'close'.
      • +
      • Writable streams which have emitted 'finish' or 'close'.
      • +
      +

      stream.pipeline() leaves dangling event listeners on the streams +after the callback has been invoked. In the case of reuse of streams after +failure, this can cause event listener leaks and swallowed errors.

      +

      stream.Readable.from(iterable, [options])#

      + +
        +
      • iterable <Iterable> Object implementing the Symbol.asyncIterator or +Symbol.iterator iterable protocol. Emits an 'error' event if a null +value is passed.
      • +
      • options <Object> Options provided to new stream.Readable([options]). +By default, Readable.from() will set options.objectMode to true, unless +this is explicitly opted out by setting options.objectMode to false.
      • +
      • Returns: <stream.Readable>
      • +
      +

      A utility method for creating readable streams out of iterators.

      +
      const { Readable } = require('stream');
      +
      +async function * generate() {
      +  yield 'hello';
      +  yield 'streams';
      +}
      +
      +const readable = Readable.from(generate());
      +
      +readable.on('data', (chunk) => {
      +  console.log(chunk);
      +});
      +

      Calling Readable.from(string) or Readable.from(buffer) will not have +the strings or buffers be iterated to match the other streams semantics +for performance reasons.

      +

      API for stream implementers#

      + +

      The stream module API has been designed to make it possible to easily +implement streams using JavaScript's prototypal inheritance model.

      +

      First, a stream developer would declare a new JavaScript class that extends one +of the four basic stream classes (stream.Writable, stream.Readable, +stream.Duplex, or stream.Transform), making sure they call the appropriate +parent class constructor:

      + +
      const { Writable } = require('stream');
      +
      +class MyWritable extends Writable {
      +  constructor({ highWaterMark, ...options }) {
      +    super({
      +      highWaterMark,
      +      autoDestroy: true,
      +      emitClose: true
      +    });
      +    // ...
      +  }
      +}
      +

      When extending streams, keep in mind what options the user +can and should provide before forwarding these to the base constructor. For +example, if the implementation makes assumptions in regard to the +autoDestroy and emitClose options, do not allow the +user to override these. Be explicit about what +options are forwarded instead of implicitly forwarding all options.

      +

      The new stream class must then implement one or more specific methods, depending +on the type of stream being created, as detailed in the chart below:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Use-caseClassMethod(s) to implement
      Reading onlyReadable_read()
      Writing onlyWritable_write(), _writev(), _final()
      Reading and writingDuplex_read(), _write(), _writev(), _final()
      Operate on written data, then read the resultTransform_transform(), _flush(), _final()
      +

      The implementation code for a stream should never call the "public" methods +of a stream that are intended for use by consumers (as described in the +API for stream consumers section). Doing so may lead to adverse side effects +in application code consuming the stream.

      +

      Avoid overriding public methods such as write(), end(), cork(), +uncork(), read() and destroy(), or emitting internal events such +as 'error', 'data', 'end', 'finish' and 'close' through .emit(). +Doing so can break current and future stream invariants leading to behavior +and/or compatibility issues with other streams, stream utilities, and user +expectations.

      +

      Simplified construction#

      + +

      For many simple cases, it is possible to construct a stream without relying on +inheritance. This can be accomplished by directly creating instances of the +stream.Writable, stream.Readable, stream.Duplex or stream.Transform +objects and passing appropriate methods as constructor options.

      +
      const { Writable } = require('stream');
      +
      +const myWritable = new Writable({
      +  write(chunk, encoding, callback) {
      +    // ...
      +  }
      +});
      +

      Implementing a writable stream#

      +

      The stream.Writable class is extended to implement a Writable stream.

      +

      Custom Writable streams must call the new stream.Writable([options]) +constructor and implement the writable._write() and/or writable._writev() +method.

      +

      new stream.Writable([options])#

      + +
        +
      • options <Object> +
          +
        • highWaterMark <number> Buffer level when +stream.write() starts returning false. Default: +16384 (16KB), or 16 for objectMode streams.
        • +
        • decodeStrings <boolean> Whether to encode strings passed to +stream.write() to Buffers (with the encoding +specified in the stream.write() call) before passing +them to stream._write(). Other types of data are not +converted (i.e. Buffers are not decoded into strings). Setting to +false will prevent strings from being converted. Default: true.
        • +
        • defaultEncoding <string> The default encoding that is used when no +encoding is specified as an argument to stream.write(). +Default: 'utf8'.
        • +
        • objectMode <boolean> Whether or not the +stream.write(anyObj) is a valid operation. When set, +it becomes possible to write JavaScript values other than string, +Buffer or Uint8Array if supported by the stream implementation. +Default: false.
        • +
        • emitClose <boolean> Whether or not the stream should emit 'close' +after it has been destroyed. Default: true.
        • +
        • write <Function> Implementation for the +stream._write() method.
        • +
        • writev <Function> Implementation for the +stream._writev() method.
        • +
        • destroy <Function> Implementation for the +stream._destroy() method.
        • +
        • final <Function> Implementation for the +stream._final() method.
        • +
        • autoDestroy <boolean> Whether this stream should automatically call +.destroy() on itself after ending. Default: false.
        • +
        +
      • +
      + +
      const { Writable } = require('stream');
      +
      +class MyWritable extends Writable {
      +  constructor(options) {
      +    // Calls the stream.Writable() constructor.
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Writable } = require('stream');
      +const util = require('util');
      +
      +function MyWritable(options) {
      +  if (!(this instanceof MyWritable))
      +    return new MyWritable(options);
      +  Writable.call(this, options);
      +}
      +util.inherits(MyWritable, Writable);
      +

      Or, using the simplified constructor approach:

      +
      const { Writable } = require('stream');
      +
      +const myWritable = new Writable({
      +  write(chunk, encoding, callback) {
      +    // ...
      +  },
      +  writev(chunks, callback) {
      +    // ...
      +  }
      +});
      +

      writable._write(chunk, encoding, callback)#

      + +
        +
      • chunk <Buffer> | <string> | <any> The Buffer to be written, converted from the +string passed to stream.write(). If the stream's +decodeStrings option is false or the stream is operating in object mode, +the chunk will not be converted & will be whatever was passed to +stream.write().
      • +
      • encoding <string> If the chunk is a string, then encoding is the +character encoding of that string. If chunk is a Buffer, or if the +stream is operating in object mode, encoding may be ignored.
      • +
      • callback <Function> Call this function (optionally with an error +argument) when processing is complete for the supplied chunk.
      • +
      +

      All Writable stream implementations must provide a +writable._write() and/or +writable._writev() method to send data to the underlying +resource.

      +

      Transform streams provide their own implementation of the +writable._write().

      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Writable class +methods only.

      +

      The callback method must be called to signal either that the write completed +successfully or failed with an error. The first argument passed to the +callback must be the Error object if the call failed or null if the +write succeeded.

      +

      All calls to writable.write() that occur between the time writable._write() +is called and the callback is called will cause the written data to be +buffered. When the callback is invoked, the stream might emit a 'drain' +event. If a stream implementation is capable of processing multiple chunks of +data at once, the writable._writev() method should be implemented.

      +

      If the decodeStrings property is explicitly set to false in the constructor +options, then chunk will remain the same object that is passed to .write(), +and may be a string rather than a Buffer. This is to support implementations +that have an optimized handling for certain string data encodings. In that case, +the encoding argument will indicate the character encoding of the string. +Otherwise, the encoding argument can be safely ignored.

      +

      The writable._write() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      writable._writev(chunks, callback)#

      +
        +
      • chunks <Object[]> The chunks to be written. Each chunk has following +format: { chunk: ..., encoding: ... }.
      • +
      • callback <Function> A callback function (optionally with an error +argument) to be invoked when processing is complete for the supplied chunks.
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Writable class +methods only.

      +

      The writable._writev() method may be implemented in addition or alternatively +to writable._write() in stream implementations that are capable of processing +multiple chunks of data at once. If implemented and if there is buffered data +from previous writes, _writev() will be called instead of _write().

      +

      The writable._writev() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      writable._destroy(err, callback)#

      + +
        +
      • err <Error> A possible error.
      • +
      • callback <Function> A callback function that takes an optional error +argument.
      • +
      +

      The _destroy() method is called by writable.destroy(). +It can be overridden by child classes but it must not be called directly.

      +

      writable._final(callback)#

      + +
        +
      • callback <Function> Call this function (optionally with an error +argument) when finished writing any remaining data.
      • +
      +

      The _final() method must not be called directly. It may be implemented +by child classes, and if so, will be called by the internal Writable +class methods only.

      +

      This optional function will be called before the stream closes, delaying the +'finish' event until callback is called. This is useful to close resources +or write buffered data before a stream ends.

      +

      Errors while writing#

      +

      Errors occurring during the processing of the writable._write(), +writable._writev() and writable._final() methods must be propagated +by invoking the callback and passing the error as the first argument. +Throwing an Error from within these methods or manually emitting an 'error' +event results in undefined behavior.

      +

      If a Readable stream pipes into a Writable stream when Writable emits an +error, the Readable stream will be unpiped.

      +
      const { Writable } = require('stream');
      +
      +const myWritable = new Writable({
      +  write(chunk, encoding, callback) {
      +    if (chunk.toString().indexOf('a') >= 0) {
      +      callback(new Error('chunk is invalid'));
      +    } else {
      +      callback();
      +    }
      +  }
      +});
      +

      An example writable stream#

      +

      The following illustrates a rather simplistic (and somewhat pointless) custom +Writable stream implementation. While this specific Writable stream instance +is not of any real particular usefulness, the example illustrates each of the +required elements of a custom Writable stream instance:

      +
      const { Writable } = require('stream');
      +
      +class MyWritable extends Writable {
      +  _write(chunk, encoding, callback) {
      +    if (chunk.toString().indexOf('a') >= 0) {
      +      callback(new Error('chunk is invalid'));
      +    } else {
      +      callback();
      +    }
      +  }
      +}
      +

      Decoding buffers in a writable stream#

      +

      Decoding buffers is a common task, for instance, when using transformers whose +input is a string. This is not a trivial process when using multi-byte +characters encoding, such as UTF-8. The following example shows how to decode +multi-byte strings using StringDecoder and Writable.

      +
      const { Writable } = require('stream');
      +const { StringDecoder } = require('string_decoder');
      +
      +class StringWritable extends Writable {
      +  constructor(options) {
      +    super(options);
      +    this._decoder = new StringDecoder(options && options.defaultEncoding);
      +    this.data = '';
      +  }
      +  _write(chunk, encoding, callback) {
      +    if (encoding === 'buffer') {
      +      chunk = this._decoder.write(chunk);
      +    }
      +    this.data += chunk;
      +    callback();
      +  }
      +  _final(callback) {
      +    this.data += this._decoder.end();
      +    callback();
      +  }
      +}
      +
      +const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
      +const w = new StringWritable();
      +
      +w.write('currency: ');
      +w.write(euro[0]);
      +w.end(euro[1]);
      +
      +console.log(w.data); // currency: €
      +

      Implementing a readable stream#

      +

      The stream.Readable class is extended to implement a Readable stream.

      +

      Custom Readable streams must call the new stream.Readable([options]) +constructor and implement the readable._read() method.

      +

      new stream.Readable([options])#

      + +
        +
      • options <Object> +
          +
        • highWaterMark <number> The maximum number of bytes to store +in the internal buffer before ceasing to read from the underlying resource. +Default: 16384 (16KB), or 16 for objectMode streams.
        • +
        • encoding <string> If specified, then buffers will be decoded to +strings using the specified encoding. Default: null.
        • +
        • objectMode <boolean> Whether this stream should behave +as a stream of objects. Meaning that stream.read(n) returns +a single value instead of a Buffer of size n. Default: false.
        • +
        • emitClose <boolean> Whether or not the stream should emit 'close' +after it has been destroyed. Default: true.
        • +
        • read <Function> Implementation for the stream._read() +method.
        • +
        • destroy <Function> Implementation for the +stream._destroy() method.
        • +
        • autoDestroy <boolean> Whether this stream should automatically call +.destroy() on itself after ending. Default: false.
        • +
        +
      • +
      + +
      const { Readable } = require('stream');
      +
      +class MyReadable extends Readable {
      +  constructor(options) {
      +    // Calls the stream.Readable(options) constructor.
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Readable } = require('stream');
      +const util = require('util');
      +
      +function MyReadable(options) {
      +  if (!(this instanceof MyReadable))
      +    return new MyReadable(options);
      +  Readable.call(this, options);
      +}
      +util.inherits(MyReadable, Readable);
      +

      Or, using the simplified constructor approach:

      +
      const { Readable } = require('stream');
      +
      +const myReadable = new Readable({
      +  read(size) {
      +    // ...
      +  }
      +});
      +

      readable._read(size)#

      + +
        +
      • size <number> Number of bytes to read asynchronously
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Readable class +methods only.

      +

      All Readable stream implementations must provide an implementation of the +readable._read() method to fetch data from the underlying resource.

      +

      When readable._read() is called, if data is available from the resource, +the implementation should begin pushing that data into the read queue using the +this.push(dataChunk) method. _read() should continue reading +from the resource and pushing data until readable.push() returns false. Only +when _read() is called again after it has stopped should it resume pushing +additional data onto the queue.

      +

      Once the readable._read() method has been called, it will not be called +again until more data is pushed through the readable.push() +method. Empty data such as empty buffers and strings will not cause +readable._read() to be called.

      +

      The size argument is advisory. For implementations where a "read" is a +single operation that returns data can use the size argument to determine how +much data to fetch. Other implementations may ignore this argument and simply +provide data whenever it becomes available. There is no need to "wait" until +size bytes are available before calling stream.push(chunk).

      +

      The readable._read() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      readable._destroy(err, callback)#

      + +
        +
      • err <Error> A possible error.
      • +
      • callback <Function> A callback function that takes an optional error +argument.
      • +
      +

      The _destroy() method is called by readable.destroy(). +It can be overridden by child classes but it must not be called directly.

      +

      readable.push(chunk[, encoding])#

      + +
        +
      • chunk <Buffer> | <Uint8Array> | <string> | <null> | <any> Chunk of data to push into the +read queue. For streams not operating in object mode, chunk must be a +string, Buffer or Uint8Array. For object mode streams, chunk may be +any JavaScript value.
      • +
      • encoding <string> Encoding of string chunks. Must be a valid +Buffer encoding, such as 'utf8' or 'ascii'.
      • +
      • Returns: <boolean> true if additional chunks of data may continue to be +pushed; false otherwise.
      • +
      +

      When chunk is a Buffer, Uint8Array or string, the chunk of data will +be added to the internal queue for users of the stream to consume. +Passing chunk as null signals the end of the stream (EOF), after which no +more data can be written.

      +

      When the Readable is operating in paused mode, the data added with +readable.push() can be read out by calling the +readable.read() method when the 'readable' event is +emitted.

      +

      When the Readable is operating in flowing mode, the data added with +readable.push() will be delivered by emitting a 'data' event.

      +

      The readable.push() method is designed to be as flexible as possible. For +example, when wrapping a lower-level source that provides some form of +pause/resume mechanism, and a data callback, the low-level source can be wrapped +by the custom Readable instance:

      +
      // `_source` is an object with readStop() and readStart() methods,
      +// and an `ondata` member that gets called when it has data, and
      +// an `onend` member that gets called when the data is over.
      +
      +class SourceWrapper extends Readable {
      +  constructor(options) {
      +    super(options);
      +
      +    this._source = getLowLevelSourceObject();
      +
      +    // Every time there's data, push it into the internal buffer.
      +    this._source.ondata = (chunk) => {
      +      // If push() returns false, then stop reading from source.
      +      if (!this.push(chunk))
      +        this._source.readStop();
      +    };
      +
      +    // When the source ends, push the EOF-signaling `null` chunk.
      +    this._source.onend = () => {
      +      this.push(null);
      +    };
      +  }
      +  // _read() will be called when the stream wants to pull more data in.
      +  // The advisory size argument is ignored in this case.
      +  _read(size) {
      +    this._source.readStart();
      +  }
      +}
      +

      The readable.push() method is used to push the content +into the internal buffer. It can be driven by the readable._read() method.

      +

      For streams not operating in object mode, if the chunk parameter of +readable.push() is undefined, it will be treated as empty string or +buffer. See readable.push('') for more information.

      +

      Errors while reading#

      +

      Errors occurring during processing of the readable._read() must be +propagated through the readable.destroy(err) method. +Throwing an Error from within readable._read() or manually emitting an +'error' event results in undefined behavior.

      +
      const { Readable } = require('stream');
      +
      +const myReadable = new Readable({
      +  read(size) {
      +    const err = checkSomeErrorCondition();
      +    if (err) {
      +      this.destroy(err);
      +    } else {
      +      // Do some work.
      +    }
      +  }
      +});
      +

      An example counting stream#

      + +

      The following is a basic example of a Readable stream that emits the numerals +from 1 to 1,000,000 in ascending order, and then ends.

      +
      const { Readable } = require('stream');
      +
      +class Counter extends Readable {
      +  constructor(opt) {
      +    super(opt);
      +    this._max = 1000000;
      +    this._index = 1;
      +  }
      +
      +  _read() {
      +    const i = this._index++;
      +    if (i > this._max)
      +      this.push(null);
      +    else {
      +      const str = String(i);
      +      const buf = Buffer.from(str, 'ascii');
      +      this.push(buf);
      +    }
      +  }
      +}
      +

      Implementing a duplex stream#

      +

      A Duplex stream is one that implements both Readable and +Writable, such as a TCP socket connection.

      +

      Because JavaScript does not have support for multiple inheritance, the +stream.Duplex class is extended to implement a Duplex stream (as opposed +to extending the stream.Readable and stream.Writable classes).

      +

      The stream.Duplex class prototypically inherits from stream.Readable and +parasitically from stream.Writable, but instanceof will work properly for +both base classes due to overriding Symbol.hasInstance on +stream.Writable.

      +

      Custom Duplex streams must call the new stream.Duplex([options]) +constructor and implement both the readable._read() and +writable._write() methods.

      +

      new stream.Duplex(options)#

      + +
        +
      • options <Object> Passed to both Writable and Readable +constructors. Also has the following fields: +
          +
        • allowHalfOpen <boolean> If set to false, then the stream will +automatically end the writable side when the readable side ends. +Default: true.
        • +
        • readable <boolean> Sets whether the Duplex should be readable. +Default: true.
        • +
        • writable <boolean> Sets whether the Duplex should be writable. +Default: true.
        • +
        • readableObjectMode <boolean> Sets objectMode for readable side of the +stream. Has no effect if objectMode is true. Default: false.
        • +
        • writableObjectMode <boolean> Sets objectMode for writable side of the +stream. Has no effect if objectMode is true. Default: false.
        • +
        • readableHighWaterMark <number> Sets highWaterMark for the readable side +of the stream. Has no effect if highWaterMark is provided.
        • +
        • writableHighWaterMark <number> Sets highWaterMark for the writable side +of the stream. Has no effect if highWaterMark is provided.
        • +
        +
      • +
      + +
      const { Duplex } = require('stream');
      +
      +class MyDuplex extends Duplex {
      +  constructor(options) {
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Duplex } = require('stream');
      +const util = require('util');
      +
      +function MyDuplex(options) {
      +  if (!(this instanceof MyDuplex))
      +    return new MyDuplex(options);
      +  Duplex.call(this, options);
      +}
      +util.inherits(MyDuplex, Duplex);
      +

      Or, using the simplified constructor approach:

      +
      const { Duplex } = require('stream');
      +
      +const myDuplex = new Duplex({
      +  read(size) {
      +    // ...
      +  },
      +  write(chunk, encoding, callback) {
      +    // ...
      +  }
      +});
      +

      An example duplex stream#

      +

      The following illustrates a simple example of a Duplex stream that wraps a +hypothetical lower-level source object to which data can be written, and +from which data can be read, albeit using an API that is not compatible with +Node.js streams. +The following illustrates a simple example of a Duplex stream that buffers +incoming written data via the Writable interface that is read back out +via the Readable interface.

      +
      const { Duplex } = require('stream');
      +const kSource = Symbol('source');
      +
      +class MyDuplex extends Duplex {
      +  constructor(source, options) {
      +    super(options);
      +    this[kSource] = source;
      +  }
      +
      +  _write(chunk, encoding, callback) {
      +    // The underlying source only deals with strings.
      +    if (Buffer.isBuffer(chunk))
      +      chunk = chunk.toString();
      +    this[kSource].writeSomeData(chunk);
      +    callback();
      +  }
      +
      +  _read(size) {
      +    this[kSource].fetchSomeData(size, (data, encoding) => {
      +      this.push(Buffer.from(data, encoding));
      +    });
      +  }
      +}
      +

      The most important aspect of a Duplex stream is that the Readable and +Writable sides operate independently of one another despite co-existing within +a single object instance.

      +

      Object mode duplex streams#

      +

      For Duplex streams, objectMode can be set exclusively for either the +Readable or Writable side using the readableObjectMode and +writableObjectMode options respectively.

      +

      In the following example, for instance, a new Transform stream (which is a +type of Duplex stream) is created that has an object mode Writable side +that accepts JavaScript numbers that are converted to hexadecimal strings on +the Readable side.

      +
      const { Transform } = require('stream');
      +
      +// All Transform streams are also Duplex Streams.
      +const myTransform = new Transform({
      +  writableObjectMode: true,
      +
      +  transform(chunk, encoding, callback) {
      +    // Coerce the chunk to a number if necessary.
      +    chunk |= 0;
      +
      +    // Transform the chunk into something else.
      +    const data = chunk.toString(16);
      +
      +    // Push the data onto the readable queue.
      +    callback(null, '0'.repeat(data.length % 2) + data);
      +  }
      +});
      +
      +myTransform.setEncoding('ascii');
      +myTransform.on('data', (chunk) => console.log(chunk));
      +
      +myTransform.write(1);
      +// Prints: 01
      +myTransform.write(10);
      +// Prints: 0a
      +myTransform.write(100);
      +// Prints: 64
      +

      Implementing a transform stream#

      +

      A Transform stream is a Duplex stream where the output is computed +in some way from the input. Examples include zlib streams or crypto +streams that compress, encrypt, or decrypt data.

      +

      There is no requirement that the output be the same size as the input, the same +number of chunks, or arrive at the same time. For example, a Hash stream will +only ever have a single chunk of output which is provided when the input is +ended. A zlib stream will produce output that is either much smaller or much +larger than its input.

      +

      The stream.Transform class is extended to implement a Transform stream.

      +

      The stream.Transform class prototypically inherits from stream.Duplex and +implements its own versions of the writable._write() and +readable._read() methods. Custom Transform implementations must +implement the transform._transform() method and may +also implement the transform._flush() method.

      +

      Care must be taken when using Transform streams in that data written to the +stream can cause the Writable side of the stream to become paused if the +output on the Readable side is not consumed.

      +

      new stream.Transform([options])#

      + + +
      const { Transform } = require('stream');
      +
      +class MyTransform extends Transform {
      +  constructor(options) {
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Transform } = require('stream');
      +const util = require('util');
      +
      +function MyTransform(options) {
      +  if (!(this instanceof MyTransform))
      +    return new MyTransform(options);
      +  Transform.call(this, options);
      +}
      +util.inherits(MyTransform, Transform);
      +

      Or, using the simplified constructor approach:

      +
      const { Transform } = require('stream');
      +
      +const myTransform = new Transform({
      +  transform(chunk, encoding, callback) {
      +    // ...
      +  }
      +});
      +

      Events: 'finish' and 'end'#

      +

      The 'finish' and 'end' events are from the stream.Writable +and stream.Readable classes, respectively. The 'finish' event is emitted +after stream.end() is called and all chunks have been processed +by stream._transform(). The 'end' event is emitted +after all data has been output, which occurs after the callback in +transform._flush() has been called.

      +

      transform._flush(callback)#

      +
        +
      • callback <Function> A callback function (optionally with an error +argument and data) to be called when remaining data has been flushed.
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Readable class +methods only.

      +

      In some cases, a transform operation may need to emit an additional bit of +data at the end of the stream. For example, a zlib compression stream will +store an amount of internal state used to optimally compress the output. When +the stream ends, however, that additional data needs to be flushed so that the +compressed data will be complete.

      +

      Custom Transform implementations may implement the transform._flush() +method. This will be called when there is no more written data to be consumed, +but before the 'end' event is emitted signaling the end of the +Readable stream.

      +

      Within the transform._flush() implementation, the transform.push() method +may be called zero or more times, as appropriate. The callback function must +be called when the flush operation is complete.

      +

      The transform._flush() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      transform._transform(chunk, encoding, callback)#

      +
        +
      • chunk <Buffer> | <string> | <any> The Buffer to be transformed, converted from +the string passed to stream.write(). If the stream's +decodeStrings option is false or the stream is operating in object mode, +the chunk will not be converted & will be whatever was passed to +stream.write().
      • +
      • encoding <string> If the chunk is a string, then this is the +encoding type. If chunk is a buffer, then this is the special +value 'buffer'. Ignore it in that case.
      • +
      • callback <Function> A callback function (optionally with an error +argument and data) to be called after the supplied chunk has been +processed.
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Readable class +methods only.

      +

      All Transform stream implementations must provide a _transform() +method to accept input and produce output. The transform._transform() +implementation handles the bytes being written, computes an output, then passes +that output off to the readable portion using the transform.push() method.

      +

      The transform.push() method may be called zero or more times to generate +output from a single input chunk, depending on how much is to be output +as a result of the chunk.

      +

      It is possible that no output is generated from any given chunk of input data.

      +

      The callback function must be called only when the current chunk is completely +consumed. The first argument passed to the callback must be an Error object +if an error occurred while processing the input or null otherwise. If a second +argument is passed to the callback, it will be forwarded on to the +transform.push() method. In other words, the following are equivalent:

      +
      transform.prototype._transform = function(data, encoding, callback) {
      +  this.push(data);
      +  callback();
      +};
      +
      +transform.prototype._transform = function(data, encoding, callback) {
      +  callback(null, data);
      +};
      +

      The transform._transform() method is prefixed with an underscore because it +is internal to the class that defines it, and should never be called directly by +user programs.

      +

      transform._transform() is never called in parallel; streams implement a +queue mechanism, and to receive the next chunk, callback must be +called, either synchronously or asynchronously.

      +

      Class: stream.PassThrough#

      +

      The stream.PassThrough class is a trivial implementation of a Transform +stream that simply passes the input bytes across to the output. Its purpose is +primarily for examples and testing, but there are some use cases where +stream.PassThrough is useful as a building block for novel sorts of streams.

      +

      Additional notes#

      + +

      Streams compatibility with async generators and async iterators#

      +

      With the support of async generators and iterators in JavaScript, async +generators are effectively a first-class language-level stream construct at +this point.

      +

      Some common interop cases of using Node.js streams with async generators +and async iterators are provided below.

      +

      Consuming readable streams with async iterators#

      +
      (async function() {
      +  for await (const chunk of readable) {
      +    console.log(chunk);
      +  }
      +})();
      +

      Async iterators register a permanent error handler on the stream to prevent any +unhandled post-destroy errors.

      +

      Creating readable streams with async generators#

      +

      We can construct a Node.js readable stream from an asynchronous generator +using the Readable.from() utility method:

      +
      const { Readable } = require('stream');
      +
      +async function * generate() {
      +  yield 'a';
      +  yield 'b';
      +  yield 'c';
      +}
      +
      +const readable = Readable.from(generate());
      +
      +readable.on('data', (chunk) => {
      +  console.log(chunk);
      +});
      +

      Piping to writable streams from async iterators#

      +

      In the scenario of writing to a writable stream from an async iterator, ensure +the correct handling of backpressure and errors.

      +
      const { once } = require('events');
      +const finished = util.promisify(stream.finished);
      +
      +const writable = fs.createWriteStream('./file');
      +
      +function drain(writable) {
      +  if (writable.destroyed) {
      +    return Promise.reject(new Error('premature close'));
      +  }
      +  return Promise.race([
      +    once(writable, 'drain'),
      +    once(writable, 'close')
      +      .then(() => Promise.reject(new Error('premature close')))
      +  ]);
      +}
      +
      +async function pump(iterable, writable) {
      +  for await (const chunk of iterable) {
      +    // Handle backpressure on write().
      +    if (!writable.write(chunk)) {
      +      await drain(writable);
      +    }
      +  }
      +  writable.end();
      +}
      +
      +(async function() {
      +  // Ensure completion without errors.
      +  await Promise.all([
      +    pump(iterable, writable),
      +    finished(writable)
      +  ]);
      +})();
      +

      In the above, errors on write() would be caught and thrown by the +once() listener for the 'drain' event, since once() will also handle the +'error' event. To ensure completion of the write stream without errors, +it is safer to use the finished() method as above, instead of using the +once() listener for the 'finish' event. Under certain cases, an 'error' +event could be emitted by the writable stream after 'finish' and as once() +will release the 'error' handler on handling the 'finish' event, it could +result in an unhandled error.

      +

      Alternatively, the readable stream could be wrapped with Readable.from() and +then piped via .pipe():

      +
      const finished = util.promisify(stream.finished);
      +
      +const writable = fs.createWriteStream('./file');
      +
      +(async function() {
      +  const readable = Readable.from(iterable);
      +  readable.pipe(writable);
      +  // Ensure completion without errors.
      +  await finished(writable);
      +})();
      +

      Or, using stream.pipeline() to pipe streams:

      +
      const pipeline = util.promisify(stream.pipeline);
      +
      +const writable = fs.createWriteStream('./file');
      +
      +(async function() {
      +  const readable = Readable.from(iterable);
      +  await pipeline(readable, writable);
      +})();
      + +

      Compatibility with older Node.js versions#

      + +

      Prior to Node.js 0.10, the Readable stream interface was simpler, but also +less powerful and less useful.

      +
        +
      • Rather than waiting for calls to the stream.read() method, +'data' events would begin emitting immediately. Applications that +would need to perform some amount of work to decide how to handle data +were required to store read data into buffers so the data would not be lost.
      • +
      • The stream.pause() method was advisory, rather than +guaranteed. This meant that it was still necessary to be prepared to receive +'data' events even when the stream was in a paused state.
      • +
      +

      In Node.js 0.10, the Readable class was added. For backward +compatibility with older Node.js programs, Readable streams switch into +"flowing mode" when a 'data' event handler is added, or when the +stream.resume() method is called. The effect is that, even +when not using the new stream.read() method and +'readable' event, it is no longer necessary to worry about losing +'data' chunks.

      +

      While most applications will continue to function normally, this introduces an +edge case in the following conditions:

      +
        +
      • No 'data' event listener is added.
      • +
      • The stream.resume() method is never called.
      • +
      • The stream is not piped to any writable destination.
      • +
      +

      For example, consider the following code:

      +
      // WARNING!  BROKEN!
      +net.createServer((socket) => {
      +
      +  // We add an 'end' listener, but never consume the data.
      +  socket.on('end', () => {
      +    // It will never get here.
      +    socket.end('The message was received but was not processed.\n');
      +  });
      +
      +}).listen(1337);
      +

      Prior to Node.js 0.10, the incoming message data would be simply discarded. +However, in Node.js 0.10 and beyond, the socket remains paused forever.

      +

      The workaround in this situation is to call the +stream.resume() method to begin the flow of data:

      +
      // Workaround.
      +net.createServer((socket) => {
      +  socket.on('end', () => {
      +    socket.end('The message was received but was not processed.\n');
      +  });
      +
      +  // Start the flow of data, discarding it.
      +  socket.resume();
      +}).listen(1337);
      +

      In addition to new Readable streams switching into flowing mode, +pre-0.10 style streams can be wrapped in a Readable class using the +readable.wrap() method.

      +

      readable.read(0)#

      +

      There are some cases where it is necessary to trigger a refresh of the +underlying readable stream mechanisms, without actually consuming any +data. In such cases, it is possible to call readable.read(0), which will +always return null.

      +

      If the internal read buffer is below the highWaterMark, and the +stream is not currently reading, then calling stream.read(0) will trigger +a low-level stream._read() call.

      +

      While most applications will almost never need to do this, there are +situations within Node.js where this is done, particularly in the +Readable stream class internals.

      +

      readable.push('')#

      +

      Use of readable.push('') is not recommended.

      +

      Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in +object mode has an interesting side effect. Because it is a call to +readable.push(), the call will end the reading process. +However, because the argument is an empty string, no data is added to the +readable buffer so there is nothing for a user to consume.

      +

      highWaterMark discrepancy after calling readable.setEncoding()#

      +

      The use of readable.setEncoding() will change the behavior of how the +highWaterMark operates in non-object mode.

      +

      Typically, the size of the current buffer is measured against the +highWaterMark in bytes. However, after setEncoding() is called, the +comparison function will begin to measure the buffer's size in characters.

      +

      This is not a problem in common cases with latin1 or ascii. But it is +advised to be mindful about this behavior when working with strings that could +contain multi-byte characters.

      +

      String decoder#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/string_decoder.js

      +

      The string_decoder module provides an API for decoding Buffer objects into +strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 +characters. It can be accessed using:

      +
      const { StringDecoder } = require('string_decoder');
      +

      The following example shows the basic use of the StringDecoder class.

      +
      const { StringDecoder } = require('string_decoder');
      +const decoder = new StringDecoder('utf8');
      +
      +const cent = Buffer.from([0xC2, 0xA2]);
      +console.log(decoder.write(cent));
      +
      +const euro = Buffer.from([0xE2, 0x82, 0xAC]);
      +console.log(decoder.write(euro));
      +

      When a Buffer instance is written to the StringDecoder instance, an +internal buffer is used to ensure that the decoded string does not contain +any incomplete multibyte characters. These are held in the buffer until the +next call to stringDecoder.write() or until stringDecoder.end() is called.

      +

      In the following example, the three UTF-8 encoded bytes of the European Euro +symbol (€) are written over three separate operations:

      +
      const { StringDecoder } = require('string_decoder');
      +const decoder = new StringDecoder('utf8');
      +
      +decoder.write(Buffer.from([0xE2]));
      +decoder.write(Buffer.from([0x82]));
      +console.log(decoder.end(Buffer.from([0xAC])));
      +

      Class: StringDecoder#

      +

      new StringDecoder([encoding])#

      + +
        +
      • encoding <string> The character encoding the StringDecoder will use. +Default: 'utf8'.
      • +
      +

      Creates a new StringDecoder instance.

      +

      stringDecoder.end([buffer])#

      + + +

      Returns any remaining input stored in the internal buffer as a string. Bytes +representing incomplete UTF-8 and UTF-16 characters will be replaced with +substitution characters appropriate for the character encoding.

      +

      If the buffer argument is provided, one final call to stringDecoder.write() +is performed before returning the remaining input.

      +

      stringDecoder.write(buffer)#

      + + +

      Returns a decoded string, ensuring that any incomplete multibyte characters at +the end of the Buffer, or TypedArray, or DataView are omitted from the +returned string and stored in an internal buffer for the next call to +stringDecoder.write() or stringDecoder.end().

      +

      Timers#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/timers.js

      +

      The timer module exposes a global API for scheduling functions to +be called at some future period of time. Because the timer functions are +globals, there is no need to call require('timers') to use the API.

      +

      The timer functions within Node.js implement a similar API as the timers API +provided by Web Browsers but use a different internal implementation that is +built around the Node.js Event Loop.

      +

      Class: Immediate#

      +

      This object is created internally and is returned from setImmediate(). It +can be passed to clearImmediate() in order to cancel the scheduled +actions.

      +

      By default, when an immediate is scheduled, the Node.js event loop will continue +running as long as the immediate is active. The Immediate object returned by +setImmediate() exports both immediate.ref() and immediate.unref() +functions that can be used to control this default behavior.

      +

      immediate.hasRef()#

      + + +

      If true, the Immediate object will keep the Node.js event loop active.

      +

      immediate.ref()#

      + + +

      When called, requests that the Node.js event loop not exit so long as the +Immediate is active. Calling immediate.ref() multiple times will have no +effect.

      +

      By default, all Immediate objects are "ref'ed", making it normally unnecessary +to call immediate.ref() unless immediate.unref() had been called previously.

      +

      immediate.unref()#

      + + +

      When called, the active Immediate object will not require the Node.js event +loop to remain active. If there is no other activity keeping the event loop +running, the process may exit before the Immediate object's callback is +invoked. Calling immediate.unref() multiple times will have no effect.

      +

      Class: Timeout#

      +

      This object is created internally and is returned from setTimeout() and +setInterval(). It can be passed to either clearTimeout() or +clearInterval() in order to cancel the scheduled actions.

      +

      By default, when a timer is scheduled using either setTimeout() or +setInterval(), the Node.js event loop will continue running as long as the +timer is active. Each of the Timeout objects returned by these functions +export both timeout.ref() and timeout.unref() functions that can be used to +control this default behavior.

      +

      timeout.hasRef()#

      + + +

      If true, the Timeout object will keep the Node.js event loop active.

      +

      timeout.ref()#

      + +
        +
      • Returns: <Timeout> a reference to timeout
      • +
      +

      When called, requests that the Node.js event loop not exit so long as the +Timeout is active. Calling timeout.ref() multiple times will have no effect.

      +

      By default, all Timeout objects are "ref'ed", making it normally unnecessary +to call timeout.ref() unless timeout.unref() had been called previously.

      +

      timeout.refresh()#

      + +
        +
      • Returns: <Timeout> a reference to timeout
      • +
      +

      Sets the timer's start time to the current time, and reschedules the timer to +call its callback at the previously specified duration adjusted to the current +time. This is useful for refreshing a timer without allocating a new +JavaScript object.

      +

      Using this on a timer that has already called its callback will reactivate the +timer.

      +

      timeout.unref()#

      + +
        +
      • Returns: <Timeout> a reference to timeout
      • +
      +

      When called, the active Timeout object will not require the Node.js event loop +to remain active. If there is no other activity keeping the event loop running, +the process may exit before the Timeout object's callback is invoked. Calling +timeout.unref() multiple times will have no effect.

      +

      Calling timeout.unref() creates an internal timer that will wake the Node.js +event loop. Creating too many of these can adversely impact performance +of the Node.js application.

      +

      timeout[Symbol.toPrimitive]()#

      + +
        +
      • Returns: <integer> a number that can be used to reference this timeout
      • +
      +

      Coerce a Timeout to a primitive. The primitive can be used to +clear the Timeout. The primitive can only be used in the +same thread where the timeout was created. Therefore, to use it +across worker_threads it must first be passed to the correct +thread. This allows enhanced compatibility with browser +setTimeout() and setInterval() implementations.

      +

      Scheduling timers#

      +

      A timer in Node.js is an internal construct that calls a given function after +a certain period of time. When a timer's function is called varies depending on +which method was used to create the timer and what other work the Node.js +event loop is doing.

      +

      setImmediate(callback[, ...args])#

      + + +

      Schedules the "immediate" execution of the callback after I/O events' +callbacks.

      +

      When multiple calls to setImmediate() are made, the callback functions are +queued for execution in the order in which they are created. The entire callback +queue is processed every event loop iteration. If an immediate timer is queued +from inside an executing callback, that timer will not be triggered until the +next event loop iteration.

      +

      If callback is not a function, a TypeError will be thrown.

      +

      This method has a custom variant for promises that is available using +util.promisify():

      +
      const util = require('util');
      +const setImmediatePromise = util.promisify(setImmediate);
      +
      +setImmediatePromise('foobar').then((value) => {
      +  // value === 'foobar' (passing values is optional)
      +  // This is executed after all I/O callbacks.
      +});
      +
      +// Or with async function
      +async function timerExample() {
      +  console.log('Before I/O callbacks');
      +  await setImmediatePromise();
      +  console.log('After I/O callbacks');
      +}
      +timerExample();
      +

      setInterval(callback, delay[, ...args])#

      + +
        +
      • callback <Function> The function to call when the timer elapses.
      • +
      • delay <number> The number of milliseconds to wait before calling the +callback.
      • +
      • ...args <any> Optional arguments to pass when the callback is called.
      • +
      • Returns: <Timeout> for use with clearInterval()
      • +
      +

      Schedules repeated execution of callback every delay milliseconds.

      +

      When delay is larger than 2147483647 or less than 1, the delay will be +set to 1. Non-integer delays are truncated to an integer.

      +

      If callback is not a function, a TypeError will be thrown.

      +

      setTimeout(callback, delay[, ...args])#

      + +
        +
      • callback <Function> The function to call when the timer elapses.
      • +
      • delay <number> The number of milliseconds to wait before calling the +callback.
      • +
      • ...args <any> Optional arguments to pass when the callback is called.
      • +
      • Returns: <Timeout> for use with clearTimeout()
      • +
      +

      Schedules execution of a one-time callback after delay milliseconds.

      +

      The callback will likely not be invoked in precisely delay milliseconds. +Node.js makes no guarantees about the exact timing of when callbacks will fire, +nor of their ordering. The callback will be called as close as possible to the +time specified.

      +

      When delay is larger than 2147483647 or less than 1, the delay +will be set to 1. Non-integer delays are truncated to an integer.

      +

      If callback is not a function, a TypeError will be thrown.

      +

      This method has a custom variant for promises that is available using +util.promisify():

      +
      const util = require('util');
      +const setTimeoutPromise = util.promisify(setTimeout);
      +
      +setTimeoutPromise(40, 'foobar').then((value) => {
      +  // value === 'foobar' (passing values is optional)
      +  // This is executed after about 40 milliseconds.
      +});
      +

      Cancelling timers#

      +

      The setImmediate(), setInterval(), and setTimeout() methods +each return objects that represent the scheduled timers. These can be used to +cancel the timer and prevent it from triggering.

      +

      It is not possible to cancel timers that were created using the promisified +variants of setImmediate(), setTimeout().

      +

      clearImmediate(immediate)#

      + + +

      Cancels an Immediate object created by setImmediate().

      +

      clearInterval(timeout)#

      + + +

      Cancels a Timeout object created by setInterval().

      +

      clearTimeout(timeout)#

      + + +

      Cancels a Timeout object created by setTimeout().

      +

      TLS (SSL)#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/tls.js

      +

      The tls module provides an implementation of the Transport Layer Security +(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. +The module can be accessed using:

      +
      const tls = require('tls');
      +

      TLS/SSL concepts#

      +

      The TLS/SSL is a public/private key infrastructure (PKI). For most common +cases, each client and server must have a private key.

      +

      Private keys can be generated in multiple ways. The example below illustrates +use of the OpenSSL command-line interface to generate a 2048-bit RSA private +key:

      +
      openssl genrsa -out ryans-key.pem 2048
      +

      With TLS/SSL, all servers (and some clients) must have a certificate. +Certificates are public keys that correspond to a private key, and that are +digitally signed either by a Certificate Authority or by the owner of the +private key (such certificates are referred to as "self-signed"). The first +step to obtaining a certificate is to create a Certificate Signing Request +(CSR) file.

      +

      The OpenSSL command-line interface can be used to generate a CSR for a private +key:

      +
      openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
      +

      Once the CSR file is generated, it can either be sent to a Certificate +Authority for signing or used to generate a self-signed certificate.

      +

      Creating a self-signed certificate using the OpenSSL command-line interface +is illustrated in the example below:

      +
      openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
      +

      Once the certificate is generated, it can be used to generate a .pfx or +.p12 file:

      +
      openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \
      +      -certfile ca-cert.pem -out ryans.pfx
      +

      Where:

      +
        +
      • in: is the signed certificate
      • +
      • inkey: is the associated private key
      • +
      • certfile: is a concatenation of all Certificate Authority (CA) certs into +a single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
      • +
      +

      Perfect forward secrecy#

      + +

      The term forward secrecy or perfect forward secrecy describes a feature +of key-agreement (i.e., key-exchange) methods. That is, the server and client +keys are used to negotiate new temporary keys that are used specifically and +only for the current communication session. Practically, this means that even +if the server's private key is compromised, communication can only be decrypted +by eavesdroppers if the attacker manages to obtain the key-pair specifically +generated for the session.

      +

      Perfect forward secrecy is achieved by randomly generating a key pair for +key-agreement on every TLS/SSL handshake (in contrast to using the same key for +all sessions). Methods implementing this technique are called "ephemeral".

      +

      Currently two methods are commonly used to achieve perfect forward secrecy (note +the character "E" appended to the traditional abbreviations):

      +
        +
      • DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.
      • +
      • ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman +key-agreement protocol.
      • +
      +

      Ephemeral methods may have some performance drawbacks, because key generation +is expensive.

      +

      To use perfect forward secrecy using DHE with the tls module, it is required +to generate Diffie-Hellman parameters and specify them with the dhparam +option to tls.createSecureContext(). The following illustrates the use of +the OpenSSL command-line interface to generate such parameters:

      +
      openssl dhparam -outform PEM -out dhparam.pem 2048
      +

      If using perfect forward secrecy using ECDHE, Diffie-Hellman parameters are +not required and a default ECDHE curve will be used. The ecdhCurve property +can be used when creating a TLS Server to specify the list of names of supported +curves to use, see tls.createServer() for more info.

      +

      Perfect forward secrecy was optional up to TLSv1.2, but it is not optional for +TLSv1.3, because all TLSv1.3 cipher suites use ECDHE.

      +

      ALPN and SNI#

      + +

      ALPN (Application-Layer Protocol Negotiation Extension) and +SNI (Server Name Indication) are TLS handshake extensions:

      +
        +
      • ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)
      • +
      • SNI: Allows the use of one TLS server for multiple hostnames with different +SSL certificates.
      • +
      +

      Pre-shared keys#

      + +

      TLS-PSK support is available as an alternative to normal certificate-based +authentication. It uses a pre-shared key instead of certificates to +authenticate a TLS connection, providing mutual authentication. +TLS-PSK and public key infrastructure are not mutually exclusive. Clients and +servers can accommodate both, choosing either of them during the normal cipher +negotiation step.

      +

      TLS-PSK is only a good choice where means exist to securely share a +key with every connecting machine, so it does not replace PKI +(Public Key Infrastructure) for the majority of TLS uses. +The TLS-PSK implementation in OpenSSL has seen many security flaws in +recent years, mostly because it is used only by a minority of applications. +Please consider all alternative solutions before switching to PSK ciphers. +Upon generating PSK it is of critical importance to use sufficient entropy as +discussed in RFC 4086. Deriving a shared secret from a password or other +low-entropy sources is not secure.

      +

      PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly +specifying a cipher suite with the ciphers option. The list of available +ciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3 +ciphers are eligible for PSK but currently only those that use SHA256 digest are +supported they can be retrieved via openssl ciphers -v -s -tls1_3 -psk.

      +

      According to the RFC 4279, PSK identities up to 128 bytes in length and +PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0 +maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.

      +

      The current implementation doesn't support asynchronous PSK callbacks due to the +limitations of the underlying OpenSSL API.

      +

      Client-initiated renegotiation attack mitigation#

      + +

      The TLS protocol allows clients to renegotiate certain aspects of the TLS +session. Unfortunately, session renegotiation requires a disproportionate amount +of server-side resources, making it a potential vector for denial-of-service +attacks.

      +

      To mitigate the risk, renegotiation is limited to three times every ten minutes. +An 'error' event is emitted on the tls.TLSSocket instance when this +threshold is exceeded. The limits are configurable:

      +
        +
      • tls.CLIENT_RENEG_LIMIT <number> Specifies the number of renegotiation +requests. Default: 3.
      • +
      • tls.CLIENT_RENEG_WINDOW <number> Specifies the time renegotiation window +in seconds. Default: 600 (10 minutes).
      • +
      +

      The default renegotiation limits should not be modified without a full +understanding of the implications and risks.

      +

      TLSv1.3 does not support renegotiation.

      +

      Session resumption#

      +

      Establishing a TLS session can be relatively slow. The process can be sped +up by saving and later reusing the session state. There are several mechanisms +to do so, discussed here from oldest to newest (and preferred).

      +

      Session identifiers#

      +

      Servers generate a unique ID for new connections and +send it to the client. Clients and servers save the session state. When +reconnecting, clients send the ID of their saved session state and if the server +also has the state for that ID, it can agree to use it. Otherwise, the server +will create a new session. See RFC 2246 for more information, page 23 and +30.

      +

      Resumption using session identifiers is supported by most web browsers when +making HTTPS requests.

      +

      For Node.js, clients wait for the 'session' event to get the session data, +and provide the data to the session option of a subsequent tls.connect() +to reuse the session. Servers must +implement handlers for the 'newSession' and 'resumeSession' events +to save and restore the session data using the session ID as the lookup key to +reuse sessions. To reuse sessions across load balancers or cluster workers, +servers must use a shared session cache (such as Redis) in their session +handlers.

      +

      Session tickets#

      +

      The servers encrypt the entire session state and send it +to the client as a "ticket". When reconnecting, the state is sent to the server +in the initial connection. This mechanism avoids the need for server-side +session cache. If the server doesn't use the ticket, for any reason (failure +to decrypt it, it's too old, etc.), it will create a new session and send a new +ticket. See RFC 5077 for more information.

      +

      Resumption using session tickets is becoming commonly supported by many web +browsers when making HTTPS requests.

      +

      For Node.js, clients use the same APIs for resumption with session identifiers +as for resumption with session tickets. For debugging, if +tls.TLSSocket.getTLSTicket() returns a value, the session data contains a +ticket, otherwise it contains client-side session state.

      +

      With TLSv1.3, be aware that multiple tickets may be sent by the server, +resulting in multiple 'session' events, see 'session' for more +information.

      +

      Single process servers need no specific implementation to use session tickets. +To use session tickets across server restarts or load balancers, servers must +all have the same ticket keys. There are three 16-byte keys internally, but the +tls API exposes them as a single 48-byte buffer for convenience.

      +

      Its possible to get the ticket keys by calling server.getTicketKeys() on +one server instance and then distribute them, but it is more reasonable to +securely generate 48 bytes of secure random data and set them with the +ticketKeys option of tls.createServer(). The keys should be regularly +regenerated and server's keys can be reset with +server.setTicketKeys().

      +

      Session ticket keys are cryptographic keys, and they must be stored +securely. With TLS 1.2 and below, if they are compromised all sessions that +used tickets encrypted with them can be decrypted. They should not be stored +on disk, and they should be regenerated regularly.

      +

      If clients advertise support for tickets, the server will send them. The +server can disable tickets by supplying +require('constants').SSL_OP_NO_TICKET in secureOptions.

      +

      Both session identifiers and session tickets timeout, causing the server to +create new sessions. The timeout can be configured with the sessionTimeout +option of tls.createServer().

      +

      For all the mechanisms, when resumption fails, servers will create new sessions. +Since failing to resume the session does not cause TLS/HTTPS connection +failures, it is easy to not notice unnecessarily poor TLS performance. The +OpenSSL CLI can be used to verify that servers are resuming sessions. Use the +-reconnect option to openssl s_client, for example:

      +
      $ openssl s_client -connect localhost:443 -reconnect
      +

      Read through the debug output. The first connection should say "New", for +example:

      +
      New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
      +

      Subsequent connections should say "Reused", for example:

      +
      Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
      +

      Modifying the default TLS cipher suite#

      +

      Node.js is built with a default suite of enabled and disabled TLS ciphers. This +default cipher list can be configured when building Node.js to allow +distributions to provide their own default list.

      +

      The following command can be used to show the default cipher suite:

      +
      node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
      +TLS_AES_256_GCM_SHA384
      +TLS_CHACHA20_POLY1305_SHA256
      +TLS_AES_128_GCM_SHA256
      +ECDHE-RSA-AES128-GCM-SHA256
      +ECDHE-ECDSA-AES128-GCM-SHA256
      +ECDHE-RSA-AES256-GCM-SHA384
      +ECDHE-ECDSA-AES256-GCM-SHA384
      +DHE-RSA-AES128-GCM-SHA256
      +ECDHE-RSA-AES128-SHA256
      +DHE-RSA-AES128-SHA256
      +ECDHE-RSA-AES256-SHA384
      +DHE-RSA-AES256-SHA384
      +ECDHE-RSA-AES256-SHA256
      +DHE-RSA-AES256-SHA256
      +HIGH
      +!aNULL
      +!eNULL
      +!EXPORT
      +!DES
      +!RC4
      +!MD5
      +!PSK
      +!SRP
      +!CAMELLIA
      +

      This default can be replaced entirely using the --tls-cipher-list command +line switch (directly, or via the NODE_OPTIONS environment variable). For +instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS +cipher suite:

      +
      node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js
      +
      +export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
      +node server.js
      +

      The default can also be replaced on a per client or server basis using the +ciphers option from tls.createSecureContext(), which is also available +in tls.createServer(), tls.connect(), and when creating new +tls.TLSSockets.

      +

      The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones +that start with 'TLS_', and specifications for TLSv1.2 and below cipher +suites. The TLSv1.2 ciphers support a legacy specification format, consult +the OpenSSL cipher list format documentation for details, but those +specifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only +be enabled by including their full name in the cipher list. They cannot, for +example, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or +'!EECDH' specification.

      +

      Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3 +protocol is significantly more secure than TLSv1.2, and will always be chosen +over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3 +cipher suites are enabled.

      +

      The default cipher suite included within Node.js has been carefully +selected to reflect current security best practices and risk mitigation. +Changing the default cipher suite can have a significant impact on the security +of an application. The --tls-cipher-list switch and ciphers option should by +used only if absolutely necessary.

      +

      The default cipher suite prefers GCM ciphers for Chrome's 'modern +cryptography' setting and also prefers ECDHE and DHE ciphers for perfect +forward secrecy, while offering some backward compatibility.

      +

      128 bit AES is preferred over 192 and 256 bit AES in light of specific +attacks affecting larger AES key sizes.

      +

      Old clients that rely on insecure and deprecated RC4 or DES-based ciphers +(like Internet Explorer 6) cannot complete the handshaking process with +the default configuration. If these clients must be supported, the +TLS recommendations may offer a compatible cipher suite. For more details +on the format, see the OpenSSL cipher list format documentation.

      +

      There are only 5 TLSv1.3 cipher suites:

      +
        +
      • 'TLS_AES_256_GCM_SHA384'
      • +
      • 'TLS_CHACHA20_POLY1305_SHA256'
      • +
      • 'TLS_AES_128_GCM_SHA256'
      • +
      • 'TLS_AES_128_CCM_SHA256'
      • +
      • 'TLS_AES_128_CCM_8_SHA256'
      • +
      +

      The first 3 are enabled by default. The last 2 CCM-based suites are supported +by TLSv1.3 because they may be more performant on constrained systems, but they +are not enabled by default since they offer less security.

      +

      Class: tls.CryptoStream#

      + +

      Stability: 0 - Deprecated: Use tls.TLSSocket instead.

      +

      The tls.CryptoStream class represents a stream of encrypted data. This class +is deprecated and should no longer be used.

      +

      cryptoStream.bytesWritten#

      + +

      The cryptoStream.bytesWritten property returns the total number of bytes +written to the underlying socket including the bytes required for the +implementation of the TLS protocol.

      +

      Class: tls.SecurePair#

      + +

      Stability: 0 - Deprecated: Use tls.TLSSocket instead.

      +

      Returned by tls.createSecurePair().

      +

      Event: 'secure'#

      + +

      The 'secure' event is emitted by the SecurePair object once a secure +connection has been established.

      +

      As with checking for the server +'secureConnection' +event, pair.cleartext.authorized should be inspected to confirm whether the +certificate used is properly authorized.

      +

      Class: tls.Server#

      + + +

      Accepts encrypted connections using TLS or SSL.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established, before the TLS +handshake begins. socket is typically an object of type net.Socket. +Usually users will not want to access this event.

      +

      This event can also be explicitly emitted by users to inject connections +into the TLS server. In that case, any Duplex stream can be passed.

      +

      Event: 'keylog'#

      + +
        +
      • line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.
      • +
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance on which it was +generated.
      • +
      +

      The keylog event is emitted when key material is generated or received by +a connection to this server (typically before handshake has completed, but not +necessarily). This keying material can be stored for debugging, as it allows +captured TLS traffic to be decrypted. It may be emitted multiple times for +each socket.

      +

      A typical use case is to append received lines to a common text file, which +is later used by software (such as Wireshark) to decrypt the traffic:

      +
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
      +// ...
      +server.on('keylog', (line, tlsSocket) => {
      +  if (tlsSocket.remoteAddress !== '...')
      +    return; // Only log keys for a particular IP
      +  logFile.write(line);
      +});
      +

      Event: 'newSession'#

      + +

      The 'newSession' event is emitted upon creation of a new TLS session. This may +be used to store sessions in external storage. The data should be provided to +the 'resumeSession' callback.

      +

      The listener callback is passed three arguments when called:

      +
        +
      • sessionId <Buffer> The TLS session identifier
      • +
      • sessionData <Buffer> The TLS session data
      • +
      • callback <Function> A callback function taking no arguments that must be +invoked in order for data to be sent or received over the secure connection.
      • +
      +

      Listening for this event will have an effect only on connections established +after the addition of the event listener.

      +

      Event: 'OCSPRequest'#

      + +

      The 'OCSPRequest' event is emitted when the client sends a certificate status +request. The listener callback is passed three arguments when called:

      +
        +
      • certificate <Buffer> The server certificate
      • +
      • issuer <Buffer> The issuer's certificate
      • +
      • callback <Function> A callback function that must be invoked to provide +the results of the OCSP request.
      • +
      +

      The server's current certificate can be parsed to obtain the OCSP URL +and certificate ID; after obtaining an OCSP response, callback(null, resp) is +then invoked, where resp is a Buffer instance containing the OCSP response. +Both certificate and issuer are Buffer DER-representations of the +primary and issuer's certificates. These can be used to obtain the OCSP +certificate ID and OCSP endpoint URL.

      +

      Alternatively, callback(null, null) may be called, indicating that there was +no OCSP response.

      +

      Calling callback(err) will result in a socket.destroy(err) call.

      +

      The typical flow of an OCSP Request is as follows:

      +
        +
      1. Client connects to the server and sends an 'OCSPRequest' (via the status +info extension in ClientHello).
      2. +
      3. Server receives the request and emits the 'OCSPRequest' event, calling the +listener if registered.
      4. +
      5. Server extracts the OCSP URL from either the certificate or issuer and +performs an OCSP request to the CA.
      6. +
      7. Server receives 'OCSPResponse' from the CA and sends it back to the client +via the callback argument
      8. +
      9. Client validates the response and either destroys the socket or performs a +handshake.
      10. +
      +

      The issuer can be null if the certificate is either self-signed or the +issuer is not in the root certificates list. (An issuer may be provided +via the ca option when establishing the TLS connection.)

      +

      Listening for this event will have an effect only on connections established +after the addition of the event listener.

      +

      An npm module like asn1.js may be used to parse the certificates.

      +

      Event: 'resumeSession'#

      + +

      The 'resumeSession' event is emitted when the client requests to resume a +previous TLS session. The listener callback is passed two arguments when +called:

      +
        +
      • sessionId <Buffer> The TLS session identifier
      • +
      • callback <Function> A callback function to be called when the prior session +has been recovered: callback([err[, sessionData]]) + +
      • +
      +

      The event listener should perform a lookup in external storage for the +sessionData saved by the 'newSession' event handler using the given +sessionId. If found, call callback(null, sessionData) to resume the session. +If not found, the session cannot be resumed. callback() must be called +without sessionData so that the handshake can continue and a new session can +be created. It is possible to call callback(err) to terminate the incoming +connection and destroy the socket.

      +

      Listening for this event will have an effect only on connections established +after the addition of the event listener.

      +

      The following illustrates resuming a TLS session:

      +
      const tlsSessionStore = {};
      +server.on('newSession', (id, data, cb) => {
      +  tlsSessionStore[id.toString('hex')] = data;
      +  cb();
      +});
      +server.on('resumeSession', (id, cb) => {
      +  cb(null, tlsSessionStore[id.toString('hex')] || null);
      +});
      +

      Event: 'secureConnection'#

      + +

      The 'secureConnection' event is emitted after the handshaking process for a +new connection has successfully completed. The listener callback is passed a +single argument when called:

      + +

      The tlsSocket.authorized property is a boolean indicating whether the +client has been verified by one of the supplied Certificate Authorities for the +server. If tlsSocket.authorized is false, then socket.authorizationError +is set to describe how authorization failed. Depending on the settings +of the TLS server, unauthorized connections may still be accepted.

      +

      The tlsSocket.alpnProtocol property is a string that contains the selected +ALPN protocol. When ALPN has no selected protocol, tlsSocket.alpnProtocol +equals false.

      +

      The tlsSocket.servername property is a string containing the server name +requested via SNI.

      +

      Event: 'tlsClientError'#

      + +

      The 'tlsClientError' event is emitted when an error occurs before a secure +connection is established. The listener callback is passed two arguments when +called:

      +
        +
      • exception <Error> The Error object describing the error
      • +
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance from which the +error originated.
      • +
      +

      server.addContext(hostname, context)#

      + +
        +
      • hostname <string> A SNI host name or wildcard (e.g. '*')
      • +
      • context <Object> An object containing any of the possible properties +from the tls.createSecureContext() options arguments (e.g. key, +cert, ca, etc).
      • +
      +

      The server.addContext() method adds a secure context that will be used if +the client request's SNI name matches the supplied hostname (or wildcard).

      +

      server.address()#

      + + +

      Returns the bound address, the address family name, and port of the +server as reported by the operating system. See net.Server.address() for +more information.

      +

      server.close([callback])#

      + +
        +
      • callback <Function> A listener callback that will be registered to listen +for the server instance's 'close' event.
      • +
      • Returns: <tls.Server>
      • +
      +

      The server.close() method stops the server from accepting new connections.

      +

      This function operates asynchronously. The 'close' event will be emitted +when the server has no more open connections.

      +

      server.connections#

      + +

      Stability: 0 - Deprecated: Use server.getConnections() instead.

      + +

      Returns the current number of concurrent connections on the server.

      +

      server.getTicketKeys()#

      + +
        +
      • Returns: <Buffer> A 48-byte buffer containing the session ticket keys.
      • +
      +

      Returns the session ticket keys.

      +

      See Session Resumption for more information.

      +

      server.listen()#

      +

      Starts the server listening for encrypted connections. +This method is identical to server.listen() from net.Server.

      +

      server.setSecureContext(options)#

      + + +

      The server.setSecureContext() method replaces the secure context of an +existing server. Existing connections to the server are not interrupted.

      +

      server.setTicketKeys(keys)#

      + +
        +
      • keys <Buffer> A 48-byte buffer containing the session ticket keys.
      • +
      +

      Sets the session ticket keys.

      +

      Changes to the ticket keys are effective only for future server connections. +Existing or currently pending server connections will use the previous keys.

      +

      See Session Resumption for more information.

      +

      Class: tls.TLSSocket#

      + + +

      Performs transparent encryption of written data and all required TLS +negotiation.

      +

      Instances of tls.TLSSocket implement the duplex Stream interface.

      +

      Methods that return TLS connection metadata (e.g. +tls.TLSSocket.getPeerCertificate() will only return data while the +connection is open.

      +

      new tls.TLSSocket(socket[, options])#

      + +
        +
      • socket <net.Socket> | <stream.Duplex> +On the server side, any Duplex stream. On the client side, any +instance of net.Socket (for generic Duplex stream support +on the client side, tls.connect() must be used).
      • +
      • options <Object> +
          +
        • enableTrace: See tls.createServer()
        • +
        • isServer: The SSL/TLS protocol is asymmetrical, TLSSockets must know if +they are to behave as a server or a client. If true the TLS socket will be +instantiated as a server. Default: false.
        • +
        • server <net.Server> A net.Server instance.
        • +
        • requestCert: Whether to authenticate the remote peer by requesting a +certificate. Clients always request a server certificate. Servers +(isServer is true) may set requestCert to true to request a client +certificate.
        • +
        • rejectUnauthorized: See tls.createServer()
        • +
        • ALPNProtocols: See tls.createServer()
        • +
        • SNICallback: See tls.createServer()
        • +
        • session <Buffer> A Buffer instance containing a TLS session.
        • +
        • requestOCSP <boolean> If true, specifies that the OCSP status request +extension will be added to the client hello and an 'OCSPResponse' event +will be emitted on the socket before establishing a secure communication
        • +
        • secureContext: TLS context object created with +tls.createSecureContext(). If a secureContext is not provided, one +will be created by passing the entire options object to +tls.createSecureContext().
        • +
        • ...: tls.createSecureContext() options that are used if the +secureContext option is missing. Otherwise, they are ignored.
        • +
        +
      • +
      +

      Construct a new tls.TLSSocket object from an existing TCP socket.

      +

      Event: 'keylog'#

      + +
        +
      • line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.
      • +
      +

      The keylog event is emitted on a tls.TLSSocket when key material +is generated or received by the socket. This keying material can be stored +for debugging, as it allows captured TLS traffic to be decrypted. It may +be emitted multiple times, before or after the handshake completes.

      +

      A typical use case is to append received lines to a common text file, which +is later used by software (such as Wireshark) to decrypt the traffic:

      +
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
      +// ...
      +tlsSocket.on('keylog', (line) => logFile.write(line));
      +

      Event: 'OCSPResponse'#

      + +

      The 'OCSPResponse' event is emitted if the requestOCSP option was set +when the tls.TLSSocket was created and an OCSP response has been received. +The listener callback is passed a single argument when called:

      +
        +
      • response <Buffer> The server's OCSP response
      • +
      +

      Typically, the response is a digitally signed object from the server's CA that +contains information about server's certificate revocation status.

      +

      Event: 'secureConnect'#

      + +

      The 'secureConnect' event is emitted after the handshaking process for a new +connection has successfully completed. The listener callback will be called +regardless of whether or not the server's certificate has been authorized. It +is the client's responsibility to check the tlsSocket.authorized property to +determine if the server certificate was signed by one of the specified CAs. If +tlsSocket.authorized === false, then the error can be found by examining the +tlsSocket.authorizationError property. If ALPN was used, the +tlsSocket.alpnProtocol property can be checked to determine the negotiated +protocol.

      +

      Event: 'session'#

      + + +

      The 'session' event is emitted on a client tls.TLSSocket when a new session +or TLS ticket is available. This may or may not be before the handshake is +complete, depending on the TLS protocol version that was negotiated. The event +is not emitted on the server, or if a new session was not created, for example, +when the connection was resumed. For some TLS protocol versions the event may be +emitted multiple times, in which case all the sessions can be used for +resumption.

      +

      On the client, the session can be provided to the session option of +tls.connect() to resume the connection.

      +

      See Session Resumption for more information.

      +

      For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once +the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed +by the protocol, multiple tickets are sent, and the tickets aren't sent until +after the handshake completes. So it is necessary to wait for the +'session' event to get a resumable session. Applications +should use the 'session' event instead of getSession() to ensure +they will work for all TLS versions. Applications that only expect to +get or use one session should listen for this event only once:

      +
      tlsSocket.once('session', (session) => {
      +  // The session can be used immediately or later.
      +  tls.connect({
      +    session: session,
      +    // Other connect options...
      +  });
      +});
      +

      tlsSocket.address()#

      + + +

      Returns the bound address, the address family name, and port of the +underlying socket as reported by the operating system: +{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      +

      tlsSocket.authorizationError#

      + +

      Returns the reason why the peer's certificate was not been verified. This +property is set only when tlsSocket.authorized === false.

      +

      tlsSocket.authorized#

      + + +

      Returns true if the peer certificate was signed by one of the CAs specified +when creating the tls.TLSSocket instance, otherwise false.

      +

      tlsSocket.disableRenegotiation()#

      + +

      Disables TLS renegotiation for this TLSSocket instance. Once called, attempts +to renegotiate will trigger an 'error' event on the TLSSocket.

      +

      tlsSocket.enableTrace()#

      + +

      When enabled, TLS packet trace information is written to stderr. This can be +used to debug TLS connection problems.

      +

      Note: The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's +SSL_trace() function, the format is undocumented, can change without notice, +and should not be relied on.

      +

      tlsSocket.encrypted#

      + +

      Always returns true. This may be used to distinguish TLS sockets from regular +net.Socket instances.

      +

      tlsSocket.getCertificate()#

      + + +

      Returns an object representing the local certificate. The returned object has +some properties corresponding to the fields of the certificate.

      +

      See tls.TLSSocket.getPeerCertificate() for an example of the certificate +structure.

      +

      If there is no local certificate, an empty object will be returned. If the +socket has been destroyed, null will be returned.

      +

      tlsSocket.getCipher()#

      + +
        +
      • Returns: <Object> +
          +
        • name <string> OpenSSL name for the cipher suite.
        • +
        • standardName <string> IETF name for the cipher suite.
        • +
        • version <string> The minimum TLS protocol version supported by this cipher +suite.
        • +
        +
      • +
      +

      Returns an object containing information on the negotiated cipher suite.

      +

      For example:

      +
      {
      +    "name": "AES128-SHA256",
      +    "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256",
      +    "version": "TLSv1.2"
      +}
      +

      See +SSL_CIPHER_get_name +for more information.

      +

      tlsSocket.getEphemeralKeyInfo()#

      + + +

      Returns an object representing the type, name, and size of parameter of +an ephemeral key exchange in perfect forward secrecy on a client +connection. It returns an empty object when the key exchange is not +ephemeral. As this is only supported on a client socket; null is returned +if called on a server socket. The supported types are 'DH' and 'ECDH'. The +name property is available only when type is 'ECDH'.

      +

      For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

      +

      tlsSocket.getFinished()#

      + +
        +
      • Returns: <Buffer> | <undefined> The latest Finished message that has been +sent to the socket as part of a SSL/TLS handshake, or undefined if +no Finished message has been sent yet.
      • +
      +

      As the Finished messages are message digests of the complete handshake +(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can +be used for external authentication procedures when the authentication +provided by SSL/TLS is not desired or is not enough.

      +

      Corresponds to the SSL_get_finished routine in OpenSSL and may be used +to implement the tls-unique channel binding from RFC 5929.

      +

      tlsSocket.getPeerCertificate([detailed])#

      + +
        +
      • detailed <boolean> Include the full certificate chain if true, otherwise +include just the peer's certificate.
      • +
      • Returns: <Object> A certificate object.
      • +
      +

      Returns an object representing the peer's certificate. If the peer does not +provide a certificate, an empty object will be returned. If the socket has been +destroyed, null will be returned.

      +

      If the full certificate chain was requested, each certificate will include an +issuerCertificate property containing an object representing its issuer's +certificate.

      +

      Certificate object#

      + +

      A certificate object has properties corresponding to the fields of the +certificate.

      +
        +
      • raw <Buffer> The DER encoded X.509 certificate data.
      • +
      • subject <Object> The certificate subject, described in terms of + Country (C:), StateOrProvince (ST), Locality (L), Organization (O), +OrganizationalUnit (OU), and CommonName (CN). The CommonName is typically +a DNS name with TLS certificates. Example: +{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.
      • +
      • issuer <Object> The certificate issuer, described in the same terms as the + subject.
      • +
      • valid_from <string> The date-time the certificate is valid from.
      • +
      • valid_to <string> The date-time the certificate is valid to.
      • +
      • serialNumber <string> The certificate serial number, as a hex string. + Example: 'B9B0D332A1AA5635'.
      • +
      • fingerprint <string> The SHA-1 digest of the DER encoded certificate. It is +returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
      • +
      • fingerprint256 <string> The SHA-256 digest of the DER encoded certificate. + It is returned as a : separated hexadecimal string. Example: +'2A:7A:C2:DD:...'.
      • +
      • ext_key_usage <Array> (Optional) The extended key usage, a set of OIDs.
      • +
      • subjectaltname <string> (Optional) A string containing concatenated names +for the subject, an alternative to the subject names.
      • +
      • infoAccess <Array> (Optional) An array describing the AuthorityInfoAccess, + used with OCSP.
      • +
      • issuerCertificate <Object> (Optional) The issuer certificate object. For + self-signed certificates, this may be a circular reference.
      • +
      +

      The certificate may contain information about the public key, depending on +the key type.

      +

      For RSA keys, the following properties may be defined:

      +
        +
      • bits <number> The RSA bit size. Example: 1024.
      • +
      • exponent <string> The RSA exponent, as a string in hexadecimal number +notation. Example: '0x010001'.
      • +
      • modulus <string> The RSA modulus, as a hexadecimal string. Example: + 'B56CE45CB7...'.
      • +
      • pubkey <Buffer> The public key.
      • +
      +

      For EC keys, the following properties may be defined:

      +
        +
      • pubkey <Buffer> The public key.
      • +
      • bits <number> The key size in bits. Example: 256.
      • +
      • asn1Curve <string> (Optional) The ASN.1 name of the OID of the elliptic +curve. Well-known curves are identified by an OID. While it is unusual, it is +possible that the curve is identified by its mathematical properties, in which +case it will not have an OID. Example: 'prime256v1'.
      • +
      • nistCurve <string> (Optional) The NIST name for the elliptic curve, if it +has one (not all well-known curves have been assigned names by NIST). Example: +'P-256'.
      • +
      +

      Example certificate:

      + +
      { subject:
      +   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
      +     CN: '*.nodejs.org' },
      +  issuer:
      +   { C: 'GB',
      +     ST: 'Greater Manchester',
      +     L: 'Salford',
      +     O: 'COMODO CA Limited',
      +     CN: 'COMODO RSA Domain Validation Secure Server CA' },
      +  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',
      +  infoAccess:
      +   { 'CA Issuers - URI':
      +      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],
      +     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },
      +  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',
      +  exponent: '0x10001',
      +  pubkey: <Buffer ... >,
      +  valid_from: 'Aug 14 00:00:00 2017 GMT',
      +  valid_to: 'Nov 20 23:59:59 2019 GMT',
      +  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',
      +  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',
      +  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],
      +  serialNumber: '66593D57F20CBC573E433381B5FEC280',
      +  raw: <Buffer ... > }
      +

      tlsSocket.getPeerFinished()#

      + +
        +
      • Returns: <Buffer> | <undefined> The latest Finished message that is expected +or has actually been received from the socket as part of a SSL/TLS handshake, +or undefined if there is no Finished message so far.
      • +
      +

      As the Finished messages are message digests of the complete handshake +(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can +be used for external authentication procedures when the authentication +provided by SSL/TLS is not desired or is not enough.

      +

      Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used +to implement the tls-unique channel binding from RFC 5929.

      +

      tlsSocket.getProtocol()#

      + + +

      Returns a string containing the negotiated SSL/TLS protocol version of the +current connection. The value 'unknown' will be returned for connected +sockets that have not completed the handshaking process. The value null will +be returned for server sockets or disconnected client sockets.

      +

      Protocol versions are:

      +
        +
      • 'SSLv3'
      • +
      • 'TLSv1'
      • +
      • 'TLSv1.1'
      • +
      • 'TLSv1.2'
      • +
      • 'TLSv1.3'
      • +
      +

      See the OpenSSL SSL_get_version documentation for more information.

      +

      tlsSocket.getSession()#

      + + +

      Returns the TLS session data or undefined if no session was +negotiated. On the client, the data can be provided to the session option of +tls.connect() to resume the connection. On the server, it may be useful +for debugging.

      +

      See Session Resumption for more information.

      +

      Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications +must use the 'session' event (it also works for TLSv1.2 and below).

      +

      tlsSocket.getSharedSigalgs()#

      + +
        +
      • Returns: <Array> List of signature algorithms shared between the server and +the client in the order of decreasing preference.
      • +
      +

      See +SSL_get_shared_sigalgs +for more information.

      +

      tlsSocket.exportKeyingMaterial(length, label[, context])#

      + +
        +
      • +

        length <number> number of bytes to retrieve from keying material

        +
      • +
      • +

        label <string> an application specific label, typically this will be a +value from the +IANA Exporter Label Registry.

        +
      • +
      • +

        context <Buffer> Optionally provide a context.

        +
      • +
      • +

        Returns: <Buffer> requested bytes of the keying material

        +
      • +
      +

      Keying material is used for validations to prevent different kind of attacks in +network protocols, for example in the specifications of IEEE 802.1X.

      +

      Example

      +
      const keyingMaterial = tlsSocket.exportKeyingMaterial(
      +  128,
      +  'client finished');
      +
      +/**
      + Example return value of keyingMaterial:
      + <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
      +    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
      +    74 ef 2c ... 78 more bytes>
      +*/
      +

      See the OpenSSL SSL_export_keying_material documentation for more +information.

      +

      tlsSocket.getTLSTicket()#

      + + +

      For a client, returns the TLS session ticket if one is available, or +undefined. For a server, always returns undefined.

      +

      It may be useful for debugging.

      +

      See Session Resumption for more information.

      +

      tlsSocket.isSessionReused()#

      + +
        +
      • Returns: <boolean> true if the session was reused, false otherwise.
      • +
      +

      See Session Resumption for more information.

      +

      tlsSocket.localAddress#

      + + +

      Returns the string representation of the local IP address.

      +

      tlsSocket.localPort#

      + + +

      Returns the numeric representation of the local port.

      +

      tlsSocket.remoteAddress#

      + + +

      Returns the string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'.

      +

      tlsSocket.remoteFamily#

      + + +

      Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

      +

      tlsSocket.remotePort#

      + + +

      Returns the numeric representation of the remote port. For example, 443.

      +

      tlsSocket.renegotiate(options, callback)#

      + +
        +
      • +

        options <Object>

        +
          +
        • rejectUnauthorized <boolean> If not false, the server certificate is +verified against the list of supplied CAs. An 'error' event is emitted if +verification fails; err.code contains the OpenSSL error code. Default: +true.
        • +
        • requestCert
        • +
        +
      • +
      • +

        callback <Function> If renegotiate() returned true, callback is +attached once to the 'secure' event. If renegotiate() returned false, +callback will be called in the next tick with an error, unless the +tlsSocket has been destroyed, in which case callback will not be called +at all.

        +
      • +
      • +

        Returns: <boolean> true if renegotiation was initiated, false otherwise.

        +
      • +
      +

      The tlsSocket.renegotiate() method initiates a TLS renegotiation process. +Upon completion, the callback function will be passed a single argument +that is either an Error (if the request failed) or null.

      +

      This method can be used to request a peer's certificate after the secure +connection has been established.

      +

      When running as the server, the socket will be destroyed with an error after +handshakeTimeout timeout.

      +

      For TLSv1.3, renegotiation cannot be initiated, it is not supported by the +protocol.

      +

      tlsSocket.setMaxSendFragment(size)#

      + +
        +
      • size <number> The maximum TLS fragment size. The maximum value is 16384. +Default: 16384.
      • +
      • Returns: <boolean>
      • +
      +

      The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size. +Returns true if setting the limit succeeded; false otherwise.

      +

      Smaller fragment sizes decrease the buffering latency on the client: larger +fragments are buffered by the TLS layer until the entire fragment is received +and its integrity is verified; large fragments can span multiple roundtrips +and their processing can be delayed due to packet loss or reordering. However, +smaller fragments add extra TLS framing bytes and CPU overhead, which may +decrease overall server throughput.

      +

      tls.checkServerIdentity(hostname, cert)#

      + + +

      Verifies the certificate cert is issued to hostname.

      +

      Returns <Error> object, populating it with reason, host, and cert on +failure. On success, returns <undefined>.

      +

      This function can be overwritten by providing alternative function as part of +the options.checkServerIdentity option passed to tls.connect(). The +overwriting function can call tls.checkServerIdentity() of course, to augment +the checks done with additional verification.

      +

      This function is only called if the certificate passed all other checks, such as +being issued by trusted CA (options.ca).

      +

      tls.connect(options[, callback])#

      + +
        +
      • options <Object> +
          +
        • enableTrace: See tls.createServer()
        • +
        • host <string> Host the client should connect to. Default: +'localhost'.
        • +
        • port <number> Port the client should connect to.
        • +
        • path <string> Creates Unix socket connection to path. If this option is +specified, host and port are ignored.
        • +
        • socket <stream.Duplex> Establish secure connection on a given socket +rather than creating a new socket. Typically, this is an instance of +net.Socket, but any Duplex stream is allowed. +If this option is specified, path, host and port are ignored, +except for certificate validation. Usually, a socket is already connected +when passed to tls.connect(), but it can be connected later. +Connection/disconnection/destruction of socket is the user's +responsibility; calling tls.connect() will not cause net.connect() to be +called.
        • +
        • allowHalfOpen <boolean> If the socket option is missing, indicates +whether or not to allow the internally created socket to be half-open, +otherwise the option is ignored. See the allowHalfOpen option of +net.Socket for details. Default: false.
        • +
        • rejectUnauthorized <boolean> If not false, the server certificate is +verified against the list of supplied CAs. An 'error' event is emitted if +verification fails; err.code contains the OpenSSL error code. Default: +true.
        • +
        • pskCallback <Function> +
            +
          • hint: <string> optional message sent from the server to help client +decide which identity to use during negotiation. +Always null if TLS 1.3 is used.
          • +
          • Returns: <Object> in the form + { psk: <Buffer|TypedArray|DataView>, identity: <string> } +or null to stop the negotiation process. psk must be +compatible with the selected cipher's digest. +identity must use UTF-8 encoding. +When negotiating TLS-PSK (pre-shared keys), this function is called +with optional identity hint provided by the server or null +in case of TLS 1.3 where hint was removed. +It will be necessary to provide a custom tls.checkServerIdentity() +for the connection as the default one will try to check host name/IP +of the server against the certificate but that's not applicable for PSK +because there won't be a certificate present. +More information can be found in the RFC 4279.
          • +
          +
        • +
        • ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> +An array of strings, Buffers or TypedArrays or DataViews, or a +single Buffer or TypedArray or DataView containing the supported ALPN +protocols. Buffers should have the format [len][name][len][name]... +e.g. '\x08http/1.1\x08http/1.0', where the len byte is the length of the +next protocol name. Passing an array is usually much simpler, e.g. +['http/1.1', 'http/1.0']. Protocols earlier in the list have higher +preference than those later.
        • +
        • servername: <string> Server name for the SNI (Server Name Indication) TLS +extension. It is the name of the host being connected to, and must be a host +name, and not an IP address. It can be used by a multi-homed server to +choose the correct certificate to present to the client, see the +SNICallback option to tls.createServer().
        • +
        • checkServerIdentity(servername, cert) <Function> A callback function +to be used (instead of the builtin tls.checkServerIdentity() function) +when checking the server's host name (or the provided servername when +explicitly set) against the certificate. This should return an <Error> if +verification fails. The method should return undefined if the servername +and cert are verified.
        • +
        • session <Buffer> A Buffer instance, containing TLS session.
        • +
        • minDHSize <number> Minimum size of the DH parameter in bits to accept a +TLS connection. When a server offers a DH parameter with a size less +than minDHSize, the TLS connection is destroyed and an error is thrown. +Default: 1024.
        • +
        • secureContext: TLS context object created with +tls.createSecureContext(). If a secureContext is not provided, one +will be created by passing the entire options object to +tls.createSecureContext().
        • +
        • ...: tls.createSecureContext() options that are used if the +secureContext option is missing, otherwise they are ignored.
        • +
        • ...: Any socket.connect() option not already listed.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <tls.TLSSocket>
      • +
      +

      The callback function, if specified, will be added as a listener for the +'secureConnect' event.

      +

      tls.connect() returns a tls.TLSSocket object.

      +

      Unlike the https API, tls.connect() does not enable the +SNI (Server Name Indication) extension by default, which may cause some +servers to return an incorrect certificate or reject the connection +altogether. To enable SNI, set the servername option in addition +to host.

      +

      The following illustrates a client for the echo server example from +tls.createServer():

      +
      // Assumes an echo server that is listening on port 8000.
      +const tls = require('tls');
      +const fs = require('fs');
      +
      +const options = {
      +  // Necessary only if the server requires client certificate authentication.
      +  key: fs.readFileSync('client-key.pem'),
      +  cert: fs.readFileSync('client-cert.pem'),
      +
      +  // Necessary only if the server uses a self-signed certificate.
      +  ca: [ fs.readFileSync('server-cert.pem') ],
      +
      +  // Necessary only if the server's cert isn't for "localhost".
      +  checkServerIdentity: () => { return null; },
      +};
      +
      +const socket = tls.connect(8000, options, () => {
      +  console.log('client connected',
      +              socket.authorized ? 'authorized' : 'unauthorized');
      +  process.stdin.pipe(socket);
      +  process.stdin.resume();
      +});
      +socket.setEncoding('utf8');
      +socket.on('data', (data) => {
      +  console.log(data);
      +});
      +socket.on('end', () => {
      +  console.log('server ends connection');
      +});
      +

      tls.connect(path[, options][, callback])#

      + + +

      Same as tls.connect() except that path can be provided +as an argument instead of an option.

      +

      A path option, if specified, will take precedence over the path argument.

      +

      tls.connect(port[, host][, options][, callback])#

      + + +

      Same as tls.connect() except that port and host can be provided +as arguments instead of options.

      +

      A port or host option, if specified, will take precedence over any port or host +argument.

      +

      tls.createSecureContext([options])#

      + +
        +
      • options <Object> +
          +
        • ca <string> | <string[]> | <Buffer> | <Buffer[]> Optionally override the trusted CA +certificates. Default is to trust the well-known CAs curated by Mozilla. +Mozilla's CAs are completely replaced when CAs are explicitly specified +using this option. The value can be a string or Buffer, or an Array of +strings and/or Buffers. Any string or Buffer can contain multiple PEM +CAs concatenated together. The peer's certificate must be chainable to a CA +trusted by the server for the connection to be authenticated. When using +certificates that are not chainable to a well-known CA, the certificate's CA +must be explicitly specified as a trusted or the connection will fail to +authenticate. +If the peer uses a certificate that doesn't match or chain to one of the +default CAs, use the ca option to provide a CA certificate that the peer's +certificate can match or chain to. +For self-signed certificates, the certificate is its own CA, and must be +provided. +For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", +"X509 CERTIFICATE", and "CERTIFICATE". +See also tls.rootCertificates.
        • +
        • cert <string> | <string[]> | <Buffer> | <Buffer[]> Cert chains in PEM format. One cert +chain should be provided per private key. Each cert chain should consist of +the PEM formatted certificate for a provided private key, followed by the +PEM formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, see ca). +When providing multiple cert chains, they do not have to be in the same +order as their private keys in key. If the intermediate certificates are +not provided, the peer will not be able to validate the certificate, and the +handshake will fail.
        • +
        • sigalgs <string> Colon-separated list of supported signature algorithms. +The list can contain digest algorithms (SHA256, MD5 etc.), public key +algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g +'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). +See OpenSSL man pages +for more info.
        • +
        • ciphers <string> Cipher suite specification, replacing the default. For +more information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
        • +
        • clientCertEngine <string> Name of an OpenSSL engine which can provide the +client certificate.
        • +
        • crl <string> | <string[]> | <Buffer> | <Buffer[]> PEM formatted CRLs (Certificate +Revocation Lists).
        • +
        • dhparam <string> | <Buffer> Diffie-Hellman parameters, required for +perfect forward secrecy. Use openssl dhparam to create the parameters. +The key length must be greater than or equal to 1024 bits or else an error +will be thrown. Although 1024 bits is permissible, use 2048 bits or larger +for stronger security. If omitted or invalid, the parameters are silently +discarded and DHE ciphers will not be available.
        • +
        • ecdhCurve <string> A string describing a named curve or a colon separated +list of curve NIDs or names, for example P-521:P-384:P-256, to use for +ECDH key agreement. Set to auto to select the +curve automatically. Use crypto.getCurves() to obtain a list of +available curve names. On recent releases, openssl ecparam -list_curves +will also display the name and description of each available elliptic curve. +Default: tls.DEFAULT_ECDH_CURVE.
        • +
        • honorCipherOrder <boolean> Attempt to use the server's cipher suite +preferences instead of the client's. When true, causes +SSL_OP_CIPHER_SERVER_PREFERENCE to be set in secureOptions, see +OpenSSL Options for more information.
        • +
        • key <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> Private keys in PEM format. +PEM allows the option of private keys being encrypted. Encrypted keys will +be decrypted with options.passphrase. Multiple keys using different +algorithms can be provided either as an array of unencrypted key strings or +buffers, or an array of objects in the form +{pem: <string|buffer>[, passphrase: <string>]}. The object form can only +occur in an array. object.passphrase is optional. Encrypted keys will be +decrypted with object.passphrase if provided, or options.passphrase if +it is not.
        • +
        • privateKeyEngine <string> Name of an OpenSSL engine to get private key +from. Should be used together with privateKeyIdentifier.
        • +
        • privateKeyIdentifier <string> Identifier of a private key managed by +an OpenSSL engine. Should be used together with privateKeyEngine. +Should not be set together with key, because both options define a +private key in different ways.
        • +
        • maxVersion <string> Optionally set the maximum TLS version to allow. One +of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified +along with the secureProtocol option, use one or the other. +Default: tls.DEFAULT_MAX_VERSION.
        • +
        • minVersion <string> Optionally set the minimum TLS version to allow. One +of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified +along with the secureProtocol option, use one or the other. It is not +recommended to use less than TLSv1.2, but it may be required for +interoperability. +Default: tls.DEFAULT_MIN_VERSION.
        • +
        • passphrase <string> Shared passphrase used for a single private key and/or +a PFX.
        • +
        • pfx <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PFX or PKCS12 encoded +private key and certificate chain. pfx is an alternative to providing +key and cert individually. PFX is usually encrypted, if it is, +passphrase will be used to decrypt it. Multiple PFX can be provided either +as an array of unencrypted PFX buffers, or an array of objects in the form +{buf: <string|buffer>[, passphrase: <string>]}. The object form can only +occur in an array. object.passphrase is optional. Encrypted PFX will be +decrypted with object.passphrase if provided, or options.passphrase if +it is not.
        • +
        • secureOptions <number> Optionally affect the OpenSSL protocol behavior, +which is not usually necessary. This should be used carefully if at all! +Value is a numeric bitmask of the SSL_OP_* options from +OpenSSL Options.
        • +
        • secureProtocol <string> Legacy mechanism to select the TLS protocol +version to use, it does not support independent control of the minimum and +maximum version, and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow any +TLS protocol version up to TLSv1.3. It is not recommended to use TLS +versions less than 1.2, but it may be required for interoperability. +Default: none, see minVersion.
        • +
        • sessionIdContext <string> Opaque identifier used by servers to ensure +session state is not shared between applications. Unused by clients.
        • +
        • ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudo-random +data. See Session Resumption for more information.
        • +
        • sessionTimeout <number> The number of seconds after which a TLS session +created by the server will no longer be resumable. See +Session Resumption for more information. Default: 300.
        • +
        +
      • +
      +

      tls.createServer() sets the default value of the honorCipherOrder option +to true, other APIs that create secure contexts leave it unset.

      +

      tls.createServer() uses a 128 bit truncated SHA1 hash value generated +from process.argv as the default value of the sessionIdContext option, other +APIs that create secure contexts have no default value.

      +

      The tls.createSecureContext() method creates a SecureContext object. It is +usable as an argument to several tls APIs, such as tls.createServer() +and server.addContext(), but has no public methods.

      +

      A key is required for ciphers that use certificates. Either key or +pfx can be used to provide it.

      +

      If the ca option is not given, then Node.js will default to using +Mozilla's publicly trusted list of CAs.

      +

      tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])#

      + +

      Stability: 0 - Deprecated: Use tls.TLSSocket instead.

      +
        +
      • context <Object> A secure context object as returned by +tls.createSecureContext()
      • +
      • isServer <boolean> true to specify that this TLS connection should be +opened as a server.
      • +
      • requestCert <boolean> true to specify whether a server should request a +certificate from a connecting client. Only applies when isServer is true.
      • +
      • rejectUnauthorized <boolean> If not false a server automatically reject +clients with invalid certificates. Only applies when isServer is true.
      • +
      • options + +
      • +
      +

      Creates a new secure pair object with two streams, one of which reads and writes +the encrypted data and the other of which reads and writes the cleartext data. +Generally, the encrypted stream is piped to/from an incoming encrypted data +stream and the cleartext one is used as a replacement for the initial encrypted +stream.

      +

      tls.createSecurePair() returns a tls.SecurePair object with cleartext and +encrypted stream properties.

      +

      Using cleartext has the same API as tls.TLSSocket.

      +

      The tls.createSecurePair() method is now deprecated in favor of +tls.TLSSocket(). For example, the code:

      +
      pair = tls.createSecurePair(/* ... */);
      +pair.encrypted.pipe(socket);
      +socket.pipe(pair.encrypted);
      +

      can be replaced by:

      +
      secureSocket = tls.TLSSocket(socket, options);
      +

      where secureSocket has the same API as pair.cleartext.

      +

      tls.createServer([options][, secureConnectionListener])#

      + +
        +
      • options <Object> +
          +
        • ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> +An array of strings, Buffers or TypedArrays or DataViews, or a single +Buffer or TypedArray or DataView containing the supported ALPN +protocols. Buffers should have the format [len][name][len][name]... +e.g. 0x05hello0x05world, where the first byte is the length of the next +protocol name. Passing an array is usually much simpler, e.g. +['hello', 'world']. (Protocols should be ordered by their priority.)
        • +
        • clientCertEngine <string> Name of an OpenSSL engine which can provide the +client certificate.
        • +
        • enableTrace <boolean> If true, tls.TLSSocket.enableTrace() will be +called on new connections. Tracing can be enabled after the secure +connection is established, but this option must be used to trace the secure +connection setup. Default: false.
        • +
        • handshakeTimeout <number> Abort the connection if the SSL/TLS handshake +does not finish in the specified number of milliseconds. +A 'tlsClientError' is emitted on the tls.Server object whenever +a handshake times out. Default: 120000 (120 seconds).
        • +
        • rejectUnauthorized <boolean> If not false the server will reject any +connection which is not authorized with the list of supplied CAs. This +option only has an effect if requestCert is true. Default: true.
        • +
        • requestCert <boolean> If true the server will request a certificate from +clients that connect and attempt to verify that certificate. Default: +false.
        • +
        • sessionTimeout <number> The number of seconds after which a TLS session +created by the server will no longer be resumable. See +Session Resumption for more information. Default: 300.
        • +
        • SNICallback(servername, callback) <Function> A function that will be +called if the client supports SNI TLS extension. Two arguments will be +passed when called: servername and callback. callback is an +error-first callback that takes two optional arguments: error and ctx. +ctx, if provided, is a SecureContext instance. +tls.createSecureContext() can be used to get a proper SecureContext. +If callback is called with a falsy ctx argument, the default secure +context of the server will be used. If SNICallback wasn't provided the +default callback with high-level API will be used (see below).
        • +
        • ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudo-random +data. See Session Resumption for more information.
        • +
        • pskCallback <Function> +
            +
          • socket: <tls.TLSSocket> the server tls.TLSSocket instance for +this connection.
          • +
          • identity: <string> identity parameter sent from the client.
          • +
          • Returns: <Buffer> | <TypedArray> | <DataView> pre-shared key that must either be + a buffer or null to stop the negotiation process. Returned PSK must be +compatible with the selected cipher's digest. +When negotiating TLS-PSK (pre-shared keys), this function is called +with the identity provided by the client. +If the return value is null the negotiation process will stop and an +"unknown_psk_identity" alert message will be sent to the other party. +If the server wishes to hide the fact that the PSK identity was not known, +the callback must provide some random data as psk to make the connection +fail with "decrypt_error" before negotiation is finished. +PSK ciphers are disabled by default, and using TLS-PSK thus +requires explicitly specifying a cipher suite with the ciphers option. +More information can be found in the RFC 4279.
          • +
          +
        • +
        • pskIdentityHint <string> optional hint to send to a client to help +with selecting the identity during TLS-PSK negotiation. Will be ignored +in TLS 1.3. Upon failing to set pskIdentityHint 'tlsClientError' will be +emitted with 'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' code.
        • +
        • ...: Any tls.createSecureContext() option can be provided. For +servers, the identity options (pfx, key/cert or pskCallback) +are usually required.
        • +
        • ...: Any net.createServer() option can be provided.
        • +
        +
      • +
      • secureConnectionListener <Function>
      • +
      • Returns: <tls.Server>
      • +
      +

      Creates a new tls.Server. The secureConnectionListener, if provided, is +automatically set as a listener for the 'secureConnection' event.

      +

      The ticketKeys options is automatically shared between cluster module +workers.

      +

      The following illustrates a simple echo server:

      +
      const tls = require('tls');
      +const fs = require('fs');
      +
      +const options = {
      +  key: fs.readFileSync('server-key.pem'),
      +  cert: fs.readFileSync('server-cert.pem'),
      +
      +  // This is necessary only if using client certificate authentication.
      +  requestCert: true,
      +
      +  // This is necessary only if the client uses a self-signed certificate.
      +  ca: [ fs.readFileSync('client-cert.pem') ]
      +};
      +
      +const server = tls.createServer(options, (socket) => {
      +  console.log('server connected',
      +              socket.authorized ? 'authorized' : 'unauthorized');
      +  socket.write('welcome!\n');
      +  socket.setEncoding('utf8');
      +  socket.pipe(socket);
      +});
      +server.listen(8000, () => {
      +  console.log('server bound');
      +});
      +

      The server can be tested by connecting to it using the example client from +tls.connect().

      +

      tls.getCiphers()#

      + + +

      Returns an array with the names of the supported TLS ciphers. The names are +lower-case for historical reasons, but must be uppercased to be used in +the ciphers option of tls.createSecureContext().

      +

      Cipher names that start with 'tls_' are for TLSv1.3, all the others are for +TLSv1.2 and below.

      +
      console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
      +

      tls.rootCertificates#

      + + +

      An immutable array of strings representing the root certificates (in PEM format) +from the bundled Mozilla CA store as supplied by current Node.js version.

      +

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store +that is fixed at release time. It is identical on all supported platforms.

      +

      tls.DEFAULT_ECDH_CURVE#

      + +

      The default curve name to use for ECDH key agreement in a tls server. The +default value is 'auto'. See tls.createSecureContext() for further +information.

      +

      tls.DEFAULT_MAX_VERSION#

      + +
        +
      • <string> The default value of the maxVersion option of +tls.createSecureContext(). It can be assigned any of the supported TLS +protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. +Default: 'TLSv1.3', unless changed using CLI options. Using +--tls-max-v1.2 sets the default to 'TLSv1.2'. Using --tls-max-v1.3 sets +the default to 'TLSv1.3'. If multiple of the options are provided, the +highest maximum is used.
      • +
      +

      tls.DEFAULT_MIN_VERSION#

      + +
        +
      • <string> The default value of the minVersion option of +tls.createSecureContext(). It can be assigned any of the supported TLS +protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. +Default: 'TLSv1.2', unless changed using CLI options. Using +--tls-min-v1.0 sets the default to 'TLSv1'. Using --tls-min-v1.1 sets +the default to 'TLSv1.1'. Using --tls-min-v1.3 sets the default to +'TLSv1.3'. If multiple of the options are provided, the lowest minimum is +used.
      • +
      +

      Trace events#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/trace_events.js

      +

      The trace_events module provides a mechanism to centralize tracing information +generated by V8, Node.js core, and userspace code.

      +

      Tracing can be enabled with the --trace-event-categories command-line flag +or by using the trace_events module. The --trace-event-categories flag +accepts a list of comma-separated category names.

      +

      The available categories are:

      +
        +
      • node: An empty placeholder.
      • +
      • node.async_hooks: Enables capture of detailed async_hooks trace data. +The async_hooks events have a unique asyncId and a special triggerId +triggerAsyncId property.
      • +
      • node.bootstrap: Enables capture of Node.js bootstrap milestones.
      • +
      • node.console: Enables capture of console.time() and console.count() +output.
      • +
      • node.dns.native: Enables capture of trace data for DNS queries.
      • +
      • node.environment: Enables capture of Node.js Environment milestones.
      • +
      • node.fs.sync: Enables capture of trace data for file system sync methods.
      • +
      • node.perf: Enables capture of Performance API measurements. +
          +
        • node.perf.usertiming: Enables capture of only Performance API User Timing +measures and marks.
        • +
        • node.perf.timerify: Enables capture of only Performance API timerify +measurements.
        • +
        +
      • +
      • node.promises.rejections: Enables capture of trace data tracking the number +of unhandled Promise rejections and handled-after-rejections.
      • +
      • node.vm.script: Enables capture of trace data for the vm module's +runInNewContext(), runInContext(), and runInThisContext() methods.
      • +
      • v8: The V8 events are GC, compiling, and execution related.
      • +
      +

      By default the node, node.async_hooks, and v8 categories are enabled.

      +
      node --trace-event-categories v8,node,node.async_hooks server.js
      +

      Prior versions of Node.js required the use of the --trace-events-enabled +flag to enable trace events. This requirement has been removed. However, the +--trace-events-enabled flag may still be used and will enable the +node, node.async_hooks, and v8 trace event categories by default.

      +
      node --trace-events-enabled
      +
      +# is equivalent to
      +
      +node --trace-event-categories v8,node,node.async_hooks
      +

      Alternatively, trace events may be enabled using the trace_events module:

      +
      const trace_events = require('trace_events');
      +const tracing = trace_events.createTracing({ categories: ['node.perf'] });
      +tracing.enable();  // Enable trace event capture for the 'node.perf' category
      +
      +// do work
      +
      +tracing.disable();  // Disable trace event capture for the 'node.perf' category
      +

      Running Node.js with tracing enabled will produce log files that can be opened +in the chrome://tracing +tab of Chrome.

      +

      The logging file is by default called node_trace.${rotation}.log, where +${rotation} is an incrementing log-rotation id. The filepath pattern can +be specified with --trace-event-file-pattern that accepts a template +string that supports ${rotation} and ${pid}:

      +
      node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
      +

      The tracing system uses the same time source +as the one used by process.hrtime(). +However the trace-event timestamps are expressed in microseconds, +unlike process.hrtime() which returns nanoseconds.

      +

      The features from this module are not available in Worker threads.

      +

      The trace_events module#

      + +

      Tracing object#

      + +

      The Tracing object is used to enable or disable tracing for sets of +categories. Instances are created using the trace_events.createTracing() +method.

      +

      When created, the Tracing object is disabled. Calling the +tracing.enable() method adds the categories to the set of enabled trace event +categories. Calling tracing.disable() will remove the categories from the +set of enabled trace event categories.

      +

      tracing.categories#

      + + +

      A comma-separated list of the trace event categories covered by this +Tracing object.

      +

      tracing.disable()#

      + +

      Disables this Tracing object.

      +

      Only trace event categories not covered by other enabled Tracing objects +and not specified by the --trace-event-categories flag will be disabled.

      +
      const trace_events = require('trace_events');
      +const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
      +const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
      +t1.enable();
      +t2.enable();
      +
      +// Prints 'node,node.perf,v8'
      +console.log(trace_events.getEnabledCategories());
      +
      +t2.disable(); // Will only disable emission of the 'node.perf' category
      +
      +// Prints 'node,v8'
      +console.log(trace_events.getEnabledCategories());
      +

      tracing.enable()#

      + +

      Enables this Tracing object for the set of categories covered by the +Tracing object.

      +

      tracing.enabled#

      + +
        +
      • <boolean> true only if the Tracing object has been enabled.
      • +
      +

      trace_events.createTracing(options)#

      + +
        +
      • options <Object> +
          +
        • categories <string[]> An array of trace category names. Values included +in the array are coerced to a string when possible. An error will be +thrown if the value cannot be coerced.
        • +
        +
      • +
      • Returns: <Tracing>.
      • +
      +

      Creates and returns a Tracing object for the given set of categories.

      +
      const trace_events = require('trace_events');
      +const categories = ['node.perf', 'node.async_hooks'];
      +const tracing = trace_events.createTracing({ categories });
      +tracing.enable();
      +// do stuff
      +tracing.disable();
      +

      trace_events.getEnabledCategories()#

      + + +

      Returns a comma-separated list of all currently-enabled trace event +categories. The current set of enabled trace event categories is determined +by the union of all currently-enabled Tracing objects and any categories +enabled using the --trace-event-categories flag.

      +

      Given the file test.js below, the command +node --trace-event-categories node.perf test.js will print +'node.async_hooks,node.perf' to the console.

      +
      const trace_events = require('trace_events');
      +const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
      +const t2 = trace_events.createTracing({ categories: ['node.perf'] });
      +const t3 = trace_events.createTracing({ categories: ['v8'] });
      +
      +t1.enable();
      +t2.enable();
      +
      +console.log(trace_events.getEnabledCategories());
      +

      TTY#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/tty.js

      +

      The tty module provides the tty.ReadStream and tty.WriteStream classes. +In most cases, it will not be necessary or possible to use this module directly. +However, it can be accessed using:

      +
      const tty = require('tty');
      +

      When Node.js detects that it is being run with a text terminal ("TTY") +attached, process.stdin will, by default, be initialized as an instance of +tty.ReadStream and both process.stdout and process.stderr will, by +default be instances of tty.WriteStream. The preferred method of determining +whether Node.js is being run within a TTY context is to check that the value of +the process.stdout.isTTY property is true:

      +
      $ node -p -e "Boolean(process.stdout.isTTY)"
      +true
      +$ node -p -e "Boolean(process.stdout.isTTY)" | cat
      +false
      +

      In most cases, there should be little to no reason for an application to +manually create instances of the tty.ReadStream and tty.WriteStream +classes.

      +

      Class: tty.ReadStream#

      + + +

      Represents the readable side of a TTY. In normal circumstances +process.stdin will be the only tty.ReadStream instance in a Node.js +process and there should be no reason to create additional instances.

      +

      readStream.isRaw#

      + +

      A boolean that is true if the TTY is currently configured to operate as a +raw device. Defaults to false.

      +

      readStream.isTTY#

      + +

      A boolean that is always true for tty.ReadStream instances.

      +

      readStream.setRawMode(mode)#

      + +
        +
      • mode <boolean> If true, configures the tty.ReadStream to operate as a +raw device. If false, configures the tty.ReadStream to operate in its +default mode. The readStream.isRaw property will be set to the resulting +mode.
      • +
      • Returns: <this> The read stream instance.
      • +
      +

      Allows configuration of tty.ReadStream so that it operates as a raw device.

      +

      When in raw mode, input is always available character-by-character, not +including modifiers. Additionally, all special processing of characters by the +terminal is disabled, including echoing input characters. +CTRL+C will no longer cause a SIGINT when in this mode.

      +

      Class: tty.WriteStream#

      + + +

      Represents the writable side of a TTY. In normal circumstances, +process.stdout and process.stderr will be the only +tty.WriteStream instances created for a Node.js process and there +should be no reason to create additional instances.

      +

      Event: 'resize'#

      + +

      The 'resize' event is emitted whenever either of the writeStream.columns +or writeStream.rows properties have changed. No arguments are passed to the +listener callback when called.

      +
      process.stdout.on('resize', () => {
      +  console.log('screen size has changed!');
      +  console.log(`${process.stdout.columns}x${process.stdout.rows}`);
      +});
      +

      writeStream.clearLine(dir[, callback])#

      + +
        +
      • dir <number> +
          +
        • -1: to the left from cursor
        • +
        • 1: to the right from cursor
        • +
        • 0: the entire line
        • +
        +
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.clearLine() clears the current line of this WriteStream in a +direction identified by dir.

      +

      writeStream.clearScreenDown([callback])#

      + +
        +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.clearScreenDown() clears this WriteStream from the current +cursor down.

      +

      writeStream.columns#

      + +

      A number specifying the number of columns the TTY currently has. This property +is updated whenever the 'resize' event is emitted.

      +

      writeStream.cursorTo(x[, y][, callback])#

      + +
        +
      • x <number>
      • +
      • y <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.cursorTo() moves this WriteStream's cursor to the specified +position.

      +

      writeStream.getColorDepth([env])#

      + +
        +
      • env <Object> An object containing the environment variables to check. This +enables simulating the usage of a specific terminal. Default: +process.env.
      • +
      • Returns: <number>
      • +
      +

      Returns:

      +
        +
      • 1 for 2,
      • +
      • 4 for 16,
      • +
      • 8 for 256,
      • +
      • 24 for 16,777,216 +colors supported.
      • +
      +

      Use this to determine what colors the terminal supports. Due to the nature of +colors in terminals it is possible to either have false positives or false +negatives. It depends on process information and the environment variables that +may lie about what terminal is used. +It is possible to pass in an env object to simulate the usage of a specific +terminal. This can be useful to check how specific environment settings behave.

      +

      To enforce a specific color support, use one of the below environment settings.

      +
        +
      • 2 colors: FORCE_COLOR = 0 (Disables colors)
      • +
      • 16 colors: FORCE_COLOR = 1
      • +
      • 256 colors: FORCE_COLOR = 2
      • +
      • 16,777,216 colors: FORCE_COLOR = 3
      • +
      +

      Disabling color support is also possible by using the NO_COLOR and +NODE_DISABLE_COLORS environment variables.

      +

      writeStream.getWindowSize()#

      + + +

      writeStream.getWindowSize() returns the size of the TTY +corresponding to this WriteStream. The array is of the type +[numColumns, numRows] where numColumns and numRows represent the number +of columns and rows in the corresponding TTY.

      +

      writeStream.hasColors([count][, env])#

      + +
        +
      • count <integer> The number of colors that are requested (minimum 2). +Default: 16.
      • +
      • env <Object> An object containing the environment variables to check. This +enables simulating the usage of a specific terminal. Default: +process.env.
      • +
      • Returns: <boolean>
      • +
      +

      Returns true if the writeStream supports at least as many colors as provided +in count. Minimum support is 2 (black and white).

      +

      This has the same false positives and negatives as described in +writeStream.getColorDepth().

      +
      process.stdout.hasColors();
      +// Returns true or false depending on if `stdout` supports at least 16 colors.
      +process.stdout.hasColors(256);
      +// Returns true or false depending on if `stdout` supports at least 256 colors.
      +process.stdout.hasColors({ TMUX: '1' });
      +// Returns true.
      +process.stdout.hasColors(2 ** 24, { TMUX: '1' });
      +// Returns false (the environment setting pretends to support 2 ** 8 colors).
      +

      writeStream.isTTY#

      + +

      A boolean that is always true.

      +

      writeStream.moveCursor(dx, dy[, callback])#

      + +
        +
      • dx <number>
      • +
      • dy <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.moveCursor() moves this WriteStream's cursor relative to its +current position.

      +

      writeStream.rows#

      + +

      A number specifying the number of rows the TTY currently has. This property +is updated whenever the 'resize' event is emitted.

      +

      tty.isatty(fd)#

      + + +

      The tty.isatty() method returns true if the given fd is associated with +a TTY and false if it is not, including whenever fd is not a non-negative +integer.

      +

      UDP/datagram sockets#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/dgram.js

      +

      The dgram module provides an implementation of UDP datagram sockets.

      +
      const dgram = require('dgram');
      +const server = dgram.createSocket('udp4');
      +
      +server.on('error', (err) => {
      +  console.log(`server error:\n${err.stack}`);
      +  server.close();
      +});
      +
      +server.on('message', (msg, rinfo) => {
      +  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
      +});
      +
      +server.on('listening', () => {
      +  const address = server.address();
      +  console.log(`server listening ${address.address}:${address.port}`);
      +});
      +
      +server.bind(41234);
      +// Prints: server listening 0.0.0.0:41234
      +

      Class: dgram.Socket#

      + + +

      Encapsulates the datagram functionality.

      +

      New instances of dgram.Socket are created using dgram.createSocket(). +The new keyword is not to be used to create dgram.Socket instances.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted after a socket is closed with close(). +Once triggered, no new 'message' events will be emitted on this socket.

      +

      Event: 'connect'#

      + +

      The 'connect' event is emitted after a socket is associated to a remote +address as a result of a successful connect() call.

      +

      Event: 'error'#

      + + +

      The 'error' event is emitted whenever any error occurs. The event handler +function is passed a single Error object.

      +

      Event: 'listening'#

      + +

      The 'listening' event is emitted once the dgram.Socket is addressable and +can receive data. This happens either explicitly with socket.bind() or +implicitly the first time data is sent using socket.send(). +Until the dgram.Socket is listening, the underlying system resources do not +exist and calls such as socket.address() and socket.setTTL() will fail.

      +

      Event: 'message'#

      + +

      The 'message' event is emitted when a new datagram is available on a socket. +The event handler function is passed two arguments: msg and rinfo.

      + +

      If the source address of the incoming packet is an IPv6 link-local +address, the interface name is added to the address. For +example, a packet received on the en0 interface might have the +address field set to 'fe80::2618:1234:ab11:3b9c%en0', where '%en0' +is the interface name as a zone ID suffix.

      +

      socket.addMembership(multicastAddress[, multicastInterface])#

      + + +

      Tells the kernel to join a multicast group at the given multicastAddress and +multicastInterface using the IP_ADD_MEMBERSHIP socket option. If the +multicastInterface argument is not specified, the operating system will choose +one interface and will add membership to it. To add membership to every +available interface, call addMembership multiple times, once per interface.

      +

      When called on an unbound socket, this method will implicitly bind to a random +port, listening on all interfaces.

      +

      When sharing a UDP socket across multiple cluster workers, the +socket.addMembership() function must be called only once or an +EADDRINUSE error will occur:

      +
      const cluster = require('cluster');
      +const dgram = require('dgram');
      +if (cluster.isMaster) {
      +  cluster.fork(); // Works ok.
      +  cluster.fork(); // Fails with EADDRINUSE.
      +} else {
      +  const s = dgram.createSocket('udp4');
      +  s.bind(1234, () => {
      +    s.addMembership('224.0.0.114');
      +  });
      +}
      +

      socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])#

      + + +

      Tells the kernel to join a source-specific multicast channel at the given +sourceAddress and groupAddress, using the multicastInterface with the +IP_ADD_SOURCE_MEMBERSHIP socket option. If the multicastInterface argument +is not specified, the operating system will choose one interface and will add +membership to it. To add membership to every available interface, call +socket.addSourceSpecificMembership() multiple times, once per interface.

      +

      When called on an unbound socket, this method will implicitly bind to a random +port, listening on all interfaces.

      +

      socket.address()#

      + + +

      Returns an object containing the address information for a socket. +For UDP sockets, this object will contain address, family and port +properties.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.bind([port][, address][, callback])#

      + + +

      For UDP sockets, causes the dgram.Socket to listen for datagram +messages on a named port and optional address. If port is not +specified or is 0, the operating system will attempt to bind to a +random port. If address is not specified, the operating system will +attempt to listen on all addresses. Once binding is complete, a +'listening' event is emitted and the optional callback function is +called.

      +

      Specifying both a 'listening' event listener and passing a +callback to the socket.bind() method is not harmful but not very +useful.

      +

      A bound datagram socket keeps the Node.js process running to receive +datagram messages.

      +

      If binding fails, an 'error' event is generated. In rare case (e.g. +attempting to bind with a closed socket), an Error may be thrown.

      +

      Example of a UDP server listening on port 41234:

      +
      const dgram = require('dgram');
      +const server = dgram.createSocket('udp4');
      +
      +server.on('error', (err) => {
      +  console.log(`server error:\n${err.stack}`);
      +  server.close();
      +});
      +
      +server.on('message', (msg, rinfo) => {
      +  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
      +});
      +
      +server.on('listening', () => {
      +  const address = server.address();
      +  console.log(`server listening ${address.address}:${address.port}`);
      +});
      +
      +server.bind(41234);
      +// Prints: server listening 0.0.0.0:41234
      +

      socket.bind(options[, callback])#

      + + +

      For UDP sockets, causes the dgram.Socket to listen for datagram +messages on a named port and optional address that are passed as +properties of an options object passed as the first argument. If +port is not specified or is 0, the operating system will attempt +to bind to a random port. If address is not specified, the operating +system will attempt to listen on all addresses. Once binding is +complete, a 'listening' event is emitted and the optional callback +function is called.

      +

      The options object may contain a fd property. When a fd greater +than 0 is set, it will wrap around an existing socket with the given +file descriptor. In this case, the properties of port and address +will be ignored.

      +

      Specifying both a 'listening' event listener and passing a +callback to the socket.bind() method is not harmful but not very +useful.

      +

      The options object may contain an additional exclusive property that is +used when using dgram.Socket objects with the cluster module. When +exclusive is set to false (the default), cluster workers will use the same +underlying socket handle allowing connection handling duties to be shared. +When exclusive is true, however, the handle is not shared and attempted +port sharing results in an error.

      +

      A bound datagram socket keeps the Node.js process running to receive +datagram messages.

      +

      If binding fails, an 'error' event is generated. In rare case (e.g. +attempting to bind with a closed socket), an Error may be thrown.

      +

      An example socket listening on an exclusive port is shown below.

      +
      socket.bind({
      +  address: 'localhost',
      +  port: 8000,
      +  exclusive: true
      +});
      +

      socket.close([callback])#

      + +
        +
      • callback <Function> Called when the socket has been closed.
      • +
      +

      Close the underlying socket and stop listening for data on it. If a callback is +provided, it is added as a listener for the 'close' event.

      +

      socket.connect(port[, address][, callback])#

      + + +

      Associates the dgram.Socket to a remote address and port. Every +message sent by this handle is automatically sent to that destination. Also, +the socket will only receive messages from that remote peer. +Trying to call connect() on an already connected socket will result +in an ERR_SOCKET_DGRAM_IS_CONNECTED exception. If address is not +provided, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets) +will be used by default. Once the connection is complete, a 'connect' event +is emitted and the optional callback function is called. In case of failure, +the callback is called or, failing this, an 'error' event is emitted.

      +

      socket.disconnect()#

      + +

      A synchronous function that disassociates a connected dgram.Socket from +its remote address. Trying to call disconnect() on an unbound or already +disconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED +exception.

      +

      socket.dropMembership(multicastAddress[, multicastInterface])#

      + + +

      Instructs the kernel to leave a multicast group at multicastAddress using the +IP_DROP_MEMBERSHIP socket option. This method is automatically called by the +kernel when the socket is closed or the process terminates, so most apps will +never have reason to call this.

      +

      If multicastInterface is not specified, the operating system will attempt to +drop membership on all valid interfaces.

      +

      socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])#

      + + +

      Instructs the kernel to leave a source-specific multicast channel at the given +sourceAddress and groupAddress using the IP_DROP_SOURCE_MEMBERSHIP +socket option. This method is automatically called by the kernel when the +socket is closed or the process terminates, so most apps will never have +reason to call this.

      +

      If multicastInterface is not specified, the operating system will attempt to +drop membership on all valid interfaces.

      +

      socket.getRecvBufferSize()#

      + +
        +
      • Returns: <number> the SO_RCVBUF socket receive buffer size in bytes.
      • +
      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.getSendBufferSize()#

      + +
        +
      • Returns: <number> the SO_SNDBUF socket send buffer size in bytes.
      • +
      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.ref()#

      + + +

      By default, binding a socket will cause it to block the Node.js process from +exiting as long as the socket is open. The socket.unref() method can be used +to exclude the socket from the reference counting that keeps the Node.js +process active. The socket.ref() method adds the socket back to the reference +counting and restores the default behavior.

      +

      Calling socket.ref() multiples times will have no additional effect.

      +

      The socket.ref() method returns a reference to the socket so calls can be +chained.

      +

      socket.remoteAddress()#

      + + +

      Returns an object containing the address, family, and port of the remote +endpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED exception +if the socket is not connected.

      +

      socket.send(msg[, offset, length][, port][, address][, callback])#

      + + +

      Broadcasts a datagram on the socket. +For connectionless sockets, the destination port and address must be +specified. Connected sockets, on the other hand, will use their associated +remote endpoint, so the port and address arguments must not be set.

      +

      The msg argument contains the message to be sent. +Depending on its type, different behavior can apply. If msg is a Buffer, +any TypedArray or a DataView, +the offset and length specify the offset within the Buffer where the +message begins and the number of bytes in the message, respectively. +If msg is a String, then it is automatically converted to a Buffer +with 'utf8' encoding. With messages that +contain multi-byte characters, offset and length will be calculated with +respect to byte length and not the character position. +If msg is an array, offset and length must not be specified.

      +

      The address argument is a string. If the value of address is a host name, +DNS will be used to resolve the address of the host. If address is not +provided or otherwise falsy, '127.0.0.1' (for udp4 sockets) or '::1' +(for udp6 sockets) will be used by default.

      +

      If the socket has not been previously bound with a call to bind, the socket +is assigned a random port number and is bound to the "all interfaces" address +('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

      +

      An optional callback function may be specified to as a way of reporting +DNS errors or for determining when it is safe to reuse the buf object. +DNS lookups delay the time to send for at least one tick of the +Node.js event loop.

      +

      The only way to know for sure that the datagram has been sent is by using a +callback. If an error occurs and a callback is given, the error will be +passed as the first argument to the callback. If a callback is not given, +the error is emitted as an 'error' event on the socket object.

      +

      Offset and length are optional but both must be set if either are used. +They are supported only when the first argument is a Buffer, a TypedArray, +or a DataView.

      +

      This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.

      +

      Example of sending a UDP packet to a port on localhost;

      +
      const dgram = require('dgram');
      +const message = Buffer.from('Some bytes');
      +const client = dgram.createSocket('udp4');
      +client.send(message, 41234, 'localhost', (err) => {
      +  client.close();
      +});
      +

      Example of sending a UDP packet composed of multiple buffers to a port on +127.0.0.1;

      +
      const dgram = require('dgram');
      +const buf1 = Buffer.from('Some ');
      +const buf2 = Buffer.from('bytes');
      +const client = dgram.createSocket('udp4');
      +client.send([buf1, buf2], 41234, (err) => {
      +  client.close();
      +});
      +

      Sending multiple buffers might be faster or slower depending on the +application and operating system. Run benchmarks to +determine the optimal strategy on a case-by-case basis. Generally speaking, +however, sending multiple buffers is faster.

      +

      Example of sending a UDP packet using a socket connected to a port on +localhost:

      +
      const dgram = require('dgram');
      +const message = Buffer.from('Some bytes');
      +const client = dgram.createSocket('udp4');
      +client.connect(41234, 'localhost', (err) => {
      +  client.send(message, (err) => {
      +    client.close();
      +  });
      +});
      +

      Note about UDP datagram size#

      +

      The maximum size of an IPv4/v6 datagram depends on the MTU +(Maximum Transmission Unit) and on the Payload Length field size.

      +
        +
      • +

        The Payload Length field is 16 bits wide, which means that a normal +payload cannot exceed 64K octets including the internet header and data +(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); +this is generally true for loopback interfaces, but such long datagram +messages are impractical for most hosts and networks.

        +
      • +
      • +

        The MTU is the largest size a given link layer technology can support for +datagram messages. For any link, IPv4 mandates a minimum MTU of 68 +octets, while the recommended MTU for IPv4 is 576 (typically recommended +as the MTU for dial-up type applications), whether they arrive whole or in +fragments.

        +

        For IPv6, the minimum MTU is 1280 octets. However, the mandatory minimum +fragment reassembly buffer size is 1500 octets. The value of 68 octets is +very small, since most current link layer technologies, like Ethernet, have a +minimum MTU of 1500.

        +
      • +
      +

      It is impossible to know in advance the MTU of each link through which +a packet might travel. Sending a datagram greater than the receiver MTU will +not work because the packet will get silently dropped without informing the +source that the data did not reach its intended recipient.

      +

      socket.setBroadcast(flag)#

      + + +

      Sets or clears the SO_BROADCAST socket option. When set to true, UDP +packets may be sent to a local interface's broadcast address.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.setMulticastInterface(multicastInterface)#

      + + +

      All references to scope in this section are referring to +IPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP +with a scope index is written as 'IP%scope' where scope is an interface name +or interface number.

      +

      Sets the default outgoing multicast interface of the socket to a chosen +interface or back to system interface selection. The multicastInterface must +be a valid string representation of an IP from the socket's family.

      +

      For IPv4 sockets, this should be the IP configured for the desired physical +interface. All packets sent to multicast on the socket will be sent on the +interface determined by the most recent successful use of this call.

      +

      For IPv6 sockets, multicastInterface should include a scope to indicate the +interface as in the examples that follow. In IPv6, individual send calls can +also use explicit scope in addresses, so only packets sent to a multicast +address without specifying an explicit scope are affected by the most recent +successful use of this call.

      +

      This method throws EBADF if called on an unbound socket.

      +

      Example: IPv6 outgoing multicast interface#

      +

      On most systems, where scope format uses the interface name:

      +
      const socket = dgram.createSocket('udp6');
      +
      +socket.bind(1234, () => {
      +  socket.setMulticastInterface('::%eth1');
      +});
      +

      On Windows, where scope format uses an interface number:

      +
      const socket = dgram.createSocket('udp6');
      +
      +socket.bind(1234, () => {
      +  socket.setMulticastInterface('::%2');
      +});
      +

      Example: IPv4 outgoing multicast interface#

      +

      All systems use an IP of the host on the desired physical interface:

      +
      const socket = dgram.createSocket('udp4');
      +
      +socket.bind(1234, () => {
      +  socket.setMulticastInterface('10.0.0.2');
      +});
      +

      Call results#

      +

      A call on a socket that is not ready to send or no longer open may throw a Not +running Error.

      +

      If multicastInterface can not be parsed into an IP then an EINVAL +System Error is thrown.

      +

      On IPv4, if multicastInterface is a valid address but does not match any +interface, or if the address does not match the family then +a System Error such as EADDRNOTAVAIL or EPROTONOSUP is thrown.

      +

      On IPv6, most errors with specifying or omitting scope will result in the socket +continuing to use (or returning to) the system's default interface selection.

      +

      A socket's address family's ANY address (IPv4 '0.0.0.0' or IPv6 '::') can be +used to return control of the sockets default outgoing interface to the system +for future multicast packets.

      +

      socket.setMulticastLoopback(flag)#

      + + +

      Sets or clears the IP_MULTICAST_LOOP socket option. When set to true, +multicast packets will also be received on the local interface.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.setMulticastTTL(ttl)#

      + + +

      Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for +"Time to Live", in this context it specifies the number of IP hops that a +packet is allowed to travel through, specifically for multicast traffic. Each +router or gateway that forwards a packet decrements the TTL. If the TTL is +decremented to 0 by a router, it will not be forwarded.

      +

      The ttl argument may be between 0 and 255. The default on most systems is 1.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.setRecvBufferSize(size)#

      + + +

      Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer +in bytes.

      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.setSendBufferSize(size)#

      + + +

      Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer +in bytes.

      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.setTTL(ttl)#

      + + +

      Sets the IP_TTL socket option. While TTL generally stands for "Time to Live", +in this context it specifies the number of IP hops that a packet is allowed to +travel through. Each router or gateway that forwards a packet decrements the +TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. +Changing TTL values is typically done for network probes or when multicasting.

      +

      The ttl argument may be between between 1 and 255. The default on most systems +is 64.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.unref()#

      + + +

      By default, binding a socket will cause it to block the Node.js process from +exiting as long as the socket is open. The socket.unref() method can be used +to exclude the socket from the reference counting that keeps the Node.js +process active, allowing the process to exit even if the socket is still +listening.

      +

      Calling socket.unref() multiple times will have no addition effect.

      +

      The socket.unref() method returns a reference to the socket so calls can be +chained.

      +

      dgram module functions#

      +

      dgram.createSocket(options[, callback])#

      + +
        +
      • options <Object> Available options are: +
          +
        • type <string> The family of socket. Must be either 'udp4' or 'udp6'. +Required.
        • +
        • reuseAddr <boolean> When true socket.bind() will reuse the +address, even if another process has already bound a socket on it. +Default: false.
        • +
        • ipv6Only <boolean> Setting ipv6Only to true will +disable dual-stack support, i.e., binding to address :: won't make +0.0.0.0 be bound. Default: false.
        • +
        • recvBufferSize <number> Sets the SO_RCVBUF socket value.
        • +
        • sendBufferSize <number> Sets the SO_SNDBUF socket value.
        • +
        • lookup <Function> Custom lookup function. Default: dns.lookup().
        • +
        +
      • +
      • callback <Function> Attached as a listener for 'message' events. Optional.
      • +
      • Returns: <dgram.Socket>
      • +
      +

      Creates a dgram.Socket object. Once the socket is created, calling +socket.bind() will instruct the socket to begin listening for datagram +messages. When address and port are not passed to socket.bind() the +method will bind the socket to the "all interfaces" address on a random port +(it does the right thing for both udp4 and udp6 sockets). The bound address +and port can be retrieved using socket.address().address and +socket.address().port.

      +

      dgram.createSocket(type[, callback])#

      + + +

      Creates a dgram.Socket object of the specified type.

      +

      Once the socket is created, calling socket.bind() will instruct the +socket to begin listening for datagram messages. When address and port are +not passed to socket.bind() the method will bind the socket to the "all +interfaces" address on a random port (it does the right thing for both udp4 +and udp6 sockets). The bound address and port can be retrieved using +socket.address().address and socket.address().port.

      +

      URL#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/url.js

      +

      The url module provides utilities for URL resolution and parsing. It can be +accessed using:

      +
      const url = require('url');
      +

      URL strings and URL objects#

      +

      A URL string is a structured string containing multiple meaningful components. +When parsed, a URL object is returned containing properties for each of these +components.

      +

      The url module provides two APIs for working with URLs: a legacy API that is +Node.js specific, and a newer API that implements the same +WHATWG URL Standard used by web browsers.

      +

      A comparison between the WHATWG and Legacy APIs is provided below. Above the URL +'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', properties +of an object returned by the legacy url.parse() are shown. Below it are +properties of a WHATWG URL object.

      +

      WHATWG URL's origin property includes protocol and host, but not +username or password.

      +
      ┌────────────────────────────────────────────────────────────────────────────────────────────────â”
      +│                                              href                                              │
      +├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
      +│ protocol │  │        auth         │          host          │           path            │ hash  │
      +│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
      +│          │  │                     │    hostname     │ port │ pathname │     search     │       │
      +│          │  │                     │                 │      │          ├─┬──────────────┤       │
      +│          │  │                     │                 │      │          │ │    query     │       │
      +"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
      +│          │  │          │          │    hostname     │ port │          │                │       │
      +│          │  │          │          ├─────────────────┴──────┤          │                │       │
      +│ protocol │  │ username │ password │          host          │          │                │       │
      +├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
      +│   origin    │                     │         origin         │ pathname │     search     │ hash  │
      +├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
      +│                                              href                                              │
      +└────────────────────────────────────────────────────────────────────────────────────────────────┘
      +(All spaces in the "" line should be ignored. They are purely for formatting.)
      +

      Parsing the URL string using the WHATWG API:

      +
      const myURL =
      +  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
      +

      Parsing the URL string using the Legacy API:

      +
      const url = require('url');
      +const myURL =
      +  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
      +

      The WHATWG URL API#

      +

      Class: URL#

      + +

      Browser-compatible URL class, implemented by following the WHATWG URL +Standard. Examples of parsed URLs may be found in the Standard itself. +The URL class is also available on the global object.

      +

      In accordance with browser conventions, all properties of URL objects +are implemented as getters and setters on the class prototype, rather than as +data properties on the object itself. Thus, unlike legacy urlObjects, +using the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still +return true.

      +

      new URL(input[, base])#

      +
        +
      • input <string> The absolute or relative input URL to parse. If input +is relative, then base is required. If input is absolute, the base +is ignored.
      • +
      • base <string> | <URL> The base URL to resolve against if the input is not +absolute.
      • +
      +

      Creates a new URL object by parsing the input relative to the base. If +base is passed as a string, it will be parsed equivalent to new URL(base).

      +
      const myURL = new URL('/foo', 'https://example.org/');
      +// https://example.org/foo
      +

      The URL constructor is accessible as a property on the global object. +It can also be imported from the built-in url module:

      +
      console.log(URL === require('url').URL); // Prints 'true'.
      +

      A TypeError will be thrown if the input or base are not valid URLs. Note +that an effort will be made to coerce the given values into strings. For +instance:

      +
      const myURL = new URL({ toString: () => 'https://example.org/' });
      +// https://example.org/
      +

      Unicode characters appearing within the host name of input will be +automatically converted to ASCII using the Punycode algorithm.

      +
      const myURL = new URL('https://測試');
      +// https://xn--g6w251d/
      +

      This feature is only available if the node executable was compiled with +ICU enabled. If not, the domain names are passed through unchanged.

      +

      In cases where it is not known in advance if input is an absolute URL +and a base is provided, it is advised to validate that the origin of +the URL object is what is expected.

      +
      let myURL = new URL('http://Example.com/', 'https://example.org/');
      +// http://example.com/
      +
      +myURL = new URL('https://Example.com/', 'https://example.org/');
      +// https://example.com/
      +
      +myURL = new URL('foo://Example.com/', 'https://example.org/');
      +// foo://Example.com/
      +
      +myURL = new URL('http:Example.com/', 'https://example.org/');
      +// http://example.com/
      +
      +myURL = new URL('https:Example.com/', 'https://example.org/');
      +// https://example.org/Example.com/
      +
      +myURL = new URL('foo:Example.com/', 'https://example.org/');
      +// foo:Example.com/
      +

      url.hash#

      + +

      Gets and sets the fragment portion of the URL.

      +
      const myURL = new URL('https://example.org/foo#bar');
      +console.log(myURL.hash);
      +// Prints #bar
      +
      +myURL.hash = 'baz';
      +console.log(myURL.href);
      +// Prints https://example.org/foo#baz
      +

      Invalid URL characters included in the value assigned to the hash property +are percent-encoded. The selection of which characters to +percent-encode may vary somewhat from what the url.parse() and +url.format() methods would produce.

      +

      url.host#

      + +

      Gets and sets the host portion of the URL.

      +
      const myURL = new URL('https://example.org:81/foo');
      +console.log(myURL.host);
      +// Prints example.org:81
      +
      +myURL.host = 'example.com:82';
      +console.log(myURL.href);
      +// Prints https://example.com:82/foo
      +

      Invalid host values assigned to the host property are ignored.

      +

      url.hostname#

      + +

      Gets and sets the host name portion of the URL. The key difference between +url.host and url.hostname is that url.hostname does not include the +port.

      +
      const myURL = new URL('https://example.org:81/foo');
      +console.log(myURL.hostname);
      +// Prints example.org
      +
      +myURL.hostname = 'example.com:82';
      +console.log(myURL.href);
      +// Prints https://example.com:81/foo
      +

      Invalid host name values assigned to the hostname property are ignored.

      +

      url.href#

      + +

      Gets and sets the serialized URL.

      +
      const myURL = new URL('https://example.org/foo');
      +console.log(myURL.href);
      +// Prints https://example.org/foo
      +
      +myURL.href = 'https://example.com/bar';
      +console.log(myURL.href);
      +// Prints https://example.com/bar
      +

      Getting the value of the href property is equivalent to calling +url.toString().

      +

      Setting the value of this property to a new value is equivalent to creating a +new URL object using new URL(value). Each of the URL +object's properties will be modified.

      +

      If the value assigned to the href property is not a valid URL, a TypeError +will be thrown.

      +

      url.origin#

      + +

      Gets the read-only serialization of the URL's origin.

      +
      const myURL = new URL('https://example.org/foo/bar?baz');
      +console.log(myURL.origin);
      +// Prints https://example.org
      +
      const idnURL = new URL('https://測試');
      +console.log(idnURL.origin);
      +// Prints https://xn--g6w251d
      +
      +console.log(idnURL.hostname);
      +// Prints xn--g6w251d
      +

      url.password#

      + +

      Gets and sets the password portion of the URL.

      +
      const myURL = new URL('https://abc:xyz@example.com');
      +console.log(myURL.password);
      +// Prints xyz
      +
      +myURL.password = '123';
      +console.log(myURL.href);
      +// Prints https://abc:123@example.com
      +

      Invalid URL characters included in the value assigned to the password property +are percent-encoded. The selection of which characters to +percent-encode may vary somewhat from what the url.parse() and +url.format() methods would produce.

      +

      url.pathname#

      + +

      Gets and sets the path portion of the URL.

      +
      const myURL = new URL('https://example.org/abc/xyz?123');
      +console.log(myURL.pathname);
      +// Prints /abc/xyz
      +
      +myURL.pathname = '/abcdef';
      +console.log(myURL.href);
      +// Prints https://example.org/abcdef?123
      +

      Invalid URL characters included in the value assigned to the pathname +property are percent-encoded. The selection of which characters +to percent-encode may vary somewhat from what the url.parse() and +url.format() methods would produce.

      +

      url.port#

      + +

      Gets and sets the port portion of the URL.

      +

      The port value may be a number or a string containing a number in the range +0 to 65535 (inclusive). Setting the value to the default port of the +URL objects given protocol will result in the port value becoming +the empty string ('').

      +

      The port value can be an empty string in which case the port depends on +the protocol/scheme:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      protocolport
      "ftp"21
      "file"
      "gopher"70
      "http"80
      "https"443
      "ws"80
      "wss"443
      +

      Upon assigning a value to the port, the value will first be converted to a +string using .toString().

      +

      If that string is invalid but it begins with a number, the leading number is +assigned to port. +If the number lies outside the range denoted above, it is ignored.

      +
      const myURL = new URL('https://example.org:8888');
      +console.log(myURL.port);
      +// Prints 8888
      +
      +// Default ports are automatically transformed to the empty string
      +// (HTTPS protocol's default port is 443)
      +myURL.port = '443';
      +console.log(myURL.port);
      +// Prints the empty string
      +console.log(myURL.href);
      +// Prints https://example.org/
      +
      +myURL.port = 1234;
      +console.log(myURL.port);
      +// Prints 1234
      +console.log(myURL.href);
      +// Prints https://example.org:1234/
      +
      +// Completely invalid port strings are ignored
      +myURL.port = 'abcd';
      +console.log(myURL.port);
      +// Prints 1234
      +
      +// Leading numbers are treated as a port number
      +myURL.port = '5678abcd';
      +console.log(myURL.port);
      +// Prints 5678
      +
      +// Non-integers are truncated
      +myURL.port = 1234.5678;
      +console.log(myURL.port);
      +// Prints 1234
      +
      +// Out-of-range numbers which are not represented in scientific notation
      +// will be ignored.
      +myURL.port = 1e10; // 10000000000, will be range-checked as described below
      +console.log(myURL.port);
      +// Prints 1234
      +

      Numbers which contain a decimal point, +such as floating-point numbers or numbers in scientific notation, +are not an exception to this rule. +Leading numbers up to the decimal point will be set as the URL's port, +assuming they are valid:

      +
      myURL.port = 4.567e21;
      +console.log(myURL.port);
      +// Prints 4 (because it is the leading number in the string '4.567e21')
      +

      url.protocol#

      + +

      Gets and sets the protocol portion of the URL.

      +
      const myURL = new URL('https://example.org');
      +console.log(myURL.protocol);
      +// Prints https:
      +
      +myURL.protocol = 'ftp';
      +console.log(myURL.href);
      +// Prints ftp://example.org/
      +

      Invalid URL protocol values assigned to the protocol property are ignored.

      +
      Special schemes#
      +

      The WHATWG URL Standard considers a handful of URL protocol schemes to be +special in terms of how they are parsed and serialized. When a URL is +parsed using one of these special protocols, the url.protocol property +may be changed to another special protocol but cannot be changed to a +non-special protocol, and vice versa.

      +

      For instance, changing from http to https works:

      +
      const u = new URL('http://example.org');
      +u.protocol = 'https';
      +console.log(u.href);
      +// https://example.org
      +

      However, changing from http to a hypothetical fish protocol does not +because the new protocol is not special.

      +
      const u = new URL('http://example.org');
      +u.protocol = 'fish';
      +console.log(u.href);
      +// http://example.org
      +

      Likewise, changing from a non-special protocol to a special protocol is also +not permitted:

      +
      const u = new URL('fish://example.org');
      +u.protocol = 'http';
      +console.log(u.href);
      +// fish://example.org
      +

      According to the WHATWG URL Standard, special protocol schemes are ftp, +file, gopher, http, https, ws, and wss.

      +

      url.search#

      + +

      Gets and sets the serialized query portion of the URL.

      +
      const myURL = new URL('https://example.org/abc?123');
      +console.log(myURL.search);
      +// Prints ?123
      +
      +myURL.search = 'abc=xyz';
      +console.log(myURL.href);
      +// Prints https://example.org/abc?abc=xyz
      +

      Any invalid URL characters appearing in the value assigned the search +property will be percent-encoded. The selection of which +characters to percent-encode may vary somewhat from what the url.parse() +and url.format() methods would produce.

      +

      url.searchParams#

      + +

      Gets the URLSearchParams object representing the query parameters of the +URL. This property is read-only but the URLSearchParams object it provides +can be used to mutate the URL instance; to replace the entirety of query +parameters of the URL, use the url.search setter. See +URLSearchParams documentation for details.

      +

      Use care when using .searchParams to modify the URL because, +per the WHATWG specification, the URLSearchParams object uses +different rules to determine which characters to percent-encode. For +instance, the URL object will not percent encode the ASCII tilde (~) +character, while URLSearchParams will always encode it:

      +
      const myUrl = new URL('https://example.org/abc?foo=~bar');
      +
      +console.log(myUrl.search);  // prints ?foo=~bar
      +
      +// Modify the URL via searchParams...
      +myUrl.searchParams.sort();
      +
      +console.log(myUrl.search);  // prints ?foo=%7Ebar
      +

      url.username#

      + +

      Gets and sets the username portion of the URL.

      +
      const myURL = new URL('https://abc:xyz@example.com');
      +console.log(myURL.username);
      +// Prints abc
      +
      +myURL.username = '123';
      +console.log(myURL.href);
      +// Prints https://123:xyz@example.com/
      +

      Any invalid URL characters appearing in the value assigned the username +property will be percent-encoded. The selection of which +characters to percent-encode may vary somewhat from what the url.parse() +and url.format() methods would produce.

      +

      url.toString()#

      + +

      The toString() method on the URL object returns the serialized URL. The +value returned is equivalent to that of url.href and url.toJSON().

      +

      Because of the need for standard compliance, this method does not allow users +to customize the serialization process of the URL. For more flexibility, +require('url').format() method might be of interest.

      +

      url.toJSON()#

      + +

      The toJSON() method on the URL object returns the serialized URL. The +value returned is equivalent to that of url.href and +url.toString().

      +

      This method is automatically called when an URL object is serialized +with JSON.stringify().

      +
      const myURLs = [
      +  new URL('https://www.example.com'),
      +  new URL('https://test.example.org')
      +];
      +console.log(JSON.stringify(myURLs));
      +// Prints ["https://www.example.com/","https://test.example.org/"]
      +

      Class: URLSearchParams#

      + +

      The URLSearchParams API provides read and write access to the query of a +URL. The URLSearchParams class can also be used standalone with one of the +four following constructors. +The URLSearchParams class is also available on the global object.

      +

      The WHATWG URLSearchParams interface and the querystring module have +similar purpose, but the purpose of the querystring module is more +general, as it allows the customization of delimiter characters (& and =). +On the other hand, this API is designed purely for URL query strings.

      +
      const myURL = new URL('https://example.org/?abc=123');
      +console.log(myURL.searchParams.get('abc'));
      +// Prints 123
      +
      +myURL.searchParams.append('abc', 'xyz');
      +console.log(myURL.href);
      +// Prints https://example.org/?abc=123&abc=xyz
      +
      +myURL.searchParams.delete('abc');
      +myURL.searchParams.set('a', 'b');
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b
      +
      +const newSearchParams = new URLSearchParams(myURL.searchParams);
      +// The above is equivalent to
      +// const newSearchParams = new URLSearchParams(myURL.search);
      +
      +newSearchParams.append('a', 'c');
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b
      +console.log(newSearchParams.toString());
      +// Prints a=b&a=c
      +
      +// newSearchParams.toString() is implicitly called
      +myURL.search = newSearchParams;
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b&a=c
      +newSearchParams.delete('a');
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b&a=c
      +

      new URLSearchParams()#

      +

      Instantiate a new empty URLSearchParams object.

      +

      new URLSearchParams(string)#

      + +

      Parse the string as a query string, and use it to instantiate a new +URLSearchParams object. A leading '?', if present, is ignored.

      +
      let params;
      +
      +params = new URLSearchParams('user=abc&query=xyz');
      +console.log(params.get('user'));
      +// Prints 'abc'
      +console.log(params.toString());
      +// Prints 'user=abc&query=xyz'
      +
      +params = new URLSearchParams('?user=abc&query=xyz');
      +console.log(params.toString());
      +// Prints 'user=abc&query=xyz'
      +

      new URLSearchParams(obj)#

      + +
        +
      • obj <Object> An object representing a collection of key-value pairs
      • +
      +

      Instantiate a new URLSearchParams object with a query hash map. The key and +value of each property of obj are always coerced to strings.

      +

      Unlike querystring module, duplicate keys in the form of array values are +not allowed. Arrays are stringified using array.toString(), which simply +joins all array elements with commas.

      +
      const params = new URLSearchParams({
      +  user: 'abc',
      +  query: ['first', 'second']
      +});
      +console.log(params.getAll('query'));
      +// Prints [ 'first,second' ]
      +console.log(params.toString());
      +// Prints 'user=abc&query=first%2Csecond'
      +

      new URLSearchParams(iterable)#

      + +
        +
      • iterable <Iterable> An iterable object whose elements are key-value pairs
      • +
      +

      Instantiate a new URLSearchParams object with an iterable map in a way that +is similar to Map's constructor. iterable can be an Array or any +iterable object. That means iterable can be another URLSearchParams, in +which case the constructor will simply create a clone of the provided +URLSearchParams. Elements of iterable are key-value pairs, and can +themselves be any iterable object.

      +

      Duplicate keys are allowed.

      +
      let params;
      +
      +// Using an array
      +params = new URLSearchParams([
      +  ['user', 'abc'],
      +  ['query', 'first'],
      +  ['query', 'second']
      +]);
      +console.log(params.toString());
      +// Prints 'user=abc&query=first&query=second'
      +
      +// Using a Map object
      +const map = new Map();
      +map.set('user', 'abc');
      +map.set('query', 'xyz');
      +params = new URLSearchParams(map);
      +console.log(params.toString());
      +// Prints 'user=abc&query=xyz'
      +
      +// Using a generator function
      +function* getQueryPairs() {
      +  yield ['user', 'abc'];
      +  yield ['query', 'first'];
      +  yield ['query', 'second'];
      +}
      +params = new URLSearchParams(getQueryPairs());
      +console.log(params.toString());
      +// Prints 'user=abc&query=first&query=second'
      +
      +// Each key-value pair must have exactly two elements
      +new URLSearchParams([
      +  ['user', 'abc', 'error']
      +]);
      +// Throws TypeError [ERR_INVALID_TUPLE]:
      +//        Each query pair must be an iterable [name, value] tuple
      +

      urlSearchParams.append(name, value)#

      + +

      Append a new name-value pair to the query string.

      +

      urlSearchParams.delete(name)#

      + +

      Remove all name-value pairs whose name is name.

      +

      urlSearchParams.entries()#

      + +

      Returns an ES6 Iterator over each of the name-value pairs in the query. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the name, the second item of the Array is the value.

      +

      Alias for urlSearchParams[@@iterator]().

      +

      urlSearchParams.forEach(fn[, thisArg])#

      +
        +
      • fn <Function> Invoked for each name-value pair in the query
      • +
      • thisArg <Object> To be used as this value for when fn is called
      • +
      +

      Iterates over each name-value pair in the query and invokes the given function.

      +
      const myURL = new URL('https://example.org/?a=b&c=d');
      +myURL.searchParams.forEach((value, name, searchParams) => {
      +  console.log(name, value, myURL.searchParams === searchParams);
      +});
      +// Prints:
      +//   a b true
      +//   c d true
      +

      urlSearchParams.get(name)#

      +
        +
      • name <string>
      • +
      • Returns: <string> or null if there is no name-value pair with the given +name.
      • +
      +

      Returns the value of the first name-value pair whose name is name. If there +are no such pairs, null is returned.

      +

      urlSearchParams.getAll(name)#

      + +

      Returns the values of all name-value pairs whose name is name. If there are +no such pairs, an empty array is returned.

      +

      urlSearchParams.has(name)#

      + +

      Returns true if there is at least one name-value pair whose name is name.

      +

      urlSearchParams.keys()#

      + +

      Returns an ES6 Iterator over the names of each name-value pair.

      +
      const params = new URLSearchParams('foo=bar&foo=baz');
      +for (const name of params.keys()) {
      +  console.log(name);
      +}
      +// Prints:
      +//   foo
      +//   foo
      +

      urlSearchParams.set(name, value)#

      + +

      Sets the value in the URLSearchParams object associated with name to +value. If there are any pre-existing name-value pairs whose names are name, +set the first such pair's value to value and remove all others. If not, +append the name-value pair to the query string.

      +
      const params = new URLSearchParams();
      +params.append('foo', 'bar');
      +params.append('foo', 'baz');
      +params.append('abc', 'def');
      +console.log(params.toString());
      +// Prints foo=bar&foo=baz&abc=def
      +
      +params.set('foo', 'def');
      +params.set('xyz', 'opq');
      +console.log(params.toString());
      +// Prints foo=def&abc=def&xyz=opq
      +

      urlSearchParams.sort()#

      + +

      Sort all existing name-value pairs in-place by their names. Sorting is done +with a stable sorting algorithm, so relative order between name-value pairs +with the same name is preserved.

      +

      This method can be used, in particular, to increase cache hits.

      +
      const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
      +params.sort();
      +console.log(params.toString());
      +// Prints query%5B%5D=abc&query%5B%5D=123&type=search
      +

      urlSearchParams.toString()#

      + +

      Returns the search parameters serialized as a string, with characters +percent-encoded where necessary.

      +

      urlSearchParams.values()#

      + +

      Returns an ES6 Iterator over the values of each name-value pair.

      +

      urlSearchParams[Symbol.iterator]()#

      + +

      Returns an ES6 Iterator over each of the name-value pairs in the query string. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the name, the second item of the Array is the value.

      +

      Alias for urlSearchParams.entries().

      +
      const params = new URLSearchParams('foo=bar&xyz=baz');
      +for (const [name, value] of params) {
      +  console.log(name, value);
      +}
      +// Prints:
      +//   foo bar
      +//   xyz baz
      +

      url.domainToASCII(domain)#

      + + +

      Returns the Punycode ASCII serialization of the domain. If domain is an +invalid domain, the empty string is returned.

      +

      It performs the inverse operation to url.domainToUnicode().

      +
      const url = require('url');
      +console.log(url.domainToASCII('español.com'));
      +// Prints xn--espaol-zwa.com
      +console.log(url.domainToASCII('中文.com'));
      +// Prints xn--fiq228c.com
      +console.log(url.domainToASCII('xn--iñvalid.com'));
      +// Prints an empty string
      +

      url.domainToUnicode(domain)#

      + + +

      Returns the Unicode serialization of the domain. If domain is an invalid +domain, the empty string is returned.

      +

      It performs the inverse operation to url.domainToASCII().

      +
      const url = require('url');
      +console.log(url.domainToUnicode('xn--espaol-zwa.com'));
      +// Prints español.com
      +console.log(url.domainToUnicode('xn--fiq228c.com'));
      +// Prints 中文.com
      +console.log(url.domainToUnicode('xn--iñvalid.com'));
      +// Prints an empty string
      +

      url.fileURLToPath(url)#

      + +
        +
      • url <URL> | <string> The file URL string or URL object to convert to a path.
      • +
      • Returns: <string> The fully-resolved platform-specific Node.js file path.
      • +
      +

      This function ensures the correct decodings of percent-encoded characters as +well as ensuring a cross-platform valid absolute path string.

      +
      new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/
      +fileURLToPath('file:///C:/path/');       // Correct:   C:\path\ (Windows)
      +
      +new URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt
      +fileURLToPath('file://nas/foo.txt');     // Correct:   \\nas\foo.txt (Windows)
      +
      +new URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
      +fileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)
      +
      +new URL('file:///hello world').pathname; // Incorrect: /hello%20world
      +fileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)
      +

      url.format(URL[, options])#

      + +
        +
      • URL <URL> A WHATWG URL object
      • +
      • options <Object> +
          +
        • auth <boolean> true if the serialized URL string should include the +username and password, false otherwise. Default: true.
        • +
        • fragment <boolean> true if the serialized URL string should include the +fragment, false otherwise. Default: true.
        • +
        • search <boolean> true if the serialized URL string should include the +search query, false otherwise. Default: true.
        • +
        • unicode <boolean> true if Unicode characters appearing in the host +component of the URL string should be encoded directly as opposed to being +Punycode encoded. Default: false.
        • +
        +
      • +
      • Returns: <string>
      • +
      +

      Returns a customizable serialization of a URL String representation of a +WHATWG URL object.

      +

      The URL object has both a toString() method and href property that return +string serializations of the URL. These are not, however, customizable in +any way. The url.format(URL[, options]) method allows for basic customization +of the output.

      +
      const myURL = new URL('https://a:b@測試?abc#foo');
      +
      +console.log(myURL.href);
      +// Prints https://a:b@xn--g6w251d/?abc#foo
      +
      +console.log(myURL.toString());
      +// Prints https://a:b@xn--g6w251d/?abc#foo
      +
      +console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
      +// Prints 'https://測試/?abc'
      +

      url.pathToFileURL(path)#

      + +
        +
      • path <string> The path to convert to a File URL.
      • +
      • Returns: <URL> The file URL object.
      • +
      +

      This function ensures that path is resolved absolutely, and that the URL +control characters are correctly encoded when converting into a File URL.

      +
      new URL(__filename);                // Incorrect: throws (POSIX)
      +new URL(__filename);                // Incorrect: C:\... (Windows)
      +pathToFileURL(__filename);          // Correct:   file:///... (POSIX)
      +pathToFileURL(__filename);          // Correct:   file:///C:/... (Windows)
      +
      +new URL('/foo#1', 'file:');         // Incorrect: file:///foo#1
      +pathToFileURL('/foo#1');            // Correct:   file:///foo%231 (POSIX)
      +
      +new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
      +pathToFileURL('/some/path%.c');    // Correct:   file:///some/path%25.c (POSIX)
      +

      Legacy URL API#

      + +

      Legacy urlObject#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +

      The legacy urlObject (require('url').Url) is created and returned by the +url.parse() function.

      +

      urlObject.auth#

      +

      The auth property is the username and password portion of the URL, also +referred to as userinfo. This string subset follows the protocol and +double slashes (if present) and precedes the host component, delimited by @. +The string is either the username, or it is the username and password separated +by :.

      +

      For example: 'user:pass'.

      +

      urlObject.hash#

      +

      The hash property is the fragment identifier portion of the URL including the +leading # character.

      +

      For example: '#hash'.

      +

      urlObject.host#

      +

      The host property is the full lower-cased host portion of the URL, including +the port if specified.

      +

      For example: 'sub.example.com:8080'.

      +

      urlObject.hostname#

      +

      The hostname property is the lower-cased host name portion of the host +component without the port included.

      +

      For example: 'sub.example.com'.

      +

      urlObject.href#

      +

      The href property is the full URL string that was parsed with both the +protocol and host components converted to lower-case.

      +

      For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.

      +

      urlObject.path#

      +

      The path property is a concatenation of the pathname and search +components.

      +

      For example: '/p/a/t/h?query=string'.

      +

      No decoding of the path is performed.

      +

      urlObject.pathname#

      +

      The pathname property consists of the entire path section of the URL. This +is everything following the host (including the port) and before the start +of the query or hash components, delimited by either the ASCII question +mark (?) or hash (#) characters.

      +

      For example: '/p/a/t/h'.

      +

      No decoding of the path string is performed.

      +

      urlObject.port#

      +

      The port property is the numeric port portion of the host component.

      +

      For example: '8080'.

      +

      urlObject.protocol#

      +

      The protocol property identifies the URL's lower-cased protocol scheme.

      +

      For example: 'http:'.

      +

      urlObject.query#

      +

      The query property is either the query string without the leading ASCII +question mark (?), or an object returned by the querystring module's +parse() method. Whether the query property is a string or object is +determined by the parseQueryString argument passed to url.parse().

      +

      For example: 'query=string' or {'query': 'string'}.

      +

      If returned as a string, no decoding of the query string is performed. If +returned as an object, both keys and values are decoded.

      +

      urlObject.search#

      +

      The search property consists of the entire "query string" portion of the +URL, including the leading ASCII question mark (?) character.

      +

      For example: '?query=string'.

      +

      No decoding of the query string is performed.

      +

      urlObject.slashes#

      +

      The slashes property is a boolean with a value of true if two ASCII +forward-slash characters (/) are required following the colon in the +protocol.

      +

      url.format(urlObject)#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +
        +
      • urlObject <Object> | <string> A URL object (as returned by url.parse() or +constructed otherwise). If a string, it is converted to an object by passing +it to url.parse().
      • +
      +

      The url.format() method returns a formatted URL string derived from +urlObject.

      +
      url.format({
      +  protocol: 'https',
      +  hostname: 'example.com',
      +  pathname: '/some/path',
      +  query: {
      +    page: 1,
      +    format: 'json'
      +  }
      +});
      +
      +// => 'https://example.com/some/path?page=1&format=json'
      +

      If urlObject is not an object or a string, url.format() will throw a +TypeError.

      +

      The formatting process operates as follows:

      +
        +
      • A new empty string result is created.
      • +
      • If urlObject.protocol is a string, it is appended as-is to result.
      • +
      • Otherwise, if urlObject.protocol is not undefined and is not a string, an +Error is thrown.
      • +
      • For all string values of urlObject.protocol that do not end with an ASCII +colon (:) character, the literal string : will be appended to result.
      • +
      • If either of the following conditions is true, then the literal string // +will be appended to result: +
          +
        • urlObject.slashes property is true;
        • +
        • urlObject.protocol begins with http, https, ftp, gopher, or +file;
        • +
        +
      • +
      • If the value of the urlObject.auth property is truthy, and either +urlObject.host or urlObject.hostname are not undefined, the value of +urlObject.auth will be coerced into a string and appended to result +followed by the literal string @.
      • +
      • If the urlObject.host property is undefined then: +
          +
        • If the urlObject.hostname is a string, it is appended to result.
        • +
        • Otherwise, if urlObject.hostname is not undefined and is not a string, +an Error is thrown.
        • +
        • If the urlObject.port property value is truthy, and urlObject.hostname +is not undefined: +
            +
          • The literal string : is appended to result, and
          • +
          • The value of urlObject.port is coerced to a string and appended to +result.
          • +
          +
        • +
        +
      • +
      • Otherwise, if the urlObject.host property value is truthy, the value of +urlObject.host is coerced to a string and appended to result.
      • +
      • If the urlObject.pathname property is a string that is not an empty string: +
          +
        • If the urlObject.pathname does not start with an ASCII forward slash +(/), then the literal string '/' is appended to result.
        • +
        • The value of urlObject.pathname is appended to result.
        • +
        +
      • +
      • Otherwise, if urlObject.pathname is not undefined and is not a string, an +Error is thrown.
      • +
      • If the urlObject.search property is undefined and if the urlObject.query +property is an Object, the literal string ? is appended to result +followed by the output of calling the querystring module's stringify() +method passing the value of urlObject.query.
      • +
      • Otherwise, if urlObject.search is a string: +
          +
        • If the value of urlObject.search does not start with the ASCII question +mark (?) character, the literal string ? is appended to result.
        • +
        • The value of urlObject.search is appended to result.
        • +
        +
      • +
      • Otherwise, if urlObject.search is not undefined and is not a string, an +Error is thrown.
      • +
      • If the urlObject.hash property is a string: +
          +
        • If the value of urlObject.hash does not start with the ASCII hash (#) +character, the literal string # is appended to result.
        • +
        • The value of urlObject.hash is appended to result.
        • +
        +
      • +
      • Otherwise, if the urlObject.hash property is not undefined and is not a +string, an Error is thrown.
      • +
      • result is returned.
      • +
      +

      url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +
        +
      • urlString <string> The URL string to parse.
      • +
      • parseQueryString <boolean> If true, the query property will always +be set to an object returned by the querystring module's parse() +method. If false, the query property on the returned URL object will be an +unparsed, undecoded string. Default: false.
      • +
      • slashesDenoteHost <boolean> If true, the first token after the literal +string // and preceding the next / will be interpreted as the host. +For instance, given //foo/bar, the result would be +{host: 'foo', pathname: '/bar'} rather than {pathname: '//foo/bar'}. +Default: false.
      • +
      +

      The url.parse() method takes a URL string, parses it, and returns a URL +object.

      +

      A TypeError is thrown if urlString is not a string.

      +

      A URIError is thrown if the auth property is present but cannot be decoded.

      +

      Use of the legacy url.parse() method is discouraged. Users should +use the WHATWG URL API. Because the url.parse() method uses a +lenient, non-standard algorithm for parsing URL strings, security +issues can be introduced. Specifically, issues with host name spoofing and +incorrect handling of usernames and passwords have been identified.

      +

      url.resolve(from, to)#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +
        +
      • from <string> The Base URL being resolved against.
      • +
      • to <string> The HREF URL being resolved.
      • +
      +

      The url.resolve() method resolves a target URL relative to a base URL in a +manner similar to that of a Web browser resolving an anchor tag HREF.

      +
      const url = require('url');
      +url.resolve('/one/two/three', 'four');         // '/one/two/four'
      +url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
      +url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
      +

      +

      Percent-encoding in URLs#

      +

      URLs are permitted to only contain a certain range of characters. Any character +falling outside of that range must be encoded. How such characters are encoded, +and which characters to encode depends entirely on where the character is +located within the structure of the URL.

      +

      Legacy API#

      +

      Within the Legacy API, spaces (' ') and the following characters will be +automatically escaped in the properties of URL objects:

      +
      < > " ` \r \n \t { } | \ ^ '
      +

      For example, the ASCII space character (' ') is encoded as %20. The ASCII +forward slash (/) character is encoded as %3C.

      +

      WHATWG API#

      +

      The WHATWG URL Standard uses a more selective and fine grained approach to +selecting encoded characters than that used by the Legacy API.

      +

      The WHATWG algorithm defines four "percent-encode sets" that describe ranges +of characters that must be percent-encoded:

      +
        +
      • +

        The C0 control percent-encode set includes code points in range U+0000 to +U+001F (inclusive) and all code points greater than U+007E.

        +
      • +
      • +

        The fragment percent-encode set includes the C0 control percent-encode set +and code points U+0020, U+0022, U+003C, U+003E, and U+0060.

        +
      • +
      • +

        The path percent-encode set includes the C0 control percent-encode set +and code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060, +U+007B, and U+007D.

        +
      • +
      • +

        The userinfo encode set includes the path percent-encode set and code +points U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D, +U+005E, and U+007C.

        +
      • +
      +

      The userinfo percent-encode set is used exclusively for username and +passwords encoded within the URL. The path percent-encode set is used for the +path of most URLs. The fragment percent-encode set is used for URL fragments. +The C0 control percent-encode set is used for host and path under certain +specific conditions, in addition to all other cases.

      +

      When non-ASCII characters appear within a host name, the host name is encoded +using the Punycode algorithm. Note, however, that a host name may contain +both Punycode encoded and percent-encoded characters:

      +
      const myURL = new URL('https://%CF%80.example.com/foo');
      +console.log(myURL.href);
      +// Prints https://xn--1xa.example.com/foo
      +console.log(myURL.origin);
      +// Prints https://xn--1xa.example.com
      +

      Util#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/util.js

      +

      The util module supports the needs of Node.js internal APIs. Many of the +utilities are useful for application and module developers as well. To access +it:

      +
      const util = require('util');
      +

      util.callbackify(original)#

      + + +

      Takes an async function (or a function that returns a Promise) and returns a +function following the error-first callback style, i.e. taking +an (err, value) => ... callback as the last argument. In the callback, the +first argument will be the rejection reason (or null if the Promise +resolved), and the second argument will be the resolved value.

      +
      const util = require('util');
      +
      +async function fn() {
      +  return 'hello world';
      +}
      +const callbackFunction = util.callbackify(fn);
      +
      +callbackFunction((err, ret) => {
      +  if (err) throw err;
      +  console.log(ret);
      +});
      +

      Will print:

      +
      hello world
      +

      The callback is executed asynchronously, and will have a limited stack trace. +If the callback throws, the process will emit an 'uncaughtException' +event, and if not handled will exit.

      +

      Since null has a special meaning as the first argument to a callback, if a +wrapped function rejects a Promise with a falsy value as a reason, the value +is wrapped in an Error with the original value stored in a field named +reason.

      +
      function fn() {
      +  return Promise.reject(null);
      +}
      +const callbackFunction = util.callbackify(fn);
      +
      +callbackFunction((err, ret) => {
      +  // When the Promise was rejected with `null` it is wrapped with an Error and
      +  // the original value is stored in `reason`.
      +  err && err.hasOwnProperty('reason') && err.reason === null;  // true
      +});
      +

      util.debuglog(section[, callback])#

      + +
        +
      • section <string> A string identifying the portion of the application for +which the debuglog function is being created.
      • +
      • callback <Function> A callback invoked the first time the logging function +is called with a function argument that is a more optimized logging function.
      • +
      • Returns: <Function> The logging function
      • +
      +

      The util.debuglog() method is used to create a function that conditionally +writes debug messages to stderr based on the existence of the NODE_DEBUG +environment variable. If the section name appears within the value of that +environment variable, then the returned function operates similar to +console.error(). If not, then the returned function is a no-op.

      +
      const util = require('util');
      +const debuglog = util.debuglog('foo');
      +
      +debuglog('hello from foo [%d]', 123);
      +

      If this program is run with NODE_DEBUG=foo in the environment, then +it will output something like:

      +
      FOO 3245: hello from foo [123]
      +

      where 3245 is the process id. If it is not run with that +environment variable set, then it will not print anything.

      +

      The section supports wildcard also:

      +
      const util = require('util');
      +const debuglog = util.debuglog('foo-bar');
      +
      +debuglog('hi there, it\'s foo-bar [%d]', 2333);
      +

      if it is run with NODE_DEBUG=foo* in the environment, then it will output +something like:

      +
      FOO-BAR 3257: hi there, it's foo-bar [2333]
      +

      Multiple comma-separated section names may be specified in the NODE_DEBUG +environment variable: NODE_DEBUG=fs,net,tls.

      +

      The optional callback argument can be used to replace the logging function +with a different function that doesn't have any initialization or +unnecessary wrapping.

      +
      const util = require('util');
      +let debuglog = util.debuglog('internals', (debug) => {
      +  // Replace with a logging function that optimizes out
      +  // testing if the section is enabled
      +  debuglog = debug;
      +});
      +

      util.deprecate(fn, msg[, code])#

      + +
        +
      • fn <Function> The function that is being deprecated.
      • +
      • msg <string> A warning message to display when the deprecated function is +invoked.
      • +
      • code <string> A deprecation code. See the list of deprecated APIs for a +list of codes.
      • +
      • Returns: <Function> The deprecated function wrapped to emit a warning.
      • +
      +

      The util.deprecate() method wraps fn (which may be a function or class) in +such a way that it is marked as deprecated.

      +
      const util = require('util');
      +
      +exports.obsoleteFunction = util.deprecate(() => {
      +  // Do something here.
      +}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
      +

      When called, util.deprecate() will return a function that will emit a +DeprecationWarning using the 'warning' event. The warning will +be emitted and printed to stderr the first time the returned function is +called. After the warning is emitted, the wrapped function is called without +emitting a warning.

      +

      If the same optional code is supplied in multiple calls to util.deprecate(), +the warning will be emitted only once for that code.

      +
      const util = require('util');
      +
      +const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
      +const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
      +fn1(); // Emits a deprecation warning with code DEP0001
      +fn2(); // Does not emit a deprecation warning because it has the same code
      +

      If either the --no-deprecation or --no-warnings command line flags are +used, or if the process.noDeprecation property is set to true prior to +the first deprecation warning, the util.deprecate() method does nothing.

      +

      If the --trace-deprecation or --trace-warnings command line flags are set, +or the process.traceDeprecation property is set to true, a warning and a +stack trace are printed to stderr the first time the deprecated function is +called.

      +

      If the --throw-deprecation command line flag is set, or the +process.throwDeprecation property is set to true, then an exception will be +thrown when the deprecated function is called.

      +

      The --throw-deprecation command line flag and process.throwDeprecation +property take precedence over --trace-deprecation and +process.traceDeprecation.

      +

      util.format(format[, ...args])#

      + +
        +
      • format <string> A printf-like format string.
      • +
      +

      The util.format() method returns a formatted string using the first argument +as a printf-like format string which can contain zero or more format +specifiers. Each specifier is replaced with the converted value from the +corresponding argument. Supported specifiers are:

      +
        +
      • %s: String will be used to convert all values except BigInt, Object +and -0. BigInt values will be represented with an n and Objects that +have no user defined toString function are inspected using util.inspect() +with options { depth: 0, colors: false, compact: 3 }.
      • +
      • %d: Number will be used to convert all values except BigInt and +Symbol.
      • +
      • %i: parseInt(value, 10) is used for all values except BigInt and +Symbol.
      • +
      • %f: parseFloat(value) is used for all values expect Symbol.
      • +
      • %j: JSON. Replaced with the string '[Circular]' if the argument contains +circular references.
      • +
      • %o: Object. A string representation of an object with generic JavaScript +object formatting. Similar to util.inspect() with options +{ showHidden: true, showProxy: true }. This will show the full object +including non-enumerable properties and proxies.
      • +
      • %O: Object. A string representation of an object with generic JavaScript +object formatting. Similar to util.inspect() without options. This will show +the full object not including non-enumerable properties and proxies.
      • +
      • %c: CSS. This specifier is ignored and will skip any CSS passed in.
      • +
      • %%: single percent sign ('%'). This does not consume an argument.
      • +
      • Returns: <string> The formatted string
      • +
      +

      If a specifier does not have a corresponding argument, it is not replaced:

      +
      util.format('%s:%s', 'foo');
      +// Returns: 'foo:%s'
      +

      Values that are not part of the format string are formatted using +util.inspect() if their type is not string.

      +

      If there are more arguments passed to the util.format() method than the +number of specifiers, the extra arguments are concatenated to the returned +string, separated by spaces:

      +
      util.format('%s:%s', 'foo', 'bar', 'baz');
      +// Returns: 'foo:bar baz'
      +

      If the first argument does not contain a valid format specifier, util.format() +returns a string that is the concatenation of all arguments separated by spaces:

      +
      util.format(1, 2, 3);
      +// Returns: '1 2 3'
      +

      If only one argument is passed to util.format(), it is returned as it is +without any formatting:

      +
      util.format('%% %s');
      +// Returns: '%% %s'
      +

      util.format() is a synchronous method that is intended as a debugging tool. +Some input values can have a significant performance overhead that can block the +event loop. Use this function with care and never in a hot code path.

      +

      util.formatWithOptions(inspectOptions, format[, ...args])#

      + + +

      This function is identical to util.format(), except in that it takes +an inspectOptions argument which specifies options that are passed along to +util.inspect().

      +
      util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
      +// Returns 'See object { foo: 42 }', where `42` is colored as a number
      +// when printed to a terminal.
      +

      util.getSystemErrorName(err)#

      + + +

      Returns the string name for a numeric error code that comes from a Node.js API. +The mapping between error codes and error names is platform-dependent. +See Common System Errors for the names of common errors.

      +
      fs.access('file/that/does/not/exist', (err) => {
      +  const name = util.getSystemErrorName(err.errno);
      +  console.error(name);  // ENOENT
      +});
      +

      util.inherits(constructor, superConstructor)#

      + + +

      Usage of util.inherits() is discouraged. Please use the ES6 class and +extends keywords to get language level inheritance support. Also note +that the two styles are semantically incompatible.

      +

      Inherit the prototype methods from one constructor into another. The +prototype of constructor will be set to a new object created from +superConstructor.

      +

      This mainly adds some input validation on top of +Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). +As an additional convenience, superConstructor will be accessible +through the constructor.super_ property.

      +
      const util = require('util');
      +const EventEmitter = require('events');
      +
      +function MyStream() {
      +  EventEmitter.call(this);
      +}
      +
      +util.inherits(MyStream, EventEmitter);
      +
      +MyStream.prototype.write = function(data) {
      +  this.emit('data', data);
      +};
      +
      +const stream = new MyStream();
      +
      +console.log(stream instanceof EventEmitter); // true
      +console.log(MyStream.super_ === EventEmitter); // true
      +
      +stream.on('data', (data) => {
      +  console.log(`Received data: "${data}"`);
      +});
      +stream.write('It works!'); // Received data: "It works!"
      +

      ES6 example using class and extends:

      +
      const EventEmitter = require('events');
      +
      +class MyStream extends EventEmitter {
      +  write(data) {
      +    this.emit('data', data);
      +  }
      +}
      +
      +const stream = new MyStream();
      +
      +stream.on('data', (data) => {
      +  console.log(`Received data: "${data}"`);
      +});
      +stream.write('With ES6');
      +

      util.inspect(object[, options])#

      +

      util.inspect(object[, showHidden[, depth[, colors]]])#

      + +
        +
      • object <any> Any JavaScript primitive or Object.
      • +
      • options <Object> +
          +
        • showHidden <boolean> If true, object's non-enumerable symbols and +properties are included in the formatted result. WeakMap and +WeakSet entries are also included as well as user defined prototype +properties (excluding method properties). Default: false.
        • +
        • depth <number> Specifies the number of times to recurse while formatting +object. This is useful for inspecting large objects. To recurse up to +the maximum call stack size pass Infinity or null. +Default: 2.
        • +
        • colors <boolean> If true, the output is styled with ANSI color +codes. Colors are customizable. See Customizing util.inspect colors. +Default: false.
        • +
        • customInspect <boolean> If false, +[util.inspect.custom](depth, opts) functions are not invoked. +Default: true.
        • +
        • showProxy <boolean> If true, Proxy inspection includes +the target and handler objects. Default: false.
        • +
        • maxArrayLength <integer> Specifies the maximum number of Array, +TypedArray, WeakMap and WeakSet elements to include when +formatting. Set to null or Infinity to show all elements. Set to 0 or +negative to show no elements. Default: 100.
        • +
        • maxStringLength <integer> Specifies the maximum number of characters to +include when formatting. Set to null or Infinity to show all elements. +Set to 0 or negative to show no characters. Default: Infinity.
        • +
        • breakLength <integer> The length at which input values are split across +multiple lines. Set to Infinity to format the input as a single line +(in combination with compact set to true or any number >= 1). +Default: 80.
        • +
        • compact <boolean> | <integer> Setting this to false causes each object key +to be displayed on a new line. It will also add new lines to text that is +longer than breakLength. If set to a number, the most n inner elements +are united on a single line as long as all properties fit into +breakLength. Short array elements are also grouped together. No +text will be reduced below 16 characters, no matter the breakLength size. +For more information, see the example below. Default: 3.
        • +
        • sorted <boolean> | <Function> If set to true or a function, all properties +of an object, and Set and Map entries are sorted in the resulting +string. If set to true the default sort is used. If set to a function, +it is used as a compare function.
        • +
        • getters <boolean> | <string> If set to true, getters are inspected. If set +to 'get', only getters without a corresponding setter are inspected. If +set to 'set', only getters with a corresponding setter are inspected. +This might cause side effects depending on the getter function. +Default: false.
        • +
        +
      • +
      • Returns: <string> The representation of object.
      • +
      +

      The util.inspect() method returns a string representation of object that is +intended for debugging. The output of util.inspect may change at any time +and should not be depended upon programmatically. Additional options may be +passed that alter the result. +util.inspect() will use the constructor's name and/or @@toStringTag to make +an identifiable tag for an inspected value.

      +
      class Foo {
      +  get [Symbol.toStringTag]() {
      +    return 'bar';
      +  }
      +}
      +
      +class Bar {}
      +
      +const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
      +
      +util.inspect(new Foo()); // 'Foo [bar] {}'
      +util.inspect(new Bar()); // 'Bar {}'
      +util.inspect(baz);       // '[foo] {}'
      +

      Circular references are marked as '[Circular]':

      +
      const { inspect } = require('util');
      +
      +const obj = {};
      +obj.a = [obj];
      +obj.b = {};
      +obj.b.inner = obj.b;
      +obj.b.obj = obj;
      +
      +console.log(inspect(obj));
      +// {
      +//   a: [ [Circular] ],
      +//   b: { inner: [Circular], obj: [Circular] }
      +// }
      +

      The following example inspects all properties of the util object:

      +
      const util = require('util');
      +
      +console.log(util.inspect(util, { showHidden: true, depth: null }));
      +

      The following example highlights the effect of the compact option:

      +
      const util = require('util');
      +
      +const o = {
      +  a: [1, 2, [[
      +    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      +      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      +    'test',
      +    'foo']], 4],
      +  b: new Map([['za', 1], ['zb', 'test']])
      +};
      +console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
      +
      +// { a:
      +//   [ 1,
      +//     2,
      +//     [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line
      +//           'test',
      +//           'foo' ] ],
      +//     4 ],
      +//   b: Map { 'za' => 1, 'zb' => 'test' } }
      +
      +// Setting `compact` to false changes the output to be more reader friendly.
      +console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
      +
      +// {
      +//   a: [
      +//     1,
      +//     2,
      +//     [
      +//       [
      +//         'Lorem ipsum dolor sit amet, consectetur ' +
      +//           'adipiscing elit, sed do eiusmod tempor ' +
      +//           'incididunt ut labore et dolore magna ' +
      +//           'aliqua.,
      +//         'test',
      +//         'foo'
      +//       ]
      +//     ],
      +//     4
      +//   ],
      +//   b: Map {
      +//     'za' => 1,
      +//     'zb' => 'test'
      +//   }
      +// }
      +
      +// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
      +// single line.
      +// Reducing the `breakLength` will split the "Lorem ipsum" text in smaller
      +// chunks.
      +

      The showHidden option allows WeakMap and WeakSet entries to be +inspected. If there are more entries than maxArrayLength, there is no +guarantee which entries are displayed. That means retrieving the same +WeakSet entries twice may result in different output. Furthermore, entries +with no remaining strong references may be garbage collected at any time.

      +
      const { inspect } = require('util');
      +
      +const obj = { a: 1 };
      +const obj2 = { b: 2 };
      +const weakSet = new WeakSet([obj, obj2]);
      +
      +console.log(inspect(weakSet, { showHidden: true }));
      +// WeakSet { { a: 1 }, { b: 2 } }
      +

      The sorted option ensures that an object's property insertion order does not +impact the result of util.inspect().

      +
      const { inspect } = require('util');
      +const assert = require('assert');
      +
      +const o1 = {
      +  b: [2, 3, 1],
      +  a: '`a` comes before `b`',
      +  c: new Set([2, 3, 1])
      +};
      +console.log(inspect(o1, { sorted: true }));
      +// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }
      +console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
      +// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
      +
      +const o2 = {
      +  c: new Set([2, 1, 3]),
      +  a: '`a` comes before `b`',
      +  b: [2, 3, 1]
      +};
      +assert.strict.equal(
      +  inspect(o1, { sorted: true }),
      +  inspect(o2, { sorted: true })
      +);
      +

      util.inspect() is a synchronous method intended for debugging. Its maximum +output length is approximately 128 MB. Inputs that result in longer output will +be truncated.

      +

      Customizing util.inspect colors#

      + +

      Color output (if enabled) of util.inspect is customizable globally +via the util.inspect.styles and util.inspect.colors properties.

      +

      util.inspect.styles is a map associating a style name to a color from +util.inspect.colors.

      +

      The default styles and associated colors are:

      +
        +
      • bigint: yellow
      • +
      • boolean: yellow
      • +
      • date: magenta
      • +
      • module: underline
      • +
      • name: (no styling)
      • +
      • null: bold
      • +
      • number: yellow
      • +
      • regexp: red
      • +
      • special: cyan (e.g., Proxies)
      • +
      • string: green
      • +
      • symbol: green
      • +
      • undefined: grey
      • +
      +

      Color styling uses ANSI control codes that may not be supported on all +terminals. To verify color support use tty.hasColors().

      +

      Predefined control codes are listed below (grouped as "Modifiers", "Foreground +colors", and "Background colors").

      +

      Modifiers#

      +

      Modifier support varies throughout different terminals. They will mostly be +ignored, if not supported.

      +
        +
      • reset - Resets all (color) modifiers to their defaults
      • +
      • bold - Make text bold
      • +
      • italic - Make text italic
      • +
      • underline - Make text underlined
      • +
      • strikethrough - Puts a horizontal line through the center of the text +(Alias: strikeThrough, crossedout, crossedOut)
      • +
      • hidden - Prints the text, but makes it invisible (Alias: conceal)
      • +
      • dim - Decreased color intensity (Alias: +faint)
      • +
      • overlined - Make text overlined
      • +
      • blink - Hides and shows the text in an interval
      • +
      • inverse - Swap foreground and +background colors (Alias: swapcolors, swapColors)
      • +
      • doubleunderline - Make text +double underlined (Alias: doubleUnderline)
      • +
      • framed - Draw a frame around the text
      • +
      +

      Foreground colors#

      +
        +
      • black
      • +
      • red
      • +
      • green
      • +
      • yellow
      • +
      • blue
      • +
      • magenta
      • +
      • cyan
      • +
      • white
      • +
      • gray (alias: grey, blackBright)
      • +
      • redBright
      • +
      • greenBright
      • +
      • yellowBright
      • +
      • blueBright
      • +
      • magentaBright
      • +
      • cyanBright
      • +
      • whiteBright
      • +
      +

      Background colors#

      +
        +
      • bgBlack
      • +
      • bgRed
      • +
      • bgGreen
      • +
      • bgYellow
      • +
      • bgBlue
      • +
      • bgMagenta
      • +
      • bgCyan
      • +
      • bgWhite
      • +
      • bgGray (alias: bgGrey, bgBlackBright)
      • +
      • bgRedBright
      • +
      • bgGreenBright
      • +
      • bgYellowBright
      • +
      • bgBlueBright
      • +
      • bgMagentaBright
      • +
      • bgCyanBright
      • +
      • bgWhiteBright
      • +
      +

      Custom inspection functions on objects#

      + +

      Objects may also define their own +[util.inspect.custom](depth, opts) function, +which util.inspect() will invoke and use the result of when inspecting +the object:

      +
      const util = require('util');
      +
      +class Box {
      +  constructor(value) {
      +    this.value = value;
      +  }
      +
      +  [util.inspect.custom](depth, options) {
      +    if (depth < 0) {
      +      return options.stylize('[Box]', 'special');
      +    }
      +
      +    const newOptions = Object.assign({}, options, {
      +      depth: options.depth === null ? null : options.depth - 1
      +    });
      +
      +    // Five space padding because that's the size of "Box< ".
      +    const padding = ' '.repeat(5);
      +    const inner = util.inspect(this.value, newOptions)
      +                      .replace(/\n/g, `\n${padding}`);
      +    return `${options.stylize('Box', 'special')}< ${inner} >`;
      +  }
      +}
      +
      +const box = new Box(true);
      +
      +util.inspect(box);
      +// Returns: "Box< true >"
      +

      Custom [util.inspect.custom](depth, opts) functions typically return a string +but may return a value of any type that will be formatted accordingly by +util.inspect().

      +
      const util = require('util');
      +
      +const obj = { foo: 'this will not show up in the inspect() output' };
      +obj[util.inspect.custom] = (depth) => {
      +  return { bar: 'baz' };
      +};
      +
      +util.inspect(obj);
      +// Returns: "{ bar: 'baz' }"
      +

      util.inspect.custom#

      + +
        +
      • <symbol> that can be used to declare custom inspect functions.
      • +
      +

      In addition to being accessible through util.inspect.custom, this +symbol is registered globally and can be +accessed in any environment as Symbol.for('nodejs.util.inspect.custom').

      +
      const inspect = Symbol.for('nodejs.util.inspect.custom');
      +
      +class Password {
      +  constructor(value) {
      +    this.value = value;
      +  }
      +
      +  toString() {
      +    return 'xxxxxxxx';
      +  }
      +
      +  [inspect]() {
      +    return `Password <${this.toString()}>`;
      +  }
      +}
      +
      +const password = new Password('r0sebud');
      +console.log(password);
      +// Prints Password <xxxxxxxx>
      +

      See Custom inspection functions on Objects for more details.

      +

      util.inspect.defaultOptions#

      + +

      The defaultOptions value allows customization of the default options used by +util.inspect. This is useful for functions like console.log or +util.format which implicitly call into util.inspect. It shall be set to an +object containing one or more valid util.inspect() options. Setting +option properties directly is also supported.

      +
      const util = require('util');
      +const arr = Array(101).fill(0);
      +
      +console.log(arr); // Logs the truncated array
      +util.inspect.defaultOptions.maxArrayLength = null;
      +console.log(arr); // logs the full array
      +

      util.isDeepStrictEqual(val1, val2)#

      + + +

      Returns true if there is deep strict equality between val1 and val2. +Otherwise, returns false.

      +

      See assert.deepStrictEqual() for more information about deep strict +equality.

      +

      util.promisify(original)#

      + + +

      Takes a function following the common error-first callback style, i.e. taking +an (err, value) => ... callback as the last argument, and returns a version +that returns promises.

      +
      const util = require('util');
      +const fs = require('fs');
      +
      +const stat = util.promisify(fs.stat);
      +stat('.').then((stats) => {
      +  // Do something with `stats`
      +}).catch((error) => {
      +  // Handle the error.
      +});
      +

      Or, equivalently using async functions:

      +
      const util = require('util');
      +const fs = require('fs');
      +
      +const stat = util.promisify(fs.stat);
      +
      +async function callStat() {
      +  const stats = await stat('.');
      +  console.log(`This directory is owned by ${stats.uid}`);
      +}
      +

      If there is an original[util.promisify.custom] property present, promisify +will return its value, see Custom promisified functions.

      +

      promisify() assumes that original is a function taking a callback as its +final argument in all cases. If original is not a function, promisify() +will throw an error. If original is a function but its last argument is not +an error-first callback, it will still be passed an error-first +callback as its last argument.

      +

      Using promisify() on class methods or other methods that use this may not +work as expected unless handled specially:

      +
      const util = require('util');
      +
      +class Foo {
      +  constructor() {
      +    this.a = 42;
      +  }
      +
      +  bar(callback) {
      +    callback(null, this.a);
      +  }
      +}
      +
      +const foo = new Foo();
      +
      +const naiveBar = util.promisify(foo.bar);
      +// TypeError: Cannot read property 'a' of undefined
      +// naiveBar().then(a => console.log(a));
      +
      +naiveBar.call(foo).then((a) => console.log(a)); // '42'
      +
      +const bindBar = naiveBar.bind(foo);
      +bindBar().then((a) => console.log(a)); // '42'
      +

      Custom promisified functions#

      +

      Using the util.promisify.custom symbol one can override the return value of +util.promisify():

      +
      const util = require('util');
      +
      +function doSomething(foo, callback) {
      +  // ...
      +}
      +
      +doSomething[util.promisify.custom] = (foo) => {
      +  return getPromiseSomehow();
      +};
      +
      +const promisified = util.promisify(doSomething);
      +console.log(promisified === doSomething[util.promisify.custom]);
      +// prints 'true'
      +

      This can be useful for cases where the original function does not follow the +standard format of taking an error-first callback as the last argument.

      +

      For example, with a function that takes in +(foo, onSuccessCallback, onErrorCallback):

      +
      doSomething[util.promisify.custom] = (foo) => {
      +  return new Promise((resolve, reject) => {
      +    doSomething(foo, resolve, reject);
      +  });
      +};
      +

      If promisify.custom is defined but is not a function, promisify() will +throw an error.

      +

      util.promisify.custom#

      + + +

      In addition to being accessible through util.promisify.custom, this +symbol is registered globally and can be +accessed in any environment as Symbol.for('nodejs.util.promisify.custom').

      +

      For example, with a function that takes in +(foo, onSuccessCallback, onErrorCallback):

      +
      const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');
      +
      +doSomething[kCustomPromisifiedSymbol] = (foo) => {
      +  return new Promise((resolve, reject) => {
      +    doSomething(foo, resolve, reject);
      +  });
      +};
      +

      Class: util.TextDecoder#

      + +

      An implementation of the WHATWG Encoding Standard TextDecoder API.

      +
      const decoder = new TextDecoder('shift_jis');
      +let string = '';
      +let buffer;
      +while (buffer = getNextChunkSomehow()) {
      +  string += decoder.decode(buffer, { stream: true });
      +}
      +string += decoder.decode(); // end-of-stream
      +

      WHATWG supported encodings#

      +

      Per the WHATWG Encoding Standard, the encodings supported by the +TextDecoder API are outlined in the tables below. For each encoding, +one or more aliases may be used.

      +

      Different Node.js build configurations support different sets of encodings. +While a very basic set of encodings is supported even on Node.js builds without +ICU enabled, support for some encodings is provided only when Node.js is built +with ICU and using the full ICU data (see Internationalization).

      +

      Encodings Supported Without ICU#

      + + + + + + + + + + + + + + + + + +
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      +

      Encodings Supported by Default (With ICU)#

      + + + + + + + + + + + + + + + + + + + + + +
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      'utf-16be'
      +

      Encodings requiring full ICU data#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      EncodingAliases
      'ibm866''866', 'cp866', 'csibm866'
      'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
      'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
      'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
      'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
      'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
      'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
      'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
      'iso-8859-8-i''csiso88598i', 'logical'
      'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
      'iso-8859-13''iso8859-13', 'iso885913'
      'iso-8859-14''iso8859-14', 'iso885914'
      'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
      'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
      'koi8-u''koi8-ru'
      'macintosh''csmacintosh', 'mac', 'x-mac-roman'
      'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
      'windows-1250''cp1250', 'x-cp1250'
      'windows-1251''cp1251', 'x-cp1251'
      'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
      'windows-1253''cp1253', 'x-cp1253'
      'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
      'windows-1255''cp1255', 'x-cp1255'
      'windows-1256''cp1256', 'x-cp1256'
      'windows-1257''cp1257', 'x-cp1257'
      'windows-1258''cp1258', 'x-cp1258'
      'x-mac-cyrillic''x-mac-ukrainian'
      'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
      'gb18030'
      'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
      'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
      'iso-2022-jp''csiso2022jp'
      'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
      'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
      +

      The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard +is not supported.

      +

      new TextDecoder([encoding[, options]])#

      + +
        +
      • encoding <string> Identifies the encoding that this TextDecoder instance +supports. Default: 'utf-8'.
      • +
      • options <Object> +
          +
        • fatal <boolean> true if decoding failures are fatal. This option is only +supported when ICU is enabled (see Internationalization). Default: +false.
        • +
        • ignoreBOM <boolean> When true, the TextDecoder will include the byte +order mark in the decoded result. When false, the byte order mark will +be removed from the output. This option is only used when encoding is +'utf-8', 'utf-16be' or 'utf-16le'. Default: false.
        • +
        +
      • +
      +

      Creates an new TextDecoder instance. The encoding may specify one of the +supported encodings or an alias.

      +

      The TextDecoder class is also available on the global object.

      +

      textDecoder.decode([input[, options]])#

      + +

      Decodes the input and returns a string. If options.stream is true, any +incomplete byte sequences occurring at the end of the input are buffered +internally and emitted after the next call to textDecoder.decode().

      +

      If textDecoder.fatal is true, decoding errors that occur will result in a +TypeError being thrown.

      +

      textDecoder.encoding#

      + +

      The encoding supported by the TextDecoder instance.

      +

      textDecoder.fatal#

      + +

      The value will be true if decoding errors result in a TypeError being +thrown.

      +

      textDecoder.ignoreBOM#

      + +

      The value will be true if the decoding result will include the byte order +mark.

      +

      Class: util.TextEncoder#

      + +

      An implementation of the WHATWG Encoding Standard TextEncoder API. All +instances of TextEncoder only support UTF-8 encoding.

      +
      const encoder = new TextEncoder();
      +const uint8array = encoder.encode('this is some data');
      +

      The TextEncoder class is also available on the global object.

      +

      textEncoder.encode([input])#

      + +

      UTF-8 encodes the input string and returns a Uint8Array containing the +encoded bytes.

      +

      textEncoder.encodeInto(src, dest)#

      + +

      UTF-8 encodes the src string to the dest Uint8Array and returns an object +containing the read Unicode code units and written UTF-8 bytes.

      +
      const encoder = new TextEncoder();
      +const src = 'this is some data';
      +const dest = new Uint8Array(10);
      +const { read, written } = encoder.encodeInto(src, dest);
      +

      textEncoder.encoding#

      + +

      The encoding supported by the TextEncoder instance. Always set to 'utf-8'.

      +

      util.types#

      + +

      util.types provides type checks for different kinds of built-in objects. +Unlike instanceof or Object.prototype.toString.call(value), these checks do +not inspect properties of the object that are accessible from JavaScript (like +their prototype), and usually have the overhead of calling into C++.

      +

      The result generally does not make any guarantees about what kinds of +properties or behavior a value exposes in JavaScript. They are primarily +useful for addon developers who prefer to do type checking in JavaScript.

      +

      util.types.isAnyArrayBuffer(value)#

      + + +

      Returns true if the value is a built-in ArrayBuffer or +SharedArrayBuffer instance.

      +

      See also util.types.isArrayBuffer() and +util.types.isSharedArrayBuffer().

      +
      util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true
      +util.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true
      +

      util.types.isArrayBufferView(value)#

      + + +

      Returns true if the value is an instance of one of the ArrayBuffer +views, such as typed array objects or DataView. Equivalent to +ArrayBuffer.isView().

      +
      util.types.isArrayBufferView(new Int8Array());  // true
      +util.types.isArrayBufferView(Buffer.from('hello world')); // true
      +util.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true
      +util.types.isArrayBufferView(new ArrayBuffer());  // false
      +

      util.types.isArgumentsObject(value)#

      + + +

      Returns true if the value is an arguments object.

      + +
      function foo() {
      +  util.types.isArgumentsObject(arguments);  // Returns true
      +}
      +

      util.types.isArrayBuffer(value)#

      + + +

      Returns true if the value is a built-in ArrayBuffer instance. +This does not include SharedArrayBuffer instances. Usually, it is +desirable to test for both; See util.types.isAnyArrayBuffer() for that.

      +
      util.types.isArrayBuffer(new ArrayBuffer());  // Returns true
      +util.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false
      +

      util.types.isAsyncFunction(value)#

      + + +

      Returns true if the value is an async function. +This only reports back what the JavaScript engine is seeing; +in particular, the return value may not match the original source code if +a transpilation tool was used.

      +
      util.types.isAsyncFunction(function foo() {});  // Returns false
      +util.types.isAsyncFunction(async function foo() {});  // Returns true
      +

      util.types.isBigInt64Array(value)#

      + + +

      Returns true if the value is a BigInt64Array instance.

      +
      util.types.isBigInt64Array(new BigInt64Array());   // Returns true
      +util.types.isBigInt64Array(new BigUint64Array());  // Returns false
      +

      util.types.isBigUint64Array(value)#

      + + +

      Returns true if the value is a BigUint64Array instance.

      +
      util.types.isBigUint64Array(new BigInt64Array());   // Returns false
      +util.types.isBigUint64Array(new BigUint64Array());  // Returns true
      +

      util.types.isBooleanObject(value)#

      + + +

      Returns true if the value is a boolean object, e.g. created +by new Boolean().

      +
      util.types.isBooleanObject(false);  // Returns false
      +util.types.isBooleanObject(true);   // Returns false
      +util.types.isBooleanObject(new Boolean(false)); // Returns true
      +util.types.isBooleanObject(new Boolean(true));  // Returns true
      +util.types.isBooleanObject(Boolean(false)); // Returns false
      +util.types.isBooleanObject(Boolean(true));  // Returns false
      +

      util.types.isBoxedPrimitive(value)#

      + + +

      Returns true if the value is any boxed primitive object, e.g. created +by new Boolean(), new String() or Object(Symbol()).

      +

      For example:

      +
      util.types.isBoxedPrimitive(false); // Returns false
      +util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
      +util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
      +util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
      +util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
      +

      util.types.isDataView(value)#

      + + +

      Returns true if the value is a built-in DataView instance.

      +
      const ab = new ArrayBuffer(20);
      +util.types.isDataView(new DataView(ab));  // Returns true
      +util.types.isDataView(new Float64Array());  // Returns false
      +

      See also ArrayBuffer.isView().

      +

      util.types.isDate(value)#

      + + +

      Returns true if the value is a built-in Date instance.

      +
      util.types.isDate(new Date());  // Returns true
      +

      util.types.isExternal(value)#

      + + +

      Returns true if the value is a native External value.

      +

      A native External value is a special type of object that contains a +raw C++ pointer (void*) for access from native code, and has no other +properties. Such objects are created either by Node.js internals or native +addons. In JavaScript, they are frozen objects with a +null prototype.

      +
      #include <js_native_api.h>
      +#include <stdlib.h>
      +napi_value result;
      +static napi_value MyNapi(napi_env env, napi_callback_info info) {
      +  int* raw = (int*) malloc(1024);
      +  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
      +  if (status != napi_ok) {
      +    napi_throw_error(env, NULL, "napi_create_external failed");
      +    return NULL;
      +  }
      +  return result;
      +}
      +...
      +DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
      +...
      +
      const native = require('napi_addon.node');
      +const data = native.myNapi();
      +util.types.isExternal(data); // returns true
      +util.types.isExternal(0); // returns false
      +util.types.isExternal(new String('foo')); // returns false
      +

      For further information on napi_create_external, refer to +napi_create_external().

      +

      util.types.isFloat32Array(value)#

      + + +

      Returns true if the value is a built-in Float32Array instance.

      +
      util.types.isFloat32Array(new ArrayBuffer());  // Returns false
      +util.types.isFloat32Array(new Float32Array());  // Returns true
      +util.types.isFloat32Array(new Float64Array());  // Returns false
      +

      util.types.isFloat64Array(value)#

      + + +

      Returns true if the value is a built-in Float64Array instance.

      +
      util.types.isFloat64Array(new ArrayBuffer());  // Returns false
      +util.types.isFloat64Array(new Uint8Array());  // Returns false
      +util.types.isFloat64Array(new Float64Array());  // Returns true
      +

      util.types.isGeneratorFunction(value)#

      + + +

      Returns true if the value is a generator function. +This only reports back what the JavaScript engine is seeing; +in particular, the return value may not match the original source code if +a transpilation tool was used.

      +
      util.types.isGeneratorFunction(function foo() {});  // Returns false
      +util.types.isGeneratorFunction(function* foo() {});  // Returns true
      +

      util.types.isGeneratorObject(value)#

      + + +

      Returns true if the value is a generator object as returned from a +built-in generator function. +This only reports back what the JavaScript engine is seeing; +in particular, the return value may not match the original source code if +a transpilation tool was used.

      +
      function* foo() {}
      +const generator = foo();
      +util.types.isGeneratorObject(generator);  // Returns true
      +

      util.types.isInt8Array(value)#

      + + +

      Returns true if the value is a built-in Int8Array instance.

      +
      util.types.isInt8Array(new ArrayBuffer());  // Returns false
      +util.types.isInt8Array(new Int8Array());  // Returns true
      +util.types.isInt8Array(new Float64Array());  // Returns false
      +

      util.types.isInt16Array(value)#

      + + +

      Returns true if the value is a built-in Int16Array instance.

      +
      util.types.isInt16Array(new ArrayBuffer());  // Returns false
      +util.types.isInt16Array(new Int16Array());  // Returns true
      +util.types.isInt16Array(new Float64Array());  // Returns false
      +

      util.types.isInt32Array(value)#

      + + +

      Returns true if the value is a built-in Int32Array instance.

      +
      util.types.isInt32Array(new ArrayBuffer());  // Returns false
      +util.types.isInt32Array(new Int32Array());  // Returns true
      +util.types.isInt32Array(new Float64Array());  // Returns false
      +

      util.types.isMap(value)#

      + + +

      Returns true if the value is a built-in Map instance.

      +
      util.types.isMap(new Map());  // Returns true
      +

      util.types.isMapIterator(value)#

      + + +

      Returns true if the value is an iterator returned for a built-in +Map instance.

      +
      const map = new Map();
      +util.types.isMapIterator(map.keys());  // Returns true
      +util.types.isMapIterator(map.values());  // Returns true
      +util.types.isMapIterator(map.entries());  // Returns true
      +util.types.isMapIterator(map[Symbol.iterator]());  // Returns true
      +

      util.types.isModuleNamespaceObject(value)#

      + + +

      Returns true if the value is an instance of a Module Namespace Object.

      + +
      import * as ns from './a.js';
      +
      +util.types.isModuleNamespaceObject(ns);  // Returns true
      +

      util.types.isNativeError(value)#

      + + +

      Returns true if the value is an instance of a built-in Error type.

      +
      util.types.isNativeError(new Error());  // Returns true
      +util.types.isNativeError(new TypeError());  // Returns true
      +util.types.isNativeError(new RangeError());  // Returns true
      +

      util.types.isNumberObject(value)#

      + + +

      Returns true if the value is a number object, e.g. created +by new Number().

      +
      util.types.isNumberObject(0);  // Returns false
      +util.types.isNumberObject(new Number(0));   // Returns true
      +

      util.types.isPromise(value)#

      + + +

      Returns true if the value is a built-in Promise.

      +
      util.types.isPromise(Promise.resolve(42));  // Returns true
      +

      util.types.isProxy(value)#

      + + +

      Returns true if the value is a Proxy instance.

      +
      const target = {};
      +const proxy = new Proxy(target, {});
      +util.types.isProxy(target);  // Returns false
      +util.types.isProxy(proxy);  // Returns true
      +

      util.types.isRegExp(value)#

      + + +

      Returns true if the value is a regular expression object.

      +
      util.types.isRegExp(/abc/);  // Returns true
      +util.types.isRegExp(new RegExp('abc'));  // Returns true
      +

      util.types.isSet(value)#

      + + +

      Returns true if the value is a built-in Set instance.

      +
      util.types.isSet(new Set());  // Returns true
      +

      util.types.isSetIterator(value)#

      + + +

      Returns true if the value is an iterator returned for a built-in +Set instance.

      +
      const set = new Set();
      +util.types.isSetIterator(set.keys());  // Returns true
      +util.types.isSetIterator(set.values());  // Returns true
      +util.types.isSetIterator(set.entries());  // Returns true
      +util.types.isSetIterator(set[Symbol.iterator]());  // Returns true
      +

      util.types.isSharedArrayBuffer(value)#

      + + +

      Returns true if the value is a built-in SharedArrayBuffer instance. +This does not include ArrayBuffer instances. Usually, it is +desirable to test for both; See util.types.isAnyArrayBuffer() for that.

      +
      util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false
      +util.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true
      +

      util.types.isStringObject(value)#

      + + +

      Returns true if the value is a string object, e.g. created +by new String().

      +
      util.types.isStringObject('foo');  // Returns false
      +util.types.isStringObject(new String('foo'));   // Returns true
      +

      util.types.isSymbolObject(value)#

      + + +

      Returns true if the value is a symbol object, created +by calling Object() on a Symbol primitive.

      +
      const symbol = Symbol('foo');
      +util.types.isSymbolObject(symbol);  // Returns false
      +util.types.isSymbolObject(Object(symbol));   // Returns true
      +

      util.types.isTypedArray(value)#

      + + +

      Returns true if the value is a built-in TypedArray instance.

      +
      util.types.isTypedArray(new ArrayBuffer());  // Returns false
      +util.types.isTypedArray(new Uint8Array());  // Returns true
      +util.types.isTypedArray(new Float64Array());  // Returns true
      +

      See also ArrayBuffer.isView().

      +

      util.types.isUint8Array(value)#

      + + +

      Returns true if the value is a built-in Uint8Array instance.

      +
      util.types.isUint8Array(new ArrayBuffer());  // Returns false
      +util.types.isUint8Array(new Uint8Array());  // Returns true
      +util.types.isUint8Array(new Float64Array());  // Returns false
      +

      util.types.isUint8ClampedArray(value)#

      + + +

      Returns true if the value is a built-in Uint8ClampedArray instance.

      +
      util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false
      +util.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true
      +util.types.isUint8ClampedArray(new Float64Array());  // Returns false
      +

      util.types.isUint16Array(value)#

      + + +

      Returns true if the value is a built-in Uint16Array instance.

      +
      util.types.isUint16Array(new ArrayBuffer());  // Returns false
      +util.types.isUint16Array(new Uint16Array());  // Returns true
      +util.types.isUint16Array(new Float64Array());  // Returns false
      +

      util.types.isUint32Array(value)#

      + + +

      Returns true if the value is a built-in Uint32Array instance.

      +
      util.types.isUint32Array(new ArrayBuffer());  // Returns false
      +util.types.isUint32Array(new Uint32Array());  // Returns true
      +util.types.isUint32Array(new Float64Array());  // Returns false
      +

      util.types.isWeakMap(value)#

      + + +

      Returns true if the value is a built-in WeakMap instance.

      +
      util.types.isWeakMap(new WeakMap());  // Returns true
      +

      util.types.isWeakSet(value)#

      + + +

      Returns true if the value is a built-in WeakSet instance.

      +
      util.types.isWeakSet(new WeakSet());  // Returns true
      +

      util.types.isWebAssemblyCompiledModule(value)#

      + + +

      Returns true if the value is a built-in WebAssembly.Module instance.

      +
      const module = new WebAssembly.Module(wasmBuffer);
      +util.types.isWebAssemblyCompiledModule(module);  // Returns true
      +

      Deprecated APIs#

      +

      The following APIs are deprecated and should no longer be used. Existing +applications and modules should be updated to find alternative approaches.

      +

      util._extend(target, source)#

      + +

      Stability: 0 - Deprecated: Use Object.assign() instead.

      + +

      The util._extend() method was never intended to be used outside of internal +Node.js modules. The community found and used it anyway.

      +

      It is deprecated and should not be used in new code. JavaScript comes with very +similar built-in functionality through Object.assign().

      +

      util.isArray(object)#

      + +

      Stability: 0 - Deprecated: Use Array.isArray() instead.

      + +

      Alias for Array.isArray().

      +

      Returns true if the given object is an Array. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isArray([]);
      +// Returns: true
      +util.isArray(new Array());
      +// Returns: true
      +util.isArray({});
      +// Returns: false
      +

      util.isBoolean(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'boolean' instead.

      + +

      Returns true if the given object is a Boolean. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isBoolean(1);
      +// Returns: false
      +util.isBoolean(0);
      +// Returns: false
      +util.isBoolean(false);
      +// Returns: true
      +

      util.isBuffer(object)#

      + +

      Stability: 0 - Deprecated: Use Buffer.isBuffer() instead.

      + +

      Returns true if the given object is a Buffer. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isBuffer({ length: 0 });
      +// Returns: false
      +util.isBuffer([]);
      +// Returns: false
      +util.isBuffer(Buffer.from('hello world'));
      +// Returns: true
      +

      util.isDate(object)#

      + +

      Stability: 0 - Deprecated: Use util.types.isDate() instead.

      + +

      Returns true if the given object is a Date. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isDate(new Date());
      +// Returns: true
      +util.isDate(Date());
      +// false (without 'new' returns a String)
      +util.isDate({});
      +// Returns: false
      +

      util.isError(object)#

      + +

      Stability: 0 - Deprecated: Use util.types.isNativeError() instead.

      + +

      Returns true if the given object is an Error. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +util.isError(new Error());
      +// Returns: true
      +util.isError(new TypeError());
      +// Returns: true
      +util.isError({ name: 'Error', message: 'an error occurred' });
      +// Returns: false
      +

      This method relies on Object.prototype.toString() behavior. It is +possible to obtain an incorrect result when the object argument manipulates +@@toStringTag.

      +
      const util = require('util');
      +const obj = { name: 'Error', message: 'an error occurred' };
      +
      +util.isError(obj);
      +// Returns: false
      +obj[Symbol.toStringTag] = 'Error';
      +util.isError(obj);
      +// Returns: true
      +

      util.isFunction(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'function' instead.

      + +

      Returns true if the given object is a Function. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +function Foo() {}
      +const Bar = () => {};
      +
      +util.isFunction({});
      +// Returns: false
      +util.isFunction(Foo);
      +// Returns: true
      +util.isFunction(Bar);
      +// Returns: true
      +

      util.isNull(object)#

      + +

      Stability: 0 - Deprecated: Use value === null instead.

      + +

      Returns true if the given object is strictly null. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +util.isNull(0);
      +// Returns: false
      +util.isNull(undefined);
      +// Returns: false
      +util.isNull(null);
      +// Returns: true
      +

      util.isNullOrUndefined(object)#

      + +

      Stability: 0 - Deprecated: Use +value === undefined || value === null instead.

      + +

      Returns true if the given object is null or undefined. Otherwise, +returns false.

      +
      const util = require('util');
      +
      +util.isNullOrUndefined(0);
      +// Returns: false
      +util.isNullOrUndefined(undefined);
      +// Returns: true
      +util.isNullOrUndefined(null);
      +// Returns: true
      +

      util.isNumber(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'number' instead.

      + +

      Returns true if the given object is a Number. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isNumber(false);
      +// Returns: false
      +util.isNumber(Infinity);
      +// Returns: true
      +util.isNumber(0);
      +// Returns: true
      +util.isNumber(NaN);
      +// Returns: true
      +

      util.isObject(object)#

      + +

      Stability: 0 - Deprecated: +Use value !== null && typeof value === 'object' instead.

      + +

      Returns true if the given object is strictly an Object and not a +Function (even though functions are objects in JavaScript). +Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isObject(5);
      +// Returns: false
      +util.isObject(null);
      +// Returns: false
      +util.isObject({});
      +// Returns: true
      +util.isObject(() => {});
      +// Returns: false
      +

      util.isPrimitive(object)#

      + +

      Stability: 0 - Deprecated: Use +(typeof value !== 'object' && typeof value !== 'function') || value === null +instead.

      + +

      Returns true if the given object is a primitive type. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +util.isPrimitive(5);
      +// Returns: true
      +util.isPrimitive('foo');
      +// Returns: true
      +util.isPrimitive(false);
      +// Returns: true
      +util.isPrimitive(null);
      +// Returns: true
      +util.isPrimitive(undefined);
      +// Returns: true
      +util.isPrimitive({});
      +// Returns: false
      +util.isPrimitive(() => {});
      +// Returns: false
      +util.isPrimitive(/^$/);
      +// Returns: false
      +util.isPrimitive(new Date());
      +// Returns: false
      +

      util.isRegExp(object)#

      + +

      Stability: 0 - Deprecated

      + +

      Returns true if the given object is a RegExp. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isRegExp(/some regexp/);
      +// Returns: true
      +util.isRegExp(new RegExp('another regexp'));
      +// Returns: true
      +util.isRegExp({});
      +// Returns: false
      +

      util.isString(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'string' instead.

      + +

      Returns true if the given object is a string. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isString('');
      +// Returns: true
      +util.isString('foo');
      +// Returns: true
      +util.isString(String('foo'));
      +// Returns: true
      +util.isString(5);
      +// Returns: false
      +

      util.isSymbol(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'symbol' instead.

      + +

      Returns true if the given object is a Symbol. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isSymbol(5);
      +// Returns: false
      +util.isSymbol('foo');
      +// Returns: false
      +util.isSymbol(Symbol('foo'));
      +// Returns: true
      +

      util.isUndefined(object)#

      + +

      Stability: 0 - Deprecated: Use value === undefined instead.

      + +

      Returns true if the given object is undefined. Otherwise, returns false.

      +
      const util = require('util');
      +
      +const foo = undefined;
      +util.isUndefined(5);
      +// Returns: false
      +util.isUndefined(foo);
      +// Returns: true
      +util.isUndefined(null);
      +// Returns: false
      +

      util.log(string)#

      + +

      Stability: 0 - Deprecated: Use a third party module instead.

      + +

      The util.log() method prints the given string to stdout with an included +timestamp.

      +
      const util = require('util');
      +
      +util.log('Timestamped message.');
      +

      V8#

      + +

      Source Code: lib/v8.js

      +

      The v8 module exposes APIs that are specific to the version of V8 +built into the Node.js binary. It can be accessed using:

      +
      const v8 = require('v8');
      +

      The APIs and implementation are subject to change at any time.

      +

      v8.cachedDataVersionTag()#

      + + +

      Returns an integer representing a "version tag" derived from the V8 version, +command line flags and detected CPU features. This is useful for determining +whether a vm.Script cachedData buffer is compatible with this instance +of V8.

      +

      v8.getHeapSpaceStatistics()#

      + + +

      Returns statistics about the V8 heap spaces, i.e. the segments which make up +the V8 heap. Neither the ordering of heap spaces, nor the availability of a +heap space can be guaranteed as the statistics are provided via the V8 +GetHeapSpaceStatistics function and may change from one V8 version to the +next.

      +

      The value returned is an array of objects containing the following properties:

      + +
      [
      +  {
      +    "space_name": "new_space",
      +    "space_size": 2063872,
      +    "space_used_size": 951112,
      +    "space_available_size": 80824,
      +    "physical_space_size": 2063872
      +  },
      +  {
      +    "space_name": "old_space",
      +    "space_size": 3090560,
      +    "space_used_size": 2493792,
      +    "space_available_size": 0,
      +    "physical_space_size": 3090560
      +  },
      +  {
      +    "space_name": "code_space",
      +    "space_size": 1260160,
      +    "space_used_size": 644256,
      +    "space_available_size": 960,
      +    "physical_space_size": 1260160
      +  },
      +  {
      +    "space_name": "map_space",
      +    "space_size": 1094160,
      +    "space_used_size": 201608,
      +    "space_available_size": 0,
      +    "physical_space_size": 1094160
      +  },
      +  {
      +    "space_name": "large_object_space",
      +    "space_size": 0,
      +    "space_used_size": 0,
      +    "space_available_size": 1490980608,
      +    "physical_space_size": 0
      +  }
      +]
      +

      v8.getHeapSnapshot()#

      + + +

      Generates a snapshot of the current V8 heap and returns a Readable +Stream that may be used to read the JSON serialized representation. +This JSON stream format is intended to be used with tools such as +Chrome DevTools. The JSON schema is undocumented and specific to the +V8 engine, and may change from one version of V8 to the next.

      +
      const stream = v8.getHeapSnapshot();
      +stream.pipe(process.stdout);
      +

      v8.getHeapStatistics()#

      + + +

      Returns an object with the following properties:

      + +

      does_zap_garbage is a 0/1 boolean, which signifies whether the +--zap_code_space option is enabled or not. This makes V8 overwrite heap +garbage with a bit pattern. The RSS footprint (resident memory set) gets bigger +because it continuously touches all heap pages and that makes them less likely +to get swapped out by the operating system.

      +

      number_of_native_contexts The value of native_context is the number of the +top-level contexts currently active. Increase of this number over time indicates +a memory leak.

      +

      number_of_detached_contexts The value of detached_context is the number +of contexts that were detached and not yet garbage collected. This number +being non-zero indicates a potential memory leak.

      + +
      {
      +  total_heap_size: 7326976,
      +  total_heap_size_executable: 4194304,
      +  total_physical_size: 7326976,
      +  total_available_size: 1152656,
      +  used_heap_size: 3476208,
      +  heap_size_limit: 1535115264,
      +  malloced_memory: 16384,
      +  peak_malloced_memory: 1127496,
      +  does_zap_garbage: 0,
      +  number_of_native_contexts: 1,
      +  number_of_detached_contexts: 0
      +}
      +

      v8.getHeapCodeStatistics()#

      + + +

      Returns an object with the following properties:

      + + +
      {
      +  code_and_metadata_size: 212208,
      +  bytecode_and_metadata_size: 161368,
      +  external_script_source_size: 1410794
      +}
      +

      v8.setFlagsFromString(flags)#

      + + +

      The v8.setFlagsFromString() method can be used to programmatically set +V8 command line flags. This method should be used with care. Changing settings +after the VM has started may result in unpredictable behavior, including +crashes and data loss; or it may simply do nothing.

      +

      The V8 options available for a version of Node.js may be determined by running +node --v8-options.

      +

      Usage:

      +
      // Print GC events to stdout for one minute.
      +const v8 = require('v8');
      +v8.setFlagsFromString('--trace_gc');
      +setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
      +

      v8.takeCoverage()#

      + +

      The v8.takeCoverage() method allows the user to write the coverage started by +NODE_V8_COVERAGE to disk on demand. This method can be invoked multiple +times during the lifetime of the process, each time the execution counter will +be reset and a new coverage report will be written to the directory specified +by NODE_V8_COVERAGE.

      +

      When the process is about to exit, one last coverage will still be written to +disk, unless v8.stopCoverage() is invoked before the process exits.

      +

      v8.stopCoverage()#

      + +

      The v8.stopCoverage() method allows the user to stop the coverage collection +started by NODE_V8_COVERAGE, so that V8 can release the execution count +records and optimize code. This can be used in conjunction with +v8.takeCoverage() if the user wants to collect the coverage on demand.

      +

      v8.writeHeapSnapshot([filename])#

      + +
        +
      • filename <string> The file path where the V8 heap snapshot is to be +saved. If not specified, a file name with the pattern +'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot' will be +generated, where {pid} will be the PID of the Node.js process, +{thread_id} will be 0 when writeHeapSnapshot() is called from +the main Node.js thread or the id of a worker thread.
      • +
      • Returns: <string> The filename where the snapshot was saved.
      • +
      +

      Generates a snapshot of the current V8 heap and writes it to a JSON +file. This file is intended to be used with tools such as Chrome +DevTools. The JSON schema is undocumented and specific to the V8 +engine, and may change from one version of V8 to the next.

      +

      A heap snapshot is specific to a single V8 isolate. When using +worker threads, a heap snapshot generated from the main thread will +not contain any information about the workers, and vice versa.

      +
      const { writeHeapSnapshot } = require('v8');
      +const {
      +  Worker,
      +  isMainThread,
      +  parentPort
      +} = require('worker_threads');
      +
      +if (isMainThread) {
      +  const worker = new Worker(__filename);
      +
      +  worker.once('message', (filename) => {
      +    console.log(`worker heapdump: ${filename}`);
      +    // Now get a heapdump for the main thread.
      +    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
      +  });
      +
      +  // Tell the worker to create a heapdump.
      +  worker.postMessage('heapdump');
      +} else {
      +  parentPort.once('message', (message) => {
      +    if (message === 'heapdump') {
      +      // Generate a heapdump for the worker
      +      // and return the filename to the parent.
      +      parentPort.postMessage(writeHeapSnapshot());
      +    }
      +  });
      +}
      +

      Serialization API#

      +

      The serialization API provides means of serializing JavaScript values in a way +that is compatible with the HTML structured clone algorithm.

      +

      The format is backward-compatible (i.e. safe to store to disk). +Equal JavaScript values may result in different serialized output.

      +

      v8.serialize(value)#

      + + +

      Uses a DefaultSerializer to serialize value into a buffer.

      +

      v8.deserialize(buffer)#

      + + +

      Uses a DefaultDeserializer with default options to read a JS value +from a buffer.

      +

      Class: v8.Serializer#

      + +

      new Serializer()#

      +

      Creates a new Serializer object.

      +

      serializer.writeHeader()#

      +

      Writes out a header, which includes the serialization format version.

      +

      serializer.writeValue(value)#

      + +

      Serializes a JavaScript value and adds the serialized representation to the +internal buffer.

      +

      This throws an error if value cannot be serialized.

      +

      serializer.releaseBuffer()#

      + +

      Returns the stored internal buffer. This serializer should not be used once +the buffer is released. Calling this method results in undefined behavior +if a previous write has failed.

      +

      serializer.transferArrayBuffer(id, arrayBuffer)#

      + +

      Marks an ArrayBuffer as having its contents transferred out of band. +Pass the corresponding ArrayBuffer in the deserializing context to +deserializer.transferArrayBuffer().

      +

      serializer.writeUint32(value)#

      + +

      Write a raw 32-bit unsigned integer. +For use inside of a custom serializer._writeHostObject().

      +

      serializer.writeUint64(hi, lo)#

      + +

      Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. +For use inside of a custom serializer._writeHostObject().

      +

      serializer.writeDouble(value)#

      + +

      Write a JS number value. +For use inside of a custom serializer._writeHostObject().

      +

      serializer.writeRawBytes(buffer)#

      + +

      Write raw bytes into the serializer’s internal buffer. The deserializer +will require a way to compute the length of the buffer. +For use inside of a custom serializer._writeHostObject().

      +

      serializer._writeHostObject(object)#

      + +

      This method is called to write some kind of host object, i.e. an object created +by native C++ bindings. If it is not possible to serialize object, a suitable +exception should be thrown.

      +

      This method is not present on the Serializer class itself but can be provided +by subclasses.

      +

      serializer._getDataCloneError(message)#

      + +

      This method is called to generate error objects that will be thrown when an +object can not be cloned.

      +

      This method defaults to the Error constructor and can be overridden on +subclasses.

      +

      serializer._getSharedArrayBufferId(sharedArrayBuffer)#

      + +

      This method is called when the serializer is going to serialize a +SharedArrayBuffer object. It must return an unsigned 32-bit integer ID for +the object, using the same ID if this SharedArrayBuffer has already been +serialized. When deserializing, this ID will be passed to +deserializer.transferArrayBuffer().

      +

      If the object cannot be serialized, an exception should be thrown.

      +

      This method is not present on the Serializer class itself but can be provided +by subclasses.

      +

      serializer._setTreatArrayBufferViewsAsHostObjects(flag)#

      + +

      Indicate whether to treat TypedArray and DataView objects as +host objects, i.e. pass them to serializer._writeHostObject().

      +

      Class: v8.Deserializer#

      + +

      new Deserializer(buffer)#

      + +

      Creates a new Deserializer object.

      +

      deserializer.readHeader()#

      +

      Reads and validates a header (including the format version). +May, for example, reject an invalid or unsupported wire format. In that case, +an Error is thrown.

      +

      deserializer.readValue()#

      +

      Deserializes a JavaScript value from the buffer and returns it.

      +

      deserializer.transferArrayBuffer(id, arrayBuffer)#

      + +

      Marks an ArrayBuffer as having its contents transferred out of band. +Pass the corresponding ArrayBuffer in the serializing context to +serializer.transferArrayBuffer() (or return the id from +serializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).

      +

      deserializer.getWireFormatVersion()#

      + +

      Reads the underlying wire format version. Likely mostly to be useful to +legacy code reading old wire format versions. May not be called before +.readHeader().

      +

      deserializer.readUint32()#

      + +

      Read a raw 32-bit unsigned integer and return it. +For use inside of a custom deserializer._readHostObject().

      +

      deserializer.readUint64()#

      + +

      Read a raw 64-bit unsigned integer and return it as an array [hi, lo] +with two 32-bit unsigned integer entries. +For use inside of a custom deserializer._readHostObject().

      +

      deserializer.readDouble()#

      + +

      Read a JS number value. +For use inside of a custom deserializer._readHostObject().

      +

      deserializer.readRawBytes(length)#

      + +

      Read raw bytes from the deserializer’s internal buffer. The length parameter +must correspond to the length of the buffer that was passed to +serializer.writeRawBytes(). +For use inside of a custom deserializer._readHostObject().

      +

      deserializer._readHostObject()#

      +

      This method is called to read some kind of host object, i.e. an object that is +created by native C++ bindings. If it is not possible to deserialize the data, +a suitable exception should be thrown.

      +

      This method is not present on the Deserializer class itself but can be +provided by subclasses.

      +

      Class: v8.DefaultSerializer#

      + +

      A subclass of Serializer that serializes TypedArray +(in particular Buffer) and DataView objects as host objects, and only +stores the part of their underlying ArrayBuffers that they are referring to.

      +

      Class: v8.DefaultDeserializer#

      + +

      A subclass of Deserializer corresponding to the format written by +DefaultSerializer.

      +

      VM (executing JavaScript)#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/vm.js

      +

      The vm module enables compiling and running code within V8 Virtual +Machine contexts. The vm module is not a security mechanism. Do +not use it to run untrusted code.

      +

      JavaScript code can be compiled and run immediately or +compiled, saved, and run later.

      +

      A common use case is to run the code in a different V8 Context. This means +invoked code has a different global object than the invoking code.

      +

      One can provide the context by contextifying an +object. The invoked code treats any property in the context like a +global variable. Any changes to global variables caused by the invoked +code are reflected in the context object.

      +
      const vm = require('vm');
      +
      +const x = 1;
      +
      +const context = { x: 2 };
      +vm.createContext(context); // Contextify the object.
      +
      +const code = 'x += 40; var y = 17;';
      +// `x` and `y` are global variables in the context.
      +// Initially, x has the value 2 because that is the value of context.x.
      +vm.runInContext(code, context);
      +
      +console.log(context.x); // 42
      +console.log(context.y); // 17
      +
      +console.log(x); // 1; y is not defined.
      +

      Class: vm.Script#

      + +

      Instances of the vm.Script class contain precompiled scripts that can be +executed in specific contexts.

      +

      new vm.Script(code[, options])#

      + +
        +
      • code <string> The JavaScript code to compile.
      • +
      • options <Object> | <string> +
          +
        • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
        • +
        • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
        • +
        • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
        • +
        • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
            +
          • specifier <string> specifier passed to import()
          • +
          • module <vm.Module>
          • +
          • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
          • +
          +
        • +
        +
      • +
      +

      If options is a string, then it specifies the filename.

      +

      Creating a new vm.Script object compiles code but does not run it. The +compiled vm.Script can be run later multiple times. The code is not bound to +any global object; rather, it is bound before each run, just for that run.

      +

      script.createCachedData()#

      + + +

      Creates a code cache that can be used with the Script constructor's +cachedData option. Returns a Buffer. This method may be called at any +time and any number of times.

      +
      const script = new vm.Script(`
      +function add(a, b) {
      +  return a + b;
      +}
      +
      +const x = add(1, 2);
      +`);
      +
      +const cacheWithoutX = script.createCachedData();
      +
      +script.runInThisContext();
      +
      +const cacheWithX = script.createCachedData();
      +

      script.runInContext(contextifiedObject[, options])#

      + +
        +
      • contextifiedObject <Object> A contextified object as returned by the +vm.createContext() method.
      • +
      • options <Object> +
          +
        • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
        • +
        • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
        • +
        +
      • +
      • Returns: <any> the result of the very last statement executed in the script.
      • +
      +

      Runs the compiled code contained by the vm.Script object within the given +contextifiedObject and returns the result. Running code does not have access +to local scope.

      +

      The following example compiles code that increments a global variable, sets +the value of another global variable, then execute the code multiple times. +The globals are contained in the context object.

      +
      const vm = require('vm');
      +
      +const context = {
      +  animal: 'cat',
      +  count: 2
      +};
      +
      +const script = new vm.Script('count += 1; name = "kitty";');
      +
      +vm.createContext(context);
      +for (let i = 0; i < 10; ++i) {
      +  script.runInContext(context);
      +}
      +
      +console.log(context);
      +// Prints: { animal: 'cat', count: 12, name: 'kitty' }
      +

      Using the timeout or breakOnSigint options will result in new event loops +and corresponding threads being started, which have a non-zero performance +overhead.

      +

      script.runInNewContext([contextObject[, options]])#

      + +
        +
      • contextObject <Object> An object that will be contextified. If +undefined, a new object will be created.
      • +
      • options <Object> +
          +
        • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
        • +
        • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
        • +
        • contextName <string> Human-readable name of the newly created context. +Default: 'VM Context i', where i is an ascending numerical index of +the created context.
        • +
        • contextOrigin <string> Origin corresponding to the newly +created context for display purposes. The origin should be formatted like a +URL, but with only the scheme, host, and port (if necessary), like the +value of the url.origin property of a URL object. Most notably, +this string should omit the trailing slash, as that denotes a path. +Default: ''.
        • +
        • contextCodeGeneration <Object> +
            +
          • strings <boolean> If set to false any calls to eval or function +constructors (Function, GeneratorFunction, etc) will throw an +EvalError. Default: true.
          • +
          • wasm <boolean> If set to false any attempt to compile a WebAssembly +module will throw a WebAssembly.CompileError. Default: true.
          • +
          +
        • +
        +
      • +
      • Returns: <any> the result of the very last statement executed in the script.
      • +
      +

      First contextifies the given contextObject, runs the compiled code contained +by the vm.Script object within the created context, and returns the result. +Running code does not have access to local scope.

      +

      The following example compiles code that sets a global variable, then executes +the code multiple times in different contexts. The globals are set on and +contained within each individual context.

      +
      const vm = require('vm');
      +
      +const script = new vm.Script('globalVar = "set"');
      +
      +const contexts = [{}, {}, {}];
      +contexts.forEach((context) => {
      +  script.runInNewContext(context);
      +});
      +
      +console.log(contexts);
      +// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
      +

      script.runInThisContext([options])#

      + +
        +
      • options <Object> +
          +
        • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
        • +
        • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
        • +
        +
      • +
      • Returns: <any> the result of the very last statement executed in the script.
      • +
      +

      Runs the compiled code contained by the vm.Script within the context of the +current global object. Running code does not have access to local scope, but +does have access to the current global object.

      +

      The following example compiles code that increments a global variable then +executes that code multiple times:

      +
      const vm = require('vm');
      +
      +global.globalVar = 0;
      +
      +const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
      +
      +for (let i = 0; i < 1000; ++i) {
      +  script.runInThisContext();
      +}
      +
      +console.log(globalVar);
      +
      +// 1000
      +

      Class: vm.Module#

      + +

      Stability: 1 - Experimental

      +

      This feature is only available with the --experimental-vm-modules command +flag enabled.

      +

      The vm.Module class provides a low-level interface for using +ECMAScript modules in VM contexts. It is the counterpart of the vm.Script +class that closely mirrors Module Records as defined in the ECMAScript +specification.

      +

      Unlike vm.Script however, every vm.Module object is bound to a context from +its creation. Operations on vm.Module objects are intrinsically asynchronous, +in contrast with the synchronous nature of vm.Script objects. The use of +'async' functions can help with manipulating vm.Module objects.

      +

      Using a vm.Module object requires three distinct steps: creation/parsing, +linking, and evaluation. These three steps are illustrated in the following +example.

      +

      This implementation lies at a lower level than the ECMAScript Module +loader. There is also no way to interact with the Loader yet, though +support is planned.

      +
      const vm = require('vm');
      +
      +const contextifiedObject = vm.createContext({ secret: 42 });
      +
      +(async () => {
      +  // Step 1
      +  //
      +  // Create a Module by constructing a new `vm.SourceTextModule` object. This
      +  // parses the provided source text, throwing a `SyntaxError` if anything goes
      +  // wrong. By default, a Module is created in the top context. But here, we
      +  // specify `contextifiedObject` as the context this Module belongs to.
      +  //
      +  // Here, we attempt to obtain the default export from the module "foo", and
      +  // put it into local binding "secret".
      +
      +  const bar = new vm.SourceTextModule(`
      +    import s from 'foo';
      +    s;
      +  `, { context: contextifiedObject });
      +
      +  // Step 2
      +  //
      +  // "Link" the imported dependencies of this Module to it.
      +  //
      +  // The provided linking callback (the "linker") accepts two arguments: the
      +  // parent module (`bar` in this case) and the string that is the specifier of
      +  // the imported module. The callback is expected to return a Module that
      +  // corresponds to the provided specifier, with certain requirements documented
      +  // in `module.link()`.
      +  //
      +  // If linking has not started for the returned Module, the same linker
      +  // callback will be called on the returned Module.
      +  //
      +  // Even top-level Modules without dependencies must be explicitly linked. The
      +  // callback provided would never be called, however.
      +  //
      +  // The link() method returns a Promise that will be resolved when all the
      +  // Promises returned by the linker resolve.
      +  //
      +  // Note: This is a contrived example in that the linker function creates a new
      +  // "foo" module every time it is called. In a full-fledged module system, a
      +  // cache would probably be used to avoid duplicated modules.
      +
      +  async function linker(specifier, referencingModule) {
      +    if (specifier === 'foo') {
      +      return new vm.SourceTextModule(`
      +        // The "secret" variable refers to the global variable we added to
      +        // "contextifiedObject" when creating the context.
      +        export default secret;
      +      `, { context: referencingModule.context });
      +
      +      // Using `contextifiedObject` instead of `referencingModule.context`
      +      // here would work as well.
      +    }
      +    throw new Error(`Unable to resolve dependency: ${specifier}`);
      +  }
      +  await bar.link(linker);
      +
      +  // Step 3
      +  //
      +  // Evaluate the Module. The evaluate() method returns a Promise with a single
      +  // property "result" that contains the result of the very last statement
      +  // executed in the Module. In the case of `bar`, it is `s;`, which refers to
      +  // the default export of the `foo` module, the `secret` we set in the
      +  // beginning to 42.
      +
      +  const { result } = await bar.evaluate();
      +
      +  console.log(result);
      +  // Prints 42.
      +})();
      +

      module.dependencySpecifiers#

      + +

      The specifiers of all dependencies of this module. The returned array is frozen +to disallow any changes to it.

      +

      Corresponds to the [[RequestedModules]] field of Cyclic Module Records in +the ECMAScript specification.

      +

      module.error#

      + +

      If the module.status is 'errored', this property contains the exception +thrown by the module during evaluation. If the status is anything else, +accessing this property will result in a thrown exception.

      +

      The value undefined cannot be used for cases where there is not a thrown +exception due to possible ambiguity with throw undefined;.

      +

      Corresponds to the [[EvaluationError]] field of Cyclic Module Records +in the ECMAScript specification.

      +

      module.evaluate([options])#

      +
        +
      • options <Object> +
          +
        • timeout <integer> Specifies the number of milliseconds to evaluate +before terminating execution. If execution is interrupted, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the event that have +been attached via process.on('SIGINT') will be disabled during script +execution, but will continue to work after that. If execution is +interrupted, an Error will be thrown. Default: false.
        • +
        +
      • +
      • Returns: <Promise>
      • +
      +

      Evaluate the module.

      +

      This must be called after the module has been linked; otherwise it will +throw an error. It could be called also when the module has already been +evaluated, in which case it will do one of the following two things:

      +
        +
      • return undefined if the initial evaluation ended in success (module.status +is 'evaluated')
      • +
      • rethrow the same exception the initial evaluation threw if the initial +evaluation ended in an error (module.status is 'errored')
      • +
      +

      This method cannot be called while the module is being evaluated +(module.status is 'evaluating') to prevent infinite recursion.

      +

      Corresponds to the Evaluate() concrete method field of Cyclic Module +Records in the ECMAScript specification.

      +

      module.link(linker)#

      + +

      Link module dependencies. This method must be called before evaluation, and +can only be called once per module.

      +

      The function is expected to return a Module object or a Promise that +eventually resolves to a Module object. The returned Module must satisfy the +following two invariants:

      +
        +
      • It must belong to the same context as the parent Module.
      • +
      • Its status must not be 'errored'.
      • +
      +

      If the returned Module's status is 'unlinked', this method will be +recursively called on the returned Module with the same provided linker +function.

      +

      link() returns a Promise that will either get resolved when all linking +instances resolve to a valid Module, or rejected if the linker function either +throws an exception or returns an invalid Module.

      +

      The linker function roughly corresponds to the implementation-defined +HostResolveImportedModule abstract operation in the ECMAScript +specification, with a few key differences:

      + +

      The actual HostResolveImportedModule implementation used during module +linking is one that returns the modules linked during linking. Since at +that point all modules would have been fully linked already, the +HostResolveImportedModule implementation is fully synchronous per +specification.

      +

      Corresponds to the Link() concrete method field of Cyclic Module +Records in the ECMAScript specification.

      +

      module.namespace#

      + +

      The namespace object of the module. This is only available after linking +(module.link()) has completed.

      +

      Corresponds to the GetModuleNamespace abstract operation in the ECMAScript +specification.

      +

      module.status#

      + +

      The current status of the module. Will be one of:

      +
        +
      • +

        'unlinked': module.link() has not yet been called.

        +
      • +
      • +

        'linking': module.link() has been called, but not all Promises returned +by the linker function have been resolved yet.

        +
      • +
      • +

        'linked': The module has been linked successfully, and all of its +dependencies are linked, but module.evaluate() has not yet been called.

        +
      • +
      • +

        'evaluating': The module is being evaluated through a module.evaluate() on +itself or a parent module.

        +
      • +
      • +

        'evaluated': The module has been successfully evaluated.

        +
      • +
      • +

        'errored': The module has been evaluated, but an exception was thrown.

        +
      • +
      +

      Other than 'errored', this status string corresponds to the specification's +Cyclic Module Record's [[Status]] field. 'errored' corresponds to +'evaluated' in the specification, but with [[EvaluationError]] set to a +value that is not undefined.

      +

      module.identifier#

      + +

      The identifier of the current module, as set in the constructor.

      +

      Class: vm.SourceTextModule#

      + +

      Stability: 1 - Experimental

      +

      This feature is only available with the --experimental-vm-modules command +flag enabled.

      + +

      The vm.SourceTextModule class provides the Source Text Module Record as +defined in the ECMAScript specification.

      +

      new vm.SourceTextModule(code[, options])#

      +
        +
      • code <string> JavaScript Module code to parse
      • +
      • options +
          +
        • identifier <string> String used in stack traces. +Default: 'vm:module(i)' where i is a context-specific ascending +index.
        • +
        • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. The code must be the same as the module from which this +cachedData was created.
        • +
        • context <Object> The contextified object as returned by the +vm.createContext() method, to compile and evaluate this Module in.
        • +
        • lineOffset <integer> Specifies the line number offset that is displayed +in stack traces produced by this Module. Default: 0.
        • +
        • columnOffset <integer> Specifies the column number offset that is +displayed in stack traces produced by this Module. Default: 0.
        • +
        • initializeImportMeta <Function> Called during evaluation of this Module +to initialize the import.meta. + +
        • +
        • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +
            +
          • specifier <string> specifier passed to import()
          • +
          • module <vm.Module>
          • +
          • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
          • +
          +
        • +
        +
      • +
      +

      Creates a new SourceTextModule instance.

      +

      Properties assigned to the import.meta object that are objects may +allow the module to access information outside the specified context. Use +vm.runInContext() to create objects in a specific context.

      +
      const vm = require('vm');
      +
      +const contextifiedObject = vm.createContext({ secret: 42 });
      +
      +(async () => {
      +  const module = new vm.SourceTextModule(
      +    'Object.getPrototypeOf(import.meta.prop).secret = secret;',
      +    {
      +      initializeImportMeta(meta) {
      +        // Note: this object is created in the top context. As such,
      +        // Object.getPrototypeOf(import.meta.prop) points to the
      +        // Object.prototype in the top context rather than that in
      +        // the contextified object.
      +        meta.prop = {};
      +      }
      +    });
      +  // Since module has no dependencies, the linker function will never be called.
      +  await module.link(() => {});
      +  await module.evaluate();
      +
      +  // Now, Object.prototype.secret will be equal to 42.
      +  //
      +  // To fix this problem, replace
      +  //     meta.prop = {};
      +  // above with
      +  //     meta.prop = vm.runInContext('{}', contextifiedObject);
      +})();
      +

      sourceTextModule.createCachedData()#

      + + +

      Creates a code cache that can be used with the SourceTextModule constructor's +cachedData option. Returns a Buffer. This method may be called any number +of times before the module has been evaluated.

      +
      // Create an initial module
      +const module = new vm.SourceTextModule('const a = 1;');
      +
      +// Create cached data from this module
      +const cachedData = module.createCachedData();
      +
      +// Create a new module using the cached data. The code must be the same.
      +const module2 = new vm.SourceTextModule('const a = 1;', { cachedData });
      +

      Class: vm.SyntheticModule#

      + +

      Stability: 1 - Experimental

      +

      This feature is only available with the --experimental-vm-modules command +flag enabled.

      + +

      The vm.SyntheticModule class provides the Synthetic Module Record as +defined in the WebIDL specification. The purpose of synthetic modules is to +provide a generic interface for exposing non-JavaScript sources to ECMAScript +module graphs.

      +
      const vm = require('vm');
      +
      +const source = '{ "a": 1 }';
      +const module = new vm.SyntheticModule(['default'], function() {
      +  const obj = JSON.parse(source);
      +  this.setExport('default', obj);
      +});
      +
      +// Use `module` in linking...
      +

      new vm.SyntheticModule(exportNames, evaluateCallback[, options])#

      + +
        +
      • exportNames <string[]> Array of names that will be exported from the module.
      • +
      • evaluateCallback <Function> Called when the module is evaluated.
      • +
      • options +
          +
        • identifier <string> String used in stack traces. +Default: 'vm:module(i)' where i is a context-specific ascending +index.
        • +
        • context <Object> The contextified object as returned by the +vm.createContext() method, to compile and evaluate this Module in.
        • +
        +
      • +
      +

      Creates a new SyntheticModule instance.

      +

      Objects assigned to the exports of this instance may allow importers of +the module to access information outside the specified context. Use +vm.runInContext() to create objects in a specific context.

      +

      syntheticModule.setExport(name, value)#

      + +
        +
      • name <string> Name of the export to set.
      • +
      • value <any> The value to set the export to.
      • +
      +

      This method is used after the module is linked to set the values of exports. If +it is called before the module is linked, an ERR_VM_MODULE_STATUS error +will be thrown.

      +
      const vm = require('vm');
      +
      +(async () => {
      +  const m = new vm.SyntheticModule(['x'], () => {
      +    m.setExport('x', 1);
      +  });
      +
      +  await m.link(() => {});
      +  await m.evaluate();
      +
      +  assert.strictEqual(m.namespace.x, 1);
      +})();
      +

      vm.compileFunction(code[, params[, options]])#

      + +
        +
      • code <string> The body of the function to compile.
      • +
      • params <string[]> An array of strings containing all parameters for the +function.
      • +
      • options <Object> +
          +
        • filename <string> Specifies the filename used in stack traces produced +by this script. Default: ''.
        • +
        • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source.
        • +
        • produceCachedData <boolean> Specifies whether to produce new cache data. +Default: false.
        • +
        • parsingContext <Object> The contextified object in which the said +function should be compiled in.
        • +
        • contextExtensions <Object[]> An array containing a collection of context +extensions (objects wrapping the current scope) to be applied while +compiling. Default: [].
        • +
        +
      • +
      • Returns: <Function>
      • +
      +

      Compiles the given code into the provided context (if no context is +supplied, the current context is used), and returns it wrapped inside a +function with the given params.

      +

      vm.createContext([contextObject[, options]])#

      + +
        +
      • contextObject <Object>
      • +
      • options <Object> +
          +
        • name <string> Human-readable name of the newly created context. +Default: 'VM Context i', where i is an ascending numerical index of +the created context.
        • +
        • origin <string> Origin corresponding to the newly created +context for display purposes. The origin should be formatted like a URL, +but with only the scheme, host, and port (if necessary), like the value of +the url.origin property of a URL object. Most notably, this +string should omit the trailing slash, as that denotes a path. +Default: ''.
        • +
        • codeGeneration <Object> +
            +
          • strings <boolean> If set to false any calls to eval or function +constructors (Function, GeneratorFunction, etc) will throw an +EvalError. Default: true.
          • +
          • wasm <boolean> If set to false any attempt to compile a WebAssembly +module will throw a WebAssembly.CompileError. Default: true.
          • +
          +
        • +
        +
      • +
      • Returns: <Object> contextified object.
      • +
      +

      If given a contextObject, the vm.createContext() method will prepare +that object so that it can be used in calls to +vm.runInContext() or script.runInContext(). Inside such scripts, +the contextObject will be the global object, retaining all of its existing +properties but also having the built-in objects and functions any standard +global object has. Outside of scripts run by the vm module, global variables +will remain unchanged.

      +
      const vm = require('vm');
      +
      +global.globalVar = 3;
      +
      +const context = { globalVar: 1 };
      +vm.createContext(context);
      +
      +vm.runInContext('globalVar *= 2;', context);
      +
      +console.log(context);
      +// Prints: { globalVar: 2 }
      +
      +console.log(global.globalVar);
      +// Prints: 3
      +

      If contextObject is omitted (or passed explicitly as undefined), a new, +empty contextified object will be returned.

      +

      The vm.createContext() method is primarily useful for creating a single +context that can be used to run multiple scripts. For instance, if emulating a +web browser, the method can be used to create a single context representing a +window's global object, then run all <script> tags together within that +context.

      +

      The provided name and origin of the context are made visible through the +Inspector API.

      +

      vm.isContext(object)#

      + + +

      Returns true if the given oject object has been contextified using +vm.createContext().

      +

      vm.runInContext(code, contextifiedObject[, options])#

      + +
        +
      • code <string> The JavaScript code to compile and run.
      • +
      • contextifiedObject <Object> The contextified object that will be used +as the global when the code is compiled and run.
      • +
      • options <Object> | <string> +
          +
        • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
        • +
        • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
        • +
        • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
        • +
        • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
        • +
        • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
        • +
        • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
            +
          • specifier <string> specifier passed to import()
          • +
          • module <vm.Module>
          • +
          • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
          • +
          +
        • +
        +
      • +
      • Returns: <any> the result of the very last statement executed in the script.
      • +
      +

      The vm.runInContext() method compiles code, runs it within the context of +the contextifiedObject, then returns the result. Running code does not have +access to the local scope. The contextifiedObject object must have been +previously contextified using the vm.createContext() method.

      +

      If options is a string, then it specifies the filename.

      +

      The following example compiles and executes different scripts using a single +contextified object:

      +
      const vm = require('vm');
      +
      +const contextObject = { globalVar: 1 };
      +vm.createContext(contextObject);
      +
      +for (let i = 0; i < 10; ++i) {
      +  vm.runInContext('globalVar *= 2;', contextObject);
      +}
      +console.log(contextObject);
      +// Prints: { globalVar: 1024 }
      +

      vm.runInNewContext(code[, contextObject[, options]])#

      + +
        +
      • code <string> The JavaScript code to compile and run.
      • +
      • contextObject <Object> An object that will be contextified. If +undefined, a new object will be created.
      • +
      • options <Object> | <string> +
          +
        • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
        • +
        • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
        • +
        • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
        • +
        • contextName <string> Human-readable name of the newly created context. +Default: 'VM Context i', where i is an ascending numerical index of +the created context.
        • +
        • contextOrigin <string> Origin corresponding to the newly +created context for display purposes. The origin should be formatted like a +URL, but with only the scheme, host, and port (if necessary), like the +value of the url.origin property of a URL object. Most notably, +this string should omit the trailing slash, as that denotes a path. +Default: ''.
        • +
        • contextCodeGeneration <Object> +
            +
          • strings <boolean> If set to false any calls to eval or function +constructors (Function, GeneratorFunction, etc) will throw an +EvalError. Default: true.
          • +
          • wasm <boolean> If set to false any attempt to compile a WebAssembly +module will throw a WebAssembly.CompileError. Default: true.
          • +
          +
        • +
        • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
        • +
        • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
        • +
        • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
            +
          • specifier <string> specifier passed to import()
          • +
          • module <vm.Module>
          • +
          • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
          • +
          +
        • +
        +
      • +
      • Returns: <any> the result of the very last statement executed in the script.
      • +
      +

      The vm.runInNewContext() first contextifies the given contextObject (or +creates a new contextObject if passed as undefined), compiles the code, +runs it within the created context, then returns the result. Running code +does not have access to the local scope.

      +

      If options is a string, then it specifies the filename.

      +

      The following example compiles and executes code that increments a global +variable and sets a new one. These globals are contained in the contextObject.

      +
      const vm = require('vm');
      +
      +const contextObject = {
      +  animal: 'cat',
      +  count: 2
      +};
      +
      +vm.runInNewContext('count += 1; name = "kitty"', contextObject);
      +console.log(contextObject);
      +// Prints: { animal: 'cat', count: 3, name: 'kitty' }
      +

      vm.runInThisContext(code[, options])#

      + +
        +
      • code <string> The JavaScript code to compile and run.
      • +
      • options <Object> | <string> +
          +
        • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
        • +
        • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
        • +
        • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
        • +
        • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
        • +
        • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
        • +
        • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
        • +
        • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
        • +
        • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
            +
          • specifier <string> specifier passed to import()
          • +
          • module <vm.Module>
          • +
          • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
          • +
          +
        • +
        +
      • +
      • Returns: <any> the result of the very last statement executed in the script.
      • +
      +

      vm.runInThisContext() compiles code, runs it within the context of the +current global and returns the result. Running code does not have access to +local scope, but does have access to the current global object.

      +

      If options is a string, then it specifies the filename.

      +

      The following example illustrates using both vm.runInThisContext() and +the JavaScript eval() function to run the same code:

      + +
      const vm = require('vm');
      +let localVar = 'initial value';
      +
      +const vmResult = vm.runInThisContext('localVar = "vm";');
      +console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);
      +// Prints: vmResult: 'vm', localVar: 'initial value'
      +
      +const evalResult = eval('localVar = "eval";');
      +console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);
      +// Prints: evalResult: 'eval', localVar: 'eval'
      +

      Because vm.runInThisContext() does not have access to the local scope, +localVar is unchanged. In contrast, eval() does have access to the +local scope, so the value localVar is changed. In this way +vm.runInThisContext() is much like an indirect eval() call, e.g. +(0,eval)('code').

      +

      Example: Running an HTTP server within a VM#

      +

      When using either script.runInThisContext() or +vm.runInThisContext(), the code is executed within the current V8 global +context. The code passed to this VM context will have its own isolated scope.

      +

      In order to run a simple web server using the http module the code passed to +the context must either call require('http') on its own, or have a reference +to the http module passed to it. For instance:

      +
      'use strict';
      +const vm = require('vm');
      +
      +const code = `
      +((require) => {
      +  const http = require('http');
      +
      +  http.createServer((request, response) => {
      +    response.writeHead(200, { 'Content-Type': 'text/plain' });
      +    response.end('Hello World\\n');
      +  }).listen(8124);
      +
      +  console.log('Server running at http://127.0.0.1:8124/');
      +})`;
      +
      +vm.runInThisContext(code)(require);
      +

      The require() in the above case shares the state with the context it is +passed from. This may introduce risks when untrusted code is executed, e.g. +altering objects in the context in unwanted ways.

      +

      What does it mean to "contextify" an object?#

      +

      All JavaScript executed within Node.js runs within the scope of a "context". +According to the V8 Embedder's Guide:

      +
      +

      In V8, a context is an execution environment that allows separate, unrelated, +JavaScript applications to run in a single instance of V8. You must explicitly +specify the context in which you want any JavaScript code to be run.

      +
      +

      When the method vm.createContext() is called, the contextObject argument +(or a newly-created object if contextObject is undefined) is associated +internally with a new instance of a V8 Context. This V8 Context provides the +code run using the vm module's methods with an isolated global environment +within which it can operate. The process of creating the V8 Context and +associating it with the contextObject is what this document refers to as +"contextifying" the object.

      +

      Timeout limitations when using process.nextTick(), promises, and queueMicrotask()#

      +

      Because of the internal mechanics of how the process.nextTick() queue and +the microtask queue that underlies Promises are implemented within V8 and +Node.js, it is possible for code running within a context to "escape" the +timeout set using vm.runInContext(), vm.runInNewContext(), and +vm.runInThisContext().

      +

      For example, the following code executed by vm.runInNewContext() with a +timeout of 5 milliseconds schedules an infinite loop to run after a promise +resolves. The scheduled loop is never interrupted by the timeout:

      +
      const vm = require('vm');
      +
      +function loop() {
      +  while (1) console.log(Date.now());
      +}
      +
      +vm.runInNewContext(
      +  'Promise.resolve().then(loop);',
      +  { loop, console },
      +  { timeout: 5 }
      +);
      +

      This issue also occurs when the loop() call is scheduled using +the process.nextTick() and queueMicrotask() functions.

      +

      This issue occurs because all contexts share the same microtask and nextTick +queues.

      +

      WebAssembly System Interface (WASI)#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/wasi.js

      +

      The WASI API provides an implementation of the WebAssembly System Interface +specification. WASI gives sandboxed WebAssembly applications access to the +underlying operating system via a collection of POSIX-like functions.

      +
      'use strict';
      +const fs = require('fs');
      +const { WASI } = require('wasi');
      +const wasi = new WASI({
      +  args: process.argv,
      +  env: process.env,
      +  preopens: {
      +    '/sandbox': '/some/real/path/that/wasm/can/access'
      +  }
      +});
      +const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
      +
      +(async () => {
      +  const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
      +  const instance = await WebAssembly.instantiate(wasm, importObject);
      +
      +  wasi.start(instance);
      +})();
      +

      To run the above example, create a new WebAssembly text format file named +demo.wat:

      +
      (module
      +    ;; Import the required fd_write WASI function which will write the given io vectors to stdout
      +    ;; The function signature for fd_write is:
      +    ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
      +    (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
      +
      +    (memory 1)
      +    (export "memory" (memory 0))
      +
      +    ;; Write 'hello world\n' to memory at an offset of 8 bytes
      +    ;; Note the trailing newline which is required for the text to appear
      +    (data (i32.const 8) "hello world\n")
      +
      +    (func $main (export "_start")
      +        ;; Creating a new io vector within linear memory
      +        (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
      +        (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\n' string
      +
      +        (call $fd_write
      +            (i32.const 1) ;; file_descriptor - 1 for stdout
      +            (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
      +            (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
      +            (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
      +        )
      +        drop ;; Discard the number of bytes written from the top of the stack
      +    )
      +)
      +

      Use wabt to compile .wat to .wasm

      +
      $ wat2wasm demo.wat
      +

      The --experimental-wasi-unstable-preview1 and --experimental-wasm-bigint +CLI arguments are needed for this example to run.

      +

      Class: WASI#

      + +

      The WASI class provides the WASI system call API and additional convenience +methods for working with WASI-based applications. Each WASI instance +represents a distinct sandbox environment. For security purposes, each WASI +instance must have its command line arguments, environment variables, and +sandbox directory structure configured explicitly.

      +

      new WASI([options])#

      + +
        +
      • options <Object> +
          +
        • args <Array> An array of strings that the WebAssembly application will +see as command line arguments. The first argument is the virtual path to the +WASI command itself. Default: [].
        • +
        • env <Object> An object similar to process.env that the WebAssembly +application will see as its environment. Default: {}.
        • +
        • preopens <Object> This object represents the WebAssembly application's +sandbox directory structure. The string keys of preopens are treated as +directories within the sandbox. The corresponding values in preopens are +the real paths to those directories on the host machine.
        • +
        • returnOnExit <boolean> By default, WASI applications terminate the Node.js +process via the __wasi_proc_exit() function. Setting this option to true +causes wasi.start() to return the exit code rather than terminate the +process. Default: false.
        • +
        • stdin <integer> The file descriptor used as standard input in the +WebAssembly application. Default: 0.
        • +
        • stdout <integer> The file descriptor used as standard output in the +WebAssembly application. Default: 1.
        • +
        • stderr <integer> The file descriptor used as standard error in the +WebAssembly application. Default: 2.
        • +
        +
      • +
      +

      wasi.start(instance)#

      + + +

      Attempt to begin execution of instance as a WASI command by invoking its +_start() export. If instance does not contain a _start() export, or if +instance contains an _initialize() export, then an exception is thrown.

      +

      start() requires that instance exports a WebAssembly.Memory named +memory. If instance does not have a memory export an exception is thrown.

      +

      If start() is called more than once, an exception is thrown.

      +

      wasi.initialize(instance)#

      + + +

      Attempt to initialize instance as a WASI reactor by invoking its +_initialize() export, if it is present. If instance contains a _start() +export, then an exception is thrown.

      +

      initialize() requires that instance exports a WebAssembly.Memory named +memory. If instance does not have a memory export an exception is thrown.

      +

      If initialize() is called more than once, an exception is thrown.

      +

      wasi.wasiImport#

      + + +

      wasiImport is an object that implements the WASI system call API. This object +should be passed as the wasi_snapshot_preview1 import during the instantiation +of a WebAssembly.Instance.

      +

      Worker threads#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/worker_threads.js

      +

      The worker_threads module enables the use of threads that execute JavaScript +in parallel. To access it:

      +
      const worker = require('worker_threads');
      +

      Workers (threads) are useful for performing CPU-intensive JavaScript operations. +They will not help much with I/O-intensive work. Node.js’s built-in asynchronous +I/O operations are more efficient than Workers can be.

      +

      Unlike child_process or cluster, worker_threads can share memory. They do +so by transferring ArrayBuffer instances or sharing SharedArrayBuffer +instances.

      +
      const {
      +  Worker, isMainThread, parentPort, workerData
      +} = require('worker_threads');
      +
      +if (isMainThread) {
      +  module.exports = function parseJSAsync(script) {
      +    return new Promise((resolve, reject) => {
      +      const worker = new Worker(__filename, {
      +        workerData: script
      +      });
      +      worker.on('message', resolve);
      +      worker.on('error', reject);
      +      worker.on('exit', (code) => {
      +        if (code !== 0)
      +          reject(new Error(`Worker stopped with exit code ${code}`));
      +      });
      +    });
      +  };
      +} else {
      +  const { parse } = require('some-js-parsing-library');
      +  const script = workerData;
      +  parentPort.postMessage(parse(script));
      +}
      +

      The above example spawns a Worker thread for each parse() call. In actual +practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the +overhead of creating Workers would likely exceed their benefit.

      +

      When implementing a worker pool, use the AsyncResource API to inform +diagnostic tools (e.g. in order to provide asynchronous stack traces) about the +correlation between tasks and their outcomes. See +"Using AsyncResource for a Worker thread pool" +in the async_hooks documentation for an example implementation.

      +

      Worker threads inherit non-process-specific options by default. Refer to +Worker constructor options to know how to customize worker thread options, +specifically argv and execArgv options.

      +

      worker.isMainThread#

      + + +

      Is true if this code is not running inside of a Worker thread.

      +
      const { Worker, isMainThread } = require('worker_threads');
      +
      +if (isMainThread) {
      +  // This re-loads the current file inside a Worker instance.
      +  new Worker(__filename);
      +} else {
      +  console.log('Inside Worker!');
      +  console.log(isMainThread);  // Prints 'false'.
      +}
      +

      worker.markAsUntransferable(object)#

      + +

      Mark an object as not transferable. If object occurs in the transfer list of +a port.postMessage() call, it will be ignored.

      +

      In particular, this makes sense for objects that can be cloned, rather than +transferred, and which are used by other objects on the sending side. +For example, Node.js marks the ArrayBuffers it uses for its +Buffer pool with this.

      +

      This operation cannot be undone.

      +
      const { MessageChannel, markAsUntransferable } = require('worker_threads');
      +
      +const pooledBuffer = new ArrayBuffer(8);
      +const typedArray1 = new Uint8Array(pooledBuffer);
      +const typedArray2 = new Float64Array(pooledBuffer);
      +
      +markAsUntransferable(pooledBuffer);
      +
      +const { port1 } = new MessageChannel();
      +port1.postMessage(typedArray1, [ typedArray1.buffer ]);
      +
      +// The following line prints the contents of typedArray1 -- it still owns
      +// its memory and has been cloned, not transferred. Without
      +// `markAsUntransferable()`, this would print an empty Uint8Array.
      +// typedArray2 is intact as well.
      +console.log(typedArray1);
      +console.log(typedArray2);
      +

      There is no equivalent to this API in browsers.

      +

      worker.moveMessagePortToContext(port, contextifiedSandbox)#

      + + +

      Transfer a MessagePort to a different vm Context. The original port +object will be rendered unusable, and the returned MessagePort instance will +take its place.

      +

      The returned MessagePort will be an object in the target context, and will +inherit from its global Object class. Objects passed to the +port.onmessage() listener will also be created in the target context +and inherit from its global Object class.

      +

      However, the created MessagePort will no longer inherit from +EventEmitter, and only port.onmessage() can be used to receive +events using it.

      +

      worker.parentPort#

      + + +

      If this thread was spawned as a Worker, this will be a MessagePort +allowing communication with the parent thread. Messages sent using +parentPort.postMessage() will be available in the parent thread +using worker.on('message'), and messages sent from the parent thread +using worker.postMessage() will be available in this thread using +parentPort.on('message').

      +
      const { Worker, isMainThread, parentPort } = require('worker_threads');
      +
      +if (isMainThread) {
      +  const worker = new Worker(__filename);
      +  worker.once('message', (message) => {
      +    console.log(message);  // Prints 'Hello, world!'.
      +  });
      +  worker.postMessage('Hello, world!');
      +} else {
      +  // When a message from the parent thread is received, send it back:
      +  parentPort.once('message', (message) => {
      +    parentPort.postMessage(message);
      +  });
      +}
      +

      worker.receiveMessageOnPort(port)#

      + + +

      Receive a single message from a given MessagePort. If no message is available, +undefined is returned, otherwise an object with a single message property +that contains the message payload, corresponding to the oldest message in the +MessagePort’s queue.

      +
      const { MessageChannel, receiveMessageOnPort } = require('worker_threads');
      +const { port1, port2 } = new MessageChannel();
      +port1.postMessage({ hello: 'world' });
      +
      +console.log(receiveMessageOnPort(port2));
      +// Prints: { message: { hello: 'world' } }
      +console.log(receiveMessageOnPort(port2));
      +// Prints: undefined
      +

      When this function is used, no 'message' event will be emitted and the +onmessage listener will not be invoked.

      +

      worker.resourceLimits#

      + + +

      Provides the set of JS engine resource constraints inside this Worker thread. +If the resourceLimits option was passed to the Worker constructor, +this matches its values.

      +

      If this is used in the main thread, its value is an empty object.

      +

      worker.SHARE_ENV#

      + + +

      A special value that can be passed as the env option of the Worker +constructor, to indicate that the current thread and the Worker thread should +share read and write access to the same set of environment variables.

      +
      const { Worker, SHARE_ENV } = require('worker_threads');
      +new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
      +  .on('exit', () => {
      +    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.
      +  });
      +

      worker.threadId#

      + + +

      An integer identifier for the current thread. On the corresponding worker object +(if there is any), it is available as worker.threadId. +This value is unique for each Worker instance inside a single process.

      +

      worker.workerData#

      + +

      An arbitrary JavaScript value that contains a clone of the data passed +to this thread’s Worker constructor.

      +

      The data is cloned as if using postMessage(), +according to the HTML structured clone algorithm.

      +
      const { Worker, isMainThread, workerData } = require('worker_threads');
      +
      +if (isMainThread) {
      +  const worker = new Worker(__filename, { workerData: 'Hello, world!' });
      +} else {
      +  console.log(workerData);  // Prints 'Hello, world!'.
      +}
      +

      Class: MessageChannel#

      + +

      Instances of the worker.MessageChannel class represent an asynchronous, +two-way communications channel. +The MessageChannel has no methods of its own. new MessageChannel() +yields an object with port1 and port2 properties, which refer to linked +MessagePort instances.

      +
      const { MessageChannel } = require('worker_threads');
      +
      +const { port1, port2 } = new MessageChannel();
      +port1.on('message', (message) => console.log('received', message));
      +port2.postMessage({ foo: 'bar' });
      +// Prints: received { foo: 'bar' } from the `port1.on('message')` listener
      +

      Class: MessagePort#

      + + +

      Instances of the worker.MessagePort class represent one end of an +asynchronous, two-way communications channel. It can be used to transfer +structured data, memory regions and other MessagePorts between different +Workers.

      +

      With the exception of MessagePorts being EventEmitters rather +than EventTargets, this implementation matches browser MessagePorts.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted once either side of the channel has been +disconnected.

      +
      const { MessageChannel } = require('worker_threads');
      +const { port1, port2 } = new MessageChannel();
      +
      +// Prints:
      +//   foobar
      +//   closed!
      +port2.on('message', (message) => console.log(message));
      +port2.on('close', () => console.log('closed!'));
      +
      +port1.postMessage('foobar');
      +port1.close();
      +

      Event: 'message'#

      + +
        +
      • value <any> The transmitted value
      • +
      +

      The 'message' event is emitted for any incoming message, containing the cloned +input of port.postMessage().

      +

      Listeners on this event will receive a clone of the value parameter as passed +to postMessage() and no further arguments.

      +

      Event: 'messageerror'#

      + + +

      The 'messageerror' event is emitted when deserializing a message failed.

      +

      port.close()#

      + +

      Disables further sending of messages on either side of the connection. +This method can be called when no further communication will happen over this +MessagePort.

      +

      The 'close' event will be emitted on both MessagePort instances that +are part of the channel.

      +

      port.postMessage(value[, transferList])#

      + + +

      Sends a JavaScript value to the receiving side of this channel. +value will be transferred in a way which is compatible with +the HTML structured clone algorithm.

      +

      In particular, the significant differences to JSON are:

      +
        +
      • value may contain circular references.
      • +
      • value may contain instances of builtin JS types such as RegExps, +BigInts, Maps, Sets, etc.
      • +
      • value may contain typed arrays, both using ArrayBuffers +and SharedArrayBuffers.
      • +
      • value may contain WebAssembly.Module instances.
      • +
      • value may not contain native (C++-backed) objects other than MessagePorts, +FileHandles, and KeyObjects.
      • +
      +
      const { MessageChannel } = require('worker_threads');
      +const { port1, port2 } = new MessageChannel();
      +
      +port1.on('message', (message) => console.log(message));
      +
      +const circularData = {};
      +circularData.foo = circularData;
      +// Prints: { foo: [Circular] }
      +port2.postMessage(circularData);
      +

      transferList may be a list of ArrayBuffer, MessagePort and +FileHandle objects. +After transferring, they will not be usable on the sending side of the channel +anymore (even if they are not contained in value). Unlike with +child processes, transferring handles such as network sockets is currently +not supported.

      +

      If value contains SharedArrayBuffer instances, those will be accessible +from either thread. They cannot be listed in transferList.

      +

      value may still contain ArrayBuffer instances that are not in +transferList; in that case, the underlying memory is copied rather than moved.

      +
      const { MessageChannel } = require('worker_threads');
      +const { port1, port2 } = new MessageChannel();
      +
      +port1.on('message', (message) => console.log(message));
      +
      +const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
      +// This posts a copy of `uint8Array`:
      +port2.postMessage(uint8Array);
      +// This does not copy data, but renders `uint8Array` unusable:
      +port2.postMessage(uint8Array, [ uint8Array.buffer ]);
      +
      +// The memory for the `sharedUint8Array` will be accessible from both the
      +// original and the copy received by `.on('message')`:
      +const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
      +port2.postMessage(sharedUint8Array);
      +
      +// This transfers a freshly created message port to the receiver.
      +// This can be used, for example, to create communication channels between
      +// multiple `Worker` threads that are children of the same parent thread.
      +const otherChannel = new MessageChannel();
      +port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
      +

      Because the object cloning uses the structured clone algorithm, +non-enumerable properties, property accessors, and object prototypes are +not preserved. In particular, Buffer objects will be read as +plain Uint8Arrays on the receiving side.

      +

      The message object will be cloned immediately, and can be modified after +posting without having side effects.

      +

      For more information on the serialization and deserialization mechanisms +behind this API, see the serialization API of the v8 module.

      +

      Considerations when transferring TypedArrays and Buffers#

      +

      All TypedArray and Buffer instances are views over an underlying +ArrayBuffer. That is, it is the ArrayBuffer that actually stores +the raw data while the TypedArray and Buffer objects provide a +way of viewing and manipulating the data. It is possible and common +for multiple views to be created over the same ArrayBuffer instance. +Great care must be taken when using a transfer list to transfer an +ArrayBuffer as doing so will cause all TypedArray and Buffer +instances that share that same ArrayBuffer to become unusable.

      +
      const ab = new ArrayBuffer(10);
      +
      +const u1 = new Uint8Array(ab);
      +const u2 = new Uint16Array(ab);
      +
      +console.log(u2.length);  // prints 5
      +
      +port.postMessage(u1, [u1.buffer]);
      +
      +console.log(u2.length);  // prints 0
      +

      For Buffer instances, specifically, whether the underlying +ArrayBuffer can be transferred or cloned depends entirely on how +instances were created, which often cannot be reliably determined.

      +

      An ArrayBuffer can be marked with markAsUntransferable() to indicate +that it should always be cloned and never transferred.

      +

      Depending on how a Buffer instance was created, it may or may +not own its underlying ArrayBuffer. An ArrayBuffer must not +be transferred unless it is known that the Buffer instance +owns it. In particular, for Buffers created from the internal +Buffer pool (using, for instance Buffer.from() or Buffer.alloc()), +transferring them is not possible and they will always be cloned, +which sends a copy of the entire Buffer pool. +This behavior may come with unintended higher memory +usage and possible security concerns.

      +

      See Buffer.allocUnsafe() for more details on Buffer pooling.

      +

      The ArrayBuffers for Buffer instances created using +Buffer.alloc() or Buffer.allocUnsafeSlow() can always be +transferred but doing so will render all other existing views of +those ArrayBuffers unusable.

      +

      port.ref()#

      + +

      Opposite of unref(). Calling ref() on a previously unref()ed port will +not let the program exit if it's the only active handle left (the default +behavior). If the port is ref()ed, calling ref() again will have no effect.

      +

      If listeners are attached or removed using .on('message'), the port will +be ref()ed and unref()ed automatically depending on whether +listeners for the event exist.

      +

      port.start()#

      + +

      Starts receiving messages on this MessagePort. When using this port +as an event emitter, this will be called automatically once 'message' +listeners are attached.

      +

      This method exists for parity with the Web MessagePort API. In Node.js, +it is only useful for ignoring messages when no event listener is present. +Node.js also diverges in its handling of .onmessage. Setting it will +automatically call .start(), but unsetting it will let messages queue up +until a new handler is set or the port is discarded.

      +

      port.unref()#

      + +

      Calling unref() on a port will allow the thread to exit if this is the only +active handle in the event system. If the port is already unref()ed calling +unref() again will have no effect.

      +

      If listeners are attached or removed using .on('message'), the port will +be ref()ed and unref()ed automatically depending on whether +listeners for the event exist.

      +

      Class: Worker#

      + + +

      The Worker class represents an independent JavaScript execution thread. +Most Node.js APIs are available inside of it.

      +

      Notable differences inside a Worker environment are:

      + +

      Creating Worker instances inside of other Workers is possible.

      +

      Like Web Workers and the cluster module, two-way communication can be +achieved through inter-thread message passing. Internally, a Worker has a +built-in pair of MessagePorts that are already associated with each other +when the Worker is created. While the MessagePort object on the parent side +is not directly exposed, its functionalities are exposed through +worker.postMessage() and the worker.on('message') event +on the Worker object for the parent thread.

      +

      To create custom messaging channels (which is encouraged over using the default +global channel because it facilitates separation of concerns), users can create +a MessageChannel object on either thread and pass one of the +MessagePorts on that MessageChannel to the other thread through a +pre-existing channel, such as the global one.

      +

      See port.postMessage() for more information on how messages are passed, +and what kind of JavaScript values can be successfully transported through +the thread barrier.

      +
      const assert = require('assert');
      +const {
      +  Worker, MessageChannel, MessagePort, isMainThread, parentPort
      +} = require('worker_threads');
      +if (isMainThread) {
      +  const worker = new Worker(__filename);
      +  const subChannel = new MessageChannel();
      +  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
      +  subChannel.port2.on('message', (value) => {
      +    console.log('received:', value);
      +  });
      +} else {
      +  parentPort.once('message', (value) => {
      +    assert(value.hereIsYourPort instanceof MessagePort);
      +    value.hereIsYourPort.postMessage('the worker is sending this');
      +    value.hereIsYourPort.close();
      +  });
      +}
      +

      new Worker(filename[, options])#

      + +
        +
      • filename <string> | <URL> The path to the Worker’s main script or module. Must +be either an absolute path or a relative path (i.e. relative to the +current working directory) starting with ./ or ../, or a WHATWG URL +object using file: protocol. +If options.eval is true, this is a string containing JavaScript code +rather than a path.
      • +
      • options <Object> +
          +
        • argv <any[]> List of arguments which would be stringified and appended to +process.argv in the worker. This is mostly similar to the workerData +but the values will be available on the global process.argv as if they +were passed as CLI options to the script.
        • +
        • env <Object> If set, specifies the initial value of process.env inside +the Worker thread. As a special value, worker.SHARE_ENV may be used +to specify that the parent thread and the child thread should share their +environment variables; in that case, changes to one thread’s process.env +object will affect the other thread as well. Default: process.env.
        • +
        • eval <boolean> If true and the first argument is a string, interpret +the first argument to the constructor as a script that is executed once the +worker is online.
        • +
        • execArgv <string[]> List of node CLI options passed to the worker. +V8 options (such as --max-old-space-size) and options that affect the +process (such as --title) are not supported. If set, this will be provided +as process.execArgv inside the worker. By default, options will be +inherited from the parent thread.
        • +
        • stdin <boolean> If this is set to true, then worker.stdin will +provide a writable stream whose contents will appear as process.stdin +inside the Worker. By default, no data is provided.
        • +
        • stdout <boolean> If this is set to true, then worker.stdout will +not automatically be piped through to process.stdout in the parent.
        • +
        • stderr <boolean> If this is set to true, then worker.stderr will +not automatically be piped through to process.stderr in the parent.
        • +
        • workerData <any> Any JavaScript value that will be cloned and made +available as require('worker_threads').workerData. The cloning will +occur as described in the HTML structured clone algorithm, and an error +will be thrown if the object cannot be cloned (e.g. because it contains +functions).
        • +
        • trackUnmanagedFds <boolean> If this is set to true, then the Worker will +track raw file descriptors managed through fs.open() and +fs.close(), and close them when the Worker exits, similar to other +resources like network sockets or file descriptors managed through +the FileHandle API. This option is automatically inherited by all +nested Workers. Default: false.
        • +
        • transferList <Object[]> If one or more MessagePort-like objects +are passed in workerData, a transferList is required for those +items or ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST will be thrown. +See port.postMessage() for more information.
        • +
        • resourceLimits <Object> An optional set of resource limits for the new +JS engine instance. Reaching these limits will lead to termination of the +Worker instance. These limits only affect the JS engine, and no external +data, including no ArrayBuffers. Even if these limits are set, the process +may still abort if it encounters a global out-of-memory situation. +
            +
          • maxOldGenerationSizeMb <number> The maximum size of the main heap in MB.
          • +
          • maxYoungGenerationSizeMb <number> The maximum size of a heap space for +recently created objects.
          • +
          • codeRangeSizeMb <number> The size of a pre-allocated memory range +used for generated code.
          • +
          • stackSizeMb <number> The default maximum stack size for the thread. +Small values may lead to unusable Worker instances. Default: 4.
          • +
          +
        • +
        +
      • +
      +

      Event: 'error'#

      + + +

      The 'error' event is emitted if the worker thread throws an uncaught +exception. In that case, the worker will be terminated.

      +

      Event: 'exit'#

      + + +

      The 'exit' event is emitted once the worker has stopped. If the worker +exited by calling process.exit(), the exitCode parameter will be the +passed exit code. If the worker was terminated, the exitCode parameter will +be 1.

      +

      This is the final event emitted by any Worker instance.

      +

      Event: 'message'#

      + +
        +
      • value <any> The transmitted value
      • +
      +

      The 'message' event is emitted when the worker thread has invoked +require('worker_threads').parentPort.postMessage(). +See the port.on('message') event for more details.

      +

      All messages sent from the worker thread will be emitted before the +'exit' event is emitted on the Worker object.

      +

      Event: 'messageerror'#

      + + +

      The 'messageerror' event is emitted when deserializing a message failed.

      +

      Event: 'online'#

      + +

      The 'online' event is emitted when the worker thread has started executing +JavaScript code.

      +

      worker.getHeapSnapshot()#

      + +
        +
      • Returns: <Promise> A promise for a Readable Stream containing +a V8 heap snapshot
      • +
      +

      Returns a readable stream for a V8 snapshot of the current state of the Worker. +See v8.getHeapSnapshot() for more details.

      +

      If the Worker thread is no longer running, which may occur before the +'exit' event is emitted, the returned Promise will be rejected +immediately with an ERR_WORKER_NOT_RUNNING error.

      +

      worker.performance#

      + +

      An object that can be used to query performance information from a worker +instance. Similar to perf_hooks.performance.

      +

      performance.eventLoopUtilization([utilization1[, utilization2]])#

      + +
        +
      • utilization1 <Object> The result of a previous call to + eventLoopUtilization().
      • +
      • utilization2 <Object> The result of a previous call to + eventLoopUtilization() prior to utilization1.
      • +
      • Returns <Object> + +
      • +
      +

      The same call as perf_hooks eventLoopUtilization(), except the values +of the worker instance are returned.

      +

      One difference is that, unlike the main thread, bootstrapping within a worker +is done within the event loop. So the event loop utilization will be +immediately available once the worker's script begins execution.

      +

      An idle time that does not increase does not indicate that the worker is +stuck in bootstrap. The following examples shows how the worker's entire +lifetime will never accumulate any idle time, but is still be able to process +messages.

      +
      const { Worker, isMainThread, parentPort } = require('worker_threads');
      +
      +if (isMainThread) {
      +  const worker = new Worker(__filename);
      +  setInterval(() => {
      +    worker.postMessage('hi');
      +    console.log(worker.performance.eventLoopUtilization());
      +  }, 100).unref();
      +  return;
      +}
      +
      +parentPort.on('message', () => console.log('msg')).unref();
      +(function r(n) {
      +  if (--n < 0) return;
      +  const t = Date.now();
      +  while (Date.now() - t < 300);
      +  setImmediate(r, n);
      +})(10);
      +

      The event loop utilization of a worker is available only after the 'online' +event emitted, and if called before this, or after the 'exit' +event, then all properties have the value of 0.

      +

      worker.postMessage(value[, transferList])#

      + + +

      Send a message to the worker that will be received via +require('worker_threads').parentPort.on('message'). +See port.postMessage() for more details.

      +

      worker.ref()#

      + +

      Opposite of unref(), calling ref() on a previously unref()ed worker will +not let the program exit if it's the only active handle left (the default +behavior). If the worker is ref()ed, calling ref() again will have +no effect.

      +

      worker.resourceLimits#

      + + +

      Provides the set of JS engine resource constraints for this Worker thread. +If the resourceLimits option was passed to the Worker constructor, +this matches its values.

      +

      If the worker has stopped, the return value is an empty object.

      +

      worker.stderr#

      + + +

      This is a readable stream which contains data written to process.stderr +inside the worker thread. If stderr: true was not passed to the +Worker constructor, then data will be piped to the parent thread's +process.stderr stream.

      +

      worker.stdin#

      + + +

      If stdin: true was passed to the Worker constructor, this is a +writable stream. The data written to this stream will be made available in +the worker thread as process.stdin.

      +

      worker.stdout#

      + + +

      This is a readable stream which contains data written to process.stdout +inside the worker thread. If stdout: true was not passed to the +Worker constructor, then data will be piped to the parent thread's +process.stdout stream.

      +

      worker.terminate()#

      + + +

      Stop all JavaScript execution in the worker thread as soon as possible. +Returns a Promise for the exit code that is fulfilled when the +'exit' event is emitted.

      +

      worker.threadId#

      + + +

      An integer identifier for the referenced thread. Inside the worker thread, +it is available as require('worker_threads').threadId. +This value is unique for each Worker instance inside a single process.

      +

      worker.unref()#

      + +

      Calling unref() on a worker will allow the thread to exit if this is the only +active handle in the event system. If the worker is already unref()ed calling +unref() again will have no effect.

      +

      Zlib#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/zlib.js

      +

      The zlib module provides compression functionality implemented using Gzip, +Deflate/Inflate, and Brotli.

      +

      To access it:

      +
      const zlib = require('zlib');
      +

      Compression and decompression are built around the Node.js Streams API.

      +

      Compressing or decompressing a stream (such as a file) can be accomplished by +piping the source stream through a zlib Transform stream into a destination +stream:

      +
      const { createGzip } = require('zlib');
      +const { pipeline } = require('stream');
      +const {
      +  createReadStream,
      +  createWriteStream
      +} = require('fs');
      +
      +const gzip = createGzip();
      +const source = createReadStream('input.txt');
      +const destination = createWriteStream('input.txt.gz');
      +
      +pipeline(source, gzip, destination, (err) => {
      +  if (err) {
      +    console.error('An error occurred:', err);
      +    process.exitCode = 1;
      +  }
      +});
      +
      +// Or, Promisified
      +
      +const { promisify } = require('util');
      +const pipe = promisify(pipeline);
      +
      +async function do_gzip(input, output) {
      +  const gzip = createGzip();
      +  const source = createReadStream(input);
      +  const destination = createWriteStream(output);
      +  await pipe(source, gzip, destination);
      +}
      +
      +do_gzip('input.txt', 'input.txt.gz')
      +  .catch((err) => {
      +    console.error('An error occurred:', err);
      +    process.exitCode = 1;
      +  });
      +

      It is also possible to compress or decompress data in a single step:

      +
      const { deflate, unzip } = require('zlib');
      +
      +const input = '.................................';
      +deflate(input, (err, buffer) => {
      +  if (err) {
      +    console.error('An error occurred:', err);
      +    process.exitCode = 1;
      +  }
      +  console.log(buffer.toString('base64'));
      +});
      +
      +const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
      +unzip(buffer, (err, buffer) => {
      +  if (err) {
      +    console.error('An error occurred:', err);
      +    process.exitCode = 1;
      +  }
      +  console.log(buffer.toString());
      +});
      +
      +// Or, Promisified
      +
      +const { promisify } = require('util');
      +const do_unzip = promisify(unzip);
      +
      +do_unzip(buffer)
      +  .then((buf) => console.log(buf.toString()))
      +  .catch((err) => {
      +    console.error('An error occurred:', err);
      +    process.exitCode = 1;
      +  });
      +

      Threadpool usage and performance considerations#

      +

      All zlib APIs, except those that are explicitly synchronous, use the Node.js +internal threadpool. This can lead to surprising effects and performance +limitations in some applications.

      +

      Creating and using a large number of zlib objects simultaneously can cause +significant memory fragmentation.

      +
      const zlib = require('zlib');
      +
      +const payload = Buffer.from('This is some data');
      +
      +// WARNING: DO NOT DO THIS!
      +for (let i = 0; i < 30000; ++i) {
      +  zlib.deflate(payload, (err, buffer) => {});
      +}
      +

      In the preceding example, 30,000 deflate instances are created concurrently. +Because of how some operating systems handle memory allocation and +deallocation, this may lead to to significant memory fragmentation.

      +

      It is strongly recommended that the results of compression +operations be cached to avoid duplication of effort.

      +

      Compressing HTTP requests and responses#

      +

      The zlib module can be used to implement support for the gzip, deflate +and br content-encoding mechanisms defined by +HTTP.

      +

      The HTTP Accept-Encoding header is used within an http request to identify +the compression encodings accepted by the client. The Content-Encoding +header is used to identify the compression encodings actually applied to a +message.

      +

      The examples given below are drastically simplified to show the basic concept. +Using zlib encoding can be expensive, and the results ought to be cached. +See Memory usage tuning for more information on the speed/memory/compression +tradeoffs involved in zlib usage.

      +
      // Client request example
      +const zlib = require('zlib');
      +const http = require('http');
      +const fs = require('fs');
      +const { pipeline } = require('stream');
      +
      +const request = http.get({ host: 'example.com',
      +                           path: '/',
      +                           port: 80,
      +                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });
      +request.on('response', (response) => {
      +  const output = fs.createWriteStream('example.com_index.html');
      +
      +  const onError = (err) => {
      +    if (err) {
      +      console.error('An error occurred:', err);
      +      process.exitCode = 1;
      +    }
      +  };
      +
      +  switch (response.headers['content-encoding']) {
      +    case 'br':
      +      pipeline(response, zlib.createBrotliDecompress(), output, onError);
      +      break;
      +    // Or, just use zlib.createUnzip() to handle both of the following cases:
      +    case 'gzip':
      +      pipeline(response, zlib.createGunzip(), output, onError);
      +      break;
      +    case 'deflate':
      +      pipeline(response, zlib.createInflate(), output, onError);
      +      break;
      +    default:
      +      pipeline(response, output, onError);
      +      break;
      +  }
      +});
      +
      // server example
      +// Running a gzip operation on every request is quite expensive.
      +// It would be much more efficient to cache the compressed buffer.
      +const zlib = require('zlib');
      +const http = require('http');
      +const fs = require('fs');
      +const { pipeline } = require('stream');
      +
      +http.createServer((request, response) => {
      +  const raw = fs.createReadStream('index.html');
      +  // Store both a compressed and an uncompressed version of the resource.
      +  response.setHeader('Vary', 'Accept-Encoding');
      +  let acceptEncoding = request.headers['accept-encoding'];
      +  if (!acceptEncoding) {
      +    acceptEncoding = '';
      +  }
      +
      +  const onError = (err) => {
      +    if (err) {
      +      // If an error occurs, there's not much we can do because
      +      // the server has already sent the 200 response code and
      +      // some amount of data has already been sent to the client.
      +      // The best we can do is terminate the response immediately
      +      // and log the error.
      +      response.end();
      +      console.error('An error occurred:', err);
      +    }
      +  };
      +
      +  // Note: This is not a conformant accept-encoding parser.
      +  // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
      +  if (/\bdeflate\b/.test(acceptEncoding)) {
      +    response.writeHead(200, { 'Content-Encoding': 'deflate' });
      +    pipeline(raw, zlib.createDeflate(), response, onError);
      +  } else if (/\bgzip\b/.test(acceptEncoding)) {
      +    response.writeHead(200, { 'Content-Encoding': 'gzip' });
      +    pipeline(raw, zlib.createGzip(), response, onError);
      +  } else if (/\bbr\b/.test(acceptEncoding)) {
      +    response.writeHead(200, { 'Content-Encoding': 'br' });
      +    pipeline(raw, zlib.createBrotliCompress(), response, onError);
      +  } else {
      +    response.writeHead(200, {});
      +    pipeline(raw, response, onError);
      +  }
      +}).listen(1337);
      +

      By default, the zlib methods will throw an error when decompressing +truncated data. However, if it is known that the data is incomplete, or +the desire is to inspect only the beginning of a compressed file, it is +possible to suppress the default error handling by changing the flushing +method that is used to decompress the last chunk of input data:

      +
      // This is a truncated version of the buffer from the above examples
      +const buffer = Buffer.from('eJzT0yMA', 'base64');
      +
      +zlib.unzip(
      +  buffer,
      +  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
      +  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
      +  (err, buffer) => {
      +    if (err) {
      +      console.error('An error occurred:', err);
      +      process.exitCode = 1;
      +    }
      +    console.log(buffer.toString());
      +  });
      +

      This will not change the behavior in other error-throwing situations, e.g. +when the input data has an invalid format. Using this method, it will not be +possible to determine whether the input ended prematurely or lacks the +integrity checks, making it necessary to manually check that the +decompressed result is valid.

      +

      Memory usage tuning#

      + +

      For zlib-based streams#

      +

      From zlib/zconf.h, modified for Node.js usage:

      +

      The memory requirements for deflate are (in bytes):

      + +
      (1 << (windowBits + 2)) + (1 << (memLevel + 9))
      +

      That is: 128K for windowBits = 15 + 128K for memLevel = 8 +(default values) plus a few kilobytes for small objects.

      +

      For example, to reduce the default memory requirements from 256K to 128K, the +options should be set to:

      +
      const options = { windowBits: 14, memLevel: 7 };
      +

      This will, however, generally degrade compression.

      +

      The memory requirements for inflate are (in bytes) 1 << windowBits. +That is, 32K for windowBits = 15 (default value) plus a few kilobytes +for small objects.

      +

      This is in addition to a single internal output slab buffer of size +chunkSize, which defaults to 16K.

      +

      The speed of zlib compression is affected most dramatically by the +level setting. A higher level will result in better compression, but +will take longer to complete. A lower level will result in less +compression, but will be much faster.

      +

      In general, greater memory usage options will mean that Node.js has to make +fewer calls to zlib because it will be able to process more data on +each write operation. So, this is another factor that affects the +speed, at the cost of memory usage.

      +

      For Brotli-based streams#

      +

      There are equivalents to the zlib options for Brotli-based streams, although +these options have different ranges than the zlib ones:

      +
        +
      • zlib’s level option matches Brotli’s BROTLI_PARAM_QUALITY option.
      • +
      • zlib’s windowBits option matches Brotli’s BROTLI_PARAM_LGWIN option.
      • +
      +

      See below for more details on Brotli-specific options.

      +

      Flushing#

      +

      Calling .flush() on a compression stream will make zlib return as much +output as currently possible. This may come at the cost of degraded compression +quality, but can be useful when data needs to be available as soon as possible.

      +

      In the following example, flush() is used to write a compressed partial +HTTP response to the client:

      +
      const zlib = require('zlib');
      +const http = require('http');
      +const { pipeline } = require('stream');
      +
      +http.createServer((request, response) => {
      +  // For the sake of simplicity, the Accept-Encoding checks are omitted.
      +  response.writeHead(200, { 'content-encoding': 'gzip' });
      +  const output = zlib.createGzip();
      +  let i;
      +
      +  pipeline(output, response, (err) => {
      +    if (err) {
      +      // If an error occurs, there's not much we can do because
      +      // the server has already sent the 200 response code and
      +      // some amount of data has already been sent to the client.
      +      // The best we can do is terminate the response immediately
      +      // and log the error.
      +      clearInterval(i);
      +      response.end();
      +      console.error('An error occurred:', err);
      +    }
      +  });
      +
      +  i = setInterval(() => {
      +    output.write(`The current time is ${Date()}\n`, () => {
      +      // The data has been passed to zlib, but the compression algorithm may
      +      // have decided to buffer the data for more efficient compression.
      +      // Calling .flush() will make the data available as soon as the client
      +      // is ready to receive it.
      +      output.flush();
      +    });
      +  }, 1000);
      +}).listen(1337);
      +

      Constants#

      + + +

      zlib constants#

      +

      All of the constants defined in zlib.h are also defined on +require('zlib').constants. In the normal course of operations, it will not be +necessary to use these constants. They are documented so that their presence is +not surprising. This section is taken almost directly from the +zlib documentation.

      +

      Previously, the constants were available directly from require('zlib'), for +instance zlib.Z_NO_FLUSH. Accessing the constants directly from the module is +currently still possible but is deprecated.

      +

      Allowed flush values.

      +
        +
      • zlib.constants.Z_NO_FLUSH
      • +
      • zlib.constants.Z_PARTIAL_FLUSH
      • +
      • zlib.constants.Z_SYNC_FLUSH
      • +
      • zlib.constants.Z_FULL_FLUSH
      • +
      • zlib.constants.Z_FINISH
      • +
      • zlib.constants.Z_BLOCK
      • +
      • zlib.constants.Z_TREES
      • +
      +

      Return codes for the compression/decompression functions. Negative +values are errors, positive values are used for special but normal +events.

      +
        +
      • zlib.constants.Z_OK
      • +
      • zlib.constants.Z_STREAM_END
      • +
      • zlib.constants.Z_NEED_DICT
      • +
      • zlib.constants.Z_ERRNO
      • +
      • zlib.constants.Z_STREAM_ERROR
      • +
      • zlib.constants.Z_DATA_ERROR
      • +
      • zlib.constants.Z_MEM_ERROR
      • +
      • zlib.constants.Z_BUF_ERROR
      • +
      • zlib.constants.Z_VERSION_ERROR
      • +
      +

      Compression levels.

      +
        +
      • zlib.constants.Z_NO_COMPRESSION
      • +
      • zlib.constants.Z_BEST_SPEED
      • +
      • zlib.constants.Z_BEST_COMPRESSION
      • +
      • zlib.constants.Z_DEFAULT_COMPRESSION
      • +
      +

      Compression strategy.

      +
        +
      • zlib.constants.Z_FILTERED
      • +
      • zlib.constants.Z_HUFFMAN_ONLY
      • +
      • zlib.constants.Z_RLE
      • +
      • zlib.constants.Z_FIXED
      • +
      • zlib.constants.Z_DEFAULT_STRATEGY
      • +
      +

      Brotli constants#

      + +

      There are several options and other constants available for Brotli-based +streams:

      +

      Flush operations#

      +

      The following values are valid flush operations for Brotli-based streams:

      +
        +
      • zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)
      • +
      • zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())
      • +
      • zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)
      • +
      • zlib.constants.BROTLI_OPERATION_EMIT_METADATA +
          +
        • This particular operation may be hard to use in a Node.js context, +as the streaming layer makes it hard to know which data will end up +in this frame. Also, there is currently no way to consume this data through +the Node.js API.
        • +
        +
      • +
      +

      Compressor options#

      +

      There are several options that can be set on Brotli encoders, affecting +compression efficiency and speed. Both the keys and the values can be accessed +as properties of the zlib.constants object.

      +

      The most important options are:

      +
        +
      • BROTLI_PARAM_MODE +
          +
        • BROTLI_MODE_GENERIC (default)
        • +
        • BROTLI_MODE_TEXT, adjusted for UTF-8 text
        • +
        • BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts
        • +
        +
      • +
      • BROTLI_PARAM_QUALITY +
          +
        • Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY, +with a default of BROTLI_DEFAULT_QUALITY.
        • +
        +
      • +
      • BROTLI_PARAM_SIZE_HINT +
          +
        • Integer value representing the expected input size; +defaults to 0 for an unknown input size.
        • +
        +
      • +
      +

      The following flags can be set for advanced control over the compression +algorithm and memory usage tuning:

      +
        +
      • BROTLI_PARAM_LGWIN +
          +
        • Ranges from BROTLI_MIN_WINDOW_BITS to BROTLI_MAX_WINDOW_BITS, +with a default of BROTLI_DEFAULT_WINDOW, or up to +BROTLI_LARGE_MAX_WINDOW_BITS if the BROTLI_PARAM_LARGE_WINDOW flag +is set.
        • +
        +
      • +
      • BROTLI_PARAM_LGBLOCK +
          +
        • Ranges from BROTLI_MIN_INPUT_BLOCK_BITS to BROTLI_MAX_INPUT_BLOCK_BITS.
        • +
        +
      • +
      • BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING +
          +
        • Boolean flag that decreases compression ratio in favour of +decompression speed.
        • +
        +
      • +
      • BROTLI_PARAM_LARGE_WINDOW +
          +
        • Boolean flag enabling “Large Window Brotli†mode (not compatible with the +Brotli format as standardized in RFC 7932).
        • +
        +
      • +
      • BROTLI_PARAM_NPOSTFIX +
          +
        • Ranges from 0 to BROTLI_MAX_NPOSTFIX.
        • +
        +
      • +
      • BROTLI_PARAM_NDIRECT +
          +
        • Ranges from 0 to 15 << NPOSTFIX in steps of 1 << NPOSTFIX.
        • +
        +
      • +
      +

      Decompressor options#

      +

      These advanced options are available for controlling decompression:

      +
        +
      • BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION +
          +
        • Boolean flag that affects internal memory allocation patterns.
        • +
        +
      • +
      • BROTLI_DECODER_PARAM_LARGE_WINDOW +
          +
        • Boolean flag enabling “Large Window Brotli†mode (not compatible with the +Brotli format as standardized in RFC 7932).
        • +
        +
      • +
      +

      Class: Options#

      + + +

      Each zlib-based class takes an options object. No options are required.

      +

      Some options are only relevant when compressing and are +ignored by the decompression classes.

      + +

      See the deflateInit2 and inflateInit2 documentation for more +information.

      +

      Class: BrotliOptions#

      + + +

      Each Brotli-based class takes an options object. All options are optional.

      + +

      For example:

      +
      const stream = zlib.createBrotliCompress({
      +  chunkSize: 32 * 1024,
      +  params: {
      +    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
      +    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
      +    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
      +  }
      +});
      +

      Class: zlib.BrotliCompress#

      + +

      Compress data using the Brotli algorithm.

      +

      Class: zlib.BrotliDecompress#

      + +

      Decompress data using the Brotli algorithm.

      +

      Class: zlib.Deflate#

      + +

      Compress data using deflate.

      +

      Class: zlib.DeflateRaw#

      + +

      Compress data using deflate, and do not append a zlib header.

      +

      Class: zlib.Gunzip#

      + +

      Decompress a gzip stream.

      +

      Class: zlib.Gzip#

      + +

      Compress data using gzip.

      +

      Class: zlib.Inflate#

      + +

      Decompress a deflate stream.

      +

      Class: zlib.InflateRaw#

      + +

      Decompress a raw deflate stream.

      +

      Class: zlib.Unzip#

      + +

      Decompress either a Gzip- or Deflate-compressed stream by auto-detecting +the header.

      +

      Class: zlib.ZlibBase#

      + +

      Not exported by the zlib module. It is documented here because it is the base +class of the compressor/decompressor classes.

      +

      This class inherits from stream.Transform, allowing zlib objects to be +used in pipes and similar stream operations.

      +

      zlib.bytesRead#

      + +

      Stability: 0 - Deprecated: Use zlib.bytesWritten instead.

      + +

      Deprecated alias for zlib.bytesWritten. This original name was chosen +because it also made sense to interpret the value as the number of bytes +read by the engine, but is inconsistent with other streams in Node.js that +expose values under these names.

      +

      zlib.bytesWritten#

      + + +

      The zlib.bytesWritten property specifies the number of bytes written to +the engine, before the bytes are processed (compressed or decompressed, +as appropriate for the derived class).

      +

      zlib.close([callback])#

      + + +

      Close the underlying handle.

      +

      zlib.flush([kind, ]callback)#

      + +
        +
      • kind Default: zlib.constants.Z_FULL_FLUSH for zlib-based streams, +zlib.constants.BROTLI_OPERATION_FLUSH for Brotli-based streams.
      • +
      • callback <Function>
      • +
      +

      Flush pending data. Don't call this frivolously, premature flushes negatively +impact the effectiveness of the compression algorithm.

      +

      Calling this only flushes data from the internal zlib state, and does not +perform flushing of any kind on the streams level. Rather, it behaves like a +normal call to .write(), i.e. it will be queued up behind other pending +writes and will only produce output when data is being read from the stream.

      +

      zlib.params(level, strategy, callback)#

      + + +

      This function is only available for zlib-based streams, i.e. not Brotli.

      +

      Dynamically update the compression level and compression strategy. +Only applicable to deflate algorithm.

      +

      zlib.reset()#

      + +

      Reset the compressor/decompressor to factory defaults. Only applicable to +the inflate and deflate algorithms.

      +

      zlib.constants#

      + +

      Provides an object enumerating Zlib-related constants.

      +

      zlib.createBrotliCompress([options])#

      + + +

      Creates and returns a new BrotliCompress object.

      +

      zlib.createBrotliDecompress([options])#

      + + +

      Creates and returns a new BrotliDecompress object.

      +

      zlib.createDeflate([options])#

      + + +

      Creates and returns a new Deflate object.

      +

      zlib.createDeflateRaw([options])#

      + + +

      Creates and returns a new DeflateRaw object.

      +

      An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits +is set to 8 for raw deflate streams. zlib would automatically set windowBits +to 9 if was initially set to 8. Newer versions of zlib will throw an exception, +so Node.js restored the original behavior of upgrading a value of 8 to 9, +since passing windowBits = 9 to zlib actually results in a compressed stream +that effectively uses an 8-bit window only.

      +

      zlib.createGunzip([options])#

      + + +

      Creates and returns a new Gunzip object.

      +

      zlib.createGzip([options])#

      + + +

      Creates and returns a new Gzip object. +See example.

      +

      zlib.createInflate([options])#

      + + +

      Creates and returns a new Inflate object.

      +

      zlib.createInflateRaw([options])#

      + + +

      Creates and returns a new InflateRaw object.

      +

      zlib.createUnzip([options])#

      + + +

      Creates and returns a new Unzip object.

      +

      Convenience methods#

      + +

      All of these take a Buffer, TypedArray, DataView, +ArrayBuffer or string as the first argument, an optional second argument +to supply options to the zlib classes and will call the supplied callback +with callback(error, result).

      +

      Every method has a *Sync counterpart, which accept the same arguments, but +without a callback.

      +

      zlib.brotliCompress(buffer[, options], callback)#

      + + +

      zlib.brotliCompressSync(buffer[, options])#

      + + +

      Compress a chunk of data with BrotliCompress.

      +

      zlib.brotliDecompress(buffer[, options], callback)#

      + + +

      zlib.brotliDecompressSync(buffer[, options])#

      + + +

      Decompress a chunk of data with BrotliDecompress.

      +

      zlib.deflate(buffer[, options], callback)#

      + + +

      zlib.deflateSync(buffer[, options])#

      + + +

      Compress a chunk of data with Deflate.

      +

      zlib.deflateRaw(buffer[, options], callback)#

      + + +

      zlib.deflateRawSync(buffer[, options])#

      + + +

      Compress a chunk of data with DeflateRaw.

      +

      zlib.gunzip(buffer[, options], callback)#

      + + +

      zlib.gunzipSync(buffer[, options])#

      + + +

      Decompress a chunk of data with Gunzip.

      +

      zlib.gzip(buffer[, options], callback)#

      + + +

      zlib.gzipSync(buffer[, options])#

      + + +

      Compress a chunk of data with Gzip.

      +

      zlib.inflate(buffer[, options], callback)#

      + + +

      zlib.inflateSync(buffer[, options])#

      + + +

      Decompress a chunk of data with Inflate.

      +

      zlib.inflateRaw(buffer[, options], callback)#

      + + +

      zlib.inflateRawSync(buffer[, options])#

      + + +

      Decompress a chunk of data with InflateRaw.

      +

      zlib.unzip(buffer[, options], callback)#

      + + +

      zlib.unzipSync(buffer[, options])#

      + + +

      Decompress a chunk of data with Unzip.

      + +
      +
      +
      + + diff --git a/doc/api/all.json b/doc/api/all.json new file mode 100644 index 0000000000000000000000000000000000000000..46c3fc0dcd6d2548af0eea12768a376dbf446b5b --- /dev/null +++ b/doc/api/all.json @@ -0,0 +1,65167 @@ +{ + "miscs": [ + { + "textRaw": "About this documentation", + "name": "About this documentation", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      Welcome to the official API reference documentation for Node.js!

      \n

      Node.js is a JavaScript runtime built on the V8 JavaScript engine.

      ", + "miscs": [ + { + "textRaw": "Contributing", + "name": "contributing", + "desc": "

      Report errors in this documentation in the issue tracker. See\nthe contributing guide for directions on how to submit pull requests.

      ", + "type": "misc", + "displayName": "Contributing" + }, + { + "textRaw": "Stability index", + "name": "Stability index", + "type": "misc", + "desc": "

      Throughout the documentation are indications of a section's stability. Some APIs\nare so proven and so relied upon that they are unlikely to ever change at all.\nOthers are brand new and experimental, or known to be hazardous.

      \n

      The stability indices are as follows:

      \n
      \n

      Stability: 0 - Deprecated. The feature may emit warnings. Backward\ncompatibility is not guaranteed.

      \n
      \n\n
      \n

      Stability: 1 - Experimental. The feature is not subject to\nSemantic Versioning rules. Non-backward compatible changes or removal may\noccur in any future release. Use of the feature is not recommended in\nproduction environments.

      \n
      \n\n
      \n

      Stability: 2 - Stable. Compatibility with the npm ecosystem is a high\npriority.

      \n
      \n

      Use caution when making use of Experimental features, particularly within\nmodules. Users may not be aware that experimental features are being used.\nBugs or behavior changes may surprise users when Experimental API\nmodifications occur. To avoid surprises, use of an Experimental feature may need\na command-line flag. Experimental features may also emit a warning.

      " + }, + { + "textRaw": "JSON output", + "name": "json_output", + "meta": { + "added": [ + "v0.6.12" + ], + "changes": [] + }, + "desc": "

      Every .html document has a corresponding .json document. This is for IDEs\nand other utilities that consume the documentation.

      ", + "type": "misc", + "displayName": "JSON output" + }, + { + "textRaw": "System calls and man pages", + "name": "system_calls_and_man_pages", + "desc": "

      Node.js functions which wrap a system call will document that. The docs link\nto the corresponding man pages which describe how the system call works.

      \n

      Most Unix system calls have Windows analogues. Still, behavior differences may\nbe unavoidable.

      ", + "type": "misc", + "displayName": "System calls and man pages" + } + ] + }, + { + "textRaw": "C++ addons", + "name": "C++ addons", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      Addons are dynamically-linked shared objects written in C++. The\nrequire() function can load addons as ordinary Node.js modules.\nAddons provide an interface between JavaScript and C/C++ libraries.

      \n

      There are three options for implementing addons: N-API, nan, or direct\nuse of internal V8, libuv and Node.js libraries. Unless there is a need for\ndirect access to functionality which is not exposed by N-API, use N-API.\nRefer to C/C++ addons with N-API for more information on N-API.

      \n

      When not using N-API, implementing addons is complicated,\ninvolving knowledge of several components and APIs:

      \n
        \n
      • \n

        V8: the C++ library Node.js uses to provide the\nJavaScript implementation. V8 provides the mechanisms for creating objects,\ncalling functions, etc. V8's API is documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node.js source\ntree), which is also available online.

        \n
      • \n
      • \n

        libuv: The C library that implements the Node.js event loop, its worker\nthreads and all of the asynchronous behaviors of the platform. It also\nserves as a cross-platform abstraction library, giving easy, POSIX-like\naccess across all major operating systems to many common system tasks, such\nas interacting with the filesystem, sockets, timers, and system events. libuv\nalso provides a pthreads-like threading abstraction that may be used to\npower more sophisticated asynchronous addons that need to move beyond the\nstandard event loop. Addon authors are encouraged to think about how to\navoid blocking the event loop with I/O or other time-intensive tasks by\noff-loading work via libuv to non-blocking system operations, worker threads\nor a custom use of libuv's threads.

        \n
      • \n
      • \n

        Internal Node.js libraries. Node.js itself exports C++ APIs that addons can\nuse, the most important of which is the node::ObjectWrap class.

        \n
      • \n
      • \n

        Node.js includes other statically linked libraries including OpenSSL. These\nother libraries are located in the deps/ directory in the Node.js source\ntree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully\nre-exported by Node.js and may be used to various extents by addons. See\nLinking to libraries included with Node.js for additional information.

        \n
      • \n
      \n

      All of the following examples are available for download and may\nbe used as the starting-point for an addon.

      ", + "miscs": [ + { + "textRaw": "Hello world", + "name": "hello_world", + "desc": "

      This \"Hello world\" example is a simple addon, written in C++, that is the\nequivalent of the following JavaScript code:

      \n
      module.exports.hello = () => 'world';\n
      \n

      First, create the file hello.cc:

      \n
      // hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid Method(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"hello\", Method);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n\n}  // namespace demo\n
      \n

      All Node.js addons must export an initialization function following\nthe pattern:

      \n
      void Initialize(Local<Object> exports);\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n
      \n

      There is no semi-colon after NODE_MODULE as it's not a function (see\nnode.h).

      \n

      The module_name must match the filename of the final binary (excluding\nthe .node suffix).

      \n

      In the hello.cc example, then, the initialization function is Initialize\nand the addon module name is addon.

      \n

      When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as\nthe first parameter of NODE_MODULE() will ensure that the name of the final\nbinary will be passed to NODE_MODULE().

      ", + "modules": [ + { + "textRaw": "Context-aware addons", + "name": "context-aware_addons", + "desc": "

      There are environments in which Node.js addons may need to be loaded multiple\ntimes in multiple contexts. For example, the Electron runtime runs multiple\ninstances of Node.js in a single process. Each instance will have its own\nrequire() cache, and thus each instance will need a native addon to behave\ncorrectly when loaded via require(). From the addon's perspective, this means\nthat it must support multiple initializations.

      \n

      A context-aware addon can be constructed by using the macro\nNODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js\nwill expect to find when it loads an addon. An addon can thus be initialized as\nin the following example:

      \n
      using namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local<Object> exports,\n                        Local<Value> module,\n                        Local<Context> context) {\n  /* Perform addon initialization steps here. */\n}\n
      \n

      Another option is to use the macro NODE_MODULE_INIT(), which will also\nconstruct a context-aware addon. Unlike NODE_MODULE(), which is used to\nconstruct an addon around a given addon initializer function,\nNODE_MODULE_INIT() serves as the declaration of such an initializer to be\nfollowed by a function body.

      \n

      The following three variables may be used inside the function body following an\ninvocation of NODE_MODULE_INIT():

      \n
        \n
      • Local<Object> exports,
      • \n
      • Local<Value> module, and
      • \n
      • Local<Context> context
      • \n
      \n

      The choice to build a context-aware addon carries with it the responsibility of\ncarefully managing global static data. Since the addon may be loaded multiple\ntimes, potentially even from different threads, any global static data stored\nin the addon must be properly protected, and must not contain any persistent\nreferences to JavaScript objects. The reason for this is that JavaScript\nobjects are only valid in one context, and will likely cause a crash when\naccessed from the wrong context or from a different thread than the one on which\nthey were created.

      \n

      The context-aware addon can be structured to avoid global static data by\nperforming the following steps:

      \n
        \n
      • Define a class which will hold per-addon-instance data and which has a static\nmember of the form\n
        static void DeleteInstance(void* data) {\n  // Cast `data` to an instance of the class and delete it.\n}\n
        \n
      • \n
      • Heap-allocate an instance of this class in the addon initializer. This can be\naccomplished using the new keyword.
      • \n
      • Call node::AddEnvironmentCleanupHook(), passing it the above-created\ninstance and a pointer to DeleteInstance(). This will ensure the instance is\ndeleted when the environment is torn down.
      • \n
      • Store the instance of the class in a v8::External, and
      • \n
      • Pass the v8::External to all methods exposed to JavaScript by passing it\nto v8::FunctionTemplate::New() or v8::Function::New() which creates the\nnative-backed JavaScript functions. The third parameter of\nv8::FunctionTemplate::New() or v8::Function::New() accepts the\nv8::External and makes it available in the native callback using the\nv8::FunctionCallbackInfo::Data() method.
      • \n
      \n

      This will ensure that the per-addon-instance data reaches each binding that can\nbe called from JavaScript. The per-addon-instance data must also be passed into\nany asynchronous callbacks the addon may create.

      \n

      The following example illustrates the implementation of a context-aware addon:

      \n
      #include <node.h>\n\nusing namespace v8;\n\nclass AddonData {\n public:\n  explicit AddonData(Isolate* isolate):\n      call_count(0) {\n    // Ensure this per-addon-instance data is deleted at environment cleanup.\n    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);\n  }\n\n  // Per-addon data.\n  int call_count;\n\n  static void DeleteInstance(void* data) {\n    delete static_cast<AddonData*>(data);\n  }\n};\n\nstatic void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {\n  // Retrieve the per-addon-instance data.\n  AddonData* data =\n      reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());\n  data->call_count++;\n  info.GetReturnValue().Set((double)data->call_count);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = context->GetIsolate();\n\n  // Create a new instance of `AddonData` for this instance of the addon and\n  // tie its life cycle to that of the Node.js environment.\n  AddonData* data = new AddonData(isolate);\n\n  // Wrap the data in a `v8::External` so we can pass it to the method we\n  // expose.\n  Local<External> external = External::New(isolate, data);\n\n  // Expose the method `Method` to JavaScript, and make sure it receives the\n  // per-addon-instance data we created above by passing `external` as the\n  // third parameter to the `FunctionTemplate` constructor.\n  exports->Set(context,\n               String::NewFromUtf8(isolate, \"method\", NewStringType::kNormal)\n                  .ToLocalChecked(),\n               FunctionTemplate::New(isolate, Method, external)\n                  ->GetFunction(context).ToLocalChecked()).FromJust();\n}\n
      ", + "modules": [ + { + "textRaw": "Worker support", + "name": "worker_support", + "meta": { + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34572", + "description": "Cleanup hooks may now be asynchronous." + } + ] + }, + "desc": "

      In order to be loaded from multiple Node.js environments,\nsuch as a main thread and a Worker thread, an add-on needs to either:

      \n
        \n
      • Be an N-API addon, or
      • \n
      • Be declared as context-aware using NODE_MODULE_INIT() as described above
      • \n
      \n

      In order to support Worker threads, addons need to clean up any resources\nthey may have allocated when such a thread exists. This can be achieved through\nthe usage of the AddEnvironmentCleanupHook() function:

      \n
      void AddEnvironmentCleanupHook(v8::Isolate* isolate,\n                               void (*fun)(void* arg),\n                               void* arg);\n
      \n

      This function adds a hook that will run before a given Node.js instance shuts\ndown. If necessary, such hooks can be removed before they are run using\nRemoveEnvironmentCleanupHook(), which has the same signature. Callbacks are\nrun in last-in first-out order.

      \n

      If necessary, there is an additional pair of AddEnvironmentCleanupHook()\nand RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a\ncallback function. This can be used for shutting down asynchronous resources,\nsuch as any libuv handles registered by the addon.

      \n

      The following addon.cc uses AddEnvironmentCleanupHook:

      \n
      // addon.cc\n#include <assert.h>\n#include <stdlib.h>\n#include <node.h>\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\n// Note: In a real-world application, do not rely on static/global data.\nstatic char cookie[] = \"yum yum\";\nstatic int cleanup_cb1_called = 0;\nstatic int cleanup_cb2_called = 0;\n\nstatic void cleanup_cb1(void* arg) {\n  Isolate* isolate = static_cast<Isolate*>(arg);\n  HandleScope scope(isolate);\n  Local<Object> obj = Object::New(isolate);\n  assert(!obj.IsEmpty());  // assert VM is still alive\n  assert(obj->IsObject());\n  cleanup_cb1_called++;\n}\n\nstatic void cleanup_cb2(void* arg) {\n  assert(arg == static_cast<void*>(cookie));\n  cleanup_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n  assert(cleanup_cb1_called == 1);\n  assert(cleanup_cb2_called == 1);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n  Isolate* isolate = context->GetIsolate();\n\n  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);\n}\n
      \n

      Test in JavaScript by running:

      \n
      // test.js\nrequire('./build/Release/addon');\n
      ", + "type": "module", + "displayName": "Worker support" + } + ], + "type": "module", + "displayName": "Context-aware addons" + }, + { + "textRaw": "Building", + "name": "building", + "desc": "

      Once the source code has been written, it must be compiled into the binary\naddon.node file. To do so, create a file called binding.gyp in the\ntop-level of the project describing the build configuration of the module\nusing a JSON-like format. This file is used by node-gyp, a tool written\nspecifically to compile Node.js addons.

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}\n
      \n

      A version of the node-gyp utility is bundled and distributed with\nNode.js as part of npm. This version is not made directly available for\ndevelopers to use and is intended only to support the ability to use the\nnpm install command to compile and install addons. Developers who wish to\nuse node-gyp directly can install it using the command\nnpm install -g node-gyp. See the node-gyp installation instructions for\nmore information, including platform-specific requirements.

      \n

      Once the binding.gyp file has been created, use node-gyp configure to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory.

      \n

      Next, invoke the node-gyp build command to generate the compiled addon.node\nfile. This will be put into the build/Release/ directory.

      \n

      When using npm install to install a Node.js addon, npm uses its own bundled\nversion of node-gyp to perform this same set of actions, generating a\ncompiled version of the addon for the user's platform on demand.

      \n

      Once built, the binary addon can be used from within Node.js by pointing\nrequire() to the built addon.node module:

      \n
      // hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n
      \n

      Because the exact path to the compiled addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in ./build/Debug/), addons can use\nthe bindings package to load the compiled module.

      \n

      While the bindings package implementation is more sophisticated in how it\nlocates addon modules, it is essentially using a try…catch pattern similar to:

      \n
      try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n
      ", + "type": "module", + "displayName": "Building" + }, + { + "textRaw": "Linking to libraries included with Node.js", + "name": "linking_to_libraries_included_with_node.js", + "desc": "

      Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All\naddons are required to link to V8 and may link to any of the other dependencies\nas well. Typically, this is as simple as including the appropriate\n#include <...> statements (e.g. #include <v8.h>) and node-gyp will locate\nthe appropriate headers automatically. However, there are a few caveats to be\naware of:

      \n
        \n
      • \n

        When node-gyp runs, it will detect the specific release version of Node.js\nand download either the full source tarball or just the headers. If the full\nsource is downloaded, addons will have complete access to the full set of\nNode.js dependencies. However, if only the Node.js headers are downloaded, then\nonly the symbols exported by Node.js will be available.

        \n
      • \n
      • \n

        node-gyp can be run using the --nodedir flag pointing at a local Node.js\nsource image. Using this option, the addon will have access to the full set of\ndependencies.

        \n
      • \n
      ", + "type": "module", + "displayName": "Linking to libraries included with Node.js" + }, + { + "textRaw": "Loading addons using `require()`", + "name": "loading_addons_using_`require()`", + "desc": "

      The filename extension of the compiled addon binary is .node (as opposed\nto .dll or .so). The require() function is written to look for\nfiles with the .node file extension and initialize those as dynamically-linked\nlibraries.

      \n

      When calling require(), the .node extension can usually be\nomitted and Node.js will still find and initialize the addon. One caveat,\nhowever, is that Node.js will first attempt to locate and load modules or\nJavaScript files that happen to share the same base name. For instance, if\nthere is a file addon.js in the same directory as the binary addon.node,\nthen require('addon') will give precedence to the addon.js file\nand load it instead.

      ", + "type": "module", + "displayName": "Loading addons using `require()`" + } + ], + "type": "misc", + "displayName": "Hello world" + }, + { + "textRaw": "Native abstractions for Node.js", + "name": "native_abstractions_for_node.js", + "desc": "

      Each of the examples illustrated in this document directly use the\nNode.js and V8 APIs for implementing addons. The V8 API can, and has, changed\ndramatically from one V8 release to the next (and one major Node.js release to\nthe next). With each change, addons may need to be updated and recompiled in\norder to continue functioning. The Node.js release schedule is designed to\nminimize the frequency and impact of such changes but there is little that\nNode.js can do to ensure stability of the V8 APIs.

      \n

      The Native Abstractions for Node.js (or nan) provide a set of tools that\naddon developers are recommended to use to keep compatibility between past and\nfuture releases of V8 and Node.js. See the nan examples for an\nillustration of how it can be used.

      ", + "type": "misc", + "displayName": "Native abstractions for Node.js" + }, + { + "textRaw": "N-API", + "name": "n-api", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      N-API is an API for building native addons. It is independent from\nthe underlying JavaScript runtime (e.g. V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross versions of Node.js. It is intended to insulate addons from\nchanges in the underlying JavaScript engine and allow modules\ncompiled for one version to run on later versions of Node.js without\nrecompilation. Addons are built/packaged with the same approach/tools\noutlined in this document (node-gyp, etc.). The only difference is the\nset of APIs that are used by the native code. Instead of using the V8\nor Native Abstractions for Node.js APIs, the functions available\nin the N-API are used.

      \n

      Creating and maintaining an addon that benefits from the ABI stability\nprovided by N-API carries with it certain\nimplementation considerations.

      \n

      To use N-API in the above \"Hello world\" example, replace the content of\nhello.cc with the following. All other instructions remain the same.

      \n
      // hello.cc using N-API\n#include <node_api.h>\n\nnamespace demo {\n\nnapi_value Method(napi_env env, napi_callback_info args) {\n  napi_value greeting;\n  napi_status status;\n\n  status = napi_create_string_utf8(env, \"world\", NAPI_AUTO_LENGTH, &greeting);\n  if (status != napi_ok) return nullptr;\n  return greeting;\n}\n\nnapi_value init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_value fn;\n\n  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);\n  if (status != napi_ok) return nullptr;\n\n  status = napi_set_named_property(env, exports, \"hello\", fn);\n  if (status != napi_ok) return nullptr;\n  return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, init)\n\n}  // namespace demo\n
      \n

      The functions available and how to use them are documented in\nC/C++ addons with N-API.

      ", + "type": "misc", + "displayName": "N-API" + }, + { + "textRaw": "Addon examples", + "name": "addon_examples", + "desc": "

      Following are some example addons intended to help developers get started. The\nexamples use the V8 APIs. Refer to the online V8 reference\nfor help with the various V8 calls, and V8's Embedder's Guide for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.

      \n

      Each of these examples using the following binding.gyp file:

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}\n
      \n

      In cases where there is more than one .cc file, simply add the additional\nfilename to the sources array:

      \n
      \"sources\": [\"addon.cc\", \"myexample.cc\"]\n
      \n

      Once the binding.gyp file is ready, the example addons can be configured and\nbuilt using node-gyp:

      \n
      $ node-gyp configure build\n
      ", + "modules": [ + { + "textRaw": "Function arguments", + "name": "function_arguments", + "desc": "

      Addons will typically expose objects and functions that can be accessed from\nJavaScript running within Node.js. When functions are invoked from JavaScript,\nthe input arguments and return value must be mapped to and from the C/C++\ncode.

      \n

      The following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the \"add\" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  // Check the number of arguments passed.\n  if (args.Length() < 2) {\n    // Throw an Error that is passed back to JavaScript\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong number of arguments\",\n                            NewStringType::kNormal).ToLocalChecked()));\n    return;\n  }\n\n  // Check the argument types\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    isolate->ThrowException(Exception::TypeError(\n        String::NewFromUtf8(isolate,\n                            \"Wrong arguments\",\n                            NewStringType::kNormal).ToLocalChecked()));\n    return;\n  }\n\n  // Perform the operation\n  double value =\n      args[0].As<Number>()->Value() + args[1].As<Number>()->Value();\n  Local<Number> num = Number::New(isolate, value);\n\n  // Set the return value (using the passed in\n  // FunctionCallbackInfo<Value>&)\n  args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local<Object> exports) {\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      Once compiled, the example addon can be required and used from within Node.js:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n
      ", + "type": "module", + "displayName": "Function arguments" + }, + { + "textRaw": "Callbacks", + "name": "callbacks", + "desc": "

      It is common practice within addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = {\n      String::NewFromUtf8(isolate,\n                          \"hello world\",\n                          NewStringType::kNormal).ToLocalChecked() };\n  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      This example uses a two-argument form of Init() that receives the full\nmodule object as the second argument. This allows the addon to completely\noverwrite exports with a single function instead of adding the function as a\nproperty of exports.

      \n

      To test it, run the following JavaScript:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg);\n// Prints: 'hello world'\n});\n
      \n

      In this example, the callback function is invoked synchronously.

      ", + "type": "module", + "displayName": "Callbacks" + }, + { + "textRaw": "Object factory", + "name": "object_factory", + "desc": "

      Addons can create and return new objects from within a C++ function as\nillustrated in the following example. An object is created and returned with a\nproperty msg that echoes the string passed to createObject():

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<Object> obj = Object::New(isolate);\n  obj->Set(context,\n           String::NewFromUtf8(isolate,\n                               \"msg\",\n                               NewStringType::kNormal).ToLocalChecked(),\n                               args[0]->ToString(context).ToLocalChecked())\n           .FromJust();\n\n  args.GetReturnValue().Set(obj);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      To test it in JavaScript:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'\n
      ", + "type": "module", + "displayName": "Object factory" + }, + { + "textRaw": "Function factory", + "name": "function_factory", + "desc": "

      Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:

      \n
      // addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"hello world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();\n\n  // omit this to make it anonymous\n  fn->SetName(String::NewFromUtf8(\n      isolate, \"theFunction\", NewStringType::kNormal).ToLocalChecked());\n\n  args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n}  // namespace demo\n
      \n

      To test:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n
      ", + "type": "module", + "displayName": "Function factory" + }, + { + "textRaw": "Wrapping C++ objects", + "name": "wrapping_c++_objects", + "desc": "

      It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript new operator:

      \n
      // addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
      \n

      Then, in myobject.h, the wrapper class inherits from node::ObjectWrap:

      \n
      // myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Local<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
      \n

      In myobject.cc, implement the various methods that are to be exposed.\nBelow, the method plusOne() is exposed by adding it to the constructor's\nprototype:

      \n
      // myobject.cc\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n  Isolate* isolate = exports->GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);\n  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()\n  Local<Object> addon_data =\n      addon_data_tpl->NewInstance(context).ToLocalChecked();\n\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();\n  addon_data->SetInternalField(0, constructor);\n  exports->Set(context, String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked(),\n               constructor).FromJust();\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons =\n        args.Data().As<Object>()->GetInternalField(0).As<Function>();\n    Local<Object> result =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(result);\n  }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
      \n

      To build this example, the myobject.cc file must be added to the\nbinding.gyp:

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
      \n

      Test it with:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n
      \n

      The destructor for a wrapper object will run when the object is\ngarbage-collected. For destructor testing, there are command-line flags that\ncan be used to make it possible to force garbage collection. These flags are\nprovided by the underlying V8 JavaScript engine. They are subject to change\nor removal at any time. They are not documented by Node.js or V8, and they\nshould never be used outside of testing.

      ", + "type": "module", + "displayName": "Wrapping C++ objects" + }, + { + "textRaw": "Factory of wrapped objects", + "name": "factory_of_wrapped_objects", + "desc": "

      Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript new operator:

      \n
      const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n
      \n

      First, the createObject() method is implemented in addon.cc:

      \n
      // addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n  MyObject::Init(exports->GetIsolate());\n\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
      \n

      In myobject.h, the static method NewInstance() is added to handle\ninstantiating the object. This method takes the place of using new in\nJavaScript:

      \n
      // myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Isolate* isolate);\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
      \n

      The implementation in myobject.cc is similar to the previous example:

      \n
      // myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
      \n

      Once again, to build this example, the myobject.cc file must be added to the\nbinding.gyp:

      \n
      {\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
      \n

      Test it with:

      \n
      // test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23\n
      ", + "type": "module", + "displayName": "Factory of wrapped objects" + }, + { + "textRaw": "Passing wrapped objects around", + "name": "passing_wrapped_objects_around", + "desc": "

      In addition to wrapping and returning C++ objects, it is possible to pass\nwrapped objects around by unwrapping them with the Node.js helper function\nnode::ObjectWrap::Unwrap. The following examples shows a function add()\nthat can take two MyObject objects as input arguments:

      \n
      // addon.cc\n#include <node.h>\n#include <node_object_wrap.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n  MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject(context).ToLocalChecked());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject(context).ToLocalChecked());\n\n  double sum = obj1->value() + obj2->value();\n  args.GetReturnValue().Set(Number::New(isolate, sum));\n}\n\nvoid InitAll(Local<Object> exports) {\n  MyObject::Init(exports->GetIsolate());\n\n  NODE_SET_METHOD(exports, \"createObject\", CreateObject);\n  NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
      \n

      In myobject.h, a new public method is added to allow access to private values\nafter unwrapping the object.

      \n
      // myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Isolate* isolate);\n  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n  inline double value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n  static v8::Global<v8::Function> constructor;\n  double value_;\n};\n\n}  // namespace demo\n\n#endif\n
      \n

      The implementation of myobject.cc is similar to before:

      \n
      // myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(\n      isolate, \"MyObject\", NewStringType::kNormal).ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  Local<Context> context = isolate->GetCurrentContext();\n  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n  AddEnvironmentCleanupHook(isolate, [](void*) {\n    constructor.Reset();\n  }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  Local<Context> context = isolate->GetCurrentContext();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ?\n        0 : args[0]->NumberValue(context).FromMaybe(0);\n    MyObject* obj = new MyObject(value);\n    obj->Wrap(args.This());\n    args.GetReturnValue().Set(args.This());\n  } else {\n    // Invoked as plain function `MyObject(...)`, turn into construct call.\n    const int argc = 1;\n    Local<Value> argv[argc] = { args[0] };\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\n    Local<Object> instance =\n        cons->NewInstance(context, argc, argv).ToLocalChecked();\n    args.GetReturnValue().Set(instance);\n  }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { args[0] };\n  Local<Function> cons = Local<Function>::New(isolate, constructor);\n  Local<Context> context = isolate->GetCurrentContext();\n  Local<Object> instance =\n      cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo\n
      \n

      Test it with:

      \n
      // test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30\n
      ", + "type": "module", + "displayName": "Passing wrapped objects around" + } + ], + "type": "misc", + "displayName": "Addon examples" + } + ] + }, + { + "textRaw": "N-API", + "name": "N-API", + "introduced_in": "v8.0.0", + "type": "misc", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      N-API (pronounced N as in the letter, followed by API)\nis an API for building native Addons. It is independent from\nthe underlying JavaScript runtime (for example, V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross versions of Node.js. It is intended to insulate Addons from\nchanges in the underlying JavaScript engine and allow modules\ncompiled for one major version to run on later major versions of Node.js without\nrecompilation. The ABI Stability guide provides a more in-depth explanation.

      \n

      Addons are built/packaged with the same approach/tools outlined in the section\ntitled C++ Addons. The only difference is the set of APIs that are used by\nthe native code. Instead of using the V8 or Native Abstractions for Node.js\nAPIs, the functions available in the N-API are used.

      \n

      APIs exposed by N-API are generally used to create and manipulate\nJavaScript values. Concepts and operations generally map to ideas specified\nin the ECMA-262 Language Specification. The APIs have the following\nproperties:

      \n
        \n
      • All N-API calls return a status code of type napi_status. This\nstatus indicates whether the API call succeeded or failed.
      • \n
      • The API's return value is passed via an out parameter.
      • \n
      • All JavaScript values are abstracted behind an opaque type named\nnapi_value.
      • \n
      • In case of an error status code, additional information can be obtained\nusing napi_get_last_error_info. More information can be found in the error\nhandling section Error handling.
      • \n
      \n

      The N-API is a C API that ensures ABI stability across Node.js versions\nand different compiler levels. A C++ API can be easier to use.\nTo support using C++, the project maintains a\nC++ wrapper module called node-addon-api.\nThis wrapper provides an inlineable C++ API. Binaries built\nwith node-addon-api will depend on the symbols for the N-API C-based\nfunctions exported by Node.js. node-addon-api is a more\nefficient way to write code that calls N-API. Take, for example, the\nfollowing node-addon-api code. The first section shows the\nnode-addon-api code and the second section shows what actually gets\nused in the addon.

      \n
      Object obj = Object::New(env);\nobj[\"foo\"] = String::New(env, \"bar\");\n
      \n
      napi_status status;\nnapi_value object, string;\nstatus = napi_create_object(env, &object);\nif (status != napi_ok) {\n  napi_throw_error(env, ...);\n  return;\n}\n\nstatus = napi_create_string_utf8(env, \"bar\", NAPI_AUTO_LENGTH, &string);\nif (status != napi_ok) {\n  napi_throw_error(env, ...);\n  return;\n}\n\nstatus = napi_set_named_property(env, object, \"foo\", string);\nif (status != napi_ok) {\n  napi_throw_error(env, ...);\n  return;\n}\n
      \n

      The end result is that the addon only uses the exported C APIs. As a result,\nit still gets the benefits of the ABI stability provided by the C API.

      \n

      When using node-addon-api instead of the C APIs, start with the API docs\nfor node-addon-api.

      \n

      The N-API Resource offers an\nexcellent orientation and tips for developers just getting started with N-API\nand node-addon-api.

      ", + "miscs": [ + { + "textRaw": "Implications of ABI stability", + "name": "implications_of_abi_stability", + "desc": "

      Although N-API provides an ABI stability guarantee, other parts of Node.js do\nnot, and any external libraries used from the addon may not. In particular,\nnone of the following APIs provide an ABI stability guarantee across major\nversions:

      \n
        \n
      • \n

        the Node.js C++ APIs available via any of

        \n
        #include <node.h>\n#include <node_buffer.h>\n#include <node_version.h>\n#include <node_object_wrap.h>\n
        \n
      • \n
      • \n

        the libuv APIs which are also included with Node.js and available via

        \n
        #include <uv.h>\n
        \n
      • \n
      • \n

        the V8 API available via

        \n
        #include <v8.h>\n
        \n
      • \n
      \n

      Thus, for an addon to remain ABI-compatible across Node.js major versions, it\nmust use N-API exclusively by restricting itself to using

      \n
      #include <node_api.h>\n
      \n

      and by checking, for all external libraries that it uses, that the external\nlibrary makes ABI stability guarantees similar to N-API.

      ", + "type": "misc", + "displayName": "Implications of ABI stability" + }, + { + "textRaw": "Building", + "name": "building", + "desc": "

      Unlike modules written in JavaScript, developing and deploying Node.js\nnative addons using N-API requires an additional set of tools. Besides the\nbasic tools required to develop for Node.js, the native addon developer\nrequires a toolchain that can compile C and C++ code into a binary. In\naddition, depending upon how the native addon is deployed, the user of\nthe native addon will also need to have a C/C++ toolchain installed.

      \n

      For Linux developers, the necessary C/C++ toolchain packages are readily\navailable. GCC is widely used in the Node.js community to build and\ntest across a variety of platforms. For many developers, the LLVM\ncompiler infrastructure is also a good choice.

      \n

      For Mac developers, Xcode offers all the required compiler tools.\nHowever, it is not necessary to install the entire Xcode IDE. The following\ncommand installs the necessary toolchain:

      \n
      xcode-select --install\n
      \n

      For Windows developers, Visual Studio offers all the required compiler\ntools. However, it is not necessary to install the entire Visual Studio\nIDE. The following command installs the necessary toolchain:

      \n
      npm install --global windows-build-tools\n
      \n

      The sections below describe the additional tools available for developing\nand deploying Node.js native addons.

      ", + "modules": [ + { + "textRaw": "Build tools", + "name": "build_tools", + "desc": "

      Both the tools listed here require that users of the native\naddon have a C/C++ toolchain installed in order to successfully install\nthe native addon.

      ", + "modules": [ + { + "textRaw": "node-gyp", + "name": "node-gyp", + "desc": "

      node-gyp is a build system based on Google's GYP tool and comes\nbundled with npm. GYP, and therefore node-gyp, requires that Python be\ninstalled.

      \n

      Historically, node-gyp has been the tool of choice for building native\naddons. It has widespread adoption and documentation. However, some\ndevelopers have run into limitations in node-gyp.

      ", + "type": "module", + "displayName": "node-gyp" + } + ], + "properties": [ + { + "textRaw": "CMake.js", + "name": "js", + "desc": "

      CMake.js is an alternative build system based on CMake.

      \n

      CMake.js is a good choice for projects that already use CMake or for\ndevelopers affected by limitations in node-gyp.

      " + } + ], + "type": "module", + "displayName": "Build tools" + }, + { + "textRaw": "Uploading precompiled binaries", + "name": "uploading_precompiled_binaries", + "desc": "

      The three tools listed here permit native addon developers and maintainers\nto create and upload binaries to public or private servers. These tools are\ntypically integrated with CI/CD build systems like Travis CI and\nAppVeyor to build and upload binaries for a variety of platforms and\narchitectures. These binaries are then available for download by users who\ndo not need to have a C/C++ toolchain installed.

      ", + "modules": [ + { + "textRaw": "node-pre-gyp", + "name": "node-pre-gyp", + "desc": "

      node-pre-gyp is a tool based on node-gyp that adds the ability to\nupload binaries to a server of the developer's choice. node-pre-gyp has\nparticularly good support for uploading binaries to Amazon S3.

      ", + "type": "module", + "displayName": "node-pre-gyp" + }, + { + "textRaw": "prebuild", + "name": "prebuild", + "desc": "

      prebuild is a tool that supports builds using either node-gyp or\nCMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild\nuploads binaries only to GitHub releases. prebuild is a good choice for\nGitHub projects using CMake.js.

      ", + "type": "module", + "displayName": "prebuild" + }, + { + "textRaw": "prebuildify", + "name": "prebuildify", + "desc": "

      prebuildify is a tool based on node-gyp. The advantage of prebuildify is\nthat the built binaries are bundled with the native module when it's\nuploaded to npm. The binaries are downloaded from npm and are immediately\navailable to the module user when the native module is installed.

      ", + "type": "module", + "displayName": "prebuildify" + } + ], + "type": "module", + "displayName": "Uploading precompiled binaries" + } + ], + "type": "misc", + "displayName": "Building" + }, + { + "textRaw": "Usage", + "name": "usage", + "desc": "

      In order to use the N-API functions, include the file node_api.h which is\nlocated in the src directory in the node development tree:

      \n
      #include <node_api.h>\n
      \n

      This will opt into the default NAPI_VERSION for the given release of Node.js.\nIn order to ensure compatibility with specific versions of N-API, the version\ncan be specified explicitly when including the header:

      \n
      #define NAPI_VERSION 3\n#include <node_api.h>\n
      \n

      This restricts the N-API surface to just the functionality that was available in\nthe specified (and earlier) versions.

      \n

      Some of the N-API surface is experimental and requires explicit opt-in:

      \n
      #define NAPI_EXPERIMENTAL\n#include <node_api.h>\n
      \n

      In this case the entire API surface, including any experimental APIs, will be\navailable to the module code.

      ", + "type": "misc", + "displayName": "Usage" + }, + { + "textRaw": "N-API version matrix", + "name": "n-api_version_matrix", + "desc": "

      N-API versions are additive and versioned independently from Node.js.\nVersion 4 is an extension to version 3 in that it has all of the APIs\nfrom version 3 with some additions. This means that it is not necessary\nto recompile for new versions of Node.js which are\nlisted as supporting a later version.

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      123456
      v6.xv6.14.2*
      v8.xv8.0.0*v8.10.0*v8.11.2v8.16.0
      v9.xv9.0.0*v9.3.0*v9.11.0*
      v10.xv10.0.0v10.0.0v10.0.0v10.16.0v10.17.0v10.20.0
      v11.xv11.0.0v11.0.0v11.0.0v11.8.0
      v12.xv12.0.0v12.0.0v12.0.0v12.0.0v12.11.0v12.17.0
      v13.xv13.0.0v13.0.0v13.0.0v13.0.0v13.0.0
      v14.xv14.0.0v14.0.0v14.0.0v14.0.0v14.0.0v14.0.0
      \n

      * Indicates that the N-API version was released as experimental

      \n

      Each API documented for N-API will have a header named added in:, and APIs\nwhich are stable will have the additional header N-API version:.\nAPIs are directly usable when using a Node.js version which supports\nthe N-API version shown in N-API version: or higher.\nWhen using a Node.js version that does not support the\nN-API version: listed or if there is no N-API version: listed,\nthen the API will only be available if\n#define NAPI_EXPERIMENTAL precedes the inclusion of node_api.h\nor js_native_api.h. If an API appears not to be available on\na version of Node.js which is later than the one shown in added in: then\nthis is most likely the reason for the apparent absence.

      \n

      The N-APIs associated strictly with accessing ECMAScript features from native\ncode can be found separately in js_native_api.h and js_native_api_types.h.\nThe APIs defined in these headers are included in node_api.h and\nnode_api_types.h. The headers are structured in this way in order to allow\nimplementations of N-API outside of Node.js. For those implementations the\nNode.js specific APIs may not be applicable.

      \n

      The Node.js-specific parts of an addon can be separated from the code that\nexposes the actual functionality to the JavaScript environment so that the\nlatter may be used with multiple implementations of N-API. In the example below,\naddon.c and addon.h refer only to js_native_api.h. This ensures that\naddon.c can be reused to compile against either the Node.js implementation of\nN-API or any implementation of N-API outside of Node.js.

      \n

      addon_node.c is a separate file that contains the Node.js specific entry point\nto the addon and which instantiates the addon by calling into addon.c when the\naddon is loaded into a Node.js environment.

      \n
      // addon.h\n#ifndef _ADDON_H_\n#define _ADDON_H_\n#include <js_native_api.h>\nnapi_value create_addon(napi_env env);\n#endif  // _ADDON_H_\n
      \n
      // addon.c\n#include \"addon.h\"\n\n#define NAPI_CALL(env, call)                                      \\\n  do {                                                            \\\n    napi_status status = (call);                                  \\\n    if (status != napi_ok) {                                      \\\n      const napi_extended_error_info* error_info = NULL;          \\\n      napi_get_last_error_info((env), &error_info);               \\\n      bool is_pending;                                            \\\n      napi_is_exception_pending((env), &is_pending);              \\\n      if (!is_pending) {                                          \\\n        const char* message = (error_info->error_message == NULL) \\\n            ? \"empty error message\"                               \\\n            : error_info->error_message;                          \\\n        napi_throw_error((env), NULL, message);                   \\\n        return NULL;                                              \\\n      }                                                           \\\n    }                                                             \\\n  } while(0)\n\nstatic napi_value\nDoSomethingUseful(napi_env env, napi_callback_info info) {\n  // Do something useful.\n  return NULL;\n}\n\nnapi_value create_addon(napi_env env) {\n  napi_value result;\n  NAPI_CALL(env, napi_create_object(env, &result));\n\n  napi_value exported_function;\n  NAPI_CALL(env, napi_create_function(env,\n                                      \"doSomethingUseful\",\n                                      NAPI_AUTO_LENGTH,\n                                      DoSomethingUseful,\n                                      NULL,\n                                      &exported_function));\n\n  NAPI_CALL(env, napi_set_named_property(env,\n                                         result,\n                                         \"doSomethingUseful\",\n                                         exported_function));\n\n  return result;\n}\n
      \n
      // addon_node.c\n#include <node_api.h>\n#include \"addon.h\"\n\nNAPI_MODULE_INIT() {\n  // This function body is expected to return a `napi_value`.\n  // The variables `napi_env env` and `napi_value exports` may be used within\n  // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.\n  return create_addon(env);\n}\n
      ", + "type": "misc", + "displayName": "N-API version matrix" + }, + { + "textRaw": "Environment life cycle APIs", + "name": "environment_life_cycle_apis", + "desc": "

      Section 8.7 of the ECMAScript Language Specification defines the concept\nof an \"Agent\" as a self-contained environment in which JavaScript code runs.\nMultiple such Agents may be started and terminated either concurrently or in\nsequence by the process.

      \n

      A Node.js environment corresponds to an ECMAScript Agent. In the main process,\nan environment is created at startup, and additional environments can be created\non separate threads to serve as worker threads. When Node.js is embedded in\nanother application, the main thread of the application may also construct and\ndestroy a Node.js environment multiple times during the life cycle of the\napplication process such that each Node.js environment created by the\napplication may, in turn, during its life cycle create and destroy additional\nenvironments as worker threads.

      \n

      From the perspective of a native addon this means that the bindings it provides\nmay be called multiple times, from multiple contexts, and even concurrently from\nmultiple threads.

      \n

      Native addons may need to allocate global state which they use during\ntheir entire life cycle such that the state must be unique to each instance of\nthe addon.

      \n

      To this end, N-API provides a way to allocate data such that its life cycle is\ntied to the life cycle of the Agent.

      ", + "modules": [ + { + "textRaw": "napi_set_instance_data", + "name": "napi_set_instance_data", + "meta": { + "added": [ + "v12.8.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_instance_data(napi_env env,\n                                   void* data,\n                                   napi_finalize finalize_cb,\n                                   void* finalize_hint);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] data: The data item to make available to bindings of this instance.
      • \n
      • [in] finalize_cb: The function to call when the environment is being torn\ndown. The function receives data so that it might free it.\nnapi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API associates data with the currently running Agent. data can later\nbe retrieved using napi_get_instance_data(). Any existing data associated with\nthe currently running Agent which was set by means of a previous call to\nnapi_set_instance_data() will be overwritten. If a finalize_cb was provided\nby the previous call, it will not be called.

      ", + "type": "module", + "displayName": "napi_set_instance_data" + }, + { + "textRaw": "napi_get_instance_data", + "name": "napi_get_instance_data", + "meta": { + "added": [ + "v12.8.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_instance_data(napi_env env,\n                                   void** data);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [out] data: The data item that was previously associated with the currently\nrunning Agent by a call to napi_set_instance_data().
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API retrieves data that was previously associated with the currently\nrunning Agent via napi_set_instance_data(). If no data is set, the call will\nsucceed and data will be set to NULL.

      ", + "type": "module", + "displayName": "napi_get_instance_data" + } + ], + "type": "misc", + "displayName": "Environment life cycle APIs" + }, + { + "textRaw": "Basic N-API data types", + "name": "basic_n-api_data_types", + "desc": "

      N-API exposes the following fundamental datatypes as abstractions that are\nconsumed by the various APIs. These APIs should be treated as opaque,\nintrospectable only with other N-API calls.

      ", + "modules": [ + { + "textRaw": "napi_status", + "name": "napi_status", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Integral status code indicating the success or failure of a N-API call.\nCurrently, the following status codes are supported.

      \n
      typedef enum {\n  napi_ok,\n  napi_invalid_arg,\n  napi_object_expected,\n  napi_string_expected,\n  napi_name_expected,\n  napi_function_expected,\n  napi_number_expected,\n  napi_boolean_expected,\n  napi_array_expected,\n  napi_generic_failure,\n  napi_pending_exception,\n  napi_cancelled,\n  napi_escape_called_twice,\n  napi_handle_scope_mismatch,\n  napi_callback_scope_mismatch,\n  napi_queue_full,\n  napi_closing,\n  napi_bigint_expected,\n  napi_date_expected,\n  napi_arraybuffer_expected,\n  napi_detachable_arraybuffer_expected,\n} napi_status;\n
      \n

      If additional information is required upon an API returning a failed status,\nit can be obtained by calling napi_get_last_error_info.

      ", + "type": "module", + "displayName": "napi_status" + }, + { + "textRaw": "napi_extended_error_info", + "name": "napi_extended_error_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      typedef struct {\n  const char* error_message;\n  void* engine_reserved;\n  uint32_t engine_error_code;\n  napi_status error_code;\n} napi_extended_error_info;\n
      \n
        \n
      • error_message: UTF8-encoded string containing a VM-neutral description of\nthe error.
      • \n
      • engine_reserved: Reserved for VM-specific error details. This is currently\nnot implemented for any VM.
      • \n
      • engine_error_code: VM-specific error code. This is currently\nnot implemented for any VM.
      • \n
      • error_code: The N-API status code that originated with the last error.
      • \n
      \n

      See the Error handling section for additional information.

      ", + "type": "module", + "displayName": "napi_extended_error_info" + }, + { + "textRaw": "napi_env", + "name": "napi_env", + "desc": "

      napi_env is used to represent a context that the underlying N-API\nimplementation can use to persist VM-specific state. This structure is passed\nto native functions when they're invoked, and it must be passed back when\nmaking N-API calls. Specifically, the same napi_env that was passed in when\nthe initial native function was called must be passed to any subsequent\nnested N-API calls. Caching the napi_env for the purpose of general reuse,\nand passing the napi_env between instances of the same addon running on\ndifferent Worker threads is not allowed. The napi_env becomes invalid\nwhen an instance of a native addon is unloaded. Notification of this event is\ndelivered through the callbacks given to napi_add_env_cleanup_hook and\nnapi_set_instance_data.

      ", + "type": "module", + "displayName": "napi_env" + }, + { + "textRaw": "napi_value", + "name": "napi_value", + "desc": "

      This is an opaque pointer that is used to represent a JavaScript value.

      ", + "type": "module", + "displayName": "napi_value" + }, + { + "textRaw": "napi_threadsafe_function", + "name": "napi_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      This is an opaque pointer that represents a JavaScript function which can be\ncalled asynchronously from multiple threads via\nnapi_call_threadsafe_function().

      ", + "type": "module", + "displayName": "napi_threadsafe_function" + }, + { + "textRaw": "napi_threadsafe_function_release_mode", + "name": "napi_threadsafe_function_release_mode", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      A value to be given to napi_release_threadsafe_function() to indicate whether\nthe thread-safe function is to be closed immediately (napi_tsfn_abort) or\nmerely released (napi_tsfn_release) and thus available for subsequent use via\nnapi_acquire_threadsafe_function() and napi_call_threadsafe_function().

      \n
      typedef enum {\n  napi_tsfn_release,\n  napi_tsfn_abort\n} napi_threadsafe_function_release_mode;\n
      ", + "type": "module", + "displayName": "napi_threadsafe_function_release_mode" + }, + { + "textRaw": "napi_threadsafe_function_call_mode", + "name": "napi_threadsafe_function_call_mode", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      A value to be given to napi_call_threadsafe_function() to indicate whether\nthe call should block whenever the queue associated with the thread-safe\nfunction is full.

      \n
      typedef enum {\n  napi_tsfn_nonblocking,\n  napi_tsfn_blocking\n} napi_threadsafe_function_call_mode;\n
      ", + "type": "module", + "displayName": "napi_threadsafe_function_call_mode" + }, + { + "textRaw": "N-API memory management types", + "name": "n-api_memory_management_types", + "modules": [ + { + "textRaw": "napi_handle_scope", + "name": "napi_handle_scope", + "desc": "

      This is an abstraction used to control and modify the lifetime of objects\ncreated within a particular scope. In general, N-API values are created within\nthe context of a handle scope. When a native method is called from\nJavaScript, a default handle scope will exist. If the user does not explicitly\ncreate a new handle scope, N-API values will be created in the default handle\nscope. For any invocations of code outside the execution of a native method\n(for instance, during a libuv callback invocation), the module is required to\ncreate a scope before invoking any functions that can result in the creation\nof JavaScript values.

      \n

      Handle scopes are created using napi_open_handle_scope and are destroyed\nusing napi_close_handle_scope. Closing the scope can indicate to the GC\nthat all napi_values created during the lifetime of the handle scope are no\nlonger referenced from the current stack frame.

      \n

      For more details, review the Object lifetime management.

      ", + "type": "module", + "displayName": "napi_handle_scope" + }, + { + "textRaw": "napi_escapable_handle_scope", + "name": "napi_escapable_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Escapable handle scopes are a special type of handle scope to return values\ncreated within a particular handle scope to a parent scope.

      ", + "type": "module", + "displayName": "napi_escapable_handle_scope" + }, + { + "textRaw": "napi_ref", + "name": "napi_ref", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      This is the abstraction to use to reference a napi_value. This allows for\nusers to manage the lifetimes of JavaScript values, including defining their\nminimum lifetimes explicitly.

      \n

      For more details, review the Object lifetime management.

      ", + "type": "module", + "displayName": "napi_ref" + }, + { + "textRaw": "napi_type_tag", + "name": "napi_type_tag", + "meta": { + "added": [ + "v12.19.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "

      A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID\nwith which JavaScript objects can be \"tagged\" in order to ensure that they are\nof a certain type. This is a stronger check than napi_instanceof, because\nthe latter can report a false positive if the object's prototype has been\nmanipulated. Type-tagging is most useful in conjunction with napi_wrap\nbecause it ensures that the pointer retrieved from a wrapped object can be\nsafely cast to the native type corresponding to the type tag that had been\npreviously applied to the JavaScript object.

      \n
      typedef struct {\n  uint64_t lower;\n  uint64_t upper;\n} napi_type_tag;\n
      ", + "type": "module", + "displayName": "napi_type_tag" + }, + { + "textRaw": "napi_async_cleanup_hook_handle", + "name": "napi_async_cleanup_hook_handle", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      An opaque value returned by napi_add_async_cleanup_hook. It must be passed\nto napi_remove_async_cleanup_hook when the chain of asynchronous cleanup\nevents completes.

      ", + "type": "module", + "displayName": "napi_async_cleanup_hook_handle" + } + ], + "type": "module", + "displayName": "N-API memory management types" + }, + { + "textRaw": "N-API callback types", + "name": "n-api_callback_types", + "modules": [ + { + "textRaw": "napi_callback_info", + "name": "napi_callback_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Opaque datatype that is passed to a callback function. It can be used for\ngetting additional information about the context in which the callback was\ninvoked.

      ", + "type": "module", + "displayName": "napi_callback_info" + }, + { + "textRaw": "napi_callback", + "name": "napi_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer type for user-provided native functions which are to be\nexposed to JavaScript via N-API. Callback functions should satisfy the\nfollowing signature:

      \n
      typedef napi_value (*napi_callback)(napi_env, napi_callback_info);\n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside a napi_callback is not necessary.

      ", + "type": "module", + "displayName": "napi_callback" + }, + { + "textRaw": "napi_finalize", + "name": "napi_finalize", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer type for add-on provided functions that allow the user to be\nnotified when externally-owned data is ready to be cleaned up because the\nobject with which it was associated with, has been garbage-collected. The user\nmust provide a function satisfying the following signature which would get\ncalled upon the object's collection. Currently, napi_finalize can be used for\nfinding out when objects that have external data are collected.

      \n
      typedef void (*napi_finalize)(napi_env env,\n                              void* finalize_data,\n                              void* finalize_hint);\n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

      ", + "type": "module", + "displayName": "napi_finalize" + }, + { + "textRaw": "napi_async_execute_callback", + "name": "napi_async_execute_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_async_execute_callback)(napi_env env, void* data);\n
      \n

      Implementations of this function must avoid making N-API calls that execute\nJavaScript or interact with JavaScript objects. N-API calls should be in the\nnapi_async_complete_callback instead. Do not use the napi_env parameter as\nit will likely result in execution of JavaScript.

      ", + "type": "module", + "displayName": "napi_async_execute_callback" + }, + { + "textRaw": "napi_async_complete_callback", + "name": "napi_async_complete_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_async_complete_callback)(napi_env env,\n                                             napi_status status,\n                                             void* data);\n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

      ", + "type": "module", + "displayName": "napi_async_complete_callback" + }, + { + "textRaw": "napi_threadsafe_function_call_js", + "name": "napi_threadsafe_function_call_js", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      Function pointer used with asynchronous thread-safe function calls. The callback\nwill be called on the main thread. Its purpose is to use a data item arriving\nvia the queue from one of the secondary threads to construct the parameters\nnecessary for a call into JavaScript, usually via napi_call_function, and then\nmake the call into JavaScript.

      \n

      The data arriving from the secondary thread via the queue is given in the data\nparameter and the JavaScript function to call is given in the js_callback\nparameter.

      \n

      N-API sets up the environment prior to calling this callback, so it is\nsufficient to call the JavaScript function via napi_call_function rather than\nvia napi_make_callback.

      \n

      Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_threadsafe_function_call_js)(napi_env env,\n                                                 napi_value js_callback,\n                                                 void* context,\n                                                 void* data);\n
      \n
        \n
      • [in] env: The environment to use for API calls, or NULL if the thread-safe\nfunction is being torn down and data may need to be freed.
      • \n
      • [in] js_callback: The JavaScript function to call, or NULL if the\nthread-safe function is being torn down and data may need to be freed. It\nmay also be NULL if the thread-safe function was created without\njs_callback.
      • \n
      • [in] context: The optional data with which the thread-safe function was\ncreated.
      • \n
      • [in] data: Data created by the secondary thread. It is the responsibility of\nthe callback to convert this native data to JavaScript values (with N-API\nfunctions) that can be passed as parameters when js_callback is invoked.\nThis pointer is managed entirely by the threads and this callback. Thus this\ncallback should free the data.
      • \n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

      ", + "type": "module", + "displayName": "napi_threadsafe_function_call_js" + }, + { + "textRaw": "napi_async_cleanup_hook", + "name": "napi_async_cleanup_hook", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      Function pointer used with napi_add_async_cleanup_hook. It will be called\nwhen the environment is being torn down.

      \n

      Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,\n                                        void* data);\n
      \n\n

      The body of the function should initiate the asynchronous cleanup actions at the\nend of which handle must be passed in a call to\nnapi_remove_async_cleanup_hook.

      ", + "type": "module", + "displayName": "napi_async_cleanup_hook" + } + ], + "type": "module", + "displayName": "N-API callback types" + } + ], + "type": "misc", + "displayName": "Basic N-API data types" + }, + { + "textRaw": "Error handling", + "name": "error_handling", + "desc": "

      N-API uses both return values and JavaScript exceptions for error handling.\nThe following sections explain the approach for each case.

      ", + "modules": [ + { + "textRaw": "Return values", + "name": "return_values", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      All of the N-API functions share the same error handling pattern. The\nreturn type of all API functions is napi_status.

      \n

      The return value will be napi_ok if the request was successful and\nno uncaught JavaScript exception was thrown. If an error occurred AND\nan exception was thrown, the napi_status value for the error\nwill be returned. If an exception was thrown, and no error occurred,\nnapi_pending_exception will be returned.

      \n

      In cases where a return value other than napi_ok or\nnapi_pending_exception is returned, napi_is_exception_pending\nmust be called to check if an exception is pending.\nSee the section on exceptions for more details.

      \n

      The full set of possible napi_status values is defined\nin napi_api_types.h.

      \n

      The napi_status return value provides a VM-independent representation of\nthe error which occurred. In some cases it is useful to be able to get\nmore detailed information, including a string representing the error as well as\nVM (engine)-specific information.

      \n

      In order to retrieve this information napi_get_last_error_info\nis provided which returns a napi_extended_error_info structure.\nThe format of the napi_extended_error_info structure is as follows:

      \n
      typedef struct napi_extended_error_info {\n  const char* error_message;\n  void* engine_reserved;\n  uint32_t engine_error_code;\n  napi_status error_code;\n};\n
      \n
        \n
      • error_message: Textual representation of the error that occurred.
      • \n
      • engine_reserved: Opaque handle reserved for engine use only.
      • \n
      • engine_error_code: VM specific error code.
      • \n
      • error_code: n-api status code for the last error.
      • \n
      \n

      napi_get_last_error_info returns the information for the last\nN-API call that was made.

      \n

      Do not rely on the content or format of any of the extended information as it\nis not subject to SemVer and may change at any time. It is intended only for\nlogging purposes.

      ", + "modules": [ + { + "textRaw": "napi_get_last_error_info", + "name": "napi_get_last_error_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status\nnapi_get_last_error_info(napi_env env,\n                         const napi_extended_error_info** result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: The napi_extended_error_info structure with more\ninformation about the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API retrieves a napi_extended_error_info structure with information\nabout the last error that occurred.

      \n

      The content of the napi_extended_error_info returned is only valid up until\nan n-api function is called on the same env.

      \n

      Do not rely on the content or format of any of the extended information as it\nis not subject to SemVer and may change at any time. It is intended only for\nlogging purposes.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_get_last_error_info" + } + ], + "type": "module", + "displayName": "Return values" + }, + { + "textRaw": "Exceptions", + "name": "exceptions", + "desc": "

      Any N-API function call may result in a pending JavaScript exception. This is\nthe case for any of the API functions, even those that may not cause the\nexecution of JavaScript.

      \n

      If the napi_status returned by a function is napi_ok then no\nexception is pending and no additional action is required. If the\nnapi_status returned is anything other than napi_ok or\nnapi_pending_exception, in order to try to recover and continue\ninstead of simply returning immediately, napi_is_exception_pending\nmust be called in order to determine if an exception is pending or not.

      \n

      In many cases when an N-API function is called and an exception is\nalready pending, the function will return immediately with a\nnapi_status of napi_pending_exception. However, this is not the case\nfor all functions. N-API allows a subset of the functions to be\ncalled to allow for some minimal cleanup before returning to JavaScript.\nIn that case, napi_status will reflect the status for the function. It\nwill not reflect previous pending exceptions. To avoid confusion, check\nthe error status after every function call.

      \n

      When an exception is pending one of two approaches can be employed.

      \n

      The first approach is to do any appropriate cleanup and then return so that\nexecution will return to JavaScript. As part of the transition back to\nJavaScript, the exception will be thrown at the point in the JavaScript\ncode where the native method was invoked. The behavior of most N-API calls\nis unspecified while an exception is pending, and many will simply return\nnapi_pending_exception, so do as little as possible and then return to\nJavaScript where the exception can be handled.

      \n

      The second approach is to try to handle the exception. There will be cases\nwhere the native code can catch the exception, take the appropriate action,\nand then continue. This is only recommended in specific cases\nwhere it is known that the exception can be safely handled. In these\ncases napi_get_and_clear_last_exception can be used to get and\nclear the exception. On success, result will contain the handle to\nthe last JavaScript Object thrown. If it is determined, after\nretrieving the exception, the exception cannot be handled after all\nit can be re-thrown it with napi_throw where error is the\nJavaScript Error object to be thrown.

      \n

      The following utility functions are also available in case native code\nneeds to throw an exception or determine if a napi_value is an instance\nof a JavaScript Error object: napi_throw_error,\nnapi_throw_type_error, napi_throw_range_error and\nnapi_is_error.

      \n

      The following utility functions are also available in case native\ncode needs to create an Error object: napi_create_error,\nnapi_create_type_error, and napi_create_range_error,\nwhere result is the napi_value that refers to the newly created\nJavaScript Error object.

      \n

      The Node.js project is adding error codes to all of the errors\ngenerated internally. The goal is for applications to use these\nerror codes for all error checking. The associated error messages\nwill remain, but will only be meant to be used for logging and\ndisplay with the expectation that the message can change without\nSemVer applying. In order to support this model with N-API, both\nin internal functionality and for module specific functionality\n(as its good practice), the throw_ and create_ functions\ntake an optional code parameter which is the string for the code\nto be added to the error object. If the optional parameter is NULL\nthen no code will be associated with the error. If a code is provided,\nthe name associated with the error is also updated to be:

      \n
      originalName [code]\n
      \n

      where originalName is the original name associated with the error\nand code is the code that was provided. For example, if the code\nis 'ERR_ERROR_1' and a TypeError is being created the name will be:

      \n
      TypeError [ERR_ERROR_1]\n
      ", + "modules": [ + { + "textRaw": "napi_throw", + "name": "napi_throw", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] error: The JavaScript value to be thrown.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws the JavaScript value provided.

      ", + "type": "module", + "displayName": "napi_throw" + }, + { + "textRaw": "napi_throw_error", + "name": "napi_throw_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw_error(napi_env env,\n                                         const char* code,\n                                         const char* msg);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional error code to be set on the error.
      • \n
      • [in] msg: C string representing the text to be associated with the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws a JavaScript Error with the text provided.

      ", + "type": "module", + "displayName": "napi_throw_error" + }, + { + "textRaw": "napi_throw_type_error", + "name": "napi_throw_type_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,\n                                              const char* code,\n                                              const char* msg);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional error code to be set on the error.
      • \n
      • [in] msg: C string representing the text to be associated with the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws a JavaScript TypeError with the text provided.

      ", + "type": "module", + "displayName": "napi_throw_type_error" + }, + { + "textRaw": "napi_throw_range_error", + "name": "napi_throw_range_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,\n                                               const char* code,\n                                               const char* msg);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional error code to be set on the error.
      • \n
      • [in] msg: C string representing the text to be associated with the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws a JavaScript RangeError with the text provided.

      ", + "type": "module", + "displayName": "napi_throw_range_error" + }, + { + "textRaw": "napi_is_error", + "name": "napi_is_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_is_error(napi_env env,\n                                      napi_value value,\n                                      bool* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The napi_value to be checked.
      • \n
      • [out] result: Boolean value that is set to true if napi_value represents\nan error, false otherwise.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API queries a napi_value to check if it represents an error object.

      ", + "type": "module", + "displayName": "napi_is_error" + }, + { + "textRaw": "napi_create_error", + "name": "napi_create_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_error(napi_env env,\n                                          napi_value code,\n                                          napi_value msg,\n                                          napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional napi_value with the string for the error code to be\nassociated with the error.
      • \n
      • [in] msg: napi_value that references a JavaScript String to be used as\nthe message for the Error.
      • \n
      • [out] result: napi_value representing the error created.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns a JavaScript Error with the text provided.

      ", + "type": "module", + "displayName": "napi_create_error" + }, + { + "textRaw": "napi_create_type_error", + "name": "napi_create_type_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_type_error(napi_env env,\n                                               napi_value code,\n                                               napi_value msg,\n                                               napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional napi_value with the string for the error code to be\nassociated with the error.
      • \n
      • [in] msg: napi_value that references a JavaScript String to be used as\nthe message for the Error.
      • \n
      • [out] result: napi_value representing the error created.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns a JavaScript TypeError with the text provided.

      ", + "type": "module", + "displayName": "napi_create_type_error" + }, + { + "textRaw": "napi_create_range_error", + "name": "napi_create_range_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_range_error(napi_env env,\n                                                napi_value code,\n                                                napi_value msg,\n                                                napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional napi_value with the string for the error code to be\nassociated with the error.
      • \n
      • [in] msg: napi_value that references a JavaScript String to be used as\nthe message for the Error.
      • \n
      • [out] result: napi_value representing the error created.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns a JavaScript RangeError with the text provided.

      ", + "type": "module", + "displayName": "napi_create_range_error" + }, + { + "textRaw": "napi_get_and_clear_last_exception", + "name": "napi_get_and_clear_last_exception", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_and_clear_last_exception(napi_env env,\n                                              napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: The exception if one is pending, NULL otherwise.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_get_and_clear_last_exception" + }, + { + "textRaw": "napi_is_exception_pending", + "name": "napi_is_exception_pending", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_exception_pending(napi_env env, bool* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: Boolean value that is set to true if an exception is pending.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_is_exception_pending" + }, + { + "textRaw": "napi_fatal_exception", + "name": "napi_fatal_exception", + "meta": { + "added": [ + "v9.10.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      napi_status napi_fatal_exception(napi_env env, napi_value err);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] err: The error that is passed to 'uncaughtException'.
      • \n
      \n

      Trigger an 'uncaughtException' in JavaScript. Useful if an async\ncallback throws an exception with no way to recover.

      ", + "type": "module", + "displayName": "napi_fatal_exception" + } + ], + "type": "module", + "displayName": "Exceptions" + }, + { + "textRaw": "Fatal errors", + "name": "fatal_errors", + "desc": "

      In the event of an unrecoverable error in a native module, a fatal error can be\nthrown to immediately terminate the process.

      ", + "modules": [ + { + "textRaw": "napi_fatal_error", + "name": "napi_fatal_error", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_NO_RETURN void napi_fatal_error(const char* location,\n                                                 size_t location_len,\n                                                 const char* message,\n                                                 size_t message_len);\n
      \n
        \n
      • [in] location: Optional location at which the error occurred.
      • \n
      • [in] location_len: The length of the location in bytes, or\nNAPI_AUTO_LENGTH if it is null-terminated.
      • \n
      • [in] message: The message associated with the error.
      • \n
      • [in] message_len: The length of the message in bytes, or NAPI_AUTO_LENGTH\nif it is null-terminated.
      • \n
      \n

      The function call does not return, the process will be terminated.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_fatal_error" + } + ], + "type": "module", + "displayName": "Fatal errors" + } + ], + "type": "misc", + "displayName": "Error handling" + }, + { + "textRaw": "Object lifetime management", + "name": "object_lifetime_management", + "desc": "

      As N-API calls are made, handles to objects in the heap for the underlying\nVM may be returned as napi_values. These handles must hold the\nobjects 'live' until they are no longer required by the native code,\notherwise the objects could be collected before the native code was\nfinished using them.

      \n

      As object handles are returned they are associated with a\n'scope'. The lifespan for the default scope is tied to the lifespan\nof the native method call. The result is that, by default, handles\nremain valid and the objects associated with these handles will be\nheld live for the lifespan of the native method call.

      \n

      In many cases, however, it is necessary that the handles remain valid for\neither a shorter or longer lifespan than that of the native method.\nThe sections which follow describe the N-API functions that can be used\nto change the handle lifespan from the default.

      ", + "modules": [ + { + "textRaw": "Making handle lifespan shorter than that of the native method", + "name": "making_handle_lifespan_shorter_than_that_of_the_native_method", + "desc": "

      It is often necessary to make the lifespan of handles shorter than\nthe lifespan of a native method. For example, consider a native method\nthat has a loop which iterates through the elements in a large array:

      \n
      for (int i = 0; i < 1000000; i++) {\n  napi_value result;\n  napi_status status = napi_get_element(env, object, i, &result);\n  if (status != napi_ok) {\n    break;\n  }\n  // do something with element\n}\n
      \n

      This would result in a large number of handles being created, consuming\nsubstantial resources. In addition, even though the native code could only\nuse the most recent handle, all of the associated objects would also be\nkept alive since they all share the same scope.

      \n

      To handle this case, N-API provides the ability to establish a new 'scope' to\nwhich newly created handles will be associated. Once those handles\nare no longer required, the scope can be 'closed' and any handles associated\nwith the scope are invalidated. The methods available to open/close scopes are\nnapi_open_handle_scope and napi_close_handle_scope.

      \n

      N-API only supports a single nested hierarchy of scopes. There is only one\nactive scope at any time, and all new handles will be associated with that\nscope while it is active. Scopes must be closed in the reverse order from\nwhich they are opened. In addition, all scopes created within a native method\nmust be closed before returning from that method.

      \n

      Taking the earlier example, adding calls to napi_open_handle_scope and\nnapi_close_handle_scope would ensure that at most a single handle\nis valid throughout the execution of the loop:

      \n
      for (int i = 0; i < 1000000; i++) {\n  napi_handle_scope scope;\n  napi_status status = napi_open_handle_scope(env, &scope);\n  if (status != napi_ok) {\n    break;\n  }\n  napi_value result;\n  status = napi_get_element(env, object, i, &result);\n  if (status != napi_ok) {\n    break;\n  }\n  // do something with element\n  status = napi_close_handle_scope(env, scope);\n  if (status != napi_ok) {\n    break;\n  }\n}\n
      \n

      When nesting scopes, there are cases where a handle from an\ninner scope needs to live beyond the lifespan of that scope. N-API supports an\n'escapable scope' in order to support this case. An escapable scope\nallows one handle to be 'promoted' so that it 'escapes' the\ncurrent scope and the lifespan of the handle changes from the current\nscope to that of the outer scope.

      \n

      The methods available to open/close escapable scopes are\nnapi_open_escapable_handle_scope and\nnapi_close_escapable_handle_scope.

      \n

      The request to promote a handle is made through napi_escape_handle which\ncan only be called once.

      ", + "modules": [ + { + "textRaw": "napi_open_handle_scope", + "name": "napi_open_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,\n                                               napi_handle_scope* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing the new scope.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API opens a new scope.

      ", + "type": "module", + "displayName": "napi_open_handle_scope" + }, + { + "textRaw": "napi_close_handle_scope", + "name": "napi_close_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,\n                                                napi_handle_scope scope);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: napi_value representing the scope to be closed.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_close_handle_scope" + }, + { + "textRaw": "napi_open_escapable_handle_scope", + "name": "napi_open_escapable_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\n    napi_open_escapable_handle_scope(napi_env env,\n                                     napi_handle_scope* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing the new scope.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API opens a new scope from which one object can be promoted\nto the outer scope.

      ", + "type": "module", + "displayName": "napi_open_escapable_handle_scope" + }, + { + "textRaw": "napi_close_escapable_handle_scope", + "name": "napi_close_escapable_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\n    napi_close_escapable_handle_scope(napi_env env,\n                                      napi_handle_scope scope);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: napi_value representing the scope to be closed.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_close_escapable_handle_scope" + }, + { + "textRaw": "napi_escape_handle", + "name": "napi_escape_handle", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_escape_handle(napi_env env,\n                               napi_escapable_handle_scope scope,\n                               napi_value escapee,\n                               napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: napi_value representing the current scope.
      • \n
      • [in] escapee: napi_value representing the JavaScript Object to be\nescaped.
      • \n
      • [out] result: napi_value representing the handle to the escaped Object\nin the outer scope.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API promotes the handle to the JavaScript object so that it is valid\nfor the lifetime of the outer scope. It can only be called once per scope.\nIf it is called more than once an error will be returned.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_escape_handle" + } + ], + "type": "module", + "displayName": "Making handle lifespan shorter than that of the native method" + }, + { + "textRaw": "References to objects with a lifespan longer than that of the native method", + "name": "references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method", + "desc": "

      In some cases an addon will need to be able to create and reference objects\nwith a lifespan longer than that of a single native method invocation. For\nexample, to create a constructor and later use that constructor\nin a request to creates instances, it must be possible to reference\nthe constructor object across many different instance creation requests. This\nwould not be possible with a normal handle returned as a napi_value as\ndescribed in the earlier section. The lifespan of a normal handle is\nmanaged by scopes and all scopes must be closed before the end of a native\nmethod.

      \n

      N-API provides methods to create persistent references to an object.\nEach persistent reference has an associated count with a value of 0\nor higher. The count determines if the reference will keep\nthe corresponding object live. References with a count of 0 do not\nprevent the object from being collected and are often called 'weak'\nreferences. Any count greater than 0 will prevent the object\nfrom being collected.

      \n

      References can be created with an initial reference count. The count can\nthen be modified through napi_reference_ref and\nnapi_reference_unref. If an object is collected while the count\nfor a reference is 0, all subsequent calls to\nget the object associated with the reference napi_get_reference_value\nwill return NULL for the returned napi_value. An attempt to call\nnapi_reference_ref for a reference whose object has been collected\nwill result in an error.

      \n

      References must be deleted once they are no longer required by the addon. When\na reference is deleted it will no longer prevent the corresponding object from\nbeing collected. Failure to delete a persistent reference will result in\na 'memory leak' with both the native memory for the persistent reference and\nthe corresponding object on the heap being retained forever.

      \n

      There can be multiple persistent references created which refer to the same\nobject, each of which will either keep the object live or not based on its\nindividual count.

      ", + "modules": [ + { + "textRaw": "napi_create_reference", + "name": "napi_create_reference", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_reference(napi_env env,\n                                              napi_value value,\n                                              uint32_t initial_refcount,\n                                              napi_ref* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing the Object to which we want a\nreference.
      • \n
      • [in] initial_refcount: Initial reference count for the new reference.
      • \n
      • [out] result: napi_ref pointing to the new reference.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API create a new reference with the specified reference count\nto the Object passed in.

      ", + "type": "module", + "displayName": "napi_create_reference" + }, + { + "textRaw": "napi_delete_reference", + "name": "napi_delete_reference", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref to be deleted.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API deletes the reference passed in.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_delete_reference" + }, + { + "textRaw": "napi_reference_ref", + "name": "napi_reference_ref", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_reference_ref(napi_env env,\n                                           napi_ref ref,\n                                           uint32_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref for which the reference count will be incremented.
      • \n
      • [out] result: The new reference count.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API increments the reference count for the reference\npassed in and returns the resulting reference count.

      ", + "type": "module", + "displayName": "napi_reference_ref" + }, + { + "textRaw": "napi_reference_unref", + "name": "napi_reference_unref", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_reference_unref(napi_env env,\n                                             napi_ref ref,\n                                             uint32_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref for which the reference count will be decremented.
      • \n
      • [out] result: The new reference count.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API decrements the reference count for the reference\npassed in and returns the resulting reference count.

      ", + "type": "module", + "displayName": "napi_reference_unref" + }, + { + "textRaw": "napi_get_reference_value", + "name": "napi_get_reference_value", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,\n                                                 napi_ref ref,\n                                                 napi_value* result);\n
      \n

      the napi_value passed in or out of these methods is a handle to the\nobject to which the reference is related.

      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref for which we requesting the corresponding Object.
      • \n
      • [out] result: The napi_value for the Object referenced by the\nnapi_ref.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      If still valid, this API returns the napi_value representing the\nJavaScript Object associated with the napi_ref. Otherwise, result\nwill be NULL.

      ", + "type": "module", + "displayName": "napi_get_reference_value" + } + ], + "type": "module", + "displayName": "References to objects with a lifespan longer than that of the native method" + }, + { + "textRaw": "Cleanup on exit of the current Node.js instance", + "name": "cleanup_on_exit_of_the_current_node.js_instance", + "desc": "

      While a Node.js process typically releases all its resources when exiting,\nembedders of Node.js, or future Worker support, may require addons to register\nclean-up hooks that will be run once the current Node.js instance exits.

      \n

      N-API provides functions for registering and un-registering such callbacks.\nWhen those callbacks are run, all resources that are being held by the addon\nshould be freed up.

      ", + "modules": [ + { + "textRaw": "napi_add_env_cleanup_hook", + "name": "napi_add_env_cleanup_hook", + "meta": { + "added": [ + "v10.2.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,\n                                                  void (*fun)(void* arg),\n                                                  void* arg);\n
      \n

      Registers fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits.

      \n

      A function can safely be specified multiple times with different\narg values. In that case, it will be called multiple times as well.\nProviding the same fun and arg values multiple times is not allowed\nand will lead the process to abort.

      \n

      The hooks will be called in reverse order, i.e. the most recently added one\nwill be called first.

      \n

      Removing this hook can be done by using napi_remove_env_cleanup_hook.\nTypically, that happens when the resource for which this hook was added\nis being torn down anyway.

      \n

      For asynchronous cleanup, napi_add_async_cleanup_hook is available.

      ", + "type": "module", + "displayName": "napi_add_env_cleanup_hook" + }, + { + "textRaw": "napi_remove_env_cleanup_hook", + "name": "napi_remove_env_cleanup_hook", + "meta": { + "added": [ + "v10.2.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,\n                                                     void (*fun)(void* arg),\n                                                     void* arg);\n
      \n

      Unregisters fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits. Both the argument and the function value\nneed to be exact matches.

      \n

      The function must have originally been registered\nwith napi_add_env_cleanup_hook, otherwise the process will abort.

      ", + "type": "module", + "displayName": "napi_remove_env_cleanup_hook" + }, + { + "textRaw": "napi_add_async_cleanup_hook", + "name": "napi_add_async_cleanup_hook", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34819", + "description": "Changed signature of the `hook` callback." + } + ], + "napiVersion": [ + 8 + ] + }, + "desc": "
      NAPI_EXTERN napi_status napi_add_async_cleanup_hook(\n    napi_env env,\n    napi_async_cleanup_hook hook,\n    void* arg,\n    napi_async_cleanup_hook_handle* remove_handle);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] hook: The function pointer to call at environment teardown.
      • \n
      • [in] arg: The pointer to pass to hook when it gets called.
      • \n
      • [out] remove_handle: Optional handle that refers to the asynchronous cleanup\nhook.
      • \n
      \n

      Registers hook, which is a function of type napi_async_cleanup_hook, as\na function to be run with the remove_handle and arg parameters once the\ncurrent Node.js environment exits.

      \n

      Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.

      \n

      Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.

      \n

      If remove_handle is not NULL, an opaque value will be stored in it\nthat must later be passed to napi_remove_async_cleanup_hook,\nregardless of whether the hook has already been invoked.\nTypically, that happens when the resource for which this hook was added\nis being torn down anyway.

      ", + "type": "module", + "displayName": "napi_add_async_cleanup_hook" + }, + { + "textRaw": "napi_remove_async_cleanup_hook", + "name": "napi_remove_async_cleanup_hook", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34819", + "description": "Removed `env` parameter." + } + ] + }, + "desc": "
      NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(\n    napi_async_cleanup_hook_handle remove_handle);\n
      \n\n

      Unregisters the cleanup hook corresponding to remove_handle. This will prevent\nthe hook from being executed, unless it has already started executing.\nThis must be called on any napi_async_cleanup_hook_handle value obtained\nfrom napi_add_async_cleanup_hook.

      ", + "type": "module", + "displayName": "napi_remove_async_cleanup_hook" + } + ], + "type": "module", + "displayName": "Cleanup on exit of the current Node.js instance" + } + ], + "type": "misc", + "displayName": "Object lifetime management" + }, + { + "textRaw": "Module registration", + "name": "module_registration", + "desc": "

      N-API modules are registered in a manner similar to other modules\nexcept that instead of using the NODE_MODULE macro the following\nis used:

      \n
      NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n
      \n

      The next difference is the signature for the Init method. For a N-API\nmodule it is as follows:

      \n
      napi_value Init(napi_env env, napi_value exports);\n
      \n

      The return value from Init is treated as the exports object for the module.\nThe Init method is passed an empty object via the exports parameter as a\nconvenience. If Init returns NULL, the parameter passed as exports is\nexported by the module. N-API modules cannot modify the module object but can\nspecify anything as the exports property of the module.

      \n

      To add the method hello as a function so that it can be called as a method\nprovided by the addon:

      \n
      napi_value Init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_property_descriptor desc = {\n    \"hello\",\n    NULL,\n    Method,\n    NULL,\n    NULL,\n    NULL,\n    napi_writable | napi_enumerable | napi_configurable,\n    NULL\n  };\n  status = napi_define_properties(env, exports, 1, &desc);\n  if (status != napi_ok) return NULL;\n  return exports;\n}\n
      \n

      To set a function to be returned by the require() for the addon:

      \n
      napi_value Init(napi_env env, napi_value exports) {\n  napi_value method;\n  napi_status status;\n  status = napi_create_function(env, \"exports\", NAPI_AUTO_LENGTH, Method, NULL, &method);\n  if (status != napi_ok) return NULL;\n  return method;\n}\n
      \n

      To define a class so that new instances can be created (often used with\nObject wrap):

      \n
      // NOTE: partial example, not all referenced code is included\nnapi_value Init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_property_descriptor properties[] = {\n    { \"value\", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL },\n    DECLARE_NAPI_METHOD(\"plusOne\", PlusOne),\n    DECLARE_NAPI_METHOD(\"multiply\", Multiply),\n  };\n\n  napi_value cons;\n  status =\n      napi_define_class(env, \"MyObject\", New, NULL, 3, properties, &cons);\n  if (status != napi_ok) return NULL;\n\n  status = napi_create_reference(env, cons, 1, &constructor);\n  if (status != napi_ok) return NULL;\n\n  status = napi_set_named_property(env, exports, \"MyObject\", cons);\n  if (status != napi_ok) return NULL;\n\n  return exports;\n}\n
      \n

      If the module will be loaded multiple times during the lifetime of the Node.js\nprocess, use the NAPI_MODULE_INIT macro to initialize the module:

      \n
      NAPI_MODULE_INIT() {\n  napi_value answer;\n  napi_status result;\n\n  status = napi_create_int64(env, 42, &answer);\n  if (status != napi_ok) return NULL;\n\n  status = napi_set_named_property(env, exports, \"answer\", answer);\n  if (status != napi_ok) return NULL;\n\n  return exports;\n}\n
      \n

      This macro includes NAPI_MODULE, and declares an Init function with a\nspecial name and with visibility beyond the addon. This will allow Node.js to\ninitialize the module even if it is loaded multiple times.

      \n

      There are a few design considerations when declaring a module that may be loaded\nmultiple times. The documentation of context-aware addons provides more\ndetails.

      \n

      The variables env and exports will be available inside the function body\nfollowing the macro invocation.

      \n

      For more details on setting properties on objects, see the section on\nWorking with JavaScript properties.

      \n

      For more details on building addon modules in general, refer to the existing\nAPI.

      ", + "type": "misc", + "displayName": "Module registration" + }, + { + "textRaw": "Working with JavaScript values", + "name": "working_with_javascript_values", + "desc": "

      N-API exposes a set of APIs to create all types of JavaScript values.\nSome of these types are documented under Section 6\nof the ECMAScript Language Specification.

      \n

      Fundamentally, these APIs are used to do one of the following:

      \n
        \n
      1. Create a new JavaScript object
      2. \n
      3. Convert from a primitive C type to an N-API value
      4. \n
      5. Convert from N-API value to a primitive C type
      6. \n
      7. Get global instances including undefined and null
      8. \n
      \n

      N-API values are represented by the type napi_value.\nAny N-API call that requires a JavaScript value takes in a napi_value.\nIn some cases, the API does check the type of the napi_value up-front.\nHowever, for better performance, it's better for the caller to make sure that\nthe napi_value in question is of the JavaScript type expected by the API.

      ", + "modules": [ + { + "textRaw": "Enum types", + "name": "enum_types", + "modules": [ + { + "textRaw": "napi_key_collection_mode", + "name": "napi_key_collection_mode", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      typedef enum {\n  napi_key_include_prototypes,\n  napi_key_own_only\n} napi_key_collection_mode;\n
      \n

      Describes the Keys/Properties filter enums:

      \n

      napi_key_collection_mode limits the range of collected properties.

      \n

      napi_key_own_only limits the collected properties to the given\nobject only. napi_key_include_prototypes will include all keys\nof the objects's prototype chain as well.

      ", + "type": "module", + "displayName": "napi_key_collection_mode" + }, + { + "textRaw": "napi_key_filter", + "name": "napi_key_filter", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      typedef enum {\n  napi_key_all_properties = 0,\n  napi_key_writable = 1,\n  napi_key_enumerable = 1 << 1,\n  napi_key_configurable = 1 << 2,\n  napi_key_skip_strings = 1 << 3,\n  napi_key_skip_symbols = 1 << 4\n} napi_key_filter;\n
      \n

      Property filter bits. They can be or'ed to build a composite filter.

      ", + "type": "module", + "displayName": "napi_key_filter" + }, + { + "textRaw": "napi_key_conversion", + "name": "napi_key_conversion", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      typedef enum {\n  napi_key_keep_numbers,\n  napi_key_numbers_to_strings\n} napi_key_conversion;\n
      \n

      napi_key_numbers_to_strings will convert integer indices to\nstrings. napi_key_keep_numbers will return numbers for integer\nindices.

      ", + "type": "module", + "displayName": "napi_key_conversion" + }, + { + "textRaw": "napi_valuetype", + "name": "napi_valuetype", + "desc": "
      typedef enum {\n  // ES6 types (corresponds to typeof)\n  napi_undefined,\n  napi_null,\n  napi_boolean,\n  napi_number,\n  napi_string,\n  napi_symbol,\n  napi_object,\n  napi_function,\n  napi_external,\n  napi_bigint,\n} napi_valuetype;\n
      \n

      Describes the type of a napi_value. This generally corresponds to the types\ndescribed in Section 6.1 of the ECMAScript Language Specification.\nIn addition to types in that section, napi_valuetype can also represent\nFunctions and Objects with external data.

      \n

      A JavaScript value of type napi_external appears in JavaScript as a plain\nobject such that no properties can be set on it, and no prototype.

      ", + "type": "module", + "displayName": "napi_valuetype" + }, + { + "textRaw": "napi_typedarray_type", + "name": "napi_typedarray_type", + "desc": "
      typedef enum {\n  napi_int8_array,\n  napi_uint8_array,\n  napi_uint8_clamped_array,\n  napi_int16_array,\n  napi_uint16_array,\n  napi_int32_array,\n  napi_uint32_array,\n  napi_float32_array,\n  napi_float64_array,\n  napi_bigint64_array,\n  napi_biguint64_array,\n} napi_typedarray_type;\n
      \n

      This represents the underlying binary scalar datatype of the TypedArray.\nElements of this enum correspond to\nSection 22.2 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_typedarray_type" + } + ], + "type": "module", + "displayName": "Enum types" + }, + { + "textRaw": "Object creation functions", + "name": "object_creation_functions", + "modules": [ + { + "textRaw": "napi_create_array", + "name": "napi_create_array", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_array(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [out] result: A napi_value representing a JavaScript Array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript Array type.\nJavaScript arrays are described in\nSection 22.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_array" + }, + { + "textRaw": "napi_create_array_with_length", + "name": "napi_create_array_with_length", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_array_with_length(napi_env env,\n                                          size_t length,\n                                          napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: The initial length of the Array.
      • \n
      • [out] result: A napi_value representing a JavaScript Array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript Array type.\nThe Array's length property is set to the passed-in length parameter.\nHowever, the underlying buffer is not guaranteed to be pre-allocated by the VM\nwhen the array is created. That behavior is left to the underlying VM\nimplementation. If the buffer must be a contiguous block of memory that can be\ndirectly read and/or written via C, consider using\nnapi_create_external_arraybuffer.

      \n

      JavaScript arrays are described in\nSection 22.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_array_with_length" + }, + { + "textRaw": "napi_create_arraybuffer", + "name": "napi_create_arraybuffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_arraybuffer(napi_env env,\n                                    size_t byte_length,\n                                    void** data,\n                                    napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: The length in bytes of the array buffer to create.
      • \n
      • [out] data: Pointer to the underlying byte buffer of the ArrayBuffer.
      • \n
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer.\nArrayBuffers are used to represent fixed-length binary data buffers. They are\nnormally used as a backing-buffer for TypedArray objects.\nThe ArrayBuffer allocated will have an underlying byte buffer whose size is\ndetermined by the length parameter that's passed in.\nThe underlying buffer is optionally returned back to the caller in case the\ncaller wants to directly manipulate the buffer. This buffer can only be\nwritten to directly from native code. To write to this buffer from JavaScript,\na typed array or DataView object would need to be created.

      \n

      JavaScript ArrayBuffer objects are described in\nSection 24.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_arraybuffer" + }, + { + "textRaw": "napi_create_buffer", + "name": "napi_create_buffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_buffer(napi_env env,\n                               size_t size,\n                               void** data,\n                               napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] size: Size in bytes of the underlying buffer.
      • \n
      • [out] data: Raw pointer to the underlying buffer.
      • \n
      • [out] result: A napi_value representing a node::Buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a node::Buffer object. While this is still a\nfully-supported data structure, in most cases using a TypedArray will suffice.

      ", + "type": "module", + "displayName": "napi_create_buffer" + }, + { + "textRaw": "napi_create_buffer_copy", + "name": "napi_create_buffer_copy", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_buffer_copy(napi_env env,\n                                    size_t length,\n                                    const void* data,\n                                    void** result_data,\n                                    napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] size: Size in bytes of the input buffer (should be the same as the size\nof the new buffer).
      • \n
      • [in] data: Raw pointer to the underlying buffer to copy from.
      • \n
      • [out] result_data: Pointer to the new Buffer's underlying data buffer.
      • \n
      • [out] result: A napi_value representing a node::Buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a node::Buffer object and initializes it with data copied\nfrom the passed-in buffer. While this is still a fully-supported data\nstructure, in most cases using a TypedArray will suffice.

      ", + "type": "module", + "displayName": "napi_create_buffer_copy" + }, + { + "textRaw": "napi_create_date", + "name": "napi_create_date", + "meta": { + "added": [ + "v11.11.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_date(napi_env env,\n                             double time,\n                             napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] time: ECMAScript time value in milliseconds since 01 January, 1970 UTC.
      • \n
      • [out] result: A napi_value representing a JavaScript Date.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.

      \n

      This API allocates a JavaScript Date object.

      \n

      JavaScript Date objects are described in\nSection 20.3 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_date" + }, + { + "textRaw": "napi_create_external", + "name": "napi_create_external", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_external(napi_env env,\n                                 void* data,\n                                 napi_finalize finalize_cb,\n                                 void* finalize_hint,\n                                 napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] data: Raw pointer to the external data.
      • \n
      • [in] finalize_cb: Optional callback to call when the external value is being\ncollected. napi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      • [out] result: A napi_value representing an external value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a JavaScript value with external data attached to it. This\nis used to pass external data through JavaScript code, so it can be retrieved\nlater by native code using napi_get_value_external.

      \n

      The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the object created by the API can be used with napi_wrap().
      • \n
      \n

      The created value is not an object, and therefore does not support additional\nproperties. It is considered a distinct value type: calling napi_typeof() with\nan external value yields napi_external.

      ", + "type": "module", + "displayName": "napi_create_external" + }, + { + "textRaw": "napi_create_external_arraybuffer", + "name": "napi_create_external_arraybuffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status\nnapi_create_external_arraybuffer(napi_env env,\n                                 void* external_data,\n                                 size_t byte_length,\n                                 napi_finalize finalize_cb,\n                                 void* finalize_hint,\n                                 napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] external_data: Pointer to the underlying byte buffer of the\nArrayBuffer.
      • \n
      • [in] byte_length: The length in bytes of the underlying buffer.
      • \n
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being\ncollected. napi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer.\nThe underlying byte buffer of the ArrayBuffer is externally allocated and\nmanaged. The caller must ensure that the byte buffer remains valid until the\nfinalize callback is called.

      \n

      The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the object created by the API can be used with napi_wrap().
      • \n
      \n

      JavaScript ArrayBuffers are described in\nSection 24.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_external_arraybuffer" + }, + { + "textRaw": "napi_create_external_buffer", + "name": "napi_create_external_buffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_external_buffer(napi_env env,\n                                        size_t length,\n                                        void* data,\n                                        napi_finalize finalize_cb,\n                                        void* finalize_hint,\n                                        napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: Size in bytes of the input buffer (should be the same as the\nsize of the new buffer).
      • \n
      • [in] data: Raw pointer to the underlying buffer to expose to JavaScript.
      • \n
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being\ncollected. napi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      • [out] result: A napi_value representing a node::Buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a node::Buffer object and initializes it with data\nbacked by the passed in buffer. While this is still a fully-supported data\nstructure, in most cases using a TypedArray will suffice.

      \n

      The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the object created by the API can be used with napi_wrap().
      • \n
      \n

      For Node.js >=4 Buffers are Uint8Arrays.

      ", + "type": "module", + "displayName": "napi_create_external_buffer" + }, + { + "textRaw": "napi_create_object", + "name": "napi_create_object", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_object(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: A napi_value representing a JavaScript Object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a default JavaScript Object.\nIt is the equivalent of doing new Object() in JavaScript.

      \n

      The JavaScript Object type is described in Section 6.1.7 of the\nECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_object" + }, + { + "textRaw": "napi_create_symbol", + "name": "napi_create_symbol", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_symbol(napi_env env,\n                               napi_value description,\n                               napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] description: Optional napi_value which refers to a JavaScript\nString to be set as the description for the symbol.
      • \n
      • [out] result: A napi_value representing a JavaScript Symbol.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript Symbol object from a UTF8-encoded C string.

      \n

      The JavaScript Symbol type is described in Section 19.4\nof the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_symbol" + }, + { + "textRaw": "napi_create_typedarray", + "name": "napi_create_typedarray", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_typedarray(napi_env env,\n                                   napi_typedarray_type type,\n                                   size_t length,\n                                   napi_value arraybuffer,\n                                   size_t byte_offset,\n                                   napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] type: Scalar datatype of the elements within the TypedArray.
      • \n
      • [in] length: Number of elements in the TypedArray.
      • \n
      • [in] arraybuffer: ArrayBuffer underlying the typed array.
      • \n
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to\nstart projecting the TypedArray.
      • \n
      • [out] result: A napi_value representing a JavaScript TypedArray.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript TypedArray object over an existing\nArrayBuffer. TypedArray objects provide an array-like view over an\nunderlying data buffer where each element has the same underlying binary scalar\ndatatype.

      \n

      It's required that (length * size_of_element) + byte_offset should\nbe <= the size in bytes of the array passed in. If not, a RangeError exception\nis raised.

      \n

      JavaScript TypedArray objects are described in\nSection 22.2 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_typedarray" + }, + { + "textRaw": "napi_create_dataview", + "name": "napi_create_dataview", + "meta": { + "added": [ + "v8.3.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_dataview(napi_env env,\n                                 size_t byte_length,\n                                 napi_value arraybuffer,\n                                 size_t byte_offset,\n                                 napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: Number of elements in the DataView.
      • \n
      • [in] arraybuffer: ArrayBuffer underlying the DataView.
      • \n
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to\nstart projecting the DataView.
      • \n
      • [out] result: A napi_value representing a JavaScript DataView.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript DataView object over an existing ArrayBuffer.\nDataView objects provide an array-like view over an underlying data buffer,\nbut one which allows items of different size and type in the ArrayBuffer.

      \n

      It is required that byte_length + byte_offset is less than or equal to the\nsize in bytes of the array passed in. If not, a RangeError exception is\nraised.

      \n

      JavaScript DataView objects are described in\nSection 24.3 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_dataview" + } + ], + "type": "module", + "displayName": "Object creation functions" + }, + { + "textRaw": "Functions to convert from C types to N-API", + "name": "functions_to_convert_from_c_types_to_n-api", + "modules": [ + { + "textRaw": "napi_create_int32", + "name": "napi_create_int32", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C int32_t type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_int32" + }, + { + "textRaw": "napi_create_uint32", + "name": "napi_create_uint32", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C uint32_t type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_uint32" + }, + { + "textRaw": "napi_create_int64", + "name": "napi_create_int64", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C int64_t type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in Section 6.1.6\nof the ECMAScript Language Specification. Note the complete range of int64_t\ncannot be represented with full precision in JavaScript. Integer values\noutside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) -\nNumber.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.

      ", + "type": "module", + "displayName": "napi_create_int64" + }, + { + "textRaw": "napi_create_double", + "name": "napi_create_double", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_double(napi_env env, double value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Double-precision value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C double type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_double" + }, + { + "textRaw": "napi_create_bigint_int64", + "name": "napi_create_bigint_int64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_bigint_int64(napi_env env,\n                                     int64_t value,\n                                     napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript BigInt.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts the C int64_t type to the JavaScript BigInt type.

      ", + "type": "module", + "displayName": "napi_create_bigint_int64" + }, + { + "textRaw": "napi_create_bigint_uint64", + "name": "napi_create_bigint_uint64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_bigint_uint64(napi_env env,\n                                      uint64_t value,\n                                      napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript BigInt.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts the C uint64_t type to the JavaScript BigInt type.

      ", + "type": "module", + "displayName": "napi_create_bigint_uint64" + }, + { + "textRaw": "napi_create_bigint_words", + "name": "napi_create_bigint_words", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_bigint_words(napi_env env,\n                                     int sign_bit,\n                                     size_t word_count,\n                                     const uint64_t* words,\n                                     napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] sign_bit: Determines if the resulting BigInt will be positive or\nnegative.
      • \n
      • [in] word_count: The length of the words array.
      • \n
      • [in] words: An array of uint64_t little-endian 64-bit words.
      • \n
      • [out] result: A napi_value representing a JavaScript BigInt.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts an array of unsigned 64-bit words into a single BigInt\nvalue.

      \n

      The resulting BigInt is calculated as: (–1)sign_bit (words[0]\n× (264)0 + words[1] × (264)1 + …)

      ", + "type": "module", + "displayName": "napi_create_bigint_words" + }, + { + "textRaw": "napi_create_string_latin1", + "name": "napi_create_string_latin1", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_string_latin1(napi_env env,\n                                      const char* str,\n                                      size_t length,\n                                      napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] str: Character buffer representing an ISO-8859-1-encoded string.
      • \n
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.
      • \n
      • [out] result: A napi_value representing a JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript String object from an ISO-8859-1-encoded C\nstring. The native string is copied.

      \n

      The JavaScript String type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_string_latin1" + }, + { + "textRaw": "napi_create_string_utf16", + "name": "napi_create_string_utf16", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_string_utf16(napi_env env,\n                                     const char16_t* str,\n                                     size_t length,\n                                     napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] str: Character buffer representing a UTF16-LE-encoded string.
      • \n
      • [in] length: The length of the string in two-byte code units, or\nNAPI_AUTO_LENGTH if it is null-terminated.
      • \n
      • [out] result: A napi_value representing a JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript String object from a UTF16-LE-encoded C string.\nThe native string is copied.

      \n

      The JavaScript String type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_string_utf16" + }, + { + "textRaw": "napi_create_string_utf8", + "name": "napi_create_string_utf8", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_string_utf8(napi_env env,\n                                    const char* str,\n                                    size_t length,\n                                    napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] str: Character buffer representing a UTF8-encoded string.
      • \n
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.
      • \n
      • [out] result: A napi_value representing a JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript String object from a UTF8-encoded C string.\nThe native string is copied.

      \n

      The JavaScript String type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_string_utf8" + } + ], + "type": "module", + "displayName": "Functions to convert from C types to N-API" + }, + { + "textRaw": "Functions to convert from N-API to C types", + "name": "functions_to_convert_from_n-api_to_c_types", + "modules": [ + { + "textRaw": "napi_get_array_length", + "name": "napi_get_array_length", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_array_length(napi_env env,\n                                  napi_value value,\n                                  uint32_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing the JavaScript Array whose length is\nbeing queried.
      • \n
      • [out] result: uint32 representing length of the array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the length of an array.

      \n

      Array length is described in Section 22.1.4.1 of the ECMAScript Language\nSpecification.

      ", + "type": "module", + "displayName": "napi_get_array_length" + }, + { + "textRaw": "napi_get_arraybuffer_info", + "name": "napi_get_arraybuffer_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_arraybuffer_info(napi_env env,\n                                      napi_value arraybuffer,\n                                      void** data,\n                                      size_t* byte_length)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] arraybuffer: napi_value representing the ArrayBuffer being queried.
      • \n
      • [out] data: The underlying data buffer of the ArrayBuffer. If byte_length\nis 0, this may be NULL or any other pointer value.
      • \n
      • [out] byte_length: Length in bytes of the underlying data buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to retrieve the underlying data buffer of an ArrayBuffer and\nits length.

      \n

      WARNING: Use caution while using this API. The lifetime of the underlying data\nbuffer is managed by the ArrayBuffer even after it's returned. A\npossible safe way to use this API is in conjunction with\nnapi_create_reference, which can be used to guarantee control over the\nlifetime of the ArrayBuffer. It's also safe to use the returned data buffer\nwithin the same callback as long as there are no calls to other APIs that might\ntrigger a GC.

      ", + "type": "module", + "displayName": "napi_get_arraybuffer_info" + }, + { + "textRaw": "napi_get_buffer_info", + "name": "napi_get_buffer_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_buffer_info(napi_env env,\n                                 napi_value value,\n                                 void** data,\n                                 size_t* length)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing the node::Buffer being queried.
      • \n
      • [out] data: The underlying data buffer of the node::Buffer.\nIf length is 0, this may be NULL or any other pointer value.
      • \n
      • [out] length: Length in bytes of the underlying data buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to retrieve the underlying data buffer of a node::Buffer\nand it's length.

      \n

      Warning: Use caution while using this API since the underlying data buffer's\nlifetime is not guaranteed if it's managed by the VM.

      ", + "type": "module", + "displayName": "napi_get_buffer_info" + }, + { + "textRaw": "napi_get_prototype", + "name": "napi_get_prototype", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_prototype(napi_env env,\n                               napi_value object,\n                               napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] object: napi_value representing JavaScript Object whose prototype\nto return. This returns the equivalent of Object.getPrototypeOf (which is\nnot the same as the function's prototype property).
      • \n
      • [out] result: napi_value representing prototype of the given object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      ", + "type": "module", + "displayName": "napi_get_prototype" + }, + { + "textRaw": "napi_get_typedarray_info", + "name": "napi_get_typedarray_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_typedarray_info(napi_env env,\n                                     napi_value typedarray,\n                                     napi_typedarray_type* type,\n                                     size_t* length,\n                                     void** data,\n                                     napi_value* arraybuffer,\n                                     size_t* byte_offset)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] typedarray: napi_value representing the TypedArray whose\nproperties to query.
      • \n
      • [out] type: Scalar datatype of the elements within the TypedArray.
      • \n
      • [out] length: The number of elements in the TypedArray.
      • \n
      • [out] data: The data buffer underlying the TypedArray adjusted by\nthe byte_offset value so that it points to the first element in the\nTypedArray. If the length of the array is 0, this may be NULL or\nany other pointer value.
      • \n
      • [out] arraybuffer: The ArrayBuffer underlying the TypedArray.
      • \n
      • [out] byte_offset: The byte offset within the underlying native array\nat which the first element of the arrays is located. The value for the data\nparameter has already been adjusted so that data points to the first element\nin the array. Therefore, the first byte of the native array would be at\ndata - byte_offset.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns various properties of a typed array.

      \n

      Warning: Use caution while using this API since the underlying data buffer\nis managed by the VM.

      ", + "type": "module", + "displayName": "napi_get_typedarray_info" + }, + { + "textRaw": "napi_get_dataview_info", + "name": "napi_get_dataview_info", + "meta": { + "added": [ + "v8.3.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_dataview_info(napi_env env,\n                                   napi_value dataview,\n                                   size_t* byte_length,\n                                   void** data,\n                                   napi_value* arraybuffer,\n                                   size_t* byte_offset)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] dataview: napi_value representing the DataView whose\nproperties to query.
      • \n
      • [out] byte_length: Number of bytes in the DataView.
      • \n
      • [out] data: The data buffer underlying the DataView.\nIf byte_length is 0, this may be NULL or any other pointer value.
      • \n
      • [out] arraybuffer: ArrayBuffer underlying the DataView.
      • \n
      • [out] byte_offset: The byte offset within the data buffer from which\nto start projecting the DataView.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns various properties of a DataView.

      ", + "type": "module", + "displayName": "napi_get_dataview_info" + }, + { + "textRaw": "napi_get_date_value", + "name": "napi_get_date_value", + "meta": { + "added": [ + "v11.11.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_date_value(napi_env env,\n                                napi_value value,\n                                double* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing a JavaScript Date.
      • \n
      • [out] result: Time value as a double represented as milliseconds since\nmidnight at the beginning of 01 January, 1970 UTC.
      • \n
      \n

      This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.

      \n

      Returns napi_ok if the API succeeded. If a non-date napi_value is passed\nin it returns napi_date_expected.

      \n

      This API returns the C double primitive of time value for the given JavaScript\nDate.

      ", + "type": "module", + "displayName": "napi_get_date_value" + }, + { + "textRaw": "napi_get_value_bool", + "name": "napi_get_value_bool", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Boolean.
      • \n
      • [out] result: C boolean primitive equivalent of the given JavaScript\nBoolean.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-boolean napi_value is\npassed in it returns napi_boolean_expected.

      \n

      This API returns the C boolean primitive equivalent of the given JavaScript\nBoolean.

      ", + "type": "module", + "displayName": "napi_get_value_bool" + }, + { + "textRaw": "napi_get_value_double", + "name": "napi_get_value_double", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_double(napi_env env,\n                                  napi_value value,\n                                  double* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C double primitive equivalent of the given JavaScript\nNumber.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value is passed\nin it returns napi_number_expected.

      \n

      This API returns the C double primitive equivalent of the given JavaScript\nNumber.

      ", + "type": "module", + "displayName": "napi_get_value_double" + }, + { + "textRaw": "napi_get_value_bigint_int64", + "name": "napi_get_value_bigint_int64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bigint_int64(napi_env env,\n                                        napi_value value,\n                                        int64_t* result,\n                                        bool* lossless);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under
      • \n
      • [in] value: napi_value representing JavaScript BigInt.
      • \n
      • [out] result: C int64_t primitive equivalent of the given JavaScript\nBigInt.
      • \n
      • [out] lossless: Indicates whether the BigInt value was converted\nlosslessly.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.

      \n

      This API returns the C int64_t primitive equivalent of the given JavaScript\nBigInt. If needed it will truncate the value, setting lossless to false.

      ", + "type": "module", + "displayName": "napi_get_value_bigint_int64" + }, + { + "textRaw": "napi_get_value_bigint_uint64", + "name": "napi_get_value_bigint_uint64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bigint_uint64(napi_env env,\n                                        napi_value value,\n                                        uint64_t* result,\n                                        bool* lossless);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript BigInt.
      • \n
      • [out] result: C uint64_t primitive equivalent of the given JavaScript\nBigInt.
      • \n
      • [out] lossless: Indicates whether the BigInt value was converted\nlosslessly.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.

      \n

      This API returns the C uint64_t primitive equivalent of the given JavaScript\nBigInt. If needed it will truncate the value, setting lossless to false.

      ", + "type": "module", + "displayName": "napi_get_value_bigint_uint64" + }, + { + "textRaw": "napi_get_value_bigint_words", + "name": "napi_get_value_bigint_words", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bigint_words(napi_env env,\n                                        napi_value value,\n                                        int* sign_bit,\n                                        size_t* word_count,\n                                        uint64_t* words);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript BigInt.
      • \n
      • [out] sign_bit: Integer representing if the JavaScript BigInt is positive\nor negative.
      • \n
      • [in/out] word_count: Must be initialized to the length of the words\narray. Upon return, it will be set to the actual number of words that\nwould be needed to store this BigInt.
      • \n
      • [out] words: Pointer to a pre-allocated 64-bit word array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts a single BigInt value into a sign bit, 64-bit little-endian\narray, and the number of elements in the array. sign_bit and words may be\nboth set to NULL, in order to get only word_count.

      ", + "type": "module", + "displayName": "napi_get_value_bigint_words" + }, + { + "textRaw": "napi_get_value_external", + "name": "napi_get_value_external", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_external(napi_env env,\n                                    napi_value value,\n                                    void** result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript external value.
      • \n
      • [out] result: Pointer to the data wrapped by the JavaScript external value.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-external napi_value is\npassed in it returns napi_invalid_arg.

      \n

      This API retrieves the external data pointer that was previously passed to\nnapi_create_external().

      ", + "type": "module", + "displayName": "napi_get_value_external" + }, + { + "textRaw": "napi_get_value_int32", + "name": "napi_get_value_int32", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_int32(napi_env env,\n                                 napi_value value,\n                                 int32_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C int32 primitive equivalent of the given JavaScript\nNumber.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in napi_number_expected.

      \n

      This API returns the C int32 primitive equivalent\nof the given JavaScript Number.

      \n

      If the number exceeds the range of the 32 bit integer, then the result is\ntruncated to the equivalent of the bottom 32 bits. This can result in a large\npositive number becoming a negative number if the value is > 231 - 1.

      \n

      Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.

      ", + "type": "module", + "displayName": "napi_get_value_int32" + }, + { + "textRaw": "napi_get_value_int64", + "name": "napi_get_value_int64", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_int64(napi_env env,\n                                 napi_value value,\n                                 int64_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C int64 primitive equivalent of the given JavaScript\nNumber.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.

      \n

      This API returns the C int64 primitive equivalent of the given JavaScript\nNumber.

      \n

      Number values outside the range of Number.MIN_SAFE_INTEGER\n-(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose\nprecision.

      \n

      Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.

      ", + "type": "module", + "displayName": "napi_get_value_int64" + }, + { + "textRaw": "napi_get_value_string_latin1", + "name": "napi_get_value_string_latin1", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_string_latin1(napi_env env,\n                                         napi_value value,\n                                         char* buf,\n                                         size_t bufsize,\n                                         size_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript string.
      • \n
      • [in] buf: Buffer to write the ISO-8859-1-encoded string into. If NULL is\npassed in, the length of the string (in bytes) is returned.
      • \n
      • [in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string will be truncated.
      • \n
      • [out] result: Number of bytes copied into the buffer, excluding the null\nterminator.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-String napi_value\nis passed in it returns napi_string_expected.

      \n

      This API returns the ISO-8859-1-encoded string corresponding the value passed\nin.

      ", + "type": "module", + "displayName": "napi_get_value_string_latin1" + }, + { + "textRaw": "napi_get_value_string_utf8", + "name": "napi_get_value_string_utf8", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_string_utf8(napi_env env,\n                                       napi_value value,\n                                       char* buf,\n                                       size_t bufsize,\n                                       size_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript string.
      • \n
      • [in] buf: Buffer to write the UTF8-encoded string into. If NULL is passed\nin, the length of the string (in bytes) is returned.
      • \n
      • [in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string will be truncated.
      • \n
      • [out] result: Number of bytes copied into the buffer, excluding the null\nterminator.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-String napi_value\nis passed in it returns napi_string_expected.

      \n

      This API returns the UTF8-encoded string corresponding the value passed in.

      ", + "type": "module", + "displayName": "napi_get_value_string_utf8" + }, + { + "textRaw": "napi_get_value_string_utf16", + "name": "napi_get_value_string_utf16", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_string_utf16(napi_env env,\n                                        napi_value value,\n                                        char16_t* buf,\n                                        size_t bufsize,\n                                        size_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript string.
      • \n
      • [in] buf: Buffer to write the UTF16-LE-encoded string into. If NULL is\npassed in, the length of the string (in 2-byte code units) is returned.
      • \n
      • [in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string will be truncated.
      • \n
      • [out] result: Number of 2-byte code units copied into the buffer, excluding\nthe null terminator.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-String napi_value\nis passed in it returns napi_string_expected.

      \n

      This API returns the UTF16-encoded string corresponding the value passed in.

      ", + "type": "module", + "displayName": "napi_get_value_string_utf16" + }, + { + "textRaw": "napi_get_value_uint32", + "name": "napi_get_value_uint32", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_uint32(napi_env env,\n                                  napi_value value,\n                                  uint32_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C primitive equivalent of the given napi_value as a\nuint32_t.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.

      \n

      This API returns the C primitive equivalent of the given napi_value as a\nuint32_t.

      ", + "type": "module", + "displayName": "napi_get_value_uint32" + } + ], + "type": "module", + "displayName": "Functions to convert from N-API to C types" + }, + { + "textRaw": "Functions to get global instances", + "name": "functions_to_get_global_instances", + "modules": [ + { + "textRaw": "napi_get_boolean", + "name": "napi_get_boolean", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The value of the boolean to retrieve.
      • \n
      • [out] result: napi_value representing JavaScript Boolean singleton to\nretrieve.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to return the JavaScript singleton object that is used to\nrepresent the given boolean value.

      ", + "type": "module", + "displayName": "napi_get_boolean" + }, + { + "textRaw": "napi_get_global", + "name": "napi_get_global", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_global(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing JavaScript global object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the global object.

      ", + "type": "module", + "displayName": "napi_get_global" + }, + { + "textRaw": "napi_get_null", + "name": "napi_get_null", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_null(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing JavaScript null object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the null object.

      ", + "type": "module", + "displayName": "napi_get_null" + }, + { + "textRaw": "napi_get_undefined", + "name": "napi_get_undefined", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_undefined(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing JavaScript Undefined value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the Undefined object.

      ", + "type": "module", + "displayName": "napi_get_undefined" + } + ], + "type": "module", + "displayName": "Functions to get global instances" + } + ], + "type": "misc", + "displayName": "Working with JavaScript values" + }, + { + "textRaw": "Working with JavaScript values and abstract operations", + "name": "working_with_javascript_values_and_abstract_operations", + "desc": "

      N-API exposes a set of APIs to perform some abstract operations on JavaScript\nvalues. Some of these operations are documented under Section 7\nof the ECMAScript Language Specification.

      \n

      These APIs support doing one of the following:

      \n
        \n
      1. Coerce JavaScript values to specific JavaScript types (such as Number or\nString).
      2. \n
      3. Check the type of a JavaScript value.
      4. \n
      5. Check for equality between two JavaScript values.
      6. \n
      ", + "modules": [ + { + "textRaw": "napi_coerce_to_bool", + "name": "napi_coerce_to_bool", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_bool(napi_env env,\n                                napi_value value,\n                                napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript Boolean.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToBoolean() as defined in\nSection 7.1.2 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_bool" + }, + { + "textRaw": "napi_coerce_to_number", + "name": "napi_coerce_to_number", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_number(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToNumber() as defined in\nSection 7.1.3 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_number" + }, + { + "textRaw": "napi_coerce_to_object", + "name": "napi_coerce_to_object", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_object(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript Object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToObject() as defined in\nSection 7.1.13 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_object" + }, + { + "textRaw": "napi_coerce_to_string", + "name": "napi_coerce_to_string", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_string(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToString() as defined in\nSection 7.1.13 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_string" + }, + { + "textRaw": "napi_typeof", + "name": "napi_typeof", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value whose type to query.
      • \n
      • [out] result: The type of the JavaScript value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n
        \n
      • napi_invalid_arg if the type of value is not a known ECMAScript type and\nvalue is not an External value.
      • \n
      \n

      This API represents behavior similar to invoking the typeof Operator on\nthe object as defined in Section 12.5.5 of the ECMAScript Language\nSpecification. However, there are some differences:

      \n
        \n
      1. It has support for detecting an External value.
      2. \n
      3. It detects null as a separate type, while ECMAScript typeof would detect\nobject.
      4. \n
      \n

      If value has a type that is invalid, an error is returned.

      ", + "type": "module", + "displayName": "napi_typeof" + }, + { + "textRaw": "napi_instanceof", + "name": "napi_instanceof", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_instanceof(napi_env env,\n                            napi_value object,\n                            napi_value constructor,\n                            bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] object: The JavaScript value to check.
      • \n
      • [in] constructor: The JavaScript function object of the constructor function\nto check against.
      • \n
      • [out] result: Boolean that is set to true if object instanceof constructor\nis true.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API represents invoking the instanceof Operator on the object as\ndefined in Section 12.10.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_instanceof" + }, + { + "textRaw": "napi_is_array", + "name": "napi_is_array", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_array(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given object is an array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API represents invoking the IsArray operation on the object\nas defined in Section 7.2.2 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_is_array" + }, + { + "textRaw": "napi_is_arraybuffer", + "name": "napi_is_arraybuffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given object is an ArrayBuffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is an array buffer.

      ", + "type": "module", + "displayName": "napi_is_arraybuffer" + }, + { + "textRaw": "napi_is_buffer", + "name": "napi_is_buffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a node::Buffer\nobject.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a buffer.

      ", + "type": "module", + "displayName": "napi_is_buffer" + }, + { + "textRaw": "napi_is_date", + "name": "napi_is_date", + "meta": { + "added": [ + "v11.11.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_date(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a JavaScript Date\nobject.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a date.

      ", + "type": "module", + "displayName": "napi_is_date" + }, + { + "textRaw": "napi_is_error", + "name": "napi_is_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_error(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents an Error object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is an Error.

      ", + "type": "module", + "displayName": "napi_is_error" + }, + { + "textRaw": "napi_is_typedarray", + "name": "napi_is_typedarray", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a TypedArray.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a typed array.

      ", + "type": "module", + "displayName": "napi_is_typedarray" + }, + { + "textRaw": "napi_is_dataview", + "name": "napi_is_dataview", + "meta": { + "added": [ + "v8.3.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a DataView.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a DataView.

      ", + "type": "module", + "displayName": "napi_is_dataview" + }, + { + "textRaw": "napi_strict_equals", + "name": "napi_strict_equals", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_strict_equals(napi_env env,\n                               napi_value lhs,\n                               napi_value rhs,\n                               bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] lhs: The JavaScript value to check.
      • \n
      • [in] rhs: The JavaScript value to check against.
      • \n
      • [out] result: Whether the two napi_value objects are equal.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API represents the invocation of the Strict Equality algorithm as\ndefined in Section 7.2.14 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_strict_equals" + }, + { + "textRaw": "napi_detach_arraybuffer", + "name": "napi_detach_arraybuffer", + "meta": { + "added": [ + "v12.16.0" + ], + "napiVersion": [ + 7 + ], + "changes": [] + }, + "desc": "
      napi_status napi_detach_arraybuffer(napi_env env,\n                                    napi_value arraybuffer)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] arraybuffer: The JavaScript ArrayBuffer to be detached.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is\npassed in it returns napi_detachable_arraybuffer_expected.

      \n

      Generally, an ArrayBuffer is non-detachable if it has been detached before.\nThe engine may impose additional conditions on whether an ArrayBuffer is\ndetachable. For example, V8 requires that the ArrayBuffer be external,\nthat is, created with napi_create_external_arraybuffer.

      \n

      This API represents the invocation of the ArrayBuffer detach operation as\ndefined in Section 24.1.1.3 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_detach_arraybuffer" + }, + { + "textRaw": "napi_is_detached_arraybuffer", + "name": "napi_is_detached_arraybuffer", + "meta": { + "added": [ + "v12.16.0" + ], + "napiVersion": [ + 7 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_detached_arraybuffer(napi_env env,\n                                         napi_value arraybuffer,\n                                         bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] arraybuffer: The JavaScript ArrayBuffer to be checked.
      • \n
      • [out] result: Whether the arraybuffer is detached.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      The ArrayBuffer is considered detached if its internal data is null.

      \n

      This API represents the invocation of the ArrayBuffer IsDetachedBuffer\noperation as defined in Section 24.1.1.2 of the ECMAScript Language\nSpecification.

      ", + "type": "module", + "displayName": "napi_is_detached_arraybuffer" + } + ], + "type": "misc", + "displayName": "Working with JavaScript values and abstract operations" + }, + { + "textRaw": "Working with JavaScript properties", + "name": "working_with_javascript_properties", + "desc": "

      N-API exposes a set of APIs to get and set properties on JavaScript\nobjects. Some of these types are documented under Section 7 of the\nECMAScript Language Specification.

      \n

      Properties in JavaScript are represented as a tuple of a key and a value.\nFundamentally, all property keys in N-API can be represented in one of the\nfollowing forms:

      \n
        \n
      • Named: a simple UTF8-encoded string
      • \n
      • Integer-Indexed: an index value represented by uint32_t
      • \n
      • JavaScript value: these are represented in N-API by napi_value. This can\nbe a napi_value representing a String, Number, or Symbol.
      • \n
      \n

      N-API values are represented by the type napi_value.\nAny N-API call that requires a JavaScript value takes in a napi_value.\nHowever, it's the caller's responsibility to make sure that the\nnapi_value in question is of the JavaScript type expected by the API.

      \n

      The APIs documented in this section provide a simple interface to\nget and set properties on arbitrary JavaScript objects represented by\nnapi_value.

      \n

      For instance, consider the following JavaScript code snippet:

      \n
      const obj = {};\nobj.myProp = 123;\n
      \n

      The equivalent can be done using N-API values with the following snippet:

      \n
      napi_status status = napi_generic_failure;\n\n// const obj = {}\nnapi_value obj, value;\nstatus = napi_create_object(env, &obj);\nif (status != napi_ok) return status;\n\n// Create a napi_value for 123\nstatus = napi_create_int32(env, 123, &value);\nif (status != napi_ok) return status;\n\n// obj.myProp = 123\nstatus = napi_set_named_property(env, obj, \"myProp\", value);\nif (status != napi_ok) return status;\n
      \n

      Indexed properties can be set in a similar manner. Consider the following\nJavaScript snippet:

      \n
      const arr = [];\narr[123] = 'hello';\n
      \n

      The equivalent can be done using N-API values with the following snippet:

      \n
      napi_status status = napi_generic_failure;\n\n// const arr = [];\nnapi_value arr, value;\nstatus = napi_create_array(env, &arr);\nif (status != napi_ok) return status;\n\n// Create a napi_value for 'hello'\nstatus = napi_create_string_utf8(env, \"hello\", NAPI_AUTO_LENGTH, &value);\nif (status != napi_ok) return status;\n\n// arr[123] = 'hello';\nstatus = napi_set_element(env, arr, 123, value);\nif (status != napi_ok) return status;\n
      \n

      Properties can be retrieved using the APIs described in this section.\nConsider the following JavaScript snippet:

      \n
      const arr = [];\nconst value = arr[123];\n
      \n

      The following is the approximate equivalent of the N-API counterpart:

      \n
      napi_status status = napi_generic_failure;\n\n// const arr = []\nnapi_value arr, value;\nstatus = napi_create_array(env, &arr);\nif (status != napi_ok) return status;\n\n// const value = arr[123]\nstatus = napi_get_element(env, arr, 123, &value);\nif (status != napi_ok) return status;\n
      \n

      Finally, multiple properties can also be defined on an object for performance\nreasons. Consider the following JavaScript:

      \n
      const obj = {};\nObject.defineProperties(obj, {\n  'foo': { value: 123, writable: true, configurable: true, enumerable: true },\n  'bar': { value: 456, writable: true, configurable: true, enumerable: true }\n});\n
      \n

      The following is the approximate equivalent of the N-API counterpart:

      \n
      napi_status status = napi_status_generic_failure;\n\n// const obj = {};\nnapi_value obj;\nstatus = napi_create_object(env, &obj);\nif (status != napi_ok) return status;\n\n// Create napi_values for 123 and 456\nnapi_value fooValue, barValue;\nstatus = napi_create_int32(env, 123, &fooValue);\nif (status != napi_ok) return status;\nstatus = napi_create_int32(env, 456, &barValue);\nif (status != napi_ok) return status;\n\n// Set the properties\nnapi_property_descriptor descriptors[] = {\n  { \"foo\", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL },\n  { \"bar\", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL }\n}\nstatus = napi_define_properties(env,\n                                obj,\n                                sizeof(descriptors) / sizeof(descriptors[0]),\n                                descriptors);\nif (status != napi_ok) return status;\n
      ", + "modules": [ + { + "textRaw": "Structures", + "name": "structures", + "modules": [ + { + "textRaw": "napi_property_attributes", + "name": "napi_property_attributes", + "meta": { + "changes": [ + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/35214", + "description": "added `napi_default_method` and `napi_default_property`" + } + ] + }, + "desc": "
      typedef enum {\n  napi_default = 0,\n  napi_writable = 1 << 0,\n  napi_enumerable = 1 << 1,\n  napi_configurable = 1 << 2,\n\n  // Used with napi_define_class to distinguish static properties\n  // from instance properties. Ignored by napi_define_properties.\n  napi_static = 1 << 10,\n\n  // Default for class methods.\n  napi_default_method = napi_writable | napi_configurable,\n\n  // Default for object properties, like in JS obj[prop].\n  napi_default_property = napi_writable |\n                          napi_enumerable |\n                          napi_configurable,\n} napi_property_attributes;\n
      \n

      napi_property_attributes are flags used to control the behavior of properties\nset on a JavaScript object. Other than napi_static they correspond to the\nattributes listed in Section 6.1.7.1\nof the ECMAScript Language Specification.\nThey can be one or more of the following bitflags:

      \n
        \n
      • napi_default: No explicit attributes are set on the property. By default, a\nproperty is read only, not enumerable and not configurable.
      • \n
      • napi_writable: The property is writable.
      • \n
      • napi_enumerable: The property is enumerable.
      • \n
      • napi_configurable: The property is configurable as defined in\nSection 6.1.7.1 of the ECMAScript Language Specification.
      • \n
      • napi_static: The property will be defined as a static property on a class as\nopposed to an instance property, which is the default. This is used only by\nnapi_define_class. It is ignored by napi_define_properties.
      • \n
      • napi_default_method: The property is configureable, writeable but not\nenumerable like a method in a JS class.
      • \n
      • napi_default_property: The property is writable, enumerable and configurable\nlike a property set via JS code obj.key = value.
      • \n
      ", + "type": "module", + "displayName": "napi_property_attributes" + }, + { + "textRaw": "napi_property_descriptor", + "name": "napi_property_descriptor", + "desc": "
      typedef struct {\n  // One of utf8name or name should be NULL.\n  const char* utf8name;\n  napi_value name;\n\n  napi_callback method;\n  napi_callback getter;\n  napi_callback setter;\n  napi_value value;\n\n  napi_property_attributes attributes;\n  void* data;\n} napi_property_descriptor;\n
      \n
        \n
      • utf8name: Optional String describing the key for the property,\nencoded as UTF8. One of utf8name or name must be provided for the\nproperty.
      • \n
      • name: Optional napi_value that points to a JavaScript string or symbol\nto be used as the key for the property. One of utf8name or name must\nbe provided for the property.
      • \n
      • value: The value that's retrieved by a get access of the property if the\nproperty is a data property. If this is passed in, set getter, setter,\nmethod and data to NULL (since these members won't be used).
      • \n
      • getter: A function to call when a get access of the property is performed.\nIf this is passed in, set value and method to NULL (since these members\nwon't be used). The given function is called implicitly by the runtime when\nthe property is accessed from JavaScript code (or if a get on the property is\nperformed using a N-API call). napi_callback provides more details.
      • \n
      • setter: A function to call when a set access of the property is performed.\nIf this is passed in, set value and method to NULL (since these members\nwon't be used). The given function is called implicitly by the runtime when\nthe property is set from JavaScript code (or if a set on the property is\nperformed using a N-API call). napi_callback provides more details.
      • \n
      • method: Set this to make the property descriptor object's value\nproperty to be a JavaScript function represented by method. If this is\npassed in, set value, getter and setter to NULL (since these members\nwon't be used). napi_callback provides more details.
      • \n
      • attributes: The attributes associated with the particular property. See\nnapi_property_attributes.
      • \n
      • data: The callback data passed into method, getter and setter if this\nfunction is invoked.
      • \n
      ", + "type": "module", + "displayName": "napi_property_descriptor" + } + ], + "type": "module", + "displayName": "Structures" + }, + { + "textRaw": "Functions", + "name": "functions", + "modules": [ + { + "textRaw": "napi_get_property_names", + "name": "napi_get_property_names", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_property_names(napi_env env,\n                                    napi_value object,\n                                    napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the properties.
      • \n
      • [out] result: A napi_value representing an array of JavaScript values\nthat represent the property names of the object. The API can be used to\niterate over result using napi_get_array_length\nand napi_get_element.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the names of the enumerable properties of object as an array\nof strings. The properties of object whose key is a symbol will not be\nincluded.

      ", + "type": "module", + "displayName": "napi_get_property_names" + }, + { + "textRaw": "napi_get_all_property_names", + "name": "napi_get_all_property_names", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_get_all_property_names(napi_env env,\n                            napi_value object,\n                            napi_key_collection_mode key_mode,\n                            napi_key_filter key_filter,\n                            napi_key_conversion key_conversion,\n                            napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the properties.
      • \n
      • [in] key_mode: Whether to retrieve prototype properties as well.
      • \n
      • [in] key_filter: Which properties to retrieve\n(enumerable/readable/writable).
      • \n
      • [in] key_conversion: Whether to convert numbered property keys to strings.
      • \n
      • [out] result: A napi_value representing an array of JavaScript values\nthat represent the property names of the object. napi_get_array_length and\nnapi_get_element can be used to iterate over result.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an array containing the names of the available properties\nof this object.

      ", + "type": "module", + "displayName": "napi_get_all_property_names" + }, + { + "textRaw": "napi_set_property", + "name": "napi_set_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              napi_value value);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object on which to set the property.
      • \n
      • [in] key: The name of the property to set.
      • \n
      • [in] value: The property value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API set a property on the Object passed in.

      ", + "type": "module", + "displayName": "napi_set_property" + }, + { + "textRaw": "napi_get_property", + "name": "napi_get_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the property.
      • \n
      • [in] key: The name of the property to retrieve.
      • \n
      • [out] result: The value of the property.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API gets the requested property from the Object passed in.

      ", + "type": "module", + "displayName": "napi_get_property" + }, + { + "textRaw": "napi_has_property", + "name": "napi_has_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] key: The name of the property whose existence to check.
      • \n
      • [out] result: Whether the property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in has the named property.

      ", + "type": "module", + "displayName": "napi_has_property" + }, + { + "textRaw": "napi_delete_property", + "name": "napi_delete_property", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_delete_property(napi_env env,\n                                 napi_value object,\n                                 napi_value key,\n                                 bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] key: The name of the property to delete.
      • \n
      • [out] result: Whether the property deletion succeeded or not. result can\noptionally be ignored by passing NULL.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API attempts to delete the key own property from object.

      ", + "type": "module", + "displayName": "napi_delete_property" + }, + { + "textRaw": "napi_has_own_property", + "name": "napi_has_own_property", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_own_property(napi_env env,\n                                  napi_value object,\n                                  napi_value key,\n                                  bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] key: The name of the own property whose existence to check.
      • \n
      • [out] result: Whether the own property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in has the named own property. key must\nbe a string or a Symbol, or an error will be thrown. N-API will not perform\nany conversion between data types.

      ", + "type": "module", + "displayName": "napi_has_own_property" + }, + { + "textRaw": "napi_set_named_property", + "name": "napi_set_named_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    napi_value value);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object on which to set the property.
      • \n
      • [in] utf8Name: The name of the property to set.
      • \n
      • [in] value: The property value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is equivalent to calling napi_set_property with a napi_value\ncreated from the string passed in as utf8Name.

      ", + "type": "module", + "displayName": "napi_set_named_property" + }, + { + "textRaw": "napi_get_named_property", + "name": "napi_get_named_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the property.
      • \n
      • [in] utf8Name: The name of the property to get.
      • \n
      • [out] result: The value of the property.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is equivalent to calling napi_get_property with a napi_value\ncreated from the string passed in as utf8Name.

      ", + "type": "module", + "displayName": "napi_get_named_property" + }, + { + "textRaw": "napi_has_named_property", + "name": "napi_has_named_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] utf8Name: The name of the property whose existence to check.
      • \n
      • [out] result: Whether the property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is equivalent to calling napi_has_property with a napi_value\ncreated from the string passed in as utf8Name.

      ", + "type": "module", + "displayName": "napi_has_named_property" + }, + { + "textRaw": "napi_set_element", + "name": "napi_set_element", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             napi_value value);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to set the properties.
      • \n
      • [in] index: The index of the property to set.
      • \n
      • [in] value: The property value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API sets and element on the Object passed in.

      ", + "type": "module", + "displayName": "napi_set_element" + }, + { + "textRaw": "napi_get_element", + "name": "napi_get_element", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the property.
      • \n
      • [in] index: The index of the property to get.
      • \n
      • [out] result: The value of the property.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API gets the element at the requested index.

      ", + "type": "module", + "displayName": "napi_get_element" + }, + { + "textRaw": "napi_has_element", + "name": "napi_has_element", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] index: The index of the property whose existence to check.
      • \n
      • [out] result: Whether the property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns if the Object passed in has an element at the\nrequested index.

      ", + "type": "module", + "displayName": "napi_has_element" + }, + { + "textRaw": "napi_delete_element", + "name": "napi_delete_element", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_delete_element(napi_env env,\n                                napi_value object,\n                                uint32_t index,\n                                bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] index: The index of the property to delete.
      • \n
      • [out] result: Whether the element deletion succeeded or not. result can\noptionally be ignored by passing NULL.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API attempts to delete the specified index from object.

      ", + "type": "module", + "displayName": "napi_delete_element" + }, + { + "textRaw": "napi_define_properties", + "name": "napi_define_properties", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_define_properties(napi_env env,\n                                   napi_value object,\n                                   size_t property_count,\n                                   const napi_property_descriptor* properties);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the properties.
      • \n
      • [in] property_count: The number of elements in the properties array.
      • \n
      • [in] properties: The array of property descriptors.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method allows the efficient definition of multiple properties on a given\nobject. The properties are defined using property descriptors (see\nnapi_property_descriptor). Given an array of such property descriptors,\nthis API will set the properties on the object one at a time, as defined by\nDefineOwnProperty() (described in Section 9.1.6 of the ECMA-262\nspecification).

      ", + "type": "module", + "displayName": "napi_define_properties" + }, + { + "textRaw": "napi_object_freeze", + "name": "napi_object_freeze", + "meta": { + "added": [ + "v12.20.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_object_freeze(napi_env env,\n                               napi_value object);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to freeze.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method freezes a given object. This prevents new properties from\nbeing added to it, existing properties from being removed, prevents\nchanging the enumerability, configurability, or writability of existing\nproperties, and prevents the values of existing properties from being changed.\nIt also prevents the object's prototype from being changed. This is described\nin Section 19.1.2.6 of the\nECMA-262 specification.

      ", + "type": "module", + "displayName": "napi_object_freeze" + }, + { + "textRaw": "napi_object_seal", + "name": "napi_object_seal", + "meta": { + "added": [ + "v12.20.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_object_seal(napi_env env,\n                             napi_value object);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to seal.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method seals a given object. This prevents new properties from being\nadded to it, as well as marking all existing properties as non-configurable.\nThis is described in Section 19.1.2.20\nof the ECMA-262 specification.

      ", + "type": "module", + "displayName": "napi_object_seal" + } + ], + "type": "module", + "displayName": "Functions" + } + ], + "type": "misc", + "displayName": "Working with JavaScript properties" + }, + { + "textRaw": "Working with JavaScript functions", + "name": "working_with_javascript_functions", + "desc": "

      N-API provides a set of APIs that allow JavaScript code to\ncall back into native code. N-API APIs that support calling back\ninto native code take in a callback functions represented by\nthe napi_callback type. When the JavaScript VM calls back to\nnative code, the napi_callback function provided is invoked. The APIs\ndocumented in this section allow the callback function to do the\nfollowing:

      \n
        \n
      • Get information about the context in which the callback was invoked.
      • \n
      • Get the arguments passed into the callback.
      • \n
      • Return a napi_value back from the callback.
      • \n
      \n

      Additionally, N-API provides a set of functions which allow calling\nJavaScript functions from native code. One can either call a function\nlike a regular JavaScript function call, or as a constructor\nfunction.

      \n

      Any non-NULL data which is passed to this API via the data field of the\nnapi_property_descriptor items can be associated with object and freed\nwhenever object is garbage-collected by passing both object and the data to\nnapi_add_finalizer.

      ", + "modules": [ + { + "textRaw": "napi_call_function", + "name": "napi_call_function", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_call_function(napi_env env,\n                                           napi_value recv,\n                                           napi_value func,\n                                           size_t argc,\n                                           const napi_value* argv,\n                                           napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] recv: The this object passed to the called function.
      • \n
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • \n
      • [in] argc: The count of elements in the argv array.
      • \n
      • [in] argv: Array of napi_values representing JavaScript values passed in\nas arguments to the function.
      • \n
      • [out] result: napi_value representing the JavaScript object returned.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method allows a JavaScript function object to be called from a native\nadd-on. This is the primary mechanism of calling back from the add-on's\nnative code into JavaScript. For the special case of calling into JavaScript\nafter an async operation, see napi_make_callback.

      \n

      A sample use case might look as follows. Consider the following JavaScript\nsnippet:

      \n
      function AddTwo(num) {\n  return num + 2;\n}\n
      \n

      Then, the above function can be invoked from a native add-on using the\nfollowing code:

      \n
      // Get the function named \"AddTwo\" on the global object\nnapi_value global, add_two, arg;\nnapi_status status = napi_get_global(env, &global);\nif (status != napi_ok) return;\n\nstatus = napi_get_named_property(env, global, \"AddTwo\", &add_two);\nif (status != napi_ok) return;\n\n// const arg = 1337\nstatus = napi_create_int32(env, 1337, &arg);\nif (status != napi_ok) return;\n\nnapi_value* argv = &arg;\nsize_t argc = 1;\n\n// AddTwo(arg);\nnapi_value return_val;\nstatus = napi_call_function(env, global, add_two, argc, argv, &return_val);\nif (status != napi_ok) return;\n\n// Convert the result back to a native type\nint32_t result;\nstatus = napi_get_value_int32(env, return_val, &result);\nif (status != napi_ok) return;\n
      ", + "type": "module", + "displayName": "napi_call_function" + }, + { + "textRaw": "napi_create_function", + "name": "napi_create_function", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_function(napi_env env,\n                                 const char* utf8name,\n                                 size_t length,\n                                 napi_callback cb,\n                                 void* data,\n                                 napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] utf8Name: The name of the function encoded as UTF8. This is visible\nwithin JavaScript as the new function object's name property.
      • \n
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH if\nit is null-terminated.
      • \n
      • [in] cb: The native function which should be called when this function\nobject is invoked. napi_callback provides more details.
      • \n
      • [in] data: User-provided data context. This will be passed back into the\nfunction when invoked later.
      • \n
      • [out] result: napi_value representing the JavaScript function object for\nthe newly created function.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allows an add-on author to create a function object in native code.\nThis is the primary mechanism to allow calling into the add-on's native code\nfrom JavaScript.

      \n

      The newly created function is not automatically visible from script after this\ncall. Instead, a property must be explicitly set on any object that is visible\nto JavaScript, in order for the function to be accessible from script.

      \n

      In order to expose a function as part of the\nadd-on's module exports, set the newly created function on the exports\nobject. A sample module might look as follows:

      \n
      napi_value SayHello(napi_env env, napi_callback_info info) {\n  printf(\"Hello\\n\");\n  return NULL;\n}\n\nnapi_value Init(napi_env env, napi_value exports) {\n  napi_status status;\n\n  napi_value fn;\n  status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);\n  if (status != napi_ok) return NULL;\n\n  status = napi_set_named_property(env, exports, \"sayHello\", fn);\n  if (status != napi_ok) return NULL;\n\n  return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n
      \n

      Given the above code, the add-on can be used from JavaScript as follows:

      \n
      const myaddon = require('./addon');\nmyaddon.sayHello();\n
      \n

      The string passed to require() is the name of the target in binding.gyp\nresponsible for creating the .node file.

      \n

      Any non-NULL data which is passed to this API via the data parameter can\nbe associated with the resulting JavaScript function (which is returned in the\nresult parameter) and freed whenever the function is garbage-collected by\npassing both the JavaScript function and the data to napi_add_finalizer.

      \n

      JavaScript Functions are described in Section 19.2 of the ECMAScript\nLanguage Specification.

      ", + "type": "module", + "displayName": "napi_create_function" + }, + { + "textRaw": "napi_get_cb_info", + "name": "napi_get_cb_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_cb_info(napi_env env,\n                             napi_callback_info cbinfo,\n                             size_t* argc,\n                             napi_value* argv,\n                             napi_value* thisArg,\n                             void** data)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] cbinfo: The callback info passed into the callback function.
      • \n
      • [in-out] argc: Specifies the size of the provided argv array and receives\nthe actual count of arguments.
      • \n
      • [out] argv: Buffer to which the napi_value representing the arguments are\ncopied. If there are more arguments than the provided count, only the\nrequested number of arguments are copied. If there are fewer arguments\nprovided than claimed, the rest of argv is filled with napi_value values\nthat represent undefined.
      • \n
      • [out] this: Receives the JavaScript this argument for the call.
      • \n
      • [out] data: Receives the data pointer for the callback.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is used within a callback function to retrieve details about the\ncall like the arguments and the this pointer from a given callback info.

      ", + "type": "module", + "displayName": "napi_get_cb_info" + }, + { + "textRaw": "napi_get_new_target", + "name": "napi_get_new_target", + "meta": { + "added": [ + "v8.6.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_new_target(napi_env env,\n                                napi_callback_info cbinfo,\n                                napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] cbinfo: The callback info passed into the callback function.
      • \n
      • [out] result: The new.target of the constructor call.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the new.target of the constructor call. If the current\ncallback is not a constructor call, the result is NULL.

      ", + "type": "module", + "displayName": "napi_get_new_target" + }, + { + "textRaw": "napi_new_instance", + "name": "napi_new_instance", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_new_instance(napi_env env,\n                              napi_value cons,\n                              size_t argc,\n                              napi_value* argv,\n                              napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] cons: napi_value representing the JavaScript function to be invoked\nas a constructor.
      • \n
      • [in] argc: The count of elements in the argv array.
      • \n
      • [in] argv: Array of JavaScript values as napi_value representing the\narguments to the constructor.
      • \n
      • [out] result: napi_value representing the JavaScript object returned,\nwhich in this case is the constructed object.
      • \n
      \n

      This method is used to instantiate a new JavaScript value using a given\nnapi_value that represents the constructor for the object. For example,\nconsider the following snippet:

      \n
      function MyObject(param) {\n  this.param = param;\n}\n\nconst arg = 'hello';\nconst value = new MyObject(arg);\n
      \n

      The following can be approximated in N-API using the following snippet:

      \n
      // Get the constructor function MyObject\nnapi_value global, constructor, arg, value;\nnapi_status status = napi_get_global(env, &global);\nif (status != napi_ok) return;\n\nstatus = napi_get_named_property(env, global, \"MyObject\", &constructor);\nif (status != napi_ok) return;\n\n// const arg = \"hello\"\nstatus = napi_create_string_utf8(env, \"hello\", NAPI_AUTO_LENGTH, &arg);\nif (status != napi_ok) return;\n\nnapi_value* argv = &arg;\nsize_t argc = 1;\n\n// const value = new MyObject(arg)\nstatus = napi_new_instance(env, constructor, argc, argv, &value);\n
      \n

      Returns napi_ok if the API succeeded.

      ", + "type": "module", + "displayName": "napi_new_instance" + } + ], + "type": "misc", + "displayName": "Working with JavaScript functions" + }, + { + "textRaw": "Object wrap", + "name": "object_wrap", + "desc": "

      N-API offers a way to \"wrap\" C++ classes and instances so that the class\nconstructor and methods can be called from JavaScript.

      \n
        \n
      1. The napi_define_class API defines a JavaScript class with constructor,\nstatic properties and methods, and instance properties and methods that\ncorrespond to the C++ class.
      2. \n
      3. When JavaScript code invokes the constructor, the constructor callback\nuses napi_wrap to wrap a new C++ instance in a JavaScript object,\nthen returns the wrapper object.
      4. \n
      5. When JavaScript code invokes a method or property accessor on the class,\nthe corresponding napi_callback C++ function is invoked. For an instance\ncallback, napi_unwrap obtains the C++ instance that is the target of\nthe call.
      6. \n
      \n

      For wrapped objects it may be difficult to distinguish between a function\ncalled on a class prototype and a function called on an instance of a class.\nA common pattern used to address this problem is to save a persistent\nreference to the class constructor for later instanceof checks.

      \n
      napi_value MyClass_constructor = NULL;\nstatus = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);\nassert(napi_ok == status);\nbool is_instance = false;\nstatus = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);\nassert(napi_ok == status);\nif (is_instance) {\n  // napi_unwrap() ...\n} else {\n  // otherwise...\n}\n
      \n

      The reference must be freed once it is no longer needed.

      \n

      There are occasions where napi_instanceof() is insufficient for ensuring that\na JavaScript object is a wrapper for a certain native type. This is the case\nespecially when wrapped JavaScript objects are passed back into the addon via\nstatic methods rather than as the this value of prototype methods. In such\ncases there is a chance that they may be unwrapped incorrectly.

      \n
      const myAddon = require('./build/Release/my_addon.node');\n\n// `openDatabase()` returns a JavaScript object that wraps a native database\n// handle.\nconst dbHandle = myAddon.openDatabase();\n\n// `query()` returns a JavaScript object that wraps a native query handle.\nconst queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!');\n\n// There is an accidental error in the line below. The first parameter to\n// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not\n// the query handle (`query`), so the correct condition for the while-loop\n// should be\n//\n// myAddon.queryHasRecords(dbHandle, queryHandle)\n//\nwhile (myAddon.queryHasRecords(queryHandle, dbHandle)) {\n  // retrieve records\n}\n
      \n

      In the above example myAddon.queryHasRecords() is a method that accepts two\narguments. The first is a database handle and the second is a query handle.\nInternally, it unwraps the first argument and casts the resulting pointer to a\nnative database handle. It then unwraps the second argument and casts the\nresulting pointer to a query handle. If the arguments are passed in the wrong\norder, the casts will work, however, there is a good chance that the underlying\ndatabase operation will fail, or will even cause an invalid memory access.

      \n

      To ensure that the pointer retrieved from the first argument is indeed a pointer\nto a database handle and, similarly, that the pointer retrieved from the second\nargument is indeed a pointer to a query handle, the implementation of\nqueryHasRecords() has to perform a type validation. Retaining the JavaScript\nclass constructor from which the database handle was instantiated and the\nconstructor from which the query handle was instantiated in napi_refs can\nhelp, because napi_instanceof() can then be used to ensure that the instances\npassed into queryHashRecords() are indeed of the correct type.

      \n

      Unfortunately, napi_instanceof() does not protect against prototype\nmanipulation. For example, the prototype of the database handle instance can be\nset to the prototype of the constructor for query handle instances. In this\ncase, the database handle instance can appear as a query handle instance, and it\nwill pass the napi_instanceof() test for a query handle instance, while still\ncontaining a pointer to a database handle.

      \n

      To this end, N-API provides type-tagging capabilities.

      \n

      A type tag is a 128-bit integer unique to the addon. N-API provides the\nnapi_type_tag structure for storing a type tag. When such a value is passed\nalong with a JavaScript object stored in a napi_value to\nnapi_type_tag_object(), the JavaScript object will be \"marked\" with the\ntype tag. The \"mark\" is invisible on the JavaScript side. When a JavaScript\nobject arrives into a native binding, napi_check_object_type_tag() can be used\nalong with the original type tag to determine whether the JavaScript object was\npreviously \"marked\" with the type tag. This creates a type-checking capability\nof a higher fidelity than napi_instanceof() can provide, because such type-\ntagging survives prototype manipulation and addon unloading/reloading.

      \n

      Continuing the above example, the following skeleton addon implementation\nillustrates the use of napi_type_tag_object() and\nnapi_check_object_type_tag().

      \n
      // This value is the type tag for a database handle. The command\n//\n//   uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\\1, 0x\\2/'\n//\n// can be used to obtain the two values with which to initialize the structure.\nstatic const napi_type_tag DatabaseHandleTypeTag = {\n  0x1edf75a38336451d, 0xa5ed9ce2e4c00c38\n};\n\n// This value is the type tag for a query handle.\nstatic const napi_type_tag QueryHandleTypeTag = {\n  0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a\n};\n\nstatic napi_value\nopenDatabase(napi_env env, napi_callback_info info) {\n  napi_status status;\n  napi_value result;\n\n  // Perform the underlying action which results in a database handle.\n  DatabaseHandle* dbHandle = open_database();\n\n  // Create a new, empty JS object.\n  status = napi_create_object(env, &result);\n  if (status != napi_ok) return NULL;\n\n  // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.\n  status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);\n  if (status != napi_ok) return NULL;\n\n  // Store the pointer to the `DatabaseHandle` structure inside the JS object.\n  status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL);\n  if (status != napi_ok) return NULL;\n\n  return result;\n}\n\n// Later when we receive a JavaScript object purporting to be a database handle\n// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a\n// handle.\n\nstatic napi_value\nquery(napi_env env, napi_callback_info info) {\n  napi_status status;\n  size_t argc = 2;\n  napi_value argv[2];\n  bool is_db_handle;\n\n  status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);\n  if (status != napi_ok) return NULL;\n\n  // Check that the object passed as the first parameter has the previously\n  // applied tag.\n  status = napi_check_object_type_tag(env,\n                                      argv[0],\n                                      &DatabaseHandleTypeTag,\n                                      &is_db_handle);\n  if (status != napi_ok) return NULL;\n\n  // Throw a `TypeError` if it doesn't.\n  if (!is_db_handle) {\n    // Throw a TypeError.\n    return NULL;\n  }\n}\n
      ", + "modules": [ + { + "textRaw": "napi_define_class", + "name": "napi_define_class", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_define_class(napi_env env,\n                              const char* utf8name,\n                              size_t length,\n                              napi_callback constructor,\n                              void* data,\n                              size_t property_count,\n                              const napi_property_descriptor* properties,\n                              napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] utf8name: Name of the JavaScript constructor function; this is\nnot required to be the same as the C++ class name, though it is recommended\nfor clarity.
      • \n
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH\nif it is null-terminated.
      • \n
      • [in] constructor: Callback function that handles constructing instances\nof the class. This should be a static method on the class, not an actual\nC++ constructor function. napi_callback provides more details.
      • \n
      • [in] data: Optional data to be passed to the constructor callback as\nthe data property of the callback info.
      • \n
      • [in] property_count: Number of items in the properties array argument.
      • \n
      • [in] properties: Array of property descriptors describing static and\ninstance data properties, accessors, and methods on the class\nSee napi_property_descriptor.
      • \n
      • [out] result: A napi_value representing the constructor function for\nthe class.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Defines a JavaScript class that corresponds to a C++ class, including:

      \n
        \n
      • A JavaScript constructor function that has the class name and invokes the\nprovided C++ constructor callback.
      • \n
      • Properties on the constructor function corresponding to static data\nproperties, accessors, and methods of the C++ class (defined by\nproperty descriptors with the napi_static attribute).
      • \n
      • Properties on the constructor function's prototype object corresponding to\nnon-static data properties, accessors, and methods of the C++ class\n(defined by property descriptors without the napi_static attribute).
      • \n
      \n

      The C++ constructor callback should be a static method on the class that calls\nthe actual class constructor, then wraps the new C++ instance in a JavaScript\nobject, and returns the wrapper object. See napi_wrap() for details.

      \n

      The JavaScript constructor function returned from napi_define_class is\noften saved and used later, to construct new instances of the class from native\ncode, and/or check whether provided values are instances of the class. In that\ncase, to prevent the function value from being garbage-collected, create a\npersistent reference to it using napi_create_reference and ensure the\nreference count is kept >= 1.

      \n

      Any non-NULL data which is passed to this API via the data parameter or via\nthe data field of the napi_property_descriptor array items can be associated\nwith the resulting JavaScript constructor (which is returned in the result\nparameter) and freed whenever the class is garbage-collected by passing both\nthe JavaScript function and the data to napi_add_finalizer.

      ", + "type": "module", + "displayName": "napi_define_class" + }, + { + "textRaw": "napi_wrap", + "name": "napi_wrap", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_wrap(napi_env env,\n                      napi_value js_object,\n                      void* native_object,\n                      napi_finalize finalize_cb,\n                      void* finalize_hint,\n                      napi_ref* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object that will be the wrapper for the\nnative object.
      • \n
      • [in] native_object: The native instance that will be wrapped in the\nJavaScript object.
      • \n
      • [in] finalize_cb: Optional native callback that can be used to free the\nnative instance when the JavaScript object is ready for garbage-collection.\nnapi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.
      • \n
      • [out] result: Optional reference to the wrapped object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Wraps a native instance in a JavaScript object. The native instance can be\nretrieved later using napi_unwrap().

      \n

      When JavaScript code invokes a constructor for a class that was defined using\nnapi_define_class(), the napi_callback for the constructor is invoked.\nAfter constructing an instance of the native class, the callback must then call\nnapi_wrap() to wrap the newly constructed instance in the already-created\nJavaScript object that is the this argument to the constructor callback.\n(That this object was created from the constructor function's prototype,\nso it already has definitions of all the instance properties and methods.)

      \n

      Typically when wrapping a class instance, a finalize callback should be\nprovided that simply deletes the native instance that is received as the data\nargument to the finalize callback.

      \n

      The optional returned reference is initially a weak reference, meaning it\nhas a reference count of 0. Typically this reference count would be incremented\ntemporarily during async operations that require the instance to remain valid.

      \n

      Caution: The optional returned reference (if obtained) should be deleted via\nnapi_delete_reference ONLY in response to the finalize callback\ninvocation. If it is deleted before then, then the finalize callback may never\nbe invoked. Therefore, when obtaining a reference a finalize callback is also\nrequired in order to enable correct disposal of the reference.

      \n

      Calling napi_wrap() a second time on an object will return an error. To\nassociate another native instance with the object, use napi_remove_wrap()\nfirst.

      ", + "type": "module", + "displayName": "napi_wrap" + }, + { + "textRaw": "napi_unwrap", + "name": "napi_unwrap", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_unwrap(napi_env env,\n                        napi_value js_object,\n                        void** result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The object associated with the native instance.
      • \n
      • [out] result: Pointer to the wrapped native instance.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Retrieves a native instance that was previously wrapped in a JavaScript\nobject using napi_wrap().

      \n

      When JavaScript code invokes a method or property accessor on the class, the\ncorresponding napi_callback is invoked. If the callback is for an instance\nmethod or accessor, then the this argument to the callback is the wrapper\nobject; the wrapped C++ instance that is the target of the call can be obtained\nthen by calling napi_unwrap() on the wrapper object.

      ", + "type": "module", + "displayName": "napi_unwrap" + }, + { + "textRaw": "napi_remove_wrap", + "name": "napi_remove_wrap", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_remove_wrap(napi_env env,\n                             napi_value js_object,\n                             void** result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The object associated with the native instance.
      • \n
      • [out] result: Pointer to the wrapped native instance.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Retrieves a native instance that was previously wrapped in the JavaScript\nobject js_object using napi_wrap() and removes the wrapping. If a finalize\ncallback was associated with the wrapping, it will no longer be called when the\nJavaScript object becomes garbage-collected.

      ", + "type": "module", + "displayName": "napi_remove_wrap" + }, + { + "textRaw": "napi_type_tag_object", + "name": "napi_type_tag_object", + "meta": { + "added": [ + "v12.19.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_type_tag_object(napi_env env,\n                                 napi_value js_object,\n                                 const napi_type_tag* type_tag);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object to be marked.
      • \n
      • [in] type_tag: The tag with which the object is to be marked.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Associates the value of the type_tag pointer with the JavaScript object.\nnapi_check_object_type_tag() can then be used to compare the tag that was\nattached to the object with one owned by the addon to ensure that the object\nhas the right type.

      \n

      If the object already has an associated type tag, this API will return\nnapi_invalid_arg.

      ", + "type": "module", + "displayName": "napi_type_tag_object" + }, + { + "textRaw": "napi_check_object_type_tag", + "name": "napi_check_object_type_tag", + "meta": { + "added": [ + "v12.19.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_check_object_type_tag(napi_env env,\n                                       napi_value js_object,\n                                       const napi_type_tag* type_tag,\n                                       bool* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object whose type tag to examine.
      • \n
      • [in] type_tag: The tag with which to compare any tag found on the object.
      • \n
      • [out] result: Whether the type tag given matched the type tag on the\nobject. false is also returned if no type tag was found on the object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Compares the pointer given as type_tag with any that can be found on\njs_object. If no tag is found on js_object or, if a tag is found but it does\nnot match type_tag, then result is set to false. If a tag is found and it\nmatches type_tag, then result is set to true.

      ", + "type": "module", + "displayName": "napi_check_object_type_tag" + }, + { + "textRaw": "napi_add_finalizer", + "name": "napi_add_finalizer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_add_finalizer(napi_env env,\n                               napi_value js_object,\n                               void* native_object,\n                               napi_finalize finalize_cb,\n                               void* finalize_hint,\n                               napi_ref* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object to which the native data will be\nattached.
      • \n
      • [in] native_object: The native data that will be attached to the JavaScript\nobject.
      • \n
      • [in] finalize_cb: Native callback that will be used to free the\nnative data when the JavaScript object is ready for garbage-collection.\nnapi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.
      • \n
      • [out] result: Optional reference to the JavaScript object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Adds a napi_finalize callback which will be called when the JavaScript object\nin js_object is ready for garbage collection. This API is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the API can be called multiple times with different data items in order to\nattach each of them to the JavaScript object, and
      • \n
      • the object manipulated by the API can be used with napi_wrap().
      • \n
      \n

      Caution: The optional returned reference (if obtained) should be deleted via\nnapi_delete_reference ONLY in response to the finalize callback\ninvocation. If it is deleted before then, then the finalize callback may never\nbe invoked. Therefore, when obtaining a reference a finalize callback is also\nrequired in order to enable correct disposal of the reference.

      ", + "type": "module", + "displayName": "napi_add_finalizer" + } + ], + "type": "misc", + "displayName": "Object wrap" + }, + { + "textRaw": "Simple asynchronous operations", + "name": "simple_asynchronous_operations", + "desc": "

      Addon modules often need to leverage async helpers from libuv as part of their\nimplementation. This allows them to schedule work to be executed asynchronously\nso that their methods can return in advance of the work being completed. This\nallows them to avoid blocking overall execution of the Node.js application.

      \n

      N-API provides an ABI-stable interface for these\nsupporting functions which covers the most common asynchronous use cases.

      \n

      N-API defines the napi_async_work structure which is used to manage\nasynchronous workers. Instances are created/deleted with\nnapi_create_async_work and napi_delete_async_work.

      \n

      The execute and complete callbacks are functions that will be\ninvoked when the executor is ready to execute and when it completes its\ntask respectively.

      \n

      The execute function should avoid making any N-API calls\nthat could result in the execution of JavaScript or interaction with\nJavaScript objects. Most often, any code that needs to make N-API\ncalls should be made in complete callback instead.\nAvoid using the napi_env parameter in the execute callback as\nit will likely execute JavaScript.

      \n

      These functions implement the following interfaces:

      \n
      typedef void (*napi_async_execute_callback)(napi_env env,\n                                            void* data);\ntypedef void (*napi_async_complete_callback)(napi_env env,\n                                             napi_status status,\n                                             void* data);\n
      \n

      When these methods are invoked, the data parameter passed will be the\naddon-provided void* data that was passed into the\nnapi_create_async_work call.

      \n

      Once created the async worker can be queued\nfor execution using the napi_queue_async_work function:

      \n
      napi_status napi_queue_async_work(napi_env env,\n                                  napi_async_work work);\n
      \n

      napi_cancel_async_work can be used if the work needs\nto be cancelled before the work has started execution.

      \n

      After calling napi_cancel_async_work, the complete callback\nwill be invoked with a status value of napi_cancelled.\nThe work should not be deleted before the complete\ncallback invocation, even when it was cancelled.

      ", + "modules": [ + { + "textRaw": "napi_create_async_work", + "name": "napi_create_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [ + { + "version": "v8.6.0", + "pr-url": "https://github.com/nodejs/node/pull/14697", + "description": "Added `async_resource` and `async_resource_name` parameters." + } + ] + }, + "desc": "
      napi_status napi_create_async_work(napi_env env,\n                                   napi_value async_resource,\n                                   napi_value async_resource_name,\n                                   napi_async_execute_callback execute,\n                                   napi_async_complete_callback complete,\n                                   void* data,\n                                   napi_async_work* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_resource: An optional object associated with the async work\nthat will be passed to possible async_hooks init hooks.
      • \n
      • [in] async_resource_name: Identifier for the kind of resource that is being\nprovided for diagnostic information exposed by the async_hooks API.
      • \n
      • [in] execute: The native function which should be called to execute the\nlogic asynchronously. The given function is called from a worker pool thread\nand can execute in parallel with the main event loop thread.
      • \n
      • [in] complete: The native function which will be called when the\nasynchronous logic is completed or is cancelled. The given function is called\nfrom the main event loop thread. napi_async_complete_callback provides\nmore details.
      • \n
      • [in] data: User-provided data context. This will be passed back into the\nexecute and complete functions.
      • \n
      • [out] result: napi_async_work* which is the handle to the newly created\nasync work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a work object that is used to execute logic asynchronously.\nIt should be freed using napi_delete_async_work once the work is no longer\nrequired.

      \n

      async_resource_name should be a null-terminated, UTF-8-encoded string.

      \n

      The async_resource_name identifier is provided by the user and should be\nrepresentative of the type of async work being performed. It is also recommended\nto apply namespacing to the identifier, e.g. by including the module name. See\nthe async_hooks documentation for more information.

      ", + "type": "module", + "displayName": "napi_create_async_work" + }, + { + "textRaw": "napi_delete_async_work", + "name": "napi_delete_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_delete_async_work(napi_env env,\n                                   napi_async_work work);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] work: The handle returned by the call to napi_create_async_work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API frees a previously allocated work object.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_delete_async_work" + }, + { + "textRaw": "napi_queue_async_work", + "name": "napi_queue_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_queue_async_work(napi_env env,\n                                  napi_async_work work);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] work: The handle returned by the call to napi_create_async_work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API requests that the previously allocated work be scheduled\nfor execution. Once it returns successfully, this API must not be called again\nwith the same napi_async_work item or the result will be undefined.

      ", + "type": "module", + "displayName": "napi_queue_async_work" + }, + { + "textRaw": "napi_cancel_async_work", + "name": "napi_cancel_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_cancel_async_work(napi_env env,\n                                   napi_async_work work);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] work: The handle returned by the call to napi_create_async_work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API cancels queued work if it has not yet\nbeen started. If it has already started executing, it cannot be\ncancelled and napi_generic_failure will be returned. If successful,\nthe complete callback will be invoked with a status value of\nnapi_cancelled. The work should not be deleted before the complete\ncallback invocation, even if it has been successfully cancelled.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_cancel_async_work" + } + ], + "type": "misc", + "displayName": "Simple asynchronous operations" + }, + { + "textRaw": "Custom asynchronous operations", + "name": "custom_asynchronous_operations", + "desc": "

      The simple asynchronous work APIs above may not be appropriate for every\nscenario. When using any other asynchronous mechanism, the following APIs\nare necessary to ensure an asynchronous operation is properly tracked by\nthe runtime.

      ", + "modules": [ + { + "textRaw": "napi_async_init", + "name": "napi_async_init", + "meta": { + "added": [ + "v8.6.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_async_init(napi_env env,\n                            napi_value async_resource,\n                            napi_value async_resource_name,\n                            napi_async_context* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_resource: Object associated with the async work\nthat will be passed to possible async_hooks init hooks.\nIn order to retain ABI compatibility with previous versions,\npassing NULL for async_resource will not result in an error, however,\nthis will result incorrect operation of async hooks for the\nnapi_async_context created. Potential issues include\nloss of async context when using the AsyncLocalStorage API.
      • \n
      • [in] async_resource_name: Identifier for the kind of resource\nthat is being provided for diagnostic information exposed by the\nasync_hooks API.
      • \n
      • [out] result: The initialized async context.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      ", + "type": "module", + "displayName": "napi_async_init" + }, + { + "textRaw": "napi_async_destroy", + "name": "napi_async_destroy", + "meta": { + "added": [ + "v8.6.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_async_destroy(napi_env env,\n                               napi_async_context async_context);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_context: The async context to be destroyed.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_async_destroy" + }, + { + "textRaw": "napi_make_callback", + "name": "napi_make_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [ + { + "version": "v8.6.0", + "description": "Added `async_context` parameter." + } + ] + }, + "desc": "
      NAPI_EXTERN napi_status napi_make_callback(napi_env env,\n                                           napi_async_context async_context,\n                                           napi_value recv,\n                                           napi_value func,\n                                           size_t argc,\n                                           const napi_value* argv,\n                                           napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_context: Context for the async operation that is\ninvoking the callback. This should normally be a value previously\nobtained from napi_async_init. However NULL is also allowed,\nwhich indicates the current async context (if any) is to be used\nfor the callback.
      • \n
      • [in] recv: The this object passed to the called function.
      • \n
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • \n
      • [in] argc: The count of elements in the argv array.
      • \n
      • [in] argv: Array of JavaScript values as napi_value representing the\narguments to the function.
      • \n
      • [out] result: napi_value representing the JavaScript object returned.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method allows a JavaScript function object to be called from a native\nadd-on. This API is similar to napi_call_function. However, it is used to call\nfrom native code back into JavaScript after returning from an async\noperation (when there is no other script on the stack). It is a fairly simple\nwrapper around node::MakeCallback.

      \n

      Note it is not necessary to use napi_make_callback from within a\nnapi_async_complete_callback; in that situation the callback's async\ncontext has already been set up, so a direct call to napi_call_function\nis sufficient and appropriate. Use of the napi_make_callback function\nmay be required when implementing custom async behavior that does not use\nnapi_create_async_work.

      \n

      Any process.nextTicks or Promises scheduled on the microtask queue by\nJavaScript during the callback are ran before returning back to C/C++.

      ", + "type": "module", + "displayName": "napi_make_callback" + }, + { + "textRaw": "napi_open_callback_scope", + "name": "napi_open_callback_scope", + "meta": { + "added": [ + "v9.6.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,\n                                                 napi_value resource_object,\n                                                 napi_async_context context,\n                                                 napi_callback_scope* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] resource_object: An object associated with the async work\nthat will be passed to possible async_hooks init hooks.
      • \n
      • [in] context: Context for the async operation that is invoking the callback.\nThis should be a value previously obtained from napi_async_init.
      • \n
      • [out] result: The newly created scope.
      • \n
      \n

      There are cases (for example, resolving promises) where it is\nnecessary to have the equivalent of the scope associated with a callback\nin place when making certain N-API calls. If there is no other script on\nthe stack the napi_open_callback_scope and\nnapi_close_callback_scope functions can be used to open/close\nthe required scope.

      ", + "type": "module", + "displayName": "napi_open_callback_scope" + }, + { + "textRaw": "napi_close_callback_scope", + "name": "napi_close_callback_scope", + "meta": { + "added": [ + "v9.6.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,\n                                                  napi_callback_scope scope)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: The scope to be closed.
      • \n
      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_close_callback_scope" + } + ], + "type": "misc", + "displayName": "Custom asynchronous operations" + }, + { + "textRaw": "Version management", + "name": "version_management", + "modules": [ + { + "textRaw": "napi_get_node_version", + "name": "napi_get_node_version", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      typedef struct {\n  uint32_t major;\n  uint32_t minor;\n  uint32_t patch;\n  const char* release;\n} napi_node_version;\n\nnapi_status napi_get_node_version(napi_env env,\n                                  const napi_node_version** version);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] version: A pointer to version information for Node.js itself.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This function fills the version struct with the major, minor, and patch\nversion of Node.js that is currently running, and the release field with the\nvalue of process.release.name.

      \n

      The returned buffer is statically allocated and does not need to be freed.

      ", + "type": "module", + "displayName": "napi_get_node_version" + }, + { + "textRaw": "napi_get_version", + "name": "napi_get_version", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_version(napi_env env,\n                             uint32_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: The highest version of N-API supported.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the highest N-API version supported by the\nNode.js runtime. N-API is planned to be additive such that\nnewer releases of Node.js may support additional API functions.\nIn order to allow an addon to use a newer function when running with\nversions of Node.js that support it, while providing\nfallback behavior when running with Node.js versions that don't\nsupport it:

      \n
        \n
      • Call napi_get_version() to determine if the API is available.
      • \n
      • If available, dynamically load a pointer to the function using uv_dlsym().
      • \n
      • Use the dynamically loaded pointer to invoke the function.
      • \n
      • If the function is not available, provide an alternate implementation\nthat does not use the function.
      • \n
      ", + "type": "module", + "displayName": "napi_get_version" + } + ], + "type": "misc", + "displayName": "Version management" + }, + { + "textRaw": "Memory management", + "name": "memory_management", + "modules": [ + { + "textRaw": "napi_adjust_external_memory", + "name": "napi_adjust_external_memory", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,\n                                                    int64_t change_in_bytes,\n                                                    int64_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] change_in_bytes: The change in externally allocated memory that is kept\nalive by JavaScript objects.
      • \n
      • [out] result: The adjusted value
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This function gives V8 an indication of the amount of externally allocated\nmemory that is kept alive by JavaScript objects (i.e. a JavaScript object\nthat points to its own memory allocated by a native module). Registering\nexternally allocated memory will trigger global garbage collections more\noften than it would otherwise.

      ", + "type": "module", + "displayName": "napi_adjust_external_memory" + } + ], + "type": "misc", + "displayName": "Memory management" + }, + { + "textRaw": "Promises", + "name": "promises", + "desc": "

      N-API provides facilities for creating Promise objects as described in\nSection 25.4 of the ECMA specification. It implements promises as a pair of\nobjects. When a promise is created by napi_create_promise(), a \"deferred\"\nobject is created and returned alongside the Promise. The deferred object is\nbound to the created Promise and is the only means to resolve or reject the\nPromise using napi_resolve_deferred() or napi_reject_deferred(). The\ndeferred object that is created by napi_create_promise() is freed by\nnapi_resolve_deferred() or napi_reject_deferred(). The Promise object may\nbe returned to JavaScript where it can be used in the usual fashion.

      \n

      For example, to create a promise and pass it to an asynchronous worker:

      \n
      napi_deferred deferred;\nnapi_value promise;\nnapi_status status;\n\n// Create the promise.\nstatus = napi_create_promise(env, &deferred, &promise);\nif (status != napi_ok) return NULL;\n\n// Pass the deferred to a function that performs an asynchronous action.\ndo_something_asynchronous(deferred);\n\n// Return the promise to JS\nreturn promise;\n
      \n

      The above function do_something_asynchronous() would perform its asynchronous\naction and then it would resolve or reject the deferred, thereby concluding the\npromise and freeing the deferred:

      \n
      napi_deferred deferred;\nnapi_value undefined;\nnapi_status status;\n\n// Create a value with which to conclude the deferred.\nstatus = napi_get_undefined(env, &undefined);\nif (status != napi_ok) return NULL;\n\n// Resolve or reject the promise associated with the deferred depending on\n// whether the asynchronous action succeeded.\nif (asynchronous_action_succeeded) {\n  status = napi_resolve_deferred(env, deferred, undefined);\n} else {\n  status = napi_reject_deferred(env, deferred, undefined);\n}\nif (status != napi_ok) return NULL;\n\n// At this point the deferred has been freed, so we should assign NULL to it.\ndeferred = NULL;\n
      ", + "modules": [ + { + "textRaw": "napi_create_promise", + "name": "napi_create_promise", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_promise(napi_env env,\n                                napi_deferred* deferred,\n                                napi_value* promise);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] deferred: A newly created deferred object which can later be passed to\nnapi_resolve_deferred() or napi_reject_deferred() to resolve resp. reject\nthe associated promise.
      • \n
      • [out] promise: The JavaScript promise associated with the deferred object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a deferred object and a JavaScript promise.

      ", + "type": "module", + "displayName": "napi_create_promise" + }, + { + "textRaw": "napi_resolve_deferred", + "name": "napi_resolve_deferred", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_resolve_deferred(napi_env env,\n                                  napi_deferred deferred,\n                                  napi_value resolution);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] deferred: The deferred object whose associated promise to resolve.
      • \n
      • [in] resolution: The value with which to resolve the promise.
      • \n
      \n

      This API resolves a JavaScript promise by way of the deferred object\nwith which it is associated. Thus, it can only be used to resolve JavaScript\npromises for which the corresponding deferred object is available. This\neffectively means that the promise must have been created using\nnapi_create_promise() and the deferred object returned from that call must\nhave been retained in order to be passed to this API.

      \n

      The deferred object is freed upon successful completion.

      ", + "type": "module", + "displayName": "napi_resolve_deferred" + }, + { + "textRaw": "napi_reject_deferred", + "name": "napi_reject_deferred", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_reject_deferred(napi_env env,\n                                 napi_deferred deferred,\n                                 napi_value rejection);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] deferred: The deferred object whose associated promise to resolve.
      • \n
      • [in] rejection: The value with which to reject the promise.
      • \n
      \n

      This API rejects a JavaScript promise by way of the deferred object\nwith which it is associated. Thus, it can only be used to reject JavaScript\npromises for which the corresponding deferred object is available. This\neffectively means that the promise must have been created using\nnapi_create_promise() and the deferred object returned from that call must\nhave been retained in order to be passed to this API.

      \n

      The deferred object is freed upon successful completion.

      ", + "type": "module", + "displayName": "napi_reject_deferred" + }, + { + "textRaw": "napi_is_promise", + "name": "napi_is_promise", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_promise(napi_env env,\n                            napi_value value,\n                            bool* is_promise);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The value to examine
      • \n
      • [out] is_promise: Flag indicating whether promise is a native promise\nobject (that is, a promise object created by the underlying engine).
      • \n
      ", + "type": "module", + "displayName": "napi_is_promise" + } + ], + "type": "misc", + "displayName": "Promises" + }, + { + "textRaw": "Script execution", + "name": "script_execution", + "desc": "

      N-API provides an API for executing a string containing JavaScript using the\nunderlying JavaScript engine.

      ", + "modules": [ + { + "textRaw": "napi_run_script", + "name": "napi_run_script", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_run_script(napi_env env,\n                                        napi_value script,\n                                        napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] script: A JavaScript string containing the script to execute.
      • \n
      • [out] result: The value resulting from having executed the script.
      • \n
      \n

      This function executes a string of JavaScript code and returns its result with\nthe following caveats:

      \n
        \n
      • Unlike eval, this function does not allow the script to access the current\nlexical scope, and therefore also does not allow to access the\nmodule scope, meaning that pseudo-globals such as require will not be\navailable.
      • \n
      • The script can access the global scope. Function and var declarations\nin the script will be added to the global object. Variable declarations\nmade using let and const will be visible globally, but will not be added\nto the global object.
      • \n
      • The value of this is global within the script.
      • \n
      ", + "type": "module", + "displayName": "napi_run_script" + } + ], + "type": "misc", + "displayName": "Script execution" + }, + { + "textRaw": "libuv event loop", + "name": "libuv_event_loop", + "desc": "

      N-API provides a function for getting the current event loop associated with\na specific napi_env.

      ", + "modules": [ + { + "textRaw": "napi_get_uv_event_loop", + "name": "napi_get_uv_event_loop", + "meta": { + "added": [ + "v8.10.0", + "v9.3.0" + ], + "napiVersion": [ + 2 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,\n                                               struct uv_loop_s** loop);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] loop: The current libuv loop instance.
      • \n
      ", + "type": "module", + "displayName": "napi_get_uv_event_loop" + } + ], + "type": "misc", + "displayName": "libuv event loop" + }, + { + "textRaw": "Asynchronous thread-safe function calls", + "name": "asynchronous_thread-safe_function_calls", + "desc": "

      JavaScript functions can normally only be called from a native addon's main\nthread. If an addon creates additional threads, then N-API functions that\nrequire a napi_env, napi_value, or napi_ref must not be called from those\nthreads.

      \n

      When an addon has additional threads and JavaScript functions need to be invoked\nbased on the processing completed by those threads, those threads must\ncommunicate with the addon's main thread so that the main thread can invoke the\nJavaScript function on their behalf. The thread-safe function APIs provide an\neasy way to do this.

      \n

      These APIs provide the type napi_threadsafe_function as well as APIs to\ncreate, destroy, and call objects of this type.\nnapi_create_threadsafe_function() creates a persistent reference to a\nnapi_value that holds a JavaScript function which can be called from multiple\nthreads. The calls happen asynchronously. This means that values with which the\nJavaScript callback is to be called will be placed in a queue, and, for each\nvalue in the queue, a call will eventually be made to the JavaScript function.

      \n

      Upon creation of a napi_threadsafe_function a napi_finalize callback can be\nprovided. This callback will be invoked on the main thread when the thread-safe\nfunction is about to be destroyed. It receives the context and the finalize data\ngiven during construction, and provides an opportunity for cleaning up after the\nthreads e.g. by calling uv_thread_join(). Aside from the main loop thread,\nno threads should be using the thread-safe function after the finalize callback\ncompletes.

      \n

      The context given during the call to napi_create_threadsafe_function() can\nbe retrieved from any thread with a call to\nnapi_get_threadsafe_function_context().

      ", + "modules": [ + { + "textRaw": "Calling a thread-safe function", + "name": "calling_a_thread-safe_function", + "desc": "

      napi_call_threadsafe_function() can be used for initiating a call into\nJavaScript. napi_call_threadsafe_function() accepts a parameter which controls\nwhether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API\nbehaves non-blockingly, returning napi_queue_full if the queue was full,\npreventing data from being successfully added to the queue. If set to\nnapi_tsfn_blocking, the API blocks until space becomes available in the queue.\nnapi_call_threadsafe_function() never blocks if the thread-safe function was\ncreated with a maximum queue size of 0.

      \n

      The actual call into JavaScript is controlled by the callback given via the\ncall_js_cb parameter. call_js_cb is invoked on the main thread once for each\nvalue that was placed into the queue by a successful call to\nnapi_call_threadsafe_function(). If such a callback is not given, a default\ncallback will be used, and the resulting JavaScript call will have no arguments.\nThe call_js_cb callback receives the JavaScript function to call as a\nnapi_value in its parameters, as well as the void* context pointer used when\ncreating the napi_threadsafe_function, and the next data pointer that was\ncreated by one of the secondary threads. The callback can then use an API such\nas napi_call_function() to call into JavaScript.

      \n

      The callback may also be invoked with env and call_js_cb both set to NULL\nto indicate that calls into JavaScript are no longer possible, while items\nremain in the queue that may need to be freed. This normally occurs when the\nNode.js process exits while there is a thread-safe function still active.

      \n

      It is not necessary to call into JavaScript via napi_make_callback() because\nN-API runs call_js_cb in a context appropriate for callbacks.

      ", + "type": "module", + "displayName": "Calling a thread-safe function" + }, + { + "textRaw": "Reference counting of thread-safe functions", + "name": "reference_counting_of_thread-safe_functions", + "desc": "

      Threads can be added to and removed from a napi_threadsafe_function object\nduring its existence. Thus, in addition to specifying an initial number of\nthreads upon creation, napi_acquire_threadsafe_function can be called to\nindicate that a new thread will start making use of the thread-safe function.\nSimilarly, napi_release_threadsafe_function can be called to indicate that an\nexisting thread will stop making use of the thread-safe function.

      \n

      napi_threadsafe_function objects are destroyed when every thread which uses\nthe object has called napi_release_threadsafe_function() or has received a\nreturn status of napi_closing in response to a call to\nnapi_call_threadsafe_function. The queue is emptied before the\nnapi_threadsafe_function is destroyed. napi_release_threadsafe_function()\nshould be the last API call made in conjunction with a given\nnapi_threadsafe_function, because after the call completes, there is no\nguarantee that the napi_threadsafe_function is still allocated. For the same\nreason, do not use a thread-safe function\nafter receiving a return value of napi_closing in response to a call to\nnapi_call_threadsafe_function. Data associated with the\nnapi_threadsafe_function can be freed in its napi_finalize callback which\nwas passed to napi_create_threadsafe_function(). The parameter\ninitial_thread_count of napi_create_threadsafe_function marks the initial\nnumber of aquisitions of the thread-safe functions, instead of calling\nnapi_acquire_threadsafe_function multiple times at creation.

      \n

      Once the number of threads making use of a napi_threadsafe_function reaches\nzero, no further threads can start making use of it by calling\nnapi_acquire_threadsafe_function(). In fact, all subsequent API calls\nassociated with it, except napi_release_threadsafe_function(), will return an\nerror value of napi_closing.

      \n

      The thread-safe function can be \"aborted\" by giving a value of napi_tsfn_abort\nto napi_release_threadsafe_function(). This will cause all subsequent APIs\nassociated with the thread-safe function except\nnapi_release_threadsafe_function() to return napi_closing even before its\nreference count reaches zero. In particular, napi_call_threadsafe_function()\nwill return napi_closing, thus informing the threads that it is no longer\npossible to make asynchronous calls to the thread-safe function. This can be\nused as a criterion for terminating the thread. Upon receiving a return value\nof napi_closing from napi_call_threadsafe_function() a thread must not use\nthe thread-safe function anymore because it is no longer guaranteed to\nbe allocated.

      ", + "type": "module", + "displayName": "Reference counting of thread-safe functions" + }, + { + "textRaw": "Deciding whether to keep the process running", + "name": "deciding_whether_to_keep_the_process_running", + "desc": "

      Similarly to libuv handles, thread-safe functions can be \"referenced\" and\n\"unreferenced\". A \"referenced\" thread-safe function will cause the event loop on\nthe thread on which it is created to remain alive until the thread-safe function\nis destroyed. In contrast, an \"unreferenced\" thread-safe function will not\nprevent the event loop from exiting. The APIs napi_ref_threadsafe_function and\nnapi_unref_threadsafe_function exist for this purpose.

      \n

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as\nable to be destroyed nor does napi_ref_threadsafe_function prevent it from\nbeing destroyed.

      ", + "type": "module", + "displayName": "Deciding whether to keep the process running" + }, + { + "textRaw": "napi_create_threadsafe_function", + "name": "napi_create_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [ + { + "version": "v12.6.0", + "pr-url": "https://github.com/nodejs/node/pull/27791", + "description": "Made `func` parameter optional with custom `call_js_cb`." + } + ] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_create_threadsafe_function(napi_env env,\n                                napi_value func,\n                                napi_value async_resource,\n                                napi_value async_resource_name,\n                                size_t max_queue_size,\n                                size_t initial_thread_count,\n                                void* thread_finalize_data,\n                                napi_finalize thread_finalize_cb,\n                                void* context,\n                                napi_threadsafe_function_call_js call_js_cb,\n                                napi_threadsafe_function* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] func: An optional JavaScript function to call from another thread. It\nmust be provided if NULL is passed to call_js_cb.
      • \n
      • [in] async_resource: An optional object associated with the async work that\nwill be passed to possible async_hooks init hooks.
      • \n
      • [in] async_resource_name: A JavaScript string to provide an identifier for\nthe kind of resource that is being provided for diagnostic information exposed\nby the async_hooks API.
      • \n
      • [in] max_queue_size: Maximum size of the queue. 0 for no limit.
      • \n
      • [in] initial_thread_count: The initial number of acquisitions, i.e. the\ninitial number of threads, including the main thread, which will be making use\nof this function.
      • \n
      • [in] thread_finalize_data: Optional data to be passed to thread_finalize_cb.
      • \n
      • [in] thread_finalize_cb: Optional function to call when the\nnapi_threadsafe_function is being destroyed.
      • \n
      • [in] context: Optional data to attach to the resulting\nnapi_threadsafe_function.
      • \n
      • [in] call_js_cb: Optional callback which calls the JavaScript function in\nresponse to a call on a different thread. This callback will be called on the\nmain thread. If not given, the JavaScript function will be called with no\nparameters and with undefined as its this value.\nnapi_threadsafe_function_call_js provides more details.
      • \n
      • [out] result: The asynchronous thread-safe JavaScript function.
      • \n
      ", + "type": "module", + "displayName": "napi_create_threadsafe_function" + }, + { + "textRaw": "napi_get_threadsafe_function_context", + "name": "napi_get_threadsafe_function_context", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_get_threadsafe_function_context(napi_threadsafe_function func,\n                                     void** result);\n
      \n
        \n
      • [in] func: The thread-safe function for which to retrieve the context.
      • \n
      • [out] result: The location where to store the context.
      • \n
      \n

      This API may be called from any thread which makes use of func.

      ", + "type": "module", + "displayName": "napi_get_threadsafe_function_context" + }, + { + "textRaw": "napi_call_threadsafe_function", + "name": "napi_call_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_call_threadsafe_function(napi_threadsafe_function func,\n                              void* data,\n                              napi_threadsafe_function_call_mode is_blocking);\n
      \n
        \n
      • [in] func: The asynchronous thread-safe JavaScript function to invoke.
      • \n
      • [in] data: Data to send into JavaScript via the callback call_js_cb\nprovided during the creation of the thread-safe JavaScript function.
      • \n
      • [in] is_blocking: Flag whose value can be either napi_tsfn_blocking to\nindicate that the call should block if the queue is full or\nnapi_tsfn_nonblocking to indicate that the call should return immediately\nwith a status of napi_queue_full whenever the queue is full.
      • \n
      \n

      This API will return napi_closing if napi_release_threadsafe_function() was\ncalled with abort set to napi_tsfn_abort from any thread. The value is only\nadded to the queue if the API returns napi_ok.

      \n

      This API may be called from any thread which makes use of func.

      ", + "type": "module", + "displayName": "napi_call_threadsafe_function" + }, + { + "textRaw": "napi_acquire_threadsafe_function", + "name": "napi_acquire_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_acquire_threadsafe_function(napi_threadsafe_function func);\n
      \n
        \n
      • [in] func: The asynchronous thread-safe JavaScript function to start making\nuse of.
      • \n
      \n

      A thread should call this API before passing func to any other thread-safe\nfunction APIs to indicate that it will be making use of func. This prevents\nfunc from being destroyed when all other threads have stopped making use of\nit.

      \n

      This API may be called from any thread which will start making use of func.

      ", + "type": "module", + "displayName": "napi_acquire_threadsafe_function" + }, + { + "textRaw": "napi_release_threadsafe_function", + "name": "napi_release_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_release_threadsafe_function(napi_threadsafe_function func,\n                                 napi_threadsafe_function_release_mode mode);\n
      \n
        \n
      • [in] func: The asynchronous thread-safe JavaScript function whose reference\ncount to decrement.
      • \n
      • [in] mode: Flag whose value can be either napi_tsfn_release to indicate\nthat the current thread will make no further calls to the thread-safe\nfunction, or napi_tsfn_abort to indicate that in addition to the current\nthread, no other thread should make any further calls to the thread-safe\nfunction. If set to napi_tsfn_abort, further calls to\nnapi_call_threadsafe_function() will return napi_closing, and no further\nvalues will be placed in the queue.
      • \n
      \n

      A thread should call this API when it stops making use of func. Passing func\nto any thread-safe APIs after having called this API has undefined results, as\nfunc may have been destroyed.

      \n

      This API may be called from any thread which will stop making use of func.

      ", + "type": "module", + "displayName": "napi_release_threadsafe_function" + }, + { + "textRaw": "napi_ref_threadsafe_function", + "name": "napi_ref_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] func: The thread-safe function to reference.
      • \n
      \n

      This API is used to indicate that the event loop running on the main thread\nshould not exit until func has been destroyed. Similar to uv_ref it is\nalso idempotent.

      \n

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as\nable to be destroyed nor does napi_ref_threadsafe_function prevent it from\nbeing destroyed. napi_acquire_threadsafe_function and\nnapi_release_threadsafe_function are available for that purpose.

      \n

      This API may only be called from the main thread.

      ", + "type": "module", + "displayName": "napi_ref_threadsafe_function" + }, + { + "textRaw": "napi_unref_threadsafe_function", + "name": "napi_unref_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] func: The thread-safe function to unreference.
      • \n
      \n

      This API is used to indicate that the event loop running on the main thread\nmay exit before func is destroyed. Similar to uv_unref it is also\nidempotent.

      \n

      This API may only be called from the main thread.

      ", + "type": "module", + "displayName": "napi_unref_threadsafe_function" + } + ], + "type": "misc", + "displayName": "Asynchronous thread-safe function calls" + }, + { + "textRaw": "Miscellaneous utilities", + "name": "miscellaneous_utilities", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "
      NAPI_EXTERN napi_status\nnode_api_get_module_file_name(napi_env env, const char** result);\n\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: A URL containing the absolute path of the\nlocation from which the add-on was loaded. For a file on the local\nfile system it will start with file://. The string is null-terminated and\nowned by env and must thus not be modified or freed.
      • \n
      \n

      result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.

      ", + "type": "misc", + "displayName": "Miscellaneous utilities" + }, + { + "textRaw": "node_api_get_module_file_name", + "name": "node_api_get_module_file_name", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "
      NAPI_EXTERN napi_status\nnode_api_get_module_file_name(napi_env env, const char** result);\n\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: A URL containing the absolute path of the\nlocation from which the add-on was loaded. For a file on the local\nfile system it will start with file://. The string is null-terminated and\nowned by env and must thus not be modified or freed.
      • \n
      \n

      result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.

      ", + "type": "misc", + "displayName": "node_api_get_module_file_name" + } + ] + }, + { + "textRaw": "Command line options", + "name": "Command line options", + "introduced_in": "v5.9.1", + "type": "misc", + "desc": "

      Node.js comes with a variety of CLI options. These options expose built-in\ndebugging, multiple ways to execute scripts, and other helpful runtime options.

      \n

      To view this documentation as a manual page in a terminal, run man node.

      ", + "miscs": [ + { + "textRaw": "Synopsis", + "name": "synopsis", + "desc": "

      node [options] [V8 options] [script.js | -e \"script\" | -] [--] [arguments]

      \n

      node inspect [script.js | -e \"script\" | <host>:<port>] …

      \n

      node --v8-options

      \n

      Execute without arguments to start the REPL.

      \n

      For more info about node inspect, please see the debugger documentation.

      ", + "type": "misc", + "displayName": "Synopsis" + }, + { + "textRaw": "Options", + "name": "options", + "meta": { + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/23020", + "description": "Underscores instead of dashes are now allowed for Node.js options as well, in addition to V8 options." + } + ] + }, + "desc": "

      All options, including V8 options, allow words to be separated by both\ndashes (-) or underscores (_).

      \n

      For example, --pending-deprecation is equivalent to --pending_deprecation.

      \n

      If an option that takes a single value, for example --max-http-header-size,\nis passed more than once, then the last passed value will be used. Options\nfrom the command line take precedence over options passed through the\nNODE_OPTIONS environment variable.

      ", + "modules": [ + { + "textRaw": "`-`", + "name": "`-`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Alias for stdin. Analogous to the use of - in other command line utilities,\nmeaning that the script will be read from stdin, and the rest of the options\nare passed to that script.

      ", + "type": "module", + "displayName": "`-`" + }, + { + "textRaw": "`--`", + "name": "`--`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      Indicate the end of node options. Pass the rest of the arguments to the script.\nIf no script filename or eval/print script is supplied prior to this, then\nthe next argument will be used as a script filename.

      ", + "type": "module", + "displayName": "`--`" + }, + { + "textRaw": "`--abort-on-uncaught-exception`", + "name": "`--abort-on-uncaught-exception`", + "meta": { + "added": [ + "v0.10.8" + ], + "changes": [] + }, + "desc": "

      Aborting instead of exiting causes a core file to be generated for post-mortem\nanalysis using a debugger (such as lldb, gdb, and mdb).

      \n

      If this flag is passed, the behavior can still be set to not abort through\nprocess.setUncaughtExceptionCaptureCallback() (and through usage of the\ndomain module that uses it).

      ", + "type": "module", + "displayName": "`--abort-on-uncaught-exception`" + }, + { + "textRaw": "`--completion-bash`", + "name": "`--completion-bash`", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "desc": "

      Print source-able bash completion script for Node.js.

      \n
      $ node --completion-bash > node_bash_completion\n$ source node_bash_completion\n
      ", + "type": "module", + "displayName": "`--completion-bash`" + }, + { + "textRaw": "`--conditions=condition`", + "name": "`--conditions=condition`", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Enable experimental support for custom conditional exports resolution\nconditions.

      \n

      Any number of custom string condition names are permitted.

      \n

      The default Node.js conditions of \"node\", \"default\", \"import\", and\n\"require\" will always apply as defined.

      ", + "type": "module", + "displayName": "`--conditions=condition`" + }, + { + "textRaw": "`--cpu-prof`", + "name": "`--cpu-prof`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Starts the V8 CPU profiler on start up, and writes the CPU profile to disk\nbefore exit.

      \n

      If --cpu-prof-dir is not specified, the generated profile will be placed\nin the current working directory.

      \n

      If --cpu-prof-name is not specified, the generated profile will be\nnamed CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.

      \n
      $ node --cpu-prof index.js\n$ ls *.cpuprofile\nCPU.20190409.202950.15293.0.0.cpuprofile\n
      ", + "type": "module", + "displayName": "`--cpu-prof`" + }, + { + "textRaw": "`--cpu-prof-dir`", + "name": "`--cpu-prof-dir`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the directory where the CPU profiles generated by --cpu-prof will\nbe placed.

      \n

      The default value is controlled by the\n--diagnostic-dir command line option.

      ", + "type": "module", + "displayName": "`--cpu-prof-dir`" + }, + { + "textRaw": "`--cpu-prof-interval`", + "name": "`--cpu-prof-interval`", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the sampling interval in microseconds for the CPU profiles generated\nby --cpu-prof. The default is 1000 microseconds.

      ", + "type": "module", + "displayName": "`--cpu-prof-interval`" + }, + { + "textRaw": "`--cpu-prof-name`", + "name": "`--cpu-prof-name`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the file name of the CPU profile generated by --cpu-prof.

      ", + "type": "module", + "displayName": "`--cpu-prof-name`" + }, + { + "textRaw": "`--diagnostic-dir=directory`", + "name": "`--diagnostic-dir=directory`", + "desc": "

      Set the directory to which all diagnostic output files will be written to.\nDefaults to current working directory.

      \n

      Affects the default output directory of:

      \n", + "type": "module", + "displayName": "`--diagnostic-dir=directory`" + }, + { + "textRaw": "`--disable-proto=mode`", + "name": "`--disable-proto=mode`", + "desc": "\n

      Disable the Object.prototype.__proto__ property. If mode is delete, the\nproperty will be removed entirely. If mode is throw, accesses to the\nproperty will throw an exception with the code ERR_PROTO_ACCESS.

      ", + "type": "module", + "displayName": "`--disable-proto=mode`" + }, + { + "textRaw": "`--disallow-code-generation-from-strings`", + "name": "`--disallow-code-generation-from-strings`", + "meta": { + "added": [ + "v9.8.0" + ], + "changes": [] + }, + "desc": "

      Make built-in language features like eval and new Function that generate\ncode from strings throw an exception instead. This does not affect the Node.js\nvm module.

      ", + "type": "module", + "displayName": "`--disallow-code-generation-from-strings`" + }, + { + "textRaw": "`--enable-fips`", + "name": "`--enable-fips`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with\n./configure --openssl-fips.)

      ", + "type": "module", + "displayName": "`--enable-fips`" + }, + { + "textRaw": "`--enable-source-maps`", + "name": "`--enable-source-maps`", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Enable experimental Source Map v3 support for stack traces.

      \n

      Currently, overriding Error.prepareStackTrace is ignored when the\n--enable-source-maps flag is set.

      ", + "type": "module", + "displayName": "`--enable-source-maps`" + }, + { + "textRaw": "`--experimental-import-meta-resolve`", + "name": "`--experimental-import-meta-resolve`", + "meta": { + "added": [ + "v12.16.2" + ], + "changes": [] + }, + "desc": "

      Enable experimental import.meta.resolve() support.

      ", + "type": "module", + "displayName": "`--experimental-import-meta-resolve`" + }, + { + "textRaw": "`--experimental-json-modules`", + "name": "`--experimental-json-modules`", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental JSON support for the ES Module loader.

      ", + "type": "module", + "displayName": "`--experimental-json-modules`" + }, + { + "textRaw": "`--experimental-loader=module`", + "name": "`--experimental-loader=module`", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "desc": "

      Specify the module of a custom experimental ECMAScript Module loader.\nmodule may be either a path to a file, or an ECMAScript Module name.

      ", + "type": "module", + "displayName": "`--experimental-loader=module`" + }, + { + "textRaw": "`--experimental-modules`", + "name": "`--experimental-modules`", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      Enable latest experimental modules features (deprecated).

      ", + "type": "module", + "displayName": "`--experimental-modules`" + }, + { + "textRaw": "`--experimental-policy`", + "name": "`--experimental-policy`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [] + }, + "desc": "

      Use the specified file as a security policy.

      ", + "type": "module", + "displayName": "`--experimental-policy`" + }, + { + "textRaw": "`--experimental-repl-await`", + "name": "`--experimental-repl-await`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental top-level await keyword support in REPL.

      ", + "type": "module", + "displayName": "`--experimental-repl-await`" + }, + { + "textRaw": "`--experimental-specifier-resolution=mode`", + "name": "`--experimental-specifier-resolution=mode`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Sets the resolution algorithm for resolving ES module specifiers. Valid options\nare explicit and node.

      \n

      The default is explicit, which requires providing the full path to a\nmodule. The node mode will enable support for optional file extensions and\nthe ability to import a directory that has an index file.

      \n

      Please see customizing ESM specifier resolution for example usage.

      ", + "type": "module", + "displayName": "`--experimental-specifier-resolution=mode`" + }, + { + "textRaw": "`--experimental-vm-modules`", + "name": "`--experimental-vm-modules`", + "meta": { + "added": [ + "v9.6.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental ES Module support in the vm module.

      ", + "type": "module", + "displayName": "`--experimental-vm-modules`" + }, + { + "textRaw": "`--experimental-wasi-unstable-preview1`", + "name": "`--experimental-wasi-unstable-preview1`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental WebAssembly System Interface (WASI) support.

      ", + "type": "module", + "displayName": "`--experimental-wasi-unstable-preview1`" + }, + { + "textRaw": "`--experimental-wasm-modules`", + "name": "`--experimental-wasm-modules`", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "type": "module", + "displayName": "`--experimental-wasm-modules`" + }, + { + "textRaw": "`--force-context-aware`", + "name": "`--force-context-aware`", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      Disable loading native addons that are not context-aware.

      \n

      Enable experimental WebAssembly module support.

      ", + "type": "module", + "displayName": "`--force-context-aware`" + }, + { + "textRaw": "`--force-fips`", + "name": "`--force-fips`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)\n(Same requirements as --enable-fips.)

      ", + "type": "module", + "displayName": "`--force-fips`" + }, + { + "textRaw": "`--frozen-intrinsics`", + "name": "`--frozen-intrinsics`", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Enable experimental frozen intrinsics like Array and Object.

      \n

      Support is currently only provided for the root context and no guarantees are\ncurrently provided that global.Array is indeed the default intrinsic\nreference. Code may break under this flag.

      \n

      --require runs prior to freezing intrinsics in order to allow polyfills to\nbe added.

      ", + "type": "module", + "displayName": "`--frozen-intrinsics`" + }, + { + "textRaw": "`--heapsnapshot-signal=signal`", + "name": "`--heapsnapshot-signal=signal`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Enables a signal handler that causes the Node.js process to write a heap dump\nwhen the specified signal is received. signal must be a valid signal name.\nDisabled by default.

      \n
      $ node --heapsnapshot-signal=SIGUSR2 index.js &\n$ ps aux\nUSER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND\nnode         1  5.5  6.1 787252 247004 ?       Ssl  16:43   0:02 node --heapsnapshot-signal=SIGUSR2 index.js\n$ kill -USR2 1\n$ ls\nHeap.20190718.133405.15554.0.001.heapsnapshot\n
      ", + "type": "module", + "displayName": "`--heapsnapshot-signal=signal`" + }, + { + "textRaw": "`--heap-prof`", + "name": "`--heap-prof`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Starts the V8 heap profiler on start up, and writes the heap profile to disk\nbefore exit.

      \n

      If --heap-prof-dir is not specified, the generated profile will be placed\nin the current working directory.

      \n

      If --heap-prof-name is not specified, the generated profile will be\nnamed Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.

      \n
      $ node --heap-prof index.js\n$ ls *.heapprofile\nHeap.20190409.202950.15293.0.001.heapprofile\n
      ", + "type": "module", + "displayName": "`--heap-prof`" + }, + { + "textRaw": "`--heap-prof-dir`", + "name": "`--heap-prof-dir`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the directory where the heap profiles generated by --heap-prof will\nbe placed.

      \n

      The default value is controlled by the\n--diagnostic-dir command line option.

      ", + "type": "module", + "displayName": "`--heap-prof-dir`" + }, + { + "textRaw": "`--heap-prof-interval`", + "name": "`--heap-prof-interval`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the average sampling interval in bytes for the heap profiles generated\nby --heap-prof. The default is 512 * 1024 bytes.

      ", + "type": "module", + "displayName": "`--heap-prof-interval`" + }, + { + "textRaw": "`--heap-prof-name`", + "name": "`--heap-prof-name`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the file name of the heap profile generated by --heap-prof.

      ", + "type": "module", + "displayName": "`--heap-prof-name`" + }, + { + "textRaw": "`--http-parser=library`", + "name": "`--http-parser=library`", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [ + { + "version": "v12.22.0", + "pr-url": "https://github.com/nodejs/node/pull/37603", + "description": "The legacy HTTP parser will emit a deprecation warning." + } + ] + }, + "desc": "

      Chooses an HTTP parser library. Available values are:

      \n\n

      The default is llhttp, unless otherwise specified when building Node.js.

      \n

      The legacy HTTP parser is deprecated and will emit a deprecation warning.

      \n

      This flag exists to aid in experimentation with the internal implementation of\nthe Node.js http parser.\nThis flag is likely to become a no-op and removed at some point in the future.

      ", + "type": "module", + "displayName": "`--http-parser=library`" + }, + { + "textRaw": "`--http-server-default-timeout=milliseconds`", + "name": "`--http-server-default-timeout=milliseconds`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "desc": "

      Overrides the default value of http, https and http2 server socket\ntimeout. Setting the value to 0 disables server socket timeout. Unless\nprovided, http server sockets timeout after 120s (2 minutes). Programmatic\nsetting of the timeout takes precedence over the value set through this\nflag.

      ", + "type": "module", + "displayName": "`--http-server-default-timeout=milliseconds`" + }, + { + "textRaw": "`--icu-data-dir=file`", + "name": "`--icu-data-dir=file`", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      Specify ICU data load path. (Overrides NODE_ICU_DATA.)

      ", + "type": "module", + "displayName": "`--icu-data-dir=file`" + }, + { + "textRaw": "`--input-type=type`", + "name": "`--input-type=type`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      This configures Node.js to interpret string input as CommonJS or as an ES\nmodule. String input is input via --eval, --print, or STDIN.

      \n

      Valid values are \"commonjs\" and \"module\". The default is \"commonjs\".

      ", + "type": "module", + "displayName": "`--input-type=type`" + }, + { + "textRaw": "`--inspect-brk[=[host:]port]`", + "name": "`--inspect-brk[=[host:]port]`", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "desc": "

      Activate inspector on host:port and break at start of user script.\nDefault host:port is 127.0.0.1:9229.

      ", + "type": "module", + "displayName": "`--inspect-brk[=[host:]port]`" + }, + { + "textRaw": "`--inspect-port=[host:]port`", + "name": "`--inspect-port=[host:]port`", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "desc": "

      Set the host:port to be used when the inspector is activated.\nUseful when activating the inspector by sending the SIGUSR1 signal.

      \n

      Default host is 127.0.0.1.

      \n

      See the security warning below regarding the host\nparameter usage.

      ", + "type": "module", + "displayName": "`--inspect-port=[host:]port`" + }, + { + "textRaw": "`--inspect[=[host:]port]`", + "name": "`--inspect[=[host:]port]`", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "

      Activate inspector on host:port. Default is 127.0.0.1:9229.

      \n

      V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug\nand profile Node.js instances. The tools attach to Node.js instances via a\ntcp port and communicate using the Chrome DevTools Protocol.

      \n

      ", + "modules": [ + { + "textRaw": "Warning: binding inspector to a public IP:port combination is insecure", + "name": "warning:_binding_inspector_to_a_public_ip:port_combination_is_insecure", + "desc": "

      Binding the inspector to a public IP (including 0.0.0.0) with an open port is\ninsecure, as it allows external hosts to connect to the inspector and perform\na remote code execution attack.

      \n

      If specifying a host, make sure that either:

      \n
        \n
      • The host is not accessible from public networks.
      • \n
      • A firewall disallows unwanted connections on the port.
      • \n
      \n

      More specifically, --inspect=0.0.0.0 is insecure if the port (9229 by\ndefault) is not firewall-protected.

      \n

      See the debugging security implications section for more information.

      ", + "type": "module", + "displayName": "Warning: binding inspector to a public IP:port combination is insecure" + } + ], + "type": "module", + "displayName": "`--inspect[=[host:]port]`" + }, + { + "textRaw": "`--inspect-publish-uid=stderr,http`", + "name": "`--inspect-publish-uid=stderr,http`", + "desc": "

      Specify ways of the inspector web socket url exposure.

      \n

      By default inspector websocket url is available in stderr and under /json/list\nendpoint on http://host:port/json/list.

      ", + "type": "module", + "displayName": "`--inspect-publish-uid=stderr,http`" + }, + { + "textRaw": "`--insecure-http-parser`", + "name": "`--insecure-http-parser`", + "meta": { + "added": [ + "v12.15.0" + ], + "changes": [] + }, + "desc": "

      Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow\ninteroperability with non-conformant HTTP implementations. It may also allow\nrequest smuggling and other HTTP attacks that rely on invalid headers being\naccepted. Avoid using this option.

      ", + "type": "module", + "displayName": "`--insecure-http-parser`" + }, + { + "textRaw": "`--jitless`", + "name": "`--jitless`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Disable runtime allocation of executable memory. This may be\nrequired on some platforms for security reasons. It can also reduce attack\nsurface on other platforms, but the performance impact may be severe.

      \n

      This flag is inherited from V8 and is subject to change upstream. It may\ndisappear in a non-semver-major release.

      ", + "type": "module", + "displayName": "`--jitless`" + }, + { + "textRaw": "`--max-http-header-size=size`", + "name": "`--max-http-header-size=size`", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB.

      ", + "type": "module", + "displayName": "`--max-http-header-size=size`" + }, + { + "textRaw": "`--napi-modules`", + "name": "`--napi-modules`", + "meta": { + "added": [ + "v7.10.0" + ], + "changes": [] + }, + "desc": "

      This option is a no-op. It is kept for compatibility.

      ", + "type": "module", + "displayName": "`--napi-modules`" + }, + { + "textRaw": "`--no-deprecation`", + "name": "`--no-deprecation`", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      Silence deprecation warnings.

      ", + "type": "module", + "displayName": "`--no-deprecation`" + }, + { + "textRaw": "`--no-force-async-hooks-checks`", + "name": "`--no-force-async-hooks-checks`", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "desc": "

      Disables runtime checks for async_hooks. These will still be enabled\ndynamically when async_hooks is enabled.

      ", + "type": "module", + "displayName": "`--no-force-async-hooks-checks`" + }, + { + "textRaw": "`--no-warnings`", + "name": "`--no-warnings`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Silence all process warnings (including deprecations).

      ", + "type": "module", + "displayName": "`--no-warnings`" + }, + { + "textRaw": "`--openssl-config=file`", + "name": "`--openssl-config=file`", + "meta": { + "added": [ + "v6.9.0" + ], + "changes": [] + }, + "desc": "

      Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built with\n./configure --openssl-fips.

      ", + "type": "module", + "displayName": "`--openssl-config=file`" + }, + { + "textRaw": "`--pending-deprecation`", + "name": "`--pending-deprecation`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Emit pending deprecation warnings.

      \n

      Pending deprecations are generally identical to a runtime deprecation with the\nnotable exception that they are turned off by default and will not be emitted\nunless either the --pending-deprecation command line flag, or the\nNODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations\nare used to provide a kind of selective \"early warning\" mechanism that\ndevelopers may leverage to detect deprecated API usage.

      ", + "type": "module", + "displayName": "`--pending-deprecation`" + }, + { + "textRaw": "`--policy-integrity=sri`", + "name": "`--policy-integrity=sri`", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Instructs Node.js to error prior to running any code if the policy does not have\nthe specified integrity. It expects a Subresource Integrity string as a\nparameter.

      ", + "type": "module", + "displayName": "`--policy-integrity=sri`" + }, + { + "textRaw": "`--preserve-symlinks`", + "name": "`--preserve-symlinks`", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "

      Instructs the module loader to preserve symbolic links when resolving and\ncaching modules.

      \n

      By default, when Node.js loads a module from a path that is symbolically linked\nto a different on-disk location, Node.js will dereference the link and use the\nactual on-disk \"real path\" of the module as both an identifier and as a root\npath to locate other dependency modules. In most cases, this default behavior\nis acceptable. However, when using symbolically linked peer dependencies, as\nillustrated in the example below, the default behavior causes an exception to\nbe thrown if moduleA attempts to require moduleB as a peer dependency:

      \n
      {appDir}\n ├── app\n │   ├── index.js\n │   └── node_modules\n │       ├── moduleA -> {appDir}/moduleA\n │       └── moduleB\n │           ├── index.js\n │           └── package.json\n └── moduleA\n     ├── index.js\n     └── package.json\n
      \n

      The --preserve-symlinks command line flag instructs Node.js to use the\nsymlink path for modules as opposed to the real path, allowing symbolically\nlinked peer dependencies to be found.

      \n

      Note, however, that using --preserve-symlinks can have other side effects.\nSpecifically, symbolically linked native modules can fail to load if those\nare linked from more than one location in the dependency tree (Node.js would\nsee those as two separate modules and would attempt to load the module multiple\ntimes, causing an exception to be thrown).

      \n

      The --preserve-symlinks flag does not apply to the main module, which allows\nnode --preserve-symlinks node_module/.bin/<foo> to work. To apply the same\nbehavior for the main module, also use --preserve-symlinks-main.

      ", + "type": "module", + "displayName": "`--preserve-symlinks`" + }, + { + "textRaw": "`--preserve-symlinks-main`", + "name": "`--preserve-symlinks-main`", + "meta": { + "added": [ + "v10.2.0" + ], + "changes": [] + }, + "desc": "

      Instructs the module loader to preserve symbolic links when resolving and\ncaching the main module (require.main).

      \n

      This flag exists so that the main module can be opted-in to the same behavior\nthat --preserve-symlinks gives to all other imports; they are separate flags,\nhowever, for backward compatibility with older Node.js versions.

      \n

      --preserve-symlinks-main does not imply --preserve-symlinks; it\nis expected that --preserve-symlinks-main will be used in addition to\n--preserve-symlinks when it is not desirable to follow symlinks before\nresolving relative paths.

      \n

      See --preserve-symlinks for more information.

      ", + "type": "module", + "displayName": "`--preserve-symlinks-main`" + }, + { + "textRaw": "`--prof`", + "name": "`--prof`", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "desc": "

      Generate V8 profiler output.

      ", + "type": "module", + "displayName": "`--prof`" + }, + { + "textRaw": "`--prof-process`", + "name": "`--prof-process`", + "meta": { + "added": [ + "v5.2.0" + ], + "changes": [] + }, + "desc": "

      Process V8 profiler output generated using the V8 option --prof.

      ", + "type": "module", + "displayName": "`--prof-process`" + }, + { + "textRaw": "`--redirect-warnings=file`", + "name": "`--redirect-warnings=file`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Write process warnings to the given file instead of printing to stderr. The\nfile will be created if it does not exist, and will be appended to if it does.\nIf an error occurs while attempting to write the warning to the file, the\nwarning will be written to stderr instead.

      \n

      The file name may be an absolute path. If it is not, the default directory it\nwill be written to is controlled by the\n--diagnostic-dir command line option.

      ", + "type": "module", + "displayName": "`--redirect-warnings=file`" + }, + { + "textRaw": "`--report-compact`", + "name": "`--report-compact`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Write reports in a compact format, single-line JSON, more easily consumable\nby log processing systems than the default multi-line format designed for\nhuman consumption.

      ", + "type": "module", + "displayName": "`--report-compact`" + }, + { + "textRaw": "`--report-dir=directory`, `report-directory=directory`", + "name": "`--report-dir=directory`,_`report-directory=directory`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "Changed from `--diagnostic-report-directory` to `--report-directory`" + } + ] + }, + "desc": "

      Location at which the report will be generated.

      ", + "type": "module", + "displayName": "`--report-dir=directory`, `report-directory=directory`" + }, + { + "textRaw": "`--report-filename=filename`", + "name": "`--report-filename=filename`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-filename` to `--report-filename`" + } + ] + }, + "desc": "

      Name of the file to which the report will be written.

      ", + "type": "module", + "displayName": "`--report-filename=filename`" + }, + { + "textRaw": "`--report-on-fatalerror`", + "name": "`--report-on-fatalerror`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32496", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-on-fatalerror` to `--report-on-fatalerror`" + } + ] + }, + "desc": "

      Enables the report to be triggered on fatal errors (internal errors within\nthe Node.js runtime such as out of memory) that lead to termination of the\napplication. Useful to inspect various diagnostic data elements such as heap,\nstack, event loop state, resource consumption etc. to reason about the fatal\nerror.

      ", + "type": "module", + "displayName": "`--report-on-fatalerror`" + }, + { + "textRaw": "`--report-on-signal`", + "name": "`--report-on-signal`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-on-signal` to `--report-on-signal`" + } + ] + }, + "desc": "

      Enables report to be generated upon receiving the specified (or predefined)\nsignal to the running Node.js process. The signal to trigger the report is\nspecified through --report-signal.

      ", + "type": "module", + "displayName": "`--report-on-signal`" + }, + { + "textRaw": "`--report-signal=signal`", + "name": "`--report-signal=signal`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-signal` to `--report-signal`" + } + ] + }, + "desc": "

      Sets or resets the signal for report generation (not supported on Windows).\nDefault signal is SIGUSR2.

      ", + "type": "module", + "displayName": "`--report-signal=signal`" + }, + { + "textRaw": "`--report-uncaught-exception`", + "name": "`--report-uncaught-exception`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-uncaught-exception` to `--report-uncaught-exception`" + } + ] + }, + "desc": "

      Enables report to be generated on uncaught exceptions. Useful when inspecting\nthe JavaScript stack in conjunction with native stack and other runtime\nenvironment data.

      ", + "type": "module", + "displayName": "`--report-uncaught-exception`" + }, + { + "textRaw": "`--throw-deprecation`", + "name": "`--throw-deprecation`", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "desc": "

      Throw errors for deprecations.

      ", + "type": "module", + "displayName": "`--throw-deprecation`" + }, + { + "textRaw": "`--title=title`", + "name": "`--title=title`", + "meta": { + "added": [ + "v10.7.0" + ], + "changes": [] + }, + "desc": "

      Set process.title on startup.

      ", + "type": "module", + "displayName": "`--title=title`" + }, + { + "textRaw": "`--tls-cipher-list=list`", + "name": "`--tls-cipher-list=list`", + "meta": { + "added": [ + "v4.0.0" + ], + "changes": [] + }, + "desc": "

      Specify an alternative default TLS cipher list. Requires Node.js to be built\nwith crypto support (default).

      ", + "type": "module", + "displayName": "`--tls-cipher-list=list`" + }, + { + "textRaw": "`--tls-keylog=file`", + "name": "`--tls-keylog=file`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Log TLS key material to a file. The key material is in NSS SSLKEYLOGFILE\nformat and can be used by software (such as Wireshark) to decrypt the TLS\ntraffic.

      ", + "type": "module", + "displayName": "`--tls-keylog=file`" + }, + { + "textRaw": "`--tls-max-v1.2`", + "name": "`--tls-max-v1.2`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for\nTLSv1.3.

      ", + "type": "module", + "displayName": "`--tls-max-v1.2`" + }, + { + "textRaw": "`--tls-max-v1.3`", + "name": "`--tls-max-v1.3`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support\nfor TLSv1.3.

      ", + "type": "module", + "displayName": "`--tls-max-v1.3`" + }, + { + "textRaw": "`--tls-min-v1.0`", + "name": "`--tls-min-v1.0`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with\nold TLS clients or servers.

      ", + "type": "module", + "displayName": "`--tls-min-v1.0`" + }, + { + "textRaw": "`--tls-min-v1.1`", + "name": "`--tls-min-v1.1`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility\nwith old TLS clients or servers.

      ", + "type": "module", + "displayName": "`--tls-min-v1.1`" + }, + { + "textRaw": "`--tls-min-v1.2`", + "name": "`--tls-min-v1.2`", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.2'. This is the default for\n12.x and later, but the option is supported for compatibility with older Node.js\nversions.

      ", + "type": "module", + "displayName": "`--tls-min-v1.2`" + }, + { + "textRaw": "`--tls-min-v1.3`", + "name": "`--tls-min-v1.3`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support\nfor TLSv1.2, which is not as secure as TLSv1.3.

      ", + "type": "module", + "displayName": "`--tls-min-v1.3`" + }, + { + "textRaw": "`--trace-deprecation`", + "name": "`--trace-deprecation`", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      Print stack traces for deprecations.

      ", + "type": "module", + "displayName": "`--trace-deprecation`" + }, + { + "textRaw": "`--trace-event-categories`", + "name": "`--trace-event-categories`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      A comma separated list of categories that should be traced when trace event\ntracing is enabled using --trace-events-enabled.

      ", + "type": "module", + "displayName": "`--trace-event-categories`" + }, + { + "textRaw": "`--trace-event-file-pattern`", + "name": "`--trace-event-file-pattern`", + "meta": { + "added": [ + "v9.8.0" + ], + "changes": [] + }, + "desc": "

      Template string specifying the filepath for the trace event data, it\nsupports ${rotation} and ${pid}.

      ", + "type": "module", + "displayName": "`--trace-event-file-pattern`" + }, + { + "textRaw": "`--trace-events-enabled`", + "name": "`--trace-events-enabled`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      Enables the collection of trace event tracing information.

      ", + "type": "module", + "displayName": "`--trace-events-enabled`" + }, + { + "textRaw": "`--trace-exit`", + "name": "`--trace-exit`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Prints a stack trace whenever an environment is exited proactively,\ni.e. invoking process.exit().

      ", + "type": "module", + "displayName": "`--trace-exit`" + }, + { + "textRaw": "`--trace-sigint`", + "name": "`--trace-sigint`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Prints a stack trace on SIGINT.

      ", + "type": "module", + "displayName": "`--trace-sigint`" + }, + { + "textRaw": "`--trace-sync-io`", + "name": "`--trace-sync-io`", + "meta": { + "added": [ + "v2.1.0" + ], + "changes": [] + }, + "desc": "

      Prints a stack trace whenever synchronous I/O is detected after the first turn\nof the event loop.

      ", + "type": "module", + "displayName": "`--trace-sync-io`" + }, + { + "textRaw": "`--trace-tls`", + "name": "`--trace-tls`", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "desc": "

      Prints TLS packet trace information to stderr. This can be used to debug TLS\nconnection problems.

      ", + "type": "module", + "displayName": "`--trace-tls`" + }, + { + "textRaw": "`--trace-uncaught`", + "name": "`--trace-uncaught`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Print stack traces for uncaught exceptions; usually, the stack trace associated\nwith the creation of an Error is printed, whereas this makes Node.js also\nprint the stack trace associated with throwing the value (which does not need\nto be an Error instance).

      \n

      Enabling this option may affect garbage collection behavior negatively.

      ", + "type": "module", + "displayName": "`--trace-uncaught`" + }, + { + "textRaw": "`--trace-warnings`", + "name": "`--trace-warnings`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Print stack traces for process warnings (including deprecations).

      ", + "type": "module", + "displayName": "`--trace-warnings`" + }, + { + "textRaw": "`--track-heap-objects`", + "name": "`--track-heap-objects`", + "meta": { + "added": [ + "v2.4.0" + ], + "changes": [] + }, + "desc": "

      Track heap object allocations for heap snapshots.

      ", + "type": "module", + "displayName": "`--track-heap-objects`" + }, + { + "textRaw": "`--unhandled-rejections=mode`", + "name": "`--unhandled-rejections=mode`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      By default all unhandled rejections trigger a warning plus a deprecation warning\nfor the very first unhandled rejection in case no unhandledRejection hook\nis used.

      \n

      Using this flag allows to change what should happen when an unhandled rejection\noccurs. One of three modes can be chosen:

      \n
        \n
      • strict: Raise the unhandled rejection as an uncaught exception.
      • \n
      • warn: Always trigger a warning, no matter if the unhandledRejection\nhook is set or not but do not print the deprecation warning.
      • \n
      • none: Silence all warnings.
      • \n
      ", + "type": "module", + "displayName": "`--unhandled-rejections=mode`" + }, + { + "textRaw": "`--use-bundled-ca`, `--use-openssl-ca`", + "name": "`--use-bundled-ca`,_`--use-openssl-ca`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      Use bundled Mozilla CA store as supplied by current Node.js version\nor use OpenSSL's default CA store. The default store is selectable\nat build-time.

      \n

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store\nthat is fixed at release time. It is identical on all supported platforms.

      \n

      Using OpenSSL store allows for external modifications of the store. For most\nLinux and BSD distributions, this store is maintained by the distribution\nmaintainers and system administrators. OpenSSL CA store location is dependent on\nconfiguration of the OpenSSL library but this can be altered at runtime using\nenvironment variables.

      \n

      See SSL_CERT_DIR and SSL_CERT_FILE.

      ", + "type": "module", + "displayName": "`--use-bundled-ca`, `--use-openssl-ca`" + }, + { + "textRaw": "`--use-largepages=mode`", + "name": "`--use-largepages=mode`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Re-map the Node.js static code to large memory pages at startup. If supported on\nthe target system, this will cause the Node.js static code to be moved onto 2\nMiB pages instead of 4 KiB pages.

      \n

      The following values are valid for mode:

      \n
        \n
      • off: No mapping will be attempted. This is the default.
      • \n
      • on: If supported by the OS, mapping will be attempted. Failure to map will\nbe ignored and a message will be printed to standard error.
      • \n
      • silent: If supported by the OS, mapping will be attempted. Failure to map\nwill be ignored and will not be reported.
      • \n
      ", + "type": "module", + "displayName": "`--use-largepages=mode`" + }, + { + "textRaw": "`--v8-options`", + "name": "`--v8-options`", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      Print V8 command line options.

      ", + "type": "module", + "displayName": "`--v8-options`" + }, + { + "textRaw": "`--v8-pool-size=num`", + "name": "`--v8-pool-size=num`", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "desc": "

      Set V8's thread pool size which will be used to allocate background jobs.

      \n

      If set to 0 then V8 will choose an appropriate size of the thread pool based\non the number of online processors.

      \n

      If the value provided is larger than V8's maximum, then the largest value\nwill be chosen.

      ", + "type": "module", + "displayName": "`--v8-pool-size=num`" + }, + { + "textRaw": "`--zero-fill-buffers`", + "name": "`--zero-fill-buffers`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Automatically zero-fills all newly allocated Buffer and SlowBuffer\ninstances.

      ", + "type": "module", + "displayName": "`--zero-fill-buffers`" + }, + { + "textRaw": "`-c`, `--check`", + "name": "`-c`,_`--check`", + "meta": { + "added": [ + "v5.0.0", + "v4.2.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19600", + "description": "The `--require` option is now supported when checking a file." + } + ] + }, + "desc": "

      Syntax check the script without executing.

      ", + "type": "module", + "displayName": "`-c`, `--check`" + }, + { + "textRaw": "`-e`, `--eval \"script\"`", + "name": "`-e`,_`--eval_\"script\"`", + "meta": { + "added": [ + "v0.5.2" + ], + "changes": [ + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Built-in libraries are now available as predefined variables." + } + ] + }, + "desc": "

      Evaluate the following argument as JavaScript. The modules which are\npredefined in the REPL can also be used in script.

      \n

      On Windows, using cmd.exe a single quote will not work correctly because it\nonly recognizes double \" for quoting. In Powershell or Git bash, both '\nand \" are usable.

      ", + "type": "module", + "displayName": "`-e`, `--eval \"script\"`" + }, + { + "textRaw": "`-h`, `--help`", + "name": "`-h`,_`--help`", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      Print node command line options.\nThe output of this option is less detailed than this document.

      ", + "type": "module", + "displayName": "`-h`, `--help`" + }, + { + "textRaw": "`-i`, `--interactive`", + "name": "`-i`,_`--interactive`", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      Opens the REPL even if stdin does not appear to be a terminal.

      ", + "type": "module", + "displayName": "`-i`, `--interactive`" + }, + { + "textRaw": "`-p`, `--print \"script\"`", + "name": "`-p`,_`--print_\"script\"`", + "meta": { + "added": [ + "v0.6.4" + ], + "changes": [ + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Built-in libraries are now available as predefined variables." + } + ] + }, + "desc": "

      Identical to -e but prints the result.

      ", + "type": "module", + "displayName": "`-p`, `--print \"script\"`" + }, + { + "textRaw": "`-r`, `--require module`", + "name": "`-r`,_`--require_module`", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "desc": "

      Preload the specified module at startup.

      \n

      Follows require()'s module resolution\nrules. module may be either a path to a file, or a node module name.

      ", + "type": "module", + "displayName": "`-r`, `--require module`" + }, + { + "textRaw": "`-v`, `--version`", + "name": "`-v`,_`--version`", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      Print node's version.

      ", + "type": "module", + "displayName": "`-v`, `--version`" + } + ], + "type": "misc", + "displayName": "Options" + }, + { + "textRaw": "Environment variables", + "name": "environment_variables", + "modules": [ + { + "textRaw": "`NODE_DEBUG=module[,…]`", + "name": "`node_debug=module[,…]`", + "meta": { + "added": [ + "v0.1.32" + ], + "changes": [] + }, + "desc": "

      ','-separated list of core modules that should print debug information.

      ", + "type": "module", + "displayName": "`NODE_DEBUG=module[,…]`" + }, + { + "textRaw": "`NODE_DEBUG_NATIVE=module[,…]`", + "name": "`node_debug_native=module[,…]`", + "desc": "

      ','-separated list of core C++ modules that should print debug information.

      ", + "type": "module", + "displayName": "`NODE_DEBUG_NATIVE=module[,…]`" + }, + { + "textRaw": "`NODE_DISABLE_COLORS=1`", + "name": "`node_disable_colors=1`", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      When set, colors will not be used in the REPL.

      ", + "type": "module", + "displayName": "`NODE_DISABLE_COLORS=1`" + }, + { + "textRaw": "`NODE_EXTRA_CA_CERTS=file`", + "name": "`node_extra_ca_certs=file`", + "meta": { + "added": [ + "v7.3.0" + ], + "changes": [] + }, + "desc": "

      When set, the well known \"root\" CAs (like VeriSign) will be extended with the\nextra certificates in file. The file should consist of one or more trusted\ncertificates in PEM format. A message will be emitted (once) with\nprocess.emitWarning() if the file is missing or\nmalformed, but any errors are otherwise ignored.

      \n

      Neither the well known nor extra certificates are used when the ca\noptions property is explicitly specified for a TLS or HTTPS client or server.

      \n

      This environment variable is ignored when node runs as setuid root or\nhas Linux file capabilities set.

      ", + "type": "module", + "displayName": "`NODE_EXTRA_CA_CERTS=file`" + }, + { + "textRaw": "`NODE_ICU_DATA=file`", + "name": "`node_icu_data=file`", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      Data path for ICU (Intl object) data. Will extend linked-in data when compiled\nwith small-icu support.

      ", + "type": "module", + "displayName": "`NODE_ICU_DATA=file`" + }, + { + "textRaw": "`NODE_NO_WARNINGS=1`", + "name": "`node_no_warnings=1`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      When set to 1, process warnings are silenced.

      ", + "type": "module", + "displayName": "`NODE_NO_WARNINGS=1`" + }, + { + "textRaw": "`NODE_OPTIONS=options...`", + "name": "`node_options=options...`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      A space-separated list of command line options. options... are interpreted\nbefore command line options, so command line options will override or\ncompound after anything in options.... Node.js will exit with an error if\nan option that is not allowed in the environment is used, such as -p or a\nscript file.

      \n

      In case an option value happens to contain a space (for example a path listed\nin --require), it must be escaped using double quotes. For example:

      \n
      NODE_OPTIONS='--require \"./my path/file.js\"'\n
      \n

      A singleton flag passed as a command line option will override the same flag\npassed into NODE_OPTIONS:

      \n
      # The inspector will be available on port 5555\nNODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555\n
      \n

      A flag that can be passed multiple times will be treated as if its\nNODE_OPTIONS instances were passed first, and then its command line\ninstances afterwards:

      \n
      NODE_OPTIONS='--require \"./a.js\"' node --require \"./b.js\"\n# is equivalent to:\nnode --require \"./a.js\" --require \"./b.js\"\n
      \n

      Node.js options that are allowed are:

      \n\n
        \n
      • --conditions
      • \n
      • --diagnostic-dir
      • \n
      • --disable-proto
      • \n
      • --enable-fips
      • \n
      • --enable-source-maps
      • \n
      • --experimental-import-meta-resolve
      • \n
      • --experimental-json-modules
      • \n
      • --experimental-loader
      • \n
      • --experimental-modules
      • \n
      • --experimental-policy
      • \n
      • --experimental-repl-await
      • \n
      • --experimental-specifier-resolution
      • \n
      • --experimental-vm-modules
      • \n
      • --experimental-wasi-unstable-preview1
      • \n
      • --experimental-wasm-modules
      • \n
      • --force-context-aware
      • \n
      • --force-fips
      • \n
      • --frozen-intrinsics
      • \n
      • --heapsnapshot-signal
      • \n
      • --http-parser
      • \n
      • --http-server-default-timeout
      • \n
      • --icu-data-dir
      • \n
      • --input-type
      • \n
      • --insecure-http-parser
      • \n
      • --inspect-brk
      • \n
      • --inspect-port, --debug-port
      • \n
      • --inspect-publish-uid
      • \n
      • --inspect
      • \n
      • --max-http-header-size
      • \n
      • --napi-modules
      • \n
      • --no-deprecation
      • \n
      • --no-force-async-hooks-checks
      • \n
      • --no-warnings
      • \n
      • --openssl-config
      • \n
      • --pending-deprecation
      • \n
      • --policy-integrity
      • \n
      • --preserve-symlinks-main
      • \n
      • --preserve-symlinks
      • \n
      • --prof-process
      • \n
      • --redirect-warnings
      • \n
      • --report-compact
      • \n
      • --report-dir, --report-directory
      • \n
      • --report-filename
      • \n
      • --report-on-fatalerror
      • \n
      • --report-on-signal
      • \n
      • --report-signal
      • \n
      • --report-uncaught-exception
      • \n
      • --require, -r
      • \n
      • --throw-deprecation
      • \n
      • --title
      • \n
      • --tls-cipher-list
      • \n
      • --tls-keylog
      • \n
      • --tls-max-v1.2
      • \n
      • --tls-max-v1.3
      • \n
      • --tls-min-v1.0
      • \n
      • --tls-min-v1.1
      • \n
      • --tls-min-v1.2
      • \n
      • --tls-min-v1.3
      • \n
      • --trace-deprecation
      • \n
      • --trace-event-categories
      • \n
      • --trace-event-file-pattern
      • \n
      • --trace-events-enabled
      • \n
      • --trace-exit
      • \n
      • --trace-sigint
      • \n
      • --trace-sync-io
      • \n
      • --trace-tls
      • \n
      • --trace-uncaught
      • \n
      • --trace-warnings
      • \n
      • --track-heap-objects
      • \n
      • --unhandled-rejections
      • \n
      • --use-bundled-ca
      • \n
      • --use-largepages
      • \n
      • --use-openssl-ca
      • \n
      • --v8-pool-size
      • \n
      • --zero-fill-buffers\n\n
      • \n
      \n

      V8 options that are allowed are:

      \n\n
        \n
      • --abort-on-uncaught-exception
      • \n
      • --disallow-code-generation-from-strings
      • \n
      • --huge-max-old-generation-size
      • \n
      • --interpreted-frames-native-stack
      • \n
      • --jitless
      • \n
      • --max-old-space-size
      • \n
      • --perf-basic-prof-only-functions
      • \n
      • --perf-basic-prof
      • \n
      • --perf-prof-unwinding-info
      • \n
      • --perf-prof
      • \n
      • --stack-trace-limit\n\n
      • \n
      \n

      --perf-basic-prof-only-functions, --perf-basic-prof,\n--perf-prof-unwinding-info, and --perf-prof are only available on Linux.

      ", + "type": "module", + "displayName": "`NODE_OPTIONS=options...`" + }, + { + "textRaw": "`NODE_PATH=path[:…]`", + "name": "`node_path=path[:…]`", + "meta": { + "added": [ + "v0.1.32" + ], + "changes": [] + }, + "desc": "

      ':'-separated list of directories prefixed to the module search path.

      \n

      On Windows, this is a ';'-separated list instead.

      ", + "type": "module", + "displayName": "`NODE_PATH=path[:…]`" + }, + { + "textRaw": "`NODE_PENDING_DEPRECATION=1`", + "name": "`node_pending_deprecation=1`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      When set to 1, emit pending deprecation warnings.

      \n

      Pending deprecations are generally identical to a runtime deprecation with the\nnotable exception that they are turned off by default and will not be emitted\nunless either the --pending-deprecation command line flag, or the\nNODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations\nare used to provide a kind of selective \"early warning\" mechanism that\ndevelopers may leverage to detect deprecated API usage.

      ", + "type": "module", + "displayName": "`NODE_PENDING_DEPRECATION=1`" + }, + { + "textRaw": "`NODE_PENDING_PIPE_INSTANCES=instances`", + "name": "`node_pending_pipe_instances=instances`", + "desc": "

      Set the number of pending pipe instance handles when the pipe server is waiting\nfor connections. This setting applies to Windows only.

      ", + "type": "module", + "displayName": "`NODE_PENDING_PIPE_INSTANCES=instances`" + }, + { + "textRaw": "`NODE_PRESERVE_SYMLINKS=1`", + "name": "`node_preserve_symlinks=1`", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [] + }, + "desc": "

      When set to 1, instructs the module loader to preserve symbolic links when\nresolving and caching modules.

      ", + "type": "module", + "displayName": "`NODE_PRESERVE_SYMLINKS=1`" + }, + { + "textRaw": "`NODE_REDIRECT_WARNINGS=file`", + "name": "`node_redirect_warnings=file`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      When set, process warnings will be emitted to the given file instead of\nprinting to stderr. The file will be created if it does not exist, and will be\nappended to if it does. If an error occurs while attempting to write the\nwarning to the file, the warning will be written to stderr instead. This is\nequivalent to using the --redirect-warnings=file command-line flag.

      ", + "type": "module", + "displayName": "`NODE_REDIRECT_WARNINGS=file`" + }, + { + "textRaw": "`NODE_REPL_HISTORY=file`", + "name": "`node_repl_history=file`", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "desc": "

      Path to the file used to store the persistent REPL history. The default path is\n~/.node_repl_history, which is overridden by this variable. Setting the value\nto an empty string ('' or ' ') disables persistent REPL history.

      ", + "type": "module", + "displayName": "`NODE_REPL_HISTORY=file`" + }, + { + "textRaw": "`NODE_REPL_EXTERNAL_MODULE=file`", + "name": "`node_repl_external_module=file`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Path to a Node.js module which will be loaded in place of the built-in REPL.\nOverriding this value to an empty string ('') will use the built-in REPL.

      ", + "type": "module", + "displayName": "`NODE_REPL_EXTERNAL_MODULE=file`" + }, + { + "textRaw": "`NODE_TLS_REJECT_UNAUTHORIZED=value`", + "name": "`node_tls_reject_unauthorized=value`", + "desc": "

      If value equals '0', certificate validation is disabled for TLS connections.\nThis makes TLS, and HTTPS by extension, insecure. The use of this environment\nvariable is strongly discouraged.

      ", + "type": "module", + "displayName": "`NODE_TLS_REJECT_UNAUTHORIZED=value`" + }, + { + "textRaw": "`NODE_V8_COVERAGE=dir`", + "name": "`node_v8_coverage=dir`", + "desc": "

      When set, Node.js will begin outputting V8 JavaScript code coverage and\nSource Map data to the directory provided as an argument (coverage\ninformation is written as JSON to files with a coverage prefix).

      \n

      NODE_V8_COVERAGE will automatically propagate to subprocesses, making it\neasier to instrument applications that call the child_process.spawn() family\nof functions. NODE_V8_COVERAGE can be set to an empty string, to prevent\npropagation.

      ", + "modules": [ + { + "textRaw": "Coverage output", + "name": "coverage_output", + "desc": "

      Coverage is output as an array of ScriptCoverage objects on the top-level\nkey result:

      \n
      {\n  \"result\": [\n    {\n      \"scriptId\": \"67\",\n      \"url\": \"internal/tty.js\",\n      \"functions\": []\n    }\n  ]\n}\n
      ", + "type": "module", + "displayName": "Coverage output" + }, + { + "textRaw": "Source map cache", + "name": "source_map_cache", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      If found, source map data is appended to the top-level key source-map-cache\non the JSON coverage object.

      \n

      source-map-cache is an object with keys representing the files source maps\nwere extracted from, and values which include the raw source-map URL\n(in the key url), the parsed Source Map v3 information (in the key data),\nand the line lengths of the source file (in the key lineLengths).

      \n
      {\n  \"result\": [\n    {\n      \"scriptId\": \"68\",\n      \"url\": \"file:///absolute/path/to/source.js\",\n      \"functions\": []\n    }\n  ],\n  \"source-map-cache\": {\n    \"file:///absolute/path/to/source.js\": {\n      \"url\": \"./path-to-map.json\",\n      \"data\": {\n        \"version\": 3,\n        \"sources\": [\n          \"file:///absolute/path/to/original.js\"\n        ],\n        \"names\": [\n          \"Foo\",\n          \"console\",\n          \"info\"\n        ],\n        \"mappings\": \"MAAMA,IACJC,YAAaC\",\n        \"sourceRoot\": \"./\"\n      },\n      \"lineLengths\": [\n        13,\n        62,\n        38,\n        27\n      ]\n    }\n  }\n}\n
      ", + "type": "module", + "displayName": "Source map cache" + } + ], + "type": "module", + "displayName": "`NODE_V8_COVERAGE=dir`" + }, + { + "textRaw": "`OPENSSL_CONF=file`", + "name": "`openssl_conf=file`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built with ./configure --openssl-fips.

      \n

      If the --openssl-config command line option is used, the environment\nvariable is ignored.

      ", + "type": "module", + "displayName": "`OPENSSL_CONF=file`" + }, + { + "textRaw": "`SSL_CERT_DIR=dir`", + "name": "`ssl_cert_dir=dir`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory\ncontaining trusted certificates.

      \n

      Be aware that unless the child environment is explicitly set, this environment\nvariable will be inherited by any child processes, and if they use OpenSSL, it\nmay cause them to trust the same CAs as node.

      ", + "type": "module", + "displayName": "`SSL_CERT_DIR=dir`" + }, + { + "textRaw": "`SSL_CERT_FILE=file`", + "name": "`ssl_cert_file=file`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file\ncontaining trusted certificates.

      \n

      Be aware that unless the child environment is explicitly set, this environment\nvariable will be inherited by any child processes, and if they use OpenSSL, it\nmay cause them to trust the same CAs as node.

      ", + "type": "module", + "displayName": "`SSL_CERT_FILE=file`" + }, + { + "textRaw": "`UV_THREADPOOL_SIZE=size`", + "name": "`uv_threadpool_size=size`", + "desc": "

      Set the number of threads used in libuv's threadpool to size threads.

      \n

      Asynchronous system APIs are used by Node.js whenever possible, but where they\ndo not exist, libuv's threadpool is used to create asynchronous node APIs based\non synchronous system APIs. Node.js APIs that use the threadpool are:

      \n
        \n
      • all fs APIs, other than the file watcher APIs and those that are explicitly\nsynchronous
      • \n
      • asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(),\ncrypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
      • \n
      • dns.lookup()
      • \n
      • all zlib APIs, other than those that are explicitly synchronous
      • \n
      \n

      Because libuv's threadpool has a fixed size, it means that if for whatever\nreason any of these APIs takes a long time, other (seemingly unrelated) APIs\nthat run in libuv's threadpool will experience degraded performance. In order to\nmitigate this issue, one potential solution is to increase the size of libuv's\nthreadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value\ngreater than 4 (its current default value). For more information, see the\nlibuv threadpool documentation.

      ", + "type": "module", + "displayName": "`UV_THREADPOOL_SIZE=size`" + } + ], + "type": "misc", + "displayName": "Environment variables" + }, + { + "textRaw": "Useful V8 options", + "name": "useful_v8_options", + "desc": "

      V8 has its own set of CLI options. Any V8 CLI option that is provided to node\nwill be passed on to V8 to handle. V8's options have no stability guarantee.\nThe V8 team themselves don't consider them to be part of their formal API,\nand reserve the right to change them at any time. Likewise, they are not\ncovered by the Node.js stability guarantees. Many of the V8\noptions are of interest only to V8 developers. Despite this, there is a small\nset of V8 options that are widely applicable to Node.js, and they are\ndocumented here:

      ", + "modules": [ + { + "textRaw": "`--max-old-space-size=SIZE` (in megabytes)", + "name": "`--max-old-space-size=size`_(in_megabytes)", + "desc": "

      Sets the max memory size of V8's old memory section. As memory\nconsumption approaches the limit, V8 will spend more time on\ngarbage collection in an effort to free unused memory.

      \n

      On a machine with 2GB of memory, consider setting this to\n1536 (1.5GB) to leave some memory for other uses and avoid swapping.

      \n
      $ node --max-old-space-size=1536 index.js\n
      ", + "type": "module", + "displayName": "`--max-old-space-size=SIZE` (in megabytes)" + } + ], + "type": "misc", + "displayName": "Useful V8 options" + } + ] + }, + { + "textRaw": "Debugger", + "name": "Debugger", + "introduced_in": "v0.9.12", + "stability": 2, + "stabilityText": "Stable", + "type": "misc", + "desc": "

      Node.js includes an out-of-process debugging utility accessible via a\nV8 Inspector and built-in debugging client. To use it, start Node.js\nwith the inspect argument followed by the path to the script to debug; a\nprompt will be displayed indicating successful launch of the debugger:

      \n
      $ node inspect myscript.js\n< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba\n< For help, see: https://nodejs.org/en/docs/inspector\n< Debugger attached.\nBreak on start in myscript.js:1\n> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;\n  2 setTimeout(() => {\n  3   console.log('world');\ndebug>\n
      \n

      The Node.js debugger client is not a full-featured debugger, but simple step and\ninspection are possible.

      \n

      Inserting the statement debugger; into the source code of a script will\nenable a breakpoint at that position in the code:

      \n\n
      // myscript.js\nglobal.x = 5;\nsetTimeout(() => {\n  debugger;\n  console.log('world');\n}, 1000);\nconsole.log('hello');\n
      \n

      Once the debugger is run, a breakpoint will occur at line 3:

      \n
      $ node inspect myscript.js\n< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba\n< For help, see: https://nodejs.org/en/docs/inspector\n< Debugger attached.\nBreak on start in myscript.js:1\n> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;\n  2 setTimeout(() => {\n  3   debugger;\ndebug> cont\n< hello\nbreak in myscript.js:3\n  1 (function (exports, require, module, __filename, __dirname) { global.x = 5;\n  2 setTimeout(() => {\n> 3   debugger;\n  4   console.log('world');\n  5 }, 1000);\ndebug> next\nbreak in myscript.js:4\n  2 setTimeout(() => {\n  3   debugger;\n> 4   console.log('world');\n  5 }, 1000);\n  6 console.log('hello');\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2 + 2\n4\ndebug> next\n< world\nbreak in myscript.js:5\n  3   debugger;\n  4   console.log('world');\n> 5 }, 1000);\n  6 console.log('hello');\n  7\ndebug> .exit\n
      \n

      The repl command allows code to be evaluated remotely. The next command\nsteps to the next line. Type help to see what other commands are available.

      \n

      Pressing enter without typing a command will repeat the previous debugger\ncommand.

      ", + "miscs": [ + { + "textRaw": "Watchers", + "name": "watchers", + "desc": "

      It is possible to watch expression and variable values while debugging. On\nevery breakpoint, each expression from the watchers list will be evaluated\nin the current context and displayed immediately before the breakpoint's\nsource code listing.

      \n

      To begin watching an expression, type watch('my_expression'). The command\nwatchers will print the active watchers. To remove a watcher, type\nunwatch('my_expression').

      ", + "type": "misc", + "displayName": "Watchers" + }, + { + "textRaw": "Command reference", + "name": "command_reference", + "modules": [ + { + "textRaw": "Stepping", + "name": "stepping", + "desc": "
        \n
      • cont, c: Continue execution
      • \n
      • next, n: Step next
      • \n
      • step, s: Step in
      • \n
      • out, o: Step out
      • \n
      • pause: Pause running code (like pause button in Developer Tools)
      • \n
      ", + "type": "module", + "displayName": "Stepping" + }, + { + "textRaw": "Breakpoints", + "name": "breakpoints", + "desc": "
        \n
      • setBreakpoint(), sb(): Set breakpoint on current line
      • \n
      • setBreakpoint(line), sb(line): Set breakpoint on specific line
      • \n
      • setBreakpoint('fn()'), sb(...): Set breakpoint on a first statement in\nfunctions body
      • \n
      • setBreakpoint('script.js', 1), sb(...): Set breakpoint on first line of\nscript.js
      • \n
      • clearBreakpoint('script.js', 1), cb(...): Clear breakpoint in script.js\non line 1
      • \n
      \n

      It is also possible to set a breakpoint in a file (module) that\nis not loaded yet:

      \n
      $ node inspect main.js\n< Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd\n< For help, see: https://nodejs.org/en/docs/inspector\n< Debugger attached.\nBreak on start in main.js:1\n> 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 22)\nWarning: script 'mod.js' was not loaded yet.\ndebug> c\nbreak in mod.js:22\n 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.\n 21\n>22 exports.hello = function() {\n 23   return 'hello from module';\n 24 };\ndebug>\n
      ", + "type": "module", + "displayName": "Breakpoints" + }, + { + "textRaw": "Information", + "name": "information", + "desc": "
        \n
      • backtrace, bt: Print backtrace of current execution frame
      • \n
      • list(5): List scripts source code with 5 line context (5 lines before and\nafter)
      • \n
      • watch(expr): Add expression to watch list
      • \n
      • unwatch(expr): Remove expression from watch list
      • \n
      • watchers: List all watchers and their values (automatically listed on each\nbreakpoint)
      • \n
      • repl: Open debugger's repl for evaluation in debugging script's context
      • \n
      • exec expr: Execute an expression in debugging script's context
      • \n
      ", + "type": "module", + "displayName": "Information" + }, + { + "textRaw": "Execution control", + "name": "execution_control", + "desc": "
        \n
      • run: Run script (automatically runs on debugger's start)
      • \n
      • restart: Restart script
      • \n
      • kill: Kill script
      • \n
      ", + "type": "module", + "displayName": "Execution control" + }, + { + "textRaw": "Various", + "name": "various", + "desc": "
        \n
      • scripts: List all loaded scripts
      • \n
      • version: Display V8's version
      • \n
      ", + "type": "module", + "displayName": "Various" + } + ], + "type": "misc", + "displayName": "Command reference" + }, + { + "textRaw": "Advanced usage", + "name": "advanced_usage", + "modules": [ + { + "textRaw": "V8 inspector integration for Node.js", + "name": "v8_inspector_integration_for_node.js", + "desc": "

      V8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling. It uses the\nChrome DevTools Protocol.

      \n

      V8 Inspector can be enabled by passing the --inspect flag when starting a\nNode.js application. It is also possible to supply a custom port with that flag,\ne.g. --inspect=9222 will accept DevTools connections on port 9222.

      \n

      To break on the first line of the application code, pass the --inspect-brk\nflag instead of --inspect.

      \n
      $ node --inspect index.js\nDebugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29\nFor help, see: https://nodejs.org/en/docs/inspector\n
      \n

      (In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29\nat the end of the URL is generated on the fly, it varies in different\ndebugging sessions.)

      \n

      If the Chrome browser is older than 66.0.3345.0,\nuse inspector.html instead of js_app.html in the above URL.

      \n

      Chrome DevTools doesn't support debugging worker threads yet.\nndb can be used to debug them.

      ", + "type": "module", + "displayName": "V8 inspector integration for Node.js" + } + ], + "type": "misc", + "displayName": "Advanced usage" + } + ] + }, + { + "textRaw": "Deprecated APIs", + "name": "Deprecated APIs", + "introduced_in": "v7.7.0", + "type": "misc", + "desc": "

      Node.js may deprecate APIs for any of the following reasons:

      \n
        \n
      • Use of the API is unsafe.
      • \n
      • An improved alternative API is available.
      • \n
      • Breaking changes to the API are expected in a future major release.
      • \n
      \n

      Node.js utilizes three kinds of Deprecations:

      \n
        \n
      • Documentation-only
      • \n
      • Runtime
      • \n
      • End-of-Life
      • \n
      \n

      A Documentation-only deprecation is one that is expressed only within the\nNode.js API docs. These generate no side-effects while running Node.js.\nSome Documentation-only deprecations trigger a runtime warning when launched\nwith --pending-deprecation flag (or its alternative,\nNODE_PENDING_DEPRECATION=1 environment variable), similarly to Runtime\ndeprecations below. Documentation-only deprecations that support that flag\nare explicitly labeled as such in the\nlist of Deprecated APIs.

      \n

      A Runtime deprecation will, by default, generate a process warning that will\nbe printed to stderr the first time the deprecated API is used. When the\n--throw-deprecation command-line flag is used, a Runtime deprecation will\ncause an error to be thrown.

      \n

      An End-of-Life deprecation is used when functionality is or will soon be removed\nfrom Node.js.

      ", + "miscs": [ + { + "textRaw": "Revoking deprecations", + "name": "revoking_deprecations", + "desc": "

      Occasionally, the deprecation of an API may be reversed. In such situations,\nthis document will be updated with information relevant to the decision.\nHowever, the deprecation identifier will not be modified.

      ", + "type": "misc", + "displayName": "Revoking deprecations" + }, + { + "textRaw": "List of deprecated APIs", + "name": "list_of_deprecated_apis", + "desc": "

      ", + "modules": [ + { + "textRaw": "DEP0001: `http.OutgoingMessage.prototype.flush`", + "name": "dep0001:_`http.outgoingmessage.prototype.flush`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.6.0", + "pr-url": "https://github.com/nodejs/node/pull/1156", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The OutgoingMessage.prototype.flush() method is deprecated. Use\nOutgoingMessage.prototype.flushHeaders() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0001: `http.OutgoingMessage.prototype.flush`" + }, + { + "textRaw": "DEP0002: `require('_linklist')`", + "name": "dep0002:_`require('_linklist')`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12113", + "description": "End-of-Life." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3078", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The _linklist module is deprecated. Please use a userland alternative.

      \n

      ", + "type": "module", + "displayName": "DEP0002: `require('_linklist')`" + }, + { + "textRaw": "DEP0003: `_writableState.buffer`", + "name": "dep0003:_`_writablestate.buffer`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.15", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/8826", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The _writableState.buffer property is deprecated. Use the\n_writableState.getBuffer() method instead.

      \n

      ", + "type": "module", + "displayName": "DEP0003: `_writableState.buffer`" + }, + { + "textRaw": "DEP0004: `CryptoStream.prototype.readyState`", + "name": "dep0004:_`cryptostream.prototype.readystate`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17882", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "0.4.0", + "commit": "9c7f89bf56abd37a796fea621ad2e47dd33d2b82", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The CryptoStream.prototype.readyState property was removed.

      \n

      ", + "type": "module", + "displayName": "DEP0004: `CryptoStream.prototype.readyState`" + }, + { + "textRaw": "DEP0005: `Buffer()` constructor", + "name": "dep0005:_`buffer()`_constructor", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19524", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4682", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime (supports --pending-deprecation)

      \n

      The Buffer() function and new Buffer() constructor are deprecated due to\nAPI usability issues that can lead to accidental security issues.

      \n

      As an alternative, use one of the following methods of constructing Buffer\nobjects:

      \n\n

      Without --pending-deprecation, runtime warnings occur only for code not in\nnode_modules. This means there will not be deprecation warnings for\nBuffer() usage in dependencies. With --pending-deprecation, a runtime\nwarning results no matter where the Buffer() usage occurs.

      \n

      ", + "type": "module", + "displayName": "DEP0005: `Buffer()` constructor" + }, + { + "textRaw": "DEP0006: `child_process` `options.customFds`", + "name": "dep0006:_`child_process`_`options.customfds`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25279", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.14", + "description": "Runtime deprecation." + }, + { + "version": "v0.5.11", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Within the child_process module's spawn(), fork(), and exec()\nmethods, the options.customFds option is deprecated. The options.stdio\noption should be used instead.

      \n

      ", + "type": "module", + "displayName": "DEP0006: `child_process` `options.customFds`" + }, + { + "textRaw": "DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`", + "name": "dep0007:_replace_`cluster`_`worker.suicide`_with_`worker.exitedafterdisconnect`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13702", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3747", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3743", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      In an earlier version of the Node.js cluster, a boolean property with the name\nsuicide was added to the Worker object. The intent of this property was to\nprovide an indication of how and why the Worker instance exited. In Node.js\n6.0.0, the old property was deprecated and replaced with a new\nworker.exitedAfterDisconnect property. The old property name did not\nprecisely describe the actual semantics and was unnecessarily emotion-laden.

      \n

      ", + "type": "module", + "displayName": "DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`" + }, + { + "textRaw": "DEP0008: `require('constants')`", + "name": "dep0008:_`require('constants')`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6534", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The constants module is deprecated. When requiring access to constants\nrelevant to specific Node.js builtin modules, developers should instead refer\nto the constants property exposed by the relevant module. For instance,\nrequire('fs').constants and require('os').constants.

      \n

      ", + "type": "module", + "displayName": "DEP0008: `require('constants')`" + }, + { + "textRaw": "DEP0009: `crypto.pbkdf2` without digest", + "name": "dep0009:_`crypto.pbkdf2`_without_digest", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22861", + "description": "Runtime deprecation (for `digest === null`)." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11305", + "description": "End-of-Life (for `digest === undefined`)." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4047", + "description": "Runtime deprecation (for `digest === undefined`)." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Use of the crypto.pbkdf2() API without specifying a digest was deprecated\nin Node.js 6.0 because the method defaulted to using the non-recommended\n'SHA1' digest. Previously, a deprecation warning was printed. Starting in\nNode.js 8.0.0, calling crypto.pbkdf2() or crypto.pbkdf2Sync() with\ndigest set to undefined will throw a TypeError.

      \n

      Beginning in Node.js v11.0.0, calling these functions with digest set to\nnull will print a deprecation warning to align with the behavior when digest\nis undefined.

      \n

      ", + "type": "module", + "displayName": "DEP0009: `crypto.pbkdf2` without digest" + }, + { + "textRaw": "DEP0010: `crypto.createCredentials`", + "name": "dep0010:_`crypto.createcredentials`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/21153", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.13", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7265", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The crypto.createCredentials() API was removed. Please use\ntls.createSecureContext() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0010: `crypto.createCredentials`" + }, + { + "textRaw": "DEP0011: `crypto.Credentials`", + "name": "dep0011:_`crypto.credentials`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/21153", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.13", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7265", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The crypto.Credentials class was removed. Please use tls.SecureContext\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0011: `crypto.Credentials`" + }, + { + "textRaw": "DEP0012: `Domain.dispose`", + "name": "dep0012:_`domain.dispose`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15412", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.7", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/5021", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Domain.dispose() has been removed. Recover from failed I/O actions\nexplicitly via error event handlers set on the domain instead.

      \n

      ", + "type": "module", + "displayName": "DEP0012: `Domain.dispose`" + }, + { + "textRaw": "DEP0013: `fs` asynchronous function without callback", + "name": "dep0013:_`fs`_asynchronous_function_without_callback", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18668", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Calling an asynchronous function without a callback throws a TypeError\nin Node.js 10.0.0 onwards. See https://github.com/nodejs/node/pull/12562.

      \n

      ", + "type": "module", + "displayName": "DEP0013: `fs` asynchronous function without callback" + }, + { + "textRaw": "DEP0014: `fs.read` legacy String interface", + "name": "dep0014:_`fs.read`_legacy_string_interface", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9683", + "description": "End-of-Life." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4525", + "description": "Runtime deprecation." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.1.96", + "commit": "c93e0aaf062081db3ec40ac45b3e2c979d5759d6", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The fs.read() legacy String interface is deprecated. Use the Buffer\nAPI as mentioned in the documentation instead.

      \n

      ", + "type": "module", + "displayName": "DEP0014: `fs.read` legacy String interface" + }, + { + "textRaw": "DEP0015: `fs.readSync` legacy String interface", + "name": "dep0015:_`fs.readsync`_legacy_string_interface", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9683", + "description": "End-of-Life." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4525", + "description": "Runtime deprecation." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.1.96", + "commit": "c93e0aaf062081db3ec40ac45b3e2c979d5759d6", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The fs.readSync() legacy String interface is deprecated. Use the\nBuffer API as mentioned in the documentation instead.

      \n

      ", + "type": "module", + "displayName": "DEP0015: `fs.readSync` legacy String interface" + }, + { + "textRaw": "DEP0016: `GLOBAL`/`root`", + "name": "dep0016:_`global`/`root`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/1838", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The GLOBAL and root aliases for the global property are deprecated\nand should no longer be used.

      \n

      ", + "type": "module", + "displayName": "DEP0016: `GLOBAL`/`root`" + }, + { + "textRaw": "DEP0017: `Intl.v8BreakIterator`", + "name": "dep0017:_`intl.v8breakiterator`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15238", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8908", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Intl.v8BreakIterator was a non-standard extension and has been removed.\nSee Intl.Segmenter.

      \n

      ", + "type": "module", + "displayName": "DEP0017: `Intl.v8BreakIterator`" + }, + { + "textRaw": "DEP0018: Unhandled promise rejections", + "name": "dep0018:_unhandled_promise_rejections", + "meta": { + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8217", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Unhandled promise rejections are deprecated. In the future, promise rejections\nthat are not handled will terminate the Node.js process with a non-zero exit\ncode.

      \n

      ", + "type": "module", + "displayName": "DEP0018: Unhandled promise rejections" + }, + { + "textRaw": "DEP0019: `require('.')` resolved outside directory", + "name": "dep0019:_`require('.')`_resolved_outside_directory", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26973", + "description": "Removed functionality." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.8.1", + "pr-url": "https://github.com/nodejs/node/pull/1363", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      In certain cases, require('.') could resolve outside the package directory.\nThis behavior has been removed.

      \n

      ", + "type": "module", + "displayName": "DEP0019: `require('.')` resolved outside directory" + }, + { + "textRaw": "DEP0020: `Server.connections`", + "name": "dep0020:_`server.connections`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.9.7", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/4595", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The Server.connections property is deprecated. Please use the\nServer.getConnections() method instead.

      \n

      ", + "type": "module", + "displayName": "DEP0020: `Server.connections`" + }, + { + "textRaw": "DEP0021: `Server.listenFD`", + "name": "dep0021:_`server.listenfd`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27127", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.7.12", + "commit": "41421ff9da1288aa241a5e9dcf915b685ade1c23", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The Server.listenFD() method was deprecated and removed. Please use\nServer.listen({fd: <number>}) instead.

      \n

      ", + "type": "module", + "displayName": "DEP0021: `Server.listenFD`" + }, + { + "textRaw": "DEP0022: `os.tmpDir()`", + "name": "dep0022:_`os.tmpdir()`", + "meta": { + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6739", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The os.tmpDir() API is deprecated. Please use os.tmpdir() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0022: `os.tmpDir()`" + }, + { + "textRaw": "DEP0023: `os.getNetworkInterfaces()`", + "name": "dep0023:_`os.getnetworkinterfaces()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25280", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.6.0", + "commit": "37bb37d151fb6ee4696730e63ff28bb7a4924f97", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The os.getNetworkInterfaces() method is deprecated. Please use the\nos.networkInterfaces() method instead.

      \n

      ", + "type": "module", + "displayName": "DEP0023: `os.getNetworkInterfaces()`" + }, + { + "textRaw": "DEP0024: `REPLServer.prototype.convertToContext()`", + "name": "dep0024:_`replserver.prototype.converttocontext()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13434", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7829", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The REPLServer.prototype.convertToContext() API has been removed.

      \n

      ", + "type": "module", + "displayName": "DEP0024: `REPLServer.prototype.convertToContext()`" + }, + { + "textRaw": "DEP0025: `require('sys')`", + "name": "dep0025:_`require('sys')`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.0.0", + "pr-url": "https://github.com/nodejs/node/pull/317", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The sys module is deprecated. Please use the util module instead.

      \n

      ", + "type": "module", + "displayName": "DEP0025: `require('sys')`" + }, + { + "textRaw": "DEP0026: `util.print()`", + "name": "dep0026:_`util.print()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.print() has been removed. Please use console.log() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0026: `util.print()`" + }, + { + "textRaw": "DEP0027: `util.puts()`", + "name": "dep0027:_`util.puts()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.puts() has been removed. Please use console.log() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0027: `util.puts()`" + }, + { + "textRaw": "DEP0028: `util.debug()`", + "name": "dep0028:_`util.debug()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.debug() has been removed. Please use console.error() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0028: `util.debug()`" + }, + { + "textRaw": "DEP0029: `util.error()`", + "name": "dep0029:_`util.error()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.error() has been removed. Please use console.error() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0029: `util.error()`" + }, + { + "textRaw": "DEP0030: `SlowBuffer`", + "name": "dep0030:_`slowbuffer`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5833", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The SlowBuffer class is deprecated. Please use\nBuffer.allocUnsafeSlow(size) instead.

      \n

      ", + "type": "module", + "displayName": "DEP0030: `SlowBuffer`" + }, + { + "textRaw": "DEP0031: `ecdh.setPublicKey()`", + "name": "dep0031:_`ecdh.setpublickey()`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v5.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3511", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful.

      \n

      ", + "type": "module", + "displayName": "DEP0031: `ecdh.setPublicKey()`" + }, + { + "textRaw": "DEP0032: `domain` module", + "name": "dep0032:_`domain`_module", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.4.2", + "pr-url": "https://github.com/nodejs/node/pull/943", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The domain module is deprecated and should not be used.

      \n

      ", + "type": "module", + "displayName": "DEP0032: `domain` module" + }, + { + "textRaw": "DEP0033: `EventEmitter.listenerCount()`", + "name": "dep0033:_`eventemitter.listenercount()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v3.2.0", + "pr-url": "https://github.com/nodejs/node/pull/2349", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The EventEmitter.listenerCount(emitter, eventName) API is\ndeprecated. Please use emitter.listenerCount(eventName) instead.

      \n

      ", + "type": "module", + "displayName": "DEP0033: `EventEmitter.listenerCount()`" + }, + { + "textRaw": "DEP0034: `fs.exists(path, callback)`", + "name": "dep0034:_`fs.exists(path,_callback)`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.0.0", + "pr-url": "https://github.com/iojs/io.js/pull/166", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The fs.exists(path, callback) API is deprecated. Please use\nfs.stat() or fs.access() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0034: `fs.exists(path, callback)`" + }, + { + "textRaw": "DEP0035: `fs.lchmod(path, mode, callback)`", + "name": "dep0035:_`fs.lchmod(path,_mode,_callback)`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The fs.lchmod(path, mode, callback) API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0035: `fs.lchmod(path, mode, callback)`" + }, + { + "textRaw": "DEP0036: `fs.lchmodSync(path, mode)`", + "name": "dep0036:_`fs.lchmodsync(path,_mode)`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The fs.lchmodSync(path, mode) API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0036: `fs.lchmodSync(path, mode)`" + }, + { + "textRaw": "DEP0037: `fs.lchown(path, uid, gid, callback)`", + "name": "dep0037:_`fs.lchown(path,_uid,_gid,_callback)`", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "Deprecation revoked." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Deprecation revoked

      \n

      The fs.lchown(path, uid, gid, callback) API was deprecated. The\ndeprecation was revoked because the requisite supporting APIs were added in\nlibuv.

      \n

      ", + "type": "module", + "displayName": "DEP0037: `fs.lchown(path, uid, gid, callback)`" + }, + { + "textRaw": "DEP0038: `fs.lchownSync(path, uid, gid)`", + "name": "dep0038:_`fs.lchownsync(path,_uid,_gid)`", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "Deprecation revoked." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Deprecation revoked

      \n

      The fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was\nrevoked because the requisite supporting APIs were added in libuv.

      \n

      ", + "type": "module", + "displayName": "DEP0038: `fs.lchownSync(path, uid, gid)`" + }, + { + "textRaw": "DEP0039: `require.extensions`", + "name": "dep0039:_`require.extensions`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.10.6", + "commit": "7bd8a5a2a60b75266f89f9a32877d55294a3881c", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The require.extensions property is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0039: `require.extensions`" + }, + { + "textRaw": "DEP0040: `punycode` module", + "name": "dep0040:_`punycode`_module", + "meta": { + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7941", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The punycode module is deprecated. Please use a userland alternative\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0040: `punycode` module" + }, + { + "textRaw": "DEP0041: `NODE_REPL_HISTORY_FILE` environment variable", + "name": "dep0041:_`node_repl_history_file`_environment_variable", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13876", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v3.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2224", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The NODE_REPL_HISTORY_FILE environment variable was removed. Please use\nNODE_REPL_HISTORY instead.

      \n

      ", + "type": "module", + "displayName": "DEP0041: `NODE_REPL_HISTORY_FILE` environment variable" + }, + { + "textRaw": "DEP0042: `tls.CryptoStream`", + "name": "dep0042:_`tls.cryptostream`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17882", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The tls.CryptoStream class was removed. Please use\ntls.TLSSocket instead.

      \n

      ", + "type": "module", + "displayName": "DEP0042: `tls.CryptoStream`" + }, + { + "textRaw": "DEP0043: `tls.SecurePair`", + "name": "dep0043:_`tls.securepair`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11349", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6063", + "description": "Documentation-only deprecation." + }, + { + "version": "v0.11.15", + "pr-url": [ + "https://github.com/nodejs/node-v0.x-archive/pull/8695", + "https://github.com/nodejs/node-v0.x-archive/pull/8700" + ], + "description": "Deprecation revoked." + }, + { + "version": "v0.11.3", + "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The tls.SecurePair class is deprecated. Please use\ntls.TLSSocket instead.

      \n

      ", + "type": "module", + "displayName": "DEP0043: `tls.SecurePair`" + }, + { + "textRaw": "DEP0044: `util.isArray()`", + "name": "dep0044:_`util.isarray()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isArray() API is deprecated. Please use Array.isArray()\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0044: `util.isArray()`" + }, + { + "textRaw": "DEP0045: `util.isBoolean()`", + "name": "dep0045:_`util.isboolean()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isBoolean() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0045: `util.isBoolean()`" + }, + { + "textRaw": "DEP0046: `util.isBuffer()`", + "name": "dep0046:_`util.isbuffer()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isBuffer() API is deprecated. Please use\nBuffer.isBuffer() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0046: `util.isBuffer()`" + }, + { + "textRaw": "DEP0047: `util.isDate()`", + "name": "dep0047:_`util.isdate()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isDate() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0047: `util.isDate()`" + }, + { + "textRaw": "DEP0048: `util.isError()`", + "name": "dep0048:_`util.iserror()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isError() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0048: `util.isError()`" + }, + { + "textRaw": "DEP0049: `util.isFunction()`", + "name": "dep0049:_`util.isfunction()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isFunction() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0049: `util.isFunction()`" + }, + { + "textRaw": "DEP0050: `util.isNull()`", + "name": "dep0050:_`util.isnull()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isNull() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0050: `util.isNull()`" + }, + { + "textRaw": "DEP0051: `util.isNullOrUndefined()`", + "name": "dep0051:_`util.isnullorundefined()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isNullOrUndefined() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0051: `util.isNullOrUndefined()`" + }, + { + "textRaw": "DEP0052: `util.isNumber()`", + "name": "dep0052:_`util.isnumber()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isNumber() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0052: `util.isNumber()`" + }, + { + "textRaw": "DEP0053 `util.isObject()`", + "name": "dep0053_`util.isobject()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isObject() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0053 `util.isObject()`" + }, + { + "textRaw": "DEP0054: `util.isPrimitive()`", + "name": "dep0054:_`util.isprimitive()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isPrimitive() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0054: `util.isPrimitive()`" + }, + { + "textRaw": "DEP0055: `util.isRegExp()`", + "name": "dep0055:_`util.isregexp()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isRegExp() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0055: `util.isRegExp()`" + }, + { + "textRaw": "DEP0056: `util.isString()`", + "name": "dep0056:_`util.isstring()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isString() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0056: `util.isString()`" + }, + { + "textRaw": "DEP0057: `util.isSymbol()`", + "name": "dep0057:_`util.issymbol()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isSymbol() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0057: `util.isSymbol()`" + }, + { + "textRaw": "DEP0058: `util.isUndefined()`", + "name": "dep0058:_`util.isundefined()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isUndefined() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0058: `util.isUndefined()`" + }, + { + "textRaw": "DEP0059: `util.log()`", + "name": "dep0059:_`util.log()`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6161", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.log() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0059: `util.log()`" + }, + { + "textRaw": "DEP0060: `util._extend()`", + "name": "dep0060:_`util._extend()`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4903", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util._extend() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0060: `util._extend()`" + }, + { + "textRaw": "DEP0061: `fs.SyncWriteStream`", + "name": "dep0061:_`fs.syncwritestream`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20735", + "description": "End-of-Life." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10467", + "description": "Runtime deprecation." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6749", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The fs.SyncWriteStream class was never intended to be a publicly accessible\nAPI and has been removed. No alternative API is available. Please use a userland\nalternative.

      \n

      ", + "type": "module", + "displayName": "DEP0061: `fs.SyncWriteStream`" + }, + { + "textRaw": "DEP0062: `node --debug`", + "name": "dep0062:_`node_--debug`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10970", + "description": "Runtime deprecation." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25828", + "description": "End-of-Life." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      --debug activates the legacy V8 debugger interface, which was removed as\nof V8 5.8. It is replaced by Inspector which is activated with --inspect\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0062: `node --debug`" + }, + { + "textRaw": "DEP0063: `ServerResponse.prototype.writeHeader()`", + "name": "dep0063:_`serverresponse.prototype.writeheader()`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11355", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The http module ServerResponse.prototype.writeHeader() API is\ndeprecated. Please use ServerResponse.prototype.writeHead() instead.

      \n

      The ServerResponse.prototype.writeHeader() method was never documented as an\nofficially supported API.

      \n

      ", + "type": "module", + "displayName": "DEP0063: `ServerResponse.prototype.writeHeader()`" + }, + { + "textRaw": "DEP0064: `tls.createSecurePair()`", + "name": "dep0064:_`tls.createsecurepair()`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11349", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6063", + "description": "Documentation-only deprecation." + }, + { + "version": "v0.11.15", + "pr-url": [ + "https://github.com/nodejs/node-v0.x-archive/pull/8695", + "https://github.com/nodejs/node-v0.x-archive/pull/8700" + ], + "description": "Deprecation revoked." + }, + { + "version": "v0.11.3", + "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The tls.createSecurePair() API was deprecated in documentation in Node.js\n0.11.3. Users should use tls.Socket instead.

      \n

      ", + "type": "module", + "displayName": "DEP0064: `tls.createSecurePair()`" + }, + { + "textRaw": "DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`", + "name": "dep0065:_`repl.repl_mode_magic`_and_`node_repl_mode=magic`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19187", + "description": "End-of-Life." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11599", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The repl module's REPL_MODE_MAGIC constant, used for replMode option, has\nbeen removed. Its behavior has been functionally identical to that of\nREPL_MODE_SLOPPY since Node.js 6.0.0, when V8 5.0 was imported. Please use\nREPL_MODE_SLOPPY instead.

      \n

      The NODE_REPL_MODE environment variable is used to set the underlying\nreplMode of an interactive node session. Its value, magic, is also\nremoved. Please use sloppy instead.

      \n

      ", + "type": "module", + "displayName": "DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`" + }, + { + "textRaw": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`", + "name": "dep0066:_`outgoingmessage.prototype._headers,_outgoingmessage.prototype._headernames`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24167", + "description": "Runtime deprecation." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10941", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The http module OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties are deprecated. Use one of\nthe public methods (e.g. OutgoingMessage.prototype.getHeader(),\nOutgoingMessage.prototype.getHeaders(),\nOutgoingMessage.prototype.getHeaderNames(),\nOutgoingMessage.prototype.hasHeader(),\nOutgoingMessage.prototype.removeHeader(),\nOutgoingMessage.prototype.setHeader()) for working with outgoing headers.

      \n

      The OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties were never documented as\nofficially supported properties.

      \n

      ", + "type": "module", + "displayName": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`" + }, + { + "textRaw": "DEP0067: `OutgoingMessage.prototype._renderHeaders`", + "name": "dep0067:_`outgoingmessage.prototype._renderheaders`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10941", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The http module OutgoingMessage.prototype._renderHeaders() API is\ndeprecated.

      \n

      The OutgoingMessage.prototype._renderHeaders property was never documented as\nan officially supported API.

      \n

      ", + "type": "module", + "displayName": "DEP0067: `OutgoingMessage.prototype._renderHeaders`" + }, + { + "textRaw": "DEP0068: `node debug`", + "name": "dep0068:_`node_debug`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11441", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      node debug corresponds to the legacy CLI debugger which has been replaced with\na V8-inspector based CLI debugger available through node inspect.

      \n

      ", + "type": "module", + "displayName": "DEP0068: `node debug`" + }, + { + "textRaw": "DEP0069: `vm.runInDebugContext(string)`", + "name": "dep0069:_`vm.runindebugcontext(string)`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13295", + "description": "End-of-Life." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12815", + "description": "Runtime deprecation." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12243", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      DebugContext has been removed in V8 and is not available in Node.js 10+.

      \n

      DebugContext was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0069: `vm.runInDebugContext(string)`" + }, + { + "textRaw": "DEP0070: `async_hooks.currentId()`", + "name": "dep0070:_`async_hooks.currentid()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14414", + "description": "End-of-Life." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      async_hooks.currentId() was renamed to async_hooks.executionAsyncId() for\nclarity.

      \n

      This change was made while async_hooks was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0070: `async_hooks.currentId()`" + }, + { + "textRaw": "DEP0071: `async_hooks.triggerId()`", + "name": "dep0071:_`async_hooks.triggerid()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14414", + "description": "End-of-Life." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      async_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for\nclarity.

      \n

      This change was made while async_hooks was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0071: `async_hooks.triggerId()`" + }, + { + "textRaw": "DEP0072: `async_hooks.AsyncResource.triggerId()`", + "name": "dep0072:_`async_hooks.asyncresource.triggerid()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14414", + "description": "End-of-Life." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      async_hooks.AsyncResource.triggerId() was renamed to\nasync_hooks.AsyncResource.triggerAsyncId() for clarity.

      \n

      This change was made while async_hooks was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0072: `async_hooks.AsyncResource.triggerId()`" + }, + { + "textRaw": "DEP0073: Several internal properties of `net.Server`", + "name": "dep0073:_several_internal_properties_of_`net.server`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17141", + "description": "End-of-Life." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14449", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Accessing several internal, undocumented properties of net.Server instances\nwith inappropriate names is deprecated.

      \n

      As the original API was undocumented and not generally useful for non-internal\ncode, no replacement API is provided.

      \n

      ", + "type": "module", + "displayName": "DEP0073: Several internal properties of `net.Server`" + }, + { + "textRaw": "DEP0074: `REPLServer.bufferedCommand`", + "name": "dep0074:_`replserver.bufferedcommand`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13687", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The REPLServer.bufferedCommand property was deprecated in favor of\nREPLServer.clearBufferedCommand().

      \n

      ", + "type": "module", + "displayName": "DEP0074: `REPLServer.bufferedCommand`" + }, + { + "textRaw": "DEP0075: `REPLServer.parseREPLKeyword()`", + "name": "dep0075:_`replserver.parsereplkeyword()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14223", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      REPLServer.parseREPLKeyword() was removed from userland visibility.

      \n

      ", + "type": "module", + "displayName": "DEP0075: `REPLServer.parseREPLKeyword()`" + }, + { + "textRaw": "DEP0076: `tls.parseCertString()`", + "name": "dep0076:_`tls.parsecertstring()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14249", + "description": "Runtime deprecation." + }, + { + "version": "v8.6.0", + "pr-url": "https://github.com/nodejs/node/pull/14245", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      tls.parseCertString() is a trivial parsing helper that was made public by\nmistake. This function can usually be replaced with:

      \n
      const querystring = require('querystring');\nquerystring.parse(str, '\\n', '=');\n
      \n

      This function is not completely equivalent to querystring.parse(). One\ndifference is that querystring.parse() does url decoding:

      \n
      > querystring.parse('%E5%A5%BD=1', '\\n', '=');\n{ '好': '1' }\n> tls.parseCertString('%E5%A5%BD=1');\n{ '%E5%A5%BD': '1' }\n
      \n

      ", + "type": "module", + "displayName": "DEP0076: `tls.parseCertString()`" + }, + { + "textRaw": "DEP0077: `Module._debug()`", + "name": "dep0077:_`module._debug()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13948", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Module._debug() is deprecated.

      \n

      The Module._debug() function was never documented as an officially\nsupported API.

      \n

      ", + "type": "module", + "displayName": "DEP0077: `Module._debug()`" + }, + { + "textRaw": "DEP0078: `REPLServer.turnOffEditorMode()`", + "name": "dep0078:_`replserver.turnoffeditormode()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15136", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      REPLServer.turnOffEditorMode() was removed from userland visibility.

      \n

      ", + "type": "module", + "displayName": "DEP0078: `REPLServer.turnOffEditorMode()`" + }, + { + "textRaw": "DEP0079: Custom inspection function on objects via `.inspect()`", + "name": "dep0079:_custom_inspection_function_on_objects_via_`.inspect()`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20722", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16393", + "description": "Runtime deprecation." + }, + { + "version": "v8.7.0", + "pr-url": "https://github.com/nodejs/node/pull/15631", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Using a property named inspect on an object to specify a custom inspection\nfunction for util.inspect() is deprecated. Use util.inspect.custom\ninstead. For backward compatibility with Node.js prior to version 6.4.0, both\nmay be specified.

      \n

      ", + "type": "module", + "displayName": "DEP0079: Custom inspection function on objects via `.inspect()`" + }, + { + "textRaw": "DEP0080: `path._makeLong()`", + "name": "dep0080:_`path._makelong()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14956", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The internal path._makeLong() was not intended for public use. However,\nuserland modules have found it useful. The internal API is deprecated\nand replaced with an identical, public path.toNamespacedPath() method.

      \n

      ", + "type": "module", + "displayName": "DEP0080: `path._makeLong()`" + }, + { + "textRaw": "DEP0081: `fs.truncate()` using a file descriptor", + "name": "dep0081:_`fs.truncate()`_using_a_file_descriptor", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15990", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      fs.truncate() fs.truncateSync() usage with a file descriptor is\ndeprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with\nfile descriptors.

      \n

      ", + "type": "module", + "displayName": "DEP0081: `fs.truncate()` using a file descriptor" + }, + { + "textRaw": "DEP0082: `REPLServer.prototype.memory()`", + "name": "dep0082:_`replserver.prototype.memory()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16242", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      REPLServer.prototype.memory() is only necessary for the internal mechanics of\nthe REPLServer itself. Do not use this function.

      \n

      ", + "type": "module", + "displayName": "DEP0082: `REPLServer.prototype.memory()`" + }, + { + "textRaw": "DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`", + "name": "dep0083:_disabling_ecdh_by_setting_`ecdhcurve`_to_`false`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19794", + "description": "End-of-Life." + }, + { + "version": "v9.2.0", + "pr-url": "https://github.com/nodejs/node/pull/16130", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life.

      \n

      The ecdhCurve option to tls.createSecureContext() and tls.TLSSocket could\nbe set to false to disable ECDH entirely on the server only. This mode was\ndeprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with\nthe client and is now unsupported. Use the ciphers parameter instead.

      \n

      ", + "type": "module", + "displayName": "DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`" + }, + { + "textRaw": "DEP0084: requiring bundled internal dependencies", + "name": "dep0084:_requiring_bundled_internal_dependencies", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25138", + "description": "This functionality has been removed." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16392", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for\ninternal usage were mistakenly exposed to user code through require(). These\nmodules were:

      \n
        \n
      • v8/tools/codemap
      • \n
      • v8/tools/consarray
      • \n
      • v8/tools/csvparser
      • \n
      • v8/tools/logreader
      • \n
      • v8/tools/profile_view
      • \n
      • v8/tools/profile
      • \n
      • v8/tools/SourceMap
      • \n
      • v8/tools/splaytree
      • \n
      • v8/tools/tickprocessor-driver
      • \n
      • v8/tools/tickprocessor
      • \n
      • node-inspect/lib/_inspect (from 7.6.0)
      • \n
      • node-inspect/lib/internal/inspect_client (from 7.6.0)
      • \n
      • node-inspect/lib/internal/inspect_repl (from 7.6.0)
      • \n
      \n

      The v8/* modules do not have any exports, and if not imported in a specific\norder would in fact throw errors. As such there are virtually no legitimate use\ncases for importing them through require().

      \n

      On the other hand, node-inspect may be installed locally through a package\nmanager, as it is published on the npm registry under the same name. No source\ncode modification is necessary if that is done.

      \n

      ", + "type": "module", + "displayName": "DEP0084: requiring bundled internal dependencies" + }, + { + "textRaw": "DEP0085: AsyncHooks sensitive API", + "name": "dep0085:_asynchooks_sensitive_api", + "meta": { + "changes": [ + { + "version": "10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17147", + "description": "End-of-Life." + }, + { + "version": [ + "v8.10.0", + "v9.4.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/16972", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The AsyncHooks sensitive API was never documented and had various minor issues.\nUse the AsyncResource API instead. See\nhttps://github.com/nodejs/node/issues/15572.

      \n

      ", + "type": "module", + "displayName": "DEP0085: AsyncHooks sensitive API" + }, + { + "textRaw": "DEP0086: Remove `runInAsyncIdScope`", + "name": "dep0086:_remove_`runinasyncidscope`", + "meta": { + "changes": [ + { + "version": "10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17147", + "description": "End-of-Life." + }, + { + "version": [ + "v8.10.0", + "v9.4.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/16972", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      runInAsyncIdScope doesn't emit the 'before' or 'after' event and can thus\ncause a lot of issues. See https://github.com/nodejs/node/issues/14328.

      \n

      ", + "type": "module", + "displayName": "DEP0086: Remove `runInAsyncIdScope`" + }, + { + "textRaw": "DEP0089: `require('assert')`", + "name": "dep0089:_`require('assert')`", + "meta": { + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28892", + "description": "Deprecation revoked." + }, + { + "version": [ + "v9.9.0", + "v10.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/17002", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Deprecation revoked

      \n

      Importing assert directly was not recommended as the exposed functions use\nloose equality checks. The deprecation was revoked because use of the assert\nmodule is not discouraged, and the deprecation caused developer confusion.

      \n

      ", + "type": "module", + "displayName": "DEP0089: `require('assert')`" + }, + { + "textRaw": "DEP0090: Invalid GCM authentication tag lengths", + "name": "dep0090:_invalid_gcm_authentication_tag_lengths", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17825", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18017", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Node.js used to support all GCM authentication tag lengths which are accepted by\nOpenSSL when calling decipher.setAuthTag(). Beginning with Node.js\nv11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32\nbits are allowed. Authentication tags of other lengths are invalid per\nNIST SP 800-38D.

      \n

      ", + "type": "module", + "displayName": "DEP0090: Invalid GCM authentication tag lengths" + }, + { + "textRaw": "DEP0091: `crypto.DEFAULT_ENCODING`", + "name": "dep0091:_`crypto.default_encoding`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18333", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The crypto.DEFAULT_ENCODING property is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0091: `crypto.DEFAULT_ENCODING`" + }, + { + "textRaw": "DEP0092: Top-level `this` bound to `module.exports`", + "name": "dep0092:_top-level_`this`_bound_to_`module.exports`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16878", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Assigning properties to the top-level this as an alternative\nto module.exports is deprecated. Developers should use exports\nor module.exports instead.

      \n

      ", + "type": "module", + "displayName": "DEP0092: Top-level `this` bound to `module.exports`" + }, + { + "textRaw": "DEP0093: `crypto.fips` is deprecated and replaced.", + "name": "dep0093:_`crypto.fips`_is_deprecated_and_replaced.", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18335", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The crypto.fips property is deprecated. Please use crypto.setFips()\nand crypto.getFips() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0093: `crypto.fips` is deprecated and replaced." + }, + { + "textRaw": "DEP0094: Using `assert.fail()` with more than one argument.", + "name": "dep0094:_using_`assert.fail()`_with_more_than_one_argument.", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18418", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Using assert.fail() with more than one argument is deprecated. Use\nassert.fail() with only one argument or use a different assert module\nmethod.

      \n

      ", + "type": "module", + "displayName": "DEP0094: Using `assert.fail()` with more than one argument." + }, + { + "textRaw": "DEP0095: `timers.enroll()`", + "name": "dep0095:_`timers.enroll()`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18066", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      timers.enroll() is deprecated. Please use the publicly documented\nsetTimeout() or setInterval() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0095: `timers.enroll()`" + }, + { + "textRaw": "DEP0096: `timers.unenroll()`", + "name": "dep0096:_`timers.unenroll()`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18066", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      timers.unenroll() is deprecated. Please use the publicly documented\nclearTimeout() or clearInterval() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0096: `timers.unenroll()`" + }, + { + "textRaw": "DEP0097: `MakeCallback` with `domain` property", + "name": "dep0097:_`makecallback`_with_`domain`_property", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17417", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Users of MakeCallback that add the domain property to carry context,\nshould start using the async_context variant of MakeCallback or\nCallbackScope, or the high-level AsyncResource class.

      \n

      ", + "type": "module", + "displayName": "DEP0097: `MakeCallback` with `domain` property" + }, + { + "textRaw": "DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs", + "name": "dep0098:_asynchooks_embedder_`asyncresource.emitbefore`_and_`asyncresource.emitafter`_apis", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26530", + "description": "End-of-Life" + }, + { + "version": [ + "v8.12.0", + "v9.6.0", + "v10.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/18632", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The embedded API provided by AsyncHooks exposes .emitBefore() and\n.emitAfter() methods which are very easy to use incorrectly which can lead\nto unrecoverable errors.

      \n

      Use asyncResource.runInAsyncScope() API instead which provides a much\nsafer, and more convenient, alternative. See\nhttps://github.com/nodejs/node/pull/18513.

      \n

      ", + "type": "module", + "displayName": "DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs" + }, + { + "textRaw": "DEP0099: Async context-unaware `node::MakeCallback` C++ APIs", + "name": "dep0099:_async_context-unaware_`node::makecallback`_c++_apis", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18632", + "description": "Compile-time deprecation." + } + ] + }, + "desc": "

      Type: Compile-time

      \n

      Certain versions of node::MakeCallback APIs available to native modules are\ndeprecated. Please use the versions of the API that accept an async_context\nparameter.

      \n

      ", + "type": "module", + "displayName": "DEP0099: Async context-unaware `node::MakeCallback` C++ APIs" + }, + { + "textRaw": "DEP0100: `process.assert()`", + "name": "dep0100:_`process.assert()`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18666", + "description": "Runtime deprecation." + }, + { + "version": "v0.3.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      process.assert() is deprecated. Please use the assert module instead.

      \n

      This was never a documented feature.

      \n

      ", + "type": "module", + "displayName": "DEP0100: `process.assert()`" + }, + { + "textRaw": "DEP0101: `--with-lttng`", + "name": "dep0101:_`--with-lttng`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18982", + "description": "End-of-Life." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The --with-lttng compile-time option has been removed.

      \n

      ", + "type": "module", + "displayName": "DEP0101: `--with-lttng`" + }, + { + "textRaw": "DEP0102: Using `noAssert` in `Buffer#(read|write)` operations.", + "name": "dep0102:_using_`noassert`_in_`buffer#(read|write)`_operations.", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "End-of-Life." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Using the noAssert argument has no functionality anymore. All input is going\nto be verified, no matter if it is set to true or not. Skipping the verification\ncould lead to hard to find errors and crashes.

      \n

      ", + "type": "module", + "displayName": "DEP0102: Using `noAssert` in `Buffer#(read|write)` operations." + }, + { + "textRaw": "DEP0103: `process.binding('util').is[...]` typechecks", + "name": "dep0103:_`process.binding('util').is[...]`_typechecks", + "meta": { + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/22004", + "description": "Superseded by [DEP0111](#DEP0111)." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18415", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      Using process.binding() in general should be avoided. The type checking\nmethods in particular can be replaced by using util.types.

      \n

      This deprecation has been superseded by the deprecation of the\nprocess.binding() API (DEP0111).

      \n

      ", + "type": "module", + "displayName": "DEP0103: `process.binding('util').is[...]` typechecks" + }, + { + "textRaw": "DEP0104: `process.env` string coercion", + "name": "dep0104:_`process.env`_string_coercion", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18990", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      When assigning a non-string property to process.env, the assigned value is\nimplicitly converted to a string. This behavior is deprecated if the assigned\nvalue is not a string, boolean, or number. In the future, such assignment may\nresult in a thrown error. Please convert the property to a string before\nassigning it to process.env.

      \n

      ", + "type": "module", + "displayName": "DEP0104: `process.env` string coercion" + }, + { + "textRaw": "DEP0105: `decipher.finaltol`", + "name": "dep0105:_`decipher.finaltol`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19941", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19353", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      decipher.finaltol() has never been documented and was an alias for\ndecipher.final(). This API has been removed, and it is recommended to use\ndecipher.final() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0105: `decipher.finaltol`" + }, + { + "textRaw": "DEP0106: `crypto.createCipher` and `crypto.createDecipher`", + "name": "dep0106:_`crypto.createcipher`_and_`crypto.createdecipher`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22089", + "description": "Runtime deprecation." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19343", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Using crypto.createCipher() and crypto.createDecipher() should be\navoided as they use a weak key derivation function (MD5 with no salt) and static\ninitialization vectors. It is recommended to derive a key using\ncrypto.pbkdf2() or crypto.scrypt() and to use\ncrypto.createCipheriv() and crypto.createDecipheriv() to obtain the\nCipher and Decipher objects respectively.

      \n

      ", + "type": "module", + "displayName": "DEP0106: `crypto.createCipher` and `crypto.createDecipher`" + }, + { + "textRaw": "DEP0107: `tls.convertNPNProtocols()`", + "name": "dep0107:_`tls.convertnpnprotocols()`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20736", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19403", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      This was an undocumented helper function not intended for use outside Node.js\ncore and obsoleted by the removal of NPN (Next Protocol Negotiation) support.

      \n

      ", + "type": "module", + "displayName": "DEP0107: `tls.convertNPNProtocols()`" + }, + { + "textRaw": "DEP0108: `zlib.bytesRead`", + "name": "dep0108:_`zlib.bytesread`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23308", + "description": "Runtime deprecation." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19414", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Deprecated alias for zlib.bytesWritten. This original name was chosen\nbecause it also made sense to interpret the value as the number of bytes\nread by the engine, but is inconsistent with other streams in Node.js that\nexpose values under these names.

      \n

      ", + "type": "module", + "displayName": "DEP0108: `zlib.bytesRead`" + }, + { + "textRaw": "DEP0109: `http`, `https`, and `tls` support for invalid URLs", + "name": "dep0109:_`http`,_`https`,_and_`tls`_support_for_invalid_urls", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20270", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Some previously supported (but strictly invalid) URLs were accepted through the\nhttp.request(), http.get(), https.request(),\nhttps.get(), and tls.checkServerIdentity() APIs because those were\naccepted by the legacy url.parse() API. The mentioned APIs now use the WHATWG\nURL parser that requires strictly valid URLs. Passing an invalid URL is\ndeprecated and support will be removed in the future.

      \n

      ", + "type": "module", + "displayName": "DEP0109: `http`, `https`, and `tls` support for invalid URLs" + }, + { + "textRaw": "DEP0110: `vm.Script` cached data", + "name": "dep0110:_`vm.script`_cached_data", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/20300", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The produceCachedData option is deprecated. Use\nscript.createCachedData() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0110: `vm.Script` cached data" + }, + { + "textRaw": "DEP0111: `process.binding()`", + "name": "dep0111:_`process.binding()`", + "meta": { + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/22004", + "description": "Documentation-only deprecation." + }, + { + "version": "v11.12.0", + "pr-url": "https://github.com/nodejs/node/pull/26500", + "description": "Added support for `--pending-deprecation`." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      process.binding() is for use by Node.js internal code only.

      \n

      ", + "type": "module", + "displayName": "DEP0111: `process.binding()`" + }, + { + "textRaw": "DEP0112: `dgram` private APIs", + "name": "dep0112:_`dgram`_private_apis", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22011", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The dgram module previously contained several APIs that were never meant to\naccessed outside of Node.js core: Socket.prototype._handle,\nSocket.prototype._receiving, Socket.prototype._bindState,\nSocket.prototype._queue, Socket.prototype._reuseAddr,\nSocket.prototype._healthCheck(), Socket.prototype._stopReceiving(), and\ndgram._createSocketHandle().

      \n

      ", + "type": "module", + "displayName": "DEP0112: `dgram` private APIs" + }, + { + "textRaw": "DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`", + "name": "dep0113:_`cipher.setauthtag()`,_`decipher.getauthtag()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26249", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22126", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Cipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They\nwere never documented and would throw when called.

      \n

      ", + "type": "module", + "displayName": "DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`" + }, + { + "textRaw": "DEP0114: `crypto._toBuf()`", + "name": "dep0114:_`crypto._tobuf()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25338", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22501", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The crypto._toBuf() function was not designed to be used by modules outside\nof Node.js core and was removed.

      \n

      ", + "type": "module", + "displayName": "DEP0114: `crypto._toBuf()`" + }, + { + "textRaw": "DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`", + "name": "dep0115:_`crypto.prng()`,_`crypto.pseudorandombytes()`,_`crypto.rng()`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": [ + "https://github.com/nodejs/node/pull/22519", + "https://github.com/nodejs/node/pull/23017" + ], + "description": "Added documentation-only deprecation with `--pending-deprecation` support." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      In recent versions of Node.js, there is no difference between\ncrypto.randomBytes() and crypto.pseudoRandomBytes(). The latter is\ndeprecated along with the undocumented aliases crypto.prng() and\ncrypto.rng() in favor of crypto.randomBytes() and may be removed in a\nfuture release.

      \n

      ", + "type": "module", + "displayName": "DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`" + }, + { + "textRaw": "DEP0116: Legacy URL API", + "name": "dep0116:_legacy_url_api", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The Legacy URL API is deprecated. This includes url.format(),\nurl.parse(), url.resolve(), and the legacy urlObject. Please\nuse the WHATWG URL API instead.

      \n

      ", + "type": "module", + "displayName": "DEP0116: Legacy URL API" + }, + { + "textRaw": "DEP0117: Native crypto handles", + "name": "dep0117:_native_crypto_handles", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27011", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22747", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Previous versions of Node.js exposed handles to internal native objects through\nthe _handle property of the Cipher, Decipher, DiffieHellman,\nDiffieHellmanGroup, ECDH, Hash, Hmac, Sign, and Verify classes.\nThe _handle property has been removed because improper use of the native\nobject can lead to crashing the application.

      \n

      ", + "type": "module", + "displayName": "DEP0117: Native crypto handles" + }, + { + "textRaw": "DEP0118: `dns.lookup()` support for a falsy host name", + "name": "dep0118:_`dns.lookup()`_support_for_a_falsy_host_name", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23173", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Previous versions of Node.js supported dns.lookup() with a falsy host name\nlike dns.lookup(false) due to backward compatibility.\nThis behavior is undocumented and is thought to be unused in real world apps.\nIt will become an error in future versions of Node.js.

      \n

      ", + "type": "module", + "displayName": "DEP0118: `dns.lookup()` support for a falsy host name" + }, + { + "textRaw": "DEP0119: `process.binding('uv').errname()` private API", + "name": "dep0119:_`process.binding('uv').errname()`_private_api", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23597", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      process.binding('uv').errname() is deprecated. Please use\nutil.getSystemErrorName() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0119: `process.binding('uv').errname()` private API" + }, + { + "textRaw": "DEP0120: Windows Performance Counter support", + "name": "dep0120:_windows_performance_counter_support", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24862", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22485", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Windows Performance Counter support has been removed from Node.js. The\nundocumented COUNTER_NET_SERVER_CONNECTION(),\nCOUNTER_NET_SERVER_CONNECTION_CLOSE(), COUNTER_HTTP_SERVER_REQUEST(),\nCOUNTER_HTTP_SERVER_RESPONSE(), COUNTER_HTTP_CLIENT_REQUEST(), and\nCOUNTER_HTTP_CLIENT_RESPONSE() functions have been deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0120: Windows Performance Counter support" + }, + { + "textRaw": "DEP0121: `net._setSimultaneousAccepts()`", + "name": "dep0121:_`net._setsimultaneousaccepts()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23760", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The undocumented net._setSimultaneousAccepts() function was originally\nintended for debugging and performance tuning when using the child_process\nand cluster modules on Windows. The function is not generally useful and\nis being removed. See discussion here:\nhttps://github.com/nodejs/node/issues/18391

      \n

      ", + "type": "module", + "displayName": "DEP0121: `net._setSimultaneousAccepts()`" + }, + { + "textRaw": "DEP0122: `tls` `Server.prototype.setOptions()`", + "name": "dep0122:_`tls`_`server.prototype.setoptions()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23820", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Please use Server.prototype.setSecureContext() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0122: `tls` `Server.prototype.setOptions()`" + }, + { + "textRaw": "DEP0123: setting the TLS ServerName to an IP address", + "name": "dep0123:_setting_the_tls_servername_to_an_ip_address", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23329", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Setting the TLS ServerName to an IP address is not permitted by\nRFC 6066. This will be ignored in a future version.

      \n

      ", + "type": "module", + "displayName": "DEP0123: setting the TLS ServerName to an IP address" + }, + { + "textRaw": "DEP0124: using `REPLServer.rli`", + "name": "dep0124:_using_`replserver.rli`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26260", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      This property is a reference to the instance itself.

      \n

      ", + "type": "module", + "displayName": "DEP0124: using `REPLServer.rli`" + }, + { + "textRaw": "DEP0125: `require('_stream_wrap')`", + "name": "dep0125:_`require('_stream_wrap')`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26245", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The _stream_wrap module is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0125: `require('_stream_wrap')`" + }, + { + "textRaw": "DEP0126: `timers.active()`", + "name": "dep0126:_`timers.active()`", + "meta": { + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26760", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The previously undocumented timers.active() is deprecated.\nPlease use the publicly documented timeout.refresh() instead.\nIf re-referencing the timeout is necessary, timeout.ref() can be used\nwith no performance impact since Node.js 10.

      \n

      ", + "type": "module", + "displayName": "DEP0126: `timers.active()`" + }, + { + "textRaw": "DEP0127: `timers._unrefActive()`", + "name": "dep0127:_`timers._unrefactive()`", + "meta": { + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26760", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The previously undocumented and \"private\" timers._unrefActive() is deprecated.\nPlease use the publicly documented timeout.refresh() instead.\nIf unreferencing the timeout is necessary, timeout.unref() can be used\nwith no performance impact since Node.js 10.

      \n

      ", + "type": "module", + "displayName": "DEP0127: `timers._unrefActive()`" + }, + { + "textRaw": "DEP0128: modules with an invalid `main` entry and an `index.js` file", + "name": "dep0128:_modules_with_an_invalid_`main`_entry_and_an_`index.js`_file", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26823", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      Modules that have an invalid main entry (e.g., ./does-not-exist.js) and\nalso have an index.js file in the top level directory will resolve the\nindex.js file. That is deprecated and is going to throw an error in future\nNode.js versions.

      \n

      ", + "type": "module", + "displayName": "DEP0128: modules with an invalid `main` entry and an `index.js` file" + }, + { + "textRaw": "DEP0129: `ChildProcess._channel`", + "name": "dep0129:_`childprocess._channel`", + "meta": { + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26982", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The _channel property of child process objects returned by spawn() and\nsimilar functions is not intended for public use. Use ChildProcess.channel\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0129: `ChildProcess._channel`" + }, + { + "textRaw": "DEP0130: `Module.createRequireFromPath()`", + "name": "dep0130:_`module.createrequirefrompath()`", + "meta": { + "changes": [ + { + "version": "v12.2.0", + "pr-url": "https://github.com/nodejs/node/pull/27405", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Module.createRequireFromPath() is deprecated. Please use module.createRequire() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0130: `Module.createRequireFromPath()`" + }, + { + "textRaw": "DEP0131: Legacy HTTP parser", + "name": "dep0131:_legacy_http_parser", + "meta": { + "changes": [ + { + "version": "v12.22.0", + "pr-url": "https://github.com/nodejs/node/pull/37603", + "description": "Runtime deprecation." + }, + { + "version": "v12.3.0", + "pr-url": "https://github.com/nodejs/node/pull/27498", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0,\nis deprecated. This deprecation applies to users of the\n--http-parser=legacy command-line flag.

      \n

      ", + "type": "module", + "displayName": "DEP0131: Legacy HTTP parser" + }, + { + "textRaw": "DEP0132: `worker.terminate()` with callback", + "name": "dep0132:_`worker.terminate()`_with_callback", + "meta": { + "changes": [ + { + "version": "v12.5.0", + "pr-url": "https://github.com/nodejs/node/pull/28021", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Passing a callback to worker.terminate() is deprecated. Use the returned\nPromise instead, or a listener to the worker’s 'exit' event.

      \n

      ", + "type": "module", + "displayName": "DEP0132: `worker.terminate()` with callback" + }, + { + "textRaw": "DEP0133: `http` `connection`", + "name": "dep0133:_`http`_`connection`", + "meta": { + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29015", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Prefer response.socket over response.connection and\nrequest.socket over request.connection.

      \n

      ", + "type": "module", + "displayName": "DEP0133: `http` `connection`" + }, + { + "textRaw": "DEP0134: `process._tickCallback`", + "name": "dep0134:_`process._tickcallback`", + "meta": { + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29781", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      The process._tickCallback property was never documented as\nan officially supported API.

      \n

      ", + "type": "module", + "displayName": "DEP0134: `process._tickCallback`" + }, + { + "textRaw": "DEP0136: `http` `finished`", + "name": "dep0136:_`http`_`finished`", + "meta": { + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/28679", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      response.finished indicates whether response.end() has been\ncalled, not whether 'finish' has been emitted and the underlying data\nis flushed.

      \n

      Use response.writableFinished or response.writableEnded\naccordingly instead to avoid the ambigiuty.

      \n

      To maintain existing behaviour response.finished should be replaced with\nresponse.writableEnded.

      \n

      ", + "type": "module", + "displayName": "DEP0136: `http` `finished`" + }, + { + "textRaw": "DEP0139: `process.umask()` with no arguments", + "name": "dep0139:_`process.umask()`_with_no_arguments", + "meta": { + "changes": [ + { + "version": [ + "v12.19.0", + "v14.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/32499", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Calling process.umask() with no argument causes the process-wide umask to be\nwritten twice. This introduces a race condition between threads, and is a\npotential security vulnerability. There is no safe, cross-platform alternative\nAPI.

      \n

      ", + "type": "module", + "displayName": "DEP0139: `process.umask()` with no arguments" + }, + { + "textRaw": "DEP0144: `module.parent`", + "name": "dep0144:_`module.parent`", + "meta": { + "changes": [ + { + "version": [ + "v12.19.0", + "v14.6.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/32217", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      A CommonJS module can access the first module that required it using\nmodule.parent. This feature is deprecated because it does not work\nconsistently in the presence of ECMAScript modules and because it gives an\ninaccurate representation of the CommonJS module graph.

      \n

      Some modules use it to check if they are the entry point of the current process.\nInstead, it is recommended to compare require.main and module:

      \n
      if (require.main === module) {\n  // Code section that will run only if current file is the entry point.\n}\n
      \n

      When looking for the CommonJS modules that have required the current one,\nrequire.cache and module.children can be used:

      \n
      const moduleParents = Object.values(require.cache)\n  .filter((m) => m.children.includes(module));\n
      ", + "type": "module", + "displayName": "DEP0144: `module.parent`" + } + ], + "type": "misc", + "displayName": "List of deprecated APIs" + } + ] + }, + { + "textRaw": "Errors", + "name": "Errors", + "introduced_in": "v4.0.0", + "type": "misc", + "desc": "

      Applications running in Node.js will generally experience four categories of\nerrors:

      \n
        \n
      • Standard JavaScript errors such as <EvalError>, <SyntaxError>, <RangeError>,\n<ReferenceError>, <TypeError>, and <URIError>.
      • \n
      • System errors triggered by underlying operating system constraints such\nas attempting to open a file that does not exist or attempting to send data\nover a closed socket.
      • \n
      • User-specified errors triggered by application code.
      • \n
      • AssertionErrors are a special class of error that can be triggered when\nNode.js detects an exceptional logic violation that should never occur. These\nare raised typically by the assert module.
      • \n
      \n

      All JavaScript and system errors raised by Node.js inherit from, or are\ninstances of, the standard JavaScript <Error> class and are guaranteed\nto provide at least the properties available on that class.

      ", + "miscs": [ + { + "textRaw": "Error propagation and interception", + "name": "Error propagation and interception", + "type": "misc", + "desc": "

      Node.js supports several mechanisms for propagating and handling errors that\noccur while an application is running. How these errors are reported and\nhandled depends entirely on the type of Error and the style of the API that is\ncalled.

      \n

      All JavaScript errors are handled as exceptions that immediately generate\nand throw an error using the standard JavaScript throw mechanism. These\nare handled using the try…catch construct provided by the\nJavaScript language.

      \n
      // Throws with a ReferenceError because z is not defined.\ntry {\n  const m = 1;\n  const n = m + z;\n} catch (err) {\n  // Handle the error here.\n}\n
      \n

      Any use of the JavaScript throw mechanism will raise an exception that\nmust be handled using try…catch or the Node.js process will exit\nimmediately.

      \n

      With few exceptions, Synchronous APIs (any blocking method that does not\naccept a callback function, such as fs.readFileSync), will use throw\nto report errors.

      \n

      Errors that occur within Asynchronous APIs may be reported in multiple ways:

      \n
        \n
      • Most asynchronous methods that accept a callback function will accept an\nError object passed as the first argument to that function. If that first\nargument is not null and is an instance of Error, then an error occurred\nthat should be handled.
      • \n
      \n\n
      const fs = require('fs');\nfs.readFile('a file that does not exist', (err, data) => {\n  if (err) {\n    console.error('There was an error reading the file!', err);\n    return;\n  }\n  // Otherwise handle the data\n});\n
      \n
        \n
      • \n

        When an asynchronous method is called on an object that is an\nEventEmitter, errors can be routed to that object's 'error' event.

        \n
        const net = require('net');\nconst connection = net.connect('localhost');\n\n// Adding an 'error' event handler to a stream:\nconnection.on('error', (err) => {\n  // If the connection is reset by the server, or if it can't\n  // connect at all, or on any sort of error encountered by\n  // the connection, the error will be sent here.\n  console.error(err);\n});\n\nconnection.pipe(process.stdout);\n
        \n
      • \n
      • \n

        A handful of typically asynchronous methods in the Node.js API may still\nuse the throw mechanism to raise exceptions that must be handled using\ntry…catch. There is no comprehensive list of such methods; please\nrefer to the documentation of each method to determine the appropriate\nerror handling mechanism required.

        \n
      • \n
      \n

      The use of the 'error' event mechanism is most common for stream-based\nand event emitter-based APIs, which themselves represent a series of\nasynchronous operations over time (as opposed to a single operation that may\npass or fail).

      \n

      For all EventEmitter objects, if an 'error' event handler is not\nprovided, the error will be thrown, causing the Node.js process to report an\nuncaught exception and crash unless either: The domain module is\nused appropriately or a handler has been registered for the\n'uncaughtException' event.

      \n
      const EventEmitter = require('events');\nconst ee = new EventEmitter();\n\nsetImmediate(() => {\n  // This will crash the process because no 'error' event\n  // handler has been added.\n  ee.emit('error', new Error('This will crash'));\n});\n
      \n

      Errors generated in this way cannot be intercepted using try…catch as\nthey are thrown after the calling code has already exited.

      \n

      Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.

      ", + "miscs": [ + { + "textRaw": "Error-first callbacks", + "name": "Error-first callbacks", + "type": "misc", + "desc": "

      Most asynchronous methods exposed by the Node.js core API follow an idiomatic\npattern referred to as an error-first callback. With this pattern, a callback\nfunction is passed to the method as an argument. When the operation either\ncompletes or an error is raised, the callback function is called with the\nError object (if any) passed as the first argument. If no error was raised,\nthe first argument will be passed as null.

      \n
      const fs = require('fs');\n\nfunction errorFirstCallback(err, data) {\n  if (err) {\n    console.error('There was an error', err);\n    return;\n  }\n  console.log(data);\n}\n\nfs.readFile('/some/file/that/does-not-exist', errorFirstCallback);\nfs.readFile('/some/file/that/does-exist', errorFirstCallback);\n
      \n

      The JavaScript try…catch mechanism cannot be used to intercept errors\ngenerated by asynchronous APIs. A common mistake for beginners is to try to\nuse throw inside an error-first callback:

      \n
      // THIS WILL NOT WORK:\nconst fs = require('fs');\n\ntry {\n  fs.readFile('/some/file/that/does-not-exist', (err, data) => {\n    // Mistaken assumption: throwing here...\n    if (err) {\n      throw err;\n    }\n  });\n} catch (err) {\n  // This will not catch the throw!\n  console.error(err);\n}\n
      \n

      This will not work because the callback function passed to fs.readFile() is\ncalled asynchronously. By the time the callback has been called, the\nsurrounding code, including the try…catch block, will have already exited.\nThrowing an error inside the callback can crash the Node.js process in most\ncases. If domains are enabled, or a handler has been registered with\nprocess.on('uncaughtException'), such errors can be intercepted.

      " + } + ] + }, + { + "textRaw": "Exceptions vs. errors", + "name": "Exceptions vs. errors", + "type": "misc", + "desc": "

      A JavaScript exception is a value that is thrown as a result of an invalid\noperation or as the target of a throw statement. While it is not required\nthat these values are instances of Error or classes which inherit from\nError, all exceptions thrown by Node.js or the JavaScript runtime will be\ninstances of Error.

      \n

      Some exceptions are unrecoverable at the JavaScript layer. Such exceptions\nwill always cause the Node.js process to crash. Examples include assert()\nchecks or abort() calls in the C++ layer.

      " + }, + { + "textRaw": "OpenSSL errors", + "name": "openssl_errors", + "desc": "

      Errors originating in crypto or tls are of class Error, and in addition to\nthe standard .code and .message properties, may have some additional\nOpenSSL-specific properties.

      ", + "properties": [ + { + "textRaw": "`error.opensslErrorStack`", + "name": "opensslErrorStack", + "desc": "

      An array of errors that can give context to where in the OpenSSL library an\nerror originates from.

      " + }, + { + "textRaw": "`error.function`", + "name": "function", + "desc": "

      The OpenSSL function the error originates in.

      " + }, + { + "textRaw": "`error.library`", + "name": "library", + "desc": "

      The OpenSSL library the error originates in.

      " + }, + { + "textRaw": "`error.reason`", + "name": "reason", + "desc": "

      A human-readable string describing the reason for the error.

      \n

      " + } + ], + "type": "misc", + "displayName": "OpenSSL errors" + }, + { + "textRaw": "Node.js error codes", + "name": "node.js_error_codes", + "desc": "

      ", + "modules": [ + { + "textRaw": "`ERR_AMBIGUOUS_ARGUMENT`", + "name": "`err_ambiguous_argument`", + "desc": "

      A function argument is being used in a way that suggests that the function\nsignature may be misunderstood. This is thrown by the assert module when the\nmessage parameter in assert.throws(block, message) matches the error message\nthrown by block because that usage suggests that the user believes message\nis the expected message rather than the message the AssertionError will\ndisplay if block does not throw.

      \n

      ", + "type": "module", + "displayName": "`ERR_AMBIGUOUS_ARGUMENT`" + }, + { + "textRaw": "`ERR_ARG_NOT_ITERABLE`", + "name": "`err_arg_not_iterable`", + "desc": "

      An iterable argument (i.e. a value that works with for...of loops) was\nrequired, but not provided to a Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_ARG_NOT_ITERABLE`" + }, + { + "textRaw": "`ERR_ASSERTION`", + "name": "`err_assertion`", + "desc": "

      A special type of error that can be triggered whenever Node.js detects an\nexceptional logic violation that should never occur. These are raised typically\nby the assert module.

      \n

      ", + "type": "module", + "displayName": "`ERR_ASSERTION`" + }, + { + "textRaw": "`ERR_ASYNC_CALLBACK`", + "name": "`err_async_callback`", + "desc": "

      An attempt was made to register something that is not a function as an\nAsyncHooks callback.

      \n

      ", + "type": "module", + "displayName": "`ERR_ASYNC_CALLBACK`" + }, + { + "textRaw": "`ERR_ASYNC_TYPE`", + "name": "`err_async_type`", + "desc": "

      The type of an asynchronous resource was invalid. Users are also able\nto define their own types if using the public embedder API.

      \n

      ", + "type": "module", + "displayName": "`ERR_ASYNC_TYPE`" + }, + { + "textRaw": "`ERR_BROTLI_COMPRESSION_FAILED`", + "name": "`err_brotli_compression_failed`", + "desc": "

      Data passed to a Brotli stream was not successfully compressed.

      \n

      ", + "type": "module", + "displayName": "`ERR_BROTLI_COMPRESSION_FAILED`" + }, + { + "textRaw": "`ERR_BROTLI_INVALID_PARAM`", + "name": "`err_brotli_invalid_param`", + "desc": "

      An invalid parameter key was passed during construction of a Brotli stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_BROTLI_INVALID_PARAM`" + }, + { + "textRaw": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`", + "name": "`err_buffer_context_not_available`", + "desc": "

      An attempt was made to create a Node.js Buffer instance from addon or embedder\ncode, while in a JS engine Context that is not associated with a Node.js\ninstance. The data passed to the Buffer method will have been released\nby the time the method returns.

      \n

      When encountering this error, a possible alternative to creating a Buffer\ninstance is to create a normal Uint8Array, which only differs in the\nprototype of the resulting object. Uint8Arrays are generally accepted in all\nNode.js core APIs where Buffers are; they are available in all Contexts.

      \n

      ", + "type": "module", + "displayName": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_BUFFER_OUT_OF_BOUNDS`", + "name": "`err_buffer_out_of_bounds`", + "desc": "

      An operation outside the bounds of a Buffer was attempted.

      \n

      ", + "type": "module", + "displayName": "`ERR_BUFFER_OUT_OF_BOUNDS`" + }, + { + "textRaw": "`ERR_BUFFER_TOO_LARGE`", + "name": "`err_buffer_too_large`", + "desc": "

      An attempt has been made to create a Buffer larger than the maximum allowed\nsize.

      \n

      ", + "type": "module", + "displayName": "`ERR_BUFFER_TOO_LARGE`" + }, + { + "textRaw": "`ERR_CANNOT_WATCH_SIGINT`", + "name": "`err_cannot_watch_sigint`", + "desc": "

      Node.js was unable to watch for the SIGINT signal.

      \n

      ", + "type": "module", + "displayName": "`ERR_CANNOT_WATCH_SIGINT`" + }, + { + "textRaw": "`ERR_CHILD_CLOSED_BEFORE_REPLY`", + "name": "`err_child_closed_before_reply`", + "desc": "

      A child process was closed before the parent received a reply.

      \n

      ", + "type": "module", + "displayName": "`ERR_CHILD_CLOSED_BEFORE_REPLY`" + }, + { + "textRaw": "`ERR_CHILD_PROCESS_IPC_REQUIRED`", + "name": "`err_child_process_ipc_required`", + "desc": "

      Used when a child process is being forked without specifying an IPC channel.

      \n

      ", + "type": "module", + "displayName": "`ERR_CHILD_PROCESS_IPC_REQUIRED`" + }, + { + "textRaw": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`", + "name": "`err_child_process_stdio_maxbuffer`", + "desc": "

      Used when the main process is trying to read data from the child process's\nSTDERR/STDOUT, and the data's length is longer than the maxBuffer option.

      \n

      ", + "type": "module", + "displayName": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`" + }, + { + "textRaw": "`ERR_CONSOLE_WRITABLE_STREAM`", + "name": "`err_console_writable_stream`", + "desc": "

      Console was instantiated without stdout stream, or Console has a\nnon-writable stdout or stderr stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_CONSOLE_WRITABLE_STREAM`" + }, + { + "textRaw": "`ERR_CONSTRUCT_CALL_REQUIRED`", + "name": "`err_construct_call_required`", + "desc": "

      A constructor for a class was called without new.

      \n

      ", + "type": "module", + "displayName": "`ERR_CONSTRUCT_CALL_REQUIRED`" + }, + { + "textRaw": "`ERR_CONSTRUCT_CALL_INVALID`", + "name": "`err_construct_call_invalid`", + "desc": "\n

      A class constructor was called that is not callable.

      \n

      ", + "type": "module", + "displayName": "`ERR_CONSTRUCT_CALL_INVALID`" + }, + { + "textRaw": "`ERR_CPU_USAGE`", + "name": "`err_cpu_usage`", + "desc": "

      The native call from process.cpuUsage could not be processed.

      \n

      ", + "type": "module", + "displayName": "`ERR_CPU_USAGE`" + }, + { + "textRaw": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`", + "name": "`err_crypto_custom_engine_not_supported`", + "desc": "

      A client certificate engine was requested that is not supported by the version\nof OpenSSL being used.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`" + }, + { + "textRaw": "`ERR_CRYPTO_ECDH_INVALID_FORMAT`", + "name": "`err_crypto_ecdh_invalid_format`", + "desc": "

      An invalid value for the format argument was passed to the crypto.ECDH()\nclass getPublicKey() method.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_ECDH_INVALID_FORMAT`" + }, + { + "textRaw": "`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY`", + "name": "`err_crypto_ecdh_invalid_public_key`", + "desc": "

      An invalid value for the key argument has been passed to the\ncrypto.ECDH() class computeSecret() method. It means that the public\nkey lies outside of the elliptic curve.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY`" + }, + { + "textRaw": "`ERR_CRYPTO_ENGINE_UNKNOWN`", + "name": "`err_crypto_engine_unknown`", + "desc": "

      An invalid crypto engine identifier was passed to\nrequire('crypto').setEngine().

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_ENGINE_UNKNOWN`" + }, + { + "textRaw": "`ERR_CRYPTO_FIPS_FORCED`", + "name": "`err_crypto_fips_forced`", + "desc": "

      The --force-fips command-line argument was used but there was an attempt\nto enable or disable FIPS mode in the crypto module.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_FIPS_FORCED`" + }, + { + "textRaw": "`ERR_CRYPTO_FIPS_UNAVAILABLE`", + "name": "`err_crypto_fips_unavailable`", + "desc": "

      An attempt was made to enable or disable FIPS mode, but FIPS mode was not\navailable.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_FIPS_UNAVAILABLE`" + }, + { + "textRaw": "`ERR_CRYPTO_HASH_FINALIZED`", + "name": "`err_crypto_hash_finalized`", + "desc": "

      hash.digest() was called multiple times. The hash.digest() method must\nbe called no more than one time per instance of a Hash object.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_HASH_FINALIZED`" + }, + { + "textRaw": "`ERR_CRYPTO_HASH_UPDATE_FAILED`", + "name": "`err_crypto_hash_update_failed`", + "desc": "

      hash.update() failed for any reason. This should rarely, if ever, happen.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_HASH_UPDATE_FAILED`" + }, + { + "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY`", + "name": "`err_crypto_incompatible_key`", + "desc": "

      The given crypto keys are incompatible with the attempted operation.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY`" + }, + { + "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`", + "name": "`err_crypto_incompatible_key_options`", + "desc": "

      The selected public or private key encoding is incompatible with other options.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`" + }, + { + "textRaw": "`ERR_CRYPTO_INVALID_DIGEST`", + "name": "`err_crypto_invalid_digest`", + "desc": "

      An invalid crypto digest algorithm was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INVALID_DIGEST`" + }, + { + "textRaw": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`", + "name": "`err_crypto_invalid_key_object_type`", + "desc": "

      The given crypto key object's type is invalid for the attempted operation.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`" + }, + { + "textRaw": "`ERR_CRYPTO_INVALID_STATE`", + "name": "`err_crypto_invalid_state`", + "desc": "

      A crypto method was used on an object that was in an invalid state. For\ninstance, calling cipher.getAuthTag() before calling cipher.final().

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INVALID_STATE`" + }, + { + "textRaw": "`ERR_CRYPTO_PBKDF2_ERROR`", + "name": "`err_crypto_pbkdf2_error`", + "desc": "

      The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide\nmore details and therefore neither does Node.js.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_PBKDF2_ERROR`" + }, + { + "textRaw": "`ERR_CRYPTO_SCRYPT_INVALID_PARAMETER`", + "name": "`err_crypto_scrypt_invalid_parameter`", + "desc": "

      One or more crypto.scrypt() or crypto.scryptSync() parameters are\noutside their legal range.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_SCRYPT_INVALID_PARAMETER`" + }, + { + "textRaw": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`", + "name": "`err_crypto_scrypt_not_supported`", + "desc": "

      Node.js was compiled without scrypt support. Not possible with the official\nrelease binaries but can happen with custom builds, including distro builds.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`" + }, + { + "textRaw": "`ERR_CRYPTO_SIGN_KEY_REQUIRED`", + "name": "`err_crypto_sign_key_required`", + "desc": "

      A signing key was not provided to the sign.sign() method.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_SIGN_KEY_REQUIRED`" + }, + { + "textRaw": "`ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH`", + "name": "`err_crypto_timing_safe_equal_length`", + "desc": "

      crypto.timingSafeEqual() was called with Buffer, TypedArray, or\nDataView arguments of different lengths.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH`" + }, + { + "textRaw": "`ERR_CRYPTO_UNKNOWN_CIPHER`", + "name": "`err_crypto_unknown_cipher`", + "desc": "

      An unknown cipher was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_UNKNOWN_CIPHER`" + }, + { + "textRaw": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`", + "name": "`err_crypto_unknown_dh_group`", + "desc": "

      An unknown Diffie-Hellman group name was given. See\ncrypto.getDiffieHellman() for a list of valid group names.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`" + }, + { + "textRaw": "`ERR_DIR_CLOSED`", + "name": "`err_dir_closed`", + "desc": "

      The fs.Dir was previously closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_DIR_CLOSED`" + }, + { + "textRaw": "`ERR_DIR_CONCURRENT_OPERATION`", + "name": "`err_dir_concurrent_operation`", + "meta": { + "added": [ + "v12.18.1" + ], + "changes": [] + }, + "desc": "

      A synchronous read or close call was attempted on an fs.Dir which has\nongoing asynchronous operations.

      \n

      ", + "type": "module", + "displayName": "`ERR_DIR_CONCURRENT_OPERATION`" + }, + { + "textRaw": "`ERR_DNS_SET_SERVERS_FAILED`", + "name": "`err_dns_set_servers_failed`", + "desc": "

      c-ares failed to set the DNS server.

      \n

      ", + "type": "module", + "displayName": "`ERR_DNS_SET_SERVERS_FAILED`" + }, + { + "textRaw": "`ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`", + "name": "`err_domain_callback_not_available`", + "desc": "

      The domain module was not usable since it could not establish the required\nerror handling hooks, because\nprocess.setUncaughtExceptionCaptureCallback() had been called at an\nearlier point in time.

      \n

      ", + "type": "module", + "displayName": "`ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`", + "name": "`err_domain_cannot_set_uncaught_exception_capture`", + "desc": "

      process.setUncaughtExceptionCaptureCallback() could not be called\nbecause the domain module has been loaded at an earlier point in time.

      \n

      The stack trace is extended to include the point in time at which the\ndomain module had been loaded.

      \n

      ", + "type": "module", + "displayName": "`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`" + }, + { + "textRaw": "`ERR_ENCODING_INVALID_ENCODED_DATA`", + "name": "`err_encoding_invalid_encoded_data`", + "desc": "

      Data provided to TextDecoder() API was invalid according to the encoding\nprovided.

      \n

      ", + "type": "module", + "displayName": "`ERR_ENCODING_INVALID_ENCODED_DATA`" + }, + { + "textRaw": "`ERR_ENCODING_NOT_SUPPORTED`", + "name": "`err_encoding_not_supported`", + "desc": "

      Encoding provided to TextDecoder() API was not one of the\nWHATWG Supported Encodings.

      \n

      ", + "type": "module", + "displayName": "`ERR_ENCODING_NOT_SUPPORTED`" + }, + { + "textRaw": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`", + "name": "`err_execution_environment_not_available`", + "desc": "

      The JS execution context is not associated with a Node.js environment.\nThis may occur when Node.js is used as an embedded library and some hooks\nfor the JS engine are not set up properly.

      \n

      ", + "type": "module", + "displayName": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_FALSY_VALUE_REJECTION`", + "name": "`err_falsy_value_rejection`", + "desc": "

      A Promise that was callbackified via util.callbackify() was rejected with a\nfalsy value.

      \n

      ", + "type": "module", + "displayName": "`ERR_FALSY_VALUE_REJECTION`" + }, + { + "textRaw": "`ERR_FS_FILE_TOO_LARGE`", + "name": "`err_fs_file_too_large`", + "desc": "

      An attempt has been made to read a file whose size is larger than the maximum\nallowed size for a Buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_FS_FILE_TOO_LARGE`" + }, + { + "textRaw": "`ERR_FS_INVALID_SYMLINK_TYPE`", + "name": "`err_fs_invalid_symlink_type`", + "desc": "

      An invalid symlink type was passed to the fs.symlink() or\nfs.symlinkSync() methods.

      \n

      ", + "type": "module", + "displayName": "`ERR_FS_INVALID_SYMLINK_TYPE`" + }, + { + "textRaw": "`ERR_HTTP_HEADERS_SENT`", + "name": "`err_http_headers_sent`", + "desc": "

      An attempt was made to add more headers after the headers had already been sent.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_HEADERS_SENT`" + }, + { + "textRaw": "`ERR_HTTP_INVALID_HEADER_VALUE`", + "name": "`err_http_invalid_header_value`", + "desc": "

      An invalid HTTP header value was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_INVALID_HEADER_VALUE`" + }, + { + "textRaw": "`ERR_HTTP_INVALID_STATUS_CODE`", + "name": "`err_http_invalid_status_code`", + "desc": "

      Status code was outside the regular status code range (100-999).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_INVALID_STATUS_CODE`" + }, + { + "textRaw": "`ERR_HTTP_TRAILER_INVALID`", + "name": "`err_http_trailer_invalid`", + "desc": "

      The Trailer header was set even though the transfer encoding does not support\nthat.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_TRAILER_INVALID`" + }, + { + "textRaw": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`", + "name": "`err_http2_altsvc_invalid_origin`", + "desc": "

      HTTP/2 ALTSVC frames require a valid origin.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`" + }, + { + "textRaw": "`ERR_HTTP2_ALTSVC_LENGTH`", + "name": "`err_http2_altsvc_length`", + "desc": "

      HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ALTSVC_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_CONNECT_AUTHORITY`", + "name": "`err_http2_connect_authority`", + "desc": "

      For HTTP/2 requests using the CONNECT method, the :authority pseudo-header\nis required.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_CONNECT_AUTHORITY`" + }, + { + "textRaw": "`ERR_HTTP2_CONNECT_PATH`", + "name": "`err_http2_connect_path`", + "desc": "

      For HTTP/2 requests using the CONNECT method, the :path pseudo-header is\nforbidden.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_CONNECT_PATH`" + }, + { + "textRaw": "`ERR_HTTP2_CONNECT_SCHEME`", + "name": "`err_http2_connect_scheme`", + "desc": "

      For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is\nforbidden.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_CONNECT_SCHEME`" + }, + { + "textRaw": "`ERR_HTTP2_ERROR`", + "name": "`err_http2_error`", + "desc": "

      A non-specific HTTP/2 error has occurred.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_GOAWAY_SESSION`", + "name": "`err_http2_goaway_session`", + "desc": "

      New HTTP/2 Streams may not be opened after the Http2Session has received a\nGOAWAY frame from the connected peer.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_GOAWAY_SESSION`" + }, + { + "textRaw": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`", + "name": "`err_http2_headers_after_respond`", + "desc": "

      An additional headers was specified after an HTTP/2 response was initiated.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`" + }, + { + "textRaw": "`ERR_HTTP2_HEADERS_SENT`", + "name": "`err_http2_headers_sent`", + "desc": "

      An attempt was made to send multiple response headers.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADERS_SENT`" + }, + { + "textRaw": "`ERR_HTTP2_HEADER_SINGLE_VALUE`", + "name": "`err_http2_header_single_value`", + "desc": "

      Multiple values were provided for an HTTP/2 header field that was required to\nhave only a single value.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADER_SINGLE_VALUE`" + }, + { + "textRaw": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`", + "name": "`err_http2_info_status_not_allowed`", + "desc": "

      Informational HTTP status codes (1xx) may not be set as the response status\ncode on HTTP/2 responses.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`", + "name": "`err_http2_invalid_connection_headers`", + "desc": "

      HTTP/1 connection specific headers are forbidden to be used in HTTP/2\nrequests and responses.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_HEADER_VALUE`", + "name": "`err_http2_invalid_header_value`", + "desc": "

      An invalid HTTP/2 header value was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_HEADER_VALUE`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_INFO_STATUS`", + "name": "`err_http2_invalid_info_status`", + "desc": "

      An invalid HTTP informational status code has been specified. Informational\nstatus codes must be an integer between 100 and 199 (inclusive).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_INFO_STATUS`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_ORIGIN`", + "name": "`err_http2_invalid_origin`", + "desc": "

      HTTP/2 ORIGIN frames require a valid origin.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_ORIGIN`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH`", + "name": "`err_http2_invalid_packed_settings_length`", + "desc": "

      Input Buffer and Uint8Array instances passed to the\nhttp2.getUnpackedSettings() API must have a length that is a multiple of\nsix.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_PSEUDOHEADER`", + "name": "`err_http2_invalid_pseudoheader`", + "desc": "

      Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme,\nand :method) may be used.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_PSEUDOHEADER`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_SESSION`", + "name": "`err_http2_invalid_session`", + "desc": "

      An action was performed on an Http2Session object that had already been\ndestroyed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_SESSION`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_SETTING_VALUE`", + "name": "`err_http2_invalid_setting_value`", + "desc": "

      An invalid value has been specified for an HTTP/2 setting.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_SETTING_VALUE`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_STREAM`", + "name": "`err_http2_invalid_stream`", + "desc": "

      An operation was performed on a stream that had already been destroyed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_STREAM`" + }, + { + "textRaw": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`", + "name": "`err_http2_max_pending_settings_ack`", + "desc": "

      Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is\nrequired to send an acknowledgment that it has received and applied the new\nSETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may\nbe sent at any given time. This error code is used when that limit has been\nreached.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`" + }, + { + "textRaw": "`ERR_HTTP2_NESTED_PUSH`", + "name": "`err_http2_nested_push`", + "desc": "

      An attempt was made to initiate a new push stream from within a push stream.\nNested push streams are not permitted.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_NESTED_PUSH`" + }, + { + "textRaw": "`ERR_HTTP2_NO_SOCKET_MANIPULATION`", + "name": "`err_http2_no_socket_manipulation`", + "desc": "

      An attempt was made to directly manipulate (read, write, pause, resume, etc.) a\nsocket attached to an Http2Session.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_NO_SOCKET_MANIPULATION`" + }, + { + "textRaw": "`ERR_HTTP2_ORIGIN_LENGTH`", + "name": "`err_http2_origin_length`", + "desc": "

      HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ORIGIN_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_OUT_OF_STREAMS`", + "name": "`err_http2_out_of_streams`", + "desc": "

      The number of streams created on a single HTTP/2 session reached the maximum\nlimit.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_OUT_OF_STREAMS`" + }, + { + "textRaw": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`", + "name": "`err_http2_payload_forbidden`", + "desc": "

      A message payload was specified for an HTTP response code for which a payload is\nforbidden.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`" + }, + { + "textRaw": "`ERR_HTTP2_PING_CANCEL`", + "name": "`err_http2_ping_cancel`", + "desc": "

      An HTTP/2 ping was canceled.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PING_CANCEL`" + }, + { + "textRaw": "`ERR_HTTP2_PING_LENGTH`", + "name": "`err_http2_ping_length`", + "desc": "

      HTTP/2 ping payloads must be exactly 8 bytes in length.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PING_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`", + "name": "`err_http2_pseudoheader_not_allowed`", + "desc": "

      An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header\nkey names that begin with the : prefix.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`" + }, + { + "textRaw": "`ERR_HTTP2_PUSH_DISABLED`", + "name": "`err_http2_push_disabled`", + "desc": "

      An attempt was made to create a push stream, which had been disabled by the\nclient.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PUSH_DISABLED`" + }, + { + "textRaw": "`ERR_HTTP2_SEND_FILE`", + "name": "`err_http2_send_file`", + "desc": "

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend a directory.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SEND_FILE`" + }, + { + "textRaw": "`ERR_HTTP2_SEND_FILE_NOSEEK`", + "name": "`err_http2_send_file_noseek`", + "desc": "

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend something other than a regular file, but offset or length options were\nprovided.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SEND_FILE_NOSEEK`" + }, + { + "textRaw": "`ERR_HTTP2_SESSION_ERROR`", + "name": "`err_http2_session_error`", + "desc": "

      The Http2Session closed with a non-zero error code.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SESSION_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_SETTINGS_CANCEL`", + "name": "`err_http2_settings_cancel`", + "desc": "

      The Http2Session settings canceled.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SETTINGS_CANCEL`" + }, + { + "textRaw": "`ERR_HTTP2_SOCKET_BOUND`", + "name": "`err_http2_socket_bound`", + "desc": "

      An attempt was made to connect a Http2Session object to a net.Socket or\ntls.TLSSocket that had already been bound to another Http2Session object.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SOCKET_BOUND`" + }, + { + "textRaw": "`ERR_HTTP2_SOCKET_UNBOUND`", + "name": "`err_http2_socket_unbound`", + "desc": "

      An attempt was made to use the socket property of an Http2Session that\nhas already been closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SOCKET_UNBOUND`" + }, + { + "textRaw": "`ERR_HTTP2_STATUS_101`", + "name": "`err_http2_status_101`", + "desc": "

      Use of the 101 Informational status code is forbidden in HTTP/2.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STATUS_101`" + }, + { + "textRaw": "`ERR_HTTP2_STATUS_INVALID`", + "name": "`err_http2_status_invalid`", + "desc": "

      An invalid HTTP status code has been specified. Status codes must be an integer\nbetween 100 and 599 (inclusive).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STATUS_INVALID`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_CANCEL`", + "name": "`err_http2_stream_cancel`", + "desc": "

      An Http2Stream was destroyed before any data was transmitted to the connected\npeer.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_CANCEL`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_ERROR`", + "name": "`err_http2_stream_error`", + "desc": "

      A non-zero error code was been specified in an RST_STREAM frame.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`", + "name": "`err_http2_stream_self_dependency`", + "desc": "

      When setting the priority for an HTTP/2 stream, the stream may be marked as\na dependency for a parent stream. This error code is used when an attempt is\nmade to mark a stream and dependent of itself.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`" + }, + { + "textRaw": "`ERR_HTTP2_TRAILERS_ALREADY_SENT`", + "name": "`err_http2_trailers_already_sent`", + "desc": "

      Trailing headers have already been sent on the Http2Stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_TRAILERS_ALREADY_SENT`" + }, + { + "textRaw": "`ERR_HTTP2_TRAILERS_NOT_READY`", + "name": "`err_http2_trailers_not_ready`", + "desc": "

      The http2stream.sendTrailers() method cannot be called until after the\n'wantTrailers' event is emitted on an Http2Stream object. The\n'wantTrailers' event will only be emitted if the waitForTrailers option\nis set for the Http2Stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_TRAILERS_NOT_READY`" + }, + { + "textRaw": "`ERR_HTTP2_UNSUPPORTED_PROTOCOL`", + "name": "`err_http2_unsupported_protocol`", + "desc": "

      http2.connect() was passed a URL that uses any protocol other than http: or\nhttps:.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_UNSUPPORTED_PROTOCOL`" + }, + { + "textRaw": "`ERR_INTERNAL_ASSERTION`", + "name": "`err_internal_assertion`", + "desc": "

      There was a bug in Node.js or incorrect usage of Node.js internals.\nTo fix the error, open an issue at https://github.com/nodejs/node/issues.

      \n

      ", + "type": "module", + "displayName": "`ERR_INTERNAL_ASSERTION`" + }, + { + "textRaw": "`ERR_INCOMPATIBLE_OPTION_PAIR`", + "name": "`err_incompatible_option_pair`", + "desc": "

      An option pair is incompatible with each other and cannot be used at the same\ntime.

      \n

      ", + "type": "module", + "displayName": "`ERR_INCOMPATIBLE_OPTION_PAIR`" + }, + { + "textRaw": "`ERR_INPUT_TYPE_NOT_ALLOWED`", + "name": "`err_input_type_not_allowed`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      The --input-type flag was used to attempt to execute a file. This flag can\nonly be used with input via --eval, --print or STDIN.

      \n

      ", + "type": "module", + "displayName": "`ERR_INPUT_TYPE_NOT_ALLOWED`" + }, + { + "textRaw": "`ERR_INSPECTOR_ALREADY_ACTIVATED`", + "name": "`err_inspector_already_activated`", + "desc": "

      While using the inspector module, an attempt was made to activate the\ninspector when it already started to listen on a port. Use inspector.close()\nbefore activating it on a different address.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_ALREADY_ACTIVATED`" + }, + { + "textRaw": "`ERR_INSPECTOR_ALREADY_CONNECTED`", + "name": "`err_inspector_already_connected`", + "desc": "

      While using the inspector module, an attempt was made to connect when the\ninspector was already connected.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_ALREADY_CONNECTED`" + }, + { + "textRaw": "`ERR_INSPECTOR_CLOSED`", + "name": "`err_inspector_closed`", + "desc": "

      While using the inspector module, an attempt was made to use the inspector\nafter the session had already closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_CLOSED`" + }, + { + "textRaw": "`ERR_INSPECTOR_COMMAND`", + "name": "`err_inspector_command`", + "desc": "

      An error occurred while issuing a command via the inspector module.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_COMMAND`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_ACTIVE`", + "name": "`err_inspector_not_active`", + "desc": "

      The inspector is not active when inspector.waitForDebugger() is called.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_ACTIVE`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_AVAILABLE`", + "name": "`err_inspector_not_available`", + "desc": "

      The inspector module is not available for use.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_CONNECTED`", + "name": "`err_inspector_not_connected`", + "desc": "

      While using the inspector module, an attempt was made to use the inspector\nbefore it was connected.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_CONNECTED`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_WORKER`", + "name": "`err_inspector_not_worker`", + "desc": "

      An API was called on the main thread that can only be used from\nthe worker thread.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_WORKER`" + }, + { + "textRaw": "`ERR_INVALID_ADDRESS_FAMILY`", + "name": "`err_invalid_address_family`", + "desc": "

      The provided address family is not understood by the Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ADDRESS_FAMILY`" + }, + { + "textRaw": "`ERR_INVALID_ARG_TYPE`", + "name": "`err_invalid_arg_type`", + "desc": "

      An argument of the wrong type was passed to a Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ARG_TYPE`" + }, + { + "textRaw": "`ERR_INVALID_ARG_VALUE`", + "name": "`err_invalid_arg_value`", + "desc": "

      An invalid or unsupported value was passed for a given argument.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ARG_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_ASYNC_ID`", + "name": "`err_invalid_async_id`", + "desc": "

      An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id\nless than -1 should never happen.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ASYNC_ID`" + }, + { + "textRaw": "`ERR_INVALID_BUFFER_SIZE`", + "name": "`err_invalid_buffer_size`", + "desc": "

      A swap was performed on a Buffer but its size was not compatible with the\noperation.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_BUFFER_SIZE`" + }, + { + "textRaw": "`ERR_INVALID_CALLBACK`", + "name": "`err_invalid_callback`", + "desc": "

      A callback function was required but was not been provided to a Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_CALLBACK`" + }, + { + "textRaw": "`ERR_INVALID_CHAR`", + "name": "`err_invalid_char`", + "desc": "

      Invalid characters were detected in headers.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_CHAR`" + }, + { + "textRaw": "`ERR_INVALID_CURSOR_POS`", + "name": "`err_invalid_cursor_pos`", + "desc": "

      A cursor on a given stream cannot be moved to a specified row without a\nspecified column.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_CURSOR_POS`" + }, + { + "textRaw": "`ERR_INVALID_FD`", + "name": "`err_invalid_fd`", + "desc": "

      A file descriptor ('fd') was not valid (e.g. it was a negative value).

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FD`" + }, + { + "textRaw": "`ERR_INVALID_FD_TYPE`", + "name": "`err_invalid_fd_type`", + "desc": "

      A file descriptor ('fd') type was not valid.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FD_TYPE`" + }, + { + "textRaw": "`ERR_INVALID_FILE_URL_HOST`", + "name": "`err_invalid_file_url_host`", + "desc": "

      A Node.js API that consumes file: URLs (such as certain functions in the\nfs module) encountered a file URL with an incompatible host. This\nsituation can only occur on Unix-like systems where only localhost or an empty\nhost is supported.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FILE_URL_HOST`" + }, + { + "textRaw": "`ERR_INVALID_FILE_URL_PATH`", + "name": "`err_invalid_file_url_path`", + "desc": "

      A Node.js API that consumes file: URLs (such as certain functions in the\nfs module) encountered a file URL with an incompatible path. The exact\nsemantics for determining whether a path can be used is platform-dependent.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FILE_URL_PATH`" + }, + { + "textRaw": "`ERR_INVALID_HANDLE_TYPE`", + "name": "`err_invalid_handle_type`", + "desc": "

      An attempt was made to send an unsupported \"handle\" over an IPC communication\nchannel to a child process. See subprocess.send() and process.send()\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_HANDLE_TYPE`" + }, + { + "textRaw": "`ERR_INVALID_HTTP_TOKEN`", + "name": "`err_invalid_http_token`", + "desc": "

      An invalid HTTP token was supplied.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_HTTP_TOKEN`" + }, + { + "textRaw": "`ERR_INVALID_IP_ADDRESS`", + "name": "`err_invalid_ip_address`", + "desc": "

      An IP address is not valid.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_IP_ADDRESS`" + }, + { + "textRaw": "`ERR_INVALID_MODULE_SPECIFIER`", + "name": "`err_invalid_module_specifier`", + "desc": "

      The imported module string is an invalid URL, package name, or package subpath\nspecifier.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_MODULE_SPECIFIER`" + }, + { + "textRaw": "`ERR_INVALID_OPT_VALUE`", + "name": "`err_invalid_opt_value`", + "desc": "

      An invalid or unexpected value was passed in an options object.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_OPT_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_OPT_VALUE_ENCODING`", + "name": "`err_invalid_opt_value_encoding`", + "desc": "

      An invalid or unknown file encoding was passed.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_OPT_VALUE_ENCODING`" + }, + { + "textRaw": "`ERR_INVALID_PACKAGE_CONFIG`", + "name": "`err_invalid_package_config`", + "desc": "

      An invalid package.json file was found which failed parsing.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PACKAGE_CONFIG`" + }, + { + "textRaw": "`ERR_INVALID_PACKAGE_TARGET`", + "name": "`err_invalid_package_target`", + "desc": "

      The package.json \"exports\" field contains an invalid target mapping\nvalue for the attempted module resolution.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PACKAGE_TARGET`" + }, + { + "textRaw": "`ERR_INVALID_PERFORMANCE_MARK`", + "name": "`err_invalid_performance_mark`", + "desc": "

      While using the Performance Timing API (perf_hooks), a performance mark is\ninvalid.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PERFORMANCE_MARK`" + }, + { + "textRaw": "`ERR_INVALID_PROTOCOL`", + "name": "`err_invalid_protocol`", + "desc": "

      An invalid options.protocol was passed to http.request().

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PROTOCOL`" + }, + { + "textRaw": "`ERR_INVALID_REPL_EVAL_CONFIG`", + "name": "`err_invalid_repl_eval_config`", + "desc": "

      Both breakEvalOnSigint and eval options were set in the REPL config,\nwhich is not supported.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_REPL_EVAL_CONFIG`" + }, + { + "textRaw": "`ERR_INVALID_REPL_INPUT`", + "name": "`err_invalid_repl_input`", + "desc": "

      The input may not be used in the REPL. All prohibited inputs are\ndocumented in the REPL's documentation.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_REPL_INPUT`" + }, + { + "textRaw": "`ERR_INVALID_RETURN_PROPERTY`", + "name": "`err_invalid_return_property`", + "desc": "

      Thrown in case a function option does not provide a valid value for one of its\nreturned object properties on execution.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_RETURN_PROPERTY`" + }, + { + "textRaw": "`ERR_INVALID_RETURN_PROPERTY_VALUE`", + "name": "`err_invalid_return_property_value`", + "desc": "

      Thrown in case a function option does not provide an expected value\ntype for one of its returned object properties on execution.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_RETURN_PROPERTY_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_RETURN_VALUE`", + "name": "`err_invalid_return_value`", + "desc": "

      Thrown in case a function option does not return an expected value\ntype on execution, such as when a function is expected to return a promise.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_RETURN_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_SYNC_FORK_INPUT`", + "name": "`err_invalid_sync_fork_input`", + "desc": "

      A Buffer, TypedArray, DataView or string was provided as stdio input to\nan asynchronous fork. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_SYNC_FORK_INPUT`" + }, + { + "textRaw": "`ERR_INVALID_THIS`", + "name": "`err_invalid_this`", + "desc": "

      A Node.js API function was called with an incompatible this value.

      \n
      const urlSearchParams = new URLSearchParams('foo=bar&baz=new');\n\nconst buf = Buffer.alloc(1);\nurlSearchParams.has.call(buf, 'foo');\n// Throws a TypeError with code 'ERR_INVALID_THIS'\n
      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_THIS`" + }, + { + "textRaw": "`ERR_INVALID_TRANSFER_OBJECT`", + "name": "`err_invalid_transfer_object`", + "desc": "

      An invalid transfer object was passed to postMessage().

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_TRANSFER_OBJECT`" + }, + { + "textRaw": "`ERR_INVALID_TUPLE`", + "name": "`err_invalid_tuple`", + "desc": "

      An element in the iterable provided to the WHATWG\nURLSearchParams constructor did not\nrepresent a [name, value] tuple – that is, if an element is not iterable, or\ndoes not consist of exactly two elements.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_TUPLE`" + }, + { + "textRaw": "`ERR_INVALID_URI`", + "name": "`err_invalid_uri`", + "desc": "

      An invalid URI was passed.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_URI`" + }, + { + "textRaw": "`ERR_INVALID_URL`", + "name": "`err_invalid_url`", + "desc": "

      An invalid URL was passed to the WHATWG\nURL constructor to be parsed. The thrown error object\ntypically has an additional property 'input' that contains the URL that failed\nto parse.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_URL`" + }, + { + "textRaw": "`ERR_INVALID_URL_SCHEME`", + "name": "`err_invalid_url_scheme`", + "desc": "

      An attempt was made to use a URL of an incompatible scheme (protocol) for a\nspecific purpose. It is only used in the WHATWG URL API support in the\nfs module (which only accepts URLs with 'file' scheme), but may be used\nin other Node.js APIs as well in the future.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_URL_SCHEME`" + }, + { + "textRaw": "`ERR_IPC_CHANNEL_CLOSED`", + "name": "`err_ipc_channel_closed`", + "desc": "

      An attempt was made to use an IPC communication channel that was already closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_CHANNEL_CLOSED`" + }, + { + "textRaw": "`ERR_IPC_DISCONNECTED`", + "name": "`err_ipc_disconnected`", + "desc": "

      An attempt was made to disconnect an IPC communication channel that was already\ndisconnected. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_DISCONNECTED`" + }, + { + "textRaw": "`ERR_IPC_ONE_PIPE`", + "name": "`err_ipc_one_pipe`", + "desc": "

      An attempt was made to create a child Node.js process using more than one IPC\ncommunication channel. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_ONE_PIPE`" + }, + { + "textRaw": "`ERR_IPC_SYNC_FORK`", + "name": "`err_ipc_sync_fork`", + "desc": "

      An attempt was made to open an IPC communication channel with a synchronously\nforked Node.js process. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_SYNC_FORK`" + }, + { + "textRaw": "`ERR_MANIFEST_ASSERT_INTEGRITY`", + "name": "`err_manifest_assert_integrity`", + "desc": "

      An attempt was made to load a resource, but the resource did not match the\nintegrity defined by the policy manifest. See the documentation for policy\nmanifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_ASSERT_INTEGRITY`" + }, + { + "textRaw": "`ERR_MANIFEST_DEPENDENCY_MISSING`", + "name": "`err_manifest_dependency_missing`", + "desc": "

      An attempt was made to load a resource, but the resource was not listed as a\ndependency from the location that attempted to load it. See the documentation\nfor policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_DEPENDENCY_MISSING`" + }, + { + "textRaw": "`ERR_MANIFEST_INTEGRITY_MISMATCH`", + "name": "`err_manifest_integrity_mismatch`", + "desc": "

      An attempt was made to load a policy manifest, but the manifest had multiple\nentries for a resource which did not match each other. Update the manifest\nentries to match in order to resolve this error. See the documentation for\npolicy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_INTEGRITY_MISMATCH`" + }, + { + "textRaw": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`", + "name": "`err_manifest_invalid_resource_field`", + "desc": "

      A policy manifest resource had an invalid value for one of its fields. Update\nthe manifest entry to match in order to resolve this error. See the\ndocumentation for policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`" + }, + { + "textRaw": "`ERR_MANIFEST_PARSE_POLICY`", + "name": "`err_manifest_parse_policy`", + "desc": "

      An attempt was made to load a policy manifest, but the manifest was unable to\nbe parsed. See the documentation for policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_PARSE_POLICY`" + }, + { + "textRaw": "`ERR_MANIFEST_TDZ`", + "name": "`err_manifest_tdz`", + "desc": "

      An attempt was made to read from a policy manifest, but the manifest\ninitialization has not yet taken place. This is likely a bug in Node.js.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_TDZ`" + }, + { + "textRaw": "`ERR_MANIFEST_UNKNOWN_ONERROR`", + "name": "`err_manifest_unknown_onerror`", + "desc": "

      A policy manifest was loaded, but had an unknown value for its \"onerror\"\nbehavior. See the documentation for policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_UNKNOWN_ONERROR`" + }, + { + "textRaw": "`ERR_MEMORY_ALLOCATION_FAILED`", + "name": "`err_memory_allocation_failed`", + "desc": "

      An attempt was made to allocate memory (usually in the C++ layer) but it\nfailed.

      \n

      ", + "type": "module", + "displayName": "`ERR_MEMORY_ALLOCATION_FAILED`" + }, + { + "textRaw": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`", + "name": "`err_message_target_context_unavailable`", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      A message posted to a MessagePort could not be deserialized in the target\nvm Context. Not all Node.js objects can be successfully instantiated in\nany context at this time, and attempting to transfer them using postMessage()\ncan fail on the receiving side in that case.

      \n

      ", + "type": "module", + "displayName": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`" + }, + { + "textRaw": "`ERR_METHOD_NOT_IMPLEMENTED`", + "name": "`err_method_not_implemented`", + "desc": "

      A method is required but not implemented.

      \n

      ", + "type": "module", + "displayName": "`ERR_METHOD_NOT_IMPLEMENTED`" + }, + { + "textRaw": "`ERR_MISSING_ARGS`", + "name": "`err_missing_args`", + "desc": "

      A required argument of a Node.js API was not passed. This is only used for\nstrict compliance with the API specification (which in some cases may accept\nfunc(undefined) but not func()). In most native Node.js APIs,\nfunc(undefined) and func() are treated identically, and the\nERR_INVALID_ARG_TYPE error code may be used instead.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_ARGS`" + }, + { + "textRaw": "`ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK`", + "name": "`err_missing_dynamic_instantiate_hook`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An ES Module loader hook specified format: 'dynamic' but did not provide\na dynamicInstantiate hook.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK`" + }, + { + "textRaw": "`ERR_MISSING_OPTION`", + "name": "`err_missing_option`", + "desc": "

      For APIs that accept options objects, some options might be mandatory. This code\nis thrown if a required option is missing.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_OPTION`" + }, + { + "textRaw": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`", + "name": "`err_missing_message_port_in_transfer_list`", + "desc": "

      An object that needs to be explicitly listed in the transferList argument\nwas found in the object passed to a postMessage() call, but not provided in\nthe transferList for that call. Usually, this is a MessagePort.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`" + }, + { + "textRaw": "`ERR_MISSING_PASSPHRASE`", + "name": "`err_missing_passphrase`", + "desc": "

      An attempt was made to read an encrypted key without specifying a passphrase.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_PASSPHRASE`" + }, + { + "textRaw": "`ERR_MISSING_PLATFORM_FOR_WORKER`", + "name": "`err_missing_platform_for_worker`", + "desc": "

      The V8 platform used by this instance of Node.js does not support creating\nWorkers. This is caused by lack of embedder support for Workers. In particular,\nthis error will not occur with standard builds of Node.js.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_PLATFORM_FOR_WORKER`" + }, + { + "textRaw": "`ERR_MODULE_NOT_FOUND`", + "name": "`err_module_not_found`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An ES Module could not be resolved.

      \n

      ", + "type": "module", + "displayName": "`ERR_MODULE_NOT_FOUND`" + }, + { + "textRaw": "`ERR_MULTIPLE_CALLBACK`", + "name": "`err_multiple_callback`", + "desc": "

      A callback was called more than once.

      \n

      A callback is almost always meant to only be called once as the query\ncan either be fulfilled or rejected but not both at the same time. The latter\nwould be possible by calling a callback more than once.

      \n

      ", + "type": "module", + "displayName": "`ERR_MULTIPLE_CALLBACK`" + }, + { + "textRaw": "`ERR_NAPI_CONS_FUNCTION`", + "name": "`err_napi_cons_function`", + "desc": "

      While using N-API, a constructor passed was not a function.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_CONS_FUNCTION`" + }, + { + "textRaw": "`ERR_NAPI_INVALID_DATAVIEW_ARGS`", + "name": "`err_napi_invalid_dataview_args`", + "desc": "

      While calling napi_create_dataview(), a given offset was outside the bounds\nof the dataview or offset + length was larger than a length of given buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_INVALID_DATAVIEW_ARGS`" + }, + { + "textRaw": "`ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT`", + "name": "`err_napi_invalid_typedarray_alignment`", + "desc": "

      While calling napi_create_typedarray(), the provided offset was not a\nmultiple of the element size.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT`" + }, + { + "textRaw": "`ERR_NAPI_INVALID_TYPEDARRAY_LENGTH`", + "name": "`err_napi_invalid_typedarray_length`", + "desc": "

      While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_INVALID_TYPEDARRAY_LENGTH`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_CALL_JS`", + "name": "`err_napi_tsfn_call_js`", + "desc": "

      An error occurred while invoking the JavaScript portion of the thread-safe\nfunction.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_CALL_JS`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_GET_UNDEFINED`", + "name": "`err_napi_tsfn_get_undefined`", + "desc": "

      An error occurred while attempting to retrieve the JavaScript undefined\nvalue.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_GET_UNDEFINED`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_START_IDLE_LOOP`", + "name": "`err_napi_tsfn_start_idle_loop`", + "desc": "

      On the main thread, values are removed from the queue associated with the\nthread-safe function in an idle loop. This error indicates that an error\nhas occurred when attempting to start the loop.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_START_IDLE_LOOP`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`", + "name": "`err_napi_tsfn_stop_idle_loop`", + "desc": "

      Once no more items are left in the queue, the idle loop must be suspended. This\nerror indicates that the idle loop has failed to stop.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`" + }, + { + "textRaw": "`ERR_NO_CRYPTO`", + "name": "`err_no_crypto`", + "desc": "

      An attempt was made to use crypto features while Node.js was not compiled with\nOpenSSL crypto support.

      \n

      ", + "type": "module", + "displayName": "`ERR_NO_CRYPTO`" + }, + { + "textRaw": "`ERR_NO_ICU`", + "name": "`err_no_icu`", + "desc": "

      An attempt was made to use features that require ICU, but Node.js was not\ncompiled with ICU support.

      \n

      ", + "type": "module", + "displayName": "`ERR_NO_ICU`" + }, + { + "textRaw": "`ERR_NON_CONTEXT_AWARE_DISABLED`", + "name": "`err_non_context_aware_disabled`", + "desc": "

      A non-context-aware native addon was loaded in a process that disallows them.

      \n

      ", + "type": "module", + "displayName": "`ERR_NON_CONTEXT_AWARE_DISABLED`" + }, + { + "textRaw": "`ERR_OUT_OF_RANGE`", + "name": "`err_out_of_range`", + "desc": "

      A given value is out of the accepted range.

      \n

      ", + "type": "module", + "displayName": "`ERR_OUT_OF_RANGE`" + }, + { + "textRaw": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`", + "name": "`err_package_import_not_defined`", + "desc": "

      The package.json \"imports\" field does not define the given internal\npackage specifier mapping.

      \n

      ", + "type": "module", + "displayName": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`" + }, + { + "textRaw": "`ERR_PACKAGE_PATH_NOT_EXPORTED`", + "name": "`err_package_path_not_exported`", + "desc": "

      The package.json \"exports\" field does not export the requested subpath.\nBecause exports are encapsulated, private internal modules that are not exported\ncannot be imported through the package resolution, unless using an absolute URL.

      \n

      ", + "type": "module", + "displayName": "`ERR_PACKAGE_PATH_NOT_EXPORTED`" + }, + { + "textRaw": "`ERR_PROTO_ACCESS`", + "name": "`err_proto_access`", + "desc": "

      Accessing Object.prototype.__proto__ has been forbidden using\n--disable-proto=throw. Object.getPrototypeOf and\nObject.setPrototypeOf should be used to get and set the prototype of an\nobject.

      \n

      ", + "type": "module", + "displayName": "`ERR_PROTO_ACCESS`" + }, + { + "textRaw": "`ERR_REQUIRE_ESM`", + "name": "`err_require_esm`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An attempt was made to require() an ES Module.

      \n

      ", + "type": "module", + "displayName": "`ERR_REQUIRE_ESM`" + }, + { + "textRaw": "`ERR_SCRIPT_EXECUTION_INTERRUPTED`", + "name": "`err_script_execution_interrupted`", + "desc": "

      Script execution was interrupted by SIGINT (For example,\nCtrl+C was pressed.)

      \n

      ", + "type": "module", + "displayName": "`ERR_SCRIPT_EXECUTION_INTERRUPTED`" + }, + { + "textRaw": "`ERR_SCRIPT_EXECUTION_TIMEOUT`", + "name": "`err_script_execution_timeout`", + "desc": "

      Script execution timed out, possibly due to bugs in the script being executed.

      \n

      ", + "type": "module", + "displayName": "`ERR_SCRIPT_EXECUTION_TIMEOUT`" + }, + { + "textRaw": "`ERR_SERVER_ALREADY_LISTEN`", + "name": "`err_server_already_listen`", + "desc": "

      The server.listen() method was called while a net.Server was already\nlistening. This applies to all instances of net.Server, including HTTP, HTTPS,\nand HTTP/2 Server instances.

      \n

      ", + "type": "module", + "displayName": "`ERR_SERVER_ALREADY_LISTEN`" + }, + { + "textRaw": "`ERR_SERVER_NOT_RUNNING`", + "name": "`err_server_not_running`", + "desc": "

      The server.close() method was called when a net.Server was not\nrunning. This applies to all instances of net.Server, including HTTP, HTTPS,\nand HTTP/2 Server instances.

      \n

      ", + "type": "module", + "displayName": "`ERR_SERVER_NOT_RUNNING`" + }, + { + "textRaw": "`ERR_SOCKET_ALREADY_BOUND`", + "name": "`err_socket_already_bound`", + "desc": "

      An attempt was made to bind a socket that has already been bound.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_ALREADY_BOUND`" + }, + { + "textRaw": "`ERR_SOCKET_BAD_BUFFER_SIZE`", + "name": "`err_socket_bad_buffer_size`", + "desc": "

      An invalid (negative) size was passed for either the recvBufferSize or\nsendBufferSize options in dgram.createSocket().

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BAD_BUFFER_SIZE`" + }, + { + "textRaw": "`ERR_SOCKET_BAD_PORT`", + "name": "`err_socket_bad_port`", + "desc": "

      An API function expecting a port >= 0 and < 65536 received an invalid value.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BAD_PORT`" + }, + { + "textRaw": "`ERR_SOCKET_BAD_TYPE`", + "name": "`err_socket_bad_type`", + "desc": "

      An API function expecting a socket type (udp4 or udp6) received an invalid\nvalue.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BAD_TYPE`" + }, + { + "textRaw": "`ERR_SOCKET_BUFFER_SIZE`", + "name": "`err_socket_buffer_size`", + "desc": "

      While using dgram.createSocket(), the size of the receive or send Buffer\ncould not be determined.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BUFFER_SIZE`" + }, + { + "textRaw": "`ERR_SOCKET_CANNOT_SEND`", + "name": "`err_socket_cannot_send`", + "desc": "

      Data could be sent on a socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_CANNOT_SEND`" + }, + { + "textRaw": "`ERR_SOCKET_CLOSED`", + "name": "`err_socket_closed`", + "desc": "

      An attempt was made to operate on an already closed socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_CLOSED`" + }, + { + "textRaw": "`ERR_SOCKET_DGRAM_IS_CONNECTED`", + "name": "`err_socket_dgram_is_connected`", + "desc": "

      A dgram.connect() call was made on an already connected socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_DGRAM_IS_CONNECTED`" + }, + { + "textRaw": "`ERR_SOCKET_DGRAM_NOT_CONNECTED`", + "name": "`err_socket_dgram_not_connected`", + "desc": "

      A dgram.disconnect() or dgram.remoteAddress() call was made on a\ndisconnected socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_DGRAM_NOT_CONNECTED`" + }, + { + "textRaw": "`ERR_SOCKET_DGRAM_NOT_RUNNING`", + "name": "`err_socket_dgram_not_running`", + "desc": "

      A call was made and the UDP subsystem was not running.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_DGRAM_NOT_RUNNING`" + }, + { + "textRaw": "`ERR_SRI_PARSE`", + "name": "`err_sri_parse`", + "desc": "

      A string was provided for a Subresource Integrity check, but was unable to be\nparsed. Check the format of integrity attributes by looking at the\nSubresource Integrity specification.

      \n

      ", + "type": "module", + "displayName": "`ERR_SRI_PARSE`" + }, + { + "textRaw": "`ERR_STREAM_CANNOT_PIPE`", + "name": "`err_stream_cannot_pipe`", + "desc": "

      An attempt was made to call stream.pipe() on a Writable stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_CANNOT_PIPE`" + }, + { + "textRaw": "`ERR_STREAM_DESTROYED`", + "name": "`err_stream_destroyed`", + "desc": "

      A stream method was called that cannot complete because the stream was\ndestroyed using stream.destroy().

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_DESTROYED`" + }, + { + "textRaw": "`ERR_STREAM_NULL_VALUES`", + "name": "`err_stream_null_values`", + "desc": "

      An attempt was made to call stream.write() with a null chunk.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_NULL_VALUES`" + }, + { + "textRaw": "`ERR_STREAM_PREMATURE_CLOSE`", + "name": "`err_stream_premature_close`", + "desc": "

      An error returned by stream.finished() and stream.pipeline(), when a stream\nor a pipeline ends non gracefully with no explicit error.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_PREMATURE_CLOSE`" + }, + { + "textRaw": "`ERR_STREAM_PUSH_AFTER_EOF`", + "name": "`err_stream_push_after_eof`", + "desc": "

      An attempt was made to call stream.push() after a null(EOF) had been\npushed to the stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_PUSH_AFTER_EOF`" + }, + { + "textRaw": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`", + "name": "`err_stream_unshift_after_end_event`", + "desc": "

      An attempt was made to call stream.unshift() after the 'end' event was\nemitted.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`" + }, + { + "textRaw": "`ERR_STREAM_WRAP`", + "name": "`err_stream_wrap`", + "desc": "

      Prevents an abort if a string decoder was set on the Socket or if the decoder\nis in objectMode.

      \n
      const Socket = require('net').Socket;\nconst instance = new Socket();\n\ninstance.setEncoding('utf8');\n
      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_WRAP`" + }, + { + "textRaw": "`ERR_STREAM_WRITE_AFTER_END`", + "name": "`err_stream_write_after_end`", + "desc": "

      An attempt was made to call stream.write() after stream.end() has been\ncalled.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_WRITE_AFTER_END`" + }, + { + "textRaw": "`ERR_STRING_TOO_LONG`", + "name": "`err_string_too_long`", + "desc": "

      An attempt has been made to create a string longer than the maximum allowed\nlength.

      \n

      ", + "type": "module", + "displayName": "`ERR_STRING_TOO_LONG`" + }, + { + "textRaw": "`ERR_SYNTHETIC`", + "name": "`err_synthetic`", + "desc": "

      An artificial error object used to capture the call stack for diagnostic\nreports.

      \n

      ", + "type": "module", + "displayName": "`ERR_SYNTHETIC`" + }, + { + "textRaw": "`ERR_SYSTEM_ERROR`", + "name": "`err_system_error`", + "desc": "

      An unspecified or non-specific system error has occurred within the Node.js\nprocess. The error object will have an err.info object property with\nadditional details.

      \n

      ", + "type": "module", + "displayName": "`ERR_SYSTEM_ERROR`" + }, + { + "textRaw": "`ERR_TLS_CERT_ALTNAME_INVALID`", + "name": "`err_tls_cert_altname_invalid`", + "desc": "

      While using TLS, the host name/IP of the peer did not match any of the\nsubjectAltNames in its certificate.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_CERT_ALTNAME_INVALID`" + }, + { + "textRaw": "`ERR_TLS_DH_PARAM_SIZE`", + "name": "`err_tls_dh_param_size`", + "desc": "

      While using TLS, the parameter offered for the Diffie-Hellman (DH)\nkey-agreement protocol is too small. By default, the key length must be greater\nthan or equal to 1024 bits to avoid vulnerabilities, even though it is strongly\nrecommended to use 2048 bits or larger for stronger security.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_DH_PARAM_SIZE`" + }, + { + "textRaw": "`ERR_TLS_HANDSHAKE_TIMEOUT`", + "name": "`err_tls_handshake_timeout`", + "desc": "

      A TLS/SSL handshake timed out. In this case, the server must also abort the\nconnection.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_HANDSHAKE_TIMEOUT`" + }, + { + "textRaw": "`ERR_TLS_INVALID_CONTEXT`", + "name": "`err_tls_invalid_context`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      The context must be a SecureContext.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_CONTEXT`" + }, + { + "textRaw": "`ERR_TLS_INVALID_STATE`", + "name": "`err_tls_invalid_state`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      The TLS socket must be connected and securily established. Ensure the 'secure'\nevent is emitted before continuing.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_STATE`" + }, + { + "textRaw": "`ERR_TLS_INVALID_PROTOCOL_METHOD`", + "name": "`err_tls_invalid_protocol_method`", + "desc": "

      The specified secureProtocol method is invalid. It is either unknown, or\ndisabled because it is insecure.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_PROTOCOL_METHOD`" + }, + { + "textRaw": "`ERR_TLS_INVALID_PROTOCOL_VERSION`", + "name": "`err_tls_invalid_protocol_version`", + "desc": "

      Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_PROTOCOL_VERSION`" + }, + { + "textRaw": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`", + "name": "`err_tls_protocol_version_conflict`", + "desc": "

      Attempting to set a TLS protocol minVersion or maxVersion conflicts with an\nattempt to set the secureProtocol explicitly. Use one mechanism or the other.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`" + }, + { + "textRaw": "`ERR_TLS_RENEGOTIATION_DISABLED`", + "name": "`err_tls_renegotiation_disabled`", + "desc": "

      An attempt was made to renegotiate TLS on a socket instance with TLS disabled.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_RENEGOTIATION_DISABLED`" + }, + { + "textRaw": "`ERR_TLS_REQUIRED_SERVER_NAME`", + "name": "`err_tls_required_server_name`", + "desc": "

      While using TLS, the server.addContext() method was called without providing\na host name in the first parameter.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_REQUIRED_SERVER_NAME`" + }, + { + "textRaw": "`ERR_TLS_SESSION_ATTACK`", + "name": "`err_tls_session_attack`", + "desc": "

      An excessive amount of TLS renegotiations is detected, which is a potential\nvector for denial-of-service attacks.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_SESSION_ATTACK`" + }, + { + "textRaw": "`ERR_TLS_SNI_FROM_SERVER`", + "name": "`err_tls_sni_from_server`", + "desc": "

      An attempt was made to issue Server Name Indication from a TLS server-side\nsocket, which is only valid from a client.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_SNI_FROM_SERVER`" + }, + { + "textRaw": "`ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`", + "name": "`err_tls_psk_set_identiy_hint_failed`", + "desc": "

      Failed to set PSK identity hint. Hint may be too long.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`" + }, + { + "textRaw": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`", + "name": "`err_trace_events_category_required`", + "desc": "

      The trace_events.createTracing() method requires at least one trace event\ncategory.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`" + }, + { + "textRaw": "`ERR_TRACE_EVENTS_UNAVAILABLE`", + "name": "`err_trace_events_unavailable`", + "desc": "

      The trace_events module could not be loaded because Node.js was compiled with\nthe --without-v8-platform flag.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRACE_EVENTS_UNAVAILABLE`" + }, + { + "textRaw": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`", + "name": "`err_transferring_externalized_sharedarraybuffer`", + "desc": "

      A SharedArrayBuffer whose memory is not managed by the JavaScript engine\nor by Node.js was encountered during serialization. Such a SharedArrayBuffer\ncannot be serialized.

      \n

      This can only happen when native addons create SharedArrayBuffers in\n\"externalized\" mode, or put existing SharedArrayBuffer into externalized mode.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`" + }, + { + "textRaw": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`", + "name": "`err_transform_already_transforming`", + "desc": "

      A Transform stream finished while it was still transforming.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`" + }, + { + "textRaw": "`ERR_TRANSFORM_WITH_LENGTH_0`", + "name": "`err_transform_with_length_0`", + "desc": "

      A Transform stream finished with data still in the write buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRANSFORM_WITH_LENGTH_0`" + }, + { + "textRaw": "`ERR_TTY_INIT_FAILED`", + "name": "`err_tty_init_failed`", + "desc": "

      The initialization of a TTY failed due to a system error.

      \n

      ", + "type": "module", + "displayName": "`ERR_TTY_INIT_FAILED`" + }, + { + "textRaw": "`ERR_UNAVAILABLE_DURING_EXIT`", + "name": "`err_unavailable_during_exit`", + "desc": "

      Function was called within a process.on('exit') handler that shouldn't be\ncalled within process.on('exit') handler.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNAVAILABLE_DURING_EXIT`" + }, + { + "textRaw": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`", + "name": "`err_uncaught_exception_capture_already_set`", + "desc": "

      process.setUncaughtExceptionCaptureCallback() was called twice,\nwithout first resetting the callback to null.

      \n

      This error is designed to prevent accidentally overwriting a callback registered\nfrom another module.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`" + }, + { + "textRaw": "`ERR_UNESCAPED_CHARACTERS`", + "name": "`err_unescaped_characters`", + "desc": "

      A string that contained unescaped characters was received.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNESCAPED_CHARACTERS`" + }, + { + "textRaw": "`ERR_UNHANDLED_ERROR`", + "name": "`err_unhandled_error`", + "desc": "

      An unhandled error occurred (for instance, when an 'error' event is emitted\nby an EventEmitter but an 'error' handler is not registered).

      \n

      ", + "type": "module", + "displayName": "`ERR_UNHANDLED_ERROR`" + }, + { + "textRaw": "`ERR_UNKNOWN_BUILTIN_MODULE`", + "name": "`err_unknown_builtin_module`", + "desc": "

      Used to identify a specific kind of internal Node.js error that should not\ntypically be triggered by user code. Instances of this error point to an\ninternal bug within the Node.js binary itself.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_BUILTIN_MODULE`" + }, + { + "textRaw": "`ERR_UNKNOWN_CREDENTIAL`", + "name": "`err_unknown_credential`", + "desc": "

      A Unix group or user identifier that does not exist was passed.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_CREDENTIAL`" + }, + { + "textRaw": "`ERR_UNKNOWN_ENCODING`", + "name": "`err_unknown_encoding`", + "desc": "

      An invalid or unknown encoding option was passed to an API.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_ENCODING`" + }, + { + "textRaw": "`ERR_UNKNOWN_FILE_EXTENSION`", + "name": "`err_unknown_file_extension`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An attempt was made to load a module with an unknown or unsupported file\nextension.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_FILE_EXTENSION`" + }, + { + "textRaw": "`ERR_UNKNOWN_MODULE_FORMAT`", + "name": "`err_unknown_module_format`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An attempt was made to load a module with an unknown or unsupported format.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_MODULE_FORMAT`" + }, + { + "textRaw": "`ERR_UNKNOWN_SIGNAL`", + "name": "`err_unknown_signal`", + "desc": "

      An invalid or unknown process signal was passed to an API expecting a valid\nsignal (such as subprocess.kill()).

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_SIGNAL`" + }, + { + "textRaw": "`ERR_UNSUPPORTED_DIR_IMPORT`", + "name": "`err_unsupported_dir_import`", + "desc": "

      import a directory URL is unsupported. Instead,\nself-reference a package using its name and define a custom subpath in\nthe \"exports\" field of the package.json file.

      \n\n
      import './'; // unsupported\nimport './index.js'; // supported\nimport 'package-name'; // supported\n
      \n

      ", + "type": "module", + "displayName": "`ERR_UNSUPPORTED_DIR_IMPORT`" + }, + { + "textRaw": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`", + "name": "`err_unsupported_esm_url_scheme`", + "desc": "

      import with URL schemes other than file and data is unsupported.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`" + }, + { + "textRaw": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`", + "name": "`err_valid_performance_entry_type`", + "desc": "

      While using the Performance Timing API (perf_hooks), no valid performance\nentry types were found.

      \n

      ", + "type": "module", + "displayName": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`" + }, + { + "textRaw": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`", + "name": "`err_vm_dynamic_import_callback_missing`", + "desc": "

      A dynamic import callback was not specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`" + }, + { + "textRaw": "`ERR_VM_MODULE_ALREADY_LINKED`", + "name": "`err_vm_module_already_linked`", + "desc": "

      The module attempted to be linked is not eligible for linking, because of one of\nthe following reasons:

      \n
        \n
      • It has already been linked (linkingStatus is 'linked')
      • \n
      • It is being linked (linkingStatus is 'linking')
      • \n
      • Linking has failed for this module (linkingStatus is 'errored')
      • \n
      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_ALREADY_LINKED`" + }, + { + "textRaw": "`ERR_VM_MODULE_CACHED_DATA_REJECTED`", + "name": "`err_vm_module_cached_data_rejected`", + "desc": "

      The cachedData option passed to a module constructor is invalid.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_CACHED_DATA_REJECTED`" + }, + { + "textRaw": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`", + "name": "`err_vm_module_cannot_create_cached_data`", + "desc": "

      Cached data cannot be created for modules which have already been evaluated.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`" + }, + { + "textRaw": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`", + "name": "`err_vm_module_different_context`", + "desc": "

      The module being returned from the linker function is from a different context\nthan the parent module. Linked modules must share the same context.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`" + }, + { + "textRaw": "`ERR_VM_MODULE_LINKING_ERRORED`", + "name": "`err_vm_module_linking_errored`", + "desc": "

      The linker function returned a module for which linking has failed.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_LINKING_ERRORED`" + }, + { + "textRaw": "`ERR_VM_MODULE_NOT_MODULE`", + "name": "`err_vm_module_not_module`", + "desc": "

      The fulfilled value of a linking promise is not a vm.Module object.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_NOT_MODULE`" + }, + { + "textRaw": "`ERR_VM_MODULE_STATUS`", + "name": "`err_vm_module_status`", + "desc": "

      The current module's status does not allow for this operation. The specific\nmeaning of the error depends on the specific function.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_STATUS`" + }, + { + "textRaw": "`ERR_WASI_ALREADY_STARTED`", + "name": "`err_wasi_already_started`", + "desc": "

      The WASI instance has already started.

      \n

      ", + "type": "module", + "displayName": "`ERR_WASI_ALREADY_STARTED`" + }, + { + "textRaw": "`ERR_WASI_NOT_STARTED`", + "name": "`err_wasi_not_started`", + "desc": "

      The WASI instance has not been started.

      \n

      ", + "type": "module", + "displayName": "`ERR_WASI_NOT_STARTED`" + }, + { + "textRaw": "`ERR_WORKER_INIT_FAILED`", + "name": "`err_worker_init_failed`", + "desc": "

      The Worker initialization failed.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_INIT_FAILED`" + }, + { + "textRaw": "`ERR_WORKER_INVALID_EXEC_ARGV`", + "name": "`err_worker_invalid_exec_argv`", + "desc": "

      The execArgv option passed to the Worker constructor contains\ninvalid flags.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_INVALID_EXEC_ARGV`" + }, + { + "textRaw": "`ERR_WORKER_NOT_RUNNING`", + "name": "`err_worker_not_running`", + "desc": "

      An operation failed because the Worker instance is not currently running.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_NOT_RUNNING`" + }, + { + "textRaw": "`ERR_WORKER_OUT_OF_MEMORY`", + "name": "`err_worker_out_of_memory`", + "desc": "

      The Worker instance terminated because it reached its memory limit.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_OUT_OF_MEMORY`" + }, + { + "textRaw": "`ERR_WORKER_PATH`", + "name": "`err_worker_path`", + "desc": "

      The path for the main script of a worker is neither an absolute path\nnor a relative path starting with ./ or ../.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_PATH`" + }, + { + "textRaw": "`ERR_WORKER_UNSERIALIZABLE_ERROR`", + "name": "`err_worker_unserializable_error`", + "desc": "

      All attempts at serializing an uncaught exception from a worker thread failed.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_UNSERIALIZABLE_ERROR`" + }, + { + "textRaw": "`ERR_WORKER_UNSUPPORTED_EXTENSION`", + "name": "`err_worker_unsupported_extension`", + "desc": "

      The pathname used for the main script of a worker has an\nunknown file extension.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_UNSUPPORTED_EXTENSION`" + }, + { + "textRaw": "`ERR_WORKER_UNSUPPORTED_OPERATION`", + "name": "`err_worker_unsupported_operation`", + "desc": "

      The requested functionality is not supported in worker threads.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_UNSUPPORTED_OPERATION`" + }, + { + "textRaw": "`ERR_ZLIB_INITIALIZATION_FAILED`", + "name": "`err_zlib_initialization_failed`", + "desc": "

      Creation of a zlib object failed due to incorrect configuration.

      \n

      ", + "type": "module", + "displayName": "`ERR_ZLIB_INITIALIZATION_FAILED`" + }, + { + "textRaw": "`HPE_HEADER_OVERFLOW`", + "name": "`hpe_header_overflow`", + "meta": { + "changes": [ + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/commit/186035243fad247e3955f", + "description": "Max header size in `http_parser` was set to 8KB." + } + ] + }, + "desc": "

      Too much HTTP header data was received. In order to protect against malicious or\nmalconfigured clients, if more than 8KB of HTTP header data is received then\nHTTP parsing will abort without a request or response object being created, and\nan Error with this code will be emitted.

      \n

      ", + "type": "module", + "displayName": "`HPE_HEADER_OVERFLOW`" + }, + { + "textRaw": "`HPE_UNEXPECTED_CONTENT_LENGTH`", + "name": "`hpe_unexpected_content_length`", + "desc": "

      Server is sending both a Content-Length header and Transfer-Encoding: chunked.

      \n

      Transfer-Encoding: chunked allows the server to maintain an HTTP persistent\nconnection for dynamically generated content.\nIn this case, the Content-Length HTTP header cannot be used.

      \n

      Use Content-Length or Transfer-Encoding: chunked.

      \n

      ", + "type": "module", + "displayName": "`HPE_UNEXPECTED_CONTENT_LENGTH`" + }, + { + "textRaw": "`MODULE_NOT_FOUND`", + "name": "`module_not_found`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25690", + "description": "Added `requireStack` property." + } + ] + }, + "desc": "

      A module file could not be resolved while attempting a require() or\nimport operation.

      ", + "type": "module", + "displayName": "`MODULE_NOT_FOUND`" + } + ], + "type": "misc", + "displayName": "Node.js error codes" + }, + { + "textRaw": "Legacy Node.js error codes", + "name": "legacy_node.js_error_codes", + "stability": 0, + "stabilityText": "Deprecated. These error codes are either inconsistent, or have\nbeen removed.", + "desc": "

      ", + "modules": [ + { + "textRaw": "`ERR_CANNOT_TRANSFER_OBJECT`", + "name": "`err_cannot_transfer_object`", + "desc": "\n

      The value passed to postMessage() contained an object that is not supported\nfor transferring.

      \n

      ", + "type": "module", + "displayName": "`ERR_CANNOT_TRANSFER_OBJECT`" + }, + { + "textRaw": "`ERR_CLOSED_MESSAGE_PORT`", + "name": "`err_closed_message_port`", + "meta": { + "added": [ + "v10.5.0" + ], + "removed": [ + "v11.12.0" + ], + "changes": [] + }, + "desc": "

      There was an attempt to use a MessagePort instance in a closed\nstate, usually after .close() has been called.

      \n

      ", + "type": "module", + "displayName": "`ERR_CLOSED_MESSAGE_PORT`" + }, + { + "textRaw": "`ERR_CRYPTO_HASH_DIGEST_NO_UTF16`", + "name": "`err_crypto_hash_digest_no_utf16`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      The UTF-16 encoding was used with hash.digest(). While the\nhash.digest() method does allow an encoding argument to be passed in,\ncausing the method to return a string rather than a Buffer, the UTF-16\nencoding (e.g. ucs or utf16le) is not supported.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_HASH_DIGEST_NO_UTF16`" + }, + { + "textRaw": "`ERR_HTTP2_FRAME_ERROR`", + "name": "`err_http2_frame_error`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a failure occurs sending an individual frame on the HTTP/2\nsession.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_FRAME_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_HEADERS_OBJECT`", + "name": "`err_http2_headers_object`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an HTTP/2 Headers Object is expected.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADERS_OBJECT`" + }, + { + "textRaw": "`ERR_HTTP2_HEADER_REQUIRED`", + "name": "`err_http2_header_required`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a required header is missing in an HTTP/2 message.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADER_REQUIRED`" + }, + { + "textRaw": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`", + "name": "`err_http2_info_headers_after_respond`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      HTTP/2 informational headers must only be sent prior to calling the\nHttp2Stream.prototype.respond() method.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_CLOSED`", + "name": "`err_http2_stream_closed`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an action has been performed on an HTTP/2 Stream that has already\nbeen closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_CLOSED`" + }, + { + "textRaw": "`ERR_HTTP_INVALID_CHAR`", + "name": "`err_http_invalid_char`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an invalid character is found in an HTTP response status message\n(reason phrase).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_INVALID_CHAR`" + }, + { + "textRaw": "`ERR_INDEX_OUT_OF_RANGE`", + "name": "`err_index_out_of_range`", + "meta": { + "added": [ + "v10.0.0" + ], + "removed": [ + "v11.0.0" + ], + "changes": [] + }, + "desc": "

      A given index was out of the accepted range (e.g. negative offsets).

      \n

      ", + "type": "module", + "displayName": "`ERR_INDEX_OUT_OF_RANGE`" + }, + { + "textRaw": "`ERR_NAPI_CONS_PROTOTYPE_OBJECT`", + "name": "`err_napi_cons_prototype_object`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used by the N-API when Constructor.prototype is not an object.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_CONS_PROTOTYPE_OBJECT`" + }, + { + "textRaw": "`ERR_NO_LONGER_SUPPORTED`", + "name": "`err_no_longer_supported`", + "desc": "

      A Node.js API was called in an unsupported manner, such as\nBuffer.write(string, encoding, offset[, length]).

      \n

      ", + "type": "module", + "displayName": "`ERR_NO_LONGER_SUPPORTED`" + }, + { + "textRaw": "`ERR_OUTOFMEMORY`", + "name": "`err_outofmemory`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used generically to identify that an operation caused an out of memory\ncondition.

      \n

      ", + "type": "module", + "displayName": "`ERR_OUTOFMEMORY`" + }, + { + "textRaw": "`ERR_PARSE_HISTORY_DATA`", + "name": "`err_parse_history_data`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      The repl module was unable to parse data from the REPL history file.

      \n

      ", + "type": "module", + "displayName": "`ERR_PARSE_HISTORY_DATA`" + }, + { + "textRaw": "`ERR_STDERR_CLOSE`", + "name": "`err_stderr_close`", + "meta": { + "removed": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/23053", + "description": "Rather than emitting an error, `process.stderr.end()` now only closes the stream side but not the underlying resource, making this error obsolete." + } + ] + }, + "desc": "

      An attempt was made to close the process.stderr stream. By design, Node.js\ndoes not allow stdout or stderr streams to be closed by user code.

      \n

      ", + "type": "module", + "displayName": "`ERR_STDERR_CLOSE`" + }, + { + "textRaw": "`ERR_STDOUT_CLOSE`", + "name": "`err_stdout_close`", + "meta": { + "removed": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/23053", + "description": "Rather than emitting an error, `process.stderr.end()` now only closes the stream side but not the underlying resource, making this error obsolete." + } + ] + }, + "desc": "

      An attempt was made to close the process.stdout stream. By design, Node.js\ndoes not allow stdout or stderr streams to be closed by user code.

      \n

      ", + "type": "module", + "displayName": "`ERR_STDOUT_CLOSE`" + }, + { + "textRaw": "`ERR_STREAM_READ_NOT_IMPLEMENTED`", + "name": "`err_stream_read_not_implemented`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an attempt is made to use a readable stream that has not implemented\nreadable._read().

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_READ_NOT_IMPLEMENTED`" + }, + { + "textRaw": "`ERR_TLS_RENEGOTIATION_FAILED`", + "name": "`err_tls_renegotiation_failed`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a TLS renegotiation request has failed in a non-specific way.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_RENEGOTIATION_FAILED`" + }, + { + "textRaw": "`ERR_UNKNOWN_BUILTIN_MODULE`", + "name": "`err_unknown_builtin_module`", + "meta": { + "added": [ + "v8.0.0" + ], + "removed": [ + "v9.0.0" + ], + "changes": [] + }, + "desc": "

      The 'ERR_UNKNOWN_BUILTIN_MODULE' error code is used to identify a specific\nkind of internal Node.js error that should not typically be triggered by user\ncode. Instances of this error point to an internal bug within the Node.js\nbinary itself.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_BUILTIN_MODULE`" + }, + { + "textRaw": "`ERR_UNKNOWN_STDIN_TYPE`", + "name": "`err_unknown_stdin_type`", + "meta": { + "added": [ + "v8.0.0" + ], + "removed": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      An attempt was made to launch a Node.js process with an unknown stdin file\ntype. This error is usually an indication of a bug within Node.js itself,\nalthough it is possible for user code to trigger it.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_STDIN_TYPE`" + }, + { + "textRaw": "`ERR_UNKNOWN_STREAM_TYPE`", + "name": "`err_unknown_stream_type`", + "meta": { + "added": [ + "v8.0.0" + ], + "removed": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      An attempt was made to launch a Node.js process with an unknown stdout or\nstderr file type. This error is usually an indication of a bug within Node.js\nitself, although it is possible for user code to trigger it.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_STREAM_TYPE`" + }, + { + "textRaw": "`ERR_V8BREAKITERATOR`", + "name": "`err_v8breakiterator`", + "desc": "

      The V8 BreakIterator API was used but the full ICU data set is not installed.

      \n

      ", + "type": "module", + "displayName": "`ERR_V8BREAKITERATOR`" + }, + { + "textRaw": "`ERR_VALUE_OUT_OF_RANGE`", + "name": "`err_value_out_of_range`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a given value is out of the accepted range.

      \n

      ", + "type": "module", + "displayName": "`ERR_VALUE_OUT_OF_RANGE`" + }, + { + "textRaw": "`ERR_VM_MODULE_NOT_LINKED`", + "name": "`err_vm_module_not_linked`", + "desc": "

      The module must be successfully linked before instantiation.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_NOT_LINKED`" + }, + { + "textRaw": "`ERR_ZLIB_BINDING_CLOSED`", + "name": "`err_zlib_binding_closed`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an attempt is made to use a zlib object after it has already been\nclosed.

      ", + "type": "module", + "displayName": "`ERR_ZLIB_BINDING_CLOSED`" + } + ], + "type": "misc", + "displayName": "Legacy Node.js error codes" + } + ], + "classes": [ + { + "textRaw": "Class: `Error`", + "type": "class", + "name": "Error", + "desc": "

      A generic JavaScript <Error> object that does not denote any specific\ncircumstance of why the error occurred. Error objects capture a \"stack trace\"\ndetailing the point in the code at which the Error was instantiated, and may\nprovide a text description of the error.

      \n

      All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

      ", + "methods": [ + { + "textRaw": "`Error.captureStackTrace(targetObject[, constructorOpt])`", + "type": "method", + "name": "captureStackTrace", + "signatures": [ + { + "params": [ + { + "textRaw": "`targetObject` {Object}", + "name": "targetObject", + "type": "Object" + }, + { + "textRaw": "`constructorOpt` {Function}", + "name": "constructorOpt", + "type": "Function" + } + ] + } + ], + "desc": "

      Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

      \n
      const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack;  // Similar to `new Error().stack`\n
      \n

      The first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.

      \n

      The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

      \n

      The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:

      \n
      function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
      " + } + ], + "properties": [ + { + "textRaw": "`stackTraceLimit` {number}", + "type": "number", + "name": "stackTraceLimit", + "desc": "

      The Error.stackTraceLimit property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack or\nError.captureStackTrace(obj)).

      \n

      The default value is 10 but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.

      \n

      If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string label that identifies the kind of error.\nerror.code is the most stable way to identify an error. It will only change\nbetween major versions of Node.js. In contrast, error.message strings may\nchange between any versions of Node.js. See Node.js error codes for details\nabout specific codes.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      The error.message property is the string description of the error as set by\ncalling new Error(message). The message passed to the constructor will also\nappear in the first line of the stack trace of the Error, however changing\nthis property after the Error object is created may not change the first\nline of the stack trace (for example, when error.stack is read before this\nproperty is changed).

      \n
      const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
      " + }, + { + "textRaw": "`stack` {string}", + "type": "string", + "name": "stack", + "desc": "

      The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.

      \n
      Error: Things keep happening!\n   at /home/gbusey/file.js:525:2\n   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n   at increaseSynergy (/home/gbusey/actors.js:701:6)\n
      \n

      The first line is formatted as <error class name>: <error message>, and\nis followed by a series of stack frames (each line beginning with \"at \").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.

      \n

      Frames are only generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called cheetahify which\nitself calls a JavaScript function, the frame representing the cheetahify call\nwill not be present in the stack traces:

      \n
      const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n  // `cheetahify()` *synchronously* calls speedy.\n  cheetahify(function speedy() {\n    throw new Error('oh no!');\n  });\n}\n\nmakeFaster();\n// will throw:\n//   /home/gbusey/file.js:6\n//       throw new Error('oh no!');\n//           ^\n//   Error: oh no!\n//       at speedy (/home/gbusey/file.js:6:11)\n//       at makeFaster (/home/gbusey/file.js:5:3)\n//       at Object.<anonymous> (/home/gbusey/file.js:10:1)\n//       at Module._compile (module.js:456:26)\n//       at Object.Module._extensions..js (module.js:474:10)\n//       at Module.load (module.js:356:32)\n//       at Function.Module._load (module.js:312:12)\n//       at Function.Module.runMain (module.js:497:10)\n//       at startup (node.js:119:16)\n//       at node.js:906:3\n
      \n

      The location information will be one of:

      \n
        \n
      • native, if the frame represents a call internal to V8 (as in [].forEach).
      • \n
      • plain-filename.js:line:column, if the frame represents a call internal\nto Node.js.
      • \n
      • /absolute/path/to/file.js:line:column, if the frame represents a call in\na user program, or its dependencies.
      • \n
      \n

      The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

      \n

      The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit or the number of available frames on the current event\nloop tick.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ], + "desc": "

      Creates a new Error object and sets the error.message property to the\nprovided text message. If an object is passed as message, the text message\nis generated by calling message.toString(). The error.stack property will\nrepresent the point in the code at which new Error() was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit, whichever is smaller.

      " + } + ] + }, + { + "textRaw": "Class: `AssertionError`", + "type": "class", + "name": "AssertionError", + "desc": "\n

      Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.

      " + }, + { + "textRaw": "Class: `RangeError`", + "type": "class", + "name": "RangeError", + "desc": "\n

      Indicates that a provided argument was not within the set or range of\nacceptable values for a function; whether that is a numeric range, or\noutside the set of options for a given function parameter.

      \n
      require('net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n
      \n

      Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

      " + }, + { + "textRaw": "Class: `ReferenceError`", + "type": "class", + "name": "ReferenceError", + "desc": "\n

      Indicates that an attempt is being made to access a variable that is not\ndefined. Such errors commonly indicate typos in code, or an otherwise broken\nprogram.

      \n

      While client code may generate and propagate these errors, in practice, only V8\nwill do so.

      \n
      doesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n
      \n

      Unless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.

      " + }, + { + "textRaw": "Class: `SyntaxError`", + "type": "class", + "name": "SyntaxError", + "desc": "\n

      Indicates that a program is not valid JavaScript. These errors may only be\ngenerated and propagated as a result of code evaluation. Code evaluation may\nhappen as a result of eval, Function, require, or vm. These errors\nare almost always indicative of a broken program.

      \n
      try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n  // 'err' will be a SyntaxError.\n}\n
      \n

      SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

      " + }, + { + "textRaw": "Class: `SystemError`", + "type": "class", + "name": "SystemError", + "desc": "\n

      Node.js generates system errors when exceptions occur within its runtime\nenvironment. These usually occur when an application violates an operating\nsystem constraint. For example, a system error will occur if an application\nattempts to read a file that does not exist.

      \n
        \n
      • address <string> If present, the address to which a network connection\nfailed
      • \n
      • code <string> The string error code
      • \n
      • dest <string> If present, the file path destination when reporting a file\nsystem error
      • \n
      • errno <number> | <string> The system-provided error number
      • \n
      • info <Object> If present, extra details about the error condition
      • \n
      • message <string> A system-provided human-readable description of the error
      • \n
      • path <string> If present, the file path when reporting a file system error
      • \n
      • port <number> If present, the network connection port that is not available
      • \n
      • syscall <string> The name of the system call that triggered the error
      • \n
      ", + "properties": [ + { + "textRaw": "`address` {string}", + "type": "string", + "name": "address", + "desc": "

      If present, error.address is a string describing the address to which a\nnetwork connection failed.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string representing the error code.

      " + }, + { + "textRaw": "`dest` {string}", + "type": "string", + "name": "dest", + "desc": "

      If present, error.dest is the file path destination when reporting a file\nsystem error.

      " + }, + { + "textRaw": "`errno` {string|number}", + "type": "string|number", + "name": "errno", + "desc": "

      The error.errno property is a number or a string. If it is a number, it is a\nnegative value which corresponds to the error code defined in\nlibuv Error handling. See the libuv errno.h header file\n(deps/uv/include/uv/errno.h in the Node.js source tree) for details. In case\nof a string, it is the same as error.code.

      " + }, + { + "textRaw": "`info` {Object}", + "type": "Object", + "name": "info", + "desc": "

      If present, error.info is an object with details about the error condition.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      error.message is a system-provided human-readable description of the error.

      " + }, + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "desc": "

      If present, error.path is a string containing a relevant invalid pathname.

      " + }, + { + "textRaw": "`port` {number}", + "type": "number", + "name": "port", + "desc": "

      If present, error.port is the network connection port that is not available.

      " + }, + { + "textRaw": "`syscall` {string}", + "type": "string", + "name": "syscall", + "desc": "

      The error.syscall property is a string describing the syscall that failed.

      " + } + ], + "modules": [ + { + "textRaw": "Common system errors", + "name": "common_system_errors", + "desc": "

      This is a list of system errors commonly-encountered when writing a Node.js\nprogram. For a comprehensive list, see the errno(3) man page.

      \n
        \n
      • \n

        EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.

        \n
      • \n
      • \n

        EADDRINUSE (Address already in use): An attempt to bind a server\n(net, http, or https) to a local address failed due to\nanother server on the local system already occupying that address.

        \n
      • \n
      • \n

        ECONNREFUSED (Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.

        \n
      • \n
      • \n

        ECONNRESET (Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http\nand net modules.

        \n
      • \n
      • \n

        EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.

        \n
      • \n
      • \n

        EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.

        \n
      • \n
      • \n

        EMFILE (Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, macOS) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048 in the same shell that will run the Node.js process.

        \n
      • \n
      • \n

        ENOENT (No such file or directory): Commonly raised by fs operations\nto indicate that a component of the specified pathname does not exist. No\nentity (file or directory) could be found by the given path.

        \n
      • \n
      • \n

        ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.

        \n
      • \n
      • \n

        ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.

        \n
      • \n
      • \n

        ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

        \n
      • \n
      • \n

        EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.

        \n
      • \n
      • \n

        EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net and\nhttp layers, indicative that the remote side of the stream being\nwritten to has been closed.

        \n
      • \n
      • \n

        ETIMEDOUT (Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http or net. Often a sign that a socket.end()\nwas not properly called.

        \n
      • \n
      ", + "type": "module", + "displayName": "Common system errors" + } + ] + }, + { + "textRaw": "Class: `TypeError`", + "type": "class", + "name": "TypeError", + "desc": "\n

      Indicates that a provided argument is not an allowable type. For example,\npassing a function to a parameter which expects a string would be a TypeError.

      \n
      require('url').parse(() => { });\n// Throws TypeError, since it expected a string.\n
      \n

      Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

      " + } + ] + }, + { + "textRaw": "Global objects", + "name": "Global objects", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      These objects are available in all modules. The following variables may appear\nto be global but are not. They exist only in the scope of modules, see the\nmodule system documentation:

      \n\n

      The objects listed here are specific to Node.js. There are built-in objects\nthat are part of the JavaScript language itself, which are also globally\naccessible.

      ", + "globals": [ + { + "textRaw": "Class: `Buffer`", + "type": "global", + "name": "Buffer", + "meta": { + "added": [ + "v0.1.103" + ], + "changes": [] + }, + "desc": "\n

      Used to handle binary data. See the buffer section.

      " + }, + { + "textRaw": "`clearImmediate(immediateObject)`", + "type": "global", + "name": "clearImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      clearImmediate is described in the timers section.

      " + }, + { + "textRaw": "`clearInterval(intervalObject)`", + "type": "global", + "name": "clearInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearInterval is described in the timers section.

      " + }, + { + "textRaw": "`clearTimeout(timeoutObject)`", + "type": "global", + "name": "clearTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearTimeout is described in the timers section.

      " + }, + { + "textRaw": "`console`", + "name": "`console`", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      Used to print to stdout and stderr. See the console section.

      " + }, + { + "textRaw": "`global`", + "name": "`global`", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "type": "global", + "desc": "
        \n
      • <Object> The global namespace object.
      • \n
      \n

      In browsers, the top-level scope is the global scope. This means that\nwithin the browser var something will define a new global variable. In\nNode.js this is different. The top-level scope is not the global scope;\nvar something inside a Node.js module will be local to that module.

      " + }, + { + "textRaw": "`process`", + "name": "`process`", + "meta": { + "added": [ + "v0.1.7" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The process object. See the process object section.

      " + }, + { + "textRaw": "`queueMicrotask(callback)`", + "type": "global", + "name": "queueMicrotask", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "desc": "\n

      The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.

      \n

      The microtask queue is managed by V8 and may be used in a similar manner to\nthe process.nextTick() queue, which is managed by Node.js. The\nprocess.nextTick() queue is always processed before the microtask queue\nwithin each turn of the Node.js event loop.

      \n
      // Here, `queueMicrotask()` is used to ensure the 'load' event is always\n// emitted asynchronously, and therefore consistently. Using\n// `process.nextTick()` here would result in the 'load' event always emitting\n// before any other promise jobs.\n\nDataHandler.prototype.load = async function load(key) {\n  const hit = this._cache.get(url);\n  if (hit !== undefined) {\n    queueMicrotask(() => {\n      this.emit('load', hit);\n    });\n    return;\n  }\n\n  const data = await fetchData(key);\n  this._cache.set(url, data);\n  this.emit('load', data);\n};\n
      " + }, + { + "textRaw": "`setImmediate(callback[, ...args])`", + "type": "global", + "name": "setImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      setImmediate is described in the timers section.

      " + }, + { + "textRaw": "`setInterval(callback, delay[, ...args])`", + "type": "global", + "name": "setInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setInterval is described in the timers section.

      " + }, + { + "textRaw": "`setTimeout(callback, delay[, ...args])`", + "type": "global", + "name": "setTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setTimeout is described in the timers section.

      " + }, + { + "textRaw": "`TextDecoder`", + "name": "`TextDecoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextDecoder class. See the TextDecoder section.

      " + }, + { + "textRaw": "`TextEncoder`", + "name": "`TextEncoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextEncoder class. See the TextEncoder section.

      " + }, + { + "textRaw": "`URL`", + "name": "`URL`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URL class. See the URL section.

      " + }, + { + "textRaw": "`URLSearchParams`", + "name": "`URLSearchParams`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URLSearchParams class. See the URLSearchParams section.

      " + }, + { + "textRaw": "`WebAssembly`", + "name": "`WebAssembly`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.

      " + } + ], + "miscs": [ + { + "textRaw": "`__dirname`", + "name": "`__dirname`", + "desc": "

      This variable may appear to be global but is not. See __dirname.

      ", + "type": "misc", + "displayName": "`__dirname`" + }, + { + "textRaw": "`__filename`", + "name": "`__filename`", + "desc": "

      This variable may appear to be global but is not. See __filename.

      ", + "type": "misc", + "displayName": "`__filename`" + }, + { + "textRaw": "`exports`", + "name": "`exports`", + "desc": "

      This variable may appear to be global but is not. See exports.

      ", + "type": "misc", + "displayName": "`exports`" + }, + { + "textRaw": "`module`", + "name": "`module`", + "desc": "

      This variable may appear to be global but is not. See module.

      ", + "type": "misc", + "displayName": "`module`" + } + ], + "methods": [ + { + "textRaw": "`require()`", + "type": "method", + "name": "require", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This variable may appear to be global but is not. See require().

      " + } + ] + }, + { + "textRaw": "Internationalization support", + "name": "Internationalization support", + "introduced_in": "v8.2.0", + "type": "misc", + "desc": "

      Node.js has many features that make it easier to write internationalized\nprograms. Some of them are:

      \n\n

      Node.js (and its underlying V8 engine) uses ICU to implement these features\nin native C/C++ code. However, some of them require a very large ICU data file\nin order to support all locales of the world. Because it is expected that most\nNode.js users will make use of only a small portion of ICU functionality, only\na subset of the full ICU data set is provided by Node.js by default. Several\noptions are provided for customizing and expanding the ICU data set either when\nbuilding or running Node.js.

      ", + "miscs": [ + { + "textRaw": "Options for building Node.js", + "name": "options_for_building_node.js", + "desc": "

      To control how ICU is used in Node.js, four configure options are available\nduring compilation. Additional details on how to compile Node.js are documented\nin BUILDING.md.

      \n
        \n
      • --with-intl=none/--without-intl
      • \n
      • --with-intl=system-icu
      • \n
      • --with-intl=small-icu (default)
      • \n
      • --with-intl=full-icu
      • \n
      \n

      An overview of available Node.js and JavaScript features for each configure\noption:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      nonesystem-icusmall-icufull-icu
      String.prototype.normalize()none (function is no-op)fullfullfull
      String.prototype.to*Case()fullfullfullfull
      Intlnone (object does not exist)partial/full (depends on OS)partial (English-only)full
      String.prototype.localeCompare()partial (not locale-aware)fullfullfull
      String.prototype.toLocale*Case()partial (not locale-aware)fullfullfull
      Number.prototype.toLocaleString()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      Date.prototype.toLocale*String()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      WHATWG URL Parserpartial (no IDN support)fullfullfull
      require('buffer').transcode()none (function does not exist)fullfullfull
      REPLpartial (inaccurate line editing)fullfullfull
      require('util').TextDecoderpartial (basic encodings support)partial/full (depends on OS)partial (Unicode-only)full
      RegExp Unicode Property Escapesnone (invalid RegExp error)fullfullfull
      \n

      The \"(not locale-aware)\" designation denotes that the function carries out its\noperation just like the non-Locale version of the function, if one\nexists. For example, under none mode, Date.prototype.toLocaleString()'s\noperation is identical to that of Date.prototype.toString().

      ", + "modules": [ + { + "textRaw": "Disable all internationalization features (`none`)", + "name": "disable_all_internationalization_features_(`none`)", + "desc": "

      If this option is chosen, most internationalization features mentioned above\nwill be unavailable in the resulting node binary.

      ", + "type": "module", + "displayName": "Disable all internationalization features (`none`)" + }, + { + "textRaw": "Build with a pre-installed ICU (`system-icu`)", + "name": "build_with_a_pre-installed_icu_(`system-icu`)", + "desc": "

      Node.js can link against an ICU build already installed on the system. In fact,\nmost Linux distributions already come with ICU installed, and this option would\nmake it possible to reuse the same set of data used by other components in the\nOS.

      \n

      Functionalities that only require the ICU library itself, such as\nString.prototype.normalize() and the WHATWG URL parser, are fully\nsupported under system-icu. Features that require ICU locale data in\naddition, such as Intl.DateTimeFormat may be fully or partially\nsupported, depending on the completeness of the ICU data installed on the\nsystem.

      ", + "type": "module", + "displayName": "Build with a pre-installed ICU (`system-icu`)" + }, + { + "textRaw": "Embed a limited set of ICU data (`small-icu`)", + "name": "embed_a_limited_set_of_icu_data_(`small-icu`)", + "desc": "

      This option makes the resulting binary link against the ICU library statically,\nand includes a subset of ICU data (typically only the English locale) within\nthe node executable.

      \n

      Functionalities that only require the ICU library itself, such as\nString.prototype.normalize() and the WHATWG URL parser, are fully\nsupported under small-icu. Features that require ICU locale data in addition,\nsuch as Intl.DateTimeFormat, generally only work with the English locale:

      \n
      const january = new Date(9e8);\nconst english = new Intl.DateTimeFormat('en', { month: 'long' });\nconst spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n\nconsole.log(english.format(january));\n// Prints \"January\"\nconsole.log(spanish.format(january));\n// Prints \"M01\" on small-icu\n// Should print \"enero\"\n
      \n

      This mode provides a good balance between features and binary size, and it is\nthe default behavior if no --with-intl flag is passed. The official binaries\nare also built in this mode.

      ", + "modules": [ + { + "textRaw": "Providing ICU data at runtime", + "name": "providing_icu_data_at_runtime", + "desc": "

      If the small-icu option is used, one can still provide additional locale data\nat runtime so that the JS methods would work for all ICU locales. Assuming the\ndata file is stored at /some/directory, it can be made available to ICU\nthrough either:

      \n
        \n
      • \n

        The NODE_ICU_DATA environment variable:

        \n
        env NODE_ICU_DATA=/some/directory node\n
        \n
      • \n
      • \n

        The --icu-data-dir CLI parameter:

        \n
        node --icu-data-dir=/some/directory\n
        \n
      • \n
      \n

      (If both are specified, the --icu-data-dir CLI parameter takes precedence.)

      \n

      ICU is able to automatically find and load a variety of data formats, but the\ndata must be appropriate for the ICU version, and the file correctly named.\nThe most common name for the data file is icudt6X[bl].dat, where 6X denotes\nthe intended ICU version, and b or l indicates the system's endianness.\nCheck \"ICU Data\" article in the ICU User Guide for other supported formats\nand more details on ICU data in general.

      \n

      The full-icu npm module can greatly simplify ICU data installation by\ndetecting the ICU version of the running node executable and downloading the\nappropriate data file. After installing the module through npm i full-icu,\nthe data file will be available at ./node_modules/full-icu. This path can be\nthen passed either to NODE_ICU_DATA or --icu-data-dir as shown above to\nenable full Intl support.

      ", + "type": "module", + "displayName": "Providing ICU data at runtime" + } + ], + "type": "module", + "displayName": "Embed a limited set of ICU data (`small-icu`)" + }, + { + "textRaw": "Embed the entire ICU (`full-icu`)", + "name": "embed_the_entire_icu_(`full-icu`)", + "desc": "

      This option makes the resulting binary link against ICU statically and include\na full set of ICU data. A binary created this way has no further external\ndependencies and supports all locales, but might be rather large. See\nBUILDING.md on how to compile a binary using this mode.

      ", + "type": "module", + "displayName": "Embed the entire ICU (`full-icu`)" + } + ], + "type": "misc", + "displayName": "Options for building Node.js" + }, + { + "textRaw": "Detecting internationalization support", + "name": "detecting_internationalization_support", + "desc": "

      To verify that ICU is enabled at all (system-icu, small-icu, or\nfull-icu), simply checking the existence of Intl should suffice:

      \n
      const hasICU = typeof Intl === 'object';\n
      \n

      Alternatively, checking for process.versions.icu, a property defined only\nwhen ICU is enabled, works too:

      \n
      const hasICU = typeof process.versions.icu === 'string';\n
      \n

      To check for support for a non-English locale (i.e. full-icu or\nsystem-icu), Intl.DateTimeFormat can be a good distinguishing factor:

      \n
      const hasFullICU = (() => {\n  try {\n    const january = new Date(9e8);\n    const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n    return spanish.format(january) === 'enero';\n  } catch (err) {\n    return false;\n  }\n})();\n
      \n

      For more verbose tests for Intl support, the following resources may be found\nto be helpful:

      \n
        \n
      • btest402: Generally used to check whether Node.js with Intl support is\nbuilt correctly.
      • \n
      • Test262: ECMAScript's official conformance test suite includes a section\ndedicated to ECMA-402.
      • \n
      ", + "type": "misc", + "displayName": "Detecting internationalization support" + } + ] + }, + { + "textRaw": "Modules: ECMAScript modules", + "name": "Modules: ECMAScript modules", + "introduced_in": "v8.5.0", + "type": "misc", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": [ + "v12.22.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/35781", + "description": "Stabilize modules implementation." + }, + { + "version": [ + "v12.20.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/35249", + "description": "Support for detection of CommonJS named exports." + }, + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/31974", + "description": "Remove experimental modules warning." + }, + { + "version": [ + "v12.17.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29866", + "description": "Loading ECMAScript modules no longer requires a command-line flag." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26745", + "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." + } + ] + }, + "stability": 2, + "stabilityText": "Stable", + "miscs": [ + { + "textRaw": "Introduction", + "name": "esm", + "desc": "

      ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import and\nexport statements.

      \n

      The following example of an ES module exports a function:

      \n
      // addTwo.mjs\nfunction addTwo(num) {\n  return num + 2;\n}\n\nexport { addTwo };\n
      \n

      The following example of an ES module imports the function from addTwo.mjs:

      \n
      // app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
      \n

      Node.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.

      \n\n

      \n\n

      ", + "type": "misc", + "displayName": "esm" + }, + { + "textRaw": "Enabling", + "name": "Enabling", + "type": "misc", + "desc": "

      Node.js treats JavaScript code as CommonJS modules by default.\nAuthors can tell Node.js to treat JavaScript code as ECMAScript modules\nvia the .mjs file extension, the package.json \"type\" field, or the\n--input-type flag. See\nModules: Packages for more\ndetails.

      \n\n

      \n\n\n\n\n\n\n\n\n\n\n\n\n

      " + }, + { + "textRaw": "Packages", + "name": "packages", + "desc": "

      This section was moved to Modules: Packages.

      ", + "type": "misc", + "displayName": "Packages" + }, + { + "textRaw": "`import` Specifiers", + "name": "`import`_specifiers", + "modules": [ + { + "textRaw": "Terminology", + "name": "terminology", + "desc": "

      The specifier of an import statement is the string after the from keyword,\ne.g. 'path' in import { sep } from 'path'. Specifiers are also used in\nexport from statements, and as the argument to an import() expression.

      \n

      There are four types of specifiers:

      \n
        \n
      • \n

        Bare specifiers like 'some-package'. They refer to an entry point of a\npackage by the package name.

        \n
      • \n
      • \n

        Deep import specifiers like 'some-package/lib/shuffle.mjs'. They refer to\na path within a package prefixed by the package name.

        \n
      • \n
      • \n

        Relative specifiers like './startup.js' or '../config.mjs'. They refer\nto a path relative to the location of the importing file.

        \n
      • \n
      • \n

        Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer\ndirectly and explicitly to a full path.

        \n
      • \n
      \n

      Bare specifiers, and the bare specifier portion of deep import specifiers, are\nstrings; but everything else in a specifier is a URL.

      \n

      file:, node:, and data: URLs are supported. A specifier like\n'https://example.com/app.js' may be supported by browsers but it is not\nsupported in Node.js.

      \n

      Specifiers may not begin with / or //. These are reserved for potential\nfuture use. The root of the current volume may be referenced via file:///.

      ", + "modules": [ + { + "textRaw": "`node:` Imports", + "name": "`node:`_imports", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "desc": "

      node: URLs are supported as a means to load Node.js builtin modules. This\nURL scheme allows for builtin modules to be referenced by valid absolute URL\nstrings.

      \n
      import fs from 'node:fs/promises';\n
      ", + "type": "module", + "displayName": "`node:` Imports" + }, + { + "textRaw": "`data:` Imports", + "name": "`data:`_imports", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      data: URLs are supported for importing with the following MIME types:

      \n
        \n
      • text/javascript for ES Modules
      • \n
      • application/json for JSON
      • \n
      • application/wasm for Wasm
      • \n
      \n

      data: URLs only resolve Bare specifiers for builtin modules\nand Absolute specifiers. Resolving\nRelative specifiers does not work because data: is not a\nspecial scheme. For example, attempting to load ./foo\nfrom data:text/javascript,import \"./foo\"; fails to resolve because there\nis no concept of relative resolution for data: URLs. An example of a data:\nURLs being used is:

      \n
      import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
      ", + "type": "module", + "displayName": "`data:` Imports" + } + ], + "type": "module", + "displayName": "Terminology" + } + ], + "type": "misc", + "displayName": "`import` Specifiers" + }, + { + "textRaw": "Differences between ES modules and CommonJS", + "name": "differences_between_es_modules_and_commonjs", + "modules": [ + { + "textRaw": "Mandatory file extensions", + "name": "mandatory_file_extensions", + "desc": "

      A file extension must be provided when using the import keyword. Directory\nindexes (e.g. './startup/index.js') must also be fully specified.

      \n

      This behavior matches how import behaves in browser environments, assuming a\ntypically configured server.

      ", + "type": "module", + "displayName": "Mandatory file extensions" + }, + { + "textRaw": "No `NODE_PATH`", + "name": "no_`node_path`", + "desc": "

      NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.

      ", + "type": "module", + "displayName": "No `NODE_PATH`" + }, + { + "textRaw": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`", + "name": "no_`require`,_`exports`,_`module.exports`,_`__filename`,_`__dirname`", + "desc": "

      These CommonJS variables are not available in ES modules.

      \n

      require can be imported into an ES module using module.createRequire().

      \n

      Equivalents of __filename and __dirname can be created inside of each file\nvia import.meta.url.

      \n
      import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n
      ", + "type": "module", + "displayName": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`" + }, + { + "textRaw": "No `require.resolve`", + "name": "no_`require.resolve`", + "desc": "

      Former use cases relying on require.resolve to determine the resolved path\nof a module can be supported via import.meta.resolve, which is experimental\nand supported via the --experimental-import-meta-resolve flag:

      \n
      (async () => {\n  const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n})();\n
      \n

      import.meta.resolve also accepts a second argument which is the parent module\nfrom which to resolve from:

      \n
      (async () => {\n  // Equivalent to import.meta.resolve('./dep')\n  await import.meta.resolve('./dep', import.meta.url);\n})();\n
      \n

      This function is asynchronous because the ES module resolver in Node.js is\nasynchronous. With the introduction of Top-Level Await, these use cases\nwill be easier as they won't require an async function wrapper.

      ", + "type": "module", + "displayName": "No `require.resolve`" + }, + { + "textRaw": "No `require.extensions`", + "name": "no_`require.extensions`", + "desc": "

      require.extensions is not used by import. The expectation is that loader\nhooks can provide this workflow in the future.

      ", + "type": "module", + "displayName": "No `require.extensions`" + }, + { + "textRaw": "No `require.cache`", + "name": "no_`require.cache`", + "desc": "

      require.cache is not used by import. It has a separate cache.

      ", + "type": "module", + "displayName": "No `require.cache`" + }, + { + "textRaw": "URL-based paths", + "name": "url-based_paths", + "desc": "

      ES modules are resolved and cached based upon\nURL semantics. This means that files containing\nspecial characters such as # and ? need to be escaped.

      \n

      Modules are loaded multiple times if the import specifier used to resolve\nthem has a different query or fragment.

      \n
      import './foo.mjs?query=1'; // loads ./foo.mjs with query of \"?query=1\"\nimport './foo.mjs?query=2'; // loads ./foo.mjs with query of \"?query=2\"\n
      \n

      For now, only modules using the file: protocol can be loaded.

      ", + "type": "module", + "displayName": "URL-based paths" + } + ], + "type": "misc", + "displayName": "Differences between ES modules and CommonJS" + }, + { + "textRaw": "Interoperability with CommonJS", + "name": "interoperability_with_commonjs", + "modules": [ + { + "textRaw": "`require`", + "name": "`require`", + "desc": "

      require always treats the files it references as CommonJS. This applies\nwhether require is used the traditional way within a CommonJS environment, or\nin an ES module environment using module.createRequire().

      \n

      To include an ES module into CommonJS, use import().

      ", + "type": "module", + "displayName": "`require`" + }, + { + "textRaw": "`import` statements", + "name": "`import`_statements", + "desc": "

      An import statement can reference an ES module or a CommonJS module.\nimport statements are permitted only in ES modules. For similar functionality\nin CommonJS, see import().

      \n

      When importing CommonJS modules, the\nmodule.exports object is provided as the default export. Named exports may be\navailable, provided by static analysis as a convenience for better ecosystem\ncompatibility.

      \n

      Additional experimental flags are available for importing\nWasm modules or\nJSON modules. For importing native modules or\nJSON modules unflagged, see module.createRequire().

      \n

      The specifier of an import statement (the string after the from keyword)\ncan either be an URL-style relative path like './file.mjs' or a package name\nlike 'fs'.

      \n

      Like in CommonJS, files within packages can be accessed by appending a path to\nthe package name; unless the package’s package.json contains an\n\"exports\" field, in which case files within packages need to be accessed\nvia the path defined in \"exports\".

      \n
      import { sin, cos } from 'geometry/trigonometry-functions.mjs';\n
      ", + "type": "module", + "displayName": "`import` statements" + }, + { + "textRaw": "`import()` expressions", + "name": "`import()`_expressions", + "desc": "

      Dynamic import() is supported in both CommonJS and ES modules. It can be\nused to include ES module files from CommonJS code.

      ", + "type": "module", + "displayName": "`import()` expressions" + } + ], + "type": "misc", + "displayName": "Interoperability with CommonJS" + }, + { + "textRaw": "CommonJS Namespaces", + "name": "commonjs_namespaces", + "desc": "

      CommonJS modules consist of a module.exports object which can be of any type.

      \n

      When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:

      \n\n
      import { default as cjs } from 'cjs';\n\n// The following import statement is \"syntax sugar\" (equivalent but sweeter)\n// for `{ default as cjsSugar }` in the above import statement:\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n//   <module.exports>\n//   true\n
      \n

      The ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default export key pointing to the CommonJS\nmodule.exports value.

      \n

      This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:

      \n\n
      import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n//   [Module] { default: <module.exports> }\n//   true\n
      \n

      For better compatibility with existing usage in the JS ecosystem, Node.js\nin addition attempts to determine the CommonJS named exports of every imported\nCommonJS module to provide them as separate ES module exports using a static\nanalysis process.

      \n

      For example, consider a CommonJS module written:

      \n
      // cjs.cjs\nexports.name = 'exported';\n
      \n

      The preceding module supports named imports in ES modules:

      \n\n
      import { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }\n
      \n

      As can be seen from the last example of the Module Namespace Exotic Object being\nlogged, the name export is copied off of the module.exports object and set\ndirectly on the ES module namespace when the module is imported.

      \n

      Live binding updates or new exports added to module.exports are not detected\nfor these named exports.

      \n

      The detection of named exports is based on common syntax patterns but does not\nalways correctly detect named exports. In these cases, using the default\nimport form described above can be a better option.

      \n

      Named exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See cjs-module-lexer for the exact\nsemantics implemented.

      ", + "type": "misc", + "displayName": "CommonJS Namespaces" + }, + { + "textRaw": "Builtin modules", + "name": "builtin_modules", + "desc": "

      Core modules provide named exports of their public API. A\ndefault export is also provided which is the value of the CommonJS exports.\nThe default export can be used for, among other things, modifying the named\nexports. Named exports of builtin modules are updated only by calling\nmodule.syncBuiltinESMExports().

      \n
      import EventEmitter from 'events';\nconst e = new EventEmitter();\n
      \n
      import { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});\n
      \n
      import fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
      ", + "type": "misc", + "displayName": "Builtin modules" + }, + { + "textRaw": "CommonJS, JSON, and native modules", + "name": "commonjs,_json,_and_native_modules", + "desc": "

      CommonJS, JSON, and native modules can be used with\nmodule.createRequire().

      \n
      // cjs.cjs\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\n\nconst require = createRequire(import.meta.url);\n\nconst cjs = require('./cjs.cjs');\ncjs === 'cjs'; // true\n
      ", + "type": "misc", + "displayName": "CommonJS, JSON, and native modules" + }, + { + "textRaw": "Experimental JSON modules", + "name": "experimental_json_modules", + "desc": "

      Currently importing JSON modules are only supported in the commonjs mode\nand are loaded using the CJS loader. WHATWG JSON modules specification are\nstill being standardized, and are experimentally supported by including the\nadditional flag --experimental-json-modules when running Node.js.

      \n

      When the --experimental-json-modules flag is included, both the\ncommonjs and module mode use the new experimental JSON\nloader. The imported JSON only exposes a default. There is no\nsupport for named exports. A cache entry is created in the CommonJS\ncache to avoid duplication. The same object is returned in\nCommonJS if the JSON module has already been imported from the\nsame path.

      \n

      Assuming an index.mjs with

      \n\n
      import packageConfig from './package.json';\n
      \n

      The --experimental-json-modules flag is needed for the module\nto work.

      \n
      node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n
      ", + "type": "misc", + "displayName": "Experimental JSON modules" + }, + { + "textRaw": "Experimental Wasm modules", + "name": "experimental_wasm_modules", + "desc": "

      Importing Web Assembly modules is supported under the\n--experimental-wasm-modules flag, allowing any .wasm files to be\nimported as normal modules while also supporting their module imports.

      \n

      This integration is in line with the\nES Module Integration Proposal for Web Assembly.

      \n

      For example, an index.mjs containing:

      \n
      import * as M from './module.wasm';\nconsole.log(M);\n
      \n

      executed under:

      \n
      node --experimental-wasm-modules index.mjs\n
      \n

      would provide the exports interface for the instantiation of module.wasm.

      ", + "type": "misc", + "displayName": "Experimental Wasm modules" + }, + { + "textRaw": "Experimental loaders", + "name": "Experimental loaders", + "type": "misc", + "desc": "

      Note: This API is currently being redesigned and will still change.

      \n

      To customize the default module resolution, loader hooks can optionally be\nprovided via a --experimental-loader ./loader-name.mjs argument to Node.js.

      \n

      When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.

      ", + "miscs": [ + { + "textRaw": "Hooks", + "name": "hooks", + "methods": [ + { + "textRaw": "`resolve(specifier, context, defaultResolve)`", + "type": "method", + "name": "resolve", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The resolve hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an import statement or\nimport() expression, and the parent URL is the URL of the module that imported\nthis one, or undefined if this is the main entry point for the application.

      \n

      The conditions property on the context is an array of conditions for\nConditional exports that apply to this resolution request. They can be used\nfor looking up conditional mappings elsewhere or to modify the list when calling\nthe default resolution logic.

      \n

      The current package exports conditions are always in\nthe context.conditions array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve, the\ncontext.conditions array passed to it must include all elements of the\ncontext.conditions array originally passed into the resolve hook.

      \n
      /**\n * @param {string} specifier\n * @param {{\n *   conditions: !Array<string>,\n *   parentURL: !(string | undefined),\n * }} context\n * @param {Function} defaultResolve\n * @returns {Promise<{ url: string }>}\n */\nexport async function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all specifiers, do some custom logic for resolving.\n    // Always return an object of the form {url: <string>}.\n    return {\n      url: parentURL ?\n        new URL(specifier, parentURL).href :\n        new URL(specifier).href,\n    };\n  }\n  if (Math.random() < 0.5) { // Another condition.\n    // When calling `defaultResolve`, the arguments can be modified. In this\n    // case it's adding another value for matching conditional exports.\n    return defaultResolve(specifier, {\n      ...context,\n      conditions: [...context.conditions, 'another-condition'],\n    });\n  }\n  // Defer to Node.js for all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n
      " + }, + { + "textRaw": "`getFormat(url, context, defaultGetFormat)`", + "type": "method", + "name": "getFormat", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The getFormat hook provides a way to define a custom method of determining how\na URL should be interpreted. The format returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      formatDescriptionAcceptable Types For source Returned by getSource or transformSource
      'builtin'Load a Node.js builtin moduleNot applicable
      'dynamic'Use a dynamic instantiate hookNot applicable
      'commonjs'Load a Node.js CommonJS moduleNot applicable
      'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
      'module'Load an ES module{ string, ArrayBuffer, TypedArray }
      'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
      \n

      Note: These types all correspond to classes defined in ECMAScript.

      \n\n

      Note: If the source value of a text-based format (i.e., 'json', 'module') is\nnot a string, it is converted to a string using util.TextDecoder.

      \n
      /**\n * @param {string} url\n * @param {Object} context (currently empty)\n * @param {Function} defaultGetFormat\n * @returns {Promise<{ format: string }>}\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for determining format.\n    // Always return an object of the form {format: <string>}, where the\n    // format is one of the strings in the preceding table.\n    return {\n      format: 'module',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n
      " + }, + { + "textRaw": "`getSource(url, context, defaultGetSource)`", + "type": "method", + "name": "getSource", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The getSource hook provides a way to define a custom method for retrieving\nthe source code of an ES module specifier. This would allow a loader to\npotentially avoid reading files from disk.

      \n
      /**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function getSource(url, context, defaultGetSource) {\n  const { format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for retrieving the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
      " + }, + { + "textRaw": "`transformSource(source, context, defaultTransformSource)`", + "type": "method", + "name": "transformSource", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js\n
      \n
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The transformSource hook provides a way to modify the source code of a loaded\nES module file after the source string has been loaded but before Node.js has\ndone anything with it.

      \n

      If this hook is used to convert unknown-to-Node.js file types into executable\nJavaScript, a resolve hook is also necessary in order to register any\nunknown-to-Node.js file extensions. See the transpiler loader example below.

      \n
      /**\n * @param {!(string | SharedArrayBuffer | Uint8Array)} source\n * @param {{\n *   format: string,\n *   url: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for modifying the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
      " + }, + { + "textRaw": "`getGlobalPreloadCode()`", + "type": "method", + "name": "getGlobalPreloadCode", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      Sometimes it might be necessary to run some code inside of the same global scope\nthat the application runs in. This hook allows the return of a string that is\nrun as sloppy-mode script on startup.

      \n

      Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string).

      \n

      If the code needs more advanced require features, it has to construct\nits own require using module.createRequire().

      \n
      /**\n * @returns {string} Code to run before application startup\n */\nexport function getGlobalPreloadCode() {\n  return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\n\nconst require = createRequire(process.cwd() + '/<preload>');\n// [...]\n`;\n}\n
      " + } + ], + "modules": [ + { + "textRaw": "dynamicInstantiate hook", + "name": "dynamicinstantiate_hook", + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n

      To create a custom dynamic module that doesn't correspond to one of the\nexisting format interpretations, the dynamicInstantiate hook can be used.\nThis hook is called only for modules that return format: 'dynamic' from\nthe getFormat hook.

      \n
      /**\n * @param {string} url\n * @returns {object} response\n * @returns {array} response.exports\n * @returns {function} response.execute\n */\nexport async function dynamicInstantiate(url) {\n  return {\n    exports: ['customExportName'],\n    execute: (exports) => {\n      // Get and set functions provided for pre-allocated export names\n      exports.customExportName.set('value');\n    }\n  };\n}\n
      \n

      With the list of module exports provided upfront, the execute function will\nthen be called at the exact point of module evaluation order for that module\nin the import tree.

      \n

      Examples

      \n

      The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.

      ", + "type": "module", + "displayName": "dynamicInstantiate hook" + }, + { + "textRaw": "HTTPS loader", + "name": "https_loader", + "desc": "

      In current Node.js, specifiers starting with https:// are unsupported. The\nloader below registers hooks to enable rudimentary support for such specifiers.\nWhile this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.

      \n
      // https-loader.mjs\nimport { get } from 'https';\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n\n  // Normally Node.js would error on specifiers starting with 'https://', so\n  // this hook intercepts them and converts them into absolute URLs to be\n  // passed along to the later hooks below.\n  if (specifier.startsWith('https://')) {\n    return {\n      url: specifier\n    };\n  } else if (parentURL && parentURL.startsWith('https://')) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // This loader assumes all network-provided JavaScript is ES module code.\n  if (url.startsWith('https://')) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function getSource(url, context, defaultGetSource) {\n  // For JavaScript to be loaded over the network, we need to fetch and\n  // return it.\n  if (url.startsWith('https://')) {\n    return new Promise((resolve, reject) => {\n      get(url, (res) => {\n        let data = '';\n        res.on('data', (chunk) => data += chunk);\n        res.on('end', () => resolve({ source: data }));\n      }).on('error', (err) => reject(err));\n    });\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
      \n
      // main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
      \n

      With the preceding loader, running\nnode --experimental-loader ./https-loader.mjs ./main.mjs\nprints the current version of CoffeeScript per the module at the URL in\nmain.mjs.

      ", + "type": "module", + "displayName": "HTTPS loader" + }, + { + "textRaw": "Transpiler loader", + "name": "transpiler_loader", + "desc": "

      Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the transformSource hook. Before that hook gets called,\nhowever, other hooks need to tell Node.js not to throw an error on unknown file\ntypes; and to tell Node.js how to load this new file type.

      \n

      This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.

      \n
      // coffeescript-loader.mjs\nimport { URL, pathToFileURL } from 'url';\nimport CoffeeScript from 'coffeescript';\n\nconst baseURL = pathToFileURL(`${process.cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = baseURL } = context;\n\n  // Node.js normally errors on unknown file extensions, so return a URL for\n  // specifiers ending in the CoffeeScript file extensions.\n  if (extensionsRegex.test(specifier)) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // Now that we patched resolve to let CoffeeScript URLs through, we need to\n  // tell Node.js what format such URLs should be interpreted as. For the\n  // purposes of this loader, all CoffeeScript URLs are ES modules.\n  if (extensionsRegex.test(url)) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n\n  if (extensionsRegex.test(url)) {\n    return {\n      source: CoffeeScript.compile(source, { bare: true })\n    };\n  }\n\n  // Let Node.js handle all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
      \n
      # main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
      \n
      # scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
      \n

      With the preceding loader, running\nnode --experimental-loader ./coffeescript-loader.mjs main.coffee\ncauses main.coffee to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any .coffee,\n.litcoffee or .coffee.md files referenced via import statements of any\nloaded file.

      ", + "type": "module", + "displayName": "Transpiler loader" + } + ], + "type": "misc", + "displayName": "Hooks" + } + ] + }, + { + "textRaw": "Resolution algorithm", + "name": "resolution_algorithm", + "modules": [ + { + "textRaw": "Features", + "name": "features", + "desc": "

      The resolver has the following properties:

      \n
        \n
      • FileURL-based resolution as is used by ES modules
      • \n
      • Support for builtin module loading
      • \n
      • Relative and absolute URL resolution
      • \n
      • No default extensions
      • \n
      • No folder mains
      • \n
      • Bare specifier package resolution lookup through node_modules
      • \n
      ", + "type": "module", + "displayName": "Features" + }, + { + "textRaw": "Resolver algorithm", + "name": "resolver_algorithm", + "desc": "

      The algorithm to load an ES module specifier is given through the\nESM_RESOLVE method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.

      \n

      The algorithm to determine the module format of a resolved URL is\nprovided by ESM_FORMAT, which returns the unique module\nformat for any file. The \"module\" format is returned for an ECMAScript\nModule, while the \"commonjs\" format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as \"addon\" can be extended in\nfuture updates.

      \n

      In the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.

      \n

      defaultConditions is the conditional environment name array,\n[\"node\", \"import\"].

      \n

      The resolver can throw the following errors:

      \n
        \n
      • Invalid Module Specifier: Module specifier is an invalid URL, package name\nor package subpath specifier.
      • \n
      • Invalid Package Configuration: package.json configuration is invalid or\ncontains an invalid configuration.
      • \n
      • Invalid Package Target: Package exports or imports define a target module\nfor the package that is an invalid type or string target.
      • \n
      • Package Path Not Exported: Package exports do not define or permit a target\nsubpath in the package for the given module.
      • \n
      • Package Import Not Defined: Package imports do not define the specifier.
      • \n
      • Module Not Found: The package or module requested does not exist.
      • \n
      ", + "type": "module", + "displayName": "Resolver algorithm" + }, + { + "textRaw": "Resolver Algorithm Specification", + "name": "resolver_algorithm_specification", + "desc": "

      ESM_RESOLVE(specifier, parentURL)

      \n
      \n
        \n
      1. Let resolved be undefined.
      2. \n
      3. If specifier is a valid URL, then\n
          \n
        1. Set resolved to the result of parsing and reserializing\nspecifier as a URL.
        2. \n
        \n
      4. \n
      5. Otherwise, if specifier starts with \"/\", \"./\" or \"../\", then\n
          \n
        1. Set resolved to the URL resolution of specifier relative to\nparentURL.
        2. \n
        \n
      6. \n
      7. Otherwise, if specifier starts with \"#\", then\n
          \n
        1. Set resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).
        2. \n
        \n
      8. \n
      9. Otherwise,\n
          \n
        1. Note: specifier is now a bare specifier.
        2. \n
        3. Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
        4. \n
        \n
      10. \n
      11. If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      12. \n
      13. If the file at resolved is a directory, then\n
          \n
        1. Throw an Unsupported Directory Import error.
        2. \n
        \n
      14. \n
      15. If the file at resolved does not exist, then\n
          \n
        1. Throw a Module Not Found error.
        2. \n
        \n
      16. \n
      17. Set resolved to the real path of resolved.
      18. \n
      19. Let format be the result of ESM_FORMAT(resolved).
      20. \n
      21. Load resolved as module format, format.
      22. \n
      23. Return resolved.
      24. \n
      \n
      \n

      PACKAGE_RESOLVE(packageSpecifier, parentURL)

      \n
      \n
        \n
      1. Let packageName be undefined.
      2. \n
      3. If packageSpecifier is an empty string, then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      4. \n
      5. If packageSpecifier does not start with \"@\", then\n
          \n
        1. Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
        2. \n
        \n
      6. \n
      7. Otherwise,\n
          \n
        1. If packageSpecifier does not contain a \"/\" separator, then\n
            \n
          1. Throw an Invalid Module Specifier error.
          2. \n
          \n
        2. \n
        3. Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
        4. \n
        \n
      8. \n
      9. If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      10. \n
      11. Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
      12. \n
      13. Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
      14. \n
      15. If selfUrl is not undefined, return selfUrl.
      16. \n
      17. If packageSubpath is \".\" and packageName is a Node.js builtin\nmodule, then\n
          \n
        1. Return the string \"node:\" concatenated with packageSpecifier.
        2. \n
        \n
      18. \n
      19. While parentURL is not the file system root,\n
          \n
        1. Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.
        2. \n
        3. Set parentURL to the parent folder URL of parentURL.
        4. \n
        5. If the folder at packageURL does not exist, then\n
            \n
          1. Set parentURL to the parent URL path of parentURL.
          2. \n
          3. Continue the next loop iteration.
          4. \n
          \n
        6. \n
        7. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        8. \n
        9. If pjson is not null and pjson.exports is not null or\nundefined, then\n
            \n
          1. Let exports be pjson.exports.
          2. \n
          3. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).
          4. \n
          \n
        10. \n
        11. Otherwise, if packageSubpath is equal to \".\", then\n
            \n
          1. Return the result applying the legacy LOAD_AS_DIRECTORY\nCommonJS resolver to packageURL, throwing a Module Not Found\nerror for no resolution.
          2. \n
          \n
        12. \n
        13. Otherwise,\n
            \n
          1. Return the URL resolution of packageSubpath in packageURL.
          2. \n
          \n
        14. \n
        \n
      20. \n
      21. Throw a Module Not Found error.
      22. \n
      \n
      \n

      PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

      \n
      \n
        \n
      1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      2. \n
      3. If packageURL is null, then\n
          \n
        1. Return undefined.
        2. \n
        \n
      4. \n
      5. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
      6. \n
      7. If pjson is null or if pjson.exports is null or\nundefined, then\n
          \n
        1. Return undefined.
        2. \n
        \n
      8. \n
      9. If pjson.name is equal to packageName, then\n
          \n
        1. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports,\ndefaultConditions).
        2. \n
        \n
      10. \n
      11. Otherwise, return undefined.
      12. \n
      \n
      \n

      PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

      \n
      \n
        \n
      1. If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
      2. \n
      3. If subpath is equal to \".\", then\n
          \n
        1. Let mainExport be undefined.
        2. \n
        3. If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
            \n
          1. Set mainExport to exports.
          2. \n
          \n
        4. \n
        5. Otherwise if exports is an Object containing a \".\" property, then\n
            \n
          1. Set mainExport to exports[\".\"].
          2. \n
          \n
        6. \n
        7. If mainExport is not undefined, then\n
            \n
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, false,\nconditions).
          2. \n
          3. If resolved is not null or undefined, then\n
              \n
            1. Return resolved.
            2. \n
            \n
          4. \n
          \n
        8. \n
        \n
      4. \n
      5. Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
          \n
        1. Let matchKey be the string \"./\" concatenated with subpath.
        2. \n
        3. Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
        4. \n
        5. If resolvedMatch.resolve is not null or undefined, then\n
            \n
          1. Return resolvedMatch.
          2. \n
          \n
        6. \n
        \n
      6. \n
      7. Throw a Package Path Not Exported error.
      8. \n
      \n
      \n

      PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

      \n
      \n
        \n
      1. Assert: specifier begins with \"#\".
      2. \n
      3. If specifier is exactly equal to \"#\" or starts with \"#/\", then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      4. \n
      5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      6. \n
      7. If packageURL is not null, then\n
          \n
        1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        2. \n
        3. If pjson.imports is a non-null Object, then\n
            \n
          1. Let resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).
          2. \n
          3. If resolvedMatch.resolve is not null or undefined, then\n
              \n
            1. Return resolvedMatch.
            2. \n
            \n
          4. \n
          \n
        4. \n
        \n
      8. \n
      9. Throw a Package Import Not Defined error.
      10. \n
      \n
      \n

      PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)

      \n
      \n
        \n
      1. If matchKey is a key of matchObj, and does not end in \"*\", then\n
          \n
        1. Let target be the value of matchObj[matchKey].
        2. \n
        3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", false, isImports, conditions).
        4. \n
        5. Return the object { resolved, exact: true }.
        6. \n
        \n
      2. \n
      3. Let expansionKeys be the list of keys of matchObj ending in \"/\"\nor \"*\", sorted by length descending.
      4. \n
      5. For each key expansionKey in expansionKeys, do\n
          \n
        1. If expansionKey ends in \"*\" and matchKey starts with but is\nnot equal to the substring of expansionKey excluding the last \"*\"\ncharacter, then\n
            \n
          1. Let target be the value of matchObj[expansionKey].
          2. \n
          3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey minus one.
          4. \n
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, true, isImports,\nconditions).
          6. \n
          7. Return the object { resolved, exact: true }.
          8. \n
          \n
        2. \n
        3. If matchKey starts with expansionKey, then\n
            \n
          1. Let target be the value of matchObj[expansionKey].
          2. \n
          3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.
          4. \n
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, false, isImports,\nconditions).
          6. \n
          7. Return the object { resolved, exact: false }.
          8. \n
          \n
        4. \n
        \n
      6. \n
      7. Return the object { resolved: null, exact: true }.
      8. \n
      \n
      \n

      PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern,\ninternal, conditions)

      \n
      \n
        \n
      1. If target is a String, then\n
          \n
        1. If pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.
        2. \n
        3. If target does not start with \"./\", then\n
            \n
          1. If internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n
              \n
            1. If pattern is true, then\n
                \n
              1. Return PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\")_.
              2. \n
              \n
            2. \n
            3. Return PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\")_.
            4. \n
            \n
          2. \n
          3. Otherwise, throw an Invalid Package Target error.
          4. \n
          \n
        4. \n
        5. If target split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments after the first segment, throw an\nInvalid Package Target error.
        6. \n
        7. Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
        8. \n
        9. Assert: resolvedTarget is contained in packageURL.
        10. \n
        11. If subpath split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments, throw an Invalid Module Specifier error.
        12. \n
        13. If pattern is true, then\n
            \n
          1. Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.
          2. \n
          \n
        14. \n
        15. Otherwise,\n
            \n
          1. Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
          2. \n
          \n
        16. \n
        \n
      2. \n
      3. Otherwise, if target is a non-null Object, then\n
          \n
        1. If exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
        2. \n
        3. For each property p of target, in object insertion order as,\n
            \n
          1. If p equals \"default\" or conditions contains an entry for p,\nthen\n
              \n
            1. Let targetValue be the value of the p property in target.
            2. \n
            3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions).
            4. \n
            5. If resolved is equal to undefined, continue the loop.
            6. \n
            7. Return resolved.
            8. \n
            \n
          2. \n
          \n
        4. \n
        5. Return undefined.
        6. \n
        \n
      4. \n
      5. Otherwise, if target is an Array, then\n
          \n
        1. If _target.length is zero, return null.
        2. \n
        3. For each item targetValue in target, do\n
            \n
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions), continuing the loop on any Invalid Package Target\nerror.
          2. \n
          3. If resolved is undefined, continue the loop.
          4. \n
          5. Return resolved.
          6. \n
          \n
        4. \n
        5. Return or throw the last fallback resolution null return or error.
        6. \n
        \n
      6. \n
      7. Otherwise, if target is null, return null.
      8. \n
      9. Otherwise throw an Invalid Package Target error.
      10. \n
      \n
      \n

      ESM_FORMAT(url)

      \n
      \n
        \n
      1. Assert: url corresponds to an existing file.
      2. \n
      3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
      4. \n
      5. If url ends in \".mjs\", then\n
          \n
        1. Return \"module\".
        2. \n
        \n
      6. \n
      7. If url ends in \".cjs\", then\n
          \n
        1. Return \"commonjs\".
        2. \n
        \n
      8. \n
      9. If pjson?.type exists and is \"module\", then\n
          \n
        1. If url ends in \".js\", then\n
            \n
          1. Return \"module\".
          2. \n
          \n
        2. \n
        3. Throw an Unsupported File Extension error.
        4. \n
        \n
      10. \n
      11. Otherwise,\n
          \n
        1. Throw an Unsupported File Extension error.
        2. \n
        \n
      12. \n
      \n
      \n

      READ_PACKAGE_SCOPE(url)

      \n
      \n
        \n
      1. Let scopeURL be url.
      2. \n
      3. While scopeURL is not the file system root,\n
          \n
        1. Set scopeURL to the parent URL of scopeURL.
        2. \n
        3. If scopeURL ends in a \"node_modules\" path segment, return null.
        4. \n
        5. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
        6. \n
        7. If pjson is not null, then\n
            \n
          1. Return pjson.
          2. \n
          \n
        8. \n
        \n
      4. \n
      5. Return null.
      6. \n
      \n
      \n

      READ_PACKAGE_JSON(packageURL)

      \n
      \n
        \n
      1. Let pjsonURL be the resolution of \"package.json\" within packageURL.
      2. \n
      3. If the file at pjsonURL does not exist, then\n
          \n
        1. Return null.
        2. \n
        \n
      4. \n
      5. If the file at packageURL does not parse as valid JSON, then\n
          \n
        1. Throw an Invalid Package Configuration error.
        2. \n
        \n
      6. \n
      7. Return the parsed JSON source of the file at pjsonURL.
      8. \n
      \n
      ", + "type": "module", + "displayName": "Resolver Algorithm Specification" + }, + { + "textRaw": "Customizing ESM specifier resolution algorithm", + "name": "customizing_esm_specifier_resolution_algorithm", + "desc": "

      The current specifier resolution does not support all default behavior of\nthe CommonJS loader. One of the behavior differences is automatic resolution\nof file extensions and the ability to import directories that have an index\nfile.

      \n

      The --experimental-specifier-resolution=[mode] flag can be used to customize\nthe extension resolution algorithm. The default mode is explicit, which\nrequires the full path to a module be provided to the loader. To enable the\nautomatic extension resolution and importing from directories that include an\nindex file use the node mode.

      \n
      $ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n
      \n", + "type": "module", + "displayName": "Customizing ESM specifier resolution algorithm" + } + ], + "type": "misc", + "displayName": "Resolution algorithm" + } + ], + "properties": [ + { + "textRaw": "`meta` {Object}", + "type": "Object", + "name": "meta", + "desc": "

      The import.meta metaproperty is an Object that contains the following\nproperty:

      \n
        \n
      • url <string> The absolute file: URL of the module.
      • \n
      " + } + ] + }, + { + "textRaw": "Modules: Packages", + "name": "Modules: Packages", + "type": "misc", + "meta": { + "changes": [ + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/34718", + "description": "Add support for `\"exports\"` patterns." + }, + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34117", + "description": "Add package `\"imports\"` field." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31001", + "description": "Unflag conditional exports." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31002", + "description": "Unflag self-referencing a package using its name." + }, + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28568", + "description": "Introduce `\"exports\"` `package.json` field as a more powerful alternative to the classic `\"main\"` field." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26745", + "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." + } + ] + }, + "miscs": [ + { + "textRaw": "Introduction", + "name": "introduction", + "desc": "

      A package is a folder tree described by a package.json file. The package\nconsists of the folder containing the package.json file and all subfolders\nuntil the next folder containing another package.json file, or a folder\nnamed node_modules.

      \n

      This page provides guidance for package authors writing package.json files\nalong with a reference for the package.json fields defined by Node.js.

      ", + "type": "misc", + "displayName": "Introduction" + }, + { + "textRaw": "Determining module system", + "name": "determining_module_system", + "desc": "

      Node.js will treat the following as ES modules when passed to node as the\ninitial input, or when referenced by import statements within ES module code:

      \n
        \n
      • \n

        Files ending in .mjs.

        \n
      • \n
      • \n

        Files ending in .js when the nearest parent package.json file contains a\ntop-level \"type\" field with a value of \"module\".

        \n
      • \n
      • \n

        Strings passed in as an argument to --eval, or piped to node via STDIN,\nwith the flag --input-type=module.

        \n
      • \n
      \n

      Node.js will treat as CommonJS all other forms of input, such as .js files\nwhere the nearest parent package.json file contains no top-level \"type\"\nfield, or string input without the flag --input-type. This behavior is to\npreserve backward compatibility. However, now that Node.js supports both\nCommonJS and ES modules, it is best to be explicit whenever possible. Node.js\nwill treat the following as CommonJS when passed to node as the initial input,\nor when referenced by import statements within ES module code:

      \n
        \n
      • \n

        Files ending in .cjs.

        \n
      • \n
      • \n

        Files ending in .js when the nearest parent package.json file contains a\ntop-level field \"type\" with a value of \"commonjs\".

        \n
      • \n
      • \n

        Strings passed in as an argument to --eval or --print, or piped to node\nvia STDIN, with the flag --input-type=commonjs.

        \n
      • \n
      \n

      Package authors should include the \"type\" field, even in packages where\nall sources are CommonJS. Being explicit about the type of the package will\nfuture-proof the package in case the default type of Node.js ever changes, and\nit will also make things easier for build tools and loaders to determine how the\nfiles in the package should be interpreted.

      ", + "modules": [ + { + "textRaw": "`package.json` and file extensions", + "name": "`package.json`_and_file_extensions", + "desc": "

      Within a package, the package.json \"type\" field defines how\nNode.js should interpret .js files. If a package.json file does not have a\n\"type\" field, .js files are treated as CommonJS.

      \n

      A package.json \"type\" value of \"module\" tells Node.js to interpret .js\nfiles within that package as using ES module syntax.

      \n

      The \"type\" field applies not only to initial entry points (node my-app.js)\nbut also to files referenced by import statements and import() expressions.

      \n
      // my-app.js, treated as an ES module because there is a package.json\n// file in the same folder with \"type\": \"module\".\n\nimport './startup/init.js';\n// Loaded as ES module since ./startup contains no package.json file,\n// and therefore inherits the \"type\" value from one level up.\n\nimport 'commonjs-package';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nimport './node_modules/commonjs-package/index.js';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n
      \n

      Files ending with .mjs are always loaded as ES modules regardless of\nthe nearest parent package.json.

      \n

      Files ending with .cjs are always loaded as CommonJS regardless of the\nnearest parent package.json.

      \n
      import './legacy-file.cjs';\n// Loaded as CommonJS since .cjs is always loaded as CommonJS.\n\nimport 'commonjs-package/src/index.mjs';\n// Loaded as ES module since .mjs is always loaded as ES module.\n
      \n

      The .mjs and .cjs extensions can be used to mix types within the same\npackage:

      \n
        \n
      • \n

        Within a \"type\": \"module\" package, Node.js can be instructed to\ninterpret a particular file as CommonJS by naming it with a .cjs\nextension (since both .js and .mjs files are treated as ES modules within\na \"module\" package).

        \n
      • \n
      • \n

        Within a \"type\": \"commonjs\" package, Node.js can be instructed to\ninterpret a particular file as an ES module by naming it with an .mjs\nextension (since both .js and .cjs files are treated as CommonJS within a\n\"commonjs\" package).

        \n
      • \n
      ", + "type": "module", + "displayName": "`package.json` and file extensions" + }, + { + "textRaw": "`--input-type` flag", + "name": "`--input-type`_flag", + "desc": "

      Strings passed in as an argument to --eval (or -e), or piped to node via\nSTDIN, are treated as ES modules when the --input-type=module flag\nis set.

      \n
      node --input-type=module --eval \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | node --input-type=module\n
      \n

      For completeness there is also --input-type=commonjs, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type is\nunspecified.

      ", + "type": "module", + "displayName": "`--input-type` flag" + } + ], + "type": "misc", + "displayName": "Determining module system" + }, + { + "textRaw": "Package entry points", + "name": "package_entry_points", + "desc": "

      In a package’s package.json file, two fields can define entry points for a\npackage: \"main\" and \"exports\". The \"main\" field is supported\nin all versions of Node.js, but its capabilities are limited: it only defines\nthe main entry point of the package.

      \n

      The \"exports\" field provides an alternative to \"main\" where the\npackage main entry point can be defined while also encapsulating the package,\npreventing any other entry points besides those defined in \"exports\".\nThis encapsulation allows module authors to define a public interface for\ntheir package.

      \n

      If both \"exports\" and \"main\" are defined, the \"exports\" field\ntakes precedence over \"main\". \"exports\" are not specific to ES\nmodules or CommonJS; \"main\" is overridden by \"exports\" if it\nexists. As such \"main\" cannot be used as a fallback for CommonJS but it\ncan be used as a fallback for legacy versions of Node.js that do not support the\n\"exports\" field.

      \n

      Conditional exports can be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import. For more information about supporting\nboth CommonJS and ES Modules in a single package please consult\nthe dual CommonJS/ES module packages section.

      \n

      Warning: Introducing the \"exports\" field prevents consumers of a\npackage from using any entry points that are not defined, including the\npackage.json (e.g. require('your-package/package.json'). This will\nlikely be a breaking change.

      \n

      To make the introduction of \"exports\" non-breaking, ensure that every\npreviously supported entry point is exported. It is best to explicitly specify\nentry points so that the package’s public API is well-defined. For example,\na project that previous exported main, lib,\nfeature, and the package.json could use the following package.exports:

      \n
      {\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/index\": \"./lib/index.js\",\n    \"./lib/index.js\": \"./lib/index.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/index.js\": \"./feature/index.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
      \n

      Alternatively a project could choose to export entire folders:

      \n
      {\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/*\": \"./lib/*.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/*\": \"./feature/*.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
      \n

      As a last resort, package encapsulation can be disabled entirely by creating an\nexport for the root of the package \"./*\": \"./*\". This exposes every file\nin the package at the cost of disabling the encapsulation and potential tooling\nbenefits this provides. As the ES Module loader in Node.js enforces the use of\nthe full specifier path, exporting the root rather than being explicit\nabout entry is less expressive than either of the prior examples. Not only\nis encapsulation lost but module consumers are unable to\nimport feature from 'my-mod/feature' as they need to provide the full\npath import feature from 'my-mod/feature/index.js.

      ", + "modules": [ + { + "textRaw": "Main entry point export", + "name": "main_entry_point_export", + "desc": "

      To set the main entry point for a package, it is advisable to define both\n\"exports\" and \"main\" in the package’s package.json file:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": \"./main.js\"\n}\n
      \n

      When the \"exports\" field is defined, all subpaths of the package are\nencapsulated and no longer available to importers. For example,\nrequire('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED\nerror.

      \n

      This encapsulation of exports provides more reliable guarantees\nabout package interfaces for tools and when handling semver upgrades for a\npackage. It is not a strong encapsulation since a direct require of any\nabsolute subpath of the package such as\nrequire('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.

      ", + "type": "module", + "displayName": "Main entry point export" + }, + { + "textRaw": "Subpath exports", + "name": "subpath_exports", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      When using the \"exports\" field, custom subpaths can be defined along\nwith the main entry point by treating the main entry point as the\n\".\" subpath:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./submodule\": \"./src/submodule.js\"\n  }\n}\n
      \n

      Now only the defined subpath in \"exports\" can be imported by a consumer:

      \n
      import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
      \n

      While other subpaths will error:

      \n
      import submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n
      ", + "type": "module", + "displayName": "Subpath exports" + }, + { + "textRaw": "Subpath imports", + "name": "subpath_imports", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      In addition to the \"exports\" field, it is possible to define internal\npackage import maps that only apply to import specifiers from within the package\nitself.

      \n

      Entries in the imports field must always start with # to ensure they are\ndisambiguated from package specifiers.

      \n

      For example, the imports field can be used to gain the benefits of conditional\nexports for internal modules:

      \n
      // package.json\n{\n  \"imports\": {\n    \"#dep\": {\n      \"node\": \"dep-node-native\",\n      \"default\": \"./dep-polyfill.js\"\n    }\n  },\n  \"dependencies\": {\n    \"dep-node-native\": \"^1.0.0\"\n  }\n}\n
      \n

      where import '#dep' does not get the resolution of the external package\ndep-node-native (including its exports in turn), and instead gets the local\nfile ./dep-polyfill.js relative to the package in other environments.

      \n

      Unlike the \"exports\" field, the \"imports\" field permits mapping to external\npackages.

      \n

      The resolution rules for the imports field are otherwise\nanalogous to the exports field.

      ", + "type": "module", + "displayName": "Subpath imports" + }, + { + "textRaw": "Subpath patterns", + "name": "subpath_patterns", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      For packages with a small number of exports or imports, we recommend\nexplicitly listing each exports subpath entry. But for packages that have\nlarge numbers of subpaths, this might cause package.json bloat and\nmaintenance issues.

      \n

      For these use cases, subpath export patterns can be used instead:

      \n
      // ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./features/*\": \"./src/features/*.js\"\n  },\n  \"imports\": {\n    \"#internal/*\": \"./src/internal/*.js\"\n  }\n}\n
      \n

      The left hand matching pattern must always end in *. All instances of * on\nthe right hand side will then be replaced with this value, including if it\ncontains any / separators.

      \n
      import featureX from 'es-module-package/features/x';\n// Loads ./node_modules/es-module-package/src/features/x.js\n\nimport featureY from 'es-module-package/features/y/y';\n// Loads ./node_modules/es-module-package/src/features/y/y.js\n\nimport internalZ from '#internal/z';\n// Loads ./node_modules/es-module-package/src/internal/z.js\n
      \n

      This is a direct static replacement without any special handling for file\nextensions. In the previous example, pkg/features/x.json would be resolved to\n./src/features/x.json.js in the mapping.

      \n

      The property of exports being statically enumerable is maintained with exports\npatterns since the individual exports for a package can be determined by\ntreating the right hand side target pattern as a ** glob against the list of\nfiles within the package. Because node_modules paths are forbidden in exports\ntargets, this expansion is dependent on only the files of the package itself.

      ", + "type": "module", + "displayName": "Subpath patterns" + }, + { + "textRaw": "Exports sugar", + "name": "exports_sugar", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      If the \".\" export is the only export, the \"exports\" field provides sugar\nfor this case being the direct \"exports\" field value.

      \n

      If the \".\" export has a fallback array or string value, then the\n\"exports\" field can be set to this value directly.

      \n
      {\n  \"exports\": {\n    \".\": \"./main.js\"\n  }\n}\n
      \n

      can be written:

      \n
      {\n  \"exports\": \"./main.js\"\n}\n
      ", + "type": "module", + "displayName": "Exports sugar" + }, + { + "textRaw": "Conditional exports", + "name": "conditional_exports", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Conditional exports provide a way to map to different paths depending on\ncertain conditions. They are supported for both CommonJS and ES module imports.

      \n

      For example, a package that wants to provide different ES module exports for\nrequire() and import can be written:

      \n
      // package.json\n{\n  \"main\": \"./main-require.cjs\",\n  \"exports\": {\n    \"import\": \"./main-module.js\",\n    \"require\": \"./main-require.cjs\"\n  },\n  \"type\": \"module\"\n}\n
      \n

      Node.js supports the following conditions out of the box:

      \n
        \n
      • \"import\" - matches when the package is loaded via import or\nimport(), or via any top-level import or resolve operation by the\nECMAScript module loader. Applies regardless of the module format of the\ntarget file. Always mutually exclusive with \"require\".
      • \n
      • \"require\" - matches when the package is loaded via require(). The\nreferenced file should be loadable with require() although the condition\nmatches regardless of the module format of the target file. Expected\nformats include CommonJS, JSON, and native addons but not ES modules as\nrequire() doesn't support them. Always mutually exclusive with\n\"import\".
      • \n
      • \"node\" - matches for any Node.js environment. Can be a CommonJS or ES\nmodule file. This condition should always come after \"import\" or\n\"require\".
      • \n
      • \"default\" - the generic fallback that always matches. Can be a CommonJS\nor ES module file. This condition should always come last.
      • \n
      \n

      Within the \"exports\" object, key order is significant. During condition\nmatching, earlier entries have higher priority and take precedence over later\nentries. The general rule is that conditions should be from most specific to\nleast specific in object order.

      \n

      Other conditions such as \"browser\", \"electron\", \"deno\", \"react-native\",\netc., are unknown to Node.js, and thus ignored. Runtimes or tools other than\nNode.js can use them at their discretion. Further restrictions, definitions, or\nguidance on condition names might occur in the future.

      \n

      Using the \"import\" and \"require\" conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.

      \n

      Conditional exports can also be extended to exports subpaths, for example:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./feature\": {\n      \"node\": \"./feature-node.js\",\n      \"default\": \"./feature.js\"\n    }\n  }\n}\n
      \n

      Defines a package where require('pkg/feature') and import 'pkg/feature'\ncould provide different implementations between Node.js and other JS\nenvironments.

      \n

      When using environment branches, always include a \"default\" condition where\npossible. Providing a \"default\" condition ensures that any unknown JS\nenvironments are able to use this universal implementation, which helps avoid\nthese JS environments from having to pretend to be existing environments in\norder to support packages with conditional exports. For this reason, using\n\"node\" and \"default\" condition branches is usually preferable to using\n\"node\" and \"browser\" condition branches.

      ", + "type": "module", + "displayName": "Conditional exports" + }, + { + "textRaw": "Nested conditions", + "name": "nested_conditions", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      In addition to direct mappings, Node.js also supports nested condition objects.

      \n

      For example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \"node\": {\n      \"import\": \"./feature-node.mjs\",\n      \"require\": \"./feature-node.cjs\"\n    },\n    \"default\": \"./feature.mjs\",\n  }\n}\n
      \n

      Conditions continue to be matched in order as with flat conditions. If\na nested conditional does not have any mapping it will continue checking\nthe remaining conditions of the parent condition. In this way nested\nconditions behave analogously to nested JavaScript if statements.

      ", + "type": "module", + "displayName": "Nested conditions" + }, + { + "textRaw": "Resolving user conditions", + "name": "resolving_user_conditions", + "desc": "

      When running Node.js, custom user conditions can be added with the\n--conditions flag:

      \n
      node --conditions=development main.js\n
      \n

      which would then resolve the \"development\" condition in package imports and\nexports, while resolving the existing \"node\", \"default\", \"import\", and\n\"require\" conditions as appropriate.

      \n

      Any number of custom conditions can be set with repeat flags.

      ", + "type": "module", + "displayName": "Resolving user conditions" + }, + { + "textRaw": "Self-referencing a package using its name", + "name": "self-referencing_a_package_using_its_name", + "desc": "

      Within a package, the values defined in the package’s\npackage.json \"exports\" field can be referenced via the package’s name.\nFor example, assuming the package.json is:

      \n
      // package.json\n{\n  \"name\": \"a-package\",\n  \"exports\": {\n    \".\": \"./main.mjs\",\n    \"./foo\": \"./foo.js\"\n  }\n}\n
      \n

      Then any module in that package can reference an export in the package itself:

      \n
      // ./a-module.mjs\nimport { something } from 'a-package'; // Imports \"something\" from ./main.mjs.\n
      \n

      Self-referencing is available only if package.json has \"exports\", and\nwill allow importing only what that \"exports\" (in the package.json)\nallows. So the code below, given the previous package, will generate a runtime\nerror:

      \n
      // ./another-module.mjs\n\n// Imports \"another\" from ./m.mjs. Fails because\n// the \"package.json\" \"exports\" field\n// does not provide an export named \"./m.mjs\".\nimport { another } from 'a-package/m.mjs';\n
      \n

      Self-referencing is also available when using require, both in an ES module,\nand in a CommonJS one. For example, this code will also work:

      \n
      // ./a-module.js\nconst { something } = require('a-package/foo'); // Loads from ./foo.js.\n
      ", + "type": "module", + "displayName": "Self-referencing a package using its name" + } + ], + "type": "misc", + "displayName": "Package entry points" + }, + { + "textRaw": "Dual CommonJS/ES module packages", + "name": "dual_commonjs/es_module_packages", + "desc": "

      Prior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with package.json \"main\" specifying the\nCommonJS entry point and package.json \"module\" specifying the ES module\nentry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) the top-level \"module\" field.

      \n

      Node.js can now run ES module entry points, and a package can contain both\nCommonJS and ES module entry points (either via separate specifiers such as\n'pkg' and 'pkg/es-module', or both at the same specifier via Conditional\nexports). Unlike in the scenario where \"module\" is only used by bundlers,\nor ES module files are transpiled into CommonJS on the fly before evaluation by\nNode.js, the files referenced by the ES module entry point are evaluated as ES\nmodules.

      ", + "modules": [ + { + "textRaw": "Dual package hazard", + "name": "dual_package_hazard", + "desc": "

      When an application is using a package that provides both CommonJS and ES module\nsources, there is a risk of certain bugs if both versions of the package get\nloaded. This potential comes from the fact that the pkgInstance created by\nconst pkgInstance = require('pkg') is not the same as the pkgInstance\ncreated by import pkgInstance from 'pkg' (or an alternative main path like\n'pkg/module'). This is the “dual package hazard,†where two versions of the\nsame package can be loaded within the same runtime environment. While it is\nunlikely that an application or package would intentionally load both versions\ndirectly, it is common for an application to load one version while a dependency\nof the application loads the other version. This hazard can happen because\nNode.js supports intermixing CommonJS and ES modules, and can lead to unexpected\nbehavior.

      \n

      If the package main export is a constructor, an instanceof comparison of\ninstances created by the two versions returns false, and if the export is an\nobject, properties added to one (like pkgInstance.foo = 3) are not present on\nthe other. This differs from how import and require statements work in\nall-CommonJS or all-ES module environments, respectively, and therefore is\nsurprising to users. It also differs from the behavior users are familiar with\nwhen using transpilation via tools like Babel or esm.

      ", + "type": "module", + "displayName": "Dual package hazard" + }, + { + "textRaw": "Writing dual packages while avoiding or minimizing hazards", + "name": "writing_dual_packages_while_avoiding_or_minimizing_hazards", + "desc": "

      First, the hazard described in the previous section occurs when a package\ncontains both CommonJS and ES module sources and both sources are provided for\nuse in Node.js, either via separate main entry points or exported paths. A\npackage might instead be written where any version of Node.js receives only\nCommonJS sources, and any separate ES module sources the package might contain\nare intended only for other environments such as browsers. Such a package\nwould be usable by any version of Node.js, since import can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.

      \n

      A package might also switch from CommonJS to ES module syntax in a breaking\nchange version bump. This has the disadvantage that the\nnewest version of the package would only be usable in ES module-supporting\nversions of Node.js.

      \n

      Every pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:

      \n
        \n
      1. The package is usable via both require and import.
      2. \n
      3. The package is usable in both current Node.js and older versions of Node.js\nthat lack support for ES modules.
      4. \n
      5. The package main entry point, e.g. 'pkg' can be used by both require to\nresolve to a CommonJS file and by import to resolve to an ES module file.\n(And likewise for exported paths, e.g. 'pkg/feature'.)
      6. \n
      7. The package provides named exports, e.g. import { name } from 'pkg' rather\nthan import pkg from 'pkg'; pkg.name.
      8. \n
      9. The package is potentially usable in other ES module environments such as\nbrowsers.
      10. \n
      11. The hazards described in the previous section are avoided or minimized.
      12. \n
      ", + "modules": [ + { + "textRaw": "Approach #1: Use an ES module wrapper", + "name": "approach_#1:_use_an_es_module_wrapper", + "desc": "

      Write the package in CommonJS or transpile ES module sources into CommonJS, and\ncreate an ES module wrapper file that defines the named exports. Using\nConditional exports, the ES module wrapper is used for import and the\nCommonJS entry point for require.

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./wrapper.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
      \n

      The preceding example uses explicit extensions .mjs and .cjs.\nIf your files use the .js extension, \"type\": \"module\" will cause such files\nto be treated as ES modules, just as \"type\": \"commonjs\" would cause them\nto be treated as CommonJS.\nSee Enabling.

      \n
      // ./node_modules/pkg/index.cjs\nexports.name = 'value';\n
      \n
      // ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n
      \n

      In this example, the name from import { name } from 'pkg' is the same\nsingleton as the name from const { name } = require('pkg'). Therefore ===\nreturns true when comparing the two names and the divergent specifier hazard\nis avoided.

      \n

      If the module is not simply a list of named exports, but rather contains a\nunique function or object export like module.exports = function () { ... },\nor if support in the wrapper for the import pkg from 'pkg' pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:

      \n
      import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n
      \n

      This approach is appropriate for any of the following use cases:

      \n
        \n
      • The package is currently written in CommonJS and the author would prefer not\nto refactor it into ES module syntax, but wishes to provide named exports for\nES module consumers.
      • \n
      • The package has other packages that depend on it, and the end user might\ninstall both this package and those other packages. For example a utilities\npackage is used directly in an application, and a utilities-plus package\nadds a few more functions to utilities. Because the wrapper exports\nunderlying CommonJS files, it doesn’t matter if utilities-plus is written in\nCommonJS or ES module syntax; it will work either way.
      • \n
      • The package stores internal state, and the package author would prefer not to\nrefactor the package to isolate its state management. See the next section.
      • \n
      \n

      A variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. \"./module\", to point to an all-ES module-syntax\nversion of the package. This could be used via import 'pkg/module' by users\nwho are certain that the CommonJS version will not be loaded anywhere in the\napplication, such as by dependencies; or if the CommonJS version can be loaded\nbut doesn’t affect the ES module version (for example, because the package is\nstateless):

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./wrapper.mjs\"\n  }\n}\n
      ", + "type": "module", + "displayName": "Approach #1: Use an ES module wrapper" + }, + { + "textRaw": "Approach #2: Isolate state", + "name": "approach_#2:_isolate_state", + "desc": "

      A package.json file can define the separate CommonJS and ES module entry\npoints directly:

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./index.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
      \n

      This can be done if both the CommonJS and ES module versions of the package are\nequivalent, for example because one is the transpiled output of the other; and\nthe package’s management of state is carefully isolated (or the package is\nstateless).

      \n

      The reason that state is an issue is because both the CommonJS and ES module\nversions of the package might get used within an application; for example, the\nuser’s application code could import the ES module version while a dependency\nrequires the CommonJS version. If that were to occur, two copies of the\npackage would be loaded in memory and therefore two separate states would be\npresent. This would likely cause hard-to-troubleshoot bugs.

      \n

      Aside from writing a stateless package (if JavaScript’s Math were a package,\nfor example, it would be stateless as all of its methods are static), there are\nsome ways to isolate state so that it’s shared between the potentially loaded\nCommonJS and ES module instances of the package:

      \n
        \n
      1. \n

        If possible, contain all state within an instantiated object. JavaScript’s\nDate, for example, needs to be instantiated to contain state; if it were a\npackage, it would be used like this:

        \n
        import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n
        \n

        The new keyword isn’t required; a package’s function can return a new\nobject, or modify a passed-in object, to keep the state external to the\npackage.

        \n
      2. \n
      3. \n

        Isolate the state in one or more CommonJS files that are shared between the\nCommonJS and ES module versions of the package. For example, if the CommonJS\nand ES module entry points are index.cjs and index.mjs, respectively:

        \n
        // ./node_modules/pkg/index.cjs\nconst state = require('./state.cjs');\nmodule.exports.state = state;\n
        \n
        // ./node_modules/pkg/index.mjs\nimport state from './state.cjs';\nexport {\n  state\n};\n
        \n

        Even if pkg is used via both require and import in an application (for\nexample, via import in application code and via require by a dependency)\neach reference of pkg will contain the same state; and modifying that\nstate from either module system will apply to both.

        \n
      4. \n
      \n

      Any plugins that attach to the package’s singleton would need to separately\nattach to both the CommonJS and ES module singletons.

      \n

      This approach is appropriate for any of the following use cases:

      \n
        \n
      • The package is currently written in ES module syntax and the package author\nwants that version to be used wherever such syntax is supported.
      • \n
      • The package is stateless or its state can be isolated without too much\ndifficulty.
      • \n
      • The package is unlikely to have other public packages that depend on it, or if\nit does, the package is stateless or has state that need not be shared between\ndependencies or with the overall application.
      • \n
      \n

      Even with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.

      \n

      As with the previous approach, a variant of this approach not requiring\nconditional exports for consumers could be to add an export, e.g.\n\"./module\", to point to an all-ES module-syntax version of the package:

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./index.mjs\"\n  }\n}\n
      ", + "type": "module", + "displayName": "Approach #2: Isolate state" + } + ], + "type": "module", + "displayName": "Writing dual packages while avoiding or minimizing hazards" + } + ], + "type": "misc", + "displayName": "Dual CommonJS/ES module packages" + }, + { + "textRaw": "Node.js `package.json` field definitions", + "name": "node.js_`package.json`_field_definitions", + "desc": "

      This section describes the fields used by the Node.js runtime. Other tools (such\nas npm) use\nadditional fields which are ignored by Node.js and not documented here.

      \n

      The following fields in package.json files are used in Node.js:

      \n
        \n
      • \"name\" - Relevant when using named imports within a package. Also used\nby package managers as the name of the package.
      • \n
      • \"type\" - The package type determining whether to load .js files as\nCommonJS or ES modules.
      • \n
      • \"exports\" - Package exports and conditional exports. When present,\nlimits which submodules can be loaded from within the package.
      • \n
      • \"main\" - The default module when loading the package, if exports is not\nspecified, and in versions of Node.js prior to the introduction of exports.
      • \n
      • \"imports\" - Package imports, for use by modules within the package\nitself.
      • \n
      ", + "modules": [ + { + "textRaw": "`\"name\"`", + "name": "`\"name\"`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [ + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31002", + "description": "Remove the `--experimental-resolve-self` option." + } + ] + }, + "desc": "\n
      {\n  \"name\": \"package-name\"\n}\n
      \n

      The \"name\" field defines your package’s name. Publishing to the\nnpm registry requires a name that satisfies\ncertain requirements.

      \n

      The \"name\" field can be used in addition to the \"exports\" field to\nself-reference a package using its name.

      ", + "type": "module", + "displayName": "`\"name\"`" + }, + { + "textRaw": "`\"type\"`", + "name": "`\"type\"`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [ + { + "version": [ + "v12.17.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29866", + "description": "Unflag `--experimental-modules`." + } + ] + }, + "desc": "\n

      The \"type\" field defines the module format that Node.js uses for all\n.js files that have that package.json file as their nearest parent.

      \n

      Files ending with .js are loaded as ES modules when the nearest parent\npackage.json file contains a top-level field \"type\" with a value of\n\"module\".

      \n

      The nearest parent package.json is defined as the first package.json found\nwhen searching in the current folder, that folder’s parent, and so on up\nuntil a node_modules folder or the volume root is reached.

      \n
      // package.json\n{\n  \"type\": \"module\"\n}\n
      \n
      # In same folder as preceding package.json\nnode my-app.js # Runs as ES module\n
      \n

      If the nearest parent package.json lacks a \"type\" field, or contains\n\"type\": \"commonjs\", .js files are treated as CommonJS. If the volume\nroot is reached and no package.json is found, .js files are treated as\nCommonJS.

      \n

      import statements of .js files are treated as ES modules if the nearest\nparent package.json contains \"type\": \"module\".

      \n
      // my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
      \n

      Regardless of the value of the \"type\" field, .mjs files are always treated\nas ES modules and .cjs files are always treated as CommonJS.

      ", + "type": "module", + "displayName": "`\"type\"`" + }, + { + "textRaw": "`\"exports\"`", + "name": "`\"exports\"`", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [ + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29978", + "description": "Implement conditional exports." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31001", + "description": "Remove the `--experimental-conditional-exports` option." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31008", + "description": "Implement logical conditional exports ordering." + }, + { + "version": [ + "v12.20.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/34718", + "description": "Add support for `\"exports\"` patterns." + } + ] + }, + "desc": "\n
      {\n  \"exports\": \"./index.js\"\n}\n
      \n

      The \"exports\" field allows defining the entry points of a package when\nimported by name loaded either via a node_modules lookup or a\nself-reference to its own name. It is supported in Node.js 12+ as an\nalternative to the \"main\" that can support defining subpath exports\nand conditional exports while encapsulating internal unexported modules.

      \n

      Conditional Exports can also be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import.

      \n

      All paths defined in the \"exports\" must be relative file URLs starting with\n./.

      ", + "type": "module", + "displayName": "`\"exports\"`" + }, + { + "textRaw": "`\"main\"`", + "name": "`\"main\"`", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "desc": "\n
      {\n  \"main\": \"./main.js\"\n}\n
      \n

      The \"main\" field defines the script that is used when the package directory\nis loaded via require(). Its value\nis interpreted as a path.

      \n
      require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.\n
      \n

      When a package has an \"exports\" field, this will take precedence over the\n\"main\" field when importing the package by name.

      ", + "type": "module", + "displayName": "`\"main\"`" + }, + { + "textRaw": "`\"imports\"`", + "name": "`\"imports\"`", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "\n
      // package.json\n{\n  \"imports\": {\n    \"#dep\": {\n      \"node\": \"dep-node-native\",\n      \"default\": \"./dep-polyfill.js\"\n    }\n  },\n  \"dependencies\": {\n    \"dep-node-native\": \"^1.0.0\"\n  }\n}\n
      \n

      Entries in the imports field must be strings starting with #.

      \n

      Import maps permit mapping to external packages.

      \n

      This field defines subpath imports for the current package.

      ", + "type": "module", + "displayName": "`\"imports\"`" + } + ], + "type": "misc", + "displayName": "Node.js `package.json` field definitions" + } + ] + }, + { + "textRaw": "Policies", + "name": "policy", + "introduced_in": "v11.8.0", + "type": "misc", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Node.js contains experimental support for creating policies on loading code.

      \n

      Policies are a security feature intended to allow guarantees\nabout what code Node.js is able to load. The use of policies assumes\nsafe practices for the policy files such as ensuring that policy\nfiles cannot be overwritten by the Node.js application by using\nfile permissions.

      \n

      A best practice would be to ensure that the policy manifest is read only for\nthe running Node.js application, and that the file cannot be changed\nby the running Node.js application in any way. A typical setup would be to\ncreate the policy file as a different user id than the one running Node.js\nand granting read permissions to the user id running Node.js.

      ", + "miscs": [ + { + "textRaw": "Enabling", + "name": "Enabling", + "type": "misc", + "desc": "

      The --experimental-policy flag can be used to enable features for policies\nwhen loading modules.

      \n

      Once this has been set, all modules must conform to a policy manifest file\npassed to the flag:

      \n
      node --experimental-policy=policy.json app.js\n
      \n

      The policy manifest will be used to enforce constraints on code loaded by\nNode.js.

      \n

      To mitigate tampering with policy files on disk, an integrity for\nthe policy file itself may be provided via --policy-integrity.\nThis allows running node and asserting the policy file contents\neven if the file is changed on disk.

      \n
      node --experimental-policy=policy.json --policy-integrity=\"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\" app.js\n
      " + }, + { + "textRaw": "Features", + "name": "features", + "modules": [ + { + "textRaw": "Error behavior", + "name": "error_behavior", + "desc": "

      When a policy check fails, Node.js by default will throw an error.\nIt is possible to change the error behavior to one of a few possibilities\nby defining an \"onerror\" field in a policy manifest. The following values are\navailable to change the behavior:

      \n
        \n
      • \"exit\": will exit the process immediately.\nNo cleanup code will be allowed to run.
      • \n
      • \"log\": will log the error at the site of the failure.
      • \n
      • \"throw\": will throw a JS error at the site of the failure. This is the\ndefault.
      • \n
      \n
      {\n  \"onerror\": \"log\",\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
      ", + "type": "module", + "displayName": "Error behavior" + }, + { + "textRaw": "Integrity checks", + "name": "integrity_checks", + "desc": "

      Policy files must use integrity checks with Subresource Integrity strings\ncompatible with the browser\nintegrity attribute\nassociated with absolute URLs.

      \n

      When using require() all resources involved in loading are checked for\nintegrity if a policy manifest has been specified. If a resource does not match\nthe integrity listed in the manifest, an error will be thrown.

      \n

      An example policy file that would allow loading a file checked.js:

      \n
      {\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
      \n

      Each resource listed in the policy manifest can be of one the following\nformats to determine its location:

      \n
        \n
      1. A relative url string to a resource from the manifest such as ./resource.js, ../resource.js, or /resource.js.
      2. \n
      3. A complete url string to a resource such as file:///resource.js.
      4. \n
      \n

      When loading resources the entire URL must match including search parameters\nand hash fragment. ./a.js?b will not be used when attempting to load\n./a.js and vice versa.

      \n

      To generate integrity strings, a script such as\nprintf \"sha384-$(cat checked.js | openssl dgst -sha384 -binary | base64)\"\ncan be used.

      \n

      Integrity can be specified as the boolean value true to accept any\nbody for the resource which can be useful for local development. It is not\nrecommended in production since it would allow unexpected alteration of\nresources to be considered valid.

      ", + "type": "module", + "displayName": "Integrity checks" + }, + { + "textRaw": "Dependency redirection", + "name": "dependency_redirection", + "desc": "

      An application may need to ship patched versions of modules or to prevent\nmodules from allowing all modules access to all other modules. Redirection\ncan be used by intercepting attempts to load the modules wishing to be\nreplaced.

      \n
      {\n  \"builtins\": [],\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"dependencies\": {\n        \"fs\": true,\n        \"os\": \"./app/node_modules/alt-os\"\n      }\n    }\n  }\n}\n
      \n

      The dependencies are keyed by the requested string specifier and have values\nof either true or a string pointing to a module that will be resolved.

      \n

      The specifier string does not perform any searching and must match exactly\nwhat is provided to the require(). Therefore, multiple specifiers may be\nneeded in the policy if require() uses multiple different strings to point\nto the same module (such as excluding the extension).

      \n

      If the value of the redirection is true the default searching algorithms will\nbe used to find the module.

      \n

      If the value of the redirection is a string, it will be resolved relative to\nthe manifest and then immediately be used without searching.

      \n

      Any specifier string that is require()ed and not listed in the dependencies\nwill result in an error according to the policy.

      \n

      Redirection will not prevent access to APIs through means such as direct access\nto require.cache and/or through module.constructor which allow access to\nloading modules. Policy redirection only affect specifiers to require().\nOther means such as to prevent undesired access to APIs through variables are\nnecessary to lock down that path of loading modules.

      \n

      A boolean value of true for the dependencies map can be specified to allow a\nmodule to load any specifier without redirection. This can be useful for local\ndevelopment and may have some valid usage in production, but should be used\nonly with care after auditing a module to ensure its behavior is valid.

      \n

      Example: Patched dependency

      \n

      Redirected dependencies can provide attenuated or modified functionality as fits\nthe application. For example, log data about timing of function durations by\nwrapping the original:

      \n
      const original = require('fn');\nmodule.exports = function fn(...args) {\n  console.time();\n  try {\n    return new.target ?\n      Reflect.construct(original, args) :\n      Reflect.apply(original, this, args);\n  } finally {\n    console.timeEnd();\n  }\n};\n
      ", + "type": "module", + "displayName": "Dependency redirection" + } + ], + "type": "misc", + "displayName": "Features" + } + ] + }, + { + "textRaw": "Diagnostic report", + "name": "report", + "introduced_in": "v11.8.0", + "type": "misc", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Delivers a JSON-formatted diagnostic summary, written to a file.

      \n

      The report is intended for development, test and production use, to capture\nand preserve information for problem determination. It includes JavaScript\nand native stack traces, heap statistics, platform information, resource\nusage etc. With the report option enabled, diagnostic reports can be triggered\non unhandled exceptions, fatal errors and user signals, in addition to\ntriggering programmatically through API calls.

      \n

      A complete example report that was generated on an uncaught exception\nis provided below for reference.

      \n
      {\n  \"header\": {\n    \"reportVersion\": 1,\n    \"event\": \"exception\",\n    \"trigger\": \"Exception\",\n    \"filename\": \"report.20181221.005011.8974.0.001.json\",\n    \"dumpEventTime\": \"2018-12-21T00:50:11Z\",\n    \"dumpEventTimeStamp\": \"1545371411331\",\n    \"processId\": 8974,\n    \"cwd\": \"/home/nodeuser/project/node\",\n    \"commandLine\": [\n      \"/home/nodeuser/project/node/out/Release/node\",\n      \"--report-uncaught-exception\",\n      \"/home/nodeuser/project/node/test/report/test-exception.js\",\n      \"child\"\n    ],\n    \"nodejsVersion\": \"v12.0.0-pre\",\n    \"glibcVersionRuntime\": \"2.17\",\n    \"glibcVersionCompiler\": \"2.17\",\n    \"wordSize\": \"64 bit\",\n    \"arch\": \"x64\",\n    \"platform\": \"linux\",\n    \"componentVersions\": {\n      \"node\": \"12.0.0-pre\",\n      \"v8\": \"7.1.302.28-node.5\",\n      \"uv\": \"1.24.1\",\n      \"zlib\": \"1.2.11\",\n      \"ares\": \"1.15.0\",\n      \"modules\": \"68\",\n      \"nghttp2\": \"1.34.0\",\n      \"napi\": \"3\",\n      \"llhttp\": \"1.0.1\",\n      \"http_parser\": \"2.8.0\",\n      \"openssl\": \"1.1.0j\"\n    },\n    \"release\": {\n      \"name\": \"node\"\n    },\n    \"osName\": \"Linux\",\n    \"osRelease\": \"3.10.0-862.el7.x86_64\",\n    \"osVersion\": \"#1 SMP Wed Mar 21 18:14:51 EDT 2018\",\n    \"osMachine\": \"x86_64\",\n    \"cpus\": [\n      {\n        \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n        \"speed\": 2700,\n        \"user\": 88902660,\n        \"nice\": 0,\n        \"sys\": 50902570,\n        \"idle\": 241732220,\n        \"irq\": 0\n      },\n      {\n        \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n        \"speed\": 2700,\n        \"user\": 88902660,\n        \"nice\": 0,\n        \"sys\": 50902570,\n        \"idle\": 241732220,\n        \"irq\": 0\n      }\n    ],\n    \"networkInterfaces\": [\n      {\n        \"name\": \"en0\",\n        \"internal\": false,\n        \"mac\": \"13:10:de:ad:be:ef\",\n        \"address\": \"10.0.0.37\",\n        \"netmask\": \"255.255.255.0\",\n        \"family\": \"IPv4\"\n      }\n    ],\n    \"host\": \"test_machine\"\n  },\n  \"javascriptStack\": {\n    \"message\": \"Error: *** test-exception.js: throwing uncaught Error\",\n    \"stack\": [\n      \"at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)\",\n      \"at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)\",\n      \"at Module._compile (internal/modules/cjs/loader.js:718:30)\",\n      \"at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)\",\n      \"at Module.load (internal/modules/cjs/loader.js:617:32)\",\n      \"at tryModuleLoad (internal/modules/cjs/loader.js:560:12)\",\n      \"at Function.Module._load (internal/modules/cjs/loader.js:552:3)\",\n      \"at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)\",\n      \"at executeUserCode (internal/bootstrap/node.js:332:15)\"\n    ]\n  },\n  \"nativeStack\": [\n    {\n      \"pc\": \"0x000055b57f07a9ef\",\n      \"symbol\": \"report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57f07cf03\",\n      \"symbol\": \"report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57f1bccfd\",\n      \"symbol\": \" [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57f1be048\",\n      \"symbol\": \"v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57feeda0e\",\n      \"symbol\": \" [./node]\"\n    }\n  ],\n  \"javascriptHeap\": {\n    \"totalMemory\": 6127616,\n    \"totalCommittedMemory\": 4357352,\n    \"usedMemory\": 3221136,\n    \"availableMemory\": 1521370240,\n    \"memoryLimit\": 1526909922,\n    \"heapSpaces\": {\n      \"read_only_space\": {\n        \"memorySize\": 524288,\n        \"committedMemory\": 39208,\n        \"capacity\": 515584,\n        \"used\": 30504,\n        \"available\": 485080\n      },\n      \"new_space\": {\n        \"memorySize\": 2097152,\n        \"committedMemory\": 2019312,\n        \"capacity\": 1031168,\n        \"used\": 985496,\n        \"available\": 45672\n      },\n      \"old_space\": {\n        \"memorySize\": 2273280,\n        \"committedMemory\": 1769008,\n        \"capacity\": 1974640,\n        \"used\": 1725488,\n        \"available\": 249152\n      },\n      \"code_space\": {\n        \"memorySize\": 696320,\n        \"committedMemory\": 184896,\n        \"capacity\": 152128,\n        \"used\": 152128,\n        \"available\": 0\n      },\n      \"map_space\": {\n        \"memorySize\": 536576,\n        \"committedMemory\": 344928,\n        \"capacity\": 327520,\n        \"used\": 327520,\n        \"available\": 0\n      },\n      \"large_object_space\": {\n        \"memorySize\": 0,\n        \"committedMemory\": 0,\n        \"capacity\": 1520590336,\n        \"used\": 0,\n        \"available\": 1520590336\n      },\n      \"new_large_object_space\": {\n        \"memorySize\": 0,\n        \"committedMemory\": 0,\n        \"capacity\": 0,\n        \"used\": 0,\n        \"available\": 0\n      }\n    }\n  },\n  \"resourceUsage\": {\n    \"userCpuSeconds\": 0.069595,\n    \"kernelCpuSeconds\": 0.019163,\n    \"cpuConsumptionPercent\": 0.000000,\n    \"maxRss\": 18079744,\n    \"pageFaults\": {\n      \"IORequired\": 0,\n      \"IONotRequired\": 4610\n    },\n    \"fsActivity\": {\n      \"reads\": 0,\n      \"writes\": 0\n    }\n  },\n  \"uvthreadResourceUsage\": {\n    \"userCpuSeconds\": 0.068457,\n    \"kernelCpuSeconds\": 0.019127,\n    \"cpuConsumptionPercent\": 0.000000,\n    \"fsActivity\": {\n      \"reads\": 0,\n      \"writes\": 0\n    }\n  },\n  \"libuv\": [\n    {\n      \"type\": \"async\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x0000000102910900\",\n      \"details\": \"\"\n    },\n    {\n      \"type\": \"timer\",\n      \"is_active\": false,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfeab0\",\n      \"repeat\": 0,\n      \"firesInMsFromNow\": 94403548320796,\n      \"expired\": true\n    },\n    {\n      \"type\": \"check\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfeb48\"\n    },\n    {\n      \"type\": \"idle\",\n      \"is_active\": false,\n      \"is_referenced\": true,\n      \"address\": \"0x00007fff5fbfebc0\"\n    },\n    {\n      \"type\": \"prepare\",\n      \"is_active\": false,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfec38\"\n    },\n    {\n      \"type\": \"check\",\n      \"is_active\": false,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfecb0\"\n    },\n    {\n      \"type\": \"async\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x000000010188f2e0\"\n    },\n    {\n      \"type\": \"tty\",\n      \"is_active\": false,\n      \"is_referenced\": true,\n      \"address\": \"0x000055b581db0e18\",\n      \"width\": 204,\n      \"height\": 55,\n      \"fd\": 17,\n      \"writeQueueSize\": 0,\n      \"readable\": true,\n      \"writable\": true\n    },\n    {\n      \"type\": \"signal\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x000055b581d80010\",\n      \"signum\": 28,\n      \"signal\": \"SIGWINCH\"\n    },\n    {\n      \"type\": \"tty\",\n      \"is_active\": true,\n      \"is_referenced\": true,\n      \"address\": \"0x000055b581df59f8\",\n      \"width\": 204,\n      \"height\": 55,\n      \"fd\": 19,\n      \"writeQueueSize\": 0,\n      \"readable\": true,\n      \"writable\": true\n    },\n    {\n      \"type\": \"loop\",\n      \"is_active\": true,\n      \"address\": \"0x000055fc7b2cb180\"\n    }\n  ],\n  \"workers\": [],\n  \"environmentVariables\": {\n    \"REMOTEHOST\": \"REMOVED\",\n    \"MANPATH\": \"/opt/rh/devtoolset-3/root/usr/share/man:\",\n    \"XDG_SESSION_ID\": \"66126\",\n    \"HOSTNAME\": \"test_machine\",\n    \"HOST\": \"test_machine\",\n    \"TERM\": \"xterm-256color\",\n    \"SHELL\": \"/bin/csh\",\n    \"SSH_CLIENT\": \"REMOVED\",\n    \"PERL5LIB\": \"/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl\",\n    \"OLDPWD\": \"/home/nodeuser/project/node/src\",\n    \"JAVACONFDIRS\": \"/opt/rh/devtoolset-3/root/etc/java:/etc/java\",\n    \"SSH_TTY\": \"/dev/pts/0\",\n    \"PCP_DIR\": \"/opt/rh/devtoolset-3/root\",\n    \"GROUP\": \"normaluser\",\n    \"USER\": \"nodeuser\",\n    \"LD_LIBRARY_PATH\": \"/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib\",\n    \"HOSTTYPE\": \"x86_64-linux\",\n    \"XDG_CONFIG_DIRS\": \"/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg\",\n    \"MAIL\": \"/var/spool/mail/nodeuser\",\n    \"PATH\": \"/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin\",\n    \"PWD\": \"/home/nodeuser/project/node\",\n    \"LANG\": \"en_US.UTF-8\",\n    \"PS1\": \"\\\\u@\\\\h : \\\\[\\\\e[31m\\\\]\\\\w\\\\[\\\\e[m\\\\] >  \",\n    \"SHLVL\": \"2\",\n    \"HOME\": \"/home/nodeuser\",\n    \"OSTYPE\": \"linux\",\n    \"VENDOR\": \"unknown\",\n    \"PYTHONPATH\": \"/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages\",\n    \"MACHTYPE\": \"x86_64\",\n    \"LOGNAME\": \"nodeuser\",\n    \"XDG_DATA_DIRS\": \"/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share\",\n    \"LESSOPEN\": \"||/usr/bin/lesspipe.sh %s\",\n    \"INFOPATH\": \"/opt/rh/devtoolset-3/root/usr/share/info\",\n    \"XDG_RUNTIME_DIR\": \"/run/user/50141\",\n    \"_\": \"./node\"\n  },\n  \"userLimits\": {\n    \"core_file_size_blocks\": {\n      \"soft\": \"\",\n      \"hard\": \"unlimited\"\n    },\n    \"data_seg_size_kbytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"file_size_blocks\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"max_locked_memory_bytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": 65536\n    },\n    \"max_memory_size_kbytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"open_files\": {\n      \"soft\": \"unlimited\",\n      \"hard\": 4096\n    },\n    \"stack_size_bytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"cpu_time_seconds\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"max_user_processes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": 4127290\n    },\n    \"virtual_memory_kbytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    }\n  },\n  \"sharedObjects\": [\n    \"/lib64/libdl.so.2\",\n    \"/lib64/librt.so.1\",\n    \"/lib64/libstdc++.so.6\",\n    \"/lib64/libm.so.6\",\n    \"/lib64/libgcc_s.so.1\",\n    \"/lib64/libpthread.so.0\",\n    \"/lib64/libc.so.6\",\n    \"/lib64/ld-linux-x86-64.so.2\"\n  ]\n}\n
      ", + "miscs": [ + { + "textRaw": "Usage", + "name": "usage", + "desc": "
      node --report-uncaught-exception --report-on-signal \\\n--report-on-fatalerror app.js\n
      \n
        \n
      • \n

        --report-uncaught-exception Enables report to be generated on\nun-caught exceptions. Useful when inspecting JavaScript stack in conjunction\nwith native stack and other runtime environment data.

        \n
      • \n
      • \n

        --report-on-signal Enables report to be generated upon receiving\nthe specified (or predefined) signal to the running Node.js process. (See below\non how to modify the signal that triggers the report.) Default signal is SIGUSR2.\nUseful when a report needs to be triggered from another program.\nApplication monitors may leverage this feature to collect report at regular\nintervals and plot rich set of internal runtime data to their views.

        \n
      • \n
      \n

      Signal based report generation is not supported in Windows.

      \n

      Under normal circumstances, there is no need to modify the report triggering\nsignal. However, if SIGUSR2 is already used for other purposes, then this\nflag helps to change the signal for report generation and preserve the original\nmeaning of SIGUSR2 for the said purposes.

      \n
        \n
      • \n

        --report-on-fatalerror Enables the report to be triggered on\nfatal errors (internal errors within the Node.js runtime, such as out of memory)\nthat leads to termination of the application. Useful to inspect various\ndiagnostic data elements such as heap, stack, event loop state, resource\nconsumption etc. to reason about the fatal error.

        \n
      • \n
      • \n

        --report-compact Write reports in a compact format, single-line JSON, more\neasily consumable by log processing systems than the default multi-line format\ndesigned for human consumption.

        \n
      • \n
      • \n

        --report-directory Location at which the report will be\ngenerated.

        \n
      • \n
      • \n

        --report-filename Name of the file to which the report will be\nwritten.

        \n
      • \n
      • \n

        --report-signal Sets or resets the signal for report generation\n(not supported on Windows). Default signal is SIGUSR2.

        \n
      • \n
      \n

      A report can also be triggered via an API call from a JavaScript application:

      \n
      process.report.writeReport();\n
      \n

      This function takes an optional additional argument filename, which is\nthe name of a file into which the report is written.

      \n
      process.report.writeReport('./foo.json');\n
      \n

      This function takes an optional additional argument err which is an Error\nobject that will be used as the context for the JavaScript stack printed in the\nreport. When using report to handle errors in a callback or an exception\nhandler, this allows the report to include the location of the original error as\nwell as where it was handled.

      \n
      try {\n  process.chdir('/non-existent-path');\n} catch (err) {\n  process.report.writeReport(err);\n}\n// Any other code\n
      \n

      If both filename and error object are passed to writeReport() the\nerror object must be the second parameter.

      \n
      try {\n  process.chdir('/non-existent-path');\n} catch (err) {\n  process.report.writeReport(filename, err);\n}\n// Any other code\n
      \n

      The content of the diagnostic report can be returned as a JavaScript Object\nvia an API call from a JavaScript application:

      \n
      const report = process.report.getReport();\nconsole.log(typeof report === 'object'); // true\n\n// Similar to process.report.writeReport() output\nconsole.log(JSON.stringify(report, null, 2));\n
      \n

      This function takes an optional additional argument err, which is an Error\nobject that will be used as the context for the JavaScript stack printed in the\nreport.

      \n
      const report = process.report.getReport(new Error('custom error'));\nconsole.log(typeof report === 'object'); // true\n
      \n

      The API versions are useful when inspecting the runtime state from within\nthe application, in expectation of self-adjusting the resource consumption,\nload balancing, monitoring etc.

      \n

      The content of the report consists of a header section containing the event\ntype, date, time, PID and Node.js version, sections containing JavaScript and\nnative stack traces, a section containing V8 heap information, a section\ncontaining libuv handle information and an OS platform information section\nshowing CPU and memory usage and system limits. An example report can be\ntriggered using the Node.js REPL:

      \n
      $ node\n> process.report.writeReport();\nWriting Node.js report to file: report.20181126.091102.8480.0.001.json\nNode.js report completed\n>\n
      \n

      When a report is written, start and end messages are issued to stderr\nand the filename of the report is returned to the caller. The default filename\nincludes the date, time, PID and a sequence number. The sequence number helps\nin associating the report dump with the runtime state if generated multiple\ntimes for the same Node.js process.

      ", + "type": "misc", + "displayName": "Usage" + }, + { + "textRaw": "Configuration", + "name": "configuration", + "desc": "

      Additional runtime configuration of report generation is available via\nthe following properties of process.report:

      \n

      reportOnFatalError triggers diagnostic reporting on fatal errors when true.\nDefaults to false.

      \n

      reportOnSignal triggers diagnostic reporting on signal when true. This is\nnot supported on Windows. Defaults to false.

      \n

      reportOnUncaughtException triggers diagnostic reporting on uncaught exception\nwhen true. Defaults to false.

      \n

      signal specifies the POSIX signal identifier that will be used\nto intercept external triggers for report generation. Defaults to\n'SIGUSR2'.

      \n

      filename specifies the name of the output file in the file system.\nSpecial meaning is attached to stdout and stderr. Usage of these\nwill result in report being written to the associated standard streams.\nIn cases where standard streams are used, the value in directory is ignored.\nURLs are not supported. Defaults to a composite filename that contains\ntimestamp, PID and sequence number.

      \n

      directory specifies the filesystem directory where the report will be written.\nURLs are not supported. Defaults to the current working directory of the\nNode.js process.

      \n
      // Trigger report only on uncaught exceptions.\nprocess.report.reportOnFatalError = false;\nprocess.report.reportOnSignal = false;\nprocess.report.reportOnUncaughtException = true;\n\n// Trigger report for both internal errors as well as external signal.\nprocess.report.reportOnFatalError = true;\nprocess.report.reportOnSignal = true;\nprocess.report.reportOnUncaughtException = false;\n\n// Change the default signal to 'SIGQUIT' and enable it.\nprocess.report.reportOnFatalError = false;\nprocess.report.reportOnUncaughtException = false;\nprocess.report.reportOnSignal = true;\nprocess.report.signal = 'SIGQUIT';\n
      \n

      Configuration on module initialization is also available via\nenvironment variables:

      \n
      NODE_OPTIONS=\"--report-uncaught-exception \\\n  --report-on-fatalerror --report-on-signal \\\n  --report-signal=SIGUSR2  --report-filename=./report.json \\\n  --report-directory=/home/nodeuser\"\n
      \n

      Specific API documentation can be found under\nprocess API documentation section.

      ", + "type": "misc", + "displayName": "Configuration" + }, + { + "textRaw": "Interaction with workers", + "name": "interaction_with_workers", + "meta": { + "changes": [ + { + "version": "v12.16.2", + "pr-url": "https://github.com/nodejs/node/pull/31386", + "description": "Workers are now included in the report." + } + ] + }, + "desc": "

      Worker threads can create reports in the same way that the main thread\ndoes.

      \n

      Reports will include information on any Workers that are children of the current\nthread as part of the workers section, with each Worker generating a report\nin the standard report format.

      \n

      The thread which is generating the report will wait for the reports from Worker\nthreads to finish. However, the latency for this will usually be low, as both\nrunning JavaScript and the event loop are interrupted to generate the report.

      ", + "type": "misc", + "displayName": "Interaction with workers" + } + ] + } + ], + "modules": [ + { + "textRaw": "Usage and example", + "name": "usage_and_example", + "introduced_in": "v0.10.0", + "miscs": [ + { + "textRaw": "Usage", + "name": "Usage", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      node [options] [V8 options] [script.js | -e \"script\" | - ] [arguments]

      \n

      Please see the Command Line Options document for more information.

      \n

      Example

      \n

      An example of a web server written with Node.js which responds with\n'Hello, World!':

      \n

      Commands in this document start with $ or > to replicate how they would\nappear in a user's terminal. Do not include the $ and > characters. They are\nthere to show the start of each command.

      \n

      Lines that don’t start with $ or > character show the output of the previous\ncommand.

      \n

      First, make sure to have downloaded and installed Node.js. See this guide\nfor further install information.

      \n

      Now, create an empty project folder called projects, then navigate into it.

      \n

      Linux and Mac:

      \n
      $ mkdir ~/projects\n$ cd ~/projects\n
      \n

      Windows CMD:

      \n
      > mkdir %USERPROFILE%\\projects\n> cd %USERPROFILE%\\projects\n
      \n

      Windows PowerShell:

      \n
      > mkdir $env:USERPROFILE\\projects\n> cd $env:USERPROFILE\\projects\n
      \n

      Next, create a new source file in the projects\nfolder and call it hello-world.js.

      \n

      Open hello-world.js in any preferred text editor and\npaste in the following content:

      \n
      const http = require('http');\n\nconst hostname = '127.0.0.1';\nconst port = 3000;\n\nconst server = http.createServer((req, res) => {\n  res.statusCode = 200;\n  res.setHeader('Content-Type', 'text/plain');\n  res.end('Hello, World!\\n');\n});\n\nserver.listen(port, hostname, () => {\n  console.log(`Server running at http://${hostname}:${port}/`);\n});\n
      \n

      Save the file, go back to the terminal window, and enter the following command:

      \n
      $ node hello-world.js\n
      \n

      Output like this should appear in the terminal:

      \n
      Server running at http://127.0.0.1:3000/\n
      \n

      Now, open any preferred web browser and visit http://127.0.0.1:3000.

      \n

      If the browser displays the string Hello, World!, that indicates\nthe server is working.

      " + } + ], + "type": "module", + "displayName": "Usage and example" + }, + { + "textRaw": "Assert", + "name": "assert", + "introduced_in": "v0.1.21", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/assert.js

      \n

      The assert module provides a set of assertion functions for verifying\ninvariants.

      ", + "modules": [ + { + "textRaw": "Strict assertion mode", + "name": "strict_assertion_mode", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [ + { + "version": "v12.16.2", + "description": "Changed \"strict mode\" to \"strict assertion mode\" and \"legacy mode\" to \"legacy assertion mode\" to avoid confusion with the more usual meaning of \"strict mode\"." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17615", + "description": "Added error diffs to the strict assertion mode." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17002", + "description": "Added strict assertion mode to the assert module." + } + ] + }, + "desc": "

      In strict assertion mode, non-strict methods behave like their corresponding\nstrict methods. For example, assert.deepEqual() will behave like\nassert.deepStrictEqual().

      \n

      In strict assertion mode, error messages for objects display a diff. In legacy\nassertion mode, error messages for objects display the objects, often truncated.

      \n

      To use strict assertion mode:

      \n
      const assert = require('assert').strict;\n
      \n

      Example error diff:

      \n
      const assert = require('assert').strict;\n\nassert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected ... Lines skipped\n//\n//   [\n//     [\n// ...\n//       2,\n// +     3\n// -     '3'\n//     ],\n// ...\n//     5\n//   ]\n
      \n

      To deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS\nenvironment variables. This will also deactivate the colors in the REPL. For\nmore on color support in terminal environments, read the tty\ngetColorDepth() documentation.

      ", + "type": "module", + "displayName": "Strict assertion mode" + }, + { + "textRaw": "Legacy assertion mode", + "name": "legacy_assertion_mode", + "desc": "

      Legacy assertion mode uses the Abstract Equality Comparison in:

      \n\n

      To use legacy assertion mode:

      \n
      const assert = require('assert');\n
      \n

      Whenever possible, use the strict assertion mode instead. Otherwise, the\nAbstract Equality Comparison may cause surprising results. This is\nespecially true for assert.deepEqual(), where the comparison rules are\nlax:

      \n
      // WARNING: This does not throw an AssertionError!\nassert.deepEqual(/a/gi, new Date());\n
      ", + "type": "module", + "displayName": "Legacy assertion mode" + } + ], + "classes": [ + { + "textRaw": "Class: assert.AssertionError", + "type": "class", + "name": "assert.AssertionError", + "desc": "\n

      Indicates the failure of an assertion. All errors thrown by the assert module\nwill be instances of the AssertionError class.

      ", + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`message` {string} If provided, the error message is set to this value.", + "name": "message", + "type": "string", + "desc": "If provided, the error message is set to this value." + }, + { + "textRaw": "`actual` {any} The `actual` property on the error instance.", + "name": "actual", + "type": "any", + "desc": "The `actual` property on the error instance." + }, + { + "textRaw": "`expected` {any} The `expected` property on the error instance.", + "name": "expected", + "type": "any", + "desc": "The `expected` property on the error instance." + }, + { + "textRaw": "`operator` {string} The `operator` property on the error instance.", + "name": "operator", + "type": "string", + "desc": "The `operator` property on the error instance." + }, + { + "textRaw": "`stackStartFn` {Function} If provided, the generated stack trace omits frames before this function.", + "name": "stackStartFn", + "type": "Function", + "desc": "If provided, the generated stack trace omits frames before this function." + } + ] + } + ], + "desc": "

      A subclass of Error that indicates the failure of an assertion.

      \n

      All instances contain the built-in Error properties (message and name)\nand:

      \n
        \n
      • actual <any> Set to the actual argument for methods such as\nassert.strictEqual().
      • \n
      • expected <any> Set to the expected value for methods such as\nassert.strictEqual().
      • \n
      • generatedMessage <boolean> Indicates if the message was auto-generated\n(true) or not.
      • \n
      • code <string> Value is always ERR_ASSERTION to show that the error is an\nassertion error.
      • \n
      • operator <string> Set to the passed in operator value.
      • \n
      \n
      const assert = require('assert');\n\n// Generate an AssertionError to compare the error message later:\nconst { message } = new assert.AssertionError({\n  actual: 1,\n  expected: 2,\n  operator: 'strictEqual'\n});\n\n// Verify error output:\ntry {\n  assert.strictEqual(1, 2);\n} catch (err) {\n  assert(err instanceof assert.AssertionError);\n  assert.strictEqual(err.message, message);\n  assert.strictEqual(err.name, 'AssertionError');\n  assert.strictEqual(err.actual, 1);\n  assert.strictEqual(err.expected, 2);\n  assert.strictEqual(err.code, 'ERR_ASSERTION');\n  assert.strictEqual(err.operator, 'strictEqual');\n  assert.strictEqual(err.generatedMessage, true);\n}\n
      " + } + ] + }, + { + "textRaw": "Class: `assert.CallTracker`", + "type": "class", + "name": "assert.CallTracker", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      This feature is currently experimental and behavior might still change.

      \n

      ### new assert.CallTracker()

      \n

      Creates a new CallTracker object which can be used to track if functions\nwere called a specific number of times. The tracker.verify() must be called\nfor the verification to take place. The usual pattern would be to call it in a\nprocess.on('exit') handler.

      \n
      const assert = require('assert');\n\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// callsfunc() must be called exactly 1 time before tracker.verify().\nconst callsfunc = tracker.calls(func, 1);\n\ncallsfunc();\n\n// Calls tracker.verify() and verifies if all tracker.calls() functions have\n// been called exact times.\nprocess.on('exit', () => {\n  tracker.verify();\n});\n
      ", + "methods": [ + { + "textRaw": "`tracker.calls([fn][, exact])`", + "type": "method", + "name": "calls", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} that wraps `fn`.", + "name": "return", + "type": "Function", + "desc": "that wraps `fn`." + }, + "params": [ + { + "textRaw": "`fn` {Function} **Default** A no-op function.", + "name": "fn", + "type": "Function", + "desc": "**Default** A no-op function." + }, + { + "textRaw": "`exact` {number} **Default** `1`.", + "name": "exact", + "type": "number", + "desc": "**Default** `1`." + } + ] + } + ], + "desc": "

      The wrapper function is expected to be called exactly exact times. If the\nfunction has not been called exactly exact times when\ntracker.verify() is called, then tracker.verify() will throw an\nerror.

      \n
      const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func);\n
      " + }, + { + "textRaw": "`tracker.report()`", + "type": "method", + "name": "report", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Array} of objects containing information about the wrapper functions returned by [`tracker.calls()`][].", + "name": "return", + "type": "Array", + "desc": "of objects containing information about the wrapper functions returned by [`tracker.calls()`][]." + }, + "params": [ + { + "textRaw": "Object {Object}", + "name": "Object", + "type": "Object", + "options": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + }, + { + "textRaw": "`actual` {number} The actual number of times the function was called.", + "name": "actual", + "type": "number", + "desc": "The actual number of times the function was called." + }, + { + "textRaw": "`expected` {number} The number of times the function was expected to be called.", + "name": "expected", + "type": "number", + "desc": "The number of times the function was expected to be called." + }, + { + "textRaw": "`operator` {string} The name of the function that is wrapped.", + "name": "operator", + "type": "string", + "desc": "The name of the function that is wrapped." + }, + { + "textRaw": "`stack` {Object} A stack trace of the function.", + "name": "stack", + "type": "Object", + "desc": "A stack trace of the function." + } + ] + } + ] + } + ], + "desc": "

      The arrays contains information about the expected and actual number of calls of\nthe functions that have not been called the expected number of times.

      \n
      const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\nfunction foo() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\n// Returns an array containing information on callsfunc()\ntracker.report();\n// [\n//  {\n//    message: 'Expected the func function to be executed 2 time(s) but was\n//    executed 0 time(s).',\n//    actual: 0,\n//    expected: 2,\n//    operator: 'func',\n//    stack: stack trace\n//  }\n// ]\n
      " + }, + { + "textRaw": "`tracker.verify()`", + "type": "method", + "name": "verify", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Iterates through the list of functions passed to\ntracker.calls() and will throw an error for functions that\nhave not been called the expected number of times.

      \n
      const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\ncallsfunc();\n\n// Will throw an error since callsfunc() was only called once.\ntracker.verify();\n
      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`assert(value[, message])`", + "type": "method", + "name": "assert", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any} The input that is checked for being truthy.", + "name": "value", + "type": "any", + "desc": "The input that is checked for being truthy." + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      An alias of assert.ok().

      " + }, + { + "textRaw": "`assert.deepEqual(actual, expected[, message])`", + "type": "method", + "name": "deepEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25008", + "description": "The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.deepStrictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.deepStrictEqual() instead.

      \n
      \n

      Tests for deep equality between the actual and expected parameters. Consider\nusing assert.deepStrictEqual() instead. assert.deepEqual() can have\nsurprising results.

      \n

      Deep equality means that the enumerable \"own\" properties of child objects\nare also recursively evaluated by the following rules.

      ", + "modules": [ + { + "textRaw": "Comparison details", + "name": "comparison_details", + "desc": "
        \n
      • Primitive values are compared with the Abstract Equality Comparison\n( == ).
      • \n
      • Type tags of objects should be the same.
      • \n
      • Only enumerable \"own\" properties are considered.
      • \n
      • Error names and messages are always compared, even if these are not\nenumerable properties.
      • \n
      • Object wrappers are compared both as objects and unwrapped values.
      • \n
      • Object properties are compared unordered.
      • \n
      • Map keys and Set items are compared unordered.
      • \n
      • Recursion stops when both sides differ or both sides encounter a circular\nreference.
      • \n
      • Implementation does not test the [[Prototype]] of\nobjects.
      • \n
      • Symbol properties are not compared.
      • \n
      • WeakMap and WeakSet comparison does not rely on their values.
      • \n
      \n

      The following example does not throw an AssertionError because the\nprimitives are considered equal by the Abstract Equality Comparison\n( == ).

      \n
      // WARNING: This does not throw an AssertionError!\nassert.deepEqual('+00000000', false);\n
      \n

      \"Deep\" equality means that the enumerable \"own\" properties of child objects\nare evaluated also:

      \n
      const assert = require('assert');\n\nconst obj1 = {\n  a: {\n    b: 1\n  }\n};\nconst obj2 = {\n  a: {\n    b: 2\n  }\n};\nconst obj3 = {\n  a: {\n    b: 1\n  }\n};\nconst obj4 = Object.create(obj1);\n\nassert.deepEqual(obj1, obj1);\n// OK\n\n// Values of b are different:\nassert.deepEqual(obj1, obj2);\n// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }\n\nassert.deepEqual(obj1, obj3);\n// OK\n\n// Prototypes are ignored:\nassert.deepEqual(obj1, obj4);\n// AssertionError: { a: { b: 1 } } deepEqual {}\n
      \n

      If the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      ", + "type": "module", + "displayName": "Comparison details" + } + ] + }, + { + "textRaw": "`assert.deepStrictEqual(actual, expected[, message])`", + "type": "method", + "name": "deepStrictEqual", + "meta": { + "added": [ + "v1.2.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15169", + "description": "Enumerable symbol properties are now compared." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15036", + "description": "The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison." + }, + { + "version": "v8.5.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests for deep equality between the actual and expected parameters.\n\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare recursively evaluated also by the following rules.

      ", + "modules": [ + { + "textRaw": "Comparison details", + "name": "comparison_details", + "desc": "\n
      const assert = require('assert').strict;\n\n// This fails because 1 !== '1'.\nassert.deepStrictEqual({ a: 1 }, { a: '1' });\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n//   {\n// +   a: 1\n// -   a: '1'\n//   }\n\n// The following objects don't have own properties\nconst date = new Date();\nconst object = {};\nconst fakeDate = {};\nObject.setPrototypeOf(fakeDate, Date.prototype);\n\n// Different [[Prototype]]:\nassert.deepStrictEqual(object, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + {}\n// - Date {}\n\n// Different type tags:\nassert.deepStrictEqual(date, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 2018-04-26T00:49:08.604Z\n// - Date {}\n\nassert.deepStrictEqual(NaN, NaN);\n// OK, because of the SameValue comparison\n\n// Different unwrapped numbers:\nassert.deepStrictEqual(new Number(1), new Number(2));\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + [Number: 1]\n// - [Number: 2]\n\nassert.deepStrictEqual(new String('foo'), Object('foo'));\n// OK because the object and the string are identical when unwrapped.\n\nassert.deepStrictEqual(-0, -0);\n// OK\n\n// Different zeros using the SameValue Comparison:\nassert.deepStrictEqual(0, -0);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 0\n// - -0\n\nconst symbol1 = Symbol();\nconst symbol2 = Symbol();\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });\n// OK, because it is the same symbol on both objects.\n\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });\n// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:\n//\n// {\n//   [Symbol()]: 1\n// }\n\nconst weakMap1 = new WeakMap();\nconst weakMap2 = new WeakMap([[{}, {}]]);\nconst weakMap3 = new WeakMap();\nweakMap3.unequal = true;\n\nassert.deepStrictEqual(weakMap1, weakMap2);\n// OK, because it is impossible to compare the entries\n\n// Fails because weakMap3 has a property that weakMap1 does not contain:\nassert.deepStrictEqual(weakMap1, weakMap3);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n//   WeakMap {\n// +   [items unknown]\n// -   [items unknown],\n// -   unequal: true\n//   }\n
      \n

      If the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      ", + "type": "module", + "displayName": "Comparison details" + } + ] + }, + { + "textRaw": "`assert.doesNotMatch(string, regexp[, message])`", + "type": "method", + "name": "doesNotMatch", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`regexp` {RegExp}", + "name": "regexp", + "type": "RegExp" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Expects the string input not to match the regular expression.

      \n

      This feature is currently experimental and the name might change or it might be\ncompletely removed again.

      \n
      const assert = require('assert').strict;\n\nassert.doesNotMatch('I will fail', /fail/);\n// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...\n\nassert.doesNotMatch(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.doesNotMatch('I will pass', /different/);\n// OK\n
      \n

      If the values do match, or if the string argument is of another type than\nstring, an AssertionError is thrown with a message property set equal\nto the value of the message parameter. If the message parameter is\nundefined, a default error message is assigned. If the message parameter is an\ninstance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.doesNotReject(asyncFn[, error][, message])`", + "type": "method", + "name": "doesNotReject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncFn` {Function|Promise}", + "name": "asyncFn", + "type": "Function|Promise" + }, + { + "textRaw": "`error` {RegExp|Function}", + "name": "error", + "type": "RegExp|Function" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Awaits the asyncFn promise or, if asyncFn is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is not rejected.

      \n

      If asyncFn is a function and it throws an error synchronously,\nassert.doesNotReject() will return a rejected Promise with that error. If\nthe function does not return a promise, assert.doesNotReject() will return a\nrejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases\nthe error handler is skipped.

      \n

      Using assert.doesNotReject() is actually not useful because there is little\nbenefit in catching a rejection and then rejecting it again. Instead, consider\nadding a comment next to the specific code path that should not reject and keep\nerror messages as expressive as possible.

      \n

      If specified, error can be a Class, RegExp or a validation\nfunction. See assert.throws() for more details.

      \n

      Besides the async nature to await the completion behaves identically to\nassert.doesNotThrow().

      \n\n
      (async () => {\n  await assert.doesNotReject(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    SyntaxError\n  );\n})();\n
      \n\n
      assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n  .then(() => {\n    // ...\n  });\n
      " + }, + { + "textRaw": "`assert.doesNotThrow(fn[, error][, message])`", + "type": "method", + "name": "doesNotThrow", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v5.11.0, v4.4.5", + "pr-url": "https://github.com/nodejs/node/pull/2407", + "description": "The `message` parameter is respected now." + }, + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3276", + "description": "The `error` parameter can now be an arrow function." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + }, + { + "textRaw": "`error` {RegExp|Function}", + "name": "error", + "type": "RegExp|Function" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Asserts that the function fn does not throw an error.

      \n

      Using assert.doesNotThrow() is actually not useful because there\nis no benefit in catching an error and then rethrowing it. Instead, consider\nadding a comment next to the specific code path that should not throw and keep\nerror messages as expressive as possible.

      \n

      When assert.doesNotThrow() is called, it will immediately call the fn\nfunction.

      \n

      If an error is thrown and it is the same type as that specified by the error\nparameter, then an AssertionError is thrown. If the error is of a\ndifferent type, or if the error parameter is undefined, the error is\npropagated back to the caller.

      \n

      If specified, error can be a Class, RegExp or a validation\nfunction. See assert.throws() for more details.

      \n

      The following, for instance, will throw the TypeError because there is no\nmatching error type in the assertion:

      \n\n
      assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  SyntaxError\n);\n
      \n

      However, the following will result in an AssertionError with the message\n'Got unwanted exception...':

      \n\n
      assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  TypeError\n);\n
      \n

      If an AssertionError is thrown and a value is provided for the message\nparameter, the value of message will be appended to the AssertionError\nmessage:

      \n\n
      assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  /Wrong value/,\n  'Whoops'\n);\n// Throws: AssertionError: Got unwanted exception: Whoops\n
      " + }, + { + "textRaw": "`assert.equal(actual, expected[, message])`", + "type": "method", + "name": "equal", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.strictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.strictEqual() instead.

      \n
      \n

      Tests shallow, coercive equality between the actual and expected parameters\nusing the Abstract Equality Comparison ( == ).

      \n
      const assert = require('assert');\n\nassert.equal(1, 1);\n// OK, 1 == 1\nassert.equal(1, '1');\n// OK, 1 == '1'\n\nassert.equal(1, 2);\n// AssertionError: 1 == 2\nassert.equal({ a: { b: 1 } }, { a: { b: 1 } });\n// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }\n
      \n

      If the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.fail([message])`", + "type": "method", + "name": "fail", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string|Error} **Default:** `'Failed'`", + "name": "message", + "type": "string|Error", + "default": "`'Failed'`" + } + ] + } + ], + "desc": "

      Throws an AssertionError with the provided error message or a default\nerror message. If the message parameter is an instance of an Error then\nit will be thrown instead of the AssertionError.

      \n
      const assert = require('assert').strict;\n\nassert.fail();\n// AssertionError [ERR_ASSERTION]: Failed\n\nassert.fail('boom');\n// AssertionError [ERR_ASSERTION]: boom\n\nassert.fail(new TypeError('need array'));\n// TypeError: need array\n
      \n

      Using assert.fail() with more than two arguments is possible but deprecated.\nSee below for further details.

      " + }, + { + "textRaw": "`assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`", + "type": "method", + "name": "fail", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18418", + "description": "Calling `assert.fail()` with more than one argument is deprecated and emits a warning." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `assert.fail([message])` or other assert\nfunctions instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + }, + { + "textRaw": "`operator` {string} **Default:** `'!='`", + "name": "operator", + "type": "string", + "default": "`'!='`" + }, + { + "textRaw": "`stackStartFn` {Function} **Default:** `assert.fail`", + "name": "stackStartFn", + "type": "Function", + "default": "`assert.fail`" + } + ] + } + ], + "desc": "

      If message is falsy, the error message is set as the values of actual and\nexpected separated by the provided operator. If just the two actual and\nexpected arguments are provided, operator will default to '!='. If\nmessage is provided as third argument it will be used as the error message and\nthe other arguments will be stored as properties on the thrown object. If\nstackStartFn is provided, all stack frames above that function will be\nremoved from stacktrace (see Error.captureStackTrace). If no arguments are\ngiven, the default message Failed will be used.

      \n
      const assert = require('assert').strict;\n\nassert.fail('a', 'b');\n// AssertionError [ERR_ASSERTION]: 'a' != 'b'\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError [ERR_ASSERTION]: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError [ERR_ASSERTION]: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError [ERR_ASSERTION]: whoops\n\nassert.fail(1, 2, new TypeError('need array'));\n// TypeError: need array\n
      \n

      In the last three cases actual, expected, and operator have no\ninfluence on the error message.

      \n

      Example use of stackStartFn for truncating the exception's stacktrace:

      \n
      function suppressFrame() {\n  assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError [ERR_ASSERTION]: 'a' !== 'b'\n//     at repl:1:1\n//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n//     ...\n
      " + }, + { + "textRaw": "`assert.ifError(value)`", + "type": "method", + "name": "ifError", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18247", + "description": "Instead of throwing the original error it is now wrapped into an [`AssertionError`][] that contains the full stack trace." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18247", + "description": "Value may now only be `undefined` or `null`. Before all falsy values were handled the same as `null` and did not throw." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Throws value if value is not undefined or null. This is useful when\ntesting the error argument in callbacks. The stack trace contains all frames\nfrom the error passed to ifError() including the potential new frames for\nifError() itself.

      \n
      const assert = require('assert').strict;\n\nassert.ifError(null);\n// OK\nassert.ifError(0);\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0\nassert.ifError('error');\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'\nassert.ifError(new Error());\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error\n\n// Create some random error frames.\nlet err;\n(function errorFrame() {\n  err = new Error('test error');\n})();\n\n(function ifErrorFrame() {\n  assert.ifError(err);\n})();\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error\n//     at ifErrorFrame\n//     at errorFrame\n
      " + }, + { + "textRaw": "`assert.match(string, regexp[, message])`", + "type": "method", + "name": "match", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`regexp` {RegExp}", + "name": "regexp", + "type": "RegExp" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Expects the string input to match the regular expression.

      \n

      This feature is currently experimental and the name might change or it might be\ncompletely removed again.

      \n
      const assert = require('assert').strict;\n\nassert.match('I will fail', /pass/);\n// AssertionError [ERR_ASSERTION]: The input did not match the regular ...\n\nassert.match(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.match('I will pass', /pass/);\n// OK\n
      \n

      If the values do not match, or if the string argument is of another type than\nstring, an AssertionError is thrown with a message property set equal\nto the value of the message parameter. If the message parameter is\nundefined, a default error message is assigned. If the message parameter is an\ninstance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.notDeepEqual(actual, expected[, message])`", + "type": "method", + "name": "notDeepEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.notDeepStrictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.notDeepStrictEqual() instead.

      \n
      \n

      Tests for any deep inequality. Opposite of assert.deepEqual().

      \n
      const assert = require('assert');\n\nconst obj1 = {\n  a: {\n    b: 1\n  }\n};\nconst obj2 = {\n  a: {\n    b: 2\n  }\n};\nconst obj3 = {\n  a: {\n    b: 1\n  }\n};\nconst obj4 = Object.create(obj1);\n\nassert.notDeepEqual(obj1, obj1);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj2);\n// OK\n\nassert.notDeepEqual(obj1, obj3);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj4);\n// OK\n
      \n

      If the values are deeply equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.notDeepStrictEqual(actual, expected[, message])`", + "type": "method", + "name": "notDeepStrictEqual", + "meta": { + "added": [ + "v1.2.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15398", + "description": "The `-0` and `+0` are not considered equal anymore." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15036", + "description": "The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests for deep strict inequality. Opposite of assert.deepStrictEqual().

      \n
      const assert = require('assert').strict;\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n
      \n

      If the values are deeply and strictly equal, an AssertionError is thrown\nwith a message property set equal to the value of the message parameter. If\nthe message parameter is undefined, a default error message is assigned. If\nthe message parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.notEqual(actual, expected[, message])`", + "type": "method", + "name": "notEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.notStrictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.notStrictEqual() instead.

      \n
      \n

      Tests shallow, coercive inequality with the Abstract Equality Comparison\n( != ).

      \n
      const assert = require('assert');\n\nassert.notEqual(1, 2);\n// OK\n\nassert.notEqual(1, 1);\n// AssertionError: 1 != 1\n\nassert.notEqual(1, '1');\n// AssertionError: 1 != '1'\n
      \n

      If the values are equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.notStrictEqual(actual, expected[, message])`", + "type": "method", + "name": "notStrictEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17003", + "description": "Used comparison changed from Strict Equality to `Object.is()`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests strict inequality between the actual and expected parameters as\ndetermined by the SameValue Comparison.

      \n
      const assert = require('assert').strict;\n\nassert.notStrictEqual(1, 2);\n// OK\n\nassert.notStrictEqual(1, 1);\n// AssertionError [ERR_ASSERTION]: Expected \"actual\" to be strictly unequal to:\n//\n// 1\n\nassert.notStrictEqual(1, '1');\n// OK\n
      \n

      If the values are strictly equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.ok(value[, message])`", + "type": "method", + "name": "ok", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18319", + "description": "The `assert.ok()` (no arguments) will now use a predefined error message." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests if value is truthy. It is equivalent to\nassert.equal(!!value, true, message).

      \n

      If value is not truthy, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.\nIf no arguments are passed in at all message will be set to the string:\n'No value argument passed to `assert.ok()`'.

      \n

      Be aware that in the repl the error message will be different to the one\nthrown in a file! See below for further details.

      \n
      const assert = require('assert').strict;\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\n\nassert.ok();\n// AssertionError: No value argument passed to `assert.ok()`\n\nassert.ok(false, 'it\\'s false');\n// AssertionError: it's false\n\n// In the repl:\nassert.ok(typeof 123 === 'string');\n// AssertionError: false == true\n\n// In a file (e.g. test.js):\nassert.ok(typeof 123 === 'string');\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert.ok(typeof 123 === 'string')\n\nassert.ok(false);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert.ok(false)\n\nassert.ok(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert.ok(0)\n\n// Using `assert()` works the same:\nassert(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert(0)\n
      " + }, + { + "textRaw": "`assert.rejects(asyncFn[, error][, message])`", + "type": "method", + "name": "rejects", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncFn` {Function|Promise}", + "name": "asyncFn", + "type": "Function|Promise" + }, + { + "textRaw": "`error` {RegExp|Function|Object|Error}", + "name": "error", + "type": "RegExp|Function|Object|Error" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Awaits the asyncFn promise or, if asyncFn is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is rejected.

      \n

      If asyncFn is a function and it throws an error synchronously,\nassert.rejects() will return a rejected Promise with that error. If the\nfunction does not return a promise, assert.rejects() will return a rejected\nPromise with an ERR_INVALID_RETURN_VALUE error. In both cases the error\nhandler is skipped.

      \n

      Besides the async nature to await the completion behaves identically to\nassert.throws().

      \n

      If specified, error can be a Class, RegExp, a validation function,\nan object where each property will be tested for, or an instance of error where\neach property will be tested for including the non-enumerable message and\nname properties.

      \n

      If specified, message will be the message provided by the AssertionError\nif the asyncFn fails to reject.

      \n
      (async () => {\n  await assert.rejects(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    {\n      name: 'TypeError',\n      message: 'Wrong value'\n    }\n  );\n})();\n
      \n
      (async () => {\n  await assert.rejects(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    (err) => {\n      assert.strictEqual(err.name, 'TypeError');\n      assert.strictEqual(err.message, 'Wrong value');\n      return true;\n    }\n  );\n})();\n
      \n
      assert.rejects(\n  Promise.reject(new Error('Wrong value')),\n  Error\n).then(() => {\n  // ...\n});\n
      \n

      error cannot be a string. If a string is provided as the second\nargument, then error is assumed to be omitted and the string will be used for\nmessage instead. This can lead to easy-to-miss mistakes. Please read the\nexample in assert.throws() carefully if using a string as the second\nargument gets considered.

      " + }, + { + "textRaw": "`assert.strictEqual(actual, expected[, message])`", + "type": "method", + "name": "strictEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17003", + "description": "Used comparison changed from Strict Equality to `Object.is()`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests strict equality between the actual and expected parameters as\ndetermined by the SameValue Comparison.

      \n
      const assert = require('assert').strict;\n\nassert.strictEqual(1, 2);\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n//\n// 1 !== 2\n\nassert.strictEqual(1, 1);\n// OK\n\nassert.strictEqual('Hello foobar', 'Hello World!');\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n// + actual - expected\n//\n// + 'Hello foobar'\n// - 'Hello World!'\n//          ^\n\nconst apples = 1;\nconst oranges = 2;\nassert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);\n// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2\n\nassert.strictEqual(1, '1', new TypeError('Inputs are not identical'));\n// TypeError: Inputs are not identical\n
      \n

      If the values are not strictly equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.throws(fn[, error][, message])`", + "type": "method", + "name": "throws", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20485", + "description": "The `error` parameter can be an object containing regular expressions now." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17584", + "description": "The `error` parameter can now be an object as well." + }, + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3276", + "description": "The `error` parameter can now be an arrow function." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + }, + { + "textRaw": "`error` {RegExp|Function|Object|Error}", + "name": "error", + "type": "RegExp|Function|Object|Error" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Expects the function fn to throw an error.

      \n

      If specified, error can be a Class, RegExp, a validation function,\na validation object where each property will be tested for strict deep equality,\nor an instance of error where each property will be tested for strict deep\nequality including the non-enumerable message and name properties. When\nusing an object, it is also possible to use a regular expression, when\nvalidating against a string property. See below for examples.

      \n

      If specified, message will be appended to the message provided by the\nAssertionError if the fn call fails to throw or in case the error validation\nfails.

      \n

      Custom validation object/error instance:

      \n
      const err = new TypeError('Wrong value');\nerr.code = 404;\nerr.foo = 'bar';\nerr.info = {\n  nested: true,\n  baz: 'text'\n};\nerr.reg = /abc/i;\n\nassert.throws(\n  () => {\n    throw err;\n  },\n  {\n    name: 'TypeError',\n    message: 'Wrong value',\n    info: {\n      nested: true,\n      baz: 'text'\n    }\n    // Only properties on the validation object will be tested for.\n    // Using nested objects requires all properties to be present. Otherwise\n    // the validation is going to fail.\n  }\n);\n\n// Using regular expressions to validate error properties:\nassert.throws(\n  () => {\n    throw err;\n  },\n  {\n    // The `name` and `message` properties are strings and using regular\n    // expressions on those will match against the string. If they fail, an\n    // error is thrown.\n    name: /^TypeError$/,\n    message: /Wrong/,\n    foo: 'bar',\n    info: {\n      nested: true,\n      // It is not possible to use regular expressions for nested properties!\n      baz: 'text'\n    },\n    // The `reg` property contains a regular expression and only if the\n    // validation object contains an identical regular expression, it is going\n    // to pass.\n    reg: /abc/i\n  }\n);\n\n// Fails due to the different `message` and `name` properties:\nassert.throws(\n  () => {\n    const otherErr = new Error('Not found');\n    // Copy all enumerable properties from `err` to `otherErr`.\n    for (const [key, value] of Object.entries(err)) {\n      otherErr[key] = value;\n    }\n    throw otherErr;\n  },\n  // The error's `message` and `name` properties will also be checked when using\n  // an error as validation object.\n  err\n);\n
      \n

      Validate instanceof using constructor:

      \n
      assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  Error\n);\n
      \n

      Validate error message using RegExp:

      \n

      Using a regular expression runs .toString on the error object, and will\ntherefore also include the error name.

      \n
      assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  /^Error: Wrong value$/\n);\n
      \n

      Custom error validation:

      \n

      The function must return true to indicate all internal validations passed.\nIt will otherwise fail with an AssertionError.

      \n
      assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  (err) => {\n    assert(err instanceof Error);\n    assert(/value/.test(err));\n    // Avoid returning anything from validation functions besides `true`.\n    // Otherwise, it's not clear what part of the validation failed. Instead,\n    // throw an error about the specific validation that failed (as done in this\n    // example) and add as much helpful debugging information to that error as\n    // possible.\n    return true;\n  },\n  'unexpected error'\n);\n
      \n

      error cannot be a string. If a string is provided as the second\nargument, then error is assumed to be omitted and the string will be used for\nmessage instead. This can lead to easy-to-miss mistakes. Using the same\nmessage as the thrown error message is going to result in an\nERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using\na string as the second argument gets considered:

      \n\n
      function throwingFirst() {\n  throw new Error('First');\n}\n\nfunction throwingSecond() {\n  throw new Error('Second');\n}\n\nfunction notThrowing() {}\n\n// The second argument is a string and the input function threw an Error.\n// The first case will not throw as it does not match for the error message\n// thrown by the input function!\nassert.throws(throwingFirst, 'Second');\n// In the next example the message has no benefit over the message from the\n// error and since it is not clear if the user intended to actually match\n// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.\nassert.throws(throwingSecond, 'Second');\n// TypeError [ERR_AMBIGUOUS_ARGUMENT]\n\n// The string is only used (as message) in case the function does not throw:\nassert.throws(notThrowing, 'Second');\n// AssertionError [ERR_ASSERTION]: Missing expected exception: Second\n\n// If it was intended to match for the error message do this instead:\n// It does not throw because the error messages match.\nassert.throws(throwingSecond, /Second$/);\n\n// If the error message does not match, an AssertionError is thrown.\nassert.throws(throwingFirst, /Second$/);\n// AssertionError [ERR_ASSERTION]\n
      \n

      Due to the confusing error-prone notation, avoid a string as the second\nargument.

      " + } + ], + "type": "module", + "displayName": "Assert" + }, + { + "textRaw": "Async hooks", + "name": "async_hooks", + "introduced_in": "v8.1.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/async_hooks.js

      \n

      The async_hooks module provides an API to track asynchronous resources. It\ncan be accessed using:

      \n
      const async_hooks = require('async_hooks');\n
      ", + "modules": [ + { + "textRaw": "Terminology", + "name": "terminology", + "desc": "

      An asynchronous resource represents an object with an associated callback.\nThis callback may be called multiple times, for example, the 'connection'\nevent in net.createServer(), or just a single time like in fs.open().\nA resource can also be closed before the callback is called. AsyncHook does\nnot explicitly distinguish between these different cases but will represent them\nas the abstract concept that is a resource.

      \n

      If Workers are used, each thread has an independent async_hooks\ninterface, and each thread will use a new set of async IDs.

      ", + "type": "module", + "displayName": "Terminology" + }, + { + "textRaw": "Public API", + "name": "public_api", + "modules": [ + { + "textRaw": "Overview", + "name": "overview", + "desc": "

      Following is a simple overview of the public API.

      \n
      const async_hooks = require('async_hooks');\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init is called during object construction. The resource may not have\n// completed construction when this callback runs, therefore all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// Before is called just before the resource's callback is called. It can be\n// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1\n// time for requests (e.g. FSReqCallback).\nfunction before(asyncId) { }\n\n// After is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// Destroy is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve is called only for promise resources, when the\n// `resolve` function passed to the `Promise` constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n
      ", + "methods": [ + { + "textRaw": "`async_hooks.createHook(callbacks)`", + "type": "method", + "name": "createHook", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncHook} Instance used for disabling and enabling hooks", + "name": "return", + "type": "AsyncHook", + "desc": "Instance used for disabling and enabling hooks" + }, + "params": [ + { + "textRaw": "`callbacks` {Object} The [Hook Callbacks][] to register", + "name": "callbacks", + "type": "Object", + "desc": "The [Hook Callbacks][] to register", + "options": [ + { + "textRaw": "`init` {Function} The [`init` callback][].", + "name": "init", + "type": "Function", + "desc": "The [`init` callback][]." + }, + { + "textRaw": "`before` {Function} The [`before` callback][].", + "name": "before", + "type": "Function", + "desc": "The [`before` callback][]." + }, + { + "textRaw": "`after` {Function} The [`after` callback][].", + "name": "after", + "type": "Function", + "desc": "The [`after` callback][]." + }, + { + "textRaw": "`destroy` {Function} The [`destroy` callback][].", + "name": "destroy", + "type": "Function", + "desc": "The [`destroy` callback][]." + }, + { + "textRaw": "`promiseResolve` {Function} The [`promiseResolve` callback][].", + "name": "promiseResolve", + "type": "Function", + "desc": "The [`promiseResolve` callback][]." + } + ] + } + ] + } + ], + "desc": "

      Registers functions to be called for different lifetime events of each async\noperation.

      \n

      The callbacks init()/before()/after()/destroy() are called for the\nrespective asynchronous event during a resource's lifetime.

      \n

      All callbacks are optional. For example, if only resource cleanup needs to\nbe tracked, then only the destroy callback needs to be passed. The\nspecifics of all functions that can be passed to callbacks is in the\nHook Callbacks section.

      \n
      const async_hooks = require('async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { }\n});\n
      \n

      The callbacks will be inherited via the prototype chain:

      \n
      class MyAsyncCallbacks {\n  init(asyncId, type, triggerAsyncId, resource) { }\n  destroy(asyncId) {}\n}\n\nclass MyAddedCallbacks extends MyAsyncCallbacks {\n  before(asyncId) { }\n  after(asyncId) { }\n}\n\nconst asyncHook = async_hooks.createHook(new MyAddedCallbacks());\n
      ", + "modules": [ + { + "textRaw": "Error handling", + "name": "error_handling", + "desc": "

      If any AsyncHook callbacks throw, the application will print the stack trace\nand exit. The exit path does follow that of an uncaught exception, but\nall 'uncaughtException' listeners are removed, thus forcing the process to\nexit. The 'exit' callbacks will still be called unless the application is run\nwith --abort-on-uncaught-exception, in which case a stack trace will be\nprinted and the application exits, leaving a core file.

      \n

      The reason for this error handling behavior is that these callbacks are running\nat potentially volatile points in an object's lifetime, for example during\nclass construction and destruction. Because of this, it is deemed necessary to\nbring down the process quickly in order to prevent an unintentional abort in the\nfuture. This is subject to change in the future if a comprehensive analysis is\nperformed to ensure an exception can follow the normal control flow without\nunintentional side effects.

      ", + "type": "module", + "displayName": "Error handling" + }, + { + "textRaw": "Printing in AsyncHooks callbacks", + "name": "printing_in_asynchooks_callbacks", + "desc": "

      Because printing to the console is an asynchronous operation, console.log()\nwill cause the AsyncHooks callbacks to be called. Using console.log() or\nsimilar asynchronous operations inside an AsyncHooks callback function will thus\ncause an infinite recursion. An easy solution to this when debugging is to use a\nsynchronous logging operation such as fs.writeFileSync(file, msg, flag).\nThis will print to the file and will not invoke AsyncHooks recursively because\nit is synchronous.

      \n
      const fs = require('fs');\nconst util = require('util');\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHooks callback\n  fs.writeFileSync('log.out', `${util.format(...args)}\\n`, { flag: 'a' });\n}\n
      \n

      If an asynchronous operation is needed for logging, it is possible to keep\ntrack of what caused the asynchronous operation using the information\nprovided by AsyncHooks itself. The logging should then be skipped when\nit was the logging itself that caused AsyncHooks callback to call. By\ndoing this the otherwise infinite recursion is broken.

      ", + "type": "module", + "displayName": "Printing in AsyncHooks callbacks" + } + ] + } + ], + "type": "module", + "displayName": "Overview" + } + ], + "classes": [ + { + "textRaw": "Class: `AsyncHook`", + "type": "class", + "name": "AsyncHook", + "desc": "

      The class AsyncHook exposes an interface for tracking lifetime events\nof asynchronous operations.

      ", + "methods": [ + { + "textRaw": "`asyncHook.enable()`", + "type": "method", + "name": "enable", + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.", + "name": "return", + "type": "AsyncHook", + "desc": "A reference to `asyncHook`." + }, + "params": [] + } + ], + "desc": "

      Enable the callbacks for a given AsyncHook instance. If no callbacks are\nprovided enabling is a noop.

      \n

      The AsyncHook instance is disabled by default. If the AsyncHook instance\nshould be enabled immediately after creation, the following pattern can be used.

      \n
      const async_hooks = require('async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();\n
      " + }, + { + "textRaw": "`asyncHook.disable()`", + "type": "method", + "name": "disable", + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.", + "name": "return", + "type": "AsyncHook", + "desc": "A reference to `asyncHook`." + }, + "params": [] + } + ], + "desc": "

      Disable the callbacks for a given AsyncHook instance from the global pool of\nAsyncHook callbacks to be executed. Once a hook has been disabled it will not\nbe called again until enabled.

      \n

      For API consistency disable() also returns the AsyncHook instance.

      " + }, + { + "textRaw": "`async_hooks.executionAsyncResource()`", + "type": "method", + "name": "executionAsyncResource", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} The resource representing the current execution. Useful to store data within the resource.", + "name": "return", + "type": "Object", + "desc": "The resource representing the current execution. Useful to store data within the resource." + }, + "params": [] + } + ], + "desc": "

      Resource objects returned by executionAsyncResource() are most often internal\nNode.js handle objects with undocumented APIs. Using any functions or properties\non the object is likely to crash your application and should be avoided.

      \n

      Using executionAsyncResource() in the top-level execution context will\nreturn an empty object as there is no handle or request object to use,\nbut having an object representing the top-level can be helpful.

      \n
      const { open } = require('fs');\nconst { executionAsyncId, executionAsyncResource } = require('async_hooks');\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(__filename, 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});\n
      \n

      This can be used to implement continuation local storage without the\nuse of a tracking Map to store the metadata:

      \n
      const { createServer } = require('http');\nconst {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook\n} = require('async_hooks');\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    const cr = executionAsyncResource();\n    if (cr) {\n      resource[sym] = cr[sym];\n    }\n  }\n}).enable();\n\nconst server = createServer((req, res) => {\n  executionAsyncResource()[sym] = { state: req.url };\n  setTimeout(function() {\n    res.end(JSON.stringify(executionAsyncResource()[sym]));\n  }, 100);\n}).listen(3000);\n
      " + }, + { + "textRaw": "`async_hooks.executionAsyncId()`", + "type": "method", + "name": "executionAsyncId", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [ + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Renamed from `currentId`" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The `asyncId` of the current execution context. Useful to track when something calls.", + "name": "return", + "type": "number", + "desc": "The `asyncId` of the current execution context. Useful to track when something calls." + }, + "params": [] + } + ], + "desc": "
      const async_hooks = require('async_hooks');\n\nconsole.log(async_hooks.executionAsyncId());  // 1 - bootstrap\nfs.open(path, 'r', (err, fd) => {\n  console.log(async_hooks.executionAsyncId());  // 6 - open()\n});\n
      \n

      The ID returned from executionAsyncId() is related to execution timing, not\ncausality (which is covered by triggerAsyncId()):

      \n
      const server = net.createServer((conn) => {\n  // Returns the ID of the server, not of the new connection, because the\n  // callback runs in the execution scope of the server's MakeCallback().\n  async_hooks.executionAsyncId();\n\n}).listen(port, () => {\n  // Returns the ID of a TickObject (i.e. process.nextTick()) because all\n  // callbacks passed to .listen() are wrapped in a nextTick().\n  async_hooks.executionAsyncId();\n});\n
      \n

      Promise contexts may not get precise executionAsyncIds by default.\nSee the section on promise execution tracking.

      " + }, + { + "textRaw": "`async_hooks.triggerAsyncId()`", + "type": "method", + "name": "triggerAsyncId", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The ID of the resource responsible for calling the callback that is currently being executed.", + "name": "return", + "type": "number", + "desc": "The ID of the resource responsible for calling the callback that is currently being executed." + }, + "params": [] + } + ], + "desc": "
      const server = net.createServer((conn) => {\n  // The resource that caused (or triggered) this callback to be called\n  // was that of the new connection. Thus the return value of triggerAsyncId()\n  // is the asyncId of \"conn\".\n  async_hooks.triggerAsyncId();\n\n}).listen(port, () => {\n  // Even though all callbacks passed to .listen() are wrapped in a nextTick()\n  // the callback itself exists because the call to the server's .listen()\n  // was made. So the return value would be the ID of the server.\n  async_hooks.triggerAsyncId();\n});\n
      \n

      Promise contexts may not get valid triggerAsyncIds by default. See\nthe section on promise execution tracking.

      " + } + ], + "modules": [ + { + "textRaw": "Hook callbacks", + "name": "hook_callbacks", + "desc": "

      Key events in the lifetime of asynchronous events have been categorized into\nfour areas: instantiation, before/after the callback is called, and when the\ninstance is destroyed.

      ", + "methods": [ + { + "textRaw": "`init(asyncId, type, triggerAsyncId, resource)`", + "type": "method", + "name": "init", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number} A unique ID for the async resource.", + "name": "asyncId", + "type": "number", + "desc": "A unique ID for the async resource." + }, + { + "textRaw": "`type` {string} The type of the async resource.", + "name": "type", + "type": "string", + "desc": "The type of the async resource." + }, + { + "textRaw": "`triggerAsyncId` {number} The unique ID of the async resource in whose execution context this async resource was created.", + "name": "triggerAsyncId", + "type": "number", + "desc": "The unique ID of the async resource in whose execution context this async resource was created." + }, + { + "textRaw": "`resource` {Object} Reference to the resource representing the async operation, needs to be released during _destroy_.", + "name": "resource", + "type": "Object", + "desc": "Reference to the resource representing the async operation, needs to be released during _destroy_." + } + ] + } + ], + "desc": "

      Called when a class is constructed that has the possibility to emit an\nasynchronous event. This does not mean the instance must call\nbefore/after before destroy is called, only that the possibility\nexists.

      \n

      This behavior can be observed by doing something like opening a resource then\nclosing it before the resource can be used. The following snippet demonstrates\nthis.

      \n
      require('net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n
      \n

      Every new resource is assigned an ID that is unique within the scope of the\ncurrent Node.js instance.

      ", + "modules": [ + { + "textRaw": "`type`", + "name": "`type`", + "desc": "

      The type is a string identifying the type of resource that caused\ninit to be called. Generally, it will correspond to the name of the\nresource's constructor.

      \n
      FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,\nHTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,\nSHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,\nTTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,\nRANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject\n
      \n

      There is also the PROMISE resource type, which is used to track Promise\ninstances and asynchronous work scheduled by them.

      \n

      Users are able to define their own type when using the public embedder API.

      \n

      It is possible to have type name collisions. Embedders are encouraged to use\nunique prefixes, such as the npm package name, to prevent collisions when\nlistening to the hooks.

      ", + "type": "module", + "displayName": "`type`" + }, + { + "textRaw": "`triggerAsyncId`", + "name": "`triggerasyncid`", + "desc": "

      triggerAsyncId is the asyncId of the resource that caused (or \"triggered\")\nthe new resource to initialize and that caused init to call. This is different\nfrom async_hooks.executionAsyncId() that only shows when a resource was\ncreated, while triggerAsyncId shows why a resource was created.

      \n

      The following is a simple demonstration of triggerAsyncId:

      \n
      async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    fs.writeSync(\n      process.stdout.fd,\n      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  }\n}).enable();\n\nrequire('net').createServer((conn) => {}).listen(8080);\n
      \n

      Output when hitting the server with nc localhost 8080:

      \n
      TCPSERVERWRAP(5): trigger: 1 execution: 1\nTCPWRAP(7): trigger: 5 execution: 0\n
      \n

      The TCPSERVERWRAP is the server which receives the connections.

      \n

      The TCPWRAP is the new connection from the client. When a new\nconnection is made, the TCPWrap instance is immediately constructed. This\nhappens outside of any JavaScript stack. (An executionAsyncId() of 0 means\nthat it is being executed from C++ with no JavaScript stack above it.) With only\nthat information, it would be impossible to link resources together in\nterms of what caused them to be created, so triggerAsyncId is given the task\nof propagating what resource is responsible for the new resource's existence.

      ", + "type": "module", + "displayName": "`triggerAsyncId`" + }, + { + "textRaw": "`resource`", + "name": "`resource`", + "desc": "

      resource is an object that represents the actual async resource that has\nbeen initialized. This can contain useful information that can vary based on\nthe value of type. For instance, for the GETADDRINFOREQWRAP resource type,\nresource provides the host name used when looking up the IP address for the\nhost in net.Server.listen(). The API for accessing this information is\nnot supported, but using the Embedder API, users can provide\nand document their own resource objects. For example, such a resource object\ncould contain the SQL query being executed.

      \n

      In the case of Promises, the resource object will have an\nisChainedPromise property, set to true if the promise has a parent promise,\nand false otherwise. For example, in the case of b = a.then(handler), a is\nconsidered a parent Promise of b. Here, b is considered a chained promise.

      \n

      In some cases the resource object is reused for performance reasons, it is\nthus not safe to use it as a key in a WeakMap or add properties to it.

      ", + "type": "module", + "displayName": "`resource`" + }, + { + "textRaw": "Asynchronous context example", + "name": "asynchronous_context_example", + "desc": "

      The following is an example with additional information about the calls to\ninit between the before and after calls, specifically what the\ncallback to listen() will look like. The output formatting is slightly more\nelaborate to make calling context easier to see.

      \n
      let indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      process.stdout.fd,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(process.stdout.fd, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(process.stdout.fd, `${indentStr}after:  ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(process.stdout.fd, `${indentStr}destroy:  ${asyncId}\\n`);\n  },\n}).enable();\n\nrequire('net').createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});\n
      \n

      Output from only starting the server:

      \n
      TCPSERVERWRAP(5): trigger: 1 execution: 1\nTickObject(6): trigger: 5 execution: 1\nbefore:  6\n  Timeout(7): trigger: 6 execution: 6\nafter:   6\ndestroy: 6\nbefore:  7\n>>> 7\n  TickObject(8): trigger: 7 execution: 7\nafter:   7\nbefore:  8\nafter:   8\n
      \n

      As illustrated in the example, executionAsyncId() and execution each specify\nthe value of the current execution context; which is delineated by calls to\nbefore and after.

      \n

      Only using execution to graph resource allocation results in the following:

      \n
        root(1)\n     ^\n     |\nTickObject(6)\n     ^\n     |\n Timeout(7)\n
      \n

      The TCPSERVERWRAP is not part of this graph, even though it was the reason for\nconsole.log() being called. This is because binding to a port without a host\nname is a synchronous operation, but to maintain a completely asynchronous\nAPI the user's callback is placed in a process.nextTick(). Which is why\nTickObject is present in the output and is a 'parent' for .listen()\ncallback.

      \n

      The graph only shows when a resource was created, not why, so to track\nthe why use triggerAsyncId. Which can be represented with the following\ngraph:

      \n
       bootstrap(1)\n     |\n     Ë…\nTCPSERVERWRAP(5)\n     |\n     Ë…\n TickObject(6)\n     |\n     Ë…\n  Timeout(7)\n
      ", + "type": "module", + "displayName": "Asynchronous context example" + } + ] + }, + { + "textRaw": "`before(asyncId)`", + "type": "method", + "name": "before", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      When an asynchronous operation is initiated (such as a TCP server receiving a\nnew connection) or completes (such as writing data to disk) a callback is\ncalled to notify the user. The before callback is called just before said\ncallback is executed. asyncId is the unique identifier assigned to the\nresource about to execute the callback.

      \n

      The before callback will be called 0 to N times. The before callback\nwill typically be called 0 times if the asynchronous operation was cancelled\nor, for example, if no connections are received by a TCP server. Persistent\nasynchronous resources like a TCP server will typically call the before\ncallback multiple times, while other operations like fs.open() will call\nit only once.

      " + }, + { + "textRaw": "`after(asyncId)`", + "type": "method", + "name": "after", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      Called immediately after the callback specified in before is completed.

      \n

      If an uncaught exception occurs during execution of the callback, then after\nwill run after the 'uncaughtException' event is emitted or a domain's\nhandler runs.

      " + }, + { + "textRaw": "`destroy(asyncId)`", + "type": "method", + "name": "destroy", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      Called after the resource corresponding to asyncId is destroyed. It is also\ncalled asynchronously from the embedder API emitDestroy().

      \n

      Some resources depend on garbage collection for cleanup, so if a reference is\nmade to the resource object passed to init it is possible that destroy\nwill never be called, causing a memory leak in the application. If the resource\ndoes not depend on garbage collection, then this will not be an issue.

      " + }, + { + "textRaw": "`promiseResolve(asyncId)`", + "type": "method", + "name": "promiseResolve", + "meta": { + "added": [ + "v8.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      Called when the resolve function passed to the Promise constructor is\ninvoked (either directly or through other means of resolving a promise).

      \n

      resolve() does not do any observable synchronous work.

      \n

      The Promise is not necessarily fulfilled or rejected at this point if the\nPromise was resolved by assuming the state of another Promise.

      \n
      new Promise((resolve) => resolve(true)).then((a) => {});\n
      \n

      calls the following callbacks:

      \n
      init for PROMISE with id 5, trigger id: 1\n  promise resolve 5      # corresponds to resolve(true)\ninit for PROMISE with id 6, trigger id: 5  # the Promise returned by then()\n  before 6               # the then() callback is entered\n  promise resolve 6      # the then() callback resolves the promise by returning\n  after 6\n
      " + } + ], + "type": "module", + "displayName": "Hook callbacks" + } + ] + } + ], + "type": "module", + "displayName": "Public API" + }, + { + "textRaw": "Promise execution tracking", + "name": "promise_execution_tracking", + "desc": "

      By default, promise executions are not assigned asyncIds due to the relatively\nexpensive nature of the promise introspection API provided by\nV8. This means that programs using promises or async/await will not get\ncorrect execution and trigger ids for promise callback contexts by default.

      \n
      const ah = require('async_hooks');\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n
      \n

      Observe that the then() callback claims to have executed in the context of the\nouter scope even though there was an asynchronous hop involved. Also,\nthe triggerAsyncId value is 0, which means that we are missing context about\nthe resource that caused (triggered) the then() callback to be executed.

      \n

      Installing async hooks via async_hooks.createHook enables promise execution\ntracking:

      \n
      const ah = require('async_hooks');\nah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n
      \n

      In this example, adding any actual hook function enabled the tracking of\npromises. There are two promises in the example above; the promise created by\nPromise.resolve() and the promise returned by the call to then(). In the\nexample above, the first promise got the asyncId 6 and the latter got\nasyncId 7. During the execution of the then() callback, we are executing\nin the context of promise with asyncId 7. This promise was triggered by\nasync resource 6.

      \n

      Another subtlety with promises is that before and after callbacks are run\nonly on chained promises. That means promises not created by then()/catch()\nwill not have the before and after callbacks fired on them. For more details\nsee the details of the V8 PromiseHooks API.

      ", + "type": "module", + "displayName": "Promise execution tracking" + }, + { + "textRaw": "JavaScript embedder API", + "name": "javascript_embedder_api", + "desc": "

      Library developers that handle their own asynchronous resources performing tasks\nlike I/O, connection pooling, or managing callback queues may use the\nAsyncResource JavaScript API so that all the appropriate callbacks are called.

      ", + "classes": [ + { + "textRaw": "Class: `AsyncResource`", + "type": "class", + "name": "AsyncResource", + "desc": "

      The class AsyncResource is designed to be extended by the embedder's async\nresources. Using this, users can easily trigger the lifetime events of their\nown resources.

      \n

      The init hook will trigger when an AsyncResource is instantiated.

      \n

      The following is an overview of the AsyncResource API.

      \n
      const { AsyncResource, executionAsyncId } = require('async_hooks');\n\n// AsyncResource() is meant to be extended. Instantiating a\n// new AsyncResource() also triggers init. If triggerAsyncId is omitted then\n// async_hook.executionAsyncId() is used.\nconst asyncResource = new AsyncResource(\n  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }\n);\n\n// Run a function in the execution context of the resource. This will\n// * establish the context of the resource\n// * trigger the AsyncHooks before callbacks\n// * call the provided function `fn` with the supplied arguments\n// * trigger the AsyncHooks after callbacks\n// * restore the original execution context\nasyncResource.runInAsyncScope(fn, thisArg, ...args);\n\n// Call AsyncHooks destroy callbacks.\nasyncResource.emitDestroy();\n\n// Return the unique ID assigned to the AsyncResource instance.\nasyncResource.asyncId();\n\n// Return the trigger ID for the AsyncResource instance.\nasyncResource.triggerAsyncId();\n
      ", + "classMethods": [ + { + "textRaw": "Static method: `AsyncResource.bind(fn[, type])`", + "type": "classMethod", + "name": "bind", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} The function to bind to the current execution context.", + "name": "fn", + "type": "Function", + "desc": "The function to bind to the current execution context." + }, + { + "textRaw": "`type` {string} An optional name to associate with the underlying `AsyncResource`.", + "name": "type", + "type": "string", + "desc": "An optional name to associate with the underlying `AsyncResource`." + } + ] + } + ], + "desc": "

      Binds the given function to the current execution context.

      \n

      The returned function will have an asyncResource property referencing\nthe AsyncResource to which the function is bound.

      " + } + ], + "methods": [ + { + "textRaw": "`asyncResource.bind(fn)`", + "type": "method", + "name": "bind", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} The function to bind to the current `AsyncResource`.", + "name": "fn", + "type": "Function", + "desc": "The function to bind to the current `AsyncResource`." + } + ] + } + ], + "desc": "

      Binds the given function to execute to this AsyncResource's scope.

      \n

      The returned function will have an asyncResource property referencing\nthe AsyncResource to which the function is bound.

      " + }, + { + "textRaw": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`", + "type": "method", + "name": "runInAsyncScope", + "meta": { + "added": [ + "v9.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} The function to call in the execution context of this async resource.", + "name": "fn", + "type": "Function", + "desc": "The function to call in the execution context of this async resource." + }, + { + "textRaw": "`thisArg` {any} The receiver to be used for the function call.", + "name": "thisArg", + "type": "any", + "desc": "The receiver to be used for the function call." + }, + { + "textRaw": "`...args` {any} Optional arguments to pass to the function.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass to the function." + } + ] + } + ], + "desc": "

      Call the provided function with the provided arguments in the execution context\nof the async resource. This will establish the context, trigger the AsyncHooks\nbefore callbacks, call the function, trigger the AsyncHooks after callbacks, and\nthen restore the original execution context.

      " + }, + { + "textRaw": "`asyncResource.emitDestroy()`", + "type": "method", + "name": "emitDestroy", + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", + "name": "return", + "type": "AsyncResource", + "desc": "A reference to `asyncResource`." + }, + "params": [] + } + ], + "desc": "

      Call all destroy hooks. This should only ever be called once. An error will\nbe thrown if it is called more than once. This must be manually called. If\nthe resource is left to be collected by the GC then the destroy hooks will\nnever be called.

      " + }, + { + "textRaw": "`asyncResource.asyncId()`", + "type": "method", + "name": "asyncId", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The unique `asyncId` assigned to the resource.", + "name": "return", + "type": "number", + "desc": "The unique `asyncId` assigned to the resource." + }, + "params": [] + } + ] + }, + { + "textRaw": "`asyncResource.triggerAsyncId()`", + "type": "method", + "name": "triggerAsyncId", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.", + "name": "return", + "type": "number", + "desc": "The same `triggerAsyncId` that is passed to the `AsyncResource` constructor." + }, + "params": [] + } + ], + "desc": "

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`type` {string} The type of async event.", + "name": "type", + "type": "string", + "desc": "The type of async event." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`triggerAsyncId` {number} The ID of the execution context that created this async event. **Default:** `executionAsyncId()`.", + "name": "triggerAsyncId", + "type": "number", + "default": "`executionAsyncId()`", + "desc": "The ID of the execution context that created this async event." + }, + { + "textRaw": "`requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if `emitDestroy` is called manually), unless the resource's `asyncId` is retrieved and the sensitive API's `emitDestroy` is called with it. When set to `false`, the `emitDestroy` call on garbage collection will only take place if there is at least one active `destroy` hook. **Default:** `false`.", + "name": "requireManualDestroy", + "type": "boolean", + "default": "`false`", + "desc": "If set to `true`, disables `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if `emitDestroy` is called manually), unless the resource's `asyncId` is retrieved and the sensitive API's `emitDestroy` is called with it. When set to `false`, the `emitDestroy` call on garbage collection will only take place if there is at least one active `destroy` hook." + } + ] + } + ], + "desc": "

      Example usage:

      \n
      class DBQuery extends AsyncResource {\n  constructor(db) {\n    super('DBQuery');\n    this.db = db;\n  }\n\n  getInfo(query, callback) {\n    this.db.get(query, (err, data) => {\n      this.runInAsyncScope(callback, null, err, data);\n    });\n  }\n\n  close() {\n    this.db = null;\n    this.emitDestroy();\n  }\n}\n
      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Using `AsyncResource` for a `Worker` thread pool", + "name": "using_`asyncresource`_for_a_`worker`_thread_pool", + "desc": "

      The following example shows how to use the AsyncResource class to properly\nprovide async tracking for a Worker pool. Other resource pools, such as\ndatabase connection pools, can follow a similar model.

      \n

      Assuming that the task is adding two numbers, using a file named\ntask_processor.js with the following content:

      \n
      const { parentPort } = require('worker_threads');\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
      \n

      a Worker pool around it could use the following structure:

      \n
      const { AsyncResource } = require('async_hooks');\nconst { EventEmitter } = require('events');\nconst path = require('path');\nconst { Worker } = require('worker_threads');\n\nconst kTaskInfo = Symbol('kTaskInfo');\nconst kWorkerFreedEvent = Symbol('kWorkerFreedEvent');\n\nclass WorkerPoolTaskInfo extends AsyncResource {\n  constructor(callback) {\n    super('WorkerPoolTaskInfo');\n    this.callback = callback;\n  }\n\n  done(err, result) {\n    this.runInAsyncScope(this.callback, null, err, result);\n    this.emitDestroy();  // `TaskInfo`s are used only once.\n  }\n}\n\nclass WorkerPool extends EventEmitter {\n  constructor(numThreads) {\n    super();\n    this.numThreads = numThreads;\n    this.workers = [];\n    this.freeWorkers = [];\n\n    for (let i = 0; i < numThreads; i++)\n      this.addNewWorker();\n  }\n\n  addNewWorker() {\n    const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));\n    worker.on('message', (result) => {\n      // In case of success: Call the callback that was passed to `runTask`,\n      // remove the `TaskInfo` associated with the Worker, and mark it as free\n      // again.\n      worker[kTaskInfo].done(null, result);\n      worker[kTaskInfo] = null;\n      this.freeWorkers.push(worker);\n      this.emit(kWorkerFreedEvent);\n    });\n    worker.on('error', (err) => {\n      // In case of an uncaught exception: Call the callback that was passed to\n      // `runTask` with the error.\n      if (worker[kTaskInfo])\n        worker[kTaskInfo].done(err, null);\n      else\n        this.emit('error', err);\n      // Remove the worker from the list and start a new Worker to replace the\n      // current one.\n      this.workers.splice(this.workers.indexOf(worker), 1);\n      this.addNewWorker();\n    });\n    this.workers.push(worker);\n    this.freeWorkers.push(worker);\n    this.emit(kWorkerFreedEvent);\n  }\n\n  runTask(task, callback) {\n    if (this.freeWorkers.length === 0) {\n      // No free threads, wait until a worker thread becomes free.\n      this.once(kWorkerFreedEvent, () => this.runTask(task, callback));\n      return;\n    }\n\n    const worker = this.freeWorkers.pop();\n    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);\n    worker.postMessage(task);\n  }\n\n  close() {\n    for (const worker of this.workers) worker.terminate();\n  }\n}\n\nmodule.exports = WorkerPool;\n
      \n

      Without the explicit tracking added by the WorkerPoolTaskInfo objects,\nit would appear that the callbacks are associated with the individual Worker\nobjects. However, the creation of the Workers is not associated with the\ncreation of the tasks and does not provide information about when tasks\nwere scheduled.

      \n

      This pool could be used as follows:

      \n
      const WorkerPool = require('./worker_pool.js');\nconst os = require('os');\n\nconst pool = new WorkerPool(os.cpus().length);\n\nlet finished = 0;\nfor (let i = 0; i < 10; i++) {\n  pool.runTask({ a: 42, b: 100 }, (err, result) => {\n    console.log(i, err, result);\n    if (++finished === 10)\n      pool.close();\n  });\n}\n
      ", + "type": "module", + "displayName": "Using `AsyncResource` for a `Worker` thread pool" + }, + { + "textRaw": "Integrating `AsyncResource` with `EventEmitter`", + "name": "integrating_`asyncresource`_with_`eventemitter`", + "desc": "

      Event listeners triggered by an EventEmitter may be run in a different\nexecution context than the one that was active when eventEmitter.on() was\ncalled.

      \n

      The following example shows how to use the AsyncResource class to properly\nassociate an event listener with the correct execution context. The same\napproach can be applied to a Stream or a similar event-driven class.

      \n
      const { createServer } = require('http');\nconst { AsyncResource, executionAsyncId } = require('async_hooks');\n\nconst server = createServer((req, res) => {\n  req.on('close', AsyncResource.bind(() => {\n    // Execution context is bound to the current outer scope.\n  }));\n  req.on('close', () => {\n    // Execution context is bound to the scope that caused 'close' to emit.\n  });\n  res.end();\n}).listen(3000);\n
      ", + "type": "module", + "displayName": "Integrating `AsyncResource` with `EventEmitter`" + } + ], + "type": "module", + "displayName": "JavaScript embedder API" + } + ], + "classes": [ + { + "textRaw": "Class: `AsyncLocalStorage`", + "type": "class", + "name": "AsyncLocalStorage", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      This class is used to create asynchronous state within callbacks and promise\nchains. It allows storing data throughout the lifetime of a web request\nor any other asynchronous duration. It is similar to thread-local storage\nin other languages.

      \n

      The following example uses AsyncLocalStorage to build a simple logger\nthat assigns IDs to incoming HTTP requests and includes them in messages\nlogged within each request.

      \n
      const http = require('http');\nconst { AsyncLocalStorage } = require('async_hooks');\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nfunction logWithId(msg) {\n  const id = asyncLocalStorage.getStore();\n  console.log(`${id !== undefined ? id : '-'}:`, msg);\n}\n\nlet idSeq = 0;\nhttp.createServer((req, res) => {\n  asyncLocalStorage.run(idSeq++, () => {\n    logWithId('start');\n    // Imagine any chain of async operations here\n    setImmediate(() => {\n      logWithId('finish');\n      res.end();\n    });\n  });\n}).listen(8080);\n\nhttp.get('http://localhost:8080');\nhttp.get('http://localhost:8080');\n// Prints:\n//   0: start\n//   1: start\n//   0: finish\n//   1: finish\n
      \n

      When having multiple instances of AsyncLocalStorage, they are independent\nfrom each other. It is safe to instantiate this class multiple times.

      ", + "methods": [ + { + "textRaw": "`asyncLocalStorage.disable()`", + "type": "method", + "name": "disable", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This method disables the instance of AsyncLocalStorage. All subsequent calls\nto asyncLocalStorage.getStore() will return undefined until\nasyncLocalStorage.run() is called again.

      \n

      When calling asyncLocalStorage.disable(), all current contexts linked to the\ninstance will be exited.

      \n

      Calling asyncLocalStorage.disable() is required before the\nasyncLocalStorage can be garbage collected. This does not apply to stores\nprovided by the asyncLocalStorage, as those objects are garbage collected\nalong with the corresponding async resources.

      \n

      This method is to be used when the asyncLocalStorage is not in use anymore\nin the current process.

      " + }, + { + "textRaw": "`asyncLocalStorage.getStore()`", + "type": "method", + "name": "getStore", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any}", + "name": "return", + "type": "any" + }, + "params": [] + } + ], + "desc": "

      This method returns the current store.\nIf this method is called outside of an asynchronous context initialized by\ncalling asyncLocalStorage.run, it will return undefined.

      " + }, + { + "textRaw": "`asyncLocalStorage.enterWith(store)`", + "type": "method", + "name": "enterWith", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`store` {any}", + "name": "store", + "type": "any" + } + ] + } + ], + "desc": "

      Calling asyncLocalStorage.enterWith(store) will transition into the context\nfor the remainder of the current synchronous execution and will persist\nthrough any following asynchronous calls.

      \n

      Example:

      \n
      const store = { id: 1 };\nasyncLocalStorage.enterWith(store);\nasyncLocalStorage.getStore(); // Returns the store object\nsomeAsyncOperation(() => {\n  asyncLocalStorage.getStore(); // Returns the same object\n});\n
      \n

      This transition will continue for the entire synchronous execution.\nThis means that if, for example, the context is entered within an event\nhandler subsequent event handlers will also run within that context unless\nspecifically bound to another context with an AsyncResource.

      \n
      const store = { id: 1 };\n\nemitter.on('my-event', () => {\n  asyncLocalStorage.enterWith(store);\n});\nemitter.on('my-event', () => {\n  asyncLocalStorage.getStore(); // Returns the same object\n});\n\nasyncLocalStorage.getStore(); // Returns undefined\nemitter.emit('my-event');\nasyncLocalStorage.getStore(); // Returns the same object\n
      " + }, + { + "textRaw": "`asyncLocalStorage.run(store, callback[, ...args])`", + "type": "method", + "name": "run", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`store` {any}", + "name": "store", + "type": "any" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      This methods runs a function synchronously within a context and return its\nreturn value. The store is not accessible outside of the callback function or\nthe asynchronous operations created within the callback.

      \n

      Optionally, arguments can be passed to the function. They will be passed to\nthe callback function.

      \n

      If the callback function throws an error, it will be thrown by run too.\nThe stacktrace will not be impacted by this call and the context will\nbe exited.

      \n

      Example:

      \n
      const store = { id: 2 };\ntry {\n  asyncLocalStorage.run(store, () => {\n    asyncLocalStorage.getStore(); // Returns the store object\n    throw new Error();\n  });\n} catch (e) {\n  asyncLocalStorage.getStore(); // Returns undefined\n  // The error will be caught here\n}\n
      " + }, + { + "textRaw": "`asyncLocalStorage.exit(callback[, ...args])`", + "type": "method", + "name": "exit", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      This methods runs a function synchronously outside of a context and return its\nreturn value. The store is not accessible within the callback function or\nthe asynchronous operations created within the callback.

      \n

      Optionally, arguments can be passed to the function. They will be passed to\nthe callback function.

      \n

      If the callback function throws an error, it will be thrown by exit too.\nThe stacktrace will not be impacted by this call and\nthe context will be re-entered.

      \n

      Example:

      \n
      // Within a call to run\ntry {\n  asyncLocalStorage.getStore(); // Returns the store object or value\n  asyncLocalStorage.exit(() => {\n    asyncLocalStorage.getStore(); // Returns undefined\n    throw new Error();\n  });\n} catch (e) {\n  asyncLocalStorage.getStore(); // Returns the same object or value\n  // The error will be caught here\n}\n
      " + } + ], + "modules": [ + { + "textRaw": "Usage with `async/await`", + "name": "usage_with_`async/await`", + "desc": "

      If, within an async function, only one await call is to run within a context,\nthe following pattern should be used:

      \n
      async function fn() {\n  await asyncLocalStorage.run(new Map(), () => {\n    asyncLocalStorage.getStore().set('key', value);\n    return foo(); // The return value of foo will be awaited\n  });\n}\n
      \n

      In this example, the store is only available in the callback function and the\nfunctions called by foo. Outside of run, calling getStore will return\nundefined.

      ", + "type": "module", + "displayName": "Usage with `async/await`" + }, + { + "textRaw": "Troubleshooting", + "name": "troubleshooting", + "desc": "

      In most cases your application or library code should have no issues with\nAsyncLocalStorage. But in rare cases you may face situations when the\ncurrent store is lost in one of asynchronous operations. In those cases,\nconsider the following options.

      \n

      If your code is callback-based, it is enough to promisify it with\nutil.promisify(), so it starts working with native promises.

      \n

      If you need to keep using callback-based API, or your code assumes\na custom thenable implementation, use the AsyncResource class\nto associate the asynchronous operation with the correct execution context.

      ", + "type": "module", + "displayName": "Troubleshooting" + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Creates a new instance of AsyncLocalStorage. Store is only provided within a\nrun method call.

      " + } + ] + } + ], + "type": "module", + "displayName": "Async hooks" + }, + { + "textRaw": "Buffer", + "name": "buffer", + "introduced_in": "v0.1.90", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/buffer.js

      \n

      Buffer objects are used to represent a fixed-length sequence of bytes. Many\nNode.js APIs support Buffers.

      \n

      The Buffer class is a subclass of JavaScript's Uint8Array class and\nextends it with methods that cover additional use cases. Node.js APIs accept\nplain Uint8Arrays wherever Buffers are supported as well.

      \n

      The Buffer class is within the global scope, making it unlikely that one\nwould need to ever use require('buffer').Buffer.

      \n
      // Creates a zero-filled Buffer of length 10.\nconst buf1 = Buffer.alloc(10);\n\n// Creates a Buffer of length 10,\n// filled with bytes which all have the value `1`.\nconst buf2 = Buffer.alloc(10, 1);\n\n// Creates an uninitialized buffer of length 10.\n// This is faster than calling Buffer.alloc() but the returned\n// Buffer instance might contain old data that needs to be\n// overwritten using fill(), write(), or other functions that fill the Buffer's\n// contents.\nconst buf3 = Buffer.allocUnsafe(10);\n\n// Creates a Buffer containing the bytes [1, 2, 3].\nconst buf4 = Buffer.from([1, 2, 3]);\n\n// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries\n// are all truncated using `(value & 255)` to fit into the range 0–255.\nconst buf5 = Buffer.from([257, 257.5, -255, '1']);\n\n// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':\n// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)\n// [116, 195, 169, 115, 116] (in decimal notation)\nconst buf6 = Buffer.from('tést');\n\n// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].\nconst buf7 = Buffer.from('tést', 'latin1');\n
      ", + "modules": [ + { + "textRaw": "Buffers and character encodings", + "name": "buffers_and_character_encodings", + "meta": { + "changes": [ + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7111", + "description": "Introduced `latin1` as an alias for `binary`." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2859", + "description": "Removed the deprecated `raw` and `raws` encodings." + } + ] + }, + "desc": "

      When converting between Buffers and strings, a character encoding may be\nspecified. If no character encoding is specified, UTF-8 will be used as the\ndefault.

      \n
      const buf = Buffer.from('hello world', 'utf8');\n\nconsole.log(buf.toString('hex'));\n// Prints: 68656c6c6f20776f726c64\nconsole.log(buf.toString('base64'));\n// Prints: aGVsbG8gd29ybGQ=\n\nconsole.log(Buffer.from('fhqwhgads', 'utf8'));\n// Prints: <Buffer 66 68 71 77 68 67 61 64 73>\nconsole.log(Buffer.from('fhqwhgads', 'utf16le'));\n// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>\n
      \n

      The character encodings currently supported by Node.js are the following:

      \n
        \n
      • \n

        'utf8': Multi-byte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8. This is the default character encoding.\nWhen decoding a Buffer into a string that does not exclusively contain\nvalid UTF-8 data, the Unicode replacement character U+FFFD � will be used\nto represent those errors.

        \n
      • \n
      • \n

        'utf16le': Multi-byte encoded Unicode characters. Unlike 'utf8', each\ncharacter in the string will be encoded using either 2 or 4 bytes.\nNode.js only supports the little-endian variant of UTF-16.

        \n
      • \n
      • \n

        'latin1': Latin-1 stands for ISO-8859-1. This character encoding only\nsupports the Unicode characters from U+0000 to U+00FF. Each character is\nencoded using a single byte. Characters that do not fit into that range are\ntruncated and will be mapped to characters in that range.

        \n
      • \n
      \n

      Converting a Buffer into a string using one of the above is referred to as\ndecoding, and converting a string into a Buffer is referred to as encoding.

      \n

      Node.js also supports the following two binary-to-text encodings. For\nbinary-to-text encodings, the naming convention is reversed: Converting a\nBuffer into a string is typically referred to as encoding, and converting a\nstring into a Buffer as decoding.

      \n
        \n
      • \n

        'base64': Base64 encoding. When creating a Buffer from a string,\nthis encoding will also correctly accept \"URL and Filename Safe Alphabet\" as\nspecified in RFC 4648, Section 5. Whitespace characters such as spaces,\ntabs, and new lines contained within the base64-encoded string are ignored.

        \n
      • \n
      • \n

        'hex': Encode each byte as two hexadecimal characters. Data truncation\nmay occur when decoding strings that do exclusively contain valid hexadecimal\ncharacters. See below for an example.

        \n
      • \n
      \n

      The following legacy character encodings are also supported:

      \n
        \n
      • \n

        'ascii': For 7-bit ASCII data only. When encoding a string into a\nBuffer, this is equivalent to using 'latin1'. When decoding a Buffer\ninto a string, using this encoding will additionally unset the highest bit of\neach byte before decoding as 'latin1'.\nGenerally, there should be no reason to use this encoding, as 'utf8'\n(or, if the data is known to always be ASCII-only, 'latin1') will be a\nbetter choice when encoding or decoding ASCII-only text. It is only provided\nfor legacy compatibility.

        \n
      • \n
      • \n

        'binary': Alias for 'latin1'. See binary strings for more background\non this topic. The name of this encoding can be very misleading, as all of the\nencodings listed here convert between strings and binary data. For converting\nbetween strings and Buffers, typically 'utf-8' is the right choice.

        \n
      • \n
      • \n

        'ucs2': Alias of 'utf16le'. UCS-2 used to refer to a variant of UTF-16\nthat did not support characters that had code points larger than U+FFFF.\nIn Node.js, these code points are always supported.

        \n
      • \n
      \n
      Buffer.from('1ag', 'hex');\n// Prints <Buffer 1a>, data truncated when first non-hexadecimal value\n// ('g') encountered.\n\nBuffer.from('1a7g', 'hex');\n// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').\n\nBuffer.from('1634', 'hex');\n// Prints <Buffer 16 34>, all data represented.\n
      \n

      Modern Web browsers follow the WHATWG Encoding Standard which aliases\nboth 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing\nsomething like http.get(), if the returned charset is one of those listed in\nthe WHATWG specification it is possible that the server actually returned\n'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode\nthe characters.

      ", + "type": "module", + "displayName": "Buffers and character encodings" + }, + { + "textRaw": "Buffers and TypedArrays", + "name": "buffers_and_typedarrays", + "meta": { + "changes": [ + { + "version": "v3.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2002", + "description": "The `Buffer`s class now inherits from `Uint8Array`." + } + ] + }, + "desc": "

      Buffer instances are also JavaScript Uint8Array and TypedArray\ninstances. All TypedArray methods are available on Buffers. There are,\nhowever, subtle incompatibilities between the Buffer API and the\nTypedArray API.

      \n

      In particular:

      \n
        \n
      • While TypedArray#slice() creates a copy of part of the TypedArray,\nBuffer#slice() creates a view over the existing Buffer\nwithout copying. This behavior can be surprising, and only exists for legacy\ncompatibility. TypedArray#subarray() can be used to achieve the behavior\nof Buffer#slice() on both Buffers and other\nTypedArrays.
      • \n
      • buf.toString() is incompatible with its TypedArray equivalent.
      • \n
      • A number of methods, e.g. buf.indexOf(), support additional arguments.
      • \n
      \n

      There are two ways to create new TypedArray instances from a Buffer:

      \n
        \n
      • Passing a Buffer to a TypedArray constructor will copy the Buffers\ncontents, interpreted as an array of integers, and not as a byte sequence\nof the target type.
      • \n
      \n
      const buf = Buffer.from([1, 2, 3, 4]);\nconst uint32array = new Uint32Array(buf);\n\nconsole.log(uint32array);\n\n// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]\n
      \n
        \n
      • Passing the Buffers underlying ArrayBuffer will create a\nTypedArray that shares its memory with the Buffer.
      • \n
      \n
      const buf = Buffer.from('hello', 'utf16le');\nconst uint16arr = new Uint16Array(\n  buf.buffer,\n  buf.byteOffset,\n  buf.length / Uint16Array.BYTES_PER_ELEMENT);\n\nconsole.log(uint16array);\n\n// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]\n
      \n

      It is possible to create a new Buffer that shares the same allocated\nmemory as a TypedArray instance by using the TypedArray object’s\n.buffer property in the same way. Buffer.from()\nbehaves like new Uint8Array() in this context.

      \n
      const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Copies the contents of `arr`.\nconst buf1 = Buffer.from(arr);\n\n// Shares memory with `arr`.\nconst buf2 = Buffer.from(arr.buffer);\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 a0 0f>\n\narr[1] = 6000;\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 70 17>\n
      \n

      When creating a Buffer using a TypedArray's .buffer, it is\npossible to use only a portion of the underlying ArrayBuffer by passing in\nbyteOffset and length parameters.

      \n
      const arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\nconsole.log(buf.length);\n// Prints: 16\n
      \n

      The Buffer.from() and TypedArray.from() have different signatures and\nimplementations. Specifically, the TypedArray variants accept a second\nargument that is a mapping function that is invoked on every element of the\ntyped array:

      \n
        \n
      • TypedArray.from(source[, mapFn[, thisArg]])
      • \n
      \n

      The Buffer.from() method, however, does not support the use of a mapping\nfunction:

      \n", + "type": "module", + "displayName": "Buffers and TypedArrays" + }, + { + "textRaw": "Buffers and iteration", + "name": "buffers_and_iteration", + "desc": "

      Buffer instances can be iterated over using for..of syntax:

      \n
      const buf = Buffer.from([1, 2, 3]);\n\nfor (const b of buf) {\n  console.log(b);\n}\n// Prints:\n//   1\n//   2\n//   3\n
      \n

      Additionally, the buf.values(), buf.keys(), and\nbuf.entries() methods can be used to create iterators.

      ", + "type": "module", + "displayName": "Buffers and iteration" + }, + { + "textRaw": "`buffer` module APIs", + "name": "`buffer`_module_apis", + "desc": "

      While, the Buffer object is available as a global, there are additional\nBuffer-related APIs that are available only via the buffer module\naccessed using require('buffer').

      ", + "properties": [ + { + "textRaw": "`INSPECT_MAX_BYTES` {integer} **Default:** `50`", + "type": "integer", + "name": "INSPECT_MAX_BYTES", + "meta": { + "added": [ + "v0.5.4" + ], + "changes": [] + }, + "default": "`50`", + "desc": "

      Returns the maximum number of bytes that will be returned when\nbuf.inspect() is called. This can be overridden by user modules. See\nutil.inspect() for more details on buf.inspect() behavior.

      " + }, + { + "textRaw": "`kMaxLength` {integer} The largest size allowed for a single `Buffer` instance.", + "type": "integer", + "name": "kMaxLength", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "desc": "

      An alias for buffer.constants.MAX_LENGTH.

      ", + "shortDesc": "The largest size allowed for a single `Buffer` instance." + } + ], + "methods": [ + { + "textRaw": "`buffer.transcode(source, fromEnc, toEnc)`", + "type": "method", + "name": "transcode", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `source` parameter can now be a `Uint8Array`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`source` {Buffer|Uint8Array} A `Buffer` or `Uint8Array` instance.", + "name": "source", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or `Uint8Array` instance." + }, + { + "textRaw": "`fromEnc` {string} The current encoding.", + "name": "fromEnc", + "type": "string", + "desc": "The current encoding." + }, + { + "textRaw": "`toEnc` {string} To target encoding.", + "name": "toEnc", + "type": "string", + "desc": "To target encoding." + } + ] + } + ], + "desc": "

      Re-encodes the given Buffer or Uint8Array instance from one character\nencoding to another. Returns a new Buffer instance.

      \n

      Throws if the fromEnc or toEnc specify invalid character encodings or if\nconversion from fromEnc to toEnc is not permitted.

      \n

      Encodings supported by buffer.transcode() are: 'ascii', 'utf8',\n'utf16le', 'ucs2', 'latin1', and 'binary'.

      \n

      The transcoding process will use substitution characters if a given byte\nsequence cannot be adequately represented in the target encoding. For instance:

      \n
      const buffer = require('buffer');\n\nconst newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n
      \n

      Because the Euro (€) sign is not representable in US-ASCII, it is replaced\nwith ? in the transcoded Buffer.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `SlowBuffer`", + "type": "class", + "name": "SlowBuffer", + "meta": { + "deprecated": [ + "v6.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.", + "desc": "

      See Buffer.allocUnsafeSlow(). This was never a class in the sense that\nthe constructor always returned a Buffer instance, rather than a SlowBuffer\ninstance.

      ", + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `SlowBuffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `SlowBuffer`." + } + ], + "desc": "

      See Buffer.allocUnsafeSlow().

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Buffer constants", + "name": "buffer_constants", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "properties": [ + { + "textRaw": "`MAX_LENGTH` {integer} The largest size allowed for a single `Buffer` instance.", + "type": "integer", + "name": "MAX_LENGTH", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "desc": "

      On 32-bit architectures, this value currently is 230 - 1 (~1GB).\nOn 64-bit architectures, this value currently is 231 - 1 (~2GB).

      \n

      This value is also available as buffer.kMaxLength.

      ", + "shortDesc": "The largest size allowed for a single `Buffer` instance." + }, + { + "textRaw": "`MAX_STRING_LENGTH` {integer} The largest length allowed for a single `string` instance.", + "type": "integer", + "name": "MAX_STRING_LENGTH", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "desc": "

      Represents the largest length that a string primitive can have, counted\nin UTF-16 code units.

      \n

      This value may depend on the JS engine that is being used.

      ", + "shortDesc": "The largest length allowed for a single `string` instance." + } + ], + "type": "module", + "displayName": "Buffer constants" + } + ], + "type": "module", + "displayName": "`buffer` module APIs" + }, + { + "textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", + "name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`", + "desc": "

      In versions of Node.js prior to 6.0.0, Buffer instances were created using the\nBuffer constructor function, which allocates the returned Buffer\ndifferently based on what arguments are provided:

      \n
        \n
      • Passing a number as the first argument to Buffer() (e.g. new Buffer(10))\nallocates a new Buffer object of the specified size. Prior to Node.js 8.0.0,\nthe memory allocated for such Buffer instances is not initialized and\ncan contain sensitive data. Such Buffer instances must be subsequently\ninitialized by using either buf.fill(0) or by writing to the\nentire Buffer before reading data from the Buffer.\nWhile this behavior is intentional to improve performance,\ndevelopment experience has demonstrated that a more explicit distinction is\nrequired between creating a fast-but-uninitialized Buffer versus creating a\nslower-but-safer Buffer. Since Node.js 8.0.0, Buffer(num) and new Buffer(num) return a Buffer with initialized memory.
      • \n
      • Passing a string, array, or Buffer as the first argument copies the\npassed object's data into the Buffer.
      • \n
      • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer\nthat shares allocated memory with the given array buffer.
      • \n
      \n

      Because the behavior of new Buffer() is different depending on the type of the\nfirst argument, security and reliability issues can be inadvertently introduced\ninto applications when argument validation or Buffer initialization is not\nperformed.

      \n

      For example, if an attacker can cause an application to receive a number where\na string is expected, the application may call new Buffer(100)\ninstead of new Buffer(\"100\"), leading it to allocate a 100 byte buffer instead\nof allocating a 3 byte buffer with content \"100\". This is commonly possible\nusing JSON API calls. Since JSON distinguishes between numeric and string types,\nit allows injection of numbers where a naively written application that does not\nvalidate its input sufficiently might expect to always receive a string.\nBefore Node.js 8.0.0, the 100 byte buffer might contain\narbitrary pre-existing in-memory data, so may be used to expose in-memory\nsecrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot\noccur because the data is zero-filled. However, other attacks are still\npossible, such as causing very large buffers to be allocated by the server,\nleading to performance degradation or crashing on memory exhaustion.

      \n

      To make the creation of Buffer instances more reliable and less error-prone,\nthe various forms of the new Buffer() constructor have been deprecated\nand replaced by separate Buffer.from(), Buffer.alloc(), and\nBuffer.allocUnsafe() methods.

      \n

      Developers should migrate all existing uses of the new Buffer() constructors\nto one of these new APIs.

      \n\n

      Buffer instances returned by Buffer.allocUnsafe() and\nBuffer.from(array) may be allocated off a shared internal memory pool\nif size is less than or equal to half Buffer.poolSize. Instances\nreturned by Buffer.allocUnsafeSlow() never use the shared internal\nmemory pool.

      ", + "modules": [ + { + "textRaw": "The `--zero-fill-buffers` command line option", + "name": "the_`--zero-fill-buffers`_command_line_option", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "desc": "

      Node.js can be started using the --zero-fill-buffers command line option to\ncause all newly-allocated Buffer instances to be zero-filled upon creation by\ndefault. Without the option, buffers created with Buffer.allocUnsafe(),\nBuffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled.\nUse of this flag can have a measurable negative impact on performance. Use the\n--zero-fill-buffers option only when necessary to enforce that newly allocated\nBuffer instances cannot contain old data that is potentially sensitive.

      \n
      $ node --zero-fill-buffers\n> Buffer.allocUnsafe(5);\n<Buffer 00 00 00 00 00>\n
      ", + "type": "module", + "displayName": "The `--zero-fill-buffers` command line option" + }, + { + "textRaw": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?", + "name": "what_makes_`buffer.allocunsafe()`_and_`buffer.allocunsafeslow()`_\"unsafe\"?", + "desc": "

      When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the\nsegment of allocated memory is uninitialized (it is not zeroed-out). While\nthis design makes the allocation of memory quite fast, the allocated segment of\nmemory might contain old data that is potentially sensitive. Using a Buffer\ncreated by Buffer.allocUnsafe() without completely overwriting the\nmemory can allow this old data to be leaked when the Buffer memory is read.

      \n

      While there are clear performance advantages to using\nBuffer.allocUnsafe(), extra care must be taken in order to avoid\nintroducing security vulnerabilities into an application.

      ", + "type": "module", + "displayName": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?" + } + ], + "type": "module", + "displayName": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`" + } + ], + "classes": [ + { + "textRaw": "Class: `Buffer`", + "type": "class", + "name": "Buffer", + "desc": "

      The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.

      ", + "classMethods": [ + { + "textRaw": "Static method: `Buffer.alloc(size[, fill[, encoding]])`", + "type": "classMethod", + "name": "alloc", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18129", + "description": "Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17427", + "description": "Specifying an invalid string for `fill` triggers a thrown exception." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17428", + "description": "Specifying an invalid string for `fill` now results in a zero-filled buffer." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + }, + { + "textRaw": "`fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer` with. **Default:** `0`.", + "name": "fill", + "type": "string|Buffer|Uint8Array|integer", + "default": "`0`", + "desc": "A value to pre-fill the new `Buffer` with." + }, + { + "textRaw": "`encoding` {string} If `fill` is a string, this is its encoding. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `fill` is a string, this is its encoding." + } + ] + } + ], + "desc": "

      Allocates a new Buffer of size bytes. If fill is undefined, the\nBuffer will be zero-filled.

      \n
      const buf = Buffer.alloc(5);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00>\n
      \n

      If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE\nis thrown.

      \n

      If fill is specified, the allocated Buffer will be initialized by calling\nbuf.fill(fill).

      \n
      const buf = Buffer.alloc(5, 'a');\n\nconsole.log(buf);\n// Prints: <Buffer 61 61 61 61 61>\n
      \n

      If both fill and encoding are specified, the allocated Buffer will be\ninitialized by calling buf.fill(fill, encoding).

      \n
      const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\n\nconsole.log(buf);\n// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\n
      \n

      Calling Buffer.alloc() can be measurably slower than the alternative\nBuffer.allocUnsafe() but ensures that the newly created Buffer instance\ncontents will never contain sensitive data from previous allocations, including\ndata that might not have been allocated for Buffers.

      \n

      A TypeError will be thrown if size is not a number.

      " + }, + { + "textRaw": "Static method: `Buffer.allocUnsafe(size)`", + "type": "classMethod", + "name": "allocUnsafe", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7079", + "description": "Passing a negative `size` will now throw an error." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + } + ] + } + ], + "desc": "

      Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE\nis thrown.

      \n

      The underlying memory for Buffer instances created in this way is not\ninitialized. The contents of the newly created Buffer are unknown and\nmay contain sensitive data. Use Buffer.alloc() instead to initialize\nBuffer instances with zeroes.

      \n
      const buf = Buffer.allocUnsafe(10);\n\nconsole.log(buf);\n// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>\n\nbuf.fill(0);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\n
      \n

      A TypeError will be thrown if size is not a number.

      \n

      The Buffer module pre-allocates an internal Buffer instance of\nsize Buffer.poolSize that is used as a pool for the fast allocation of new\nBuffer instances created using Buffer.allocUnsafe(),\nBuffer.from(array), Buffer.concat(), and the deprecated\nnew Buffer(size) constructor only when size is less than or equal\nto Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).

      \n

      Use of this pre-allocated internal memory pool is a key difference between\ncalling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill).\nSpecifically, Buffer.alloc(size, fill) will never use the internal Buffer\npool, while Buffer.allocUnsafe(size).fill(fill) will use the internal\nBuffer pool if size is less than or equal to half Buffer.poolSize. The\ndifference is subtle but can be important when an application requires the\nadditional performance that Buffer.allocUnsafe() provides.

      " + }, + { + "textRaw": "Static method: `Buffer.allocUnsafeSlow(size)`", + "type": "classMethod", + "name": "allocUnsafeSlow", + "meta": { + "added": [ + "v5.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + } + ] + } + ], + "desc": "

      Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE\nis thrown. A zero-length Buffer is created if size is 0.

      \n

      The underlying memory for Buffer instances created in this way is not\ninitialized. The contents of the newly created Buffer are unknown and\nmay contain sensitive data. Use buf.fill(0) to initialize\nsuch Buffer instances with zeroes.

      \n

      When using Buffer.allocUnsafe() to allocate new Buffer instances,\nallocations under 4KB are sliced from a single pre-allocated Buffer. This\nallows applications to avoid the garbage collection overhead of creating many\nindividually allocated Buffer instances. This approach improves both\nperformance and memory usage by eliminating the need to track and clean up as\nmany individual ArrayBuffer objects.

      \n

      However, in the case where a developer may need to retain a small chunk of\nmemory from a pool for an indeterminate amount of time, it may be appropriate\nto create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and\nthen copying out the relevant bits.

      \n
      // Need to keep around a few small chunks of memory.\nconst store = [];\n\nsocket.on('readable', () => {\n  let data;\n  while (null !== (data = readable.read())) {\n    // Allocate for retained data.\n    const sb = Buffer.allocUnsafeSlow(10);\n\n    // Copy the data into the new allocation.\n    data.copy(sb, 0, 0, 10);\n\n    store.push(sb);\n  }\n});\n
      \n

      A TypeError will be thrown if size is not a number.

      " + }, + { + "textRaw": "Static method: `Buffer.byteLength(string[, encoding])`", + "type": "classMethod", + "name": "byteLength", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8946", + "description": "Passing invalid input will now throw an error." + }, + { + "version": "v5.10.0", + "pr-url": "https://github.com/nodejs/node/pull/5255", + "description": "The `string` parameter can now be any `TypedArray`, `DataView` or `ArrayBuffer`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The number of bytes contained within `string`.", + "name": "return", + "type": "integer", + "desc": "The number of bytes contained within `string`." + }, + "params": [ + { + "textRaw": "`string` {string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer} A value to calculate the length of.", + "name": "string", + "type": "string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer", + "desc": "A value to calculate the length of." + }, + { + "textRaw": "`encoding` {string} If `string` is a string, this is its encoding. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `string` is a string, this is its encoding." + } + ] + } + ], + "desc": "

      Returns the byte length of a string when encoded using encoding.\nThis is not the same as String.prototype.length, which does not account\nfor the encoding that is used to convert the string into bytes.

      \n

      For 'base64' and 'hex', this function assumes valid input. For strings that\ncontain non-base64/hex-encoded data (e.g. whitespace), the return value might be\ngreater than the length of a Buffer created from the string.

      \n
      const str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(`${str}: ${str.length} characters, ` +\n            `${Buffer.byteLength(str, 'utf8')} bytes`);\n// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes\n
      \n

      When string is a Buffer/DataView/TypedArray/ArrayBuffer/\nSharedArrayBuffer, the byte length as reported by .byteLength\nis returned.

      " + }, + { + "textRaw": "Static method: `Buffer.compare(buf1, buf2)`", + "type": "classMethod", + "name": "compare", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The arguments can now be `Uint8Array`s." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details.", + "name": "return", + "type": "integer", + "desc": "Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details." + }, + "params": [ + { + "textRaw": "`buf1` {Buffer|Uint8Array}", + "name": "buf1", + "type": "Buffer|Uint8Array" + }, + { + "textRaw": "`buf2` {Buffer|Uint8Array}", + "name": "buf2", + "type": "Buffer|Uint8Array" + } + ] + } + ], + "desc": "

      Compares buf1 to buf2, typically for the purpose of sorting arrays of\nBuffer instances. This is equivalent to calling\nbuf1.compare(buf2).

      \n
      const buf1 = Buffer.from('1234');\nconst buf2 = Buffer.from('0123');\nconst arr = [buf1, buf2];\n\nconsole.log(arr.sort(Buffer.compare));\n// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]\n// (This result is equal to: [buf2, buf1].)\n
      " + }, + { + "textRaw": "Static method: `Buffer.concat(list[, totalLength])`", + "type": "classMethod", + "name": "concat", + "meta": { + "added": [ + "v0.7.11" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The elements of `list` can now be `Uint8Array`s." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`][] instances to concatenate.", + "name": "list", + "type": "Buffer[] | Uint8Array[]", + "desc": "List of `Buffer` or [`Uint8Array`][] instances to concatenate." + }, + { + "textRaw": "`totalLength` {integer} Total length of the `Buffer` instances in `list` when concatenated.", + "name": "totalLength", + "type": "integer", + "desc": "Total length of the `Buffer` instances in `list` when concatenated." + } + ] + } + ], + "desc": "

      Returns a new Buffer which is the result of concatenating all the Buffer\ninstances in the list together.

      \n

      If the list has no items, or if the totalLength is 0, then a new zero-length\nBuffer is returned.

      \n

      If totalLength is not provided, it is calculated from the Buffer instances\nin list by adding their lengths.

      \n

      If totalLength is provided, it is coerced to an unsigned integer. If the\ncombined length of the Buffers in list exceeds totalLength, the result is\ntruncated to totalLength.

      \n
      // Create a single `Buffer` from a list of three `Buffer` instances.\n\nconst buf1 = Buffer.alloc(10);\nconst buf2 = Buffer.alloc(14);\nconst buf3 = Buffer.alloc(18);\nconst totalLength = buf1.length + buf2.length + buf3.length;\n\nconsole.log(totalLength);\n// Prints: 42\n\nconst bufA = Buffer.concat([buf1, buf2, buf3], totalLength);\n\nconsole.log(bufA);\n// Prints: <Buffer 00 00 00 00 ...>\nconsole.log(bufA.length);\n// Prints: 42\n
      \n

      Buffer.concat() may also use the internal Buffer pool like\nBuffer.allocUnsafe() does.

      " + }, + { + "textRaw": "Static method: `Buffer.from(array)`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`array` {integer[]}", + "name": "array", + "type": "integer[]" + } + ] + } + ], + "desc": "

      Allocates a new Buffer using an array of bytes in the range 0 – 255.\nArray entries outside that range will be truncated to fit into it.

      \n
      // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.\nconst buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
      \n

      A TypeError will be thrown if array is not an Array or another type\nappropriate for Buffer.from() variants.

      \n

      Buffer.from(array) and Buffer.from(string) may also use the internal\nBuffer pool like Buffer.allocUnsafe() does.

      " + }, + { + "textRaw": "Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a [`TypedArray`][].", + "name": "arrayBuffer", + "type": "ArrayBuffer|SharedArrayBuffer", + "desc": "An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a [`TypedArray`][]." + }, + { + "textRaw": "`byteOffset` {integer} Index of first byte to expose. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Index of first byte to expose." + }, + { + "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`.", + "name": "length", + "type": "integer", + "default": "`arrayBuffer.byteLength - byteOffset`", + "desc": "Number of bytes to expose." + } + ] + } + ], + "desc": "

      This creates a view of the ArrayBuffer without copying the underlying\nmemory. For example, when passed a reference to the .buffer property of a\nTypedArray instance, the newly created Buffer will share the same\nallocated memory as the TypedArray.

      \n
      const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`.\nconst buf = Buffer.from(arr.buffer);\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 a0 0f>\n\n// Changing the original Uint16Array changes the Buffer also.\narr[1] = 6000;\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 70 17>\n
      \n

      The optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.

      \n
      const ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\nconsole.log(buf.length);\n// Prints: 2\n
      \n

      A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a\nSharedArrayBuffer or another type appropriate for Buffer.from()\nvariants.

      " + }, + { + "textRaw": "Static method: `Buffer.from(buffer)`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from which to copy data.", + "name": "buffer", + "type": "Buffer|Uint8Array", + "desc": "An existing `Buffer` or [`Uint8Array`][] from which to copy data." + } + ] + } + ], + "desc": "

      Copies the passed buffer data onto a new Buffer instance.

      \n
      const buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\n\nconsole.log(buf1.toString());\n// Prints: auffer\nconsole.log(buf2.toString());\n// Prints: buffer\n
      \n

      A TypeError will be thrown if buffer is not a Buffer or another type\nappropriate for Buffer.from() variants.

      " + }, + { + "textRaw": "Static method: `Buffer.from(object[, offsetOrEncoding[, length]])`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`object` {Object} An object supporting `Symbol.toPrimitive` or `valueOf()`.", + "name": "object", + "type": "Object", + "desc": "An object supporting `Symbol.toPrimitive` or `valueOf()`." + }, + { + "textRaw": "`offsetOrEncoding` {integer|string} A byte-offset or encoding.", + "name": "offsetOrEncoding", + "type": "integer|string", + "desc": "A byte-offset or encoding." + }, + { + "textRaw": "`length` {integer} A length.", + "name": "length", + "type": "integer", + "desc": "A length." + } + ] + } + ], + "desc": "

      For objects whose valueOf() function returns a value not strictly equal to\nobject, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

      \n
      const buf = Buffer.from(new String('this is a test'));\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n
      \n

      For objects that support Symbol.toPrimitive, returns\nBuffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).

      \n
      class Foo {\n  [Symbol.toPrimitive]() {\n    return 'this is a test';\n  }\n}\n\nconst buf = Buffer.from(new Foo(), 'utf8');\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n
      \n

      A TypeError will be thrown if object does not have the mentioned methods or\nis not of another type appropriate for Buffer.from() variants.

      " + }, + { + "textRaw": "Static method: `Buffer.from(string[, encoding])`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string} A string to encode.", + "name": "string", + "type": "string", + "desc": "A string to encode." + }, + { + "textRaw": "`encoding` {string} The encoding of `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding of `string`." + } + ] + } + ], + "desc": "

      Creates a new Buffer containing string. The encoding parameter identifies\nthe character encoding to be used when converting string into bytes.

      \n
      const buf1 = Buffer.from('this is a tést');\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\n\nconsole.log(buf1.toString());\n// Prints: this is a tést\nconsole.log(buf2.toString());\n// Prints: this is a tést\nconsole.log(buf1.toString('latin1'));\n// Prints: this is a tést\n
      \n

      A TypeError will be thrown if string is not a string or another type\nappropriate for Buffer.from() variants.

      " + }, + { + "textRaw": "Static method: `Buffer.isBuffer(obj)`", + "type": "classMethod", + "name": "isBuffer", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`obj` {Object}", + "name": "obj", + "type": "Object" + } + ] + } + ], + "desc": "

      Returns true if obj is a Buffer, false otherwise.

      " + }, + { + "textRaw": "Static method: `Buffer.isEncoding(encoding)`", + "type": "classMethod", + "name": "isEncoding", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`encoding` {string} A character encoding name to check.", + "name": "encoding", + "type": "string", + "desc": "A character encoding name to check." + } + ] + } + ], + "desc": "

      Returns true if encoding is the name of a supported character encoding,\nor false otherwise.

      \n
      console.log(Buffer.isEncoding('utf-8'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('hex'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('utf/8'));\n// Prints: false\n\nconsole.log(Buffer.isEncoding(''));\n// Prints: false\n
      " + } + ], + "properties": [ + { + "textRaw": "`poolSize` {integer} **Default:** `8192`", + "type": "integer", + "name": "poolSize", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "default": "`8192`", + "desc": "

      This is the size (in bytes) of pre-allocated internal Buffer instances used\nfor pooling. This value may be modified.

      " + }, + { + "textRaw": "`[index]` `index` {integer}", + "type": "integer", + "name": "index", + "meta": { + "type": "property", + "name": [ + "index" + ], + "changes": [] + }, + "desc": "

      The index operator [index] can be used to get and set the octet at position\nindex in buf. The values refer to individual bytes, so the legal value\nrange is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).

      \n

      This operator is inherited from Uint8Array, so its behavior on out-of-bounds\naccess is the same as Uint8Array. In other words, buf[index] returns\nundefined when index is negative or greater or equal to buf.length, and\nbuf[index] = value does not modify the buffer if index is negative or\n>= buf.length.

      \n
      // Copy an ASCII string into a `Buffer` one byte at a time.\n// (This only works for ASCII-only strings. In general, one should use\n// `Buffer.from()` to perform this conversion.)\n\nconst str = 'Node.js';\nconst buf = Buffer.allocUnsafe(str.length);\n\nfor (let i = 0; i < str.length; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf.toString('utf8'));\n// Prints: Node.js\n
      " + }, + { + "textRaw": "`buffer` {ArrayBuffer} The underlying `ArrayBuffer` object based on which this `Buffer` object is created.", + "type": "ArrayBuffer", + "name": "buffer", + "desc": "

      This ArrayBuffer is not guaranteed to correspond exactly to the original\nBuffer. See the notes on buf.byteOffset for details.

      \n
      const arrayBuffer = new ArrayBuffer(16);\nconst buffer = Buffer.from(arrayBuffer);\n\nconsole.log(buffer.buffer === arrayBuffer);\n// Prints: true\n
      ", + "shortDesc": "The underlying `ArrayBuffer` object based on which this `Buffer` object is created." + }, + { + "textRaw": "`byteOffset` {integer} The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object.", + "type": "integer", + "name": "byteOffset", + "desc": "

      When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length),\nor sometimes when allocating a Buffer smaller than Buffer.poolSize, the\nbuffer does not start from a zero offset on the underlying ArrayBuffer.

      \n

      This can cause problems when accessing the underlying ArrayBuffer directly\nusing buf.buffer, as other parts of the ArrayBuffer may be unrelated\nto the Buffer object itself.

      \n

      A common issue when creating a TypedArray object that shares its memory with\na Buffer is that in this case one needs to specify the byteOffset correctly:

      \n
      // Create a buffer smaller than `Buffer.poolSize`.\nconst nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n\n// When casting the Node.js Buffer to an Int8Array, use the byteOffset\n// to refer only to the part of `nodeBuffer.buffer` that contains the memory\n// for `nodeBuffer`.\nnew Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);\n
      ", + "shortDesc": "The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object." + }, + { + "textRaw": "`length` {integer}", + "type": "integer", + "name": "length", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      Returns the number of bytes in buf.

      \n
      // Create a `Buffer` and write a shorter string to it using UTF-8.\n\nconst buf = Buffer.alloc(1234);\n\nconsole.log(buf.length);\n// Prints: 1234\n\nbuf.write('some string', 0, 'utf8');\n\nconsole.log(buf.length);\n// Prints: 1234\n
      " + }, + { + "textRaw": "`buf.parent`", + "name": "parent", + "meta": { + "deprecated": [ + "v8.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`buf.buffer`][] instead.", + "desc": "

      The buf.parent property is a deprecated alias for buf.buffer.

      " + } + ], + "methods": [ + { + "textRaw": "`buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`", + "type": "method", + "name": "compare", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `target` parameter can now be a `Uint8Array`." + }, + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/5880", + "description": "Additional parameters for specifying offsets are supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to compare `buf`.", + "name": "target", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or [`Uint8Array`][] with which to compare `buf`." + }, + { + "textRaw": "`targetStart` {integer} The offset within `target` at which to begin comparison. **Default:** `0`.", + "name": "targetStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `target` at which to begin comparison." + }, + { + "textRaw": "`targetEnd` {integer} The offset within `target` at which to end comparison (not inclusive). **Default:** `target.length`.", + "name": "targetEnd", + "type": "integer", + "default": "`target.length`", + "desc": "The offset within `target` at which to end comparison (not inclusive)." + }, + { + "textRaw": "`sourceStart` {integer} The offset within `buf` at which to begin comparison. **Default:** `0`.", + "name": "sourceStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `buf` at which to begin comparison." + }, + { + "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to end comparison (not inclusive). **Default:** [`buf.length`][].", + "name": "sourceEnd", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "The offset within `buf` at which to end comparison (not inclusive)." + } + ] + } + ], + "desc": "

      Compares buf with target and returns a number indicating whether buf\ncomes before, after, or is the same as target in sort order.\nComparison is based on the actual sequence of bytes in each Buffer.

      \n
        \n
      • 0 is returned if target is the same as buf
      • \n
      • 1 is returned if target should come before buf when sorted.
      • \n
      • -1 is returned if target should come after buf when sorted.
      • \n
      \n
      const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.compare(buf1));\n// Prints: 0\nconsole.log(buf1.compare(buf2));\n// Prints: -1\nconsole.log(buf1.compare(buf3));\n// Prints: -1\nconsole.log(buf2.compare(buf1));\n// Prints: 1\nconsole.log(buf2.compare(buf3));\n// Prints: 1\nconsole.log([buf1, buf2, buf3].sort(Buffer.compare));\n// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]\n// (This result is equal to: [buf1, buf3, buf2].)\n
      \n

      The optional targetStart, targetEnd, sourceStart, and sourceEnd\narguments can be used to limit the comparison to specific ranges within target\nand buf respectively.

      \n
      const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);\n\nconsole.log(buf1.compare(buf2, 5, 9, 0, 4));\n// Prints: 0\nconsole.log(buf1.compare(buf2, 0, 6, 4));\n// Prints: -1\nconsole.log(buf1.compare(buf2, 5, 6, 5));\n// Prints: 1\n
      \n

      ERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0,\ntargetEnd > target.byteLength, or sourceEnd > source.byteLength.

      " + }, + { + "textRaw": "`buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`", + "type": "method", + "name": "copy", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The number of bytes copied.", + "name": "return", + "type": "integer", + "desc": "The number of bytes copied." + }, + "params": [ + { + "textRaw": "`target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] to copy into.", + "name": "target", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or [`Uint8Array`][] to copy into." + }, + { + "textRaw": "`targetStart` {integer} The offset within `target` at which to begin writing. **Default:** `0`.", + "name": "targetStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `target` at which to begin writing." + }, + { + "textRaw": "`sourceStart` {integer} The offset within `buf` from which to begin copying. **Default:** `0`.", + "name": "sourceStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `buf` from which to begin copying." + }, + { + "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to stop copying (not inclusive). **Default:** [`buf.length`][].", + "name": "sourceEnd", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "The offset within `buf` at which to stop copying (not inclusive)." + } + ] + } + ], + "desc": "

      Copies data from a region of buf to a region in target, even if the target\nmemory region overlaps with buf.

      \n

      TypedArray#set() performs the same operation, and is available for all\nTypedArrays, including Node.js Buffers, although it takes different\nfunction arguments.

      \n
      // Create two `Buffer` instances.\nconst buf1 = Buffer.allocUnsafe(26);\nconst buf2 = Buffer.allocUnsafe(26).fill('!');\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf1[i] = i + 97;\n}\n\n// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.\nbuf1.copy(buf2, 8, 16, 20);\n// This is equivalent to:\n// buf2.set(buf1.subarray(16, 20), 8);\n\nconsole.log(buf2.toString('ascii', 0, 25));\n// Prints: !!!!!!!!qrst!!!!!!!!!!!!!\n
      \n
      // Create a `Buffer` and copy data from one region to an overlapping region\n// within the same `Buffer`.\n\nconst buf = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf[i] = i + 97;\n}\n\nbuf.copy(buf, 0, 4, 10);\n\nconsole.log(buf.toString());\n// Prints: efghijghijklmnopqrstuvwxyz\n
      " + }, + { + "textRaw": "`buf.entries()`", + "type": "method", + "name": "entries", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Creates and returns an iterator of [index, byte] pairs from the contents\nof buf.

      \n
      // Log the entire contents of a `Buffer`.\n\nconst buf = Buffer.from('buffer');\n\nfor (const pair of buf.entries()) {\n  console.log(pair);\n}\n// Prints:\n//   [0, 98]\n//   [1, 117]\n//   [2, 102]\n//   [3, 102]\n//   [4, 101]\n//   [5, 114]\n
      " + }, + { + "textRaw": "`buf.equals(otherBuffer)`", + "type": "method", + "name": "equals", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The arguments can now be `Uint8Array`s." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`otherBuffer` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to compare `buf`.", + "name": "otherBuffer", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or [`Uint8Array`][] with which to compare `buf`." + } + ] + } + ], + "desc": "

      Returns true if both buf and otherBuffer have exactly the same bytes,\nfalse otherwise. Equivalent to\nbuf.compare(otherBuffer) === 0.

      \n
      const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.equals(buf2));\n// Prints: true\nconsole.log(buf1.equals(buf3));\n// Prints: false\n
      " + }, + { + "textRaw": "`buf.fill(value[, offset[, end]][, encoding])`", + "type": "method", + "name": "fill", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22969", + "description": "Throws `ERR_OUT_OF_RANGE` instead of `ERR_INDEX_OUT_OF_RANGE`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18790", + "description": "Negative `end` values throw an `ERR_INDEX_OUT_OF_RANGE` error." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18129", + "description": "Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17427", + "description": "Specifying an invalid string for `value` triggers a thrown exception." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4935", + "description": "The `encoding` parameter is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "The value with which to fill `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to fill `buf`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to fill `buf`." + }, + { + "textRaw": "`end` {integer} Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "Where to stop filling `buf` (not inclusive)." + }, + { + "textRaw": "`encoding` {string} The encoding for `value` if `value` is a string. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding for `value` if `value` is a string." + } + ] + } + ], + "desc": "

      Fills buf with the specified value. If the offset and end are not given,\nthe entire buf will be filled:

      \n
      // Fill a `Buffer` with the ASCII character 'h'.\n\nconst b = Buffer.allocUnsafe(50).fill('h');\n\nconsole.log(b.toString());\n// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\n
      \n

      value is coerced to a uint32 value if it is not a string, Buffer, or\ninteger. If the resulting integer is greater than 255 (decimal), buf will be\nfilled with value & 255.

      \n

      If the final write of a fill() operation falls on a multi-byte character,\nthen only the bytes of that character that fit into buf are written:

      \n
      // Fill a `Buffer` with character that takes up two bytes in UTF-8.\n\nconsole.log(Buffer.allocUnsafe(5).fill('\\u0222'));\n// Prints: <Buffer c8 a2 c8 a2 c8>\n
      \n

      If value contains invalid characters, it is truncated; if no valid\nfill data remains, an exception is thrown:

      \n
      const buf = Buffer.allocUnsafe(5);\n\nconsole.log(buf.fill('a'));\n// Prints: <Buffer 61 61 61 61 61>\nconsole.log(buf.fill('aazz', 'hex'));\n// Prints: <Buffer aa aa aa aa aa>\nconsole.log(buf.fill('zz', 'hex'));\n// Throws an exception.\n
      " + }, + { + "textRaw": "`buf.includes(value[, byteOffset][, encoding])`", + "type": "method", + "name": "includes", + "meta": { + "added": [ + "v5.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if `value` was found in `buf`, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if `value` was found in `buf`, `false` otherwise." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "What to search for." + }, + { + "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`." + }, + { + "textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `value` is a string, this is its encoding." + } + ] + } + ], + "desc": "

      Equivalent to buf.indexOf() !== -1.

      \n
      const buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.includes('this'));\n// Prints: true\nconsole.log(buf.includes('is'));\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n// Prints: true\nconsole.log(buf.includes(97));\n// Prints: true (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: true\nconsole.log(buf.includes('this', 4));\n// Prints: false\n
      " + }, + { + "textRaw": "`buf.indexOf(value[, byteOffset][, encoding])`", + "type": "method", + "name": "indexOf", + "meta": { + "added": [ + "v1.5.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `value` can now be a `Uint8Array`." + }, + { + "version": "v5.7.0, v4.4.0", + "pr-url": "https://github.com/nodejs/node/pull/4803", + "description": "When `encoding` is being passed, the `byteOffset` parameter is no longer required." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.", + "name": "return", + "type": "integer", + "desc": "The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "What to search for." + }, + { + "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`." + }, + { + "textRaw": "`encoding` {string} If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`." + } + ] + } + ], + "desc": "

      If value is:

      \n
        \n
      • a string, value is interpreted according to the character encoding in\nencoding.
      • \n
      • a Buffer or Uint8Array, value will be used in its entirety.\nTo compare a partial Buffer, use buf.slice().
      • \n
      • a number, value will be interpreted as an unsigned 8-bit integer\nvalue between 0 and 255.
      • \n
      \n
      const buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.indexOf('this'));\n// Prints: 0\nconsole.log(buf.indexOf('is'));\n// Prints: 2\nconsole.log(buf.indexOf(Buffer.from('a buffer')));\n// Prints: 8\nconsole.log(buf.indexOf(97));\n// Prints: 8 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.indexOf(Buffer.from('a buffer example')));\n// Prints: -1\nconsole.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: 8\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.indexOf('\\u03a3', 0, 'utf16le'));\n// Prints: 4\nconsole.log(utf16Buffer.indexOf('\\u03a3', -4, 'utf16le'));\n// Prints: 6\n
      \n

      If value is not a string, number, or Buffer, this method will throw a\nTypeError. If value is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.

      \n

      If byteOffset is not a number, it will be coerced to a number. If the result\nof coercion is NaN or 0, then the entire buffer will be searched. This\nbehavior matches String#indexOf().

      \n
      const b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.indexOf(99.9));\nconsole.log(b.indexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN or 0.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.indexOf('b', undefined));\nconsole.log(b.indexOf('b', {}));\nconsole.log(b.indexOf('b', null));\nconsole.log(b.indexOf('b', []));\n
      \n

      If value is an empty string or empty Buffer and byteOffset is less\nthan buf.length, byteOffset will be returned. If value is empty and\nbyteOffset is at least buf.length, buf.length will be returned.

      " + }, + { + "textRaw": "`buf.keys()`", + "type": "method", + "name": "keys", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Creates and returns an iterator of buf keys (indices).

      \n
      const buf = Buffer.from('buffer');\n\nfor (const key of buf.keys()) {\n  console.log(key);\n}\n// Prints:\n//   0\n//   1\n//   2\n//   3\n//   4\n//   5\n
      " + }, + { + "textRaw": "`buf.lastIndexOf(value[, byteOffset][, encoding])`", + "type": "method", + "name": "lastIndexOf", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `value` can now be a `Uint8Array`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.", + "name": "return", + "type": "integer", + "desc": "The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "What to search for." + }, + { + "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `buf.length - 1`.", + "name": "byteOffset", + "type": "integer", + "default": "`buf.length - 1`", + "desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`." + }, + { + "textRaw": "`encoding` {string} If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`." + } + ] + } + ], + "desc": "

      Identical to buf.indexOf(), except the last occurrence of value is found\nrather than the first occurrence.

      \n
      const buf = Buffer.from('this buffer is a buffer');\n\nconsole.log(buf.lastIndexOf('this'));\n// Prints: 0\nconsole.log(buf.lastIndexOf('buffer'));\n// Prints: 17\nconsole.log(buf.lastIndexOf(Buffer.from('buffer')));\n// Prints: 17\nconsole.log(buf.lastIndexOf(97));\n// Prints: 15 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.lastIndexOf(Buffer.from('yolo')));\n// Prints: -1\nconsole.log(buf.lastIndexOf('buffer', 5));\n// Prints: 5\nconsole.log(buf.lastIndexOf('buffer', 4));\n// Prints: -1\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', undefined, 'utf16le'));\n// Prints: 6\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', -5, 'utf16le'));\n// Prints: 4\n
      \n

      If value is not a string, number, or Buffer, this method will throw a\nTypeError. If value is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.

      \n

      If byteOffset is not a number, it will be coerced to a number. Any arguments\nthat coerce to NaN, like {} or undefined, will search the whole buffer.\nThis behavior matches String#lastIndexOf().

      \n
      const b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.lastIndexOf(99.9));\nconsole.log(b.lastIndexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.lastIndexOf('b', undefined));\nconsole.log(b.lastIndexOf('b', {}));\n\n// Passing a byteOffset that coerces to 0.\n// Prints: -1, equivalent to passing 0.\nconsole.log(b.lastIndexOf('b', null));\nconsole.log(b.lastIndexOf('b', []));\n
      \n

      If value is an empty string or empty Buffer, byteOffset will be returned.

      " + }, + { + "textRaw": "`buf.readBigInt64BE([offset])`", + "type": "method", + "name": "readBigInt64BE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a signed, big-endian 64-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed\nvalues.

      " + }, + { + "textRaw": "`buf.readBigInt64LE([offset])`", + "type": "method", + "name": "readBigInt64LE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a signed, little-endian 64-bit integer from buf at the specified\noffset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed\nvalues.

      " + }, + { + "textRaw": "`buf.readBigUInt64BE([offset])`", + "type": "method", + "name": "readBigUInt64BE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.readBigUint64BE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads an unsigned, big-endian 64-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64BE(0));\n// Prints: 4294967295n\n
      " + }, + { + "textRaw": "`buf.readBigUInt64LE([offset])`", + "type": "method", + "name": "readBigUInt64LE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.readBigUint64LE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads an unsigned, little-endian 64-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64LE(0));\n// Prints: 18446744069414584320n\n
      " + }, + { + "textRaw": "`buf.readDoubleBE([offset])`", + "type": "method", + "name": "readDoubleBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a 64-bit, big-endian double from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleBE(0));\n// Prints: 8.20788039913184e-304\n
      " + }, + { + "textRaw": "`buf.readDoubleLE([offset])`", + "type": "method", + "name": "readDoubleLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a 64-bit, little-endian double from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleLE(0));\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readFloatBE([offset])`", + "type": "method", + "name": "readFloatBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a 32-bit, big-endian float from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatBE(0));\n// Prints: 2.387939260590663e-38\n
      " + }, + { + "textRaw": "`buf.readFloatLE([offset])`", + "type": "method", + "name": "readFloatLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a 32-bit, little-endian float from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatLE(0));\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readInt8([offset])`", + "type": "method", + "name": "readInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Reads a signed 8-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([-1, 5]);\n\nconsole.log(buf.readInt8(0));\n// Prints: -1\nconsole.log(buf.readInt8(1));\n// Prints: 5\nconsole.log(buf.readInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readInt16BE([offset])`", + "type": "method", + "name": "readInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads a signed, big-endian 16-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16BE(0));\n// Prints: 5\n
      " + }, + { + "textRaw": "`buf.readInt16LE([offset])`", + "type": "method", + "name": "readInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads a signed, little-endian 16-bit integer from buf at the specified\noffset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16LE(0));\n// Prints: 1280\nconsole.log(buf.readInt16LE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readInt32BE([offset])`", + "type": "method", + "name": "readInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a signed, big-endian 32-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32BE(0));\n// Prints: 5\n
      " + }, + { + "textRaw": "`buf.readInt32LE([offset])`", + "type": "method", + "name": "readInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a signed, little-endian 32-bit integer from buf at the specified\noffset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32LE(0));\n// Prints: 83886080\nconsole.log(buf.readInt32LE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readIntBE(offset, byteLength)`", + "type": "method", + "name": "readIntBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a big-endian, two's complement signed value\nsupporting up to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\nconsole.log(buf.readIntBE(1, 0).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readIntLE(offset, byteLength)`", + "type": "method", + "name": "readIntLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a little-endian, two's complement signed value\nsupporting up to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntLE(0, 6).toString(16));\n// Prints: -546f87a9cbee\n
      " + }, + { + "textRaw": "`buf.readUInt8([offset])`", + "type": "method", + "name": "readUInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint8()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Reads an unsigned 8-bit integer from buf at the specified offset.

      \n
      const buf = Buffer.from([1, -2]);\n\nconsole.log(buf.readUInt8(0));\n// Prints: 1\nconsole.log(buf.readUInt8(1));\n// Prints: 254\nconsole.log(buf.readUInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUInt16BE([offset])`", + "type": "method", + "name": "readUInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint16BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads an unsigned, big-endian 16-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16BE(0).toString(16));\n// Prints: 1234\nconsole.log(buf.readUInt16BE(1).toString(16));\n// Prints: 3456\n
      " + }, + { + "textRaw": "`buf.readUInt16LE([offset])`", + "type": "method", + "name": "readUInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint16LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads an unsigned, little-endian 16-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16LE(0).toString(16));\n// Prints: 3412\nconsole.log(buf.readUInt16LE(1).toString(16));\n// Prints: 5634\nconsole.log(buf.readUInt16LE(2).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUInt32BE([offset])`", + "type": "method", + "name": "readUInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint32BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads an unsigned, big-endian 32-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32BE(0).toString(16));\n// Prints: 12345678\n
      " + }, + { + "textRaw": "`buf.readUInt32LE([offset])`", + "type": "method", + "name": "readUInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint32LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads an unsigned, little-endian 32-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32LE(0).toString(16));\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(1).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUIntBE(offset, byteLength)`", + "type": "method", + "name": "readUIntBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUintBE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned big-endian integer supporting\nup to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUIntLE(offset, byteLength)`", + "type": "method", + "name": "readUIntLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUintLE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned, little-endian integer supporting\nup to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n// Prints: ab9078563412\n
      " + }, + { + "textRaw": "`buf.subarray([start[, end]])`", + "type": "method", + "name": "subarray", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`start` {integer} Where the new `Buffer` will start. **Default:** `0`.", + "name": "start", + "type": "integer", + "default": "`0`", + "desc": "Where the new `Buffer` will start." + }, + { + "textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "Where the new `Buffer` will end (not inclusive)." + } + ] + } + ], + "desc": "

      Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

      \n

      Specifying end greater than buf.length will return the same result as\nthat of end equal to buf.length.

      \n

      This method is inherited from TypedArray#subarray().

      \n

      Modifying the new Buffer slice will modify the memory in the original Buffer\nbecause the allocated memory of the two objects overlap.

      \n
      // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte\n// from the original `Buffer`.\n\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf1[i] = i + 97;\n}\n\nconst buf2 = buf1.subarray(0, 3);\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: abc\n\nbuf1[0] = 33;\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: !bc\n
      \n

      Specifying negative indexes causes the slice to be generated relative to the\nend of buf rather than the beginning.

      \n
      const buf = Buffer.from('buffer');\n\nconsole.log(buf.subarray(-6, -1).toString());\n// Prints: buffe\n// (Equivalent to buf.subarray(0, 5).)\n\nconsole.log(buf.subarray(-6, -2).toString());\n// Prints: buff\n// (Equivalent to buf.subarray(0, 4).)\n\nconsole.log(buf.subarray(-5, -2).toString());\n// Prints: uff\n// (Equivalent to buf.subarray(1, 4).)\n
      " + }, + { + "textRaw": "`buf.slice([start[, end]])`", + "type": "method", + "name": "slice", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v7.1.0, v6.9.2", + "pr-url": "https://github.com/nodejs/node/pull/9341", + "description": "Coercing the offsets to integers now handles values outside the 32-bit integer range properly." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9101", + "description": "All offsets are now coerced to integers before doing any calculations with them." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`start` {integer} Where the new `Buffer` will start. **Default:** `0`.", + "name": "start", + "type": "integer", + "default": "`0`", + "desc": "Where the new `Buffer` will start." + }, + { + "textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "Where the new `Buffer` will end (not inclusive)." + } + ] + } + ], + "desc": "

      Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

      \n

      This is the same behavior as buf.subarray().

      \n

      This method is not compatible with the Uint8Array.prototype.slice(),\nwhich is a superclass of Buffer. To copy the slice, use\nUint8Array.prototype.slice().

      \n
      const buf = Buffer.from('buffer');\n\nconst copiedBuf = Uint8Array.prototype.slice.call(buf);\ncopiedBuf[0]++;\nconsole.log(copiedBuf.toString());\n// Prints: cuffer\n\nconsole.log(buf.toString());\n// Prints: buffer\n
      " + }, + { + "textRaw": "`buf.swap16()`", + "type": "method", + "name": "swap16", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [] + } + ], + "desc": "

      Interprets buf as an array of unsigned 16-bit integers and swaps the\nbyte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length\nis not a multiple of 2.

      \n
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap16();\n\nconsole.log(buf1);\n// Prints: <Buffer 02 01 04 03 06 05 08 07>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap16();\n// Throws ERR_INVALID_BUFFER_SIZE.\n
      \n

      One convenient use of buf.swap16() is to perform a fast in-place conversion\nbetween UTF-16 little-endian and UTF-16 big-endian:

      \n
      const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');\nbuf.swap16(); // Convert to big-endian UTF-16 text.\n
      " + }, + { + "textRaw": "`buf.swap32()`", + "type": "method", + "name": "swap32", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [] + } + ], + "desc": "

      Interprets buf as an array of unsigned 32-bit integers and swaps the\nbyte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length\nis not a multiple of 4.

      \n
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap32();\n\nconsole.log(buf1);\n// Prints: <Buffer 04 03 02 01 08 07 06 05>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap32();\n// Throws ERR_INVALID_BUFFER_SIZE.\n
      " + }, + { + "textRaw": "`buf.swap64()`", + "type": "method", + "name": "swap64", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [] + } + ], + "desc": "

      Interprets buf as an array of 64-bit numbers and swaps byte order in-place.\nThrows ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.

      \n
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap64();\n\nconsole.log(buf1);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap64();\n// Throws ERR_INVALID_BUFFER_SIZE.\n
      " + }, + { + "textRaw": "`buf.toJSON()`", + "type": "method", + "name": "toJSON", + "meta": { + "added": [ + "v0.9.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns a JSON representation of buf. JSON.stringify() implicitly calls\nthis function when stringifying a Buffer instance.

      \n

      Buffer.from() accepts objects in the format returned from this method.\nIn particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

      \n
      const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);\nconst json = JSON.stringify(buf);\n\nconsole.log(json);\n// Prints: {\"type\":\"Buffer\",\"data\":[1,2,3,4,5]}\n\nconst copy = JSON.parse(json, (key, value) => {\n  return value && value.type === 'Buffer' ?\n    Buffer.from(value) :\n    value;\n});\n\nconsole.log(copy);\n// Prints: <Buffer 01 02 03 04 05>\n
      " + }, + { + "textRaw": "`buf.toString([encoding[, start[, end]]])`", + "type": "method", + "name": "toString", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The character encoding to use. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The character encoding to use." + }, + { + "textRaw": "`start` {integer} The byte offset to start decoding at. **Default:** `0`.", + "name": "start", + "type": "integer", + "default": "`0`", + "desc": "The byte offset to start decoding at." + }, + { + "textRaw": "`end` {integer} The byte offset to stop decoding at (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "The byte offset to stop decoding at (not inclusive)." + } + ] + } + ], + "desc": "

      Decodes buf to a string according to the specified character encoding in\nencoding. start and end may be passed to decode only a subset of buf.

      \n

      If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8,\nthen each invalid byte is replaced with the replacement character U+FFFD.

      \n

      The maximum length of a string instance (in UTF-16 code units) is available\nas buffer.constants.MAX_STRING_LENGTH.

      \n
      const buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf1[i] = i + 97;\n}\n\nconsole.log(buf1.toString('utf8'));\n// Prints: abcdefghijklmnopqrstuvwxyz\nconsole.log(buf1.toString('utf8', 0, 5));\n// Prints: abcde\n\nconst buf2 = Buffer.from('tést');\n\nconsole.log(buf2.toString('hex'));\n// Prints: 74c3a97374\nconsole.log(buf2.toString('utf8', 0, 3));\n// Prints: té\nconsole.log(buf2.toString(undefined, 0, 3));\n// Prints: té\n
      " + }, + { + "textRaw": "`buf.values()`", + "type": "method", + "name": "values", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Creates and returns an iterator for buf values (bytes). This function is\ncalled automatically when a Buffer is used in a for..of statement.

      \n
      const buf = Buffer.from('buffer');\n\nfor (const value of buf.values()) {\n  console.log(value);\n}\n// Prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\n\nfor (const value of buf) {\n  console.log(value);\n}\n// Prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\n
      " + }, + { + "textRaw": "`buf.write(string[, offset[, length]][, encoding])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} Number of bytes written.", + "name": "return", + "type": "integer", + "desc": "Number of bytes written." + }, + "params": [ + { + "textRaw": "`string` {string} String to write to `buf`.", + "name": "string", + "type": "string", + "desc": "String to write to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write `string`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write `string`." + }, + { + "textRaw": "`length` {integer} Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). **Default:** `buf.length - offset`.", + "name": "length", + "type": "integer", + "default": "`buf.length - offset`", + "desc": "Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`)." + }, + { + "textRaw": "`encoding` {string} The character encoding of `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The character encoding of `string`." + } + ] + } + ], + "desc": "

      Writes string to buf at offset according to the character encoding in\nencoding. The length parameter is the number of bytes to write. If buf did\nnot contain enough space to fit the entire string, only part of string will be\nwritten. However, partially encoded characters will not be written.

      \n
      const buf = Buffer.alloc(256);\n\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\n\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n// Prints: 12 bytes: ½ + ¼ = ¾\n\nconst buffer = Buffer.alloc(10);\n\nconst length = buffer.write('abcd', 8);\n\nconsole.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);\n// Prints: 2 bytes : ab\n
      " + }, + { + "textRaw": "`buf.writeBigInt64BE(value[, offset])`", + "type": "method", + "name": "writeBigInt64BE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian.

      \n

      value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64BE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n
      " + }, + { + "textRaw": "`buf.writeBigInt64LE(value[, offset])`", + "type": "method", + "name": "writeBigInt64LE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian.

      \n

      value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64LE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n
      " + }, + { + "textRaw": "`buf.writeBigUInt64BE(value[, offset])`", + "type": "method", + "name": "writeBigUInt64BE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.writeBigUint64BE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64BE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de ca fa fe ca ce fa de>\n
      " + }, + { + "textRaw": "`buf.writeBigUInt64LE(value[, offset])`", + "type": "method", + "name": "writeBigUInt64LE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.writeBigUint64LE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64LE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de fa ce ca fe fa ca de>\n
      " + }, + { + "textRaw": "`buf.writeDoubleBE(value[, offset])`", + "type": "method", + "name": "writeDoubleBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a JavaScript number. Behavior is undefined when value is anything\nother than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>\n
      " + }, + { + "textRaw": "`buf.writeDoubleLE(value[, offset])`", + "type": "method", + "name": "writeDoubleLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a JavaScript number. Behavior is undefined when value is anything\nother than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleLE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>\n
      " + }, + { + "textRaw": "`buf.writeFloatBE(value[, offset])`", + "type": "method", + "name": "writeFloatBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. Behavior is\nundefined when value is anything other than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 4f 4a fe bb>\n\n
      " + }, + { + "textRaw": "`buf.writeFloatLE(value[, offset])`", + "type": "method", + "name": "writeFloatLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. Behavior is\nundefined when value is anything other than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer bb fe 4a 4f>\n
      " + }, + { + "textRaw": "`buf.writeInt8(value[, offset])`", + "type": "method", + "name": "writeInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset. value must be a valid\nsigned 8-bit integer. Behavior is undefined when value is anything other than\na signed 8-bit integer.

      \n

      value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\n\nconsole.log(buf);\n// Prints: <Buffer 02 fe>\n
      " + }, + { + "textRaw": "`buf.writeInt16BE(value[, offset])`", + "type": "method", + "name": "writeInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid signed 16-bit integer. Behavior is undefined when value is\nanything other than a signed 16-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16BE(0x0102, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02>\n
      " + }, + { + "textRaw": "`buf.writeInt16LE(value[, offset])`", + "type": "method", + "name": "writeInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid signed 16-bit integer. Behavior is undefined when value is\nanything other than a signed 16-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16LE(0x0304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 04 03>\n
      " + }, + { + "textRaw": "`buf.writeInt32BE(value[, offset])`", + "type": "method", + "name": "writeInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid signed 32-bit integer. Behavior is undefined when value is\nanything other than a signed 32-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32BE(0x01020304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04>\n
      " + }, + { + "textRaw": "`buf.writeInt32LE(value[, offset])`", + "type": "method", + "name": "writeInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid signed 32-bit integer. Behavior is undefined when value is\nanything other than a signed 32-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32LE(0x05060708, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05>\n
      " + }, + { + "textRaw": "`buf.writeIntBE(value, offset, byteLength)`", + "type": "method", + "name": "writeIntBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when\nvalue is anything other than a signed integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n\n
      " + }, + { + "textRaw": "`buf.writeIntLE(value, offset, byteLength)`", + "type": "method", + "name": "writeIntLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas little-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than a signed integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n
      " + }, + { + "textRaw": "`buf.writeUInt8(value[, offset])`", + "type": "method", + "name": "writeUInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint8()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset. value must be a\nvalid unsigned 8-bit integer. Behavior is undefined when value is anything\nother than an unsigned 8-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n// Prints: <Buffer 03 04 23 42>\n
      " + }, + { + "textRaw": "`buf.writeUInt16BE(value[, offset])`", + "type": "method", + "name": "writeUInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint16BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid unsigned 16-bit integer. Behavior is undefined when value\nis anything other than an unsigned 16-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer de ad be ef>\n
      " + }, + { + "textRaw": "`buf.writeUInt16LE(value[, offset])`", + "type": "method", + "name": "writeUInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint16LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid unsigned 16-bit integer. Behavior is undefined when value is\nanything other than an unsigned 16-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer ad de ef be>\n
      " + }, + { + "textRaw": "`buf.writeUInt32BE(value[, offset])`", + "type": "method", + "name": "writeUInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint32BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid unsigned 32-bit integer. Behavior is undefined when value\nis anything other than an unsigned 32-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer fe ed fa ce>\n
      " + }, + { + "textRaw": "`buf.writeUInt32LE(value[, offset])`", + "type": "method", + "name": "writeUInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint32LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid unsigned 32-bit integer. Behavior is undefined when value is\nanything other than an unsigned 32-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer ce fa ed fe>\n
      " + }, + { + "textRaw": "`buf.writeUIntBE(value, offset, byteLength)`", + "type": "method", + "name": "writeUIntBE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUintBE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas big-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than an unsigned integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n
      " + }, + { + "textRaw": "`buf.writeUIntLE(value, offset, byteLength)`", + "type": "method", + "name": "writeUIntLE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUintLE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas little-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than an unsigned integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`array` {integer[]} An array of bytes to copy from.", + "name": "array", + "type": "integer[]", + "desc": "An array of bytes to copy from." + } + ], + "desc": "

      See Buffer.from(array).

      " + }, + { + "params": [ + { + "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].", + "name": "arrayBuffer", + "type": "ArrayBuffer|SharedArrayBuffer", + "desc": "An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][]." + }, + { + "textRaw": "`byteOffset` {integer} Index of first byte to expose. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Index of first byte to expose." + }, + { + "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`.", + "name": "length", + "type": "integer", + "default": "`arrayBuffer.byteLength - byteOffset`", + "desc": "Number of bytes to expose." + } + ], + "desc": "

      See\nBuffer.from(arrayBuffer[, byteOffset[, length]]).

      " + }, + { + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from which to copy data.", + "name": "buffer", + "type": "Buffer|Uint8Array", + "desc": "An existing `Buffer` or [`Uint8Array`][] from which to copy data." + } + ], + "desc": "

      See Buffer.from(buffer).

      " + }, + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + } + ], + "desc": "

      See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the\nconstructor is equivalent to Buffer.alloc().

      " + }, + { + "params": [ + { + "textRaw": "`string` {string} String to encode.", + "name": "string", + "type": "string", + "desc": "String to encode." + }, + { + "textRaw": "`encoding` {string} The encoding of `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding of `string`." + } + ], + "desc": "

      See Buffer.from(string[, encoding]).

      " + } + ] + } + ], + "type": "module", + "displayName": "Buffer" + }, + { + "textRaw": "C++ Embedder API", + "name": "c++_embedder_api", + "introduced_in": "v12.19.0", + "desc": "

      Node.js provides a number of C++ APIs that can be used to execute JavaScript\nin a Node.js environment from other C++ software.

      \n

      The documentation for these APIs can be found in src/node.h in the Node.js\nsource tree. In addition to the APIs exposed by Node.js, some required concepts\nare provided by the V8 embedder API.

      \n

      Because using Node.js as an embedded library is different from writing code\nthat is executed by Node.js, breaking changes do not follow typical Node.js\ndeprecation policy and may occur on each semver-major release without prior\nwarning.

      \n

      Example embedding application

      \n

      The following sections will provide an overview over how to use these APIs\nto create an application from scratch that will perform the equivalent of\nnode -e <code>, i.e. that will take a piece of JavaScript and run it in\na Node.js-specific environment.

      \n

      The full code can be found in the Node.js source tree.

      ", + "modules": [ + { + "textRaw": "Setting up per-process state", + "name": "setting_up_per-process_state", + "desc": "

      Node.js requires some per-process state management in order to run:

      \n
        \n
      • Arguments parsing for Node.js CLI options,
      • \n
      • V8 per-process requirements, such as a v8::Platform instance.
      • \n
      \n

      The following example shows how these can be set up. Some class names are from\nthe node and v8 C++ namespaces, respectively.

      \n
      int main(int argc, char** argv) {\n  argv = uv_setup_args(argc, argv);\n  std::vector<std::string> args(argv, argv + argc);\n  std::vector<std::string> exec_args;\n  std::vector<std::string> errors;\n  // Parse Node.js CLI options, and print any errors that have occurred while\n  // trying to parse them.\n  int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);\n  for (const std::string& error : errors)\n    fprintf(stderr, \"%s: %s\\n\", args[0].c_str(), error.c_str());\n  if (exit_code != 0) {\n    return exit_code;\n  }\n\n  // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way\n  // to create a v8::Platform instance that Node.js can use when creating\n  // Worker threads. When no `MultiIsolatePlatform` instance is present,\n  // Worker threads are disabled.\n  std::unique_ptr<MultiIsolatePlatform> platform =\n      MultiIsolatePlatform::Create(4);\n  V8::InitializePlatform(platform.get());\n  V8::Initialize();\n\n  // See below for the contents of this function.\n  int ret = RunNodeInstance(platform.get(), args, exec_args);\n\n  V8::Dispose();\n  V8::ShutdownPlatform();\n  return ret;\n}\n
      ", + "type": "module", + "displayName": "Setting up per-process state" + }, + { + "textRaw": "Per-instance state", + "name": "per-instance_state", + "desc": "

      Node.js has a concept of a “Node.js instanceâ€, that is commonly being referred\nto as node::Environment. Each node::Environment is associated with:

      \n
        \n
      • Exactly one v8::Isolate, i.e. one JS Engine instance,
      • \n
      • Exactly one uv_loop_t, i.e. one event loop, and
      • \n
      • A number of v8::Contexts, but exactly one main v8::Context.
      • \n
      • One node::IsolateData instance that contains information that could be\nshared by multiple node::Environments that use the same v8::Isolate.\nCurrently, no testing if performed for this scenario.
      • \n
      \n

      In order to set up a v8::Isolate, an v8::ArrayBuffer::Allocator needs\nto be provided. One possible choice is the default Node.js allocator, which\ncan be created through node::ArrayBufferAllocator::Create(). Using the Node.js\nallocator allows minor performance optimizations when addons use the Node.js\nC++ Buffer API, and is required in order to track ArrayBuffer memory in\nprocess.memoryUsage().

      \n

      Additionally, each v8::Isolate that is used for a Node.js instance needs to\nbe registered and unregistered with the MultiIsolatePlatform instance, if one\nis being used, in order for the platform to know which event loop to use\nfor tasks scheduled by the v8::Isolate.

      \n

      The node::NewIsolate() helper function creates a v8::Isolate,\nsets it up with some Node.js-specific hooks (e.g. the Node.js error handler),\nand registers it with the platform automatically.

      \n
      int RunNodeInstance(MultiIsolatePlatform* platform,\n                    const std::vector<std::string>& args,\n                    const std::vector<std::string>& exec_args) {\n  int exit_code = 0;\n  // Set up a libuv event loop.\n  uv_loop_t loop;\n  int ret = uv_loop_init(&loop);\n  if (ret != 0) {\n    fprintf(stderr, \"%s: Failed to initialize loop: %s\\n\",\n            args[0].c_str(),\n            uv_err_name(ret));\n    return 1;\n  }\n\n  std::shared_ptr<ArrayBufferAllocator> allocator =\n      ArrayBufferAllocator::Create();\n\n  Isolate* isolate = NewIsolate(allocator, &loop, platform);\n  if (isolate == nullptr) {\n    fprintf(stderr, \"%s: Failed to initialize V8 Isolate\\n\", args[0].c_str());\n    return 1;\n  }\n\n  {\n    Locker locker(isolate);\n    Isolate::Scope isolate_scope(isolate);\n\n    // Create a node::IsolateData instance that will later be released using\n    // node::FreeIsolateData().\n    std::unique_ptr<IsolateData, decltype(&node::FreeIsolateData)> isolate_data(\n        node::CreateIsolateData(isolate, &loop, platform, allocator.get()),\n        node::FreeIsolateData);\n\n    // Set up a new v8::Context.\n    HandleScope handle_scope(isolate);\n    Local<Context> context = node::NewContext(isolate);\n    if (context.IsEmpty()) {\n      fprintf(stderr, \"%s: Failed to initialize V8 Context\\n\", args[0].c_str());\n      return 1;\n    }\n\n    // The v8::Context needs to be entered when node::CreateEnvironment() and\n    // node::LoadEnvironment() are being called.\n    Context::Scope context_scope(context);\n\n    // Create a node::Environment instance that will later be released using\n    // node::FreeEnvironment().\n    std::unique_ptr<Environment, decltype(&node::FreeEnvironment)> env(\n        node::CreateEnvironment(isolate_data.get(), context, args, exec_args),\n        node::FreeEnvironment);\n\n    // Set up the Node.js instance for execution, and run code inside of it.\n    // There is also a variant that takes a callback and provides it with\n    // the `require` and `process` objects, so that it can manually compile\n    // and run scripts as needed.\n    // The `require` function inside this script does *not* access the file\n    // system, and can only load built-in Node.js modules.\n    // `module.createRequire()` is being used to create one that is able to\n    // load files from the disk, and uses the standard CommonJS file loader\n    // instead of the internal-only `require` function.\n    MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(\n        env.get(),\n        \"const publicRequire =\"\n        \"  require('module').createRequire(process.cwd() + '/');\"\n        \"globalThis.require = publicRequire;\"\n        \"require('vm').runInThisContext(process.argv[1]);\");\n\n    if (loadenv_ret.IsEmpty())  // There has been a JS exception.\n      return 1;\n\n    {\n      // SealHandleScope protects against handle leaks from callbacks.\n      SealHandleScope seal(isolate);\n      bool more;\n      do {\n        uv_run(&loop, UV_RUN_DEFAULT);\n\n        // V8 tasks on background threads may end up scheduling new tasks in the\n        // foreground, which in turn can keep the event loop going. For example,\n        // WebAssembly.compile() may do so.\n        platform->DrainTasks(isolate);\n\n        // If there are new tasks, continue.\n        more = uv_loop_alive(&loop);\n        if (more) continue;\n\n        // node::EmitBeforeExit() is used to emit the 'beforeExit' event on\n        // the `process` object.\n        node::EmitBeforeExit(env.get());\n\n        // 'beforeExit' can also schedule new work that keeps the event loop\n        // running.\n        more = uv_loop_alive(&loop);\n      } while (more == true);\n    }\n\n    // node::EmitExit() returns the current exit code.\n    exit_code = node::EmitExit(env.get());\n\n    // node::Stop() can be used to explicitly stop the event loop and keep\n    // further JavaScript from running. It can be called from any thread,\n    // and will act like worker.terminate() if called from another thread.\n    node::Stop(env.get());\n  }\n\n  // Unregister the Isolate with the platform and add a listener that is called\n  // when the Platform is done cleaning up any state it had associated with\n  // the Isolate.\n  bool platform_finished = false;\n  platform->AddIsolateFinishedCallback(isolate, [](void* data) {\n    *static_cast<bool*>(data) = true;\n  }, &platform_finished);\n  platform->UnregisterIsolate(isolate);\n  isolate->Dispose();\n\n  // Wait until the platform has cleaned up all relevant resources.\n  while (!platform_finished)\n    uv_run(&loop, UV_RUN_ONCE);\n  int err = uv_loop_close(&loop);\n  assert(err == 0);\n\n  return exit_code;\n}\n
      ", + "type": "module", + "displayName": "Per-instance state" + } + ], + "type": "module", + "displayName": "C++ Embedder API" + }, + { + "textRaw": "Child process", + "name": "child_process", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/child_process.js

      \n

      The child_process module provides the ability to spawn child processes in\na manner that is similar, but not identical, to popen(3). This capability\nis primarily provided by the child_process.spawn() function:

      \n
      const { spawn } = require('child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n  console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n  console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n  console.log(`child process exited with code ${code}`);\n});\n
      \n

      By default, pipes for stdin, stdout, and stderr are established between\nthe parent Node.js process and the spawned child. These pipes have\nlimited (and platform-specific) capacity. If the child process writes to\nstdout in excess of that limit without the output being captured, the child\nprocess will block waiting for the pipe buffer to accept more data. This is\nidentical to the behavior of pipes in the shell. Use the { stdio: 'ignore' }\noption if the output will not be consumed.

      \n

      The command lookup will be performed using options.env.PATH environment\nvariable if passed in options object, otherwise process.env.PATH will be\nused. To account for the fact that Windows environment variables are\ncase-insensitive Node.js will lexicographically sort all env keys and choose\nthe first one case-insensitively matching PATH to perform command lookup.\nThis may lead to issues on Windows when passing objects to env option that\nhave multiple variants of PATH variable.

      \n

      The child_process.spawn() method spawns the child process asynchronously,\nwithout blocking the Node.js event loop. The child_process.spawnSync()\nfunction provides equivalent functionality in a synchronous manner that blocks\nthe event loop until the spawned process either exits or is terminated.

      \n

      For convenience, the child_process module provides a handful of synchronous\nand asynchronous alternatives to child_process.spawn() and\nchild_process.spawnSync(). Each of these alternatives are implemented on\ntop of child_process.spawn() or child_process.spawnSync().

      \n\n

      For certain use cases, such as automating shell scripts, the\nsynchronous counterparts may be more convenient. In many cases, however,\nthe synchronous methods can have significant impact on performance due to\nstalling the event loop while spawned processes complete.

      ", + "modules": [ + { + "textRaw": "Asynchronous process creation", + "name": "asynchronous_process_creation", + "desc": "

      The child_process.spawn(), child_process.fork(), child_process.exec(),\nand child_process.execFile() methods all follow the idiomatic asynchronous\nprogramming pattern typical of other Node.js APIs.

      \n

      Each of the methods returns a ChildProcess instance. These objects\nimplement the Node.js EventEmitter API, allowing the parent process to\nregister listener functions that are called when certain events occur during\nthe life cycle of the child process.

      \n

      The child_process.exec() and child_process.execFile() methods\nadditionally allow for an optional callback function to be specified that is\ninvoked when the child process terminates.

      ", + "modules": [ + { + "textRaw": "Spawning `.bat` and `.cmd` files on Windows", + "name": "spawning_`.bat`_and_`.cmd`_files_on_windows", + "desc": "

      The importance of the distinction between child_process.exec() and\nchild_process.execFile() can vary based on platform. On Unix-type\noperating systems (Unix, Linux, macOS) child_process.execFile() can be\nmore efficient because it does not spawn a shell by default. On Windows,\nhowever, .bat and .cmd files are not executable on their own without a\nterminal, and therefore cannot be launched using child_process.execFile().\nWhen running on Windows, .bat and .cmd files can be invoked using\nchild_process.spawn() with the shell option set, with\nchild_process.exec(), or by spawning cmd.exe and passing the .bat or\n.cmd file as an argument (which is what the shell option and\nchild_process.exec() do). In any case, if the script filename contains\nspaces it needs to be quoted.

      \n
      // On Windows Only...\nconst { spawn } = require('child_process');\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\nbat.stdout.on('data', (data) => {\n  console.log(data.toString());\n});\n\nbat.stderr.on('data', (data) => {\n  console.error(data.toString());\n});\n\nbat.on('exit', (code) => {\n  console.log(`Child exited with code ${code}`);\n});\n
      \n
      // OR...\nconst { exec, spawn } = require('child_process');\nexec('my.bat', (err, stdout, stderr) => {\n  if (err) {\n    console.error(err);\n    return;\n  }\n  console.log(stdout);\n});\n\n// Script with spaces in the filename:\nconst bat = spawn('\"my script.cmd\"', ['a', 'b'], { shell: true });\n// or:\nexec('\"my script.cmd\" a b', (err, stdout, stderr) => {\n  // ...\n});\n
      ", + "type": "module", + "displayName": "Spawning `.bat` and `.cmd` files on Windows" + } + ], + "methods": [ + { + "textRaw": "`child_process.exec(command[, options][, callback])`", + "type": "method", + "name": "exec", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`command` {string} The command to run, with space-separated arguments.", + "name": "command", + "type": "string", + "desc": "The command to run, with space-separated arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process. **Default:** `null`.", + "name": "cwd", + "type": "string", + "default": "`null`", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`shell` {string} Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.", + "name": "shell", + "type": "string", + "default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows", + "desc": "Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`timeout` {number} **Default:** `0`", + "name": "timeout", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`" + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + }, + { + "textRaw": "`callback` {Function} called with the output when process terminates.", + "name": "callback", + "type": "Function", + "desc": "called with the output when process terminates.", + "options": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {string|Buffer}", + "name": "stdout", + "type": "string|Buffer" + }, + { + "textRaw": "`stderr` {string|Buffer}", + "name": "stderr", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Spawns a shell then executes the command within that shell, buffering any\ngenerated output. The command string passed to the exec function is processed\ndirectly by the shell and special characters (vary based on\nshell)\nneed to be dealt with accordingly:

      \n
      exec('\"/path/to/test file/test.sh\" arg1 arg2');\n// Double quotes are used so that the space in the path is not interpreted as\n// a delimiter of multiple arguments.\n\nexec('echo \"The \\\\$HOME variable is $HOME\"');\n// The $HOME variable is escaped in the first instance, but not in the second.\n
      \n

      Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.

      \n

      If a callback function is provided, it is called with the arguments\n(error, stdout, stderr). On success, error will be null. On error,\nerror will be an instance of Error. The error.code property will be\nthe exit code of the process. By convention, any exit code other than 0\nindicates an error. error.signal will be the signal that terminated the\nprocess.

      \n

      The stdout and stderr arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding is 'buffer', or an unrecognized character\nencoding, Buffer objects will be passed to the callback instead.

      \n
      const { exec } = require('child_process');\nexec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {\n  if (error) {\n    console.error(`exec error: ${error}`);\n    return;\n  }\n  console.log(`stdout: ${stdout}`);\n  console.error(`stderr: ${stderr}`);\n});\n
      \n

      If timeout is greater than 0, the parent will send the signal\nidentified by the killSignal property (the default is 'SIGTERM') if the\nchild runs longer than timeout milliseconds.

      \n

      Unlike the exec(3) POSIX system call, child_process.exec() does not replace\nthe existing process and uses a shell to execute the command.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with stdout and stderr properties. The returned\nChildProcess instance is attached to the Promise as a child property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error object given in the\ncallback, but with two additional properties stdout and stderr.

      \n
      const util = require('util');\nconst exec = util.promisify(require('child_process').exec);\n\nasync function lsExample() {\n  const { stdout, stderr } = await exec('ls');\n  console.log('stdout:', stdout);\n  console.error('stderr:', stderr);\n}\nlsExample();\n
      " + }, + { + "textRaw": "`child_process.execFile(file[, args][, options][, callback])`", + "type": "method", + "name": "execFile", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [ + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`file` {string} The name or path of the executable file to run.", + "name": "file", + "type": "string", + "desc": "The name or path of the executable file to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`timeout` {number} **Default:** `0`", + "name": "timeout", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`" + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + } + ] + }, + { + "textRaw": "`callback` {Function} Called with the output when process terminates.", + "name": "callback", + "type": "Function", + "desc": "Called with the output when process terminates.", + "options": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {string|Buffer}", + "name": "stdout", + "type": "string|Buffer" + }, + { + "textRaw": "`stderr` {string|Buffer}", + "name": "stderr", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      The child_process.execFile() function is similar to child_process.exec()\nexcept that it does not spawn a shell by default. Rather, the specified\nexecutable file is spawned directly as a new process making it slightly more\nefficient than child_process.exec().

      \n

      The same options as child_process.exec() are supported. Since a shell is\nnot spawned, behaviors such as I/O redirection and file globbing are not\nsupported.

      \n
      const { execFile } = require('child_process');\nconst child = execFile('node', ['--version'], (error, stdout, stderr) => {\n  if (error) {\n    throw error;\n  }\n  console.log(stdout);\n});\n
      \n

      The stdout and stderr arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding is 'buffer', or an unrecognized character\nencoding, Buffer objects will be passed to the callback instead.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with stdout and stderr properties. The returned\nChildProcess instance is attached to the Promise as a child property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error object given in the\ncallback, but with two additional properties stdout and stderr.

      \n
      const util = require('util');\nconst execFile = util.promisify(require('child_process').execFile);\nasync function getVersion() {\n  const { stdout } = await execFile('node', ['--version']);\n  console.log(stdout);\n}\ngetVersion();\n
      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      " + }, + { + "textRaw": "`child_process.fork(modulePath[, args][, options])`", + "type": "method", + "name": "fork", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30162", + "description": "The `serialization` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10866", + "description": "The `stdio` option can now be a string." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7811", + "description": "The `stdio` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`modulePath` {string} The module to run in the child.", + "name": "modulePath", + "type": "string", + "desc": "The module to run in the child." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).", + "name": "detached", + "type": "boolean", + "desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][])." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`execPath` {string} Executable used to create the child process.", + "name": "execPath", + "type": "string", + "desc": "Executable used to create the child process." + }, + { + "textRaw": "`execArgv` {string[]} List of string arguments passed to the executable. **Default:** `process.execArgv`.", + "name": "execArgv", + "type": "string[]", + "default": "`process.execArgv`", + "desc": "List of string arguments passed to the executable." + }, + { + "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details. **Default:** `'json'`.", + "name": "serialization", + "type": "string", + "default": "`'json'`", + "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details." + }, + { + "textRaw": "`silent` {boolean} If `true`, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s [`stdio`][] for more details. **Default:** `false`.", + "name": "silent", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s [`stdio`][] for more details." + }, + { + "textRaw": "`stdio` {Array|string} See [`child_process.spawn()`][]'s [`stdio`][]. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`.", + "name": "stdio", + "type": "Array|string", + "desc": "See [`child_process.spawn()`][]'s [`stdio`][]. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + } + ] + } + ] + } + ], + "desc": "

      The child_process.fork() method is a special case of\nchild_process.spawn() used specifically to spawn new Node.js processes.\nLike child_process.spawn(), a ChildProcess object is returned. The\nreturned ChildProcess will have an additional communication channel\nbuilt-in that allows messages to be passed back and forth between the parent and\nchild. See subprocess.send() for details.

      \n

      Keep in mind that spawned Node.js child processes are\nindependent of the parent with exception of the IPC communication channel\nthat is established between the two. Each process has its own memory, with\ntheir own V8 instances. Because of the additional resource allocations\nrequired, spawning a large number of child Node.js processes is not\nrecommended.

      \n

      By default, child_process.fork() will spawn new Node.js instances using the\nprocess.execPath of the parent process. The execPath property in the\noptions object allows for an alternative execution path to be used.

      \n

      Node.js processes launched with a custom execPath will communicate with the\nparent process using the file descriptor (fd) identified using the\nenvironment variable NODE_CHANNEL_FD on the child process.

      \n

      Unlike the fork(2) POSIX system call, child_process.fork() does not clone the\ncurrent process.

      \n

      The shell option available in child_process.spawn() is not supported by\nchild_process.fork() and will be ignored if set.

      " + }, + { + "textRaw": "`child_process.spawn(command[, args][, options])`", + "type": "method", + "name": "spawn", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30162", + "description": "The `serialization` option is supported now." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7696", + "description": "The `argv0` option is supported now." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4598", + "description": "The `shell` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`command` {string} The command to run.", + "name": "command", + "type": "string", + "desc": "The command to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.", + "name": "argv0", + "type": "string", + "desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified." + }, + { + "textRaw": "`stdio` {Array|string} Child's stdio configuration (see [`options.stdio`][`stdio`]).", + "name": "stdio", + "type": "Array|string", + "desc": "Child's stdio configuration (see [`options.stdio`][`stdio`])." + }, + { + "textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).", + "name": "detached", + "type": "boolean", + "desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][])." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details. **Default:** `'json'`.", + "name": "serialization", + "type": "string", + "default": "`'json'`", + "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + } + ] + } + ], + "desc": "

      The child_process.spawn() method spawns a new process using the given\ncommand, with command line arguments in args. If omitted, args defaults\nto an empty array.

      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      \n

      A third argument may be used to specify additional options, with these defaults:

      \n
      const defaults = {\n  cwd: undefined,\n  env: process.env\n};\n
      \n

      Use cwd to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory.

      \n

      Use env to specify environment variables that will be visible to the new\nprocess, the default is process.env.

      \n

      undefined values in env will be ignored.

      \n

      Example of running ls -lh /usr, capturing stdout, stderr, and the\nexit code:

      \n
      const { spawn } = require('child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n  console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n  console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n  console.log(`child process exited with code ${code}`);\n});\n
      \n

      Example: A very elaborate way to run ps ax | grep ssh

      \n
      const { spawn } = require('child_process');\nconst ps = spawn('ps', ['ax']);\nconst grep = spawn('grep', ['ssh']);\n\nps.stdout.on('data', (data) => {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', (data) => {\n  console.error(`ps stderr: ${data}`);\n});\n\nps.on('close', (code) => {\n  if (code !== 0) {\n    console.log(`ps process exited with code ${code}`);\n  }\n  grep.stdin.end();\n});\n\ngrep.stdout.on('data', (data) => {\n  console.log(data.toString());\n});\n\ngrep.stderr.on('data', (data) => {\n  console.error(`grep stderr: ${data}`);\n});\n\ngrep.on('close', (code) => {\n  if (code !== 0) {\n    console.log(`grep process exited with code ${code}`);\n  }\n});\n
      \n

      Example of checking for failed spawn:

      \n
      const { spawn } = require('child_process');\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n  console.error('Failed to start subprocess.');\n});\n
      \n

      Certain platforms (macOS, Linux) will use the value of argv[0] for the process\ntitle while others (Windows, SunOS) will use command.

      \n

      Node.js currently overwrites argv[0] with process.execPath on startup, so\nprocess.argv[0] in a Node.js child process will not match the argv0\nparameter passed to spawn from the parent, retrieve it with the\nprocess.argv0 property instead.

      ", + "properties": [ + { + "textRaw": "`options.detached`", + "name": "detached", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "desc": "

      On Windows, setting options.detached to true makes it possible for the\nchild process to continue running after the parent exits. The child will have\nits own console window. Once enabled for a child process, it cannot be\ndisabled.

      \n

      On non-Windows platforms, if options.detached is set to true, the child\nprocess will be made the leader of a new process group and session. Child\nprocesses may continue running after the parent exits regardless of whether\nthey are detached or not. See setsid(2) for more information.

      \n

      By default, the parent will wait for the detached child to exit. To prevent the\nparent from waiting for a given subprocess to exit, use the\nsubprocess.unref() method. Doing so will cause the parent's event loop to not\ninclude the child in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent.

      \n

      When using the detached option to start a long-running process, the process\nwill not stay running in the background after the parent exits unless it is\nprovided with a stdio configuration that is not connected to the parent.\nIf the parent's stdio is inherited, the child will remain attached to the\ncontrolling terminal.

      \n

      Example of a long-running process, by detaching and also ignoring its parent\nstdio file descriptors, in order to ignore the parent's termination:

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\n
      \n

      Alternatively one can redirect the child process' output into files:

      \n
      const fs = require('fs');\nconst { spawn } = require('child_process');\nconst out = fs.openSync('./out.log', 'a');\nconst err = fs.openSync('./out.log', 'a');\n\nconst subprocess = spawn('prg', [], {\n  detached: true,\n  stdio: [ 'ignore', out, err ]\n});\n\nsubprocess.unref();\n
      " + }, + { + "textRaw": "`options.stdio`", + "name": "stdio", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [ + { + "version": "v3.3.1", + "pr-url": "https://github.com/nodejs/node/pull/2727", + "description": "The value `0` is now accepted as a file descriptor." + } + ] + }, + "desc": "

      The options.stdio option is used to configure the pipes that are established\nbetween the parent and child process. By default, the child's stdin, stdout,\nand stderr are redirected to corresponding subprocess.stdin,\nsubprocess.stdout, and subprocess.stderr streams on the\nChildProcess object. This is equivalent to setting the options.stdio\nequal to ['pipe', 'pipe', 'pipe'].

      \n

      For convenience, options.stdio may be one of the following strings:

      \n
        \n
      • 'pipe': equivalent to ['pipe', 'pipe', 'pipe'] (the default)
      • \n
      • 'ignore': equivalent to ['ignore', 'ignore', 'ignore']
      • \n
      • 'inherit': equivalent to ['inherit', 'inherit', 'inherit'] or [0, 1, 2]
      • \n
      \n

      Otherwise, the value of options.stdio is an array where each index corresponds\nto an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,\nand stderr, respectively. Additional fds can be specified to create additional\npipes between the parent and child. The value is one of the following:

      \n
        \n
      1. \n

        'pipe': Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as subprocess.stdio[fd]. Pipes\ncreated for fds 0, 1, and 2 are also available as subprocess.stdin,\nsubprocess.stdout and subprocess.stderr, respectively.

        \n
      2. \n
      3. \n

        'ipc': Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC\nstdio file descriptor. Setting this option enables the\nsubprocess.send() method. If the child is a Node.js process, the\npresence of an IPC channel will enable process.send() and\nprocess.disconnect() methods, as well as 'disconnect' and\n'message' events within the child.

        \n

        Accessing the IPC channel fd in any way other than process.send()\nor using the IPC channel with a child process that is not a Node.js instance\nis not supported.

        \n
      4. \n
      5. \n

        'ignore': Instructs Node.js to ignore the fd in the child. While Node.js\nwill always open fds 0, 1, and 2 for the processes it spawns, setting the fd\nto 'ignore' will cause Node.js to open /dev/null and attach it to the\nchild's fd.

        \n
      6. \n
      7. \n

        'inherit': Pass through the corresponding stdio stream to/from the\nparent process. In the first three positions, this is equivalent to\nprocess.stdin, process.stdout, and process.stderr, respectively. In\nany other position, equivalent to 'ignore'.

        \n
      8. \n
      9. \n

        <Stream> object: Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that\ncorresponds to the index in the stdio array. The stream must have an\nunderlying descriptor (file streams do not until the 'open' event has\noccurred).

        \n
      10. \n
      11. \n

        Positive integer: The integer value is interpreted as a file descriptor\nthat is currently open in the parent process. It is shared with the child\nprocess, similar to how <Stream> objects can be shared. Passing sockets\nis not supported on Windows.

        \n
      12. \n
      13. \n

        null, undefined: Use default value. For stdio fds 0, 1, and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.

        \n
      14. \n
      \n
      const { spawn } = require('child_process');\n\n// Child will use parent's stdios.\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr.\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs presenting a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });\n
      \n

      It is worth noting that when an IPC channel is established between the\nparent and child processes, and the child is a Node.js process, the child\nis launched with the IPC channel unreferenced (using unref()) until the\nchild registers an event handler for the 'disconnect' event\nor the 'message' event. This allows the child to exit\nnormally without the process being held open by the open IPC channel.

      \n

      On Unix-like operating systems, the child_process.spawn() method\nperforms memory operations synchronously before decoupling the event loop\nfrom the child. Applications with a large memory footprint may find frequent\nchild_process.spawn() calls to be a bottleneck. For more information,\nsee V8 issue 7381.

      \n

      See also: child_process.exec() and child_process.fork().

      " + } + ] + } + ], + "type": "module", + "displayName": "Asynchronous process creation" + }, + { + "textRaw": "Synchronous process creation", + "name": "synchronous_process_creation", + "desc": "

      The child_process.spawnSync(), child_process.execSync(), and\nchild_process.execFileSync() methods are synchronous and will block the\nNode.js event loop, pausing execution of any additional code until the spawned\nprocess exits.

      \n

      Blocking calls like these are mostly useful for simplifying general-purpose\nscripting tasks and for simplifying the loading/processing of application\nconfiguration at startup.

      ", + "methods": [ + { + "textRaw": "`child_process.execFileSync(file[, args][, options])`", + "type": "method", + "name": "execFileSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22409", + "description": "The `input` option can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10653", + "description": "The `input` option can now be a `Uint8Array`." + }, + { + "version": "v6.2.1, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6939", + "description": "The `encoding` option can now explicitly be set to `buffer`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|string} The stdout from the command.", + "name": "return", + "type": "Buffer|string", + "desc": "The stdout from the command." + }, + "params": [ + { + "textRaw": "`file` {string} The name or path of the executable file to run.", + "name": "file", + "type": "string", + "desc": "The name or path of the executable file to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`.", + "name": "input", + "type": "string|Buffer|TypedArray|DataView", + "desc": "The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`." + }, + { + "textRaw": "`stdio` {string|Array} Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.", + "name": "stdio", + "type": "string|Array", + "default": "`'pipe'`", + "desc": "Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", + "name": "timeout", + "type": "number", + "default": "`undefined`", + "desc": "In milliseconds the maximum amount of time the process is allowed to run." + }, + { + "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`", + "desc": "The signal value to be used when the spawned process will be killed." + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", + "name": "encoding", + "type": "string", + "default": "`'buffer'`", + "desc": "The encoding used for all stdio inputs and outputs." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + } + ] + } + ] + } + ], + "desc": "

      The child_process.execFileSync() method is generally identical to\nchild_process.execFile() with the exception that the method will not\nreturn until the child process has fully closed. When a timeout has been\nencountered and killSignal is sent, the method won't return until the process\nhas completely exited.

      \n

      If the child process intercepts and handles the SIGTERM signal and\ndoes not exit, the parent process will still wait until the child process has\nexited.

      \n

      If the process times out or has a non-zero exit code, this method will throw an\nError that will include the full result of the underlying\nchild_process.spawnSync().

      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      " + }, + { + "textRaw": "`child_process.execSync(command[, options])`", + "type": "method", + "name": "execSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22409", + "description": "The `input` option can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10653", + "description": "The `input` option can now be a `Uint8Array`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|string} The stdout from the command.", + "name": "return", + "type": "Buffer|string", + "desc": "The stdout from the command." + }, + "params": [ + { + "textRaw": "`command` {string} The command to run.", + "name": "command", + "type": "string", + "desc": "The command to run." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`.", + "name": "input", + "type": "string|Buffer|TypedArray|DataView", + "desc": "The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`." + }, + { + "textRaw": "`stdio` {string|Array} Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.", + "name": "stdio", + "type": "string|Array", + "default": "`'pipe'`", + "desc": "Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`shell` {string} Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.", + "name": "shell", + "type": "string", + "default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows", + "desc": "Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process. (See setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process. (See setgid(2))." + }, + { + "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", + "name": "timeout", + "type": "number", + "default": "`undefined`", + "desc": "In milliseconds the maximum amount of time the process is allowed to run." + }, + { + "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`", + "desc": "The signal value to be used when the spawned process will be killed." + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", + "name": "encoding", + "type": "string", + "default": "`'buffer'`", + "desc": "The encoding used for all stdio inputs and outputs." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + } + ] + } + ], + "desc": "

      The child_process.execSync() method is generally identical to\nchild_process.exec() with the exception that the method will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal is sent, the method won't return until the process has\ncompletely exited. If the child process intercepts and handles the SIGTERM\nsignal and doesn't exit, the parent process will wait until the child process\nhas exited.

      \n

      If the process times out or has a non-zero exit code, this method will throw.\nThe Error object will contain the entire result from\nchild_process.spawnSync().

      \n

      Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.

      " + }, + { + "textRaw": "`child_process.spawnSync(command[, args][, options])`", + "type": "method", + "name": "spawnSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22409", + "description": "The `input` option can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10653", + "description": "The `input` option can now be a `Uint8Array`." + }, + { + "version": "v6.2.1, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6939", + "description": "The `encoding` option can now explicitly be set to `buffer`." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4598", + "description": "The `shell` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`pid` {number} Pid of the child process.", + "name": "pid", + "type": "number", + "desc": "Pid of the child process." + }, + { + "textRaw": "`output` {Array} Array of results from stdio output.", + "name": "output", + "type": "Array", + "desc": "Array of results from stdio output." + }, + { + "textRaw": "`stdout` {Buffer|string} The contents of `output[1]`.", + "name": "stdout", + "type": "Buffer|string", + "desc": "The contents of `output[1]`." + }, + { + "textRaw": "`stderr` {Buffer|string} The contents of `output[2]`.", + "name": "stderr", + "type": "Buffer|string", + "desc": "The contents of `output[2]`." + }, + { + "textRaw": "`status` {number|null} The exit code of the subprocess, or `null` if the subprocess terminated due to a signal.", + "name": "status", + "type": "number|null", + "desc": "The exit code of the subprocess, or `null` if the subprocess terminated due to a signal." + }, + { + "textRaw": "`signal` {string|null} The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal.", + "name": "signal", + "type": "string|null", + "desc": "The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal." + }, + { + "textRaw": "`error` {Error} The error object if the child process failed or timed out.", + "name": "error", + "type": "Error", + "desc": "The error object if the child process failed or timed out." + } + ] + }, + "params": [ + { + "textRaw": "`command` {string} The command to run.", + "name": "command", + "type": "string", + "desc": "The command to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`.", + "name": "input", + "type": "string|Buffer|TypedArray|DataView", + "desc": "The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`." + }, + { + "textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.", + "name": "argv0", + "type": "string", + "desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified." + }, + { + "textRaw": "`stdio` {string|Array} Child's stdio configuration.", + "name": "stdio", + "type": "string|Array", + "desc": "Child's stdio configuration." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", + "name": "timeout", + "type": "number", + "default": "`undefined`", + "desc": "In milliseconds the maximum amount of time the process is allowed to run." + }, + { + "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`", + "desc": "The signal value to be used when the spawned process will be killed." + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", + "name": "encoding", + "type": "string", + "default": "`'buffer'`", + "desc": "The encoding used for all stdio inputs and outputs." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + } + ] + } + ], + "desc": "

      The child_process.spawnSync() method is generally identical to\nchild_process.spawn() with the exception that the function will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal is sent, the method won't return until the process has\ncompletely exited. If the process intercepts and handles the SIGTERM signal\nand doesn't exit, the parent process will wait until the child process has\nexited.

      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      " + } + ], + "type": "module", + "displayName": "Synchronous process creation" + }, + { + "textRaw": "`maxBuffer` and Unicode", + "name": "`maxbuffer`_and_unicode", + "desc": "

      The maxBuffer option specifies the largest number of bytes allowed on stdout\nor stderr. If this value is exceeded, then the child process is terminated.\nThis impacts output that includes multibyte character encodings such as UTF-8 or\nUTF-16. For instance, console.log('中文测试') will send 13 UTF-8 encoded bytes\nto stdout although there are only 4 characters.

      ", + "type": "module", + "displayName": "`maxBuffer` and Unicode" + }, + { + "textRaw": "Shell requirements", + "name": "shell_requirements", + "desc": "

      The shell should understand the -c switch. If the shell is 'cmd.exe', it\nshould understand the /d /s /c switches and command line parsing should be\ncompatible.

      ", + "type": "module", + "displayName": "Shell requirements" + }, + { + "textRaw": "Default Windows shell", + "name": "default_windows_shell", + "desc": "

      Although Microsoft specifies %COMSPEC% must contain the path to\n'cmd.exe' in the root environment, child processes are not always subject to\nthe same requirement. Thus, in child_process functions where a shell can be\nspawned, 'cmd.exe' is used as a fallback if process.env.ComSpec is\nunavailable.

      ", + "type": "module", + "displayName": "Default Windows shell" + }, + { + "textRaw": "Advanced serialization", + "name": "advanced_serialization", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Child processes support a serialization mechanism for IPC that is based on the\nserialization API of the v8 module, based on the\nHTML structured clone algorithm. This is generally more powerful and\nsupports more built-in JavaScript object types, such as BigInt, Map\nand Set, ArrayBuffer and TypedArray, Buffer, Error, RegExp etc.

      \n

      However, this format is not a full superset of JSON, and e.g. properties set on\nobjects of such built-in types will not be passed on through the serialization\nstep. Additionally, performance may not be equivalent to that of JSON, depending\non the structure of the passed data.\nTherefore, this feature requires opting in by setting the\nserialization option to 'advanced' when calling child_process.spawn()\nor child_process.fork().

      ", + "type": "module", + "displayName": "Advanced serialization" + } + ], + "classes": [ + { + "textRaw": "Class: `ChildProcess`", + "type": "class", + "name": "ChildProcess", + "meta": { + "added": [ + "v2.2.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of the ChildProcess represent spawned child processes.

      \n

      Instances of ChildProcess are not intended to be created directly. Rather,\nuse the child_process.spawn(), child_process.exec(),\nchild_process.execFile(), or child_process.fork() methods to create\ninstances of ChildProcess.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {number} The exit code if the child exited on its own.", + "name": "code", + "type": "number", + "desc": "The exit code if the child exited on its own." + }, + { + "textRaw": "`signal` {string} The signal by which the child process was terminated.", + "name": "signal", + "type": "string", + "desc": "The signal by which the child process was terminated." + } + ], + "desc": "

      The 'close' event is emitted when the stdio streams of a child process have\nbeen closed. This is distinct from the 'exit' event, since multiple\nprocesses might share the same stdio streams.

      \n
      const { spawn } = require('child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n  console.log(`stdout: ${data}`);\n});\n\nls.on('close', (code) => {\n  console.log(`child process close all stdio with code ${code}`);\n});\n\nls.on('exit', (code) => {\n  console.log(`child process exited with code ${code}`);\n});\n
      " + }, + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'disconnect' event is emitted after calling the\nsubprocess.disconnect() method in parent process or\nprocess.disconnect() in child process. After disconnecting it is no longer\npossible to send or receive messages, and the subprocess.connected\nproperty is false.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "params": [ + { + "textRaw": "`err` {Error} The error.", + "name": "err", + "type": "Error", + "desc": "The error." + } + ], + "desc": "

      The 'error' event is emitted whenever:

      \n
        \n
      1. The process could not be spawned, or
      2. \n
      3. The process could not be killed, or
      4. \n
      5. Sending a message to the child process failed.
      6. \n
      \n

      The 'exit' event may or may not fire after an error has occurred. When\nlistening to both the 'exit' and 'error' events, guard\nagainst accidentally invoking handler functions multiple times.

      \n

      See also subprocess.kill() and subprocess.send().

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {number} The exit code if the child exited on its own.", + "name": "code", + "type": "number", + "desc": "The exit code if the child exited on its own." + }, + { + "textRaw": "`signal` {string} The signal by which the child process was terminated.", + "name": "signal", + "type": "string", + "desc": "The signal by which the child process was terminated." + } + ], + "desc": "

      The 'exit' event is emitted after the child process ends. If the process\nexited, code is the final exit code of the process, otherwise null. If the\nprocess terminated due to receipt of a signal, signal is the string name of\nthe signal, otherwise null. One of the two will always be non-null.

      \n

      When the 'exit' event is triggered, child process stdio streams might still be\nopen.

      \n

      Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js\nprocesses will not terminate immediately due to receipt of those signals.\nRather, Node.js will perform a sequence of cleanup actions and then will\nre-raise the handled signal.

      \n

      See waitpid(2).

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`message` {Object} A parsed JSON object or primitive value.", + "name": "message", + "type": "Object", + "desc": "A parsed JSON object or primitive value." + }, + { + "textRaw": "`sendHandle` {Handle} A [`net.Socket`][] or [`net.Server`][] object, or undefined.", + "name": "sendHandle", + "type": "Handle", + "desc": "A [`net.Socket`][] or [`net.Server`][] object, or undefined." + } + ], + "desc": "

      The 'message' event is triggered when a child process uses\nprocess.send() to send messages.

      \n

      The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.

      \n

      If the serialization option was set to 'advanced' used when spawning the\nchild process, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for more details.

      " + } + ], + "properties": [ + { + "textRaw": "`channel` {Object} A pipe representing the IPC channel to the child process.", + "type": "Object", + "name": "channel", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [] + }, + "desc": "

      The subprocess.channel property is a reference to the child's IPC channel. If\nno IPC channel currently exists, this property is undefined.

      ", + "shortDesc": "A pipe representing the IPC channel to the child process." + }, + { + "textRaw": "`connected` {boolean} Set to `false` after `subprocess.disconnect()` is called.", + "type": "boolean", + "name": "connected", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "desc": "

      The subprocess.connected property indicates whether it is still possible to\nsend and receive messages from a child process. When subprocess.connected is\nfalse, it is no longer possible to send or receive messages.

      ", + "shortDesc": "Set to `false` after `subprocess.disconnect()` is called." + }, + { + "textRaw": "`exitCode` {integer}", + "type": "integer", + "name": "exitCode", + "desc": "

      The subprocess.exitCode property indicates the exit code of the child process.\nIf the child process is still running, the field will be null.

      " + }, + { + "textRaw": "`killed` {boolean} Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process.", + "type": "boolean", + "name": "killed", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "desc": "

      The subprocess.killed property indicates whether the child process\nsuccessfully received a signal from subprocess.kill(). The killed property\ndoes not indicate that the child process has been terminated.

      ", + "shortDesc": "Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process." + }, + { + "textRaw": "`pid` {integer}", + "type": "integer", + "name": "pid", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      Returns the process identifier (PID) of the child process.

      \n
      const { spawn } = require('child_process');\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n
      " + }, + { + "textRaw": "`signalCode` {integer}", + "type": "integer", + "name": "signalCode", + "desc": "

      The subprocess.signalCode property indicates the signal number received by\nthe child process if any, else null.

      " + }, + { + "textRaw": "`spawnargs` {Array}", + "type": "Array", + "name": "spawnargs", + "desc": "

      The subprocess.spawnargs property represents the full list of command line\narguments the child process was launched with.

      " + }, + { + "textRaw": "`spawnfile` {string}", + "type": "string", + "name": "spawnfile", + "desc": "

      The subprocess.spawnfile property indicates the executable file name of\nthe child process that is launched.

      \n

      For child_process.fork(), its value will be equal to\nprocess.execPath.\nFor child_process.spawn(), its value will be the name of\nthe executable file.\nFor child_process.exec(), its value will be the name of the shell\nin which the child process is launched.

      " + }, + { + "textRaw": "`stderr` {stream.Readable}", + "type": "stream.Readable", + "name": "stderr", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      A Readable Stream that represents the child process's stderr.

      \n

      If the child was spawned with stdio[2] set to anything other than 'pipe',\nthen this will be null.

      \n

      subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will\nrefer to the same value.

      " + }, + { + "textRaw": "`stdin` {stream.Writable}", + "type": "stream.Writable", + "name": "stdin", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      A Writable Stream that represents the child process's stdin.

      \n

      If a child process waits to read all of its input, the child will not continue\nuntil this stream has been closed via end().

      \n

      If the child was spawned with stdio[0] set to anything other than 'pipe',\nthen this will be null.

      \n

      subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will\nrefer to the same value.

      " + }, + { + "textRaw": "`stdio` {Array}", + "type": "Array", + "name": "stdio", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "desc": "

      A sparse array of pipes to the child process, corresponding with positions in\nthe stdio option passed to child_process.spawn() that have been set\nto the value 'pipe'. subprocess.stdio[0], subprocess.stdio[1], and\nsubprocess.stdio[2] are also available as subprocess.stdin,\nsubprocess.stdout, and subprocess.stderr, respectively.

      \n

      In the following example, only the child's fd 1 (stdout) is configured as a\npipe, so only the parent's subprocess.stdio[1] is a stream, all other values\nin the array are null.

      \n
      const assert = require('assert');\nconst fs = require('fs');\nconst child_process = require('child_process');\n\nconst subprocess = child_process.spawn('ls', {\n  stdio: [\n    0, // Use parent's stdin for child.\n    'pipe', // Pipe child's stdout to parent.\n    fs.openSync('err.out', 'w') // Direct child's stderr to a file.\n  ]\n});\n\nassert.strictEqual(subprocess.stdio[0], null);\nassert.strictEqual(subprocess.stdio[0], subprocess.stdin);\n\nassert(subprocess.stdout);\nassert.strictEqual(subprocess.stdio[1], subprocess.stdout);\n\nassert.strictEqual(subprocess.stdio[2], null);\nassert.strictEqual(subprocess.stdio[2], subprocess.stderr);\n
      " + }, + { + "textRaw": "`stdout` {stream.Readable}", + "type": "stream.Readable", + "name": "stdout", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      A Readable Stream that represents the child process's stdout.

      \n

      If the child was spawned with stdio[1] set to anything other than 'pipe',\nthen this will be null.

      \n

      subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will\nrefer to the same value.

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn('ls');\n\nsubprocess.stdout.on('data', (data) => {\n  console.log(`Received chunk ${data}`);\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`subprocess.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Closes the IPC channel between parent and child, allowing the child to exit\ngracefully once there are no other connections keeping it alive. After calling\nthis method the subprocess.connected and process.connected properties in\nboth the parent and child (respectively) will be set to false, and it will be\nno longer possible to pass messages between the processes.

      \n

      The 'disconnect' event will be emitted when there are no messages in the\nprocess of being received. This will most often be triggered immediately after\ncalling subprocess.disconnect().

      \n

      When the child process is a Node.js instance (e.g. spawned using\nchild_process.fork()), the process.disconnect() method can be invoked\nwithin the child process to close the IPC channel as well.

      " + }, + { + "textRaw": "`subprocess.kill([signal])`", + "type": "method", + "name": "kill", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`signal` {number|string}", + "name": "signal", + "type": "number|string" + } + ] + } + ], + "desc": "

      The subprocess.kill() method sends a signal to the child process. If no\nargument is given, the process will be sent the 'SIGTERM' signal. See\nsignal(7) for a list of available signals. This function returns true if\nkill(2) succeeds, and false otherwise.

      \n
      const { spawn } = require('child_process');\nconst grep = spawn('grep', ['ssh']);\n\ngrep.on('close', (code, signal) => {\n  console.log(\n    `child process terminated due to receipt of signal ${signal}`);\n});\n\n// Send SIGHUP to process.\ngrep.kill('SIGHUP');\n
      \n

      The ChildProcess object may emit an 'error' event if the signal\ncannot be delivered. Sending a signal to a child process that has already exited\nis not an error but may have unforeseen consequences. Specifically, if the\nprocess identifier (PID) has been reassigned to another process, the signal will\nbe delivered to that process instead which can have unexpected results.

      \n

      While the function is called kill, the signal delivered to the child process\nmay not actually terminate the process.

      \n

      See kill(2) for reference.

      \n

      On Linux, child processes of child processes will not be terminated\nwhen attempting to kill their parent. This is likely to happen when running a\nnew process in a shell or with the use of the shell option of ChildProcess:

      \n
      'use strict';\nconst { spawn } = require('child_process');\n\nconst subprocess = spawn(\n  'sh',\n  [\n    '-c',\n    `node -e \"setInterval(() => {\n      console.log(process.pid, 'is alive')\n    }, 500);\"`\n  ], {\n    stdio: ['inherit', 'inherit', 'inherit']\n  }\n);\n\nsetTimeout(() => {\n  subprocess.kill(); // Does not terminate the Node.js process in the shell.\n}, 2000);\n
      " + }, + { + "textRaw": "`subprocess.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calling subprocess.ref() after making a call to subprocess.unref() will\nrestore the removed reference count for the child process, forcing the parent\nto wait for the child to exit before exiting itself.

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\nsubprocess.ref();\n
      " + }, + { + "textRaw": "`subprocess.send(message[, sendHandle[, options]][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [ + { + "version": "v5.8.0", + "pr-url": "https://github.com/nodejs/node/pull/5283", + "description": "The `options` parameter, and the `keepOpen` option in particular, is supported now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3516", + "description": "This method returns a boolean for flow control now." + }, + { + "version": "v4.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2620", + "description": "The `callback` parameter is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle}", + "name": "sendHandle", + "type": "Handle" + }, + { + "textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "name": "options", + "type": "Object", + "desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "options": [ + { + "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", + "name": "keepOpen", + "type": "boolean", + "default": "`false`", + "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      When an IPC channel has been established between the parent and child (\ni.e. when using child_process.fork()), the subprocess.send() method can\nbe used to send messages to the child process. When the child process is a\nNode.js instance, these messages can be received via the 'message' event.

      \n

      The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.

      \n

      For example, in the parent script:

      \n
      const cp = require('child_process');\nconst n = cp.fork(`${__dirname}/sub.js`);\n\nn.on('message', (m) => {\n  console.log('PARENT got message:', m);\n});\n\n// Causes the child to print: CHILD got message: { hello: 'world' }\nn.send({ hello: 'world' });\n
      \n

      And then the child script, 'sub.js' might look like this:

      \n
      process.on('message', (m) => {\n  console.log('CHILD got message:', m);\n});\n\n// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }\nprocess.send({ foo: 'bar', baz: NaN });\n
      \n

      Child Node.js processes will have a process.send() method of their own\nthat allows the child to send messages back to the parent.

      \n

      There is a special case when sending a {cmd: 'NODE_foo'} message. Messages\ncontaining a NODE_ prefix in the cmd property are reserved for use within\nNode.js core and will not be emitted in the child's 'message'\nevent. Rather, such messages are emitted using the\n'internalMessage' event and are consumed internally by Node.js.\nApplications should avoid using such messages or listening for\n'internalMessage' events as it is subject to change without notice.

      \n

      The optional sendHandle argument that may be passed to subprocess.send() is\nfor passing a TCP server or socket object to the child process. The child will\nreceive the object as the second argument passed to the callback function\nregistered on the 'message' event. Any data that is received\nand buffered in the socket will not be sent to the child.

      \n

      The optional callback is a function that is invoked after the message is\nsent but before the child may have received it. The function is called with a\nsingle argument: null on success, or an Error object on failure.

      \n

      If no callback function is provided and the message cannot be sent, an\n'error' event will be emitted by the ChildProcess object. This can\nhappen, for instance, when the child process has already exited.

      \n

      subprocess.send() will return false if the channel has closed or when the\nbacklog of unsent messages exceeds a threshold that makes it unwise to send\nmore. Otherwise, the method returns true. The callback function can be\nused to implement flow control.

      \n

      Example: sending a server object

      \n

      The sendHandle argument can be used, for instance, to pass the handle of\na TCP server object to the child process as illustrated in the example below:

      \n
      const subprocess = require('child_process').fork('subprocess.js');\n\n// Open up the server object and send the handle.\nconst server = require('net').createServer();\nserver.on('connection', (socket) => {\n  socket.end('handled by parent');\n});\nserver.listen(1337, () => {\n  subprocess.send('server', server);\n});\n
      \n

      The child would then receive the server object as:

      \n
      process.on('message', (m, server) => {\n  if (m === 'server') {\n    server.on('connection', (socket) => {\n      socket.end('handled by child');\n    });\n  }\n});\n
      \n

      Once the server is now shared between the parent and child, some connections\ncan be handled by the parent and some by the child.

      \n

      While the example above uses a server created using the net module, dgram\nmodule servers use exactly the same workflow with the exceptions of listening on\na 'message' event instead of 'connection' and using server.bind() instead\nof server.listen(). This is, however, currently only supported on Unix\nplatforms.

      \n

      Example: sending a socket object

      \n

      Similarly, the sendHandler argument can be used to pass the handle of a\nsocket to the child process. The example below spawns two children that each\nhandle connections with \"normal\" or \"special\" priority:

      \n
      const { fork } = require('child_process');\nconst normal = fork('subprocess.js', ['normal']);\nconst special = fork('subprocess.js', ['special']);\n\n// Open up the server and send sockets to child. Use pauseOnConnect to prevent\n// the sockets from being read before they are sent to the child process.\nconst server = require('net').createServer({ pauseOnConnect: true });\nserver.on('connection', (socket) => {\n\n  // If this is special priority...\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // This is normal priority.\n  normal.send('socket', socket);\n});\nserver.listen(1337);\n
      \n

      The subprocess.js would receive the socket handle as the second argument\npassed to the event callback function:

      \n
      process.on('message', (m, socket) => {\n  if (m === 'socket') {\n    if (socket) {\n      // Check that the client socket exists.\n      // It is possible for the socket to be closed between the time it is\n      // sent and the time it is received in the child process.\n      socket.end(`Request handled with ${process.argv[2]} priority`);\n    }\n  }\n});\n
      \n

      Do not use .maxConnections on a socket that has been passed to a subprocess.\nThe parent cannot track when the socket is destroyed.

      \n

      Any 'message' handlers in the subprocess should verify that socket exists,\nas the connection may have been closed during the time it takes to send the\nconnection to the child.

      " + }, + { + "textRaw": "`subprocess.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      By default, the parent will wait for the detached child to exit. To prevent the\nparent from waiting for a given subprocess to exit, use the\nsubprocess.unref() method. Doing so will cause the parent's event loop to not\ninclude the child in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent.

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\n
      " + } + ] + } + ], + "type": "module", + "displayName": "Child process" + }, + { + "textRaw": "Cluster", + "name": "cluster", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/cluster.js

      \n

      A single instance of Node.js runs in a single thread. To take advantage of\nmulti-core systems, the user will sometimes want to launch a cluster of Node.js\nprocesses to handle the load.

      \n

      The cluster module allows easy creation of child processes that all share\nserver ports.

      \n
      const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', (worker, code, signal) => {\n    console.log(`worker ${worker.process.pid} died`);\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case it is an HTTP server\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end('hello world\\n');\n  }).listen(8000);\n\n  console.log(`Worker ${process.pid} started`);\n}\n
      \n

      Running Node.js will now share port 8000 between the workers:

      \n
      $ node server.js\nMaster 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n
      \n

      On Windows, it is not yet possible to set up a named pipe server in a worker.

      ", + "miscs": [ + { + "textRaw": "How it works", + "name": "How it works", + "type": "misc", + "desc": "

      The worker processes are spawned using the child_process.fork() method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.

      \n

      The cluster module supports two methods of distributing incoming\nconnections.

      \n

      The first one (and the default one on all platforms except Windows),\nis the round-robin approach, where the master process listens on a\nport, accepts new connections and distributes them across the workers\nin a round-robin fashion, with some built-in smarts to avoid\noverloading a worker process.

      \n

      The second approach is where the master process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.

      \n

      The second approach should, in theory, give the best performance.\nIn practice however, distribution tends to be very unbalanced due\nto operating system scheduler vagaries. Loads have been observed\nwhere over 70% of all connections ended up in just two processes,\nout of a total of eight.

      \n

      Because server.listen() hands off most of the work to the master\nprocess, there are three cases where the behavior between a normal\nNode.js process and a cluster worker differs:

      \n
        \n
      1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
      2. \n
      3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess.
      4. \n
      5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame \"random\" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. To listen\non a unique port, generate a port number based on the cluster worker ID.
      6. \n
      \n

      Node.js does not provide routing logic. It is, therefore important to design an\napplication such that it does not rely too heavily on in-memory data objects for\nthings like sessions and login.

      \n

      Because workers are all separate processes, they can be killed or\nre-spawned depending on a program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. If no workers are alive, existing connections\nwill be dropped and new connections will be refused. Node.js does not\nautomatically manage the number of workers, however. It is the application's\nresponsibility to manage the worker pool based on its own needs.

      \n

      Although a primary use case for the cluster module is networking, it can\nalso be used for other use cases requiring worker processes.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `Worker`", + "type": "class", + "name": "Worker", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "\n

      A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.

      ", + "events": [ + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      Similar to the cluster.on('disconnect') event, but specific to this worker.

      \n
      cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n
      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.7.3" + ], + "changes": [] + }, + "params": [], + "desc": "

      This event is the same as the one provided by child_process.fork().

      \n

      Within a worker, process.on('error') may also be used.

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {number} The exit code, if it exited normally.", + "name": "code", + "type": "number", + "desc": "The exit code, if it exited normally." + }, + { + "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.", + "name": "signal", + "type": "string", + "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed." + } + ], + "desc": "

      Similar to the cluster.on('exit') event, but specific to this worker.

      \n
      const worker = cluster.fork();\nworker.on('exit', (code, signal) => {\n  if (signal) {\n    console.log(`worker was killed by signal: ${signal}`);\n  } else if (code !== 0) {\n    console.log(`worker exited with error code: ${code}`);\n  } else {\n    console.log('worker success!');\n  }\n});\n
      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`address` {Object}", + "name": "address", + "type": "Object" + } + ], + "desc": "

      Similar to the cluster.on('listening') event, but specific to this worker.

      \n
      cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n
      \n

      It is not emitted in the worker.

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`handle` {undefined|Object}", + "name": "handle", + "type": "undefined|Object" + } + ], + "desc": "

      Similar to the 'message' event of cluster, but specific to this worker.

      \n

      Within a worker, process.on('message') may also be used.

      \n

      See process event: 'message'.

      \n

      Here is an example using the message system. It keeps a count in the master\nprocess of the number of HTTP requests received by the workers:

      \n
      const cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  let numReqs = 0;\n  setInterval(() => {\n    console.log(`numReqs = ${numReqs}`);\n  }, 1000);\n\n  // Count requests\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  const numCPUs = require('os').cpus().length;\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  for (const id in cluster.workers) {\n    cluster.workers[id].on('message', messageHandler);\n  }\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server((req, res) => {\n    res.writeHead(200);\n    res.end('hello world\\n');\n\n    // Notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n
      " + }, + { + "textRaw": "Event: `'online'`", + "type": "event", + "name": "online", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Similar to the cluster.on('online') event, but specific to this worker.

      \n
      cluster.fork().on('online', () => {\n  // Worker is online\n});\n
      \n

      It is not emitted in the worker.

      " + } + ], + "methods": [ + { + "textRaw": "`worker.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v7.3.0", + "pr-url": "https://github.com/nodejs/node/pull/10019", + "description": "This method now returns a reference to `worker`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {cluster.Worker} A reference to `worker`.", + "name": "return", + "type": "cluster.Worker", + "desc": "A reference to `worker`." + }, + "params": [] + } + ], + "desc": "

      In a worker, this function will close all servers, wait for the 'close' event\non those servers, and then disconnect the IPC channel.

      \n

      In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.

      \n

      Causes .exitedAfterDisconnect to be set.

      \n

      After a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker will close allowing it\nto die gracefully.

      \n

      The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.

      \n

      In a worker, process.disconnect exists, but it is not this function;\nit is disconnect().

      \n

      Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe 'disconnect' event has not been emitted after some time.

      \n
      if (cluster.isMaster) {\n  const worker = cluster.fork();\n  let timeout;\n\n  worker.on('listening', (address) => {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(() => {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', () => {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  const net = require('net');\n  const server = net.createServer((socket) => {\n    // Connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', (msg) => {\n    if (msg === 'shutdown') {\n      // Initiate graceful close of any connections to server\n    }\n  });\n}\n
      " + }, + { + "textRaw": "`worker.isConnected()`", + "type": "method", + "name": "isConnected", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This function returns true if the worker is connected to its master via its\nIPC channel, false otherwise. A worker is connected to its master after it\nhas been created. It is disconnected after the 'disconnect' event is emitted.

      " + }, + { + "textRaw": "`worker.isDead()`", + "type": "method", + "name": "isDead", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.

      \n
      const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('fork', (worker) => {\n    console.log('worker is dead:', worker.isDead());\n  });\n\n  cluster.on('exit', (worker, code, signal) => {\n    console.log('worker is dead:', worker.isDead());\n  });\n} else {\n  // Workers can share any TCP connection. In this case, it is an HTTP server.\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end(`Current process\\n ${process.pid}`);\n    process.kill(process.pid);\n  }).listen(8000);\n}\n
      " + }, + { + "textRaw": "`worker.kill([signal])`", + "type": "method", + "name": "kill", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`signal` {string} Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`", + "name": "signal", + "type": "string", + "desc": "Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`" + } + ] + } + ], + "desc": "

      This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.

      \n

      Because kill() attempts to gracefully disconnect the worker process, it is\nsusceptible to waiting indefinitely for the disconnect to complete. For example,\nif the worker enters an infinite loop, a graceful disconnect will never occur.\nIf the graceful disconnect behavior is not needed, use worker.process.kill().

      \n

      Causes .exitedAfterDisconnect to be set.

      \n

      This method is aliased as worker.destroy() for backward compatibility.

      \n

      In a worker, process.kill() exists, but it is not this function;\nit is kill().

      " + }, + { + "textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [ + { + "version": "v4.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2620", + "description": "The `callback` parameter is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle}", + "name": "sendHandle", + "type": "Handle" + }, + { + "textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "name": "options", + "type": "Object", + "desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "options": [ + { + "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", + "name": "keepOpen", + "type": "boolean", + "default": "`false`", + "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Send a message to a worker or master, optionally with a handle.

      \n

      In the master this sends a message to a specific worker. It is identical to\nChildProcess.send().

      \n

      In a worker this sends a message to the master. It is identical to\nprocess.send().

      \n

      This example will echo back all messages from the master:

      \n
      if (cluster.isMaster) {\n  const worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', (msg) => {\n    process.send(msg);\n  });\n}\n
      " + } + ], + "properties": [ + { + "textRaw": "`exitedAfterDisconnect` {boolean}", + "type": "boolean", + "name": "exitedAfterDisconnect", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      This property is true if the worker exited due to .kill() or\n.disconnect(). If the worker exited any other way, it is false. If the\nworker has not exited, it is undefined.

      \n

      The boolean worker.exitedAfterDisconnect allows distinguishing between\nvoluntary and accidental exit, the master may choose not to respawn a worker\nbased on this value.

      \n
      cluster.on('exit', (worker, code, signal) => {\n  if (worker.exitedAfterDisconnect === true) {\n    console.log('Oh, it was just voluntary – no need to worry');\n  }\n});\n\n// kill worker\nworker.kill();\n
      " + }, + { + "textRaw": "`id` {number}", + "type": "number", + "name": "id", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      Each new worker is given its own unique id, this id is stored in the\nid.

      \n

      While a worker is alive, this is the key that indexes it in\ncluster.workers.

      " + }, + { + "textRaw": "`process` {ChildProcess}", + "type": "ChildProcess", + "name": "process", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "

      All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.

      \n

      See: Child Process module.

      \n

      Workers will call process.exit(0) if the 'disconnect' event occurs\non process and .exitedAfterDisconnect is not true. This protects against\naccidental disconnection.

      " + } + ] + } + ], + "events": [ + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.9" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + } + ], + "desc": "

      Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).

      \n

      There may be a delay between the 'disconnect' and 'exit' events. These\nevents can be used to detect if the process is stuck in a cleanup or if there\nare long-living connections.

      \n
      cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n
      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.7.9" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + }, + { + "textRaw": "`code` {number} The exit code, if it exited normally.", + "name": "code", + "type": "number", + "desc": "The exit code, if it exited normally." + }, + { + "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.", + "name": "signal", + "type": "string", + "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed." + } + ], + "desc": "

      When any of the workers die the cluster module will emit the 'exit' event.

      \n

      This can be used to restart the worker by calling .fork() again.

      \n
      cluster.on('exit', (worker, code, signal) => {\n  console.log('worker %d died (%s). restarting...',\n              worker.process.pid, signal || code);\n  cluster.fork();\n});\n
      \n

      See child_process event: 'exit'.

      " + }, + { + "textRaw": "Event: `'fork'`", + "type": "event", + "name": "fork", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + } + ], + "desc": "

      When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create a custom timeout.

      \n
      const timeouts = [];\nfunction errorMsg() {\n  console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});\n
      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + }, + { + "textRaw": "`address` {Object}", + "name": "address", + "type": "Object" + } + ], + "desc": "

      After calling listen() from a worker, when the 'listening' event is emitted\non the server a 'listening' event will also be emitted on cluster in the\nmaster.

      \n

      The event handler is executed with two arguments, the worker contains the\nworker object and the address object contains the following connection\nproperties: address, port and addressType. This is very useful if the\nworker is listening on more than one address.

      \n
      cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});\n
      \n

      The addressType is one of:

      \n
        \n
      • 4 (TCPv4)
      • \n
      • 6 (TCPv6)
      • \n
      • -1 (Unix domain socket)
      • \n
      • 'udp4' or 'udp6' (UDP v4 or v6)
      • \n
      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v2.5.0" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5361", + "description": "The `worker` parameter is passed now; see below for details." + } + ] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + }, + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`handle` {undefined|Object}", + "name": "handle", + "type": "undefined|Object" + } + ], + "desc": "

      Emitted when the cluster master receives a message from any worker.

      \n

      See child_process event: 'message'.

      " + }, + { + "textRaw": "Event: `'online'`", + "type": "event", + "name": "online", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + } + ], + "desc": "

      After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.

      \n
      cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});\n
      " + }, + { + "textRaw": "Event: `'setup'`", + "type": "event", + "name": "setup", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`settings` {Object}", + "name": "settings", + "type": "Object" + } + ], + "desc": "

      Emitted every time .setupMaster() is called.

      \n

      The settings object is the cluster.settings object at the time\n.setupMaster() was called and is advisory only, since multiple calls to\n.setupMaster() can be made in a single tick.

      \n

      If accuracy is important, use cluster.settings.

      " + } + ], + "methods": [ + { + "textRaw": "`cluster.disconnect([callback])`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} Called when all workers are disconnected and handles are closed.", + "name": "callback", + "type": "Function", + "desc": "Called when all workers are disconnected and handles are closed." + } + ] + } + ], + "desc": "

      Calls .disconnect() on each worker in cluster.workers.

      \n

      When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.

      \n

      The method takes an optional callback argument which will be called when\nfinished.

      \n

      This can only be called from the master process.

      " + }, + { + "textRaw": "`cluster.fork([env])`", + "type": "method", + "name": "fork", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {cluster.Worker}", + "name": "return", + "type": "cluster.Worker" + }, + "params": [ + { + "textRaw": "`env` {Object} Key/value pairs to add to worker process environment.", + "name": "env", + "type": "Object", + "desc": "Key/value pairs to add to worker process environment." + } + ] + } + ], + "desc": "

      Spawn a new worker process.

      \n

      This can only be called from the master process.

      " + }, + { + "textRaw": "`cluster.setupMaster([settings])`", + "type": "method", + "name": "setupMaster", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [ + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7838", + "description": "The `stdio` option is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`settings` {Object} See [`cluster.settings`][].", + "name": "settings", + "type": "Object", + "desc": "See [`cluster.settings`][]." + } + ] + } + ], + "desc": "

      setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.

      \n

      Any settings changes only affect future calls to .fork() and have no\neffect on workers that are already running.

      \n

      The only attribute of a worker that cannot be set via .setupMaster() is\nthe env passed to .fork().

      \n

      The defaults above apply to the first call only; the defaults for later\ncalls are the current values at the time of cluster.setupMaster() is called.

      \n
      const cluster = require('cluster');\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true\n});\ncluster.fork(); // https worker\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'http']\n});\ncluster.fork(); // http worker\n
      \n

      This can only be called from the master process.

      " + } + ], + "properties": [ + { + "textRaw": "`isMaster` {boolean}", + "type": "boolean", + "name": "isMaster", + "meta": { + "added": [ + "v0.8.1" + ], + "changes": [] + }, + "desc": "

      True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.

      " + }, + { + "textRaw": "`isWorker` {boolean}", + "type": "boolean", + "name": "isWorker", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "desc": "

      True if the process is not a master (it is the negation of cluster.isMaster).

      " + }, + { + "textRaw": "`cluster.schedulingPolicy`", + "name": "schedulingPolicy", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "desc": "

      The scheduling policy, either cluster.SCHED_RR for round-robin or\ncluster.SCHED_NONE to leave it to the operating system. This is a\nglobal setting and effectively frozen once either the first worker is spawned,\nor .setupMaster() is called, whichever comes first.

      \n

      SCHED_RR is the default on all operating systems except Windows.\nWindows will change to SCHED_RR once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.

      \n

      cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are 'rr' and 'none'.

      " + }, + { + "textRaw": "`settings` {Object}", + "type": "Object", + "name": "settings", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30162", + "description": "The `serialization` option is supported now." + }, + { + "version": "v9.5.0", + "pr-url": "https://github.com/nodejs/node/pull/18399", + "description": "The `cwd` option is supported now." + }, + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/17412", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/14140", + "description": "The `inspectPort` option is supported now." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7838", + "description": "The `stdio` option is supported now." + } + ] + }, + "options": [ + { + "textRaw": "`execArgv` {string[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`.", + "name": "execArgv", + "type": "string[]", + "default": "`process.execArgv`", + "desc": "List of string arguments passed to the Node.js executable." + }, + { + "textRaw": "`exec` {string} File path to worker file. **Default:** `process.argv[1]`.", + "name": "exec", + "type": "string", + "default": "`process.argv[1]`", + "desc": "File path to worker file." + }, + { + "textRaw": "`args` {string[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`.", + "name": "args", + "type": "string[]", + "default": "`process.argv.slice(2)`", + "desc": "String arguments passed to worker." + }, + { + "textRaw": "`cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process).", + "name": "cwd", + "type": "string", + "default": "`undefined` (inherits from parent process)", + "desc": "Current working directory of the worker process." + }, + { + "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization for `child_process`][] for more details. **Default:** `false`.", + "name": "serialization", + "type": "string", + "default": "`false`", + "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization for `child_process`][] for more details." + }, + { + "textRaw": "`silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false`.", + "name": "silent", + "type": "boolean", + "default": "`false`", + "desc": "Whether or not to send output to parent's stdio." + }, + { + "textRaw": "`stdio` {Array} Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`.", + "name": "stdio", + "type": "Array", + "desc": "Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2).)", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process. (See setuid(2).)" + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2).)", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process. (See setgid(2).)" + }, + { + "textRaw": "`inspectPort` {number|Function} Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`.", + "name": "inspectPort", + "type": "number|Function", + "desc": "Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the forked processes console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the forked processes console window that would normally be created on Windows systems." + } + ], + "desc": "

      After calling .setupMaster() (or .fork()) this settings object will\ncontain the settings, including the default values.

      \n

      This object is not intended to be changed or set manually.

      " + }, + { + "textRaw": "`worker` {Object}", + "type": "Object", + "name": "worker", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "

      A reference to the current worker object. Not available in the master process.

      \n
      const cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n
      " + }, + { + "textRaw": "`workers` {Object}", + "type": "Object", + "name": "workers", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "

      A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.

      \n

      A worker is removed from cluster.workers after the worker has disconnected\nand exited. The order between these two events cannot be determined in\nadvance. However, it is guaranteed that the removal from the cluster.workers\nlist happens before last 'disconnect' or 'exit' event is emitted.

      \n
      // Go through all workers\nfunction eachWorker(callback) {\n  for (const id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\n});\n
      \n

      Using the worker's unique id is the easiest way to locate the worker.

      \n
      socket.on('data', (id) => {\n  const worker = cluster.workers[id];\n});\n
      " + } + ], + "type": "module", + "displayName": "Cluster" + }, + { + "textRaw": "Console", + "name": "console", + "introduced_in": "v0.10.13", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/console.js

      \n

      The console module provides a simple debugging console that is similar to the\nJavaScript console mechanism provided by web browsers.

      \n

      The module exports two specific components:

      \n
        \n
      • A Console class with methods such as console.log(), console.error() and\nconsole.warn() that can be used to write to any Node.js stream.
      • \n
      • A global console instance configured to write to process.stdout and\nprocess.stderr. The global console can be used without calling\nrequire('console').
      • \n
      \n

      Warning: The global console object's methods are neither consistently\nsynchronous like the browser APIs they resemble, nor are they consistently\nasynchronous like all other Node.js streams. See the note on process I/O for\nmore information.

      \n

      Example using the global console:

      \n
      console.log('hello world');\n// Prints: hello world, to stdout\nconsole.log('hello %s', 'world');\n// Prints: hello world, to stdout\nconsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to stderr\n\nconst name = 'Will Robinson';\nconsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to stderr\n
      \n

      Example using the Console class:

      \n
      const out = getStreamSomehow();\nconst err = getStreamSomehow();\nconst myConsole = new console.Console(out, err);\n\nmyConsole.log('hello world');\n// Prints: hello world, to out\nmyConsole.log('hello %s', 'world');\n// Prints: hello world, to out\nmyConsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to err\n\nconst name = 'Will Robinson';\nmyConsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to err\n
      ", + "classes": [ + { + "textRaw": "Class: `Console`", + "type": "class", + "name": "Console", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9744", + "description": "Errors that occur while writing to the underlying streams will now be ignored by default." + } + ] + }, + "desc": "

      The Console class can be used to create a simple logger with configurable\noutput streams and can be accessed using either require('console').Console\nor console.Console (or their destructured counterparts):

      \n
      const { Console } = require('console');\n
      \n
      const { Console } = console;\n
      ", + "methods": [ + { + "textRaw": "`console.assert(value[, ...message])`", + "type": "method", + "name": "assert", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17706", + "description": "The implementation is now spec compliant and does not throw anymore." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any} The value tested for being truthy.", + "name": "value", + "type": "any", + "desc": "The value tested for being truthy." + }, + { + "textRaw": "`...message` {any} All arguments besides `value` are used as error message.", + "name": "...message", + "type": "any", + "desc": "All arguments besides `value` are used as error message." + } + ] + } + ], + "desc": "

      console.assert() writes a message if value is falsy or omitted. It only\nwrites a message and does not otherwise affect execution. The output always\nstarts with \"Assertion failed\". If provided, message is formatted using\nutil.format().

      \n

      If value is truthy, nothing happens.

      \n
      console.assert(true, 'does nothing');\n\nconsole.assert(false, 'Whoops %s work', 'didn\\'t');\n// Assertion failed: Whoops didn't work\n\nconsole.assert();\n// Assertion failed\n
      " + }, + { + "textRaw": "`console.clear()`", + "type": "method", + "name": "clear", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      When stdout is a TTY, calling console.clear() will attempt to clear the\nTTY. When stdout is not a TTY, this method does nothing.

      \n

      The specific operation of console.clear() can vary across operating systems\nand terminal types. For most Linux operating systems, console.clear()\noperates similarly to the clear shell command. On Windows, console.clear()\nwill clear only the output in the current terminal viewport for the Node.js\nbinary.

      " + }, + { + "textRaw": "`console.count([label])`", + "type": "method", + "name": "count", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} The display label for the counter. **Default:** `'default'`.", + "name": "label", + "type": "string", + "default": "`'default'`", + "desc": "The display label for the counter." + } + ] + } + ], + "desc": "

      Maintains an internal counter specific to label and outputs to stdout the\nnumber of times console.count() has been called with the given label.

      \n\n
      > console.count()\ndefault: 1\nundefined\n> console.count('default')\ndefault: 2\nundefined\n> console.count('abc')\nabc: 1\nundefined\n> console.count('xyz')\nxyz: 1\nundefined\n> console.count('abc')\nabc: 2\nundefined\n> console.count()\ndefault: 3\nundefined\n>\n
      " + }, + { + "textRaw": "`console.countReset([label])`", + "type": "method", + "name": "countReset", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} The display label for the counter. **Default:** `'default'`.", + "name": "label", + "type": "string", + "default": "`'default'`", + "desc": "The display label for the counter." + } + ] + } + ], + "desc": "

      Resets the internal counter specific to label.

      \n\n
      > console.count('abc');\nabc: 1\nundefined\n> console.countReset('abc');\nundefined\n> console.count('abc');\nabc: 1\nundefined\n>\n
      " + }, + { + "textRaw": "`console.debug(data[, ...args])`", + "type": "method", + "name": "debug", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [ + { + "version": "v8.10.0", + "pr-url": "https://github.com/nodejs/node/pull/17033", + "description": "`console.debug` is now an alias for `console.log`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      The console.debug() function is an alias for console.log().

      " + }, + { + "textRaw": "`console.dir(obj[, options])`", + "type": "method", + "name": "dir", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`obj` {any}", + "name": "obj", + "type": "any" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`showHidden` {boolean} If `true` then the object's non-enumerable and symbol properties will be shown too. **Default:** `false`.", + "name": "showHidden", + "type": "boolean", + "default": "`false`", + "desc": "If `true` then the object's non-enumerable and symbol properties will be shown too." + }, + { + "textRaw": "`depth` {number} Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`. **Default:** `2`.", + "name": "depth", + "type": "number", + "default": "`2`", + "desc": "Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`." + }, + { + "textRaw": "`colors` {boolean} If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]. **Default:** `false`.", + "name": "colors", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]." + } + ] + } + ] + } + ], + "desc": "

      Uses util.inspect() on obj and prints the resulting string to stdout.\nThis function bypasses any custom inspect() function defined on obj.

      " + }, + { + "textRaw": "`console.dirxml(...data)`", + "type": "method", + "name": "dirxml", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [ + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/17152", + "description": "`console.dirxml` now calls `console.log` for its arguments." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...data` {any}", + "name": "...data", + "type": "any" + } + ] + } + ], + "desc": "

      This method calls console.log() passing it the arguments received.\nThis method does not produce any XML formatting.

      " + }, + { + "textRaw": "`console.error([data][, ...args])`", + "type": "method", + "name": "error", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Prints to stderr with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()).

      \n
      const code = 5;\nconsole.error('error #%d', code);\n// Prints: error #5, to stderr\nconsole.error('error', code);\n// Prints: error 5, to stderr\n
      \n

      If formatting elements (e.g. %d) are not found in the first string then\nutil.inspect() is called on each argument and the resulting string\nvalues are concatenated. See util.format() for more information.

      " + }, + { + "textRaw": "`console.group([...label])`", + "type": "method", + "name": "group", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...label` {any}", + "name": "...label", + "type": "any" + } + ] + } + ], + "desc": "

      Increases indentation of subsequent lines by spaces for groupIndentation\nlength.

      \n

      If one or more labels are provided, those are printed first without the\nadditional indentation.

      " + }, + { + "textRaw": "`console.groupCollapsed()`", + "type": "method", + "name": "groupCollapsed", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      An alias for console.group().

      " + }, + { + "textRaw": "`console.groupEnd()`", + "type": "method", + "name": "groupEnd", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Decreases indentation of subsequent lines by spaces for groupIndentation\nlength.

      " + }, + { + "textRaw": "`console.info([data][, ...args])`", + "type": "method", + "name": "info", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      The console.info() function is an alias for console.log().

      " + }, + { + "textRaw": "`console.log([data][, ...args])`", + "type": "method", + "name": "log", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Prints to stdout with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()).

      \n
      const count = 5;\nconsole.log('count: %d', count);\n// Prints: count: 5, to stdout\nconsole.log('count:', count);\n// Prints: count: 5, to stdout\n
      \n

      See util.format() for more information.

      " + }, + { + "textRaw": "`console.table(tabularData[, properties])`", + "type": "method", + "name": "table", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`tabularData` {any}", + "name": "tabularData", + "type": "any" + }, + { + "textRaw": "`properties` {string[]} Alternate properties for constructing the table.", + "name": "properties", + "type": "string[]", + "desc": "Alternate properties for constructing the table." + } + ] + } + ], + "desc": "

      Try to construct a table with the columns of the properties of tabularData\n(or use properties) and rows of tabularData and log it. Falls back to just\nlogging the argument if it can’t be parsed as tabular.

      \n
      // These can't be parsed as tabular data\nconsole.table(Symbol());\n// Symbol()\n\nconsole.table(undefined);\n// undefined\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);\n// ┌─────────┬─────┬─────â”\n// │ (index) │  a  │  b  │\n// ├─────────┼─────┼─────┤\n// │    0    │  1  │ 'Y' │\n// │    1    │ 'Z' │  2  │\n// └─────────┴─────┴─────┘\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);\n// ┌─────────┬─────â”\n// │ (index) │  a  │\n// ├─────────┼─────┤\n// │    0    │  1  │\n// │    1    │ 'Z' │\n// └─────────┴─────┘\n
      " + }, + { + "textRaw": "`console.time([label])`", + "type": "method", + "name": "time", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} **Default:** `'default'`", + "name": "label", + "type": "string", + "default": "`'default'`" + } + ] + } + ], + "desc": "

      Starts a timer that can be used to compute the duration of an operation. Timers\nare identified by a unique label. Use the same label when calling\nconsole.timeEnd() to stop the timer and output the elapsed time in\nmilliseconds to stdout. Timer durations are accurate to the sub-millisecond.

      " + }, + { + "textRaw": "`console.timeEnd([label])`", + "type": "method", + "name": "timeEnd", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5901", + "description": "This method no longer supports multiple calls that don’t map to individual `console.time()` calls; see below for details." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} **Default:** `'default'`", + "name": "label", + "type": "string", + "default": "`'default'`" + } + ] + } + ], + "desc": "

      Stops a timer that was previously started by calling console.time() and\nprints the result to stdout:

      \n
      console.time('100-elements');\nfor (let i = 0; i < 100; i++) {}\nconsole.timeEnd('100-elements');\n// prints 100-elements: 225.438ms\n
      " + }, + { + "textRaw": "`console.timeLog([label][, ...data])`", + "type": "method", + "name": "timeLog", + "meta": { + "added": [ + "v10.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} **Default:** `'default'`", + "name": "label", + "type": "string", + "default": "`'default'`" + }, + { + "textRaw": "`...data` {any}", + "name": "...data", + "type": "any" + } + ] + } + ], + "desc": "

      For a timer that was previously started by calling console.time(), prints\nthe elapsed time and other data arguments to stdout:

      \n
      console.time('process');\nconst value = expensiveProcess1(); // Returns 42\nconsole.timeLog('process', value);\n// Prints \"process: 365.227ms 42\".\ndoExpensiveProcess2(value);\nconsole.timeEnd('process');\n
      " + }, + { + "textRaw": "`console.trace([message][, ...args])`", + "type": "method", + "name": "trace", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {any}", + "name": "message", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Prints to stderr the string 'Trace: ', followed by the util.format()\nformatted message and stack trace to the current position in the code.

      \n
      console.trace('Show me');\n// Prints: (stack trace will vary based on where trace is called)\n//  Trace: Show me\n//    at repl:2:9\n//    at REPLServer.defaultEval (repl.js:248:27)\n//    at bound (domain.js:287:14)\n//    at REPLServer.runBound [as eval] (domain.js:300:12)\n//    at REPLServer.<anonymous> (repl.js:412:12)\n//    at emitOne (events.js:82:20)\n//    at REPLServer.emit (events.js:169:7)\n//    at REPLServer.Interface._onLine (readline.js:210:10)\n//    at REPLServer.Interface._line (readline.js:549:8)\n//    at REPLServer.Interface._ttyWrite (readline.js:826:14)\n
      " + }, + { + "textRaw": "`console.warn([data][, ...args])`", + "type": "method", + "name": "warn", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      The console.warn() function is an alias for console.error().

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`stdout` {stream.Writable}", + "name": "stdout", + "type": "stream.Writable" + }, + { + "textRaw": "`stderr` {stream.Writable}", + "name": "stderr", + "type": "stream.Writable" + }, + { + "textRaw": "`ignoreErrors` {boolean} Ignore errors when writing to the underlying streams. **Default:** `true`.", + "name": "ignoreErrors", + "type": "boolean", + "default": "`true`", + "desc": "Ignore errors when writing to the underlying streams." + }, + { + "textRaw": "`colorMode` {boolean|string} Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well. **Default:** `'auto'`.", + "name": "colorMode", + "type": "boolean|string", + "default": "`'auto'`", + "desc": "Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well." + }, + { + "textRaw": "`inspectOptions` {Object} Specifies options that are passed along to [`util.inspect()`][].", + "name": "inspectOptions", + "type": "Object", + "desc": "Specifies options that are passed along to [`util.inspect()`][]." + }, + { + "textRaw": "`groupIndentation` {number} Set group indentation. **Default:** `2`.", + "name": "groupIndentation", + "type": "number", + "default": "`2`", + "desc": "Set group indentation." + } + ] + } + ], + "desc": "

      Creates a new Console with one or two writable stream instances. stdout is a\nwritable stream to print log or info output. stderr is used for warning or\nerror output. If stderr is not provided, stdout is used for stderr.

      \n
      const output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n
      \n

      The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:

      \n
      new Console({ stdout: process.stdout, stderr: process.stderr });\n
      " + }, + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`stdout` {stream.Writable}", + "name": "stdout", + "type": "stream.Writable" + }, + { + "textRaw": "`stderr` {stream.Writable}", + "name": "stderr", + "type": "stream.Writable" + }, + { + "textRaw": "`ignoreErrors` {boolean} Ignore errors when writing to the underlying streams. **Default:** `true`.", + "name": "ignoreErrors", + "type": "boolean", + "default": "`true`", + "desc": "Ignore errors when writing to the underlying streams." + }, + { + "textRaw": "`colorMode` {boolean|string} Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well. **Default:** `'auto'`.", + "name": "colorMode", + "type": "boolean|string", + "default": "`'auto'`", + "desc": "Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well." + }, + { + "textRaw": "`inspectOptions` {Object} Specifies options that are passed along to [`util.inspect()`][].", + "name": "inspectOptions", + "type": "Object", + "desc": "Specifies options that are passed along to [`util.inspect()`][]." + }, + { + "textRaw": "`groupIndentation` {number} Set group indentation. **Default:** `2`.", + "name": "groupIndentation", + "type": "number", + "default": "`2`", + "desc": "Set group indentation." + } + ] + } + ], + "desc": "

      Creates a new Console with one or two writable stream instances. stdout is a\nwritable stream to print log or info output. stderr is used for warning or\nerror output. If stderr is not provided, stdout is used for stderr.

      \n
      const output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n
      \n

      The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:

      \n
      new Console({ stdout: process.stdout, stderr: process.stderr });\n
      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Inspector only methods", + "name": "inspector_only_methods", + "desc": "

      The following methods are exposed by the V8 engine in the general API but do\nnot display anything unless used in conjunction with the inspector\n(--inspect flag).

      ", + "methods": [ + { + "textRaw": "`console.profile([label])`", + "type": "method", + "name": "profile", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string}", + "name": "label", + "type": "string" + } + ] + } + ], + "desc": "

      This method does not display anything unless used in the inspector. The\nconsole.profile() method starts a JavaScript CPU profile with an optional\nlabel until console.profileEnd() is called. The profile is then added to\nthe Profile panel of the inspector.

      \n
      console.profile('MyLabel');\n// Some code\nconsole.profileEnd('MyLabel');\n// Adds the profile 'MyLabel' to the Profiles panel of the inspector.\n
      " + }, + { + "textRaw": "`console.profileEnd([label])`", + "type": "method", + "name": "profileEnd", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string}", + "name": "label", + "type": "string" + } + ] + } + ], + "desc": "

      This method does not display anything unless used in the inspector. Stops the\ncurrent JavaScript CPU profiling session if one has been started and prints\nthe report to the Profiles panel of the inspector. See\nconsole.profile() for an example.

      \n

      If this method is called without a label, the most recently started profile is\nstopped.

      " + }, + { + "textRaw": "`console.timeStamp([label])`", + "type": "method", + "name": "timeStamp", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string}", + "name": "label", + "type": "string" + } + ] + } + ], + "desc": "

      This method does not display anything unless used in the inspector. The\nconsole.timeStamp() method adds an event with the label 'label' to the\nTimeline panel of the inspector.

      " + } + ], + "type": "module", + "displayName": "Inspector only methods" + } + ], + "type": "module", + "displayName": "Console" + }, + { + "textRaw": "Crypto", + "name": "crypto", + "introduced_in": "v0.3.6", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/crypto.js

      \n

      The crypto module provides cryptographic functionality that includes a set of\nwrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

      \n

      Use require('crypto') to access this module.

      \n
      const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n                   .update('I love cupcakes')\n                   .digest('hex');\nconsole.log(hash);\n// Prints:\n//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
      ", + "modules": [ + { + "textRaw": "Determining if crypto support is unavailable", + "name": "determining_if_crypto_support_is_unavailable", + "desc": "

      It is possible for Node.js to be built without including support for the\ncrypto module. In such cases, calling require('crypto') will result in an\nerror being thrown.

      \n
      let crypto;\ntry {\n  crypto = require('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\n
      ", + "type": "module", + "displayName": "Determining if crypto support is unavailable" + }, + { + "textRaw": "`crypto` module methods and properties", + "name": "`crypto`_module_methods_and_properties", + "properties": [ + { + "textRaw": "`constants` Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][].", + "type": "Object", + "name": "return", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][]." + }, + { + "textRaw": "`crypto.DEFAULT_ENCODING`", + "name": "DEFAULT_ENCODING", + "meta": { + "added": [ + "v0.9.3" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes methods\ndefault to Buffer objects.

      \n

      The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.

      \n

      New applications should expect the default to be 'buffer'.

      \n

      This property is deprecated.

      " + }, + { + "textRaw": "`crypto.fips`", + "name": "fips", + "meta": { + "added": [ + "v6.0.0" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Property for checking and controlling whether a FIPS compliant crypto provider\nis currently in use. Setting to true requires a FIPS build of Node.js.

      \n

      This property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.

      " + } + ], + "methods": [ + { + "textRaw": "`crypto.createCipher(algorithm, password[, options])`", + "type": "method", + "name": "createCipher", + "meta": { + "added": [ + "v0.1.94" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + }, + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20235", + "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`crypto.createCipheriv()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher}", + "name": "return", + "type": "Cipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`password` {string | Buffer | TypedArray | DataView}", + "name": "password", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Cipher object that uses the given algorithm and\npassword.

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.

      \n

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

      \n

      The password is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'latin1' encoded string, a Buffer, a\nTypedArray, or a DataView.

      \n

      The implementation of crypto.createCipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

      \n

      In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createCipheriv()\nto create the Cipher object. Users should not use ciphers with counter mode\n(e.g. CTR, GCM, or CCM) in crypto.createCipher(). A warning is emitted when\nthey are used in order to avoid the risk of IV reuse that causes\nvulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting\nAdversaries for details.

      " + }, + { + "textRaw": "`crypto.createCipheriv(algorithm, key, iv[, options])`", + "type": "method", + "name": "createCipheriv", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `key` argument can now be a `KeyObject`." + }, + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/24081", + "description": "The cipher `chacha20-poly1305` is now supported." + }, + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + }, + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20235", + "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18644", + "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher}", + "name": "return", + "type": "Cipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView | KeyObject}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView | KeyObject" + }, + { + "textRaw": "`iv` {string | Buffer | TypedArray | DataView | null}", + "name": "iv", + "type": "string | Buffer | TypedArray | DataView | null" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.

      \n

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

      \n

      The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.

      \n

      Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a\ngiven IV will be.

      " + }, + { + "textRaw": "`crypto.createDecipher(algorithm, password[, options])`", + "type": "method", + "name": "createDecipher", + "meta": { + "added": [ + "v0.1.94" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`crypto.createDecipheriv()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher}", + "name": "return", + "type": "Decipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`password` {string | Buffer | TypedArray | DataView}", + "name": "password", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Decipher object that uses the given algorithm and\npassword (key).

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.

      \n

      The implementation of crypto.createDecipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

      \n

      In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createDecipheriv()\nto create the Decipher object.

      " + }, + { + "textRaw": "`crypto.createDecipheriv(algorithm, key, iv[, options])`", + "type": "method", + "name": "createDecipheriv", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `key` argument can now be a `KeyObject`." + }, + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/24081", + "description": "The cipher `chacha20-poly1305` is now supported." + }, + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + }, + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20039", + "description": "The `authTagLength` option can now be used to restrict accepted GCM authentication tag lengths." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18644", + "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher}", + "name": "return", + "type": "Decipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView | KeyObject}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView | KeyObject" + }, + { + "textRaw": "`iv` {string | Buffer | TypedArray | DataView | null}", + "name": "iv", + "type": "string | Buffer | TypedArray | DataView | null" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to restrict accepted authentication tags\nto those with the specified length.

      \n

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

      \n

      The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.

      \n

      Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a given\nIV will be.

      " + }, + { + "textRaw": "`crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])`", + "type": "method", + "name": "createDiffieHellman", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `prime` argument can be any `TypedArray` or `DataView` now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11983", + "description": "The `prime` argument can be a `Uint8Array` now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default for the encoding parameters changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellman}", + "name": "return", + "type": "DiffieHellman" + }, + "params": [ + { + "textRaw": "`prime` {string | Buffer | TypedArray | DataView}", + "name": "prime", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`primeEncoding` {string} The [encoding][] of the `prime` string.", + "name": "primeEncoding", + "type": "string", + "desc": "The [encoding][] of the `prime` string." + }, + { + "textRaw": "`generator` {number | string | Buffer | TypedArray | DataView} **Default:** `2`", + "name": "generator", + "type": "number | string | Buffer | TypedArray | DataView", + "default": "`2`" + }, + { + "textRaw": "`generatorEncoding` {string} The [encoding][] of the `generator` string.", + "name": "generatorEncoding", + "type": "string", + "desc": "The [encoding][] of the `generator` string." + } + ] + } + ], + "desc": "

      Creates a DiffieHellman key exchange object using the supplied prime and an\noptional specific generator.

      \n

      The generator argument can be a number, string, or Buffer. If\ngenerator is not specified, the value 2 is used.

      \n

      If primeEncoding is specified, prime is expected to be a string; otherwise\na Buffer, TypedArray, or DataView is expected.

      \n

      If generatorEncoding is specified, generator is expected to be a string;\notherwise a number, Buffer, TypedArray, or DataView is expected.

      " + }, + { + "textRaw": "`crypto.createDiffieHellman(primeLength[, generator])`", + "type": "method", + "name": "createDiffieHellman", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellman}", + "name": "return", + "type": "DiffieHellman" + }, + "params": [ + { + "textRaw": "`primeLength` {number}", + "name": "primeLength", + "type": "number" + }, + { + "textRaw": "`generator` {number} **Default:** `2`", + "name": "generator", + "type": "number", + "default": "`2`" + } + ] + } + ], + "desc": "

      Creates a DiffieHellman key exchange object and generates a prime of\nprimeLength bits using an optional specific numeric generator.\nIf generator is not specified, the value 2 is used.

      " + }, + { + "textRaw": "`crypto.createDiffieHellmanGroup(name)`", + "type": "method", + "name": "createDiffieHellmanGroup", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellmanGroup}", + "name": "return", + "type": "DiffieHellmanGroup" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      An alias for crypto.getDiffieHellman()

      " + }, + { + "textRaw": "`crypto.createECDH(curveName)`", + "type": "method", + "name": "createECDH", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ECDH}", + "name": "return", + "type": "ECDH" + }, + "params": [ + { + "textRaw": "`curveName` {string}", + "name": "curveName", + "type": "string" + } + ] + } + ], + "desc": "

      Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curveName string. Use\ncrypto.getCurves() to obtain a list of available curve names. On recent\nOpenSSL releases, openssl ecparam -list_curves will also display the name\nand description of each available elliptic curve.

      " + }, + { + "textRaw": "`crypto.createHash(algorithm[, options])`", + "type": "method", + "name": "createHash", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28805", + "description": "The `outputLength` option was added for XOF hash functions." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Hash}", + "name": "return", + "type": "Hash" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm. Optional options argument controls stream\nbehavior. For XOF hash functions such as 'shake256', the outputLength option\ncan be used to specify the desired output length in bytes.

      \n

      The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

      \n

      Example: generating the sha256 sum of a file

      \n
      const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hash.update(data);\n  else {\n    console.log(`${hash.digest('hex')} ${filename}`);\n  }\n});\n
      " + }, + { + "textRaw": "`crypto.createHmac(algorithm, key[, options])`", + "type": "method", + "name": "createHmac", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `key` argument can now be a `KeyObject`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Hmac}", + "name": "return", + "type": "Hmac" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView | KeyObject}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView | KeyObject" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns an Hmac object that uses the given algorithm and key.\nOptional options argument controls stream behavior.

      \n

      The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

      \n

      The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret.

      \n

      Example: generating the sha256 HMAC of a file

      \n
      const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hmac.update(data);\n  else {\n    console.log(`${hmac.digest('hex')} ${filename}`);\n  }\n});\n
      " + }, + { + "textRaw": "`crypto.createPrivateKey(key)`", + "type": "method", + "name": "createPrivateKey", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {KeyObject}", + "name": "return", + "type": "KeyObject" + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer}", + "name": "key", + "type": "Object | string | Buffer", + "options": [ + { + "textRaw": "`key`: {string | Buffer} The key material, either in PEM or DER format.", + "name": "key", + "type": "string | Buffer", + "desc": "The key material, either in PEM or DER format." + }, + { + "textRaw": "`format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`.", + "name": "format", + "type": "string", + "default": "`'pem'`", + "desc": "Must be `'pem'` or `'der'`." + }, + { + "textRaw": "`type`: {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored if it is `'pem'`.", + "name": "type", + "type": "string", + "desc": "Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored if it is `'pem'`." + }, + { + "textRaw": "`passphrase`: {string | Buffer} The passphrase to use for decryption.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "The passphrase to use for decryption." + } + ] + } + ] + } + ], + "desc": "

      Creates and returns a new key object containing a private key. If key is a\nstring or Buffer, format is assumed to be 'pem'; otherwise, key\nmust be an object with the properties described above.

      \n

      If the private key is encrypted, a passphrase must be specified. The length\nof the passphrase is limited to 1024 bytes.

      " + }, + { + "textRaw": "`crypto.createPublicKey(key)`", + "type": "method", + "name": "createPublicKey", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [ + { + "version": "v11.13.0", + "pr-url": "https://github.com/nodejs/node/pull/26278", + "description": "The `key` argument can now be a `KeyObject` with type `private`." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25217", + "description": "The `key` argument can now be a private key." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {KeyObject}", + "name": "return", + "type": "KeyObject" + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`key`: {string | Buffer}", + "name": "key", + "type": "string | Buffer" + }, + { + "textRaw": "`format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`.", + "name": "format", + "type": "string", + "default": "`'pem'`", + "desc": "Must be `'pem'` or `'der'`." + }, + { + "textRaw": "`type`: {string} Must be `'pkcs1'` or `'spki'`. This option is required only if the `format` is `'der'`.", + "name": "type", + "type": "string", + "desc": "Must be `'pkcs1'` or `'spki'`. This option is required only if the `format` is `'der'`." + } + ] + } + ] + } + ], + "desc": "

      Creates and returns a new key object containing a public key. If key is a\nstring or Buffer, format is assumed to be 'pem'; if key is a KeyObject\nwith type 'private', the public key is derived from the given private key;\notherwise, key must be an object with the properties described above.

      \n

      If the format is 'pem', the 'key' may also be an X.509 certificate.

      \n

      Because public keys can be derived from private keys, a private key may be\npassed instead of a public key. In that case, this function behaves as if\ncrypto.createPrivateKey() had been called, except that the type of the\nreturned KeyObject will be 'public' and that the private key cannot be\nextracted from the returned KeyObject. Similarly, if a KeyObject with type\n'private' is given, a new KeyObject with type 'public' will be returned\nand it will be impossible to extract the private key from the returned object.

      " + }, + { + "textRaw": "`crypto.createSecretKey(key)`", + "type": "method", + "name": "createSecretKey", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {KeyObject}", + "name": "return", + "type": "KeyObject" + }, + "params": [ + { + "textRaw": "`key` {Buffer}", + "name": "key", + "type": "Buffer" + } + ] + } + ], + "desc": "

      Creates and returns a new key object containing a secret key for symmetric\nencryption or Hmac.

      " + }, + { + "textRaw": "`crypto.createSign(algorithm[, options])`", + "type": "method", + "name": "createSign", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Sign}", + "name": "return", + "type": "Sign" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`options` {Object} [`stream.Writable` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.Writable` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Sign object that uses the given algorithm. Use\ncrypto.getHashes() to obtain the names of the available digest algorithms.\nOptional options argument controls the stream.Writable behavior.

      \n

      In some cases, a Sign instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.

      " + }, + { + "textRaw": "`crypto.createVerify(algorithm[, options])`", + "type": "method", + "name": "createVerify", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Verify}", + "name": "return", + "type": "Verify" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`options` {Object} [`stream.Writable` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.Writable` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Verify object that uses the given algorithm.\nUse crypto.getHashes() to obtain an array of names of the available\nsigning algorithms. Optional options argument controls the\nstream.Writable behavior.

      \n

      In some cases, a Verify instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.

      " + }, + { + "textRaw": "`crypto.diffieHellman(options)`", + "type": "method", + "name": "diffieHellman", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`privateKey`: {KeyObject}", + "name": "privateKey", + "type": "KeyObject" + }, + { + "textRaw": "`publicKey`: {KeyObject}", + "name": "publicKey", + "type": "KeyObject" + } + ] + } + ] + } + ], + "desc": "

      Computes the Diffie-Hellman secret based on a privateKey and a publicKey.\nBoth keys must have the same asymmetricKeyType, which must be one of 'dh'\n(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).

      " + }, + { + "textRaw": "`crypto.generateKeyPair(type, options, callback)`", + "type": "method", + "name": "generateKeyPair", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31178", + "description": "Add support for Diffie-Hellman." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26774", + "description": "Add ability to generate X25519 and X448 key pairs." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26554", + "description": "Add ability to generate Ed25519 and Ed448 key pairs." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", + "name": "type", + "type": "string", + "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." + }, + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", + "name": "modulusLength", + "type": "number", + "desc": "Key size in bits (RSA, DSA)." + }, + { + "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", + "name": "publicExponent", + "type": "number", + "default": "`0x10001`", + "desc": "Public exponent (RSA)." + }, + { + "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", + "name": "divisorLength", + "type": "number", + "desc": "Size of `q` in bits (DSA)." + }, + { + "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", + "name": "namedCurve", + "type": "string", + "desc": "Name of the curve to use (EC)." + }, + { + "textRaw": "`prime`: {Buffer} The prime parameter (DH).", + "name": "prime", + "type": "Buffer", + "desc": "The prime parameter (DH)." + }, + { + "textRaw": "`primeLength`: {number} Prime length in bits (DH).", + "name": "primeLength", + "type": "number", + "desc": "Prime length in bits (DH)." + }, + { + "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", + "name": "generator", + "type": "number", + "default": "`2`", + "desc": "Custom generator (DH)." + }, + { + "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", + "name": "groupName", + "type": "string", + "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." + }, + { + "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "publicKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + }, + { + "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "privateKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + } + ] + }, + { + "textRaw": "`callback`: {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err`: {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`publicKey`: {string | Buffer | KeyObject}", + "name": "publicKey", + "type": "string | Buffer | KeyObject" + }, + { + "textRaw": "`privateKey`: {string | Buffer | KeyObject}", + "name": "privateKey", + "type": "string | Buffer | KeyObject" + } + ] + } + ] + } + ], + "desc": "

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

      \n

      If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.

      \n

      It is recommended to encode public keys as 'spki' and private keys as\n'pkcs8' with encryption for long-term storage:

      \n
      const { generateKeyPair } = require('crypto');\ngenerateKeyPair('rsa', {\n  modulusLength: 4096,\n  publicKeyEncoding: {\n    type: 'spki',\n    format: 'pem'\n  },\n  privateKeyEncoding: {\n    type: 'pkcs8',\n    format: 'pem',\n    cipher: 'aes-256-cbc',\n    passphrase: 'top secret'\n  }\n}, (err, publicKey, privateKey) => {\n  // Handle errors and use the generated key pair.\n});\n
      \n

      On completion, callback will be called with err set to undefined and\npublicKey / privateKey representing the generated key pair.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with publicKey and privateKey properties.

      " + }, + { + "textRaw": "`crypto.generateKeyPairSync(type, options)`", + "type": "method", + "name": "generateKeyPairSync", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31178", + "description": "Add support for Diffie-Hellman." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26554", + "description": "Add ability to generate Ed25519 and Ed448 key pairs." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`publicKey`: {string | Buffer | KeyObject}", + "name": "publicKey", + "type": "string | Buffer | KeyObject" + }, + { + "textRaw": "`privateKey`: {string | Buffer | KeyObject}", + "name": "privateKey", + "type": "string | Buffer | KeyObject" + } + ] + }, + "params": [ + { + "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", + "name": "type", + "type": "string", + "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." + }, + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", + "name": "modulusLength", + "type": "number", + "desc": "Key size in bits (RSA, DSA)." + }, + { + "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", + "name": "publicExponent", + "type": "number", + "default": "`0x10001`", + "desc": "Public exponent (RSA)." + }, + { + "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", + "name": "divisorLength", + "type": "number", + "desc": "Size of `q` in bits (DSA)." + }, + { + "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", + "name": "namedCurve", + "type": "string", + "desc": "Name of the curve to use (EC)." + }, + { + "textRaw": "`prime`: {Buffer} The prime parameter (DH).", + "name": "prime", + "type": "Buffer", + "desc": "The prime parameter (DH)." + }, + { + "textRaw": "`primeLength`: {number} Prime length in bits (DH).", + "name": "primeLength", + "type": "number", + "desc": "Prime length in bits (DH)." + }, + { + "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", + "name": "generator", + "type": "number", + "default": "`2`", + "desc": "Custom generator (DH)." + }, + { + "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", + "name": "groupName", + "type": "string", + "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." + }, + { + "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "publicKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + }, + { + "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "privateKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + } + ] + } + ] + } + ], + "desc": "

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

      \n

      If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.

      \n

      When encoding public keys, it is recommended to use 'spki'. When encoding\nprivate keys, it is recommended to use 'pkcs8' with a strong passphrase,\nand to keep the passphrase confidential.

      \n
      const { generateKeyPairSync } = require('crypto');\nconst { publicKey, privateKey } = generateKeyPairSync('rsa', {\n  modulusLength: 4096,\n  publicKeyEncoding: {\n    type: 'spki',\n    format: 'pem'\n  },\n  privateKeyEncoding: {\n    type: 'pkcs8',\n    format: 'pem',\n    cipher: 'aes-256-cbc',\n    passphrase: 'top secret'\n  }\n});\n
      \n

      The return value { publicKey, privateKey } represents the generated key pair.\nWhen PEM encoding was selected, the respective key will be a string, otherwise\nit will be a buffer containing the data encoded as DER.

      " + }, + { + "textRaw": "`crypto.getCiphers()`", + "type": "method", + "name": "getCiphers", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]} An array with the names of the supported cipher algorithms.", + "name": "return", + "type": "string[]", + "desc": "An array with the names of the supported cipher algorithms." + }, + "params": [] + } + ], + "desc": "
      const ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
      " + }, + { + "textRaw": "`crypto.getCurves()`", + "type": "method", + "name": "getCurves", + "meta": { + "added": [ + "v2.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]} An array with the names of the supported elliptic curves.", + "name": "return", + "type": "string[]", + "desc": "An array with the names of the supported elliptic curves." + }, + "params": [] + } + ], + "desc": "
      const curves = crypto.getCurves();\nconsole.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
      " + }, + { + "textRaw": "`crypto.getDiffieHellman(groupName)`", + "type": "method", + "name": "getDiffieHellman", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellmanGroup}", + "name": "return", + "type": "DiffieHellmanGroup" + }, + "params": [ + { + "textRaw": "`groupName` {string}", + "name": "groupName", + "type": "string" + } + ] + } + ], + "desc": "

      Creates a predefined DiffieHellmanGroup key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in\nRFC 2412, but see Caveats) and 'modp14', 'modp15',\n'modp16', 'modp17', 'modp18' (defined in RFC 3526). The\nreturned object mimics the interface of objects created by\ncrypto.createDiffieHellman(), but will not allow changing\nthe keys (with diffieHellman.setPublicKey(), for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.

      \n

      Example (obtaining a shared secret):

      \n
      const crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
      " + }, + { + "textRaw": "`crypto.getFips()`", + "type": "method", + "name": "getFips", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.", + "name": "return", + "type": "number", + "desc": "`1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}." + }, + "params": [] + } + ] + }, + { + "textRaw": "`crypto.getHashes()`", + "type": "method", + "name": "getHashes", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]} An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms.", + "name": "return", + "type": "string[]", + "desc": "An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms." + }, + "params": [] + } + ], + "desc": "
      const hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
      " + }, + { + "textRaw": "`crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`", + "type": "method", + "name": "pbkdf2", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11305", + "description": "The `digest` parameter is always required now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4047", + "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`iterations` {number}", + "name": "iterations", + "type": "number" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`digest` {string}", + "name": "digest", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`derivedKey` {Buffer}", + "name": "derivedKey", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest is\napplied to derive a key of the requested byte length (keylen) from the\npassword, salt and iterations.

      \n

      The supplied callback function is called with two arguments: err and\nderivedKey. If an error occurs while deriving the key, err will be set;\notherwise err will be null. By default, the successfully generated\nderivedKey will be passed to the callback as a Buffer. An error will be\nthrown if any of the input arguments specify invalid values or types.

      \n

      If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

      \n

      The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n
      const crypto = require('crypto');\ncrypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'\n});\n
      \n

      The crypto.DEFAULT_ENCODING property can be used to change the way the\nderivedKey is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.

      \n
      const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey);  // '3745e48...aa39b34'\n});\n
      \n

      An array of supported digest functions can be retrieved using\ncrypto.getHashes().

      \n

      This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.

      " + }, + { + "textRaw": "`crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)`", + "type": "method", + "name": "pbkdf2Sync", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4047", + "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`iterations` {number}", + "name": "iterations", + "type": "number" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`digest` {string}", + "name": "digest", + "type": "string" + } + ] + } + ], + "desc": "

      Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest is\napplied to derive a key of the requested byte length (keylen) from the\npassword, salt and iterations.

      \n

      If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a Buffer.

      \n

      If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

      \n

      The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n
      const crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...08d59ae'\n
      \n

      The crypto.DEFAULT_ENCODING property may be used to change the way the\nderivedKey is returned. This property, however, is deprecated and use\nshould be avoided.

      \n
      const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key);  // '3745e48...aa39b34'\n
      \n

      An array of supported digest functions can be retrieved using\ncrypto.getHashes().

      " + }, + { + "textRaw": "`crypto.privateDecrypt(privateKey, buffer)`", + "type": "method", + "name": "privateDecrypt", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29489", + "description": "The `oaepLabel` option was added." + }, + { + "version": "v12.9.0", + "pr-url": "https://github.com/nodejs/node/pull/28335", + "description": "The `oaepHash` option was added." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the decrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the decrypted content." + }, + "params": [ + { + "textRaw": "`privateKey` {Object | string | Buffer | KeyObject}", + "name": "privateKey", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'`", + "name": "oaepHash", + "type": "string", + "default": "`'sha1'`", + "desc": "The hash function to use for OAEP padding and MGF1." + }, + { + "textRaw": "`oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP padding. If not specified, no label is used.", + "name": "oaepLabel", + "type": "Buffer | TypedArray | DataView", + "desc": "The label to use for OAEP padding. If not specified, no label is used." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Decrypts buffer with privateKey. buffer was previously encrypted using\nthe corresponding public key, for example using crypto.publicEncrypt().

      \n

      If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.

      " + }, + { + "textRaw": "`crypto.privateEncrypt(privateKey, buffer)`", + "type": "method", + "name": "privateEncrypt", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the encrypted content." + }, + "params": [ + { + "textRaw": "`privateKey` {Object | string | Buffer | KeyObject}", + "name": "privateKey", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`key` {string | Buffer | KeyObject} A PEM encoded private key.", + "name": "key", + "type": "string | Buffer | KeyObject", + "desc": "A PEM encoded private key." + }, + { + "textRaw": "`passphrase` {string | Buffer} An optional passphrase for the private key.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "An optional passphrase for the private key." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Encrypts buffer with privateKey. The returned data can be decrypted using\nthe corresponding public key, for example using crypto.publicDecrypt().

      \n

      If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.

      " + }, + { + "textRaw": "`crypto.publicDecrypt(key, buffer)`", + "type": "method", + "name": "publicDecrypt", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the decrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the decrypted content." + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`passphrase` {string | Buffer} An optional passphrase for the private key.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "An optional passphrase for the private key." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Decrypts buffer with key.buffer was previously encrypted using\nthe corresponding private key, for example using crypto.privateEncrypt().

      \n

      If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.

      \n

      Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

      " + }, + { + "textRaw": "`crypto.publicEncrypt(key, buffer)`", + "type": "method", + "name": "publicEncrypt", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29489", + "description": "The `oaepLabel` option was added." + }, + { + "version": "v12.9.0", + "pr-url": "https://github.com/nodejs/node/pull/28335", + "description": "The `oaepHash` option was added." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the encrypted content." + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`key` {string | Buffer | KeyObject} A PEM encoded public or private key.", + "name": "key", + "type": "string | Buffer | KeyObject", + "desc": "A PEM encoded public or private key." + }, + { + "textRaw": "`oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'`", + "name": "oaepHash", + "type": "string", + "default": "`'sha1'`", + "desc": "The hash function to use for OAEP padding and MGF1." + }, + { + "textRaw": "`oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP padding. If not specified, no label is used.", + "name": "oaepLabel", + "type": "Buffer | TypedArray | DataView", + "desc": "The label to use for OAEP padding. If not specified, no label is used." + }, + { + "textRaw": "`passphrase` {string | Buffer} An optional passphrase for the private key.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "An optional passphrase for the private key." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Encrypts the content of buffer with key and returns a new\nBuffer with encrypted content. The returned data can be decrypted using\nthe corresponding private key, for example using crypto.privateDecrypt().

      \n

      If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.

      \n

      Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

      " + }, + { + "textRaw": "`crypto.randomBytes(size[, callback])`", + "type": "method", + "name": "randomBytes", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16454", + "description": "Passing `null` as the `callback` argument now throws `ERR_INVALID_CALLBACK`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", + "name": "return", + "type": "Buffer", + "desc": "if the `callback` function is not provided." + }, + "params": [ + { + "textRaw": "`size` {number}", + "name": "size", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`buf` {Buffer}", + "name": "buf", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Generates cryptographically strong pseudo-random data. The size argument\nis a number indicating the number of bytes to generate.

      \n

      If a callback function is provided, the bytes are generated asynchronously\nand the callback function is invoked with two arguments: err and buf.\nIf an error occurs, err will be an Error object; otherwise it is null. The\nbuf argument is a Buffer containing the generated bytes.

      \n
      // Asynchronous\nconst crypto = require('crypto');\ncrypto.randomBytes(256, (err, buf) => {\n  if (err) throw err;\n  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n
      \n

      If the callback function is not provided, the random bytes are generated\nsynchronously and returned as a Buffer. An error will be thrown if\nthere is a problem generating the bytes.

      \n
      // Synchronous\nconst buf = crypto.randomBytes(256);\nconsole.log(\n  `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
      \n

      The crypto.randomBytes() method will not complete until there is\nsufficient entropy available.\nThis should normally never take longer than a few milliseconds. The only time\nwhen generating the random bytes may conceivably block for a longer period of\ntime is right after boot, when the whole system is still low on entropy.

      \n

      This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.

      \n

      The asynchronous version of crypto.randomBytes() is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomBytes requests when doing so as part of fulfilling a client\nrequest.

      " + }, + { + "textRaw": "`crypto.randomFillSync(buffer[, offset][, size])`", + "type": "method", + "name": "randomFillSync", + "meta": { + "added": [ + "v7.10.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15231", + "description": "The `buffer` argument may be any `TypedArray` or `DataView`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|TypedArray|DataView} The object passed as `buffer` argument.", + "name": "return", + "type": "Buffer|TypedArray|DataView", + "desc": "The object passed as `buffer` argument." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} Must be supplied.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "Must be supplied." + }, + { + "textRaw": "`offset` {number} **Default:** `0`", + "name": "offset", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`size` {number} **Default:** `buffer.length - offset`", + "name": "size", + "type": "number", + "default": "`buffer.length - offset`" + } + ] + } + ], + "desc": "

      Synchronous version of crypto.randomFill().

      \n
      const buf = Buffer.alloc(10);\nconsole.log(crypto.randomFillSync(buf).toString('hex'));\n\ncrypto.randomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\ncrypto.randomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
      \n

      Any TypedArray or DataView instance may be passed as buffer.

      \n
      const a = new Uint32Array(10);\nconsole.log(Buffer.from(crypto.randomFillSync(a).buffer,\n                        a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new Float64Array(10);\nconsole.log(Buffer.from(crypto.randomFillSync(b).buffer,\n                        b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(crypto.randomFillSync(c).buffer,\n                        c.byteOffset, c.byteLength).toString('hex'));\n
      " + }, + { + "textRaw": "`crypto.randomFill(buffer[, offset][, size], callback)`", + "type": "method", + "name": "randomFill", + "meta": { + "added": [ + "v7.10.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15231", + "description": "The `buffer` argument may be any `TypedArray` or `DataView`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} Must be supplied.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "Must be supplied." + }, + { + "textRaw": "`offset` {number} **Default:** `0`", + "name": "offset", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`size` {number} **Default:** `buffer.length - offset`", + "name": "size", + "type": "number", + "default": "`buffer.length - offset`" + }, + { + "textRaw": "`callback` {Function} `function(err, buf) {}`.", + "name": "callback", + "type": "Function", + "desc": "`function(err, buf) {}`." + } + ] + } + ], + "desc": "

      This function is similar to crypto.randomBytes() but requires the first\nargument to be a Buffer that will be filled. It also\nrequires that a callback is passed in.

      \n

      If the callback function is not provided, an error will be thrown.

      \n
      const buf = Buffer.alloc(10);\ncrypto.randomFill(buf, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\ncrypto.randomFill(buf, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\ncrypto.randomFill(buf, 5, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n
      \n

      Any TypedArray or DataView instance may be passed as buffer.

      \n
      const a = new Uint32Array(10);\ncrypto.randomFill(a, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst b = new Float64Array(10);\ncrypto.randomFill(b, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst c = new DataView(new ArrayBuffer(10));\ncrypto.randomFill(c, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n
      \n

      This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.

      \n

      The asynchronous version of crypto.randomFill() is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomFill requests when doing so as part of fulfilling a client\nrequest.

      " + }, + { + "textRaw": "`crypto.randomInt([min, ]max[, callback])`", + "type": "method", + "name": "randomInt", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`min` {integer} Start of random range (inclusive). **Default**: `0`.", + "name": "min", + "type": "integer", + "desc": "Start of random range (inclusive). **Default**: `0`." + }, + { + "textRaw": "`max` {integer} End of random range (exclusive).", + "name": "max", + "type": "integer", + "desc": "End of random range (exclusive)." + }, + { + "textRaw": "`callback` {Function} `function(err, n) {}`.", + "name": "callback", + "type": "Function", + "desc": "`function(err, n) {}`." + } + ] + } + ], + "desc": "

      Return a random integer n such that min <= n < max. This\nimplementation avoids modulo bias.

      \n

      The range (max - min) must be less than 248. min and max must\nbe safe integers.

      \n

      If the callback function is not provided, the random integer is\ngenerated synchronously.

      \n
      // Asynchronous\ncrypto.randomInt(3, (err, n) => {\n  if (err) throw err;\n  console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n
      \n
      // Synchronous\nconst n = crypto.randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
      \n
      // With `min` argument\nconst n = crypto.randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
      " + }, + { + "textRaw": "`crypto.scrypt(password, salt, keylen[, options], callback)`", + "type": "method", + "name": "scrypt", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28799", + "description": "The `maxmem` value can now be any safe integer." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21525", + "description": "The `cost`, `blockSize` and `parallelization` option names have been added." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", + "name": "cost", + "type": "number", + "default": "`16384`", + "desc": "CPU/memory cost parameter. Must be a power of two greater than one." + }, + { + "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", + "name": "blockSize", + "type": "number", + "default": "`8`", + "desc": "Block size parameter." + }, + { + "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", + "name": "parallelization", + "type": "number", + "default": "`1`", + "desc": "Parallelization parameter." + }, + { + "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", + "name": "N", + "type": "number", + "desc": "Alias for `cost`. Only one of both may be specified." + }, + { + "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", + "name": "r", + "type": "number", + "desc": "Alias for `blockSize`. Only one of both may be specified." + }, + { + "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", + "name": "p", + "type": "number", + "desc": "Alias for `parallelization`. Only one of both may be specified." + }, + { + "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", + "name": "maxmem", + "type": "number", + "default": "`32 * 1024 * 1024`", + "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`derivedKey` {Buffer}", + "name": "derivedKey", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Provides an asynchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n

      The callback function is called with two arguments: err and derivedKey.\nerr is an exception object when key derivation fails, otherwise err is\nnull. derivedKey is passed to the callback as a Buffer.

      \n

      An exception is thrown when any of the input arguments specify invalid values\nor types.

      \n
      const crypto = require('crypto');\n// Using the factory defaults.\ncrypto.scrypt('secret', 'salt', 64, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\ncrypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'\n});\n
      " + }, + { + "textRaw": "`crypto.scryptSync(password, salt, keylen[, options])`", + "type": "method", + "name": "scryptSync", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28799", + "description": "The `maxmem` value can now be any safe integer." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21525", + "description": "The `cost`, `blockSize` and `parallelization` option names have been added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", + "name": "cost", + "type": "number", + "default": "`16384`", + "desc": "CPU/memory cost parameter. Must be a power of two greater than one." + }, + { + "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", + "name": "blockSize", + "type": "number", + "default": "`8`", + "desc": "Block size parameter." + }, + { + "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", + "name": "parallelization", + "type": "number", + "default": "`1`", + "desc": "Parallelization parameter." + }, + { + "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", + "name": "N", + "type": "number", + "desc": "Alias for `cost`. Only one of both may be specified." + }, + { + "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", + "name": "r", + "type": "number", + "desc": "Alias for `blockSize`. Only one of both may be specified." + }, + { + "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", + "name": "p", + "type": "number", + "desc": "Alias for `parallelization`. Only one of both may be specified." + }, + { + "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", + "name": "maxmem", + "type": "number", + "default": "`32 * 1024 * 1024`", + "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." + } + ] + } + ] + } + ], + "desc": "

      Provides a synchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n

      An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.

      \n

      An exception is thrown when any of the input arguments specify invalid values\nor types.

      \n
      const crypto = require('crypto');\n// Using the factory defaults.\nconst key1 = crypto.scryptSync('secret', 'salt', 64);\nconsole.log(key1.toString('hex'));  // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex'));  // '3745e48...aa39b34'\n
      " + }, + { + "textRaw": "`crypto.setEngine(engine[, flags])`", + "type": "method", + "name": "setEngine", + "meta": { + "added": [ + "v0.11.11" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`engine` {string}", + "name": "engine", + "type": "string" + }, + { + "textRaw": "`flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`", + "name": "flags", + "type": "crypto.constants", + "default": "`crypto.constants.ENGINE_METHOD_ALL`" + } + ] + } + ], + "desc": "

      Load and set the engine for some or all OpenSSL functions (selected by flags).

      \n

      engine could be either an id or a path to the engine's shared library.

      \n

      The optional flags argument uses ENGINE_METHOD_ALL by default. The flags\nis a bit field taking one of or a mix of the following flags (defined in\ncrypto.constants):

      \n
        \n
      • crypto.constants.ENGINE_METHOD_RSA
      • \n
      • crypto.constants.ENGINE_METHOD_DSA
      • \n
      • crypto.constants.ENGINE_METHOD_DH
      • \n
      • crypto.constants.ENGINE_METHOD_RAND
      • \n
      • crypto.constants.ENGINE_METHOD_EC
      • \n
      • crypto.constants.ENGINE_METHOD_CIPHERS
      • \n
      • crypto.constants.ENGINE_METHOD_DIGESTS
      • \n
      • crypto.constants.ENGINE_METHOD_PKEY_METHS
      • \n
      • crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
      • \n
      • crypto.constants.ENGINE_METHOD_ALL
      • \n
      • crypto.constants.ENGINE_METHOD_NONE
      • \n
      \n

      The flags below are deprecated in OpenSSL-1.1.0.

      \n
        \n
      • crypto.constants.ENGINE_METHOD_ECDH
      • \n
      • crypto.constants.ENGINE_METHOD_ECDSA
      • \n
      • crypto.constants.ENGINE_METHOD_STORE
      • \n
      " + }, + { + "textRaw": "`crypto.setFips(bool)`", + "type": "method", + "name": "setFips", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`bool` {boolean} `true` to enable FIPS mode.", + "name": "bool", + "type": "boolean", + "desc": "`true` to enable FIPS mode." + } + ] + } + ], + "desc": "

      Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.\nThrows an error if FIPS mode is not available.

      " + }, + { + "textRaw": "`crypto.sign(algorithm, data, key)`", + "type": "method", + "name": "sign", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`algorithm` {string | null | undefined}", + "name": "algorithm", + "type": "string | null | undefined" + }, + { + "textRaw": "`data` {Buffer | TypedArray | DataView}", + "name": "data", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject" + } + ] + } + ], + "desc": "

      Calculates and returns the signature for data using the given private key and\nalgorithm. If algorithm is null or undefined, then the algorithm is\ndependent upon the key type (especially Ed25519 and Ed448).

      \n

      If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPrivateKey(). If it is an object, the following\nadditional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.

        \n
      • \n
      " + }, + { + "textRaw": "`crypto.timingSafeEqual(a, b)`", + "type": "method", + "name": "timingSafeEqual", + "meta": { + "added": [ + "v6.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`a` {Buffer | TypedArray | DataView}", + "name": "a", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`b` {Buffer | TypedArray | DataView}", + "name": "b", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      This function is based on a constant-time algorithm.\nReturns true if a is equal to b, without leaking timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.

      \n

      a and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same length.

      \n

      Use of crypto.timingSafeEqual does not guarantee that the surrounding code\nis timing-safe. Care should be taken to ensure that the surrounding code does\nnot introduce timing vulnerabilities.

      " + }, + { + "textRaw": "`crypto.verify(algorithm, data, key, signature)`", + "type": "method", + "name": "verify", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`algorithm` {string | null | undefined}", + "name": "algorithm", + "type": "string | null | undefined" + }, + { + "textRaw": "`data` {Buffer | TypedArray | DataView}", + "name": "data", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject" + }, + { + "textRaw": "`signature` {Buffer | TypedArray | DataView}", + "name": "signature", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Verifies the given signature for data using the given key and algorithm. If\nalgorithm is null or undefined, then the algorithm is dependent upon the\nkey type (especially Ed25519 and Ed448).

      \n

      If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPublicKey(). If it is an object, the following\nadditional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.

        \n
      • \n
      \n

      The signature argument is the previously calculated signature for the data.

      \n

      Because public keys can be derived from private keys, a private key or a public\nkey may be passed for key.

      " + } + ], + "type": "module", + "displayName": "`crypto` module methods and properties" + }, + { + "textRaw": "Notes", + "name": "notes", + "modules": [ + { + "textRaw": "Legacy Streams API (prior to Node.js 0.10)", + "name": "legacy_streams_api_(prior_to_node.js_0.10)", + "desc": "

      The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data. As such, the many of the crypto defined classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update(), final(), or digest()). Also, many methods accepted\nand returned 'latin1' encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use Buffer objects by default\ninstead.

      ", + "type": "module", + "displayName": "Legacy Streams API (prior to Node.js 0.10)" + }, + { + "textRaw": "Recent ECDH changes", + "name": "recent_ecdh_changes", + "desc": "

      Usage of ECDH with non-dynamically generated key pairs has been simplified.\nNow, ecdh.setPrivateKey() can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\necdh.setPrivateKey() now also validates that the private key is valid for\nthe selected curve.

      \n

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful. Either a previously stored private key should be set, which\nautomatically generates the associated public key, or ecdh.generateKeys()\nshould be called. The main drawback of using ecdh.setPublicKey() is that\nit can be used to put the ECDH key pair into an inconsistent state.

      ", + "type": "module", + "displayName": "Recent ECDH changes" + }, + { + "textRaw": "Support for weak or compromised algorithms", + "name": "support_for_weak_or_compromised_algorithms", + "desc": "

      The crypto module still supports some algorithms which are already\ncompromised and are not currently recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are too weak for safe\nuse.

      \n

      Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.

      \n

      Based on the recommendations of NIST SP 800-131A:

      \n
        \n
      • MD5 and SHA-1 are no longer acceptable where collision resistance is\nrequired such as digital signatures.
      • \n
      • The key used with RSA, DSA, and DH algorithms is recommended to have\nat least 2048 bits and that of the curve of ECDSA and ECDH at least\n224 bits, to be safe to use for several years.
      • \n
      • The DH groups of modp1, modp2 and modp5 have a key size\nsmaller than 2048 bits and are not recommended.
      • \n
      \n

      See the reference for other recommendations and details.

      ", + "type": "module", + "displayName": "Support for weak or compromised algorithms" + }, + { + "textRaw": "CCM mode", + "name": "ccm_mode", + "desc": "

      CCM is one of the supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:

      \n
        \n
      • The authentication tag length must be specified during cipher creation by\nsetting the authTagLength option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.
      • \n
      • The length of the initialization vector (nonce) N must be between 7 and 13\nbytes (7 ≤ N ≤ 13).
      • \n
      • The length of the plaintext is limited to 2 ** (8 * (15 - N)) bytes.
      • \n
      • When decrypting, the authentication tag must be set via setAuthTag() before\ncalling update().\nOtherwise, decryption will fail and final() will throw an error in\ncompliance with section 2.6 of RFC 3610.
      • \n
      • Using stream methods such as write(data), end(data) or pipe() in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.
      • \n
      • When passing additional authenticated data (AAD), the length of the actual\nmessage in bytes must be passed to setAAD() via the plaintextLength\noption.\nMany crypto libraries include the authentication tag in the ciphertext,\nwhich means that they produce ciphertexts of the length\nplaintextLength + authTagLength. Node.js does not include the authentication\ntag, so the ciphertext length is always plaintextLength.\nThis is not necessary if no AAD is used.
      • \n
      • As CCM processes the whole message at once, update() can only be called\nonce.
      • \n
      • Even though calling update() is sufficient to encrypt/decrypt the message,\napplications must call final() to compute or verify the\nauthentication tag.
      • \n
      \n
      const crypto = require('crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = crypto.randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n  plaintextLength: Buffer.byteLength(plaintext)\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n  plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n  decipher.final();\n} catch (err) {\n  console.error('Authentication failed!');\n  return;\n}\n\nconsole.log(receivedPlaintext);\n
      ", + "type": "module", + "displayName": "CCM mode" + } + ], + "type": "module", + "displayName": "Notes" + }, + { + "textRaw": "Crypto constants", + "name": "crypto_constants", + "desc": "

      The following constants exported by crypto.constants apply to various uses of\nthe crypto, tls, and https modules and are generally specific to OpenSSL.

      ", + "modules": [ + { + "textRaw": "OpenSSL options", + "name": "openssl_options", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\n for detail.
      SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode\n for TLS v1.3
      SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CIPHER_SERVER_PREFERENCEAttempts to use the server's preferences instead of the client's when\n selecting a cipher. Behavior depends on protocol version. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's \"speshul\" version of DTLS_BAD_VER.
      SSL_OP_COOKIE_EXCHANGEInstructs OpenSSL to turn on cookie exchange.
      SSL_OP_CRYPTOPRO_TLSEXT_BUGInstructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft.
      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d.
      SSL_OP_EPHEMERAL_RSAInstructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations.
      SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
      SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
      SSL_OP_MICROSOFT_SESS_ID_BUG
      SSL_OP_MSIE_SSLV2_RSA_PADDINGInstructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation.
      SSL_OP_NETSCAPE_CA_DN_BUG
      SSL_OP_NETSCAPE_CHALLENGE_BUG
      SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
      SSL_OP_NO_COMPRESSIONInstructs OpenSSL to disable support for SSL/TLS compression.
      SSL_OP_NO_ENCRYPT_THEN_MACInstructs OpenSSL to disable encrypt-then-MAC.
      SSL_OP_NO_QUERY_MTU
      SSL_OP_NO_RENEGOTIATIONInstructs OpenSSL to disable renegotiation.
      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATIONInstructs OpenSSL to always start a new session when performing\n renegotiation.
      SSL_OP_NO_SSLv2Instructs OpenSSL to turn off SSL v2
      SSL_OP_NO_SSLv3Instructs OpenSSL to turn off SSL v3
      SSL_OP_NO_TICKETInstructs OpenSSL to disable use of RFC4507bis tickets.
      SSL_OP_NO_TLSv1Instructs OpenSSL to turn off TLS v1
      SSL_OP_NO_TLSv1_1Instructs OpenSSL to turn off TLS v1.1
      SSL_OP_NO_TLSv1_2Instructs OpenSSL to turn off TLS v1.2
      SSL_OP_NO_TLSv1_3Instructs OpenSSL to turn off TLS v1.3
      SSL_OP_PKCS1_CHECK_1
      SSL_OP_PKCS1_CHECK_2
      SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20Poly1305\n when client does.\n This option has no effect if\n SSL_OP_CIPHER_SERVER_PREFERENCE\n is not enabled.
      SSL_OP_SINGLE_DH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters.
      SSL_OP_SINGLE_ECDH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters.
      SSL_OP_SSLEAY_080_CLIENT_DH_BUG
      SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
      SSL_OP_TLS_BLOCK_PADDING_BUG
      SSL_OP_TLS_D5_BUG
      SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.
      ", + "type": "module", + "displayName": "OpenSSL options" + }, + { + "textRaw": "OpenSSL engine constants", + "name": "openssl_engine_constants", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      ENGINE_METHOD_RSALimit engine usage to RSA
      ENGINE_METHOD_DSALimit engine usage to DSA
      ENGINE_METHOD_DHLimit engine usage to DH
      ENGINE_METHOD_RANDLimit engine usage to RAND
      ENGINE_METHOD_ECLimit engine usage to EC
      ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
      ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
      ENGINE_METHOD_PKEY_METHSLimit engine usage to PKEY_METHDS
      ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
      ENGINE_METHOD_ALL
      ENGINE_METHOD_NONE
      ", + "type": "module", + "displayName": "OpenSSL engine constants" + }, + { + "textRaw": "Other OpenSSL constants", + "name": "other_openssl_constants", + "desc": "

      See the list of SSL OP Flags for details.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      DH_CHECK_P_NOT_SAFE_PRIME
      DH_CHECK_P_NOT_PRIME
      DH_UNABLE_TO_CHECK_GENERATOR
      DH_NOT_SUITABLE_GENERATOR
      ALPN_ENABLED
      RSA_PKCS1_PADDING
      RSA_SSLV23_PADDING
      RSA_NO_PADDING
      RSA_PKCS1_OAEP_PADDING
      RSA_X931_PADDING
      RSA_PKCS1_PSS_PADDING
      RSA_PSS_SALTLEN_DIGESTSets the salt length for RSA_PKCS1_PSS_PADDING to the\n digest size when signing or verifying.
      RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the\n maximum permissible value when signing data.
      RSA_PSS_SALTLEN_AUTOCauses the salt length for RSA_PKCS1_PSS_PADDING to be\n determined automatically when verifying a signature.
      POINT_CONVERSION_COMPRESSED
      POINT_CONVERSION_UNCOMPRESSED
      POINT_CONVERSION_HYBRID
      ", + "type": "module", + "displayName": "Other OpenSSL constants" + }, + { + "textRaw": "Node.js crypto constants", + "name": "node.js_crypto_constants", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
      defaultCipherListSpecifies the active default cipher list used by the current Node.js\n process.
      ", + "type": "module", + "displayName": "Node.js crypto constants" + } + ], + "type": "module", + "displayName": "Crypto constants" + } + ], + "classes": [ + { + "textRaw": "Class: `Certificate`", + "type": "class", + "name": "Certificate", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen element.

      \n

      <keygen> is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.

      \n

      The crypto module provides the Certificate class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.

      ", + "methods": [ + { + "textRaw": "`Certificate.exportChallenge(spkac)`", + "type": "method", + "name": "exportChallenge", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
      " + }, + { + "textRaw": "`Certificate.exportPublicKey(spkac[, encoding])`", + "type": "method", + "name": "exportPublicKey", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `spkac` string." + } + ] + } + ], + "desc": "
      const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
      " + }, + { + "textRaw": "`Certificate.verifySpkac(spkac)`", + "type": "method", + "name": "verifySpkac", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if the given `spkac` data structure is valid, `false` otherwise." + }, + "params": [ + { + "textRaw": "`spkac` {Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
      " + } + ], + "modules": [ + { + "textRaw": "Legacy API", + "name": "legacy_api", + "desc": "

      As a still supported legacy interface, it is possible to create new instances of\nthe crypto.Certificate class as illustrated in the examples below.

      ", + "ctors": [ + { + "textRaw": "`new crypto.Certificate()`", + "type": "ctor", + "name": "crypto.Certificate", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:

      \n
      const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n
      " + } + ], + "methods": [ + { + "textRaw": "`certificate.exportChallenge(spkac)`", + "type": "method", + "name": "exportChallenge", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
      " + }, + { + "textRaw": "`certificate.exportPublicKey(spkac)`", + "type": "method", + "name": "exportPublicKey", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
      " + }, + { + "textRaw": "`certificate.verifySpkac(spkac)`", + "type": "method", + "name": "verifySpkac", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if the given `spkac` data structure is valid, `false` otherwise." + }, + "params": [ + { + "textRaw": "`spkac` {Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
      " + } + ], + "type": "module", + "displayName": "Legacy API" + } + ] + }, + { + "textRaw": "Class: `Cipher`", + "type": "class", + "name": "Cipher", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "desc": "\n

      Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where plain unencrypted\ndata is written to produce encrypted data on the readable side, or
      • \n
      • Using the cipher.update() and cipher.final() methods to produce\nthe encrypted data.
      • \n
      \n

      The crypto.createCipher() or crypto.createCipheriv() methods are\nused to create Cipher instances. Cipher objects are not to be created\ndirectly using the new keyword.

      \n

      Example: Using Cipher objects as streams:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes()` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nlet encrypted = '';\ncipher.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = cipher.read())) {\n    encrypted += chunk.toString('hex');\n  }\n});\ncipher.on('end', () => {\n  console.log(encrypted);\n  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa\n});\n\ncipher.write('some clear text data');\ncipher.end();\n
      \n

      Example: Using Cipher and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes()` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nconst input = fs.createReadStream('test.js');\nconst output = fs.createWriteStream('test.enc');\n\ninput.pipe(cipher).pipe(output);\n
      \n

      Example: Using the cipher.update() and cipher.final() methods:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nlet encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa\n
      ", + "methods": [ + { + "textRaw": "`cipher.final([outputEncoding])`", + "type": "method", + "name": "final", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.", + "name": "return", + "type": "Buffer | string", + "desc": "Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned." + }, + "params": [ + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Once the cipher.final() method has been called, the Cipher object can no\nlonger be used to encrypt data. Attempts to call cipher.final() more than\nonce will result in an error being thrown.

      " + }, + { + "textRaw": "`cipher.setAAD(buffer[, options])`", + "type": "method", + "name": "setAAD", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher} for method chaining.", + "name": "return", + "type": "Cipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]", + "options": [ + { + "textRaw": "`plaintextLength` {number}", + "name": "plaintextLength", + "type": "number" + } + ] + } + ] + } + ], + "desc": "

      When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

      \n

      The options argument is optional for GCM and OCB. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the plaintext in bytes. See CCM mode.

      \n

      The cipher.setAAD() method must be called before cipher.update().

      " + }, + { + "textRaw": "`cipher.getAuthTag()`", + "type": "method", + "name": "getAuthTag", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data.", + "name": "return", + "type": "Buffer", + "desc": "When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data." + }, + "params": [] + } + ], + "desc": "

      The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.

      " + }, + { + "textRaw": "`cipher.setAutoPadding([autoPadding])`", + "type": "method", + "name": "setAutoPadding", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher} for method chaining.", + "name": "return", + "type": "Cipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`autoPadding` {boolean} **Default:** `true`", + "name": "autoPadding", + "type": "boolean", + "default": "`true`" + } + ] + } + ], + "desc": "

      When using block encryption algorithms, the Cipher class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false).

      \n

      When autoPadding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or cipher.final() will throw an error.\nDisabling automatic padding is useful for non-standard padding, for instance\nusing 0x0 instead of PKCS padding.

      \n

      The cipher.setAutoPadding() method must be called before\ncipher.final().

      " + }, + { + "textRaw": "`cipher.update(data[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the data.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the data." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Updates the cipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer, TypedArray, or\nDataView. If data is a Buffer, TypedArray, or DataView, then\ninputEncoding is ignored.

      \n

      The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.

      \n

      The cipher.update() method can be called multiple times with new data until\ncipher.final() is called. Calling cipher.update() after\ncipher.final() will result in an error being thrown.

      " + } + ] + }, + { + "textRaw": "Class: `Decipher`", + "type": "class", + "name": "Decipher", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "desc": "\n

      Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where plain encrypted\ndata is written to produce unencrypted data on the readable side, or
      • \n
      • Using the decipher.update() and decipher.final() methods to\nproduce the unencrypted data.
      • \n
      \n

      The crypto.createDecipher() or crypto.createDecipheriv() methods are\nused to create Decipher instances. Decipher objects are not to be created\ndirectly using the new keyword.

      \n

      Example: Using Decipher objects as streams:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n  while (null !== (chunk = decipher.read())) {\n    decrypted += chunk.toString('utf8');\n  }\n});\ndecipher.on('end', () => {\n  console.log(decrypted);\n  // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
      \n

      Example: Using Decipher and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\nconst input = fs.createReadStream('test.enc');\nconst output = fs.createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n
      \n

      Example: Using the decipher.update() and decipher.final() methods:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
      ", + "methods": [ + { + "textRaw": "`decipher.final([outputEncoding])`", + "type": "method", + "name": "final", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.", + "name": "return", + "type": "Buffer | string", + "desc": "Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned." + }, + "params": [ + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Once the decipher.final() method has been called, the Decipher object can\nno longer be used to decrypt data. Attempts to call decipher.final() more\nthan once will result in an error being thrown.

      " + }, + { + "textRaw": "`decipher.setAAD(buffer[, options])`", + "type": "method", + "name": "setAAD", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9398", + "description": "This method now returns a reference to `decipher`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher} for method chaining.", + "name": "return", + "type": "Decipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]", + "options": [ + { + "textRaw": "`plaintextLength` {number}", + "name": "plaintextLength", + "type": "number" + } + ] + } + ] + } + ], + "desc": "

      When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

      \n

      The options argument is optional for GCM. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the ciphertext in bytes. See CCM mode.

      \n

      The decipher.setAAD() method must be called before decipher.update().

      " + }, + { + "textRaw": "`decipher.setAuthTag(buffer)`", + "type": "method", + "name": "setAuthTag", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17825", + "description": "This method now throws if the GCM tag length is invalid." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9398", + "description": "This method now returns a reference to `decipher`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher} for method chaining.", + "name": "return", + "type": "Decipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAuthTag() method is used to pass in the\nreceived authentication tag. If no tag is provided, or if the cipher text\nhas been tampered with, decipher.final() will throw, indicating that the\ncipher text should be discarded due to failed authentication. If the tag length\nis invalid according to NIST SP 800-38D or does not match the value of the\nauthTagLength option, decipher.setAuthTag() will throw an error.

      \n

      The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes.\ndecipher.setAuthTag() can only be called once.

      " + }, + { + "textRaw": "`decipher.setAutoPadding([autoPadding])`", + "type": "method", + "name": "setAutoPadding", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher} for method chaining.", + "name": "return", + "type": "Decipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`autoPadding` {boolean} **Default:** `true`", + "name": "autoPadding", + "type": "boolean", + "default": "`true`" + } + ] + } + ], + "desc": "

      When data has been encrypted without standard block padding, calling\ndecipher.setAutoPadding(false) will disable automatic padding to prevent\ndecipher.final() from checking for and removing padding.

      \n

      Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.

      \n

      The decipher.setAutoPadding() method must be called before\ndecipher.final().

      " + }, + { + "textRaw": "`decipher.update(data[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Updates the decipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then inputEncoding is ignored.

      \n

      The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.

      \n

      The decipher.update() method can be called multiple times with new data until\ndecipher.final() is called. Calling decipher.update() after\ndecipher.final() will result in an error being thrown.

      " + } + ] + }, + { + "textRaw": "Class: `DiffieHellman`", + "type": "class", + "name": "DiffieHellman", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "desc": "

      The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.

      \n

      Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.

      \n
      const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
      ", + "methods": [ + { + "textRaw": "`diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "computeSecret", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`otherPublicKey` {string | Buffer | TypedArray | DataView}", + "name": "otherPublicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of an `otherPublicKey` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of an `otherPublicKey` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified inputEncoding, and secret is\nencoded using specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.generateKeys([encoding])`", + "type": "method", + "name": "generateKeys", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party.\nIf encoding is provided a string is returned; otherwise a\nBuffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getGenerator([encoding])`", + "type": "method", + "name": "getGenerator", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getPrime([encoding])`", + "type": "method", + "name": "getPrime", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getPrivateKey([encoding])`", + "type": "method", + "name": "getPrivateKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getPublicKey([encoding])`", + "type": "method", + "name": "getPublicKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.setPrivateKey(privateKey[, encoding])`", + "type": "method", + "name": "setPrivateKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`privateKey` {string | Buffer | TypedArray | DataView}", + "name": "privateKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `privateKey` string." + } + ] + } + ], + "desc": "

      Sets the Diffie-Hellman private key. If the encoding argument is provided,\nprivateKey is expected\nto be a string. If no encoding is provided, privateKey is expected\nto be a Buffer, TypedArray, or DataView.

      " + }, + { + "textRaw": "`diffieHellman.setPublicKey(publicKey[, encoding])`", + "type": "method", + "name": "setPublicKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`publicKey` {string | Buffer | TypedArray | DataView}", + "name": "publicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `publicKey` string." + } + ] + } + ], + "desc": "

      Sets the Diffie-Hellman public key. If the encoding argument is provided,\npublicKey is expected\nto be a string. If no encoding is provided, publicKey is expected\nto be a Buffer, TypedArray, or DataView.

      " + } + ], + "properties": [ + { + "textRaw": "`diffieHellman.verifyError`", + "name": "verifyError", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [] + }, + "desc": "

      A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.

      \n

      The following values are valid for this property (as defined in constants\nmodule):

      \n
        \n
      • DH_CHECK_P_NOT_SAFE_PRIME
      • \n
      • DH_CHECK_P_NOT_PRIME
      • \n
      • DH_UNABLE_TO_CHECK_GENERATOR
      • \n
      • DH_NOT_SUITABLE_GENERATOR
      • \n
      " + } + ] + }, + { + "textRaw": "Class: `DiffieHellmanGroup`", + "type": "class", + "name": "DiffieHellmanGroup", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "desc": "

      The DiffieHellmanGroup class takes a well-known modp group as its argument but\notherwise works the same as DiffieHellman.

      \n
      const name = 'modp1';\nconst dh = crypto.createDiffieHellmanGroup(name);\n
      \n

      name is taken from RFC 2412 (modp1 and 2) and RFC 3526:

      \n
      $ perl -ne 'print \"$1\\n\" if /\"(modp\\d+)\"/' src/node_crypto_groups.h\nmodp1  #  768 bits\nmodp2  # 1024 bits\nmodp5  # 1536 bits\nmodp14 # 2048 bits\nmodp15 # etc.\nmodp16\nmodp17\nmodp18\n
      " + }, + { + "textRaw": "Class: `ECDH`", + "type": "class", + "name": "ECDH", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "desc": "

      The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.

      \n

      Instances of the ECDH class can be created using the\ncrypto.createECDH() function.

      \n
      const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n
      ", + "classMethods": [ + { + "textRaw": "Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])`", + "type": "classMethod", + "name": "convertKey", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`curve` {string}", + "name": "curve", + "type": "string" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `key` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `key` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + }, + { + "textRaw": "`format` {string} **Default:** `'uncompressed'`", + "name": "format", + "type": "string", + "default": "`'uncompressed'`" + } + ] + } + ], + "desc": "

      Converts the EC Diffie-Hellman public key specified by key and curve to the\nformat specified by format. The format argument specifies point encoding\nand can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is\ninterpreted using the specified inputEncoding, and the returned key is encoded\nusing the specified outputEncoding.

      \n

      Use crypto.getCurves() to obtain a list of available curve names.\nOn recent OpenSSL releases, openssl ecparam -list_curves will also display\nthe name and description of each available elliptic curve.

      \n

      If format is not specified the point will be returned in 'uncompressed'\nformat.

      \n

      If the inputEncoding is not provided, key is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      Example (uncompressing a key):

      \n
      const { createECDH, ECDH } = require('crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n                                        'secp256k1',\n                                        'hex',\n                                        'hex',\n                                        'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
      " + } + ], + "methods": [ + { + "textRaw": "`ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "computeSecret", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`" + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16849", + "description": "Changed error format to better support invalid public key error" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`otherPublicKey` {string | Buffer | TypedArray | DataView}", + "name": "otherPublicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `otherPublicKey` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `otherPublicKey` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified inputEncoding, and the returned secret\nis encoded using the specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer, TypedArray, or\nDataView.

      \n

      If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.

      \n

      ecdh.computeSecret will throw an\nERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey\nlies outside of the elliptic curve. Since otherPublicKey is\nusually supplied from a remote user over an insecure network,\nbe sure to handle this exception accordingly.

      " + }, + { + "textRaw": "`ecdh.generateKeys([encoding[, format]])`", + "type": "method", + "name": "generateKeys", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + }, + { + "textRaw": "`format` {string} **Default:** `'uncompressed'`", + "name": "format", + "type": "string", + "default": "`'uncompressed'`" + } + ] + } + ], + "desc": "

      Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format and encoding. This key should be\ntransferred to the other party.

      \n

      The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified, the point will be returned in\n'uncompressed' format.

      \n

      If encoding is provided a string is returned; otherwise a Buffer\nis returned.

      " + }, + { + "textRaw": "`ecdh.getPrivateKey([encoding])`", + "type": "method", + "name": "getPrivateKey", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.", + "name": "return", + "type": "Buffer | string", + "desc": "The EC Diffie-Hellman in the specified `encoding`." + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

      " + }, + { + "textRaw": "`ecdh.getPublicKey([encoding][, format])`", + "type": "method", + "name": "getPublicKey", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified `encoding` and `format`.", + "name": "return", + "type": "Buffer | string", + "desc": "The EC Diffie-Hellman public key in the specified `encoding` and `format`." + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + }, + { + "textRaw": "`format` {string} **Default:** `'uncompressed'`", + "name": "format", + "type": "string", + "default": "`'uncompressed'`" + } + ] + } + ], + "desc": "

      The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified the point will be returned in\n'uncompressed' format.

      \n

      If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

      " + }, + { + "textRaw": "`ecdh.setPrivateKey(privateKey[, encoding])`", + "type": "method", + "name": "setPrivateKey", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`privateKey` {string | Buffer | TypedArray | DataView}", + "name": "privateKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `privateKey` string." + } + ] + } + ], + "desc": "

      Sets the EC Diffie-Hellman private key.\nIf encoding is provided, privateKey is expected\nto be a string; otherwise privateKey is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      If privateKey is not valid for the curve specified when the ECDH object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH object.

      " + }, + { + "textRaw": "`ecdh.setPublicKey(publicKey[, encoding])`", + "type": "method", + "name": "setPublicKey", + "meta": { + "added": [ + "v0.11.14" + ], + "deprecated": [ + "v5.2.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "signatures": [ + { + "params": [ + { + "textRaw": "`publicKey` {string | Buffer | TypedArray | DataView}", + "name": "publicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `publicKey` string." + } + ] + } + ], + "desc": "

      Sets the EC Diffie-Hellman public key.\nIf encoding is provided publicKey is expected to\nbe a string; otherwise a Buffer, TypedArray, or DataView is expected.

      \n

      There is not normally a reason to call this method because ECDH\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys() or\necdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method\nattempts to generate the public point/key associated with the private key being\nset.

      \n

      Example (obtaining a shared secret):

      \n
      const crypto = require('crypto');\nconst alice = crypto.createECDH('secp256k1');\nconst bob = crypto.createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n  crypto.createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
      " + } + ] + }, + { + "textRaw": "Class: `Hash`", + "type": "class", + "name": "Hash", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "desc": "\n

      The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where data is written\nto produce a computed hash digest on the readable side, or
      • \n
      • Using the hash.update() and hash.digest() methods to produce the\ncomputed hash.
      • \n
      \n

      The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.

      \n

      Example: Using Hash objects as streams:

      \n
      const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = hash.read();\n  if (data) {\n    console.log(data.toString('hex'));\n    // Prints:\n    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n  }\n});\n\nhash.write('some data to hash');\nhash.end();\n
      \n

      Example: Using Hash and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hash).pipe(process.stdout);\n
      \n

      Example: Using the hash.update() and hash.digest() methods:

      \n
      const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
      ", + "methods": [ + { + "textRaw": "`hash.copy([options])`", + "type": "method", + "name": "copy", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Hash}", + "name": "return", + "type": "Hash" + }, + "params": [ + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates a new Hash object that contains a deep copy of the internal state\nof the current Hash object.

      \n

      The optional options argument controls stream behavior. For XOF hash\nfunctions such as 'shake256', the outputLength option can be used to\nspecify the desired output length in bytes.

      \n

      An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.

      \n
      // Calculate a rolling hash.\nconst crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n
      " + }, + { + "textRaw": "`hash.digest([encoding])`", + "type": "method", + "name": "digest", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method).\nIf encoding is provided a string will be returned; otherwise\na Buffer is returned.

      \n

      The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.

      " + }, + { + "textRaw": "`hash.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the hash content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + } + ] + }, + { + "textRaw": "Class: `Hmac`", + "type": "class", + "name": "Hmac", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "desc": "\n

      The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where data is written\nto produce a computed HMAC digest on the readable side, or
      • \n
      • Using the hmac.update() and hmac.digest() methods to produce the\ncomputed HMAC digest.
      • \n
      \n

      The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.

      \n

      Example: Using Hmac objects as streams:

      \n
      const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = hmac.read();\n  if (data) {\n    console.log(data.toString('hex'));\n    // Prints:\n    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n  }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
      \n

      Example: Using Hmac and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hmac).pipe(process.stdout);\n
      \n

      Example: Using the hmac.update() and hmac.digest() methods:

      \n
      const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
      ", + "methods": [ + { + "textRaw": "`hmac.digest([encoding])`", + "type": "method", + "name": "digest", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Calculates the HMAC digest of all of the data passed using hmac.update().\nIf encoding is\nprovided a string is returned; otherwise a Buffer is returned;

      \n

      The Hmac object can not be used again after hmac.digest() has been\ncalled. Multiple calls to hmac.digest() will result in an error being thrown.

      " + }, + { + "textRaw": "`hmac.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the Hmac content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + } + ] + }, + { + "textRaw": "Class: `KeyObject`", + "type": "class", + "name": "KeyObject", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33360", + "description": "Instances of this class can now be passed to worker threads using `postMessage`." + }, + { + "version": "v11.13.0", + "pr-url": "https://github.com/nodejs/node/pull/26438", + "description": "This class is now exported." + } + ] + }, + "desc": "

      Node.js uses a KeyObject class to represent a symmetric or asymmetric key,\nand each kind of key exposes different functions. The\ncrypto.createSecretKey(), crypto.createPublicKey() and\ncrypto.createPrivateKey() methods are used to create KeyObject\ninstances. KeyObject objects are not to be created directly using the new\nkeyword.

      \n

      Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.

      \n

      KeyObject instances can be passed to other threads via postMessage().\nThe receiver obtains a cloned KeyObject, and the KeyObject does not need to\nbe listed in the transferList argument.

      ", + "properties": [ + { + "textRaw": "`asymmetricKeyType` {string}", + "type": "string", + "name": "asymmetricKeyType", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31178", + "description": "Added support for `'dh'`." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26960", + "description": "Added support for `'rsa-pss'`" + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26786", + "description": "This property now returns `undefined` for KeyObject instances of unrecognized type instead of aborting." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26774", + "description": "Added support for `'x25519'` and `'x448'`" + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26319", + "description": "Added support for `'ed25519'` and `'ed448'`." + } + ] + }, + "desc": "

      For asymmetric keys, this property represents the type of the key. Supported key\ntypes are:

      \n
        \n
      • 'rsa' (OID 1.2.840.113549.1.1.1)
      • \n
      • 'rsa-pss' (OID 1.2.840.113549.1.1.10)
      • \n
      • 'dsa' (OID 1.2.840.10040.4.1)
      • \n
      • 'ec' (OID 1.2.840.10045.2.1)
      • \n
      • 'x25519' (OID 1.3.101.110)
      • \n
      • 'x448' (OID 1.3.101.111)
      • \n
      • 'ed25519' (OID 1.3.101.112)
      • \n
      • 'ed448' (OID 1.3.101.113)
      • \n
      • 'dh' (OID 1.2.840.113549.1.3.1)
      • \n
      \n

      This property is undefined for unrecognized KeyObject types and symmetric\nkeys.

      " + }, + { + "textRaw": "`symmetricKeySize` {number}", + "type": "number", + "name": "symmetricKeySize", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.

      " + }, + { + "textRaw": "`type` {string}", + "type": "string", + "name": "type", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      Depending on the type of this KeyObject, this property is either\n'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys\nor 'private' for private (asymmetric) keys.

      " + } + ], + "methods": [ + { + "textRaw": "`keyObject.export([options])`", + "type": "method", + "name": "export", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string | Buffer}", + "name": "return", + "type": "string | Buffer" + }, + "params": [ + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object" + } + ] + } + ], + "desc": "

      For symmetric keys, this function allocates a Buffer containing the key\nmaterial and ignores any options.

      \n

      For asymmetric keys, the options parameter is used to determine the export\nformat.

      \n

      For public keys, the following encoding options can be used:

      \n
        \n
      • type: <string> Must be one of 'pkcs1' (RSA only) or 'spki'.
      • \n
      • format: <string> Must be 'pem' or 'der'.
      • \n
      \n

      For private keys, the following encoding options can be used:

      \n
        \n
      • type: <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or\n'sec1' (EC only).
      • \n
      • format: <string> Must be 'pem' or 'der'.
      • \n
      • cipher: <string> If specified, the private key will be encrypted with\n the given cipher and passphrase using PKCS#5 v2.0 password based\nencryption.
      • \n
      • passphrase: <string> | <Buffer> The passphrase to use for encryption, see\ncipher.
      • \n
      \n

      When PEM encoding was selected, the result will be a string, otherwise it will\nbe a buffer containing the data encoded as DER.

      \n

      PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of\nthe cipher and format options. The PKCS#8 type can be used with any\nformat to encrypt any key algorithm (RSA, EC, or DH) by specifying a\ncipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher\nwhen the PEM format is used. For maximum compatibility, use PKCS#8 for\nencrypted private keys. Since PKCS#8 defines its own\nencryption mechanism, PEM-level encryption is not supported when encrypting\na PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for\nPKCS#1 and SEC1 encryption.

      " + } + ] + }, + { + "textRaw": "Class: `Sign`", + "type": "class", + "name": "Sign", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "desc": "\n

      The Sign class is a utility for generating signatures. It can be used in one\nof two ways:

      \n
        \n
      • As a writable stream, where data to be signed is written and the\nsign.sign() method is used to generate and return the signature, or
      • \n
      • Using the sign.update() and sign.sign() methods to produce the\nsignature.
      • \n
      \n

      The crypto.createSign() method is used to create Sign instances. The\nargument is the string name of the hash function to use. Sign objects are not\nto be created directly using the new keyword.

      \n

      Example: Using Sign and Verify objects as streams:

      \n
      const crypto = require('crypto');\n\nconst { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {\n  namedCurve: 'sect239k1'\n});\n\nconst sign = crypto.createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = crypto.createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n
      \n

      Example: Using the sign.update() and verify.update() methods:

      \n
      const crypto = require('crypto');\n\nconst { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {\n  modulusLength: 2048,\n});\n\nconst sign = crypto.createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = crypto.createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n
      ", + "methods": [ + { + "textRaw": "`sign.sign(privateKey[, outputEncoding])`", + "type": "method", + "name": "sign", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26960", + "description": "This function now supports RSA-PSS keys." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11705", + "description": "Support for RSASSA-PSS and additional options was added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`privateKey` {Object | string | Buffer | KeyObject}", + "name": "privateKey", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`dsaEncoding` {string}", + "name": "dsaEncoding", + "type": "string" + }, + { + "textRaw": "`padding` {integer}", + "name": "padding", + "type": "integer" + }, + { + "textRaw": "`saltLength` {integer}", + "name": "saltLength", + "type": "integer" + } + ] + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Calculates the signature on all the data passed through using either\nsign.update() or sign.write().

      \n

      If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the following additional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.

        \n
      • \n
      \n

      If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.

      \n

      The Sign object can not be again used after sign.sign() method has been\ncalled. Multiple calls to sign.sign() will result in an error being thrown.

      " + }, + { + "textRaw": "`sign.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the Sign content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + } + ] + }, + { + "textRaw": "Class: `Verify`", + "type": "class", + "name": "Verify", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "desc": "\n

      The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:

      \n
        \n
      • As a writable stream where written data is used to validate against the\nsupplied signature, or
      • \n
      • Using the verify.update() and verify.verify() methods to verify\nthe signature.
      • \n
      \n

      The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.

      \n

      See Sign for examples.

      ", + "methods": [ + { + "textRaw": "`verify.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the Verify content with the given data, the encoding of which\nis given in inputEncoding.\nIf inputEncoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + }, + { + "textRaw": "`verify.verify(object, signature[, signatureEncoding])`", + "type": "method", + "name": "verify", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26960", + "description": "This function now supports RSA-PSS keys." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25217", + "description": "The key can now be a private key." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11705", + "description": "Support for RSASSA-PSS and additional options was added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key.", + "name": "return", + "type": "boolean", + "desc": "`true` or `false` depending on the validity of the signature for the data and public key." + }, + "params": [ + { + "textRaw": "`object` {Object | string | Buffer | KeyObject}", + "name": "object", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`dsaEncoding` {string}", + "name": "dsaEncoding", + "type": "string" + }, + { + "textRaw": "`padding` {integer}", + "name": "padding", + "type": "integer" + }, + { + "textRaw": "`saltLength` {integer}", + "name": "saltLength", + "type": "integer" + } + ] + }, + { + "textRaw": "`signature` {string | Buffer | TypedArray | DataView}", + "name": "signature", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`signatureEncoding` {string} The [encoding][] of the `signature` string.", + "name": "signatureEncoding", + "type": "string", + "desc": "The [encoding][] of the `signature` string." + } + ] + } + ], + "desc": "

      Verifies the provided data using the given object and signature.

      \n

      If object is not a KeyObject, this function behaves as if\nobject had been passed to crypto.createPublicKey(). If it is an\nobject, the following additional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to verify the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be\ndetermined automatically.

        \n
      • \n
      \n

      The signature argument is the previously calculated signature for the data, in\nthe signatureEncoding.\nIf a signatureEncoding is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      The verify object can not be used again after verify.verify() has been\ncalled. Multiple calls to verify.verify() will result in an error being\nthrown.

      \n

      Because public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

      " + } + ] + } + ], + "type": "module", + "displayName": "Crypto" + }, + { + "textRaw": "DNS", + "name": "dns", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/dns.js

      \n

      The dns module enables name resolution. For example, use it to look up IP\naddresses of host names.

      \n

      Although named for the Domain Name System (DNS), it does not always use the\nDNS protocol for lookups. dns.lookup() uses the operating system\nfacilities to perform name resolution. It may not need to perform any network\ncommunication. To perform name resolution the way other applications on the same\nsystem do, use dns.lookup().

      \n
      const dns = require('dns');\n\ndns.lookup('example.org', (err, address, family) => {\n  console.log('address: %j family: IPv%s', address, family);\n});\n// address: \"93.184.216.34\" family: IPv4\n
      \n

      All other functions in the dns module connect to an actual DNS server to\nperform name resolution. They will always use the network to perform DNS\nqueries. These functions do not use the same set of configuration files used by\ndns.lookup() (e.g. /etc/hosts). Use these functions to always perform\nDNS queries, bypassing other name-resolution facilities.

      \n
      const dns = require('dns');\n\ndns.resolve4('archive.org', (err, addresses) => {\n  if (err) throw err;\n\n  console.log(`addresses: ${JSON.stringify(addresses)}`);\n\n  addresses.forEach((a) => {\n    dns.reverse(a, (err, hostnames) => {\n      if (err) {\n        throw err;\n      }\n      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);\n    });\n  });\n});\n
      \n

      See the Implementation considerations section for more information.

      ", + "classes": [ + { + "textRaw": "Class: `dns.Resolver`", + "type": "class", + "name": "dns.Resolver", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "desc": "

      An independent resolver for DNS requests.

      \n

      Creating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:

      \n
      const { Resolver } = require('dns');\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org', (err, addresses) => {\n  // ...\n});\n
      \n

      The following methods from the dns module are available:

      \n", + "methods": [ + { + "textRaw": "`Resolver([options])`", + "type": "method", + "name": "Resolver", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [ + { + "version": "v12.18.3", + "pr-url": "https://github.com/nodejs/node/pull/33472", + "description": "The constructor now accepts an `options` object. The single supported option is `timeout`." + } + ] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Create a new resolver.

      \n
        \n
      • options <Object>\n
          \n
        • timeout <integer> Query timeout in milliseconds, or -1 to use the\ndefault timeout.
        • \n
        \n
      • \n
      " + }, + { + "textRaw": "`resolver.cancel()`", + "type": "method", + "name": "cancel", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Cancel all outstanding DNS queries made by this resolver. The corresponding\ncallbacks will be called with an error with code ECANCELLED.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`dns.getServers()`", + "type": "method", + "name": "getServers", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array of IP address strings, formatted according to RFC 5952,\nthat are currently configured for DNS resolution. A string will include a port\nsection if a custom port is used.

      \n\n
      [\n  '4.4.4.4',\n  '2001:4860:4860::8888',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]\n
      " + }, + { + "textRaw": "`dns.lookup(hostname[, options], callback)`", + "type": "method", + "name": "lookup", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v8.5.0", + "pr-url": "https://github.com/nodejs/node/pull/14731", + "description": "The `verbatim` option is supported now." + }, + { + "version": "v1.2.0", + "pr-url": "https://github.com/nodejs/node/pull/744", + "description": "The `all` option is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`options` {integer | Object}", + "name": "options", + "type": "integer | Object", + "options": [ + { + "textRaw": "`family` {integer} The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:** `0`.", + "name": "family", + "type": "integer", + "default": "`0`", + "desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned." + }, + { + "textRaw": "`hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values.", + "name": "hints", + "type": "number", + "desc": "One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values." + }, + { + "textRaw": "`all` {boolean} When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. **Default:** `false`.", + "name": "all", + "type": "boolean", + "default": "`false`", + "desc": "When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address." + }, + { + "textRaw": "`verbatim` {boolean} When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. **Default:** currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`.", + "name": "verbatim", + "type": "boolean", + "default": "currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`", + "desc": "When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`address` {string} A string representation of an IPv4 or IPv6 address.", + "name": "address", + "type": "string", + "desc": "A string representation of an IPv4 or IPv6 address." + }, + { + "textRaw": "`family` {integer} `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a bug in the name resolution service used by the operating system.", + "name": "family", + "type": "integer", + "desc": "`4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a bug in the name resolution service used by the operating system." + } + ] + } + ] + } + ], + "desc": "

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. All option properties are optional. If options is an\ninteger, then it must be 4 or 6 – if options is not provided, then IPv4\nand IPv6 addresses are both returned if found.

      \n

      With the all option set to true, the arguments for callback change to\n(err, addresses), with addresses being an array of objects with the\nproperties address and family.

      \n

      On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOTFOUND' not only when\nthe host name does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.

      \n

      dns.lookup() does not necessarily have anything to do with the DNS protocol.\nThe implementation uses an operating system facility that can associate names\nwith addresses, and vice versa. This implementation can have subtle but\nimportant consequences on the behavior of any Node.js program. Please take some\ntime to consult the Implementation considerations section before using\ndns.lookup().

      \n

      Example usage:

      \n
      const dns = require('dns');\nconst options = {\n  family: 6,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\ndns.lookup('example.com', options, (err, address, family) =>\n  console.log('address: %j family: IPv%s', address, family));\n// address: \"2606:2800:220:1:248:1893:25c8:1946\" family: IPv6\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndns.lookup('example.com', options, (err, addresses) =>\n  console.log('addresses: %j', addresses));\n// addresses: [{\"address\":\"2606:2800:220:1:248:1893:25c8:1946\",\"family\":6}]\n
      \n

      If this method is invoked as its util.promisify()ed version, and all\nis not set to true, it returns a Promise for an Object with address and\nfamily properties.

      ", + "modules": [ + { + "textRaw": "Supported getaddrinfo flags", + "name": "supported_getaddrinfo_flags", + "meta": { + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32183", + "description": "Added support for the `dns.ALL` flag." + } + ] + }, + "desc": "

      The following flags can be passed as hints to dns.lookup().

      \n
        \n
      • dns.ADDRCONFIG: Limits returned address types to the types of non-loopback\naddresses configured on the system. For example, IPv4 addresses are only\nreturned if the current system has at least one IPv4 address configured.
      • \n
      • dns.V4MAPPED: If the IPv6 family was specified, but no IPv6 addresses were\nfound, then return IPv4 mapped IPv6 addresses. It is not supported\non some operating systems (e.g FreeBSD 10.1).
      • \n
      • dns.ALL: If dns.V4MAPPED is specified, return resolved IPv6 addresses as\nwell as IPv4 mapped IPv6 addresses.
      • \n
      ", + "type": "module", + "displayName": "Supported getaddrinfo flags" + } + ] + }, + { + "textRaw": "`dns.lookupService(address, port, callback)`", + "type": "method", + "name": "lookupService", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`hostname` {string} e.g. `example.com`", + "name": "hostname", + "type": "string", + "desc": "e.g. `example.com`" + }, + { + "textRaw": "`service` {string} e.g. `http`", + "name": "service", + "type": "string", + "desc": "e.g. `http`" + } + ] + } + ] + } + ], + "desc": "

      Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.

      \n

      If address is not a valid IP address, a TypeError will be thrown.\nThe port will be coerced to a number. If it is not a legal port, a TypeError\nwill be thrown.

      \n

      On an error, err is an Error object, where err.code is the error code.

      \n
      const dns = require('dns');\ndns.lookupService('127.0.0.1', 22, (err, hostname, service) => {\n  console.log(hostname, service);\n  // Prints: localhost ssh\n});\n
      \n

      If this method is invoked as its util.promisify()ed version, it returns a\nPromise for an Object with hostname and service properties.

      " + }, + { + "textRaw": "`dns.resolve(hostname[, rrtype], callback)`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`rrtype` {string} Resource record type. **Default:** `'A'`.", + "name": "rrtype", + "type": "string", + "default": "`'A'`", + "desc": "Resource record type." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`records` {string[] | Object[] | Object}", + "name": "records", + "type": "string[] | Object[] | Object" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array\nof the resource records. The callback function has arguments\n(err, records). When successful, records will be an array of resource\nrecords. The type and structure of individual results varies based on rrtype:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dns.resolve4()
      'AAAA'IPv6 addresses<string>dns.resolve6()
      'ANY'any records<Object>dns.resolveAny()
      'CNAME'canonical name records<string>dns.resolveCname()
      'MX'mail exchange records<Object>dns.resolveMx()
      'NAPTR'name authority pointer records<Object>dns.resolveNaptr()
      'NS'name server records<string>dns.resolveNs()
      'PTR'pointer records<string>dns.resolvePtr()
      'SOA'start of authority records<Object>dns.resolveSoa()
      'SRV'service records<Object>dns.resolveSrv()
      'TXT'text records<string[]>dns.resolveTxt()
      \n

      On error, err is an Error object, where err.code is one of the\nDNS error codes.

      " + }, + { + "textRaw": "`dns.resolve4(hostname[, options], callback)`", + "type": "method", + "name": "resolve4", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9296", + "description": "This method now supports passing `options`, specifically `options.ttl`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[] | Object[]}", + "name": "addresses", + "type": "string[] | Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a IPv4 addresses (A records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      " + }, + { + "textRaw": "`dns.resolve6(hostname[, options], callback)`", + "type": "method", + "name": "resolve6", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9296", + "description": "This method now supports passing `options`, specifically `options.ttl`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[] | Object[]}", + "name": "addresses", + "type": "string[] | Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a IPv6 addresses (AAAA records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv6 addresses.

      " + }, + { + "textRaw": "`dns.resolveAny(hostname, callback)`", + "type": "method", + "name": "resolveAny", + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`ret` {Object[]}", + "name": "ret", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve all records (also known as ANY or * query).\nThe ret argument passed to the callback function will be an array containing\nvarious types of records. Each object has a property type that indicates the\ntype of the current record. And depending on the type, additional properties\nwill be present on the object:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dns.resolveMx()
      'NAPTR'Refer to dns.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dns.resolveSoa()
      'SRV'Refer to dns.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      \n

      Here is an example of the ret object passed to the callback:

      \n\n
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },\n  { type: 'CNAME', value: 'example.com' },\n  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },\n  { type: 'NS', value: 'ns1.example.com' },\n  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },\n  { type: 'SOA',\n    nsname: 'ns1.example.com',\n    hostmaster: 'admin.example.com',\n    serial: 156696742,\n    refresh: 900,\n    retry: 900,\n    expire: 1800,\n    minttl: 60 } ]\n
      \n

      DNS server operators may choose not to respond to ANY\nqueries. It may be better to call individual methods like dns.resolve4(),\ndns.resolveMx(), and so on. For more details, see RFC 8482.

      " + }, + { + "textRaw": "`dns.resolveCname(hostname, callback)`", + "type": "method", + "name": "resolveCname", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[]}", + "name": "addresses", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve CNAME records for the hostname. The\naddresses argument passed to the callback function\nwill contain an array of canonical name records available for the hostname\n(e.g. ['bar.example.com']).

      " + }, + { + "textRaw": "`dns.resolveMx(hostname, callback)`", + "type": "method", + "name": "resolveMx", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {Object[]}", + "name": "addresses", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve mail exchange records (MX records) for the\nhostname. The addresses argument passed to the callback function will\ncontain an array of objects containing both a priority and exchange\nproperty (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).

      " + }, + { + "textRaw": "`dns.resolveNaptr(hostname, callback)`", + "type": "method", + "name": "resolveNaptr", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {Object[]}", + "name": "addresses", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve regular expression based records (NAPTR\nrecords) for the hostname. The addresses argument passed to the callback\nfunction will contain an array of objects with the following properties:

      \n
        \n
      • flags
      • \n
      • service
      • \n
      • regexp
      • \n
      • replacement
      • \n
      • order
      • \n
      • preference
      • \n
      \n\n
      {\n  flags: 's',\n  service: 'SIP+D2U',\n  regexp: '',\n  replacement: '_sip._udp.example.com',\n  order: 30,\n  preference: 100\n}\n
      " + }, + { + "textRaw": "`dns.resolveNs(hostname, callback)`", + "type": "method", + "name": "resolveNs", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[]}", + "name": "addresses", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve name server records (NS records) for the\nhostname. The addresses argument passed to the callback function will\ncontain an array of name server records available for hostname\n(e.g. ['ns1.example.com', 'ns2.example.com']).

      " + }, + { + "textRaw": "`dns.resolvePtr(hostname, callback)`", + "type": "method", + "name": "resolvePtr", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[]}", + "name": "addresses", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve pointer records (PTR records) for the\nhostname. The addresses argument passed to the callback function will\nbe an array of strings containing the reply records.

      " + }, + { + "textRaw": "`dns.resolveSoa(hostname, callback)`", + "type": "method", + "name": "resolveSoa", + "meta": { + "added": [ + "v0.11.10" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`address` {Object}", + "name": "address", + "type": "Object" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. The address argument passed to the callback function will\nbe an object with the following properties:

      \n
        \n
      • nsname
      • \n
      • hostmaster
      • \n
      • serial
      • \n
      • refresh
      • \n
      • retry
      • \n
      • expire
      • \n
      • minttl
      • \n
      \n\n
      {\n  nsname: 'ns.example.com',\n  hostmaster: 'root.example.com',\n  serial: 2013101809,\n  refresh: 10000,\n  retry: 2400,\n  expire: 604800,\n  minttl: 3600\n}\n
      " + }, + { + "textRaw": "`dns.resolveSrv(hostname, callback)`", + "type": "method", + "name": "resolveSrv", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {Object[]}", + "name": "addresses", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve service records (SRV records) for the\nhostname. The addresses argument passed to the callback function will\nbe an array of objects with the following properties:

      \n
        \n
      • priority
      • \n
      • weight
      • \n
      • port
      • \n
      • name
      • \n
      \n\n
      {\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
      " + }, + { + "textRaw": "`dns.resolveTxt(hostname, callback)`", + "type": "method", + "name": "resolveTxt", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`records` <string[][]>", + "name": "records", + "desc": "<string[][]>" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. The records argument passed to the callback function is a\ntwo-dimensional array of the text records available for hostname (e.g.\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.

      " + }, + { + "textRaw": "`dns.reverse(ip, callback)`", + "type": "method", + "name": "reverse", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ip` {string}", + "name": "ip", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`hostnames` {string[]}", + "name": "hostnames", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.

      \n

      On error, err is an Error object, where err.code is\none of the DNS error codes.

      " + }, + { + "textRaw": "`dns.setServers(servers)`", + "type": "method", + "name": "setServers", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`servers` {string[]} array of [RFC 5952][] formatted addresses", + "name": "servers", + "type": "string[]", + "desc": "array of [RFC 5952][] formatted addresses" + } + ] + } + ], + "desc": "

      Sets the IP address and port of servers to be used when performing DNS\nresolution. The servers argument is an array of RFC 5952 formatted\naddresses. If the port is the IANA default DNS port (53) it can be omitted.

      \n
      dns.setServers([\n  '4.4.4.4',\n  '[2001:4860:4860::8888]',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]);\n
      \n

      An error will be thrown if an invalid address is provided.

      \n

      The dns.setServers() method must not be called while a DNS query is in\nprogress.

      \n

      The dns.setServers() method affects only dns.resolve(),\ndns.resolve*() and dns.reverse() (and specifically not\ndns.lookup()).

      \n

      This method works much like\nresolve.conf.\nThat is, if attempting to resolve with the first server provided results in a\nNOTFOUND error, the resolve() method will not attempt to resolve with\nsubsequent servers provided. Fallback DNS servers will only be used if the\nearlier ones time out or result in some other error.

      " + } + ], + "modules": [ + { + "textRaw": "DNS promises API", + "name": "dns_promises_api", + "desc": "

      The dns.promises API provides an alternative set of asynchronous DNS methods\nthat return Promise objects rather than using callbacks. The API is accessible\nvia require('dns').promises.

      ", + "classes": [ + { + "textRaw": "Class: `dnsPromises.Resolver`", + "type": "class", + "name": "dnsPromises.Resolver", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "desc": "

      An independent resolver for DNS requests.

      \n

      Creating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:

      \n
      const { Resolver } = require('dns').promises;\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org').then((addresses) => {\n  // ...\n});\n\n// Alternatively, the same code can be written using async-await style.\n(async function() {\n  const addresses = await resolver.resolve4('example.org');\n})();\n
      \n

      The following methods from the dnsPromises API are available:

      \n" + } + ], + "methods": [ + { + "textRaw": "`dnsPromises.getServers()`", + "type": "method", + "name": "getServers", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array of IP address strings, formatted according to RFC 5952,\nthat are currently configured for DNS resolution. A string will include a port\nsection if a custom port is used.

      \n\n
      [\n  '4.4.4.4',\n  '2001:4860:4860::8888',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]\n
      " + }, + { + "textRaw": "`dnsPromises.lookup(hostname[, options])`", + "type": "method", + "name": "lookup", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`options` {integer | Object}", + "name": "options", + "type": "integer | Object", + "options": [ + { + "textRaw": "`family` {integer} The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:** `0`.", + "name": "family", + "type": "integer", + "default": "`0`", + "desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned." + }, + { + "textRaw": "`hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values.", + "name": "hints", + "type": "number", + "desc": "One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values." + }, + { + "textRaw": "`all` {boolean} When `true`, the `Promise` is resolved with all addresses in an array. Otherwise, returns a single address. **Default:** `false`.", + "name": "all", + "type": "boolean", + "default": "`false`", + "desc": "When `true`, the `Promise` is resolved with all addresses in an array. Otherwise, returns a single address." + }, + { + "textRaw": "`verbatim` {boolean} When `true`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. **Default:** currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`.", + "name": "verbatim", + "type": "boolean", + "default": "currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`", + "desc": "When `true`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses." + } + ] + } + ] + } + ], + "desc": "

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. All option properties are optional. If options is an\ninteger, then it must be 4 or 6 – if options is not provided, then IPv4\nand IPv6 addresses are both returned if found.

      \n

      With the all option set to true, the Promise is resolved with addresses\nbeing an array of objects with the properties address and family.

      \n

      On error, the Promise is rejected with an Error object, where err.code\nis the error code.\nKeep in mind that err.code will be set to 'ENOTFOUND' not only when\nthe host name does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.

      \n

      dnsPromises.lookup() does not necessarily have anything to do with the DNS\nprotocol. The implementation uses an operating system facility that can\nassociate names with addresses, and vice versa. This implementation can have\nsubtle but important consequences on the behavior of any Node.js program. Please\ntake some time to consult the Implementation considerations section before\nusing dnsPromises.lookup().

      \n

      Example usage:

      \n
      const dns = require('dns');\nconst dnsPromises = dns.promises;\nconst options = {\n  family: 6,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\n\ndnsPromises.lookup('example.com', options).then((result) => {\n  console.log('address: %j family: IPv%s', result.address, result.family);\n  // address: \"2606:2800:220:1:248:1893:25c8:1946\" family: IPv6\n});\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndnsPromises.lookup('example.com', options).then((result) => {\n  console.log('addresses: %j', result);\n  // addresses: [{\"address\":\"2606:2800:220:1:248:1893:25c8:1946\",\"family\":6}]\n});\n
      " + }, + { + "textRaw": "`dnsPromises.lookupService(address, port)`", + "type": "method", + "name": "lookupService", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + } + ] + } + ], + "desc": "

      Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.

      \n

      If address is not a valid IP address, a TypeError will be thrown.\nThe port will be coerced to a number. If it is not a legal port, a TypeError\nwill be thrown.

      \n

      On error, the Promise is rejected with an Error object, where err.code\nis the error code.

      \n
      const dnsPromises = require('dns').promises;\ndnsPromises.lookupService('127.0.0.1', 22).then((result) => {\n  console.log(result.hostname, result.service);\n  // Prints: localhost ssh\n});\n
      " + }, + { + "textRaw": "`dnsPromises.resolve(hostname[, rrtype])`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`rrtype` {string} Resource record type. **Default:** `'A'`.", + "name": "rrtype", + "type": "string", + "default": "`'A'`", + "desc": "Resource record type." + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array\nof the resource records. When successful, the Promise is resolved with an\narray of resource records. The type and structure of individual results vary\nbased on rrtype:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dnsPromises.resolve4()
      'AAAA'IPv6 addresses<string>dnsPromises.resolve6()
      'ANY'any records<Object>dnsPromises.resolveAny()
      'CNAME'canonical name records<string>dnsPromises.resolveCname()
      'MX'mail exchange records<Object>dnsPromises.resolveMx()
      'NAPTR'name authority pointer records<Object>dnsPromises.resolveNaptr()
      'NS'name server records<string>dnsPromises.resolveNs()
      'PTR'pointer records<string>dnsPromises.resolvePtr()
      'SOA'start of authority records<Object>dnsPromises.resolveSoa()
      'SRV'service records<Object>dnsPromises.resolveSrv()
      'TXT'text records<string[]>dnsPromises.resolveTxt()
      \n

      On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.

      " + }, + { + "textRaw": "`dnsPromises.resolve4(hostname[, options])`", + "type": "method", + "name": "resolve4", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve IPv4 addresses (A records) for the\nhostname. On success, the Promise is resolved with an array of IPv4\naddresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      " + }, + { + "textRaw": "`dnsPromises.resolve6(hostname[, options])`", + "type": "method", + "name": "resolve6", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the\nhostname. On success, the Promise is resolved with an array of IPv6\naddresses.

      " + }, + { + "textRaw": "`dnsPromises.resolveAny(hostname)`", + "type": "method", + "name": "resolveAny", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve all records (also known as ANY or * query).\nOn success, the Promise is resolved with an array containing various types of\nrecords. Each object has a property type that indicates the type of the\ncurrent record. And depending on the type, additional properties will be\npresent on the object:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dnsPromises.resolveMx()
      'NAPTR'Refer to dnsPromises.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dnsPromises.resolveSoa()
      'SRV'Refer to dnsPromises.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      \n

      Here is an example of the result object:

      \n\n
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },\n  { type: 'CNAME', value: 'example.com' },\n  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },\n  { type: 'NS', value: 'ns1.example.com' },\n  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },\n  { type: 'SOA',\n    nsname: 'ns1.example.com',\n    hostmaster: 'admin.example.com',\n    serial: 156696742,\n    refresh: 900,\n    retry: 900,\n    expire: 1800,\n    minttl: 60 } ]\n
      " + }, + { + "textRaw": "`dnsPromises.resolveCname(hostname)`", + "type": "method", + "name": "resolveCname", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve CNAME records for the hostname. On success,\nthe Promise is resolved with an array of canonical name records available for\nthe hostname (e.g. ['bar.example.com']).

      " + }, + { + "textRaw": "`dnsPromises.resolveMx(hostname)`", + "type": "method", + "name": "resolveMx", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve mail exchange records (MX records) for the\nhostname. On success, the Promise is resolved with an array of objects\ncontaining both a priority and exchange property (e.g.\n[{priority: 10, exchange: 'mx.example.com'}, ...]).

      " + }, + { + "textRaw": "`dnsPromises.resolveNaptr(hostname)`", + "type": "method", + "name": "resolveNaptr", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve regular expression based records (NAPTR\nrecords) for the hostname. On success, the Promise is resolved with an array\nof objects with the following properties:

      \n
        \n
      • flags
      • \n
      • service
      • \n
      • regexp
      • \n
      • replacement
      • \n
      • order
      • \n
      • preference
      • \n
      \n\n
      {\n  flags: 's',\n  service: 'SIP+D2U',\n  regexp: '',\n  replacement: '_sip._udp.example.com',\n  order: 30,\n  preference: 100\n}\n
      " + }, + { + "textRaw": "`dnsPromises.resolveNs(hostname)`", + "type": "method", + "name": "resolveNs", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve name server records (NS records) for the\nhostname. On success, the Promise is resolved with an array of name server\nrecords available for hostname (e.g.\n['ns1.example.com', 'ns2.example.com']).

      " + }, + { + "textRaw": "`dnsPromises.resolvePtr(hostname)`", + "type": "method", + "name": "resolvePtr", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve pointer records (PTR records) for the\nhostname. On success, the Promise is resolved with an array of strings\ncontaining the reply records.

      " + }, + { + "textRaw": "`dnsPromises.resolveSoa(hostname)`", + "type": "method", + "name": "resolveSoa", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. On success, the Promise is resolved with an object with the\nfollowing properties:

      \n
        \n
      • nsname
      • \n
      • hostmaster
      • \n
      • serial
      • \n
      • refresh
      • \n
      • retry
      • \n
      • expire
      • \n
      • minttl
      • \n
      \n\n
      {\n  nsname: 'ns.example.com',\n  hostmaster: 'root.example.com',\n  serial: 2013101809,\n  refresh: 10000,\n  retry: 2400,\n  expire: 604800,\n  minttl: 3600\n}\n
      " + }, + { + "textRaw": "`dnsPromises.resolveSrv(hostname)`", + "type": "method", + "name": "resolveSrv", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve service records (SRV records) for the\nhostname. On success, the Promise is resolved with an array of objects with\nthe following properties:

      \n
        \n
      • priority
      • \n
      • weight
      • \n
      • port
      • \n
      • name
      • \n
      \n\n
      {\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
      " + }, + { + "textRaw": "`dnsPromises.resolveTxt(hostname)`", + "type": "method", + "name": "resolveTxt", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. On success, the Promise is resolved with a two-dimensional array\nof the text records available for hostname (e.g.\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.

      " + }, + { + "textRaw": "`dnsPromises.reverse(ip)`", + "type": "method", + "name": "reverse", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ip` {string}", + "name": "ip", + "type": "string" + } + ] + } + ], + "desc": "

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.

      \n

      On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.

      " + }, + { + "textRaw": "`dnsPromises.setServers(servers)`", + "type": "method", + "name": "setServers", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`servers` {string[]} array of [RFC 5952][] formatted addresses", + "name": "servers", + "type": "string[]", + "desc": "array of [RFC 5952][] formatted addresses" + } + ] + } + ], + "desc": "

      Sets the IP address and port of servers to be used when performing DNS\nresolution. The servers argument is an array of RFC 5952 formatted\naddresses. If the port is the IANA default DNS port (53) it can be omitted.

      \n
      dnsPromises.setServers([\n  '4.4.4.4',\n  '[2001:4860:4860::8888]',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]);\n
      \n

      An error will be thrown if an invalid address is provided.

      \n

      The dnsPromises.setServers() method must not be called while a DNS query is in\nprogress.

      \n

      This method works much like\nresolve.conf.\nThat is, if attempting to resolve with the first server provided results in a\nNOTFOUND error, the resolve() method will not attempt to resolve with\nsubsequent servers provided. Fallback DNS servers will only be used if the\nearlier ones time out or result in some other error.

      " + } + ], + "type": "module", + "displayName": "DNS promises API" + }, + { + "textRaw": "Error codes", + "name": "error_codes", + "desc": "

      Each DNS query can return one of the following error codes:

      \n
        \n
      • dns.NODATA: DNS server returned answer with no data.
      • \n
      • dns.FORMERR: DNS server claims query was misformatted.
      • \n
      • dns.SERVFAIL: DNS server returned general failure.
      • \n
      • dns.NOTFOUND: Domain name not found.
      • \n
      • dns.NOTIMP: DNS server does not implement requested operation.
      • \n
      • dns.REFUSED: DNS server refused query.
      • \n
      • dns.BADQUERY: Misformatted DNS query.
      • \n
      • dns.BADNAME: Misformatted host name.
      • \n
      • dns.BADFAMILY: Unsupported address family.
      • \n
      • dns.BADRESP: Misformatted DNS reply.
      • \n
      • dns.CONNREFUSED: Could not contact DNS servers.
      • \n
      • dns.TIMEOUT: Timeout while contacting DNS servers.
      • \n
      • dns.EOF: End of file.
      • \n
      • dns.FILE: Error reading file.
      • \n
      • dns.NOMEM: Out of memory.
      • \n
      • dns.DESTRUCTION: Channel is being destroyed.
      • \n
      • dns.BADSTR: Misformatted string.
      • \n
      • dns.BADFLAGS: Illegal flags specified.
      • \n
      • dns.NONAME: Given host name is not numeric.
      • \n
      • dns.BADHINTS: Illegal hints flags specified.
      • \n
      • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
      • \n
      • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
      • \n
      • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
      • \n
      • dns.CANCELLED: DNS query cancelled.
      • \n
      ", + "type": "module", + "displayName": "Error codes" + }, + { + "textRaw": "Implementation considerations", + "name": "implementation_considerations", + "desc": "

      Although dns.lookup() and the various dns.resolve*()/dns.reverse()\nfunctions have the same goal of associating a network name with a network\naddress (or vice versa), their behavior is quite different. These differences\ncan have subtle but significant consequences on the behavior of Node.js\nprograms.

      ", + "methods": [ + { + "textRaw": "`dns.lookup()`", + "type": "method", + "name": "lookup", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Under the hood, dns.lookup() uses the same operating system facilities\nas most other programs. For instance, dns.lookup() will almost always\nresolve a given name the same way as the ping command. On most POSIX-like\noperating systems, the behavior of the dns.lookup() function can be\nmodified by changing settings in nsswitch.conf(5) and/or resolv.conf(5),\nbut changing these files will change the behavior of all other\nprograms running on the same operating system.

      \n

      Though the call to dns.lookup() will be asynchronous from JavaScript's\nperspective, it is implemented as a synchronous call to getaddrinfo(3) that runs\non libuv's threadpool. This can have surprising negative performance\nimplications for some applications, see the UV_THREADPOOL_SIZE\ndocumentation for more information.

      \n

      Various networking APIs will call dns.lookup() internally to resolve\nhost names. If that is an issue, consider resolving the host name to an address\nusing dns.resolve() and using the address instead of a host name. Also, some\nnetworking APIs (such as socket.connect() and dgram.createSocket())\nallow the default resolver, dns.lookup(), to be replaced.

      " + } + ], + "modules": [ + { + "textRaw": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`", + "name": "`dns.resolve()`,_`dns.resolve*()`_and_`dns.reverse()`", + "desc": "

      These functions are implemented quite differently than dns.lookup(). They\ndo not use getaddrinfo(3) and they always perform a DNS query on the\nnetwork. This network communication is always done asynchronously, and does not\nuse libuv's threadpool.

      \n

      As a result, these functions cannot have the same negative impact on other\nprocessing that happens on libuv's threadpool that dns.lookup() can have.

      \n

      They do not use the same set of configuration files than what dns.lookup()\nuses. For instance, they do not use the configuration from /etc/hosts.

      ", + "type": "module", + "displayName": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`" + } + ], + "type": "module", + "displayName": "Implementation considerations" + } + ], + "type": "module", + "displayName": "DNS" + }, + { + "textRaw": "Domain", + "name": "domain", + "meta": { + "deprecated": [ + "v1.4.2" + ], + "changes": [ + { + "version": "v8.8.0", + "description": "Any `Promise`s created in VM contexts no longer have a `.domain` property. Their handlers are still executed in the proper domain, however, and `Promise`s created in the main context still possess a `.domain` property." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12489", + "description": "Handlers for `Promise`s are now invoked in the domain in which the first promise of a chain was created." + } + ] + }, + "introduced_in": "v0.10.0", + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Source Code: lib/domain.js

      \n

      This module is pending deprecation. Once a replacement API has been\nfinalized, this module will be fully deprecated. Most developers should\nnot have cause to use this module. Users who absolutely must have\nthe functionality that domains provide may rely on it for the time being\nbut should expect to have to migrate to a different solution\nin the future.

      \n

      Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an 'error' event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.

      ", + "miscs": [ + { + "textRaw": "Warning: Don't ignore errors!", + "name": "Warning: Don't ignore errors!", + "type": "misc", + "desc": "

      Domain error handlers are not a substitute for closing down a\nprocess when an error occurs.

      \n

      By the very nature of how throw works in JavaScript, there is almost\nnever any way to safely \"pick up where it left off\", without leaking\nreferences, or creating some other sort of undefined brittle state.

      \n

      The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, there may be many\nopen connections, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.

      \n

      The better approach is to send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.

      \n

      In this way, domain usage goes hand-in-hand with the cluster module,\nsince the master process can fork a new worker when a worker\nencounters an error. For Node.js programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.

      \n

      For example, this is not a good idea:

      \n
      // XXX WARNING! BAD IDEA!\n\nconst d = require('domain').create();\nd.on('error', (er) => {\n  // The error won't crash the process, but what it does is worse!\n  // Though we've prevented abrupt process restarting, we are leaking\n  // resources like crazy if this ever happens.\n  // This is no better than process.on('uncaughtException')!\n  console.log(`error, but oh well ${er.message}`);\n});\nd.run(() => {\n  require('http').createServer((req, res) => {\n    handleRequest(req, res);\n  }).listen(PORT);\n});\n
      \n

      By using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.

      \n
      // Much better!\n\nconst cluster = require('cluster');\nconst PORT = +process.env.PORT || 1337;\n\nif (cluster.isMaster) {\n  // A more realistic scenario would have more than 2 workers,\n  // and perhaps not put the master and worker in the same file.\n  //\n  // It is also possible to get a bit fancier about logging, and\n  // implement whatever custom logic is needed to prevent DoS\n  // attacks and other bad behavior.\n  //\n  // See the options in the cluster documentation.\n  //\n  // The important thing is that the master does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', (worker) => {\n    console.error('disconnect!');\n    cluster.fork();\n  });\n\n} else {\n  // the worker\n  //\n  // This is where we put our bugs!\n\n  const domain = require('domain');\n\n  // See the cluster documentation for more details about using\n  // worker processes to serve requests. How it works, caveats, etc.\n\n  const server = require('http').createServer((req, res) => {\n    const d = domain.create();\n    d.on('error', (er) => {\n      console.error(`error ${er.stack}`);\n\n      // We're in dangerous territory!\n      // By definition, something unexpected occurred,\n      // which we probably didn't want.\n      // Anything can happen now! Be very careful!\n\n      try {\n        // Make sure we close down within 30 seconds\n        const killtimer = setTimeout(() => {\n          process.exit(1);\n        }, 30000);\n        // But don't keep the process open just for that!\n        killtimer.unref();\n\n        // Stop taking new requests.\n        server.close();\n\n        // Let the master know we're dead. This will trigger a\n        // 'disconnect' in the cluster master, and then it will fork\n        // a new worker.\n        cluster.worker.disconnect();\n\n        // Try to send an error to the request that triggered the problem\n        res.statusCode = 500;\n        res.setHeader('content-type', 'text/plain');\n        res.end('Oops, there was a problem!\\n');\n      } catch (er2) {\n        // Oh well, not much we can do at this point.\n        console.error(`Error sending 500! ${er2.stack}`);\n      }\n    });\n\n    // Because req and res were created before this domain existed,\n    // we need to explicitly add them.\n    // See the explanation of implicit vs explicit binding below.\n    d.add(req);\n    d.add(res);\n\n    // Now run the handler function in the domain.\n    d.run(() => {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part is not important. Just an example routing thing.\n// Put fancy application logic here.\nfunction handleRequest(req, res) {\n  switch (req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(() => {\n        // Whoops!\n        flerb.bark();\n      }, timeout);\n      break;\n    default:\n      res.end('ok');\n  }\n}\n
      " + }, + { + "textRaw": "Additions to `Error` objects", + "name": "Additions to `Error` objects", + "type": "misc", + "desc": "

      Any time an Error object is routed through a domain, a few extra fields\nare added to it.

      \n
        \n
      • error.domain The domain that first handled the error.
      • \n
      • error.domainEmitter The event emitter that emitted an 'error' event\nwith the error object.
      • \n
      • error.domainBound The callback function which was bound to the\ndomain, and passed an error as its first argument.
      • \n
      • error.domainThrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
      • \n
      " + }, + { + "textRaw": "Implicit binding", + "name": "Implicit binding", + "type": "misc", + "desc": "

      If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.

      \n

      Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open(), or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.

      \n

      In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.

      \n

      To nest Domain objects as children of a parent Domain they must be\nexplicitly added.

      \n

      Implicit binding routes thrown errors and 'error' events to the\nDomain's 'error' event, but does not register the EventEmitter on the\nDomain.\nImplicit binding only takes care of thrown errors and 'error' events.

      " + }, + { + "textRaw": "Explicit binding", + "name": "Explicit binding", + "type": "misc", + "desc": "

      Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.

      \n

      For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.

      \n

      That is possible via explicit binding.

      \n
      // Create a top-level domain for the server\nconst domain = require('domain');\nconst http = require('http');\nconst serverDomain = domain.create();\n\nserverDomain.run(() => {\n  // Server is created in the scope of serverDomain\n  http.createServer((req, res) => {\n    // Req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    const reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', (er) => {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er2) {\n        console.error('Error sending 500', er2, req.url);\n      }\n    });\n  }).listen(1337);\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`domain.create()`", + "type": "method", + "name": "create", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Domain}", + "name": "return", + "type": "Domain" + }, + "params": [] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: `Domain`", + "type": "class", + "name": "Domain", + "desc": "\n

      The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.

      \n

      To handle the errors that it catches, listen to its 'error' event.

      ", + "properties": [ + { + "textRaw": "`members` {Array}", + "type": "Array", + "name": "members", + "desc": "

      An array of timers and event emitters that have been explicitly added\nto the domain.

      " + } + ], + "methods": [ + { + "textRaw": "`domain.add(emitter)`", + "type": "method", + "name": "add", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be added to the domain", + "name": "emitter", + "type": "EventEmitter|Timer", + "desc": "emitter or timer to be added to the domain" + } + ] + } + ], + "desc": "

      Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an 'error' event, it\nwill be routed to the domain's 'error' event, just like with implicit\nbinding.

      \n

      This also works with timers that are returned from setInterval() and\nsetTimeout(). If their callback function throws, it will be caught by\nthe domain 'error' handler.

      \n

      If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.

      " + }, + { + "textRaw": "`domain.bind(callback)`", + "type": "method", + "name": "bind", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The bound function", + "name": "return", + "type": "Function", + "desc": "The bound function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's 'error' event.

      \n
      const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind((er, data) => {\n    // If this throws, it will also be passed to the domain.\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n
      " + }, + { + "textRaw": "`domain.enter()`", + "type": "method", + "name": "enter", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The enter() method is plumbing used by the run(), bind(), and\nintercept() methods to set the active domain. It sets domain.active and\nprocess.domain to the domain, and implicitly pushes the domain onto the domain\nstack managed by the domain module (see domain.exit() for details on the\ndomain stack). The call to enter() delimits the beginning of a chain of\nasynchronous calls and I/O operations bound to a domain.

      \n

      Calling enter() changes only the active domain, and does not alter the domain\nitself. enter() and exit() can be called an arbitrary number of times on a\nsingle domain.

      " + }, + { + "textRaw": "`domain.exit()`", + "type": "method", + "name": "exit", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The exit() method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit() delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.

      \n

      If there are multiple, nested domains bound to the current execution context,\nexit() will exit any domains nested within this domain.

      \n

      Calling exit() changes only the active domain, and does not alter the domain\nitself. enter() and exit() can be called an arbitrary number of times on a\nsingle domain.

      " + }, + { + "textRaw": "`domain.intercept(callback)`", + "type": "method", + "name": "intercept", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The intercepted function", + "name": "return", + "type": "Function", + "desc": "The intercepted function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.

      \n

      In this way, the common if (err) return callback(err); pattern can be replaced\nwith a single error handler in a single place.

      \n
      const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept((data) => {\n    // Note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // If this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n
      " + }, + { + "textRaw": "`domain.remove(emitter)`", + "type": "method", + "name": "remove", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be removed from the domain", + "name": "emitter", + "type": "EventEmitter|Timer", + "desc": "emitter or timer to be removed from the domain" + } + ] + } + ], + "desc": "

      The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.

      " + }, + { + "textRaw": "`domain.run(fn[, ...args])`", + "type": "method", + "name": "run", + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context. Optionally, arguments can be passed to\nthe function.

      \n

      This is the most basic way to use a domain.

      \n
      const domain = require('domain');\nconst fs = require('fs');\nconst d = domain.create();\nd.on('error', (er) => {\n  console.error('Caught error!', er);\n});\nd.run(() => {\n  process.nextTick(() => {\n    setTimeout(() => { // Simulating some various async stuff\n      fs.open('non-existent file', 'r', (er, fd) => {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});\n
      \n

      In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Domains and promises", + "name": "domains_and_promises", + "desc": "

      As of Node.js 8.0.0, the handlers of promises are run inside the domain in\nwhich the call to .then() or .catch() itself was made:

      \n
      const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then((v) => {\n    // running in d2\n  });\n});\n
      \n

      A callback may be bound to a specific domain using domain.bind(callback):

      \n
      const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then(p.domain.bind((v) => {\n    // running in d1\n  }));\n});\n
      \n

      Domains will not interfere with the error handling mechanisms for\npromises. In other words, no 'error' event will be emitted for unhandled\nPromise rejections.

      ", + "type": "module", + "displayName": "Domains and promises" + } + ], + "type": "module", + "displayName": "Domain" + }, + { + "textRaw": "Events", + "name": "Events", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "type": "module", + "desc": "

      Source Code: lib/events.js

      \n

      Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called \"emitters\")\nemit named events that cause Function objects (\"listeners\") to be called.

      \n

      For instance: a net.Server object emits an event each time a peer\nconnects to it; a fs.ReadStream emits an event when the file is opened;\na stream emits an event whenever data is available to be read.

      \n

      All objects that emit events are instances of the EventEmitter class. These\nobjects expose an eventEmitter.on() function that allows one or more\nfunctions to be attached to named events emitted by the object. Typically,\nevent names are camel-cased strings but any valid JavaScript property key\ncan be used.

      \n

      When the EventEmitter object emits an event, all of the functions attached\nto that specific event are called synchronously. Any values returned by the\ncalled listeners are ignored and will be discarded.

      \n

      The following example shows a simple EventEmitter instance with a single\nlistener. The eventEmitter.on() method is used to register listeners, while\nthe eventEmitter.emit() method is used to trigger the event.

      \n
      const EventEmitter = require('events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n  console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
      ", + "modules": [ + { + "textRaw": "Passing arguments and `this` to listeners", + "name": "passing_arguments_and_`this`_to_listeners", + "desc": "

      The eventEmitter.emit() method allows an arbitrary set of arguments to be\npassed to the listener functions. Keep in mind that when\nan ordinary listener function is called, the standard this keyword\nis intentionally set to reference the EventEmitter instance to which the\nlistener is attached.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n  console.log(a, b, this, this === myEmitter);\n  // Prints:\n  //   a b MyEmitter {\n  //     domain: null,\n  //     _events: { event: [Function] },\n  //     _eventsCount: 1,\n  //     _maxListeners: undefined } true\n});\nmyEmitter.emit('event', 'a', 'b');\n
      \n

      It is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this keyword will no longer reference the EventEmitter instance:

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  console.log(a, b, this);\n  // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');\n
      ", + "type": "module", + "displayName": "Passing arguments and `this` to listeners" + }, + { + "textRaw": "Asynchronous vs. synchronous", + "name": "asynchronous_vs._synchronous", + "desc": "

      The EventEmitter calls all listeners synchronously in the order in which\nthey were registered. This ensures the proper sequencing of\nevents and helps avoid race conditions and logic errors. When appropriate,\nlistener functions can switch to an asynchronous mode of operation using\nthe setImmediate() or process.nextTick() methods:

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  setImmediate(() => {\n    console.log('this happens asynchronously');\n  });\n});\nmyEmitter.emit('event', 'a', 'b');\n
      ", + "type": "module", + "displayName": "Asynchronous vs. synchronous" + }, + { + "textRaw": "Handling events only once", + "name": "handling_events_only_once", + "desc": "

      When a listener is registered using the eventEmitter.on() method, that\nlistener will be invoked every time the named event is emitted.

      \n
      const myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.on('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Prints: 2\n
      \n

      Using the eventEmitter.once() method, it is possible to register a listener\nthat is called at most once for a particular event. Once the event is emitted,\nthe listener is unregistered and then called.

      \n
      const myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.once('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Ignored\n
      ", + "type": "module", + "displayName": "Handling events only once" + }, + { + "textRaw": "Error events", + "name": "error_events", + "desc": "

      When an error occurs within an EventEmitter instance, the typical action is\nfor an 'error' event to be emitted. These are treated as special cases\nwithin Node.js.

      \n

      If an EventEmitter does not have at least one listener registered for the\n'error' event, and an 'error' event is emitted, the error is thrown, a\nstack trace is printed, and the Node.js process exits.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n
      \n

      To guard against crashing the Node.js process the domain module can be\nused. (Note, however, that the domain module is deprecated.)

      \n

      As a best practice, listeners should always be added for the 'error' events.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n  console.error('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Prints: whoops! there was an error\n
      \n

      It is possible to monitor 'error' events without consuming the emitted error\nby installing a listener using the symbol errorMonitor.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on(EventEmitter.errorMonitor, (err) => {\n  MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n
      ", + "type": "module", + "displayName": "Error events" + }, + { + "textRaw": "Capture rejections of promises", + "name": "capture_rejections_of_promises", + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "

      Using async functions with event handlers is problematic, because it\ncan lead to an unhandled rejection in case of a thrown exception:

      \n
      const ee = new EventEmitter();\nee.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n
      \n

      The captureRejections option in the EventEmitter constructor or the global\nsetting change this behavior, installing a .then(undefined, handler)\nhandler on the Promise. This handler routes the exception\nasynchronously to the Symbol.for('nodejs.rejection') method\nif there is one, or to 'error' event handler if there is none.

      \n
      const ee1 = new EventEmitter({ captureRejections: true });\nee1.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nconst ee2 = new EventEmitter({ captureRejections: true });\nee2.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee2[Symbol.for('nodejs.rejection')] = console.log;\n
      \n

      Setting EventEmitter.captureRejections = true will change the default for all\nnew instances of EventEmitter.

      \n
      EventEmitter.captureRejections = true;\nconst ee1 = new EventEmitter();\nee1.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n
      \n

      The 'error' events that are generated by the captureRejections behavior\ndo not have a catch handler to avoid infinite error loops: the\nrecommendation is to not use async functions as 'error' event handlers.

      ", + "type": "module", + "displayName": "Capture rejections of promises" + } + ], + "classes": [ + { + "textRaw": "Class: `EventEmitter`", + "type": "class", + "name": "EventEmitter", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/27867", + "description": "Added captureRejections option." + } + ] + }, + "desc": "

      The EventEmitter class is defined and exposed by the events module:

      \n
      const EventEmitter = require('events');\n
      \n

      All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when existing listeners are removed.

      \n

      It supports the following option:

      \n", + "events": [ + { + "textRaw": "Event: 'newListener'", + "type": "event", + "name": "newListener", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event being listened for", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event being listened for" + }, + { + "textRaw": "`listener` {Function} The event handler function", + "name": "listener", + "type": "Function", + "desc": "The event handler function" + } + ], + "desc": "

      The EventEmitter instance will emit its own 'newListener' event before\na listener is added to its internal array of listeners.

      \n

      Listeners registered for the 'newListener' event will be passed the event\nname and a reference to the listener being added.

      \n

      The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any additional listeners registered to the same\nname within the 'newListener' callback will be inserted before the\nlistener that is in the process of being added.

      \n
      const myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n  if (event === 'event') {\n    // Insert a new listener in front\n    myEmitter.on('event', () => {\n      console.log('B');\n    });\n  }\n});\nmyEmitter.on('event', () => {\n  console.log('A');\n});\nmyEmitter.emit('event');\n// Prints:\n//   B\n//   A\n
      " + }, + { + "textRaw": "Event: `'removeListener'`", + "type": "event", + "name": "removeListener", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [ + { + "version": "v6.1.0, v4.7.0", + "pr-url": "https://github.com/nodejs/node/pull/6394", + "description": "For listeners attached using `.once()`, the `listener` argument now yields the original listener function." + } + ] + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The event name", + "name": "eventName", + "type": "string|symbol", + "desc": "The event name" + }, + { + "textRaw": "`listener` {Function} The event handler function", + "name": "listener", + "type": "Function", + "desc": "The event handler function" + } + ], + "desc": "

      The 'removeListener' event is emitted after the listener is removed.

      " + } + ], + "methods": [ + { + "textRaw": "`EventEmitter.listenerCount(emitter, eventName)`", + "type": "method", + "name": "listenerCount", + "meta": { + "added": [ + "v0.9.12" + ], + "deprecated": [ + "v3.2.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter} The emitter to query", + "name": "emitter", + "type": "EventEmitter", + "desc": "The emitter to query" + }, + { + "textRaw": "`eventName` {string|symbol} The event name", + "name": "eventName", + "type": "string|symbol", + "desc": "The event name" + } + ] + } + ], + "desc": "

      A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n// Prints: 2\n
      " + }, + { + "textRaw": "`emitter.addListener(eventName, listener)`", + "type": "method", + "name": "addListener", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias for emitter.on(eventName, listener).

      " + }, + { + "textRaw": "`emitter.emit(eventName[, ...args])`", + "type": "method", + "name": "emit", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.

      \n

      Returns true if the event had listeners, false otherwise.

      \n
      const EventEmitter = require('events');\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n  console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n  const parameters = args.join(', ');\n  console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n//   [Function: firstListener],\n//   [Function: secondListener],\n//   [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n
      " + }, + { + "textRaw": "`emitter.eventNames()`", + "type": "method", + "name": "eventNames", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Array}", + "name": "return", + "type": "Array" + }, + "params": [] + } + ], + "desc": "

      Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array will be strings or Symbols.

      \n
      const EventEmitter = require('events');\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n
      " + }, + { + "textRaw": "`emitter.getMaxListeners()`", + "type": "method", + "name": "getMaxListeners", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nEventEmitter.defaultMaxListeners.

      " + }, + { + "textRaw": "`emitter.listenerCount(eventName)`", + "type": "method", + "name": "listenerCount", + "meta": { + "added": [ + "v3.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event being listened for", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event being listened for" + } + ] + } + ], + "desc": "

      Returns the number of listeners listening to the event named eventName.

      " + }, + { + "textRaw": "`emitter.listeners(eventName)`", + "type": "method", + "name": "listeners", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6881", + "description": "For listeners attached using `.once()` this returns the original listeners instead of wrapper functions now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function[]}", + "name": "return", + "type": "Function[]" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + } + ] + } + ], + "desc": "

      Returns a copy of the array of listeners for the event named eventName.

      \n
      server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n// Prints: [ [Function] ]\n
      " + }, + { + "textRaw": "`emitter.off(eventName, listener)`", + "type": "method", + "name": "off", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias for emitter.removeListener().

      " + }, + { + "textRaw": "`emitter.on(eventName, listener)`", + "type": "method", + "name": "on", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds the listener function to the end of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.

      \n
      server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      \n

      By default, event listeners are invoked in the order they are added. The\nemitter.prependListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.

      \n
      const myEE = new EventEmitter();\nmyEE.on('foo', () => console.log('a'));\nmyEE.prependListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n//   b\n//   a\n
      " + }, + { + "textRaw": "`emitter.once(eventName, listener)`", + "type": "method", + "name": "once", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds a one-time listener function for the event named eventName. The\nnext time eventName is triggered, this listener is removed and then invoked.

      \n
      server.once('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      \n

      By default, event listeners are invoked in the order they are added. The\nemitter.prependOnceListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.

      \n
      const myEE = new EventEmitter();\nmyEE.once('foo', () => console.log('a'));\nmyEE.prependOnceListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n//   b\n//   a\n
      " + }, + { + "textRaw": "`emitter.prependListener(eventName, listener)`", + "type": "method", + "name": "prependListener", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds the listener function to the beginning of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.

      \n
      server.prependListener('connection', (stream) => {\n  console.log('someone connected!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.prependOnceListener(eventName, listener)`", + "type": "method", + "name": "prependOnceListener", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds a one-time listener function for the event named eventName to the\nbeginning of the listeners array. The next time eventName is triggered, this\nlistener is removed, and then invoked.

      \n
      server.prependOnceListener('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.removeAllListeners([eventName])`", + "type": "method", + "name": "removeAllListeners", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + } + ] + } + ], + "desc": "

      Removes all listeners, or those of the specified eventName.

      \n

      It is bad practice to remove listeners added elsewhere in the code,\nparticularly when the EventEmitter instance was created by some other\ncomponent or module (e.g. sockets or file streams).

      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.removeListener(eventName, listener)`", + "type": "method", + "name": "removeListener", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function" + } + ] + } + ], + "desc": "

      Removes the specified listener from the listener array for the event named\neventName.

      \n
      const callback = (stream) => {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
      \n

      removeListener() will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified eventName, then removeListener() must be\ncalled multiple times to remove each instance.

      \n

      Once an event has been emitted, all listeners attached to it at the\ntime of emitting will be called in order. This implies that any\nremoveListener() or removeAllListeners() calls after emitting and\nbefore the last listener finishes execution will not remove them from\nemit() in progress. Subsequent events will behave as expected.

      \n
      const myEmitter = new MyEmitter();\n\nconst callbackA = () => {\n  console.log('A');\n  myEmitter.removeListener('event', callbackB);\n};\n\nconst callbackB = () => {\n  console.log('B');\n};\n\nmyEmitter.on('event', callbackA);\n\nmyEmitter.on('event', callbackB);\n\n// callbackA removes listener callbackB but it will still be called.\n// Internal listener array at time of emit [callbackA, callbackB]\nmyEmitter.emit('event');\n// Prints:\n//   A\n//   B\n\n// callbackB is now removed.\n// Internal listener array [callbackA]\nmyEmitter.emit('event');\n// Prints:\n//   A\n
      \n

      Because listeners are managed using an internal array, calling this will\nchange the position indices of any listener registered after the listener\nbeing removed. This will not impact the order in which listeners are called,\nbut it means that any copies of the listener array as returned by\nthe emitter.listeners() method will need to be recreated.

      \n

      When a single function has been added as a handler multiple times for a single\nevent (as in the example below), removeListener() will remove the most\nrecently added instance. In the example the once('ping')\nlistener is removed:

      \n
      const ee = new EventEmitter();\n\nfunction pong() {\n  console.log('pong');\n}\n\nee.on('ping', pong);\nee.once('ping', pong);\nee.removeListener('ping', pong);\n\nee.emit('ping');\nee.emit('ping');\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.setMaxListeners(n)`", + "type": "method", + "name": "setMaxListeners", + "meta": { + "added": [ + "v0.3.5" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`n` {integer}", + "name": "n", + "type": "integer" + } + ] + } + ], + "desc": "

      By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default that helps finding\nmemory leaks. The emitter.setMaxListeners() method allows the limit to be\nmodified for this specific EventEmitter instance. The value can be set to\nInfinity (or 0) to indicate an unlimited number of listeners.

      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.rawListeners(eventName)`", + "type": "method", + "name": "rawListeners", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function[]}", + "name": "return", + "type": "Function[]" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + } + ] + } + ], + "desc": "

      Returns a copy of the array of listeners for the event named eventName,\nincluding any wrappers (such as those created by .once()).

      \n
      const emitter = new EventEmitter();\nemitter.once('log', () => console.log('log once'));\n\n// Returns a new Array with a function `onceWrapper` which has a property\n// `listener` which contains the original listener bound above\nconst listeners = emitter.rawListeners('log');\nconst logFnWrapper = listeners[0];\n\n// Logs \"log once\" to the console and does not unbind the `once` event\nlogFnWrapper.listener();\n\n// Logs \"log once\" to the console and removes the listener\nlogFnWrapper();\n\nemitter.on('log', () => console.log('log persistently'));\n// Will return a new Array with a single function bound by `.on()` above\nconst newListeners = emitter.rawListeners('log');\n\n// Logs \"log persistently\" twice\nnewListeners[0]();\nemitter.emit('log');\n
      " + } + ], + "properties": [ + { + "textRaw": "`EventEmitter.defaultMaxListeners`", + "name": "defaultMaxListeners", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "desc": "

      By default, a maximum of 10 listeners can be registered for any single\nevent. This limit can be changed for individual EventEmitter instances\nusing the emitter.setMaxListeners(n) method. To change the default\nfor all EventEmitter instances, the EventEmitter.defaultMaxListeners\nproperty can be used. If this value is not a positive number, a TypeError\nwill be thrown.

      \n

      Take caution when setting the EventEmitter.defaultMaxListeners because the\nchange affects all EventEmitter instances, including those created before\nthe change is made. However, calling emitter.setMaxListeners(n) still has\nprecedence over EventEmitter.defaultMaxListeners.

      \n

      This is not a hard limit. The EventEmitter instance will allow\nmore listeners to be added but will output a trace warning to stderr indicating\nthat a \"possible EventEmitter memory leak\" has been detected. For any single\nEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()\nmethods can be used to temporarily avoid this warning:

      \n
      emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
      \n

      The --trace-warnings command line flag can be used to display the\nstack trace for such warnings.

      \n

      The emitted warning can be inspected with process.on('warning') and will\nhave the additional emitter, type and count properties, referring to\nthe event emitter instance, the event’s name and the number of attached\nlisteners, respectively.\nIts name property is set to 'MaxListenersExceededWarning'.

      " + }, + { + "textRaw": "`EventEmitter.errorMonitor`", + "name": "errorMonitor", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      This symbol shall be used to install a listener for only monitoring 'error'\nevents. Listeners installed using this symbol are called before the regular\n'error' listeners are called.

      \n

      Installing a listener using this symbol does not change the behavior once an\n'error' event is emitted, therefore the process will still crash if no\nregular 'error' listener is installed.

      " + } + ], + "modules": [ + { + "textRaw": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`", + "name": "`emitter[symbol.for('nodejs.rejection')](err,_eventname[,_...args])`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "\n

      The Symbol.for('nodejs.rejection') method is called in case a\npromise rejection happens when emitting an event and\ncaptureRejections is enabled on the emitter.\nIt is possible to use events.captureRejectionSymbol in\nplace of Symbol.for('nodejs.rejection').

      \n
      const { EventEmitter, captureRejectionSymbol } = require('events');\n\nclass MyClass extends EventEmitter {\n  constructor() {\n    super({ captureRejections: true });\n  }\n\n  [captureRejectionSymbol](err, event, ...args) {\n    console.log('rejection happened for', event, 'with', err, ...args);\n    this.destroy(err);\n  }\n\n  destroy(err) {\n    // Tear the resource down here.\n  }\n}\n
      ", + "type": "module", + "displayName": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`" + } + ] + } + ], + "methods": [ + { + "textRaw": "`events.once(emitter, name)`", + "type": "method", + "name": "once", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`emitter` {EventEmitter}", + "name": "emitter", + "type": "EventEmitter" + }, + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Creates a Promise that is fulfilled when the EventEmitter emits the given\nevent or that is rejected if the EventEmitter emits 'error' while waiting.\nThe Promise will resolve with an array of all the arguments emitted to the\ngiven event.

      \n

      This method is intentionally generic and works with the web platform\nEventTarget interface, which has no special\n'error' event semantics and does not listen to the 'error' event.

      \n
      const { once, EventEmitter } = require('events');\n\nasync function run() {\n  const ee = new EventEmitter();\n\n  process.nextTick(() => {\n    ee.emit('myevent', 42);\n  });\n\n  const [value] = await once(ee, 'myevent');\n  console.log(value);\n\n  const err = new Error('kaboom');\n  process.nextTick(() => {\n    ee.emit('error', err);\n  });\n\n  try {\n    await once(ee, 'myevent');\n  } catch (err) {\n    console.log('error happened', err);\n  }\n}\n\nrun();\n
      \n

      The special handling of the 'error' event is only used when events.once()\nis used to wait for another event. If events.once() is used to wait for the\n'error' event itself, then it is treated as any other kind of event without\nspecial handling:

      \n
      const { EventEmitter, once } = require('events');\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n  .then(([err]) => console.log('ok', err.message))\n  .catch((err) => console.log('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n
      ", + "modules": [ + { + "textRaw": "Awaiting multiple events emitted on `process.nextTick()`", + "name": "awaiting_multiple_events_emitted_on_`process.nexttick()`", + "desc": "

      There is an edge case worth noting when using the events.once() function\nto await multiple events emitted on in the same batch of process.nextTick()\noperations, or whenever multiple events are emitted synchronously. Specifically,\nbecause the process.nextTick() queue is drained before the Promise microtask\nqueue, and because EventEmitter emits all events synchronously, it is possible\nfor events.once() to miss an event.

      \n
      const { EventEmitter, once } = require('events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n  await once(myEE, 'bar');\n  console.log('bar');\n\n  // This Promise will never resolve because the 'foo' event will\n  // have already been emitted before the Promise is created.\n  await once(myEE, 'foo');\n  console.log('foo');\n}\n\nprocess.nextTick(() => {\n  myEE.emit('bar');\n  myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
      \n

      To catch both events, create each of the Promises before awaiting either\nof them, then it becomes possible to use Promise.all(), Promise.race(),\nor Promise.allSettled():

      \n
      const { EventEmitter, once } = require('events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);\n  console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n  myEE.emit('bar');\n  myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
      ", + "type": "module", + "displayName": "Awaiting multiple events emitted on `process.nextTick()`" + } + ] + }, + { + "textRaw": "events.on(emitter, eventName)", + "type": "method", + "name": "on", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter`", + "name": "return", + "type": "AsyncIterator", + "desc": "that iterates `eventName` events emitted by the `emitter`" + }, + "params": [ + { + "textRaw": "`emitter` {EventEmitter}", + "name": "emitter", + "type": "EventEmitter" + }, + { + "textRaw": "`eventName` {string|symbol} The name of the event being listened for", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event being listened for" + } + ] + } + ], + "desc": "
      const { on, EventEmitter } = require('events');\n\n(async () => {\n  const ee = new EventEmitter();\n\n  // Emit later on\n  process.nextTick(() => {\n    ee.emit('foo', 'bar');\n    ee.emit('foo', 42);\n  });\n\n  for await (const event of on(ee, 'foo')) {\n    // The execution of this inner block is synchronous and it\n    // processes one event at a time (even with await). Do not use\n    // if concurrent execution is required.\n    console.log(event); // prints ['bar'] [42]\n  }\n  // Unreachable here\n})();\n
      \n

      Returns an AsyncIterator that iterates eventName events. It will throw\nif the EventEmitter emits 'error'. It removes all listeners when\nexiting the loop. The value returned by each iteration is an array\ncomposed of the emitted event arguments.

      " + } + ], + "properties": [ + { + "textRaw": "`events.captureRejections`", + "name": "captureRejections", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "

      Value: <boolean>

      \n

      Change the default captureRejections option on all new EventEmitter objects.

      " + }, + { + "textRaw": "events.captureRejectionSymbol", + "name": "captureRejectionSymbol", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "

      Value: Symbol.for('nodejs.rejection')

      \n

      See how to write a custom rejection handler.

      " + } + ] + }, + { + "textRaw": "File system", + "name": "fs", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/fs.js

      \n

      The fs module enables interacting with the file system in a\nway modeled on standard POSIX functions.

      \n

      To use this module:

      \n
      const fs = require('fs');\n
      \n

      All file system operations have synchronous, callback, and promise-based\nforms.

      ", + "modules": [ + { + "textRaw": "Synchronous example", + "name": "synchronous_example", + "desc": "

      The synchronous form blocks the Node.js event loop and further JavaScript\nexecution until the operation is complete. Exceptions are thrown immediately\nand can be handled using try…catch, or can be allowed to bubble up.

      \n
      const fs = require('fs');\n\ntry {\n  fs.unlinkSync('/tmp/hello');\n  console.log('successfully deleted /tmp/hello');\n} catch (err) {\n  // handle the error\n}\n
      ", + "type": "module", + "displayName": "Synchronous example" + }, + { + "textRaw": "Callback example", + "name": "callback_example", + "desc": "

      The callback form takes a completion callback function as its last\nargument and invokes the operation asynchronously. The arguments passed to\nthe completion callback depend on the method, but the first argument is always\nreserved for an exception. If the operation is completed successfully, then\nthe first argument is null or undefined.

      \n
      const fs = require('fs');\n\nfs.unlink('/tmp/hello', (err) => {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});\n
      ", + "type": "module", + "displayName": "Callback example" + }, + { + "textRaw": "Promise example", + "name": "promise_example", + "desc": "

      Promise-based operations return a Promise that is resolved when the\nasynchronous operation is complete.

      \n
      const fs = require('fs').promises;\n\n(async function(path) {\n  try {\n    await fs.unlink(path);\n    console.log(`successfully deleted ${path}`);\n  } catch (error) {\n    console.error('there was an error:', error.message);\n  }\n})('/tmp/hello');\n
      ", + "type": "module", + "displayName": "Promise example" + }, + { + "textRaw": "Ordering of callback and promise-based operations", + "name": "ordering_of_callback_and_promise-based_operations", + "desc": "

      There is no guaranteed ordering when using either the callback or\npromise-based methods. For example, the following is prone to error\nbecause the fs.stat() operation might complete before the fs.rename()\noperation:

      \n
      fs.rename('/tmp/hello', '/tmp/world', (err) => {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', (err, stats) => {\n  if (err) throw err;\n  console.log(`stats: ${JSON.stringify(stats)}`);\n});\n
      \n

      To correctly order the operations, move the fs.stat() call into the callback\nof the fs.rename() operation:

      \n
      fs.rename('/tmp/hello', '/tmp/world', (err) => {\n  if (err) throw err;\n  fs.stat('/tmp/world', (err, stats) => {\n    if (err) throw err;\n    console.log(`stats: ${JSON.stringify(stats)}`);\n  });\n});\n
      \n

      Or, use the promise-based API:

      \n
      const fs = require('fs').promises;\n\n(async function(from, to) {\n  try {\n    await fs.rename(from, to);\n    const stats = await fs.stat(to);\n    console.log(`stats: ${JSON.stringify(stats)}`);\n  } catch (error) {\n    console.error('there was an error:', error.message);\n  }\n})('/tmp/hello', '/tmp/world');\n
      ", + "type": "module", + "displayName": "Ordering of callback and promise-based operations" + }, + { + "textRaw": "File paths", + "name": "file_paths", + "desc": "

      Most fs operations accept filepaths that may be specified in the form of\na string, a Buffer, or a URL object using the file: protocol.

      \n

      String form paths are interpreted as UTF-8 character sequences identifying\nthe absolute or relative filename. Relative paths will be resolved relative\nto the current working directory as determined by calling process.cwd().

      \n

      Example using an absolute path on POSIX:

      \n
      const fs = require('fs');\n\nfs.open('/open/some/file.txt', 'r', (err, fd) => {\n  if (err) throw err;\n  fs.close(fd, (err) => {\n    if (err) throw err;\n  });\n});\n
      \n

      Example using a relative path on POSIX (relative to process.cwd()):

      \n
      fs.open('file.txt', 'r', (err, fd) => {\n  if (err) throw err;\n  fs.close(fd, (err) => {\n    if (err) throw err;\n  });\n});\n
      \n

      Paths specified using a Buffer are useful primarily on certain POSIX\noperating systems that treat file paths as opaque byte sequences. On such\nsystems, it is possible for a single file path to contain sub-sequences that\nuse multiple character encodings. As with string paths, Buffer paths may\nbe relative or absolute:

      \n

      Example using an absolute path on POSIX:

      \n
      fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {\n  if (err) throw err;\n  fs.close(fd, (err) => {\n    if (err) throw err;\n  });\n});\n
      \n

      On Windows, Node.js follows the concept of per-drive working directory. This\nbehavior can be observed when using a drive path without a backslash. For\nexample fs.readdirSync('C:\\\\') can potentially return a different result than\nfs.readdirSync('C:'). For more information, see\nthis MSDN page.

      ", + "modules": [ + { + "textRaw": "URL object support", + "name": "url_object_support", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "desc": "

      For most fs module functions, the path or filename argument may be passed\nas a WHATWG URL object. Only URL objects using the file: protocol\nare supported.

      \n
      const fs = require('fs');\nconst fileUrl = new URL('file:///tmp/hello');\n\nfs.readFileSync(fileUrl);\n
      \n

      file: URLs are always absolute paths.

      \n

      Using WHATWG URL objects might introduce platform-specific behaviors.

      \n

      On Windows, file: URLs with a host name convert to UNC paths, while file:\nURLs with drive letters convert to local absolute paths. file: URLs without a\nhost name nor a drive letter will result in a throw:

      \n
      // On Windows :\n\n// - WHATWG file URLs with hostname convert to UNC path\n// file://hostname/p/a/t/h/file => \\\\hostname\\p\\a\\t\\h\\file\nfs.readFileSync(new URL('file://hostname/p/a/t/h/file'));\n\n// - WHATWG file URLs with drive letters convert to absolute path\n// file:///C:/tmp/hello => C:\\tmp\\hello\nfs.readFileSync(new URL('file:///C:/tmp/hello'));\n\n// - WHATWG file URLs without hostname must have a drive letters\nfs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));\nfs.readFileSync(new URL('file:///c/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute\n
      \n

      file: URLs with drive letters must use : as a separator just after\nthe drive letter. Using another separator will result in a throw.

      \n

      On all other platforms, file: URLs with a host name are unsupported and will\nresult in a throw:

      \n
      // On other platforms:\n\n// - WHATWG file URLs with hostname are unsupported\n// file://hostname/p/a/t/h/file => throw!\nfs.readFileSync(new URL('file://hostname/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute\n\n// - WHATWG file URLs convert to absolute path\n// file:///tmp/hello => /tmp/hello\nfs.readFileSync(new URL('file:///tmp/hello'));\n
      \n

      A file: URL having encoded slash characters will result in a throw on all\nplatforms:

      \n
      // On Windows\nfs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));\nfs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n\n// On POSIX\nfs.readFileSync(new URL('file:///p/a/t/h/%2F'));\nfs.readFileSync(new URL('file:///p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n/ characters */\n
      \n

      On Windows, file: URLs having encoded backslash will result in a throw:

      \n
      // On Windows\nfs.readFileSync(new URL('file:///C:/path/%5C'));\nfs.readFileSync(new URL('file:///C:/path/%5c'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n
      ", + "type": "module", + "displayName": "URL object support" + } + ], + "type": "module", + "displayName": "File paths" + }, + { + "textRaw": "File descriptors", + "name": "file_descriptors", + "desc": "

      On POSIX systems, for every process, the kernel maintains a table of currently\nopen files and resources. Each open file is assigned a simple numeric\nidentifier called a file descriptor. At the system-level, all file system\noperations use these file descriptors to identify and track each specific\nfile. Windows systems use a different but conceptually similar mechanism for\ntracking resources. To simplify things for users, Node.js abstracts away the\nspecific differences between operating systems and assigns all open files a\nnumeric file descriptor.

      \n

      The fs.open() method is used to allocate a new file descriptor. Once\nallocated, the file descriptor may be used to read data from, write data to,\nor request information about the file.

      \n
      fs.open('/open/some/file.txt', 'r', (err, fd) => {\n  if (err) throw err;\n  fs.fstat(fd, (err, stat) => {\n    if (err) throw err;\n    // use stat\n\n    // always close the file descriptor!\n    fs.close(fd, (err) => {\n      if (err) throw err;\n    });\n  });\n});\n
      \n

      Most operating systems limit the number of file descriptors that may be open\nat any given time so it is critical to close the descriptor when operations\nare completed. Failure to do so will result in a memory leak that will\neventually cause an application to crash.

      ", + "type": "module", + "displayName": "File descriptors" + }, + { + "textRaw": "Threadpool usage", + "name": "threadpool_usage", + "desc": "

      All file system APIs except fs.FSWatcher() and those that are explicitly\nsynchronous use libuv's threadpool, which can have surprising and negative\nperformance implications for some applications. See the\nUV_THREADPOOL_SIZE documentation for more information.

      ", + "type": "module", + "displayName": "Threadpool usage" + }, + { + "textRaw": "`fs` Promises API", + "name": "`fs`_promises_api", + "desc": "

      The fs.promises API provides an alternative set of asynchronous file system\nmethods that return Promise objects rather than using callbacks. The\nAPI is accessible via require('fs').promises.

      ", + "classes": [ + { + "textRaw": "Class: `FileHandle`", + "type": "class", + "name": "FileHandle", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      A FileHandle object is a wrapper for a numeric file descriptor.\nInstances of FileHandle are distinct from numeric file descriptors\nin that they provide an object oriented API for working with files.

      \n

      If a FileHandle is not closed using the\nfilehandle.close() method, it might automatically close the file descriptor\nand will emit a process warning, thereby helping to prevent memory leaks.\nPlease do not rely on this behavior because it is unreliable and\nthe file may not be closed. Instead, always explicitly close FileHandles.\nNode.js may change this behavior in the future.

      \n

      Instances of the FileHandle object are created internally by the\nfsPromises.open() method.

      \n

      Unlike the callback-based API (fs.fstat(), fs.fchown(), fs.fchmod(), and\nso on), a numeric file descriptor is not used by the promise-based API. Instead,\nthe promise-based API uses the FileHandle class in order to help avoid\naccidental leaking of unclosed file descriptors after a Promise is resolved or\nrejected.

      ", + "methods": [ + { + "textRaw": "`filehandle.appendFile(data, options)`", + "type": "method", + "name": "appendFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Alias of filehandle.writeFile().

      \n

      When operating on file handles, the mode cannot be changed from what it was set\nto with fsPromises.open(). Therefore, this is equivalent to\nfilehandle.writeFile().

      " + }, + { + "textRaw": "`filehandle.chmod(mode)`", + "type": "method", + "name": "chmod", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + } + ] + } + ], + "desc": "

      Modifies the permissions on the file. The Promise is resolved with no\narguments upon success.

      " + }, + { + "textRaw": "`filehandle.chown(uid, gid)`", + "type": "method", + "name": "chown", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the ownership of the file then resolves the Promise with no arguments\nupon success.

      " + }, + { + "textRaw": "`filehandle.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} A `Promise` that will be resolved once the underlying file descriptor is closed, or will be rejected if an error occurs while closing.", + "name": "return", + "type": "Promise", + "desc": "A `Promise` that will be resolved once the underlying file descriptor is closed, or will be rejected if an error occurs while closing." + }, + "params": [] + } + ], + "desc": "

      Closes the file descriptor.

      \n
      const fsPromises = require('fs').promises;\nasync function openAndClose() {\n  let filehandle;\n  try {\n    filehandle = await fsPromises.open('thefile.txt', 'r');\n  } finally {\n    if (filehandle !== undefined)\n      await filehandle.close();\n  }\n}\n
      " + }, + { + "textRaw": "`filehandle.datasync()`", + "type": "method", + "name": "datasync", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Asynchronous fdatasync(2). The Promise is resolved with no arguments upon\nsuccess.

      " + }, + { + "textRaw": "`filehandle.read(buffer, offset, length, position)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array}", + "name": "buffer", + "type": "Buffer|Uint8Array" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Read data from the file.

      \n

      buffer is the buffer that the data will be written to.

      \n

      offset is the offset in the buffer to start writing at.

      \n

      length is an integer specifying the number of bytes to read.

      \n

      position is an argument specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position,\nand the file position will be updated.\nIf position is an integer, the file position will remain unchanged.

      \n

      Following successful read, the Promise is resolved with an object with a\nbytesRead property specifying the number of bytes read, and a buffer\nproperty that is a reference to the passed in buffer argument.

      " + }, + { + "textRaw": "`filehandle.read(options)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array} **Default:** `Buffer.alloc(16384)`", + "name": "buffer", + "type": "Buffer|Uint8Array", + "default": "`Buffer.alloc(16384)`" + }, + { + "textRaw": "`offset` {integer} **Default:** `0`", + "name": "offset", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`length` {integer} **Default:** `buffer.length`", + "name": "length", + "type": "integer", + "default": "`buffer.length`" + }, + { + "textRaw": "`position` {integer} **Default:** `null`", + "name": "position", + "type": "integer", + "default": "`null`" + } + ] + } + ] + } + ] + }, + { + "textRaw": "`filehandle.readFile(options)`", + "type": "method", + "name": "readFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously reads the entire contents of a file.

      \n

      The Promise is resolved with the contents of the file. If no encoding is\nspecified (using options.encoding), the data is returned as a Buffer\nobject. Otherwise, the data will be a string.

      \n

      If options is a string, then it specifies the encoding.

      \n

      The FileHandle has to support reading.

      \n

      If one or more filehandle.read() calls are made on a file handle and then a\nfilehandle.readFile() call is made, the data will be read from the current\nposition till the end of the file. It doesn't always read from the beginning\nof the file.

      " + }, + { + "textRaw": "`filehandle.readv(buffers[, position])`", + "type": "method", + "name": "readv", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Read from a file and write to an array of ArrayBufferViews

      \n

      The Promise is resolved with an object containing a bytesRead property\nidentifying the number of bytes read, and a buffers property containing\na reference to the buffers input.

      \n

      position is the offset from the beginning of the file where this data\nshould be read from. If typeof position !== 'number', the data will be read\nfrom the current position.

      " + }, + { + "textRaw": "`filehandle.stat([options])`", + "type": "method", + "name": "stat", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Retrieves the fs.Stats for the file.

      " + }, + { + "textRaw": "`filehandle.sync()`", + "type": "method", + "name": "sync", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Asynchronous fsync(2). The Promise is resolved with no arguments upon\nsuccess.

      " + }, + { + "textRaw": "`filehandle.truncate(len)`", + "type": "method", + "name": "truncate", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Truncates the file then resolves the Promise with no arguments upon success.

      \n

      If the file was larger than len bytes, only the first len bytes will be\nretained in the file.

      \n

      For example, the following program retains only the first four bytes of the\nfile:

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\n\nconsole.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\nasync function doTruncate() {\n  let filehandle = null;\n  try {\n    filehandle = await fsPromises.open('temp.txt', 'r+');\n    await filehandle.truncate(4);\n  } finally {\n    if (filehandle) {\n      // Close the file if it is opened.\n      await filehandle.close();\n    }\n  }\n  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node\n}\n\ndoTruncate().catch(console.error);\n
      \n

      If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\n\nconsole.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\nasync function doTruncate() {\n  let filehandle = null;\n  try {\n    filehandle = await fsPromises.open('temp.txt', 'r+');\n    await filehandle.truncate(10);\n  } finally {\n    if (filehandle) {\n      // Close the file if it is opened.\n      await filehandle.close();\n    }\n  }\n  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\\0\\0\\0\n}\n\ndoTruncate().catch(console.error);\n
      \n

      The last three bytes are null bytes ('\\0'), to compensate the over-truncation.

      " + }, + { + "textRaw": "`filehandle.utimes(atime, mtime)`", + "type": "method", + "name": "utimes", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by the FileHandle\nthen resolves the Promise with no arguments upon success.

      \n

      This function does not work on AIX versions before 7.1, it will resolve the\nPromise with an error using code UV_ENOSYS.

      " + }, + { + "textRaw": "`filehandle.write(buffer[, offset[, length[, position]]])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array}", + "name": "buffer", + "type": "Buffer|Uint8Array" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Write buffer to the file.

      \n

      The Promise is resolved with an object containing a bytesWritten property\nidentifying the number of bytes written, and a buffer property containing\na reference to the buffer written.

      \n

      offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position. See pwrite(2).

      \n

      It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected). For this\nscenario, use fs.createWriteStream().

      \n

      On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`filehandle.write(string[, position[, encoding]])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ], + "desc": "

      Write string to the file. If string is not a string, then\nthe value will be coerced to one.

      \n

      The Promise is resolved with an object containing a bytesWritten property\nidentifying the number of bytes written, and a buffer property containing\na reference to the string written.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If the type of position is not a number the data\nwill be written at the current position. See pwrite(2).

      \n

      encoding is the expected string encoding.

      \n

      It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected). For this\nscenario, use fs.createWriteStream().

      \n

      On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`filehandle.writeFile(data, options)`", + "type": "method", + "name": "writeFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer. The Promise will be resolved with no\narguments upon success.

      \n

      The encoding option is ignored if data is a buffer.

      \n

      If options is a string, then it specifies the encoding.

      \n

      The FileHandle has to support writing.

      \n

      It is unsafe to use filehandle.writeFile() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected).

      \n

      If one or more filehandle.write() calls are made on a file handle and then a\nfilehandle.writeFile() call is made, the data will be written from the\ncurrent position till the end of the file. It doesn't always write from the\nbeginning of the file.

      " + }, + { + "textRaw": "`filehandle.writev(buffers[, position])`", + "type": "method", + "name": "writev", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Write an array of ArrayBufferViews to the file.

      \n

      The Promise is resolved with an object containing a bytesWritten property\nidentifying the number of bytes written, and a buffers property containing\na reference to the buffers input.

      \n

      position is the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position.

      \n

      It is unsafe to call writev() multiple times on the same file without waiting\nfor the previous operation to complete.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + } + ], + "properties": [ + { + "textRaw": "`fd` {number} The numeric file descriptor managed by the `FileHandle` object.", + "type": "number", + "name": "fd", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "The numeric file descriptor managed by the `FileHandle` object." + } + ] + } + ], + "methods": [ + { + "textRaw": "`fsPromises.access(path[, mode])`", + "type": "method", + "name": "access", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", + "name": "mode", + "type": "integer", + "default": "`fs.constants.F_OK`" + } + ] + } + ], + "desc": "

      Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. Check File access constants for possible values\nof mode. It is possible to create a mask consisting of the bitwise OR of\ntwo or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      \n

      If the accessibility check is successful, the Promise is resolved with no\nvalue. If any of the accessibility checks fail, the Promise is rejected\nwith an Error object. The following example checks if the file\n/etc/passwd can be read and written by the current process.

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\n\nfsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK)\n  .then(() => console.log('can access'))\n  .catch(() => console.error('cannot access'));\n
      \n

      Using fsPromises.access() to check for the accessibility of a file before\ncalling fsPromises.open() is not recommended. Doing so introduces a race\ncondition, since other processes may change the file's state between the two\ncalls. Instead, user code should open/read/write the file directly and handle\nthe error raised if the file is not accessible.

      " + }, + { + "textRaw": "`fsPromises.appendFile(path, data[, options])`", + "type": "method", + "name": "appendFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|FileHandle} filename or `FileHandle`", + "name": "path", + "type": "string|Buffer|URL|FileHandle", + "desc": "filename or `FileHandle`" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.", + "name": "flag", + "type": "string", + "default": "`'a'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a Buffer. The Promise will be\nresolved with no arguments upon success.

      \n

      If options is a string, then it specifies the encoding.

      \n

      The path may be specified as a FileHandle that has been opened\nfor appending (using fsPromises.open()).

      " + }, + { + "textRaw": "`fsPromises.chmod(path, mode)`", + "type": "method", + "name": "chmod", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + } + ] + } + ], + "desc": "

      Changes the permissions of a file then resolves the Promise with no\narguments upon succces.

      " + }, + { + "textRaw": "`fsPromises.chown(path, uid, gid)`", + "type": "method", + "name": "chown", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the ownership of a file then resolves the Promise with no arguments\nupon success.

      " + }, + { + "textRaw": "`fsPromises.copyFile(src, dest[, flags])`", + "type": "method", + "name": "copyFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v14.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27044", + "description": "Changed 'flags' argument to 'mode' and imposed stricter type validation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`src` {string|Buffer|URL} source filename to copy", + "name": "src", + "type": "string|Buffer|URL", + "desc": "source filename to copy" + }, + { + "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", + "name": "dest", + "type": "string|Buffer|URL", + "desc": "destination filename of the copy operation" + }, + { + "textRaw": "`flags` {number} modifiers for copy operation. **Default:** `0`.", + "name": "flags", + "type": "number", + "default": "`0`", + "desc": "modifiers for copy operation." + } + ] + } + ], + "desc": "

      Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists. The Promise will be resolved with no arguments upon success.

      \n

      Node.js makes no guarantees about the atomicity of the copy operation. If an\nerror occurs after the destination file has been opened for writing, Node.js\nwill attempt to remove the destination.

      \n

      flags is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      \n
        \n
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
      • \n
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.
      • \n
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support copy-on-write,\nthen the operation will fail.
      • \n
      \n
      const fsPromises = require('fs').promises;\n\n// destination.txt will be created or overwritten by default.\nfsPromises.copyFile('source.txt', 'destination.txt')\n  .then(() => console.log('source.txt was copied to destination.txt'))\n  .catch(() => console.log('The file could not be copied'));\n
      \n

      If the third argument is a number, then it specifies flags:

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\nconst { COPYFILE_EXCL } = fs.constants;\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\nfsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL)\n  .then(() => console.log('source.txt was copied to destination.txt'))\n  .catch(() => console.log('The file could not be copied'));\n
      " + }, + { + "textRaw": "`fsPromises.lchmod(path, mode)`", + "type": "method", + "name": "lchmod", + "meta": { + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the permissions on a symbolic link then resolves the Promise with\nno arguments upon success. This method is only implemented on macOS.

      " + }, + { + "textRaw": "`fsPromises.lchown(path, uid, gid)`", + "type": "method", + "name": "lchown", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "This API is no longer deprecated." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the ownership on a symbolic link then resolves the Promise with\nno arguments upon success.

      " + }, + { + "textRaw": "`fsPromises.lutimes(path, atime, mtime)`", + "type": "method", + "name": "lutimes", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Changes the access and modification times of a file in the same way as\nfsPromises.utimes(), with the difference that if the path refers to a\nsymbolic link, then the link is not dereferenced: instead, the timestamps of\nthe symbolic link itself are changed.

      \n

      Upon success, the Promise is resolved without arguments.

      " + }, + { + "textRaw": "`fsPromises.link(existingPath, newPath)`", + "type": "method", + "name": "link", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`existingPath` {string|Buffer|URL}", + "name": "existingPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Asynchronous link(2). The Promise is resolved with no arguments upon success.

      " + }, + { + "textRaw": "`fsPromises.lstat(path[, options])`", + "type": "method", + "name": "lstat", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lstat(2). The Promise is resolved with the fs.Stats object\nfor the given symbolic link path.

      " + }, + { + "textRaw": "`fsPromises.mkdir(path[, options])`", + "type": "method", + "name": "mkdir", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object|integer}", + "name": "options", + "type": "Object|integer", + "options": [ + { + "textRaw": "`recursive` {boolean} **Default:** `false`", + "name": "recursive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", + "name": "mode", + "type": "string|integer", + "default": "`0o777`", + "desc": "Not supported on Windows." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously creates a directory then resolves the Promise with either no\narguments, or the first directory path created if recursive is true.

      \n

      The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfsPromises.mkdir() when path is a directory that exists results in a\nrejection only when recursive is false.

      " + }, + { + "textRaw": "`fsPromises.mkdtemp(prefix[, options])`", + "type": "method", + "name": "mkdtemp", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`prefix` {string}", + "name": "prefix", + "type": "string" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Creates a unique temporary directory and resolves the Promise with the created\ndirectory path. A unique directory name is generated by appending six random\ncharacters to the end of the provided prefix. Due to platform\ninconsistencies, avoid trailing X characters in prefix. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing X characters in prefix with random characters.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

      \n
      fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))\n  .catch(console.error);\n
      \n

      The fsPromises.mkdtemp() method will append the six randomly selected\ncharacters directly to the prefix string. For instance, given a directory\n/tmp, if the intention is to create a temporary directory within /tmp, the\nprefix must end with a trailing platform-specific path separator\n(require('path').sep).

      " + }, + { + "textRaw": "`fsPromises.open(path, flags[, mode])`", + "type": "method", + "name": "open", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v11.1.0", + "pr-url": "https://github.com/nodejs/node/pull/23767", + "description": "The `flags` argument is now optional and defaults to `'r'`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`flags` {string|number} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flags", + "type": "string|number", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`mode` {string|integer} **Default:** `0o666` (readable and writable)", + "name": "mode", + "type": "string|integer", + "default": "`0o666` (readable and writable)" + } + ] + } + ], + "desc": "

      Asynchronous file open that returns a Promise that, when resolved, yields a\nFileHandle object. See open(2).

      \n

      mode sets the file mode (permission and sticky bits), but only if the file was\ncreated.

      \n

      Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.

      " + }, + { + "textRaw": "`fsPromises.opendir(path[, options])`", + "type": "method", + "name": "opendir", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30114", + "description": "The `bufferSize` option was introduced." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} containing {fs.Dir}", + "name": "return", + "type": "Promise", + "desc": "containing {fs.Dir}" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`", + "name": "bufferSize", + "type": "number", + "default": "`32`", + "desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously open a directory. See opendir(3).

      \n

      Creates an fs.Dir, which contains all further functions for reading from\nand cleaning up the directory.

      \n

      The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

      \n

      Example using async iteration:

      \n
      const fs = require('fs');\n\nasync function print(path) {\n  const dir = await fs.promises.opendir(path);\n  for await (const dirent of dir) {\n    console.log(dirent.name);\n  }\n}\nprint('./').catch(console.error);\n
      " + }, + { + "textRaw": "`fsPromises.readdir(path[, options])`", + "type": "method", + "name": "readdir", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.11.0", + "pr-url": "https://github.com/nodejs/node/pull/22020", + "description": "New option `withFileTypes` was added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`withFileTypes` {boolean} **Default:** `false`", + "name": "withFileTypes", + "type": "boolean", + "default": "`false`" + } + ] + } + ] + } + ], + "desc": "

      Reads the contents of a directory then resolves the Promise with an array\nof the names of the files in the directory excluding '.' and '..'.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames. If the encoding is set to 'buffer', the filenames returned\nwill be passed as Buffer objects.

      \n

      If options.withFileTypes is set to true, the resolved array will contain\nfs.Dirent objects.

      \n
      const fs = require('fs');\n\nasync function print(path) {\n  const files = await fs.promises.readdir(path);\n  for (const file of files) {\n    console.log(file);\n  }\n}\nprint('./').catch(console.error);\n
      " + }, + { + "textRaw": "`fsPromises.readFile(path[, options])`", + "type": "method", + "name": "readFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|FileHandle} filename or `FileHandle`", + "name": "path", + "type": "string|Buffer|URL|FileHandle", + "desc": "filename or `FileHandle`" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flag", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously reads the entire contents of a file.

      \n

      The Promise is resolved with the contents of the file. If no encoding is\nspecified (using options.encoding), the data is returned as a Buffer\nobject. Otherwise, the data will be a string.

      \n

      If options is a string, then it specifies the encoding.

      \n

      When the path is a directory, the behavior of fsPromises.readFile() is\nplatform-specific. On macOS, Linux, and Windows, the promise will be rejected\nwith an error. On FreeBSD, a representation of the directory's contents will be\nreturned.

      \n

      Any specified FileHandle has to support reading.

      " + }, + { + "textRaw": "`fsPromises.readlink(path[, options])`", + "type": "method", + "name": "readlink", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous readlink(2). The Promise is resolved with the linkString upon\nsuccess.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer', the link path\nreturned will be passed as a Buffer object.

      " + }, + { + "textRaw": "`fsPromises.realpath(path[, options])`", + "type": "method", + "name": "realpath", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Determines the actual location of path using the same semantics as the\nfs.realpath.native() function then resolves the Promise with the resolved\npath.

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path. If the encoding is set to 'buffer', the path returned will be\npassed as a Buffer object.

      \n

      On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.

      " + }, + { + "textRaw": "`fsPromises.rename(oldPath, newPath)`", + "type": "method", + "name": "rename", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`oldPath` {string|Buffer|URL}", + "name": "oldPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Renames oldPath to newPath and resolves the Promise with no arguments\nupon success.

      " + }, + { + "textRaw": "`fsPromises.rmdir(path[, options])`", + "type": "method", + "name": "rmdir", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30644", + "description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried." + }, + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29168", + "description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported." + } + ] + }, + "stability": 1, + "stabilityText": "Recursive removal is experimental.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", + "name": "maxRetries", + "type": "integer", + "default": "`0`", + "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." + }, + { + "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure. **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure." + }, + { + "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", + "name": "retryDelay", + "type": "integer", + "default": "`100`", + "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." + } + ] + } + ] + } + ], + "desc": "

      Removes the directory identified by path then resolves the Promise with\nno arguments upon success.

      \n

      Using fsPromises.rmdir() on a file (not a directory) results in the\nPromise being rejected with an ENOENT error on Windows and an ENOTDIR\nerror on POSIX.

      " + }, + { + "textRaw": "`fsPromises.stat(path[, options])`", + "type": "method", + "name": "stat", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      The Promise is resolved with the fs.Stats object for the given path.

      " + }, + { + "textRaw": "`fsPromises.symlink(target, path[, type])`", + "type": "method", + "name": "symlink", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`target` {string|Buffer|URL}", + "name": "target", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`type` {string} **Default:** `'file'`", + "name": "type", + "type": "string", + "default": "`'file'`" + } + ] + } + ], + "desc": "

      Creates a symbolic link then resolves the Promise with no arguments upon\nsuccess.

      \n

      The type argument is only used on Windows platforms and can be one of 'dir',\n'file', or 'junction'. Windows junction points require the destination path\nto be absolute. When using 'junction', the target argument will\nautomatically be normalized to absolute path.

      " + }, + { + "textRaw": "`fsPromises.truncate(path[, len])`", + "type": "method", + "name": "truncate", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Truncates the path then resolves the Promise with no arguments upon\nsuccess. The path must be a string or Buffer.

      " + }, + { + "textRaw": "`fsPromises.unlink(path)`", + "type": "method", + "name": "unlink", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Asynchronous unlink(2). The Promise is resolved with no arguments upon\nsuccess.

      " + }, + { + "textRaw": "`fsPromises.utimes(path, atime, mtime)`", + "type": "method", + "name": "utimes", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by path then\nresolves the Promise with no arguments upon success.

      \n

      The atime and mtime arguments follow these rules:

      \n
        \n
      • Values can be either numbers representing Unix epoch time, Dates, or a\nnumeric string like '123456789.0'.
      • \n
      • If the value can not be converted to a number, or is NaN, Infinity or\n-Infinity, an Error will be thrown.
      • \n
      " + }, + { + "textRaw": "`fsPromises.writeFile(file, data[, options])`", + "type": "method", + "name": "writeFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`file` {string|Buffer|URL|FileHandle} filename or `FileHandle`", + "name": "file", + "type": "string|Buffer|URL|FileHandle", + "desc": "filename or `FileHandle`" + }, + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flag", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer. The Promise will be resolved with no\narguments upon success.

      \n

      The encoding option is ignored if data is a buffer.

      \n

      If options is a string, then it specifies the encoding.

      \n

      Any specified FileHandle has to support writing.

      \n

      It is unsafe to use fsPromises.writeFile() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected).

      " + } + ], + "type": "module", + "displayName": "`fs` Promises API" + }, + { + "textRaw": "FS constants", + "name": "fs_constants", + "desc": "

      The following constants are exported by fs.constants.

      \n

      Not every constant will be available on every operating system.

      \n

      To use more than one constant, use the bitwise OR | operator.

      \n

      Example:

      \n
      const fs = require('fs');\n\nconst {\n  O_RDWR,\n  O_CREAT,\n  O_EXCL\n} = fs.constants;\n\nfs.open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {\n  // ...\n});\n
      ", + "modules": [ + { + "textRaw": "File access constants", + "name": "file_access_constants", + "desc": "

      The following constants are meant for use with fs.access().

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      F_OKFlag indicating that the file is visible to the calling process.\n This is useful for determining if a file exists, but says nothing\n about rwx permissions. Default if no mode is specified.
      R_OKFlag indicating that the file can be read by the calling process.
      W_OKFlag indicating that the file can be written by the calling\n process.
      X_OKFlag indicating that the file can be executed by the calling\n process. This has no effect on Windows\n (will behave like fs.constants.F_OK).
      ", + "type": "module", + "displayName": "File access constants" + }, + { + "textRaw": "File copy constants", + "name": "file_copy_constants", + "desc": "

      The following constants are meant for use with fs.copyFile().

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      COPYFILE_EXCLIf present, the copy operation will fail with an error if the\n destination path already exists.
      COPYFILE_FICLONEIf present, the copy operation will attempt to create a\n copy-on-write reflink. If the underlying platform does not support\n copy-on-write, then a fallback copy mechanism is used.
      COPYFILE_FICLONE_FORCEIf present, the copy operation will attempt to create a\n copy-on-write reflink. If the underlying platform does not support\n copy-on-write, then the operation will fail with an error.
      ", + "type": "module", + "displayName": "File copy constants" + }, + { + "textRaw": "File open constants", + "name": "file_open_constants", + "desc": "

      The following constants are meant for use with fs.open().

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      O_RDONLYFlag indicating to open a file for read-only access.
      O_WRONLYFlag indicating to open a file for write-only access.
      O_RDWRFlag indicating to open a file for read-write access.
      O_CREATFlag indicating to create the file if it does not already exist.
      O_EXCLFlag indicating that opening a file should fail if the\n O_CREAT flag is set and the file already exists.
      O_NOCTTYFlag indicating that if path identifies a terminal device, opening the\n path shall not cause that terminal to become the controlling terminal for\n the process (if the process does not already have one).
      O_TRUNCFlag indicating that if the file exists and is a regular file, and the\n file is opened successfully for write access, its length shall be truncated\n to zero.
      O_APPENDFlag indicating that data will be appended to the end of the file.
      O_DIRECTORYFlag indicating that the open should fail if the path is not a\n directory.
      O_NOATIMEFlag indicating reading accesses to the file system will no longer\n result in an update to the atime information associated with\n the file. This flag is available on Linux operating systems only.
      O_NOFOLLOWFlag indicating that the open should fail if the path is a symbolic\n link.
      O_SYNCFlag indicating that the file is opened for synchronized I/O with write\n operations waiting for file integrity.
      O_DSYNCFlag indicating that the file is opened for synchronized I/O with write\n operations waiting for data integrity.
      O_SYMLINKFlag indicating to open the symbolic link itself rather than the\n resource it is pointing to.
      O_DIRECTWhen set, an attempt will be made to minimize caching effects of file\n I/O.
      O_NONBLOCKFlag indicating to open the file in nonblocking mode when possible.
      UV_FS_O_FILEMAPWhen set, a memory file mapping is used to access the file. This flag\n is available on Windows operating systems only. On other operating systems,\n this flag is ignored.
      ", + "type": "module", + "displayName": "File open constants" + }, + { + "textRaw": "File type constants", + "name": "file_type_constants", + "desc": "

      The following constants are meant for use with the fs.Stats object's\nmode property for determining a file's type.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      S_IFMTBit mask used to extract the file type code.
      S_IFREGFile type constant for a regular file.
      S_IFDIRFile type constant for a directory.
      S_IFCHRFile type constant for a character-oriented device file.
      S_IFBLKFile type constant for a block-oriented device file.
      S_IFIFOFile type constant for a FIFO/pipe.
      S_IFLNKFile type constant for a symbolic link.
      S_IFSOCKFile type constant for a socket.
      ", + "type": "module", + "displayName": "File type constants" + }, + { + "textRaw": "File mode constants", + "name": "file_mode_constants", + "desc": "

      The following constants are meant for use with the fs.Stats object's\nmode property for determining the access permissions for a file.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      S_IRWXUFile mode indicating readable, writable, and executable by owner.
      S_IRUSRFile mode indicating readable by owner.
      S_IWUSRFile mode indicating writable by owner.
      S_IXUSRFile mode indicating executable by owner.
      S_IRWXGFile mode indicating readable, writable, and executable by group.
      S_IRGRPFile mode indicating readable by group.
      S_IWGRPFile mode indicating writable by group.
      S_IXGRPFile mode indicating executable by group.
      S_IRWXOFile mode indicating readable, writable, and executable by others.
      S_IROTHFile mode indicating readable by others.
      S_IWOTHFile mode indicating writable by others.
      S_IXOTHFile mode indicating executable by others.
      ", + "type": "module", + "displayName": "File mode constants" + } + ], + "type": "module", + "displayName": "FS constants" + }, + { + "textRaw": "File system flags", + "name": "file_system_flags", + "desc": "

      The following flags are available wherever the flag option takes a\nstring.

      \n
        \n
      • \n

        'a': Open file for appending.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'ax': Like 'a' but fails if the path exists.

        \n
      • \n
      • \n

        'a+': Open file for reading and appending.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'ax+': Like 'a+' but fails if the path exists.

        \n
      • \n
      • \n

        'as': Open file for appending in synchronous mode.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'as+': Open file for reading and appending in synchronous mode.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'r': Open file for reading.\nAn exception occurs if the file does not exist.

        \n
      • \n
      • \n

        'r+': Open file for reading and writing.\nAn exception occurs if the file does not exist.

        \n
      • \n
      • \n

        'rs+': Open file for reading and writing in synchronous mode. Instructs\nthe operating system to bypass the local file system cache.

        \n

        This is primarily useful for opening files on NFS mounts as it allows\nskipping the potentially stale local cache. It has a very real impact on\nI/O performance so using this flag is not recommended unless it is needed.

        \n

        This doesn't turn fs.open() or fsPromises.open() into a synchronous\nblocking call. If synchronous operation is desired, something like\nfs.openSync() should be used.

        \n
      • \n
      • \n

        'w': Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

        \n
      • \n
      • \n

        'wx': Like 'w' but fails if the path exists.

        \n
      • \n
      • \n

        'w+': Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

        \n
      • \n
      • \n

        'wx+': Like 'w+' but fails if the path exists.

        \n
      • \n
      \n

      flag can also be a number as documented by open(2); commonly used constants\nare available from fs.constants. On Windows, flags are translated to\ntheir equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE,\nor O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.

      \n

      The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to\nreturn an error if the path already exists. On POSIX, if the path is a symbolic\nlink, using O_EXCL returns an error even if the link is to a path that does\nnot exist. The exclusive flag may or may not work with network file systems.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      \n

      Modifying a file rather than replacing it may require a flags mode of 'r+'\nrather than the default mode 'w'.

      \n

      The behavior of some flags are platform-specific. As such, opening a directory\non macOS and Linux with the 'a+' flag, as in the example below, will return an\nerror. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle\nwill be returned.

      \n
      // macOS and Linux\nfs.open('<directory>', 'a+', (err, fd) => {\n  // => [Error: EISDIR: illegal operation on a directory, open <directory>]\n});\n\n// Windows and FreeBSD\nfs.open('<directory>', 'a+', (err, fd) => {\n  // => null, <fd>\n});\n
      \n

      On Windows, opening an existing hidden file using the 'w' flag (either\nthrough fs.open() or fs.writeFile() or fsPromises.open()) will fail with\nEPERM. Existing hidden files can be opened for writing with the 'r+' flag.

      \n

      A call to fs.ftruncate() or filehandle.truncate() can be used to reset\nthe file contents.

      ", + "type": "module", + "displayName": "File system flags" + } + ], + "classes": [ + { + "textRaw": "Class: `fs.Dir`", + "type": "class", + "name": "fs.Dir", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      A class representing a directory stream.

      \n

      Created by fs.opendir(), fs.opendirSync(), or\nfsPromises.opendir().

      \n
      const fs = require('fs');\n\nasync function print(path) {\n  const dir = await fs.promises.opendir(path);\n  for await (const dirent of dir) {\n    console.log(dirent.name);\n  }\n}\nprint('./').catch(console.error);\n
      ", + "methods": [ + { + "textRaw": "`dir.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

      \n

      A Promise is returned that will be resolved after the resource has been\nclosed.

      " + }, + { + "textRaw": "`dir.close(callback)`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

      \n

      The callback will be called after the resource handle has been closed.

      " + }, + { + "textRaw": "`dir.closeSync()`", + "type": "method", + "name": "closeSync", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Synchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

      " + }, + { + "textRaw": "`dir.read()`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} containing {fs.Dirent|null}", + "name": "return", + "type": "Promise", + "desc": "containing {fs.Dirent|null}" + }, + "params": [] + } + ], + "desc": "

      Asynchronously read the next directory entry via readdir(3) as an\nfs.Dirent.

      \n

      After the read is completed, a Promise is returned that will be resolved with\nan fs.Dirent, or null if there are no more directory entries to read.

      \n

      Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + }, + { + "textRaw": "`dir.read(callback)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`dirent` {fs.Dirent|null}", + "name": "dirent", + "type": "fs.Dirent|null" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously read the next directory entry via readdir(3) as an\nfs.Dirent.

      \n

      After the read is completed, the callback will be called with an\nfs.Dirent, or null if there are no more directory entries to read.

      \n

      Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + }, + { + "textRaw": "`dir.readSync()`", + "type": "method", + "name": "readSync", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Dirent|null}", + "name": "return", + "type": "fs.Dirent|null" + }, + "params": [] + } + ], + "desc": "

      Synchronously read the next directory entry via readdir(3) as an\nfs.Dirent.

      \n

      If there are no more directory entries to read, null will be returned.

      \n

      Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + }, + { + "textRaw": "`dir[Symbol.asyncIterator]()`", + "type": "method", + "name": "[Symbol.asyncIterator]", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator} of {fs.Dirent}", + "name": "return", + "type": "AsyncIterator", + "desc": "of {fs.Dirent}" + }, + "params": [] + } + ], + "desc": "

      Asynchronously iterates over the directory via readdir(3) until all entries have\nbeen read.

      \n

      Entries returned by the async iterator are always an fs.Dirent.\nThe null case from dir.read() is handled internally.

      \n

      See fs.Dir for an example.

      \n

      Directory entries returned by this iterator are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + } + ], + "properties": [ + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      The read-only path of this directory as was provided to fs.opendir(),\nfs.opendirSync(), or fsPromises.opendir().

      " + } + ] + }, + { + "textRaw": "Class: `fs.Dirent`", + "type": "class", + "name": "fs.Dirent", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      A representation of a directory entry, which can be a file or a subdirectory\nwithin the directory, as returned by reading from an fs.Dir. The\ndirectory entry is a combination of the file name and file type pairs.

      \n

      Additionally, when fs.readdir() or fs.readdirSync() is called with\nthe withFileTypes option set to true, the resulting array is filled with\nfs.Dirent objects, rather than strings or Buffers.

      ", + "methods": [ + { + "textRaw": "`dirent.isBlockDevice()`", + "type": "method", + "name": "isBlockDevice", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a block device.

      " + }, + { + "textRaw": "`dirent.isCharacterDevice()`", + "type": "method", + "name": "isCharacterDevice", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a character device.

      " + }, + { + "textRaw": "`dirent.isDirectory()`", + "type": "method", + "name": "isDirectory", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a file system\ndirectory.

      " + }, + { + "textRaw": "`dirent.isFIFO()`", + "type": "method", + "name": "isFIFO", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a first-in-first-out\n(FIFO) pipe.

      " + }, + { + "textRaw": "`dirent.isFile()`", + "type": "method", + "name": "isFile", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a regular file.

      " + }, + { + "textRaw": "`dirent.isSocket()`", + "type": "method", + "name": "isSocket", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a socket.

      " + }, + { + "textRaw": "`dirent.isSymbolicLink()`", + "type": "method", + "name": "isSymbolicLink", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a symbolic link.

      " + } + ], + "properties": [ + { + "textRaw": "`name` {string|Buffer}", + "type": "string|Buffer", + "name": "name", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      The file name that this fs.Dirent object refers to. The type of this\nvalue is determined by the options.encoding passed to fs.readdir() or\nfs.readdirSync().

      " + } + ] + }, + { + "textRaw": "Class: `fs.FSWatcher`", + "type": "class", + "name": "fs.FSWatcher", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "\n

      A successful call to fs.watch() method will return a new fs.FSWatcher\nobject.

      \n

      All fs.FSWatcher objects emit a 'change' event whenever a specific watched\nfile is modified.

      ", + "events": [ + { + "textRaw": "Event: `'change'`", + "type": "event", + "name": "change", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`eventType` {string} The type of change event that has occurred", + "name": "eventType", + "type": "string", + "desc": "The type of change event that has occurred" + }, + { + "textRaw": "`filename` {string|Buffer} The filename that changed (if relevant/available)", + "name": "filename", + "type": "string|Buffer", + "desc": "The filename that changed (if relevant/available)" + } + ], + "desc": "

      Emitted when something changes in a watched directory or file.\nSee more details in fs.watch().

      \n

      The filename argument may not be provided depending on operating system\nsupport. If filename is provided, it will be provided as a Buffer if\nfs.watch() is called with its encoding option set to 'buffer', otherwise\nfilename will be a UTF-8 string.

      \n
      // Example when handled through fs.watch() listener\nfs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {\n  if (filename) {\n    console.log(filename);\n    // Prints: <Buffer ...>\n  }\n});\n
      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the watcher stops watching for changes. The closed\nfs.FSWatcher object is no longer usable in the event handler.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ], + "desc": "

      Emitted when an error occurs while watching the file. The errored\nfs.FSWatcher object is no longer usable in the event handler.

      " + } + ], + "methods": [ + { + "textRaw": "`watcher.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Stop watching for changes on the given fs.FSWatcher. Once stopped, the\nfs.FSWatcher object is no longer usable.

      " + }, + { + "textRaw": "`watcher.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.FSWatcher}", + "name": "return", + "type": "fs.FSWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nFSWatcher is active. Calling watcher.ref() multiple times will have\nno effect.

      \n

      By default, all FSWatcher objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.

      " + }, + { + "textRaw": "`watcher.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.FSWatcher}", + "name": "return", + "type": "fs.FSWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, the active FSWatcher object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the FSWatcher object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.

      " + } + ] + }, + { + "textRaw": "Class: `fs.StatWatcher`", + "type": "class", + "name": "fs.StatWatcher", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "desc": "\n

      A successful call to fs.watchFile() method will return a new fs.StatWatcher\nobject.

      ", + "methods": [ + { + "textRaw": "`watcher.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.StatWatcher}", + "name": "return", + "type": "fs.StatWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nStatWatcher is active. Calling watcher.ref() multiple times will have\nno effect.

      \n

      By default, all StatWatcher objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.

      " + }, + { + "textRaw": "`watcher.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.StatWatcher}", + "name": "return", + "type": "fs.StatWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, the active StatWatcher object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the StatWatcher object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.

      " + } + ] + }, + { + "textRaw": "Class: `fs.ReadStream`", + "type": "class", + "name": "fs.ReadStream", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "\n

      Instances of fs.ReadStream are created and returned using the\nfs.createReadStream() function.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the fs.ReadStream's underlying file descriptor has been closed.

      " + }, + { + "textRaw": "Event: `'open'`", + "type": "event", + "name": "open", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`fd` {integer} Integer file descriptor used by the `ReadStream`.", + "name": "fd", + "type": "integer", + "desc": "Integer file descriptor used by the `ReadStream`." + } + ], + "desc": "

      Emitted when the fs.ReadStream's file descriptor has been opened.

      " + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v9.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the fs.ReadStream is ready to be used.

      \n

      Fires immediately after 'open'.

      " + } + ], + "properties": [ + { + "textRaw": "`bytesRead` {number}", + "type": "number", + "name": "bytesRead", + "meta": { + "added": [ + "v6.4.0" + ], + "changes": [] + }, + "desc": "

      The number of bytes that have been read so far.

      " + }, + { + "textRaw": "`path` {string|Buffer}", + "type": "string|Buffer", + "name": "path", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "

      The path to the file the stream is reading from as specified in the first\nargument to fs.createReadStream(). If path is passed as a string, then\nreadStream.path will be a string. If path is passed as a Buffer, then\nreadStream.path will be a Buffer.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.

      " + } + ] + }, + { + "textRaw": "Class: `fs.Stats`", + "type": "class", + "name": "fs.Stats", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v8.1.0", + "pr-url": "https://github.com/nodejs/node/pull/13173", + "description": "Added times as numbers." + } + ] + }, + "desc": "

      A fs.Stats object provides information about a file.

      \n

      Objects returned from fs.stat(), fs.lstat() and fs.fstat() and\ntheir synchronous counterparts are of this type.\nIf bigint in the options passed to those methods is true, the numeric values\nwill be bigint instead of number, and the object will contain additional\nnanosecond-precision properties suffixed with Ns.

      \n
      Stats {\n  dev: 2114,\n  ino: 48064969,\n  mode: 33188,\n  nlink: 1,\n  uid: 85,\n  gid: 100,\n  rdev: 0,\n  size: 527,\n  blksize: 4096,\n  blocks: 8,\n  atimeMs: 1318289051000.1,\n  mtimeMs: 1318289051000.1,\n  ctimeMs: 1318289051000.1,\n  birthtimeMs: 1318289051000.1,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n
      \n

      bigint version:

      \n
      BigIntStats {\n  dev: 2114n,\n  ino: 48064969n,\n  mode: 33188n,\n  nlink: 1n,\n  uid: 85n,\n  gid: 100n,\n  rdev: 0n,\n  size: 527n,\n  blksize: 4096n,\n  blocks: 8n,\n  atimeMs: 1318289051000n,\n  mtimeMs: 1318289051000n,\n  ctimeMs: 1318289051000n,\n  birthtimeMs: 1318289051000n,\n  atimeNs: 1318289051000000000n,\n  mtimeNs: 1318289051000000000n,\n  ctimeNs: 1318289051000000000n,\n  birthtimeNs: 1318289051000000000n,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n
      ", + "methods": [ + { + "textRaw": "`stats.isBlockDevice()`", + "type": "method", + "name": "isBlockDevice", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a block device.

      " + }, + { + "textRaw": "`stats.isCharacterDevice()`", + "type": "method", + "name": "isCharacterDevice", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a character device.

      " + }, + { + "textRaw": "`stats.isDirectory()`", + "type": "method", + "name": "isDirectory", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a file system directory.

      " + }, + { + "textRaw": "`stats.isFIFO()`", + "type": "method", + "name": "isFIFO", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a first-in-first-out (FIFO)\npipe.

      " + }, + { + "textRaw": "`stats.isFile()`", + "type": "method", + "name": "isFile", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a regular file.

      " + }, + { + "textRaw": "`stats.isSocket()`", + "type": "method", + "name": "isSocket", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a socket.

      " + }, + { + "textRaw": "`stats.isSymbolicLink()`", + "type": "method", + "name": "isSymbolicLink", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a symbolic link.

      \n

      This method is only valid when using fs.lstat().

      " + } + ], + "properties": [ + { + "textRaw": "`dev` {number|bigint}", + "type": "number|bigint", + "name": "dev", + "desc": "

      The numeric identifier of the device containing the file.

      " + }, + { + "textRaw": "`ino` {number|bigint}", + "type": "number|bigint", + "name": "ino", + "desc": "

      The file system specific \"Inode\" number for the file.

      " + }, + { + "textRaw": "`mode` {number|bigint}", + "type": "number|bigint", + "name": "mode", + "desc": "

      A bit-field describing the file type and mode.

      " + }, + { + "textRaw": "`nlink` {number|bigint}", + "type": "number|bigint", + "name": "nlink", + "desc": "

      The number of hard-links that exist for the file.

      " + }, + { + "textRaw": "`uid` {number|bigint}", + "type": "number|bigint", + "name": "uid", + "desc": "

      The numeric user identifier of the user that owns the file (POSIX).

      " + }, + { + "textRaw": "`gid` {number|bigint}", + "type": "number|bigint", + "name": "gid", + "desc": "

      The numeric group identifier of the group that owns the file (POSIX).

      " + }, + { + "textRaw": "`rdev` {number|bigint}", + "type": "number|bigint", + "name": "rdev", + "desc": "

      A numeric device identifier if the file represents a device.

      " + }, + { + "textRaw": "`size` {number|bigint}", + "type": "number|bigint", + "name": "size", + "desc": "

      The size of the file in bytes.

      " + }, + { + "textRaw": "`blksize` {number|bigint}", + "type": "number|bigint", + "name": "blksize", + "desc": "

      The file system block size for i/o operations.

      " + }, + { + "textRaw": "`blocks` {number|bigint}", + "type": "number|bigint", + "name": "blocks", + "desc": "

      The number of blocks allocated for this file.

      " + }, + { + "textRaw": "`atimeMs` {number|bigint}", + "type": "number|bigint", + "name": "atimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was accessed expressed in\nmilliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`mtimeMs` {number|bigint}", + "type": "number|bigint", + "name": "mtimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was modified expressed in\nmilliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`ctimeMs` {number|bigint}", + "type": "number|bigint", + "name": "ctimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time the file status was changed expressed\nin milliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`birthtimeMs` {number|bigint}", + "type": "number|bigint", + "name": "birthtimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the creation time of this file expressed in\nmilliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`atimeNs` {bigint}", + "type": "bigint", + "name": "atimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was accessed expressed in\nnanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`mtimeNs` {bigint}", + "type": "bigint", + "name": "mtimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was modified expressed in\nnanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`ctimeNs` {bigint}", + "type": "bigint", + "name": "ctimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time the file status was changed expressed\nin nanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`birthtimeNs` {bigint}", + "type": "bigint", + "name": "birthtimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the creation time of this file expressed in\nnanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`atime` {Date}", + "type": "Date", + "name": "atime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was accessed.

      " + }, + { + "textRaw": "`mtime` {Date}", + "type": "Date", + "name": "mtime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was modified.

      " + }, + { + "textRaw": "`ctime` {Date}", + "type": "Date", + "name": "ctime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time the file status was changed.

      " + }, + { + "textRaw": "`birthtime` {Date}", + "type": "Date", + "name": "birthtime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the creation time of this file.

      " + } + ], + "modules": [ + { + "textRaw": "Stat time values", + "name": "stat_time_values", + "desc": "

      The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are\nnumeric values that hold the corresponding times in milliseconds. Their\nprecision is platform specific. When bigint: true is passed into the\nmethod that generates the object, the properties will be bigints,\notherwise they will be numbers.

      \n

      The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are\nbigints that hold the corresponding times in nanoseconds. They are\nonly present when bigint: true is passed into the method that generates\nthe object. Their precision is platform specific.

      \n

      atime, mtime, ctime, and birthtime are\nDate object alternate representations of the various times. The\nDate and number values are not connected. Assigning a new number value, or\nmutating the Date value, will not be reflected in the corresponding alternate\nrepresentation.

      \n

      The times in the stat object have the following semantics:

      \n
        \n
      • atime \"Access Time\": Time when file data last accessed. Changed\nby the mknod(2), utimes(2), and read(2) system calls.
      • \n
      • mtime \"Modified Time\": Time when file data last modified.\nChanged by the mknod(2), utimes(2), and write(2) system calls.
      • \n
      • ctime \"Change Time\": Time when file status was last changed\n(inode data modification). Changed by the chmod(2), chown(2),\nlink(2), mknod(2), rename(2), unlink(2), utimes(2),\nread(2), and write(2) system calls.
      • \n
      • birthtime \"Birth Time\": Time of file creation. Set once when the\nfile is created. On filesystems where birthtime is not available,\nthis field may instead hold either the ctime or\n1970-01-01T00:00Z (ie, Unix epoch timestamp 0). This value may be greater\nthan atime or mtime in this case. On Darwin and other FreeBSD variants,\nalso set if the atime is explicitly set to an earlier value than the current\nbirthtime using the utimes(2) system call.
      • \n
      \n

      Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As\nof 0.12, ctime is not \"creation time\", and on Unix systems, it never was.

      ", + "type": "module", + "displayName": "Stat time values" + } + ] + }, + { + "textRaw": "Class: `fs.WriteStream`", + "type": "class", + "name": "fs.WriteStream", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "\n

      Instances of fs.WriteStream are created and returned using the\nfs.createWriteStream() function.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the WriteStream's underlying file descriptor has been closed.

      " + }, + { + "textRaw": "Event: `'open'`", + "type": "event", + "name": "open", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`fd` {integer} Integer file descriptor used by the `WriteStream`.", + "name": "fd", + "type": "integer", + "desc": "Integer file descriptor used by the `WriteStream`." + } + ], + "desc": "

      Emitted when the WriteStream's file is opened.

      " + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v9.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the fs.WriteStream is ready to be used.

      \n

      Fires immediately after 'open'.

      " + } + ], + "properties": [ + { + "textRaw": "`writeStream.bytesWritten`", + "name": "bytesWritten", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [] + }, + "desc": "

      The number of bytes written so far. Does not include data that is still queued\nfor writing.

      " + }, + { + "textRaw": "`writeStream.path`", + "name": "path", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "

      The path to the file the stream is writing to as specified in the first\nargument to fs.createWriteStream(). If path is passed as a string, then\nwriteStream.path will be a string. If path is passed as a Buffer, then\nwriteStream.path will be a Buffer.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`fs.access(path[, mode], callback)`", + "type": "method", + "name": "access", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6534", + "description": "The constants like `fs.R_OK`, etc which were present directly on `fs` were moved into `fs.constants` as a soft deprecation. Thus for Node.js `< v6.3.0` use `fs` to access those constants, or do something like `(fs.constants || fs).R_OK` to work with all versions." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", + "name": "mode", + "type": "integer", + "default": "`fs.constants.F_OK`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. Check File access constants for possible values\nof mode. It is possible to create a mask consisting of the bitwise OR of\ntwo or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      \n

      The final argument, callback, is a callback function that is invoked with\na possible error argument. If any of the accessibility checks fail, the error\nargument will be an Error object. The following examples check if\npackage.json exists, and if it is readable or writable.

      \n
      const file = 'package.json';\n\n// Check if the file exists in the current directory.\nfs.access(file, fs.constants.F_OK, (err) => {\n  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);\n});\n\n// Check if the file is readable.\nfs.access(file, fs.constants.R_OK, (err) => {\n  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);\n});\n\n// Check if the file is writable.\nfs.access(file, fs.constants.W_OK, (err) => {\n  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);\n});\n\n// Check if the file exists in the current directory, and if it is writable.\nfs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {\n  if (err) {\n    console.error(\n      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);\n  } else {\n    console.log(`${file} exists, and it is writable`);\n  }\n});\n
      \n

      Do not use fs.access() to check for the accessibility of a file before calling\nfs.open(), fs.readFile() or fs.writeFile(). Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file is not accessible.

      \n

      write (NOT RECOMMENDED)

      \n
      fs.access('myfile', (err) => {\n  if (!err) {\n    console.error('myfile already exists');\n    return;\n  }\n\n  fs.open('myfile', 'wx', (err, fd) => {\n    if (err) throw err;\n    writeMyData(fd);\n  });\n});\n
      \n

      write (RECOMMENDED)

      \n
      fs.open('myfile', 'wx', (err, fd) => {\n  if (err) {\n    if (err.code === 'EEXIST') {\n      console.error('myfile already exists');\n      return;\n    }\n\n    throw err;\n  }\n\n  writeMyData(fd);\n});\n
      \n

      read (NOT RECOMMENDED)

      \n
      fs.access('myfile', (err) => {\n  if (err) {\n    if (err.code === 'ENOENT') {\n      console.error('myfile does not exist');\n      return;\n    }\n\n    throw err;\n  }\n\n  fs.open('myfile', 'r', (err, fd) => {\n    if (err) throw err;\n    readMyData(fd);\n  });\n});\n
      \n

      read (RECOMMENDED)

      \n
      fs.open('myfile', 'r', (err, fd) => {\n  if (err) {\n    if (err.code === 'ENOENT') {\n      console.error('myfile does not exist');\n      return;\n    }\n\n    throw err;\n  }\n\n  readMyData(fd);\n});\n
      \n

      The \"not recommended\" examples above check for accessibility and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.

      \n

      In general, check for the accessibility of a file only if the file will not be\nused directly, for example when its accessibility is a signal from another\nprocess.

      \n

      On Windows, access-control policies (ACLs) on a directory may limit access to\na file or directory. The fs.access() function, however, does not check the\nACL and therefore may report that a path is accessible even if the ACL restricts\nthe user from reading or writing to it.

      " + }, + { + "textRaw": "`fs.accessSync(path[, mode])`", + "type": "method", + "name": "accessSync", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", + "name": "mode", + "type": "integer", + "default": "`fs.constants.F_OK`" + } + ] + } + ], + "desc": "

      Synchronously tests a user's permissions for the file or directory specified\nby path. The mode argument is an optional integer that specifies the\naccessibility checks to be performed. Check File access constants for\npossible values of mode. It is possible to create a mask consisting of\nthe bitwise OR of two or more values\n(e.g. fs.constants.W_OK | fs.constants.R_OK).

      \n

      If any of the accessibility checks fail, an Error will be thrown. Otherwise,\nthe method will return undefined.

      \n
      try {\n  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);\n  console.log('can read/write');\n} catch (err) {\n  console.error('no access!');\n}\n
      " + }, + { + "textRaw": "`fs.appendFile(path, data[, options], callback)`", + "type": "method", + "name": "appendFile", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|number} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|number", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.", + "name": "flag", + "type": "string", + "default": "`'a'`", + "desc": "See [support of file system `flags`][]." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a Buffer.

      \n
      fs.appendFile('message.txt', 'data to append', (err) => {\n  if (err) throw err;\n  console.log('The \"data to append\" was appended to file!');\n});\n
      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.appendFile('message.txt', 'data to append', 'utf8', callback);\n
      \n

      The path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.

      \n
      fs.open('message.txt', 'a', (err, fd) => {\n  if (err) throw err;\n  fs.appendFile(fd, 'data to append', 'utf8', (err) => {\n    fs.close(fd, (err) => {\n      if (err) throw err;\n    });\n    if (err) throw err;\n  });\n});\n
      " + }, + { + "textRaw": "`fs.appendFileSync(path, data[, options])`", + "type": "method", + "name": "appendFileSync", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|number} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|number", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.", + "name": "flag", + "type": "string", + "default": "`'a'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Synchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a Buffer.

      \n
      try {\n  fs.appendFileSync('message.txt', 'data to append');\n  console.log('The \"data to append\" was appended to file!');\n} catch (err) {\n  /* Handle the error */\n}\n
      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.appendFileSync('message.txt', 'data to append', 'utf8');\n
      \n

      The path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.

      \n
      let fd;\n\ntry {\n  fd = fs.openSync('message.txt', 'a');\n  fs.appendFileSync(fd, 'data to append', 'utf8');\n} catch (err) {\n  /* Handle the error */\n} finally {\n  if (fd !== undefined)\n    fs.closeSync(fd);\n}\n
      " + }, + { + "textRaw": "`fs.chmod(path, mode, callback)`", + "type": "method", + "name": "chmod", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously changes the permissions of a file. No arguments other than a\npossible exception are given to the completion callback.

      \n

      See also: chmod(2).

      \n
      fs.chmod('my_file.txt', 0o775, (err) => {\n  if (err) throw err;\n  console.log('The permissions for file \"my_file.txt\" have been changed!');\n});\n
      ", + "modules": [ + { + "textRaw": "File modes", + "name": "file_modes", + "desc": "

      The mode argument used in both the fs.chmod() and fs.chmodSync()\nmethods is a numeric bitmask created using a logical OR of the following\nconstants:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      ConstantOctalDescription
      fs.constants.S_IRUSR0o400read by owner
      fs.constants.S_IWUSR0o200write by owner
      fs.constants.S_IXUSR0o100execute/search by owner
      fs.constants.S_IRGRP0o40read by group
      fs.constants.S_IWGRP0o20write by group
      fs.constants.S_IXGRP0o10execute/search by group
      fs.constants.S_IROTH0o4read by others
      fs.constants.S_IWOTH0o2write by others
      fs.constants.S_IXOTH0o1execute/search by others
      \n

      An easier method of constructing the mode is to use a sequence of three\noctal digits (e.g. 765). The left-most digit (7 in the example), specifies\nthe permissions for the file owner. The middle digit (6 in the example),\nspecifies permissions for the group. The right-most digit (5 in the example),\nspecifies the permissions for others.

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      NumberDescription
      7read, write, and execute
      6read and write
      5read and execute
      4read only
      3write and execute
      2write only
      1execute only
      0no permission
      \n

      For example, the octal value 0o765 means:

      \n
        \n
      • The owner may read, write and execute the file.
      • \n
      • The group may read and write the file.
      • \n
      • Others may read and execute the file.
      • \n
      \n

      When using raw numbers where file modes are expected, any value larger than\n0o777 may result in platform-specific behaviors that are not supported to work\nconsistently. Therefore constants like S_ISVTX, S_ISGID or S_ISUID are not\nexposed in fs.constants.

      \n

      Caveats: on Windows only the write permission can be changed, and the\ndistinction among the permissions of group, owner or others is not\nimplemented.

      ", + "type": "module", + "displayName": "File modes" + } + ] + }, + { + "textRaw": "`fs.chmodSync(path, mode)`", + "type": "method", + "name": "chmodSync", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.chmod().

      \n

      See also: chmod(2).

      " + }, + { + "textRaw": "`fs.chown(path, uid, gid, callback)`", + "type": "method", + "name": "chown", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously changes owner and group of a file. No arguments other than a\npossible exception are given to the completion callback.

      \n

      See also: chown(2).

      " + }, + { + "textRaw": "`fs.chownSync(path, uid, gid)`", + "type": "method", + "name": "chownSync", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronously changes owner and group of a file. Returns undefined.\nThis is the synchronous version of fs.chown().

      \n

      See also: chown(2).

      " + }, + { + "textRaw": "`fs.close(fd, callback)`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.

      \n

      Calling fs.close() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.

      " + }, + { + "textRaw": "`fs.closeSync(fd)`", + "type": "method", + "name": "closeSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous close(2). Returns undefined.

      \n

      Calling fs.closeSync() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.

      " + }, + { + "textRaw": "`fs.copyFile(src, dest[, flags], callback)`", + "type": "method", + "name": "copyFile", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": "v14.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27044", + "description": "Changed 'flags' argument to 'mode' and imposed stricter type validation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`src` {string|Buffer|URL} source filename to copy", + "name": "src", + "type": "string|Buffer|URL", + "desc": "source filename to copy" + }, + { + "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", + "name": "dest", + "type": "string|Buffer|URL", + "desc": "destination filename of the copy operation" + }, + { + "textRaw": "`flags` {number} modifiers for copy operation. **Default:** `0`.", + "name": "flags", + "type": "number", + "default": "`0`", + "desc": "modifiers for copy operation." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists. No arguments other than a possible exception are given to the\ncallback function. Node.js makes no guarantees about the atomicity of the copy\noperation. If an error occurs after the destination file has been opened for\nwriting, Node.js will attempt to remove the destination.

      \n

      flags is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      \n
        \n
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
      • \n
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.
      • \n
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support copy-on-write,\nthen the operation will fail.
      • \n
      \n
      const fs = require('fs');\n\n// destination.txt will be created or overwritten by default.\nfs.copyFile('source.txt', 'destination.txt', (err) => {\n  if (err) throw err;\n  console.log('source.txt was copied to destination.txt');\n});\n
      \n

      If the third argument is a number, then it specifies flags:

      \n
      const fs = require('fs');\nconst { COPYFILE_EXCL } = fs.constants;\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\nfs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback);\n
      " + }, + { + "textRaw": "`fs.copyFileSync(src, dest[, flags])`", + "type": "method", + "name": "copyFileSync", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": "v14.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27044", + "description": "Changed 'flags' argument to 'mode' and imposed stricter type validation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`src` {string|Buffer|URL} source filename to copy", + "name": "src", + "type": "string|Buffer|URL", + "desc": "source filename to copy" + }, + { + "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", + "name": "dest", + "type": "string|Buffer|URL", + "desc": "destination filename of the copy operation" + }, + { + "textRaw": "`flags` {number} modifiers for copy operation. **Default:** `0`.", + "name": "flags", + "type": "number", + "default": "`0`", + "desc": "modifiers for copy operation." + } + ] + } + ], + "desc": "

      Synchronously copies src to dest. By default, dest is overwritten if it\nalready exists. Returns undefined. Node.js makes no guarantees about the\natomicity of the copy operation. If an error occurs after the destination file\nhas been opened for writing, Node.js will attempt to remove the destination.

      \n

      flags is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      \n
        \n
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
      • \n
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.
      • \n
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support copy-on-write,\nthen the operation will fail.
      • \n
      \n
      const fs = require('fs');\n\n// destination.txt will be created or overwritten by default.\nfs.copyFileSync('source.txt', 'destination.txt');\nconsole.log('source.txt was copied to destination.txt');\n
      \n

      If the third argument is a number, then it specifies flags:

      \n
      const fs = require('fs');\nconst { COPYFILE_EXCL } = fs.constants;\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\nfs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL);\n
      " + }, + { + "textRaw": "`fs.createReadStream(path[, options])`", + "type": "method", + "name": "createReadStream", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29212", + "description": "Enable `emitClose` option." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19898", + "description": "Impose new restrictions on `start` and `end`, throwing more appropriate errors in cases when we cannot reasonably handle the input values." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v2.3.0", + "pr-url": "https://github.com/nodejs/node/pull/1845", + "description": "The passed `options` object can be a string now." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/29083", + "description": "The `fs` options allow overriding the used `fs` implementation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.ReadStream} See [Readable Stream][].", + "name": "return", + "type": "fs.ReadStream", + "desc": "See [Readable Stream][]." + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`flags` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flags", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`encoding` {string} **Default:** `null`", + "name": "encoding", + "type": "string", + "default": "`null`" + }, + { + "textRaw": "`fd` {integer} **Default:** `null`", + "name": "fd", + "type": "integer", + "default": "`null`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`autoClose` {boolean} **Default:** `true`", + "name": "autoClose", + "type": "boolean", + "default": "`true`" + }, + { + "textRaw": "`emitClose` {boolean} **Default:** `false`", + "name": "emitClose", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`start` {integer}", + "name": "start", + "type": "integer" + }, + { + "textRaw": "`end` {integer} **Default:** `Infinity`", + "name": "end", + "type": "integer", + "default": "`Infinity`" + }, + { + "textRaw": "`highWaterMark` {integer} **Default:** `64 * 1024`", + "name": "highWaterMark", + "type": "integer", + "default": "`64 * 1024`" + }, + { + "textRaw": "`fs` {Object|null} **Default:** `null`", + "name": "fs", + "type": "Object|null", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      Unlike the 16 kb default highWaterMark for a readable stream, the stream\nreturned by this method has a default highWaterMark of 64 kb.

      \n

      options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart counting at 0, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is\nomitted or undefined, fs.createReadStream() reads sequentially from the\ncurrent file position. The encoding can be any one of those accepted by\nBuffer.

      \n

      If fd is specified, ReadStream will ignore the path argument and will use\nthe specified file descriptor. This means that no 'open' event will be\nemitted. fd should be blocking; non-blocking fds should be passed to\nnet.Socket.

      \n

      If fd points to a character device that only supports blocking reads\n(such as keyboard or sound card), read operations do not finish until data is\navailable. This can prevent the process from exiting and the stream from\nclosing naturally.

      \n

      By default, the stream will not emit a 'close' event after it has been\ndestroyed. This is the opposite of the default for other Readable streams.\nSet the emitClose option to true to change this behavior.

      \n

      By providing the fs option, it is possible to override the corresponding fs\nimplementations for open, read, and close. When providing the fs option,\noverrides for open, read, and close are required.

      \n
      const fs = require('fs');\n// Create a stream from some character device.\nconst stream = fs.createReadStream('/dev/input/event0');\nsetTimeout(() => {\n  stream.close(); // This may not close the stream.\n  // Artificially marking end-of-stream, as if the underlying resource had\n  // indicated end-of-file by itself, allows the stream to close.\n  // This does not cancel pending read operations, and if there is such an\n  // operation, the process may still not be able to exit successfully\n  // until it finishes.\n  stream.push(null);\n  stream.read(0);\n}, 100);\n
      \n

      If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is the application's responsibility to close it and make\nsure there's no file descriptor leak. If autoClose is set to true (default\nbehavior), on 'error' or 'end' the file descriptor will be closed\nautomatically.

      \n

      mode sets the file mode (permission and sticky bits), but only if the\nfile was created.

      \n

      An example to read the last 10 bytes of a file which is 100 bytes long:

      \n
      fs.createReadStream('sample.txt', { start: 90, end: 99 });\n
      \n

      If options is a string, then it specifies the encoding.

      " + }, + { + "textRaw": "`fs.createWriteStream(path[, options])`", + "type": "method", + "name": "createWriteStream", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29212", + "description": "Enable `emitClose` option." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v5.5.0", + "pr-url": "https://github.com/nodejs/node/pull/3679", + "description": "The `autoClose` option is supported now." + }, + { + "version": "v2.3.0", + "pr-url": "https://github.com/nodejs/node/pull/1845", + "description": "The passed `options` object can be a string now." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/v12.17.0", + "description": "The `fs` options allow overriding the used `fs` implementation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.WriteStream} See [Writable Stream][].", + "name": "return", + "type": "fs.WriteStream", + "desc": "See [Writable Stream][]." + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`flags` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flags", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`fd` {integer} **Default:** `null`", + "name": "fd", + "type": "integer", + "default": "`null`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`autoClose` {boolean} **Default:** `true`", + "name": "autoClose", + "type": "boolean", + "default": "`true`" + }, + { + "textRaw": "`emitClose` {boolean} **Default:** `false`", + "name": "emitClose", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`start` {integer}", + "name": "start", + "type": "integer" + }, + { + "textRaw": "`fs` {Object|null} **Default:** `null`", + "name": "fs", + "type": "Object|null", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      options may also include a start option to allow writing data at\nsome position past the beginning of the file, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w. The encoding can be any one of those accepted by\nBuffer.

      \n

      If autoClose is set to true (default behavior) on 'error' or 'finish'\nthe file descriptor will be closed automatically. If autoClose is false,\nthen the file descriptor won't be closed, even if there's an error.\nIt is the application's responsibility to close it and make sure there's no\nfile descriptor leak.

      \n

      By default, the stream will not emit a 'close' event after it has been\ndestroyed. This is the opposite of the default for other Writable streams.\nSet the emitClose option to true to change this behavior.

      \n

      By providing the fs option it is possible to override the corresponding fs\nimplementations for open, write, writev and close. Overriding write()\nwithout writev() can reduce performance as some optimizations (_writev())\nwill be disabled. When providing the fs option, overrides for open,\nclose, and at least one of write and writev are required.

      \n

      Like ReadStream, if fd is specified, WriteStream will ignore the\npath argument and will use the specified file descriptor. This means that no\n'open' event will be emitted. fd should be blocking; non-blocking fds\nshould be passed to net.Socket.

      \n

      If options is a string, then it specifies the encoding.

      " + }, + { + "textRaw": "`fs.exists(path, callback)`", + "type": "method", + "name": "exists", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ], + "deprecated": [ + "v1.0.0" + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`exists` {boolean}", + "name": "exists", + "type": "boolean" + } + ] + } + ] + } + ], + "desc": "

      Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false:

      \n
      fs.exists('/etc/passwd', (exists) => {\n  console.log(exists ? 'it\\'s there' : 'no passwd!');\n});\n
      \n

      The parameters for this callback are not consistent with other Node.js\ncallbacks. Normally, the first parameter to a Node.js callback is an err\nparameter, optionally followed by other parameters. The fs.exists() callback\nhas only one boolean parameter. This is one reason fs.access() is recommended\ninstead of fs.exists().

      \n

      Using fs.exists() to check for the existence of a file before calling\nfs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file does not exist.

      \n

      write (NOT RECOMMENDED)

      \n
      fs.exists('myfile', (exists) => {\n  if (exists) {\n    console.error('myfile already exists');\n  } else {\n    fs.open('myfile', 'wx', (err, fd) => {\n      if (err) throw err;\n      writeMyData(fd);\n    });\n  }\n});\n
      \n

      write (RECOMMENDED)

      \n
      fs.open('myfile', 'wx', (err, fd) => {\n  if (err) {\n    if (err.code === 'EEXIST') {\n      console.error('myfile already exists');\n      return;\n    }\n\n    throw err;\n  }\n\n  writeMyData(fd);\n});\n
      \n

      read (NOT RECOMMENDED)

      \n
      fs.exists('myfile', (exists) => {\n  if (exists) {\n    fs.open('myfile', 'r', (err, fd) => {\n      if (err) throw err;\n      readMyData(fd);\n    });\n  } else {\n    console.error('myfile does not exist');\n  }\n});\n
      \n

      read (RECOMMENDED)

      \n
      fs.open('myfile', 'r', (err, fd) => {\n  if (err) {\n    if (err.code === 'ENOENT') {\n      console.error('myfile does not exist');\n      return;\n    }\n\n    throw err;\n  }\n\n  readMyData(fd);\n});\n
      \n

      The \"not recommended\" examples above check for existence and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.

      \n

      In general, check for the existence of a file only if the file won’t be\nused directly, for example when its existence is a signal from another\nprocess.

      " + }, + { + "textRaw": "`fs.existsSync(path)`", + "type": "method", + "name": "existsSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Returns true if the path exists, false otherwise.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.exists().

      \n

      fs.exists() is deprecated, but fs.existsSync() is not. The callback\nparameter to fs.exists() accepts parameters that are inconsistent with other\nNode.js callbacks. fs.existsSync() does not use a callback.

      \n
      if (fs.existsSync('/etc/passwd')) {\n  console.log('The path exists.');\n}\n
      " + }, + { + "textRaw": "`fs.fchmod(fd, mode, callback)`", + "type": "method", + "name": "fchmod", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.

      " + }, + { + "textRaw": "`fs.fchmodSync(fd, mode)`", + "type": "method", + "name": "fchmodSync", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + } + ] + } + ], + "desc": "

      Synchronous fchmod(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.fchown(fd, uid, gid, callback)`", + "type": "method", + "name": "fchown", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.

      " + }, + { + "textRaw": "`fs.fchownSync(fd, uid, gid)`", + "type": "method", + "name": "fchownSync", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous fchown(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.fdatasync(fd, callback)`", + "type": "method", + "name": "fdatasync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fdatasync(2). No arguments other than a possible exception are\ngiven to the completion callback.

      " + }, + { + "textRaw": "`fs.fdatasyncSync(fd)`", + "type": "method", + "name": "fdatasyncSync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous fdatasync(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.fstat(fd[, options], callback)`", + "type": "method", + "name": "fstat", + "meta": { + "added": [ + "v0.1.95" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stats` {fs.Stats}", + "name": "stats", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is an fs.Stats object. fstat() is identical to stat(),\nexcept that the file to be stat-ed is specified by the file descriptor fd.

      " + }, + { + "textRaw": "`fs.fstatSync(fd[, options])`", + "type": "method", + "name": "fstatSync", + "meta": { + "added": [ + "v0.1.95" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Stats}", + "name": "return", + "type": "fs.Stats" + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous fstat(2).

      " + }, + { + "textRaw": "`fs.fsync(fd, callback)`", + "type": "method", + "name": "fsync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.

      " + }, + { + "textRaw": "`fs.fsyncSync(fd)`", + "type": "method", + "name": "fsyncSync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous fsync(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.ftruncate(fd[, len], callback)`", + "type": "method", + "name": "ftruncate", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.

      \n

      If the file referred to by the file descriptor was larger than len bytes, only\nthe first len bytes will be retained in the file.

      \n

      For example, the following program retains only the first four bytes of the\nfile:

      \n
      console.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// Truncate the file to first four bytes\nfs.ftruncate(fd, 4, (err) => {\n  assert.ifError(err);\n  console.log(fs.readFileSync('temp.txt', 'utf8'));\n});\n// Prints: Node\n
      \n

      If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):

      \n
      console.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// Truncate the file to 10 bytes, whereas the actual size is 7 bytes\nfs.ftruncate(fd, 10, (err) => {\n  assert.ifError(err);\n  console.log(fs.readFileSync('temp.txt'));\n});\n// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>\n// ('Node.js\\0\\0\\0' in UTF8)\n
      \n

      The last three bytes are null bytes ('\\0'), to compensate the over-truncation.

      " + }, + { + "textRaw": "`fs.ftruncateSync(fd[, len])`", + "type": "method", + "name": "ftruncateSync", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.ftruncate().

      " + }, + { + "textRaw": "`fs.futimes(fd, atime, mtime, callback)`", + "type": "method", + "name": "futimes", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by the supplied file\ndescriptor. See fs.utimes().

      \n

      This function does not work on AIX versions before 7.1, it will return the\nerror UV_ENOSYS.

      " + }, + { + "textRaw": "`fs.futimesSync(fd, atime, mtime)`", + "type": "method", + "name": "futimesSync", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Synchronous version of fs.futimes(). Returns undefined.

      " + }, + { + "textRaw": "`fs.lchmod(path, mode, callback)`", + "type": "method", + "name": "lchmod", + "meta": { + "deprecated": [ + "v0.4.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.

      \n

      Only available on macOS.

      " + }, + { + "textRaw": "`fs.lchmodSync(path, mode)`", + "type": "method", + "name": "lchmodSync", + "meta": { + "deprecated": [ + "v0.4.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous lchmod(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.lchown(path, uid, gid, callback)`", + "type": "method", + "name": "lchown", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "This API is no longer deprecated." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.

      " + }, + { + "textRaw": "`fs.lchownSync(path, uid, gid)`", + "type": "method", + "name": "lchownSync", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "This API is no longer deprecated." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous lchown(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.lutimes(path, atime, mtime, callback)`", + "type": "method", + "name": "lutimes", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Changes the access and modification times of a file in the same way as\nfs.utimes(), with the difference that if the path refers to a symbolic\nlink, then the link is not dereferenced: instead, the timestamps of the\nsymbolic link itself are changed.

      \n

      No arguments other than a possible exception are given to the completion\ncallback.

      " + }, + { + "textRaw": "`fs.lutimesSync(path, atime, mtime)`", + "type": "method", + "name": "lutimesSync", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Change the file system timestamps of the symbolic link referenced by path.\nReturns undefined, or throws an exception when parameters are incorrect or\nthe operation fails. This is the synchronous version of fs.lutimes().

      " + }, + { + "textRaw": "`fs.link(existingPath, newPath, callback)`", + "type": "method", + "name": "link", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `existingPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`existingPath` {string|Buffer|URL}", + "name": "existingPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.

      " + }, + { + "textRaw": "`fs.linkSync(existingPath, newPath)`", + "type": "method", + "name": "linkSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `existingPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`existingPath` {string|Buffer|URL}", + "name": "existingPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Synchronous link(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.lstat(path[, options], callback)`", + "type": "method", + "name": "lstat", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stats` {fs.Stats}", + "name": "stats", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(),\nexcept that if path is a symbolic link, then the link itself is stat-ed,\nnot the file that it refers to.

      " + }, + { + "textRaw": "`fs.lstatSync(path[, options])`", + "type": "method", + "name": "lstatSync", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Stats}", + "name": "return", + "type": "fs.Stats" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous lstat(2).

      " + }, + { + "textRaw": "`fs.mkdir(path[, options], callback)`", + "type": "method", + "name": "mkdir", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31530", + "description": "In `recursive` mode, the callback now receives the first created path as an argument." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/21875", + "description": "The second argument can now be an `options` object with `recursive` and `mode` properties." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object|integer}", + "name": "options", + "type": "Object|integer", + "options": [ + { + "textRaw": "`recursive` {boolean} **Default:** `false`", + "name": "recursive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", + "name": "mode", + "type": "string|integer", + "default": "`0o777`", + "desc": "Not supported on Windows." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously creates a directory.

      \n

      The callback is given a possible exception and, if recursive is true, the\nfirst directory path created, (err, [path]).

      \n

      The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfs.mkdir() when path is a directory that exists results in an error only\nwhen recursive is false.

      \n
      // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.\nfs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {\n  if (err) throw err;\n});\n
      \n

      On Windows, using fs.mkdir() on the root directory even with recursion will\nresult in an error:

      \n
      fs.mkdir('/', { recursive: true }, (err) => {\n  // => [Error: EPERM: operation not permitted, mkdir 'C:\\']\n});\n
      \n

      See also: mkdir(2).

      " + }, + { + "textRaw": "`fs.mkdirSync(path[, options])`", + "type": "method", + "name": "mkdirSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31530", + "description": "In `recursive` mode, the first created path is returned now." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/21875", + "description": "The second argument can now be an `options` object with `recursive` and `mode` properties." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|undefined}", + "name": "return", + "type": "string|undefined" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object|integer}", + "name": "options", + "type": "Object|integer", + "options": [ + { + "textRaw": "`recursive` {boolean} **Default:** `false`", + "name": "recursive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", + "name": "mode", + "type": "string|integer", + "default": "`0o777`", + "desc": "Not supported on Windows." + } + ] + } + ] + } + ], + "desc": "

      Synchronously creates a directory. Returns undefined, or if recursive is\ntrue, the first directory path created.\nThis is the synchronous version of fs.mkdir().

      \n

      See also: mkdir(2).

      " + }, + { + "textRaw": "`fs.mkdtemp(prefix[, options], callback)`", + "type": "method", + "name": "mkdtemp", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v6.2.1", + "pr-url": "https://github.com/nodejs/node/pull/6828", + "description": "The `callback` parameter is optional now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`prefix` {string}", + "name": "prefix", + "type": "string" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`directory` {string}", + "name": "directory", + "type": "string" + } + ] + } + ] + } + ], + "desc": "

      Creates a unique temporary directory.

      \n

      Generates six random characters to be appended behind a required\nprefix to create a unique temporary directory. Due to platform\ninconsistencies, avoid trailing X characters in prefix. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing X characters in prefix with random characters.

      \n

      The created directory path is passed as a string to the callback's second\nparameter.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

      \n
      fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {\n  if (err) throw err;\n  console.log(directory);\n  // Prints: /tmp/foo-itXde2 or C:\\Users\\...\\AppData\\Local\\Temp\\foo-itXde2\n});\n
      \n

      The fs.mkdtemp() method will append the six randomly selected characters\ndirectly to the prefix string. For instance, given a directory /tmp, if the\nintention is to create a temporary directory within /tmp, the prefix\nmust end with a trailing platform-specific path separator\n(require('path').sep).

      \n
      // The parent directory for the new temporary directory\nconst tmpDir = os.tmpdir();\n\n// This method is *INCORRECT*:\nfs.mkdtemp(tmpDir, (err, directory) => {\n  if (err) throw err;\n  console.log(directory);\n  // Will print something similar to `/tmpabc123`.\n  // A new temporary directory is created at the file system root\n  // rather than *within* the /tmp directory.\n});\n\n// This method is *CORRECT*:\nconst { sep } = require('path');\nfs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {\n  if (err) throw err;\n  console.log(directory);\n  // Will print something similar to `/tmp/abc123`.\n  // A new temporary directory is created within\n  // the /tmp directory.\n});\n
      " + }, + { + "textRaw": "`fs.mkdtempSync(prefix[, options])`", + "type": "method", + "name": "mkdtempSync", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`prefix` {string}", + "name": "prefix", + "type": "string" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Returns the created directory path.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.mkdtemp().

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

      " + }, + { + "textRaw": "`fs.open(path[, flags[, mode]], callback)`", + "type": "method", + "name": "open", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v11.1.0", + "pr-url": "https://github.com/nodejs/node/pull/23767", + "description": "The `flags` argument is now optional and defaults to `'r'`." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18801", + "description": "The `as` and `as+` modes are supported now." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`flags` {string|number} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flags", + "type": "string|number", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`mode` {string|integer} **Default:** `0o666` (readable and writable)", + "name": "mode", + "type": "string|integer", + "default": "`0o666` (readable and writable)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous file open. See open(2).

      \n

      mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. On Windows, only the write permission can be manipulated; see\nfs.chmod().

      \n

      The callback gets two arguments (err, fd).

      \n

      Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.

      \n

      Functions based on fs.open() exhibit this behavior as well:\nfs.writeFile(), fs.readFile(), etc.

      " + }, + { + "textRaw": "`fs.opendir(path[, options], callback)`", + "type": "method", + "name": "opendir", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30114", + "description": "The `bufferSize` option was introduced." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`", + "name": "bufferSize", + "type": "number", + "default": "`32`", + "desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`dir` {fs.Dir}", + "name": "dir", + "type": "fs.Dir" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously open a directory. See opendir(3).

      \n

      Creates an fs.Dir, which contains all further functions for reading from\nand cleaning up the directory.

      \n

      The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

      " + }, + { + "textRaw": "`fs.opendirSync(path[, options])`", + "type": "method", + "name": "opendirSync", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30114", + "description": "The `bufferSize` option was introduced." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Dir}", + "name": "return", + "type": "fs.Dir" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`", + "name": "bufferSize", + "type": "number", + "default": "`32`", + "desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage." + } + ] + } + ] + } + ], + "desc": "

      Synchronously open a directory. See opendir(3).

      \n

      Creates an fs.Dir, which contains all further functions for reading from\nand cleaning up the directory.

      \n

      The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

      " + }, + { + "textRaw": "`fs.openSync(path[, flags, mode])`", + "type": "method", + "name": "openSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v11.1.0", + "pr-url": "https://github.com/nodejs/node/pull/23767", + "description": "The `flags` argument is now optional and defaults to `'r'`." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18801", + "description": "The `as` and `as+` modes are supported now." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`flags` {string|number} **Default:** `'r'`. See [support of file system `flags`][].", + "name": "flags", + "type": "string|number", + "default": "`'r'`. See [support of file system `flags`][]" + }, + { + "textRaw": "`mode` {string|integer} **Default:** `0o666`", + "name": "mode", + "type": "string|integer", + "default": "`0o666`" + } + ] + } + ], + "desc": "

      Returns an integer representing the file descriptor.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.open().

      " + }, + { + "textRaw": "`fs.read(fd, buffer, offset, length, position, callback)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray`, or a `DataView`." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `buffer` parameter can now be a `Uint8Array`." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4518", + "description": "The `length` parameter can now be `0`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesRead` {integer}", + "name": "bytesRead", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer}", + "name": "buffer", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Read data from the file specified by fd.

      \n

      buffer is the buffer that the data (read from the fd) will be written to.

      \n

      offset is the offset in the buffer to start writing at.

      \n

      length is an integer specifying the number of bytes to read.

      \n

      position is an argument specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position,\nand the file position will be updated.\nIf position is an integer, the file position will remain unchanged.

      \n

      The callback is given the three arguments, (err, bytesRead, buffer).

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with bytesRead and buffer properties.

      " + }, + { + "textRaw": "`fs.read(fd, [options,] callback)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31402", + "description": "Options object can be passed in to make Buffer, offset, length and position optional" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)`", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "default": "`Buffer.alloc(16384)`" + }, + { + "textRaw": "`offset` {integer} **Default:** `0`", + "name": "offset", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`length` {integer} **Default:** `buffer.length`", + "name": "length", + "type": "integer", + "default": "`buffer.length`" + }, + { + "textRaw": "`position` {integer} **Default:** `null`", + "name": "position", + "type": "integer", + "default": "`null`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesRead` {integer}", + "name": "bytesRead", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer}", + "name": "buffer", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Similar to the above fs.read function, this version takes an optional options object.\nIf no options object is specified, it will default with the above values.

      " + }, + { + "textRaw": "`fs.readdir(path[, options], callback)`", + "type": "method", + "name": "readdir", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22020", + "description": "New option `withFileTypes` was added." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5616", + "description": "The `options` parameter was added." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`withFileTypes` {boolean} **Default:** `false`", + "name": "withFileTypes", + "type": "boolean", + "default": "`false`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`files` {string[]|Buffer[]|fs.Dirent[]}", + "name": "files", + "type": "string[]|Buffer[]|fs.Dirent[]" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames passed to the callback. If the encoding is set to 'buffer',\nthe filenames returned will be passed as Buffer objects.

      \n

      If options.withFileTypes is set to true, the files array will contain\nfs.Dirent objects.

      " + }, + { + "textRaw": "`fs.readdirSync(path[, options])`", + "type": "method", + "name": "readdirSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22020", + "description": "New option `withFileTypes` was added." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]|Buffer[]|fs.Dirent[]}", + "name": "return", + "type": "string[]|Buffer[]|fs.Dirent[]" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`withFileTypes` {boolean} **Default:** `false`", + "name": "withFileTypes", + "type": "boolean", + "default": "`false`" + } + ] + } + ] + } + ], + "desc": "

      Synchronous readdir(3).

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames returned. If the encoding is set to 'buffer',\nthe filenames returned will be passed as Buffer objects.

      \n

      If options.withFileTypes is set to true, the result will contain\nfs.Dirent objects.

      " + }, + { + "textRaw": "`fs.readFile(path[, options], callback)`", + "type": "method", + "name": "readFile", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v5.1.0", + "pr-url": "https://github.com/nodejs/node/pull/3740", + "description": "The `callback` will always be called with `null` as the `error` parameter in case of success." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `path` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|integer} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flag", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously reads the entire contents of a file.

      \n
      fs.readFile('/etc/passwd', (err, data) => {\n  if (err) throw err;\n  console.log(data);\n});\n
      \n

      The callback is passed two arguments (err, data), where data is the\ncontents of the file.

      \n

      If no encoding is specified, then the raw buffer is returned.

      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.readFile('/etc/passwd', 'utf8', callback);\n
      \n

      When the path is a directory, the behavior of fs.readFile() and\nfs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an\nerror will be returned. On FreeBSD, a representation of the directory's contents\nwill be returned.

      \n
      // macOS, Linux, and Windows\nfs.readFile('<directory>', (err, data) => {\n  // => [Error: EISDIR: illegal operation on a directory, read <directory>]\n});\n\n//  FreeBSD\nfs.readFile('<directory>', (err, data) => {\n  // => null, <data>\n});\n
      \n

      The fs.readFile() function buffers the entire file. To minimize memory costs,\nwhen possible prefer streaming via fs.createReadStream().

      ", + "modules": [ + { + "textRaw": "File descriptors", + "name": "file_descriptors", + "desc": "
        \n
      1. Any specified file descriptor has to support reading.
      2. \n
      3. If a file descriptor is specified as the path, it will not be closed\nautomatically.
      4. \n
      5. The reading will begin at the current position. For example, if the file\nalready had 'Hello World' and six bytes are read with the file descriptor,\nthe call to fs.readFile() with the same file descriptor, would give\n'World', rather than 'Hello World'.
      6. \n
      ", + "type": "module", + "displayName": "File descriptors" + } + ] + }, + { + "textRaw": "`fs.readFileSync(path[, options])`", + "type": "method", + "name": "readFileSync", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `path` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|integer} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flag", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Returns the contents of the path.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readFile().

      \n

      If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.

      \n

      Similar to fs.readFile(), when the path is a directory, the behavior of\nfs.readFileSync() is platform-specific.

      \n
      // macOS, Linux, and Windows\nfs.readFileSync('<directory>');\n// => [Error: EISDIR: illegal operation on a directory, read <directory>]\n\n//  FreeBSD\nfs.readFileSync('<directory>'); // => <data>\n
      " + }, + { + "textRaw": "`fs.readlink(path[, options], callback)`", + "type": "method", + "name": "readlink", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`linkString` {string|Buffer}", + "name": "linkString", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous readlink(2). The callback gets two arguments (err, linkString).

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path passed to the callback. If the encoding is set to 'buffer',\nthe link path returned will be passed as a Buffer object.

      " + }, + { + "textRaw": "`fs.readlinkSync(path[, options])`", + "type": "method", + "name": "readlinkSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Synchronous readlink(2). Returns the symbolic link's string value.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer',\nthe link path returned will be passed as a Buffer object.

      " + }, + { + "textRaw": "`fs.readSync(fd, buffer, offset, length, position)`", + "type": "method", + "name": "readSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4518", + "description": "The `length` parameter can now be `0`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Returns the number of bytesRead.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().

      " + }, + { + "textRaw": "`fs.readSync(fd, buffer, [options])`", + "type": "method", + "name": "readSync", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32460", + "description": "Options object can be passed in to make offset, length and position optional" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`offset` {integer} **Default:** `0`", + "name": "offset", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`length` {integer} **Default:** `buffer.length`", + "name": "length", + "type": "integer", + "default": "`buffer.length`" + }, + { + "textRaw": "`position` {integer} **Default:** `null`", + "name": "position", + "type": "integer", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      Returns the number of bytesRead.

      \n

      Similar to the above fs.readSync function, this version takes an optional options object.\nIf no options object is specified, it will default with the above values.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().

      " + }, + { + "textRaw": "`fs.readv(fd, buffers[, position], callback)`", + "type": "method", + "name": "readv", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesRead` {integer}", + "name": "bytesRead", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + } + ] + } + ] + } + ], + "desc": "

      Read from a file specified by fd and write to an array of ArrayBufferViews\nusing readv().

      \n

      position is the offset from the beginning of the file from where data\nshould be read. If typeof position !== 'number', the data will be read\nfrom the current position.

      \n

      The callback will be given three arguments: err, bytesRead, and\nbuffers. bytesRead is how many bytes were read from the file.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with bytesRead and buffers properties.

      " + }, + { + "textRaw": "`fs.readvSync(fd, buffers[, position])`", + "type": "method", + "name": "readvSync", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes read.", + "name": "return", + "type": "number", + "desc": "The number of bytes read." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readv().

      " + }, + { + "textRaw": "`fs.realpath(path[, options], callback)`", + "type": "method", + "name": "realpath", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13028", + "description": "Pipe/Socket resolve support was added." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7899", + "description": "Calling `realpath` now works again for various edge cases on Windows." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3594", + "description": "The `cache` parameter was removed." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`resolvedPath` {string|Buffer}", + "name": "resolvedPath", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously computes the canonical pathname by resolving ., .. and\nsymbolic links.

      \n

      A canonical pathname is not necessarily unique. Hard links and bind mounts can\nexpose a file system entity through many pathnames.

      \n

      This function behaves like realpath(3), with some exceptions:

      \n
        \n
      1. \n

        No case conversion is performed on case-insensitive file systems.

        \n
      2. \n
      3. \n

        The maximum number of symbolic links is platform-independent and generally\n(much) higher than what the native realpath(3) implementation supports.

        \n
      4. \n
      \n

      The callback gets two arguments (err, resolvedPath). May use process.cwd\nto resolve relative paths.

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a Buffer object.

      \n

      If path resolves to a socket or a pipe, the function will return a system\ndependent name for that object.

      " + }, + { + "textRaw": "`fs.realpath.native(path[, options], callback)`", + "type": "method", + "name": "native", + "meta": { + "added": [ + "v9.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`resolvedPath` {string|Buffer}", + "name": "resolvedPath", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous realpath(3).

      \n

      The callback gets two arguments (err, resolvedPath).

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a Buffer object.

      \n

      On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.

      " + }, + { + "textRaw": "`fs.realpathSync(path[, options])`", + "type": "method", + "name": "realpathSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13028", + "description": "Pipe/Socket resolve support was added." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7899", + "description": "Calling `realpathSync` now works again for various edge cases on Windows." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3594", + "description": "The `cache` parameter was removed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Returns the resolved pathname.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.realpath().

      " + }, + { + "textRaw": "`fs.realpathSync.native(path[, options])`", + "type": "method", + "name": "native", + "meta": { + "added": [ + "v9.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Synchronous realpath(3).

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path returned. If the encoding is set to 'buffer',\nthe path returned will be passed as a Buffer object.

      \n

      On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.

      " + }, + { + "textRaw": "`fs.rename(oldPath, newPath, callback)`", + "type": "method", + "name": "rename", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `oldPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`oldPath` {string|Buffer|URL}", + "name": "oldPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously rename file at oldPath to the pathname provided\nas newPath. In the case that newPath already exists, it will\nbe overwritten. If there is a directory at newPath, an error will\nbe raised instead. No arguments other than a possible exception are\ngiven to the completion callback.

      \n

      See also: rename(2).

      \n
      fs.rename('oldFile.txt', 'newFile.txt', (err) => {\n  if (err) throw err;\n  console.log('Rename complete!');\n});\n
      " + }, + { + "textRaw": "`fs.renameSync(oldPath, newPath)`", + "type": "method", + "name": "renameSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `oldPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`oldPath` {string|Buffer|URL}", + "name": "oldPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Synchronous rename(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.rmdir(path[, options], callback)`", + "type": "method", + "name": "rmdir", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30644", + "description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried." + }, + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29168", + "description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameters can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "stability": 1, + "stabilityText": "Recursive removal is experimental.", + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", + "name": "maxRetries", + "type": "integer", + "default": "`0`", + "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." + }, + { + "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure. **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure." + }, + { + "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", + "name": "retryDelay", + "type": "integer", + "default": "`100`", + "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.

      \n

      Using fs.rmdir() on a file (not a directory) results in an ENOENT error on\nWindows and an ENOTDIR error on POSIX.

      " + }, + { + "textRaw": "`fs.rmdirSync(path[, options])`", + "type": "method", + "name": "rmdirSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30644", + "description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried." + }, + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29168", + "description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameters can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "stability": 1, + "stabilityText": "Recursive removal is experimental.", + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", + "name": "maxRetries", + "type": "integer", + "default": "`0`", + "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." + }, + { + "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure. **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure." + }, + { + "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", + "name": "retryDelay", + "type": "integer", + "default": "`100`", + "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous rmdir(2). Returns undefined.

      \n

      Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error\non Windows and an ENOTDIR error on POSIX.

      " + }, + { + "textRaw": "`fs.stat(path[, options], callback)`", + "type": "method", + "name": "stat", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stats` {fs.Stats}", + "name": "stats", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is an fs.Stats object.

      \n

      In case of an error, the err.code will be one of Common System Errors.

      \n

      Using fs.stat() to check for the existence of a file before calling\nfs.open(), fs.readFile() or fs.writeFile() is not recommended.\nInstead, user code should open/read/write the file directly and handle the\nerror raised if the file is not available.

      \n

      To check if a file exists without manipulating it afterwards, fs.access()\nis recommended.

      \n

      For example, given the following directory structure:

      \n
      - txtDir\n-- file.txt\n- app.js\n
      \n

      The next program will check for the stats of the given paths:

      \n
      const fs = require('fs');\n\nconst pathsToCheck = ['./txtDir', './txtDir/file.txt'];\n\nfor (let i = 0; i < pathsToCheck.length; i++) {\n  fs.stat(pathsToCheck[i], function(err, stats) {\n    console.log(stats.isDirectory());\n    console.log(stats);\n  });\n}\n
      \n

      The resulting output will resemble:

      \n
      true\nStats {\n  dev: 16777220,\n  mode: 16877,\n  nlink: 3,\n  uid: 501,\n  gid: 20,\n  rdev: 0,\n  blksize: 4096,\n  ino: 14214262,\n  size: 96,\n  blocks: 0,\n  atimeMs: 1561174653071.963,\n  mtimeMs: 1561174614583.3518,\n  ctimeMs: 1561174626623.5366,\n  birthtimeMs: 1561174126937.2893,\n  atime: 2019-06-22T03:37:33.072Z,\n  mtime: 2019-06-22T03:36:54.583Z,\n  ctime: 2019-06-22T03:37:06.624Z,\n  birthtime: 2019-06-22T03:28:46.937Z\n}\nfalse\nStats {\n  dev: 16777220,\n  mode: 33188,\n  nlink: 1,\n  uid: 501,\n  gid: 20,\n  rdev: 0,\n  blksize: 4096,\n  ino: 14214074,\n  size: 8,\n  blocks: 8,\n  atimeMs: 1561174616618.8555,\n  mtimeMs: 1561174614584,\n  ctimeMs: 1561174614583.8145,\n  birthtimeMs: 1561174007710.7478,\n  atime: 2019-06-22T03:36:56.619Z,\n  mtime: 2019-06-22T03:36:54.584Z,\n  ctime: 2019-06-22T03:36:54.584Z,\n  birthtime: 2019-06-22T03:26:47.711Z\n}\n
      " + }, + { + "textRaw": "`fs.statSync(path[, options])`", + "type": "method", + "name": "statSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Stats}", + "name": "return", + "type": "fs.Stats" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous stat(2).

      " + }, + { + "textRaw": "`fs.symlink(target, path[, type], callback)`", + "type": "method", + "name": "symlink", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `target` and `path` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23724", + "description": "If the `type` argument is left undefined, Node will autodetect `target` type and automatically select `dir` or `file`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`target` {string|Buffer|URL}", + "name": "target", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous symlink(2) which creates the link called path pointing to\ntarget. No arguments other than a possible exception are given to the\ncompletion callback.

      \n

      The type argument is only available on Windows and ignored on other platforms.\nIt can be set to 'dir', 'file', or 'junction'. If the type argument is\nnot set, Node.js will autodetect target type and use 'file' or 'dir'. If\nthe target does not exist, 'file' will be used. Windows junction points\nrequire the destination path to be absolute. When using 'junction', the\ntarget argument will automatically be normalized to absolute path.

      \n

      Relative targets are relative to the link’s parent directory.

      \n
      fs.symlink('./mew', './example/mewtwo', callback);\n
      \n

      The above example creates a symbolic link mewtwo in the example which points\nto mew in the same directory:

      \n
      $ tree example/\nexample/\n├── mew\n└── mewtwo -> ./mew\n
      " + }, + { + "textRaw": "`fs.symlinkSync(target, path[, type])`", + "type": "method", + "name": "symlinkSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `target` and `path` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23724", + "description": "If the `type` argument is left undefined, Node will autodetect `target` type and automatically select `dir` or `file`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`target` {string|Buffer|URL}", + "name": "target", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.symlink().

      " + }, + { + "textRaw": "`fs.truncate(path[, len], callback)`", + "type": "method", + "name": "truncate", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous truncate(2). No arguments other than a possible exception are\ngiven to the completion callback. A file descriptor can also be passed as the\nfirst argument. In this case, fs.ftruncate() is called.

      \n

      Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.

      " + }, + { + "textRaw": "`fs.truncateSync(path[, len])`", + "type": "method", + "name": "truncateSync", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Synchronous truncate(2). Returns undefined. A file descriptor can also be\npassed as the first argument. In this case, fs.ftruncateSync() is called.

      \n

      Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.

      " + }, + { + "textRaw": "`fs.unlink(path, callback)`", + "type": "method", + "name": "unlink", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously removes a file or symbolic link. No arguments other than a\npossible exception are given to the completion callback.

      \n
      // Assuming that 'path/file.txt' is a regular file.\nfs.unlink('path/file.txt', (err) => {\n  if (err) throw err;\n  console.log('path/file.txt was deleted');\n});\n
      \n

      fs.unlink() will not work on a directory, empty or otherwise. To remove a\ndirectory, use fs.rmdir().

      \n

      See also: unlink(2).

      " + }, + { + "textRaw": "`fs.unlinkSync(path)`", + "type": "method", + "name": "unlinkSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Synchronous unlink(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.unwatchFile(filename[, listener])`", + "type": "method", + "name": "unwatchFile", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`filename` {string|Buffer|URL}", + "name": "filename", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`listener` {Function} Optional, a listener previously attached using `fs.watchFile()`", + "name": "listener", + "type": "Function", + "desc": "Optional, a listener previously attached using `fs.watchFile()`" + } + ] + } + ], + "desc": "

      Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed,\neffectively stopping watching of filename.

      \n

      Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.

      \n

      Using fs.watch() is more efficient than fs.watchFile() and\nfs.unwatchFile(). fs.watch() should be used instead of fs.watchFile()\nand fs.unwatchFile() when possible.

      " + }, + { + "textRaw": "`fs.utimes(path, atime, mtime, callback)`", + "type": "method", + "name": "utimes", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11919", + "description": "`NaN`, `Infinity`, and `-Infinity` are no longer valid time specifiers." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by path.

      \n

      The atime and mtime arguments follow these rules:

      \n
        \n
      • Values can be either numbers representing Unix epoch time in seconds,\nDates, or a numeric string like '123456789.0'.
      • \n
      • If the value can not be converted to a number, or is NaN, Infinity or\n-Infinity, an Error will be thrown.
      • \n
      " + }, + { + "textRaw": "`fs.utimesSync(path, atime, mtime)`", + "type": "method", + "name": "utimesSync", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11919", + "description": "`NaN`, `Infinity`, and `-Infinity` are no longer valid time specifiers." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.utimes().

      " + }, + { + "textRaw": "`fs.watch(filename[, options][, listener])`", + "type": "method", + "name": "watch", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `filename` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.FSWatcher}", + "name": "return", + "type": "fs.FSWatcher" + }, + "params": [ + { + "textRaw": "`filename` {string|Buffer|URL}", + "name": "filename", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`persistent` {boolean} Indicates whether the process should continue to run as long as files are being watched. **Default:** `true`.", + "name": "persistent", + "type": "boolean", + "default": "`true`", + "desc": "Indicates whether the process should continue to run as long as files are being watched." + }, + { + "textRaw": "`recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [Caveats][]). **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [Caveats][])." + }, + { + "textRaw": "`encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "Specifies the character encoding to be used for the filename passed to the listener." + } + ] + }, + { + "textRaw": "`listener` {Function|undefined} **Default:** `undefined`", + "name": "listener", + "type": "Function|undefined", + "default": "`undefined`", + "options": [ + { + "textRaw": "`eventType` {string}", + "name": "eventType", + "type": "string" + }, + { + "textRaw": "`filename` {string|Buffer}", + "name": "filename", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Watch for changes on filename, where filename is either a file or a\ndirectory.

      \n

      The second argument is optional. If options is provided as a string, it\nspecifies the encoding. Otherwise options should be passed as an object.

      \n

      The listener callback gets two arguments (eventType, filename). eventType\nis either 'rename' or 'change', and filename is the name of the file\nwhich triggered the event.

      \n

      On most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.

      \n

      The listener callback is attached to the 'change' event fired by\nfs.FSWatcher, but it is not the same thing as the 'change' value of\neventType.

      ", + "miscs": [ + { + "textRaw": "Caveats", + "name": "Caveats", + "type": "misc", + "desc": "

      The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.

      \n

      The recursive option is only supported on macOS and Windows.

      \n

      On Windows, no events will be emitted if the watched directory is moved or\nrenamed. An EPERM error is reported when the watched directory is deleted.

      ", + "miscs": [ + { + "textRaw": "Availability", + "name": "Availability", + "type": "misc", + "desc": "

      This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.

      \n
        \n
      • On Linux systems, this uses inotify(7).
      • \n
      • On BSD systems, this uses kqueue(2).
      • \n
      • On macOS, this uses kqueue(2) for files and FSEvents for\ndirectories.
      • \n
      • On SunOS systems (including Solaris and SmartOS), this uses event ports.
      • \n
      • On Windows systems, this feature depends on ReadDirectoryChangesW.
      • \n
      • On Aix systems, this feature depends on AHAFS, which must be enabled.
      • \n
      • On IBM i systems, this feature is not supported.
      • \n
      \n

      If the underlying functionality is not available for some reason, then\nfs.watch() will not be able to function and may thrown an exception.\nFor example, watching files or directories can be unreliable, and in some\ncases impossible, on network file systems (NFS, SMB, etc) or host file systems\nwhen using virtualization software such as Vagrant or Docker.

      \n

      It is still possible to use fs.watchFile(), which uses stat polling, but\nthis method is slower and less reliable.

      " + }, + { + "textRaw": "Inodes", + "name": "Inodes", + "type": "misc", + "desc": "

      On Linux and macOS systems, fs.watch() resolves the path to an inode and\nwatches the inode. If the watched path is deleted and recreated, it is assigned\na new inode. The watch will emit an event for the delete but will continue\nwatching the original inode. Events for the new inode will not be emitted.\nThis is expected behavior.

      \n

      AIX files retain the same inode for the lifetime of a file. Saving and closing a\nwatched file on AIX will result in two notifications (one for adding new\ncontent, and one for truncation).

      " + }, + { + "textRaw": "Filename argument", + "name": "Filename argument", + "type": "misc", + "desc": "

      Providing filename argument in the callback is only supported on Linux,\nmacOS, Windows, and AIX. Even on supported platforms, filename is not always\nguaranteed to be provided. Therefore, don't assume that filename argument is\nalways provided in the callback, and have some fallback logic if it is null.

      \n
      fs.watch('somedir', (eventType, filename) => {\n  console.log(`event type is: ${eventType}`);\n  if (filename) {\n    console.log(`filename provided: ${filename}`);\n  } else {\n    console.log('filename not provided');\n  }\n});\n
      " + } + ] + } + ] + }, + { + "textRaw": "`fs.watchFile(filename[, options], listener)`", + "type": "method", + "name": "watchFile", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "The `bigint` option is now supported." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `filename` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.StatWatcher}", + "name": "return", + "type": "fs.StatWatcher" + }, + "params": [ + { + "textRaw": "`filename` {string|Buffer|URL}", + "name": "filename", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} **Default:** `false`", + "name": "bigint", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`persistent` {boolean} **Default:** `true`", + "name": "persistent", + "type": "boolean", + "default": "`true`" + }, + { + "textRaw": "`interval` {integer} **Default:** `5007`", + "name": "interval", + "type": "integer", + "default": "`5007`" + } + ] + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function", + "options": [ + { + "textRaw": "`current` {fs.Stats}", + "name": "current", + "type": "fs.Stats" + }, + { + "textRaw": "`previous` {fs.Stats}", + "name": "previous", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.

      \n

      The options argument may be omitted. If provided, it should be an object. The\noptions object may contain a boolean named persistent that indicates\nwhether the process should continue to run as long as files are being watched.\nThe options object may specify an interval property indicating how often the\ntarget should be polled in milliseconds.

      \n

      The listener gets two arguments the current stat object and the previous\nstat object:

      \n
      fs.watchFile('message.text', (curr, prev) => {\n  console.log(`the current mtime is: ${curr.mtime}`);\n  console.log(`the previous mtime was: ${prev.mtime}`);\n});\n
      \n

      These stat objects are instances of fs.Stat. If the bigint option is true,\nthe numeric values in these objects are specified as BigInts.

      \n

      To be notified when the file was modified, not just accessed, it is necessary\nto compare curr.mtime and prev.mtime.

      \n

      When an fs.watchFile operation results in an ENOENT error, it\nwill invoke the listener once, with all the fields zeroed (or, for dates, the\nUnix Epoch). If the file is created later on, the listener will be called\nagain, with the latest stat objects. This is a change in functionality since\nv0.10.

      \n

      Using fs.watch() is more efficient than fs.watchFile and\nfs.unwatchFile. fs.watch should be used instead of fs.watchFile and\nfs.unwatchFile when possible.

      \n

      When a file being watched by fs.watchFile() disappears and reappears,\nthen the contents of previous in the second callback event (the file's\nreappearance) will be the same as the contents of previous in the first\ncallback event (its disappearance).

      \n

      This happens when:

      \n
        \n
      • the file is deleted, followed by a restore
      • \n
      • the file is renamed and then renamed a second time back to its original name
      • \n
      " + }, + { + "textRaw": "`fs.write(fd, buffer[, offset[, length[, position]]], callback)`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`" + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `buffer` parameter can now be a `Uint8Array`." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `offset` and `length` parameters are optional now." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesWritten` {integer}", + "name": "bytesWritten", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + } + ] + } + ] + } + ], + "desc": "

      Write buffer to the file specified by fd.

      \n

      offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position. See pwrite(2).

      \n

      The callback will be given three arguments (err, bytesWritten, buffer) where\nbytesWritten specifies how many bytes were written from buffer.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with bytesWritten and buffer properties.

      \n

      It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`fs.write(fd, string[, position[, encoding]], callback)`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.11.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `position` parameter is optional now." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`written` {integer}", + "name": "written", + "type": "integer" + }, + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ] + } + ], + "desc": "

      Write string to the file specified by fd. If string is not a string, then\nthe value will be coerced to one.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number' the data will be written at\nthe current position. See pwrite(2).

      \n

      encoding is the expected string encoding.

      \n

      The callback will receive the arguments (err, written, string) where written\nspecifies how many bytes the passed string required to be written. Bytes\nwritten is not necessarily the same as string characters written. See\nBuffer.byteLength.

      \n

      It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      \n

      On Windows, if the file descriptor is connected to the console (e.g. fd == 1\nor stdout) a string containing non-ASCII characters will not be rendered\nproperly by default, regardless of the encoding used.\nIt is possible to configure the console to render UTF-8 properly by changing the\nactive codepage with the chcp 65001 command. See the chcp docs for more\ndetails.

      " + }, + { + "textRaw": "`fs.writeFile(file, data[, options], callback)`", + "type": "method", + "name": "writeFile", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `data` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `data` parameter can now be a `Uint8Array`." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`file` {string|Buffer|URL|integer} filename or file descriptor", + "name": "file", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer|TypedArray|DataView}", + "name": "data", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flag", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      When file is a filename, asynchronously writes data to the file, replacing the\nfile if it already exists. data can be a string or a buffer.

      \n

      When file is a file descriptor, the behavior is similar to calling\nfs.write() directly (which is recommended). See the notes below on using\na file descriptor.

      \n

      The encoding option is ignored if data is a buffer.

      \n
      const data = new Uint8Array(Buffer.from('Hello Node.js'));\nfs.writeFile('message.txt', data, (err) => {\n  if (err) throw err;\n  console.log('The file has been saved!');\n});\n
      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);\n
      \n

      It is unsafe to use fs.writeFile() multiple times on the same file without\nwaiting for the callback. For this scenario, fs.createWriteStream() is\nrecommended.

      ", + "modules": [ + { + "textRaw": "Using `fs.writeFile()` with file descriptors", + "name": "using_`fs.writefile()`_with_file_descriptors", + "desc": "

      When file is a file descriptor, the behavior is almost identical to directly\ncalling fs.write() like:

      \n
      fs.write(fd, Buffer.from(data, options.encoding), callback);\n
      \n

      The difference from directly calling fs.write() is that under some unusual\nconditions, fs.write() may write only part of the buffer and will need to be\nretried to write the remaining data, whereas fs.writeFile() will retry until\nthe data is entirely written (or an error occurs).

      \n

      The implications of this are a common source of confusion. In\nthe file descriptor case, the file is not replaced! The data is not necessarily\nwritten to the beginning of the file, and the file's original data may remain\nbefore and/or after the newly written data.

      \n

      For example, if fs.writeFile() is called twice in a row, first to write the\nstring 'Hello', then to write the string ', World', the file would contain\n'Hello, World', and might contain some of the file's original data (depending\non the size of the original file, and the position of the file descriptor). If\na file name had been used instead of a descriptor, the file would be guaranteed\nto contain only ', World'.

      ", + "type": "module", + "displayName": "Using `fs.writeFile()` with file descriptors" + } + ] + }, + { + "textRaw": "`fs.writeFileSync(file, data[, options])`", + "type": "method", + "name": "writeFileSync", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `data` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `data` parameter can now be a `Uint8Array`." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`file` {string|Buffer|URL|integer} filename or file descriptor", + "name": "file", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer|TypedArray|DataView}", + "name": "data", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flag", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writeFile().

      " + }, + { + "textRaw": "`fs.writeSync(fd, buffer[, offset[, length[, position]]])`", + "type": "method", + "name": "writeSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `buffer` parameter can now be a `Uint8Array`." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `offset` and `length` parameters are optional now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes written.", + "name": "return", + "type": "number", + "desc": "The number of bytes written." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, buffer...).

      " + }, + { + "textRaw": "`fs.writeSync(fd, string[, position[, encoding]])`", + "type": "method", + "name": "writeSync", + "meta": { + "added": [ + "v0.11.5" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `position` parameter is optional now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes written.", + "name": "return", + "type": "number", + "desc": "The number of bytes written." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, string...).

      " + }, + { + "textRaw": "`fs.writev(fd, buffers[, position], callback)`", + "type": "method", + "name": "writev", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesWritten` {integer}", + "name": "bytesWritten", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + } + ] + } + ] + } + ], + "desc": "

      Write an array of ArrayBufferViews to the file specified by fd using\nwritev().

      \n

      position is the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position.

      \n

      The callback will be given three arguments: err, bytesWritten, and\nbuffers. bytesWritten is how many bytes were written from buffers.

      \n

      If this method is util.promisify()ed, it returns a Promise for an\nObject with bytesWritten and buffers properties.

      \n

      It is unsafe to use fs.writev() multiple times on the same file without\nwaiting for the callback. For this scenario, use fs.createWriteStream().

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`fs.writevSync(fd, buffers[, position])`", + "type": "method", + "name": "writevSync", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes written.", + "name": "return", + "type": "number", + "desc": "The number of bytes written." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writev().

      " + } + ], + "properties": [ + { + "textRaw": "`constants` {Object}", + "type": "Object", + "name": "constants", + "desc": "

      Returns an object containing commonly used constants for file system\noperations. The specific constants currently defined are described in\nFS constants.

      " + } + ], + "type": "module", + "displayName": "fs" + }, + { + "textRaw": "HTTP", + "name": "http", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/http.js

      \n

      To use the HTTP server and client one must require('http').

      \n

      The HTTP interfaces in Node.js are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses, so the\nuser is able to stream data.

      \n

      HTTP message headers are represented by an object like this:

      \n\n
      { 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'host': 'mysite.com',\n  'accept': '*/*' }\n
      \n

      Keys are lowercased. Values are not modified.

      \n

      In order to support the full spectrum of possible HTTP applications, the Node.js\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.

      \n

      See message.headers for details on how duplicate headers are handled.

      \n

      The raw headers as they were received are retained in the rawHeaders\nproperty, which is an array of [key, value, key2, value2, ...]. For\nexample, the previous message header object might have a rawHeaders\nlist like the following:

      \n\n
      [ 'ConTent-Length', '123456',\n  'content-LENGTH', '123',\n  'content-type', 'text/plain',\n  'CONNECTION', 'keep-alive',\n  'Host', 'mysite.com',\n  'accepT', '*/*' ]\n
      ", + "classes": [ + { + "textRaw": "Class: `http.Agent`", + "type": "class", + "name": "http.Agent", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "desc": "

      An Agent is responsible for managing connection persistence\nand reuse for HTTP clients. It maintains a queue of pending requests\nfor a given host and port, reusing a single socket connection for each\nuntil the queue is empty, at which time the socket is either destroyed\nor put into a pool where it is kept to be used again for requests to the\nsame host and port. Whether it is destroyed or pooled depends on the\nkeepAlive option.

      \n

      Pooled connections have TCP Keep-Alive enabled for them, but servers may\nstill close idle connections, in which case they will be removed from the\npool and a new connection will be made when a new HTTP request is made for\nthat host and port. Servers may also refuse to allow multiple requests\nover the same connection, in which case the connection will have to be\nremade for every request and cannot be pooled. The Agent will still make\nthe requests to that server, but each one will occur over a new connection.

      \n

      When a connection is closed by the client or the server, it is removed\nfrom the pool. Any unused sockets in the pool will be unrefed so as not\nto keep the Node.js process running when there are no outstanding requests.\n(see socket.unref()).

      \n

      It is good practice, to destroy() an Agent instance when it is no\nlonger in use, because unused sockets consume OS resources.

      \n

      Sockets are removed from an agent when the socket emits either\na 'close' event or an 'agentRemove' event. When intending to keep one\nHTTP request open for a long time without keeping it in the agent, something\nlike the following may be done:

      \n
      http.get(options, (res) => {\n  // Do stuff\n}).on('socket', (socket) => {\n  socket.emit('agentRemove');\n});\n
      \n

      An agent may also be used for an individual request. By providing\n{agent: false} as an option to the http.get() or http.request()\nfunctions, a one-time use Agent with default options will be used\nfor the client connection.

      \n

      agent:false:

      \n
      http.get({\n  hostname: 'localhost',\n  port: 80,\n  path: '/',\n  agent: false  // Create a new agent just for this one request\n}, (res) => {\n  // Do stuff with response\n});\n
      ", + "methods": [ + { + "textRaw": "`agent.createConnection(options[, callback])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Duplex}", + "name": "return", + "type": "stream.Duplex" + }, + "params": [ + { + "textRaw": "`options` {Object} Options containing connection details. Check [`net.createConnection()`][] for the format of the options", + "name": "options", + "type": "Object", + "desc": "Options containing connection details. Check [`net.createConnection()`][] for the format of the options" + }, + { + "textRaw": "`callback` {Function} Callback function that receives the created socket", + "name": "callback", + "type": "Function", + "desc": "Callback function that receives the created socket" + } + ] + } + ], + "desc": "

      Produces a socket/stream to be used for HTTP requests.

      \n

      By default, this function is the same as net.createConnection(). However,\ncustom agents may override this method in case greater flexibility is desired.

      \n

      A socket/stream can be supplied in one of two ways: by returning the\nsocket/stream from this function, or by passing the socket/stream to callback.

      \n

      This method is guaranteed to return an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      callback has a signature of (err, stream).

      " + }, + { + "textRaw": "`agent.keepSocketAlive(socket)`", + "type": "method", + "name": "keepSocketAlive", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ] + } + ], + "desc": "

      Called when socket is detached from a request and could be persisted by the\nAgent. Default behavior is to:

      \n
      socket.setKeepAlive(true, this.keepAliveMsecs);\nsocket.unref();\nreturn true;\n
      \n

      This method can be overridden by a particular Agent subclass. If this\nmethod returns a falsy value, the socket will be destroyed instead of persisting\nit for use with the next request.

      \n

      The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.

      " + }, + { + "textRaw": "`agent.reuseSocket(socket, request)`", + "type": "method", + "name": "reuseSocket", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + }, + { + "textRaw": "`request` {http.ClientRequest}", + "name": "request", + "type": "http.ClientRequest" + } + ] + } + ], + "desc": "

      Called when socket is attached to request after being persisted because of\nthe keep-alive options. Default behavior is to:

      \n
      socket.ref();\n
      \n

      This method can be overridden by a particular Agent subclass.

      \n

      The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.

      " + }, + { + "textRaw": "`agent.destroy()`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Destroy any sockets that are currently in use by the agent.

      \n

      It is usually not necessary to do this. However, if using an\nagent with keepAlive enabled, then it is best to explicitly shut down\nthe agent when it will no longer be used. Otherwise,\nsockets may hang open for quite a long time before the server\nterminates them.

      " + }, + { + "textRaw": "`agent.getName(options)`", + "type": "method", + "name": "getName", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`options` {Object} A set of options providing information for name generation", + "name": "options", + "type": "Object", + "desc": "A set of options providing information for name generation", + "options": [ + { + "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to", + "name": "host", + "type": "string", + "desc": "A domain name or IP address of the server to issue the request to" + }, + { + "textRaw": "`port` {number} Port of remote server", + "name": "port", + "type": "number", + "desc": "Port of remote server" + }, + { + "textRaw": "`localAddress` {string} Local interface to bind for network connections when issuing the request", + "name": "localAddress", + "type": "string", + "desc": "Local interface to bind for network connections when issuing the request" + }, + { + "textRaw": "`family` {integer} Must be 4 or 6 if this doesn't equal `undefined`.", + "name": "family", + "type": "integer", + "desc": "Must be 4 or 6 if this doesn't equal `undefined`." + } + ] + } + ] + } + ], + "desc": "

      Get a unique name for a set of request options, to determine whether a\nconnection can be reused. For an HTTP agent, this returns\nhost:port:localAddress or host:port:localAddress:family. For an HTTPS agent,\nthe name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options\nthat determine socket reusability.

      " + } + ], + "properties": [ + { + "textRaw": "`freeSockets` {Object}", + "type": "Object", + "name": "freeSockets", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive is enabled. Do not modify.

      \n

      Sockets in the freeSockets list will be automatically destroyed and\nremoved from the array on 'timeout'.

      " + }, + { + "textRaw": "`maxFreeSockets` {number}", + "type": "number", + "name": "maxFreeSockets", + "meta": { + "added": [ + "v0.11.7" + ], + "changes": [] + }, + "desc": "

      By default set to 256. For agents with keepAlive enabled, this\nsets the maximum number of sockets that will be left open in the free\nstate.

      " + }, + { + "textRaw": "`maxSockets` {number}", + "type": "number", + "name": "maxSockets", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [] + }, + "desc": "

      By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is the returned value of agent.getName().

      " + }, + { + "textRaw": "`maxTotalSockets` {number}", + "type": "number", + "name": "maxTotalSockets", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open. Unlike maxSockets, this parameter applies across all origins.

      " + }, + { + "textRaw": "`requests` {Object}", + "type": "Object", + "name": "requests", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "desc": "

      An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.

      " + }, + { + "textRaw": "`sockets` {Object}", + "type": "Object", + "name": "sockets", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [] + }, + "desc": "

      An object which contains arrays of sockets currently in use by the\nagent. Do not modify.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the following fields:", + "name": "options", + "type": "Object", + "desc": "Set of configurable options to set on the agent. Can have the following fields:", + "options": [ + { + "textRaw": "`keepAlive` {boolean} Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used. **Default:** `false`.", + "name": "keepAlive", + "type": "boolean", + "default": "`false`", + "desc": "Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used." + }, + { + "textRaw": "`keepAliveMsecs` {number} When using the `keepAlive` option, specifies the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. **Default:** `1000`.", + "name": "keepAliveMsecs", + "type": "number", + "default": "`1000`", + "desc": "When using the `keepAlive` option, specifies the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`." + }, + { + "textRaw": "`maxSockets` {number} Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached. **Default:** `Infinity`.", + "name": "maxSockets", + "type": "number", + "default": "`Infinity`", + "desc": "Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached." + }, + { + "textRaw": "`maxTotalSockets` {number} Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. **Default:** `Infinity`.", + "name": "maxTotalSockets", + "type": "number", + "default": "`Infinity`", + "desc": "Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached." + }, + { + "textRaw": "`maxFreeSockets` {number} Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. **Default:** `256`.", + "name": "maxFreeSockets", + "type": "number", + "default": "`256`", + "desc": "Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`." + }, + { + "textRaw": "`scheduling` {string} Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible. **Default:** `'fifo'`.", + "name": "scheduling", + "type": "string", + "default": "`'fifo'`", + "desc": "Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible." + }, + { + "textRaw": "`timeout` {number} Socket timeout in milliseconds. This will set the timeout when the socket is created.", + "name": "timeout", + "type": "number", + "desc": "Socket timeout in milliseconds. This will set the timeout when the socket is created." + } + ] + } + ], + "desc": "

      options in socket.connect() are also supported.

      \n

      The default http.globalAgent that is used by http.request() has all\nof these values set to their respective defaults.

      \n

      To configure any of them, a custom http.Agent instance must be created.

      \n
      const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
      " + } + ] + }, + { + "textRaw": "Class: `http.ClientRequest`", + "type": "class", + "name": "http.ClientRequest", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "\n

      This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value),\ngetHeader(name), removeHeader(name) API. The actual header will\nbe sent along with the first data chunk or when calling request.end().

      \n

      To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.IncomingMessage.

      \n

      During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.

      \n

      If no 'response' handler is added, then the response will be\nentirely discarded. However, if a 'response' event handler is added,\nthen the data from the response object must be consumed, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.

      \n

      Unlike the request object, if the response closes prematurely, the\nresponse object does not emit an 'error' event but instead emits the\n'aborted' event.

      \n

      Node.js does not check whether Content-Length and the length of the\nbody which has been transmitted are equal or not.

      ", + "events": [ + { + "textRaw": "Event: `'abort'`", + "type": "event", + "name": "abort", + "meta": { + "added": [ + "v1.4.1" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`response` {http.IncomingMessage}", + "name": "response", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + }, + { + "textRaw": "`head` {Buffer}", + "name": "head", + "type": "Buffer" + } + ], + "desc": "

      Emitted each time a server responds to a request with a CONNECT method. If\nthis event is not being listened for, clients receiving a CONNECT method will\nhave their connections closed.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      A client and server pair demonstrating how to listen for the 'connect' event:

      \n
      const http = require('http');\nconst net = require('net');\nconst { URL } = require('url');\n\n// Create an HTTP tunneling proxy\nconst proxy = http.createServer((req, res) => {\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('okay');\n});\nproxy.on('connect', (req, clientSocket, head) => {\n  // Connect to an origin server\n  const { port, hostname } = new URL(`http://${req.url}`);\n  const serverSocket = net.connect(port || 80, hostname, () => {\n    clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node.js-Proxy\\r\\n' +\n                    '\\r\\n');\n    serverSocket.write(head);\n    serverSocket.pipe(clientSocket);\n    clientSocket.pipe(serverSocket);\n  });\n});\n\n// Now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n  // Make a request to a tunneling proxy\n  const options = {\n    port: 1337,\n    host: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  const req = http.request(options);\n  req.end();\n\n  req.on('connect', (res, socket, head) => {\n    console.log('got connected!');\n\n    // Make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', (chunk) => {\n      console.log(chunk.toString());\n    });\n    socket.on('end', () => {\n      proxy.close();\n    });\n  });\n});\n
      " + }, + { + "textRaw": "Event: `'continue'`", + "type": "event", + "name": "continue", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.

      " + }, + { + "textRaw": "Event: `'information'`", + "type": "event", + "name": "information", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`info` {Object}", + "name": "info", + "type": "Object", + "options": [ + { + "textRaw": "`httpVersion` {string}", + "name": "httpVersion", + "type": "string" + }, + { + "textRaw": "`httpVersionMajor` {integer}", + "name": "httpVersionMajor", + "type": "integer" + }, + { + "textRaw": "`httpVersionMinor` {integer}", + "name": "httpVersionMinor", + "type": "integer" + }, + { + "textRaw": "`statusCode` {integer}", + "name": "statusCode", + "type": "integer" + }, + { + "textRaw": "`statusMessage` {string}", + "name": "statusMessage", + "type": "string" + }, + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + }, + { + "textRaw": "`rawHeaders` {string[]}", + "name": "rawHeaders", + "type": "string[]" + } + ] + } + ], + "desc": "

      Emitted when the server sends a 1xx intermediate response (excluding 101\nUpgrade). The listeners of this event will receive an object containing the\nHTTP version, status code, status message, key-value headers object,\nand array with the raw header names followed by their respective values.

      \n
      const http = require('http');\n\nconst options = {\n  host: '127.0.0.1',\n  port: 8080,\n  path: '/length_request'\n};\n\n// Make a request\nconst req = http.request(options);\nreq.end();\n\nreq.on('information', (info) => {\n  console.log(`Got information prior to main response: ${info.statusCode}`);\n});\n
      \n

      101 Upgrade statuses do not fire this event due to their break from the\ntraditional HTTP request/response chain, such as web sockets, in-place TLS\nupgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the\n'upgrade' event instead.

      " + }, + { + "textRaw": "Event: `'response'`", + "type": "event", + "name": "response", + "meta": { + "added": [ + "v0.1.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`response` {http.IncomingMessage}", + "name": "response", + "type": "http.IncomingMessage" + } + ], + "desc": "

      Emitted when a response is received to this request. This event is emitted only\nonce.

      " + }, + { + "textRaw": "Event: `'socket'`", + "type": "event", + "name": "socket", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v0.7.8" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the underlying socket times out from inactivity. This only notifies\nthat the socket has been idle. The request must be aborted manually.

      \n

      See also: request.setTimeout().

      " + }, + { + "textRaw": "Event: `'upgrade'`", + "type": "event", + "name": "upgrade", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`response` {http.IncomingMessage}", + "name": "response", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + }, + { + "textRaw": "`head` {Buffer}", + "name": "head", + "type": "Buffer" + } + ], + "desc": "

      Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for and the response status code is 101 Switching\nProtocols, clients receiving an upgrade header will have their connections\nclosed.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      A client server pair demonstrating how to listen for the 'upgrade' event.

      \n
      const http = require('http');\n\n// Create an HTTP server\nconst server = http.createServer((req, res) => {\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('okay');\n});\nserver.on('upgrade', (req, socket, head) => {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// Now that server is running\nserver.listen(1337, '127.0.0.1', () => {\n\n  // make a request\n  const options = {\n    port: 1337,\n    host: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  const req = http.request(options);\n  req.end();\n\n  req.on('upgrade', (res, socket, upgradeHead) => {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`request.abort()`", + "type": "method", + "name": "abort", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.

      " + }, + { + "textRaw": "`request.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `ClientRequest`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.

      \n

      If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end(callback).

      \n

      If callback is specified, it will be called when the request stream\nis finished.

      " + }, + { + "textRaw": "`request.flushHeaders()`", + "type": "method", + "name": "flushHeaders", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Flushes the request headers.

      \n

      For efficiency reasons, Node.js normally buffers the request headers until\nrequest.end() is called or the first chunk of request data is written. It\nthen tries to pack the request headers and data into a single TCP packet.

      \n

      That's usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. request.flushHeaders() bypasses\nthe optimization and kickstarts the request.

      " + }, + { + "textRaw": "`request.getHeader(name)`", + "type": "method", + "name": "getHeader", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any}", + "name": "return", + "type": "any" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Reads out a header on the request. The name is case-insensitive.\nThe type of the return value depends on the arguments provided to\nrequest.setHeader().

      \n
      request.setHeader('content-type', 'text/html');\nrequest.setHeader('Content-Length', Buffer.byteLength(body));\nrequest.setHeader('Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = request.getHeader('Content-Type');\n// 'contentType' is 'text/html'\nconst contentLength = request.getHeader('Content-Length');\n// 'contentLength' is of type number\nconst cookie = request.getHeader('Cookie');\n// 'cookie' is of type string[]\n
      " + }, + { + "textRaw": "`request.removeHeader(name)`", + "type": "method", + "name": "removeHeader", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Removes a header that's already defined into headers object.

      \n
      request.removeHeader('Content-Type');\n
      " + }, + { + "textRaw": "`request.setHeader(name, value)`", + "type": "method", + "name": "setHeader", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Sets a single header value for headers object. If this header already exists in\nthe to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, request.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission.

      \n
      request.setHeader('Content-Type', 'application/json');\n
      \n

      or

      \n
      request.setHeader('Cookie', ['type=ninja', 'language=javascript']);\n
      " + }, + { + "textRaw": "`request.setNoDelay([noDelay])`", + "type": "method", + "name": "setNoDelay", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`noDelay` {boolean}", + "name": "noDelay", + "type": "boolean" + } + ] + } + ], + "desc": "

      Once a socket is assigned to this request and is connected\nsocket.setNoDelay() will be called.

      " + }, + { + "textRaw": "`request.setSocketKeepAlive([enable][, initialDelay])`", + "type": "method", + "name": "setSocketKeepAlive", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`enable` {boolean}", + "name": "enable", + "type": "boolean" + }, + { + "textRaw": "`initialDelay` {number}", + "name": "initialDelay", + "type": "number" + } + ] + } + ], + "desc": "

      Once a socket is assigned to this request and is connected\nsocket.setKeepAlive() will be called.

      " + }, + { + "textRaw": "`request.setTimeout(timeout[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8895", + "description": "Consistently set socket timeout only when the socket connects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`timeout` {number} Milliseconds before a request times out.", + "name": "timeout", + "type": "number", + "desc": "Milliseconds before a request times out." + }, + { + "textRaw": "`callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event.", + "name": "callback", + "type": "Function", + "desc": "Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event." + } + ] + } + ], + "desc": "

      Once a socket is assigned to this request and is connected\nsocket.setTimeout() will be called.

      " + }, + { + "textRaw": "`request.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer}", + "name": "chunk", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sends a chunk of the body. By calling this method\nmany times, a request body can be sent to a\nserver. In that case, it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.

      \n

      The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.

      \n

      The callback argument is optional and will be called when this chunk of data\nis flushed, but only if the chunk is non-empty.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.

      \n

      When write function is called with empty string or buffer, it does\nnothing and waits for more input.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20230", + "description": "The `aborted` property is no longer a timestamp number." + } + ] + }, + "desc": "

      The request.aborted property will be true if the request has\nbeen aborted.

      " + }, + { + "textRaw": "`connection` {stream.Duplex}", + "type": "stream.Duplex", + "name": "connection", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      See request.socket.

      " + }, + { + "textRaw": "`finished` {boolean}", + "type": "boolean", + "name": "finished", + "meta": { + "added": [ + "v0.0.1" + ], + "deprecated": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated. Use [`request.writableEnded`][].", + "desc": "

      The request.finished property will be true if request.end()\nhas been called. request.end() will automatically be called if the\nrequest was initiated via http.get().

      " + }, + { + "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", + "type": "number", + "name": "maxHeadersCount", + "default": "`2000`", + "desc": "

      Limits maximum response headers count. If set to 0, no limit will be applied.

      " + }, + { + "textRaw": "`path` {string} The request path.", + "type": "string", + "name": "path", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "desc": "The request path." + }, + { + "textRaw": "`method` {string} The request method.", + "type": "string", + "name": "method", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [] + }, + "desc": "The request method." + }, + { + "textRaw": "`host` {string} The request host.", + "type": "string", + "name": "host", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "The request host." + }, + { + "textRaw": "`protocol` {string} The request protocol.", + "type": "string", + "name": "protocol", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "The request protocol." + }, + { + "textRaw": "`reusedSocket` {boolean} Whether the request is send through a reused socket.", + "type": "boolean", + "name": "reusedSocket", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      When sending request through a keep-alive enabled agent, the underlying socket\nmight be reused. But if server closes connection at unfortunate time, client\nmay run into a 'ECONNRESET' error.

      \n
      const http = require('http');\n\n// Server has a 5 seconds keep-alive timeout by default\nhttp\n  .createServer((req, res) => {\n    res.write('hello\\n');\n    res.end();\n  })\n  .listen(3000);\n\nsetInterval(() => {\n  // Adapting a keep-alive agent\n  http.get('http://localhost:3000', { agent }, (res) => {\n    res.on('data', (data) => {\n      // Do nothing\n    });\n  });\n}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout\n
      \n

      By marking a request whether it reused socket or not, we can do\nautomatic error retry base on it.

      \n
      const http = require('http');\nconst agent = new http.Agent({ keepAlive: true });\n\nfunction retriableRequest() {\n  const req = http\n    .get('http://localhost:3000', { agent }, (res) => {\n      // ...\n    })\n    .on('error', (err) => {\n      // Check if retry is needed\n      if (req.reusedSocket && err.code === 'ECONNRESET') {\n        retriableRequest();\n      }\n    });\n}\n\nretriableRequest();\n
      ", + "shortDesc": "Whether the request is send through a reused socket." + }, + { + "textRaw": "`socket` {stream.Duplex}", + "type": "stream.Duplex", + "name": "socket", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. The socket\nmay also be accessed via request.connection.

      \n
      const http = require('http');\nconst options = {\n  host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n  const ip = req.socket.localAddress;\n  const port = req.socket.localPort;\n  console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n  // Consume response object\n});\n
      \n

      This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after request.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nrequest.writableFinished instead.

      " + }, + { + "textRaw": "`writableFinished` {boolean}", + "type": "boolean", + "name": "writableFinished", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "desc": "

      Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.

      " + } + ] + }, + { + "textRaw": "Class: `http.Server`", + "type": "class", + "name": "http.Server", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "", + "events": [ + { + "textRaw": "Event: `'checkContinue'`", + "type": "event", + "name": "checkContinue", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage}", + "name": "request", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`response` {http.ServerResponse}", + "name": "response", + "type": "http.ServerResponse" + } + ], + "desc": "

      Emitted each time a request with an HTTP Expect: 100-continue is received.\nIf this event is not listened for, the server will automatically respond\nwith a 100 Continue as appropriate.

      \n

      Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + }, + { + "textRaw": "Event: `'checkExpectation'`", + "type": "event", + "name": "checkExpectation", + "meta": { + "added": [ + "v5.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage}", + "name": "request", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`response` {http.ServerResponse}", + "name": "response", + "type": "http.ServerResponse" + } + ], + "desc": "

      Emitted each time a request with an HTTP Expect header is received, where the\nvalue is not 100-continue. If this event is not listened for, the server will\nautomatically respond with a 417 Expectation Failed as appropriate.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + }, + { + "textRaw": "Event: `'clientError'`", + "type": "event", + "name": "clientError", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4557", + "description": "The default action of calling `.destroy()` on the `socket` will no longer take place if there are listeners attached for `'clientError'`." + }, + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/17672", + "description": "The `rawPacket` is the current buffer that just parsed. Adding this buffer to the error object of `'clientError'` event is to make it possible that developers can log the broken packet." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25605", + "description": "The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs." + } + ] + }, + "params": [ + { + "textRaw": "`exception` {Error}", + "name": "exception", + "type": "Error" + }, + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      If a client connection emits an 'error' event, it will be forwarded here.\nListener of this event is responsible for closing/destroying the underlying\nsocket. For example, one may wish to more gracefully close the socket with a\ncustom HTTP response instead of abruptly severing the connection.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      Default behavior is to try close the socket with a HTTP '400 Bad Request',\nor a HTTP '431 Request Header Fields Too Large' in the case of a\nHPE_HEADER_OVERFLOW error. If the socket is not writable or has already\nwritten data it is immediately destroyed.

      \n

      socket is the net.Socket object that the error originated from.

      \n
      const http = require('http');\n\nconst server = http.createServer((req, res) => {\n  res.end();\n});\nserver.on('clientError', (err, socket) => {\n  socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n
      \n

      When the 'clientError' event occurs, there is no request or response\nobject, so any HTTP response sent, including response headers and payload,\nmust be written directly to the socket object. Care must be taken to\nensure the response is a properly formatted HTTP response message.

      \n

      err is an instance of Error with two extra columns:

      \n
        \n
      • bytesParsed: the bytes count of request packet that Node.js may have parsed\ncorrectly;
      • \n
      • rawPacket: the raw packet of current request.
      • \n
      \n

      In some cases, the client has already received the response and/or the socket\nhas already been destroyed, like in case of ECONNRESET errors. Before\ntrying to send data to the socket, it is better to check that it is still\nwritable.

      \n
      server.on('clientError', (err, socket) => {\n  if (err.code === 'ECONNRESET' || !socket.writable) {\n    return;\n  }\n\n  socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\n
      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server closes.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event", + "name": "request", + "type": "http.IncomingMessage", + "desc": "Arguments for the HTTP request, as it is in the [`'request'`][] event" + }, + { + "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", + "name": "socket", + "type": "stream.Duplex", + "desc": "Network socket between the server and client" + }, + { + "textRaw": "`head` {Buffer} The first packet of the tunneling stream (may be empty)", + "name": "head", + "type": "Buffer", + "desc": "The first packet of the tunneling stream (may be empty)" + } + ], + "desc": "

      Emitted each time a client requests an HTTP CONNECT method. If this event is\nnot listened for, then clients requesting a CONNECT method will have their\nconnections closed.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.

      " + }, + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v0.1.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. The socket can\nalso be accessed at request.connection.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.

      \n

      If socket.setTimeout() is called here, the timeout will be replaced with\nserver.keepAliveTimeout when the socket has served a request (if\nserver.keepAliveTimeout is non-zero).

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "Event: `'request'`", + "type": "event", + "name": "request", + "meta": { + "added": [ + "v0.1.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage}", + "name": "request", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`response` {http.ServerResponse}", + "name": "response", + "type": "http.ServerResponse" + } + ], + "desc": "

      Emitted each time there is a request. There may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).

      " + }, + { + "textRaw": "Event: `'upgrade'`", + "type": "event", + "name": "upgrade", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "v10.0.0", + "description": "Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header." + } + ] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event", + "name": "request", + "type": "http.IncomingMessage", + "desc": "Arguments for the HTTP request, as it is in the [`'request'`][] event" + }, + { + "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", + "name": "socket", + "type": "stream.Duplex", + "desc": "Network socket between the server and client" + }, + { + "textRaw": "`head` {Buffer} The first packet of the upgraded stream (may be empty)", + "name": "head", + "type": "Buffer", + "desc": "The first packet of the upgraded stream (may be empty)" + } + ], + "desc": "

      Emitted each time a client requests an HTTP upgrade. Listening to this event\nis optional and clients cannot insist on a protocol change.

      \n

      After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      " + } + ], + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Stops the server from accepting new connections. See net.Server.close().

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts the HTTP server listening for connections.\nThis method is identical to server.listen() from net.Server.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.Server}", + "name": "return", + "type": "http.Server" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.

      \n

      If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.

      \n

      By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if a callback is assigned\nto the Server's 'timeout' event, timeouts must be handled explicitly.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      " + } + ], + "properties": [ + { + "textRaw": "`headersTimeout` {number} **Default:** `60000`", + "type": "number", + "name": "headersTimeout", + "meta": { + "added": [ + "v11.3.0" + ], + "changes": [] + }, + "default": "`60000`", + "desc": "

      Limit the amount of time the parser will wait to receive the complete HTTP\nheaders.

      \n

      In case of inactivity, the rules defined in server.timeout apply. However,\nthat inactivity based timeout would still allow the connection to be kept open\nif the headers are being sent very slowly (by default, up to a byte per 2\nminutes). In order to prevent this, whenever header data arrives an additional\ncheck is made that more than server.headersTimeout milliseconds has not\npassed since the connection was established. If the check fails, a 'timeout'\nevent is emitted on the server object, and (by default) the socket is destroyed.\nSee server.timeout for more information on how timeout behavior can be\ncustomized.

      \n

      A value of 0 will disable the HTTP headers timeout check.

      " + }, + { + "textRaw": "`listening` {boolean} Indicates whether or not the server is listening for connections.", + "type": "boolean", + "name": "listening", + "meta": { + "added": [ + "v5.7.0" + ], + "changes": [] + }, + "desc": "Indicates whether or not the server is listening for connections." + }, + { + "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", + "type": "number", + "name": "maxHeadersCount", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "default": "`2000`", + "desc": "

      Limits maximum incoming headers count. If set to 0, no limit will be applied.

      " + }, + { + "textRaw": "`timeout` {number} Timeout in milliseconds. **Default:** `120000` (2 minutes).", + "type": "number", + "name": "timeout", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "default": "`120000` (2 minutes)", + "desc": "

      The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

      \n

      A value of 0 will disable the timeout behavior on incoming connections.

      \n

      The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      ", + "shortDesc": "Timeout in milliseconds." + }, + { + "textRaw": "`keepAliveTimeout` {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).", + "type": "number", + "name": "keepAliveTimeout", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "default": "`5000` (5 seconds)", + "desc": "

      The number of milliseconds of inactivity a server needs to wait for additional\nincoming data, after it has finished writing the last response, before a socket\nwill be destroyed. If the server receives new data before the keep-alive\ntimeout has fired, it will reset the regular inactivity timeout, i.e.,\nserver.timeout.

      \n

      A value of 0 will disable the keep-alive timeout behavior on incoming\nconnections.\nA value of 0 makes the http server behave similarly to Node.js versions prior\nto 8.0.0, which did not have a keep-alive timeout.

      \n

      The socket timeout logic is set up on connection, so changing this value only\naffects new connections to the server, not any existing connections.

      ", + "shortDesc": "Timeout in milliseconds." + } + ] + }, + { + "textRaw": "Class: `http.ServerResponse`", + "type": "class", + "name": "http.ServerResponse", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "\n

      This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the the response is completed, or its underlying connection was\nterminated prematurely (before the response completion).

      " + }, + { + "textRaw": "Event: `'finish'`", + "type": "event", + "name": "finish", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.

      " + } + ], + "methods": [ + { + "textRaw": "`response.addTrailers(headers)`", + "type": "method", + "name": "addTrailers", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

      \n

      Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g. if the request was HTTP/1.0), they will\nbe silently discarded.

      \n

      HTTP requires the Trailer header to be sent in order to\nemit trailers, with a list of the header fields in its value. E.g.,

      \n
      response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nresponse.end();\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.cork()`", + "type": "method", + "name": "cork", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      See writable.cork().

      " + }, + { + "textRaw": "`response.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `ServerResponse`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.

      \n

      If data is specified, it is similar in effect to calling\nresponse.write(data, encoding) followed by response.end(callback).

      \n

      If callback is specified, it will be called when the response stream\nis finished.

      " + }, + { + "textRaw": "`response.flushHeaders()`", + "type": "method", + "name": "flushHeaders", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Flushes the response headers. See also: request.flushHeaders().

      " + }, + { + "textRaw": "`response.getHeader(name)`", + "type": "method", + "name": "getHeader", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any}", + "name": "return", + "type": "any" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Reads out a header that's already been queued but not sent to the client.\nThe name is case-insensitive. The type of the return value depends\non the arguments provided to response.setHeader().

      \n
      response.setHeader('Content-Type', 'text/html');\nresponse.setHeader('Content-Length', Buffer.byteLength(body));\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = response.getHeader('content-type');\n// contentType is 'text/html'\nconst contentLength = response.getHeader('Content-Length');\n// contentLength is of type number\nconst setCookie = response.getHeader('set-cookie');\n// setCookie is of type string[]\n
      " + }, + { + "textRaw": "`response.getHeaderNames()`", + "type": "method", + "name": "getHeaderNames", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
      " + }, + { + "textRaw": "`response.getHeaders()`", + "type": "method", + "name": "getHeaders", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.

      \n

      The object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
      " + }, + { + "textRaw": "`response.hasHeader(name)`", + "type": "method", + "name": "hasHeader", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

      \n
      const hasContentType = response.hasHeader('content-type');\n
      " + }, + { + "textRaw": "`response.removeHeader(name)`", + "type": "method", + "name": "removeHeader", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Removes a header that's queued for implicit sending.

      \n
      response.removeHeader('Content-Encoding');\n
      " + }, + { + "textRaw": "`response.setHeader(name, value)`", + "type": "method", + "name": "setHeader", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, response.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission.

      \n
      response.setHeader('Content-Type', 'text/html');\n
      \n

      or

      \n
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n
      // Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('ok');\n});\n
      \n

      If response.writeHead() method is called and this method has not been\ncalled, it will directly write the supplied header values onto the network\nchannel without caching internally, and the response.getHeader() on the\nheader will not yield the expected result. If progressive population of headers\nis desired with potential future retrieval and modification, use\nresponse.setHeader() instead of response.writeHead().

      " + }, + { + "textRaw": "`response.setTimeout(msecs[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ServerResponse}", + "name": "return", + "type": "http.ServerResponse" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.

      \n

      If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If a handler is\nassigned to the request, the response, or the server's 'timeout' events,\ntimed out sockets must be handled explicitly.

      " + }, + { + "textRaw": "`response.uncork()`", + "type": "method", + "name": "uncork", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      See writable.uncork().

      " + }, + { + "textRaw": "`response.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer}", + "name": "chunk", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

      \n

      This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

      \n

      In the http module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204 and 304 responses\nmust not include a message body.

      \n

      chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\ncallback will be called when this chunk of data is flushed.

      \n

      This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

      \n

      The first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.

      " + }, + { + "textRaw": "`response.writeContinue()`", + "type": "method", + "name": "writeContinue", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue' event on\nServer.

      " + }, + { + "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", + "type": "method", + "name": "writeHead", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v11.10.0", + "pr-url": "https://github.com/nodejs/node/pull/25974", + "description": "Return `this` from `writeHead()` to allow chaining with `end()`." + }, + { + "version": "v5.11.0, v4.4.5", + "pr-url": "https://github.com/nodejs/node/pull/6291", + "description": "A `RangeError` is thrown if `statusCode` is not a number in the range `[100, 999]`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ServerResponse}", + "name": "return", + "type": "http.ServerResponse" + }, + "params": [ + { + "textRaw": "`statusCode` {number}", + "name": "statusCode", + "type": "number" + }, + { + "textRaw": "`statusMessage` {string}", + "name": "statusMessage", + "type": "string" + }, + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable statusMessage as the second\nargument.

      \n

      Returns a reference to the ServerResponse, so that calls can be chained.

      \n
      const body = 'hello world';\nresponse\n  .writeHead(200, {\n    'Content-Length': Buffer.byteLength(body),\n    'Content-Type': 'text/plain'\n  })\n  .end(body);\n
      \n

      This method must only be called once on a message and it must\nbe called before response.end() is called.

      \n

      If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n

      If this method is called and response.setHeader() has not been called,\nit will directly write the supplied header values onto the network channel\nwithout caching internally, and the response.getHeader() on the header\nwill not yield the expected result. If progressive population of headers is\ndesired with potential future retrieval and modification, use\nresponse.setHeader() instead.

      \n
      // Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('ok');\n});\n
      \n

      Content-Length is given in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes. Node.js\ndoes not check whether Content-Length and the length of the body which has\nbeen transmitted are equal or not.

      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.writeProcessing()`", + "type": "method", + "name": "writeProcessing", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sends a HTTP/1.1 102 Processing message to the client, indicating that\nthe request body should be sent.

      " + } + ], + "properties": [ + { + "textRaw": "`connection` {stream.Duplex}", + "type": "stream.Duplex", + "name": "connection", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      See response.socket.

      " + }, + { + "textRaw": "`finished` {boolean}", + "type": "boolean", + "name": "finished", + "meta": { + "added": [ + "v0.0.2" + ], + "deprecated": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated. Use [`response.writableEnded`][].", + "desc": "

      The response.finished property will be true if response.end()\nhas been called.

      " + }, + { + "textRaw": "`headersSent` {boolean}", + "type": "boolean", + "name": "headersSent", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "desc": "

      Boolean (read-only). True if headers were sent, false otherwise.

      " + }, + { + "textRaw": "`sendDate` {boolean}", + "type": "boolean", + "name": "sendDate", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "desc": "

      When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.

      \n

      This should only be disabled for testing; HTTP requires the Date header\nin responses.

      " + }, + { + "textRaw": "`socket` {stream.Duplex}", + "type": "stream.Duplex", + "name": "socket", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. After\nresponse.end(), the property is nulled. The socket may also be accessed\nvia response.connection.

      \n
      const http = require('http');\nconst server = http.createServer((req, res) => {\n  const ip = res.socket.remoteAddress;\n  const port = res.socket.remotePort;\n  res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
      \n

      This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "`statusCode` {number} **Default:** `200`", + "type": "number", + "name": "statusCode", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "default": "`200`", + "desc": "

      When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.

      \n
      response.statusCode = 404;\n
      \n

      After response header was sent to the client, this property indicates the\nstatus code which was sent out.

      " + }, + { + "textRaw": "`statusMessage` {string}", + "type": "string", + "name": "statusMessage", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status message that will be sent to the client when\nthe headers get flushed. If this is left as undefined then the standard\nmessage for the status code will be used.

      \n
      response.statusMessage = 'Not found';\n
      \n

      After response header was sent to the client, this property indicates the\nstatus message which was sent out.

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nresponse.writableFinished instead.

      " + }, + { + "textRaw": "`writableFinished` {boolean}", + "type": "boolean", + "name": "writableFinished", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "desc": "

      Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.

      " + } + ] + }, + { + "textRaw": "Class: `http.IncomingMessage`", + "type": "class", + "name": "http.IncomingMessage", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30135", + "description": "The `readableHighWaterMark` value mirrors that of the socket." + } + ] + }, + "desc": "\n

      An IncomingMessage object is created by http.Server or\nhttp.ClientRequest and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response\nstatus, headers and data.

      ", + "events": [ + { + "textRaw": "Event: `'aborted'`", + "type": "event", + "name": "aborted", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the request has been aborted.

      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the underlying connection was closed.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v10.1.0" + ], + "changes": [] + }, + "desc": "

      The message.aborted property will be true if the request has\nbeen aborted.

      " + }, + { + "textRaw": "`complete` {boolean}", + "type": "boolean", + "name": "complete", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      The message.complete property will be true if a complete HTTP message has\nbeen received and successfully parsed.

      \n

      This property is particularly useful as a means of determining if a client or\nserver fully transmitted a message before a connection was terminated:

      \n
      const req = http.request({\n  host: '127.0.0.1',\n  port: 8080,\n  method: 'POST'\n}, (res) => {\n  res.resume();\n  res.on('end', () => {\n    if (!res.complete)\n      console.error(\n        'The connection was terminated while the message was still being sent');\n  });\n});\n
      " + }, + { + "textRaw": "`headers` {Object}", + "type": "Object", + "name": "headers", + "meta": { + "added": [ + "v0.1.5" + ], + "changes": [] + }, + "desc": "

      The request/response headers object.

      \n

      Key-value pairs of header names and values. Header names are lower-cased.

      \n
      // Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);\n
      \n

      Duplicates in raw headers are handled in the following ways, depending on the\nheader name:

      \n
        \n
      • Duplicates of age, authorization, content-length, content-type,\netag, expires, from, host, if-modified-since, if-unmodified-since,\nlast-modified, location, max-forwards, proxy-authorization, referer,\nretry-after, server, or user-agent are discarded.
      • \n
      • set-cookie is always an array. Duplicates are added to the array.
      • \n
      • For duplicate cookie headers, the values are joined together with '; '.
      • \n
      • For all other headers, the values are joined together with ', '.
      • \n
      " + }, + { + "textRaw": "`httpVersion` {string}", + "type": "string", + "name": "httpVersion", + "meta": { + "added": [ + "v0.1.1" + ], + "changes": [] + }, + "desc": "

      In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.

      \n

      Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

      " + }, + { + "textRaw": "`method` {string}", + "type": "string", + "name": "method", + "meta": { + "added": [ + "v0.1.1" + ], + "changes": [] + }, + "desc": "

      Only valid for request obtained from http.Server.

      \n

      The request method as a string. Read only. Examples: 'GET', 'DELETE'.

      " + }, + { + "textRaw": "`rawHeaders` {string[]}", + "type": "string[]", + "name": "rawHeaders", + "meta": { + "added": [ + "v0.11.6" + ], + "changes": [] + }, + "desc": "

      The raw request/response headers list exactly as they were received.

      \n

      The keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.

      \n

      Header names are not lowercased, and duplicates are not merged.

      \n
      // Prints something like:\n//\n// [ 'user-agent',\n//   'this is invalid because there can be only one',\n//   'User-Agent',\n//   'curl/7.22.0',\n//   'Host',\n//   '127.0.0.1:8000',\n//   'ACCEPT',\n//   '*/*' ]\nconsole.log(request.rawHeaders);\n
      " + }, + { + "textRaw": "`rawTrailers` {string[]}", + "type": "string[]", + "name": "rawTrailers", + "meta": { + "added": [ + "v0.11.6" + ], + "changes": [] + }, + "desc": "

      The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`socket` {stream.Duplex}", + "type": "stream.Duplex", + "name": "socket", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      The net.Socket object associated with the connection.

      \n

      With HTTPS support, use request.socket.getPeerCertificate() to obtain the\nclient's authentication details.

      \n

      This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "`statusCode` {number}", + "type": "number", + "name": "statusCode", + "meta": { + "added": [ + "v0.1.1" + ], + "changes": [] + }, + "desc": "

      Only valid for response obtained from http.ClientRequest.

      \n

      The 3-digit HTTP response status code. E.G. 404.

      " + }, + { + "textRaw": "`statusMessage` {string}", + "type": "string", + "name": "statusMessage", + "meta": { + "added": [ + "v0.11.10" + ], + "changes": [] + }, + "desc": "

      Only valid for response obtained from http.ClientRequest.

      \n

      The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

      " + }, + { + "textRaw": "`trailers` {Object}", + "type": "Object", + "name": "trailers", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      The request/response trailers object. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`url` {string}", + "type": "string", + "name": "url", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      Only valid for request obtained from http.Server.

      \n

      Request URL string. This contains only the URL that is present in the actual\nHTTP request. Take the following request:

      \n
      GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
      \n

      To parse the URL into its parts:

      \n
      new URL(request.url, `http://${request.headers.host}`);\n
      \n

      When request.url is '/status?name=ryan' and\nrequest.headers.host is 'localhost:3000':

      \n
      $ node\n> new URL(request.url, `http://${request.headers.host}`)\nURL {\n  href: 'http://localhost:3000/status?name=ryan',\n  origin: 'http://localhost:3000',\n  protocol: 'http:',\n  username: '',\n  password: '',\n  host: 'localhost:3000',\n  hostname: 'localhost',\n  port: '3000',\n  pathname: '/status',\n  search: '?name=ryan',\n  searchParams: URLSearchParams { 'name' => 'ryan' },\n  hash: ''\n}\n
      " + } + ], + "methods": [ + { + "textRaw": "`message.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/32789", + "description": "The function returns `this` for consistency with other Readable streams." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      Calls destroy() on the socket that received the IncomingMessage. If error\nis provided, an 'error' event is emitted on the socket and error is passed\nas an argument to any listeners on the event.

      " + }, + { + "textRaw": "`message.setTimeout(msecs[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.IncomingMessage}", + "name": "return", + "type": "http.IncomingMessage" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Calls message.connection.setTimeout(msecs, callback).

      " + } + ] + } + ], + "properties": [ + { + "textRaw": "`METHODS` {string[]}", + "type": "string[]", + "name": "METHODS", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      A list of the HTTP methods that are supported by the parser.

      " + }, + { + "textRaw": "`STATUS_CODES` {Object}", + "type": "Object", + "name": "STATUS_CODES", + "meta": { + "added": [ + "v0.1.22" + ], + "changes": [] + }, + "desc": "

      A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

      " + }, + { + "textRaw": "`globalAgent` {http.Agent}", + "type": "http.Agent", + "name": "globalAgent", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "desc": "

      Global instance of Agent which is used as the default for all HTTP client\nrequests.

      " + }, + { + "textRaw": "`maxHeaderSize` {number}", + "type": "number", + "name": "maxHeaderSize", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      Read-only property specifying the maximum allowed size of HTTP headers in bytes.\nDefaults to 8KB. Configurable using the --max-http-header-size CLI option.

      " + } + ], + "methods": [ + { + "textRaw": "`http.createServer([options][, requestListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.1.13" + ], + "changes": [ + { + "version": "v12.15.0", + "pr-url": "https://github.com/nodejs/node/pull/31448", + "description": "The `insecureHTTPParser` option is supported now." + }, + { + "version": "v9.6.0, v8.12.0", + "pr-url": "https://github.com/nodejs/node/pull/15752", + "description": "The `options` argument is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.Server}", + "name": "return", + "type": "http.Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. **Default:** `IncomingMessage`.", + "name": "IncomingMessage", + "type": "http.IncomingMessage", + "default": "`IncomingMessage`", + "desc": "Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`." + }, + { + "textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. **Default:** `ServerResponse`.", + "name": "ServerResponse", + "type": "http.ServerResponse", + "default": "`ServerResponse`", + "desc": "Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`." + }, + { + "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", + "name": "insecureHTTPParser", + "type": "boolean", + "default": "`false`", + "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." + } + ] + }, + { + "textRaw": "`requestListener` {Function}", + "name": "requestListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Returns a new instance of http.Server.

      \n

      The requestListener is a function which is automatically\nadded to the 'request' event.

      " + }, + { + "textRaw": "`http.get(options[, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object} Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.", + "name": "options", + "type": "Object", + "desc": "Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request() is that it sets the method to GET and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.

      \n

      The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.

      \n

      JSON fetching example:

      \n
      http.get('http://nodejs.org/dist/index.json', (res) => {\n  const { statusCode } = res;\n  const contentType = res.headers['content-type'];\n\n  let error;\n  // Any 2xx status code signals a successful response but\n  // here we're only checking for 200.\n  if (statusCode !== 200) {\n    error = new Error('Request Failed.\\n' +\n                      `Status Code: ${statusCode}`);\n  } else if (!/^application\\/json/.test(contentType)) {\n    error = new Error('Invalid content-type.\\n' +\n                      `Expected application/json but received ${contentType}`);\n  }\n  if (error) {\n    console.error(error.message);\n    // Consume response data to free up memory\n    res.resume();\n    return;\n  }\n\n  res.setEncoding('utf8');\n  let rawData = '';\n  res.on('data', (chunk) => { rawData += chunk; });\n  res.on('end', () => {\n    try {\n      const parsedData = JSON.parse(rawData);\n      console.log(parsedData);\n    } catch (e) {\n      console.error(e.message);\n    }\n  });\n}).on('error', (e) => {\n  console.error(`Got error: ${e.message}`);\n});\n
      " + }, + { + "textRaw": "`http.get(url[, options][, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object} Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.", + "name": "options", + "type": "Object", + "desc": "Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request() is that it sets the method to GET and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.

      \n

      The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.

      \n

      JSON fetching example:

      \n
      http.get('http://nodejs.org/dist/index.json', (res) => {\n  const { statusCode } = res;\n  const contentType = res.headers['content-type'];\n\n  let error;\n  // Any 2xx status code signals a successful response but\n  // here we're only checking for 200.\n  if (statusCode !== 200) {\n    error = new Error('Request Failed.\\n' +\n                      `Status Code: ${statusCode}`);\n  } else if (!/^application\\/json/.test(contentType)) {\n    error = new Error('Invalid content-type.\\n' +\n                      `Expected application/json but received ${contentType}`);\n  }\n  if (error) {\n    console.error(error.message);\n    // Consume response data to free up memory\n    res.resume();\n    return;\n  }\n\n  res.setEncoding('utf8');\n  let rawData = '';\n  res.on('data', (chunk) => { rawData += chunk; });\n  res.on('end', () => {\n    try {\n      const parsedData = JSON.parse(rawData);\n      console.log(parsedData);\n    } catch (e) {\n      console.error(e.message);\n    }\n  });\n}).on('error', (e) => {\n  console.error(`Got error: ${e.message}`);\n});\n
      " + }, + { + "textRaw": "`http.request(options[, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v12.15.0", + "pr-url": "https://github.com/nodejs/node/pull/31448", + "description": "The `insecureHTTPParser` option is supported now." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible values:", + "name": "agent", + "type": "http.Agent | boolean", + "desc": "Controls [`Agent`][] behavior. Possible values:", + "options": [ + { + "textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port.", + "name": "undefined", + "desc": "(default): use [`http.globalAgent`][] for this host and port." + }, + { + "textRaw": "`Agent` object: explicitly use the passed in `Agent`.", + "name": "Agent", + "desc": "object: explicitly use the passed in `Agent`." + }, + { + "textRaw": "`false`: causes a new `Agent` with default values to be used.", + "name": "false", + "desc": "causes a new `Agent` with default values to be used." + } + ] + }, + { + "textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header.", + "name": "auth", + "type": "string", + "desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header." + }, + { + "textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value.", + "name": "createConnection", + "type": "Function", + "desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value." + }, + { + "textRaw": "`defaultPort` {number} Default port for the protocol. **Default:** `agent.defaultPort` if an `Agent` is used, else `undefined`.", + "name": "defaultPort", + "type": "number", + "default": "`agent.defaultPort` if an `Agent` is used, else `undefined`", + "desc": "Default port for the protocol." + }, + { + "textRaw": "`family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.", + "name": "family", + "type": "number", + "desc": "IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used." + }, + { + "textRaw": "`headers` {Object} An object containing request headers.", + "name": "headers", + "type": "Object", + "desc": "An object containing request headers." + }, + { + "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "A domain name or IP address of the server to issue the request to." + }, + { + "textRaw": "`hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified.", + "name": "hostname", + "type": "string", + "desc": "Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified." + }, + { + "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", + "name": "insecureHTTPParser", + "type": "boolean", + "default": "`false`", + "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." + }, + { + "textRaw": "`localAddress` {string} Local interface to bind for network connections.", + "name": "localAddress", + "type": "string", + "desc": "Local interface to bind for network connections." + }, + { + "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", + "name": "lookup", + "type": "Function", + "default": "[`dns.lookup()`][]", + "desc": "Custom lookup function." + }, + { + "textRaw": "`method` {string} A string specifying the HTTP request method. **Default:** `'GET'`.", + "name": "method", + "type": "string", + "default": "`'GET'`", + "desc": "A string specifying the HTTP request method." + }, + { + "textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. **Default:** `'/'`.", + "name": "path", + "type": "string", + "default": "`'/'`", + "desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future." + }, + { + "textRaw": "`port` {number} Port of remote server. **Default:** `defaultPort` if set, else `80`.", + "name": "port", + "type": "number", + "default": "`defaultPort` if set, else `80`", + "desc": "Port of remote server." + }, + { + "textRaw": "`protocol` {string} Protocol to use. **Default:** `'http:'`.", + "name": "protocol", + "type": "string", + "default": "`'http:'`", + "desc": "Protocol to use." + }, + { + "textRaw": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. Defaults to `true`.", + "name": "setHost", + "type": "boolean", + "desc": ": Specifies whether or not to automatically add the `Host` header. Defaults to `true`." + }, + { + "textRaw": "`socketPath` {string} Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket).", + "name": "socketPath", + "type": "string", + "desc": "Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket)." + }, + { + "textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.", + "name": "timeout", + "type": "number", + "desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

      \n

      url can be a string or a URL object. If url is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n

      If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.

      \n

      The optional callback parameter will be added as a one-time listener for\nthe 'response' event.

      \n

      http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.

      \n
      const postData = querystring.stringify({\n  'msg': 'Hello World!'\n});\n\nconst options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/x-www-form-urlencoded',\n    'Content-Length': Buffer.byteLength(postData)\n  }\n};\n\nconst req = http.request(options, (res) => {\n  console.log(`STATUS: ${res.statusCode}`);\n  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n  res.setEncoding('utf8');\n  res.on('data', (chunk) => {\n    console.log(`BODY: ${chunk}`);\n  });\n  res.on('end', () => {\n    console.log('No more data in response.');\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n
      \n

      In the example req.end() was called. With http.request() one\nmust always call req.end() to signify the end of the request -\neven if there is no data being written to the request body.

      \n

      If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object. As with all 'error' events, if no listeners\nare registered the error will be thrown.

      \n

      There are a few special headers that should be noted.

      \n
        \n
      • \n

        Sending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.

        \n
      • \n
      • \n

        Sending a 'Content-Length' header will disable the default chunked encoding.

        \n
      • \n
      • \n

        Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more\ninformation.

        \n
      • \n
      • \n

        Sending an Authorization header will override using the auth option\nto compute basic authentication.

        \n
      • \n
      \n

      Example using a URL as options:

      \n
      const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n  // ...\n});\n
      \n

      In a successful request, the following events will be emitted in the following\norder:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object\n('data' will not be emitted at all if the response body is empty, for\ninstance, in most redirects)
        • \n
        • 'end' on the res object
        • \n
        \n
      • \n
      • 'close'
      • \n
      \n

      In the case of a connection error, the following events will be emitted:

      \n
        \n
      • 'socket'
      • \n
      • 'error'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called before the connection succeeds, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called after the response is received, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object
        • \n
        \n
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'aborted' on the res object
      • \n
      • 'close'
      • \n
      • 'end' on the res object
      • \n
      • 'close' on the res object
      • \n
      \n

      Setting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.

      " + }, + { + "textRaw": "`http.request(url[, options][, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v12.15.0", + "pr-url": "https://github.com/nodejs/node/pull/31448", + "description": "The `insecureHTTPParser` option is supported now." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible values:", + "name": "agent", + "type": "http.Agent | boolean", + "desc": "Controls [`Agent`][] behavior. Possible values:", + "options": [ + { + "textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port.", + "name": "undefined", + "desc": "(default): use [`http.globalAgent`][] for this host and port." + }, + { + "textRaw": "`Agent` object: explicitly use the passed in `Agent`.", + "name": "Agent", + "desc": "object: explicitly use the passed in `Agent`." + }, + { + "textRaw": "`false`: causes a new `Agent` with default values to be used.", + "name": "false", + "desc": "causes a new `Agent` with default values to be used." + } + ] + }, + { + "textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header.", + "name": "auth", + "type": "string", + "desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header." + }, + { + "textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value.", + "name": "createConnection", + "type": "Function", + "desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value." + }, + { + "textRaw": "`defaultPort` {number} Default port for the protocol. **Default:** `agent.defaultPort` if an `Agent` is used, else `undefined`.", + "name": "defaultPort", + "type": "number", + "default": "`agent.defaultPort` if an `Agent` is used, else `undefined`", + "desc": "Default port for the protocol." + }, + { + "textRaw": "`family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.", + "name": "family", + "type": "number", + "desc": "IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used." + }, + { + "textRaw": "`headers` {Object} An object containing request headers.", + "name": "headers", + "type": "Object", + "desc": "An object containing request headers." + }, + { + "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "A domain name or IP address of the server to issue the request to." + }, + { + "textRaw": "`hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified.", + "name": "hostname", + "type": "string", + "desc": "Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified." + }, + { + "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", + "name": "insecureHTTPParser", + "type": "boolean", + "default": "`false`", + "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." + }, + { + "textRaw": "`localAddress` {string} Local interface to bind for network connections.", + "name": "localAddress", + "type": "string", + "desc": "Local interface to bind for network connections." + }, + { + "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", + "name": "lookup", + "type": "Function", + "default": "[`dns.lookup()`][]", + "desc": "Custom lookup function." + }, + { + "textRaw": "`method` {string} A string specifying the HTTP request method. **Default:** `'GET'`.", + "name": "method", + "type": "string", + "default": "`'GET'`", + "desc": "A string specifying the HTTP request method." + }, + { + "textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. **Default:** `'/'`.", + "name": "path", + "type": "string", + "default": "`'/'`", + "desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future." + }, + { + "textRaw": "`port` {number} Port of remote server. **Default:** `defaultPort` if set, else `80`.", + "name": "port", + "type": "number", + "default": "`defaultPort` if set, else `80`", + "desc": "Port of remote server." + }, + { + "textRaw": "`protocol` {string} Protocol to use. **Default:** `'http:'`.", + "name": "protocol", + "type": "string", + "default": "`'http:'`", + "desc": "Protocol to use." + }, + { + "textRaw": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. Defaults to `true`.", + "name": "setHost", + "type": "boolean", + "desc": ": Specifies whether or not to automatically add the `Host` header. Defaults to `true`." + }, + { + "textRaw": "`socketPath` {string} Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket).", + "name": "socketPath", + "type": "string", + "desc": "Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket)." + }, + { + "textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.", + "name": "timeout", + "type": "number", + "desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

      \n

      url can be a string or a URL object. If url is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n

      If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.

      \n

      The optional callback parameter will be added as a one-time listener for\nthe 'response' event.

      \n

      http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.

      \n
      const postData = querystring.stringify({\n  'msg': 'Hello World!'\n});\n\nconst options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/x-www-form-urlencoded',\n    'Content-Length': Buffer.byteLength(postData)\n  }\n};\n\nconst req = http.request(options, (res) => {\n  console.log(`STATUS: ${res.statusCode}`);\n  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n  res.setEncoding('utf8');\n  res.on('data', (chunk) => {\n    console.log(`BODY: ${chunk}`);\n  });\n  res.on('end', () => {\n    console.log('No more data in response.');\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n
      \n

      In the example req.end() was called. With http.request() one\nmust always call req.end() to signify the end of the request -\neven if there is no data being written to the request body.

      \n

      If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object. As with all 'error' events, if no listeners\nare registered the error will be thrown.

      \n

      There are a few special headers that should be noted.

      \n
        \n
      • \n

        Sending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.

        \n
      • \n
      • \n

        Sending a 'Content-Length' header will disable the default chunked encoding.

        \n
      • \n
      • \n

        Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more\ninformation.

        \n
      • \n
      • \n

        Sending an Authorization header will override using the auth option\nto compute basic authentication.

        \n
      • \n
      \n

      Example using a URL as options:

      \n
      const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n  // ...\n});\n
      \n

      In a successful request, the following events will be emitted in the following\norder:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object\n('data' will not be emitted at all if the response body is empty, for\ninstance, in most redirects)
        • \n
        • 'end' on the res object
        • \n
        \n
      • \n
      • 'close'
      • \n
      \n

      In the case of a connection error, the following events will be emitted:

      \n
        \n
      • 'socket'
      • \n
      • 'error'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called before the connection succeeds, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called after the response is received, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object
        • \n
        \n
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'aborted' on the res object
      • \n
      • 'close'
      • \n
      • 'end' on the res object
      • \n
      • 'close' on the res object
      • \n
      \n

      Setting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.

      " + } + ], + "type": "module", + "displayName": "HTTP" + }, + { + "textRaw": "HTTP/2", + "name": "http/2", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22466", + "description": "HTTP/2 is now Stable. Previously, it had been Experimental." + } + ] + }, + "introduced_in": "v8.4.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/http2.js

      \n

      The http2 module provides an implementation of the HTTP/2 protocol. It\ncan be accessed using:

      \n
      const http2 = require('http2');\n
      ", + "modules": [ + { + "textRaw": "Core API", + "name": "core_api", + "desc": "

      The Core API provides a low-level interface designed specifically around\nsupport for HTTP/2 protocol features. It is specifically not designed for\ncompatibility with the existing HTTP/1 module API. However,\nthe Compatibility API is.

      \n

      The http2 Core API is much more symmetric between client and server than the\nhttp API. For instance, most events, like 'error', 'connect' and\n'stream', can be emitted either by client-side code or server-side code.

      ", + "modules": [ + { + "textRaw": "Server-side example", + "name": "server-side_example", + "desc": "

      The following illustrates a simple HTTP/2 server using the Core API.\nSince there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createSecureServer({\n  key: fs.readFileSync('localhost-privkey.pem'),\n  cert: fs.readFileSync('localhost-cert.pem')\n});\nserver.on('error', (err) => console.error(err));\n\nserver.on('stream', (stream, headers) => {\n  // stream is a Duplex\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n
      \n

      To generate the certificate and key for this example, run:

      \n
      openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n  -keyout localhost-privkey.pem -out localhost-cert.pem\n
      ", + "type": "module", + "displayName": "Server-side example" + }, + { + "textRaw": "Client-side example", + "name": "client-side_example", + "desc": "

      The following illustrates an HTTP/2 client:

      \n
      const http2 = require('http2');\nconst fs = require('fs');\nconst client = http2.connect('https://localhost:8443', {\n  ca: fs.readFileSync('localhost-cert.pem')\n});\nclient.on('error', (err) => console.error(err));\n\nconst req = client.request({ ':path': '/' });\n\nreq.on('response', (headers, flags) => {\n  for (const name in headers) {\n    console.log(`${name}: ${headers[name]}`);\n  }\n});\n\nreq.setEncoding('utf8');\nlet data = '';\nreq.on('data', (chunk) => { data += chunk; });\nreq.on('end', () => {\n  console.log(`\\n${data}`);\n  client.close();\n});\nreq.end();\n
      ", + "type": "module", + "displayName": "Client-side example" + }, + { + "textRaw": "Headers object", + "name": "headers_object", + "desc": "

      Headers are represented as own-properties on JavaScript objects. The property\nkeys will be serialized to lower-case. Property values should be strings (if\nthey are not they will be coerced to strings) or an Array of strings (in order\nto send more than one value per header field).

      \n
      const headers = {\n  ':status': '200',\n  'content-type': 'text-plain',\n  'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n
      \n

      Header objects passed to callback functions will have a null prototype. This\nmeans that normal JavaScript object methods such as\nObject.prototype.toString() and Object.prototype.hasOwnProperty() will\nnot work.

      \n

      For incoming headers:

      \n
        \n
      • The :status header is converted to number.
      • \n
      • Duplicates of :status, :method, :authority, :scheme, :path,\n:protocol, age, authorization, access-control-allow-credentials,\naccess-control-max-age, access-control-request-method, content-encoding,\ncontent-language, content-length, content-location, content-md5,\ncontent-range, content-type, date, dnt, etag, expires, from,\nif-match, if-modified-since, if-none-match, if-range,\nif-unmodified-since, last-modified, location, max-forwards,\nproxy-authorization, range, referer,retry-after, tk,\nupgrade-insecure-requests, user-agent or x-content-type-options are\ndiscarded.
      • \n
      • set-cookie is always an array. Duplicates are added to the array.
      • \n
      • For duplicate cookie headers, the values are joined together with '; '.
      • \n
      • For all other headers, the values are joined together with ', '.
      • \n
      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream, headers) => {\n  console.log(headers[':path']);\n  console.log(headers.ABC);\n});\n
      ", + "type": "module", + "displayName": "Headers object" + }, + { + "textRaw": "Settings object", + "name": "settings_object", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29833", + "description": "The `maxConcurrentStreams` setting is stricter." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "The `maxHeaderListSize` setting is now strictly enforced." + } + ] + }, + "desc": "

      The http2.getDefaultSettings(), http2.getPackedSettings(),\nhttp2.createServer(), http2.createSecureServer(),\nhttp2session.settings(), http2session.localSettings, and\nhttp2session.remoteSettings APIs either return or receive as input an\nobject that defines configuration settings for an Http2Session object.\nThese objects are ordinary JavaScript objects containing the following\nproperties.

      \n
        \n
      • headerTableSize <number> Specifies the maximum number of bytes used for\nheader compression. The minimum allowed value is 0. The maximum allowed value\nis 232-1. Default: 4096.
      • \n
      • enablePush <boolean> Specifies true if HTTP/2 Push Streams are to be\npermitted on the Http2Session instances. Default: true.
      • \n
      • initialWindowSize <number> Specifies the sender's initial window size in\nbytes for stream-level flow control. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.
      • \n
      • maxFrameSize <number> Specifies the size in bytes of the largest frame\npayload. The minimum allowed value is 16,384. The maximum allowed value is\n224-1. Default: 16384.
      • \n
      • maxConcurrentStreams <number> Specifies the maximum number of concurrent\nstreams permitted on an Http2Session. There is no default value which\nimplies, at least theoretically, 232-1 streams may be open\nconcurrently at any given time in an Http2Session. The minimum value\nis 0. The maximum allowed value is 232-1. Default:\n4294967295.
      • \n
      • maxHeaderListSize <number> Specifies the maximum size (uncompressed octets)\nof header list that will be accepted. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.
      • \n
      • maxHeaderSize <number> Alias for maxHeaderListSize.
      • \n
      • enableConnectProtocol<boolean> Specifies true if the \"Extended Connect\nProtocol\" defined by RFC 8441 is to be enabled. This setting is only\nmeaningful if sent by the server. Once the enableConnectProtocol setting\nhas been enabled for a given Http2Session, it cannot be disabled.\nDefault: false.
      • \n
      \n

      All additional properties on the settings object are ignored.

      ", + "type": "module", + "displayName": "Settings object" + }, + { + "textRaw": "Using `options.selectPadding()`", + "name": "using_`options.selectpadding()`", + "desc": "

      When options.paddingStrategy is equal to\nhttp2.constants.PADDING_STRATEGY_CALLBACK, the HTTP/2 implementation will\nconsult the options.selectPadding() callback function, if provided, to\ndetermine the specific amount of padding to use per HEADERS and DATA frame.

      \n

      The options.selectPadding() function receives two numeric arguments,\nframeLen and maxFrameLen and must return a number N such that\nframeLen <= N <= maxFrameLen.

      \n
      const http2 = require('http2');\nconst server = http2.createServer({\n  paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK,\n  selectPadding(frameLen, maxFrameLen) {\n    return maxFrameLen;\n  }\n});\n
      \n

      The options.selectPadding() function is invoked once for every HEADERS and\nDATA frame. This has a definite noticeable impact on performance.

      ", + "type": "module", + "displayName": "Using `options.selectPadding()`" + }, + { + "textRaw": "Error handling", + "name": "error_handling", + "desc": "

      There are several types of error conditions that may arise when using the\nhttp2 module:

      \n

      Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.

      \n

      State errors occur when an action is attempted at an incorrect time (for\ninstance, attempting to send data on a stream after it has closed). These will\nbe reported using either a synchronous throw or via an 'error' event on\nthe Http2Stream, Http2Session or HTTP/2 Server objects, depending on where\nand when the error occurs.

      \n

      Internal errors occur when an HTTP/2 session fails unexpectedly. These will be\nreported via an 'error' event on the Http2Session or HTTP/2 Server objects.

      \n

      Protocol errors occur when various HTTP/2 protocol constraints are violated.\nThese will be reported using either a synchronous throw or via an 'error'\nevent on the Http2Stream, Http2Session or HTTP/2 Server objects, depending\non where and when the error occurs.

      ", + "type": "module", + "displayName": "Error handling" + }, + { + "textRaw": "Invalid character handling in header names and values", + "name": "invalid_character_handling_in_header_names_and_values", + "desc": "

      The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.

      \n

      Header field names are case-insensitive and are transmitted over the wire\nstrictly as lower-case strings. The API provided by Node.js allows header\nnames to be set as mixed-case strings (e.g. Content-Type) but will convert\nthose to lower-case (e.g. content-type) upon transmission.

      \n

      Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.

      \n

      Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.

      \n

      Header field values are handled with more leniency but should not contain\nnew-line or carriage return characters and should be limited to US-ASCII\ncharacters, per the requirements of the HTTP specification.

      ", + "type": "module", + "displayName": "Invalid character handling in header names and values" + }, + { + "textRaw": "Push streams on the client", + "name": "push_streams_on_the_client", + "desc": "

      To receive pushed streams on the client, set a listener for the 'stream'\nevent on the ClientHttp2Session:

      \n
      const http2 = require('http2');\n\nconst client = http2.connect('http://localhost');\n\nclient.on('stream', (pushedStream, requestHeaders) => {\n  pushedStream.on('push', (responseHeaders) => {\n    // Process response headers\n  });\n  pushedStream.on('data', (chunk) => { /* handle pushed data */ });\n});\n\nconst req = client.request({ ':path': '/' });\n
      ", + "type": "module", + "displayName": "Push streams on the client" + }, + { + "textRaw": "Supporting the `CONNECT` method", + "name": "supporting_the_`connect`_method", + "desc": "

      The CONNECT method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.

      \n

      A simple TCP Server:

      \n
      const net = require('net');\n\nconst server = net.createServer((socket) => {\n  let name = '';\n  socket.setEncoding('utf8');\n  socket.on('data', (chunk) => name += chunk);\n  socket.on('end', () => socket.end(`hello ${name}`));\n});\n\nserver.listen(8000);\n
      \n

      An HTTP/2 CONNECT proxy:

      \n
      const http2 = require('http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('net');\n\nconst proxy = http2.createServer();\nproxy.on('stream', (stream, headers) => {\n  if (headers[':method'] !== 'CONNECT') {\n    // Only accept CONNECT requests\n    stream.close(NGHTTP2_REFUSED_STREAM);\n    return;\n  }\n  const auth = new URL(`tcp://${headers[':authority']}`);\n  // It's a very good idea to verify that hostname and port are\n  // things this proxy should be connecting to.\n  const socket = net.connect(auth.port, auth.hostname, () => {\n    stream.respond();\n    socket.pipe(stream);\n    stream.pipe(socket);\n  });\n  socket.on('error', (error) => {\n    stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);\n  });\n});\n\nproxy.listen(8001);\n
      \n

      An HTTP/2 CONNECT client:

      \n
      const http2 = require('http2');\n\nconst client = http2.connect('http://localhost:8001');\n\n// Must not specify the ':path' and ':scheme' headers\n// for CONNECT requests or an error will be thrown.\nconst req = client.request({\n  ':method': 'CONNECT',\n  ':authority': `localhost:${port}`\n});\n\nreq.on('response', (headers) => {\n  console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);\n});\nlet data = '';\nreq.setEncoding('utf8');\nreq.on('data', (chunk) => data += chunk);\nreq.on('end', () => {\n  console.log(`The server says: ${data}`);\n  client.close();\n});\nreq.end('Jane');\n
      ", + "type": "module", + "displayName": "Supporting the `CONNECT` method" + }, + { + "textRaw": "The extended `CONNECT` protocol", + "name": "the_extended_`connect`_protocol", + "desc": "

      RFC 8441 defines an \"Extended CONNECT Protocol\" extension to HTTP/2 that\nmay be used to bootstrap the use of an Http2Stream using the CONNECT\nmethod as a tunnel for other communication protocols (such as WebSockets).

      \n

      The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:

      \n
      const http2 = require('http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n
      \n

      Once the client receives the SETTINGS frame from the server indicating that\nthe extended CONNECT may be used, it may send CONNECT requests that use the\n':protocol' HTTP/2 pseudo-header:

      \n
      const http2 = require('http2');\nconst client = http2.connect('http://localhost:8080');\nclient.on('remoteSettings', (settings) => {\n  if (settings.enableConnectProtocol) {\n    const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });\n    // ...\n  }\n});\n
      ", + "type": "module", + "displayName": "The extended `CONNECT` protocol" + } + ], + "classes": [ + { + "textRaw": "Class: `Http2Session`", + "type": "class", + "name": "Http2Session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of the http2.Http2Session class represent an active communications\nsession between an HTTP/2 client and server. Instances of this class are not\nintended to be constructed directly by user code.

      \n

      Each Http2Session instance will exhibit slightly different behaviors\ndepending on whether it is operating as a server or a client. The\nhttp2session.type property can be used to determine the mode in which an\nHttp2Session is operating. On the server side, user code should rarely\nhave occasion to work with the Http2Session object directly, with most\nactions typically taken through interactions with either the Http2Server or\nHttp2Stream objects.

      \n

      User code will not create Http2Session instances directly. Server-side\nHttp2Session instances are created by the Http2Server instance when a\nnew HTTP/2 connection is received. Client-side Http2Session instances are\ncreated using the http2.connect() method.

      ", + "modules": [ + { + "textRaw": "`Http2Session` and sockets", + "name": "`http2session`_and_sockets", + "desc": "

      Every Http2Session instance is associated with exactly one net.Socket or\ntls.TLSSocket when it is created. When either the Socket or the\nHttp2Session are destroyed, both will be destroyed.

      \n

      Because of the specific serialization and processing requirements imposed\nby the HTTP/2 protocol, it is not recommended for user code to read data from\nor write data to a Socket instance bound to a Http2Session. Doing so can\nput the HTTP/2 session into an indeterminate state causing the session and\nthe socket to become unusable.

      \n

      Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.

      ", + "type": "module", + "displayName": "`Http2Session` and sockets" + } + ], + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`session` {Http2Session}", + "name": "session", + "type": "Http2Session" + }, + { + "textRaw": "`socket` {net.Socket}", + "name": "socket", + "type": "net.Socket" + } + ], + "desc": "

      The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.

      \n

      User code will typically not listen for this event directly.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted when an error occurs during the processing of\nan Http2Session.

      " + }, + { + "textRaw": "Event: `'frameError'`", + "type": "event", + "name": "frameError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`type` {integer} The frame type.", + "name": "type", + "type": "integer", + "desc": "The frame type." + }, + { + "textRaw": "`code` {integer} The error code.", + "name": "code", + "type": "integer", + "desc": "The error code." + }, + { + "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", + "name": "id", + "type": "integer", + "desc": "The stream id (or `0` if the frame isn't associated with a stream)." + } + ], + "desc": "

      The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame on the session. If the frame that could not be sent is associated\nwith a specific Http2Stream, an attempt to emit a 'frameError' event on the\nHttp2Stream is made.

      \n

      If the 'frameError' event is associated with a stream, the stream will be\nclosed and destroyed immediately following the 'frameError' event. If the\nevent is not associated with a stream, the Http2Session will be shut down\nimmediately following the 'frameError' event.

      " + }, + { + "textRaw": "Event: `'goaway'`", + "type": "event", + "name": "goaway", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame.", + "name": "errorCode", + "type": "number", + "desc": "The HTTP/2 error code specified in the `GOAWAY` frame." + }, + { + "textRaw": "`lastStreamID` {number} The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified).", + "name": "lastStreamID", + "type": "number", + "desc": "The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified)." + }, + { + "textRaw": "`opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data.", + "name": "opaqueData", + "type": "Buffer", + "desc": "If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data." + } + ], + "desc": "

      The 'goaway' event is emitted when a GOAWAY frame is received.

      \n

      The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.

      " + }, + { + "textRaw": "Event: `'localSettings'`", + "type": "event", + "name": "localSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "A copy of the `SETTINGS` frame received." + } + ], + "desc": "

      The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.

      \n

      When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.

      \n
      session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n  /* Use the new settings */\n});\n
      " + }, + { + "textRaw": "Event: `'ping'`", + "type": "event", + "name": "ping", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`payload` {Buffer} The `PING` frame 8-byte payload", + "name": "payload", + "type": "Buffer", + "desc": "The `PING` frame 8-byte payload" + } + ], + "desc": "

      The 'ping' event is emitted whenever a PING frame is received from the\nconnected peer.

      " + }, + { + "textRaw": "Event: `'remoteSettings'`", + "type": "event", + "name": "remoteSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "A copy of the `SETTINGS` frame received." + } + ], + "desc": "

      The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.

      \n
      session.on('remoteSettings', (settings) => {\n  /* Use the new settings */\n});\n
      " + }, + { + "textRaw": "Event: `'stream'`", + "type": "event", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`stream` {Http2Stream} A reference to the stream", + "name": "stream", + "type": "Http2Stream", + "desc": "A reference to the stream" + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "An object describing the headers" + }, + { + "textRaw": "`flags` {number} The associated numeric flags", + "name": "flags", + "type": "number", + "desc": "The associated numeric flags" + }, + { + "textRaw": "`rawHeaders` {Array} An array containing the raw header names followed by their respective values.", + "name": "rawHeaders", + "type": "Array", + "desc": "An array containing the raw header names followed by their respective values." + } + ], + "desc": "

      The 'stream' event is emitted when a new Http2Stream is created.

      \n
      const http2 = require('http2');\nsession.on('stream', (stream, headers, flags) => {\n  const method = headers[':method'];\n  const path = headers[':path'];\n  // ...\n  stream.respond({\n    ':status': 200,\n    'content-type': 'text/plain; charset=utf-8'\n  });\n  stream.write('hello ');\n  stream.end('world');\n});\n
      \n

      On the server side, user code will typically not listen for this event directly,\nand would instead register a handler for the 'stream' event emitted by the\nnet.Server or tls.Server instances returned by http2.createServer() and\nhttp2.createSecureServer(), respectively, as in the example below:

      \n
      const http2 = require('http2');\n\n// Create an unencrypted HTTP/2 server\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.on('error', (error) => console.error(error));\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
      \n

      Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,\na network error will destroy each individual stream and must be handled on the\nstream level, as shown above.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      After the http2session.setTimeout() method is used to set the timeout period\nfor this Http2Session, the 'timeout' event is emitted if there is no\nactivity on the Http2Session after the configured number of milliseconds.\nIts listener does not expect any arguments.

      \n
      session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n
      " + } + ], + "properties": [ + { + "textRaw": "`alpnProtocol` {string|undefined}", + "type": "string|undefined", + "name": "alpnProtocol", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Value will be undefined if the Http2Session is not yet connected to a\nsocket, h2c if the Http2Session is not connected to a TLSSocket, or\nwill return the value of the connected TLSSocket's own alpnProtocol\nproperty.

      " + }, + { + "textRaw": "`closed` {boolean}", + "type": "boolean", + "name": "closed", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Will be true if this Http2Session instance has been closed, otherwise\nfalse.

      " + }, + { + "textRaw": "`connecting` {boolean}", + "type": "boolean", + "name": "connecting", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Will be true if this Http2Session instance is still connecting, will be set\nto false before emitting connect event and/or calling the http2.connect\ncallback.

      " + }, + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.

      " + }, + { + "textRaw": "`encrypted` {boolean|undefined}", + "type": "boolean|undefined", + "name": "encrypted", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Value is undefined if the Http2Session session socket has not yet been\nconnected, true if the Http2Session is connected with a TLSSocket,\nand false if the Http2Session is connected to any other kind of socket\nor stream.

      " + }, + { + "textRaw": "`localSettings` {HTTP/2 Settings Object}", + "type": "HTTP/2 Settings Object", + "name": "localSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.

      " + }, + { + "textRaw": "`originSet` {string[]|undefined}", + "type": "string[]|undefined", + "name": "originSet", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      If the Http2Session is connected to a TLSSocket, the originSet property\nwill return an Array of origins for which the Http2Session may be\nconsidered authoritative.

      \n

      The originSet property is only available when using a secure TLS connection.

      " + }, + { + "textRaw": "`pendingSettingsAck` {boolean}", + "type": "boolean", + "name": "pendingSettingsAck", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Indicates whether the Http2Session is currently waiting for acknowledgment of\na sent SETTINGS frame. Will be true after calling the\nhttp2session.settings() method. Will be false once all sent SETTINGS\nframes have been acknowledged.

      " + }, + { + "textRaw": "`remoteSettings` {HTTP/2 Settings Object}", + "type": "HTTP/2 Settings Object", + "name": "remoteSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.

      " + }, + { + "textRaw": "`socket` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "socket", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\nlimits available methods to ones safe to use with HTTP/2.

      \n

      destroy, emit, end, pause, read, resume, and write will throw\nan error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See\nHttp2Session and Sockets for more information.

      \n

      setTimeout method will be called on this Http2Session.

      \n

      All other interactions will be routed directly to the socket.

      " + }, + { + "textRaw": "`http2session.state`", + "name": "state", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Provides miscellaneous information about the current state of the\nHttp2Session.

      \n
        \n
      • <Object>\n
          \n
        • effectiveLocalWindowSize <number> The current local (receive)\nflow control window size for the Http2Session.
        • \n
        • effectiveRecvDataLength <number> The current number of bytes\nthat have been received since the last flow control WINDOW_UPDATE.
        • \n
        • nextStreamID <number> The numeric identifier to be used the\nnext time a new Http2Stream is created by this Http2Session.
        • \n
        • localWindowSize <number> The number of bytes that the remote peer can\nsend without receiving a WINDOW_UPDATE.
        • \n
        • lastProcStreamID <number> The numeric id of the Http2Stream\nfor which a HEADERS or DATA frame was most recently received.
        • \n
        • remoteWindowSize <number> The number of bytes that this Http2Session\nmay send without receiving a WINDOW_UPDATE.
        • \n
        • outboundQueueSize <number> The number of frames currently within the\noutbound queue for this Http2Session.
        • \n
        • deflateDynamicTableSize <number> The current size in bytes of the\noutbound header compression state table.
        • \n
        • inflateDynamicTableSize <number> The current size in bytes of the\ninbound header compression state table.
        • \n
        \n
      • \n
      \n

      An object describing the current status of this Http2Session.

      " + }, + { + "textRaw": "`type` {number}", + "type": "number", + "name": "type", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The http2session.type will be equal to\nhttp2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a\nserver, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a\nclient.

      " + } + ], + "methods": [ + { + "textRaw": "`http2session.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Gracefully closes the Http2Session, allowing any existing streams to\ncomplete on their own and preventing new Http2Stream instances from being\ncreated. Once closed, http2session.destroy() might be called if there\nare no open Http2Stream instances.

      \n

      If specified, the callback function is registered as a handler for the\n'close' event.

      " + }, + { + "textRaw": "`http2session.destroy([error][, code])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`error` {Error} An `Error` object if the `Http2Session` is being destroyed due to an error.", + "name": "error", + "type": "Error", + "desc": "An `Error` object if the `Http2Session` is being destroyed due to an error." + }, + { + "textRaw": "`code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`.", + "name": "code", + "type": "number", + "desc": "The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`." + } + ] + } + ], + "desc": "

      Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.

      \n

      Once destroyed, the Http2Session will emit the 'close' event. If error\nis not undefined, an 'error' event will be emitted immediately before the\n'close' event.

      \n

      If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.

      " + }, + { + "textRaw": "`http2session.goaway([code[, lastStreamID[, opaqueData]]])`", + "type": "method", + "name": "goaway", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {number} An HTTP/2 error code", + "name": "code", + "type": "number", + "desc": "An HTTP/2 error code" + }, + { + "textRaw": "`lastStreamID` {number} The numeric ID of the last processed `Http2Stream`", + "name": "lastStreamID", + "type": "number", + "desc": "The numeric ID of the last processed `Http2Stream`" + }, + { + "textRaw": "`opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", + "name": "opaqueData", + "type": "Buffer|TypedArray|DataView", + "desc": "A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame." + } + ] + } + ], + "desc": "

      Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.

      " + }, + { + "textRaw": "`http2session.ping([payload, ]callback)`", + "type": "method", + "name": "ping", + "meta": { + "added": [ + "v8.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`payload` {Buffer|TypedArray|DataView} Optional ping payload.", + "name": "payload", + "type": "Buffer|TypedArray|DataView", + "desc": "Optional ping payload." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sends a PING frame to the connected HTTP/2 peer. A callback function must\nbe provided. The method will return true if the PING was sent, false\notherwise.

      \n

      The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.

      \n

      If provided, the payload must be a Buffer, TypedArray, or DataView\ncontaining 8 bytes of data that will be transmitted with the PING and\nreturned with the ping acknowledgment.

      \n

      The callback will be invoked with three arguments: an error argument that will\nbe null if the PING was successfully acknowledged, a duration argument\nthat reports the number of milliseconds elapsed since the ping was sent and the\nacknowledgment was received, and a Buffer containing the 8-byte PING\npayload.

      \n
      session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {\n  if (!err) {\n    console.log(`Ping acknowledged in ${duration} milliseconds`);\n    console.log(`With payload '${payload.toString()}'`);\n  }\n});\n
      \n

      If the payload argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING duration.

      " + }, + { + "textRaw": "`http2session.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calls ref() on this Http2Session\ninstance's underlying net.Socket.

      " + }, + { + "textRaw": "`http2session.setTimeout(msecs, callback)`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Used to set a callback function that is called when there is no activity on\nthe Http2Session after msecs milliseconds. The given callback is\nregistered as a listener on the 'timeout' event.

      " + }, + { + "textRaw": "`http2session.settings([settings][, callback])`", + "type": "method", + "name": "settings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object}", + "name": "settings", + "type": "HTTP/2 Settings Object" + }, + { + "textRaw": "`callback` {Function} Callback that is called once the session is connected or right away if the session is already connected.", + "name": "callback", + "type": "Function", + "desc": "Callback that is called once the session is connected or right away if the session is already connected.", + "options": [ + { + "textRaw": "`err` {Error|null}", + "name": "err", + "type": "Error|null" + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The updated `settings` object.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The updated `settings` object." + }, + { + "textRaw": "`duration` {integer}", + "name": "duration", + "type": "integer" + } + ] + } + ] + } + ], + "desc": "

      Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.

      \n

      Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.

      \n

      The new settings will not become effective until the SETTINGS acknowledgment\nis received and the 'localSettings' event is emitted. It is possible to send\nmultiple SETTINGS frames while acknowledgment is still pending.

      " + }, + { + "textRaw": "`http2session.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calls unref() on this Http2Session\ninstance's underlying net.Socket.

      " + } + ] + }, + { + "textRaw": "Class: `ServerHttp2Session`", + "type": "class", + "name": "ServerHttp2Session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "", + "methods": [ + { + "textRaw": "`serverhttp2session.altsvc(alt, originOrStream)`", + "type": "method", + "name": "altsvc", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`alt` {string} A description of the alternative service configuration as defined by [RFC 7838][].", + "name": "alt", + "type": "string", + "desc": "A description of the alternative service configuration as defined by [RFC 7838][]." + }, + { + "textRaw": "`originOrStream` {number|string|URL|Object} Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property.", + "name": "originOrStream", + "type": "number|string|URL|Object", + "desc": "Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property." + } + ] + } + ], + "desc": "

      Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

      \n
      const http2 = require('http2');\n\nconst server = http2.createServer();\nserver.on('session', (session) => {\n  // Set altsvc for origin https://example.org:80\n  session.altsvc('h2=\":8000\"', 'https://example.org:80');\n});\n\nserver.on('stream', (stream) => {\n  // Set altsvc for a specific stream\n  stream.session.altsvc('h2=\":8000\"', stream.id);\n});\n
      \n

      Sending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.

      \n

      The alt and origin string must contain only ASCII bytes and are\nstrictly interpreted as a sequence of ASCII bytes. The special value 'clear'\nmay be passed to clear any previously set alternative service for a given\ndomain.

      \n

      When a string is passed for the originOrStream argument, it will be parsed as\na URL and the origin will be derived. For instance, the origin for the\nHTTP URL 'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.

      \n

      A URL object, or any object with an origin property, may be passed as\noriginOrStream, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.

      " + }, + { + "textRaw": "`serverhttp2session.origin(...origins)`", + "type": "method", + "name": "origin", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`origins` { string | URL | Object } One or more URL Strings passed as separate arguments.", + "name": "origins", + "type": " string | URL | Object ", + "desc": "One or more URL Strings passed as separate arguments." + } + ] + } + ], + "desc": "

      Submits an ORIGIN frame (as defined by RFC 8336) to the connected client\nto advertise the set of origins for which the server is capable of providing\nauthoritative responses.

      \n
      const http2 = require('http2');\nconst options = getSecureOptionsSomehow();\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\nserver.on('session', (session) => {\n  session.origin('https://example.com', 'https://example.org');\n});\n
      \n

      When a string is passed as an origin, it will be parsed as a URL and the\norigin will be derived. For instance, the origin for the HTTP URL\n'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.

      \n

      A URL object, or any object with an origin property, may be passed as\nan origin, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.

      \n

      Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:

      \n
      const http2 = require('http2');\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\n
      " + } + ], + "modules": [ + { + "textRaw": "Specifying alternative services", + "name": "specifying_alternative_services", + "desc": "

      The format of the alt parameter is strictly defined by RFC 7838 as an\nASCII string containing a comma-delimited list of \"alternative\" protocols\nassociated with a specific host and port.

      \n

      For example, the value 'h2=\"example.org:81\"' indicates that the HTTP/2\nprotocol is available on the host 'example.org' on TCP/IP port 81. The\nhost and port must be contained within the quote (\") characters.

      \n

      Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.

      \n

      The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.

      \n

      The syntax of these values is not validated by the Node.js implementation and\nare passed through as provided by the user or received from the peer.

      ", + "type": "module", + "displayName": "Specifying alternative services" + } + ] + }, + { + "textRaw": "Class: `ClientHttp2Session`", + "type": "class", + "name": "ClientHttp2Session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "", + "events": [ + { + "textRaw": "Event: `'altsvc'`", + "type": "event", + "name": "altsvc", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`alt` {string}", + "name": "alt", + "type": "string" + }, + { + "textRaw": "`origin` {string}", + "name": "origin", + "type": "string" + }, + { + "textRaw": "`streamId` {number}", + "name": "streamId", + "type": "number" + } + ], + "desc": "

      The 'altsvc' event is emitted whenever an ALTSVC frame is received by\nthe client. The event is emitted with the ALTSVC value, origin, and stream\nID. If no origin is provided in the ALTSVC frame, origin will\nbe an empty string.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('altsvc', (alt, origin, streamId) => {\n  console.log(alt);\n  console.log(origin);\n  console.log(streamId);\n});\n
      " + }, + { + "textRaw": "Event: `'origin'`", + "type": "event", + "name": "origin", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`origins` {string[]}", + "name": "origins", + "type": "string[]" + } + ], + "desc": "

      The 'origin' event is emitted whenever an ORIGIN frame is received by\nthe client. The event is emitted with an array of origin strings. The\nhttp2session.originSet will be updated to include the received\norigins.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('origin', (origins) => {\n  for (let n = 0; n < origins.length; n++)\n    console.log(origins[n]);\n});\n
      \n

      The 'origin' event is only emitted when using a secure TLS connection.

      " + } + ], + "methods": [ + { + "textRaw": "`clienthttp2session.request(headers[, options])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ClientHttp2Stream}", + "name": "return", + "type": "ClientHttp2Stream" + }, + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`endStream` {boolean} `true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body.", + "name": "endStream", + "type": "boolean", + "desc": "`true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body." + }, + { + "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`.", + "name": "exclusive", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream." + }, + { + "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", + "name": "parent", + "type": "number", + "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." + }, + { + "textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive).", + "name": "weight", + "type": "number", + "desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)." + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + } + ] + } + ] + } + ], + "desc": "

      For HTTP/2 Client Http2Session instances only, the http2session.request()\ncreates and returns an Http2Stream instance that can be used to send an\nHTTP/2 request to the connected server.

      \n

      This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.

      \n
      const http2 = require('http2');\nconst clientSession = http2.connect('https://localhost:1234');\nconst {\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS\n} = http2.constants;\n\nconst req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });\nreq.on('response', (headers) => {\n  console.log(headers[HTTP2_HEADER_STATUS]);\n  req.on('data', (chunk) => { /* .. */ });\n  req.on('end', () => { /* .. */ });\n});\n
      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nis emitted immediately after queuing the last chunk of payload data to be sent.\nThe http2stream.sendTrailers() method can then be called to send trailing\nheaders to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n

      The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:

      \n
        \n
      • :method = 'GET'
      • \n
      • :path = /
      • \n
      " + } + ] + }, + { + "textRaw": "Class: `Http2Stream`", + "type": "class", + "name": "Http2Stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Each instance of the Http2Stream class represents a bidirectional HTTP/2\ncommunications stream over an Http2Session instance. Any single Http2Session\nmay have up to 231-1 Http2Stream instances over its lifetime.

      \n

      User code will not construct Http2Stream instances directly. Rather, these\nare created, managed, and provided to user code through the Http2Session\ninstance. On the server, Http2Stream instances are created either in response\nto an incoming HTTP request (and handed off to user code via the 'stream'\nevent), or in response to a call to the http2stream.pushStream() method.\nOn the client, Http2Stream instances are created and returned when either the\nhttp2session.request() method is called, or in response to an incoming\n'push' event.

      \n

      The Http2Stream class is a base for the ServerHttp2Stream and\nClientHttp2Stream classes, each of which is used specifically by either\nthe Server or Client side, respectively.

      \n

      All Http2Stream instances are Duplex streams. The Writable side of the\nDuplex is used to send data to the connected peer, while the Readable side\nis used to receive data sent by the connected peer.

      \n

      The default text character encoding for all Http2Streams is UTF-8. As a best\npractice, it is recommended that when using an Http2Stream to send text,\nthe 'content-type' header should be set and should identify the character\nencoding used.

      \n
      stream.respond({\n  'content-type': 'text/html; charset=utf-8',\n  ':status': 200\n});\n
      ", + "modules": [ + { + "textRaw": "`Http2Stream` Lifecycle", + "name": "`http2stream`_lifecycle", + "modules": [ + { + "textRaw": "Creation", + "name": "creation", + "desc": "

      On the server side, instances of ServerHttp2Stream are created either\nwhen:

      \n
        \n
      • A new HTTP/2 HEADERS frame with a previously unused stream ID is received;
      • \n
      • The http2stream.pushStream() method is called.
      • \n
      \n

      On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.

      \n

      On the client, the Http2Stream instance returned by http2session.request()\nmay not be immediately ready for use if the parent Http2Session has not yet\nbeen fully established. In such cases, operations called on the Http2Stream\nwill be buffered until the 'ready' event is emitted. User code should rarely,\nif ever, need to handle the 'ready' event directly. The ready status of an\nHttp2Stream can be determined by checking the value of http2stream.id. If\nthe value is undefined, the stream is not yet ready for use.

      ", + "type": "module", + "displayName": "Creation" + }, + { + "textRaw": "Destruction", + "name": "destruction", + "desc": "

      All Http2Stream instances are destroyed either when:

      \n
        \n
      • An RST_STREAM frame for the stream is received by the connected peer,\nand (for client streams only) pending data has been read.
      • \n
      • The http2stream.close() method is called, and (for client streams only)\npending data has been read.
      • \n
      • The http2stream.destroy() or http2session.destroy() methods are called.
      • \n
      \n

      When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame to the connected peer.

      \n

      When the Http2Stream instance is destroyed, the 'close' event will\nbe emitted. Because Http2Stream is an instance of stream.Duplex, the\n'end' event will also be emitted if the stream data is currently flowing.\nThe 'error' event may also be emitted if http2stream.destroy() was called\nwith an Error passed as the first argument.

      \n

      After the Http2Stream has been destroyed, the http2stream.destroyed\nproperty will be true and the http2stream.rstCode property will specify the\nRST_STREAM error code. The Http2Stream instance is no longer usable once\ndestroyed.

      ", + "type": "module", + "displayName": "Destruction" + } + ], + "type": "module", + "displayName": "`Http2Stream` Lifecycle" + } + ], + "events": [ + { + "textRaw": "Event: `'aborted'`", + "type": "event", + "name": "aborted", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.\nIts listener does not expect any arguments.

      \n

      The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.

      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.

      \n

      The HTTP/2 error code used when closing the stream can be retrieved using\nthe http2stream.rstCode property. If the code is any value other than\nNGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted when an error occurs during the processing of\nan Http2Stream.

      " + }, + { + "textRaw": "Event: `'frameError'`", + "type": "event", + "name": "frameError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`type` {integer} The frame type.", + "name": "type", + "type": "integer", + "desc": "The frame type." + }, + { + "textRaw": "`code` {integer} The error code.", + "name": "code", + "type": "integer", + "desc": "The error code." + }, + { + "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", + "name": "id", + "type": "integer", + "desc": "The stream id (or `0` if the frame isn't associated with a stream)." + } + ], + "desc": "

      The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame. When invoked, the handler function will receive an integer\nargument identifying the frame type, and an integer argument identifying the\nerror code. The Http2Stream instance will be destroyed immediately after the\n'frameError' event is emitted.

      " + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'ready' event is emitted when the Http2Stream has been opened, has\nbeen assigned an id, and can be used. The listener does not expect any\narguments.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'timeout' event is emitted after no activity is received for this\nHttp2Stream within the number of milliseconds set using\nhttp2stream.setTimeout().\nIts listener does not expect any arguments.

      " + }, + { + "textRaw": "Event: `'trailers'`", + "type": "event", + "name": "trailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "An object describing the headers" + }, + { + "textRaw": "`flags` {number} The associated numeric flags", + "name": "flags", + "type": "number", + "desc": "The associated numeric flags" + } + ], + "desc": "

      The 'trailers' event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the\nHTTP/2 Headers Object and flags associated with the headers.

      \n

      This event might not be emitted if http2stream.end() is called\nbefore trailers are received and the incoming data is not being read or\nlistened for.

      \n
      stream.on('trailers', (headers, flags) => {\n  console.log(headers);\n});\n
      " + }, + { + "textRaw": "Event: `'wantTrailers'`", + "type": "event", + "name": "wantTrailers", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'wantTrailers' event is emitted when the Http2Stream has queued the\nfinal DATA frame to be sent on a frame and the Http2Stream is ready to send\ntrailing headers. When initiating a request or response, the waitForTrailers\noption must be set for this event to be emitted.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance was aborted abnormally. When set,\nthe 'aborted' event will have been emitted.

      " + }, + { + "textRaw": "`bufferSize` {number}", + "type": "number", + "name": "bufferSize", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This property shows the number of characters currently buffered to be written.\nSee net.Socket.bufferSize for details.

      " + }, + { + "textRaw": "`closed` {boolean}", + "type": "boolean", + "name": "closed", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance has been closed.

      " + }, + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.

      " + }, + { + "textRaw": "`endAfterHeaders` {boolean}", + "type": "boolean", + "name": "endAfterHeaders", + "meta": { + "added": [ + "v10.11.0" + ], + "changes": [] + }, + "desc": "

      Set the true if the END_STREAM flag was set in the request or response\nHEADERS frame received, indicating that no additional data should be received\nand the readable side of the Http2Stream will be closed.

      " + }, + { + "textRaw": "`id` {number|undefined}", + "type": "number|undefined", + "name": "id", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The numeric stream identifier of this Http2Stream instance. Set to undefined\nif the stream identifier has not yet been assigned.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.

      " + }, + { + "textRaw": "`rstCode` {number}", + "type": "number", + "name": "rstCode", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Set to the RST_STREAM error code reported when the Http2Stream is\ndestroyed after either receiving an RST_STREAM frame from the connected peer,\ncalling http2stream.close(), or http2stream.destroy(). Will be\nundefined if the Http2Stream has not been closed.

      " + }, + { + "textRaw": "`sentHeaders` {HTTP/2 Headers Object}", + "type": "HTTP/2 Headers Object", + "name": "sentHeaders", + "meta": { + "added": [ + "v9.5.0" + ], + "changes": [] + }, + "desc": "

      An object containing the outbound headers sent for this Http2Stream.

      " + }, + { + "textRaw": "`sentInfoHeaders` {HTTP/2 Headers Object[]}", + "type": "HTTP/2 Headers Object[]", + "name": "sentInfoHeaders", + "meta": { + "added": [ + "v9.5.0" + ], + "changes": [] + }, + "desc": "

      An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.

      " + }, + { + "textRaw": "`sentTrailers` {HTTP/2 Headers Object}", + "type": "HTTP/2 Headers Object", + "name": "sentTrailers", + "meta": { + "added": [ + "v9.5.0" + ], + "changes": [] + }, + "desc": "

      An object containing the outbound trailers sent for this HttpStream.

      " + }, + { + "textRaw": "`session` {Http2Session}", + "type": "Http2Session", + "name": "session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.

      " + }, + { + "textRaw": "`http2stream.state`", + "name": "state", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Provides miscellaneous information about the current state of the\nHttp2Stream.

      \n
        \n
      • <Object>\n
          \n
        • localWindowSize <number> The number of bytes the connected peer may send\nfor this Http2Stream without receiving a WINDOW_UPDATE.
        • \n
        • state <number> A flag indicating the low-level current state of the\nHttp2Stream as determined by nghttp2.
        • \n
        • localClose <number> 1 if this Http2Stream has been closed locally.
        • \n
        • remoteClose <number> 1 if this Http2Stream has been closed\nremotely.
        • \n
        • sumDependencyWeight <number> The sum weight of all Http2Stream\ninstances that depend on this Http2Stream as specified using\nPRIORITY frames.
        • \n
        • weight <number> The priority weight of this Http2Stream.
        • \n
        \n
      • \n
      \n

      A current state of this Http2Stream.

      " + } + ], + "methods": [ + { + "textRaw": "`http2stream.close(code[, callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {number} Unsigned 32-bit integer identifying the error code. **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).", + "name": "code", + "type": "number", + "default": "`http2.constants.NGHTTP2_NO_ERROR` (`0x00`)", + "desc": "Unsigned 32-bit integer identifying the error code." + }, + { + "textRaw": "`callback` {Function} An optional function registered to listen for the `'close'` event.", + "name": "callback", + "type": "Function", + "desc": "An optional function registered to listen for the `'close'` event." + } + ] + } + ], + "desc": "

      Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.

      " + }, + { + "textRaw": "`http2stream.priority(options)`", + "type": "method", + "name": "priority", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream. **Default:** `false`.", + "name": "exclusive", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream." + }, + { + "textRaw": "`parent` {number} Specifies the numeric identifier of a stream this stream is dependent on.", + "name": "parent", + "type": "number", + "desc": "Specifies the numeric identifier of a stream this stream is dependent on." + }, + { + "textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive).", + "name": "weight", + "type": "number", + "desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)." + }, + { + "textRaw": "`silent` {boolean} When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer.", + "name": "silent", + "type": "boolean", + "desc": "When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer." + } + ] + } + ] + } + ], + "desc": "

      Updates the priority for this Http2Stream instance.

      " + }, + { + "textRaw": "`http2stream.setTimeout(msecs, callback)`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "
      const http2 = require('http2');\nconst client = http2.connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = http2.constants;\nconst req = client.request({ ':path': '/' });\n\n// Cancel the stream if there's no activity after 5 seconds\nreq.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));\n
      " + }, + { + "textRaw": "`http2stream.sendTrailers(headers)`", + "type": "method", + "name": "sendTrailers", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + } + ] + } + ], + "desc": "

      Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method\nwill cause the Http2Stream to be immediately closed and must only be\ncalled after the 'wantTrailers' event has been emitted. When sending a\nrequest or sending a response, the options.waitForTrailers option must be set\nin order to keep the Http2Stream open after the final DATA frame so that\ntrailers can be sent.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond(undefined, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ xyz: 'abc' });\n  });\n  stream.end('Hello World');\n});\n
      \n

      The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).

      " + } + ] + }, + { + "textRaw": "Class: `ClientHttp2Stream`", + "type": "class", + "name": "ClientHttp2Stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      The ClientHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Clients. Http2Stream instances on the client\nprovide events such as 'response' and 'push' that are only relevant on\nthe client.

      ", + "events": [ + { + "textRaw": "Event: `'continue'`", + "type": "event", + "name": "continue", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server sends a 100 Continue status, usually because\nthe request contained Expect: 100-continue. This is an instruction that\nthe client should send the request body.

      " + }, + { + "textRaw": "Event: `'headers'`", + "type": "event", + "name": "headers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'headers' event is emitted when an additional block of headers is received\nfor a stream, such as when a block of 1xx informational headers is received.\nThe listener callback is passed the HTTP/2 Headers Object and flags\nassociated with the headers.

      \n
      stream.on('headers', (headers, flags) => {\n  console.log(headers);\n});\n
      " + }, + { + "textRaw": "Event: `'push'`", + "type": "event", + "name": "push", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'push' event is emitted when response headers for a Server Push stream\nare received. The listener callback is passed the HTTP/2 Headers Object and\nflags associated with the headers.

      \n
      stream.on('push', (headers, flags) => {\n  console.log(headers);\n});\n
      " + }, + { + "textRaw": "Event: `'response'`", + "type": "event", + "name": "response", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'response' event is emitted when a response HEADERS frame has been\nreceived for this stream from the connected HTTP/2 server. The listener is\ninvoked with two arguments: an Object containing the received\nHTTP/2 Headers Object, and flags associated with the headers.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n  console.log(headers[':status']);\n});\n
      " + } + ] + }, + { + "textRaw": "Class: `ServerHttp2Stream`", + "type": "class", + "name": "ServerHttp2Stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      The ServerHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Servers. Http2Stream instances on the server\nprovide additional methods such as http2stream.pushStream() and\nhttp2stream.respond() that are only relevant on the server.

      ", + "methods": [ + { + "textRaw": "`http2stream.additionalHeaders(headers)`", + "type": "method", + "name": "additionalHeaders", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + } + ] + } + ], + "desc": "

      Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

      " + }, + { + "textRaw": "`http2stream.pushStream(headers[, options], callback)`", + "type": "method", + "name": "pushStream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`.", + "name": "exclusive", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream." + }, + { + "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", + "name": "parent", + "type": "number", + "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." + } + ] + }, + { + "textRaw": "`callback` {Function} Callback that is called once the push stream has been initiated.", + "name": "callback", + "type": "Function", + "desc": "Callback that is called once the push stream has been initiated.", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`pushStream` {ServerHttp2Stream} The returned `pushStream` object.", + "name": "pushStream", + "type": "ServerHttp2Stream", + "desc": "The returned `pushStream` object." + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object} Headers object the `pushStream` was initiated with.", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "Headers object the `pushStream` was initiated with." + } + ] + } + ] + } + ], + "desc": "

      Initiates a push stream. The callback is invoked with the new Http2Stream\ninstance created for the push stream passed as the second argument, or an\nError passed as the first argument.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {\n    if (err) throw err;\n    pushStream.respond({ ':status': 200 });\n    pushStream.end('some pushed data');\n  });\n  stream.end('some data');\n});\n
      \n

      Setting the weight of a push stream is not allowed in the HEADERS frame. Pass\na weight value to http2stream.priority with the silent option set to\ntrue to enable server-side bandwidth balancing between concurrent streams.

      \n

      Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.

      " + }, + { + "textRaw": "`http2stream.respond([headers[, options]])`", + "type": "method", + "name": "respond", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33160", + "description": "Allow explicity setting date headers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`endStream` {boolean} Set to `true` to indicate that the response will not include payload data.", + "name": "endStream", + "type": "boolean", + "desc": "Set to `true` to indicate that the response will not include payload data." + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + } + ] + } + ] + } + ], + "desc": "
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.end('some data');\n});\n
      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 }, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n  stream.end('some data');\n});\n
      " + }, + { + "textRaw": "`http2stream.respondWithFD(fd[, headers[, options]])`", + "type": "method", + "name": "respondWithFD", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33160", + "description": "Allow explicity setting date headers." + }, + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29876", + "description": "The `fd` option may now be a `FileHandle`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18936", + "description": "Any readable file descriptor, not necessarily for a regular file, is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {number|FileHandle} A readable file descriptor.", + "name": "fd", + "type": "number|FileHandle", + "desc": "A readable file descriptor." + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`statCheck` {Function}", + "name": "statCheck", + "type": "Function" + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + }, + { + "textRaw": "`offset` {number} The offset position at which to begin reading.", + "name": "offset", + "type": "number", + "desc": "The offset position at which to begin reading." + }, + { + "textRaw": "`length` {number} The amount of data from the fd to send.", + "name": "length", + "type": "number", + "desc": "The amount of data from the fd to send." + } + ] + } + ] + } + ], + "desc": "

      Initiates a response whose data is read from the given file descriptor. No\nvalidation is performed on the given file descriptor. If an error occurs while\nattempting to read data using the file descriptor, the Http2Stream will be\nclosed using an RST_STREAM frame using the standard INTERNAL_ERROR code.

      \n

      When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  const fd = fs.openSync('/some/file', 'r');\n\n  const stat = fs.fstatSync(fd);\n  const headers = {\n    'content-length': stat.size,\n    'last-modified': stat.mtime.toUTCString(),\n    'content-type': 'text/plain; charset=utf-8'\n  };\n  stream.respondWithFD(fd, headers);\n  stream.on('close', () => fs.closeSync(fd));\n});\n
      \n

      The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given fd. If the statCheck function is provided, the\nhttp2stream.respondWithFD() method will perform an fs.fstat() call to\ncollect details on the provided file descriptor.

      \n

      The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.

      \n

      The file descriptor or FileHandle is not closed when the stream is closed,\nso it will need to be closed manually once it is no longer needed.\nUsing the same file descriptor concurrently for multiple streams\nis not supported and may result in data loss. Re-using a file descriptor\nafter a stream has finished is supported.

      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  const fd = fs.openSync('/some/file', 'r');\n\n  const stat = fs.fstatSync(fd);\n  const headers = {\n    'content-length': stat.size,\n    'last-modified': stat.mtime.toUTCString(),\n    'content-type': 'text/plain; charset=utf-8'\n  };\n  stream.respondWithFD(fd, headers, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n\n  stream.on('close', () => fs.closeSync(fd));\n});\n
      " + }, + { + "textRaw": "`http2stream.respondWithFile(path[, headers[, options]])`", + "type": "method", + "name": "respondWithFile", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33160", + "description": "Allow explicity setting date headers." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18936", + "description": "Any readable file, not necessarily a regular file, is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`statCheck` {Function}", + "name": "statCheck", + "type": "Function" + }, + { + "textRaw": "`onError` {Function} Callback function invoked in the case of an error before send.", + "name": "onError", + "type": "Function", + "desc": "Callback function invoked in the case of an error before send." + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + }, + { + "textRaw": "`offset` {number} The offset position at which to begin reading.", + "name": "offset", + "type": "number", + "desc": "The offset position at which to begin reading." + }, + { + "textRaw": "`length` {number} The amount of data from the fd to send.", + "name": "length", + "type": "number", + "desc": "The amount of data from the fd to send." + } + ] + } + ] + } + ], + "desc": "

      Sends a regular file as the response. The path must specify a regular file\nor an 'error' event will be emitted on the Http2Stream object.

      \n

      When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

      \n

      The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given file:

      \n

      If an error occurs while attempting to read the file data, the Http2Stream\nwill be closed using an RST_STREAM frame using the standard INTERNAL_ERROR\ncode. If the onError callback is defined, then it will be called. Otherwise\nthe stream will be destroyed.

      \n

      Example using a file path:

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  function statCheck(stat, headers) {\n    headers['last-modified'] = stat.mtime.toUTCString();\n  }\n\n  function onError(err) {\n    if (err.code === 'ENOENT') {\n      stream.respond({ ':status': 404 });\n    } else {\n      stream.respond({ ':status': 500 });\n    }\n    stream.end();\n  }\n\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain; charset=utf-8' },\n                         { statCheck, onError });\n});\n
      \n

      The options.statCheck function may also be used to cancel the send operation\nby returning false. For instance, a conditional request may check the stat\nresults to determine if the file has been modified to return an appropriate\n304 response:

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  function statCheck(stat, headers) {\n    // Check the stat here...\n    stream.respond({ ':status': 304 });\n    return false; // Cancel the send operation\n  }\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain; charset=utf-8' },\n                         { statCheck });\n});\n
      \n

      The content-length header field will be automatically set.

      \n

      The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.

      \n

      The options.onError function may also be used to handle all the errors\nthat could happen before the delivery of the file is initiated. The\ndefault behavior is to destroy the stream.

      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain; charset=utf-8' },\n                         { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n});\n
      " + } + ], + "properties": [ + { + "textRaw": "`headersSent` {boolean}", + "type": "boolean", + "name": "headersSent", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      True if headers were sent, false otherwise (read-only).

      " + }, + { + "textRaw": "`pushAllowed` {boolean}", + "type": "boolean", + "name": "pushAllowed", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote\nclient's most recent SETTINGS frame. Will be true if the remote peer\naccepts push streams, false otherwise. Settings are the same for every\nHttp2Stream in the same Http2Session.

      " + } + ] + }, + { + "textRaw": "Class: `Http2Server`", + "type": "class", + "name": "Http2Server", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the http2\nmodule.

      ", + "events": [ + { + "textRaw": "Event: `'checkContinue'`", + "type": "event", + "name": "checkContinue", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      If a 'request' listener is registered or http2.createServer() is\nsupplied a callback function, the 'checkContinue' event is emitted each time\na request with an HTTP Expect: 100-continue is received. If this event is\nnot listened for, the server will automatically respond with a status\n100 Continue as appropriate.

      \n

      Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + } + ] + }, + { + "textRaw": "Class: `Http2SecureServer`", + "type": "class", + "name": "Http2SecureServer", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the http2 module.

      ", + "events": [ + { + "textRaw": "Event: `'checkContinue'`", + "type": "event", + "name": "checkContinue", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      If a 'request' listener is registered or http2.createSecureServer()\nis supplied a callback function, the 'checkContinue' event is emitted each\ntime a request with an HTTP Expect: 100-continue is received. If this event\nis not listened for, the server will automatically respond with a status\n100 Continue as appropriate.

      \n

      Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + } + ] + } + ], + "events": [ + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.

      ", + "events": [ + { + "textRaw": "Event: `'request'`", + "type": "event", + "name": "request", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

      " + }, + { + "textRaw": "Event: `'session'`", + "type": "event", + "name": "session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.

      " + }, + { + "textRaw": "Event: `'sessionError'`", + "type": "event", + "name": "sessionError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.

      " + }, + { + "textRaw": "Event: `'stream'`", + "type": "event", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

      \n
      const http2 = require('http2');\nconst {\n  HTTP2_HEADER_METHOD,\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n  HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst server = http2.createServer();\nserver.on('stream', (stream, headers, flags) => {\n  const method = headers[HTTP2_HEADER_METHOD];\n  const path = headers[HTTP2_HEADER_PATH];\n  // ...\n  stream.respond({\n    [HTTP2_HEADER_STATUS]: 200,\n    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'\n  });\n  stream.write('hello ');\n  stream.end('world');\n});\n
      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().\nDefault: 2 minutes.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      " + } + ], + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.

      \n

      If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\nnet.Server.close() for more details.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2Server}", + "name": "return", + "type": "Http2Server" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Used to set the timeout value for http2 server requests,\nand sets a callback function that is called when there is no activity\non the Http2Server after msecs milliseconds.

      \n

      The given callback is registered as a listener on the 'timeout' event.

      \n

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK\nerror will be thrown.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      " + } + ] + }, + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established, before the TLS\nhandshake begins. socket is typically an object of type net.Socket.\nUsually users will not want to access this event.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.

      ", + "events": [ + { + "textRaw": "Event: `'request'`", + "type": "event", + "name": "request", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

      " + }, + { + "textRaw": "Event: `'session'`", + "type": "event", + "name": "session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.

      " + }, + { + "textRaw": "Event: `'sessionError'`", + "type": "event", + "name": "sessionError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.

      " + }, + { + "textRaw": "Event: `'stream'`", + "type": "event", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

      \n
      const http2 = require('http2');\nconst {\n  HTTP2_HEADER_METHOD,\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n  HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst options = getOptionsSomehow();\n\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream, headers, flags) => {\n  const method = headers[HTTP2_HEADER_METHOD];\n  const path = headers[HTTP2_HEADER_PATH];\n  // ...\n  stream.respond({\n    [HTTP2_HEADER_STATUS]: 200,\n    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'\n  });\n  stream.write('hello ');\n  stream.end('world');\n});\n
      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout().\nDefault: 2 minutes.

      " + }, + { + "textRaw": "Event: `'unknownProtocol'`", + "type": "event", + "name": "unknownProtocol", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'unknownProtocol' event is emitted when a connecting client fails to\nnegotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler\nreceives the socket for handling. If no listener is registered for this event,\nthe connection is terminated. A timeout may be specified using the\n'unknownProtocolTimeout' option passed to http2.createSecureServer().\nSee the Compatibility API.

      " + } + ], + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.

      \n

      If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\ntls.Server.close() for more details.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2SecureServer}", + "name": "return", + "type": "Http2SecureServer" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Used to set the timeout value for http2 secure server requests,\nand sets a callback function that is called when there is no activity\non the Http2SecureServer after msecs milliseconds.

      \n

      The given callback is registered as a listener on the 'timeout' event.

      \n

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK\nerror will be thrown.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`http2.createServer(options[, onRequestHandler])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.21.0", + "pr-url": "https://github.com/nodejs-private/node-private/pull/250", + "description": "Added `unknownProtocolTimeout` option with a default of 10000." + }, + { + "version": [ + "v12.18.0" + ], + "pr-url": "https://github.com/nodejs-private/node-private/pull/206", + "description": "Added `maxSettings` option with a default of 32." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionRejectedStreams` option with a default of 100." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionInvalidFrames` option with a default of 1000." + }, + { + "version": "v12.4.0", + "pr-url": "https://github.com/nodejs/node/pull/27782", + "description": "The `options` parameter now supports `net.createServer()` options." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17105", + "description": "Added the `maxOutstandingPings` option with a default limit of 10." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." + }, + { + "version": "v9.6.0", + "pr-url": "https://github.com/nodejs/node/pull/15752", + "description": "Added the `Http1IncomingMessage` and `Http1ServerResponse` option." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2Server}", + "name": "return", + "type": "Http2Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", + "name": "maxDeflateDynamicTableSize", + "type": "number", + "default": "`4Kib`", + "desc": "Sets the maximum dynamic table size for deflating header fields." + }, + { + "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", + "name": "maxSettings", + "type": "number", + "default": "`32`", + "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." + }, + { + "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", + "name": "maxSessionMemory", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." + }, + { + "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`. **Default:** `128`.", + "name": "maxHeaderListPairs", + "type": "number", + "default": "`128`", + "desc": "Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`." + }, + { + "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", + "name": "maxOutstandingPings", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum number of outstanding, unacknowledged pings." + }, + { + "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", + "name": "maxSendHeaderBlockLength", + "type": "number", + "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." + }, + { + "textRaw": "`paddingStrategy` {number} The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "name": "paddingStrategy", + "type": "number", + "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "desc": "The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", + "options": [ + { + "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: Specifies that no padding is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_NONE", + "desc": "Specifies that no padding is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_MAX", + "desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK`: Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding.", + "name": "http2.constants.PADDING_STRATEGY_CALLBACK", + "desc": "Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes.", + "name": "http2.constants.PADDING_STRATEGY_ALIGNED", + "desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes." + } + ] + }, + { + "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", + "name": "peerMaxConcurrentStreams", + "type": "number", + "default": "`100`", + "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." + }, + { + "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", + "name": "maxSessionInvalidFrames", + "type": "integer", + "default": "`1000`", + "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." + }, + { + "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", + "name": "maxSessionRejectedStreams", + "type": "integer", + "default": "`100`", + "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." + }, + { + "textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][].", + "name": "selectPadding", + "type": "Function", + "desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][]." + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The initial settings to send to the remote peer upon connection." + }, + { + "textRaw": "`Http1IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`.", + "name": "Http1IncomingMessage", + "type": "http.IncomingMessage", + "default": "`http.IncomingMessage`", + "desc": "Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`." + }, + { + "textRaw": "`Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`. **Default:** `http.ServerResponse`.", + "name": "Http1ServerResponse", + "type": "http.ServerResponse", + "default": "`http.ServerResponse`", + "desc": "Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`." + }, + { + "textRaw": "`Http2ServerRequest` {http2.Http2ServerRequest} Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`. **Default:** `Http2ServerRequest`.", + "name": "Http2ServerRequest", + "type": "http2.Http2ServerRequest", + "default": "`Http2ServerRequest`", + "desc": "Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`." + }, + { + "textRaw": "`Http2ServerResponse` {http2.Http2ServerResponse} Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`. **Default:** `Http2ServerResponse`.", + "name": "Http2ServerResponse", + "type": "http2.Http2ServerResponse", + "default": "`Http2ServerResponse`", + "desc": "Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`." + }, + { + "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", + "name": "unknownProtocolTimeout", + "type": "number", + "default": "`10000`", + "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] is emitted. If the socket has not been destroyed by that time the server will destroy it." + }, + { + "textRaw": "...: Any [`net.createServer()`][] option can be provided.", + "name": "...", + "desc": "Any [`net.createServer()`][] option can be provided." + } + ] + }, + { + "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", + "name": "onRequestHandler", + "type": "Function", + "desc": "See [Compatibility API][]" + } + ] + } + ], + "desc": "

      Returns a net.Server instance that creates and manages Http2Session\ninstances.

      \n

      Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

      \n
      const http2 = require('http2');\n\n// Create an unencrypted HTTP/2 server.\n// Since there are no browsers known that support\n// unencrypted HTTP/2, the use of `http2.createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
      " + }, + { + "textRaw": "`http2.createSecureServer(options[, onRequestHandler])`", + "type": "method", + "name": "createSecureServer", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.21.0", + "pr-url": "https://github.com/nodejs-private/node-private/pull/250", + "description": "Added `unknownProtocolTimeout` option with a default of 10000." + }, + { + "version": [ + "v12.18.0" + ], + "pr-url": "https://github.com/nodejs-private/node-private/pull/206", + "description": "Added `maxSettings` option with a default of 32." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionRejectedStreams` option with a default of 100." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionInvalidFrames` option with a default of 1000." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22956", + "description": "Added the `origins` option to automatically send an `ORIGIN` frame on `Http2Session` startup." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17105", + "description": "Added the `maxOutstandingPings` option with a default limit of 10." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2SecureServer}", + "name": "return", + "type": "Http2SecureServer" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`allowHTTP1` {boolean} Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. **Default:** `false`.", + "name": "allowHTTP1", + "type": "boolean", + "default": "`false`", + "desc": "Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]." + }, + { + "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", + "name": "maxDeflateDynamicTableSize", + "type": "number", + "default": "`4Kib`", + "desc": "Sets the maximum dynamic table size for deflating header fields." + }, + { + "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", + "name": "maxSettings", + "type": "number", + "default": "`32`", + "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." + }, + { + "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", + "name": "maxSessionMemory", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." + }, + { + "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`. **Default:** `128`.", + "name": "maxHeaderListPairs", + "type": "number", + "default": "`128`", + "desc": "Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`." + }, + { + "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", + "name": "maxOutstandingPings", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum number of outstanding, unacknowledged pings." + }, + { + "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", + "name": "maxSendHeaderBlockLength", + "type": "number", + "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." + }, + { + "textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "name": "paddingStrategy", + "type": "number", + "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", + "options": [ + { + "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: Specifies that no padding is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_NONE", + "desc": "Specifies that no padding is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_MAX", + "desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK`: Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding.", + "name": "http2.constants.PADDING_STRATEGY_CALLBACK", + "desc": "Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes.", + "name": "http2.constants.PADDING_STRATEGY_ALIGNED", + "desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes." + } + ] + }, + { + "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", + "name": "peerMaxConcurrentStreams", + "type": "number", + "default": "`100`", + "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." + }, + { + "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", + "name": "maxSessionInvalidFrames", + "type": "integer", + "default": "`1000`", + "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." + }, + { + "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", + "name": "maxSessionRejectedStreams", + "type": "integer", + "default": "`100`", + "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." + }, + { + "textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][].", + "name": "selectPadding", + "type": "Function", + "desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][]." + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The initial settings to send to the remote peer upon connection." + }, + { + "textRaw": "...: Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required.", + "name": "...", + "desc": "Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required." + }, + { + "textRaw": "`origins` {string[]} An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`.", + "name": "origins", + "type": "string[]", + "desc": "An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`." + }, + { + "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", + "name": "unknownProtocolTimeout", + "type": "number", + "default": "`10000`", + "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it." + } + ] + }, + { + "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", + "name": "onRequestHandler", + "type": "Function", + "desc": "See [Compatibility API][]" + } + ] + } + ], + "desc": "

      Returns a tls.Server instance that creates and manages Http2Session\ninstances.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem')\n};\n\n// Create a secure HTTP/2 server\nconst server = http2.createSecureServer(options);\n\nserver.on('stream', (stream, headers) => {\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
      " + }, + { + "textRaw": "`http2.connect(authority[, options][, listener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.21.0", + "pr-url": "https://github.com/nodejs-private/node-private/pull/250", + "description": "Added `unknownProtocolTimeout` option with a default of 10000." + }, + { + "version": [ + "v12.18.0" + ], + "pr-url": "https://github.com/nodejs-private/node-private/pull/206", + "description": "Added `maxSettings` option with a default of 32." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17105", + "description": "Added the `maxOutstandingPings` option with a default limit of 10." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ClientHttp2Session}", + "name": "return", + "type": "ClientHttp2Session" + }, + "params": [ + { + "textRaw": "`authority` {string|URL} The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored.", + "name": "authority", + "type": "string|URL", + "desc": "The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", + "name": "maxDeflateDynamicTableSize", + "type": "number", + "default": "`4Kib`", + "desc": "Sets the maximum dynamic table size for deflating header fields." + }, + { + "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", + "name": "maxSettings", + "type": "number", + "default": "`32`", + "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." + }, + { + "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", + "name": "maxSessionMemory", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." + }, + { + "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `1`. **Default:** `128`.", + "name": "maxHeaderListPairs", + "type": "number", + "default": "`128`", + "desc": "Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `1`." + }, + { + "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", + "name": "maxOutstandingPings", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum number of outstanding, unacknowledged pings." + }, + { + "textRaw": "`maxReservedRemoteStreams` {number} Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value. **Default:** `200`.", + "name": "maxReservedRemoteStreams", + "type": "number", + "default": "`200`", + "desc": "Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value." + }, + { + "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", + "name": "maxSendHeaderBlockLength", + "type": "number", + "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." + }, + { + "textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "name": "paddingStrategy", + "type": "number", + "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", + "options": [ + { + "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: Specifies that no padding is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_NONE", + "desc": "Specifies that no padding is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_MAX", + "desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK`: Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding.", + "name": "http2.constants.PADDING_STRATEGY_CALLBACK", + "desc": "Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes.", + "name": "http2.constants.PADDING_STRATEGY_ALIGNED", + "desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes." + } + ] + }, + { + "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", + "name": "peerMaxConcurrentStreams", + "type": "number", + "default": "`100`", + "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." + }, + { + "textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][].", + "name": "selectPadding", + "type": "Function", + "desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][]." + }, + { + "textRaw": "`protocol` {string} The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`. **Default:** `'https:'`", + "name": "protocol", + "type": "string", + "default": "`'https:'`", + "desc": "The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`." + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The initial settings to send to the remote peer upon connection." + }, + { + "textRaw": "`createConnection` {Function} An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any [`Duplex`][] stream that is to be used as the connection for this session.", + "name": "createConnection", + "type": "Function", + "desc": "An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any [`Duplex`][] stream that is to be used as the connection for this session." + }, + { + "textRaw": "...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided.", + "name": "...", + "desc": "Any [`net.connect()`][] or [`tls.connect()`][] options can be provided." + }, + { + "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", + "name": "unknownProtocolTimeout", + "type": "number", + "default": "`10000`", + "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it." + } + ] + }, + { + "textRaw": "`listener` {Function} Will be registered as a one-time listener of the [`'connect'`][] event.", + "name": "listener", + "type": "Function", + "desc": "Will be registered as a one-time listener of the [`'connect'`][] event." + } + ] + } + ], + "desc": "

      Returns a ClientHttp2Session instance.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n
      " + }, + { + "textRaw": "`http2.getDefaultSettings()`", + "type": "method", + "name": "getDefaultSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {HTTP/2 Settings Object}", + "name": "return", + "type": "HTTP/2 Settings Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing the default settings for an Http2Session\ninstance. This method returns a new object instance every time it is called\nso instances returned may be safely modified for use.

      " + }, + { + "textRaw": "`http2.getPackedSettings([settings])`", + "type": "method", + "name": "getPackedSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object}", + "name": "settings", + "type": "HTTP/2 Settings Object" + } + ] + } + ], + "desc": "

      Returns a Buffer instance containing serialized representation of the given\nHTTP/2 settings as specified in the HTTP/2 specification. This is intended\nfor use with the HTTP2-Settings header field.

      \n
      const http2 = require('http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
      " + }, + { + "textRaw": "`http2.getUnpackedSettings(buf)`", + "type": "method", + "name": "getUnpackedSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {HTTP/2 Settings Object}", + "name": "return", + "type": "HTTP/2 Settings Object" + }, + "params": [ + { + "textRaw": "`buf` {Buffer|Uint8Array} The packed settings.", + "name": "buf", + "type": "Buffer|Uint8Array", + "desc": "The packed settings." + } + ] + } + ], + "desc": "

      Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().

      " + } + ], + "properties": [ + { + "textRaw": "`http2.constants`", + "name": "constants", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "modules": [ + { + "textRaw": "Error codes for `RST_STREAM` and `GOAWAY`", + "name": "error_codes_for_`rst_stream`_and_`goaway`", + "desc": "

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      ValueNameConstant
      0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
      0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
      0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
      0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
      0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
      0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
      0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
      0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
      0x08Cancelhttp2.constants.NGHTTP2_CANCEL
      0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
      0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
      0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
      0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
      0x0dHTTP/1.1 Requiredhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED
      \n

      The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().

      ", + "type": "module", + "displayName": "Error codes for `RST_STREAM` and `GOAWAY`" + } + ] + } + ], + "type": "module", + "displayName": "Core API" + }, + { + "textRaw": "Compatibility API", + "name": "compatibility_api", + "desc": "

      The Compatibility API has the goal of providing a similar developer experience\nof HTTP/1 when using HTTP/2, making it possible to develop applications\nthat support both HTTP/1 and HTTP/2. This API targets only the\npublic API of the HTTP/1. However many modules use internal\nmethods or state, and those are not supported as it is a completely\ndifferent implementation.

      \n

      The following example creates an HTTP/2 server using the compatibility\nAPI:

      \n
      const http2 = require('http2');\nconst server = http2.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n  res.end('ok');\n});\n
      \n

      In order to create a mixed HTTPS and HTTP/2 server, refer to the\nALPN negotiation section.\nUpgrading from non-tls HTTP/1 servers is not supported.

      \n

      The HTTP/2 compatibility API is composed of Http2ServerRequest and\nHttp2ServerResponse. They aim at API compatibility with HTTP/1, but\nthey do not hide the differences between the protocols. As an example,\nthe status message for HTTP codes is ignored.

      ", + "modules": [ + { + "textRaw": "ALPN negotiation", + "name": "alpn_negotiation", + "desc": "

      ALPN negotiation allows supporting both HTTPS and HTTP/2 over\nthe same socket. The req and res objects can be either HTTP/1 or\nHTTP/2, and an application must restrict itself to the public API of\nHTTP/1, and detect if it is possible to use the more advanced\nfeatures of HTTP/2.

      \n

      The following example creates a server that supports both protocols:

      \n
      const { createSecureServer } = require('http2');\nconst { readFileSync } = require('fs');\n\nconst cert = readFileSync('./cert.pem');\nconst key = readFileSync('./key.pem');\n\nconst server = createSecureServer(\n  { cert, key, allowHTTP1: true },\n  onRequest\n).listen(4443);\n\nfunction onRequest(req, res) {\n  // Detects if it is a HTTPS request or HTTP/2\n  const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?\n    req.stream.session : req;\n  res.writeHead(200, { 'content-type': 'application/json' });\n  res.end(JSON.stringify({\n    alpnProtocol,\n    httpVersion: req.httpVersion\n  }));\n}\n
      \n

      The 'request' event works identically on both HTTPS and\nHTTP/2.

      ", + "type": "module", + "displayName": "ALPN negotiation" + } + ], + "classes": [ + { + "textRaw": "Class: `http2.Http2ServerRequest`", + "type": "class", + "name": "http2.Http2ServerRequest", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      A Http2ServerRequest object is created by http2.Server or\nhttp2.SecureServer and passed as the first argument to the\n'request' event. It may be used to access a request status, headers, and\ndata.

      ", + "events": [ + { + "textRaw": "Event: `'aborted'`", + "type": "event", + "name": "aborted", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.

      \n

      The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.

      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v10.1.0" + ], + "changes": [] + }, + "desc": "

      The request.aborted property will be true if the request has\nbeen aborted.

      " + }, + { + "textRaw": "`authority` {string}", + "type": "string", + "name": "authority", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request authority pseudo header field. It can also be accessed via\nreq.headers[':authority'].

      " + }, + { + "textRaw": "`complete` {boolean}", + "type": "boolean", + "name": "complete", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      The request.complete property will be true if the request has\nbeen completed, aborted, or destroyed.

      " + }, + { + "textRaw": "`headers` {Object}", + "type": "Object", + "name": "headers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request/response headers object.

      \n

      Key-value pairs of header names and values. Header names are lower-cased.

      \n
      // Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);\n
      \n

      See HTTP/2 Headers Object.

      \n

      In HTTP/2, the request path, host name, protocol, and method are represented as\nspecial headers prefixed with the : character (e.g. ':path'). These special\nheaders will be included in the request.headers object. Care must be taken not\nto inadvertently modify these special headers or errors may occur. For instance,\nremoving all headers from the request will cause errors to occur:

      \n
      removeAllHeaders(request.headers);\nassert(request.url);   // Fails because the :path header has been removed\n
      " + }, + { + "textRaw": "`httpVersion` {string}", + "type": "string", + "name": "httpVersion", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server. Returns\n'2.0'.

      \n

      Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

      " + }, + { + "textRaw": "`method` {string}", + "type": "string", + "name": "method", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

      " + }, + { + "textRaw": "`rawHeaders` {string[]}", + "type": "string[]", + "name": "rawHeaders", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The raw request/response headers list exactly as they were received.

      \n

      The keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.

      \n

      Header names are not lowercased, and duplicates are not merged.

      \n
      // Prints something like:\n//\n// [ 'user-agent',\n//   'this is invalid because there can be only one',\n//   'User-Agent',\n//   'curl/7.22.0',\n//   'Host',\n//   '127.0.0.1:8000',\n//   'ACCEPT',\n//   '*/*' ]\nconsole.log(request.rawHeaders);\n
      " + }, + { + "textRaw": "`rawTrailers` {string[]}", + "type": "string[]", + "name": "rawTrailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`scheme` {string}", + "type": "string", + "name": "scheme", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request scheme pseudo header field indicating the scheme\nportion of the target URL.

      " + }, + { + "textRaw": "`socket` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "socket", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.

      \n

      destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.

      \n

      destroy, emit, end, on and once methods will be called on\nrequest.stream.

      \n

      setTimeout method will be called on request.stream.session.

      \n

      pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

      \n

      All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.

      " + }, + { + "textRaw": "`stream` {Http2Stream}", + "type": "Http2Stream", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The Http2Stream object backing the request.

      " + }, + { + "textRaw": "`trailers` {Object}", + "type": "Object", + "name": "trailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request/response trailers object. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`url` {string}", + "type": "string", + "name": "url", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Request URL string. This contains only the URL that is present in the actual\nHTTP request. If the request is:

      \n
      GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
      \n

      Then request.url will be:

      \n\n
      '/status?name=ryan'\n
      \n

      To parse the url into its parts, require('url').parse(request.url)\ncan be used:

      \n
      $ node\n> require('url').parse('/status?name=ryan')\nUrl {\n  protocol: null,\n  slashes: null,\n  auth: null,\n  host: null,\n  port: null,\n  hostname: null,\n  hash: null,\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status',\n  path: '/status?name=ryan',\n  href: '/status?name=ryan' }\n
      \n

      To obtain the parameters from the query string, use the\nrequire('querystring').parse() function or pass\ntrue as the second argument to require('url').parse().

      \n
      $ node\n> require('url').parse('/status?name=ryan', true)\nUrl {\n  protocol: null,\n  slashes: null,\n  auth: null,\n  host: null,\n  port: null,\n  hostname: null,\n  hash: null,\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status',\n  path: '/status?name=ryan',\n  href: '/status?name=ryan' }\n
      " + } + ], + "methods": [ + { + "textRaw": "`request.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      Calls destroy() on the Http2Stream that received\nthe Http2ServerRequest. If error is provided, an 'error' event\nis emitted and error is passed as an argument to any listeners on the event.

      \n

      It does nothing if the stream was already destroyed.

      " + }, + { + "textRaw": "`request.setTimeout(msecs, callback)`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http2.Http2ServerRequest}", + "name": "return", + "type": "http2.Http2ServerRequest" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.

      \n

      If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.

      " + } + ] + }, + { + "textRaw": "Class: `http2.Http2ServerResponse`", + "type": "class", + "name": "http2.Http2ServerResponse", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.

      " + }, + { + "textRaw": "Event: `'finish'`", + "type": "event", + "name": "finish", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the HTTP/2 multiplexing for transmission over the network. It\ndoes not imply that the client has received anything yet.

      \n

      After this event, no more events will be emitted on the response object.

      " + } + ], + "methods": [ + { + "textRaw": "`response.addTrailers(headers)`", + "type": "method", + "name": "addTrailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `ServerResponse`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.

      \n

      If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).

      \n

      If callback is specified, it will be called when the response stream\nis finished.

      " + }, + { + "textRaw": "`response.getHeader(name)`", + "type": "method", + "name": "getHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Reads out a header that has already been queued but not sent to the client.\nThe name is case-insensitive.

      \n
      const contentType = response.getHeader('content-type');\n
      " + }, + { + "textRaw": "`response.getHeaderNames()`", + "type": "method", + "name": "getHeaderNames", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
      " + }, + { + "textRaw": "`response.getHeaders()`", + "type": "method", + "name": "getHeaders", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.

      \n

      The object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
      " + }, + { + "textRaw": "`response.hasHeader(name)`", + "type": "method", + "name": "hasHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

      \n
      const hasContentType = response.hasHeader('content-type');\n
      " + }, + { + "textRaw": "`response.removeHeader(name)`", + "type": "method", + "name": "removeHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Removes a header that has been queued for implicit sending.

      \n
      response.removeHeader('Content-Encoding');\n
      " + }, + { + "textRaw": "`response.setHeader(name, value)`", + "type": "method", + "name": "setHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {string|string[]}", + "name": "value", + "type": "string|string[]" + } + ] + } + ], + "desc": "

      Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.

      \n
      response.setHeader('Content-Type', 'text/html; charset=utf-8');\n
      \n

      or

      \n
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n
      // Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html; charset=utf-8');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n  res.end('ok');\n});\n
      " + }, + { + "textRaw": "`response.setTimeout(msecs[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http2.Http2ServerResponse}", + "name": "return", + "type": "http2.Http2ServerResponse" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.

      \n

      If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.

      " + }, + { + "textRaw": "`response.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer|Uint8Array}", + "name": "chunk", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

      \n

      This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

      \n

      In the http module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204 and 304 responses\nmust not include a message body.

      \n

      chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'. callback will be called when this chunk\nof data is flushed.

      \n

      This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

      \n

      The first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.

      " + }, + { + "textRaw": "`response.writeContinue()`", + "type": "method", + "name": "writeContinue", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.

      " + }, + { + "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", + "type": "method", + "name": "writeHead", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v11.10.0", + "pr-url": "https://github.com/nodejs/node/pull/25974", + "description": "Return `this` from `writeHead()` to allow chaining with `end()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http2.Http2ServerResponse}", + "name": "return", + "type": "http2.Http2ServerResponse" + }, + "params": [ + { + "textRaw": "`statusCode` {number}", + "name": "statusCode", + "type": "number" + }, + { + "textRaw": "`statusMessage` {string}", + "name": "statusMessage", + "type": "string" + }, + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.

      \n

      Returns a reference to the Http2ServerResponse, so that calls can be chained.

      \n

      For compatibility with HTTP/1, a human-readable statusMessage may be\npassed as the second argument. However, because the statusMessage has no\nmeaning within HTTP/2, the argument will have no effect and a process warning\nwill be emitted.

      \n
      const body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain; charset=utf-8' });\n
      \n

      Content-Length is given in bytes not characters. The\nBuffer.byteLength() API may be used to determine the number of bytes in a\ngiven encoding. On outbound messages, Node.js does not check if Content-Length\nand the length of the body being transmitted are equal or not. However, when\nreceiving messages, Node.js will automatically reject messages when the\nContent-Length does not match the actual payload size.

      \n

      This method may be called at most one time on a message before\nresponse.end() is called.

      \n

      If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n
      // Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html; charset=utf-8');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n  res.end('ok');\n});\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.createPushResponse(headers, callback)`", + "type": "method", + "name": "createPushResponse", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "An object describing the headers" + }, + { + "textRaw": "`callback` {Function} Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", + "name": "callback", + "type": "Function", + "desc": "Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stream` {ServerHttp2Stream} The newly-created `ServerHttp2Stream` object", + "name": "stream", + "type": "ServerHttp2Stream", + "desc": "The newly-created `ServerHttp2Stream` object" + } + ] + } + ] + } + ], + "desc": "

      Call http2stream.pushStream() with the given headers, and wrap the\ngiven Http2Stream on a newly created Http2ServerResponse as the callback\nparameter if successful. When Http2ServerRequest is closed, the callback is\ncalled with an error ERR_HTTP2_INVALID_STREAM.

      " + } + ], + "properties": [ + { + "textRaw": "`connection` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "connection", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      See response.socket.

      " + }, + { + "textRaw": "`finished` {boolean}", + "type": "boolean", + "name": "finished", + "meta": { + "added": [ + "v8.4.0" + ], + "deprecated": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated. Use [`response.writableEnded`][].", + "desc": "

      Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.

      " + }, + { + "textRaw": "`headersSent` {boolean}", + "type": "boolean", + "name": "headersSent", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      True if headers were sent, false otherwise (read-only).

      " + }, + { + "textRaw": "`sendDate` {boolean}", + "type": "boolean", + "name": "sendDate", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.

      \n

      This should only be disabled for testing; HTTP requires the Date header\nin responses.

      " + }, + { + "textRaw": "`socket` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "socket", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.

      \n

      destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.

      \n

      destroy, emit, end, on and once methods will be called on\nresponse.stream.

      \n

      setTimeout method will be called on response.stream.session.

      \n

      pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

      \n

      All other interactions will be routed directly to the socket.

      \n
      const http2 = require('http2');\nconst server = http2.createServer((req, res) => {\n  const ip = req.socket.remoteAddress;\n  const port = req.socket.remotePort;\n  res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
      " + }, + { + "textRaw": "`statusCode` {number}", + "type": "number", + "name": "statusCode", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.

      \n
      response.statusCode = 404;\n
      \n

      After response header was sent to the client, this property indicates the\nstatus code which was sent out.

      " + }, + { + "textRaw": "`statusMessage` {string}", + "type": "string", + "name": "statusMessage", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns\nan empty string.

      " + }, + { + "textRaw": "`stream` {Http2Stream}", + "type": "Http2Stream", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The Http2Stream object backing the response.

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.

      " + } + ] + } + ], + "type": "module", + "displayName": "Compatibility API" + }, + { + "textRaw": "Collecting HTTP/2 performance metrics", + "name": "collecting_http/2_performance_metrics", + "desc": "

      The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.

      \n
      const { PerformanceObserver } = require('perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n  const entry = items.getEntries()[0];\n  console.log(entry.entryType);  // prints 'http2'\n  if (entry.name === 'Http2Session') {\n    // Entry contains statistics about the Http2Session\n  } else if (entry.name === 'Http2Stream') {\n    // Entry contains statistics about the Http2Stream\n  }\n});\nobs.observe({ entryTypes: ['http2'] });\n
      \n

      The entryType property of the PerformanceEntry will be equal to 'http2'.

      \n

      The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.

      \n

      If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:

      \n
        \n
      • bytesRead <number> The number of DATA frame bytes received for this\nHttp2Stream.
      • \n
      • bytesWritten <number> The number of DATA frame bytes sent for this\nHttp2Stream.
      • \n
      • id <number> The identifier of the associated Http2Stream
      • \n
      • timeToFirstByte <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first DATA frame.
      • \n
      • timeToFirstByteSent <number> The number of milliseconds elapsed between\nthe PerformanceEntry startTime and sending of the first DATA frame.
      • \n
      • timeToFirstHeader <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first header.
      • \n
      \n

      If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:

      \n
        \n
      • bytesRead <number> The number of bytes received for this Http2Session.
      • \n
      • bytesWritten <number> The number of bytes sent for this Http2Session.
      • \n
      • framesReceived <number> The number of HTTP/2 frames received by the\nHttp2Session.
      • \n
      • framesSent <number> The number of HTTP/2 frames sent by the Http2Session.
      • \n
      • maxConcurrentStreams <number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session.
      • \n
      • pingRTT <number> The number of milliseconds elapsed since the transmission\nof a PING frame and the reception of its acknowledgment. Only present if\na PING frame has been sent on the Http2Session.
      • \n
      • streamAverageDuration <number> The average duration (in milliseconds) for\nall Http2Stream instances.
      • \n
      • streamCount <number> The number of Http2Stream instances processed by\nthe Http2Session.
      • \n
      • type <string> Either 'server' or 'client' to identify the type of\nHttp2Session.
      • \n
      ", + "type": "module", + "displayName": "Collecting HTTP/2 performance metrics" + } + ], + "type": "module", + "displayName": "HTTP/2" + }, + { + "textRaw": "HTTPS", + "name": "https", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/https.js

      \n

      HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.

      ", + "classes": [ + { + "textRaw": "Class: `https.Agent`", + "type": "class", + "name": "https.Agent", + "meta": { + "added": [ + "v0.4.5" + ], + "changes": [ + { + "version": "v2.5.0", + "pr-url": "https://github.com/nodejs/node/pull/2228", + "description": "parameter `maxCachedSessions` added to `options` for TLS sessions reuse." + }, + { + "version": "v5.3.0", + "pr-url": "https://github.com/nodejs/node/pull/4252", + "description": "support `0` `maxCachedSessions` to disable TLS session caching." + } + ] + }, + "desc": "

      An Agent object for HTTPS similar to http.Agent. See\nhttps.request() for more information.

      ", + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the same fields as for [`http.Agent(options)`][], and", + "name": "options", + "type": "Object", + "desc": "Set of configurable options to set on the agent. Can have the same fields as for [`http.Agent(options)`][], and", + "options": [ + { + "textRaw": "`maxCachedSessions` {number} maximum number of TLS cached sessions. Use `0` to disable TLS session caching. **Default:** `100`.", + "name": "maxCachedSessions", + "type": "number", + "default": "`100`", + "desc": "maximum number of TLS cached sessions. Use `0` to disable TLS session caching." + }, + { + "textRaw": "`servername` {string} the value of [Server Name Indication extension][sni wiki] to be sent to the server. Use empty string `''` to disable sending the extension. **Default:** host name of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).See [`Session Resumption`][] for information about TLS session reuse.", + "name": "servername", + "type": "string", + "default": "host name of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).See [`Session Resumption`][] for information about TLS session reuse", + "desc": "the value of [Server Name Indication extension][sni wiki] to be sent to the server. Use empty string `''` to disable sending the extension." + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: `https.Server`", + "type": "class", + "name": "https.Server", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "desc": "\n

      See http.Server for more information.

      ", + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {https.Server}", + "name": "return", + "type": "https.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      See server.close() from the HTTP module for details.

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts the HTTPS server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {https.Server}", + "name": "return", + "type": "https.Server" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      See http.Server#setTimeout().

      " + } + ], + "properties": [ + { + "textRaw": "`headersTimeout` {number} **Default:** `60000`", + "type": "number", + "name": "headersTimeout", + "meta": { + "added": [ + "v11.3.0" + ], + "changes": [] + }, + "default": "`60000`", + "desc": "

      See http.Server#headersTimeout.

      " + }, + { + "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", + "type": "number", + "name": "maxHeadersCount", + "default": "`2000`", + "desc": "

      See http.Server#maxHeadersCount.

      " + }, + { + "textRaw": "`timeout` {number} **Default:** `120000` (2 minutes)", + "type": "number", + "name": "timeout", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "default": "`120000` (2 minutes)", + "desc": "

      See http.Server#timeout.

      " + }, + { + "textRaw": "`keepAliveTimeout` {number} **Default:** `5000` (5 seconds)", + "type": "number", + "name": "keepAliveTimeout", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "default": "`5000` (5 seconds)", + "desc": "

      See http.Server#keepAliveTimeout.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`https.createServer([options][, requestListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {https.Server}", + "name": "return", + "type": "https.Server" + }, + "params": [ + { + "textRaw": "`options` {Object} Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][].", + "name": "options", + "type": "Object", + "desc": "Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][]." + }, + { + "textRaw": "`requestListener` {Function} A listener to be added to the `'request'` event.", + "name": "requestListener", + "type": "Function", + "desc": "A listener to be added to the `'request'` event." + } + ] + } + ], + "desc": "
      // curl -k https://localhost:8000/\nconst https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, (req, res) => {\n  res.writeHead(200);\n  res.end('hello world\\n');\n}).listen(8000);\n
      \n

      Or

      \n
      const https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),\n  passphrase: 'sample'\n};\n\nhttps.createServer(options, (req, res) => {\n  res.writeHead(200);\n  res.end('hello world\\n');\n}).listen(8000);\n
      " + }, + { + "textRaw": "`https.get(options[, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`.", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Like http.get() but for HTTPS.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nhttps.get('https://encrypted.google.com/', (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n\n}).on('error', (e) => {\n  console.error(e);\n});\n
      " + }, + { + "textRaw": "`https.get(url[, options][, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`.", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Like http.get() but for HTTPS.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nhttps.get('https://encrypted.google.com/', (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n\n}).on('error', (e) => {\n  console.error(e);\n});\n
      " + }, + { + "textRaw": "`https.request(options[, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts all `options` from [`http.request()`][], with some differences in default values:", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts all `options` from [`http.request()`][], with some differences in default values:", + "options": [ + { + "textRaw": "`protocol` **Default:** `'https:'`", + "name": "protocol", + "default": "`'https:'`" + }, + { + "textRaw": "`port` **Default:** `443`", + "name": "port", + "default": "`443`" + }, + { + "textRaw": "`agent` **Default:** `https.globalAgent`", + "name": "agent", + "default": "`https.globalAgent`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Makes a request to a secure web server.

      \n

      The following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nconst options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nconst req = https.request(options, (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(e);\n});\nreq.end();\n
      \n

      Example using options from tls.connect():

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Alternatively, opt out of connection pooling by not using an Agent.

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example using a URL as options:

      \n
      const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example pinning on certificate fingerprint, or the public key (similar to\npin-sha256):

      \n
      const tls = require('tls');\nconst https = require('https');\nconst crypto = require('crypto');\n\nfunction sha256(s) {\n  return crypto.createHash('sha256').update(s).digest('base64');\n}\nconst options = {\n  hostname: 'github.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  checkServerIdentity: function(host, cert) {\n    // Make sure the certificate is issued to the host we are connected to\n    const err = tls.checkServerIdentity(host, cert);\n    if (err) {\n      return err;\n    }\n\n    // Pin the public key, similar to HPKP pin-sha25 pinning\n    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';\n    if (sha256(cert.pubkey) !== pubkey256) {\n      const msg = 'Certificate verification error: ' +\n        `The public key of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // Pin the exact certificate, rather than the pub key\n    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +\n      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';\n    if (cert.fingerprint256 !== cert256) {\n      const msg = 'Certificate verification error: ' +\n        `The certificate of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // This loop is informational only.\n    // Print the certificate and public key fingerprints of all certs in the\n    // chain. Its common to pin the public key of the issuer on the public\n    // internet, while pinning the public key of the service in sensitive\n    // environments.\n    do {\n      console.log('Subject Common Name:', cert.subject.CN);\n      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);\n\n      hash = crypto.createHash('sha256');\n      console.log('  Public key ping-sha256:', sha256(cert.pubkey));\n\n      lastprint256 = cert.fingerprint256;\n      cert = cert.issuerCertificate;\n    } while (cert.fingerprint256 !== lastprint256);\n\n  },\n};\n\noptions.agent = new https.Agent(options);\nconst req = https.request(options, (res) => {\n  console.log('All OK. Server matched our pinned cert or public key');\n  console.log('statusCode:', res.statusCode);\n  // Print the HPKP values\n  console.log('headers:', res.headers['public-key-pins']);\n\n  res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n  console.error(e.message);\n});\nreq.end();\n
      \n

      Outputs for example:

      \n
      Subject Common Name: github.com\n  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16\n  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\nSubject Common Name: DigiCert SHA2 Extended Validation Server CA\n  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A\n  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\nSubject Common Name: DigiCert High Assurance EV Root CA\n  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF\n  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\nheaders: max-age=0; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\"; pin-sha256=\"k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=\"; pin-sha256=\"K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=\"; pin-sha256=\"IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=\"; pin-sha256=\"iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0=\"; pin-sha256=\"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=\"; includeSubDomains\n
      " + }, + { + "textRaw": "`https.request(url[, options][, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts all `options` from [`http.request()`][], with some differences in default values:", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts all `options` from [`http.request()`][], with some differences in default values:", + "options": [ + { + "textRaw": "`protocol` **Default:** `'https:'`", + "name": "protocol", + "default": "`'https:'`" + }, + { + "textRaw": "`port` **Default:** `443`", + "name": "port", + "default": "`443`" + }, + { + "textRaw": "`agent` **Default:** `https.globalAgent`", + "name": "agent", + "default": "`https.globalAgent`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Makes a request to a secure web server.

      \n

      The following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nconst options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nconst req = https.request(options, (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(e);\n});\nreq.end();\n
      \n

      Example using options from tls.connect():

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Alternatively, opt out of connection pooling by not using an Agent.

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example using a URL as options:

      \n
      const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example pinning on certificate fingerprint, or the public key (similar to\npin-sha256):

      \n
      const tls = require('tls');\nconst https = require('https');\nconst crypto = require('crypto');\n\nfunction sha256(s) {\n  return crypto.createHash('sha256').update(s).digest('base64');\n}\nconst options = {\n  hostname: 'github.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  checkServerIdentity: function(host, cert) {\n    // Make sure the certificate is issued to the host we are connected to\n    const err = tls.checkServerIdentity(host, cert);\n    if (err) {\n      return err;\n    }\n\n    // Pin the public key, similar to HPKP pin-sha25 pinning\n    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';\n    if (sha256(cert.pubkey) !== pubkey256) {\n      const msg = 'Certificate verification error: ' +\n        `The public key of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // Pin the exact certificate, rather than the pub key\n    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +\n      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';\n    if (cert.fingerprint256 !== cert256) {\n      const msg = 'Certificate verification error: ' +\n        `The certificate of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // This loop is informational only.\n    // Print the certificate and public key fingerprints of all certs in the\n    // chain. Its common to pin the public key of the issuer on the public\n    // internet, while pinning the public key of the service in sensitive\n    // environments.\n    do {\n      console.log('Subject Common Name:', cert.subject.CN);\n      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);\n\n      hash = crypto.createHash('sha256');\n      console.log('  Public key ping-sha256:', sha256(cert.pubkey));\n\n      lastprint256 = cert.fingerprint256;\n      cert = cert.issuerCertificate;\n    } while (cert.fingerprint256 !== lastprint256);\n\n  },\n};\n\noptions.agent = new https.Agent(options);\nconst req = https.request(options, (res) => {\n  console.log('All OK. Server matched our pinned cert or public key');\n  console.log('statusCode:', res.statusCode);\n  // Print the HPKP values\n  console.log('headers:', res.headers['public-key-pins']);\n\n  res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n  console.error(e.message);\n});\nreq.end();\n
      \n

      Outputs for example:

      \n
      Subject Common Name: github.com\n  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16\n  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\nSubject Common Name: DigiCert SHA2 Extended Validation Server CA\n  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A\n  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\nSubject Common Name: DigiCert High Assurance EV Root CA\n  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF\n  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\nheaders: max-age=0; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\"; pin-sha256=\"k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=\"; pin-sha256=\"K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=\"; pin-sha256=\"IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=\"; pin-sha256=\"iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0=\"; pin-sha256=\"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=\"; includeSubDomains\n
      " + } + ], + "properties": [ + { + "textRaw": "`https.globalAgent`", + "name": "globalAgent", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "desc": "

      Global instance of https.Agent for all HTTPS client requests.

      " + } + ], + "type": "module", + "displayName": "HTTPS" + }, + { + "textRaw": "Inspector", + "name": "inspector", + "introduced_in": "v8.0.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/inspector.js

      \n

      The inspector module provides an API for interacting with the V8 inspector.

      \n

      It can be accessed using:

      \n
      const inspector = require('inspector');\n
      ", + "methods": [ + { + "textRaw": "`inspector.close()`", + "type": "method", + "name": "close", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Deactivate the inspector. Blocks until there are no active connections.

      " + }, + { + "textRaw": "`inspector.open([port[, host[, wait]]])`", + "type": "method", + "name": "open", + "signatures": [ + { + "params": [ + { + "textRaw": "`port` {number} Port to listen on for inspector connections. Optional. **Default:** what was specified on the CLI.", + "name": "port", + "type": "number", + "default": "what was specified on the CLI", + "desc": "Port to listen on for inspector connections. Optional." + }, + { + "textRaw": "`host` {string} Host to listen on for inspector connections. Optional. **Default:** what was specified on the CLI.", + "name": "host", + "type": "string", + "default": "what was specified on the CLI", + "desc": "Host to listen on for inspector connections. Optional." + }, + { + "textRaw": "`wait` {boolean} Block until a client has connected. Optional. **Default:** `false`.", + "name": "wait", + "type": "boolean", + "default": "`false`", + "desc": "Block until a client has connected. Optional." + } + ] + } + ], + "desc": "

      Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programmatically after node has\nstarted.

      \n

      If wait is true, will block until a client has connected to the inspect port\nand flow control has been passed to the debugger client.

      \n

      See the security warning regarding the host\nparameter usage.

      " + }, + { + "textRaw": "`inspector.url()`", + "type": "method", + "name": "url", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|undefined}", + "name": "return", + "type": "string|undefined" + }, + "params": [] + } + ], + "desc": "

      Return the URL of the active inspector, or undefined if there is none.

      \n
      $ node --inspect -p 'inspector.url()'\nDebugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34\nFor help see https://nodejs.org/en/docs/inspector\nws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34\n\n$ node --inspect=localhost:3000 -p 'inspector.url()'\nDebugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a\nFor help see https://nodejs.org/en/docs/inspector\nws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a\n\n$ node -p 'inspector.url()'\nundefined\n
      " + }, + { + "textRaw": "`inspector.waitForDebugger()`", + "type": "method", + "name": "waitForDebugger", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Blocks until a client (existing or connected later) has sent\nRuntime.runIfWaitingForDebugger command.

      \n

      An exception will be thrown if there is no active inspector.

      " + } + ], + "properties": [ + { + "textRaw": "`console` {Object} An object to send messages to the remote inspector console.", + "type": "Object", + "name": "console", + "desc": "
      require('inspector').console.log('a message');\n
      \n

      The inspector console does not have API parity with Node.js\nconsole.

      ", + "shortDesc": "An object to send messages to the remote inspector console." + } + ], + "classes": [ + { + "textRaw": "Class: `inspector.Session`", + "type": "class", + "name": "inspector.Session", + "desc": "\n

      The inspector.Session is used for dispatching messages to the V8 inspector\nback-end and receiving message responses and notifications.

      ", + "events": [ + { + "textRaw": "Event: `'inspectorNotification'`", + "type": "event", + "name": "inspectorNotification", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Object} The notification message object", + "type": "Object", + "desc": "The notification message object" + } + ], + "desc": "

      Emitted when any notification from the V8 Inspector is received.

      \n
      session.on('inspectorNotification', (message) => console.log(message.method));\n// Debugger.paused\n// Debugger.resumed\n
      \n

      It is also possible to subscribe only to notifications with specific method:

      " + }, + { + "textRaw": "Event: ``;", + "type": "event", + "name": "`;", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Object} The notification message object", + "type": "Object", + "desc": "The notification message object" + } + ], + "desc": "

      Emitted when an inspector notification is received that has its method field set\nto the <inspector-protocol-method> value.

      \n

      The following snippet installs a listener on the 'Debugger.paused'\nevent, and prints the reason for program suspension whenever program\nexecution is suspended (through breakpoints, for example):

      \n
      session.on('Debugger.paused', ({ params }) => {\n  console.log(params.hitBreakpoints);\n});\n// [ '/the/file/that/has/the/breakpoint.js:11:0' ]\n
      " + } + ], + "methods": [ + { + "textRaw": "`session.connect()`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Connects a session to the inspector back-end.

      " + }, + { + "textRaw": "`session.connectToMainThread()`", + "type": "method", + "name": "connectToMainThread", + "meta": { + "added": [ + "v12.11.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Connects a session to the main thread inspector back-end. An exception will\nbe thrown if this API was not called on a Worker thread.

      " + }, + { + "textRaw": "`session.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Immediately close the session. All pending message callbacks will be called\nwith an error. session.connect() will need to be called to be able to send\nmessages again. Reconnected session will lose all inspector state, such as\nenabled agents or configured breakpoints.

      " + }, + { + "textRaw": "`session.post(method[, params][, callback])`", + "type": "method", + "name": "post", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`method` {string}", + "name": "method", + "type": "string" + }, + { + "textRaw": "`params` {Object}", + "name": "params", + "type": "Object" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Posts a message to the inspector back-end. callback will be notified when\na response is received. callback is a function that accepts two optional\narguments: error and message-specific result.

      \n
      session.post('Runtime.evaluate', { expression: '2 + 2' },\n             (error, { result }) => console.log(result));\n// Output: { type: 'number', value: 4, description: '4' }\n
      \n

      The latest version of the V8 inspector protocol is published on the\nChrome DevTools Protocol Viewer.

      \n

      Node.js inspector supports all the Chrome DevTools Protocol domains declared\nby V8. Chrome DevTools Protocol domain provides an interface for interacting\nwith one of the runtime agents used to inspect the application state and listen\nto the run-time events.

      \n

      Example usage

      \n

      Apart from the debugger, various V8 Profilers are available through the DevTools\nprotocol.

      " + } + ], + "modules": [ + { + "textRaw": "CPU profiler", + "name": "cpu_profiler", + "desc": "

      Here's an example showing how to use the CPU Profiler:

      \n
      const inspector = require('inspector');\nconst fs = require('fs');\nconst session = new inspector.Session();\nsession.connect();\n\nsession.post('Profiler.enable', () => {\n  session.post('Profiler.start', () => {\n    // Invoke business logic under measurement here...\n\n    // some time later...\n    session.post('Profiler.stop', (err, { profile }) => {\n      // Write profile to disk, upload, etc.\n      if (!err) {\n        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));\n      }\n    });\n  });\n});\n
      ", + "type": "module", + "displayName": "CPU profiler" + }, + { + "textRaw": "Heap profiler", + "name": "heap_profiler", + "desc": "

      Here's an example showing how to use the Heap Profiler:

      \n
      const inspector = require('inspector');\nconst fs = require('fs');\nconst session = new inspector.Session();\n\nconst fd = fs.openSync('profile.heapsnapshot', 'w');\n\nsession.connect();\n\nsession.on('HeapProfiler.addHeapSnapshotChunk', (m) => {\n  fs.writeSync(fd, m.params.chunk);\n});\n\nsession.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {\n  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);\n  session.disconnect();\n  fs.closeSync(fd);\n});\n
      ", + "type": "module", + "displayName": "Heap profiler" + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Create a new instance of the inspector.Session class. The inspector session\nneeds to be connected through session.connect() before the messages\ncan be dispatched to the inspector backend.

      " + } + ] + } + ], + "type": "module", + "displayName": "Inspector" + }, + { + "textRaw": "Modules: CommonJS modules", + "name": "module", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      In the Node.js module system, each file is treated as a separate module. For\nexample, consider a file named foo.js:

      \n
      const circle = require('./circle.js');\nconsole.log(`The area of a circle of radius 4 is ${circle.area(4)}`);\n
      \n

      On the first line, foo.js loads the module circle.js that is in the same\ndirectory as foo.js.

      \n

      Here are the contents of circle.js:

      \n
      const { PI } = Math;\n\nexports.area = (r) => PI * r ** 2;\n\nexports.circumference = (r) => 2 * PI * r;\n
      \n

      The module circle.js has exported the functions area() and\ncircumference(). Functions and objects are added to the root of a module\nby specifying additional properties on the special exports object.

      \n

      Variables local to the module will be private, because the module is wrapped\nin a function by Node.js (see module wrapper).\nIn this example, the variable PI is private to circle.js.

      \n

      The module.exports property can be assigned a new value (such as a function\nor object).

      \n

      Below, bar.js makes use of the square module, which exports a Square class:

      \n
      const Square = require('./square.js');\nconst mySquare = new Square(2);\nconsole.log(`The area of mySquare is ${mySquare.area()}`);\n
      \n

      The square module is defined in square.js:

      \n
      // Assigning to exports will not modify module, must use module.exports\nmodule.exports = class Square {\n  constructor(width) {\n    this.width = width;\n  }\n\n  area() {\n    return this.width ** 2;\n  }\n};\n
      \n

      The module system is implemented in the require('module') module.

      ", + "miscs": [ + { + "textRaw": "Accessing the main module", + "name": "Accessing the main module", + "type": "misc", + "desc": "

      When a file is run directly from Node.js, require.main is set to its\nmodule. That means that it is possible to determine whether a file has been\nrun directly by testing require.main === module.

      \n

      For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').

      \n

      Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.

      " + }, + { + "textRaw": "Addenda: Package manager tips", + "name": "Addenda: Package manager tips", + "type": "misc", + "desc": "

      The semantics of the Node.js require() function were designed to be general\nenough to support reasonable directory structures. Package manager programs\nsuch as dpkg, rpm, and npm will hopefully find it possible to build\nnative packages from Node.js modules without modification.

      \n

      Below we give a suggested directory structure that could work:

      \n

      Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.

      \n

      Packages can depend on one another. In order to install package foo, it\nmay be necessary to install a specific version of package bar. The bar\npackage may itself have dependencies, and in some cases, these may even collide\nor form cyclic dependencies.

      \n

      Because Node.js looks up the realpath of any modules it loads (that is, it\nresolves symlinks) and then looks for their dependencies in node_modules folders,\nthis situation can be resolved with the following architecture:

      \n
        \n
      • /usr/lib/node/foo/1.2.3/: Contents of the foo package, version 1.2.3.
      • \n
      • /usr/lib/node/bar/4.3.2/: Contents of the bar package that foo depends\non.
      • \n
      • /usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to\n/usr/lib/node/bar/4.3.2/.
      • \n
      • /usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages that\nbar depends on.
      • \n
      \n

      Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.

      \n

      When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.

      \n

      Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then Node.js will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.

      \n

      In order to make modules available to the Node.js REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.

      " + }, + { + "textRaw": "All together...", + "name": "All together...", + "type": "misc", + "desc": "

      To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.

      \n

      Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require() does:

      \n
      require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with '/'\n   a. set Y to be the filesystem root\n3. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n   c. THROW \"not found\"\n4. If X begins with '#'\n   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))\n5. LOAD_PACKAGE_SELF(X, dirname(Y))\n6. LOAD_NODE_MODULES(X, dirname(Y))\n7. THROW \"not found\"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as its file extension format. STOP\n2. If X.js is a file, load X.js as JavaScript text. STOP\n3. If X.json is a file, parse X.json to a JavaScript Object. STOP\n4. If X.node is a file, load X.node as binary addon. STOP\n\nLOAD_INDEX(X)\n1. If X/index.js is a file, load X/index.js as JavaScript text. STOP\n2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n3. If X/index.node is a file, load X/index.node as binary addon. STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for \"main\" field.\n   b. If \"main\" is a falsy value, GOTO 2.\n   c. let M = X + (json main field)\n   d. LOAD_AS_FILE(M)\n   e. LOAD_INDEX(M)\n   f. LOAD_INDEX(X) DEPRECATED\n   g. THROW \"not found\"\n2. LOAD_INDEX(X)\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS = NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_PACKAGE_EXPORTS(X, DIR)\n   b. LOAD_AS_FILE(DIR/X)\n   c. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = [GLOBAL_FOLDERS]\n4. while I >= 0,\n   a. if PARTS[I] = \"node_modules\" CONTINUE\n   b. DIR = path join(PARTS[0 .. I] + \"node_modules\")\n   c. DIRS = DIRS + DIR\n   d. let I = I - 1\n5. return DIRS\n\nLOAD_PACKAGE_IMPORTS(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"imports\" is null or undefined, return.\n4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),\n  [\"node\", \"require\"]) defined in the ESM resolver.\n5. RESOLVE_ESM_MATCH(MATCH).\n\nLOAD_PACKAGE_EXPORTS(X, DIR)\n1. Try to interpret X as a combination of NAME and SUBPATH where the name\n   may have a @scope/ prefix and the subpath begins with a slash (`/`).\n2. If X does not match this pattern or DIR/NAME/package.json is not a file,\n   return.\n3. Parse DIR/NAME/package.json, and look for \"exports\" field.\n4. If \"exports\" is null or undefined, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), \".\" + SUBPATH,\n   `package.json` \"exports\", [\"node\", \"require\"]) defined in the ESM resolver.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nLOAD_PACKAGE_SELF(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"exports\" is null or undefined, return.\n4. If the SCOPE/package.json \"name\" is not the first segment of X, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),\n   \".\" + X.slice(\"name\".length), `package.json` \"exports\", [\"node\", \"require\"])\n   defined in the ESM resolver.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nRESOLVE_ESM_MATCH(MATCH)\n1. let { RESOLVED, EXACT } = MATCH\n2. let RESOLVED_PATH = fileURLToPath(RESOLVED)\n3. If EXACT is true,\n   a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension\n      format. STOP\n4. Otherwise, if EXACT is false,\n   a. LOAD_AS_FILE(RESOLVED_PATH)\n   b. LOAD_AS_DIRECTORY(RESOLVED_PATH)\n5. THROW \"not found\"\n
      " + }, + { + "textRaw": "Caching", + "name": "Caching", + "type": "misc", + "desc": "

      Modules are cached after the first time they are loaded. This means (among other\nthings) that every call to require('foo') will get exactly the same object\nreturned, if it would resolve to the same file.

      \n

      Provided require.cache is not modified, multiple calls to require('foo')\nwill not cause the module code to be executed multiple times. This is an\nimportant feature. With it, \"partially done\" objects can be returned, thus\nallowing transitive dependencies to be loaded even when they would cause cycles.

      \n

      To have a module execute code multiple times, export a function, and call that\nfunction.

      ", + "miscs": [ + { + "textRaw": "Module caching caveats", + "name": "Module caching caveats", + "type": "misc", + "desc": "

      Modules are cached based on their resolved filename. Since modules may resolve\nto a different filename based on the location of the calling module (loading\nfrom node_modules folders), it is not a guarantee that require('foo') will\nalways return the exact same object, if it would resolve to different files.

      \n

      Additionally, on case-insensitive file systems or operating systems, different\nresolved filenames can point to the same file, but the cache will still treat\nthem as different modules and will reload the file multiple times. For example,\nrequire('./foo') and require('./FOO') return two different objects,\nirrespective of whether or not ./foo and ./FOO are the same file.

      " + } + ] + }, + { + "textRaw": "Core modules", + "name": "Core modules", + "type": "misc", + "desc": "

      Node.js has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.

      \n

      The core modules are defined within the Node.js source and are located in the\nlib/ folder.

      \n

      Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.

      " + }, + { + "textRaw": "Cycles", + "name": "Cycles", + "type": "misc", + "desc": "

      When there are circular require() calls, a module might not have finished\nexecuting when it is returned.

      \n

      Consider this situation:

      \n

      a.js:

      \n
      console.log('a starting');\nexports.done = false;\nconst b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');\n
      \n

      b.js:

      \n
      console.log('b starting');\nexports.done = false;\nconst a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');\n
      \n

      main.js:

      \n
      console.log('main starting');\nconst a = require('./a.js');\nconst b = require('./b.js');\nconsole.log('in main, a.done = %j, b.done = %j', a.done, b.done);\n
      \n

      When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop, an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.

      \n

      By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:

      \n
      $ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done = true, b.done = true\n
      \n

      Careful planning is required to allow cyclic module dependencies to work\ncorrectly within an application.

      " + }, + { + "textRaw": "File modules", + "name": "File modules", + "type": "misc", + "desc": "

      If the exact filename is not found, then Node.js will attempt to load the\nrequired filename with the added extensions: .js, .json, and finally\n.node.

      \n

      .js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with process.dlopen().

      \n

      A required module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.

      \n

      A required module prefixed with './' is relative to the file calling\nrequire(). That is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.

      \n

      Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules folder.

      \n

      If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.

      " + }, + { + "textRaw": "Folders as modules", + "name": "Folders as modules", + "type": "misc", + "desc": "

      It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to those directories.\nThere are three ways in which a folder may be passed to require() as\nan argument.

      \n

      The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:

      \n
      { \"name\" : \"some-library\",\n  \"main\" : \"./lib/some-library.js\" }\n
      \n

      If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.

      \n

      This is the extent of the awareness of package.json files within Node.js.

      \n

      If there is no package.json file present in the directory, or if the\n\"main\" entry is missing or cannot be resolved, then Node.js\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the previous\nexample, then require('./some-library') would attempt to load:

      \n
        \n
      • ./some-library/index.js
      • \n
      • ./some-library/index.node
      • \n
      \n

      If these attempts fail, then Node.js will report the entire module as missing\nwith the default error:

      \n
      Error: Cannot find module 'some-library'\n
      " + }, + { + "textRaw": "Loading from `node_modules` folders", + "name": "Loading from `node_modules` folders", + "type": "misc", + "desc": "

      If the module identifier passed to require() is not a\ncore module, and does not begin with '/', '../', or\n'./', then Node.js starts at the parent directory of the current module, and\nadds /node_modules, and attempts to load the module from that location.\nNode.js will not append node_modules to a path already ending in\nnode_modules.

      \n

      If it is not found there, then it moves to the parent directory, and so\non, until the root of the file system is reached.

      \n

      For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then Node.js would look in the following locations, in\nthis order:

      \n
        \n
      • /home/ry/projects/node_modules/bar.js
      • \n
      • /home/ry/node_modules/bar.js
      • \n
      • /home/node_modules/bar.js
      • \n
      • /node_modules/bar.js
      • \n
      \n

      This allows programs to localize their dependencies, so that they do not\nclash.

      \n

      It is possible to require specific files or sub modules distributed with a\nmodule by including a path suffix after the module name. For instance\nrequire('example-module/path/to/file') would resolve path/to/file\nrelative to where example-module is located. The suffixed path follows the\nsame module resolution semantics.

      " + }, + { + "textRaw": "Loading from the global folders", + "name": "Loading from the global folders", + "type": "misc", + "desc": "

      If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then Node.js will search those paths for modules if they\nare not found elsewhere.

      \n

      On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

      \n

      NODE_PATH was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was defined.

      \n

      NODE_PATH is still supported, but is less necessary now that the Node.js\necosystem has settled on a convention for locating dependent modules.\nSometimes deployments that rely on NODE_PATH show surprising behavior\nwhen people are unaware that NODE_PATH must be set. Sometimes a\nmodule's dependencies change, causing a different version (or even a\ndifferent module) to be loaded as the NODE_PATH is searched.

      \n

      Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

      \n
        \n
      • 1: $HOME/.node_modules
      • \n
      • 2: $HOME/.node_libraries
      • \n
      • 3: $PREFIX/lib/node
      • \n
      \n

      Where $HOME is the user's home directory, and $PREFIX is the Node.js\nconfigured node_prefix.

      \n

      These are mostly for historic reasons.

      \n

      It is strongly encouraged to place dependencies in the local node_modules\nfolder. These will be loaded faster, and more reliably.

      " + }, + { + "textRaw": "The module wrapper", + "name": "The module wrapper", + "type": "misc", + "desc": "

      Before a module's code is executed, Node.js will wrap it with a function\nwrapper that looks like the following:

      \n
      (function(exports, require, module, __filename, __dirname) {\n// Module code actually lives in here\n});\n
      \n

      By doing this, Node.js achieves a few things:

      \n
        \n
      • It keeps top-level variables (defined with var, const or let) scoped to\nthe module rather than the global object.
      • \n
      • It helps to provide some global-looking variables that are actually specific\nto the module, such as:\n
          \n
        • The module and exports objects that the implementor can use to export\nvalues from the module.
        • \n
        • The convenience variables __filename and __dirname, containing the\nmodule's absolute filename and directory path.
        • \n
        \n
      • \n
      " + } + ], + "modules": [ + { + "textRaw": "Addenda: The `.mjs` extension", + "name": "addenda:_the_`.mjs`_extension", + "desc": "

      It is not possible to require() files that have the .mjs extension.\nAttempting to do so will throw an error. The .mjs extension is\nreserved for ECMAScript Modules which cannot be loaded via require().\nSee ECMAScript Modules for more details.

      ", + "type": "module", + "displayName": "Addenda: The `.mjs` extension" + }, + { + "textRaw": "The module scope", + "name": "the_module_scope", + "vars": [ + { + "textRaw": "`__dirname`", + "name": "`__dirname`", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      The directory name of the current module. This is the same as the\npath.dirname() of the __filename.

      \n

      Example: running node example.js from /Users/mjr

      \n
      console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
      " + }, + { + "textRaw": "`__filename`", + "name": "`__filename`", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      The file name of the current module. This is the current module file's absolute\npath with symlinks resolved.

      \n

      For a main program this is not necessarily the same as the file name used in the\ncommand line.

      \n

      See __dirname for the directory name of the current module.

      \n

      Examples:

      \n

      Running node example.js from /Users/mjr

      \n
      console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
      \n

      Given two modules: a and b, where b is a dependency of\na and there is a directory structure of:

      \n
        \n
      • /Users/mjr/app/a.js
      • \n
      • /Users/mjr/app/node_modules/b/b.js
      • \n
      \n

      References to __filename within b.js will return\n/Users/mjr/app/node_modules/b/b.js while references to __filename within\na.js will return /Users/mjr/app/a.js.

      " + }, + { + "textRaw": "`exports`", + "name": "`exports`", + "meta": { + "added": [ + "v0.1.12" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      A reference to the module.exports that is shorter to type.\nSee the section about the exports shortcut for details on when to use\nexports and when to use module.exports.

      " + }, + { + "textRaw": "`module`", + "name": "`module`", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      A reference to the current module, see the section about the\nmodule object. In particular, module.exports is used for defining what\na module exports and makes available through require().

      " + }, + { + "textRaw": "`require(id)`", + "type": "var", + "name": "require", + "meta": { + "added": [ + "v0.1.13" + ], + "changes": [] + }, + "desc": "
        \n
      • id <string> module name or path
      • \n
      • Returns: <any> exported module content
      • \n
      \n

      Used to import modules, JSON, and local files. Modules can be imported\nfrom node_modules. Local modules and JSON files can be imported using\na relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be\nresolved against the directory named by __dirname (if defined) or\nthe current working directory. The relative paths of POSIX style are resolved\nin an OS independent fashion, meaning that the examples above will work on\nWindows in the same way they would on Unix systems.

      \n
      // Importing a local module with a path relative to the `__dirname` or current\n// working directory. (On Windows, this would resolve to .\\path\\myLocalModule.)\nconst myLocalModule = require('./path/myLocalModule');\n\n// Importing a JSON file:\nconst jsonData = require('./path/filename.json');\n\n// Importing a module from node_modules or Node.js built-in module:\nconst crypto = require('crypto');\n
      ", + "properties": [ + { + "textRaw": "`cache` {Object}", + "type": "Object", + "name": "cache", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\nThis does not apply to native addons, for which reloading will result in an\nerror.

      \n

      Adding or replacing entries is also possible. This cache is checked before\nnative modules and if a name matching a native module is added to the cache,\nno require call is\ngoing to receive the native module anymore. Use with care!

      " + }, + { + "textRaw": "`extensions` {Object}", + "type": "Object", + "name": "extensions", + "meta": { + "added": [ + "v0.3.0" + ], + "deprecated": [ + "v0.10.6" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Instruct require on how to handle certain file extensions.

      \n

      Process files with the extension .sjs as .js:

      \n
      require.extensions['.sjs'] = require.extensions['.js'];\n
      \n

      Deprecated. In the past, this list has been used to load non-JavaScript\nmodules into Node.js by compiling them on-demand. However, in practice, there\nare much better ways to do this, such as loading modules via some other Node.js\nprogram, or compiling them to JavaScript ahead of time.

      \n

      Avoid using require.extensions. Use could cause subtle bugs and resolving the\nextensions gets slower with each registered extension.

      " + }, + { + "textRaw": "`main` {module}", + "type": "module", + "name": "main", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "

      The Module object representing the entry script loaded when the Node.js\nprocess launched.\nSee \"Accessing the main module\".

      \n

      In entry.js script:

      \n
      console.log(require.main);\n
      \n
      node entry.js\n
      \n\n
      Module {\n  id: '.',\n  path: '/absolute/path/to',\n  exports: {},\n  parent: null,\n  filename: '/absolute/path/to/entry.js',\n  loaded: false,\n  children: [],\n  paths:\n   [ '/absolute/path/to/node_modules',\n     '/absolute/path/node_modules',\n     '/absolute/node_modules',\n     '/node_modules' ] }\n
      " + } + ], + "methods": [ + { + "textRaw": "`require.resolve(request[, options])`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v8.9.0", + "pr-url": "https://github.com/nodejs/node/pull/16397", + "description": "The `paths` option is now supported." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`request` {string} The module path to resolve.", + "name": "request", + "type": "string", + "desc": "The module path to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`paths` {string[]} Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location.", + "name": "paths", + "type": "string[]", + "desc": "Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location." + } + ] + } + ] + } + ], + "desc": "

      Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.

      \n

      If the module can not be found, a MODULE_NOT_FOUND error is thrown.

      ", + "methods": [ + { + "textRaw": "`require.resolve.paths(request)`", + "type": "method", + "name": "paths", + "meta": { + "added": [ + "v8.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]|null}", + "name": "return", + "type": "string[]|null" + }, + "params": [ + { + "textRaw": "`request` {string} The module path whose lookup paths are being retrieved.", + "name": "request", + "type": "string", + "desc": "The module path whose lookup paths are being retrieved." + } + ] + } + ], + "desc": "

      Returns an array containing the paths searched during resolution of request or\nnull if the request string references a core module, for example http or\nfs.

      " + } + ] + } + ] + } + ], + "type": "module", + "displayName": "The module scope" + }, + { + "textRaw": "The `Module` object", + "name": "the_`module`_object", + "desc": "

      This section was moved to\nModules: module core module.

      \n\n", + "type": "module", + "displayName": "The `Module` object" + }, + { + "textRaw": "Source map v3 support", + "name": "source_map_v3_support", + "desc": "

      This section was moved to\nModules: module core module.

      \n\n", + "type": "module", + "displayName": "Source map v3 support" + } + ], + "vars": [ + { + "textRaw": "The `module` object", + "name": "module", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module is not actually\na global but rather local to each module.

      ", + "properties": [ + { + "textRaw": "`children` {module[]}", + "type": "module[]", + "name": "children", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The module objects required for the first time by this one.

      " + }, + { + "textRaw": "`exports` {Object}", + "type": "Object", + "name": "exports", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The module.exports object is created by the Module system. Sometimes this is\nnot acceptable; many want their module to be an instance of some class. To do\nthis, assign the desired export object to module.exports. Assigning\nthe desired object to exports will simply rebind the local exports variable,\nwhich is probably not what is desired.

      \n

      For example, suppose we were making a module called a.js:

      \n
      const EventEmitter = require('events');\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(() => {\n  module.exports.emit('ready');\n}, 1000);\n
      \n

      Then in another file we could do:

      \n
      const a = require('./a');\na.on('ready', () => {\n  console.log('module \"a\" is ready');\n});\n
      \n

      Assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:

      \n

      x.js:

      \n
      setTimeout(() => {\n  module.exports = { a: 'hello' };\n}, 0);\n
      \n

      y.js:

      \n
      const x = require('./x');\nconsole.log(x.a);\n
      ", + "modules": [ + { + "textRaw": "`exports` shortcut", + "name": "`exports`_shortcut", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The exports variable is available within a module's file-level scope, and is\nassigned the value of module.exports before the module is evaluated.

      \n

      It allows a shortcut, so that module.exports.f = ... can be written more\nsuccinctly as exports.f = .... However, be aware that like any variable, if a\nnew value is assigned to exports, it is no longer bound to module.exports:

      \n
      module.exports.hello = true; // Exported from require of module\nexports = { hello: false };  // Not exported, only available in the module\n
      \n

      When the module.exports property is being completely replaced by a new\nobject, it is common to also reassign exports:

      \n\n
      module.exports = exports = function Constructor() {\n  // ... etc.\n};\n
      \n

      To illustrate the behavior, imagine this hypothetical implementation of\nrequire(), which is quite similar to what is actually done by require():

      \n
      function require(/* ... */) {\n  const module = { exports: {} };\n  ((module, exports) => {\n    // Module code here. In this example, define a function.\n    function someFunc() {}\n    exports = someFunc;\n    // At this point, exports is no longer a shortcut to module.exports, and\n    // this module will still export an empty default object.\n    module.exports = someFunc;\n    // At this point, the module will now export someFunc, instead of the\n    // default object.\n  })(module, module.exports);\n  return module.exports;\n}\n
      ", + "type": "module", + "displayName": "`exports` shortcut" + } + ] + }, + { + "textRaw": "`filename` {string}", + "type": "string", + "name": "filename", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The fully resolved filename of the module.

      " + }, + { + "textRaw": "`id` {string}", + "type": "string", + "name": "id", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The identifier for the module. Typically this is the fully resolved\nfilename.

      " + }, + { + "textRaw": "`loaded` {boolean}", + "type": "boolean", + "name": "loaded", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      Whether or not the module is done loading, or is in the process of\nloading.

      " + }, + { + "textRaw": "`parent` {module | null | undefined}", + "type": "module | null | undefined", + "name": "parent", + "meta": { + "added": [ + "v0.1.16" + ], + "deprecated": [ + "v12.19.0", + "v14.6.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Please use [`require.main`][] and\n[`module.children`][] instead.", + "desc": "

      The module that first required this one, or null if the current module is the\nentry point of the current process, or undefined if the module was loaded by\nsomething that is not a CommonJS module (E.G.: REPL or import).

      " + }, + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "meta": { + "added": [ + "v11.14.0" + ], + "changes": [] + }, + "desc": "

      The directory name of the module. This is usually the same as the\npath.dirname() of the module.id.

      " + }, + { + "textRaw": "`paths` {string[]}", + "type": "string[]", + "name": "paths", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "desc": "

      The search paths for the module.

      " + } + ], + "methods": [ + { + "textRaw": "`module.require(id)`", + "type": "method", + "name": "require", + "meta": { + "added": [ + "v0.5.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} exported module content", + "name": "return", + "type": "any", + "desc": "exported module content" + }, + "params": [ + { + "textRaw": "`id` {string}", + "name": "id", + "type": "string" + } + ] + } + ], + "desc": "

      The module.require() method provides a way to load a module as if\nrequire() was called from the original module.

      \n

      In order to do this, it is necessary to get a reference to the module object.\nSince require() returns the module.exports, and the module is typically\nonly available within a specific module's code, it must be explicitly exported\nin order to be used.

      " + } + ] + } + ], + "type": "module", + "displayName": "module" + }, + { + "textRaw": "Modules: `module` API", + "name": "modules:_`module`_api", + "introduced_in": "v0.3.7", + "modules": [ + { + "textRaw": "The `Module` object", + "name": "the_`module`_object", + "desc": "\n

      Provides general utility methods when interacting with instances of\nModule, the module variable often seen in CommonJS modules. Accessed\nvia import 'module' or require('module').

      ", + "properties": [ + { + "textRaw": "`builtinModules` {string[]}", + "type": "string[]", + "name": "builtinModules", + "meta": { + "added": [ + "v9.3.0", + "v8.10.0", + "v6.13.0" + ], + "changes": [] + }, + "desc": "

      A list of the names of all modules provided by Node.js. Can be used to verify\nif a module is maintained by a third party or not.

      \n

      module in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:

      \n
      // module.mjs\n// In an ECMAScript module\nimport { builtinModules as builtin } from 'module';\n
      \n
      // module.cjs\n// In a CommonJS module\nconst builtin = require('module').builtinModules;\n
      " + } + ], + "methods": [ + { + "textRaw": "`module.createRequire(filename)`", + "type": "method", + "name": "createRequire", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {require} Require function", + "name": "return", + "type": "require", + "desc": "Require function" + }, + "params": [ + { + "textRaw": "`filename` {string|URL} Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.", + "name": "filename", + "type": "string|URL", + "desc": "Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string." + } + ] + } + ], + "desc": "
      import { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\n\n// sibling-module.js is a CommonJS module.\nconst siblingModule = require('./sibling-module');\n
      " + }, + { + "textRaw": "`module.createRequireFromPath(filename)`", + "type": "method", + "name": "createRequireFromPath", + "meta": { + "added": [ + "v10.12.0" + ], + "deprecated": [ + "v12.2.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Please use [`createRequire()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {require} Require function", + "name": "return", + "type": "require", + "desc": "Require function" + }, + "params": [ + { + "textRaw": "`filename` {string} Filename to be used to construct the relative require function.", + "name": "filename", + "type": "string", + "desc": "Filename to be used to construct the relative require function." + } + ] + } + ], + "desc": "
      const { createRequireFromPath } = require('module');\nconst requireUtil = createRequireFromPath('../src/utils/');\n\n// Require `../src/utils/some-tool`\nrequireUtil('./some-tool');\n
      " + }, + { + "textRaw": "`module.syncBuiltinESMExports()`", + "type": "method", + "name": "syncBuiltinESMExports", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The module.syncBuiltinESMExports() method updates all the live bindings for\nbuiltin ES Modules to match the properties of the CommonJS exports. It\ndoes not add or remove exported names from the ES Modules.

      \n
      const fs = require('fs');\nconst { syncBuiltinESMExports } = require('module');\n\nfs.readFile = null;\n\ndelete fs.readFileSync;\n\nfs.newAPI = function newAPI() {\n  // ...\n};\n\nsyncBuiltinESMExports();\n\nimport('fs').then((esmFS) => {\n  assert.strictEqual(esmFS.readFile, null);\n  assert.strictEqual('readFileSync' in fs, true);\n  assert.strictEqual(esmFS.newAPI, undefined);\n});\n
      " + } + ], + "type": "module", + "displayName": "The `Module` object" + }, + { + "textRaw": "Source map v3 support", + "name": "source_map_v3_support", + "meta": { + "added": [ + "v13.7.0", + "v12.17.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Helpers for interacting with the source map cache. This cache is\npopulated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.

      \n

      To enable source map parsing, Node.js must be run with the flag\n--enable-source-maps, or with code coverage enabled by setting\nNODE_V8_COVERAGE=dir.

      \n
      // module.mjs\n// In an ECMAScript module\nimport { findSourceMap, SourceMap } from 'module';\n
      \n
      // module.cjs\n// In a CommonJS module\nconst { findSourceMap, SourceMap } = require('module');\n
      ", + "methods": [ + { + "textRaw": "`module.findSourceMap(path[, error])`", + "type": "method", + "name": "findSourceMap", + "meta": { + "added": [ + "v13.7.0", + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {module.SourceMap}", + "name": "return", + "type": "module.SourceMap" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + }, + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      path is the resolved path for the file for which a corresponding source map\nshould be fetched.

      \n

      The error instance should be passed as the second parameter to findSourceMap\nin exceptional flows, such as when an overridden\nError.prepareStackTrace(error, trace) is invoked. Modules are not added to\nthe module cache until they are successfully loaded. In these cases, source maps\nare associated with the error instance along with the path.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `module.SourceMap`", + "type": "class", + "name": "module.SourceMap", + "meta": { + "added": [ + "v13.7.0", + "v12.17.0" + ], + "changes": [] + }, + "properties": [ + { + "textRaw": "`payload` Returns: {Object}", + "type": "Object", + "name": "return", + "desc": "

      Getter for the payload used to construct the SourceMap instance.

      " + } + ], + "methods": [ + { + "textRaw": "`sourceMap.findEntry(lineNumber, columnNumber)`", + "type": "method", + "name": "findEntry", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`lineNumber` {number}", + "name": "lineNumber", + "type": "number" + }, + { + "textRaw": "`columnNumber` {number}", + "name": "columnNumber", + "type": "number" + } + ] + } + ], + "desc": "

      Given a line number and column number in the generated source file, returns\nan object representing the position in the original file. The object returned\nconsists of the following keys:

      \n" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`payload` {Object}", + "name": "payload", + "type": "Object" + } + ], + "desc": "

      Creates a new sourceMap instance.

      \n

      payload is an object with keys matching the Source map v3 format:

      \n" + } + ] + } + ], + "type": "module", + "displayName": "Source map v3 support" + } + ], + "type": "module", + "displayName": "Modules: `module` API" + }, + { + "textRaw": "Net", + "name": "net", + "introduced_in": "v0.10.0", + "desc": "\n
      \n

      Stability: 2 - Stable

      \n
      \n

      Source Code: lib/net.js

      \n

      The net module provides an asynchronous network API for creating stream-based\nTCP or IPC servers (net.createServer()) and clients\n(net.createConnection()).

      \n

      It can be accessed using:

      \n
      const net = require('net');\n
      ", + "modules": [ + { + "textRaw": "IPC support", + "name": "ipc_support", + "desc": "

      The net module supports IPC with named pipes on Windows, and Unix domain\nsockets on other operating systems.

      ", + "modules": [ + { + "textRaw": "Identifying paths for IPC connections", + "name": "identifying_paths_for_ipc_connections", + "desc": "

      net.connect(), net.createConnection(), server.listen() and\nsocket.connect() take a path parameter to identify IPC endpoints.

      \n

      On Unix, the local domain is also known as the Unix domain. The path is a\nfilesystem pathname. It gets truncated to an OS-dependent length of\nsizeof(sockaddr_un.sun_path) - 1. Typical values are 107 bytes on Linux and\n103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,\nit will unlink the Unix domain socket as well. For example,\nnet.createServer() may create a Unix domain socket and\nserver.close() will unlink it. But if a user creates the Unix domain\nsocket outside of these abstractions, the user will need to remove it. The same\napplies when a Node.js API creates a Unix domain socket but the program then\ncrashes. In short, a Unix domain socket will be visible in the filesystem and\nwill persist until unlinked.

      \n

      On Windows, the local domain is implemented using a named pipe. The path must\nrefer to an entry in \\\\?\\pipe\\ or \\\\.\\pipe\\. Any characters are permitted,\nbut the latter may do some processing of pipe names, such as resolving ..\nsequences. Despite how it might look, the pipe namespace is flat. Pipes will\nnot persist. They are removed when the last reference to them is closed.\nUnlike Unix domain sockets, Windows will close and remove the pipe when the\nowning process exits.

      \n

      JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:

      \n
      net.createServer().listen(\n  path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n
      ", + "type": "module", + "displayName": "Identifying paths for IPC connections" + } + ], + "type": "module", + "displayName": "IPC support" + } + ], + "classes": [ + { + "textRaw": "Class: `net.Server`", + "type": "class", + "name": "net.Server", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "\n

      This class is used to create a TCP or IPC server.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.

      " + }, + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{net.Socket} The connection object", + "type": "net.Socket", + "desc": "The connection object" + } + ], + "desc": "

      Emitted when a new connection is made. socket is an instance of\nnet.Socket.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      Emitted when an error occurs. Unlike net.Socket, the 'close'\nevent will not be emitted directly following this event unless\nserver.close() is manually called. See the example in discussion of\nserver.listen().

      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server has been bound after calling server.listen().

      " + } + ], + "methods": [ + { + "textRaw": "`server.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object|string|null}", + "name": "return", + "type": "Object|string|null" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name, and port of the server\nas reported by the operating system if listening on an IP socket\n(useful to find which port was assigned when getting an OS-assigned address):\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      \n

      For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.

      \n
      const server = net.createServer((socket) => {\n  socket.end('goodbye\\n');\n}).on('error', (err) => {\n  // Handle errors here.\n  throw err;\n});\n\n// Grab an arbitrary unused port.\nserver.listen(() => {\n  console.log('opened server on', server.address());\n});\n
      \n

      server.address() returns null before the 'listening' event has been\nemitted or after calling server.close().

      " + }, + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function} Called when the server is closed.", + "name": "callback", + "type": "Function", + "desc": "Called when the server is closed." + } + ] + } + ], + "desc": "

      Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally closed\nwhen all connections are ended and the server emits a 'close' event.\nThe optional callback will be called once the 'close' event occurs. Unlike\nthat event, it will be called with an Error as its only argument if the server\nwas not open when it was closed.

      " + }, + { + "textRaw": "`server.getConnections(callback)`", + "type": "method", + "name": "getConnections", + "meta": { + "added": [ + "v0.9.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.

      \n

      Callback should take two arguments err and count.

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.

      \n

      Possible signatures:

      \n\n

      This function is asynchronous. When the server starts listening, the\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.

      \n

      All listen() methods can take a backlog parameter to specify the maximum\nlength of the queue of pending connections. The actual length will be determined\nby the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn\non Linux. The default value of this parameter is 511 (not 512).

      \n

      All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).

      \n

      The server.listen() method can be called again if and only if there was an\nerror during the first server.listen() call or server.close() has been\ncalled. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      \n

      One of the most common errors raised when listening is EADDRINUSE.\nThis happens when another server is already listening on the requested\nport/path/handle. One way to handle this would be to retry\nafter a certain amount of time:

      \n
      server.on('error', (e) => {\n  if (e.code === 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(() => {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});\n
      ", + "methods": [ + { + "textRaw": "`server.listen(handle[, backlog][, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`handle` {Object}", + "name": "handle", + "type": "Object" + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Start a server listening for connections on a given handle that has\nalready been bound to a port, a Unix domain socket, or a Windows named pipe.

      \n

      The handle object can be either a server, a socket (anything with an\nunderlying _handle member), or an object with an fd member that is a\nvalid file descriptor.

      \n

      Listening on a file descriptor is not supported on Windows.

      " + }, + { + "textRaw": "`server.listen(options[, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/23798", + "description": "The `ipv6Only` option is supported." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`options` {Object} Required. Supports the following properties:", + "name": "options", + "type": "Object", + "desc": "Required. Supports the following properties:", + "options": [ + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`host` {string}", + "name": "host", + "type": "string" + }, + { + "textRaw": "`path` {string} Will be ignored if `port` is specified. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Will be ignored if `port` is specified. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions." + }, + { + "textRaw": "`exclusive` {boolean} **Default:** `false`", + "name": "exclusive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`readableAll` {boolean} For IPC servers makes the pipe readable for all users. **Default:** `false`.", + "name": "readableAll", + "type": "boolean", + "default": "`false`", + "desc": "For IPC servers makes the pipe readable for all users." + }, + { + "textRaw": "`writableAll` {boolean} For IPC servers makes the pipe writable for all users. **Default:** `false`.", + "name": "writableAll", + "type": "boolean", + "default": "`false`", + "desc": "For IPC servers makes the pipe writable for all users." + }, + { + "textRaw": "`ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound. **Default:** `false`.", + "name": "ipv6Only", + "type": "boolean", + "default": "`false`", + "desc": "For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound." + } + ] + }, + { + "textRaw": "`callback` {Function} functions.", + "name": "callback", + "type": "Function", + "desc": "functions." + } + ] + } + ], + "desc": "

      If port is specified, it behaves the same as\n\nserver.listen([port[, host[, backlog]]][, callback]).\nOtherwise, if path is specified, it behaves the same as\nserver.listen(path[, backlog][, callback]).\nIf none of them is specified, an error will be thrown.

      \n

      If exclusive is false (default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive is true, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.

      \n
      server.listen({\n  host: 'localhost',\n  port: 80,\n  exclusive: true\n});\n
      \n

      Starting an IPC server as root may cause the server path to be inaccessible for\nunprivileged users. Using readableAll and writableAll will make the server\naccessible for all users.

      " + }, + { + "textRaw": "`server.listen(path[, backlog][, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`path` {string} Path the server should listen to. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Path the server should listen to. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions." + }, + { + "textRaw": "`callback` {Function}.", + "name": "callback", + "type": "Function", + "desc": "." + } + ] + } + ], + "desc": "

      Start an IPC server listening for connections on the given path.

      " + }, + { + "textRaw": "`server.listen([port[, host[, backlog]]][, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`host` {string}", + "name": "host", + "type": "string" + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions." + }, + { + "textRaw": "`callback` {Function}.", + "name": "callback", + "type": "Function", + "desc": "." + } + ] + } + ], + "desc": "

      Start a TCP server listening for connections on the given port and host.

      \n

      If port is omitted or is 0, the operating system will assign an arbitrary\nunused port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.

      \n

      If host is omitted, the server will accept connections on the\nunspecified IPv6 address (::) when IPv6 is available, or the\nunspecified IPv4 address (0.0.0.0) otherwise.

      \n

      In most operating systems, listening to the unspecified IPv6 address (::)\nmay cause the net.Server to also listen on the unspecified IPv4 address\n(0.0.0.0).

      " + } + ] + }, + { + "textRaw": "`server.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [] + } + ], + "desc": "

      Opposite of unref(), calling ref() on a previously unrefed server will\nnot let the program exit if it's the only server left (the default behavior).\nIf the server is refed calling ref() again will have no effect.

      " + }, + { + "textRaw": "`server.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [] + } + ], + "desc": "

      Calling unref() on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefed calling\nunref() again will have no effect.

      " + } + ], + "properties": [ + { + "textRaw": "`connections` {integer|null}", + "type": "integer|null", + "name": "connections", + "meta": { + "added": [ + "v0.2.0" + ], + "deprecated": [ + "v0.9.7" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", + "desc": "

      The number of concurrent connections on the server.

      \n

      This becomes null when sending a socket to a child with\nchild_process.fork(). To poll forks and get current number of active\nconnections, use asynchronous server.getConnections() instead.

      " + }, + { + "textRaw": "`listening` {boolean} Indicates whether or not the server is listening for connections.", + "type": "boolean", + "name": "listening", + "meta": { + "added": [ + "v5.7.0" + ], + "changes": [] + }, + "desc": "Indicates whether or not the server is listening for connections." + }, + { + "textRaw": "`maxConnections` {integer}", + "type": "integer", + "name": "maxConnections", + "meta": { + "added": [ + "v0.2.0" + ], + "changes": [] + }, + "desc": "

      Set this property to reject connections when the server's connection count gets\nhigh.

      \n

      It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().

      " + } + ], + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`options` {Object} See [`net.createServer([options][, connectionListener])`][`net.createServer()`].", + "name": "options", + "type": "Object", + "desc": "See [`net.createServer([options][, connectionListener])`][`net.createServer()`]." + }, + { + "textRaw": "`connectionListener` {Function} Automatically set as a listener for the [`'connection'`][] event.", + "name": "connectionListener", + "type": "Function", + "desc": "Automatically set as a listener for the [`'connection'`][] event." + } + ], + "desc": "

      net.Server is an EventEmitter with the following events:

      " + } + ] + }, + { + "textRaw": "Class: `net.Socket`", + "type": "class", + "name": "net.Socket", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "desc": "\n

      This class is an abstraction of a TCP socket or a streaming IPC endpoint\n(uses named pipes on Windows, and Unix domain sockets otherwise). It is also\nan EventEmitter.

      \n

      A net.Socket can be created by the user and used directly to interact with\na server. For example, it is returned by net.createConnection(),\nso the user can use it to talk to the server.

      \n

      It can also be created by Node.js and passed to the user when a connection\nis received. For example, it is passed to the listeners of a\n'connection' event emitted on a net.Server, so the user can use\nit to interact with the client.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`hadError` {boolean} `true` if the socket had a transmission error.", + "name": "hadError", + "type": "boolean", + "desc": "`true` if the socket had a transmission error." + } + ], + "desc": "

      Emitted once the socket is fully closed. The argument hadError is a boolean\nwhich says if the socket was closed due to a transmission error.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when a socket connection is successfully established.\nSee net.createConnection().

      " + }, + { + "textRaw": "Event: `'data'`", + "type": "event", + "name": "data", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Buffer|string}", + "type": "Buffer|string" + } + ], + "desc": "

      Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().

      \n

      The data will be lost if there is no listener when a Socket\nemits a 'data' event.

      " + }, + { + "textRaw": "Event: `'drain'`", + "type": "event", + "name": "drain", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the write buffer becomes empty. Can be used to throttle uploads.

      \n

      See also: the return values of socket.write().

      " + }, + { + "textRaw": "Event: `'end'`", + "type": "event", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the other end of the socket sends a FIN packet, thus ending the\nreadable side of the socket.

      \n

      By default (allowHalfOpen is false) the socket will send a FIN packet\nback and destroy its file descriptor once it has written out its pending\nwrite queue. However, if allowHalfOpen is set to true, the socket will\nnot automatically end() its writable side, allowing the\nuser to write arbitrary amounts of data. The user must call\nend() explicitly to close the connection (i.e. sending a\nFIN packet back).

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.

      " + }, + { + "textRaw": "Event: `'lookup'`", + "type": "event", + "name": "lookup", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [ + { + "version": "v5.10.0", + "pr-url": "https://github.com/nodejs/node/pull/5598", + "description": "The `host` parameter is supported now." + } + ] + }, + "params": [], + "desc": "

      Emitted after resolving the host name but before connecting.\nNot applicable to Unix sockets.

      \n" + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v9.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when a socket is ready to be used.

      \n

      Triggered immediately after 'connect'.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.

      \n

      See also: socket.setTimeout().

      " + } + ], + "methods": [ + { + "textRaw": "`socket.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name and port of the\nsocket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

      " + }, + { + "textRaw": "`socket.connect()`", + "type": "method", + "name": "connect", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Initiate a connection on a given socket.

      \n

      Possible signatures:

      \n\n

      This function is asynchronous. When the connection is established, the\n'connect' event will be emitted. If there is a problem connecting,\ninstead of a 'connect' event, an 'error' event will be emitted with\nthe error passed to the 'error' listener.\nThe last parameter connectListener, if supplied, will be added as a listener\nfor the 'connect' event once.

      \n

      This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.

      ", + "methods": [ + { + "textRaw": "`socket.connect(options[, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/25436", + "description": "Added `onread` option." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6021", + "description": "The `hints` option defaults to `0` in all cases now. Previously, in the absence of the `family` option it would default to `dns.ADDRCONFIG | dns.V4MAPPED`." + }, + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/6000", + "description": "The `hints` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object" + }, + { + "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." + } + ] + } + ], + "desc": "

      Initiate a connection on a given socket. Normally this method is not needed,\nthe socket should be created and opened with net.createConnection(). Use\nthis only when implementing a custom Socket.

      \n

      For TCP connections, available options are:

      \n
        \n
      • port <number> Required. Port the socket should connect to.
      • \n
      • host <string> Host the socket should connect to. Default: 'localhost'.
      • \n
      • localAddress <string> Local address the socket should connect from.
      • \n
      • localPort <number> Local port the socket should connect from.
      • \n
      • family <number>: Version of IP stack. Must be 4, 6, or 0. The value\n0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.
      • \n
      • hints <number> Optional dns.lookup() hints.
      • \n
      • lookup <Function> Custom lookup function. Default: dns.lookup().
      • \n
      \n

      For IPC connections, available options are:

      \n\n

      For both types, available options include:

      \n
        \n
      • onread <Object> If specified, incoming data is stored in a single buffer\nand passed to the supplied callback when data arrives on the socket.\nThis will cause the streaming functionality to not provide any data.\nThe socket will emit events like 'error', 'end', and 'close'\nas usual. Methods like pause() and resume() will also behave as\nexpected.\n
          \n
        • buffer <Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to\nuse for storing incoming data or a function that returns such.
        • \n
        • callback <Function> This function is called for every chunk of incoming\ndata. Two arguments are passed to it: the number of bytes written to\nbuffer and a reference to buffer. Return false from this function to\nimplicitly pause() the socket. This function will be executed in the\nglobal context.
        • \n
        \n
      • \n
      \n

      Following is an example of a client using the onread option:

      \n
      const net = require('net');\nnet.connect({\n  port: 80,\n  onread: {\n    // Reuses a 4KiB Buffer for every read from the socket.\n    buffer: Buffer.alloc(4 * 1024),\n    callback: function(nread, buf) {\n      // Received data is available in `buf` from 0 to `nread`.\n      console.log(buf.toString('utf8', 0, nread));\n    }\n  }\n});\n
      " + }, + { + "textRaw": "`socket.connect(path[, connectListener])`", + "type": "method", + "name": "connect", + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`path` {string} Path the client should connect to. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Path the client should connect to. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." + } + ] + } + ], + "desc": "

      Initiate an IPC connection on the given socket.

      \n

      Alias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.

      " + }, + { + "textRaw": "`socket.connect(port[, host][, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`port` {number} Port the client should connect to.", + "name": "port", + "type": "number", + "desc": "Port the client should connect to." + }, + { + "textRaw": "`host` {string} Host the client should connect to.", + "name": "host", + "type": "string", + "desc": "Host the client should connect to." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." + } + ] + } + ], + "desc": "

      Initiate a TCP connection on the given socket.

      \n

      Alias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.

      " + } + ] + }, + { + "textRaw": "`socket.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`error` {Object}", + "name": "error", + "type": "Object" + } + ] + } + ], + "desc": "

      Ensures that no more I/O activity happens on this socket.\nDestroys the stream and closes the connection.

      \n

      See writable.destroy() for further details.

      " + }, + { + "textRaw": "`socket.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "Only used when data is `string`." + }, + { + "textRaw": "`callback` {Function} Optional callback for when the socket is finished.", + "name": "callback", + "type": "Function", + "desc": "Optional callback for when the socket is finished." + } + ] + } + ], + "desc": "

      Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.

      \n

      See writable.end() for further details.

      " + }, + { + "textRaw": "`socket.pause()`", + "type": "method", + "name": "pause", + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.

      " + }, + { + "textRaw": "`socket.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Opposite of unref(), calling ref() on a previously unrefed socket will\nnot let the program exit if it's the only socket left (the default behavior).\nIf the socket is refed calling ref again will have no effect.

      " + }, + { + "textRaw": "`socket.resume()`", + "type": "method", + "name": "resume", + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Resumes reading after a call to socket.pause().

      " + }, + { + "textRaw": "`socket.setEncoding([encoding])`", + "type": "method", + "name": "setEncoding", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + } + ] + } + ], + "desc": "

      Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.

      " + }, + { + "textRaw": "`socket.setKeepAlive([enable][, initialDelay])`", + "type": "method", + "name": "setKeepAlive", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`enable` {boolean} **Default:** `false`", + "name": "enable", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`initialDelay` {number} **Default:** `0`", + "name": "initialDelay", + "type": "number", + "default": "`0`" + } + ] + } + ], + "desc": "

      Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.

      \n

      Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting.

      " + }, + { + "textRaw": "`socket.setNoDelay([noDelay])`", + "type": "method", + "name": "setNoDelay", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`noDelay` {boolean} **Default:** `true`", + "name": "noDelay", + "type": "boolean", + "default": "`true`" + } + ] + } + ], + "desc": "

      Enable/disable the use of Nagle's algorithm.

      \n

      When a TCP connection is created, it will have Nagle's algorithm enabled.

      \n

      Nagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.

      \n

      Passing true for noDelay or not passing an argument will disable Nagle's\nalgorithm for the socket. Passing false for noDelay will enable Nagle's\nalgorithm.

      " + }, + { + "textRaw": "`socket.setTimeout(timeout[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`timeout` {number}", + "name": "timeout", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.

      \n

      When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually call\nsocket.end() or socket.destroy() to end the connection.

      \n
      socket.setTimeout(3000);\nsocket.on('timeout', () => {\n  console.log('socket timeout');\n  socket.end();\n});\n
      \n

      If timeout is 0, then the existing idle timeout is disabled.

      \n

      The optional callback parameter will be added as a one-time listener for the\n'timeout' event.

      " + }, + { + "textRaw": "`socket.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Calling unref() on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefed calling\nunref() again will have no effect.

      " + }, + { + "textRaw": "`socket.write(data[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `utf8`.", + "name": "encoding", + "type": "string", + "default": "`utf8`", + "desc": "Only used when data is `string`." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.

      \n

      The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.

      \n

      See Writable stream write() method for more\ninformation.

      " + } + ], + "properties": [ + { + "textRaw": "`bufferSize` {integer}", + "type": "integer", + "name": "bufferSize", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "desc": "

      This property shows the number of characters buffered for writing. The buffer\nmay contain strings whose length after encoding is not yet known. So this number\nis only an approximation of the number of bytes in the buffer.

      \n

      net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket. The network connection\nsimply might be too slow. Node.js will internally queue up the data written to a\nsocket and send it out over the wire when it is possible.

      \n

      The consequence of this internal buffering is that memory may grow.\nUsers who experience large or growing bufferSize should attempt to\n\"throttle\" the data flows in their program with\nsocket.pause() and socket.resume().

      " + }, + { + "textRaw": "`bytesRead` {integer}", + "type": "integer", + "name": "bytesRead", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "desc": "

      The amount of received bytes.

      " + }, + { + "textRaw": "`bytesWritten` {integer}", + "type": "integer", + "name": "bytesWritten", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "desc": "

      The amount of bytes sent.

      " + }, + { + "textRaw": "`connecting` {boolean}", + "type": "boolean", + "name": "connecting", + "meta": { + "added": [ + "v6.1.0" + ], + "changes": [] + }, + "desc": "

      If true,\nsocket.connect(options[, connectListener]) was\ncalled and has not yet finished. It will stay true until the socket becomes\nconnected, then it is set to false and the 'connect' event is emitted. Note\nthat the\nsocket.connect(options[, connectListener])\ncallback is a listener for the 'connect' event.

      " + }, + { + "textRaw": "`destroyed` {boolean} Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.", + "type": "boolean", + "name": "destroyed", + "desc": "

      See writable.destroyed for further details.

      ", + "shortDesc": "Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it." + }, + { + "textRaw": "`localAddress` {string}", + "type": "string", + "name": "localAddress", + "meta": { + "added": [ + "v0.9.6" + ], + "changes": [] + }, + "desc": "

      The string representation of the local IP address the remote client is\nconnecting on. For example, in a server listening on '0.0.0.0', if a client\nconnects on '192.168.1.1', the value of socket.localAddress would be\n'192.168.1.1'.

      " + }, + { + "textRaw": "`localPort` {integer}", + "type": "integer", + "name": "localPort", + "meta": { + "added": [ + "v0.9.6" + ], + "changes": [] + }, + "desc": "

      The numeric representation of the local port. For example, 80 or 21.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This is true if the socket is not connected yet, either because .connect()\nhas not yet been called or because it is still in the process of connecting\n(see socket.connecting).

      " + }, + { + "textRaw": "`remoteAddress` {string}", + "type": "string", + "name": "remoteAddress", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "desc": "

      The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).

      " + }, + { + "textRaw": "`remoteFamily` {string}", + "type": "string", + "name": "remoteFamily", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "desc": "

      The string representation of the remote IP family. 'IPv4' or 'IPv6'.

      " + }, + { + "textRaw": "`remotePort` {integer}", + "type": "integer", + "name": "remotePort", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "desc": "

      The numeric representation of the remote port. For example, 80 or 21.

      " + } + ], + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`options` {Object} Available options are:", + "name": "options", + "type": "Object", + "desc": "Available options are:", + "options": [ + { + "textRaw": "`fd` {number} If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.", + "name": "fd", + "type": "number", + "desc": "If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created." + }, + { + "textRaw": "`allowHalfOpen` {boolean} Indicates whether half-opened TCP connections are allowed. See [`net.createServer()`][] and the [`'end'`][] event for details. **Default:** `false`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether half-opened TCP connections are allowed. See [`net.createServer()`][] and the [`'end'`][] event for details." + }, + { + "textRaw": "`readable` {boolean} Allow reads on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", + "name": "readable", + "type": "boolean", + "default": "`false`", + "desc": "Allow reads on the socket when an `fd` is passed, otherwise ignored." + }, + { + "textRaw": "`writable` {boolean} Allow writes on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", + "name": "writable", + "type": "boolean", + "default": "`false`", + "desc": "Allow writes on the socket when an `fd` is passed, otherwise ignored." + } + ] + } + ], + "desc": "

      Creates a new socket object.

      \n

      The newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`net.connect()`", + "type": "method", + "name": "connect", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Aliases to\nnet.createConnection().

      \n

      Possible signatures:

      \n", + "methods": [ + { + "textRaw": "`net.connect(options[, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object" + }, + { + "textRaw": "`connectListener` {Function}", + "name": "connectListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias to\nnet.createConnection(options[, connectListener]).

      " + }, + { + "textRaw": "`net.connect(path[, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + }, + { + "textRaw": "`connectListener` {Function}", + "name": "connectListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias to\nnet.createConnection(path[, connectListener]).

      " + }, + { + "textRaw": "`net.connect(port[, host][, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`host` {string}", + "name": "host", + "type": "string" + }, + { + "textRaw": "`connectListener` {Function}", + "name": "connectListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias to\nnet.createConnection(port[, host][, connectListener]).

      " + } + ] + }, + { + "textRaw": "`net.createConnection()`", + "type": "method", + "name": "createConnection", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.

      \n

      When the connection is established, a 'connect' event will be emitted\non the returned socket. The last parameter connectListener, if supplied,\nwill be added as a listener for the 'connect' event once.

      \n

      Possible signatures:

      \n\n

      The net.connect() function is an alias to this function.

      ", + "methods": [ + { + "textRaw": "`net.createConnection(options[, connectListener])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.", + "name": "return", + "type": "net.Socket", + "desc": "The newly created socket used to start the connection." + }, + "params": [ + { + "textRaw": "`options` {Object} Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] method.", + "name": "options", + "type": "Object", + "desc": "Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] method." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions. If supplied, will be added as a listener for the [`'connect'`][] event on the returned socket once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of the [`net.createConnection()`][] functions. If supplied, will be added as a listener for the [`'connect'`][] event on the returned socket once." + } + ] + } + ], + "desc": "

      For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).

      \n

      Additional options:

      \n\n

      Following is an example of a client of the echo server described\nin the net.createServer() section:

      \n
      const net = require('net');\nconst client = net.createConnection({ port: 8124 }, () => {\n  // 'connect' listener.\n  console.log('connected to server!');\n  client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', () => {\n  console.log('disconnected from server');\n});\n
      \n

      To connect on the socket /tmp/echo.sock:

      \n
      const client = net.createConnection({ path: '/tmp/echo.sock' });\n
      " + }, + { + "textRaw": "`net.createConnection(path[, connectListener])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.", + "name": "return", + "type": "net.Socket", + "desc": "The newly created socket used to start the connection." + }, + "params": [ + { + "textRaw": "`path` {string} Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`].", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]." + } + ] + } + ], + "desc": "

      Initiates an IPC connection.

      \n

      This function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(path[, connectListener]),\nthen returns the net.Socket that starts the connection.

      " + }, + { + "textRaw": "`net.createConnection(port[, host][, connectListener])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.", + "name": "return", + "type": "net.Socket", + "desc": "The newly created socket used to start the connection." + }, + "params": [ + { + "textRaw": "`port` {number} Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].", + "name": "port", + "type": "number", + "desc": "Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." + }, + { + "textRaw": "`host` {string} Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." + } + ] + } + ], + "desc": "

      Initiates a TCP connection.

      \n

      This function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(port[, host][, connectListener]),\nthen returns the net.Socket that starts the connection.

      " + } + ] + }, + { + "textRaw": "`net.createServer([options][, connectionListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`allowHalfOpen` {boolean} Indicates whether half-opened TCP connections are allowed. **Default:** `false`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether half-opened TCP connections are allowed." + }, + { + "textRaw": "`pauseOnConnect` {boolean} Indicates whether the socket should be paused on incoming connections. **Default:** `false`.", + "name": "pauseOnConnect", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether the socket should be paused on incoming connections." + } + ] + }, + { + "textRaw": "`connectionListener` {Function} Automatically set as a listener for the [`'connection'`][] event.", + "name": "connectionListener", + "type": "Function", + "desc": "Automatically set as a listener for the [`'connection'`][] event." + } + ] + } + ], + "desc": "

      Creates a new TCP or IPC server.

      \n

      If allowHalfOpen is set to true, when the other end of the socket\nsends a FIN packet, the server will only send a FIN packet back when\nsocket.end() is explicitly called, until then the connection is\nhalf-closed (non-readable but still writable). See 'end' event\nand RFC 1122 (section 4.2.2.13) for more information.

      \n

      If pauseOnConnect is set to true, then the socket associated with each\nincoming connection will be paused, and no data will be read from its handle.\nThis allows connections to be passed between processes without any data being\nread by the original process. To begin reading data from a paused socket, call\nsocket.resume().

      \n

      The server can be a TCP server or an IPC server, depending on what it\nlisten() to.

      \n

      Here is an example of an TCP echo server which listens for connections\non port 8124:

      \n
      const net = require('net');\nconst server = net.createServer((c) => {\n  // 'connection' listener.\n  console.log('client connected');\n  c.on('end', () => {\n    console.log('client disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.on('error', (err) => {\n  throw err;\n});\nserver.listen(8124, () => {\n  console.log('server bound');\n});\n
      \n

      Test this by using telnet:

      \n
      $ telnet localhost 8124\n
      \n

      To listen on the socket /tmp/echo.sock:

      \n
      server.listen('/tmp/echo.sock', () => {\n  console.log('server bound');\n});\n
      \n

      Use nc to connect to a Unix domain socket server:

      \n
      $ nc -U /tmp/echo.sock\n
      " + }, + { + "textRaw": "`net.isIP(input)`", + "type": "method", + "name": "isIP", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`input` {string}", + "name": "input", + "type": "string" + } + ] + } + ], + "desc": "

      Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6\naddresses.

      " + }, + { + "textRaw": "`net.isIPv4(input)`", + "type": "method", + "name": "isIPv4", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`input` {string}", + "name": "input", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if input is a version 4 IP address, otherwise returns false.

      " + }, + { + "textRaw": "`net.isIPv6(input)`", + "type": "method", + "name": "isIPv6", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`input` {string}", + "name": "input", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if input is a version 6 IP address, otherwise returns false.

      " + } + ], + "type": "module", + "displayName": "Net" + }, + { + "textRaw": "OS", + "name": "os", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/os.js

      \n

      The os module provides operating system-related utility methods and\nproperties. It can be accessed using:

      \n
      const os = require('os');\n
      ", + "properties": [ + { + "textRaw": "`EOL` {string}", + "type": "string", + "name": "EOL", + "meta": { + "added": [ + "v0.7.8" + ], + "changes": [] + }, + "desc": "

      The operating system-specific end-of-line marker.

      \n
        \n
      • \\n on POSIX
      • \n
      • \\r\\n on Windows
      • \n
      " + }, + { + "textRaw": "`constants` {Object}", + "type": "Object", + "name": "constants", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "

      Contains commonly used operating system-specific constants for error codes,\nprocess signals, and so on. The specific constants defined are described in\nOS constants.

      " + } + ], + "methods": [ + { + "textRaw": "`os.arch()`", + "type": "method", + "name": "arch", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system CPU architecture for which the Node.js binary was\ncompiled. Possible values are 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

      \n

      The return value is equivalent to process.arch.

      " + }, + { + "textRaw": "`os.cpus()`", + "type": "method", + "name": "cpus", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object[]}", + "name": "return", + "type": "Object[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array of objects containing information about each logical CPU core.

      \n

      The properties included on each object include:

      \n
        \n
      • model <string>
      • \n
      • speed <number> (in MHz)
      • \n
      • times <Object>\n
          \n
        • user <number> The number of milliseconds the CPU has spent in user mode.
        • \n
        • nice <number> The number of milliseconds the CPU has spent in nice mode.
        • \n
        • sys <number> The number of milliseconds the CPU has spent in sys mode.
        • \n
        • idle <number> The number of milliseconds the CPU has spent in idle mode.
        • \n
        • irq <number> The number of milliseconds the CPU has spent in irq mode.
        • \n
        \n
      • \n
      \n\n
      [\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 252020,\n      nice: 0,\n      sys: 30340,\n      idle: 1070356870,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 306960,\n      nice: 0,\n      sys: 26980,\n      idle: 1071569080,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 248450,\n      nice: 0,\n      sys: 21750,\n      idle: 1070919370,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 256880,\n      nice: 0,\n      sys: 19430,\n      idle: 1070905480,\n      irq: 20\n    }\n  }\n]\n
      \n

      nice values are POSIX-only. On Windows, the nice values of all processors\nare always 0.

      " + }, + { + "textRaw": "`os.endianness()`", + "type": "method", + "name": "endianness", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a string identifying the endianness of the CPU for which the Node.js\nbinary was compiled.

      \n

      Possible values are 'BE' for big endian and 'LE' for little endian.

      " + }, + { + "textRaw": "`os.freemem()`", + "type": "method", + "name": "freemem", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the amount of free system memory in bytes as an integer.

      " + }, + { + "textRaw": "`os.getPriority([pid])`", + "type": "method", + "name": "getPriority", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`pid` {integer} The process ID to retrieve scheduling priority for. **Default** `0`.", + "name": "pid", + "type": "integer", + "desc": "The process ID to retrieve scheduling priority for. **Default** `0`." + } + ] + } + ], + "desc": "

      Returns the scheduling priority for the process specified by pid. If pid is\nnot provided or is 0, the priority of the current process is returned.

      " + }, + { + "textRaw": "`os.homedir()`", + "type": "method", + "name": "homedir", + "meta": { + "added": [ + "v2.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the string path of the current user's home directory.

      \n

      On POSIX, it uses the $HOME environment variable if defined. Otherwise it\nuses the effective UID to look up the user's home directory.

      \n

      On Windows, it uses the USERPROFILE environment variable if defined.\nOtherwise it uses the path to the profile directory of the current user.

      " + }, + { + "textRaw": "`os.hostname()`", + "type": "method", + "name": "hostname", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the host name of the operating system as a string.

      " + }, + { + "textRaw": "`os.loadavg()`", + "type": "method", + "name": "loadavg", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number[]}", + "name": "return", + "type": "number[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array containing the 1, 5, and 15 minute load averages.

      \n

      The load average is a measure of system activity calculated by the operating\nsystem and expressed as a fractional number.

      \n

      The load average is a Unix-specific concept. On Windows, the return value is\nalways [0, 0, 0].

      " + }, + { + "textRaw": "`os.networkInterfaces()`", + "type": "method", + "name": "networkInterfaces", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing network interfaces that have been assigned a\nnetwork address.

      \n

      Each key on the returned object identifies a network interface. The associated\nvalue is an array of objects that each describe an assigned network address.

      \n

      The properties available on the assigned network address object include:

      \n
        \n
      • address <string> The assigned IPv4 or IPv6 address
      • \n
      • netmask <string> The IPv4 or IPv6 network mask
      • \n
      • family <string> Either IPv4 or IPv6
      • \n
      • mac <string> The MAC address of the network interface
      • \n
      • internal <boolean> true if the network interface is a loopback or\nsimilar interface that is not remotely accessible; otherwise false
      • \n
      • scopeid <number> The numeric IPv6 scope ID (only specified when family\nis IPv6)
      • \n
      • cidr <string> The assigned IPv4 or IPv6 address with the routing prefix\nin CIDR notation. If the netmask is invalid, this property is set\nto null.
      • \n
      \n\n
      {\n  lo: [\n    {\n      address: '127.0.0.1',\n      netmask: '255.0.0.0',\n      family: 'IPv4',\n      mac: '00:00:00:00:00:00',\n      internal: true,\n      cidr: '127.0.0.1/8'\n    },\n    {\n      address: '::1',\n      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',\n      family: 'IPv6',\n      mac: '00:00:00:00:00:00',\n      scopeid: 0,\n      internal: true,\n      cidr: '::1/128'\n    }\n  ],\n  eth0: [\n    {\n      address: '192.168.1.108',\n      netmask: '255.255.255.0',\n      family: 'IPv4',\n      mac: '01:02:03:0a:0b:0c',\n      internal: false,\n      cidr: '192.168.1.108/24'\n    },\n    {\n      address: 'fe80::a00:27ff:fe4e:66a1',\n      netmask: 'ffff:ffff:ffff:ffff::',\n      family: 'IPv6',\n      mac: '01:02:03:0a:0b:0c',\n      scopeid: 1,\n      internal: false,\n      cidr: 'fe80::a00:27ff:fe4e:66a1/64'\n    }\n  ]\n}\n
      " + }, + { + "textRaw": "`os.platform()`", + "type": "method", + "name": "platform", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a string identifying the operating system platform. The value is set\nat compile time. Possible values are 'aix', 'darwin', 'freebsd',\n'linux', 'openbsd', 'sunos', and 'win32'.

      \n

      The return value is equivalent to process.platform.

      \n

      The value 'android' may also be returned if Node.js is built on the Android\noperating system. Android support is experimental.

      " + }, + { + "textRaw": "`os.release()`", + "type": "method", + "name": "release", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system as a string.

      \n

      On POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, GetVersionExW() is used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.

      " + }, + { + "textRaw": "`os.setPriority([pid, ]priority)`", + "type": "method", + "name": "setPriority", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`pid` {integer} The process ID to set scheduling priority for. **Default** `0`.", + "name": "pid", + "type": "integer", + "desc": "The process ID to set scheduling priority for. **Default** `0`." + }, + { + "textRaw": "`priority` {integer} The scheduling priority to assign to the process.", + "name": "priority", + "type": "integer", + "desc": "The scheduling priority to assign to the process." + } + ] + } + ], + "desc": "

      Attempts to set the scheduling priority for the process specified by pid. If\npid is not provided or is 0, the process ID of the current process is used.

      \n

      The priority input must be an integer between -20 (high priority) and 19\n(low priority). Due to differences between Unix priority levels and Windows\npriority classes, priority is mapped to one of six priority constants in\nos.constants.priority. When retrieving a process priority level, this range\nmapping may cause the return value to be slightly different on Windows. To avoid\nconfusion, set priority to one of the priority constants.

      \n

      On Windows, setting priority to PRIORITY_HIGHEST requires elevated user\nprivileges. Otherwise the set priority will be silently reduced to\nPRIORITY_HIGH.

      " + }, + { + "textRaw": "`os.tmpdir()`", + "type": "method", + "name": "tmpdir", + "meta": { + "added": [ + "v0.9.9" + ], + "changes": [ + { + "version": "v2.0.0", + "pr-url": "https://github.com/nodejs/node/pull/747", + "description": "This function is now cross-platform consistent and no longer returns a path with a trailing slash on any platform" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system's default directory for temporary files as a\nstring.

      " + }, + { + "textRaw": "`os.totalmem()`", + "type": "method", + "name": "totalmem", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the total amount of system memory in bytes as an integer.

      " + }, + { + "textRaw": "`os.type()`", + "type": "method", + "name": "type", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system name as returned by uname(3). For example, it\nreturns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows.

      \n

      See https://en.wikipedia.org/wiki/Uname#Examples for additional information\nabout the output of running uname(3) on various operating systems.

      " + }, + { + "textRaw": "`os.uptime()`", + "type": "method", + "name": "uptime", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20129", + "description": "The result of this function no longer contains a fraction component on Windows." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the system uptime in number of seconds.

      " + }, + { + "textRaw": "`os.userInfo([options])`", + "type": "method", + "name": "userInfo", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string} Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances." + } + ] + } + ] + } + ], + "desc": "

      Returns information about the currently effective user. On POSIX platforms,\nthis is typically a subset of the password file. The returned object includes\nthe username, uid, gid, shell, and homedir. On Windows, the uid and\ngid fields are -1, and shell is null.

      \n

      The value of homedir returned by os.userInfo() is provided by the operating\nsystem. This differs from the result of os.homedir(), which queries\nenvironment variables for the home directory before falling back to the\noperating system response.

      \n

      Throws a SystemError if a user has no username or homedir.

      " + }, + { + "textRaw": "`os.version()`", + "type": "method", + "name": "version", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a string identifying the kernel version.

      \n

      On POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, RtlGetVersion() is used, and if it is not\navailable, GetVersionExW() will be used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.

      " + } + ], + "modules": [ + { + "textRaw": "OS constants", + "name": "os_constants", + "desc": "

      The following constants are exported by os.constants.

      \n

      Not all constants will be available on every operating system.

      ", + "modules": [ + { + "textRaw": "Signal constants", + "name": "signal_constants", + "meta": { + "changes": [ + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/6093", + "description": "Added support for `SIGINFO`." + } + ] + }, + "desc": "

      The following signal constants are exported by os.constants.signals.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      SIGHUPSent to indicate when a controlling terminal is closed or a parent\n process exits.
      SIGINTSent to indicate when a user wishes to interrupt a process\n ((Ctrl+C)).
      SIGQUITSent to indicate when a user wishes to terminate a process and perform a\n core dump.
      SIGILLSent to a process to notify that it has attempted to perform an illegal,\n malformed, unknown, or privileged instruction.
      SIGTRAPSent to a process when an exception has occurred.
      SIGABRTSent to a process to request that it abort.
      SIGIOTSynonym for SIGABRT
      SIGBUSSent to a process to notify that it has caused a bus error.
      SIGFPESent to a process to notify that it has performed an illegal arithmetic\n operation.
      SIGKILLSent to a process to terminate it immediately.
      SIGUSR1 SIGUSR2Sent to a process to identify user-defined conditions.
      SIGSEGVSent to a process to notify of a segmentation fault.
      SIGPIPESent to a process when it has attempted to write to a disconnected\n pipe.
      SIGALRMSent to a process when a system timer elapses.
      SIGTERMSent to a process to request termination.
      SIGCHLDSent to a process when a child process terminates.
      SIGSTKFLTSent to a process to indicate a stack fault on a coprocessor.
      SIGCONTSent to instruct the operating system to continue a paused process.
      SIGSTOPSent to instruct the operating system to halt a process.
      SIGTSTPSent to a process to request it to stop.
      SIGBREAKSent to indicate when a user wishes to interrupt a process.
      SIGTTINSent to a process when it reads from the TTY while in the\n background.
      SIGTTOUSent to a process when it writes to the TTY while in the\n background.
      SIGURGSent to a process when a socket has urgent data to read.
      SIGXCPUSent to a process when it has exceeded its limit on CPU usage.
      SIGXFSZSent to a process when it grows a file larger than the maximum\n allowed.
      SIGVTALRMSent to a process when a virtual timer has elapsed.
      SIGPROFSent to a process when a system timer has elapsed.
      SIGWINCHSent to a process when the controlling terminal has changed its\n size.
      SIGIOSent to a process when I/O is available.
      SIGPOLLSynonym for SIGIO
      SIGLOSTSent to a process when a file lock has been lost.
      SIGPWRSent to a process to notify of a power failure.
      SIGINFOSynonym for SIGPWR
      SIGSYSSent to a process to notify of a bad argument.
      SIGUNUSEDSynonym for SIGSYS
      ", + "type": "module", + "displayName": "Signal constants" + }, + { + "textRaw": "Error constants", + "name": "error_constants", + "desc": "

      The following error constants are exported by os.constants.errno.

      ", + "modules": [ + { + "textRaw": "POSIX error constants", + "name": "posix_error_constants", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      E2BIGIndicates that the list of arguments is longer than expected.
      EACCESIndicates that the operation did not have sufficient permissions.
      EADDRINUSEIndicates that the network address is already in use.
      EADDRNOTAVAILIndicates that the network address is currently unavailable for\n use.
      EAFNOSUPPORTIndicates that the network address family is not supported.
      EAGAINIndicates that there is no data available and to try the\n operation again later.
      EALREADYIndicates that the socket already has a pending connection in\n progress.
      EBADFIndicates that a file descriptor is not valid.
      EBADMSGIndicates an invalid data message.
      EBUSYIndicates that a device or resource is busy.
      ECANCELEDIndicates that an operation was canceled.
      ECHILDIndicates that there are no child processes.
      ECONNABORTEDIndicates that the network connection has been aborted.
      ECONNREFUSEDIndicates that the network connection has been refused.
      ECONNRESETIndicates that the network connection has been reset.
      EDEADLKIndicates that a resource deadlock has been avoided.
      EDESTADDRREQIndicates that a destination address is required.
      EDOMIndicates that an argument is out of the domain of the function.
      EDQUOTIndicates that the disk quota has been exceeded.
      EEXISTIndicates that the file already exists.
      EFAULTIndicates an invalid pointer address.
      EFBIGIndicates that the file is too large.
      EHOSTUNREACHIndicates that the host is unreachable.
      EIDRMIndicates that the identifier has been removed.
      EILSEQIndicates an illegal byte sequence.
      EINPROGRESSIndicates that an operation is already in progress.
      EINTRIndicates that a function call was interrupted.
      EINVALIndicates that an invalid argument was provided.
      EIOIndicates an otherwise unspecified I/O error.
      EISCONNIndicates that the socket is connected.
      EISDIRIndicates that the path is a directory.
      ELOOPIndicates too many levels of symbolic links in a path.
      EMFILEIndicates that there are too many open files.
      EMLINKIndicates that there are too many hard links to a file.
      EMSGSIZEIndicates that the provided message is too long.
      EMULTIHOPIndicates that a multihop was attempted.
      ENAMETOOLONGIndicates that the filename is too long.
      ENETDOWNIndicates that the network is down.
      ENETRESETIndicates that the connection has been aborted by the network.
      ENETUNREACHIndicates that the network is unreachable.
      ENFILEIndicates too many open files in the system.
      ENOBUFSIndicates that no buffer space is available.
      ENODATAIndicates that no message is available on the stream head read\n queue.
      ENODEVIndicates that there is no such device.
      ENOENTIndicates that there is no such file or directory.
      ENOEXECIndicates an exec format error.
      ENOLCKIndicates that there are no locks available.
      ENOLINKIndications that a link has been severed.
      ENOMEMIndicates that there is not enough space.
      ENOMSGIndicates that there is no message of the desired type.
      ENOPROTOOPTIndicates that a given protocol is not available.
      ENOSPCIndicates that there is no space available on the device.
      ENOSRIndicates that there are no stream resources available.
      ENOSTRIndicates that a given resource is not a stream.
      ENOSYSIndicates that a function has not been implemented.
      ENOTCONNIndicates that the socket is not connected.
      ENOTDIRIndicates that the path is not a directory.
      ENOTEMPTYIndicates that the directory is not empty.
      ENOTSOCKIndicates that the given item is not a socket.
      ENOTSUPIndicates that a given operation is not supported.
      ENOTTYIndicates an inappropriate I/O control operation.
      ENXIOIndicates no such device or address.
      EOPNOTSUPPIndicates that an operation is not supported on the socket. Although\n ENOTSUP and EOPNOTSUPP have the same value\n on Linux, according to POSIX.1 these error values should be distinct.)
      EOVERFLOWIndicates that a value is too large to be stored in a given data\n type.
      EPERMIndicates that the operation is not permitted.
      EPIPEIndicates a broken pipe.
      EPROTOIndicates a protocol error.
      EPROTONOSUPPORTIndicates that a protocol is not supported.
      EPROTOTYPEIndicates the wrong type of protocol for a socket.
      ERANGEIndicates that the results are too large.
      EROFSIndicates that the file system is read only.
      ESPIPEIndicates an invalid seek operation.
      ESRCHIndicates that there is no such process.
      ESTALEIndicates that the file handle is stale.
      ETIMEIndicates an expired timer.
      ETIMEDOUTIndicates that the connection timed out.
      ETXTBSYIndicates that a text file is busy.
      EWOULDBLOCKIndicates that the operation would block.
      EXDEVIndicates an improper link.\n
      ", + "type": "module", + "displayName": "POSIX error constants" + }, + { + "textRaw": "Windows-specific error constants", + "name": "windows-specific_error_constants", + "desc": "

      The following error codes are specific to the Windows operating system.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      WSAEINTRIndicates an interrupted function call.
      WSAEBADFIndicates an invalid file handle.
      WSAEACCESIndicates insufficient permissions to complete the operation.
      WSAEFAULTIndicates an invalid pointer address.
      WSAEINVALIndicates that an invalid argument was passed.
      WSAEMFILEIndicates that there are too many open files.
      WSAEWOULDBLOCKIndicates that a resource is temporarily unavailable.
      WSAEINPROGRESSIndicates that an operation is currently in progress.
      WSAEALREADYIndicates that an operation is already in progress.
      WSAENOTSOCKIndicates that the resource is not a socket.
      WSAEDESTADDRREQIndicates that a destination address is required.
      WSAEMSGSIZEIndicates that the message size is too long.
      WSAEPROTOTYPEIndicates the wrong protocol type for the socket.
      WSAENOPROTOOPTIndicates a bad protocol option.
      WSAEPROTONOSUPPORTIndicates that the protocol is not supported.
      WSAESOCKTNOSUPPORTIndicates that the socket type is not supported.
      WSAEOPNOTSUPPIndicates that the operation is not supported.
      WSAEPFNOSUPPORTIndicates that the protocol family is not supported.
      WSAEAFNOSUPPORTIndicates that the address family is not supported.
      WSAEADDRINUSEIndicates that the network address is already in use.
      WSAEADDRNOTAVAILIndicates that the network address is not available.
      WSAENETDOWNIndicates that the network is down.
      WSAENETUNREACHIndicates that the network is unreachable.
      WSAENETRESETIndicates that the network connection has been reset.
      WSAECONNABORTEDIndicates that the connection has been aborted.
      WSAECONNRESETIndicates that the connection has been reset by the peer.
      WSAENOBUFSIndicates that there is no buffer space available.
      WSAEISCONNIndicates that the socket is already connected.
      WSAENOTCONNIndicates that the socket is not connected.
      WSAESHUTDOWNIndicates that data cannot be sent after the socket has been\n shutdown.
      WSAETOOMANYREFSIndicates that there are too many references.
      WSAETIMEDOUTIndicates that the connection has timed out.
      WSAECONNREFUSEDIndicates that the connection has been refused.
      WSAELOOPIndicates that a name cannot be translated.
      WSAENAMETOOLONGIndicates that a name was too long.
      WSAEHOSTDOWNIndicates that a network host is down.
      WSAEHOSTUNREACHIndicates that there is no route to a network host.
      WSAENOTEMPTYIndicates that the directory is not empty.
      WSAEPROCLIMIndicates that there are too many processes.
      WSAEUSERSIndicates that the user quota has been exceeded.
      WSAEDQUOTIndicates that the disk quota has been exceeded.
      WSAESTALEIndicates a stale file handle reference.
      WSAEREMOTEIndicates that the item is remote.
      WSASYSNOTREADYIndicates that the network subsystem is not ready.
      WSAVERNOTSUPPORTEDIndicates that the winsock.dll version is out of\n range.
      WSANOTINITIALISEDIndicates that successful WSAStartup has not yet been performed.
      WSAEDISCONIndicates that a graceful shutdown is in progress.
      WSAENOMOREIndicates that there are no more results.
      WSAECANCELLEDIndicates that an operation has been canceled.
      WSAEINVALIDPROCTABLEIndicates that the procedure call table is invalid.
      WSAEINVALIDPROVIDERIndicates an invalid service provider.
      WSAEPROVIDERFAILEDINITIndicates that the service provider failed to initialized.
      WSASYSCALLFAILUREIndicates a system call failure.
      WSASERVICE_NOT_FOUNDIndicates that a service was not found.
      WSATYPE_NOT_FOUNDIndicates that a class type was not found.
      WSA_E_NO_MOREIndicates that there are no more results.
      WSA_E_CANCELLEDIndicates that the call was canceled.
      WSAEREFUSEDIndicates that a database query was refused.
      ", + "type": "module", + "displayName": "Windows-specific error constants" + } + ], + "type": "module", + "displayName": "Error constants" + }, + { + "textRaw": "dlopen constants", + "name": "dlopen_constants", + "desc": "

      If available on the operating system, the following constants\nare exported in os.constants.dlopen. See dlopen(3) for detailed\ninformation.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      RTLD_LAZYPerform lazy binding. Node.js sets this flag by default.
      RTLD_NOWResolve all undefined symbols in the library before dlopen(3)\n returns.
      RTLD_GLOBALSymbols defined by the library will be made available for symbol\n resolution of subsequently loaded libraries.
      RTLD_LOCALThe converse of RTLD_GLOBAL. This is the default behavior\n if neither flag is specified.
      RTLD_DEEPBINDMake a self-contained library use its own symbols in preference to\n symbols from previously loaded libraries.
      ", + "type": "module", + "displayName": "dlopen constants" + }, + { + "textRaw": "Priority constants", + "name": "priority_constants", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      The following process scheduling constants are exported by\nos.constants.priority.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      PRIORITY_LOWThe lowest process scheduling priority. This corresponds to\n IDLE_PRIORITY_CLASS on Windows, and a nice value of\n 19 on all other platforms.
      PRIORITY_BELOW_NORMALThe process scheduling priority above PRIORITY_LOW and\n below PRIORITY_NORMAL. This corresponds to\n BELOW_NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n 10 on all other platforms.
      PRIORITY_NORMALThe default process scheduling priority. This corresponds to\n NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n 0 on all other platforms.
      PRIORITY_ABOVE_NORMALThe process scheduling priority above PRIORITY_NORMAL and\n below PRIORITY_HIGH. This corresponds to\n ABOVE_NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n -7 on all other platforms.
      PRIORITY_HIGHThe process scheduling priority above PRIORITY_ABOVE_NORMAL\n and below PRIORITY_HIGHEST. This corresponds to\n HIGH_PRIORITY_CLASS on Windows, and a nice value of\n -14 on all other platforms.
      PRIORITY_HIGHESTThe highest process scheduling priority. This corresponds to\n REALTIME_PRIORITY_CLASS on Windows, and a nice value of\n -20 on all other platforms.
      ", + "type": "module", + "displayName": "Priority constants" + }, + { + "textRaw": "libuv constants", + "name": "libuv_constants", + "desc": "\n \n \n \n \n \n \n \n \n
      ConstantDescription
      UV_UDP_REUSEADDR
      ", + "type": "module", + "displayName": "libuv constants" + } + ], + "type": "module", + "displayName": "OS constants" + } + ], + "type": "module", + "displayName": "OS" + }, + { + "textRaw": "Path", + "name": "path", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/path.js

      \n

      The path module provides utilities for working with file and directory paths.\nIt can be accessed using:

      \n
      const path = require('path');\n
      ", + "modules": [ + { + "textRaw": "Windows vs. POSIX", + "name": "windows_vs._posix", + "desc": "

      The default operation of the path module varies based on the operating system\non which a Node.js application is running. Specifically, when running on a\nWindows operating system, the path module will assume that Windows-style\npaths are being used.

      \n

      So using path.basename() might yield different results on POSIX and Windows:

      \n

      On POSIX:

      \n
      path.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'C:\\\\temp\\\\myfile.html'\n
      \n

      On Windows:

      \n
      path.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
      \n

      To achieve consistent results when working with Windows file paths on any\noperating system, use path.win32:

      \n

      On POSIX and Windows:

      \n
      path.win32.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
      \n

      To achieve consistent results when working with POSIX file paths on any\noperating system, use path.posix:

      \n

      On POSIX and Windows:

      \n
      path.posix.basename('/tmp/myfile.html');\n// Returns: 'myfile.html'\n
      \n

      On Windows Node.js follows the concept of per-drive working directory.\nThis behavior can be observed when using a drive path without a backslash. For\nexample, path.resolve('C:\\\\') can potentially return a different result than\npath.resolve('C:'). For more information, see\nthis MSDN page.

      ", + "type": "module", + "displayName": "Windows vs. POSIX" + } + ], + "methods": [ + { + "textRaw": "`path.basename(path[, ext])`", + "type": "method", + "name": "basename", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Passing a non-string as the `path` argument will throw now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + }, + { + "textRaw": "`ext` {string} An optional file extension", + "name": "ext", + "type": "string", + "desc": "An optional file extension" + } + ] + } + ], + "desc": "

      The path.basename() method returns the last portion of a path, similar to\nthe Unix basename command. Trailing directory separators are ignored, see\npath.sep.

      \n
      path.basename('/foo/bar/baz/asdf/quux.html');\n// Returns: 'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html');\n// Returns: 'quux'\n
      \n

      Although Windows usually treats file names, including file extensions, in a\ncase-insensitive manner, this function does not. For example, C:\\\\foo.html and\nC:\\\\foo.HTML refer to the same file, but basename treats the extension as a\ncase-sensitive string:

      \n
      path.win32.basename('C:\\\\foo.html', '.html');\n// Returns: 'foo'\n\npath.win32.basename('C:\\\\foo.HTML', '.html');\n// Returns: 'foo.HTML'\n
      \n

      A TypeError is thrown if path is not a string or if ext is given\nand is not a string.

      " + }, + { + "textRaw": "`path.dirname(path)`", + "type": "method", + "name": "dirname", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Passing a non-string as the `path` argument will throw now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.dirname() method returns the directory name of a path, similar to\nthe Unix dirname command. Trailing directory separators are ignored, see\npath.sep.

      \n
      path.dirname('/foo/bar/baz/asdf/quux');\n// Returns: '/foo/bar/baz/asdf'\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.extname(path)`", + "type": "method", + "name": "extname", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Passing a non-string as the `path` argument will throw now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.extname() method returns the extension of the path, from the last\noccurrence of the . (period) character to end of string in the last portion of\nthe path. If there is no . in the last portion of the path, or if\nthere are no . characters other than the first character of\nthe basename of path (see path.basename()) , an empty string is returned.

      \n
      path.extname('index.html');\n// Returns: '.html'\n\npath.extname('index.coffee.md');\n// Returns: '.md'\n\npath.extname('index.');\n// Returns: '.'\n\npath.extname('index');\n// Returns: ''\n\npath.extname('.index');\n// Returns: ''\n\npath.extname('.index.md');\n// Returns: '.md'\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.format(pathObject)`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`pathObject` {Object}", + "name": "pathObject", + "type": "Object", + "options": [ + { + "textRaw": "`dir` {string}", + "name": "dir", + "type": "string" + }, + { + "textRaw": "`root` {string}", + "name": "root", + "type": "string" + }, + { + "textRaw": "`base` {string}", + "name": "base", + "type": "string" + }, + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`ext` {string}", + "name": "ext", + "type": "string" + } + ] + } + ] + } + ], + "desc": "

      The path.format() method returns a path string from an object. This is the\nopposite of path.parse().

      \n

      When providing properties to the pathObject remember that there are\ncombinations where one property has priority over another:

      \n
        \n
      • pathObject.root is ignored if pathObject.dir is provided
      • \n
      • pathObject.ext and pathObject.name are ignored if pathObject.base exists
      • \n
      \n

      For example, on POSIX:

      \n
      // If `dir`, `root` and `base` are provided,\n// `${dir}${path.sep}${base}`\n// will be returned. `root` is ignored.\npath.format({\n  root: '/ignored',\n  dir: '/home/user/dir',\n  base: 'file.txt'\n});\n// Returns: '/home/user/dir/file.txt'\n\n// `root` will be used if `dir` is not specified.\n// If only `root` is provided or `dir` is equal to `root` then the\n// platform separator will not be included. `ext` will be ignored.\npath.format({\n  root: '/',\n  base: 'file.txt',\n  ext: 'ignored'\n});\n// Returns: '/file.txt'\n\n// `name` + `ext` will be used if `base` is not specified.\npath.format({\n  root: '/',\n  name: 'file',\n  ext: '.txt'\n});\n// Returns: '/file.txt'\n
      \n

      On Windows:

      \n
      path.format({\n  dir: 'C:\\\\path\\\\dir',\n  base: 'file.txt'\n});\n// Returns: 'C:\\\\path\\\\dir\\\\file.txt'\n
      " + }, + { + "textRaw": "`path.isAbsolute(path)`", + "type": "method", + "name": "isAbsolute", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.isAbsolute() method determines if path is an absolute path.

      \n

      If the given path is a zero-length string, false will be returned.

      \n

      For example, on POSIX:

      \n
      path.isAbsolute('/foo/bar'); // true\npath.isAbsolute('/baz/..');  // true\npath.isAbsolute('qux/');     // false\npath.isAbsolute('.');        // false\n
      \n

      On Windows:

      \n
      path.isAbsolute('//server');    // true\npath.isAbsolute('\\\\\\\\server');  // true\npath.isAbsolute('C:/foo/..');   // true\npath.isAbsolute('C:\\\\foo\\\\..'); // true\npath.isAbsolute('bar\\\\baz');    // false\npath.isAbsolute('bar/baz');     // false\npath.isAbsolute('.');           // false\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.join([...paths])`", + "type": "method", + "name": "join", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`...paths` {string} A sequence of path segments", + "name": "...paths", + "type": "string", + "desc": "A sequence of path segments" + } + ] + } + ], + "desc": "

      The path.join() method joins all given path segments together using the\nplatform-specific separator as a delimiter, then normalizes the resulting path.

      \n

      Zero-length path segments are ignored. If the joined path string is a\nzero-length string then '.' will be returned, representing the current\nworking directory.

      \n
      path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');\n// Returns: '/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar');\n// Throws 'TypeError: Path must be a string. Received {}'\n
      \n

      A TypeError is thrown if any of the path segments is not a string.

      " + }, + { + "textRaw": "`path.normalize(path)`", + "type": "method", + "name": "normalize", + "meta": { + "added": [ + "v0.1.23" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.normalize() method normalizes the given path, resolving '..' and\n'.' segments.

      \n

      When multiple, sequential path segment separation characters are found (e.g.\n/ on POSIX and either \\ or / on Windows), they are replaced by a single\ninstance of the platform-specific path segment separator (/ on POSIX and\n\\ on Windows). Trailing separators are preserved.

      \n

      If the path is a zero-length string, '.' is returned, representing the\ncurrent working directory.

      \n

      For example, on POSIX:

      \n
      path.normalize('/foo/bar//baz/asdf/quux/..');\n// Returns: '/foo/bar/baz/asdf'\n
      \n

      On Windows:

      \n
      path.normalize('C:\\\\temp\\\\\\\\foo\\\\bar\\\\..\\\\');\n// Returns: 'C:\\\\temp\\\\foo\\\\'\n
      \n

      Since Windows recognizes multiple path separators, both separators will be\nreplaced by instances of the Windows preferred separator (\\):

      \n
      path.win32.normalize('C:////temp\\\\\\\\/\\\\/\\\\/foo/bar');\n// Returns: 'C:\\\\temp\\\\foo\\\\bar'\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.parse(path)`", + "type": "method", + "name": "parse", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.parse() method returns an object whose properties represent\nsignificant elements of the path. Trailing directory separators are ignored,\nsee path.sep.

      \n

      The returned object will have the following properties:

      \n\n

      For example, on POSIX:

      \n
      path.parse('/home/user/dir/file.txt');\n// Returns:\n// { root: '/',\n//   dir: '/home/user/dir',\n//   base: 'file.txt',\n//   ext: '.txt',\n//   name: 'file' }\n
      \n
      ┌─────────────────────┬────────────â”\n│          dir        │    base    │\n├──────┬              ├──────┬─────┤\n│ root │              │ name │ ext │\n\"  /    home/user/dir / file  .txt \"\n└──────┴──────────────┴──────┴─────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
      \n

      On Windows:

      \n
      path.parse('C:\\\\path\\\\dir\\\\file.txt');\n// Returns:\n// { root: 'C:\\\\',\n//   dir: 'C:\\\\path\\\\dir',\n//   base: 'file.txt',\n//   ext: '.txt',\n//   name: 'file' }\n
      \n
      ┌─────────────────────┬────────────â”\n│          dir        │    base    │\n├──────┬              ├──────┬─────┤\n│ root │              │ name │ ext │\n\" C:\\      path\\dir   \\ file  .txt \"\n└──────┴──────────────┴──────┴─────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.relative(from, to)`", + "type": "method", + "name": "relative", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v6.8.0", + "pr-url": "https://github.com/nodejs/node/pull/8523", + "description": "On Windows, the leading slashes for UNC paths are now included in the return value." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`from` {string}", + "name": "from", + "type": "string" + }, + { + "textRaw": "`to` {string}", + "name": "to", + "type": "string" + } + ] + } + ], + "desc": "

      The path.relative() method returns the relative path from from to to based\non the current working directory. If from and to each resolve to the same\npath (after calling path.resolve() on each), a zero-length string is returned.

      \n

      If a zero-length string is passed as from or to, the current working\ndirectory will be used instead of the zero-length strings.

      \n

      For example, on POSIX:

      \n
      path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');\n// Returns: '../../impl/bbb'\n
      \n

      On Windows:

      \n
      path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb');\n// Returns: '..\\\\..\\\\impl\\\\bbb'\n
      \n

      A TypeError is thrown if either from or to is not a string.

      " + }, + { + "textRaw": "`path.resolve([...paths])`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`...paths` {string} A sequence of paths or path segments", + "name": "...paths", + "type": "string", + "desc": "A sequence of paths or path segments" + } + ] + } + ], + "desc": "

      The path.resolve() method resolves a sequence of paths or path segments into\nan absolute path.

      \n

      The given sequence of paths is processed from right to left, with each\nsubsequent path prepended until an absolute path is constructed.\nFor instance, given the sequence of path segments: /foo, /bar, baz,\ncalling path.resolve('/foo', '/bar', 'baz') would return /bar/baz\nbecause 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.

      \n

      If, after processing all given path segments, an absolute path has not yet\nbeen generated, the current working directory is used.

      \n

      The resulting path is normalized and trailing slashes are removed unless the\npath is resolved to the root directory.

      \n

      Zero-length path segments are ignored.

      \n

      If no path segments are passed, path.resolve() will return the absolute path\nof the current working directory.

      \n
      path.resolve('/foo/bar', './baz');\n// Returns: '/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/');\n// Returns: '/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');\n// If the current working directory is /home/myself/node,\n// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'\n
      \n

      A TypeError is thrown if any of the arguments is not a string.

      " + }, + { + "textRaw": "`path.toNamespacedPath(path)`", + "type": "method", + "name": "toNamespacedPath", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      On Windows systems only, returns an equivalent namespace-prefixed path for\nthe given path. If path is not a string, path will be returned without\nmodifications.

      \n

      This method is meaningful only on Windows systems. On POSIX systems, the\nmethod is non-operational and always returns path without modifications.

      " + } + ], + "properties": [ + { + "textRaw": "`delimiter` {string}", + "type": "string", + "name": "delimiter", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "desc": "

      Provides the platform-specific path delimiter:

      \n
        \n
      • ; for Windows
      • \n
      • : for POSIX
      • \n
      \n

      For example, on POSIX:

      \n
      console.log(process.env.PATH);\n// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter);\n// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']\n
      \n

      On Windows:

      \n
      console.log(process.env.PATH);\n// Prints: 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\node\\'\n\nprocess.env.PATH.split(path.delimiter);\n// Returns ['C:\\\\Windows\\\\system32', 'C:\\\\Windows', 'C:\\\\Program Files\\\\node\\\\']\n
      " + }, + { + "textRaw": "`posix` {Object}", + "type": "Object", + "name": "posix", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      The path.posix property provides access to POSIX specific implementations\nof the path methods.

      " + }, + { + "textRaw": "`sep` {string}", + "type": "string", + "name": "sep", + "meta": { + "added": [ + "v0.7.9" + ], + "changes": [] + }, + "desc": "

      Provides the platform-specific path segment separator:

      \n
        \n
      • \\ on Windows
      • \n
      • / on POSIX
      • \n
      \n

      For example, on POSIX:

      \n
      'foo/bar/baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n
      \n

      On Windows:

      \n
      'foo\\\\bar\\\\baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n
      \n

      On Windows, both the forward slash (/) and backward slash (\\) are accepted\nas path segment separators; however, the path methods only add backward\nslashes (\\).

      " + }, + { + "textRaw": "`win32` {Object}", + "type": "Object", + "name": "win32", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      The path.win32 property provides access to Windows-specific implementations\nof the path methods.

      " + } + ], + "type": "module", + "displayName": "Path" + }, + { + "textRaw": "Performance measurement APIs", + "name": "performance_measurement_apis", + "introduced_in": "v8.5.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/perf_hooks.js

      \n

      This module provides an implementation of a subset of the W3C\nWeb Performance APIs as well as additional APIs for\nNode.js-specific performance measurements.

      \n

      Node.js supports the following Web Performance APIs:

      \n\n
      const { PerformanceObserver, performance } = require('perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n  console.log(items.getEntries()[0].duration);\n  performance.clearMarks();\n});\nobs.observe({ entryTypes: ['measure'] });\nperformance.measure('Start to Now');\n\nperformance.mark('A');\ndoSomeLongRunningProcess(() => {\n  performance.measure('A to Now', 'A');\n\n  performance.mark('B');\n  performance.measure('A to B', 'A', 'B');\n});\n
      ", + "properties": [ + { + "textRaw": "`perf_hooks.performance`", + "name": "performance", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      An object that can be used to collect performance metrics from the current\nNode.js instance. It is similar to window.performance in browsers.

      ", + "methods": [ + { + "textRaw": "`performance.clearMarks([name])`", + "type": "method", + "name": "clearMarks", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      If name is not provided, removes all PerformanceMark objects from the\nPerformance Timeline. If name is provided, removes only the named mark.

      " + }, + { + "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", + "type": "method", + "name": "eventLoopUtilization", + "meta": { + "added": [ + "v14.10.0", + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`idle` {number}", + "name": "idle", + "type": "number" + }, + { + "textRaw": "`active` {number}", + "name": "active", + "type": "number" + }, + { + "textRaw": "`utilization` {number}", + "name": "utilization", + "type": "number" + } + ] + }, + "params": [ + { + "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", + "name": "utilization1", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()`." + }, + { + "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", + "name": "utilization2", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." + } + ] + } + ], + "desc": "

      The eventLoopUtilization() method returns an object that contains the\ncumulative duration of time the event loop has been both idle and active as a\nhigh resolution milliseconds timer. The utilization value is the calculated\nEvent Loop Utilization (ELU).

      \n

      If bootstrapping has not yet finished on the main thread the properties have\nthe value of 0. The ELU is immediately available on Worker threads since\nbootstrap happens within the event loop.

      \n

      Both utilization1 and utilization2 are optional parameters.

      \n

      If utilization1 is passed, then the delta between the current call's active\nand idle times, as well as the corresponding utilization value are\ncalculated and returned (similar to process.hrtime()).

      \n

      If utilization1 and utilization2 are both passed, then the delta is\ncalculated between the two arguments. This is a convenience option because,\nunlike process.hrtime(), calculating the ELU is more complex than a\nsingle subtraction.

      \n

      ELU is similar to CPU utilization, except that it only measures event loop\nstatistics and not CPU usage. It represents the percentage of time the event\nloop has spent outside the event loop's event provider (e.g. epoll_wait).\nNo other CPU idle time is taken into consideration. The following is an example\nof how a mostly idle process will have a high ELU.

      \n
      'use strict';\nconst { eventLoopUtilization } = require('perf_hooks').performance;\nconst { spawnSync } = require('child_process');\n\nsetImmediate(() => {\n  const elu = eventLoopUtilization();\n  spawnSync('sleep', ['5']);\n  console.log(eventLoopUtilization(elu).utilization);\n});\n
      \n

      Although the CPU is mostly idle while running this script, the value of\nutilization is 1. This is because the call to\nchild_process.spawnSync() blocks the event loop from proceeding.

      \n

      Passing in a user-defined object instead of the result of a previous call to\neventLoopUtilization() will lead to undefined behavior. The return values\nare not guaranteed to reflect any correct state of the event loop.

      " + }, + { + "textRaw": "`performance.mark([name])`", + "type": "method", + "name": "mark", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Creates a new PerformanceMark entry in the Performance Timeline. A\nPerformanceMark is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'mark', and whose\nperformanceEntry.duration is always 0. Performance marks are used\nto mark specific significant moments in the Performance Timeline.

      " + }, + { + "textRaw": "`performance.measure(name[, startMark[, endMark]])`", + "type": "method", + "name": "measure", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": "v12.16.3", + "pr-url": "https://github.com/nodejs/node/pull/32651", + "description": "Make `startMark` and `endMark` parameters optional." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`startMark` {string} Optional.", + "name": "startMark", + "type": "string", + "desc": "Optional." + }, + { + "textRaw": "`endMark` {string} Optional.", + "name": "endMark", + "type": "string", + "desc": "Optional." + } + ] + } + ], + "desc": "

      Creates a new PerformanceMeasure entry in the Performance Timeline. A\nPerformanceMeasure is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'measure', and whose\nperformanceEntry.duration measures the number of milliseconds elapsed since\nstartMark and endMark.

      \n

      The startMark argument may identify any existing PerformanceMark in the\nPerformance Timeline, or may identify any of the timestamp properties\nprovided by the PerformanceNodeTiming class. If the named startMark does\nnot exist, then startMark is set to timeOrigin by default.

      \n

      The optional endMark argument must identify any existing PerformanceMark\nin the Performance Timeline or any of the timestamp properties provided by the\nPerformanceNodeTiming class. endMark will be performance.now()\nif no parameter is passed, otherwise if the named endMark does not exist, an\nerror will be thrown.

      " + }, + { + "textRaw": "`performance.now()`", + "type": "method", + "name": "now", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [] + } + ], + "desc": "

      Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node process.

      " + }, + { + "textRaw": "`performance.timerify(fn)`", + "type": "method", + "name": "timerify", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + } + ] + } + ], + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      Wraps a function within a new function that measures the running time of the\nwrapped function. A PerformanceObserver must be subscribed to the 'function'\nevent type in order for the timing details to be accessed.

      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nfunction someFunction() {\n  console.log('hello world');\n}\n\nconst wrapped = performance.timerify(someFunction);\n\nconst obs = new PerformanceObserver((list) => {\n  console.log(list.getEntries()[0].duration);\n  obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n
      " + }, + { + "textRaw": "`performance.eventLoopUtilization([util1][,util2])`", + "type": "method", + "name": "eventLoopUtilization", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`idle` {number}", + "name": "idle", + "type": "number" + }, + { + "textRaw": "`active` {number}", + "name": "active", + "type": "number" + }, + { + "textRaw": "`utilization` {number}", + "name": "utilization", + "type": "number" + } + ] + }, + "params": [ + { + "textRaw": "`util1` {Object} The result of a previous call to `eventLoopUtilization()`", + "name": "util1", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()`" + }, + { + "textRaw": "`util2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `util1`", + "name": "util2", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()` prior to `util1`" + } + ] + } + ], + "desc": "

      The eventLoopUtilization() method returns an object that contains the\ncumulative duration of time the event loop has been both idle and active as a\nhigh resolution milliseconds timer. The utilization value is the calculated\nEvent Loop Utilization (ELU). If bootstrapping has not yet finished, the\nproperties have the value of 0.

      \n

      util1 and util2 are optional parameters.

      \n

      If util1 is passed then the delta between the current call's active and\nidle times are calculated and returned (similar to process.hrtime()).\nLikewise the adjusted utilization value is calculated.

      \n

      If util1 and util2 are both passed then the calculation adjustments are\ndone between the two arguments. This is a convenience option because unlike\nprocess.hrtime() additional work is done to calculate the ELU.

      \n

      ELU is similar to CPU utilization except that it is calculated using high\nprecision wall-clock time. It represents the percentage of time the event loop\nhas spent outside the event loop's event provider (e.g. epoll_wait). No other\nCPU idle time is taken into consideration. The following is an example of how\na mostly idle process will have a high ELU.

      \n\n
      'use strict';\nconst { eventLoopUtilization } = require('perf_hooks').performance;\nconst { spawnSync } = require('child_process');\n\nsetImmediate(() => {\n  const elu = eventLoopUtilization();\n  spawnSync('sleep', ['5']);\n  console.log(eventLoopUtilization(elu).utilization);\n});\n
      \n

      Although the CPU is mostly idle while running this script, the value of\nutilization is 1. This is because the call to child_process.spawnSync()\nblocks the event loop from proceeding.

      \n

      Passing in a user-defined object instead of the result of a previous call to\neventLoopUtilization() will lead to undefined behavior. The return values\nare not guaranteed to reflect any correct state of the event loop.

      " + } + ], + "properties": [ + { + "textRaw": "`nodeTiming` {PerformanceNodeTiming}", + "type": "PerformanceNodeTiming", + "name": "nodeTiming", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      An instance of the PerformanceNodeTiming class that provides performance\nmetrics for specific Node.js operational milestones.

      " + }, + { + "textRaw": "`timeOrigin` {number}", + "type": "number", + "name": "timeOrigin", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The timeOrigin specifies the high resolution millisecond timestamp at\nwhich the current node process began, measured in Unix time.

      " + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: `PerformanceEntry`", + "type": "class", + "name": "PerformanceEntry", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "properties": [ + { + "textRaw": "`duration` {number}", + "type": "number", + "name": "duration", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.

      " + }, + { + "textRaw": "`name` {string}", + "type": "string", + "name": "name", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The name of the performance entry.

      " + }, + { + "textRaw": "`startTime` {number}", + "type": "number", + "name": "startTime", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp marking the starting time of the\nPerformance Entry.

      " + }, + { + "textRaw": "`entryType` {string}", + "type": "string", + "name": "entryType", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The type of the performance entry. It may be one of:

      \n
        \n
      • 'node' (Node.js only)
      • \n
      • 'mark' (available on the Web)
      • \n
      • 'measure' (available on the Web)
      • \n
      • 'gc' (Node.js only)
      • \n
      • 'function' (Node.js only)
      • \n
      • 'http2' (Node.js only)
      • \n
      • 'http' (Node.js only)
      • \n
      " + }, + { + "textRaw": "`kind` {number}", + "type": "number", + "name": "kind", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      When performanceEntry.entryType is equal to 'gc', the performance.kind\nproperty identifies the type of garbage collection operation that occurred.\nThe value may be one of:

      \n
        \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
      • \n
      " + }, + { + "textRaw": "`flags` {number}", + "type": "number", + "name": "flags", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      When performanceEntry.entryType is equal to 'gc', the performance.flags\nproperty contains additional information about garbage collection operation.\nThe value may be one of:

      \n
        \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
      • \n
      " + } + ] + }, + { + "textRaw": "Class: `PerformanceNodeTiming extends PerformanceEntry`", + "type": "class", + "name": "PerformanceNodeTiming", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      Provides timing details for Node.js itself. The constructor of this class\nis not exposed to users.

      ", + "properties": [ + { + "textRaw": "`bootstrapComplete` {number}", + "type": "number", + "name": "bootstrapComplete", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js process\ncompleted bootstrapping. If bootstrapping has not yet finished, the property\nhas the value of -1.

      " + }, + { + "textRaw": "`environment` {number}", + "type": "number", + "name": "environment", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js environment was\ninitialized.

      " + }, + { + "textRaw": "`loopExit` {number}", + "type": "number", + "name": "loopExit", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js event loop\nexited. If the event loop has not yet exited, the property has the value of -1.\nIt can only have a value of not -1 in a handler of the 'exit' event.

      " + }, + { + "textRaw": "`loopStart` {number}", + "type": "number", + "name": "loopStart", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js event loop\nstarted. If the event loop has not yet started (e.g., in the first tick of the\nmain script), the property has the value of -1.

      " + }, + { + "textRaw": "`nodeStart` {number}", + "type": "number", + "name": "nodeStart", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js process was\ninitialized.

      " + }, + { + "textRaw": "`v8Start` {number}", + "type": "number", + "name": "v8Start", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the V8 platform was\ninitialized.

      " + }, + { + "textRaw": "`idleTime` {number}", + "type": "number", + "name": "idleTime", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp of the amount of time the event loop\nhas been idle within the event loop's event provider (e.g. epoll_wait). This\ndoes not take CPU usage into consideration. If the event loop has not yet\nstarted (e.g., in the first tick of the main script), the property has the\nvalue of 0.

      " + } + ] + }, + { + "textRaw": "Class: `perf_hooks.PerformanceObserver`", + "type": "class", + "name": "perf_hooks.PerformanceObserver", + "methods": [ + { + "textRaw": "`performanceObserver.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disconnects the PerformanceObserver instance from all notifications.

      " + }, + { + "textRaw": "`performanceObserver.observe(options)`", + "type": "method", + "name": "observe", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`entryTypes` {string[]} An array of strings identifying the types of `PerformanceEntry` instances the observer is interested in. If not provided an error will be thrown.", + "name": "entryTypes", + "type": "string[]", + "desc": "An array of strings identifying the types of `PerformanceEntry` instances the observer is interested in. If not provided an error will be thrown." + }, + { + "textRaw": "`buffered` {boolean} If true, the notification callback will be called using `setImmediate()` and multiple `PerformanceEntry` instance notifications will be buffered internally. If `false`, notifications will be immediate and synchronous. **Default:** `false`.", + "name": "buffered", + "type": "boolean", + "default": "`false`", + "desc": "If true, the notification callback will be called using `setImmediate()` and multiple `PerformanceEntry` instance notifications will be buffered internally. If `false`, notifications will be immediate and synchronous." + } + ] + } + ] + } + ], + "desc": "

      Subscribes the PerformanceObserver instance to notifications of new\nPerformanceEntry instances identified by options.entryTypes.

      \n

      When options.buffered is false, the callback will be invoked once for\nevery PerformanceEntry instance:

      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  // Called three times synchronously. `list` contains one item.\n});\nobs.observe({ entryTypes: ['mark'] });\n\nfor (let n = 0; n < 3; n++)\n  performance.mark(`test${n}`);\n
      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  // Called once. `list` contains three items.\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nfor (let n = 0; n < 3; n++)\n  performance.mark(`test${n}`);\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`list` {PerformanceObserverEntryList}", + "name": "list", + "type": "PerformanceObserverEntryList" + }, + { + "textRaw": "`observer` {PerformanceObserver}", + "name": "observer", + "type": "PerformanceObserver" + } + ] + } + ], + "desc": "

      PerformanceObserver objects provide notifications when new\nPerformanceEntry instances have been added to the Performance Timeline.

      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  console.log(list.getEntries());\n  observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nperformance.mark('test');\n
      \n

      Because PerformanceObserver instances introduce their own additional\nperformance overhead, instances should not be left subscribed to notifications\nindefinitely. Users should disconnect observers as soon as they are no\nlonger needed.

      \n

      The callback is invoked when a PerformanceObserver is\nnotified about new PerformanceEntry instances. The callback receives a\nPerformanceObserverEntryList instance and a reference to the\nPerformanceObserver.

      " + } + ] + }, + { + "textRaw": "Class: `PerformanceObserverEntryList`", + "type": "class", + "name": "PerformanceObserverEntryList", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The PerformanceObserverEntryList class is used to provide access to the\nPerformanceEntry instances passed to a PerformanceObserver.\nThe constructor of this class is not exposed to users.

      ", + "methods": [ + { + "textRaw": "`performanceObserverEntryList.getEntries()`", + "type": "method", + "name": "getEntries", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {PerformanceEntry[]}", + "name": "return", + "type": "PerformanceEntry[]" + }, + "params": [] + } + ], + "desc": "

      Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime.

      " + }, + { + "textRaw": "`performanceObserverEntryList.getEntriesByName(name[, type])`", + "type": "method", + "name": "getEntriesByName", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {PerformanceEntry[]}", + "name": "return", + "type": "PerformanceEntry[]" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + } + ] + } + ], + "desc": "

      Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.name is\nequal to name, and optionally, whose performanceEntry.entryType is equal to\ntype.

      " + }, + { + "textRaw": "`performanceObserverEntryList.getEntriesByType(type)`", + "type": "method", + "name": "getEntriesByType", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {PerformanceEntry[]}", + "name": "return", + "type": "PerformanceEntry[]" + }, + "params": [ + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + } + ] + } + ], + "desc": "

      Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.entryType\nis equal to type.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`perf_hooks.monitorEventLoopDelay([options])`", + "type": "method", + "name": "monitorEventLoopDelay", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Histogram}", + "name": "return", + "type": "Histogram" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`resolution` {number} The sampling rate in milliseconds. Must be greater than zero. **Default:** `10`.", + "name": "resolution", + "type": "number", + "default": "`10`", + "desc": "The sampling rate in milliseconds. Must be greater than zero." + } + ] + } + ] + } + ], + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      Creates a Histogram object that samples and reports the event loop delay\nover time. The delays will be reported in nanoseconds.

      \n

      Using a timer to detect approximate event loop delay works because the\nexecution of timers is tied specifically to the lifecycle of the libuv\nevent loop. That is, a delay in the loop will cause a delay in the execution\nof the timer, and those delays are specifically what this API is intended to\ndetect.

      \n
      const { monitorEventLoopDelay } = require('perf_hooks');\nconst h = monitorEventLoopDelay({ resolution: 20 });\nh.enable();\n// Do something.\nh.disable();\nconsole.log(h.min);\nconsole.log(h.max);\nconsole.log(h.mean);\nconsole.log(h.stddev);\nconsole.log(h.percentiles);\nconsole.log(h.percentile(50));\nconsole.log(h.percentile(99));\n
      ", + "classes": [ + { + "textRaw": "Class: `Histogram`", + "type": "class", + "name": "Histogram", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      Tracks the event loop delay at a given sampling rate. The constructor of\nthis class not exposed to users.

      \n

      This property is an extension by Node.js. It is not available in Web browsers.

      ", + "methods": [ + { + "textRaw": "`histogram.disable()`", + "type": "method", + "name": "disable", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Disables the event loop delay sample timer. Returns true if the timer was\nstopped, false if it was already stopped.

      " + }, + { + "textRaw": "`histogram.enable()`", + "type": "method", + "name": "enable", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Enables the event loop delay sample timer. Returns true if the timer was\nstarted, false if it was already started.

      " + }, + { + "textRaw": "`histogram.percentile(percentile)`", + "type": "method", + "name": "percentile", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`percentile` {number} A percentile value between 1 and 100.", + "name": "percentile", + "type": "number", + "desc": "A percentile value between 1 and 100." + } + ] + } + ], + "desc": "

      Returns the value at the given percentile.

      " + }, + { + "textRaw": "`histogram.reset()`", + "type": "method", + "name": "reset", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Resets the collected histogram data.

      " + } + ], + "properties": [ + { + "textRaw": "`exceeds` {number}", + "type": "number", + "name": "exceeds", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.

      " + }, + { + "textRaw": "`max` {number}", + "type": "number", + "name": "max", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The maximum recorded event loop delay.

      " + }, + { + "textRaw": "`mean` {number}", + "type": "number", + "name": "mean", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The mean of the recorded event loop delays.

      " + }, + { + "textRaw": "`min` {number}", + "type": "number", + "name": "min", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The minimum recorded event loop delay.

      " + }, + { + "textRaw": "`percentiles` {Map}", + "type": "Map", + "name": "percentiles", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      Returns a Map object detailing the accumulated percentile distribution.

      " + }, + { + "textRaw": "`stddev` {number}", + "type": "number", + "name": "stddev", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The standard deviation of the recorded event loop delays.

      \n

      Examples

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Measuring the duration of async operations", + "name": "measuring_the_duration_of_async_operations", + "desc": "

      The following example uses the Async Hooks and Performance APIs to measure\nthe actual duration of a Timeout operation (including the amount of time it took\nto execute the callback).

      \n
      'use strict';\nconst async_hooks = require('async_hooks');\nconst {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst set = new Set();\nconst hook = async_hooks.createHook({\n  init(id, type) {\n    if (type === 'Timeout') {\n      performance.mark(`Timeout-${id}-Init`);\n      set.add(id);\n    }\n  },\n  destroy(id) {\n    if (set.has(id)) {\n      set.delete(id);\n      performance.mark(`Timeout-${id}-Destroy`);\n      performance.measure(`Timeout-${id}`,\n                          `Timeout-${id}-Init`,\n                          `Timeout-${id}-Destroy`);\n    }\n  }\n});\nhook.enable();\n\nconst obs = new PerformanceObserver((list, observer) => {\n  console.log(list.getEntries()[0]);\n  performance.clearMarks();\n  observer.disconnect();\n});\nobs.observe({ entryTypes: ['measure'], buffered: true });\n\nsetTimeout(() => {}, 1000);\n
      ", + "type": "module", + "displayName": "Measuring the duration of async operations" + }, + { + "textRaw": "Measuring how long it takes to load dependencies", + "name": "measuring_how_long_it_takes_to_load_dependencies", + "desc": "

      The following example measures the duration of require() operations to load\ndependencies:

      \n\n
      'use strict';\nconst {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\nconst mod = require('module');\n\n// Monkey patch the require function\nmod.Module.prototype.require =\n  performance.timerify(mod.Module.prototype.require);\nrequire = performance.timerify(require);\n\n// Activate the observer\nconst obs = new PerformanceObserver((list) => {\n  const entries = list.getEntries();\n  entries.forEach((entry) => {\n    console.log(`require('${entry[0]}')`, entry.duration);\n  });\n  obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'], buffered: true });\n\nrequire('some-module');\n
      ", + "type": "module", + "displayName": "Measuring how long it takes to load dependencies" + } + ] + } + ], + "type": "module", + "displayName": "Performance measurement APIs" + }, + { + "textRaw": "Punycode", + "name": "punycode", + "meta": { + "deprecated": [ + "v7.0.0" + ], + "changes": [] + }, + "introduced_in": "v0.10.0", + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Source Code: lib/punycode.js

      \n

      The version of the punycode module bundled in Node.js is being deprecated.\nIn a future major version of Node.js this module will be removed. Users\ncurrently depending on the punycode module should switch to using the\nuserland-provided Punycode.js module instead.

      \n

      The punycode module is a bundled version of the Punycode.js module. It\ncan be accessed using:

      \n
      const punycode = require('punycode');\n
      \n

      Punycode is a character encoding scheme defined by RFC 3492 that is\nprimarily intended for use in Internationalized Domain Names. Because host\nnames in URLs are limited to ASCII characters only, Domain Names that contain\nnon-ASCII characters must be converted into ASCII using the Punycode scheme.\nFor instance, the Japanese character that translates into the English word,\n'example' is '例'. The Internationalized Domain Name, '例.com' (equivalent\nto 'example.com') is represented by Punycode as the ASCII string\n'xn--fsq.com'.

      \n

      The punycode module provides a simple implementation of the Punycode standard.

      \n

      The punycode module is a third-party dependency used by Node.js and\nmade available to developers as a convenience. Fixes or other modifications to\nthe module must be directed to the Punycode.js project.

      ", + "methods": [ + { + "textRaw": "`punycode.decode(string)`", + "type": "method", + "name": "decode", + "meta": { + "added": [ + "v0.5.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.decode() method converts a Punycode string of ASCII-only\ncharacters to the equivalent string of Unicode codepoints.

      \n
      punycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n
      " + }, + { + "textRaw": "`punycode.encode(string)`", + "type": "method", + "name": "encode", + "meta": { + "added": [ + "v0.5.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.encode() method converts a string of Unicode codepoints to a\nPunycode string of ASCII-only characters.

      \n
      punycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n
      " + }, + { + "textRaw": "`punycode.toASCII(domain)`", + "type": "method", + "name": "toASCII", + "meta": { + "added": [ + "v0.6.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.toASCII() method converts a Unicode string representing an\nInternationalized Domain Name to Punycode. Only the non-ASCII parts of the\ndomain name will be converted. Calling punycode.toASCII() on a string that\nalready only contains ASCII characters will have no effect.

      \n
      // encode domain names\npunycode.toASCII('mañana.com');  // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com');   // 'xn----dqo34k.com'\npunycode.toASCII('example.com'); // 'example.com'\n
      " + }, + { + "textRaw": "`punycode.toUnicode(domain)`", + "type": "method", + "name": "toUnicode", + "meta": { + "added": [ + "v0.6.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.toUnicode() method converts a string representing a domain name\ncontaining Punycode encoded characters into Unicode. Only the Punycode\nencoded parts of the domain name are be converted.

      \n
      // decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com');  // '☃-⌘.com'\npunycode.toUnicode('example.com');       // 'example.com'\n
      " + } + ], + "properties": [ + { + "textRaw": "`punycode.ucs2`", + "name": "ucs2", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "methods": [ + { + "textRaw": "`punycode.ucs2.decode(string)`", + "type": "method", + "name": "decode", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.ucs2.decode() method returns an array containing the numeric\ncodepoint values of each Unicode symbol in the string.

      \n
      punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]\n
      " + }, + { + "textRaw": "`punycode.ucs2.encode(codePoints)`", + "type": "method", + "name": "encode", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`codePoints` {integer[]}", + "name": "codePoints", + "type": "integer[]" + } + ] + } + ], + "desc": "

      The punycode.ucs2.encode() method returns a string based on an array of\nnumeric code point values.

      \n
      punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'\n
      " + } + ] + }, + { + "textRaw": "`version` {string}", + "type": "string", + "name": "version", + "meta": { + "added": [ + "v0.6.1" + ], + "changes": [] + }, + "desc": "

      Returns a string identifying the current Punycode.js version number.

      " + } + ], + "type": "module", + "displayName": "Punycode" + }, + { + "textRaw": "Query string", + "name": "querystring", + "introduced_in": "v0.1.25", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/querystring.js

      \n

      The querystring module provides utilities for parsing and formatting URL\nquery strings. It can be accessed using:

      \n
      const querystring = require('querystring');\n
      ", + "methods": [ + { + "textRaw": "`querystring.decode()`", + "type": "method", + "name": "decode", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The querystring.decode() function is an alias for querystring.parse().

      " + }, + { + "textRaw": "`querystring.encode()`", + "type": "method", + "name": "encode", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The querystring.encode() function is an alias for querystring.stringify().

      " + }, + { + "textRaw": "`querystring.escape(str)`", + "type": "method", + "name": "escape", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`str` {string}", + "name": "str", + "type": "string" + } + ] + } + ], + "desc": "

      The querystring.escape() method performs URL percent-encoding on the given\nstr in a manner that is optimized for the specific requirements of URL\nquery strings.

      \n

      The querystring.escape() method is used by querystring.stringify() and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement percent-encoding implementation if\nnecessary by assigning querystring.escape to an alternative function.

      " + }, + { + "textRaw": "`querystring.parse(str[, sep[, eq[, options]]])`", + "type": "method", + "name": "parse", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10967", + "description": "Multiple empty entries are now parsed correctly (e.g. `&=&=`)." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6055", + "description": "The returned object no longer inherits from `Object.prototype`." + }, + { + "version": "v6.0.0, v4.2.4", + "pr-url": "https://github.com/nodejs/node/pull/3807", + "description": "The `eq` parameter may now have a length of more than `1`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`str` {string} The URL query string to parse", + "name": "str", + "type": "string", + "desc": "The URL query string to parse" + }, + { + "textRaw": "`sep` {string} The substring used to delimit key and value pairs in the query string. **Default:** `'&'`.", + "name": "sep", + "type": "string", + "default": "`'&'`", + "desc": "The substring used to delimit key and value pairs in the query string." + }, + { + "textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. **Default:** `'='`.", + "name": "eq", + "type": "string", + "default": "`'='`", + "desc": ". The substring used to delimit keys and values in the query string." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`decodeURIComponent` {Function} The function to use when decoding percent-encoded characters in the query string. **Default:** `querystring.unescape()`.", + "name": "decodeURIComponent", + "type": "Function", + "default": "`querystring.unescape()`", + "desc": "The function to use when decoding percent-encoded characters in the query string." + }, + { + "textRaw": "`maxKeys` {number} Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. **Default:** `1000`.", + "name": "maxKeys", + "type": "number", + "default": "`1000`", + "desc": "Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations." + } + ] + } + ] + } + ], + "desc": "

      The querystring.parse() method parses a URL query string (str) into a\ncollection of key and value pairs.

      \n

      For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:

      \n\n
      {\n  foo: 'bar',\n  abc: ['xyz', '123']\n}\n
      \n

      The object returned by the querystring.parse() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.

      \n

      By default, percent-encoded characters within the query string will be assumed\nto use UTF-8 encoding. If an alternative character encoding is used, then an\nalternative decodeURIComponent option will need to be specified:

      \n
      // Assuming gbkDecodeURIComponent function already exists...\n\nquerystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,\n                  { decodeURIComponent: gbkDecodeURIComponent });\n
      " + }, + { + "textRaw": "`querystring.stringify(obj[, sep[, eq[, options]]])`", + "type": "method", + "name": "stringify", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`obj` {Object} The object to serialize into a URL query string", + "name": "obj", + "type": "Object", + "desc": "The object to serialize into a URL query string" + }, + { + "textRaw": "`sep` {string} The substring used to delimit key and value pairs in the query string. **Default:** `'&'`.", + "name": "sep", + "type": "string", + "default": "`'&'`", + "desc": "The substring used to delimit key and value pairs in the query string." + }, + { + "textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. **Default:** `'='`.", + "name": "eq", + "type": "string", + "default": "`'='`", + "desc": ". The substring used to delimit keys and values in the query string." + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`encodeURIComponent` {Function} The function to use when converting URL-unsafe characters to percent-encoding in the query string. **Default:** `querystring.escape()`.", + "name": "encodeURIComponent", + "type": "Function", + "default": "`querystring.escape()`", + "desc": "The function to use when converting URL-unsafe characters to percent-encoding in the query string." + } + ] + } + ] + } + ], + "desc": "

      The querystring.stringify() method produces a URL query string from a\ngiven obj by iterating through the object's \"own properties\".

      \n

      It serializes the following types of values passed in obj:\n<string> | <number> | <boolean> | <string[]> | <number[]> | <boolean[]>\nAny other input values will be coerced to empty strings.

      \n
      querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });\n// Returns 'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');\n// Returns 'foo:bar;baz:qux'\n
      \n

      By default, characters requiring percent-encoding within the query string will\nbe encoded as UTF-8. If an alternative encoding is required, then an alternative\nencodeURIComponent option will need to be specified:

      \n
      // Assuming gbkEncodeURIComponent function already exists,\n\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n                      { encodeURIComponent: gbkEncodeURIComponent });\n
      " + }, + { + "textRaw": "`querystring.unescape(str)`", + "type": "method", + "name": "unescape", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`str` {string}", + "name": "str", + "type": "string" + } + ] + } + ], + "desc": "

      The querystring.unescape() method performs decoding of URL percent-encoded\ncharacters on the given str.

      \n

      The querystring.unescape() method is used by querystring.parse() and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement decoding implementation if\nnecessary by assigning querystring.unescape to an alternative function.

      \n

      By default, the querystring.unescape() method will attempt to use the\nJavaScript built-in decodeURIComponent() method to decode. If that fails,\na safer equivalent that does not throw on malformed URLs will be used.

      " + } + ], + "type": "module", + "displayName": "querystring" + }, + { + "textRaw": "Readline", + "name": "readline", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/readline.js

      \n

      The readline module provides an interface for reading data from a Readable\nstream (such as process.stdin) one line at a time. It can be accessed\nusing:

      \n
      const readline = require('readline');\n
      \n

      The following simple example illustrates the basic use of the readline module.

      \n
      const readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question('What do you think of Node.js? ', (answer) => {\n  // TODO: Log the answer in a database\n  console.log(`Thank you for your valuable feedback: ${answer}`);\n\n  rl.close();\n});\n
      \n

      Once this code is invoked, the Node.js application will not terminate until the\nreadline.Interface is closed because the interface waits for data to be\nreceived on the input stream.

      ", + "classes": [ + { + "textRaw": "Class: `Interface`", + "type": "class", + "name": "Interface", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "desc": "\n

      Instances of the readline.Interface class are constructed using the\nreadline.createInterface() method. Every instance is associated with a\nsingle input Readable stream and a single output Writable stream.\nThe output stream is used to print prompts for user input that arrives on,\nand is read from, the input stream.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted when one of the following occur:

      \n
        \n
      • The rl.close() method is called and the readline.Interface instance has\nrelinquished control over the input and output streams;
      • \n
      • The input stream receives its 'end' event;
      • \n
      • The input stream receives <ctrl>-D to signal end-of-transmission (EOT);
      • \n
      • The input stream receives <ctrl>-C to signal SIGINT and there is no\n'SIGINT' event listener registered on the readline.Interface instance.
      • \n
      \n

      The listener function is called without passing any arguments.

      \n

      The readline.Interface instance is finished once the 'close' event is\nemitted.

      " + }, + { + "textRaw": "Event: `'line'`", + "type": "event", + "name": "line", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'line' event is emitted whenever the input stream receives an\nend-of-line input (\\n, \\r, or \\r\\n). This usually occurs when the user\npresses the <Enter>, or <Return> keys.

      \n

      The listener function is called with a string containing the single line of\nreceived input.

      \n
      rl.on('line', (input) => {\n  console.log(`Received: ${input}`);\n});\n
      " + }, + { + "textRaw": "Event: `'pause'`", + "type": "event", + "name": "pause", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'pause' event is emitted when one of the following occur:

      \n
        \n
      • The input stream is paused.
      • \n
      • The input stream is not paused and receives the 'SIGCONT' event. (See\nevents 'SIGTSTP' and 'SIGCONT'.)
      • \n
      \n

      The listener function is called without passing any arguments.

      \n
      rl.on('pause', () => {\n  console.log('Readline paused.');\n});\n
      " + }, + { + "textRaw": "Event: `'resume'`", + "type": "event", + "name": "resume", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resume' event is emitted whenever the input stream is resumed.

      \n

      The listener function is called without passing any arguments.

      \n
      rl.on('resume', () => {\n  console.log('Readline resumed.');\n});\n
      " + }, + { + "textRaw": "Event: `'SIGCONT'`", + "type": "event", + "name": "SIGCONT", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'SIGCONT' event is emitted when a Node.js process previously moved into\nthe background using <ctrl>-Z (i.e. SIGTSTP) is then brought back to the\nforeground using fg(1p).

      \n

      If the input stream was paused before the SIGTSTP request, this event will\nnot be emitted.

      \n

      The listener function is invoked without passing any arguments.

      \n
      rl.on('SIGCONT', () => {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});\n
      \n

      The 'SIGCONT' event is not supported on Windows.

      " + }, + { + "textRaw": "Event: `'SIGINT'`", + "type": "event", + "name": "SIGINT", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'SIGINT' event is emitted whenever the input stream receives a\n<ctrl>-C input, known typically as SIGINT. If there are no 'SIGINT' event\nlisteners registered when the input stream receives a SIGINT, the 'pause'\nevent will be emitted.

      \n

      The listener function is invoked without passing any arguments.

      \n
      rl.on('SIGINT', () => {\n  rl.question('Are you sure you want to exit? ', (answer) => {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});\n
      " + }, + { + "textRaw": "Event: `'SIGTSTP'`", + "type": "event", + "name": "SIGTSTP", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'SIGTSTP' event is emitted when the input stream receives a <ctrl>-Z\ninput, typically known as SIGTSTP. If there are no 'SIGTSTP' event listeners\nregistered when the input stream receives a SIGTSTP, the Node.js process\nwill be sent to the background.

      \n

      When the program is resumed using fg(1p), the 'pause' and 'SIGCONT' events\nwill be emitted. These can be used to resume the input stream.

      \n

      The 'pause' and 'SIGCONT' events will not be emitted if the input was\npaused before the process was sent to the background.

      \n

      The listener function is invoked without passing any arguments.

      \n
      rl.on('SIGTSTP', () => {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});\n
      \n

      The 'SIGTSTP' event is not supported on Windows.

      " + } + ], + "methods": [ + { + "textRaw": "`rl.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The rl.close() method closes the readline.Interface instance and\nrelinquishes control over the input and output streams. When called,\nthe 'close' event will be emitted.

      \n

      Calling rl.close() does not immediately stop other events (including 'line')\nfrom being emitted by the readline.Interface instance.

      " + }, + { + "textRaw": "`rl.pause()`", + "type": "method", + "name": "pause", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The rl.pause() method pauses the input stream, allowing it to be resumed\nlater if necessary.

      \n

      Calling rl.pause() does not immediately pause other events (including\n'line') from being emitted by the readline.Interface instance.

      " + }, + { + "textRaw": "`rl.prompt([preserveCursor])`", + "type": "method", + "name": "prompt", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`preserveCursor` {boolean} If `true`, prevents the cursor placement from being reset to `0`.", + "name": "preserveCursor", + "type": "boolean", + "desc": "If `true`, prevents the cursor placement from being reset to `0`." + } + ] + } + ], + "desc": "

      The rl.prompt() method writes the readline.Interface instances configured\nprompt to a new line in output in order to provide a user with a new\nlocation at which to provide input.

      \n

      When called, rl.prompt() will resume the input stream if it has been\npaused.

      \n

      If the readline.Interface was created with output set to null or\nundefined the prompt is not written.

      " + }, + { + "textRaw": "`rl.question(query, callback)`", + "type": "method", + "name": "question", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`query` {string} A statement or query to write to `output`, prepended to the prompt.", + "name": "query", + "type": "string", + "desc": "A statement or query to write to `output`, prepended to the prompt." + }, + { + "textRaw": "`callback` {Function} A callback function that is invoked with the user's input in response to the `query`.", + "name": "callback", + "type": "Function", + "desc": "A callback function that is invoked with the user's input in response to the `query`." + } + ] + } + ], + "desc": "

      The rl.question() method displays the query by writing it to the output,\nwaits for user input to be provided on input, then invokes the callback\nfunction passing the provided input as the first argument.

      \n

      When called, rl.question() will resume the input stream if it has been\npaused.

      \n

      If the readline.Interface was created with output set to null or\nundefined the query is not written.

      \n

      Example usage:

      \n
      rl.question('What is your favorite food? ', (answer) => {\n  console.log(`Oh, so your favorite food is ${answer}`);\n});\n
      \n

      The callback function passed to rl.question() does not follow the typical\npattern of accepting an Error object or null as the first argument.\nThe callback is called with the provided answer as the only argument.

      " + }, + { + "textRaw": "`rl.resume()`", + "type": "method", + "name": "resume", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The rl.resume() method resumes the input stream if it has been paused.

      " + }, + { + "textRaw": "`rl.setPrompt(prompt)`", + "type": "method", + "name": "setPrompt", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`prompt` {string}", + "name": "prompt", + "type": "string" + } + ] + } + ], + "desc": "

      The rl.setPrompt() method sets the prompt that will be written to output\nwhenever rl.prompt() is called.

      " + }, + { + "textRaw": "`rl.write(data[, key])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string}", + "name": "data", + "type": "string" + }, + { + "textRaw": "`key` {Object}", + "name": "key", + "type": "Object", + "options": [ + { + "textRaw": "`ctrl` {boolean} `true` to indicate the `` key.", + "name": "ctrl", + "type": "boolean", + "desc": "`true` to indicate the `` key." + }, + { + "textRaw": "`meta` {boolean} `true` to indicate the `` key.", + "name": "meta", + "type": "boolean", + "desc": "`true` to indicate the `` key." + }, + { + "textRaw": "`shift` {boolean} `true` to indicate the `` key.", + "name": "shift", + "type": "boolean", + "desc": "`true` to indicate the `` key." + }, + { + "textRaw": "`name` {string} The name of the a key.", + "name": "name", + "type": "string", + "desc": "The name of the a key." + } + ] + } + ] + } + ], + "desc": "

      The rl.write() method will write either data or a key sequence identified\nby key to the output. The key argument is supported only if output is\na TTY text terminal. See TTY keybindings for a list of key\ncombinations.

      \n

      If key is specified, data is ignored.

      \n

      When called, rl.write() will resume the input stream if it has been\npaused.

      \n

      If the readline.Interface was created with output set to null or\nundefined the data and key are not written.

      \n
      rl.write('Delete this!');\n// Simulate Ctrl+u to delete the line written previously\nrl.write(null, { ctrl: true, name: 'u' });\n
      \n

      The rl.write() method will write the data to the readline Interface's\ninput as if it were provided by the user.

      " + }, + { + "textRaw": "`rl[Symbol.asyncIterator]()`", + "type": "method", + "name": "[Symbol.asyncIterator]", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26989", + "description": "Symbol.asyncIterator support is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator}", + "name": "return", + "type": "AsyncIterator" + }, + "params": [] + } + ], + "desc": "

      Create an AsyncIterator object that iterates through each line in the input\nstream as a string. This method allows asynchronous iteration of\nreadline.Interface objects through for await...of loops.

      \n

      Errors in the input stream are not forwarded.

      \n

      If the loop is terminated with break, throw, or return,\nrl.close() will be called. In other words, iterating over a\nreadline.Interface will always consume the input stream fully.

      \n

      Performance is not on par with the traditional 'line' event API. Use 'line'\ninstead for performance-sensitive applications.

      \n
      async function processLineByLine() {\n  const rl = readline.createInterface({\n    // ...\n  });\n\n  for await (const line of rl) {\n    // Each line in the readline input will be successively available here as\n    // `line`.\n  }\n}\n
      " + }, + { + "textRaw": "`rl.getCursorPos()`", + "type": "method", + "name": "getCursorPos", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`rows` {number} the row of the prompt the cursor currently lands on", + "name": "rows", + "type": "number", + "desc": "the row of the prompt the cursor currently lands on" + }, + { + "textRaw": "`cols` {number} the screen column the cursor currently lands on", + "name": "cols", + "type": "number", + "desc": "the screen column the cursor currently lands on" + } + ] + }, + "params": [] + } + ], + "desc": "

      Returns the real position of the cursor in relation to the input\nprompt + string. Long input (wrapping) strings, as well as multiple\nline prompts are included in the calculations.

      " + } + ], + "properties": [ + { + "textRaw": "`line` {string|undefined}", + "type": "string|undefined", + "name": "line", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "desc": "

      The current input data being processed by node.

      \n

      This can be used when collecting input from a TTY stream to retrieve the\ncurrent value that has been processed thus far, prior to the line event\nbeing emitted. Once the line event has been emitted, this property will\nbe an empty string.

      \n

      Be aware that modifying the value during the instance runtime may have\nunintended consequences if rl.cursor is not also controlled.

      \n

      If not using a TTY stream for input, use the 'line' event.

      \n

      One possible use case would be as follows:

      \n
      const values = ['lorem ipsum', 'dolor sit amet'];\nconst rl = readline.createInterface(process.stdin);\nconst showResults = debounce(() => {\n  console.log(\n    '\\n',\n    values.filter((val) => val.startsWith(rl.line)).join(' ')\n  );\n}, 300);\nprocess.stdin.on('keypress', (c, k) => {\n  showResults();\n});\n
      " + }, + { + "textRaw": "`cursor` {number|undefined}", + "type": "number|undefined", + "name": "cursor", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "desc": "

      The cursor position relative to rl.line.

      \n

      This will track where the current cursor lands in the input string, when\nreading input from a TTY stream. The position of cursor determines the\nportion of the input string that will be modified as input is processed,\nas well as the column where the terminal caret will be rendered.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`readline.clearLine(stream, dir[, callback])`", + "type": "method", + "name": "clearLine", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28674", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`dir` {number}", + "name": "dir", + "type": "number", + "options": [ + { + "textRaw": "`-1`: to the left from cursor", + "name": "-1", + "desc": "to the left from cursor" + }, + { + "textRaw": "`1`: to the right from cursor", + "name": "1", + "desc": "to the right from cursor" + }, + { + "textRaw": "`0`: the entire line", + "name": "0", + "desc": "the entire line" + } + ] + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.clearLine() method clears current line of given TTY stream\nin a specified direction identified by dir.

      " + }, + { + "textRaw": "`readline.clearScreenDown(stream[, callback])`", + "type": "method", + "name": "clearScreenDown", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28641", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.clearScreenDown() method clears the given TTY stream from\nthe current position of the cursor down.

      " + }, + { + "textRaw": "`readline.createInterface(options)`", + "type": "method", + "name": "createInterface", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [ + { + "version": "v8.3.0, 6.11.4", + "pr-url": "https://github.com/nodejs/node/pull/13497", + "description": "Remove max limit of `crlfDelay` option." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8109", + "description": "The `crlfDelay` option is supported now." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/7125", + "description": "The `prompt` option is supported now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6352", + "description": "The `historySize` option can be `0` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`input` {stream.Readable} The [Readable][] stream to listen to. This option is *required*.", + "name": "input", + "type": "stream.Readable", + "desc": "The [Readable][] stream to listen to. This option is *required*." + }, + { + "textRaw": "`output` {stream.Writable} The [Writable][] stream to write readline data to.", + "name": "output", + "type": "stream.Writable", + "desc": "The [Writable][] stream to write readline data to." + }, + { + "textRaw": "`completer` {Function} An optional function used for Tab autocompletion.", + "name": "completer", + "type": "Function", + "desc": "An optional function used for Tab autocompletion." + }, + { + "textRaw": "`terminal` {boolean} `true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. **Default:** checking `isTTY` on the `output` stream upon instantiation.", + "name": "terminal", + "type": "boolean", + "default": "checking `isTTY` on the `output` stream upon instantiation", + "desc": "`true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it." + }, + { + "textRaw": "`historySize` {number} Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all. **Default:** `30`.", + "name": "historySize", + "type": "number", + "default": "`30`", + "desc": "Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all." + }, + { + "textRaw": "`prompt` {string} The prompt string to use. **Default:** `'> '`.", + "name": "prompt", + "type": "string", + "default": "`'> '`", + "desc": "The prompt string to use." + }, + { + "textRaw": "`crlfDelay` {number} If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter). **Default:** `100`.", + "name": "crlfDelay", + "type": "number", + "default": "`100`", + "desc": "If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter)." + }, + { + "textRaw": "`removeHistoryDuplicates` {boolean} If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list. **Default:** `false`.", + "name": "removeHistoryDuplicates", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list." + }, + { + "textRaw": "`escapeCodeTimeout` {number} The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence). **Default:** `500`.", + "name": "escapeCodeTimeout", + "type": "number", + "default": "`500`", + "desc": "The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence)." + } + ] + } + ] + } + ], + "desc": "

      The readline.createInterface() method creates a new readline.Interface\ninstance.

      \n
      const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n
      \n

      Once the readline.Interface instance is created, the most common case is to\nlisten for the 'line' event:

      \n
      rl.on('line', (line) => {\n  console.log(`Received: ${line}`);\n});\n
      \n

      If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property and emits\na 'resize' event on the output if or when the columns ever change\n(process.stdout does this automatically when it is a TTY).

      ", + "modules": [ + { + "textRaw": "Use of the `completer` function", + "name": "use_of_the_`completer`_function", + "desc": "

      The completer function takes the current line entered by the user\nas an argument, and returns an Array with 2 entries:

      \n
        \n
      • An Array with matching entries for the completion.
      • \n
      • The substring that was used for the matching.
      • \n
      \n

      For instance: [[substr1, substr2, ...], originalsubstring].

      \n
      function completer(line) {\n  const completions = '.help .error .exit .quit .q'.split(' ');\n  const hits = completions.filter((c) => c.startsWith(line));\n  // Show all completions if none found\n  return [hits.length ? hits : completions, line];\n}\n
      \n

      The completer function can be called asynchronously if it accepts two\narguments:

      \n
      function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}\n
      ", + "type": "module", + "displayName": "Use of the `completer` function" + } + ] + }, + { + "textRaw": "`readline.cursorTo(stream, x[, y][, callback])`", + "type": "method", + "name": "cursorTo", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28674", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`x` {number}", + "name": "x", + "type": "number" + }, + { + "textRaw": "`y` {number}", + "name": "y", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.cursorTo() method moves cursor to the specified position in a\ngiven TTY stream.

      " + }, + { + "textRaw": "`readline.emitKeypressEvents(stream[, interface])`", + "type": "method", + "name": "emitKeypressEvents", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`stream` {stream.Readable}", + "name": "stream", + "type": "stream.Readable" + }, + { + "textRaw": "`interface` {readline.Interface}", + "name": "interface", + "type": "readline.Interface" + } + ] + } + ], + "desc": "

      The readline.emitKeypressEvents() method causes the given Readable\nstream to begin emitting 'keypress' events corresponding to received input.

      \n

      Optionally, interface specifies a readline.Interface instance for which\nautocompletion is disabled when copy-pasted input is detected.

      \n

      If the stream is a TTY, then it must be in raw mode.

      \n

      This is automatically called by any readline instance on its input if the\ninput is a terminal. Closing the readline instance does not stop\nthe input from emitting 'keypress' events.

      \n
      readline.emitKeypressEvents(process.stdin);\nif (process.stdin.isTTY)\n  process.stdin.setRawMode(true);\n
      " + }, + { + "textRaw": "`readline.moveCursor(stream, dx, dy[, callback])`", + "type": "method", + "name": "moveCursor", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28674", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`dx` {number}", + "name": "dx", + "type": "number" + }, + { + "textRaw": "`dy` {number}", + "name": "dy", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.moveCursor() method moves the cursor relative to its current\nposition in a given TTY stream.

      \n

      Example: Tiny CLI

      \n

      The following example illustrates the use of readline.Interface class to\nimplement a small command-line interface:

      \n
      const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout,\n  prompt: 'OHAI> '\n});\n\nrl.prompt();\n\nrl.on('line', (line) => {\n  switch (line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log(`Say what? I might have heard '${line.trim()}'`);\n      break;\n  }\n  rl.prompt();\n}).on('close', () => {\n  console.log('Have a great day!');\n  process.exit(0);\n});\n
      \n

      Example: Read file stream line-by-Line

      \n

      A common use case for readline is to consume an input file one line at a\ntime. The easiest way to do so is leveraging the fs.ReadStream API as\nwell as a for await...of loop:

      \n
      const fs = require('fs');\nconst readline = require('readline');\n\nasync function processLineByLine() {\n  const fileStream = fs.createReadStream('input.txt');\n\n  const rl = readline.createInterface({\n    input: fileStream,\n    crlfDelay: Infinity\n  });\n  // Note: we use the crlfDelay option to recognize all instances of CR LF\n  // ('\\r\\n') in input.txt as a single line break.\n\n  for await (const line of rl) {\n    // Each line in input.txt will be successively available here as `line`.\n    console.log(`Line from file: ${line}`);\n  }\n}\n\nprocessLineByLine();\n
      \n

      Alternatively, one could use the 'line' event:

      \n
      const fs = require('fs');\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: fs.createReadStream('sample.txt'),\n  crlfDelay: Infinity\n});\n\nrl.on('line', (line) => {\n  console.log(`Line from file: ${line}`);\n});\n
      \n

      Currently, for await...of loop can be a bit slower. If async / await\nflow and speed are both essential, a mixed approach can be applied:

      \n
      const { once } = require('events');\nconst { createReadStream } = require('fs');\nconst { createInterface } = require('readline');\n\n(async function processLineByLine() {\n  try {\n    const rl = createInterface({\n      input: createReadStream('big-file.txt'),\n      crlfDelay: Infinity\n    });\n\n    rl.on('line', (line) => {\n      // Process the line.\n    });\n\n    await once(rl, 'close');\n\n    console.log('File processed.');\n  } catch (err) {\n    console.error(err);\n  }\n})();\n
      " + } + ], + "modules": [ + { + "textRaw": "TTY keybindings", + "name": "tty_keybindings", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      KeybindingsDescriptionNotes
      ctrl + shift + backspaceDelete line leftDoesn't work on Linux, Mac and Windows
      ctrl + shift + deleteDelete line rightDoesn't work on Mac
      ctrl + cEmit SIGINT or close the readline instance
      ctrl + hDelete left
      ctrl + dDelete right or close the readline instance in case the current line is empty / EOFDoesn't work on Windows
      ctrl + uDelete from the current position to the line start
      ctrl + kDelete from the current position to the end of line
      ctrl + aGo to start of line
      ctrl + eGo to to end of line
      ctrl + bBack one character
      ctrl + fForward one character
      ctrl + lClear screen
      ctrl + nNext history item
      ctrl + pPrevious history item
      ctrl + zMoves running process into background. Type\n fg and press enter\n to return.Doesn't work on Windows
      ctrl + w or ctrl\n + backspaceDelete backward to a word boundaryctrl + backspace Doesn't\n work on Linux, Mac and Windows
      ctrl + deleteDelete forward to a word boundaryDoesn't work on Mac
      ctrl + left or\n meta + bWord leftctrl + left Doesn't work\n on Mac
      ctrl + right or\n meta + fWord rightctrl + right Doesn't work\n on Mac
      meta + d or meta\n + deleteDelete word rightmeta + delete Doesn't work\n on windows
      meta + backspaceDelete word leftDoesn't work on Mac
      ", + "type": "module", + "displayName": "TTY keybindings" + } + ], + "type": "module", + "displayName": "Readline" + }, + { + "textRaw": "REPL", + "name": "repl", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/repl.js

      \n

      The repl module provides a Read-Eval-Print-Loop (REPL) implementation that\nis available both as a standalone program or includible in other applications.\nIt can be accessed using:

      \n
      const repl = require('repl');\n
      ", + "modules": [ + { + "textRaw": "Design and features", + "name": "design_and_features", + "desc": "

      The repl module exports the repl.REPLServer class. While running,\ninstances of repl.REPLServer will accept individual lines of user input,\nevaluate those according to a user-defined evaluation function, then output the\nresult. Input and output may be from stdin and stdout, respectively, or may\nbe connected to any Node.js stream.

      \n

      Instances of repl.REPLServer support automatic completion of inputs,\ncompletion preview, simplistic Emacs-style line editing, multi-line inputs,\nZSH-like reverse-i-search, ZSH-like substring-based history search,\nANSI-styled output, saving and restoring current REPL session state, error\nrecovery, and customizable evaluation functions. Terminals that do not support\nANSI styles and Emacs-style line editing automatically fall back to a limited\nfeature set.

      ", + "modules": [ + { + "textRaw": "Commands and special keys", + "name": "commands_and_special_keys", + "desc": "

      The following special commands are supported by all REPL instances:

      \n
        \n
      • .break: When in the process of inputting a multi-line expression, entering\nthe .break command (or pressing the <ctrl>-C key combination) will abort\nfurther input or processing of that expression.
      • \n
      • .clear: Resets the REPL context to an empty object and clears any\nmulti-line expression being input.
      • \n
      • .exit: Close the I/O stream, causing the REPL to exit.
      • \n
      • .help: Show this list of special commands.
      • \n
      • .save: Save the current REPL session to a file:\n> .save ./file/to/save.js
      • \n
      • .load: Load a file into the current REPL session.\n> .load ./file/to/load.js
      • \n
      • .editor: Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel).
      • \n
      \n
      > .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n  return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>\n
      \n

      The following key combinations in the REPL have these special effects:

      \n
        \n
      • <ctrl>-C: When pressed once, has the same effect as the .break command.\nWhen pressed twice on a blank line, has the same effect as the .exit\ncommand.
      • \n
      • <ctrl>-D: Has the same effect as the .exit command.
      • \n
      • <tab>: When pressed on a blank line, displays global and local (scope)\nvariables. When pressed while entering other input, displays relevant\nautocompletion options.
      • \n
      \n

      For key bindings related to the reverse-i-search, see reverse-i-search.\nFor all other key bindings, see TTY keybindings.

      ", + "type": "module", + "displayName": "Commands and special keys" + }, + { + "textRaw": "Default evaluation", + "name": "default_evaluation", + "desc": "

      By default, all instances of repl.REPLServer use an evaluation function\nthat evaluates JavaScript expressions and provides access to Node.js built-in\nmodules. This default behavior can be overridden by passing in an alternative\nevaluation function when the repl.REPLServer instance is created.

      ", + "modules": [ + { + "textRaw": "JavaScript expressions", + "name": "javascript_expressions", + "desc": "

      The default evaluator supports direct evaluation of JavaScript expressions:

      \n
      > 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n
      \n

      Unless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const, let, or var keywords\nare declared at the global scope.

      ", + "type": "module", + "displayName": "JavaScript expressions" + }, + { + "textRaw": "Global and local scope", + "name": "global_and_local_scope", + "desc": "

      The default evaluator provides access to any variables that exist in the global\nscope. It is possible to expose a variable to the REPL explicitly by assigning\nit to the context object associated with each REPLServer:

      \n
      const repl = require('repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n
      \n

      Properties in the context object appear as local within the REPL:

      \n
      $ node repl_test.js\n> m\n'message'\n
      \n

      Context properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using Object.defineProperty():

      \n
      const repl = require('repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n  configurable: false,\n  enumerable: true,\n  value: msg\n});\n
      ", + "type": "module", + "displayName": "Global and local scope" + }, + { + "textRaw": "Accessing core Node.js modules", + "name": "accessing_core_node.js_modules", + "desc": "

      The default evaluator will automatically load Node.js core modules into the\nREPL environment when used. For instance, unless otherwise declared as a\nglobal or scoped variable, the input fs will be evaluated on-demand as\nglobal.fs = require('fs').

      \n
      > fs.createReadStream('./some/file');\n
      ", + "type": "module", + "displayName": "Accessing core Node.js modules" + }, + { + "textRaw": "Global uncaught exceptions", + "name": "global_uncaught_exceptions", + "meta": { + "changes": [ + { + "version": "v12.3.0", + "pr-url": "https://github.com/nodejs/node/pull/27151", + "description": "The `'uncaughtException'` event is from now on triggered if the repl is used as standalone program." + } + ] + }, + "desc": "

      The REPL uses the domain module to catch all uncaught exceptions for that\nREPL session.

      \n

      This use of the domain module in the REPL has these side effects:

      \n\n

      As standalone program:

      \n
      process.on('uncaughtException', () => console.log('Uncaught'));\n\nthrow new Error('foobar');\n// Uncaught\n
      \n

      When used in another application:

      \n
      process.on('uncaughtException', () => console.log('Uncaught'));\n// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n// cannot be used in the REPL\n\nthrow new Error('foobar');\n// Thrown:\n// Error: foobar\n
      ", + "type": "module", + "displayName": "Global uncaught exceptions" + }, + { + "textRaw": "Assignment of the `_` (underscore) variable", + "name": "assignment_of_the_`_`_(underscore)_variable", + "meta": { + "changes": [ + { + "version": "v9.8.0", + "pr-url": "https://github.com/nodejs/node/pull/18919", + "description": "Added `_error` support." + } + ] + }, + "desc": "

      The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable _ (underscore).\nExplicitly setting _ to a value will disable this behavior.

      \n
      > [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4\n
      \n

      Similarly, _error will refer to the last seen error, if there was any.\nExplicitly setting _error to a value will disable this behavior.

      \n
      > throw new Error('foo');\nError: foo\n> _error.message\n'foo'\n
      ", + "type": "module", + "displayName": "Assignment of the `_` (underscore) variable" + }, + { + "textRaw": "`await` keyword", + "name": "`await`_keyword", + "desc": "

      With the --experimental-repl-await command line option specified,\nexperimental support for the await keyword is enabled.

      \n
      > await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nError: REPL await\n    at repl:1:45\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined\n
      ", + "type": "module", + "displayName": "`await` keyword" + } + ], + "type": "module", + "displayName": "Default evaluation" + }, + { + "textRaw": "Reverse-i-search", + "name": "reverse-i-search", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      The REPL supports bi-directional reverse-i-search similar to ZSH. It is\ntriggered with <ctrl> + R to search backward and <ctrl> + S to search\nforward.

      \n

      Duplicated history entires will be skipped.

      \n

      Entries are accepted as soon as any button is pressed that doesn't correspond\nwith the reverse search. Cancelling is possible by pressing escape or\n<ctrl> + C.

      \n

      Changing the direction immediately searches for the next entry in the expected\ndirection from the current position on.

      ", + "type": "module", + "displayName": "Reverse-i-search" + }, + { + "textRaw": "Custom evaluation functions", + "name": "custom_evaluation_functions", + "desc": "

      When a new repl.REPLServer is created, a custom evaluation function may be\nprovided. This can be used, for instance, to implement fully customized REPL\napplications.

      \n

      The following illustrates a hypothetical example of a REPL that performs\ntranslation of text from one language to another:

      \n
      const repl = require('repl');\nconst { Translator } = require('translator');\n\nconst myTranslator = new Translator('en', 'fr');\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, myTranslator.translate(cmd));\n}\n\nrepl.start({ prompt: '> ', eval: myEval });\n
      ", + "modules": [ + { + "textRaw": "Recoverable errors", + "name": "recoverable_errors", + "desc": "

      As a user is typing input into the REPL prompt, pressing the <enter> key will\nsend the current line of input to the eval function. In order to support\nmulti-line input, the eval function can return an instance of repl.Recoverable\nto the provided callback function:

      \n
      function myEval(cmd, context, filename, callback) {\n  let result;\n  try {\n    result = vm.runInThisContext(cmd);\n  } catch (e) {\n    if (isRecoverableError(e)) {\n      return callback(new repl.Recoverable(e));\n    }\n  }\n  callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n  if (error.name === 'SyntaxError') {\n    return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n  }\n  return false;\n}\n
      ", + "type": "module", + "displayName": "Recoverable errors" + } + ], + "type": "module", + "displayName": "Custom evaluation functions" + }, + { + "textRaw": "Customizing REPL output", + "name": "customizing_repl_output", + "desc": "

      By default, repl.REPLServer instances format output using the\nutil.inspect() method before writing the output to the provided Writable\nstream (process.stdout by default). The showProxy inspection option is set\nto true by default and the colors option is set to true depending on the\nREPL's useColors option.

      \n

      The useColors boolean option can be specified at construction to instruct the\ndefault writer to use ANSI style codes to colorize the output from the\nutil.inspect() method.

      \n

      If the REPL is run as standalone program, it is also possible to change the\nREPL's inspection defaults from inside the REPL by using the\ninspect.replDefaults property which mirrors the defaultOptions from\nutil.inspect().

      \n
      > util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n  1\n]\n>\n
      \n

      To fully customize the output of a repl.REPLServer instance pass in a new\nfunction for the writer option on construction. The following example, for\ninstance, simply converts any input text to upper case:

      \n
      const repl = require('repl');\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, cmd);\n}\n\nfunction myWriter(output) {\n  return output.toUpperCase();\n}\n
      ", + "type": "module", + "displayName": "Customizing REPL output" + } + ], + "type": "module", + "displayName": "Design and features" + }, + { + "textRaw": "The Node.js REPL", + "name": "the_node.js_repl", + "desc": "

      Node.js itself uses the repl module to provide its own interactive interface\nfor executing JavaScript. This can be used by executing the Node.js binary\nwithout passing any arguments (or by passing the -i argument):

      \n
      $ node\n> const a = [1, 2, 3];\nundefined\n> a\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n...   console.log(v);\n...   });\n1\n2\n3\n
      ", + "modules": [ + { + "textRaw": "Environment variable options", + "name": "environment_variable_options", + "desc": "

      Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:

      \n
        \n
      • NODE_REPL_HISTORY: When a valid path is given, persistent REPL history\nwill be saved to the specified file rather than .node_repl_history in the\nuser's home directory. Setting this value to '' (an empty string) will\ndisable persistent REPL history. Whitespace will be trimmed from the value.\nOn Windows platforms environment variables with empty values are invalid so\nset this variable to one or more spaces to disable persistent REPL history.
      • \n
      • NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be\npersisted if history is available. Must be a positive number.\nDefault: 1000.
      • \n
      • NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default:\n'sloppy', which will allow non-strict mode code to be run.
      • \n
      ", + "type": "module", + "displayName": "Environment variable options" + }, + { + "textRaw": "Persistent history", + "name": "persistent_history", + "desc": "

      By default, the Node.js REPL will persist history between node REPL sessions\nby saving inputs to a .node_repl_history file located in the user's home\ndirectory. This can be disabled by setting the environment variable\nNODE_REPL_HISTORY=''.

      ", + "type": "module", + "displayName": "Persistent history" + }, + { + "textRaw": "Using the Node.js REPL with advanced line-editors", + "name": "using_the_node.js_repl_with_advanced_line-editors", + "desc": "

      For advanced line-editors, start Node.js with the environment variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings, which will allow use with rlwrap.

      \n

      For example, the following can be added to a .bashrc file:

      \n
      alias node=\"env NODE_NO_READLINE=1 rlwrap node\"\n
      ", + "type": "module", + "displayName": "Using the Node.js REPL with advanced line-editors" + }, + { + "textRaw": "Starting multiple REPL instances against a single running instance", + "name": "starting_multiple_repl_instances_against_a_single_running_instance", + "desc": "

      It is possible to create and run multiple REPL instances against a single\nrunning instance of Node.js that share a single global object but have\nseparate I/O interfaces.

      \n

      The following example, for instance, provides separate REPLs on stdin, a Unix\nsocket, and a TCP socket:

      \n
      const net = require('net');\nconst repl = require('repl');\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    input: socket,\n    output: socket\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen('/tmp/node-repl-sock');\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    input: socket,\n    output: socket\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);\n
      \n

      Running this application from the command line will start a REPL on stdin.\nOther REPL clients may connect through the Unix socket or TCP socket. telnet,\nfor instance, is useful for connecting to TCP sockets, while socat can be used\nto connect to both Unix and TCP sockets.

      \n

      By starting a REPL from a Unix socket-based server instead of stdin, it is\npossible to connect to a long-running Node.js process without restarting it.

      \n

      For an example of running a \"full-featured\" (terminal) REPL over\na net.Server and net.Socket instance, see:\nhttps://gist.github.com/TooTallNate/2209310.

      \n

      For an example of running a REPL instance over curl(1), see:\nhttps://gist.github.com/TooTallNate/2053342.

      ", + "type": "module", + "displayName": "Starting multiple REPL instances against a single running instance" + } + ], + "type": "module", + "displayName": "The Node.js REPL" + } + ], + "classes": [ + { + "textRaw": "Class: `REPLServer`", + "type": "class", + "name": "REPLServer", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [] + }, + "desc": "\n

      Instances of repl.REPLServer are created using the repl.start() method\nor directly using the JavaScript new keyword.

      \n
      const repl = require('repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n
      ", + "events": [ + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'exit' event is emitted when the REPL is exited either by receiving the\n.exit command as input, the user pressing <ctrl>-C twice to signal SIGINT,\nor by pressing <ctrl>-D to signal 'end' on the input stream. The listener\ncallback is invoked without any arguments.

      \n
      replServer.on('exit', () => {\n  console.log('Received \"exit\" event from repl!');\n  process.exit();\n});\n
      " + }, + { + "textRaw": "Event: `'reset'`", + "type": "event", + "name": "reset", + "meta": { + "added": [ + "v0.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'reset' event is emitted when the REPL's context is reset. This occurs\nwhenever the .clear command is received as input unless the REPL is using\nthe default evaluator and the repl.REPLServer instance was created with the\nuseGlobal option set to true. The listener callback will be called with a\nreference to the context object as the only argument.

      \n

      This can be used primarily to re-initialize REPL context to some pre-defined\nstate:

      \n
      const repl = require('repl');\n\nfunction initializeContext(context) {\n  context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n
      \n

      When this code is executed, the global 'm' variable can be modified but then\nreset to its initial value using the .clear command:

      \n
      $ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n
      " + } + ], + "methods": [ + { + "textRaw": "`replServer.defineCommand(keyword, cmd)`", + "type": "method", + "name": "defineCommand", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`keyword` {string} The command keyword (*without* a leading `.` character).", + "name": "keyword", + "type": "string", + "desc": "The command keyword (*without* a leading `.` character)." + }, + { + "textRaw": "`cmd` {Object|Function} The function to invoke when the command is processed.", + "name": "cmd", + "type": "Object|Function", + "desc": "The function to invoke when the command is processed." + } + ] + } + ], + "desc": "

      The replServer.defineCommand() method is used to add new .-prefixed commands\nto the REPL instance. Such commands are invoked by typing a . followed by the\nkeyword. The cmd is either a Function or an Object with the following\nproperties:

      \n
        \n
      • help <string> Help text to be displayed when .help is entered (Optional).
      • \n
      • action <Function> The function to execute, optionally accepting a single\nstring argument.
      • \n
      \n

      The following example shows two new commands added to the REPL instance:

      \n
      const repl = require('repl');\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action(name) {\n    this.clearBufferedCommand();\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  }\n});\nreplServer.defineCommand('saybye', function saybye() {\n  console.log('Goodbye!');\n  this.close();\n});\n
      \n

      The new commands can then be used from within the REPL instance:

      \n
      > .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n
      " + }, + { + "textRaw": "`replServer.displayPrompt([preserveCursor])`", + "type": "method", + "name": "displayPrompt", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`preserveCursor` {boolean}", + "name": "preserveCursor", + "type": "boolean" + } + ] + } + ], + "desc": "

      The replServer.displayPrompt() method readies the REPL instance for input\nfrom the user, printing the configured prompt to a new line in the output\nand resuming the input to accept new input.

      \n

      When multi-line input is being entered, an ellipsis is printed rather than the\n'prompt'.

      \n

      When preserveCursor is true, the cursor placement will not be reset to 0.

      \n

      The replServer.displayPrompt method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand() method.

      " + }, + { + "textRaw": "`replServer.clearBufferedCommand()`", + "type": "method", + "name": "clearBufferedCommand", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The replServer.clearBufferedCommand() method clears any command that has been\nbuffered but not yet executed. This method is primarily intended to be\ncalled from within the action function for commands registered using the\nreplServer.defineCommand() method.

      " + }, + { + "textRaw": "`replServer.parseREPLKeyword(keyword[, rest])`", + "type": "method", + "name": "parseREPLKeyword", + "meta": { + "added": [ + "v0.8.9" + ], + "deprecated": [ + "v9.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`keyword` {string} the potential keyword to parse and execute", + "name": "keyword", + "type": "string", + "desc": "the potential keyword to parse and execute" + }, + { + "textRaw": "`rest` {any} any parameters to the keyword command", + "name": "rest", + "type": "any", + "desc": "any parameters to the keyword command" + } + ] + } + ], + "desc": "

      An internal method used to parse and execute REPLServer keywords.\nReturns true if keyword is a valid keyword, otherwise false.

      " + }, + { + "textRaw": "`replServer.setupHistory(historyPath, callback)`", + "type": "method", + "name": "setupHistory", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`historyPath` {string} the path to the history file", + "name": "historyPath", + "type": "string", + "desc": "the path to the history file" + }, + { + "textRaw": "`callback` {Function} called when history writes are ready or upon error", + "name": "callback", + "type": "Function", + "desc": "called when history writes are ready or upon error", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`repl` {repl.REPLServer}", + "name": "repl", + "type": "repl.REPLServer" + } + ] + } + ] + } + ], + "desc": "

      Initializes a history log file for the REPL instance. When executing the\nNode.js binary and using the command line REPL, a history file is initialized\nby default. However, this is not the case when creating a REPL\nprogrammatically. Use this method to initialize a history log file when working\nwith REPL instances programmatically.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`repl.start([options])`", + "type": "method", + "name": "start", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/30811", + "description": "The `preview` option is now available." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26518", + "description": "The `terminal` option now follows the default description in all cases and `useColors` checks `hasColors()` if available." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19187", + "description": "The `REPL_MAGIC_MODE` `replMode` was removed." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakEvalOnSigint` option is supported now." + }, + { + "version": "v5.8.0", + "pr-url": "https://github.com/nodejs/node/pull/5388", + "description": "The `options` parameter is optional now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {repl.REPLServer}", + "name": "return", + "type": "repl.REPLServer" + }, + "params": [ + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`prompt` {string} The input prompt to display. **Default:** `'> '` (with a trailing space).", + "name": "prompt", + "type": "string", + "default": "`'> '` (with a trailing space)", + "desc": "The input prompt to display." + }, + { + "textRaw": "`input` {stream.Readable} The `Readable` stream from which REPL input will be read. **Default:** `process.stdin`.", + "name": "input", + "type": "stream.Readable", + "default": "`process.stdin`", + "desc": "The `Readable` stream from which REPL input will be read." + }, + { + "textRaw": "`output` {stream.Writable} The `Writable` stream to which REPL output will be written. **Default:** `process.stdout`.", + "name": "output", + "type": "stream.Writable", + "default": "`process.stdout`", + "desc": "The `Writable` stream to which REPL output will be written." + }, + { + "textRaw": "`terminal` {boolean} If `true`, specifies that the `output` should be treated as a TTY terminal. **Default:** checking the value of the `isTTY` property on the `output` stream upon instantiation.", + "name": "terminal", + "type": "boolean", + "default": "checking the value of the `isTTY` property on the `output` stream upon instantiation", + "desc": "If `true`, specifies that the `output` should be treated as a TTY terminal." + }, + { + "textRaw": "`eval` {Function} The function to be used when evaluating each given line of input. **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines.", + "name": "eval", + "type": "Function", + "default": "an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines", + "desc": "The function to be used when evaluating each given line of input." + }, + { + "textRaw": "`useColors` {boolean} If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect. **Default:** checking color support on the `output` stream if the REPL instance's `terminal` value is `true`.", + "name": "useColors", + "type": "boolean", + "default": "checking color support on the `output` stream if the REPL instance's `terminal` value is `true`", + "desc": "If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect." + }, + { + "textRaw": "`useGlobal` {boolean} If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`. **Default:** `false`.", + "name": "useGlobal", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`." + }, + { + "textRaw": "`ignoreUndefined` {boolean} If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. **Default:** `false`.", + "name": "ignoreUndefined", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`." + }, + { + "textRaw": "`writer` {Function} The function to invoke to format the output of each command before writing to `output`. **Default:** [`util.inspect()`][].", + "name": "writer", + "type": "Function", + "default": "[`util.inspect()`][]", + "desc": "The function to invoke to format the output of each command before writing to `output`." + }, + { + "textRaw": "`completer` {Function} An optional function used for custom Tab auto completion. See [`readline.InterfaceCompleter`][] for an example.", + "name": "completer", + "type": "Function", + "desc": "An optional function used for custom Tab auto completion. See [`readline.InterfaceCompleter`][] for an example." + }, + { + "textRaw": "`replMode` {symbol} A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:", + "name": "replMode", + "type": "symbol", + "desc": "A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:", + "options": [ + { + "textRaw": "`repl.REPL_MODE_SLOPPY` to evaluate expressions in sloppy mode.", + "name": "repl.REPL_MODE_SLOPPY", + "desc": "to evaluate expressions in sloppy mode." + }, + { + "textRaw": "`repl.REPL_MODE_STRICT` to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`.", + "name": "repl.REPL_MODE_STRICT", + "desc": "to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`." + } + ] + }, + { + "textRaw": "`breakEvalOnSigint` {boolean} Stop evaluating the current piece of code when `SIGINT` is received, such as when `Ctrl+C` is pressed. This cannot be used together with a custom `eval` function. **Default:** `false`.", + "name": "breakEvalOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "Stop evaluating the current piece of code when `SIGINT` is received, such as when `Ctrl+C` is pressed. This cannot be used together with a custom `eval` function." + }, + { + "textRaw": "`preview` {boolean} Defines if the repl prints autocomplete and output previews or not. **Default:** `true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect.", + "name": "preview", + "type": "boolean", + "default": "`true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect", + "desc": "Defines if the repl prints autocomplete and output previews or not." + } + ] + } + ] + } + ], + "desc": "

      The repl.start() method creates and starts a repl.REPLServer instance.

      \n

      If options is a string, then it specifies the input prompt:

      \n
      const repl = require('repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n
      " + } + ], + "type": "module", + "displayName": "REPL" + }, + { + "textRaw": "Stream", + "name": "stream", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/stream.js

      \n

      A stream is an abstract interface for working with streaming data in Node.js.\nThe stream module provides an API for implementing the stream interface.

      \n

      There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout\nare both stream instances.

      \n

      Streams can be readable, writable, or both. All streams are instances of\nEventEmitter.

      \n

      To access the stream module:

      \n
      const stream = require('stream');\n
      \n

      The stream module is useful for creating new types of stream instances. It is\nusually not necessary to use the stream module to consume streams.

      ", + "modules": [ + { + "textRaw": "Organization of this document", + "name": "organization_of_this_document", + "desc": "

      This document contains two primary sections and a third section for notes. The\nfirst section explains how to use existing streams within an application. The\nsecond section explains how to create new types of streams.

      ", + "type": "module", + "displayName": "Organization of this document" + }, + { + "textRaw": "Types of streams", + "name": "types_of_streams", + "desc": "

      There are four fundamental stream types within Node.js:

      \n\n

      Additionally, this module includes the utility functions\nstream.pipeline(), stream.finished() and\nstream.Readable.from().

      ", + "modules": [ + { + "textRaw": "Object mode", + "name": "object_mode", + "desc": "

      All streams created by Node.js APIs operate exclusively on strings and Buffer\n(or Uint8Array) objects. It is possible, however, for stream implementations\nto work with other types of JavaScript values (with the exception of null,\nwhich serves a special purpose within streams). Such streams are considered to\noperate in \"object mode\".

      \n

      Stream instances are switched into object mode using the objectMode option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.

      ", + "type": "module", + "displayName": "Object mode" + } + ], + "miscs": [ + { + "textRaw": "Buffering", + "name": "Buffering", + "type": "misc", + "desc": "

      Both Writable and Readable streams will store data in an internal\nbuffer that can be retrieved using writable.writableBuffer or\nreadable.readableBuffer, respectively.

      \n

      The amount of data potentially buffered depends on the highWaterMark option\npassed into the stream's constructor. For normal streams, the highWaterMark\noption specifies a total number of bytes. For streams operating\nin object mode, the highWaterMark specifies a total number of objects.

      \n

      Data is buffered in Readable streams when the implementation calls\nstream.push(chunk). If the consumer of the Stream does not\ncall stream.read(), the data will sit in the internal\nqueue until it is consumed.

      \n

      Once the total size of the internal read buffer reaches the threshold specified\nby highWaterMark, the stream will temporarily stop reading data from the\nunderlying resource until the data currently buffered can be consumed (that is,\nthe stream will stop calling the internal readable._read() method that is\nused to fill the read buffer).

      \n

      Data is buffered in Writable streams when the\nwritable.write(chunk) method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\nhighWaterMark, calls to writable.write() will return true. Once\nthe size of the internal buffer reaches or exceeds the highWaterMark, false\nwill be returned.

      \n

      A key goal of the stream API, particularly the stream.pipe() method,\nis to limit the buffering of data to acceptable levels such that sources and\ndestinations of differing speeds will not overwhelm the available memory.

      \n

      The highWaterMark option is a threshold, not a limit: it dictates the amount\nof data that a stream buffers before it stops asking for more data. It does not\nenforce a strict memory limitation in general. Specific stream implementations\nmay choose to enforce stricter limits but doing so is optional.

      \n

      Because Duplex and Transform streams are both Readable and\nWritable, each maintains two separate internal buffers used for reading and\nwriting, allowing each side to operate independently of the other while\nmaintaining an appropriate and efficient flow of data. For example,\nnet.Socket instances are Duplex streams whose Readable side allows\nconsumption of data received from the socket and whose Writable side allows\nwriting data to the socket. Because data may be written to the socket at a\nfaster or slower rate than data is received, each side should\noperate (and buffer) independently of the other.

      " + } + ], + "type": "module", + "displayName": "Types of streams" + } + ], + "methods": [ + { + "textRaw": "`stream.finished(stream[, options], callback)`", + "type": "method", + "name": "finished", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", + "name": "return", + "type": "Function", + "desc": "A cleanup function which removes all registered listeners." + }, + "params": [ + { + "textRaw": "`stream` {Stream} A readable and/or writable stream.", + "name": "stream", + "type": "Stream", + "desc": "A readable and/or writable stream." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`.", + "name": "error", + "type": "boolean", + "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`." + }, + { + "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`.", + "name": "readable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`." + }, + { + "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`.", + "name": "writable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`." + } + ] + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

      \n
      const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n  if (err) {\n    console.error('Stream failed.', err);\n  } else {\n    console.log('Stream is done reading.');\n  }\n});\n\nrs.resume(); // Drain the stream.\n
      \n

      Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

      \n

      The finished API is promisify-able as well;

      \n
      const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n  await finished(rs);\n  console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n
      \n

      stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:

      \n
      const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n
      " + }, + { + "textRaw": "`stream.pipeline(...streams, callback)`", + "type": "method", + "name": "pipeline", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...streams` {Stream} Two or more streams to pipe between.", + "name": "...streams", + "type": "Stream", + "desc": "Two or more streams to pipe between." + }, + { + "textRaw": "`callback` {Function} Called when the pipeline is fully done.", + "name": "callback", + "type": "Function", + "desc": "Called when the pipeline is fully done.", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      A module method to pipe between streams forwarding errors and properly cleaning\nup and provide a callback when the pipeline is complete.

      \n
      const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n  fs.createReadStream('archive.tar'),\n  zlib.createGzip(),\n  fs.createWriteStream('archive.tar.gz'),\n  (err) => {\n    if (err) {\n      console.error('Pipeline failed.', err);\n    } else {\n      console.log('Pipeline succeeded.');\n    }\n  }\n);\n
      \n

      The pipeline API is promisify-able as well:

      \n
      const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
      \n

      stream.pipeline() will call stream.destroy(err) on all streams except:

      \n
        \n
      • Readable streams which have emitted 'end' or 'close'.
      • \n
      • Writable streams which have emitted 'finish' or 'close'.
      • \n
      \n

      stream.pipeline() leaves dangling event listeners on the streams\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.

      " + }, + { + "textRaw": "`stream.Readable.from(iterable, [options])`", + "type": "method", + "name": "from", + "meta": { + "added": [ + "v12.3.0", + "v10.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Readable}", + "name": "return", + "type": "stream.Readable" + }, + "params": [ + { + "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", + "name": "iterable", + "type": "Iterable", + "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." + }, + { + "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", + "name": "options", + "type": "Object", + "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`." + } + ] + } + ], + "desc": "

      A utility method for creating readable streams out of iterators.

      \n
      const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'hello';\n  yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
      \n

      Calling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.

      " + }, + { + "textRaw": "`readable.read(0)`", + "type": "method", + "name": "read", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.

      \n

      If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.

      \n

      While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.

      " + }, + { + "textRaw": "`readable.push('')`", + "type": "method", + "name": "push", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Use of readable.push('') is not recommended.

      \n

      Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.

      " + } + ], + "miscs": [ + { + "textRaw": "API for stream consumers", + "name": "API for stream consumers", + "type": "misc", + "desc": "

      Almost all Node.js applications, no matter how simple, use streams in some\nmanner. The following is an example of using streams in a Node.js application\nthat implements an HTTP server:

      \n
      const http = require('http');\n\nconst server = http.createServer((req, res) => {\n  // `req` is an http.IncomingMessage, which is a readable stream.\n  // `res` is an http.ServerResponse, which is a writable stream.\n\n  let body = '';\n  // Get the data as utf8 strings.\n  // If an encoding is not set, Buffer objects will be received.\n  req.setEncoding('utf8');\n\n  // Readable streams emit 'data' events once a listener is added.\n  req.on('data', (chunk) => {\n    body += chunk;\n  });\n\n  // The 'end' event indicates that the entire body has been received.\n  req.on('end', () => {\n    try {\n      const data = JSON.parse(body);\n      // Write back something interesting to the user:\n      res.write(typeof data);\n      res.end();\n    } catch (er) {\n      // uh oh! bad json!\n      res.statusCode = 400;\n      return res.end(`error: ${er.message}`);\n    }\n  });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d \"{}\"\n// object\n// $ curl localhost:1337 -d \"\\\"foo\\\"\"\n// string\n// $ curl localhost:1337 -d \"not json\"\n// error: Unexpected token o in JSON at position 1\n
      \n

      Writable streams (such as res in the example) expose methods such as\nwrite() and end() that are used to write data onto the stream.

      \n

      Readable streams use the EventEmitter API for notifying application\ncode when data is available to be read off the stream. That available data can\nbe read from the stream in multiple ways.

      \n

      Both Writable and Readable streams use the EventEmitter API in\nvarious ways to communicate the current state of the stream.

      \n

      Duplex and Transform streams are both Writable and\nReadable.

      \n

      Applications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call require('stream').

      \n

      Developers wishing to implement new types of streams should refer to the\nsection API for stream implementers.

      ", + "miscs": [ + { + "textRaw": "Writable streams", + "name": "writable_streams", + "desc": "

      Writable streams are an abstraction for a destination to which data is\nwritten.

      \n

      Examples of Writable streams include:

      \n\n

      Some of these examples are actually Duplex streams that implement the\nWritable interface.

      \n

      All Writable streams implement the interface defined by the\nstream.Writable class.

      \n

      While specific instances of Writable streams may differ in various ways,\nall Writable streams follow the same fundamental usage pattern as illustrated\nin the example below:

      \n
      const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n
      ", + "classes": [ + { + "textRaw": "Class: `stream.Writable`", + "type": "class", + "name": "stream.Writable", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18438", + "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." + } + ] + }, + "params": [], + "desc": "

      The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.

      \n

      A Writable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

      " + }, + { + "textRaw": "Event: `'drain'`", + "type": "event", + "name": "drain", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      If a call to stream.write(chunk) returns false, the\n'drain' event will be emitted when it is appropriate to resume writing data\nto the stream.

      \n
      // Write the data to the supplied writable stream one million times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  let i = 1000000;\n  write();\n  function write() {\n    let ok = true;\n    do {\n      i--;\n      if (i === 0) {\n        // Last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // See if we should continue, or wait.\n        // Don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // Had to stop early!\n      // Write some more once it drains.\n      writer.once('drain', write);\n    }\n  }\n}\n
      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single Error argument when called.

      \n

      The stream is not closed when the 'error' event is emitted unless the\nautoDestroy option was set to true when creating the\nstream.

      " + }, + { + "textRaw": "Event: `'finish'`", + "type": "event", + "name": "finish", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'finish' event is emitted after the stream.end() method\nhas been called, and all data has been flushed to the underlying system.

      \n
      const writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n  writer.write(`hello, #${i}!\\n`);\n}\nwriter.on('finish', () => {\n  console.log('All writes are now complete.');\n});\nwriter.end('This is the end\\n');\n
      " + }, + { + "textRaw": "Event: `'pipe'`", + "type": "event", + "name": "pipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`src` {stream.Readable} source stream that is piping to this writable", + "name": "src", + "type": "stream.Readable", + "desc": "source stream that is piping to this writable" + } + ], + "desc": "

      The 'pipe' event is emitted when the stream.pipe() method is called on\na readable stream, adding this writable to its set of destinations.

      \n
      const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n  console.log('Something is piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\n
      " + }, + { + "textRaw": "Event: `'unpipe'`", + "type": "event", + "name": "unpipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`src` {stream.Readable} The source stream that [unpiped][`stream.unpipe()`] this writable", + "name": "src", + "type": "stream.Readable", + "desc": "The source stream that [unpiped][`stream.unpipe()`] this writable" + } + ], + "desc": "

      The 'unpipe' event is emitted when the stream.unpipe() method is called\non a Readable stream, removing this Writable from its set of\ndestinations.

      \n

      This is also emitted in case this Writable stream emits an error when a\nReadable stream pipes into it.

      \n
      const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n  console.log('Something has stopped piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n
      " + } + ], + "methods": [ + { + "textRaw": "`writable.cork()`", + "type": "method", + "name": "cork", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The writable.cork() method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the stream.uncork() or\nstream.end() methods are called.

      \n

      The primary intent of writable.cork() is to accommodate a situation in which\nseveral small chunks are written to the stream in rapid succession. Instead of\nimmediately forwarding them to the underlying destination, writable.cork()\nbuffers all the chunks until writable.uncork() is called, which will pass them\nall to writable._writev(), if present. This prevents a head-of-line blocking\nsituation where data is being buffered while waiting for the first small chunk\nto be processed. However, use of writable.cork() without implementing\nwritable._writev() may have an adverse effect on throughput.

      \n

      See also: writable.uncork(), writable._writev().

      " + }, + { + "textRaw": "`writable.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error} Optional, an error to emit with `'error'` event.", + "name": "error", + "type": "Error", + "desc": "Optional, an error to emit with `'error'` event." + } + ] + } + ], + "desc": "

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the writable\nstream has ended and subsequent calls to write() or end() will result in\nan ERR_STREAM_DESTROYED error.\nThis is a destructive and immediate way to destroy a stream. Previous calls to\nwrite() may not have drained, and may trigger an ERR_STREAM_DESTROYED error.\nUse end() instead of destroy if data should flush before close, or wait for\nthe 'drain' event before destroying the stream.\nImplementors should not override this method,\nbut instead implement writable._destroy().

      " + }, + { + "textRaw": "`writable.end([chunk[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `writable`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", + "name": "chunk", + "type": "string|Buffer|Uint8Array|any", + "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." + }, + { + "textRaw": "`encoding` {string} The encoding if `chunk` is a string", + "name": "encoding", + "type": "string", + "desc": "The encoding if `chunk` is a string" + }, + { + "textRaw": "`callback` {Function} Optional callback for when the stream is finished", + "name": "callback", + "type": "Function", + "desc": "Optional callback for when the stream is finished" + } + ] + } + ], + "desc": "

      Calling the writable.end() method signals that no more data will be written\nto the Writable. The optional chunk and encoding arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream. If provided, the optional callback function is attached as a listener\nfor the 'finish' event.

      \n

      Calling the stream.write() method after calling\nstream.end() will raise an error.

      \n
      // Write 'hello, ' and then end with 'world!'.\nconst fs = require('fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!\n
      " + }, + { + "textRaw": "`writable.setDefaultEncoding(encoding)`", + "type": "method", + "name": "setDefaultEncoding", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/5040", + "description": "This method now returns a reference to `writable`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`encoding` {string} The new default encoding", + "name": "encoding", + "type": "string", + "desc": "The new default encoding" + } + ] + } + ], + "desc": "

      The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.

      " + }, + { + "textRaw": "`writable.uncork()`", + "type": "method", + "name": "uncork", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The writable.uncork() method flushes all data buffered since\nstream.cork() was called.

      \n

      When using writable.cork() and writable.uncork() to manage the buffering\nof writes to a stream, it is recommended that calls to writable.uncork() be\ndeferred using process.nextTick(). Doing so allows batching of all\nwritable.write() calls that occur within a given Node.js event loop phase.

      \n
      stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n
      \n

      If the writable.cork() method is called multiple times on a stream, the\nsame number of calls to writable.uncork() must be called to flush the buffered\ndata.

      \n
      stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n  stream.uncork();\n  // The data will not be flushed until uncork() is called a second time.\n  stream.uncork();\n});\n
      \n

      See also: writable.cork().

      " + }, + { + "textRaw": "`writable.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6170", + "description": "Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", + "name": "chunk", + "type": "string|Buffer|Uint8Array|any", + "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." + }, + { + "textRaw": "`encoding` {string} The encoding, if `chunk` is a string. **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding, if `chunk` is a string." + }, + { + "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed", + "name": "callback", + "type": "Function", + "desc": "Callback for when this chunk of data is flushed" + } + ] + } + ], + "desc": "

      The writable.write() method writes some data to the stream, and calls the\nsupplied callback once the data has been fully handled. If an error\noccurs, the callback may or may not be called with the error as its\nfirst argument. To reliably detect write errors, add a listener for the\n'error' event.

      \n

      The return value is true if the internal buffer is less than the\nhighWaterMark configured when the stream was created after admitting chunk.\nIf false is returned, further attempts to write data to the stream should\nstop until the 'drain' event is emitted.

      \n

      While a stream is not draining, calls to write() will buffer chunk, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the 'drain' event will be emitted.\nIt is recommended that once write() returns false, no more chunks be written\nuntil the 'drain' event is emitted. While calling write() on a stream that\nis not draining is allowed, Node.js will buffer all written chunks until\nmaximum memory usage occurs, at which point it will abort unconditionally.\nEven before it aborts, high memory usage will cause poor garbage collector\nperformance and high RSS (which is not typically released back to the system,\neven after the memory is no longer required). Since TCP sockets may never\ndrain if the remote peer does not read the data, writing a socket that is\nnot draining may lead to a remotely exploitable vulnerability.

      \n

      Writing data while the stream is not draining is particularly\nproblematic for a Transform, because the Transform streams are paused\nby default until they are piped or a 'data' or 'readable' event handler\nis added.

      \n

      If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a Readable and use\nstream.pipe(). However, if calling write() is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n'drain' event:

      \n
      function write(data, cb) {\n  if (!stream.write(data)) {\n    stream.once('drain', cb);\n  } else {\n    process.nextTick(cb);\n  }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n  console.log('Write completed, do more writes now.');\n});\n
      \n

      A Writable stream in object mode will always ignore the encoding argument.

      " + } + ], + "properties": [ + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Is true after writable.destroy() has been called.

      " + }, + { + "textRaw": "`writable` {boolean}", + "type": "boolean", + "name": "writable", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "desc": "

      Is true if it is safe to call writable.write().

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after writable.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.

      " + }, + { + "textRaw": "`writableCorked` {integer}", + "type": "integer", + "name": "writableCorked", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Number of times writable.uncork() needs to be\ncalled in order to fully uncork the stream.

      " + }, + { + "textRaw": "`writableFinished` {boolean}", + "type": "boolean", + "name": "writableFinished", + "meta": { + "added": [ + "v12.6.0" + ], + "changes": [] + }, + "desc": "

      Is set to true immediately before the 'finish' event is emitted.

      " + }, + { + "textRaw": "`writableHighWaterMark` {number}", + "type": "number", + "name": "writableHighWaterMark", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "desc": "

      Return the value of highWaterMark passed when constructing this\nWritable.

      " + }, + { + "textRaw": "`writableLength` {number}", + "type": "number", + "name": "writableLength", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      This property contains the number of bytes (or objects) in the queue\nready to be written. The value provides introspection data regarding\nthe status of the highWaterMark.

      " + }, + { + "textRaw": "`writableObjectMode` {boolean}", + "type": "boolean", + "name": "writableObjectMode", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "desc": "

      Getter for the property objectMode of a given Writable stream.

      " + } + ] + } + ], + "type": "misc", + "displayName": "Writable streams" + }, + { + "textRaw": "Readable streams", + "name": "readable_streams", + "desc": "

      Readable streams are an abstraction for a source from which data is\nconsumed.

      \n

      Examples of Readable streams include:

      \n\n

      All Readable streams implement the interface defined by the\nstream.Readable class.

      ", + "modules": [ + { + "textRaw": "Two reading modes", + "name": "two_reading_modes", + "desc": "

      Readable streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from object mode.\nA Readable stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.

      \n
        \n
      • \n

        In flowing mode, data is read from the underlying system automatically\nand provided to an application as quickly as possible using events via the\nEventEmitter interface.

        \n
      • \n
      • \n

        In paused mode, the stream.read() method must be called\nexplicitly to read chunks of data from the stream.

        \n
      • \n
      \n

      All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:

      \n\n

      The Readable can switch back to paused mode using one of the following:

      \n
        \n
      • If there are no pipe destinations, by calling the\nstream.pause() method.
      • \n
      • If there are pipe destinations, by removing all pipe destinations.\nMultiple pipe destinations may be removed by calling the\nstream.unpipe() method.
      • \n
      \n

      The important concept to remember is that a Readable will not generate data\nuntil a mechanism for either consuming or ignoring that data is provided. If\nthe consuming mechanism is disabled or taken away, the Readable will attempt\nto stop generating the data.

      \n

      For backward compatibility reasons, removing 'data' event handlers will\nnot automatically pause the stream. Also, if there are piped destinations,\nthen calling stream.pause() will not guarantee that the\nstream will remain paused once those destinations drain and ask for more data.

      \n

      If a Readable is switched into flowing mode and there are no consumers\navailable to handle the data, that data will be lost. This can occur, for\ninstance, when the readable.resume() method is called without a listener\nattached to the 'data' event, or when a 'data' event handler is removed\nfrom the stream.

      \n

      Adding a 'readable' event handler automatically makes the stream\nstop flowing, and the data has to be consumed via\nreadable.read(). If the 'readable' event handler is\nremoved, then the stream will start flowing again if there is a\n'data' event handler.

      ", + "type": "module", + "displayName": "Two reading modes" + }, + { + "textRaw": "Three states", + "name": "three_states", + "desc": "

      The \"two modes\" of operation for a Readable stream are a simplified\nabstraction for the more complicated internal state management that is happening\nwithin the Readable stream implementation.

      \n

      Specifically, at any given point in time, every Readable is in one of three\npossible states:

      \n
        \n
      • readable.readableFlowing === null
      • \n
      • readable.readableFlowing === false
      • \n
      • readable.readableFlowing === true
      • \n
      \n

      When readable.readableFlowing is null, no mechanism for consuming the\nstream's data is provided. Therefore, the stream will not generate data.\nWhile in this state, attaching a listener for the 'data' event, calling the\nreadable.pipe() method, or calling the readable.resume() method will switch\nreadable.readableFlowing to true, causing the Readable to begin actively\nemitting events as data is generated.

      \n

      Calling readable.pause(), readable.unpipe(), or receiving backpressure\nwill cause the readable.readableFlowing to be set as false,\ntemporarily halting the flowing of events but not halting the generation of\ndata. While in this state, attaching a listener for the 'data' event\nwill not switch readable.readableFlowing to true.

      \n
      const { PassThrough, Writable } = require('stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// readableFlowing is now false.\n\npass.on('data', (chunk) => { console.log(chunk.toString()); });\npass.write('ok');  // Will not emit 'data'.\npass.resume();     // Must be called to make stream emit 'data'.\n
      \n

      While readable.readableFlowing is false, data may be accumulating\nwithin the stream's internal buffer.

      ", + "type": "module", + "displayName": "Three states" + }, + { + "textRaw": "Choose one API style", + "name": "choose_one_api_style", + "desc": "

      The Readable stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\none of the methods of consuming data and should never use multiple methods\nto consume data from a single stream. Specifically, using a combination\nof on('data'), on('readable'), pipe(), or async iterators could\nlead to unintuitive behavior.

      \n

      Use of the readable.pipe() method is recommended for most users as it has been\nimplemented to provide the easiest way of consuming stream data. Developers that\nrequire more fine-grained control over the transfer and generation of data can\nuse the EventEmitter and readable.on('readable')/readable.read()\nor the readable.pause()/readable.resume() APIs.

      ", + "type": "module", + "displayName": "Choose one API style" + } + ], + "classes": [ + { + "textRaw": "Class: `stream.Readable`", + "type": "class", + "name": "stream.Readable", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18438", + "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." + } + ] + }, + "params": [], + "desc": "

      The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.

      \n

      A Readable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

      " + }, + { + "textRaw": "Event: `'data'`", + "type": "event", + "name": "data", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`chunk` {Buffer|string|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`.", + "name": "chunk", + "type": "Buffer|string|any", + "desc": "The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`." + } + ], + "desc": "

      The 'data' event is emitted whenever the stream is relinquishing ownership of\na chunk of data to a consumer. This may occur whenever the stream is switched\nin flowing mode by calling readable.pipe(), readable.resume(), or by\nattaching a listener callback to the 'data' event. The 'data' event will\nalso be emitted whenever the readable.read() method is called and a chunk of\ndata is available to be returned.

      \n

      Attaching a 'data' event listener to a stream that has not been explicitly\npaused will switch the stream into flowing mode. Data will then be passed as\nsoon as it is available.

      \n

      The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\nreadable.setEncoding() method; otherwise the data will be passed as a\nBuffer.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\n
      " + }, + { + "textRaw": "Event: `'end'`", + "type": "event", + "name": "end", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'end' event is emitted when there is no more data to be consumed from\nthe stream.

      \n

      The 'end' event will not be emitted unless the data is completely\nconsumed. This can be accomplished by switching the stream into flowing mode,\nor by calling stream.read() repeatedly until all data has been\nconsumed.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n  console.log('There will be no more data.');\n});\n
      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      The 'error' event may be emitted by a Readable implementation at any time.\nTypically, this may occur if the underlying stream is unable to generate data\ndue to an underlying internal failure, or when a stream implementation attempts\nto push an invalid chunk of data.

      \n

      The listener callback will be passed a single Error object.

      " + }, + { + "textRaw": "Event: `'pause'`", + "type": "event", + "name": "pause", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'pause' event is emitted when stream.pause() is called\nand readableFlowing is not false.

      " + }, + { + "textRaw": "Event: `'readable'`", + "type": "event", + "name": "readable", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17979", + "description": "The `'readable'` is always emitted in the next tick after `.push()` is called." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18994", + "description": "Using `'readable'` requires calling `.read()`." + } + ] + }, + "params": [], + "desc": "

      The 'readable' event is emitted when there is data available to be read from\nthe stream. In some cases, attaching a listener for the 'readable' event will\ncause some amount of data to be read into an internal buffer.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // There is some data to read now.\n  let data;\n\n  while (data = this.read()) {\n    console.log(data);\n  }\n});\n
      \n

      The 'readable' event will also be emitted once the end of the stream data\nhas been reached but before the 'end' event is emitted.

      \n

      Effectively, the 'readable' event indicates that the stream has new\ninformation: either new data is available or the end of the stream has been\nreached. In the former case, stream.read() will return the\navailable data. In the latter case, stream.read() will return\nnull. For instance, in the following example, foo.txt is an empty file:

      \n
      const fs = require('fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n  console.log(`readable: ${rr.read()}`);\n});\nrr.on('end', () => {\n  console.log('end');\n});\n
      \n

      The output of running this script is:

      \n
      $ node test.js\nreadable: null\nend\n
      \n

      In general, the readable.pipe() and 'data' event mechanisms are easier to\nunderstand than the 'readable' event. However, handling 'readable' might\nresult in increased throughput.

      \n

      If both 'readable' and 'data' are used at the same time, 'readable'\ntakes precedence in controlling the flow, i.e. 'data' will be emitted\nonly when stream.read() is called. The\nreadableFlowing property would become false.\nIf there are 'data' listeners when 'readable' is removed, the stream\nwill start flowing, i.e. 'data' events will be emitted without calling\n.resume().

      " + }, + { + "textRaw": "Event: `'resume'`", + "type": "event", + "name": "resume", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resume' event is emitted when stream.resume() is\ncalled and readableFlowing is not true.

      " + } + ], + "methods": [ + { + "textRaw": "`readable.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error} Error which will be passed as payload in `'error'` event", + "name": "error", + "type": "Error", + "desc": "Error which will be passed as payload in `'error'` event" + } + ] + } + ], + "desc": "

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the readable\nstream will release any internal resources and subsequent calls to push()\nwill be ignored.\nImplementors should not override this method, but instead implement\nreadable._destroy().

      " + }, + { + "textRaw": "`readable.isPaused()`", + "type": "method", + "name": "isPaused", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      The readable.isPaused() method returns the current operating state of the\nReadable. This is used primarily by the mechanism that underlies the\nreadable.pipe() method. In most typical cases, there will be no reason to\nuse this method directly.

      \n
      const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n
      " + }, + { + "textRaw": "`readable.pause()`", + "type": "method", + "name": "pause", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [] + } + ], + "desc": "

      The readable.pause() method will cause a stream in flowing mode to stop\nemitting 'data' events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n  readable.pause();\n  console.log('There will be no additional data for 1 second.');\n  setTimeout(() => {\n    console.log('Now data will start flowing again.');\n    readable.resume();\n  }, 1000);\n});\n
      \n

      The readable.pause() method has no effect if there is a 'readable'\nevent listener.

      " + }, + { + "textRaw": "`readable.pipe(destination[, options])`", + "type": "method", + "name": "pipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream", + "name": "return", + "type": "stream.Writable", + "desc": "The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream" + }, + "params": [ + { + "textRaw": "`destination` {stream.Writable} The destination for writing data", + "name": "destination", + "type": "stream.Writable", + "desc": "The destination for writing data" + }, + { + "textRaw": "`options` {Object} Pipe options", + "name": "options", + "type": "Object", + "desc": "Pipe options", + "options": [ + { + "textRaw": "`end` {boolean} End the writer when the reader ends. **Default:** `true`.", + "name": "end", + "type": "boolean", + "default": "`true`", + "desc": "End the writer when the reader ends." + } + ] + } + ] + } + ], + "desc": "

      The readable.pipe() method attaches a Writable stream to the readable,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached Writable. The flow of data will be automatically managed\nso that the destination Writable stream is not overwhelmed by a faster\nReadable stream.

      \n

      The following example pipes all of the data from the readable into a file\nnamed file.txt:

      \n
      const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);\n
      \n

      It is possible to attach multiple Writable streams to a single Readable\nstream.

      \n

      The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:

      \n
      const fs = require('fs');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n
      \n

      By default, stream.end() is called on the destination Writable\nstream when the source Readable stream emits 'end', so that the\ndestination is no longer writable. To disable this default behavior, the end\noption can be passed as false, causing the destination stream to remain open:

      \n
      reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});\n
      \n

      One important caveat is that if the Readable stream emits an error during\nprocessing, the Writable destination is not closed automatically. If an\nerror occurs, it will be necessary to manually close each stream in order\nto prevent memory leaks.

      \n

      The process.stderr and process.stdout Writable streams are never\nclosed until the Node.js process exits, regardless of the specified options.

      " + }, + { + "textRaw": "`readable.read([size])`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer|null|any}", + "name": "return", + "type": "string|Buffer|null|any" + }, + "params": [ + { + "textRaw": "`size` {number} Optional argument to specify how much data to read.", + "name": "size", + "type": "number", + "desc": "Optional argument to specify how much data to read." + } + ] + } + ], + "desc": "

      The readable.read() method pulls some data out of the internal buffer and\nreturns it. If no data available to be read, null is returned. By default,\nthe data will be returned as a Buffer object unless an encoding has been\nspecified using the readable.setEncoding() method or the stream is operating\nin object mode.

      \n

      The optional size argument specifies a specific number of bytes to read. If\nsize bytes are not available to be read, null will be returned unless\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned.

      \n

      If the size argument is not specified, all of the data contained in the\ninternal buffer will be returned.

      \n

      The size argument must be less than or equal to 1 GB.

      \n

      The readable.read() method should only be called on Readable streams\noperating in paused mode. In flowing mode, readable.read() is called\nautomatically until the internal buffer is fully drained.

      \n
      const readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n  let chunk;\n  console.log('Stream is readable (new data received in buffer)');\n  // Use a loop to make sure we read all currently available data\n  while (null !== (chunk = readable.read())) {\n    console.log(`Read ${chunk.length} bytes of data...`);\n  }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n  console.log('Reached end of stream.');\n});\n
      \n

      Each call to readable.read() returns a chunk of data, or null. The chunks\nare not concatenated. A while loop is necessary to consume all data\ncurrently in the buffer. When reading a large file .read() may return null,\nhaving consumed all buffered content so far, but there is still more data to\ncome not yet buffered. In this case a new 'readable' event will be emitted\nwhen there is more data in the buffer. Finally the 'end' event will be\nemitted when there is no more data to come.

      \n

      Therefore to read a file's whole contents from a readable, it is necessary\nto collect chunks across multiple 'readable' events:

      \n
      const chunks = [];\n\nreadable.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = readable.read())) {\n    chunks.push(chunk);\n  }\n});\n\nreadable.on('end', () => {\n  const content = chunks.join('');\n});\n
      \n

      A Readable stream in object mode will always return a single item from\na call to readable.read(size), regardless of the value of the\nsize argument.

      \n

      If the readable.read() method returns a chunk of data, a 'data' event will\nalso be emitted.

      \n

      Calling stream.read([size]) after the 'end' event has\nbeen emitted will return null. No runtime error will be raised.

      " + }, + { + "textRaw": "`readable.resume()`", + "type": "method", + "name": "resume", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18994", + "description": "The `resume()` has no effect if there is a `'readable'` event listening." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [] + } + ], + "desc": "

      The readable.resume() method causes an explicitly paused Readable stream to\nresume emitting 'data' events, switching the stream into flowing mode.

      \n

      The readable.resume() method can be used to fully consume the data from a\nstream without actually processing any of that data:

      \n
      getReadableStreamSomehow()\n  .resume()\n  .on('end', () => {\n    console.log('Reached the end, but did not read anything.');\n  });\n
      \n

      The readable.resume() method has no effect if there is a 'readable'\nevent listener.

      " + }, + { + "textRaw": "`readable.setEncoding(encoding)`", + "type": "method", + "name": "setEncoding", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`encoding` {string} The encoding to use.", + "name": "encoding", + "type": "string", + "desc": "The encoding to use." + } + ] + } + ], + "desc": "

      The readable.setEncoding() method sets the character encoding for\ndata read from the Readable stream.

      \n

      By default, no encoding is assigned and stream data will be returned as\nBuffer objects. Setting an encoding causes the stream data\nto be returned as strings of the specified encoding rather than as Buffer\nobjects. For instance, calling readable.setEncoding('utf8') will cause the\noutput data to be interpreted as UTF-8 data, and passed as strings. Calling\nreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal\nstring format.

      \n

      The Readable stream will properly handle multi-byte characters delivered\nthrough the stream that would otherwise become improperly decoded if simply\npulled from the stream as Buffer objects.

      \n
      const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n  assert.equal(typeof chunk, 'string');\n  console.log('Got %d characters of string data:', chunk.length);\n});\n
      " + }, + { + "textRaw": "`readable.unpipe([destination])`", + "type": "method", + "name": "unpipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe", + "name": "destination", + "type": "stream.Writable", + "desc": "Optional specific stream to unpipe" + } + ] + } + ], + "desc": "

      The readable.unpipe() method detaches a Writable stream previously attached\nusing the stream.pipe() method.

      \n

      If the destination is not specified, then all pipes are detached.

      \n

      If the destination is specified, but no pipe is set up for it, then\nthe method does nothing.

      \n
      const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second.\nreadable.pipe(writable);\nsetTimeout(() => {\n  console.log('Stop writing to file.txt.');\n  readable.unpipe(writable);\n  console.log('Manually close the file stream.');\n  writable.end();\n}, 1000);\n
      " + }, + { + "textRaw": "`readable.unshift(chunk[, encoding])`", + "type": "method", + "name": "unshift", + "meta": { + "added": [ + "v0.9.11" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value.", + "name": "chunk", + "type": "Buffer|Uint8Array|string|null|any", + "desc": "Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value." + }, + { + "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", + "name": "encoding", + "type": "string", + "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`." + } + ] + } + ], + "desc": "

      Passing chunk as null signals the end of the stream (EOF) and behaves the\nsame as readable.push(null), after which no more data can be written. The EOF\nsignal is put at the end of the buffer and any buffered data will still be\nflushed.

      \n

      The readable.unshift() method pushes a chunk of data back into the internal\nbuffer. This is useful in certain situations where a stream is being consumed by\ncode that needs to \"un-consume\" some amount of data that it has optimistically\npulled out of the source, so that the data can be passed on to some other party.

      \n

      The stream.unshift(chunk) method cannot be called after the 'end' event\nhas been emitted or a runtime error will be thrown.

      \n

      Developers using stream.unshift() often should consider switching to\nuse of a Transform stream instead. See the API for stream implementers\nsection for more information.

      \n
      // Pull off a header delimited by \\n\\n.\n// Use unshift() if we get too much.\n// Call the callback with (error, header, stream).\nconst { StringDecoder } = require('string_decoder');\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  const decoder = new StringDecoder('utf8');\n  let header = '';\n  function onReadable() {\n    let chunk;\n    while (null !== (chunk = stream.read())) {\n      const str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // Found the header boundary.\n        const split = str.split(/\\n\\n/);\n        header += split.shift();\n        const remaining = split.join('\\n\\n');\n        const buf = Buffer.from(remaining, 'utf8');\n        stream.removeListener('error', callback);\n        // Remove the 'readable' listener before unshifting.\n        stream.removeListener('readable', onReadable);\n        if (buf.length)\n          stream.unshift(buf);\n        // Now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // Still reading the header.\n        header += str;\n      }\n    }\n  }\n}\n
      \n

      Unlike stream.push(chunk), stream.unshift(chunk) will not\nend the reading process by resetting the internal reading state of the stream.\nThis can cause unexpected results if readable.unshift() is called during a\nread (i.e. from within a stream._read() implementation on a\ncustom stream). Following the call to readable.unshift() with an immediate\nstream.push('') will reset the reading state appropriately,\nhowever it is best to simply avoid calling readable.unshift() while in the\nprocess of performing a read.

      " + }, + { + "textRaw": "`readable.wrap(stream)`", + "type": "method", + "name": "wrap", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`stream` {Stream} An \"old style\" readable stream", + "name": "stream", + "type": "Stream", + "desc": "An \"old style\" readable stream" + } + ] + } + ], + "desc": "

      Prior to Node.js 0.10, streams did not implement the entire stream module API\nas it is currently defined. (See Compatibility for more information.)

      \n

      When using an older Node.js library that emits 'data' events and has a\nstream.pause() method that is advisory only, the\nreadable.wrap() method can be used to create a Readable stream that uses\nthe old stream as its data source.

      \n

      It will rarely be necessary to use readable.wrap() but the method has been\nprovided as a convenience for interacting with older Node.js applications and\nlibraries.

      \n
      const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n  myReader.read(); // etc.\n});\n
      " + }, + { + "textRaw": "`readable[Symbol.asyncIterator]()`", + "type": "method", + "name": "[Symbol.asyncIterator]", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26989", + "description": "Symbol.asyncIterator support is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator} to fully consume the stream.", + "name": "return", + "type": "AsyncIterator", + "desc": "to fully consume the stream." + }, + "params": [] + } + ], + "desc": "
      const fs = require('fs');\n\nasync function print(readable) {\n  readable.setEncoding('utf8');\n  let data = '';\n  for await (const chunk of readable) {\n    data += chunk;\n  }\n  console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.error);\n
      \n

      If the loop terminates with a break or a throw, the stream will be\ndestroyed. In other terms, iterating over a stream will consume the stream\nfully. The stream will be read in chunks of size equal to the highWaterMark\noption. In the code example above, data will be in a single chunk if the file\nhas less then 64KB of data because no highWaterMark option is provided to\nfs.createReadStream().

      " + } + ], + "properties": [ + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Is true after readable.destroy() has been called.

      " + }, + { + "textRaw": "`readable` {boolean}", + "type": "boolean", + "name": "readable", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "desc": "

      Is true if it is safe to call readable.read().

      " + }, + { + "textRaw": "`readableEncoding` {null|string}", + "type": "null|string", + "name": "readableEncoding", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "desc": "

      Getter for the property encoding of a given Readable stream. The encoding\nproperty can be set using the readable.setEncoding() method.

      " + }, + { + "textRaw": "`readableEnded` {boolean}", + "type": "boolean", + "name": "readableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Becomes true when 'end' event is emitted.

      " + }, + { + "textRaw": "`readableFlowing` {boolean}", + "type": "boolean", + "name": "readableFlowing", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      This property reflects the current state of a Readable stream as described\nin the Three states section.

      " + }, + { + "textRaw": "`readableHighWaterMark` {number}", + "type": "number", + "name": "readableHighWaterMark", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "desc": "

      Returns the value of highWaterMark passed when constructing this\nReadable.

      " + }, + { + "textRaw": "`readableLength` {number}", + "type": "number", + "name": "readableLength", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      This property contains the number of bytes (or objects) in the queue\nready to be read. The value provides introspection data regarding\nthe status of the highWaterMark.

      " + }, + { + "textRaw": "`readableObjectMode` {boolean}", + "type": "boolean", + "name": "readableObjectMode", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "desc": "

      Getter for the property objectMode of a given Readable stream.

      " + } + ] + } + ], + "type": "misc", + "displayName": "Readable streams" + }, + { + "textRaw": "Duplex and transform streams", + "name": "duplex_and_transform_streams", + "classes": [ + { + "textRaw": "Class: `stream.Duplex`", + "type": "class", + "name": "stream.Duplex", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v6.8.0", + "pr-url": "https://github.com/nodejs/node/pull/8834", + "description": "Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`." + } + ] + }, + "desc": "

      Duplex streams are streams that implement both the Readable and\nWritable interfaces.

      \n

      Examples of Duplex streams include:

      \n" + }, + { + "textRaw": "Class: `stream.Transform`", + "type": "class", + "name": "stream.Transform", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "desc": "

      Transform streams are Duplex streams where the output is in some way\nrelated to the input. Like all Duplex streams, Transform streams\nimplement both the Readable and Writable interfaces.

      \n

      Examples of Transform streams include:

      \n", + "methods": [ + { + "textRaw": "`transform.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      Destroy the stream, and optionally emit an 'error' event. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\nreadable._destroy().\nThe default implementation of _destroy() for Transform also emit 'close'\nunless emitClose is set in false.

      " + } + ] + } + ], + "type": "misc", + "displayName": "Duplex and transform streams" + } + ], + "methods": [ + { + "textRaw": "`stream.finished(stream[, options], callback)`", + "type": "method", + "name": "finished", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", + "name": "return", + "type": "Function", + "desc": "A cleanup function which removes all registered listeners." + }, + "params": [ + { + "textRaw": "`stream` {Stream} A readable and/or writable stream.", + "name": "stream", + "type": "Stream", + "desc": "A readable and/or writable stream." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`.", + "name": "error", + "type": "boolean", + "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`." + }, + { + "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`.", + "name": "readable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`." + }, + { + "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`.", + "name": "writable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`." + } + ] + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

      \n
      const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n  if (err) {\n    console.error('Stream failed.', err);\n  } else {\n    console.log('Stream is done reading.');\n  }\n});\n\nrs.resume(); // Drain the stream.\n
      \n

      Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

      \n

      The finished API is promisify-able as well;

      \n
      const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n  await finished(rs);\n  console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n
      \n

      stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:

      \n
      const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n
      " + }, + { + "textRaw": "`stream.pipeline(...streams, callback)`", + "type": "method", + "name": "pipeline", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...streams` {Stream} Two or more streams to pipe between.", + "name": "...streams", + "type": "Stream", + "desc": "Two or more streams to pipe between." + }, + { + "textRaw": "`callback` {Function} Called when the pipeline is fully done.", + "name": "callback", + "type": "Function", + "desc": "Called when the pipeline is fully done.", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      A module method to pipe between streams forwarding errors and properly cleaning\nup and provide a callback when the pipeline is complete.

      \n
      const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n  fs.createReadStream('archive.tar'),\n  zlib.createGzip(),\n  fs.createWriteStream('archive.tar.gz'),\n  (err) => {\n    if (err) {\n      console.error('Pipeline failed.', err);\n    } else {\n      console.log('Pipeline succeeded.');\n    }\n  }\n);\n
      \n

      The pipeline API is promisify-able as well:

      \n
      const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
      \n

      stream.pipeline() will call stream.destroy(err) on all streams except:

      \n
        \n
      • Readable streams which have emitted 'end' or 'close'.
      • \n
      • Writable streams which have emitted 'finish' or 'close'.
      • \n
      \n

      stream.pipeline() leaves dangling event listeners on the streams\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.

      " + }, + { + "textRaw": "`stream.Readable.from(iterable, [options])`", + "type": "method", + "name": "from", + "meta": { + "added": [ + "v12.3.0", + "v10.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Readable}", + "name": "return", + "type": "stream.Readable" + }, + "params": [ + { + "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", + "name": "iterable", + "type": "Iterable", + "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." + }, + { + "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", + "name": "options", + "type": "Object", + "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`." + } + ] + } + ], + "desc": "

      A utility method for creating readable streams out of iterators.

      \n
      const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'hello';\n  yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
      \n

      Calling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.

      " + } + ] + }, + { + "textRaw": "API for stream implementers", + "name": "API for stream implementers", + "type": "misc", + "desc": "

      The stream module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.

      \n

      First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (stream.Writable, stream.Readable,\nstream.Duplex, or stream.Transform), making sure they call the appropriate\nparent class constructor:

      \n\n
      const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor({ highWaterMark, ...options }) {\n    super({\n      highWaterMark,\n      autoDestroy: true,\n      emitClose: true\n    });\n    // ...\n  }\n}\n
      \n

      When extending streams, keep in mind what options the user\ncan and should provide before forwarding these to the base constructor. For\nexample, if the implementation makes assumptions in regard to the\nautoDestroy and emitClose options, do not allow the\nuser to override these. Be explicit about what\noptions are forwarded instead of implicitly forwarding all options.

      \n

      The new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      Use-caseClassMethod(s) to implement
      Reading onlyReadable_read()
      Writing onlyWritable_write(), _writev(), _final()
      Reading and writingDuplex_read(), _write(), _writev(), _final()
      Operate on written data, then read the resultTransform_transform(), _flush(), _final()
      \n

      The implementation code for a stream should never call the \"public\" methods\nof a stream that are intended for use by consumers (as described in the\nAPI for stream consumers section). Doing so may lead to adverse side effects\nin application code consuming the stream.

      \n

      Avoid overriding public methods such as write(), end(), cork(),\nuncork(), read() and destroy(), or emitting internal events such\nas 'error', 'data', 'end', 'finish' and 'close' through .emit().\nDoing so can break current and future stream invariants leading to behavior\nand/or compatibility issues with other streams, stream utilities, and user\nexpectations.

      ", + "miscs": [ + { + "textRaw": "Simplified construction", + "name": "simplified_construction", + "meta": { + "added": [ + "v1.2.0" + ], + "changes": [] + }, + "desc": "

      For many simple cases, it is possible to construct a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\nstream.Writable, stream.Readable, stream.Duplex or stream.Transform\nobjects and passing appropriate methods as constructor options.

      \n
      const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
      ", + "type": "misc", + "displayName": "Simplified construction" + }, + { + "textRaw": "Implementing a writable stream", + "name": "implementing_a_writable_stream", + "desc": "

      The stream.Writable class is extended to implement a Writable stream.

      \n

      Custom Writable streams must call the new stream.Writable([options])\nconstructor and implement the writable._write() and/or writable._writev()\nmethod.

      ", + "ctors": [ + { + "textRaw": "`new stream.Writable([options])`", + "type": "ctor", + "name": "stream.Writable", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18438", + "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." + }, + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/22795", + "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`highWaterMark` {number} Buffer level when [`stream.write()`][stream-write] starts returning `false`. **Default:** `16384` (16KB), or `16` for `objectMode` streams.", + "name": "highWaterMark", + "type": "number", + "default": "`16384` (16KB), or `16` for `objectMode` streams", + "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`." + }, + { + "textRaw": "`decodeStrings` {boolean} Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted. **Default:** `true`.", + "name": "decodeStrings", + "type": "boolean", + "default": "`true`", + "desc": "Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted." + }, + { + "textRaw": "`defaultEncoding` {string} The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]. **Default:** `'utf8'`.", + "name": "defaultEncoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]." + }, + { + "textRaw": "`objectMode` {boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation. **Default:** `false`.", + "name": "objectMode", + "type": "boolean", + "default": "`false`", + "desc": "Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation." + }, + { + "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", + "name": "emitClose", + "type": "boolean", + "default": "`true`", + "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." + }, + { + "textRaw": "`write` {Function} Implementation for the [`stream._write()`][stream-_write] method.", + "name": "write", + "type": "Function", + "desc": "Implementation for the [`stream._write()`][stream-_write] method." + }, + { + "textRaw": "`writev` {Function} Implementation for the [`stream._writev()`][stream-_writev] method.", + "name": "writev", + "type": "Function", + "desc": "Implementation for the [`stream._writev()`][stream-_writev] method." + }, + { + "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][writable-_destroy] method.", + "name": "destroy", + "type": "Function", + "desc": "Implementation for the [`stream._destroy()`][writable-_destroy] method." + }, + { + "textRaw": "`final` {Function} Implementation for the [`stream._final()`][stream-_final] method.", + "name": "final", + "type": "Function", + "desc": "Implementation for the [`stream._final()`][stream-_final] method." + }, + { + "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `false`.", + "name": "autoDestroy", + "type": "boolean", + "default": "`false`", + "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." + } + ] + } + ] + } + ], + "desc": "\n
      const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Writable } = require('stream');\nconst util = require('util');\n\nfunction MyWritable(options) {\n  if (!(this instanceof MyWritable))\n    return new MyWritable(options);\n  Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  }\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`writable._write(chunk, encoding, callback)`", + "type": "method", + "name": "_write", + "meta": { + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29639", + "description": "_write() is optional when providing _writev()." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", + "name": "chunk", + "type": "Buffer|string|any", + "desc": "The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." + }, + { + "textRaw": "`encoding` {string} If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored.", + "name": "encoding", + "type": "string", + "desc": "If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored." + }, + { + "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk.", + "name": "callback", + "type": "Function", + "desc": "Call this function (optionally with an error argument) when processing is complete for the supplied chunk." + } + ] + } + ], + "desc": "

      All Writable stream implementations must provide a\nwritable._write() and/or\nwritable._writev() method to send data to the underlying\nresource.

      \n

      Transform streams provide their own implementation of the\nwritable._write().

      \n

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.

      \n

      The callback method must be called to signal either that the write completed\nsuccessfully or failed with an error. The first argument passed to the\ncallback must be the Error object if the call failed or null if the\nwrite succeeded.

      \n

      All calls to writable.write() that occur between the time writable._write()\nis called and the callback is called will cause the written data to be\nbuffered. When the callback is invoked, the stream might emit a 'drain'\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the writable._writev() method should be implemented.

      \n

      If the decodeStrings property is explicitly set to false in the constructor\noptions, then chunk will remain the same object that is passed to .write(),\nand may be a string rather than a Buffer. This is to support implementations\nthat have an optimized handling for certain string data encodings. In that case,\nthe encoding argument will indicate the character encoding of the string.\nOtherwise, the encoding argument can be safely ignored.

      \n

      The writable._write() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`writable._writev(chunks, callback)`", + "type": "method", + "name": "_writev", + "signatures": [ + { + "params": [ + { + "textRaw": "`chunks` {Object[]} The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`.", + "name": "chunks", + "type": "Object[]", + "desc": "The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`." + }, + { + "textRaw": "`callback` {Function} A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks.", + "name": "callback", + "type": "Function", + "desc": "A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks." + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.

      \n

      The writable._writev() method may be implemented in addition or alternatively\nto writable._write() in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented and if there is buffered data\nfrom previous writes, _writev() will be called instead of _write().

      \n

      The writable._writev() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`writable._destroy(err, callback)`", + "type": "method", + "name": "_destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`err` {Error} A possible error.", + "name": "err", + "type": "Error", + "desc": "A possible error." + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      The _destroy() method is called by writable.destroy().\nIt can be overridden by child classes but it must not be called directly.

      " + }, + { + "textRaw": "`writable._final(callback)`", + "type": "method", + "name": "_final", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when finished writing any remaining data.", + "name": "callback", + "type": "Function", + "desc": "Call this function (optionally with an error argument) when finished writing any remaining data." + } + ] + } + ], + "desc": "

      The _final() method must not be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.

      \n

      This optional function will be called before the stream closes, delaying the\n'finish' event until callback is called. This is useful to close resources\nor write buffered data before a stream ends.

      " + } + ], + "modules": [ + { + "textRaw": "Errors while writing", + "name": "errors_while_writing", + "desc": "

      Errors occurring during the processing of the writable._write(),\nwritable._writev() and writable._final() methods must be propagated\nby invoking the callback and passing the error as the first argument.\nThrowing an Error from within these methods or manually emitting an 'error'\nevent results in undefined behavior.

      \n

      If a Readable stream pipes into a Writable stream when Writable emits an\nerror, the Readable stream will be unpiped.

      \n
      const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    if (chunk.toString().indexOf('a') >= 0) {\n      callback(new Error('chunk is invalid'));\n    } else {\n      callback();\n    }\n  }\n});\n
      ", + "type": "module", + "displayName": "Errors while writing" + }, + { + "textRaw": "An example writable stream", + "name": "an_example_writable_stream", + "desc": "

      The following illustrates a rather simplistic (and somewhat pointless) custom\nWritable stream implementation. While this specific Writable stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom Writable stream instance:

      \n
      const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  _write(chunk, encoding, callback) {\n    if (chunk.toString().indexOf('a') >= 0) {\n      callback(new Error('chunk is invalid'));\n    } else {\n      callback();\n    }\n  }\n}\n
      ", + "type": "module", + "displayName": "An example writable stream" + }, + { + "textRaw": "Decoding buffers in a writable stream", + "name": "decoding_buffers_in_a_writable_stream", + "desc": "

      Decoding buffers is a common task, for instance, when using transformers whose\ninput is a string. This is not a trivial process when using multi-byte\ncharacters encoding, such as UTF-8. The following example shows how to decode\nmulti-byte strings using StringDecoder and Writable.

      \n
      const { Writable } = require('stream');\nconst { StringDecoder } = require('string_decoder');\n\nclass StringWritable extends Writable {\n  constructor(options) {\n    super(options);\n    this._decoder = new StringDecoder(options && options.defaultEncoding);\n    this.data = '';\n  }\n  _write(chunk, encoding, callback) {\n    if (encoding === 'buffer') {\n      chunk = this._decoder.write(chunk);\n    }\n    this.data += chunk;\n    callback();\n  }\n  _final(callback) {\n    this.data += this._decoder.end();\n    callback();\n  }\n}\n\nconst euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);\nconst w = new StringWritable();\n\nw.write('currency: ');\nw.write(euro[0]);\nw.end(euro[1]);\n\nconsole.log(w.data); // currency: €\n
      ", + "type": "module", + "displayName": "Decoding buffers in a writable stream" + } + ], + "type": "misc", + "displayName": "Implementing a writable stream" + }, + { + "textRaw": "Implementing a readable stream", + "name": "implementing_a_readable_stream", + "desc": "

      The stream.Readable class is extended to implement a Readable stream.

      \n

      Custom Readable streams must call the new stream.Readable([options])\nconstructor and implement the readable._read() method.

      ", + "ctors": [ + { + "textRaw": "`new stream.Readable([options])`", + "type": "ctor", + "name": "stream.Readable", + "meta": { + "changes": [ + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/22795", + "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource. **Default:** `16384` (16KB), or `16` for `objectMode` streams.", + "name": "highWaterMark", + "type": "number", + "default": "`16384` (16KB), or `16` for `objectMode` streams", + "desc": "The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource." + }, + { + "textRaw": "`encoding` {string} If specified, then buffers will be decoded to strings using the specified encoding. **Default:** `null`.", + "name": "encoding", + "type": "string", + "default": "`null`", + "desc": "If specified, then buffers will be decoded to strings using the specified encoding." + }, + { + "textRaw": "`objectMode` {boolean} Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`. **Default:** `false`.", + "name": "objectMode", + "type": "boolean", + "default": "`false`", + "desc": "Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`." + }, + { + "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", + "name": "emitClose", + "type": "boolean", + "default": "`true`", + "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." + }, + { + "textRaw": "`read` {Function} Implementation for the [`stream._read()`][stream-_read] method.", + "name": "read", + "type": "Function", + "desc": "Implementation for the [`stream._read()`][stream-_read] method." + }, + { + "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][readable-_destroy] method.", + "name": "destroy", + "type": "Function", + "desc": "Implementation for the [`stream._destroy()`][readable-_destroy] method." + }, + { + "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `false`.", + "name": "autoDestroy", + "type": "boolean", + "default": "`false`", + "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." + } + ] + } + ] + } + ], + "desc": "\n
      const { Readable } = require('stream');\n\nclass MyReadable extends Readable {\n  constructor(options) {\n    // Calls the stream.Readable(options) constructor.\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Readable } = require('stream');\nconst util = require('util');\n\nfunction MyReadable(options) {\n  if (!(this instanceof MyReadable))\n    return new MyReadable(options);\n  Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  }\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`readable._read(size)`", + "type": "method", + "name": "_read", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {number} Number of bytes to read asynchronously", + "name": "size", + "type": "number", + "desc": "Number of bytes to read asynchronously" + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

      \n

      All Readable stream implementations must provide an implementation of the\nreadable._read() method to fetch data from the underlying resource.

      \n

      When readable._read() is called, if data is available from the resource,\nthe implementation should begin pushing that data into the read queue using the\nthis.push(dataChunk) method. _read() should continue reading\nfrom the resource and pushing data until readable.push() returns false. Only\nwhen _read() is called again after it has stopped should it resume pushing\nadditional data onto the queue.

      \n

      Once the readable._read() method has been called, it will not be called\nagain until more data is pushed through the readable.push()\nmethod. Empty data such as empty buffers and strings will not cause\nreadable._read() to be called.

      \n

      The size argument is advisory. For implementations where a \"read\" is a\nsingle operation that returns data can use the size argument to determine how\nmuch data to fetch. Other implementations may ignore this argument and simply\nprovide data whenever it becomes available. There is no need to \"wait\" until\nsize bytes are available before calling stream.push(chunk).

      \n

      The readable._read() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`readable._destroy(err, callback)`", + "type": "method", + "name": "_destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`err` {Error} A possible error.", + "name": "err", + "type": "Error", + "desc": "A possible error." + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      The _destroy() method is called by readable.destroy().\nIt can be overridden by child classes but it must not be called directly.

      " + }, + { + "textRaw": "`readable.push(chunk[, encoding])`", + "type": "method", + "name": "push", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if additional chunks of data may continue to be pushed; `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if additional chunks of data may continue to be pushed; `false` otherwise." + }, + "params": [ + { + "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value.", + "name": "chunk", + "type": "Buffer|Uint8Array|string|null|any", + "desc": "Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value." + }, + { + "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", + "name": "encoding", + "type": "string", + "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`." + } + ] + } + ], + "desc": "

      When chunk is a Buffer, Uint8Array or string, the chunk of data will\nbe added to the internal queue for users of the stream to consume.\nPassing chunk as null signals the end of the stream (EOF), after which no\nmore data can be written.

      \n

      When the Readable is operating in paused mode, the data added with\nreadable.push() can be read out by calling the\nreadable.read() method when the 'readable' event is\nemitted.

      \n

      When the Readable is operating in flowing mode, the data added with\nreadable.push() will be delivered by emitting a 'data' event.

      \n

      The readable.push() method is designed to be as flexible as possible. For\nexample, when wrapping a lower-level source that provides some form of\npause/resume mechanism, and a data callback, the low-level source can be wrapped\nby the custom Readable instance:

      \n
      // `_source` is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nclass SourceWrapper extends Readable {\n  constructor(options) {\n    super(options);\n\n    this._source = getLowLevelSourceObject();\n\n    // Every time there's data, push it into the internal buffer.\n    this._source.ondata = (chunk) => {\n      // If push() returns false, then stop reading from source.\n      if (!this.push(chunk))\n        this._source.readStop();\n    };\n\n    // When the source ends, push the EOF-signaling `null` chunk.\n    this._source.onend = () => {\n      this.push(null);\n    };\n  }\n  // _read() will be called when the stream wants to pull more data in.\n  // The advisory size argument is ignored in this case.\n  _read(size) {\n    this._source.readStart();\n  }\n}\n
      \n

      The readable.push() method is used to push the content\ninto the internal buffer. It can be driven by the readable._read() method.

      \n

      For streams not operating in object mode, if the chunk parameter of\nreadable.push() is undefined, it will be treated as empty string or\nbuffer. See readable.push('') for more information.

      " + } + ], + "modules": [ + { + "textRaw": "Errors while reading", + "name": "errors_while_reading", + "desc": "

      Errors occurring during processing of the readable._read() must be\npropagated through the readable.destroy(err) method.\nThrowing an Error from within readable._read() or manually emitting an\n'error' event results in undefined behavior.

      \n
      const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    const err = checkSomeErrorCondition();\n    if (err) {\n      this.destroy(err);\n    } else {\n      // Do some work.\n    }\n  }\n});\n
      ", + "type": "module", + "displayName": "Errors while reading" + } + ], + "examples": [ + { + "textRaw": "An example counting stream", + "name": "An example counting stream", + "type": "example", + "desc": "

      The following is a basic example of a Readable stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.

      \n
      const { Readable } = require('stream');\n\nclass Counter extends Readable {\n  constructor(opt) {\n    super(opt);\n    this._max = 1000000;\n    this._index = 1;\n  }\n\n  _read() {\n    const i = this._index++;\n    if (i > this._max)\n      this.push(null);\n    else {\n      const str = String(i);\n      const buf = Buffer.from(str, 'ascii');\n      this.push(buf);\n    }\n  }\n}\n
      " + } + ], + "type": "misc", + "displayName": "Implementing a readable stream" + }, + { + "textRaw": "Implementing a duplex stream", + "name": "implementing_a_duplex_stream", + "desc": "

      A Duplex stream is one that implements both Readable and\nWritable, such as a TCP socket connection.

      \n

      Because JavaScript does not have support for multiple inheritance, the\nstream.Duplex class is extended to implement a Duplex stream (as opposed\nto extending the stream.Readable and stream.Writable classes).

      \n

      The stream.Duplex class prototypically inherits from stream.Readable and\nparasitically from stream.Writable, but instanceof will work properly for\nboth base classes due to overriding Symbol.hasInstance on\nstream.Writable.

      \n

      Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.

      ", + "ctors": [ + { + "textRaw": "`new stream.Duplex(options)`", + "type": "ctor", + "name": "stream.Duplex", + "meta": { + "changes": [ + { + "version": "v8.4.0", + "pr-url": "https://github.com/nodejs/node/pull/14636", + "description": "The `readableHighWaterMark` and `writableHighWaterMark` options are supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "name": "options", + "type": "Object", + "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "options": [ + { + "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the stream will automatically end the writable side when the readable side ends. **Default:** `true`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`true`", + "desc": "If set to `false`, then the stream will automatically end the writable side when the readable side ends." + }, + { + "textRaw": "`readable` {boolean} Sets whether the `Duplex` should be readable. **Default:** `true`.", + "name": "readable", + "type": "boolean", + "default": "`true`", + "desc": "Sets whether the `Duplex` should be readable." + }, + { + "textRaw": "`writable` {boolean} Sets whether the `Duplex` should be writable. **Default:** `true`.", + "name": "writable", + "type": "boolean", + "default": "`true`", + "desc": "Sets whether the `Duplex` should be writable." + }, + { + "textRaw": "`readableObjectMode` {boolean} Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", + "name": "readableObjectMode", + "type": "boolean", + "default": "`false`", + "desc": "Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." + }, + { + "textRaw": "`writableObjectMode` {boolean} Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", + "name": "writableObjectMode", + "type": "boolean", + "default": "`false`", + "desc": "Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`." + }, + { + "textRaw": "`readableHighWaterMark` {number} Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided.", + "name": "readableHighWaterMark", + "type": "number", + "desc": "Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided." + }, + { + "textRaw": "`writableHighWaterMark` {number} Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided.", + "name": "writableHighWaterMark", + "type": "number", + "desc": "Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided." + } + ] + } + ] + } + ], + "desc": "\n
      const { Duplex } = require('stream');\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Duplex } = require('stream');\nconst util = require('util');\n\nfunction MyDuplex(options) {\n  if (!(this instanceof MyDuplex))\n    return new MyDuplex(options);\n  Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Duplex } = require('stream');\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
      " + } + ], + "modules": [ + { + "textRaw": "An example duplex stream", + "name": "an_example_duplex_stream", + "desc": "

      The following illustrates a simple example of a Duplex stream that wraps a\nhypothetical lower-level source object to which data can be written, and\nfrom which data can be read, albeit using an API that is not compatible with\nNode.js streams.\nThe following illustrates a simple example of a Duplex stream that buffers\nincoming written data via the Writable interface that is read back out\nvia the Readable interface.

      \n
      const { Duplex } = require('stream');\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n  constructor(source, options) {\n    super(options);\n    this[kSource] = source;\n  }\n\n  _write(chunk, encoding, callback) {\n    // The underlying source only deals with strings.\n    if (Buffer.isBuffer(chunk))\n      chunk = chunk.toString();\n    this[kSource].writeSomeData(chunk);\n    callback();\n  }\n\n  _read(size) {\n    this[kSource].fetchSomeData(size, (data, encoding) => {\n      this.push(Buffer.from(data, encoding));\n    });\n  }\n}\n
      \n

      The most important aspect of a Duplex stream is that the Readable and\nWritable sides operate independently of one another despite co-existing within\na single object instance.

      ", + "type": "module", + "displayName": "An example duplex stream" + }, + { + "textRaw": "Object mode duplex streams", + "name": "object_mode_duplex_streams", + "desc": "

      For Duplex streams, objectMode can be set exclusively for either the\nReadable or Writable side using the readableObjectMode and\nwritableObjectMode options respectively.

      \n

      In the following example, for instance, a new Transform stream (which is a\ntype of Duplex stream) is created that has an object mode Writable side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe Readable side.

      \n
      const { Transform } = require('stream');\n\n// All Transform streams are also Duplex Streams.\nconst myTransform = new Transform({\n  writableObjectMode: true,\n\n  transform(chunk, encoding, callback) {\n    // Coerce the chunk to a number if necessary.\n    chunk |= 0;\n\n    // Transform the chunk into something else.\n    const data = chunk.toString(16);\n\n    // Push the data onto the readable queue.\n    callback(null, '0'.repeat(data.length % 2) + data);\n  }\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n
      ", + "type": "module", + "displayName": "Object mode duplex streams" + } + ], + "type": "misc", + "displayName": "Implementing a duplex stream" + }, + { + "textRaw": "Implementing a transform stream", + "name": "implementing_a_transform_stream", + "desc": "

      A Transform stream is a Duplex stream where the output is computed\nin some way from the input. Examples include zlib streams or crypto\nstreams that compress, encrypt, or decrypt data.

      \n

      There is no requirement that the output be the same size as the input, the same\nnumber of chunks, or arrive at the same time. For example, a Hash stream will\nonly ever have a single chunk of output which is provided when the input is\nended. A zlib stream will produce output that is either much smaller or much\nlarger than its input.

      \n

      The stream.Transform class is extended to implement a Transform stream.

      \n

      The stream.Transform class prototypically inherits from stream.Duplex and\nimplements its own versions of the writable._write() and\nreadable._read() methods. Custom Transform implementations must\nimplement the transform._transform() method and may\nalso implement the transform._flush() method.

      \n

      Care must be taken when using Transform streams in that data written to the\nstream can cause the Writable side of the stream to become paused if the\noutput on the Readable side is not consumed.

      ", + "ctors": [ + { + "textRaw": "`new stream.Transform([options])`", + "type": "ctor", + "name": "stream.Transform", + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "name": "options", + "type": "Object", + "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "options": [ + { + "textRaw": "`transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method.", + "name": "transform", + "type": "Function", + "desc": "Implementation for the [`stream._transform()`][stream-_transform] method." + }, + { + "textRaw": "`flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] method.", + "name": "flush", + "type": "Function", + "desc": "Implementation for the [`stream._flush()`][stream-_flush] method." + } + ] + } + ] + } + ], + "desc": "\n
      const { Transform } = require('stream');\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Transform } = require('stream');\nconst util = require('util');\n\nfunction MyTransform(options) {\n  if (!(this instanceof MyTransform))\n    return new MyTransform(options);\n  Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Transform } = require('stream');\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  }\n});\n
      " + } + ], + "modules": [ + { + "textRaw": "Events: `'finish'` and `'end'`", + "name": "events:_`'finish'`_and_`'end'`", + "desc": "

      The 'finish' and 'end' events are from the stream.Writable\nand stream.Readable classes, respectively. The 'finish' event is emitted\nafter stream.end() is called and all chunks have been processed\nby stream._transform(). The 'end' event is emitted\nafter all data has been output, which occurs after the callback in\ntransform._flush() has been called.

      ", + "type": "module", + "displayName": "Events: `'finish'` and `'end'`" + } + ], + "methods": [ + { + "textRaw": "`transform._flush(callback)`", + "type": "method", + "name": "_flush", + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.", + "name": "callback", + "type": "Function", + "desc": "A callback function (optionally with an error argument and data) to be called when remaining data has been flushed." + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

      \n

      In some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a zlib compression stream will\nstore an amount of internal state used to optimally compress the output. When\nthe stream ends, however, that additional data needs to be flushed so that the\ncompressed data will be complete.

      \n

      Custom Transform implementations may implement the transform._flush()\nmethod. This will be called when there is no more written data to be consumed,\nbut before the 'end' event is emitted signaling the end of the\nReadable stream.

      \n

      Within the transform._flush() implementation, the transform.push() method\nmay be called zero or more times, as appropriate. The callback function must\nbe called when the flush operation is complete.

      \n

      The transform._flush() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`transform._transform(chunk, encoding, callback)`", + "type": "method", + "name": "_transform", + "signatures": [ + { + "params": [ + { + "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", + "name": "chunk", + "type": "Buffer|string|any", + "desc": "The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." + }, + { + "textRaw": "`encoding` {string} If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case.", + "name": "encoding", + "type": "string", + "desc": "If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case." + }, + { + "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed.", + "name": "callback", + "type": "Function", + "desc": "A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed." + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

      \n

      All Transform stream implementations must provide a _transform()\nmethod to accept input and produce output. The transform._transform()\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the transform.push() method.

      \n

      The transform.push() method may be called zero or more times to generate\noutput from a single input chunk, depending on how much is to be output\nas a result of the chunk.

      \n

      It is possible that no output is generated from any given chunk of input data.

      \n

      The callback function must be called only when the current chunk is completely\nconsumed. The first argument passed to the callback must be an Error object\nif an error occurred while processing the input or null otherwise. If a second\nargument is passed to the callback, it will be forwarded on to the\ntransform.push() method. In other words, the following are equivalent:

      \n
      transform.prototype._transform = function(data, encoding, callback) {\n  this.push(data);\n  callback();\n};\n\ntransform.prototype._transform = function(data, encoding, callback) {\n  callback(null, data);\n};\n
      \n

      The transform._transform() method is prefixed with an underscore because it\nis internal to the class that defines it, and should never be called directly by\nuser programs.

      \n

      transform._transform() is never called in parallel; streams implement a\nqueue mechanism, and to receive the next chunk, callback must be\ncalled, either synchronously or asynchronously.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `stream.PassThrough`", + "type": "class", + "name": "stream.PassThrough", + "desc": "

      The stream.PassThrough class is a trivial implementation of a Transform\nstream that simply passes the input bytes across to the output. Its purpose is\nprimarily for examples and testing, but there are some use cases where\nstream.PassThrough is useful as a building block for novel sorts of streams.

      " + } + ], + "type": "misc", + "displayName": "Implementing a transform stream" + } + ] + }, + { + "textRaw": "Additional notes", + "name": "Additional notes", + "type": "misc", + "miscs": [ + { + "textRaw": "Streams compatibility with async generators and async iterators", + "name": "streams_compatibility_with_async_generators_and_async_iterators", + "desc": "

      With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.

      \n

      Some common interop cases of using Node.js streams with async generators\nand async iterators are provided below.

      ", + "modules": [ + { + "textRaw": "Consuming readable streams with async iterators", + "name": "consuming_readable_streams_with_async_iterators", + "desc": "
      (async function() {\n  for await (const chunk of readable) {\n    console.log(chunk);\n  }\n})();\n
      \n

      Async iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.

      ", + "type": "module", + "displayName": "Consuming readable streams with async iterators" + }, + { + "textRaw": "Creating readable streams with async generators", + "name": "creating_readable_streams_with_async_generators", + "desc": "

      We can construct a Node.js readable stream from an asynchronous generator\nusing the Readable.from() utility method:

      \n
      const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'a';\n  yield 'b';\n  yield 'c';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
      ", + "type": "module", + "displayName": "Creating readable streams with async generators" + } + ], + "miscs": [ + { + "textRaw": "Piping to writable streams from async iterators", + "name": "Piping to writable streams from async iterators", + "type": "misc", + "desc": "

      In the scenario of writing to a writable stream from an async iterator, ensure\nthe correct handling of backpressure and errors.

      \n
      const { once } = require('events');\nconst finished = util.promisify(stream.finished);\n\nconst writable = fs.createWriteStream('./file');\n\nfunction drain(writable) {\n  if (writable.destroyed) {\n    return Promise.reject(new Error('premature close'));\n  }\n  return Promise.race([\n    once(writable, 'drain'),\n    once(writable, 'close')\n      .then(() => Promise.reject(new Error('premature close')))\n  ]);\n}\n\nasync function pump(iterable, writable) {\n  for await (const chunk of iterable) {\n    // Handle backpressure on write().\n    if (!writable.write(chunk)) {\n      await drain(writable);\n    }\n  }\n  writable.end();\n}\n\n(async function() {\n  // Ensure completion without errors.\n  await Promise.all([\n    pump(iterable, writable),\n    finished(writable)\n  ]);\n})();\n
      \n

      In the above, errors on write() would be caught and thrown by the\nonce() listener for the 'drain' event, since once() will also handle the\n'error' event. To ensure completion of the write stream without errors,\nit is safer to use the finished() method as above, instead of using the\nonce() listener for the 'finish' event. Under certain cases, an 'error'\nevent could be emitted by the writable stream after 'finish' and as once()\nwill release the 'error' handler on handling the 'finish' event, it could\nresult in an unhandled error.

      \n

      Alternatively, the readable stream could be wrapped with Readable.from() and\nthen piped via .pipe():

      \n
      const finished = util.promisify(stream.finished);\n\nconst writable = fs.createWriteStream('./file');\n\n(async function() {\n  const readable = Readable.from(iterable);\n  readable.pipe(writable);\n  // Ensure completion without errors.\n  await finished(writable);\n})();\n
      \n

      Or, using stream.pipeline() to pipe streams:

      \n
      const pipeline = util.promisify(stream.pipeline);\n\nconst writable = fs.createWriteStream('./file');\n\n(async function() {\n  const readable = Readable.from(iterable);\n  await pipeline(readable, writable);\n})();\n
      " + } + ], + "type": "misc", + "displayName": "Streams compatibility with async generators and async iterators" + }, + { + "textRaw": "Compatibility with older Node.js versions", + "name": "Compatibility with older Node.js versions", + "type": "misc", + "desc": "

      Prior to Node.js 0.10, the Readable stream interface was simpler, but also\nless powerful and less useful.

      \n
        \n
      • Rather than waiting for calls to the stream.read() method,\n'data' events would begin emitting immediately. Applications that\nwould need to perform some amount of work to decide how to handle data\nwere required to store read data into buffers so the data would not be lost.
      • \n
      • The stream.pause() method was advisory, rather than\nguaranteed. This meant that it was still necessary to be prepared to receive\n'data' events even when the stream was in a paused state.
      • \n
      \n

      In Node.js 0.10, the Readable class was added. For backward\ncompatibility with older Node.js programs, Readable streams switch into\n\"flowing mode\" when a 'data' event handler is added, or when the\nstream.resume() method is called. The effect is that, even\nwhen not using the new stream.read() method and\n'readable' event, it is no longer necessary to worry about losing\n'data' chunks.

      \n

      While most applications will continue to function normally, this introduces an\nedge case in the following conditions:

      \n
        \n
      • No 'data' event listener is added.
      • \n
      • The stream.resume() method is never called.
      • \n
      • The stream is not piped to any writable destination.
      • \n
      \n

      For example, consider the following code:

      \n
      // WARNING!  BROKEN!\nnet.createServer((socket) => {\n\n  // We add an 'end' listener, but never consume the data.\n  socket.on('end', () => {\n    // It will never get here.\n    socket.end('The message was received but was not processed.\\n');\n  });\n\n}).listen(1337);\n
      \n

      Prior to Node.js 0.10, the incoming message data would be simply discarded.\nHowever, in Node.js 0.10 and beyond, the socket remains paused forever.

      \n

      The workaround in this situation is to call the\nstream.resume() method to begin the flow of data:

      \n
      // Workaround.\nnet.createServer((socket) => {\n  socket.on('end', () => {\n    socket.end('The message was received but was not processed.\\n');\n  });\n\n  // Start the flow of data, discarding it.\n  socket.resume();\n}).listen(1337);\n
      \n

      In addition to new Readable streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap() method.

      " + }, + { + "textRaw": "`highWaterMark` discrepancy after calling `readable.setEncoding()`", + "name": "`highwatermark`_discrepancy_after_calling_`readable.setencoding()`", + "desc": "

      The use of readable.setEncoding() will change the behavior of how the\nhighWaterMark operates in non-object mode.

      \n

      Typically, the size of the current buffer is measured against the\nhighWaterMark in bytes. However, after setEncoding() is called, the\ncomparison function will begin to measure the buffer's size in characters.

      \n

      This is not a problem in common cases with latin1 or ascii. But it is\nadvised to be mindful about this behavior when working with strings that could\ncontain multi-byte characters.

      ", + "type": "misc", + "displayName": "`highWaterMark` discrepancy after calling `readable.setEncoding()`" + } + ], + "methods": [ + { + "textRaw": "`readable.read(0)`", + "type": "method", + "name": "read", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.

      \n

      If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.

      \n

      While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.

      " + }, + { + "textRaw": "`readable.push('')`", + "type": "method", + "name": "push", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Use of readable.push('') is not recommended.

      \n

      Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.

      " + } + ] + } + ], + "type": "module", + "displayName": "Stream" + }, + { + "textRaw": "String decoder", + "name": "string_decoder", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/string_decoder.js

      \n

      The string_decoder module provides an API for decoding Buffer objects into\nstrings in a manner that preserves encoded multi-byte UTF-8 and UTF-16\ncharacters. It can be accessed using:

      \n
      const { StringDecoder } = require('string_decoder');\n
      \n

      The following example shows the basic use of the StringDecoder class.

      \n
      const { StringDecoder } = require('string_decoder');\nconst decoder = new StringDecoder('utf8');\n\nconst cent = Buffer.from([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nconst euro = Buffer.from([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));\n
      \n

      When a Buffer instance is written to the StringDecoder instance, an\ninternal buffer is used to ensure that the decoded string does not contain\nany incomplete multibyte characters. These are held in the buffer until the\nnext call to stringDecoder.write() or until stringDecoder.end() is called.

      \n

      In the following example, the three UTF-8 encoded bytes of the European Euro\nsymbol (€) are written over three separate operations:

      \n
      const { StringDecoder } = require('string_decoder');\nconst decoder = new StringDecoder('utf8');\n\ndecoder.write(Buffer.from([0xE2]));\ndecoder.write(Buffer.from([0x82]));\nconsole.log(decoder.end(Buffer.from([0xAC])));\n
      ", + "classes": [ + { + "textRaw": "Class: `StringDecoder`", + "type": "class", + "name": "StringDecoder", + "methods": [ + { + "textRaw": "`stringDecoder.end([buffer])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode." + } + ] + } + ], + "desc": "

      Returns any remaining input stored in the internal buffer as a string. Bytes\nrepresenting incomplete UTF-8 and UTF-16 characters will be replaced with\nsubstitution characters appropriate for the character encoding.

      \n

      If the buffer argument is provided, one final call to stringDecoder.write()\nis performed before returning the remaining input.

      " + }, + { + "textRaw": "`stringDecoder.write(buffer)`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9618", + "description": "Each invalid character is now replaced by a single replacement character instead of one for each individual byte." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode." + } + ] + } + ], + "desc": "

      Returns a decoded string, ensuring that any incomplete multibyte characters at\nthe end of the Buffer, or TypedArray, or DataView are omitted from the\nreturned string and stored in an internal buffer for the next call to\nstringDecoder.write() or stringDecoder.end().

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`encoding` {string} The character [encoding][] the `StringDecoder` will use. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The character [encoding][] the `StringDecoder` will use." + } + ], + "desc": "

      Creates a new StringDecoder instance.

      " + } + ] + } + ], + "type": "module", + "displayName": "String decoder" + }, + { + "textRaw": "Timers", + "name": "timers", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/timers.js

      \n

      The timer module exposes a global API for scheduling functions to\nbe called at some future period of time. Because the timer functions are\nglobals, there is no need to call require('timers') to use the API.

      \n

      The timer functions within Node.js implement a similar API as the timers API\nprovided by Web Browsers but use a different internal implementation that is\nbuilt around the Node.js Event Loop.

      ", + "classes": [ + { + "textRaw": "Class: `Immediate`", + "type": "class", + "name": "Immediate", + "desc": "

      This object is created internally and is returned from setImmediate(). It\ncan be passed to clearImmediate() in order to cancel the scheduled\nactions.

      \n

      By default, when an immediate is scheduled, the Node.js event loop will continue\nrunning as long as the immediate is active. The Immediate object returned by\nsetImmediate() exports both immediate.ref() and immediate.unref()\nfunctions that can be used to control this default behavior.

      ", + "methods": [ + { + "textRaw": "`immediate.hasRef()`", + "type": "method", + "name": "hasRef", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      If true, the Immediate object will keep the Node.js event loop active.

      " + }, + { + "textRaw": "`immediate.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v9.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Immediate} a reference to `immediate`", + "name": "return", + "type": "Immediate", + "desc": "a reference to `immediate`" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nImmediate is active. Calling immediate.ref() multiple times will have no\neffect.

      \n

      By default, all Immediate objects are \"ref'ed\", making it normally unnecessary\nto call immediate.ref() unless immediate.unref() had been called previously.

      " + }, + { + "textRaw": "`immediate.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v9.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Immediate} a reference to `immediate`", + "name": "return", + "type": "Immediate", + "desc": "a reference to `immediate`" + }, + "params": [] + } + ], + "desc": "

      When called, the active Immediate object will not require the Node.js event\nloop to remain active. If there is no other activity keeping the event loop\nrunning, the process may exit before the Immediate object's callback is\ninvoked. Calling immediate.unref() multiple times will have no effect.

      " + } + ] + }, + { + "textRaw": "Class: `Timeout`", + "type": "class", + "name": "Timeout", + "desc": "

      This object is created internally and is returned from setTimeout() and\nsetInterval(). It can be passed to either clearTimeout() or\nclearInterval() in order to cancel the scheduled actions.

      \n

      By default, when a timer is scheduled using either setTimeout() or\nsetInterval(), the Node.js event loop will continue running as long as the\ntimer is active. Each of the Timeout objects returned by these functions\nexport both timeout.ref() and timeout.unref() functions that can be used to\ncontrol this default behavior.

      ", + "methods": [ + { + "textRaw": "`timeout.hasRef()`", + "type": "method", + "name": "hasRef", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      If true, the Timeout object will keep the Node.js event loop active.

      " + }, + { + "textRaw": "`timeout.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} a reference to `timeout`", + "name": "return", + "type": "Timeout", + "desc": "a reference to `timeout`" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nTimeout is active. Calling timeout.ref() multiple times will have no effect.

      \n

      By default, all Timeout objects are \"ref'ed\", making it normally unnecessary\nto call timeout.ref() unless timeout.unref() had been called previously.

      " + }, + { + "textRaw": "`timeout.refresh()`", + "type": "method", + "name": "refresh", + "meta": { + "added": [ + "v10.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} a reference to `timeout`", + "name": "return", + "type": "Timeout", + "desc": "a reference to `timeout`" + }, + "params": [] + } + ], + "desc": "

      Sets the timer's start time to the current time, and reschedules the timer to\ncall its callback at the previously specified duration adjusted to the current\ntime. This is useful for refreshing a timer without allocating a new\nJavaScript object.

      \n

      Using this on a timer that has already called its callback will reactivate the\ntimer.

      " + }, + { + "textRaw": "`timeout.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} a reference to `timeout`", + "name": "return", + "type": "Timeout", + "desc": "a reference to `timeout`" + }, + "params": [] + } + ], + "desc": "

      When called, the active Timeout object will not require the Node.js event loop\nto remain active. If there is no other activity keeping the event loop running,\nthe process may exit before the Timeout object's callback is invoked. Calling\ntimeout.unref() multiple times will have no effect.

      \n

      Calling timeout.unref() creates an internal timer that will wake the Node.js\nevent loop. Creating too many of these can adversely impact performance\nof the Node.js application.

      " + }, + { + "textRaw": "`timeout[Symbol.toPrimitive]()`", + "type": "method", + "name": "[Symbol.toPrimitive]", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} a number that can be used to reference this `timeout`", + "name": "return", + "type": "integer", + "desc": "a number that can be used to reference this `timeout`" + }, + "params": [] + } + ], + "desc": "

      Coerce a Timeout to a primitive. The primitive can be used to\nclear the Timeout. The primitive can only be used in the\nsame thread where the timeout was created. Therefore, to use it\nacross worker_threads it must first be passed to the correct\nthread. This allows enhanced compatibility with browser\nsetTimeout() and setInterval() implementations.

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Scheduling timers", + "name": "scheduling_timers", + "desc": "

      A timer in Node.js is an internal construct that calls a given function after\na certain period of time. When a timer's function is called varies depending on\nwhich method was used to create the timer and what other work the Node.js\nevent loop is doing.

      ", + "methods": [ + { + "textRaw": "`setImmediate(callback[, ...args])`", + "type": "method", + "name": "setImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Immediate} for use with [`clearImmediate()`][]", + "name": "return", + "type": "Immediate", + "desc": "for use with [`clearImmediate()`][]" + }, + "params": [ + { + "textRaw": "`callback` {Function} The function to call at the end of this turn of the Node.js [Event Loop][]", + "name": "callback", + "type": "Function", + "desc": "The function to call at the end of this turn of the Node.js [Event Loop][]" + }, + { + "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass when the `callback` is called." + } + ] + } + ], + "desc": "

      Schedules the \"immediate\" execution of the callback after I/O events'\ncallbacks.

      \n

      When multiple calls to setImmediate() are made, the callback functions are\nqueued for execution in the order in which they are created. The entire callback\nqueue is processed every event loop iteration. If an immediate timer is queued\nfrom inside an executing callback, that timer will not be triggered until the\nnext event loop iteration.

      \n

      If callback is not a function, a TypeError will be thrown.

      \n

      This method has a custom variant for promises that is available using\nutil.promisify():

      \n
      const util = require('util');\nconst setImmediatePromise = util.promisify(setImmediate);\n\nsetImmediatePromise('foobar').then((value) => {\n  // value === 'foobar' (passing values is optional)\n  // This is executed after all I/O callbacks.\n});\n\n// Or with async function\nasync function timerExample() {\n  console.log('Before I/O callbacks');\n  await setImmediatePromise();\n  console.log('After I/O callbacks');\n}\ntimerExample();\n
      " + }, + { + "textRaw": "`setInterval(callback, delay[, ...args])`", + "type": "method", + "name": "setInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} for use with [`clearInterval()`][]", + "name": "return", + "type": "Timeout", + "desc": "for use with [`clearInterval()`][]" + }, + "params": [ + { + "textRaw": "`callback` {Function} The function to call when the timer elapses.", + "name": "callback", + "type": "Function", + "desc": "The function to call when the timer elapses." + }, + { + "textRaw": "`delay` {number} The number of milliseconds to wait before calling the `callback`.", + "name": "delay", + "type": "number", + "desc": "The number of milliseconds to wait before calling the `callback`." + }, + { + "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass when the `callback` is called." + } + ] + } + ], + "desc": "

      Schedules repeated execution of callback every delay milliseconds.

      \n

      When delay is larger than 2147483647 or less than 1, the delay will be\nset to 1. Non-integer delays are truncated to an integer.

      \n

      If callback is not a function, a TypeError will be thrown.

      " + }, + { + "textRaw": "`setTimeout(callback, delay[, ...args])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} for use with [`clearTimeout()`][]", + "name": "return", + "type": "Timeout", + "desc": "for use with [`clearTimeout()`][]" + }, + "params": [ + { + "textRaw": "`callback` {Function} The function to call when the timer elapses.", + "name": "callback", + "type": "Function", + "desc": "The function to call when the timer elapses." + }, + { + "textRaw": "`delay` {number} The number of milliseconds to wait before calling the `callback`.", + "name": "delay", + "type": "number", + "desc": "The number of milliseconds to wait before calling the `callback`." + }, + { + "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass when the `callback` is called." + } + ] + } + ], + "desc": "

      Schedules execution of a one-time callback after delay milliseconds.

      \n

      The callback will likely not be invoked in precisely delay milliseconds.\nNode.js makes no guarantees about the exact timing of when callbacks will fire,\nnor of their ordering. The callback will be called as close as possible to the\ntime specified.

      \n

      When delay is larger than 2147483647 or less than 1, the delay\nwill be set to 1. Non-integer delays are truncated to an integer.

      \n

      If callback is not a function, a TypeError will be thrown.

      \n

      This method has a custom variant for promises that is available using\nutil.promisify():

      \n
      const util = require('util');\nconst setTimeoutPromise = util.promisify(setTimeout);\n\nsetTimeoutPromise(40, 'foobar').then((value) => {\n  // value === 'foobar' (passing values is optional)\n  // This is executed after about 40 milliseconds.\n});\n
      " + } + ], + "type": "module", + "displayName": "Scheduling timers" + }, + { + "textRaw": "Cancelling timers", + "name": "cancelling_timers", + "desc": "

      The setImmediate(), setInterval(), and setTimeout() methods\neach return objects that represent the scheduled timers. These can be used to\ncancel the timer and prevent it from triggering.

      \n

      It is not possible to cancel timers that were created using the promisified\nvariants of setImmediate(), setTimeout().

      ", + "methods": [ + { + "textRaw": "`clearImmediate(immediate)`", + "type": "method", + "name": "clearImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`immediate` {Immediate} An `Immediate` object as returned by [`setImmediate()`][].", + "name": "immediate", + "type": "Immediate", + "desc": "An `Immediate` object as returned by [`setImmediate()`][]." + } + ] + } + ], + "desc": "

      Cancels an Immediate object created by setImmediate().

      " + }, + { + "textRaw": "`clearInterval(timeout)`", + "type": "method", + "name": "clearInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`timeout` {Timeout} A `Timeout` object as returned by [`setInterval()`][].", + "name": "timeout", + "type": "Timeout", + "desc": "A `Timeout` object as returned by [`setInterval()`][]." + } + ] + } + ], + "desc": "

      Cancels a Timeout object created by setInterval().

      " + }, + { + "textRaw": "`clearTimeout(timeout)`", + "type": "method", + "name": "clearTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`timeout` {Timeout} A `Timeout` object as returned by [`setTimeout()`][].", + "name": "timeout", + "type": "Timeout", + "desc": "A `Timeout` object as returned by [`setTimeout()`][]." + } + ] + } + ], + "desc": "

      Cancels a Timeout object created by setTimeout().

      " + } + ], + "type": "module", + "displayName": "Cancelling timers" + } + ], + "type": "module", + "displayName": "Timers" + }, + { + "textRaw": "TLS (SSL)", + "name": "tls_(ssl)", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/tls.js

      \n

      The tls module provides an implementation of the Transport Layer Security\n(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.\nThe module can be accessed using:

      \n
      const tls = require('tls');\n
      ", + "modules": [ + { + "textRaw": "TLS/SSL concepts", + "name": "tls/ssl_concepts", + "desc": "

      The TLS/SSL is a public/private key infrastructure (PKI). For most common\ncases, each client and server must have a private key.

      \n

      Private keys can be generated in multiple ways. The example below illustrates\nuse of the OpenSSL command-line interface to generate a 2048-bit RSA private\nkey:

      \n
      openssl genrsa -out ryans-key.pem 2048\n
      \n

      With TLS/SSL, all servers (and some clients) must have a certificate.\nCertificates are public keys that correspond to a private key, and that are\ndigitally signed either by a Certificate Authority or by the owner of the\nprivate key (such certificates are referred to as \"self-signed\"). The first\nstep to obtaining a certificate is to create a Certificate Signing Request\n(CSR) file.

      \n

      The OpenSSL command-line interface can be used to generate a CSR for a private\nkey:

      \n
      openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem\n
      \n

      Once the CSR file is generated, it can either be sent to a Certificate\nAuthority for signing or used to generate a self-signed certificate.

      \n

      Creating a self-signed certificate using the OpenSSL command-line interface\nis illustrated in the example below:

      \n
      openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem\n
      \n

      Once the certificate is generated, it can be used to generate a .pfx or\n.p12 file:

      \n
      openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \\\n      -certfile ca-cert.pem -out ryans.pfx\n
      \n

      Where:

      \n
        \n
      • in: is the signed certificate
      • \n
      • inkey: is the associated private key
      • \n
      • certfile: is a concatenation of all Certificate Authority (CA) certs into\na single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
      • \n
      ", + "miscs": [ + { + "textRaw": "Perfect forward secrecy", + "name": "Perfect forward secrecy", + "type": "misc", + "desc": "

      The term forward secrecy or perfect forward secrecy describes a feature\nof key-agreement (i.e., key-exchange) methods. That is, the server and client\nkeys are used to negotiate new temporary keys that are used specifically and\nonly for the current communication session. Practically, this means that even\nif the server's private key is compromised, communication can only be decrypted\nby eavesdroppers if the attacker manages to obtain the key-pair specifically\ngenerated for the session.

      \n

      Perfect forward secrecy is achieved by randomly generating a key pair for\nkey-agreement on every TLS/SSL handshake (in contrast to using the same key for\nall sessions). Methods implementing this technique are called \"ephemeral\".

      \n

      Currently two methods are commonly used to achieve perfect forward secrecy (note\nthe character \"E\" appended to the traditional abbreviations):

      \n
        \n
      • DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.
      • \n
      • ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman\nkey-agreement protocol.
      • \n
      \n

      Ephemeral methods may have some performance drawbacks, because key generation\nis expensive.

      \n

      To use perfect forward secrecy using DHE with the tls module, it is required\nto generate Diffie-Hellman parameters and specify them with the dhparam\noption to tls.createSecureContext(). The following illustrates the use of\nthe OpenSSL command-line interface to generate such parameters:

      \n
      openssl dhparam -outform PEM -out dhparam.pem 2048\n
      \n

      If using perfect forward secrecy using ECDHE, Diffie-Hellman parameters are\nnot required and a default ECDHE curve will be used. The ecdhCurve property\ncan be used when creating a TLS Server to specify the list of names of supported\ncurves to use, see tls.createServer() for more info.

      \n

      Perfect forward secrecy was optional up to TLSv1.2, but it is not optional for\nTLSv1.3, because all TLSv1.3 cipher suites use ECDHE.

      " + }, + { + "textRaw": "ALPN and SNI", + "name": "ALPN and SNI", + "type": "misc", + "desc": "

      ALPN (Application-Layer Protocol Negotiation Extension) and\nSNI (Server Name Indication) are TLS handshake extensions:

      \n
        \n
      • ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)
      • \n
      • SNI: Allows the use of one TLS server for multiple hostnames with different\nSSL certificates.
      • \n
      " + }, + { + "textRaw": "Pre-shared keys", + "name": "Pre-shared keys", + "type": "misc", + "desc": "

      TLS-PSK support is available as an alternative to normal certificate-based\nauthentication. It uses a pre-shared key instead of certificates to\nauthenticate a TLS connection, providing mutual authentication.\nTLS-PSK and public key infrastructure are not mutually exclusive. Clients and\nservers can accommodate both, choosing either of them during the normal cipher\nnegotiation step.

      \n

      TLS-PSK is only a good choice where means exist to securely share a\nkey with every connecting machine, so it does not replace PKI\n(Public Key Infrastructure) for the majority of TLS uses.\nThe TLS-PSK implementation in OpenSSL has seen many security flaws in\nrecent years, mostly because it is used only by a minority of applications.\nPlease consider all alternative solutions before switching to PSK ciphers.\nUpon generating PSK it is of critical importance to use sufficient entropy as\ndiscussed in RFC 4086. Deriving a shared secret from a password or other\nlow-entropy sources is not secure.

      \n

      PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly\nspecifying a cipher suite with the ciphers option. The list of available\nciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3\nciphers are eligible for PSK but currently only those that use SHA256 digest are\nsupported they can be retrieved via openssl ciphers -v -s -tls1_3 -psk.

      \n

      According to the RFC 4279, PSK identities up to 128 bytes in length and\nPSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0\nmaximum identity size is 128 bytes, and maximum PSK length is 256 bytes.

      \n

      The current implementation doesn't support asynchronous PSK callbacks due to the\nlimitations of the underlying OpenSSL API.

      " + }, + { + "textRaw": "Client-initiated renegotiation attack mitigation", + "name": "Client-initiated renegotiation attack mitigation", + "type": "misc", + "desc": "

      The TLS protocol allows clients to renegotiate certain aspects of the TLS\nsession. Unfortunately, session renegotiation requires a disproportionate amount\nof server-side resources, making it a potential vector for denial-of-service\nattacks.

      \n

      To mitigate the risk, renegotiation is limited to three times every ten minutes.\nAn 'error' event is emitted on the tls.TLSSocket instance when this\nthreshold is exceeded. The limits are configurable:

      \n
        \n
      • tls.CLIENT_RENEG_LIMIT <number> Specifies the number of renegotiation\nrequests. Default: 3.
      • \n
      • tls.CLIENT_RENEG_WINDOW <number> Specifies the time renegotiation window\nin seconds. Default: 600 (10 minutes).
      • \n
      \n

      The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.

      \n

      TLSv1.3 does not support renegotiation.

      " + } + ], + "modules": [ + { + "textRaw": "Session resumption", + "name": "session_resumption", + "desc": "

      Establishing a TLS session can be relatively slow. The process can be sped\nup by saving and later reusing the session state. There are several mechanisms\nto do so, discussed here from oldest to newest (and preferred).

      ", + "modules": [ + { + "textRaw": "Session identifiers", + "name": "session_identifiers", + "desc": "

      Servers generate a unique ID for new connections and\nsend it to the client. Clients and servers save the session state. When\nreconnecting, clients send the ID of their saved session state and if the server\nalso has the state for that ID, it can agree to use it. Otherwise, the server\nwill create a new session. See RFC 2246 for more information, page 23 and\n30.

      \n

      Resumption using session identifiers is supported by most web browsers when\nmaking HTTPS requests.

      \n

      For Node.js, clients wait for the 'session' event to get the session data,\nand provide the data to the session option of a subsequent tls.connect()\nto reuse the session. Servers must\nimplement handlers for the 'newSession' and 'resumeSession' events\nto save and restore the session data using the session ID as the lookup key to\nreuse sessions. To reuse sessions across load balancers or cluster workers,\nservers must use a shared session cache (such as Redis) in their session\nhandlers.

      ", + "type": "module", + "displayName": "Session identifiers" + }, + { + "textRaw": "Session tickets", + "name": "session_tickets", + "desc": "

      The servers encrypt the entire session state and send it\nto the client as a \"ticket\". When reconnecting, the state is sent to the server\nin the initial connection. This mechanism avoids the need for server-side\nsession cache. If the server doesn't use the ticket, for any reason (failure\nto decrypt it, it's too old, etc.), it will create a new session and send a new\nticket. See RFC 5077 for more information.

      \n

      Resumption using session tickets is becoming commonly supported by many web\nbrowsers when making HTTPS requests.

      \n

      For Node.js, clients use the same APIs for resumption with session identifiers\nas for resumption with session tickets. For debugging, if\ntls.TLSSocket.getTLSTicket() returns a value, the session data contains a\nticket, otherwise it contains client-side session state.

      \n

      With TLSv1.3, be aware that multiple tickets may be sent by the server,\nresulting in multiple 'session' events, see 'session' for more\ninformation.

      \n

      Single process servers need no specific implementation to use session tickets.\nTo use session tickets across server restarts or load balancers, servers must\nall have the same ticket keys. There are three 16-byte keys internally, but the\ntls API exposes them as a single 48-byte buffer for convenience.

      \n

      Its possible to get the ticket keys by calling server.getTicketKeys() on\none server instance and then distribute them, but it is more reasonable to\nsecurely generate 48 bytes of secure random data and set them with the\nticketKeys option of tls.createServer(). The keys should be regularly\nregenerated and server's keys can be reset with\nserver.setTicketKeys().

      \n

      Session ticket keys are cryptographic keys, and they must be stored\nsecurely. With TLS 1.2 and below, if they are compromised all sessions that\nused tickets encrypted with them can be decrypted. They should not be stored\non disk, and they should be regenerated regularly.

      \n

      If clients advertise support for tickets, the server will send them. The\nserver can disable tickets by supplying\nrequire('constants').SSL_OP_NO_TICKET in secureOptions.

      \n

      Both session identifiers and session tickets timeout, causing the server to\ncreate new sessions. The timeout can be configured with the sessionTimeout\noption of tls.createServer().

      \n

      For all the mechanisms, when resumption fails, servers will create new sessions.\nSince failing to resume the session does not cause TLS/HTTPS connection\nfailures, it is easy to not notice unnecessarily poor TLS performance. The\nOpenSSL CLI can be used to verify that servers are resuming sessions. Use the\n-reconnect option to openssl s_client, for example:

      \n
      $ openssl s_client -connect localhost:443 -reconnect\n
      \n

      Read through the debug output. The first connection should say \"New\", for\nexample:

      \n
      New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256\n
      \n

      Subsequent connections should say \"Reused\", for example:

      \n
      Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256\n
      ", + "type": "module", + "displayName": "Session tickets" + } + ], + "type": "module", + "displayName": "Session resumption" + } + ], + "type": "module", + "displayName": "TLS/SSL concepts" + }, + { + "textRaw": "Modifying the default TLS cipher suite", + "name": "modifying_the_default_tls_cipher_suite", + "desc": "

      Node.js is built with a default suite of enabled and disabled TLS ciphers. This\ndefault cipher list can be configured when building Node.js to allow\ndistributions to provide their own default list.

      \n

      The following command can be used to show the default cipher suite:

      \n
      node -p crypto.constants.defaultCoreCipherList | tr ':' '\\n'\nTLS_AES_256_GCM_SHA384\nTLS_CHACHA20_POLY1305_SHA256\nTLS_AES_128_GCM_SHA256\nECDHE-RSA-AES128-GCM-SHA256\nECDHE-ECDSA-AES128-GCM-SHA256\nECDHE-RSA-AES256-GCM-SHA384\nECDHE-ECDSA-AES256-GCM-SHA384\nDHE-RSA-AES128-GCM-SHA256\nECDHE-RSA-AES128-SHA256\nDHE-RSA-AES128-SHA256\nECDHE-RSA-AES256-SHA384\nDHE-RSA-AES256-SHA384\nECDHE-RSA-AES256-SHA256\nDHE-RSA-AES256-SHA256\nHIGH\n!aNULL\n!eNULL\n!EXPORT\n!DES\n!RC4\n!MD5\n!PSK\n!SRP\n!CAMELLIA\n
      \n

      This default can be replaced entirely using the --tls-cipher-list command\nline switch (directly, or via the NODE_OPTIONS environment variable). For\ninstance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS\ncipher suite:

      \n
      node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js\n\nexport NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'\nnode server.js\n
      \n

      The default can also be replaced on a per client or server basis using the\nciphers option from tls.createSecureContext(), which is also available\nin tls.createServer(), tls.connect(), and when creating new\ntls.TLSSockets.

      \n

      The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones\nthat start with 'TLS_', and specifications for TLSv1.2 and below cipher\nsuites. The TLSv1.2 ciphers support a legacy specification format, consult\nthe OpenSSL cipher list format documentation for details, but those\nspecifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only\nbe enabled by including their full name in the cipher list. They cannot, for\nexample, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or\n'!EECDH' specification.

      \n

      Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3\nprotocol is significantly more secure than TLSv1.2, and will always be chosen\nover TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3\ncipher suites are enabled.

      \n

      The default cipher suite included within Node.js has been carefully\nselected to reflect current security best practices and risk mitigation.\nChanging the default cipher suite can have a significant impact on the security\nof an application. The --tls-cipher-list switch and ciphers option should by\nused only if absolutely necessary.

      \n

      The default cipher suite prefers GCM ciphers for Chrome's 'modern\ncryptography' setting and also prefers ECDHE and DHE ciphers for perfect\nforward secrecy, while offering some backward compatibility.

      \n

      128 bit AES is preferred over 192 and 256 bit AES in light of specific\nattacks affecting larger AES key sizes.

      \n

      Old clients that rely on insecure and deprecated RC4 or DES-based ciphers\n(like Internet Explorer 6) cannot complete the handshaking process with\nthe default configuration. If these clients must be supported, the\nTLS recommendations may offer a compatible cipher suite. For more details\non the format, see the OpenSSL cipher list format documentation.

      \n

      There are only 5 TLSv1.3 cipher suites:

      \n
        \n
      • 'TLS_AES_256_GCM_SHA384'
      • \n
      • 'TLS_CHACHA20_POLY1305_SHA256'
      • \n
      • 'TLS_AES_128_GCM_SHA256'
      • \n
      • 'TLS_AES_128_CCM_SHA256'
      • \n
      • 'TLS_AES_128_CCM_8_SHA256'
      • \n
      \n

      The first 3 are enabled by default. The last 2 CCM-based suites are supported\nby TLSv1.3 because they may be more performant on constrained systems, but they\nare not enabled by default since they offer less security.

      ", + "type": "module", + "displayName": "Modifying the default TLS cipher suite" + } + ], + "classes": [ + { + "textRaw": "Class: `tls.CryptoStream`", + "type": "class", + "name": "tls.CryptoStream", + "meta": { + "added": [ + "v0.3.4" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", + "desc": "

      The tls.CryptoStream class represents a stream of encrypted data. This class\nis deprecated and should no longer be used.

      ", + "properties": [ + { + "textRaw": "`cryptoStream.bytesWritten`", + "name": "bytesWritten", + "meta": { + "added": [ + "v0.3.4" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "desc": "

      The cryptoStream.bytesWritten property returns the total number of bytes\nwritten to the underlying socket including the bytes required for the\nimplementation of the TLS protocol.

      " + } + ] + }, + { + "textRaw": "Class: `tls.SecurePair`", + "type": "class", + "name": "tls.SecurePair", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", + "desc": "

      Returned by tls.createSecurePair().

      ", + "events": [ + { + "textRaw": "Event: `'secure'`", + "type": "event", + "name": "secure", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'secure' event is emitted by the SecurePair object once a secure\nconnection has been established.

      \n

      As with checking for the server\n'secureConnection'\nevent, pair.cleartext.authorized should be inspected to confirm whether the\ncertificate used is properly authorized.

      " + } + ] + }, + { + "textRaw": "Class: `tls.Server`", + "type": "class", + "name": "tls.Server", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "desc": "\n

      Accepts encrypted connections using TLS or SSL.

      ", + "events": [ + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established, before the TLS\nhandshake begins. socket is typically an object of type net.Socket.\nUsually users will not want to access this event.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the TLS server. In that case, any Duplex stream can be passed.

      " + }, + { + "textRaw": "Event: `'keylog'`", + "type": "event", + "name": "keylog", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`line` {Buffer} Line of ASCII text, in NSS `SSLKEYLOGFILE` format.", + "name": "line", + "type": "Buffer", + "desc": "Line of ASCII text, in NSS `SSLKEYLOGFILE` format." + }, + { + "textRaw": "`tlsSocket` {tls.TLSSocket} The `tls.TLSSocket` instance on which it was generated.", + "name": "tlsSocket", + "type": "tls.TLSSocket", + "desc": "The `tls.TLSSocket` instance on which it was generated." + } + ], + "desc": "

      The keylog event is emitted when key material is generated or received by\na connection to this server (typically before handshake has completed, but not\nnecessarily). This keying material can be stored for debugging, as it allows\ncaptured TLS traffic to be decrypted. It may be emitted multiple times for\neach socket.

      \n

      A typical use case is to append received lines to a common text file, which\nis later used by software (such as Wireshark) to decrypt the traffic:

      \n
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });\n// ...\nserver.on('keylog', (line, tlsSocket) => {\n  if (tlsSocket.remoteAddress !== '...')\n    return; // Only log keys for a particular IP\n  logFile.write(line);\n});\n
      " + }, + { + "textRaw": "Event: `'newSession'`", + "type": "event", + "name": "newSession", + "meta": { + "added": [ + "v0.9.2" + ], + "changes": [ + { + "version": "v0.11.12", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7118", + "description": "The `callback` argument is now supported." + } + ] + }, + "params": [], + "desc": "

      The 'newSession' event is emitted upon creation of a new TLS session. This may\nbe used to store sessions in external storage. The data should be provided to\nthe 'resumeSession' callback.

      \n

      The listener callback is passed three arguments when called:

      \n
        \n
      • sessionId <Buffer> The TLS session identifier
      • \n
      • sessionData <Buffer> The TLS session data
      • \n
      • callback <Function> A callback function taking no arguments that must be\ninvoked in order for data to be sent or received over the secure connection.
      • \n
      \n

      Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

      " + }, + { + "textRaw": "Event: `'OCSPRequest'`", + "type": "event", + "name": "OCSPRequest", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'OCSPRequest' event is emitted when the client sends a certificate status\nrequest. The listener callback is passed three arguments when called:

      \n
        \n
      • certificate <Buffer> The server certificate
      • \n
      • issuer <Buffer> The issuer's certificate
      • \n
      • callback <Function> A callback function that must be invoked to provide\nthe results of the OCSP request.
      • \n
      \n

      The server's current certificate can be parsed to obtain the OCSP URL\nand certificate ID; after obtaining an OCSP response, callback(null, resp) is\nthen invoked, where resp is a Buffer instance containing the OCSP response.\nBoth certificate and issuer are Buffer DER-representations of the\nprimary and issuer's certificates. These can be used to obtain the OCSP\ncertificate ID and OCSP endpoint URL.

      \n

      Alternatively, callback(null, null) may be called, indicating that there was\nno OCSP response.

      \n

      Calling callback(err) will result in a socket.destroy(err) call.

      \n

      The typical flow of an OCSP Request is as follows:

      \n
        \n
      1. Client connects to the server and sends an 'OCSPRequest' (via the status\ninfo extension in ClientHello).
      2. \n
      3. Server receives the request and emits the 'OCSPRequest' event, calling the\nlistener if registered.
      4. \n
      5. Server extracts the OCSP URL from either the certificate or issuer and\nperforms an OCSP request to the CA.
      6. \n
      7. Server receives 'OCSPResponse' from the CA and sends it back to the client\nvia the callback argument
      8. \n
      9. Client validates the response and either destroys the socket or performs a\nhandshake.
      10. \n
      \n

      The issuer can be null if the certificate is either self-signed or the\nissuer is not in the root certificates list. (An issuer may be provided\nvia the ca option when establishing the TLS connection.)

      \n

      Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

      \n

      An npm module like asn1.js may be used to parse the certificates.

      " + }, + { + "textRaw": "Event: `'resumeSession'`", + "type": "event", + "name": "resumeSession", + "meta": { + "added": [ + "v0.9.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resumeSession' event is emitted when the client requests to resume a\nprevious TLS session. The listener callback is passed two arguments when\ncalled:

      \n
        \n
      • sessionId <Buffer> The TLS session identifier
      • \n
      • callback <Function> A callback function to be called when the prior session\nhas been recovered: callback([err[, sessionData]])\n\n
      • \n
      \n

      The event listener should perform a lookup in external storage for the\nsessionData saved by the 'newSession' event handler using the given\nsessionId. If found, call callback(null, sessionData) to resume the session.\nIf not found, the session cannot be resumed. callback() must be called\nwithout sessionData so that the handshake can continue and a new session can\nbe created. It is possible to call callback(err) to terminate the incoming\nconnection and destroy the socket.

      \n

      Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

      \n

      The following illustrates resuming a TLS session:

      \n
      const tlsSessionStore = {};\nserver.on('newSession', (id, data, cb) => {\n  tlsSessionStore[id.toString('hex')] = data;\n  cb();\n});\nserver.on('resumeSession', (id, cb) => {\n  cb(null, tlsSessionStore[id.toString('hex')] || null);\n});\n
      " + }, + { + "textRaw": "Event: `'secureConnection'`", + "type": "event", + "name": "secureConnection", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'secureConnection' event is emitted after the handshaking process for a\nnew connection has successfully completed. The listener callback is passed a\nsingle argument when called:

      \n\n

      The tlsSocket.authorized property is a boolean indicating whether the\nclient has been verified by one of the supplied Certificate Authorities for the\nserver. If tlsSocket.authorized is false, then socket.authorizationError\nis set to describe how authorization failed. Depending on the settings\nof the TLS server, unauthorized connections may still be accepted.

      \n

      The tlsSocket.alpnProtocol property is a string that contains the selected\nALPN protocol. When ALPN has no selected protocol, tlsSocket.alpnProtocol\nequals false.

      \n

      The tlsSocket.servername property is a string containing the server name\nrequested via SNI.

      " + }, + { + "textRaw": "Event: `'tlsClientError'`", + "type": "event", + "name": "tlsClientError", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'tlsClientError' event is emitted when an error occurs before a secure\nconnection is established. The listener callback is passed two arguments when\ncalled:

      \n
        \n
      • exception <Error> The Error object describing the error
      • \n
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance from which the\nerror originated.
      • \n
      " + } + ], + "methods": [ + { + "textRaw": "`server.addContext(hostname, context)`", + "type": "method", + "name": "addContext", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} A SNI host name or wildcard (e.g. `'*'`)", + "name": "hostname", + "type": "string", + "desc": "A SNI host name or wildcard (e.g. `'*'`)" + }, + { + "textRaw": "`context` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc).", + "name": "context", + "type": "Object", + "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." + } + ] + } + ], + "desc": "

      The server.addContext() method adds a secure context that will be used if\nthe client request's SNI name matches the supplied hostname (or wildcard).

      " + }, + { + "textRaw": "`server.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name, and port of the\nserver as reported by the operating system. See net.Server.address() for\nmore information.

      " + }, + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.Server}", + "name": "return", + "type": "tls.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function} A listener callback that will be registered to listen for the server instance's `'close'` event.", + "name": "callback", + "type": "Function", + "desc": "A listener callback that will be registered to listen for the server instance's `'close'` event." + } + ] + } + ], + "desc": "

      The server.close() method stops the server from accepting new connections.

      \n

      This function operates asynchronously. The 'close' event will be emitted\nwhen the server has no more open connections.

      " + }, + { + "textRaw": "`server.getTicketKeys()`", + "type": "method", + "name": "getTicketKeys", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A 48-byte buffer containing the session ticket keys.", + "name": "return", + "type": "Buffer", + "desc": "A 48-byte buffer containing the session ticket keys." + }, + "params": [] + } + ], + "desc": "

      Returns the session ticket keys.

      \n

      See Session Resumption for more information.

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts the server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.

      " + }, + { + "textRaw": "`server.setSecureContext(options)`", + "type": "method", + "name": "setSecureContext", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc).", + "name": "options", + "type": "Object", + "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." + } + ] + } + ], + "desc": "

      The server.setSecureContext() method replaces the secure context of an\nexisting server. Existing connections to the server are not interrupted.

      " + }, + { + "textRaw": "`server.setTicketKeys(keys)`", + "type": "method", + "name": "setTicketKeys", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`keys` {Buffer} A 48-byte buffer containing the session ticket keys.", + "name": "keys", + "type": "Buffer", + "desc": "A 48-byte buffer containing the session ticket keys." + } + ] + } + ], + "desc": "

      Sets the session ticket keys.

      \n

      Changes to the ticket keys are effective only for future server connections.\nExisting or currently pending server connections will use the previous keys.

      \n

      See Session Resumption for more information.

      " + } + ], + "properties": [ + { + "textRaw": "`connections` {number}", + "type": "number", + "name": "connections", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.9.7" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", + "desc": "

      Returns the current number of concurrent connections on the server.

      " + } + ] + }, + { + "textRaw": "Class: `tls.TLSSocket`", + "type": "class", + "name": "tls.TLSSocket", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "\n

      Performs transparent encryption of written data and all required TLS\nnegotiation.

      \n

      Instances of tls.TLSSocket implement the duplex Stream interface.

      \n

      Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate() will only return data while the\nconnection is open.

      ", + "events": [ + { + "textRaw": "Event: `'keylog'`", + "type": "event", + "name": "keylog", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`line` {Buffer} Line of ASCII text, in NSS `SSLKEYLOGFILE` format.", + "name": "line", + "type": "Buffer", + "desc": "Line of ASCII text, in NSS `SSLKEYLOGFILE` format." + } + ], + "desc": "

      The keylog event is emitted on a tls.TLSSocket when key material\nis generated or received by the socket. This keying material can be stored\nfor debugging, as it allows captured TLS traffic to be decrypted. It may\nbe emitted multiple times, before or after the handshake completes.

      \n

      A typical use case is to append received lines to a common text file, which\nis later used by software (such as Wireshark) to decrypt the traffic:

      \n
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });\n// ...\ntlsSocket.on('keylog', (line) => logFile.write(line));\n
      " + }, + { + "textRaw": "Event: `'OCSPResponse'`", + "type": "event", + "name": "OCSPResponse", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'OCSPResponse' event is emitted if the requestOCSP option was set\nwhen the tls.TLSSocket was created and an OCSP response has been received.\nThe listener callback is passed a single argument when called:

      \n
        \n
      • response <Buffer> The server's OCSP response
      • \n
      \n

      Typically, the response is a digitally signed object from the server's CA that\ncontains information about server's certificate revocation status.

      " + }, + { + "textRaw": "Event: `'secureConnect'`", + "type": "event", + "name": "secureConnect", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'secureConnect' event is emitted after the handshaking process for a new\nconnection has successfully completed. The listener callback will be called\nregardless of whether or not the server's certificate has been authorized. It\nis the client's responsibility to check the tlsSocket.authorized property to\ndetermine if the server certificate was signed by one of the specified CAs. If\ntlsSocket.authorized === false, then the error can be found by examining the\ntlsSocket.authorizationError property. If ALPN was used, the\ntlsSocket.alpnProtocol property can be checked to determine the negotiated\nprotocol.

      " + }, + { + "textRaw": "Event: `'session'`", + "type": "event", + "name": "session", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`session` {Buffer}", + "name": "session", + "type": "Buffer" + } + ], + "desc": "

      The 'session' event is emitted on a client tls.TLSSocket when a new session\nor TLS ticket is available. This may or may not be before the handshake is\ncomplete, depending on the TLS protocol version that was negotiated. The event\nis not emitted on the server, or if a new session was not created, for example,\nwhen the connection was resumed. For some TLS protocol versions the event may be\nemitted multiple times, in which case all the sessions can be used for\nresumption.

      \n

      On the client, the session can be provided to the session option of\ntls.connect() to resume the connection.

      \n

      See Session Resumption for more information.

      \n

      For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once\nthe handshake is complete. For TLSv1.3, only ticket-based resumption is allowed\nby the protocol, multiple tickets are sent, and the tickets aren't sent until\nafter the handshake completes. So it is necessary to wait for the\n'session' event to get a resumable session. Applications\nshould use the 'session' event instead of getSession() to ensure\nthey will work for all TLS versions. Applications that only expect to\nget or use one session should listen for this event only once:

      \n
      tlsSocket.once('session', (session) => {\n  // The session can be used immediately or later.\n  tls.connect({\n    session: session,\n    // Other connect options...\n  });\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`tlsSocket.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name, and port of the\nunderlying socket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      " + }, + { + "textRaw": "`tlsSocket.disableRenegotiation()`", + "type": "method", + "name": "disableRenegotiation", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disables TLS renegotiation for this TLSSocket instance. Once called, attempts\nto renegotiate will trigger an 'error' event on the TLSSocket.

      " + }, + { + "textRaw": "`tlsSocket.enableTrace()`", + "type": "method", + "name": "enableTrace", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      When enabled, TLS packet trace information is written to stderr. This can be\nused to debug TLS connection problems.

      \n

      Note: The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's\nSSL_trace() function, the format is undocumented, can change without notice,\nand should not be relied on.

      " + }, + { + "textRaw": "`tlsSocket.getCertificate()`", + "type": "method", + "name": "getCertificate", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object representing the local certificate. The returned object has\nsome properties corresponding to the fields of the certificate.

      \n

      See tls.TLSSocket.getPeerCertificate() for an example of the certificate\nstructure.

      \n

      If there is no local certificate, an empty object will be returned. If the\nsocket has been destroyed, null will be returned.

      " + }, + { + "textRaw": "`tlsSocket.getCipher()`", + "type": "method", + "name": "getCipher", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26625", + "description": "Return the minimum cipher version, instead of a fixed string (`'TLSv1/SSLv3'`)." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30637", + "description": "Return the IETF cipher name as `standardName`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`name` {string} OpenSSL name for the cipher suite.", + "name": "name", + "type": "string", + "desc": "OpenSSL name for the cipher suite." + }, + { + "textRaw": "`standardName` {string} IETF name for the cipher suite.", + "name": "standardName", + "type": "string", + "desc": "IETF name for the cipher suite." + }, + { + "textRaw": "`version` {string} The minimum TLS protocol version supported by this cipher suite.", + "name": "version", + "type": "string", + "desc": "The minimum TLS protocol version supported by this cipher suite." + } + ] + }, + "params": [] + } + ], + "desc": "

      Returns an object containing information on the negotiated cipher suite.

      \n

      For example:

      \n
      {\n    \"name\": \"AES128-SHA256\",\n    \"standardName\": \"TLS_RSA_WITH_AES_128_CBC_SHA256\",\n    \"version\": \"TLSv1.2\"\n}\n
      \n

      See\nSSL_CIPHER_get_name\nfor more information.

      " + }, + { + "textRaw": "`tlsSocket.getEphemeralKeyInfo()`", + "type": "method", + "name": "getEphemeralKeyInfo", + "meta": { + "added": [ + "v5.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object representing the type, name, and size of parameter of\nan ephemeral key exchange in perfect forward secrecy on a client\nconnection. It returns an empty object when the key exchange is not\nephemeral. As this is only supported on a client socket; null is returned\nif called on a server socket. The supported types are 'DH' and 'ECDH'. The\nname property is available only when type is 'ECDH'.

      \n

      For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

      " + }, + { + "textRaw": "`tlsSocket.getFinished()`", + "type": "method", + "name": "getFinished", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|undefined} The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet.", + "name": "return", + "type": "Buffer|undefined", + "desc": "The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet." + }, + "params": [] + } + ], + "desc": "

      As the Finished messages are message digests of the complete handshake\n(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can\nbe used for external authentication procedures when the authentication\nprovided by SSL/TLS is not desired or is not enough.

      \n

      Corresponds to the SSL_get_finished routine in OpenSSL and may be used\nto implement the tls-unique channel binding from RFC 5929.

      " + }, + { + "textRaw": "`tlsSocket.getPeerCertificate([detailed])`", + "type": "method", + "name": "getPeerCertificate", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} A certificate object.", + "name": "return", + "type": "Object", + "desc": "A certificate object." + }, + "params": [ + { + "textRaw": "`detailed` {boolean} Include the full certificate chain if `true`, otherwise include just the peer's certificate.", + "name": "detailed", + "type": "boolean", + "desc": "Include the full certificate chain if `true`, otherwise include just the peer's certificate." + } + ] + } + ], + "desc": "

      Returns an object representing the peer's certificate. If the peer does not\nprovide a certificate, an empty object will be returned. If the socket has been\ndestroyed, null will be returned.

      \n

      If the full certificate chain was requested, each certificate will include an\nissuerCertificate property containing an object representing its issuer's\ncertificate.

      ", + "modules": [ + { + "textRaw": "Certificate object", + "name": "certificate_object", + "meta": { + "changes": [ + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24358", + "description": "Support Elliptic Curve public key info." + } + ] + }, + "desc": "

      A certificate object has properties corresponding to the fields of the\ncertificate.

      \n
        \n
      • raw <Buffer> The DER encoded X.509 certificate data.
      • \n
      • subject <Object> The certificate subject, described in terms of\n Country (C:), StateOrProvince (ST), Locality (L), Organization (O),\nOrganizationalUnit (OU), and CommonName (CN). The CommonName is typically\na DNS name with TLS certificates. Example:\n{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.
      • \n
      • issuer <Object> The certificate issuer, described in the same terms as the\n subject.
      • \n
      • valid_from <string> The date-time the certificate is valid from.
      • \n
      • valid_to <string> The date-time the certificate is valid to.
      • \n
      • serialNumber <string> The certificate serial number, as a hex string.\n Example: 'B9B0D332A1AA5635'.
      • \n
      • fingerprint <string> The SHA-1 digest of the DER encoded certificate. It is\nreturned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
      • \n
      • fingerprint256 <string> The SHA-256 digest of the DER encoded certificate.\n It is returned as a : separated hexadecimal string. Example:\n'2A:7A:C2:DD:...'.
      • \n
      • ext_key_usage <Array> (Optional) The extended key usage, a set of OIDs.
      • \n
      • subjectaltname <string> (Optional) A string containing concatenated names\nfor the subject, an alternative to the subject names.
      • \n
      • infoAccess <Array> (Optional) An array describing the AuthorityInfoAccess,\n used with OCSP.
      • \n
      • issuerCertificate <Object> (Optional) The issuer certificate object. For\n self-signed certificates, this may be a circular reference.
      • \n
      \n

      The certificate may contain information about the public key, depending on\nthe key type.

      \n

      For RSA keys, the following properties may be defined:

      \n
        \n
      • bits <number> The RSA bit size. Example: 1024.
      • \n
      • exponent <string> The RSA exponent, as a string in hexadecimal number\nnotation. Example: '0x010001'.
      • \n
      • modulus <string> The RSA modulus, as a hexadecimal string. Example:\n 'B56CE45CB7...'.
      • \n
      • pubkey <Buffer> The public key.
      • \n
      \n

      For EC keys, the following properties may be defined:

      \n
        \n
      • pubkey <Buffer> The public key.
      • \n
      • bits <number> The key size in bits. Example: 256.
      • \n
      • asn1Curve <string> (Optional) The ASN.1 name of the OID of the elliptic\ncurve. Well-known curves are identified by an OID. While it is unusual, it is\npossible that the curve is identified by its mathematical properties, in which\ncase it will not have an OID. Example: 'prime256v1'.
      • \n
      • nistCurve <string> (Optional) The NIST name for the elliptic curve, if it\nhas one (not all well-known curves have been assigned names by NIST). Example:\n'P-256'.
      • \n
      \n

      Example certificate:

      \n\n
      { subject:\n   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],\n     CN: '*.nodejs.org' },\n  issuer:\n   { C: 'GB',\n     ST: 'Greater Manchester',\n     L: 'Salford',\n     O: 'COMODO CA Limited',\n     CN: 'COMODO RSA Domain Validation Secure Server CA' },\n  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',\n  infoAccess:\n   { 'CA Issuers - URI':\n      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],\n     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },\n  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',\n  exponent: '0x10001',\n  pubkey: <Buffer ... >,\n  valid_from: 'Aug 14 00:00:00 2017 GMT',\n  valid_to: 'Nov 20 23:59:59 2019 GMT',\n  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',\n  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',\n  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],\n  serialNumber: '66593D57F20CBC573E433381B5FEC280',\n  raw: <Buffer ... > }\n
      ", + "type": "module", + "displayName": "Certificate object" + } + ] + }, + { + "textRaw": "`tlsSocket.getPeerFinished()`", + "type": "method", + "name": "getPeerFinished", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|undefined} The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so far.", + "name": "return", + "type": "Buffer|undefined", + "desc": "The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so far." + }, + "params": [] + } + ], + "desc": "

      As the Finished messages are message digests of the complete handshake\n(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can\nbe used for external authentication procedures when the authentication\nprovided by SSL/TLS is not desired or is not enough.

      \n

      Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used\nto implement the tls-unique channel binding from RFC 5929.

      " + }, + { + "textRaw": "`tlsSocket.getProtocol()`", + "type": "method", + "name": "getProtocol", + "meta": { + "added": [ + "v5.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|null}", + "name": "return", + "type": "string|null" + }, + "params": [] + } + ], + "desc": "

      Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. The value 'unknown' will be returned for connected\nsockets that have not completed the handshaking process. The value null will\nbe returned for server sockets or disconnected client sockets.

      \n

      Protocol versions are:

      \n
        \n
      • 'SSLv3'
      • \n
      • 'TLSv1'
      • \n
      • 'TLSv1.1'
      • \n
      • 'TLSv1.2'
      • \n
      • 'TLSv1.3'
      • \n
      \n

      See the OpenSSL SSL_get_version documentation for more information.

      " + }, + { + "textRaw": "`tlsSocket.getSession()`", + "type": "method", + "name": "getSession", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "{Buffer}", + "type": "Buffer" + } + ] + } + ], + "desc": "

      Returns the TLS session data or undefined if no session was\nnegotiated. On the client, the data can be provided to the session option of\ntls.connect() to resume the connection. On the server, it may be useful\nfor debugging.

      \n

      See Session Resumption for more information.

      \n

      Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications\nmust use the 'session' event (it also works for TLSv1.2 and below).

      " + }, + { + "textRaw": "`tlsSocket.getSharedSigalgs()`", + "type": "method", + "name": "getSharedSigalgs", + "meta": { + "added": [ + "v12.11.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Array} List of signature algorithms shared between the server and the client in the order of decreasing preference.", + "name": "return", + "type": "Array", + "desc": "List of signature algorithms shared between the server and the client in the order of decreasing preference." + }, + "params": [] + } + ], + "desc": "

      See\nSSL_get_shared_sigalgs\nfor more information.

      " + }, + { + "textRaw": "`tlsSocket.exportKeyingMaterial(length, label[, context])`", + "type": "method", + "name": "exportKeyingMaterial", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} requested bytes of the keying material", + "name": "return", + "type": "Buffer", + "desc": "requested bytes of the keying material" + }, + "params": [ + { + "textRaw": "`length` {number} number of bytes to retrieve from keying material", + "name": "length", + "type": "number", + "desc": "number of bytes to retrieve from keying material" + }, + { + "textRaw": "`label` {string} an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).", + "name": "label", + "type": "string", + "desc": "an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels)." + }, + { + "textRaw": "`context` {Buffer} Optionally provide a context.", + "name": "context", + "type": "Buffer", + "desc": "Optionally provide a context." + } + ] + } + ], + "desc": "

      Keying material is used for validations to prevent different kind of attacks in\nnetwork protocols, for example in the specifications of IEEE 802.1X.

      \n

      Example

      \n
      const keyingMaterial = tlsSocket.exportKeyingMaterial(\n  128,\n  'client finished');\n\n/**\n Example return value of keyingMaterial:\n <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9\n    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91\n    74 ef 2c ... 78 more bytes>\n*/\n
      \n

      See the OpenSSL SSL_export_keying_material documentation for more\ninformation.

      " + }, + { + "textRaw": "`tlsSocket.getTLSTicket()`", + "type": "method", + "name": "getTLSTicket", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "{Buffer}", + "type": "Buffer" + } + ] + } + ], + "desc": "

      For a client, returns the TLS session ticket if one is available, or\nundefined. For a server, always returns undefined.

      \n

      It may be useful for debugging.

      \n

      See Session Resumption for more information.

      " + }, + { + "textRaw": "`tlsSocket.isSessionReused()`", + "type": "method", + "name": "isSessionReused", + "meta": { + "added": [ + "v0.5.6" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if the session was reused, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if the session was reused, `false` otherwise." + }, + "params": [] + } + ], + "desc": "

      See Session Resumption for more information.

      " + }, + { + "textRaw": "`tlsSocket.renegotiate(options, callback)`", + "type": "method", + "name": "renegotiate", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if renegotiation was initiated, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if renegotiation was initiated, `false` otherwise." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "default": "`true`", + "desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code." + }, + { + "textRaw": "`requestCert`", + "name": "requestCert" + } + ] + }, + { + "textRaw": "`callback` {Function} If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.", + "name": "callback", + "type": "Function", + "desc": "If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all." + } + ] + } + ], + "desc": "

      The tlsSocket.renegotiate() method initiates a TLS renegotiation process.\nUpon completion, the callback function will be passed a single argument\nthat is either an Error (if the request failed) or null.

      \n

      This method can be used to request a peer's certificate after the secure\nconnection has been established.

      \n

      When running as the server, the socket will be destroyed with an error after\nhandshakeTimeout timeout.

      \n

      For TLSv1.3, renegotiation cannot be initiated, it is not supported by the\nprotocol.

      " + }, + { + "textRaw": "`tlsSocket.setMaxSendFragment(size)`", + "type": "method", + "name": "setMaxSendFragment", + "meta": { + "added": [ + "v0.11.11" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`size` {number} The maximum TLS fragment size. The maximum value is `16384`. **Default:** `16384`.", + "name": "size", + "type": "number", + "default": "`16384`", + "desc": "The maximum TLS fragment size. The maximum value is `16384`." + } + ] + } + ], + "desc": "

      The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size.\nReturns true if setting the limit succeeded; false otherwise.

      \n

      Smaller fragment sizes decrease the buffering latency on the client: larger\nfragments are buffered by the TLS layer until the entire fragment is received\nand its integrity is verified; large fragments can span multiple roundtrips\nand their processing can be delayed due to packet loss or reordering. However,\nsmaller fragments add extra TLS framing bytes and CPU overhead, which may\ndecrease overall server throughput.

      " + } + ], + "properties": [ + { + "textRaw": "`tlsSocket.authorizationError`", + "name": "authorizationError", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the reason why the peer's certificate was not been verified. This\nproperty is set only when tlsSocket.authorized === false.

      " + }, + { + "textRaw": "`authorized` Returns: {boolean}", + "type": "boolean", + "name": "return", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns true if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket instance, otherwise false.

      " + }, + { + "textRaw": "`tlsSocket.encrypted`", + "name": "encrypted", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Always returns true. This may be used to distinguish TLS sockets from regular\nnet.Socket instances.

      " + }, + { + "textRaw": "`localAddress` {string}", + "type": "string", + "name": "localAddress", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the string representation of the local IP address.

      " + }, + { + "textRaw": "`localPort` {number}", + "type": "number", + "name": "localPort", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the numeric representation of the local port.

      " + }, + { + "textRaw": "`remoteAddress` {string}", + "type": "string", + "name": "remoteAddress", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.

      " + }, + { + "textRaw": "`remoteFamily` {string}", + "type": "string", + "name": "remoteFamily", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

      " + }, + { + "textRaw": "`remotePort` {number}", + "type": "number", + "name": "remotePort", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the numeric representation of the remote port. For example, 443.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`socket` {net.Socket|stream.Duplex} On the server side, any `Duplex` stream. On the client side, any instance of [`net.Socket`][] (for generic `Duplex` stream support on the client side, [`tls.connect()`][] must be used).", + "name": "socket", + "type": "net.Socket|stream.Duplex", + "desc": "On the server side, any `Duplex` stream. On the client side, any instance of [`net.Socket`][] (for generic `Duplex` stream support on the client side, [`tls.connect()`][] must be used)." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`enableTrace`: See [`tls.createServer()`][]", + "name": "enableTrace", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`isServer`: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If `true` the TLS socket will be instantiated as a server. **Default:** `false`.", + "name": "isServer", + "default": "`false`", + "desc": "The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If `true` the TLS socket will be instantiated as a server." + }, + { + "textRaw": "`server` {net.Server} A [`net.Server`][] instance.", + "name": "server", + "type": "net.Server", + "desc": "A [`net.Server`][] instance." + }, + { + "textRaw": "`requestCert`: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may set `requestCert` to true to request a client certificate.", + "name": "requestCert", + "desc": "Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may set `requestCert` to true to request a client certificate." + }, + { + "textRaw": "`rejectUnauthorized`: See [`tls.createServer()`][]", + "name": "rejectUnauthorized", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`ALPNProtocols`: See [`tls.createServer()`][]", + "name": "ALPNProtocols", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`SNICallback`: See [`tls.createServer()`][]", + "name": "SNICallback", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`session` {Buffer} A `Buffer` instance containing a TLS session.", + "name": "session", + "type": "Buffer", + "desc": "A `Buffer` instance containing a TLS session." + }, + { + "textRaw": "`requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication", + "name": "requestOCSP", + "type": "boolean", + "desc": "If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication" + }, + { + "textRaw": "`secureContext`: TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`.", + "name": "secureContext", + "desc": "TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`." + }, + { + "textRaw": "...: [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing. Otherwise, they are ignored.", + "name": "...", + "desc": "[`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing. Otherwise, they are ignored." + } + ] + } + ], + "desc": "

      Construct a new tls.TLSSocket object from an existing TCP socket.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`tls.checkServerIdentity(hostname, cert)`", + "type": "method", + "name": "checkServerIdentity", + "meta": { + "added": [ + "v0.8.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Error|undefined}", + "name": "return", + "type": "Error|undefined" + }, + "params": [ + { + "textRaw": "`hostname` {string} The host name or IP address to verify the certificate against.", + "name": "hostname", + "type": "string", + "desc": "The host name or IP address to verify the certificate against." + }, + { + "textRaw": "`cert` {Object} A [certificate object][] representing the peer's certificate.", + "name": "cert", + "type": "Object", + "desc": "A [certificate object][] representing the peer's certificate." + } + ] + } + ], + "desc": "

      Verifies the certificate cert is issued to hostname.

      \n

      Returns <Error> object, populating it with reason, host, and cert on\nfailure. On success, returns <undefined>.

      \n

      This function can be overwritten by providing alternative function as part of\nthe options.checkServerIdentity option passed to tls.connect(). The\noverwriting function can call tls.checkServerIdentity() of course, to augment\nthe checks done with additional verification.

      \n

      This function is only called if the certificate passed all other checks, such as\nbeing issued by trusted CA (options.ca).

      " + }, + { + "textRaw": "`tls.connect(options[, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/23188", + "description": "The `pskCallback` option is now supported." + }, + { + "version": "v12.9.0", + "pr-url": "https://github.com/nodejs/node/pull/27836", + "description": "Support the `allowHalfOpen` option." + }, + { + "version": "v12.4.0", + "pr-url": "https://github.com/nodejs/node/pull/27816", + "description": "The `hints` option is now supported." + }, + { + "version": "v12.2.0", + "pr-url": "https://github.com/nodejs/node/pull/27497", + "description": "The `enableTrace` option is now supported." + }, + { + "version": "v11.8.0", + "pr-url": "https://github.com/nodejs/node/pull/25517", + "description": "The `timeout` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12839", + "description": "The `lookup` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11984", + "description": "The `ALPNProtocols` option can be a `TypedArray` or `DataView` now." + }, + { + "version": "v5.3.0, v4.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4246", + "description": "The `secureContext` option is supported now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2564", + "description": "ALPN options are supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.TLSSocket}", + "name": "return", + "type": "tls.TLSSocket" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`enableTrace`: See [`tls.createServer()`][]", + "name": "enableTrace", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`host` {string} Host the client should connect to. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "Host the client should connect to." + }, + { + "textRaw": "`port` {number} Port the client should connect to.", + "name": "port", + "type": "number", + "desc": "Port the client should connect to." + }, + { + "textRaw": "`path` {string} Creates Unix socket connection to path. If this option is specified, `host` and `port` are ignored.", + "name": "path", + "type": "string", + "desc": "Creates Unix socket connection to path. If this option is specified, `host` and `port` are ignored." + }, + { + "textRaw": "`socket` {stream.Duplex} Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Connection/disconnection/destruction of `socket` is the user's responsibility; calling `tls.connect()` will not cause `net.connect()` to be called.", + "name": "socket", + "type": "stream.Duplex", + "desc": "Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Connection/disconnection/destruction of `socket` is the user's responsibility; calling `tls.connect()` will not cause `net.connect()` to be called." + }, + { + "textRaw": "`allowHalfOpen` {boolean} If the `socket` option is missing, indicates whether or not to allow the internally created socket to be half-open, otherwise the option is ignored. See the `allowHalfOpen` option of [`net.Socket`][] for details. **Default:** `false`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`false`", + "desc": "If the `socket` option is missing, indicates whether or not to allow the internally created socket to be half-open, otherwise the option is ignored. See the `allowHalfOpen` option of [`net.Socket`][] for details." + }, + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "default": "`true`", + "desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code." + }, + { + "textRaw": "`pskCallback` {Function}", + "name": "pskCallback", + "type": "Function", + "options": [ + { + "textRaw": "hint: {string} optional message sent from the server to help client decide which identity to use during negotiation. Always `null` if TLS 1.3 is used.", + "name": "hint", + "type": "string", + "desc": "optional message sent from the server to help client decide which identity to use during negotiation. Always `null` if TLS 1.3 is used." + }, + { + "textRaw": "Returns: {Object} in the form `{ psk: , identity: }` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding. When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity `hint` provided by the server or `null` in case of TLS 1.3 where `hint` was removed. It will be necessary to provide a custom `tls.checkServerIdentity()` for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][].", + "name": "return", + "type": "Object", + "desc": "in the form `{ psk: , identity: }` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding. When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity `hint` provided by the server or `null` in case of TLS 1.3 where `hint` was removed. It will be necessary to provide a custom `tls.checkServerIdentity()` for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][]." + } + ] + }, + { + "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `'\\x08http/1.1\\x08http/1.0'`, where the `len` byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher preference than those later.", + "name": "ALPNProtocols", + "type": "string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView", + "desc": "An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `'\\x08http/1.1\\x08http/1.0'`, where the `len` byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher preference than those later." + }, + { + "textRaw": "`servername`: {string} Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the `SNICallback` option to [`tls.createServer()`][].", + "name": "servername", + "type": "string", + "desc": "Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the `SNICallback` option to [`tls.createServer()`][]." + }, + { + "textRaw": "`checkServerIdentity(servername, cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's host name (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified.", + "name": "checkServerIdentity(servername,", + "desc": "cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's host name (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified." + }, + { + "textRaw": "`session` {Buffer} A `Buffer` instance, containing TLS session.", + "name": "session", + "type": "Buffer", + "desc": "A `Buffer` instance, containing TLS session." + }, + { + "textRaw": "`minDHSize` {number} Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. **Default:** `1024`.", + "name": "minDHSize", + "type": "number", + "default": "`1024`", + "desc": "Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown." + }, + { + "textRaw": "`secureContext`: TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`.", + "name": "secureContext", + "desc": "TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`." + }, + { + "textRaw": "...: [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored.", + "name": "...", + "desc": "[`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored." + }, + { + "textRaw": "...: Any [`socket.connect()`][] option not already listed.", + "name": "...", + "desc": "Any [`socket.connect()`][] option not already listed." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      The callback function, if specified, will be added as a listener for the\n'secureConnect' event.

      \n

      tls.connect() returns a tls.TLSSocket object.

      \n

      Unlike the https API, tls.connect() does not enable the\nSNI (Server Name Indication) extension by default, which may cause some\nservers to return an incorrect certificate or reject the connection\naltogether. To enable SNI, set the servername option in addition\nto host.

      \n

      The following illustrates a client for the echo server example from\ntls.createServer():

      \n
      // Assumes an echo server that is listening on port 8000.\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // Necessary only if the server requires client certificate authentication.\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // Necessary only if the server uses a self-signed certificate.\n  ca: [ fs.readFileSync('server-cert.pem') ],\n\n  // Necessary only if the server's cert isn't for \"localhost\".\n  checkServerIdentity: () => { return null; },\n};\n\nconst socket = tls.connect(8000, options, () => {\n  console.log('client connected',\n              socket.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(socket);\n  process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', (data) => {\n  console.log(data);\n});\nsocket.on('end', () => {\n  console.log('server ends connection');\n});\n
      " + }, + { + "textRaw": "`tls.connect(path[, options][, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.TLSSocket}", + "name": "return", + "type": "tls.TLSSocket" + }, + "params": [ + { + "textRaw": "`path` {string} Default value for `options.path`.", + "name": "path", + "type": "string", + "desc": "Default value for `options.path`." + }, + { + "textRaw": "`options` {Object} See [`tls.connect()`][].", + "name": "options", + "type": "Object", + "desc": "See [`tls.connect()`][]." + }, + { + "textRaw": "`callback` {Function} See [`tls.connect()`][].", + "name": "callback", + "type": "Function", + "desc": "See [`tls.connect()`][]." + } + ] + } + ], + "desc": "

      Same as tls.connect() except that path can be provided\nas an argument instead of an option.

      \n

      A path option, if specified, will take precedence over the path argument.

      " + }, + { + "textRaw": "`tls.connect(port[, host][, options][, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.TLSSocket}", + "name": "return", + "type": "tls.TLSSocket" + }, + "params": [ + { + "textRaw": "`port` {number} Default value for `options.port`.", + "name": "port", + "type": "number", + "desc": "Default value for `options.port`." + }, + { + "textRaw": "`host` {string} Default value for `options.host`.", + "name": "host", + "type": "string", + "desc": "Default value for `options.host`." + }, + { + "textRaw": "`options` {Object} See [`tls.connect()`][].", + "name": "options", + "type": "Object", + "desc": "See [`tls.connect()`][]." + }, + { + "textRaw": "`callback` {Function} See [`tls.connect()`][].", + "name": "callback", + "type": "Function", + "desc": "See [`tls.connect()`][]." + } + ] + } + ], + "desc": "

      Same as tls.connect() except that port and host can be provided\nas arguments instead of options.

      \n

      A port or host option, if specified, will take precedence over any port or host\nargument.

      " + }, + { + "textRaw": "`tls.createSecureContext([options])`", + "type": "method", + "name": "createSecureContext", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/28973", + "description": "Added `privateKeyIdentifier` and `privateKeyEngine` options to get private key from an OpenSSL engine." + }, + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29598", + "description": "Added `sigalgs` option to override supported signature algorithms." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26209", + "description": "TLSv1.3 support added." + }, + { + "version": "v11.5.0", + "pr-url": "https://github.com/nodejs/node/pull/24733", + "description": "The `ca:` option now supports `BEGIN TRUSTED CERTIFICATE`." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24405", + "description": "The `minVersion` and `maxVersion` can be used to restrict the allowed TLS protocol versions." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19794", + "description": "The `ecdhCurve` cannot be set to `false` anymore due to a change in OpenSSL." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15206", + "description": "The `ecdhCurve` option can now be multiple `':'` separated curve names or `'auto'`." + }, + { + "version": "v7.3.0", + "pr-url": "https://github.com/nodejs/node/pull/10294", + "description": "If the `key` option is an array, individual entries do not need a `passphrase` property anymore. `Array` entries can also just be `string`s or `Buffer`s now." + }, + { + "version": "v5.2.0", + "pr-url": "https://github.com/nodejs/node/pull/4099", + "description": "The `ca` option can now be a single string containing multiple CA certificates." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of strings and/or `Buffer`s. Any string or `Buffer` can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are \"TRUSTED CERTIFICATE\", \"X509 CERTIFICATE\", and \"CERTIFICATE\". See also [`tls.rootCertificates`][].", + "name": "ca", + "type": "string|string[]|Buffer|Buffer[]", + "desc": "Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of strings and/or `Buffer`s. Any string or `Buffer` can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are \"TRUSTED CERTIFICATE\", \"X509 CERTIFICATE\", and \"CERTIFICATE\". See also [`tls.rootCertificates`][]." + }, + { + "textRaw": "`cert` {string|string[]|Buffer|Buffer[]} Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.", + "name": "cert", + "type": "string|string[]|Buffer|Buffer[]", + "desc": "Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail." + }, + { + "textRaw": "`sigalgs` {string} Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) for more info.", + "name": "sigalgs", + "type": "string", + "desc": "Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) for more info." + }, + { + "textRaw": "`ciphers` {string} Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted ciphers can be obtained via [`tls.getCiphers()`][]. Cipher names must be uppercased in order for OpenSSL to accept them.", + "name": "ciphers", + "type": "string", + "desc": "Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted ciphers can be obtained via [`tls.getCiphers()`][]. Cipher names must be uppercased in order for OpenSSL to accept them." + }, + { + "textRaw": "`clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate.", + "name": "clientCertEngine", + "type": "string", + "desc": "Name of an OpenSSL engine which can provide the client certificate." + }, + { + "textRaw": "`crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate Revocation Lists).", + "name": "crl", + "type": "string|string[]|Buffer|Buffer[]", + "desc": "PEM formatted CRLs (Certificate Revocation Lists)." + }, + { + "textRaw": "`dhparam` {string|Buffer} Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.", + "name": "dhparam", + "type": "string|Buffer", + "desc": "Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available." + }, + { + "textRaw": "`ecdhCurve` {string} A string describing a named curve or a colon separated list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for ECDH key agreement. Set to `auto` to select the curve automatically. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. **Default:** [`tls.DEFAULT_ECDH_CURVE`][].", + "name": "ecdhCurve", + "type": "string", + "default": "[`tls.DEFAULT_ECDH_CURVE`][]", + "desc": "A string describing a named curve or a colon separated list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for ECDH key agreement. Set to `auto` to select the curve automatically. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve." + }, + { + "textRaw": "`honorCipherOrder` {boolean} Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information.", + "name": "honorCipherOrder", + "type": "boolean", + "desc": "Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information." + }, + { + "textRaw": "`key` {string|string[]|Buffer|Buffer[]|Object[]} Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.", + "name": "key", + "type": "string|string[]|Buffer|Buffer[]|Object[]", + "desc": "Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." + }, + { + "textRaw": "`privateKeyEngine` {string} Name of an OpenSSL engine to get private key from. Should be used together with `privateKeyIdentifier`.", + "name": "privateKeyEngine", + "type": "string", + "desc": "Name of an OpenSSL engine to get private key from. Should be used together with `privateKeyIdentifier`." + }, + { + "textRaw": "`privateKeyIdentifier` {string} Identifier of a private key managed by an OpenSSL engine. Should be used together with `privateKeyEngine`. Should not be set together with `key`, because both options define a private key in different ways.", + "name": "privateKeyIdentifier", + "type": "string", + "desc": "Identifier of a private key managed by an OpenSSL engine. Should be used together with `privateKeyEngine`. Should not be set together with `key`, because both options define a private key in different ways." + }, + { + "textRaw": "`maxVersion` {string} Optionally set the maximum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other. **Default:** [`tls.DEFAULT_MAX_VERSION`][].", + "name": "maxVersion", + "type": "string", + "default": "[`tls.DEFAULT_MAX_VERSION`][]", + "desc": "Optionally set the maximum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other." + }, + { + "textRaw": "`minVersion` {string} Optionally set the minimum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability. **Default:** [`tls.DEFAULT_MIN_VERSION`][].", + "name": "minVersion", + "type": "string", + "default": "[`tls.DEFAULT_MIN_VERSION`][]", + "desc": "Optionally set the minimum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability." + }, + { + "textRaw": "`passphrase` {string} Shared passphrase used for a single private key and/or a PFX.", + "name": "passphrase", + "type": "string", + "desc": "Shared passphrase used for a single private key and/or a PFX." + }, + { + "textRaw": "`pfx` {string|string[]|Buffer|Buffer[]|Object[]} PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.", + "name": "pfx", + "type": "string|string[]|Buffer|Buffer[]|Object[]", + "desc": "PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." + }, + { + "textRaw": "`secureOptions` {number} Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][].", + "name": "secureOptions", + "type": "number", + "desc": "Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][]." + }, + { + "textRaw": "`secureProtocol` {string} Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. **Default:** none, see `minVersion`.", + "name": "secureProtocol", + "type": "string", + "default": "none, see `minVersion`", + "desc": "Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability." + }, + { + "textRaw": "`sessionIdContext` {string} Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.", + "name": "sessionIdContext", + "type": "string", + "desc": "Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients." + }, + { + "textRaw": "`ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information.", + "name": "ticketKeys", + "type": "Buffer", + "desc": "48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information." + }, + { + "textRaw": "`sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`.", + "name": "sessionTimeout", + "type": "number", + "default": "`300`", + "desc": "The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information." + } + ] + } + ] + } + ], + "desc": "

      tls.createServer() sets the default value of the honorCipherOrder option\nto true, other APIs that create secure contexts leave it unset.

      \n

      tls.createServer() uses a 128 bit truncated SHA1 hash value generated\nfrom process.argv as the default value of the sessionIdContext option, other\nAPIs that create secure contexts have no default value.

      \n

      The tls.createSecureContext() method creates a SecureContext object. It is\nusable as an argument to several tls APIs, such as tls.createServer()\nand server.addContext(), but has no public methods.

      \n

      A key is required for ciphers that use certificates. Either key or\npfx can be used to provide it.

      \n

      If the ca option is not given, then Node.js will default to using\nMozilla's publicly trusted list of CAs.

      " + }, + { + "textRaw": "`tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])`", + "type": "method", + "name": "createSecurePair", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [ + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2564", + "description": "ALPN options are supported now." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`context` {Object} A secure context object as returned by `tls.createSecureContext()`", + "name": "context", + "type": "Object", + "desc": "A secure context object as returned by `tls.createSecureContext()`" + }, + { + "textRaw": "`isServer` {boolean} `true` to specify that this TLS connection should be opened as a server.", + "name": "isServer", + "type": "boolean", + "desc": "`true` to specify that this TLS connection should be opened as a server." + }, + { + "textRaw": "`requestCert` {boolean} `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.", + "name": "requestCert", + "type": "boolean", + "desc": "`true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`." + }, + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "desc": "If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`." + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`enableTrace`: See [`tls.createServer()`][]", + "name": "enableTrace", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`secureContext`: A TLS context object from [`tls.createSecureContext()`][]", + "name": "secureContext", + "desc": "A TLS context object from [`tls.createSecureContext()`][]" + }, + { + "textRaw": "`isServer`: If `true` the TLS socket will be instantiated in server-mode. **Default:** `false`.", + "name": "isServer", + "default": "`false`", + "desc": "If `true` the TLS socket will be instantiated in server-mode." + }, + { + "textRaw": "`server` {net.Server} A [`net.Server`][] instance", + "name": "server", + "type": "net.Server", + "desc": "A [`net.Server`][] instance" + }, + { + "textRaw": "`requestCert`: See [`tls.createServer()`][]", + "name": "requestCert", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`rejectUnauthorized`: See [`tls.createServer()`][]", + "name": "rejectUnauthorized", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`ALPNProtocols`: See [`tls.createServer()`][]", + "name": "ALPNProtocols", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`SNICallback`: See [`tls.createServer()`][]", + "name": "SNICallback", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`session` {Buffer} A `Buffer` instance containing a TLS session.", + "name": "session", + "type": "Buffer", + "desc": "A `Buffer` instance containing a TLS session." + }, + { + "textRaw": "`requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication.", + "name": "requestOCSP", + "type": "boolean", + "desc": "If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication." + } + ] + } + ] + } + ], + "desc": "

      Creates a new secure pair object with two streams, one of which reads and writes\nthe encrypted data and the other of which reads and writes the cleartext data.\nGenerally, the encrypted stream is piped to/from an incoming encrypted data\nstream and the cleartext one is used as a replacement for the initial encrypted\nstream.

      \n

      tls.createSecurePair() returns a tls.SecurePair object with cleartext and\nencrypted stream properties.

      \n

      Using cleartext has the same API as tls.TLSSocket.

      \n

      The tls.createSecurePair() method is now deprecated in favor of\ntls.TLSSocket(). For example, the code:

      \n
      pair = tls.createSecurePair(/* ... */);\npair.encrypted.pipe(socket);\nsocket.pipe(pair.encrypted);\n
      \n

      can be replaced by:

      \n
      secureSocket = tls.TLSSocket(socket, options);\n
      \n

      where secureSocket has the same API as pair.cleartext.

      " + }, + { + "textRaw": "`tls.createServer([options][, secureConnectionListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [ + { + "version": "v12.3.0", + "pr-url": "https://github.com/nodejs/node/pull/27665", + "description": "The `options` parameter now supports `net.createServer()` options." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11984", + "description": "The `ALPNProtocols` option can be a `TypedArray` or `DataView` now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2564", + "description": "ALPN options are supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.Server}", + "name": "return", + "type": "tls.Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)", + "name": "ALPNProtocols", + "type": "string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView", + "desc": "An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)" + }, + { + "textRaw": "`clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate.", + "name": "clientCertEngine", + "type": "string", + "desc": "Name of an OpenSSL engine which can provide the client certificate." + }, + { + "textRaw": "`enableTrace` {boolean} If `true`, [`tls.TLSSocket.enableTrace()`][] will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. **Default:** `false`.", + "name": "enableTrace", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, [`tls.TLSSocket.enableTrace()`][] will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup." + }, + { + "textRaw": "`handshakeTimeout` {number} Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out. **Default:** `120000` (120 seconds).", + "name": "handshakeTimeout", + "type": "number", + "default": "`120000` (120 seconds)", + "desc": "Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out." + }, + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. **Default:** `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "default": "`true`", + "desc": "If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`." + }, + { + "textRaw": "`requestCert` {boolean} If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. **Default:** `false`.", + "name": "requestCert", + "type": "boolean", + "default": "`false`", + "desc": "If `true` the server will request a certificate from clients that connect and attempt to verify that certificate." + }, + { + "textRaw": "`sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`.", + "name": "sessionTimeout", + "type": "number", + "default": "`300`", + "desc": "The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information." + }, + { + "textRaw": "`SNICallback(servername, callback)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `callback`. `callback` is an error-first callback that takes two optional arguments: `error` and `ctx`. `ctx`, if provided, is a `SecureContext` instance. [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. If `callback` is called with a falsy `ctx` argument, the default secure context of the server will be used. If `SNICallback` wasn't provided the default callback with high-level API will be used (see below).", + "name": "SNICallback(servername,", + "desc": "callback)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `callback`. `callback` is an error-first callback that takes two optional arguments: `error` and `ctx`. `ctx`, if provided, is a `SecureContext` instance. [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. If `callback` is called with a falsy `ctx` argument, the default secure context of the server will be used. If `SNICallback` wasn't provided the default callback with high-level API will be used (see below)." + }, + { + "textRaw": "`ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information.", + "name": "ticketKeys", + "type": "Buffer", + "desc": "48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information." + }, + { + "textRaw": "`pskCallback` {Function}", + "name": "pskCallback", + "type": "Function", + "options": [ + { + "textRaw": "socket: {tls.TLSSocket} the server [`tls.TLSSocket`][] instance for this connection.", + "name": "socket", + "type": "tls.TLSSocket", + "desc": "the server [`tls.TLSSocket`][] instance for this connection." + }, + { + "textRaw": "identity: {string} identity parameter sent from the client.", + "name": "identity", + "type": "string", + "desc": "identity parameter sent from the client." + }, + { + "textRaw": "Returns: {Buffer|TypedArray|DataView} pre-shared key that must either be a buffer or `null` to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest. When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an \"unknown_psk_identity\" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection fail with \"decrypt_error\" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][].", + "name": "return", + "type": "Buffer|TypedArray|DataView", + "desc": "pre-shared key that must either be a buffer or `null` to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest. When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an \"unknown_psk_identity\" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection fail with \"decrypt_error\" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][]." + } + ] + }, + { + "textRaw": "`pskIdentityHint` {string} optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code.", + "name": "pskIdentityHint", + "type": "string", + "desc": "optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code." + }, + { + "textRaw": "...: Any [`tls.createSecureContext()`][] option can be provided. For servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) are usually required.", + "name": "...", + "desc": "Any [`tls.createSecureContext()`][] option can be provided. For servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) are usually required." + }, + { + "textRaw": "...: Any [`net.createServer()`][] option can be provided.", + "name": "...", + "desc": "Any [`net.createServer()`][] option can be provided." + } + ] + }, + { + "textRaw": "`secureConnectionListener` {Function}", + "name": "secureConnectionListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Creates a new tls.Server. The secureConnectionListener, if provided, is\nautomatically set as a listener for the 'secureConnection' event.

      \n

      The ticketKeys options is automatically shared between cluster module\nworkers.

      \n

      The following illustrates a simple echo server:

      \n
      const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses a self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nconst server = tls.createServer(options, (socket) => {\n  console.log('server connected',\n              socket.authorized ? 'authorized' : 'unauthorized');\n  socket.write('welcome!\\n');\n  socket.setEncoding('utf8');\n  socket.pipe(socket);\n});\nserver.listen(8000, () => {\n  console.log('server bound');\n});\n
      \n

      The server can be tested by connecting to it using the example client from\ntls.connect().

      " + }, + { + "textRaw": "`tls.getCiphers()`", + "type": "method", + "name": "getCiphers", + "meta": { + "added": [ + "v0.10.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array with the names of the supported TLS ciphers. The names are\nlower-case for historical reasons, but must be uppercased to be used in\nthe ciphers option of tls.createSecureContext().

      \n

      Cipher names that start with 'tls_' are for TLSv1.3, all the others are for\nTLSv1.2 and below.

      \n
      console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]\n
      " + } + ], + "properties": [ + { + "textRaw": "`rootCertificates` {string[]}", + "type": "string[]", + "name": "rootCertificates", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "desc": "

      An immutable array of strings representing the root certificates (in PEM format)\nfrom the bundled Mozilla CA store as supplied by current Node.js version.

      \n

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store\nthat is fixed at release time. It is identical on all supported platforms.

      " + }, + { + "textRaw": "`tls.DEFAULT_ECDH_CURVE`", + "name": "DEFAULT_ECDH_CURVE", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16853", + "description": "Default value changed to `'auto'`." + } + ] + }, + "desc": "

      The default curve name to use for ECDH key agreement in a tls server. The\ndefault value is 'auto'. See tls.createSecureContext() for further\ninformation.

      " + }, + { + "textRaw": "`DEFAULT_MAX_VERSION` {string} The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.", + "type": "string", + "name": "DEFAULT_MAX_VERSION", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "default": "`'TLSv1.3'`, unless changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used", + "desc": "The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`." + }, + { + "textRaw": "`DEFAULT_MIN_VERSION` {string} The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless changed using CLI options. Using `--tls-min-v1.0` sets the default to `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is used.", + "type": "string", + "name": "DEFAULT_MIN_VERSION", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "default": "`'TLSv1.2'`, unless changed using CLI options. Using `--tls-min-v1.0` sets the default to `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is used", + "shortDesc": "The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`." + } + ], + "type": "module", + "displayName": "TLS (SSL)" + }, + { + "textRaw": "Trace events", + "name": "trace_events", + "introduced_in": "v7.7.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/trace_events.js

      \n

      The trace_events module provides a mechanism to centralize tracing information\ngenerated by V8, Node.js core, and userspace code.

      \n

      Tracing can be enabled with the --trace-event-categories command-line flag\nor by using the trace_events module. The --trace-event-categories flag\naccepts a list of comma-separated category names.

      \n

      The available categories are:

      \n
        \n
      • node: An empty placeholder.
      • \n
      • node.async_hooks: Enables capture of detailed async_hooks trace data.\nThe async_hooks events have a unique asyncId and a special triggerId\ntriggerAsyncId property.
      • \n
      • node.bootstrap: Enables capture of Node.js bootstrap milestones.
      • \n
      • node.console: Enables capture of console.time() and console.count()\noutput.
      • \n
      • node.dns.native: Enables capture of trace data for DNS queries.
      • \n
      • node.environment: Enables capture of Node.js Environment milestones.
      • \n
      • node.fs.sync: Enables capture of trace data for file system sync methods.
      • \n
      • node.perf: Enables capture of Performance API measurements.\n
          \n
        • node.perf.usertiming: Enables capture of only Performance API User Timing\nmeasures and marks.
        • \n
        • node.perf.timerify: Enables capture of only Performance API timerify\nmeasurements.
        • \n
        \n
      • \n
      • node.promises.rejections: Enables capture of trace data tracking the number\nof unhandled Promise rejections and handled-after-rejections.
      • \n
      • node.vm.script: Enables capture of trace data for the vm module's\nrunInNewContext(), runInContext(), and runInThisContext() methods.
      • \n
      • v8: The V8 events are GC, compiling, and execution related.
      • \n
      \n

      By default the node, node.async_hooks, and v8 categories are enabled.

      \n
      node --trace-event-categories v8,node,node.async_hooks server.js\n
      \n

      Prior versions of Node.js required the use of the --trace-events-enabled\nflag to enable trace events. This requirement has been removed. However, the\n--trace-events-enabled flag may still be used and will enable the\nnode, node.async_hooks, and v8 trace event categories by default.

      \n
      node --trace-events-enabled\n\n# is equivalent to\n\nnode --trace-event-categories v8,node,node.async_hooks\n
      \n

      Alternatively, trace events may be enabled using the trace_events module:

      \n
      const trace_events = require('trace_events');\nconst tracing = trace_events.createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category\n
      \n

      Running Node.js with tracing enabled will produce log files that can be opened\nin the chrome://tracing\ntab of Chrome.

      \n

      The logging file is by default called node_trace.${rotation}.log, where\n${rotation} is an incrementing log-rotation id. The filepath pattern can\nbe specified with --trace-event-file-pattern that accepts a template\nstring that supports ${rotation} and ${pid}:

      \n
      node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js\n
      \n

      The tracing system uses the same time source\nas the one used by process.hrtime().\nHowever the trace-event timestamps are expressed in microseconds,\nunlike process.hrtime() which returns nanoseconds.

      \n

      The features from this module are not available in Worker threads.

      ", + "modules": [ + { + "textRaw": "The `trace_events` module", + "name": "the_`trace_events`_module", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "modules": [ + { + "textRaw": "`Tracing` object", + "name": "`tracing`_object", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      The Tracing object is used to enable or disable tracing for sets of\ncategories. Instances are created using the trace_events.createTracing()\nmethod.

      \n

      When created, the Tracing object is disabled. Calling the\ntracing.enable() method adds the categories to the set of enabled trace event\ncategories. Calling tracing.disable() will remove the categories from the\nset of enabled trace event categories.

      ", + "properties": [ + { + "textRaw": "`categories` {string}", + "type": "string", + "name": "categories", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      A comma-separated list of the trace event categories covered by this\nTracing object.

      " + }, + { + "textRaw": "`enabled` {boolean} `true` only if the `Tracing` object has been enabled.", + "type": "boolean", + "name": "enabled", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "`true` only if the `Tracing` object has been enabled." + } + ], + "methods": [ + { + "textRaw": "`tracing.disable()`", + "type": "method", + "name": "disable", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disables this Tracing object.

      \n

      Only trace event categories not covered by other enabled Tracing objects\nand not specified by the --trace-event-categories flag will be disabled.

      \n
      const trace_events = require('trace_events');\nconst t1 = trace_events.createTracing({ categories: ['node', 'v8'] });\nconst t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(trace_events.getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(trace_events.getEnabledCategories());\n
      " + }, + { + "textRaw": "`tracing.enable()`", + "type": "method", + "name": "enable", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Enables this Tracing object for the set of categories covered by the\nTracing object.

      " + } + ], + "type": "module", + "displayName": "`Tracing` object" + } + ], + "methods": [ + { + "textRaw": "`trace_events.createTracing(options)`", + "type": "method", + "name": "createTracing", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Tracing}.", + "name": "return", + "type": "Tracing", + "desc": "." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`categories` {string[]} An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced.", + "name": "categories", + "type": "string[]", + "desc": "An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced." + } + ] + } + ] + } + ], + "desc": "

      Creates and returns a Tracing object for the given set of categories.

      \n
      const trace_events = require('trace_events');\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = trace_events.createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();\n
      " + }, + { + "textRaw": "`trace_events.getEnabledCategories()`", + "type": "method", + "name": "getEnabledCategories", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a comma-separated list of all currently-enabled trace event\ncategories. The current set of enabled trace event categories is determined\nby the union of all currently-enabled Tracing objects and any categories\nenabled using the --trace-event-categories flag.

      \n

      Given the file test.js below, the command\nnode --trace-event-categories node.perf test.js will print\n'node.async_hooks,node.perf' to the console.

      \n
      const trace_events = require('trace_events');\nconst t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });\nconst t2 = trace_events.createTracing({ categories: ['node.perf'] });\nconst t3 = trace_events.createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(trace_events.getEnabledCategories());\n
      " + } + ], + "type": "module", + "displayName": "The `trace_events` module" + } + ], + "type": "module", + "displayName": "Trace events" + }, + { + "textRaw": "TTY", + "name": "tty", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/tty.js

      \n

      The tty module provides the tty.ReadStream and tty.WriteStream classes.\nIn most cases, it will not be necessary or possible to use this module directly.\nHowever, it can be accessed using:

      \n
      const tty = require('tty');\n
      \n

      When Node.js detects that it is being run with a text terminal (\"TTY\")\nattached, process.stdin will, by default, be initialized as an instance of\ntty.ReadStream and both process.stdout and process.stderr will, by\ndefault be instances of tty.WriteStream. The preferred method of determining\nwhether Node.js is being run within a TTY context is to check that the value of\nthe process.stdout.isTTY property is true:

      \n
      $ node -p -e \"Boolean(process.stdout.isTTY)\"\ntrue\n$ node -p -e \"Boolean(process.stdout.isTTY)\" | cat\nfalse\n
      \n

      In most cases, there should be little to no reason for an application to\nmanually create instances of the tty.ReadStream and tty.WriteStream\nclasses.

      ", + "classes": [ + { + "textRaw": "Class: `tty.ReadStream`", + "type": "class", + "name": "tty.ReadStream", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "\n

      Represents the readable side of a TTY. In normal circumstances\nprocess.stdin will be the only tty.ReadStream instance in a Node.js\nprocess and there should be no reason to create additional instances.

      ", + "properties": [ + { + "textRaw": "`readStream.isRaw`", + "name": "isRaw", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      A boolean that is true if the TTY is currently configured to operate as a\nraw device. Defaults to false.

      " + }, + { + "textRaw": "`readStream.isTTY`", + "name": "isTTY", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      A boolean that is always true for tty.ReadStream instances.

      " + } + ], + "methods": [ + { + "textRaw": "`readStream.setRawMode(mode)`", + "type": "method", + "name": "setRawMode", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this} The read stream instance.", + "name": "return", + "type": "this", + "desc": "The read stream instance." + }, + "params": [ + { + "textRaw": "`mode` {boolean} If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` property will be set to the resulting mode.", + "name": "mode", + "type": "boolean", + "desc": "If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` property will be set to the resulting mode." + } + ] + } + ], + "desc": "

      Allows configuration of tty.ReadStream so that it operates as a raw device.

      \n

      When in raw mode, input is always available character-by-character, not\nincluding modifiers. Additionally, all special processing of characters by the\nterminal is disabled, including echoing input characters.\nCTRL+C will no longer cause a SIGINT when in this mode.

      " + } + ] + }, + { + "textRaw": "Class: `tty.WriteStream`", + "type": "class", + "name": "tty.WriteStream", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "\n

      Represents the writable side of a TTY. In normal circumstances,\nprocess.stdout and process.stderr will be the only\ntty.WriteStream instances created for a Node.js process and there\nshould be no reason to create additional instances.

      ", + "events": [ + { + "textRaw": "Event: `'resize'`", + "type": "event", + "name": "resize", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resize' event is emitted whenever either of the writeStream.columns\nor writeStream.rows properties have changed. No arguments are passed to the\nlistener callback when called.

      \n
      process.stdout.on('resize', () => {\n  console.log('screen size has changed!');\n  console.log(`${process.stdout.columns}x${process.stdout.rows}`);\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`writeStream.clearLine(dir[, callback])`", + "type": "method", + "name": "clearLine", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`dir` {number}", + "name": "dir", + "type": "number", + "options": [ + { + "textRaw": "`-1`: to the left from cursor", + "name": "-1", + "desc": "to the left from cursor" + }, + { + "textRaw": "`1`: to the right from cursor", + "name": "1", + "desc": "to the right from cursor" + }, + { + "textRaw": "`0`: the entire line", + "name": "0", + "desc": "the entire line" + } + ] + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.clearLine() clears the current line of this WriteStream in a\ndirection identified by dir.

      " + }, + { + "textRaw": "`writeStream.clearScreenDown([callback])`", + "type": "method", + "name": "clearScreenDown", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.clearScreenDown() clears this WriteStream from the current\ncursor down.

      " + }, + { + "textRaw": "`writeStream.cursorTo(x[, y][, callback])`", + "type": "method", + "name": "cursorTo", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`x` {number}", + "name": "x", + "type": "number" + }, + { + "textRaw": "`y` {number}", + "name": "y", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.cursorTo() moves this WriteStream's cursor to the specified\nposition.

      " + }, + { + "textRaw": "`writeStream.getColorDepth([env])`", + "type": "method", + "name": "getColorDepth", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`env` {Object} An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "An object containing the environment variables to check. This enables simulating the usage of a specific terminal." + } + ] + } + ], + "desc": "

      Returns:

      \n
        \n
      • 1 for 2,
      • \n
      • 4 for 16,
      • \n
      • 8 for 256,
      • \n
      • 24 for 16,777,216\ncolors supported.
      • \n
      \n

      Use this to determine what colors the terminal supports. Due to the nature of\ncolors in terminals it is possible to either have false positives or false\nnegatives. It depends on process information and the environment variables that\nmay lie about what terminal is used.\nIt is possible to pass in an env object to simulate the usage of a specific\nterminal. This can be useful to check how specific environment settings behave.

      \n

      To enforce a specific color support, use one of the below environment settings.

      \n
        \n
      • 2 colors: FORCE_COLOR = 0 (Disables colors)
      • \n
      • 16 colors: FORCE_COLOR = 1
      • \n
      • 256 colors: FORCE_COLOR = 2
      • \n
      • 16,777,216 colors: FORCE_COLOR = 3
      • \n
      \n

      Disabling color support is also possible by using the NO_COLOR and\nNODE_DISABLE_COLORS environment variables.

      " + }, + { + "textRaw": "`writeStream.getWindowSize()`", + "type": "method", + "name": "getWindowSize", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number[]}", + "name": "return", + "type": "number[]" + }, + "params": [] + } + ], + "desc": "

      writeStream.getWindowSize() returns the size of the TTY\ncorresponding to this WriteStream. The array is of the type\n[numColumns, numRows] where numColumns and numRows represent the number\nof columns and rows in the corresponding TTY.

      " + }, + { + "textRaw": "`writeStream.hasColors([count][, env])`", + "type": "method", + "name": "hasColors", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`count` {integer} The number of colors that are requested (minimum 2). **Default:** 16.", + "name": "count", + "type": "integer", + "default": "16", + "desc": "The number of colors that are requested (minimum 2)." + }, + { + "textRaw": "`env` {Object} An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "An object containing the environment variables to check. This enables simulating the usage of a specific terminal." + } + ] + } + ], + "desc": "

      Returns true if the writeStream supports at least as many colors as provided\nin count. Minimum support is 2 (black and white).

      \n

      This has the same false positives and negatives as described in\nwriteStream.getColorDepth().

      \n
      process.stdout.hasColors();\n// Returns true or false depending on if `stdout` supports at least 16 colors.\nprocess.stdout.hasColors(256);\n// Returns true or false depending on if `stdout` supports at least 256 colors.\nprocess.stdout.hasColors({ TMUX: '1' });\n// Returns true.\nprocess.stdout.hasColors(2 ** 24, { TMUX: '1' });\n// Returns false (the environment setting pretends to support 2 ** 8 colors).\n
      " + }, + { + "textRaw": "`writeStream.moveCursor(dx, dy[, callback])`", + "type": "method", + "name": "moveCursor", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`dx` {number}", + "name": "dx", + "type": "number" + }, + { + "textRaw": "`dy` {number}", + "name": "dy", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.moveCursor() moves this WriteStream's cursor relative to its\ncurrent position.

      " + } + ], + "properties": [ + { + "textRaw": "`writeStream.columns`", + "name": "columns", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      A number specifying the number of columns the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

      " + }, + { + "textRaw": "`writeStream.isTTY`", + "name": "isTTY", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      A boolean that is always true.

      " + }, + { + "textRaw": "`writeStream.rows`", + "name": "rows", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      A number specifying the number of rows the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`tty.isatty(fd)`", + "type": "method", + "name": "isatty", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`fd` {number} A numeric file descriptor", + "name": "fd", + "type": "number", + "desc": "A numeric file descriptor" + } + ] + } + ], + "desc": "

      The tty.isatty() method returns true if the given fd is associated with\na TTY and false if it is not, including whenever fd is not a non-negative\ninteger.

      " + } + ], + "type": "module", + "displayName": "TTY" + }, + { + "textRaw": "UDP/datagram sockets", + "name": "dgram", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/dgram.js

      \n

      The dgram module provides an implementation of UDP datagram sockets.

      \n
      const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
      ", + "classes": [ + { + "textRaw": "Class: `dgram.Socket`", + "type": "class", + "name": "dgram.Socket", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "desc": "\n

      Encapsulates the datagram functionality.

      \n

      New instances of dgram.Socket are created using dgram.createSocket().\nThe new keyword is not to be used to create dgram.Socket instances.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted after a socket is closed with close().\nOnce triggered, no new 'message' events will be emitted on this socket.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'connect' event is emitted after a socket is associated to a remote\naddress as a result of a successful connect() call.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`exception` {Error}", + "name": "exception", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.

      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'listening' event is emitted once the dgram.Socket is addressable and\ncan receive data. This happens either explicitly with socket.bind() or\nimplicitly the first time data is sent using socket.send().\nUntil the dgram.Socket is listening, the underlying system resources do not\nexist and calls such as socket.address() and socket.setTTL() will fail.

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'message' event is emitted when a new datagram is available on a socket.\nThe event handler function is passed two arguments: msg and rinfo.

      \n\n

      If the source address of the incoming packet is an IPv6 link-local\naddress, the interface name is added to the address. For\nexample, a packet received on the en0 interface might have the\naddress field set to 'fe80::2618:1234:ab11:3b9c%en0', where '%en0'\nis the interface name as a zone ID suffix.

      " + } + ], + "methods": [ + { + "textRaw": "`socket.addMembership(multicastAddress[, multicastInterface])`", + "type": "method", + "name": "addMembership", + "meta": { + "added": [ + "v0.6.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` {string}", + "name": "multicastAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Tells the kernel to join a multicast group at the given multicastAddress and\nmulticastInterface using the IP_ADD_MEMBERSHIP socket option. If the\nmulticastInterface argument is not specified, the operating system will choose\none interface and will add membership to it. To add membership to every\navailable interface, call addMembership multiple times, once per interface.

      \n

      When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.

      \n

      When sharing a UDP socket across multiple cluster workers, the\nsocket.addMembership() function must be called only once or an\nEADDRINUSE error will occur:

      \n
      const cluster = require('cluster');\nconst dgram = require('dgram');\nif (cluster.isMaster) {\n  cluster.fork(); // Works ok.\n  cluster.fork(); // Fails with EADDRINUSE.\n} else {\n  const s = dgram.createSocket('udp4');\n  s.bind(1234, () => {\n    s.addMembership('224.0.0.114');\n  });\n}\n
      " + }, + { + "textRaw": "`socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`", + "type": "method", + "name": "addSourceSpecificMembership", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`sourceAddress` {string}", + "name": "sourceAddress", + "type": "string" + }, + { + "textRaw": "`groupAddress` {string}", + "name": "groupAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Tells the kernel to join a source-specific multicast channel at the given\nsourceAddress and groupAddress, using the multicastInterface with the\nIP_ADD_SOURCE_MEMBERSHIP socket option. If the multicastInterface argument\nis not specified, the operating system will choose one interface and will add\nmembership to it. To add membership to every available interface, call\nsocket.addSourceSpecificMembership() multiple times, once per interface.

      \n

      When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.

      " + }, + { + "textRaw": "`socket.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address, family and port\nproperties.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.bind([port][, address][, callback])`", + "type": "method", + "name": "bind", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [ + { + "version": "v0.10", + "description": "The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`port` {integer}", + "name": "port", + "type": "integer" + }, + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`callback` {Function} with no parameters. Called when binding is complete.", + "name": "callback", + "type": "Function", + "desc": "with no parameters. Called when binding is complete." + } + ] + } + ], + "desc": "

      For UDP sockets, causes the dgram.Socket to listen for datagram\nmessages on a named port and optional address. If port is not\nspecified or is 0, the operating system will attempt to bind to a\nrandom port. If address is not specified, the operating system will\nattempt to listen on all addresses. Once binding is complete, a\n'listening' event is emitted and the optional callback function is\ncalled.

      \n

      Specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

      \n

      A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

      \n

      If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

      \n

      Example of a UDP server listening on port 41234:

      \n
      const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
      " + }, + { + "textRaw": "`socket.bind(options[, callback])`", + "type": "method", + "name": "bind", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Required. Supports the following properties:", + "name": "options", + "type": "Object", + "desc": "Required. Supports the following properties:", + "options": [ + { + "textRaw": "`port` {integer}", + "name": "port", + "type": "integer" + }, + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`exclusive` {boolean}", + "name": "exclusive", + "type": "boolean" + }, + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      For UDP sockets, causes the dgram.Socket to listen for datagram\nmessages on a named port and optional address that are passed as\nproperties of an options object passed as the first argument. If\nport is not specified or is 0, the operating system will attempt\nto bind to a random port. If address is not specified, the operating\nsystem will attempt to listen on all addresses. Once binding is\ncomplete, a 'listening' event is emitted and the optional callback\nfunction is called.

      \n

      The options object may contain a fd property. When a fd greater\nthan 0 is set, it will wrap around an existing socket with the given\nfile descriptor. In this case, the properties of port and address\nwill be ignored.

      \n

      Specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

      \n

      The options object may contain an additional exclusive property that is\nused when using dgram.Socket objects with the cluster module. When\nexclusive is set to false (the default), cluster workers will use the same\nunderlying socket handle allowing connection handling duties to be shared.\nWhen exclusive is true, however, the handle is not shared and attempted\nport sharing results in an error.

      \n

      A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

      \n

      If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

      \n

      An example socket listening on an exclusive port is shown below.

      \n
      socket.bind({\n  address: 'localhost',\n  port: 8000,\n  exclusive: true\n});\n
      " + }, + { + "textRaw": "`socket.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} Called when the socket has been closed.", + "name": "callback", + "type": "Function", + "desc": "Called when the socket has been closed." + } + ] + } + ], + "desc": "

      Close the underlying socket and stop listening for data on it. If a callback is\nprovided, it is added as a listener for the 'close' event.

      " + }, + { + "textRaw": "`socket.connect(port[, address][, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`port` {integer}", + "name": "port", + "type": "integer" + }, + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`callback` {Function} Called when the connection is completed or on error.", + "name": "callback", + "type": "Function", + "desc": "Called when the connection is completed or on error." + } + ] + } + ], + "desc": "

      Associates the dgram.Socket to a remote address and port. Every\nmessage sent by this handle is automatically sent to that destination. Also,\nthe socket will only receive messages from that remote peer.\nTrying to call connect() on an already connected socket will result\nin an ERR_SOCKET_DGRAM_IS_CONNECTED exception. If address is not\nprovided, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets)\nwill be used by default. Once the connection is complete, a 'connect' event\nis emitted and the optional callback function is called. In case of failure,\nthe callback is called or, failing this, an 'error' event is emitted.

      " + }, + { + "textRaw": "`socket.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      A synchronous function that disassociates a connected dgram.Socket from\nits remote address. Trying to call disconnect() on an unbound or already\ndisconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED\nexception.

      " + }, + { + "textRaw": "`socket.dropMembership(multicastAddress[, multicastInterface])`", + "type": "method", + "name": "dropMembership", + "meta": { + "added": [ + "v0.6.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` {string}", + "name": "multicastAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Instructs the kernel to leave a multicast group at multicastAddress using the\nIP_DROP_MEMBERSHIP socket option. This method is automatically called by the\nkernel when the socket is closed or the process terminates, so most apps will\nnever have reason to call this.

      \n

      If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

      " + }, + { + "textRaw": "`socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`", + "type": "method", + "name": "dropSourceSpecificMembership", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`sourceAddress` {string}", + "name": "sourceAddress", + "type": "string" + }, + { + "textRaw": "`groupAddress` {string}", + "name": "groupAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Instructs the kernel to leave a source-specific multicast channel at the given\nsourceAddress and groupAddress using the IP_DROP_SOURCE_MEMBERSHIP\nsocket option. This method is automatically called by the kernel when the\nsocket is closed or the process terminates, so most apps will never have\nreason to call this.

      \n

      If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

      " + }, + { + "textRaw": "`socket.getRecvBufferSize()`", + "type": "method", + "name": "getRecvBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} the `SO_RCVBUF` socket receive buffer size in bytes.", + "name": "return", + "type": "number", + "desc": "the `SO_RCVBUF` socket receive buffer size in bytes." + }, + "params": [] + } + ], + "desc": "

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.getSendBufferSize()`", + "type": "method", + "name": "getSendBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} the `SO_SNDBUF` socket send buffer size in bytes.", + "name": "return", + "type": "number", + "desc": "the `SO_SNDBUF` socket send buffer size in bytes." + }, + "params": [] + } + ], + "desc": "

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [] + } + ], + "desc": "

      By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref() method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active. The socket.ref() method adds the socket back to the reference\ncounting and restores the default behavior.

      \n

      Calling socket.ref() multiples times will have no additional effect.

      \n

      The socket.ref() method returns a reference to the socket so calls can be\nchained.

      " + }, + { + "textRaw": "`socket.remoteAddress()`", + "type": "method", + "name": "remoteAddress", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing the address, family, and port of the remote\nendpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED exception\nif the socket is not connected.

      " + }, + { + "textRaw": "`socket.send(msg[, offset, length][, port][, address][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/22413", + "description": "The `msg` parameter can now be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11985", + "description": "The `msg` parameter can be an `Uint8Array` now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10473", + "description": "The `address` parameter is always optional now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5929", + "description": "On success, `callback` will now be called with an `error` argument of `null` rather than `0`." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4374", + "description": "The `msg` parameter can be an array now. Also, the `offset` and `length` parameters are optional now." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26871", + "description": "Added support for sending data on connected sockets." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`msg` {Buffer|TypedArray|DataView|string|Array} Message to be sent.", + "name": "msg", + "type": "Buffer|TypedArray|DataView|string|Array", + "desc": "Message to be sent." + }, + { + "textRaw": "`offset` {integer} Offset in the buffer where the message starts.", + "name": "offset", + "type": "integer", + "desc": "Offset in the buffer where the message starts." + }, + { + "textRaw": "`length` {integer} Number of bytes in the message.", + "name": "length", + "type": "integer", + "desc": "Number of bytes in the message." + }, + { + "textRaw": "`port` {integer} Destination port.", + "name": "port", + "type": "integer", + "desc": "Destination port." + }, + { + "textRaw": "`address` {string} Destination host name or IP address.", + "name": "address", + "type": "string", + "desc": "Destination host name or IP address." + }, + { + "textRaw": "`callback` {Function} Called when the message has been sent.", + "name": "callback", + "type": "Function", + "desc": "Called when the message has been sent." + } + ] + } + ], + "desc": "

      Broadcasts a datagram on the socket.\nFor connectionless sockets, the destination port and address must be\nspecified. Connected sockets, on the other hand, will use their associated\nremote endpoint, so the port and address arguments must not be set.

      \n

      The msg argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg is a Buffer,\nany TypedArray or a DataView,\nthe offset and length specify the offset within the Buffer where the\nmessage begins and the number of bytes in the message, respectively.\nIf msg is a String, then it is automatically converted to a Buffer\nwith 'utf8' encoding. With messages that\ncontain multi-byte characters, offset and length will be calculated with\nrespect to byte length and not the character position.\nIf msg is an array, offset and length must not be specified.

      \n

      The address argument is a string. If the value of address is a host name,\nDNS will be used to resolve the address of the host. If address is not\nprovided or otherwise falsy, '127.0.0.1' (for udp4 sockets) or '::1'\n(for udp6 sockets) will be used by default.

      \n

      If the socket has not been previously bound with a call to bind, the socket\nis assigned a random port number and is bound to the \"all interfaces\" address\n('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

      \n

      An optional callback function may be specified to as a way of reporting\nDNS errors or for determining when it is safe to reuse the buf object.\nDNS lookups delay the time to send for at least one tick of the\nNode.js event loop.

      \n

      The only way to know for sure that the datagram has been sent is by using a\ncallback. If an error occurs and a callback is given, the error will be\npassed as the first argument to the callback. If a callback is not given,\nthe error is emitted as an 'error' event on the socket object.

      \n

      Offset and length are optional but both must be set if either are used.\nThey are supported only when the first argument is a Buffer, a TypedArray,\nor a DataView.

      \n

      This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.

      \n

      Example of sending a UDP packet to a port on localhost;

      \n
      const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n  client.close();\n});\n
      \n

      Example of sending a UDP packet composed of multiple buffers to a port on\n127.0.0.1;

      \n
      const dgram = require('dgram');\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, (err) => {\n  client.close();\n});\n
      \n

      Sending multiple buffers might be faster or slower depending on the\napplication and operating system. Run benchmarks to\ndetermine the optimal strategy on a case-by-case basis. Generally speaking,\nhowever, sending multiple buffers is faster.

      \n

      Example of sending a UDP packet using a socket connected to a port on\nlocalhost:

      \n
      const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.connect(41234, 'localhost', (err) => {\n  client.send(message, (err) => {\n    client.close();\n  });\n});\n
      ", + "modules": [ + { + "textRaw": "Note about UDP datagram size", + "name": "note_about_udp_datagram_size", + "desc": "

      The maximum size of an IPv4/v6 datagram depends on the MTU\n(Maximum Transmission Unit) and on the Payload Length field size.

      \n
        \n
      • \n

        The Payload Length field is 16 bits wide, which means that a normal\npayload cannot exceed 64K octets including the internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagram\nmessages are impractical for most hosts and networks.

        \n
      • \n
      • \n

        The MTU is the largest size a given link layer technology can support for\ndatagram messages. For any link, IPv4 mandates a minimum MTU of 68\noctets, while the recommended MTU for IPv4 is 576 (typically recommended\nas the MTU for dial-up type applications), whether they arrive whole or in\nfragments.

        \n

        For IPv6, the minimum MTU is 1280 octets. However, the mandatory minimum\nfragment reassembly buffer size is 1500 octets. The value of 68 octets is\nvery small, since most current link layer technologies, like Ethernet, have a\nminimum MTU of 1500.

        \n
      • \n
      \n

      It is impossible to know in advance the MTU of each link through which\na packet might travel. Sending a datagram greater than the receiver MTU will\nnot work because the packet will get silently dropped without informing the\nsource that the data did not reach its intended recipient.

      ", + "type": "module", + "displayName": "Note about UDP datagram size" + } + ] + }, + { + "textRaw": "`socket.setBroadcast(flag)`", + "type": "method", + "name": "setBroadcast", + "meta": { + "added": [ + "v0.6.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` {boolean}", + "name": "flag", + "type": "boolean" + } + ] + } + ], + "desc": "

      Sets or clears the SO_BROADCAST socket option. When set to true, UDP\npackets may be sent to a local interface's broadcast address.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setMulticastInterface(multicastInterface)`", + "type": "method", + "name": "setMulticastInterface", + "meta": { + "added": [ + "v8.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      All references to scope in this section are referring to\nIPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP\nwith a scope index is written as 'IP%scope' where scope is an interface name\nor interface number.

      \n

      Sets the default outgoing multicast interface of the socket to a chosen\ninterface or back to system interface selection. The multicastInterface must\nbe a valid string representation of an IP from the socket's family.

      \n

      For IPv4 sockets, this should be the IP configured for the desired physical\ninterface. All packets sent to multicast on the socket will be sent on the\ninterface determined by the most recent successful use of this call.

      \n

      For IPv6 sockets, multicastInterface should include a scope to indicate the\ninterface as in the examples that follow. In IPv6, individual send calls can\nalso use explicit scope in addresses, so only packets sent to a multicast\naddress without specifying an explicit scope are affected by the most recent\nsuccessful use of this call.

      \n

      This method throws EBADF if called on an unbound socket.

      \n

      Example: IPv6 outgoing multicast interface

      \n

      On most systems, where scope format uses the interface name:

      \n
      const socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('::%eth1');\n});\n
      \n

      On Windows, where scope format uses an interface number:

      \n
      const socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('::%2');\n});\n
      \n

      Example: IPv4 outgoing multicast interface

      \n

      All systems use an IP of the host on the desired physical interface:

      \n
      const socket = dgram.createSocket('udp4');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('10.0.0.2');\n});\n
      ", + "modules": [ + { + "textRaw": "Call results", + "name": "call_results", + "desc": "

      A call on a socket that is not ready to send or no longer open may throw a Not\nrunning Error.

      \n

      If multicastInterface can not be parsed into an IP then an EINVAL\nSystem Error is thrown.

      \n

      On IPv4, if multicastInterface is a valid address but does not match any\ninterface, or if the address does not match the family then\na System Error such as EADDRNOTAVAIL or EPROTONOSUP is thrown.

      \n

      On IPv6, most errors with specifying or omitting scope will result in the socket\ncontinuing to use (or returning to) the system's default interface selection.

      \n

      A socket's address family's ANY address (IPv4 '0.0.0.0' or IPv6 '::') can be\nused to return control of the sockets default outgoing interface to the system\nfor future multicast packets.

      ", + "type": "module", + "displayName": "Call results" + } + ] + }, + { + "textRaw": "`socket.setMulticastLoopback(flag)`", + "type": "method", + "name": "setMulticastLoopback", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` {boolean}", + "name": "flag", + "type": "boolean" + } + ] + } + ], + "desc": "

      Sets or clears the IP_MULTICAST_LOOP socket option. When set to true,\nmulticast packets will also be received on the local interface.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setMulticastTTL(ttl)`", + "type": "method", + "name": "setMulticastTTL", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` {integer}", + "name": "ttl", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for\n\"Time to Live\", in this context it specifies the number of IP hops that a\npacket is allowed to travel through, specifically for multicast traffic. Each\nrouter or gateway that forwards a packet decrements the TTL. If the TTL is\ndecremented to 0 by a router, it will not be forwarded.

      \n

      The ttl argument may be between 0 and 255. The default on most systems is 1.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setRecvBufferSize(size)`", + "type": "method", + "name": "setRecvBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer}", + "name": "size", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer\nin bytes.

      \n

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setSendBufferSize(size)`", + "type": "method", + "name": "setSendBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer}", + "name": "size", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer\nin bytes.

      \n

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setTTL(ttl)`", + "type": "method", + "name": "setTTL", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` {integer}", + "name": "ttl", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the IP_TTL socket option. While TTL generally stands for \"Time to Live\",\nin this context it specifies the number of IP hops that a packet is allowed to\ntravel through. Each router or gateway that forwards a packet decrements the\nTTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\nChanging TTL values is typically done for network probes or when multicasting.

      \n

      The ttl argument may be between between 1 and 255. The default on most systems\nis 64.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [] + } + ], + "desc": "

      By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref() method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active, allowing the process to exit even if the socket is still\nlistening.

      \n

      Calling socket.unref() multiple times will have no addition effect.

      \n

      The socket.unref() method returns a reference to the socket so calls can be\nchained.

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "`dgram` module functions", + "name": "`dgram`_module_functions", + "methods": [ + { + "textRaw": "`dgram.createSocket(options[, callback])`", + "type": "method", + "name": "createSocket", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.6.0", + "pr-url": "https://github.com/nodejs/node/pull/14560", + "description": "The `lookup` option is supported." + }, + { + "version": "v8.7.0", + "pr-url": "https://github.com/nodejs/node/pull/13623", + "description": "The `recvBufferSize` and `sendBufferSize` options are supported now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/23798", + "description": "The `ipv6Only` option is supported." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [ + { + "textRaw": "`options` {Object} Available options are:", + "name": "options", + "type": "Object", + "desc": "Available options are:", + "options": [ + { + "textRaw": "`type` {string} The family of socket. Must be either `'udp4'` or `'udp6'`. Required.", + "name": "type", + "type": "string", + "desc": "The family of socket. Must be either `'udp4'` or `'udp6'`. Required." + }, + { + "textRaw": "`reuseAddr` {boolean} When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it. **Default:** `false`.", + "name": "reuseAddr", + "type": "boolean", + "default": "`false`", + "desc": "When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it." + }, + { + "textRaw": "`ipv6Only` {boolean} Setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to address `::` won't make `0.0.0.0` be bound. **Default:** `false`.", + "name": "ipv6Only", + "type": "boolean", + "default": "`false`", + "desc": "Setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to address `::` won't make `0.0.0.0` be bound." + }, + { + "textRaw": "`recvBufferSize` {number} Sets the `SO_RCVBUF` socket value.", + "name": "recvBufferSize", + "type": "number", + "desc": "Sets the `SO_RCVBUF` socket value." + }, + { + "textRaw": "`sendBufferSize` {number} Sets the `SO_SNDBUF` socket value.", + "name": "sendBufferSize", + "type": "number", + "desc": "Sets the `SO_SNDBUF` socket value." + }, + { + "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", + "name": "lookup", + "type": "Function", + "default": "[`dns.lookup()`][]", + "desc": "Custom lookup function." + } + ] + }, + { + "textRaw": "`callback` {Function} Attached as a listener for `'message'` events. Optional.", + "name": "callback", + "type": "Function", + "desc": "Attached as a listener for `'message'` events. Optional." + } + ] + } + ], + "desc": "

      Creates a dgram.Socket object. Once the socket is created, calling\nsocket.bind() will instruct the socket to begin listening for datagram\nmessages. When address and port are not passed to socket.bind() the\nmethod will bind the socket to the \"all interfaces\" address on a random port\n(it does the right thing for both udp4 and udp6 sockets). The bound address\nand port can be retrieved using socket.address().address and\nsocket.address().port.

      " + }, + { + "textRaw": "`dgram.createSocket(type[, callback])`", + "type": "method", + "name": "createSocket", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [ + { + "textRaw": "`type` {string} Either `'udp4'` or `'udp6'`.", + "name": "type", + "type": "string", + "desc": "Either `'udp4'` or `'udp6'`." + }, + { + "textRaw": "`callback` {Function} Attached as a listener to `'message'` events.", + "name": "callback", + "type": "Function", + "desc": "Attached as a listener to `'message'` events." + } + ] + } + ], + "desc": "

      Creates a dgram.Socket object of the specified type.

      \n

      Once the socket is created, calling socket.bind() will instruct the\nsocket to begin listening for datagram messages. When address and port are\nnot passed to socket.bind() the method will bind the socket to the \"all\ninterfaces\" address on a random port (it does the right thing for both udp4\nand udp6 sockets). The bound address and port can be retrieved using\nsocket.address().address and socket.address().port.

      " + } + ], + "type": "module", + "displayName": "`dgram` module functions" + } + ], + "type": "module", + "displayName": "dgram" + }, + { + "textRaw": "URL", + "name": "url", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/url.js

      \n

      The url module provides utilities for URL resolution and parsing. It can be\naccessed using:

      \n
      const url = require('url');\n
      ", + "modules": [ + { + "textRaw": "URL strings and URL objects", + "name": "url_strings_and_url_objects", + "desc": "

      A URL string is a structured string containing multiple meaningful components.\nWhen parsed, a URL object is returned containing properties for each of these\ncomponents.

      \n

      The url module provides two APIs for working with URLs: a legacy API that is\nNode.js specific, and a newer API that implements the same\nWHATWG URL Standard used by web browsers.

      \n

      A comparison between the WHATWG and Legacy APIs is provided below. Above the URL\n'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', properties\nof an object returned by the legacy url.parse() are shown. Below it are\nproperties of a WHATWG URL object.

      \n

      WHATWG URL's origin property includes protocol and host, but not\nusername or password.

      \n
      ┌────────────────────────────────────────────────────────────────────────────────────────────────â”\n│                                              href                                              │\n├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤\n│ protocol │  │        auth         │          host          │           path            │ hash  │\n│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │\n│          │  │                     │    hostname     │ port │ pathname │     search     │       │\n│          │  │                     │                 │      │          ├─┬──────────────┤       │\n│          │  │                     │                 │      │          │ │    query     │       │\n\"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash \"\n│          │  │          │          │    hostname     │ port │          │                │       │\n│          │  │          │          ├─────────────────┴──────┤          │                │       │\n│ protocol │  │ username │ password │          host          │          │                │       │\n├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │\n│   origin    │                     │         origin         │ pathname │     search     │ hash  │\n├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤\n│                                              href                                              │\n└────────────────────────────────────────────────────────────────────────────────────────────────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
      \n

      Parsing the URL string using the WHATWG API:

      \n
      const myURL =\n  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
      \n

      Parsing the URL string using the Legacy API:

      \n
      const url = require('url');\nconst myURL =\n  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
      ", + "type": "module", + "displayName": "URL strings and URL objects" + }, + { + "textRaw": "The WHATWG URL API", + "name": "the_whatwg_url_api", + "classes": [ + { + "textRaw": "Class: `URL`", + "type": "class", + "name": "URL", + "meta": { + "added": [ + "v7.0.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18281", + "description": "The class is now available on the global object." + } + ] + }, + "desc": "

      Browser-compatible URL class, implemented by following the WHATWG URL\nStandard. Examples of parsed URLs may be found in the Standard itself.\nThe URL class is also available on the global object.

      \n

      In accordance with browser conventions, all properties of URL objects\nare implemented as getters and setters on the class prototype, rather than as\ndata properties on the object itself. Thus, unlike legacy urlObjects,\nusing the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still\nreturn true.

      ", + "properties": [ + { + "textRaw": "`hash` {string}", + "type": "string", + "name": "hash", + "desc": "

      Gets and sets the fragment portion of the URL.

      \n
      const myURL = new URL('https://example.org/foo#bar');\nconsole.log(myURL.hash);\n// Prints #bar\n\nmyURL.hash = 'baz';\nconsole.log(myURL.href);\n// Prints https://example.org/foo#baz\n
      \n

      Invalid URL characters included in the value assigned to the hash property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

      " + }, + { + "textRaw": "`host` {string}", + "type": "string", + "name": "host", + "desc": "

      Gets and sets the host portion of the URL.

      \n
      const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.host);\n// Prints example.org:81\n\nmyURL.host = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:82/foo\n
      \n

      Invalid host values assigned to the host property are ignored.

      " + }, + { + "textRaw": "`hostname` {string}", + "type": "string", + "name": "hostname", + "desc": "

      Gets and sets the host name portion of the URL. The key difference between\nurl.host and url.hostname is that url.hostname does not include the\nport.

      \n
      const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.hostname);\n// Prints example.org\n\nmyURL.hostname = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:81/foo\n
      \n

      Invalid host name values assigned to the hostname property are ignored.

      " + }, + { + "textRaw": "`href` {string}", + "type": "string", + "name": "href", + "desc": "

      Gets and sets the serialized URL.

      \n
      const myURL = new URL('https://example.org/foo');\nconsole.log(myURL.href);\n// Prints https://example.org/foo\n\nmyURL.href = 'https://example.com/bar';\nconsole.log(myURL.href);\n// Prints https://example.com/bar\n
      \n

      Getting the value of the href property is equivalent to calling\nurl.toString().

      \n

      Setting the value of this property to a new value is equivalent to creating a\nnew URL object using new URL(value). Each of the URL\nobject's properties will be modified.

      \n

      If the value assigned to the href property is not a valid URL, a TypeError\nwill be thrown.

      " + }, + { + "textRaw": "`origin` {string}", + "type": "string", + "name": "origin", + "desc": "

      Gets the read-only serialization of the URL's origin.

      \n
      const myURL = new URL('https://example.org/foo/bar?baz');\nconsole.log(myURL.origin);\n// Prints https://example.org\n
      \n
      const idnURL = new URL('https://測試');\nconsole.log(idnURL.origin);\n// Prints https://xn--g6w251d\n\nconsole.log(idnURL.hostname);\n// Prints xn--g6w251d\n
      " + }, + { + "textRaw": "`password` {string}", + "type": "string", + "name": "password", + "desc": "

      Gets and sets the password portion of the URL.

      \n
      const myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.password);\n// Prints xyz\n\nmyURL.password = '123';\nconsole.log(myURL.href);\n// Prints https://abc:123@example.com\n
      \n

      Invalid URL characters included in the value assigned to the password property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

      " + }, + { + "textRaw": "`pathname` {string}", + "type": "string", + "name": "pathname", + "desc": "

      Gets and sets the path portion of the URL.

      \n
      const myURL = new URL('https://example.org/abc/xyz?123');\nconsole.log(myURL.pathname);\n// Prints /abc/xyz\n\nmyURL.pathname = '/abcdef';\nconsole.log(myURL.href);\n// Prints https://example.org/abcdef?123\n
      \n

      Invalid URL characters included in the value assigned to the pathname\nproperty are percent-encoded. The selection of which characters\nto percent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

      " + }, + { + "textRaw": "`port` {string}", + "type": "string", + "name": "port", + "desc": "

      Gets and sets the port portion of the URL.

      \n

      The port value may be a number or a string containing a number in the range\n0 to 65535 (inclusive). Setting the value to the default port of the\nURL objects given protocol will result in the port value becoming\nthe empty string ('').

      \n

      The port value can be an empty string in which case the port depends on\nthe protocol/scheme:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      protocolport
      \"ftp\"21
      \"file\"
      \"gopher\"70
      \"http\"80
      \"https\"443
      \"ws\"80
      \"wss\"443
      \n

      Upon assigning a value to the port, the value will first be converted to a\nstring using .toString().

      \n

      If that string is invalid but it begins with a number, the leading number is\nassigned to port.\nIf the number lies outside the range denoted above, it is ignored.

      \n
      const myURL = new URL('https://example.org:8888');\nconsole.log(myURL.port);\n// Prints 8888\n\n// Default ports are automatically transformed to the empty string\n// (HTTPS protocol's default port is 443)\nmyURL.port = '443';\nconsole.log(myURL.port);\n// Prints the empty string\nconsole.log(myURL.href);\n// Prints https://example.org/\n\nmyURL.port = 1234;\nconsole.log(myURL.port);\n// Prints 1234\nconsole.log(myURL.href);\n// Prints https://example.org:1234/\n\n// Completely invalid port strings are ignored\nmyURL.port = 'abcd';\nconsole.log(myURL.port);\n// Prints 1234\n\n// Leading numbers are treated as a port number\nmyURL.port = '5678abcd';\nconsole.log(myURL.port);\n// Prints 5678\n\n// Non-integers are truncated\nmyURL.port = 1234.5678;\nconsole.log(myURL.port);\n// Prints 1234\n\n// Out-of-range numbers which are not represented in scientific notation\n// will be ignored.\nmyURL.port = 1e10; // 10000000000, will be range-checked as described below\nconsole.log(myURL.port);\n// Prints 1234\n
      \n

      Numbers which contain a decimal point,\nsuch as floating-point numbers or numbers in scientific notation,\nare not an exception to this rule.\nLeading numbers up to the decimal point will be set as the URL's port,\nassuming they are valid:

      \n
      myURL.port = 4.567e21;\nconsole.log(myURL.port);\n// Prints 4 (because it is the leading number in the string '4.567e21')\n
      " + }, + { + "textRaw": "`protocol` {string}", + "type": "string", + "name": "protocol", + "desc": "

      Gets and sets the protocol portion of the URL.

      \n
      const myURL = new URL('https://example.org');\nconsole.log(myURL.protocol);\n// Prints https:\n\nmyURL.protocol = 'ftp';\nconsole.log(myURL.href);\n// Prints ftp://example.org/\n
      \n

      Invalid URL protocol values assigned to the protocol property are ignored.

      ", + "modules": [ + { + "textRaw": "Special schemes", + "name": "special_schemes", + "desc": "

      The WHATWG URL Standard considers a handful of URL protocol schemes to be\nspecial in terms of how they are parsed and serialized. When a URL is\nparsed using one of these special protocols, the url.protocol property\nmay be changed to another special protocol but cannot be changed to a\nnon-special protocol, and vice versa.

      \n

      For instance, changing from http to https works:

      \n
      const u = new URL('http://example.org');\nu.protocol = 'https';\nconsole.log(u.href);\n// https://example.org\n
      \n

      However, changing from http to a hypothetical fish protocol does not\nbecause the new protocol is not special.

      \n
      const u = new URL('http://example.org');\nu.protocol = 'fish';\nconsole.log(u.href);\n// http://example.org\n
      \n

      Likewise, changing from a non-special protocol to a special protocol is also\nnot permitted:

      \n
      const u = new URL('fish://example.org');\nu.protocol = 'http';\nconsole.log(u.href);\n// fish://example.org\n
      \n

      According to the WHATWG URL Standard, special protocol schemes are ftp,\nfile, gopher, http, https, ws, and wss.

      ", + "type": "module", + "displayName": "Special schemes" + } + ] + }, + { + "textRaw": "`search` {string}", + "type": "string", + "name": "search", + "desc": "

      Gets and sets the serialized query portion of the URL.

      \n
      const myURL = new URL('https://example.org/abc?123');\nconsole.log(myURL.search);\n// Prints ?123\n\nmyURL.search = 'abc=xyz';\nconsole.log(myURL.href);\n// Prints https://example.org/abc?abc=xyz\n
      \n

      Any invalid URL characters appearing in the value assigned the search\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

      " + }, + { + "textRaw": "`searchParams` {URLSearchParams}", + "type": "URLSearchParams", + "name": "searchParams", + "desc": "

      Gets the URLSearchParams object representing the query parameters of the\nURL. This property is read-only but the URLSearchParams object it provides\ncan be used to mutate the URL instance; to replace the entirety of query\nparameters of the URL, use the url.search setter. See\nURLSearchParams documentation for details.

      \n

      Use care when using .searchParams to modify the URL because,\nper the WHATWG specification, the URLSearchParams object uses\ndifferent rules to determine which characters to percent-encode. For\ninstance, the URL object will not percent encode the ASCII tilde (~)\ncharacter, while URLSearchParams will always encode it:

      \n
      const myUrl = new URL('https://example.org/abc?foo=~bar');\n\nconsole.log(myUrl.search);  // prints ?foo=~bar\n\n// Modify the URL via searchParams...\nmyUrl.searchParams.sort();\n\nconsole.log(myUrl.search);  // prints ?foo=%7Ebar\n
      " + }, + { + "textRaw": "`username` {string}", + "type": "string", + "name": "username", + "desc": "

      Gets and sets the username portion of the URL.

      \n
      const myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.username);\n// Prints abc\n\nmyURL.username = '123';\nconsole.log(myURL.href);\n// Prints https://123:xyz@example.com/\n
      \n

      Any invalid URL characters appearing in the value assigned the username\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

      " + } + ], + "methods": [ + { + "textRaw": "`url.toString()`", + "type": "method", + "name": "toString", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      The toString() method on the URL object returns the serialized URL. The\nvalue returned is equivalent to that of url.href and url.toJSON().

      \n

      Because of the need for standard compliance, this method does not allow users\nto customize the serialization process of the URL. For more flexibility,\nrequire('url').format() method might be of interest.

      " + }, + { + "textRaw": "`url.toJSON()`", + "type": "method", + "name": "toJSON", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      The toJSON() method on the URL object returns the serialized URL. The\nvalue returned is equivalent to that of url.href and\nurl.toString().

      \n

      This method is automatically called when an URL object is serialized\nwith JSON.stringify().

      \n
      const myURLs = [\n  new URL('https://www.example.com'),\n  new URL('https://test.example.org')\n];\nconsole.log(JSON.stringify(myURLs));\n// Prints [\"https://www.example.com/\",\"https://test.example.org/\"]\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`input` {string} The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored.", + "name": "input", + "type": "string", + "desc": "The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored." + }, + { + "textRaw": "`base` {string|URL} The base URL to resolve against if the `input` is not absolute.", + "name": "base", + "type": "string|URL", + "desc": "The base URL to resolve against if the `input` is not absolute." + } + ], + "desc": "

      Creates a new URL object by parsing the input relative to the base. If\nbase is passed as a string, it will be parsed equivalent to new URL(base).

      \n
      const myURL = new URL('/foo', 'https://example.org/');\n// https://example.org/foo\n
      \n

      The URL constructor is accessible as a property on the global object.\nIt can also be imported from the built-in url module:

      \n
      console.log(URL === require('url').URL); // Prints 'true'.\n
      \n

      A TypeError will be thrown if the input or base are not valid URLs. Note\nthat an effort will be made to coerce the given values into strings. For\ninstance:

      \n
      const myURL = new URL({ toString: () => 'https://example.org/' });\n// https://example.org/\n
      \n

      Unicode characters appearing within the host name of input will be\nautomatically converted to ASCII using the Punycode algorithm.

      \n
      const myURL = new URL('https://測試');\n// https://xn--g6w251d/\n
      \n

      This feature is only available if the node executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.

      \n

      In cases where it is not known in advance if input is an absolute URL\nand a base is provided, it is advised to validate that the origin of\nthe URL object is what is expected.

      \n
      let myURL = new URL('http://Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https://Example.com/', 'https://example.org/');\n// https://example.com/\n\nmyURL = new URL('foo://Example.com/', 'https://example.org/');\n// foo://Example.com/\n\nmyURL = new URL('http:Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https:Example.com/', 'https://example.org/');\n// https://example.org/Example.com/\n\nmyURL = new URL('foo:Example.com/', 'https://example.org/');\n// foo:Example.com/\n
      " + } + ] + }, + { + "textRaw": "Class: `URLSearchParams`", + "type": "class", + "name": "URLSearchParams", + "meta": { + "added": [ + "v7.5.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18281", + "description": "The class is now available on the global object." + } + ] + }, + "desc": "

      The URLSearchParams API provides read and write access to the query of a\nURL. The URLSearchParams class can also be used standalone with one of the\nfour following constructors.\nThe URLSearchParams class is also available on the global object.

      \n

      The WHATWG URLSearchParams interface and the querystring module have\nsimilar purpose, but the purpose of the querystring module is more\ngeneral, as it allows the customization of delimiter characters (& and =).\nOn the other hand, this API is designed purely for URL query strings.

      \n
      const myURL = new URL('https://example.org/?abc=123');\nconsole.log(myURL.searchParams.get('abc'));\n// Prints 123\n\nmyURL.searchParams.append('abc', 'xyz');\nconsole.log(myURL.href);\n// Prints https://example.org/?abc=123&abc=xyz\n\nmyURL.searchParams.delete('abc');\nmyURL.searchParams.set('a', 'b');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\n\nconst newSearchParams = new URLSearchParams(myURL.searchParams);\n// The above is equivalent to\n// const newSearchParams = new URLSearchParams(myURL.search);\n\nnewSearchParams.append('a', 'c');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\nconsole.log(newSearchParams.toString());\n// Prints a=b&a=c\n\n// newSearchParams.toString() is implicitly called\nmyURL.search = newSearchParams;\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\nnewSearchParams.delete('a');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\n
      ", + "methods": [ + { + "textRaw": "`urlSearchParams.append(name, value)`", + "type": "method", + "name": "append", + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {string}", + "name": "value", + "type": "string" + } + ] + } + ], + "desc": "

      Append a new name-value pair to the query string.

      " + }, + { + "textRaw": "`urlSearchParams.delete(name)`", + "type": "method", + "name": "delete", + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Remove all name-value pairs whose name is name.

      " + }, + { + "textRaw": "`urlSearchParams.entries()`", + "type": "method", + "name": "entries", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over each of the name-value pairs in the query.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name, the second item of the Array is the value.

      \n

      Alias for urlSearchParams[@@iterator]().

      " + }, + { + "textRaw": "`urlSearchParams.forEach(fn[, thisArg])`", + "type": "method", + "name": "forEach", + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} Invoked for each name-value pair in the query", + "name": "fn", + "type": "Function", + "desc": "Invoked for each name-value pair in the query" + }, + { + "textRaw": "`thisArg` {Object} To be used as `this` value for when `fn` is called", + "name": "thisArg", + "type": "Object", + "desc": "To be used as `this` value for when `fn` is called" + } + ] + } + ], + "desc": "

      Iterates over each name-value pair in the query and invokes the given function.

      \n
      const myURL = new URL('https://example.org/?a=b&c=d');\nmyURL.searchParams.forEach((value, name, searchParams) => {\n  console.log(name, value, myURL.searchParams === searchParams);\n});\n// Prints:\n//   a b true\n//   c d true\n
      " + }, + { + "textRaw": "`urlSearchParams.get(name)`", + "type": "method", + "name": "get", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} or `null` if there is no name-value pair with the given `name`.", + "name": "return", + "type": "string", + "desc": "or `null` if there is no name-value pair with the given `name`." + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the value of the first name-value pair whose name is name. If there\nare no such pairs, null is returned.

      " + }, + { + "textRaw": "`urlSearchParams.getAll(name)`", + "type": "method", + "name": "getAll", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the values of all name-value pairs whose name is name. If there are\nno such pairs, an empty array is returned.

      " + }, + { + "textRaw": "`urlSearchParams.has(name)`", + "type": "method", + "name": "has", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if there is at least one name-value pair whose name is name.

      " + }, + { + "textRaw": "`urlSearchParams.keys()`", + "type": "method", + "name": "keys", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over the names of each name-value pair.

      \n
      const params = new URLSearchParams('foo=bar&foo=baz');\nfor (const name of params.keys()) {\n  console.log(name);\n}\n// Prints:\n//   foo\n//   foo\n
      " + }, + { + "textRaw": "`urlSearchParams.set(name, value)`", + "type": "method", + "name": "set", + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {string}", + "name": "value", + "type": "string" + } + ] + } + ], + "desc": "

      Sets the value in the URLSearchParams object associated with name to\nvalue. If there are any pre-existing name-value pairs whose names are name,\nset the first such pair's value to value and remove all others. If not,\nappend the name-value pair to the query string.

      \n
      const params = new URLSearchParams();\nparams.append('foo', 'bar');\nparams.append('foo', 'baz');\nparams.append('abc', 'def');\nconsole.log(params.toString());\n// Prints foo=bar&foo=baz&abc=def\n\nparams.set('foo', 'def');\nparams.set('xyz', 'opq');\nconsole.log(params.toString());\n// Prints foo=def&abc=def&xyz=opq\n
      " + }, + { + "textRaw": "`urlSearchParams.sort()`", + "type": "method", + "name": "sort", + "meta": { + "added": [ + "v7.7.0", + "v6.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sort all existing name-value pairs in-place by their names. Sorting is done\nwith a stable sorting algorithm, so relative order between name-value pairs\nwith the same name is preserved.

      \n

      This method can be used, in particular, to increase cache hits.

      \n
      const params = new URLSearchParams('query[]=abc&type=search&query[]=123');\nparams.sort();\nconsole.log(params.toString());\n// Prints query%5B%5D=abc&query%5B%5D=123&type=search\n
      " + }, + { + "textRaw": "`urlSearchParams.toString()`", + "type": "method", + "name": "toString", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the search parameters serialized as a string, with characters\npercent-encoded where necessary.

      " + }, + { + "textRaw": "`urlSearchParams.values()`", + "type": "method", + "name": "values", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over the values of each name-value pair.

      " + }, + { + "textRaw": "`urlSearchParams[Symbol.iterator]()`", + "type": "method", + "name": "[Symbol.iterator]", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over each of the name-value pairs in the query string.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name, the second item of the Array is the value.

      \n

      Alias for urlSearchParams.entries().

      \n
      const params = new URLSearchParams('foo=bar&xyz=baz');\nfor (const [name, value] of params) {\n  console.log(name, value);\n}\n// Prints:\n//   foo bar\n//   xyz baz\n
      " + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Instantiate a new empty URLSearchParams object.

      " + }, + { + "params": [ + { + "textRaw": "`string` {string} A query string", + "name": "string", + "type": "string", + "desc": "A query string" + } + ], + "desc": "

      Parse the string as a query string, and use it to instantiate a new\nURLSearchParams object. A leading '?', if present, is ignored.

      \n
      let params;\n\nparams = new URLSearchParams('user=abc&query=xyz');\nconsole.log(params.get('user'));\n// Prints 'abc'\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\nparams = new URLSearchParams('?user=abc&query=xyz');\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n
      " + }, + { + "params": [ + { + "textRaw": "`obj` {Object} An object representing a collection of key-value pairs", + "name": "obj", + "type": "Object", + "desc": "An object representing a collection of key-value pairs" + } + ], + "desc": "

      Instantiate a new URLSearchParams object with a query hash map. The key and\nvalue of each property of obj are always coerced to strings.

      \n

      Unlike querystring module, duplicate keys in the form of array values are\nnot allowed. Arrays are stringified using array.toString(), which simply\njoins all array elements with commas.

      \n
      const params = new URLSearchParams({\n  user: 'abc',\n  query: ['first', 'second']\n});\nconsole.log(params.getAll('query'));\n// Prints [ 'first,second' ]\nconsole.log(params.toString());\n// Prints 'user=abc&query=first%2Csecond'\n
      " + }, + { + "params": [ + { + "textRaw": "`iterable` {Iterable} An iterable object whose elements are key-value pairs", + "name": "iterable", + "type": "Iterable", + "desc": "An iterable object whose elements are key-value pairs" + } + ], + "desc": "

      Instantiate a new URLSearchParams object with an iterable map in a way that\nis similar to Map's constructor. iterable can be an Array or any\niterable object. That means iterable can be another URLSearchParams, in\nwhich case the constructor will simply create a clone of the provided\nURLSearchParams. Elements of iterable are key-value pairs, and can\nthemselves be any iterable object.

      \n

      Duplicate keys are allowed.

      \n
      let params;\n\n// Using an array\nparams = new URLSearchParams([\n  ['user', 'abc'],\n  ['query', 'first'],\n  ['query', 'second']\n]);\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Using a Map object\nconst map = new Map();\nmap.set('user', 'abc');\nmap.set('query', 'xyz');\nparams = new URLSearchParams(map);\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\n// Using a generator function\nfunction* getQueryPairs() {\n  yield ['user', 'abc'];\n  yield ['query', 'first'];\n  yield ['query', 'second'];\n}\nparams = new URLSearchParams(getQueryPairs());\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Each key-value pair must have exactly two elements\nnew URLSearchParams([\n  ['user', 'abc', 'error']\n]);\n// Throws TypeError [ERR_INVALID_TUPLE]:\n//        Each query pair must be an iterable [name, value] tuple\n
      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`url.domainToASCII(domain)`", + "type": "method", + "name": "domainToASCII", + "meta": { + "added": [ + "v7.4.0", + "v6.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the Punycode ASCII serialization of the domain. If domain is an\ninvalid domain, the empty string is returned.

      \n

      It performs the inverse operation to url.domainToUnicode().

      \n
      const url = require('url');\nconsole.log(url.domainToASCII('español.com'));\n// Prints xn--espaol-zwa.com\nconsole.log(url.domainToASCII('中文.com'));\n// Prints xn--fiq228c.com\nconsole.log(url.domainToASCII('xn--iñvalid.com'));\n// Prints an empty string\n
      " + }, + { + "textRaw": "`url.domainToUnicode(domain)`", + "type": "method", + "name": "domainToUnicode", + "meta": { + "added": [ + "v7.4.0", + "v6.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the Unicode serialization of the domain. If domain is an invalid\ndomain, the empty string is returned.

      \n

      It performs the inverse operation to url.domainToASCII().

      \n
      const url = require('url');\nconsole.log(url.domainToUnicode('xn--espaol-zwa.com'));\n// Prints español.com\nconsole.log(url.domainToUnicode('xn--fiq228c.com'));\n// Prints 中文.com\nconsole.log(url.domainToUnicode('xn--iñvalid.com'));\n// Prints an empty string\n
      " + }, + { + "textRaw": "`url.fileURLToPath(url)`", + "type": "method", + "name": "fileURLToPath", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The fully-resolved platform-specific Node.js file path.", + "name": "return", + "type": "string", + "desc": "The fully-resolved platform-specific Node.js file path." + }, + "params": [ + { + "textRaw": "`url` {URL | string} The file URL string or URL object to convert to a path.", + "name": "url", + "type": "URL | string", + "desc": "The file URL string or URL object to convert to a path." + } + ] + } + ], + "desc": "

      This function ensures the correct decodings of percent-encoded characters as\nwell as ensuring a cross-platform valid absolute path string.

      \n
      new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/\nfileURLToPath('file:///C:/path/');       // Correct:   C:\\path\\ (Windows)\n\nnew URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt\nfileURLToPath('file://nas/foo.txt');     // Correct:   \\\\nas\\foo.txt (Windows)\n\nnew URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt\nfileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)\n\nnew URL('file:///hello world').pathname; // Incorrect: /hello%20world\nfileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)\n
      " + }, + { + "textRaw": "`url.format(URL[, options])`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`URL` {URL} A [WHATWG URL][] object", + "name": "URL", + "type": "URL", + "desc": "A [WHATWG URL][] object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`auth` {boolean} `true` if the serialized URL string should include the username and password, `false` otherwise. **Default:** `true`.", + "name": "auth", + "type": "boolean", + "default": "`true`", + "desc": "`true` if the serialized URL string should include the username and password, `false` otherwise." + }, + { + "textRaw": "`fragment` {boolean} `true` if the serialized URL string should include the fragment, `false` otherwise. **Default:** `true`.", + "name": "fragment", + "type": "boolean", + "default": "`true`", + "desc": "`true` if the serialized URL string should include the fragment, `false` otherwise." + }, + { + "textRaw": "`search` {boolean} `true` if the serialized URL string should include the search query, `false` otherwise. **Default:** `true`.", + "name": "search", + "type": "boolean", + "default": "`true`", + "desc": "`true` if the serialized URL string should include the search query, `false` otherwise." + }, + { + "textRaw": "`unicode` {boolean} `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded. **Default:** `false`.", + "name": "unicode", + "type": "boolean", + "default": "`false`", + "desc": "`true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded." + } + ] + } + ] + } + ], + "desc": "

      Returns a customizable serialization of a URL String representation of a\nWHATWG URL object.

      \n

      The URL object has both a toString() method and href property that return\nstring serializations of the URL. These are not, however, customizable in\nany way. The url.format(URL[, options]) method allows for basic customization\nof the output.

      \n
      const myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(myURL.href);\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(myURL.toString());\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));\n// Prints 'https://測試/?abc'\n
      " + }, + { + "textRaw": "`url.pathToFileURL(path)`", + "type": "method", + "name": "pathToFileURL", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {URL} The file URL object.", + "name": "return", + "type": "URL", + "desc": "The file URL object." + }, + "params": [ + { + "textRaw": "`path` {string} The path to convert to a File URL.", + "name": "path", + "type": "string", + "desc": "The path to convert to a File URL." + } + ] + } + ], + "desc": "

      This function ensures that path is resolved absolutely, and that the URL\ncontrol characters are correctly encoded when converting into a File URL.

      \n
      new URL(__filename);                // Incorrect: throws (POSIX)\nnew URL(__filename);                // Incorrect: C:\\... (Windows)\npathToFileURL(__filename);          // Correct:   file:///... (POSIX)\npathToFileURL(__filename);          // Correct:   file:///C:/... (Windows)\n\nnew URL('/foo#1', 'file:');         // Incorrect: file:///foo#1\npathToFileURL('/foo#1');            // Correct:   file:///foo%231 (POSIX)\n\nnew URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c\npathToFileURL('/some/path%.c');    // Correct:   file:///some/path%25.c (POSIX)\n
      " + } + ], + "type": "module", + "displayName": "The WHATWG URL API" + }, + { + "textRaw": "Legacy URL API", + "name": "legacy_url_api", + "meta": { + "deprecated": [ + "v11.0.0" + ], + "changes": [] + }, + "modules": [ + { + "textRaw": "Legacy `urlObject`", + "name": "legacy_`urlobject`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "desc": "

      The legacy urlObject (require('url').Url) is created and returned by the\nurl.parse() function.

      ", + "properties": [ + { + "textRaw": "`urlObject.auth`", + "name": "auth", + "desc": "

      The auth property is the username and password portion of the URL, also\nreferred to as userinfo. This string subset follows the protocol and\ndouble slashes (if present) and precedes the host component, delimited by @.\nThe string is either the username, or it is the username and password separated\nby :.

      \n

      For example: 'user:pass'.

      " + }, + { + "textRaw": "`urlObject.hash`", + "name": "hash", + "desc": "

      The hash property is the fragment identifier portion of the URL including the\nleading # character.

      \n

      For example: '#hash'.

      " + }, + { + "textRaw": "`urlObject.host`", + "name": "host", + "desc": "

      The host property is the full lower-cased host portion of the URL, including\nthe port if specified.

      \n

      For example: 'sub.example.com:8080'.

      " + }, + { + "textRaw": "`urlObject.hostname`", + "name": "hostname", + "desc": "

      The hostname property is the lower-cased host name portion of the host\ncomponent without the port included.

      \n

      For example: 'sub.example.com'.

      " + }, + { + "textRaw": "`urlObject.href`", + "name": "href", + "desc": "

      The href property is the full URL string that was parsed with both the\nprotocol and host components converted to lower-case.

      \n

      For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.

      " + }, + { + "textRaw": "`urlObject.path`", + "name": "path", + "desc": "

      The path property is a concatenation of the pathname and search\ncomponents.

      \n

      For example: '/p/a/t/h?query=string'.

      \n

      No decoding of the path is performed.

      " + }, + { + "textRaw": "`urlObject.pathname`", + "name": "pathname", + "desc": "

      The pathname property consists of the entire path section of the URL. This\nis everything following the host (including the port) and before the start\nof the query or hash components, delimited by either the ASCII question\nmark (?) or hash (#) characters.

      \n

      For example: '/p/a/t/h'.

      \n

      No decoding of the path string is performed.

      " + }, + { + "textRaw": "`urlObject.port`", + "name": "port", + "desc": "

      The port property is the numeric port portion of the host component.

      \n

      For example: '8080'.

      " + }, + { + "textRaw": "`urlObject.protocol`", + "name": "protocol", + "desc": "

      The protocol property identifies the URL's lower-cased protocol scheme.

      \n

      For example: 'http:'.

      " + }, + { + "textRaw": "`urlObject.query`", + "name": "query", + "desc": "

      The query property is either the query string without the leading ASCII\nquestion mark (?), or an object returned by the querystring module's\nparse() method. Whether the query property is a string or object is\ndetermined by the parseQueryString argument passed to url.parse().

      \n

      For example: 'query=string' or {'query': 'string'}.

      \n

      If returned as a string, no decoding of the query string is performed. If\nreturned as an object, both keys and values are decoded.

      " + }, + { + "textRaw": "`urlObject.search`", + "name": "search", + "desc": "

      The search property consists of the entire \"query string\" portion of the\nURL, including the leading ASCII question mark (?) character.

      \n

      For example: '?query=string'.

      \n

      No decoding of the query string is performed.

      " + }, + { + "textRaw": "`urlObject.slashes`", + "name": "slashes", + "desc": "

      The slashes property is a boolean with a value of true if two ASCII\nforward-slash characters (/) are required following the colon in the\nprotocol.

      " + } + ], + "type": "module", + "displayName": "Legacy `urlObject`" + } + ], + "methods": [ + { + "textRaw": "`url.format(urlObject)`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7234", + "description": "URLs with a `file:` scheme will now always use the correct number of slashes regardless of `slashes` option. A falsy `slashes` option with no protocol is now also respected at all times." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`urlObject` {Object|string} A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`.", + "name": "urlObject", + "type": "Object|string", + "desc": "A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`." + } + ] + } + ], + "desc": "

      The url.format() method returns a formatted URL string derived from\nurlObject.

      \n
      url.format({\n  protocol: 'https',\n  hostname: 'example.com',\n  pathname: '/some/path',\n  query: {\n    page: 1,\n    format: 'json'\n  }\n});\n\n// => 'https://example.com/some/path?page=1&format=json'\n
      \n

      If urlObject is not an object or a string, url.format() will throw a\nTypeError.

      \n

      The formatting process operates as follows:

      \n
        \n
      • A new empty string result is created.
      • \n
      • If urlObject.protocol is a string, it is appended as-is to result.
      • \n
      • Otherwise, if urlObject.protocol is not undefined and is not a string, an\nError is thrown.
      • \n
      • For all string values of urlObject.protocol that do not end with an ASCII\ncolon (:) character, the literal string : will be appended to result.
      • \n
      • If either of the following conditions is true, then the literal string //\nwill be appended to result:\n
          \n
        • urlObject.slashes property is true;
        • \n
        • urlObject.protocol begins with http, https, ftp, gopher, or\nfile;
        • \n
        \n
      • \n
      • If the value of the urlObject.auth property is truthy, and either\nurlObject.host or urlObject.hostname are not undefined, the value of\nurlObject.auth will be coerced into a string and appended to result\nfollowed by the literal string @.
      • \n
      • If the urlObject.host property is undefined then:\n
          \n
        • If the urlObject.hostname is a string, it is appended to result.
        • \n
        • Otherwise, if urlObject.hostname is not undefined and is not a string,\nan Error is thrown.
        • \n
        • If the urlObject.port property value is truthy, and urlObject.hostname\nis not undefined:\n
            \n
          • The literal string : is appended to result, and
          • \n
          • The value of urlObject.port is coerced to a string and appended to\nresult.
          • \n
          \n
        • \n
        \n
      • \n
      • Otherwise, if the urlObject.host property value is truthy, the value of\nurlObject.host is coerced to a string and appended to result.
      • \n
      • If the urlObject.pathname property is a string that is not an empty string:\n
          \n
        • If the urlObject.pathname does not start with an ASCII forward slash\n(/), then the literal string '/' is appended to result.
        • \n
        • The value of urlObject.pathname is appended to result.
        • \n
        \n
      • \n
      • Otherwise, if urlObject.pathname is not undefined and is not a string, an\nError is thrown.
      • \n
      • If the urlObject.search property is undefined and if the urlObject.query\nproperty is an Object, the literal string ? is appended to result\nfollowed by the output of calling the querystring module's stringify()\nmethod passing the value of urlObject.query.
      • \n
      • Otherwise, if urlObject.search is a string:\n
          \n
        • If the value of urlObject.search does not start with the ASCII question\nmark (?) character, the literal string ? is appended to result.
        • \n
        • The value of urlObject.search is appended to result.
        • \n
        \n
      • \n
      • Otherwise, if urlObject.search is not undefined and is not a string, an\nError is thrown.
      • \n
      • If the urlObject.hash property is a string:\n
          \n
        • If the value of urlObject.hash does not start with the ASCII hash (#)\ncharacter, the literal string # is appended to result.
        • \n
        • The value of urlObject.hash is appended to result.
        • \n
        \n
      • \n
      • Otherwise, if the urlObject.hash property is not undefined and is not a\nstring, an Error is thrown.
      • \n
      • result is returned.
      • \n
      " + }, + { + "textRaw": "`url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`", + "type": "method", + "name": "parse", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26941", + "description": "The `pathname` property on the returned URL object is now `/` when there is no path and the protocol scheme is `ws:` or `wss:`." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13606", + "description": "The `search` property on the returned URL object is now `null` when no query string is present." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`urlString` {string} The URL string to parse.", + "name": "urlString", + "type": "string", + "desc": "The URL string to parse." + }, + { + "textRaw": "`parseQueryString` {boolean} If `true`, the `query` property will always be set to an object returned by the [`querystring`][] module's `parse()` method. If `false`, the `query` property on the returned URL object will be an unparsed, undecoded string. **Default:** `false`.", + "name": "parseQueryString", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the `query` property will always be set to an object returned by the [`querystring`][] module's `parse()` method. If `false`, the `query` property on the returned URL object will be an unparsed, undecoded string." + }, + { + "textRaw": "`slashesDenoteHost` {boolean} If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. **Default:** `false`.", + "name": "slashesDenoteHost", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`." + } + ] + } + ], + "desc": "

      The url.parse() method takes a URL string, parses it, and returns a URL\nobject.

      \n

      A TypeError is thrown if urlString is not a string.

      \n

      A URIError is thrown if the auth property is present but cannot be decoded.

      \n

      Use of the legacy url.parse() method is discouraged. Users should\nuse the WHATWG URL API. Because the url.parse() method uses a\nlenient, non-standard algorithm for parsing URL strings, security\nissues can be introduced. Specifically, issues with host name spoofing and\nincorrect handling of usernames and passwords have been identified.

      " + }, + { + "textRaw": "`url.resolve(from, to)`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8215", + "description": "The `auth` fields are now kept intact when `from` and `to` refer to the same host." + }, + { + "version": "v6.5.0, v4.6.2", + "pr-url": "https://github.com/nodejs/node/pull/8214", + "description": "The `port` field is copied correctly now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/1480", + "description": "The `auth` fields is cleared now the `to` parameter contains a hostname." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`from` {string} The Base URL being resolved against.", + "name": "from", + "type": "string", + "desc": "The Base URL being resolved against." + }, + { + "textRaw": "`to` {string} The HREF URL being resolved.", + "name": "to", + "type": "string", + "desc": "The HREF URL being resolved." + } + ] + } + ], + "desc": "

      The url.resolve() method resolves a target URL relative to a base URL in a\nmanner similar to that of a Web browser resolving an anchor tag HREF.

      \n
      const url = require('url');\nurl.resolve('/one/two/three', 'four');         // '/one/two/four'\nurl.resolve('http://example.com/', '/one');    // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two'); // 'http://example.com/two'\n
      \n

      " + } + ], + "type": "module", + "displayName": "Legacy URL API" + }, + { + "textRaw": "Percent-encoding in URLs", + "name": "percent-encoding_in_urls", + "desc": "

      URLs are permitted to only contain a certain range of characters. Any character\nfalling outside of that range must be encoded. How such characters are encoded,\nand which characters to encode depends entirely on where the character is\nlocated within the structure of the URL.

      ", + "modules": [ + { + "textRaw": "Legacy API", + "name": "legacy_api", + "desc": "

      Within the Legacy API, spaces (' ') and the following characters will be\nautomatically escaped in the properties of URL objects:

      \n
      < > \" ` \\r \\n \\t { } | \\ ^ '\n
      \n

      For example, the ASCII space character (' ') is encoded as %20. The ASCII\nforward slash (/) character is encoded as %3C.

      ", + "type": "module", + "displayName": "Legacy API" + }, + { + "textRaw": "WHATWG API", + "name": "whatwg_api", + "desc": "

      The WHATWG URL Standard uses a more selective and fine grained approach to\nselecting encoded characters than that used by the Legacy API.

      \n

      The WHATWG algorithm defines four \"percent-encode sets\" that describe ranges\nof characters that must be percent-encoded:

      \n
        \n
      • \n

        The C0 control percent-encode set includes code points in range U+0000 to\nU+001F (inclusive) and all code points greater than U+007E.

        \n
      • \n
      • \n

        The fragment percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+003C, U+003E, and U+0060.

        \n
      • \n
      • \n

        The path percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060,\nU+007B, and U+007D.

        \n
      • \n
      • \n

        The userinfo encode set includes the path percent-encode set and code\npoints U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D,\nU+005E, and U+007C.

        \n
      • \n
      \n

      The userinfo percent-encode set is used exclusively for username and\npasswords encoded within the URL. The path percent-encode set is used for the\npath of most URLs. The fragment percent-encode set is used for URL fragments.\nThe C0 control percent-encode set is used for host and path under certain\nspecific conditions, in addition to all other cases.

      \n

      When non-ASCII characters appear within a host name, the host name is encoded\nusing the Punycode algorithm. Note, however, that a host name may contain\nboth Punycode encoded and percent-encoded characters:

      \n
      const myURL = new URL('https://%CF%80.example.com/foo');\nconsole.log(myURL.href);\n// Prints https://xn--1xa.example.com/foo\nconsole.log(myURL.origin);\n// Prints https://xn--1xa.example.com\n
      ", + "type": "module", + "displayName": "WHATWG API" + } + ], + "type": "module", + "displayName": "Percent-encoding in URLs" + } + ], + "type": "module", + "displayName": "URL" + }, + { + "textRaw": "Util", + "name": "util", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/util.js

      \n

      The util module supports the needs of Node.js internal APIs. Many of the\nutilities are useful for application and module developers as well. To access\nit:

      \n
      const util = require('util');\n
      ", + "methods": [ + { + "textRaw": "`util.callbackify(original)`", + "type": "method", + "name": "callbackify", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} a callback style function", + "name": "return", + "type": "Function", + "desc": "a callback style function" + }, + "params": [ + { + "textRaw": "`original` {Function} An `async` function", + "name": "original", + "type": "Function", + "desc": "An `async` function" + } + ] + } + ], + "desc": "

      Takes an async function (or a function that returns a Promise) and returns a\nfunction following the error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument. In the callback, the\nfirst argument will be the rejection reason (or null if the Promise\nresolved), and the second argument will be the resolved value.

      \n
      const util = require('util');\n\nasync function fn() {\n  return 'hello world';\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n  if (err) throw err;\n  console.log(ret);\n});\n
      \n

      Will print:

      \n
      hello world\n
      \n

      The callback is executed asynchronously, and will have a limited stack trace.\nIf the callback throws, the process will emit an 'uncaughtException'\nevent, and if not handled will exit.

      \n

      Since null has a special meaning as the first argument to a callback, if a\nwrapped function rejects a Promise with a falsy value as a reason, the value\nis wrapped in an Error with the original value stored in a field named\nreason.

      \n
      function fn() {\n  return Promise.reject(null);\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n  // When the Promise was rejected with `null` it is wrapped with an Error and\n  // the original value is stored in `reason`.\n  err && err.hasOwnProperty('reason') && err.reason === null;  // true\n});\n
      " + }, + { + "textRaw": "`util.debuglog(section[, callback])`", + "type": "method", + "name": "debuglog", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The logging function", + "name": "return", + "type": "Function", + "desc": "The logging function" + }, + "params": [ + { + "textRaw": "`section` {string} A string identifying the portion of the application for which the `debuglog` function is being created.", + "name": "section", + "type": "string", + "desc": "A string identifying the portion of the application for which the `debuglog` function is being created." + }, + { + "textRaw": "`callback` {Function} A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.", + "name": "callback", + "type": "Function", + "desc": "A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function." + } + ] + } + ], + "desc": "

      The util.debuglog() method is used to create a function that conditionally\nwrites debug messages to stderr based on the existence of the NODE_DEBUG\nenvironment variable. If the section name appears within the value of that\nenvironment variable, then the returned function operates similar to\nconsole.error(). If not, then the returned function is a no-op.

      \n
      const util = require('util');\nconst debuglog = util.debuglog('foo');\n\ndebuglog('hello from foo [%d]', 123);\n
      \n

      If this program is run with NODE_DEBUG=foo in the environment, then\nit will output something like:

      \n
      FOO 3245: hello from foo [123]\n
      \n

      where 3245 is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.

      \n

      The section supports wildcard also:

      \n
      const util = require('util');\nconst debuglog = util.debuglog('foo-bar');\n\ndebuglog('hi there, it\\'s foo-bar [%d]', 2333);\n
      \n

      if it is run with NODE_DEBUG=foo* in the environment, then it will output\nsomething like:

      \n
      FOO-BAR 3257: hi there, it's foo-bar [2333]\n
      \n

      Multiple comma-separated section names may be specified in the NODE_DEBUG\nenvironment variable: NODE_DEBUG=fs,net,tls.

      \n

      The optional callback argument can be used to replace the logging function\nwith a different function that doesn't have any initialization or\nunnecessary wrapping.

      \n
      const util = require('util');\nlet debuglog = util.debuglog('internals', (debug) => {\n  // Replace with a logging function that optimizes out\n  // testing if the section is enabled\n  debuglog = debug;\n});\n
      " + }, + { + "textRaw": "`util.deprecate(fn, msg[, code])`", + "type": "method", + "name": "deprecate", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16393", + "description": "Deprecation warnings are only emitted once for each code." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The deprecated function wrapped to emit a warning.", + "name": "return", + "type": "Function", + "desc": "The deprecated function wrapped to emit a warning." + }, + "params": [ + { + "textRaw": "`fn` {Function} The function that is being deprecated.", + "name": "fn", + "type": "Function", + "desc": "The function that is being deprecated." + }, + { + "textRaw": "`msg` {string} A warning message to display when the deprecated function is invoked.", + "name": "msg", + "type": "string", + "desc": "A warning message to display when the deprecated function is invoked." + }, + { + "textRaw": "`code` {string} A deprecation code. See the [list of deprecated APIs][] for a list of codes.", + "name": "code", + "type": "string", + "desc": "A deprecation code. See the [list of deprecated APIs][] for a list of codes." + } + ] + } + ], + "desc": "

      The util.deprecate() method wraps fn (which may be a function or class) in\nsuch a way that it is marked as deprecated.

      \n
      const util = require('util');\n\nexports.obsoleteFunction = util.deprecate(() => {\n  // Do something here.\n}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');\n
      \n

      When called, util.deprecate() will return a function that will emit a\nDeprecationWarning using the 'warning' event. The warning will\nbe emitted and printed to stderr the first time the returned function is\ncalled. After the warning is emitted, the wrapped function is called without\nemitting a warning.

      \n

      If the same optional code is supplied in multiple calls to util.deprecate(),\nthe warning will be emitted only once for that code.

      \n
      const util = require('util');\n\nconst fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');\nconst fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');\nfn1(); // Emits a deprecation warning with code DEP0001\nfn2(); // Does not emit a deprecation warning because it has the same code\n
      \n

      If either the --no-deprecation or --no-warnings command line flags are\nused, or if the process.noDeprecation property is set to true prior to\nthe first deprecation warning, the util.deprecate() method does nothing.

      \n

      If the --trace-deprecation or --trace-warnings command line flags are set,\nor the process.traceDeprecation property is set to true, a warning and a\nstack trace are printed to stderr the first time the deprecated function is\ncalled.

      \n

      If the --throw-deprecation command line flag is set, or the\nprocess.throwDeprecation property is set to true, then an exception will be\nthrown when the deprecated function is called.

      \n

      The --throw-deprecation command line flag and process.throwDeprecation\nproperty take precedence over --trace-deprecation and\nprocess.traceDeprecation.

      " + }, + { + "textRaw": "`util.format(format[, ...args])`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29606", + "description": "The `%c` specifier is ignored now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/23708", + "description": "The `%d`, `%f` and `%i` specifiers now support Symbols properly." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23162", + "description": "The `format` argument is now only taken as such if it actually contains format specifiers." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23162", + "description": "If the `format` argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24806", + "description": "The `%o` specifier's `depth` has default depth of 4 again." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17907", + "description": "The `%o` specifier's `depth` option will now fall back to the default depth." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22097", + "description": "The `%d` and `%i` specifiers now support BigInt." + }, + { + "version": "v8.4.0", + "pr-url": "https://github.com/nodejs/node/pull/14558", + "description": "The `%o` and `%O` specifiers are supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`format` {string} A `printf`-like format string.", + "name": "format", + "type": "string", + "desc": "A `printf`-like format string." + } + ] + } + ], + "desc": "

      The util.format() method returns a formatted string using the first argument\nas a printf-like format string which can contain zero or more format\nspecifiers. Each specifier is replaced with the converted value from the\ncorresponding argument. Supported specifiers are:

      \n
        \n
      • %s: String will be used to convert all values except BigInt, Object\nand -0. BigInt values will be represented with an n and Objects that\nhave no user defined toString function are inspected using util.inspect()\nwith options { depth: 0, colors: false, compact: 3 }.
      • \n
      • %d: Number will be used to convert all values except BigInt and\nSymbol.
      • \n
      • %i: parseInt(value, 10) is used for all values except BigInt and\nSymbol.
      • \n
      • %f: parseFloat(value) is used for all values expect Symbol.
      • \n
      • %j: JSON. Replaced with the string '[Circular]' if the argument contains\ncircular references.
      • \n
      • %o: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() with options\n{ showHidden: true, showProxy: true }. This will show the full object\nincluding non-enumerable properties and proxies.
      • \n
      • %O: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() without options. This will show\nthe full object not including non-enumerable properties and proxies.
      • \n
      • %c: CSS. This specifier is ignored and will skip any CSS passed in.
      • \n
      • %%: single percent sign ('%'). This does not consume an argument.
      • \n
      • Returns: <string> The formatted string
      • \n
      \n

      If a specifier does not have a corresponding argument, it is not replaced:

      \n
      util.format('%s:%s', 'foo');\n// Returns: 'foo:%s'\n
      \n

      Values that are not part of the format string are formatted using\nutil.inspect() if their type is not string.

      \n

      If there are more arguments passed to the util.format() method than the\nnumber of specifiers, the extra arguments are concatenated to the returned\nstring, separated by spaces:

      \n
      util.format('%s:%s', 'foo', 'bar', 'baz');\n// Returns: 'foo:bar baz'\n
      \n

      If the first argument does not contain a valid format specifier, util.format()\nreturns a string that is the concatenation of all arguments separated by spaces:

      \n
      util.format(1, 2, 3);\n// Returns: '1 2 3'\n
      \n

      If only one argument is passed to util.format(), it is returned as it is\nwithout any formatting:

      \n
      util.format('%% %s');\n// Returns: '%% %s'\n
      \n

      util.format() is a synchronous method that is intended as a debugging tool.\nSome input values can have a significant performance overhead that can block the\nevent loop. Use this function with care and never in a hot code path.

      " + }, + { + "textRaw": "`util.formatWithOptions(inspectOptions, format[, ...args])`", + "type": "method", + "name": "formatWithOptions", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`inspectOptions` {Object}", + "name": "inspectOptions", + "type": "Object" + }, + { + "textRaw": "`format` {string}", + "name": "format", + "type": "string" + } + ] + } + ], + "desc": "

      This function is identical to util.format(), except in that it takes\nan inspectOptions argument which specifies options that are passed along to\nutil.inspect().

      \n
      util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });\n// Returns 'See object { foo: 42 }', where `42` is colored as a number\n// when printed to a terminal.\n
      " + }, + { + "textRaw": "`util.getSystemErrorName(err)`", + "type": "method", + "name": "getSystemErrorName", + "meta": { + "added": [ + "v9.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`err` {number}", + "name": "err", + "type": "number" + } + ] + } + ], + "desc": "

      Returns the string name for a numeric error code that comes from a Node.js API.\nThe mapping between error codes and error names is platform-dependent.\nSee Common System Errors for the names of common errors.

      \n
      fs.access('file/that/does/not/exist', (err) => {\n  const name = util.getSystemErrorName(err.errno);\n  console.error(name);  // ENOENT\n});\n
      " + }, + { + "textRaw": "`util.inherits(constructor, superConstructor)`", + "type": "method", + "name": "inherits", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3455", + "description": "The `constructor` parameter can refer to an ES6 class now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`constructor` {Function}", + "name": "constructor", + "type": "Function" + }, + { + "textRaw": "`superConstructor` {Function}", + "name": "superConstructor", + "type": "Function" + } + ] + } + ], + "desc": "

      Usage of util.inherits() is discouraged. Please use the ES6 class and\nextends keywords to get language level inheritance support. Also note\nthat the two styles are semantically incompatible.

      \n

      Inherit the prototype methods from one constructor into another. The\nprototype of constructor will be set to a new object created from\nsuperConstructor.

      \n

      This mainly adds some input validation on top of\nObject.setPrototypeOf(constructor.prototype, superConstructor.prototype).\nAs an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.

      \n
      const util = require('util');\nconst EventEmitter = require('events');\n\nfunction MyStream() {\n  EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, EventEmitter);\n\nMyStream.prototype.write = function(data) {\n  this.emit('data', data);\n};\n\nconst stream = new MyStream();\n\nconsole.log(stream instanceof EventEmitter); // true\nconsole.log(MyStream.super_ === EventEmitter); // true\n\nstream.on('data', (data) => {\n  console.log(`Received data: \"${data}\"`);\n});\nstream.write('It works!'); // Received data: \"It works!\"\n
      \n

      ES6 example using class and extends:

      \n
      const EventEmitter = require('events');\n\nclass MyStream extends EventEmitter {\n  write(data) {\n    this.emit('data', data);\n  }\n}\n\nconst stream = new MyStream();\n\nstream.on('data', (data) => {\n  console.log(`Received data: \"${data}\"`);\n});\nstream.write('With ES6');\n
      " + }, + { + "textRaw": "`util.inspect(object[, options])`", + "type": "method", + "name": "inspect", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": [ + "v14.6.0", + "v12.19.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/33690", + "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32392", + "description": "The `maxStringLength` option is supported now." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30768", + "description": "User defined prototype properties are inspected in case `showHidden` is `true`." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27109", + "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." + }, + { + "version": "v11.11.0", + "pr-url": "https://github.com/nodejs/node/pull/26269", + "description": "The `compact` option accepts numbers for a new output mode." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24971", + "description": "Internal properties no longer appear in the context argument of a custom inspection function." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25006", + "description": "ArrayBuffers now also show their binary contents." + }, + { + "version": "v11.5.0", + "pr-url": "https://github.com/nodejs/node/pull/24852", + "description": "The `getters` option is supported now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24326", + "description": "The `depth` default changed back to `2`." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22846", + "description": "The `depth` default changed to `20`." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22788", + "description": "The `sorted` option is supported now." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22756", + "description": "The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected." + }, + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/20725", + "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19259", + "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17576", + "description": "The `compact` option is supported now." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8174", + "description": "Custom inspection functions can now return `this`." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/7499", + "description": "The `breakLength` option is supported now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6334", + "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6465", + "description": "The `showProxy` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The representation of `object`.", + "name": "return", + "type": "string", + "desc": "The representation of `object`." + }, + "params": [ + { + "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", + "name": "object", + "type": "any", + "desc": "Any JavaScript primitive or `Object`." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", + "name": "showHidden", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties)." + }, + { + "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", + "name": "depth", + "type": "number", + "default": "`2`", + "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`." + }, + { + "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]. **Default:** `false`.", + "name": "colors", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]." + }, + { + "textRaw": "`customInspect` {boolean} If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked. **Default:** `true`.", + "name": "customInspect", + "type": "boolean", + "default": "`true`", + "desc": "If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked." + }, + { + "textRaw": "`showProxy` {boolean} If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects. **Default:** `false`.", + "name": "showProxy", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects." + }, + { + "textRaw": "`maxArrayLength` {integer} Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements. **Default:** `100`.", + "name": "maxArrayLength", + "type": "integer", + "default": "`100`", + "desc": "Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements." + }, + { + "textRaw": "`maxStringLength` {integer} Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters. **Default:** `Infinity`.", + "name": "maxStringLength", + "type": "integer", + "default": "`Infinity`", + "desc": "Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters." + }, + { + "textRaw": "`breakLength` {integer} The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`). **Default:** `80`.", + "name": "breakLength", + "type": "integer", + "default": "`80`", + "desc": "The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`)." + }, + { + "textRaw": "`compact` {boolean|integer} Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below. **Default:** `3`.", + "name": "compact", + "type": "boolean|integer", + "default": "`3`", + "desc": "Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below." + }, + { + "textRaw": "`sorted` {boolean|Function} If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][].", + "name": "sorted", + "type": "boolean|Function", + "desc": "If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][]." + }, + { + "textRaw": "`getters` {boolean|string} If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. **Default:** `false`.", + "name": "getters", + "type": "boolean|string", + "default": "`false`", + "desc": "If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function." + } + ] + } + ] + } + ], + "desc": "

      The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or @@toStringTag to make\nan identifiable tag for an inspected value.

      \n
      class Foo {\n  get [Symbol.toStringTag]() {\n    return 'bar';\n  }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz);       // '[foo] {}'\n
      \n

      Circular references are marked as '[Circular]':

      \n
      const { inspect } = require('util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// {\n//   a: [ [Circular] ],\n//   b: { inner: [Circular], obj: [Circular] }\n// }\n
      \n

      The following example inspects all properties of the util object:

      \n
      const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
      \n

      The following example highlights the effect of the compact option:

      \n
      const util = require('util');\n\nconst o = {\n  a: [1, 2, [[\n    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +\n      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',\n    'test',\n    'foo']], 4],\n  b: new Map([['za', 1], ['zb', 'test']])\n};\nconsole.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n//   [ 1,\n//     2,\n//     [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line\n//           'test',\n//           'foo' ] ],\n//     4 ],\n//   b: Map { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false changes the output to be more reader friendly.\nconsole.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n//   a: [\n//     1,\n//     2,\n//     [\n//       [\n//         'Lorem ipsum dolor sit amet, consectetur ' +\n//           'adipiscing elit, sed do eiusmod tempor ' +\n//           'incididunt ut labore et dolore magna ' +\n//           'aliqua.,\n//         'test',\n//         'foo'\n//       ]\n//     ],\n//     4\n//   ],\n//   b: Map {\n//     'za' => 1,\n//     'zb' => 'test'\n//   }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n// Reducing the `breakLength` will split the \"Lorem ipsum\" text in smaller\n// chunks.\n
      \n

      The showHidden option allows WeakMap and WeakSet entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\nWeakSet entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.

      \n
      const { inspect } = require('util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n
      \n

      The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().

      \n
      const { inspect } = require('util');\nconst assert = require('assert');\n\nconst o1 = {\n  b: [2, 3, 1],\n  a: '`a` comes before `b`',\n  c: new Set([2, 3, 1])\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n  c: new Set([2, 1, 3]),\n  a: '`a` comes before `b`',\n  b: [2, 3, 1]\n};\nassert.strict.equal(\n  inspect(o1, { sorted: true }),\n  inspect(o2, { sorted: true })\n);\n
      \n

      util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MB. Inputs that result in longer output will\nbe truncated.

      " + }, + { + "textRaw": "`util.inspect(object[, showHidden[, depth[, colors]]])`", + "type": "method", + "name": "inspect", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": [ + "v14.6.0", + "v12.19.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/33690", + "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32392", + "description": "The `maxStringLength` option is supported now." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30768", + "description": "User defined prototype properties are inspected in case `showHidden` is `true`." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27109", + "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." + }, + { + "version": "v11.11.0", + "pr-url": "https://github.com/nodejs/node/pull/26269", + "description": "The `compact` option accepts numbers for a new output mode." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24971", + "description": "Internal properties no longer appear in the context argument of a custom inspection function." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25006", + "description": "ArrayBuffers now also show their binary contents." + }, + { + "version": "v11.5.0", + "pr-url": "https://github.com/nodejs/node/pull/24852", + "description": "The `getters` option is supported now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24326", + "description": "The `depth` default changed back to `2`." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22846", + "description": "The `depth` default changed to `20`." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22788", + "description": "The `sorted` option is supported now." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22756", + "description": "The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected." + }, + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/20725", + "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19259", + "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17576", + "description": "The `compact` option is supported now." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8174", + "description": "Custom inspection functions can now return `this`." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/7499", + "description": "The `breakLength` option is supported now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6334", + "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6465", + "description": "The `showProxy` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The representation of `object`.", + "name": "return", + "type": "string", + "desc": "The representation of `object`." + }, + "params": [ + { + "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", + "name": "object", + "type": "any", + "desc": "Any JavaScript primitive or `Object`." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", + "name": "showHidden", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties)." + }, + { + "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", + "name": "depth", + "type": "number", + "default": "`2`", + "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`." + }, + { + "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]. **Default:** `false`.", + "name": "colors", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]." + }, + { + "textRaw": "`customInspect` {boolean} If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked. **Default:** `true`.", + "name": "customInspect", + "type": "boolean", + "default": "`true`", + "desc": "If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked." + }, + { + "textRaw": "`showProxy` {boolean} If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects. **Default:** `false`.", + "name": "showProxy", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects." + }, + { + "textRaw": "`maxArrayLength` {integer} Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements. **Default:** `100`.", + "name": "maxArrayLength", + "type": "integer", + "default": "`100`", + "desc": "Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements." + }, + { + "textRaw": "`maxStringLength` {integer} Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters. **Default:** `Infinity`.", + "name": "maxStringLength", + "type": "integer", + "default": "`Infinity`", + "desc": "Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters." + }, + { + "textRaw": "`breakLength` {integer} The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`). **Default:** `80`.", + "name": "breakLength", + "type": "integer", + "default": "`80`", + "desc": "The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`)." + }, + { + "textRaw": "`compact` {boolean|integer} Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below. **Default:** `3`.", + "name": "compact", + "type": "boolean|integer", + "default": "`3`", + "desc": "Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below." + }, + { + "textRaw": "`sorted` {boolean|Function} If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][].", + "name": "sorted", + "type": "boolean|Function", + "desc": "If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][]." + }, + { + "textRaw": "`getters` {boolean|string} If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. **Default:** `false`.", + "name": "getters", + "type": "boolean|string", + "default": "`false`", + "desc": "If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function." + } + ] + } + ] + } + ], + "desc": "

      The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or @@toStringTag to make\nan identifiable tag for an inspected value.

      \n
      class Foo {\n  get [Symbol.toStringTag]() {\n    return 'bar';\n  }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz);       // '[foo] {}'\n
      \n

      Circular references are marked as '[Circular]':

      \n
      const { inspect } = require('util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// {\n//   a: [ [Circular] ],\n//   b: { inner: [Circular], obj: [Circular] }\n// }\n
      \n

      The following example inspects all properties of the util object:

      \n
      const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
      \n

      The following example highlights the effect of the compact option:

      \n
      const util = require('util');\n\nconst o = {\n  a: [1, 2, [[\n    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +\n      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',\n    'test',\n    'foo']], 4],\n  b: new Map([['za', 1], ['zb', 'test']])\n};\nconsole.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n//   [ 1,\n//     2,\n//     [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line\n//           'test',\n//           'foo' ] ],\n//     4 ],\n//   b: Map { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false changes the output to be more reader friendly.\nconsole.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n//   a: [\n//     1,\n//     2,\n//     [\n//       [\n//         'Lorem ipsum dolor sit amet, consectetur ' +\n//           'adipiscing elit, sed do eiusmod tempor ' +\n//           'incididunt ut labore et dolore magna ' +\n//           'aliqua.,\n//         'test',\n//         'foo'\n//       ]\n//     ],\n//     4\n//   ],\n//   b: Map {\n//     'za' => 1,\n//     'zb' => 'test'\n//   }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n// Reducing the `breakLength` will split the \"Lorem ipsum\" text in smaller\n// chunks.\n
      \n

      The showHidden option allows WeakMap and WeakSet entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\nWeakSet entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.

      \n
      const { inspect } = require('util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n
      \n

      The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().

      \n
      const { inspect } = require('util');\nconst assert = require('assert');\n\nconst o1 = {\n  b: [2, 3, 1],\n  a: '`a` comes before `b`',\n  c: new Set([2, 3, 1])\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n  c: new Set([2, 1, 3]),\n  a: '`a` comes before `b`',\n  b: [2, 3, 1]\n};\nassert.strict.equal(\n  inspect(o1, { sorted: true }),\n  inspect(o2, { sorted: true })\n);\n
      \n

      util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MB. Inputs that result in longer output will\nbe truncated.

      ", + "miscs": [ + { + "textRaw": "Customizing `util.inspect` colors", + "name": "Customizing `util.inspect` colors", + "type": "misc", + "desc": "

      Color output (if enabled) of util.inspect is customizable globally\nvia the util.inspect.styles and util.inspect.colors properties.

      \n

      util.inspect.styles is a map associating a style name to a color from\nutil.inspect.colors.

      \n

      The default styles and associated colors are:

      \n
        \n
      • bigint: yellow
      • \n
      • boolean: yellow
      • \n
      • date: magenta
      • \n
      • module: underline
      • \n
      • name: (no styling)
      • \n
      • null: bold
      • \n
      • number: yellow
      • \n
      • regexp: red
      • \n
      • special: cyan (e.g., Proxies)
      • \n
      • string: green
      • \n
      • symbol: green
      • \n
      • undefined: grey
      • \n
      \n

      Color styling uses ANSI control codes that may not be supported on all\nterminals. To verify color support use tty.hasColors().

      \n

      Predefined control codes are listed below (grouped as \"Modifiers\", \"Foreground\ncolors\", and \"Background colors\").

      ", + "miscs": [ + { + "textRaw": "Modifiers", + "name": "modifiers", + "desc": "

      Modifier support varies throughout different terminals. They will mostly be\nignored, if not supported.

      \n
        \n
      • reset - Resets all (color) modifiers to their defaults
      • \n
      • bold - Make text bold
      • \n
      • italic - Make text italic
      • \n
      • underline - Make text underlined
      • \n
      • strikethrough - Puts a horizontal line through the center of the text\n(Alias: strikeThrough, crossedout, crossedOut)
      • \n
      • hidden - Prints the text, but makes it invisible (Alias: conceal)
      • \n
      • dim - Decreased color intensity (Alias:\nfaint)
      • \n
      • overlined - Make text overlined
      • \n
      • blink - Hides and shows the text in an interval
      • \n
      • inverse - Swap foreground and\nbackground colors (Alias: swapcolors, swapColors)
      • \n
      • doubleunderline - Make text\ndouble underlined (Alias: doubleUnderline)
      • \n
      • framed - Draw a frame around the text
      • \n
      ", + "type": "misc", + "displayName": "Modifiers" + }, + { + "textRaw": "Foreground colors", + "name": "foreground_colors", + "desc": "
        \n
      • black
      • \n
      • red
      • \n
      • green
      • \n
      • yellow
      • \n
      • blue
      • \n
      • magenta
      • \n
      • cyan
      • \n
      • white
      • \n
      • gray (alias: grey, blackBright)
      • \n
      • redBright
      • \n
      • greenBright
      • \n
      • yellowBright
      • \n
      • blueBright
      • \n
      • magentaBright
      • \n
      • cyanBright
      • \n
      • whiteBright
      • \n
      ", + "type": "misc", + "displayName": "Foreground colors" + }, + { + "textRaw": "Background colors", + "name": "background_colors", + "desc": "
        \n
      • bgBlack
      • \n
      • bgRed
      • \n
      • bgGreen
      • \n
      • bgYellow
      • \n
      • bgBlue
      • \n
      • bgMagenta
      • \n
      • bgCyan
      • \n
      • bgWhite
      • \n
      • bgGray (alias: bgGrey, bgBlackBright)
      • \n
      • bgRedBright
      • \n
      • bgGreenBright
      • \n
      • bgYellowBright
      • \n
      • bgBlueBright
      • \n
      • bgMagentaBright
      • \n
      • bgCyanBright
      • \n
      • bgWhiteBright
      • \n
      ", + "type": "misc", + "displayName": "Background colors" + } + ] + }, + { + "textRaw": "Custom inspection functions on objects", + "name": "Custom inspection functions on objects", + "type": "misc", + "desc": "

      Objects may also define their own\n[util.inspect.custom](depth, opts) function,\nwhich util.inspect() will invoke and use the result of when inspecting\nthe object:

      \n
      const util = require('util');\n\nclass Box {\n  constructor(value) {\n    this.value = value;\n  }\n\n  [util.inspect.custom](depth, options) {\n    if (depth < 0) {\n      return options.stylize('[Box]', 'special');\n    }\n\n    const newOptions = Object.assign({}, options, {\n      depth: options.depth === null ? null : options.depth - 1\n    });\n\n    // Five space padding because that's the size of \"Box< \".\n    const padding = ' '.repeat(5);\n    const inner = util.inspect(this.value, newOptions)\n                      .replace(/\\n/g, `\\n${padding}`);\n    return `${options.stylize('Box', 'special')}< ${inner} >`;\n  }\n}\n\nconst box = new Box(true);\n\nutil.inspect(box);\n// Returns: \"Box< true >\"\n
      \n

      Custom [util.inspect.custom](depth, opts) functions typically return a string\nbut may return a value of any type that will be formatted accordingly by\nutil.inspect().

      \n
      const util = require('util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj[util.inspect.custom] = (depth) => {\n  return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: \"{ bar: 'baz' }\"\n
      " + } + ], + "properties": [ + { + "textRaw": "`custom` {symbol} that can be used to declare custom inspect functions.", + "type": "symbol", + "name": "custom", + "meta": { + "added": [ + "v6.6.0" + ], + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/20857", + "description": "This is now defined as a shared symbol." + } + ] + }, + "desc": "

      In addition to being accessible through util.inspect.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.inspect.custom').

      \n
      const inspect = Symbol.for('nodejs.util.inspect.custom');\n\nclass Password {\n  constructor(value) {\n    this.value = value;\n  }\n\n  toString() {\n    return 'xxxxxxxx';\n  }\n\n  [inspect]() {\n    return `Password <${this.toString()}>`;\n  }\n}\n\nconst password = new Password('r0sebud');\nconsole.log(password);\n// Prints Password <xxxxxxxx>\n
      \n

      See Custom inspection functions on Objects for more details.

      ", + "shortDesc": "that can be used to declare custom inspect functions." + }, + { + "textRaw": "`util.inspect.defaultOptions`", + "name": "defaultOptions", + "meta": { + "added": [ + "v6.4.0" + ], + "changes": [] + }, + "desc": "

      The defaultOptions value allows customization of the default options used by\nutil.inspect. This is useful for functions like console.log or\nutil.format which implicitly call into util.inspect. It shall be set to an\nobject containing one or more valid util.inspect() options. Setting\noption properties directly is also supported.

      \n
      const util = require('util');\nconst arr = Array(101).fill(0);\n\nconsole.log(arr); // Logs the truncated array\nutil.inspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n
      " + } + ] + }, + { + "textRaw": "`util.isDeepStrictEqual(val1, val2)`", + "type": "method", + "name": "isDeepStrictEqual", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`val1` {any}", + "name": "val1", + "type": "any" + }, + { + "textRaw": "`val2` {any}", + "name": "val2", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if there is deep strict equality between val1 and val2.\nOtherwise, returns false.

      \n

      See assert.deepStrictEqual() for more information about deep strict\nequality.

      " + }, + { + "textRaw": "`util.promisify(original)`", + "type": "method", + "name": "promisify", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function}", + "name": "return", + "type": "Function" + }, + "params": [ + { + "textRaw": "`original` {Function}", + "name": "original", + "type": "Function" + } + ] + } + ], + "desc": "

      Takes a function following the common error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument, and returns a version\nthat returns promises.

      \n
      const util = require('util');\nconst fs = require('fs');\n\nconst stat = util.promisify(fs.stat);\nstat('.').then((stats) => {\n  // Do something with `stats`\n}).catch((error) => {\n  // Handle the error.\n});\n
      \n

      Or, equivalently using async functions:

      \n
      const util = require('util');\nconst fs = require('fs');\n\nconst stat = util.promisify(fs.stat);\n\nasync function callStat() {\n  const stats = await stat('.');\n  console.log(`This directory is owned by ${stats.uid}`);\n}\n
      \n

      If there is an original[util.promisify.custom] property present, promisify\nwill return its value, see Custom promisified functions.

      \n

      promisify() assumes that original is a function taking a callback as its\nfinal argument in all cases. If original is not a function, promisify()\nwill throw an error. If original is a function but its last argument is not\nan error-first callback, it will still be passed an error-first\ncallback as its last argument.

      \n

      Using promisify() on class methods or other methods that use this may not\nwork as expected unless handled specially:

      \n
      const util = require('util');\n\nclass Foo {\n  constructor() {\n    this.a = 42;\n  }\n\n  bar(callback) {\n    callback(null, this.a);\n  }\n}\n\nconst foo = new Foo();\n\nconst naiveBar = util.promisify(foo.bar);\n// TypeError: Cannot read property 'a' of undefined\n// naiveBar().then(a => console.log(a));\n\nnaiveBar.call(foo).then((a) => console.log(a)); // '42'\n\nconst bindBar = naiveBar.bind(foo);\nbindBar().then((a) => console.log(a)); // '42'\n
      ", + "modules": [ + { + "textRaw": "Custom promisified functions", + "name": "custom_promisified_functions", + "desc": "

      Using the util.promisify.custom symbol one can override the return value of\nutil.promisify():

      \n
      const util = require('util');\n\nfunction doSomething(foo, callback) {\n  // ...\n}\n\ndoSomething[util.promisify.custom] = (foo) => {\n  return getPromiseSomehow();\n};\n\nconst promisified = util.promisify(doSomething);\nconsole.log(promisified === doSomething[util.promisify.custom]);\n// prints 'true'\n
      \n

      This can be useful for cases where the original function does not follow the\nstandard format of taking an error-first callback as the last argument.

      \n

      For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):

      \n
      doSomething[util.promisify.custom] = (foo) => {\n  return new Promise((resolve, reject) => {\n    doSomething(foo, resolve, reject);\n  });\n};\n
      \n

      If promisify.custom is defined but is not a function, promisify() will\nthrow an error.

      ", + "type": "module", + "displayName": "Custom promisified functions" + } + ], + "properties": [ + { + "textRaw": "`custom` {symbol} that can be used to declare custom promisified variants of functions, see [Custom promisified functions][].", + "type": "symbol", + "name": "custom", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [ + { + "version": "v12.16.2", + "pr-url": "https://github.com/nodejs/node/pull/31672", + "description": "This is now defined as a shared symbol." + } + ] + }, + "desc": "

      In addition to being accessible through util.promisify.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.promisify.custom').

      \n

      For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):

      \n
      const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');\n\ndoSomething[kCustomPromisifiedSymbol] = (foo) => {\n  return new Promise((resolve, reject) => {\n    doSomething(foo, resolve, reject);\n  });\n};\n
      ", + "shortDesc": "that can be used to declare custom promisified variants of functions, see [Custom promisified functions][]." + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: `util.TextDecoder`", + "type": "class", + "name": "util.TextDecoder", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "desc": "

      An implementation of the WHATWG Encoding Standard TextDecoder API.

      \n
      const decoder = new TextDecoder('shift_jis');\nlet string = '';\nlet buffer;\nwhile (buffer = getNextChunkSomehow()) {\n  string += decoder.decode(buffer, { stream: true });\n}\nstring += decoder.decode(); // end-of-stream\n
      ", + "modules": [ + { + "textRaw": "WHATWG supported encodings", + "name": "whatwg_supported_encodings", + "desc": "

      Per the WHATWG Encoding Standard, the encodings supported by the\nTextDecoder API are outlined in the tables below. For each encoding,\none or more aliases may be used.

      \n

      Different Node.js build configurations support different sets of encodings.\nWhile a very basic set of encodings is supported even on Node.js builds without\nICU enabled, support for some encodings is provided only when Node.js is built\nwith ICU and using the full ICU data (see Internationalization).

      ", + "modules": [ + { + "textRaw": "Encodings Supported Without ICU", + "name": "encodings_supported_without_icu", + "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      ", + "type": "module", + "displayName": "Encodings Supported Without ICU" + }, + { + "textRaw": "Encodings Supported by Default (With ICU)", + "name": "encodings_supported_by_default_(with_icu)", + "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      'utf-16be'
      ", + "type": "module", + "displayName": "Encodings Supported by Default (With ICU)" + }, + { + "textRaw": "Encodings requiring full ICU data", + "name": "encodings_requiring_full_icu_data", + "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      EncodingAliases
      'ibm866''866', 'cp866', 'csibm866'
      'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
      'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
      'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
      'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
      'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
      'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
      'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
      'iso-8859-8-i''csiso88598i', 'logical'
      'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
      'iso-8859-13''iso8859-13', 'iso885913'
      'iso-8859-14''iso8859-14', 'iso885914'
      'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
      'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
      'koi8-u''koi8-ru'
      'macintosh''csmacintosh', 'mac', 'x-mac-roman'
      'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
      'windows-1250''cp1250', 'x-cp1250'
      'windows-1251''cp1251', 'x-cp1251'
      'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
      'windows-1253''cp1253', 'x-cp1253'
      'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
      'windows-1255''cp1255', 'x-cp1255'
      'windows-1256''cp1256', 'x-cp1256'
      'windows-1257''cp1257', 'x-cp1257'
      'windows-1258''cp1258', 'x-cp1258'
      'x-mac-cyrillic''x-mac-ukrainian'
      'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
      'gb18030'
      'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
      'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
      'iso-2022-jp''csiso2022jp'
      'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
      'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
      \n

      The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard\nis not supported.

      ", + "type": "module", + "displayName": "Encodings requiring full ICU data" + } + ], + "type": "module", + "displayName": "WHATWG supported encodings" + } + ], + "methods": [ + { + "textRaw": "`textDecoder.decode([input[, options]])`", + "type": "method", + "name": "decode", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data.", + "name": "input", + "type": "ArrayBuffer|DataView|TypedArray", + "desc": "An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`stream` {boolean} `true` if additional chunks of data are expected. **Default:** `false`.", + "name": "stream", + "type": "boolean", + "default": "`false`", + "desc": "`true` if additional chunks of data are expected." + } + ] + } + ] + } + ], + "desc": "

      Decodes the input and returns a string. If options.stream is true, any\nincomplete byte sequences occurring at the end of the input are buffered\ninternally and emitted after the next call to textDecoder.decode().

      \n

      If textDecoder.fatal is true, decoding errors that occur will result in a\nTypeError being thrown.

      " + } + ], + "properties": [ + { + "textRaw": "`encoding` {string}", + "type": "string", + "name": "encoding", + "desc": "

      The encoding supported by the TextDecoder instance.

      " + }, + { + "textRaw": "`fatal` {boolean}", + "type": "boolean", + "name": "fatal", + "desc": "

      The value will be true if decoding errors result in a TypeError being\nthrown.

      " + }, + { + "textRaw": "`ignoreBOM` {boolean}", + "type": "boolean", + "name": "ignoreBOM", + "desc": "

      The value will be true if the decoding result will include the byte order\nmark.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`encoding` {string} Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf-8'`", + "desc": "Identifies the `encoding` that this `TextDecoder` instance supports." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`fatal` {boolean} `true` if decoding failures are fatal. This option is only supported when ICU is enabled (see [Internationalization][]). **Default:** `false`.", + "name": "fatal", + "type": "boolean", + "default": "`false`", + "desc": "`true` if decoding failures are fatal. This option is only supported when ICU is enabled (see [Internationalization][])." + }, + { + "textRaw": "`ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`.", + "name": "ignoreBOM", + "type": "boolean", + "default": "`false`", + "desc": "When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`." + } + ] + } + ], + "desc": "

      Creates an new TextDecoder instance. The encoding may specify one of the\nsupported encodings or an alias.

      \n

      The TextDecoder class is also available on the global object.

      " + } + ] + }, + { + "textRaw": "Class: `util.TextEncoder`", + "type": "class", + "name": "util.TextEncoder", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "v11.0.0", + "description": "The class is now available on the global object." + } + ] + }, + "desc": "

      An implementation of the WHATWG Encoding Standard TextEncoder API. All\ninstances of TextEncoder only support UTF-8 encoding.

      \n
      const encoder = new TextEncoder();\nconst uint8array = encoder.encode('this is some data');\n
      \n

      The TextEncoder class is also available on the global object.

      ", + "methods": [ + { + "textRaw": "`textEncoder.encode([input])`", + "type": "method", + "name": "encode", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Uint8Array}", + "name": "return", + "type": "Uint8Array" + }, + "params": [ + { + "textRaw": "`input` {string} The text to encode. **Default:** an empty string.", + "name": "input", + "type": "string", + "default": "an empty string", + "desc": "The text to encode." + } + ] + } + ], + "desc": "

      UTF-8 encodes the input string and returns a Uint8Array containing the\nencoded bytes.

      " + }, + { + "textRaw": "`textEncoder.encodeInto(src, dest)`", + "type": "method", + "name": "encodeInto", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`read` {number} The read Unicode code units of src.", + "name": "read", + "type": "number", + "desc": "The read Unicode code units of src." + }, + { + "textRaw": "`written` {number} The written UTF-8 bytes of dest.", + "name": "written", + "type": "number", + "desc": "The written UTF-8 bytes of dest." + } + ] + }, + "params": [ + { + "textRaw": "`src` {string} The text to encode.", + "name": "src", + "type": "string", + "desc": "The text to encode." + }, + { + "textRaw": "`dest` {Uint8Array} The array to hold the encode result.", + "name": "dest", + "type": "Uint8Array", + "desc": "The array to hold the encode result." + } + ] + } + ], + "desc": "

      UTF-8 encodes the src string to the dest Uint8Array and returns an object\ncontaining the read Unicode code units and written UTF-8 bytes.

      \n
      const encoder = new TextEncoder();\nconst src = 'this is some data';\nconst dest = new Uint8Array(10);\nconst { read, written } = encoder.encodeInto(src, dest);\n
      " + } + ], + "properties": [ + { + "textRaw": "`encoding` {string}", + "type": "string", + "name": "encoding", + "desc": "

      The encoding supported by the TextEncoder instance. Always set to 'utf-8'.

      " + } + ] + } + ], + "properties": [ + { + "textRaw": "`util.types`", + "name": "types", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      util.types provides type checks for different kinds of built-in objects.\nUnlike instanceof or Object.prototype.toString.call(value), these checks do\nnot inspect properties of the object that are accessible from JavaScript (like\ntheir prototype), and usually have the overhead of calling into C++.

      \n

      The result generally does not make any guarantees about what kinds of\nproperties or behavior a value exposes in JavaScript. They are primarily\nuseful for addon developers who prefer to do type checking in JavaScript.

      ", + "methods": [ + { + "textRaw": "`util.types.isAnyArrayBuffer(value)`", + "type": "method", + "name": "isAnyArrayBuffer", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in ArrayBuffer or\nSharedArrayBuffer instance.

      \n

      See also util.types.isArrayBuffer() and\nutil.types.isSharedArrayBuffer().

      \n
      util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true\nutil.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isArrayBufferView(value)`", + "type": "method", + "name": "isArrayBufferView", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an instance of one of the ArrayBuffer\nviews, such as typed array objects or DataView. Equivalent to\nArrayBuffer.isView().

      \n
      util.types.isArrayBufferView(new Int8Array());  // true\nutil.types.isArrayBufferView(Buffer.from('hello world')); // true\nutil.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true\nutil.types.isArrayBufferView(new ArrayBuffer());  // false\n
      " + }, + { + "textRaw": "`util.types.isArgumentsObject(value)`", + "type": "method", + "name": "isArgumentsObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an arguments object.

      \n\n
      function foo() {\n  util.types.isArgumentsObject(arguments);  // Returns true\n}\n
      " + }, + { + "textRaw": "`util.types.isArrayBuffer(value)`", + "type": "method", + "name": "isArrayBuffer", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in ArrayBuffer instance.\nThis does not include SharedArrayBuffer instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.

      \n
      util.types.isArrayBuffer(new ArrayBuffer());  // Returns true\nutil.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isAsyncFunction(value)`", + "type": "method", + "name": "isAsyncFunction", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an async function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

      \n
      util.types.isAsyncFunction(function foo() {});  // Returns false\nutil.types.isAsyncFunction(async function foo() {});  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isBigInt64Array(value)`", + "type": "method", + "name": "isBigInt64Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a BigInt64Array instance.

      \n
      util.types.isBigInt64Array(new BigInt64Array());   // Returns true\nutil.types.isBigInt64Array(new BigUint64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isBigUint64Array(value)`", + "type": "method", + "name": "isBigUint64Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a BigUint64Array instance.

      \n
      util.types.isBigUint64Array(new BigInt64Array());   // Returns false\nutil.types.isBigUint64Array(new BigUint64Array());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isBooleanObject(value)`", + "type": "method", + "name": "isBooleanObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a boolean object, e.g. created\nby new Boolean().

      \n
      util.types.isBooleanObject(false);  // Returns false\nutil.types.isBooleanObject(true);   // Returns false\nutil.types.isBooleanObject(new Boolean(false)); // Returns true\nutil.types.isBooleanObject(new Boolean(true));  // Returns true\nutil.types.isBooleanObject(Boolean(false)); // Returns false\nutil.types.isBooleanObject(Boolean(true));  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isBoxedPrimitive(value)`", + "type": "method", + "name": "isBoxedPrimitive", + "meta": { + "added": [ + "v10.11.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is any boxed primitive object, e.g. created\nby new Boolean(), new String() or Object(Symbol()).

      \n

      For example:

      \n
      util.types.isBoxedPrimitive(false); // Returns false\nutil.types.isBoxedPrimitive(new Boolean(false)); // Returns true\nutil.types.isBoxedPrimitive(Symbol('foo')); // Returns false\nutil.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true\nutil.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true\n
      " + }, + { + "textRaw": "`util.types.isDataView(value)`", + "type": "method", + "name": "isDataView", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in DataView instance.

      \n
      const ab = new ArrayBuffer(20);\nutil.types.isDataView(new DataView(ab));  // Returns true\nutil.types.isDataView(new Float64Array());  // Returns false\n
      \n

      See also ArrayBuffer.isView().

      " + }, + { + "textRaw": "`util.types.isDate(value)`", + "type": "method", + "name": "isDate", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Date instance.

      \n
      util.types.isDate(new Date());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isExternal(value)`", + "type": "method", + "name": "isExternal", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a native External value.

      \n

      A native External value is a special type of object that contains a\nraw C++ pointer (void*) for access from native code, and has no other\nproperties. Such objects are created either by Node.js internals or native\naddons. In JavaScript, they are frozen objects with a\nnull prototype.

      \n
      #include <js_native_api.h>\n#include <stdlib.h>\nnapi_value result;\nstatic napi_value MyNapi(napi_env env, napi_callback_info info) {\n  int* raw = (int*) malloc(1024);\n  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);\n  if (status != napi_ok) {\n    napi_throw_error(env, NULL, \"napi_create_external failed\");\n    return NULL;\n  }\n  return result;\n}\n...\nDECLARE_NAPI_PROPERTY(\"myNapi\", MyNapi)\n...\n
      \n
      const native = require('napi_addon.node');\nconst data = native.myNapi();\nutil.types.isExternal(data); // returns true\nutil.types.isExternal(0); // returns false\nutil.types.isExternal(new String('foo')); // returns false\n
      \n

      For further information on napi_create_external, refer to\nnapi_create_external().

      " + }, + { + "textRaw": "`util.types.isFloat32Array(value)`", + "type": "method", + "name": "isFloat32Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Float32Array instance.

      \n
      util.types.isFloat32Array(new ArrayBuffer());  // Returns false\nutil.types.isFloat32Array(new Float32Array());  // Returns true\nutil.types.isFloat32Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isFloat64Array(value)`", + "type": "method", + "name": "isFloat64Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Float64Array instance.

      \n
      util.types.isFloat64Array(new ArrayBuffer());  // Returns false\nutil.types.isFloat64Array(new Uint8Array());  // Returns false\nutil.types.isFloat64Array(new Float64Array());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isGeneratorFunction(value)`", + "type": "method", + "name": "isGeneratorFunction", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

      \n
      util.types.isGeneratorFunction(function foo() {});  // Returns false\nutil.types.isGeneratorFunction(function* foo() {});  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isGeneratorObject(value)`", + "type": "method", + "name": "isGeneratorObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a generator object as returned from a\nbuilt-in generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

      \n
      function* foo() {}\nconst generator = foo();\nutil.types.isGeneratorObject(generator);  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isInt8Array(value)`", + "type": "method", + "name": "isInt8Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Int8Array instance.

      \n
      util.types.isInt8Array(new ArrayBuffer());  // Returns false\nutil.types.isInt8Array(new Int8Array());  // Returns true\nutil.types.isInt8Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isInt16Array(value)`", + "type": "method", + "name": "isInt16Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Int16Array instance.

      \n
      util.types.isInt16Array(new ArrayBuffer());  // Returns false\nutil.types.isInt16Array(new Int16Array());  // Returns true\nutil.types.isInt16Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isInt32Array(value)`", + "type": "method", + "name": "isInt32Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Int32Array instance.

      \n
      util.types.isInt32Array(new ArrayBuffer());  // Returns false\nutil.types.isInt32Array(new Int32Array());  // Returns true\nutil.types.isInt32Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isMap(value)`", + "type": "method", + "name": "isMap", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Map instance.

      \n
      util.types.isMap(new Map());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isMapIterator(value)`", + "type": "method", + "name": "isMapIterator", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an iterator returned for a built-in\nMap instance.

      \n
      const map = new Map();\nutil.types.isMapIterator(map.keys());  // Returns true\nutil.types.isMapIterator(map.values());  // Returns true\nutil.types.isMapIterator(map.entries());  // Returns true\nutil.types.isMapIterator(map[Symbol.iterator]());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isModuleNamespaceObject(value)`", + "type": "method", + "name": "isModuleNamespaceObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an instance of a Module Namespace Object.

      \n\n
      import * as ns from './a.js';\n\nutil.types.isModuleNamespaceObject(ns);  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isNativeError(value)`", + "type": "method", + "name": "isNativeError", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an instance of a built-in Error type.

      \n
      util.types.isNativeError(new Error());  // Returns true\nutil.types.isNativeError(new TypeError());  // Returns true\nutil.types.isNativeError(new RangeError());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isNumberObject(value)`", + "type": "method", + "name": "isNumberObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a number object, e.g. created\nby new Number().

      \n
      util.types.isNumberObject(0);  // Returns false\nutil.types.isNumberObject(new Number(0));   // Returns true\n
      " + }, + { + "textRaw": "`util.types.isPromise(value)`", + "type": "method", + "name": "isPromise", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Promise.

      \n
      util.types.isPromise(Promise.resolve(42));  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isProxy(value)`", + "type": "method", + "name": "isProxy", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a Proxy instance.

      \n
      const target = {};\nconst proxy = new Proxy(target, {});\nutil.types.isProxy(target);  // Returns false\nutil.types.isProxy(proxy);  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isRegExp(value)`", + "type": "method", + "name": "isRegExp", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a regular expression object.

      \n
      util.types.isRegExp(/abc/);  // Returns true\nutil.types.isRegExp(new RegExp('abc'));  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSet(value)`", + "type": "method", + "name": "isSet", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Set instance.

      \n
      util.types.isSet(new Set());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSetIterator(value)`", + "type": "method", + "name": "isSetIterator", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an iterator returned for a built-in\nSet instance.

      \n
      const set = new Set();\nutil.types.isSetIterator(set.keys());  // Returns true\nutil.types.isSetIterator(set.values());  // Returns true\nutil.types.isSetIterator(set.entries());  // Returns true\nutil.types.isSetIterator(set[Symbol.iterator]());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSharedArrayBuffer(value)`", + "type": "method", + "name": "isSharedArrayBuffer", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in SharedArrayBuffer instance.\nThis does not include ArrayBuffer instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.

      \n
      util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false\nutil.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isStringObject(value)`", + "type": "method", + "name": "isStringObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a string object, e.g. created\nby new String().

      \n
      util.types.isStringObject('foo');  // Returns false\nutil.types.isStringObject(new String('foo'));   // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSymbolObject(value)`", + "type": "method", + "name": "isSymbolObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a symbol object, created\nby calling Object() on a Symbol primitive.

      \n
      const symbol = Symbol('foo');\nutil.types.isSymbolObject(symbol);  // Returns false\nutil.types.isSymbolObject(Object(symbol));   // Returns true\n
      " + }, + { + "textRaw": "`util.types.isTypedArray(value)`", + "type": "method", + "name": "isTypedArray", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in TypedArray instance.

      \n
      util.types.isTypedArray(new ArrayBuffer());  // Returns false\nutil.types.isTypedArray(new Uint8Array());  // Returns true\nutil.types.isTypedArray(new Float64Array());  // Returns true\n
      \n

      See also ArrayBuffer.isView().

      " + }, + { + "textRaw": "`util.types.isUint8Array(value)`", + "type": "method", + "name": "isUint8Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint8Array instance.

      \n
      util.types.isUint8Array(new ArrayBuffer());  // Returns false\nutil.types.isUint8Array(new Uint8Array());  // Returns true\nutil.types.isUint8Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isUint8ClampedArray(value)`", + "type": "method", + "name": "isUint8ClampedArray", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint8ClampedArray instance.

      \n
      util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false\nutil.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true\nutil.types.isUint8ClampedArray(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isUint16Array(value)`", + "type": "method", + "name": "isUint16Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint16Array instance.

      \n
      util.types.isUint16Array(new ArrayBuffer());  // Returns false\nutil.types.isUint16Array(new Uint16Array());  // Returns true\nutil.types.isUint16Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isUint32Array(value)`", + "type": "method", + "name": "isUint32Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint32Array instance.

      \n
      util.types.isUint32Array(new ArrayBuffer());  // Returns false\nutil.types.isUint32Array(new Uint32Array());  // Returns true\nutil.types.isUint32Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isWeakMap(value)`", + "type": "method", + "name": "isWeakMap", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in WeakMap instance.

      \n
      util.types.isWeakMap(new WeakMap());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isWeakSet(value)`", + "type": "method", + "name": "isWeakSet", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in WeakSet instance.

      \n
      util.types.isWeakSet(new WeakSet());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isWebAssemblyCompiledModule(value)`", + "type": "method", + "name": "isWebAssemblyCompiledModule", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in WebAssembly.Module instance.

      \n
      const module = new WebAssembly.Module(wasmBuffer);\nutil.types.isWebAssemblyCompiledModule(module);  // Returns true\n
      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Deprecated APIs", + "name": "deprecated_apis", + "desc": "

      The following APIs are deprecated and should no longer be used. Existing\napplications and modules should be updated to find alternative approaches.

      ", + "methods": [ + { + "textRaw": "`util._extend(target, source)`", + "type": "method", + "name": "_extend", + "meta": { + "added": [ + "v0.7.5" + ], + "deprecated": [ + "v6.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Object.assign()`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`target` {Object}", + "name": "target", + "type": "Object" + }, + { + "textRaw": "`source` {Object}", + "name": "source", + "type": "Object" + } + ] + } + ], + "desc": "

      The util._extend() method was never intended to be used outside of internal\nNode.js modules. The community found and used it anyway.

      \n

      It is deprecated and should not be used in new code. JavaScript comes with very\nsimilar built-in functionality through Object.assign().

      " + }, + { + "textRaw": "`util.isArray(object)`", + "type": "method", + "name": "isArray", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Array.isArray()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Alias for Array.isArray().

      \n

      Returns true if the given object is an Array. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isArray([]);\n// Returns: true\nutil.isArray(new Array());\n// Returns: true\nutil.isArray({});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isBoolean(object)`", + "type": "method", + "name": "isBoolean", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'boolean'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Boolean. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isBoolean(1);\n// Returns: false\nutil.isBoolean(0);\n// Returns: false\nutil.isBoolean(false);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isBuffer(object)`", + "type": "method", + "name": "isBuffer", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Buffer.isBuffer()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Buffer. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isBuffer({ length: 0 });\n// Returns: false\nutil.isBuffer([]);\n// Returns: false\nutil.isBuffer(Buffer.from('hello world'));\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isDate(object)`", + "type": "method", + "name": "isDate", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`util.types.isDate()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Date. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isDate(new Date());\n// Returns: true\nutil.isDate(Date());\n// false (without 'new' returns a String)\nutil.isDate({});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isError(object)`", + "type": "method", + "name": "isError", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`util.types.isNativeError()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is an Error. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nutil.isError(new Error());\n// Returns: true\nutil.isError(new TypeError());\n// Returns: true\nutil.isError({ name: 'Error', message: 'an error occurred' });\n// Returns: false\n
      \n

      This method relies on Object.prototype.toString() behavior. It is\npossible to obtain an incorrect result when the object argument manipulates\n@@toStringTag.

      \n
      const util = require('util');\nconst obj = { name: 'Error', message: 'an error occurred' };\n\nutil.isError(obj);\n// Returns: false\nobj[Symbol.toStringTag] = 'Error';\nutil.isError(obj);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isFunction(object)`", + "type": "method", + "name": "isFunction", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'function'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Function. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nfunction Foo() {}\nconst Bar = () => {};\n\nutil.isFunction({});\n// Returns: false\nutil.isFunction(Foo);\n// Returns: true\nutil.isFunction(Bar);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isNull(object)`", + "type": "method", + "name": "isNull", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `value === null` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is strictly null. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nutil.isNull(0);\n// Returns: false\nutil.isNull(undefined);\n// Returns: false\nutil.isNull(null);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isNullOrUndefined(object)`", + "type": "method", + "name": "isNullOrUndefined", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use\n`value === undefined || value === null` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is null or undefined. Otherwise,\nreturns false.

      \n
      const util = require('util');\n\nutil.isNullOrUndefined(0);\n// Returns: false\nutil.isNullOrUndefined(undefined);\n// Returns: true\nutil.isNullOrUndefined(null);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isNumber(object)`", + "type": "method", + "name": "isNumber", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'number'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Number. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isNumber(false);\n// Returns: false\nutil.isNumber(Infinity);\n// Returns: true\nutil.isNumber(0);\n// Returns: true\nutil.isNumber(NaN);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isObject(object)`", + "type": "method", + "name": "isObject", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated:\nUse `value !== null && typeof value === 'object'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is strictly an Object and not a\nFunction (even though functions are objects in JavaScript).\nOtherwise, returns false.

      \n
      const util = require('util');\n\nutil.isObject(5);\n// Returns: false\nutil.isObject(null);\n// Returns: false\nutil.isObject({});\n// Returns: true\nutil.isObject(() => {});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isPrimitive(object)`", + "type": "method", + "name": "isPrimitive", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use\n`(typeof value !== 'object' && typeof value !== 'function') || value === null`\ninstead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a primitive type. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nutil.isPrimitive(5);\n// Returns: true\nutil.isPrimitive('foo');\n// Returns: true\nutil.isPrimitive(false);\n// Returns: true\nutil.isPrimitive(null);\n// Returns: true\nutil.isPrimitive(undefined);\n// Returns: true\nutil.isPrimitive({});\n// Returns: false\nutil.isPrimitive(() => {});\n// Returns: false\nutil.isPrimitive(/^$/);\n// Returns: false\nutil.isPrimitive(new Date());\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isRegExp(object)`", + "type": "method", + "name": "isRegExp", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a RegExp. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isRegExp(/some regexp/);\n// Returns: true\nutil.isRegExp(new RegExp('another regexp'));\n// Returns: true\nutil.isRegExp({});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isString(object)`", + "type": "method", + "name": "isString", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'string'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a string. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isString('');\n// Returns: true\nutil.isString('foo');\n// Returns: true\nutil.isString(String('foo'));\n// Returns: true\nutil.isString(5);\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isSymbol(object)`", + "type": "method", + "name": "isSymbol", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'symbol'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Symbol. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isSymbol(5);\n// Returns: false\nutil.isSymbol('foo');\n// Returns: false\nutil.isSymbol(Symbol('foo'));\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isUndefined(object)`", + "type": "method", + "name": "isUndefined", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `value === undefined` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is undefined. Otherwise, returns false.

      \n
      const util = require('util');\n\nconst foo = undefined;\nutil.isUndefined(5);\n// Returns: false\nutil.isUndefined(foo);\n// Returns: true\nutil.isUndefined(null);\n// Returns: false\n
      " + }, + { + "textRaw": "`util.log(string)`", + "type": "method", + "name": "log", + "meta": { + "added": [ + "v0.3.0" + ], + "deprecated": [ + "v6.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use a third party module instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The util.log() method prints the given string to stdout with an included\ntimestamp.

      \n
      const util = require('util');\n\nutil.log('Timestamped message.');\n
      " + } + ], + "type": "module", + "displayName": "Deprecated APIs" + } + ], + "type": "module", + "displayName": "Util" + }, + { + "textRaw": "V8", + "name": "v8", + "introduced_in": "v4.0.0", + "desc": "

      Source Code: lib/v8.js

      \n

      The v8 module exposes APIs that are specific to the version of V8\nbuilt into the Node.js binary. It can be accessed using:

      \n
      const v8 = require('v8');\n
      \n

      The APIs and implementation are subject to change at any time.

      ", + "methods": [ + { + "textRaw": "`v8.cachedDataVersionTag()`", + "type": "method", + "name": "cachedDataVersionTag", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns an integer representing a \"version tag\" derived from the V8 version,\ncommand line flags and detected CPU features. This is useful for determining\nwhether a vm.Script cachedData buffer is compatible with this instance\nof V8.

      " + }, + { + "textRaw": "`v8.getHeapSpaceStatistics()`", + "type": "method", + "name": "getHeapSpaceStatistics", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [ + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10186", + "description": "Support values exceeding the 32-bit unsigned integer range." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object[]}", + "name": "return", + "type": "Object[]" + }, + "params": [] + } + ], + "desc": "

      Returns statistics about the V8 heap spaces, i.e. the segments which make up\nthe V8 heap. Neither the ordering of heap spaces, nor the availability of a\nheap space can be guaranteed as the statistics are provided via the V8\nGetHeapSpaceStatistics function and may change from one V8 version to the\nnext.

      \n

      The value returned is an array of objects containing the following properties:

      \n\n
      [\n  {\n    \"space_name\": \"new_space\",\n    \"space_size\": 2063872,\n    \"space_used_size\": 951112,\n    \"space_available_size\": 80824,\n    \"physical_space_size\": 2063872\n  },\n  {\n    \"space_name\": \"old_space\",\n    \"space_size\": 3090560,\n    \"space_used_size\": 2493792,\n    \"space_available_size\": 0,\n    \"physical_space_size\": 3090560\n  },\n  {\n    \"space_name\": \"code_space\",\n    \"space_size\": 1260160,\n    \"space_used_size\": 644256,\n    \"space_available_size\": 960,\n    \"physical_space_size\": 1260160\n  },\n  {\n    \"space_name\": \"map_space\",\n    \"space_size\": 1094160,\n    \"space_used_size\": 201608,\n    \"space_available_size\": 0,\n    \"physical_space_size\": 1094160\n  },\n  {\n    \"space_name\": \"large_object_space\",\n    \"space_size\": 0,\n    \"space_used_size\": 0,\n    \"space_available_size\": 1490980608,\n    \"physical_space_size\": 0\n  }\n]\n
      " + }, + { + "textRaw": "`v8.getHeapSnapshot()`", + "type": "method", + "name": "getHeapSnapshot", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Readable} A Readable Stream containing the V8 heap snapshot", + "name": "return", + "type": "stream.Readable", + "desc": "A Readable Stream containing the V8 heap snapshot" + }, + "params": [] + } + ], + "desc": "

      Generates a snapshot of the current V8 heap and returns a Readable\nStream that may be used to read the JSON serialized representation.\nThis JSON stream format is intended to be used with tools such as\nChrome DevTools. The JSON schema is undocumented and specific to the\nV8 engine, and may change from one version of V8 to the next.

      \n
      const stream = v8.getHeapSnapshot();\nstream.pipe(process.stdout);\n
      " + }, + { + "textRaw": "`v8.getHeapStatistics()`", + "type": "method", + "name": "getHeapStatistics", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/8610", + "description": "Added `malloced_memory`, `peak_malloced_memory`, and `does_zap_garbage`." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10186", + "description": "Support values exceeding the 32-bit unsigned integer range." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object with the following properties:

      \n\n

      does_zap_garbage is a 0/1 boolean, which signifies whether the\n--zap_code_space option is enabled or not. This makes V8 overwrite heap\ngarbage with a bit pattern. The RSS footprint (resident memory set) gets bigger\nbecause it continuously touches all heap pages and that makes them less likely\nto get swapped out by the operating system.

      \n

      number_of_native_contexts The value of native_context is the number of the\ntop-level contexts currently active. Increase of this number over time indicates\na memory leak.

      \n

      number_of_detached_contexts The value of detached_context is the number\nof contexts that were detached and not yet garbage collected. This number\nbeing non-zero indicates a potential memory leak.

      \n\n
      {\n  total_heap_size: 7326976,\n  total_heap_size_executable: 4194304,\n  total_physical_size: 7326976,\n  total_available_size: 1152656,\n  used_heap_size: 3476208,\n  heap_size_limit: 1535115264,\n  malloced_memory: 16384,\n  peak_malloced_memory: 1127496,\n  does_zap_garbage: 0,\n  number_of_native_contexts: 1,\n  number_of_detached_contexts: 0\n}\n
      " + }, + { + "textRaw": "`v8.getHeapCodeStatistics()`", + "type": "method", + "name": "getHeapCodeStatistics", + "meta": { + "added": [ + "v12.8.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object with the following properties:

      \n\n\n
      {\n  code_and_metadata_size: 212208,\n  bytecode_and_metadata_size: 161368,\n  external_script_source_size: 1410794\n}\n
      " + }, + { + "textRaw": "`v8.setFlagsFromString(flags)`", + "type": "method", + "name": "setFlagsFromString", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`flags` {string}", + "name": "flags", + "type": "string" + } + ] + } + ], + "desc": "

      The v8.setFlagsFromString() method can be used to programmatically set\nV8 command line flags. This method should be used with care. Changing settings\nafter the VM has started may result in unpredictable behavior, including\ncrashes and data loss; or it may simply do nothing.

      \n

      The V8 options available for a version of Node.js may be determined by running\nnode --v8-options.

      \n

      Usage:

      \n
      // Print GC events to stdout for one minute.\nconst v8 = require('v8');\nv8.setFlagsFromString('--trace_gc');\nsetTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);\n
      " + }, + { + "textRaw": "`v8.takeCoverage()`", + "type": "method", + "name": "takeCoverage", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The v8.takeCoverage() method allows the user to write the coverage started by\nNODE_V8_COVERAGE to disk on demand. This method can be invoked multiple\ntimes during the lifetime of the process, each time the execution counter will\nbe reset and a new coverage report will be written to the directory specified\nby NODE_V8_COVERAGE.

      \n

      When the process is about to exit, one last coverage will still be written to\ndisk, unless v8.stopCoverage() is invoked before the process exits.

      " + }, + { + "textRaw": "`v8.stopCoverage()`", + "type": "method", + "name": "stopCoverage", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The v8.stopCoverage() method allows the user to stop the coverage collection\nstarted by NODE_V8_COVERAGE, so that V8 can release the execution count\nrecords and optimize code. This can be used in conjunction with\nv8.takeCoverage() if the user wants to collect the coverage on demand.

      " + }, + { + "textRaw": "`v8.writeHeapSnapshot([filename])`", + "type": "method", + "name": "writeHeapSnapshot", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The filename where the snapshot was saved.", + "name": "return", + "type": "string", + "desc": "The filename where the snapshot was saved." + }, + "params": [ + { + "textRaw": "`filename` {string} The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread.", + "name": "filename", + "type": "string", + "desc": "The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread." + } + ] + } + ], + "desc": "

      Generates a snapshot of the current V8 heap and writes it to a JSON\nfile. This file is intended to be used with tools such as Chrome\nDevTools. The JSON schema is undocumented and specific to the V8\nengine, and may change from one version of V8 to the next.

      \n

      A heap snapshot is specific to a single V8 isolate. When using\nworker threads, a heap snapshot generated from the main thread will\nnot contain any information about the workers, and vice versa.

      \n
      const { writeHeapSnapshot } = require('v8');\nconst {\n  Worker,\n  isMainThread,\n  parentPort\n} = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n\n  worker.once('message', (filename) => {\n    console.log(`worker heapdump: ${filename}`);\n    // Now get a heapdump for the main thread.\n    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);\n  });\n\n  // Tell the worker to create a heapdump.\n  worker.postMessage('heapdump');\n} else {\n  parentPort.once('message', (message) => {\n    if (message === 'heapdump') {\n      // Generate a heapdump for the worker\n      // and return the filename to the parent.\n      parentPort.postMessage(writeHeapSnapshot());\n    }\n  });\n}\n
      " + } + ], + "modules": [ + { + "textRaw": "Serialization API", + "name": "serialization_api", + "desc": "

      The serialization API provides means of serializing JavaScript values in a way\nthat is compatible with the HTML structured clone algorithm.

      \n

      The format is backward-compatible (i.e. safe to store to disk).\nEqual JavaScript values may result in different serialized output.

      ", + "methods": [ + { + "textRaw": "`v8.serialize(value)`", + "type": "method", + "name": "serialize", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Uses a DefaultSerializer to serialize value into a buffer.

      " + }, + { + "textRaw": "`v8.deserialize(buffer)`", + "type": "method", + "name": "deserialize", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serialize()`][].", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A buffer returned by [`serialize()`][]." + } + ] + } + ], + "desc": "

      Uses a DefaultDeserializer with default options to read a JS value\nfrom a buffer.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `v8.Serializer`", + "type": "class", + "name": "v8.Serializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "methods": [ + { + "textRaw": "`serializer.writeHeader()`", + "type": "method", + "name": "writeHeader", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Writes out a header, which includes the serialization format version.

      " + }, + { + "textRaw": "`serializer.writeValue(value)`", + "type": "method", + "name": "writeValue", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Serializes a JavaScript value and adds the serialized representation to the\ninternal buffer.

      \n

      This throws an error if value cannot be serialized.

      " + }, + { + "textRaw": "`serializer.releaseBuffer()`", + "type": "method", + "name": "releaseBuffer", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [] + } + ], + "desc": "

      Returns the stored internal buffer. This serializer should not be used once\nthe buffer is released. Calling this method results in undefined behavior\nif a previous write has failed.

      " + }, + { + "textRaw": "`serializer.transferArrayBuffer(id, arrayBuffer)`", + "type": "method", + "name": "transferArrayBuffer", + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {integer} A 32-bit unsigned integer.", + "name": "id", + "type": "integer", + "desc": "A 32-bit unsigned integer." + }, + { + "textRaw": "`arrayBuffer` {ArrayBuffer} An `ArrayBuffer` instance.", + "name": "arrayBuffer", + "type": "ArrayBuffer", + "desc": "An `ArrayBuffer` instance." + } + ] + } + ], + "desc": "

      Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the deserializing context to\ndeserializer.transferArrayBuffer().

      " + }, + { + "textRaw": "`serializer.writeUint32(value)`", + "type": "method", + "name": "writeUint32", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {integer}", + "name": "value", + "type": "integer" + } + ] + } + ], + "desc": "

      Write a raw 32-bit unsigned integer.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer.writeUint64(hi, lo)`", + "type": "method", + "name": "writeUint64", + "signatures": [ + { + "params": [ + { + "textRaw": "`hi` {integer}", + "name": "hi", + "type": "integer" + }, + { + "textRaw": "`lo` {integer}", + "name": "lo", + "type": "integer" + } + ] + } + ], + "desc": "

      Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer.writeDouble(value)`", + "type": "method", + "name": "writeDouble", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {number}", + "name": "value", + "type": "number" + } + ] + } + ], + "desc": "

      Write a JS number value.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer.writeRawBytes(buffer)`", + "type": "method", + "name": "writeRawBytes", + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + } + ] + } + ], + "desc": "

      Write raw bytes into the serializer’s internal buffer. The deserializer\nwill require a way to compute the length of the buffer.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer._writeHostObject(object)`", + "type": "method", + "name": "_writeHostObject", + "signatures": [ + { + "params": [ + { + "textRaw": "`object` {Object}", + "name": "object", + "type": "Object" + } + ] + } + ], + "desc": "

      This method is called to write some kind of host object, i.e. an object created\nby native C++ bindings. If it is not possible to serialize object, a suitable\nexception should be thrown.

      \n

      This method is not present on the Serializer class itself but can be provided\nby subclasses.

      " + }, + { + "textRaw": "`serializer._getDataCloneError(message)`", + "type": "method", + "name": "_getDataCloneError", + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      This method is called to generate error objects that will be thrown when an\nobject can not be cloned.

      \n

      This method defaults to the Error constructor and can be overridden on\nsubclasses.

      " + }, + { + "textRaw": "`serializer._getSharedArrayBufferId(sharedArrayBuffer)`", + "type": "method", + "name": "_getSharedArrayBufferId", + "signatures": [ + { + "params": [ + { + "textRaw": "`sharedArrayBuffer` {SharedArrayBuffer}", + "name": "sharedArrayBuffer", + "type": "SharedArrayBuffer" + } + ] + } + ], + "desc": "

      This method is called when the serializer is going to serialize a\nSharedArrayBuffer object. It must return an unsigned 32-bit integer ID for\nthe object, using the same ID if this SharedArrayBuffer has already been\nserialized. When deserializing, this ID will be passed to\ndeserializer.transferArrayBuffer().

      \n

      If the object cannot be serialized, an exception should be thrown.

      \n

      This method is not present on the Serializer class itself but can be provided\nby subclasses.

      " + }, + { + "textRaw": "`serializer._setTreatArrayBufferViewsAsHostObjects(flag)`", + "type": "method", + "name": "_setTreatArrayBufferViewsAsHostObjects", + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` {boolean} **Default:** `false`", + "name": "flag", + "type": "boolean", + "default": "`false`" + } + ] + } + ], + "desc": "

      Indicate whether to treat TypedArray and DataView objects as\nhost objects, i.e. pass them to serializer._writeHostObject().

      " + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Creates a new Serializer object.

      " + } + ] + }, + { + "textRaw": "Class: `v8.Deserializer`", + "type": "class", + "name": "v8.Deserializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "methods": [ + { + "textRaw": "`deserializer.readHeader()`", + "type": "method", + "name": "readHeader", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Reads and validates a header (including the format version).\nMay, for example, reject an invalid or unsupported wire format. In that case,\nan Error is thrown.

      " + }, + { + "textRaw": "`deserializer.readValue()`", + "type": "method", + "name": "readValue", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Deserializes a JavaScript value from the buffer and returns it.

      " + }, + { + "textRaw": "`deserializer.transferArrayBuffer(id, arrayBuffer)`", + "type": "method", + "name": "transferArrayBuffer", + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {integer} A 32-bit unsigned integer.", + "name": "id", + "type": "integer", + "desc": "A 32-bit unsigned integer." + }, + { + "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An `ArrayBuffer` instance.", + "name": "arrayBuffer", + "type": "ArrayBuffer|SharedArrayBuffer", + "desc": "An `ArrayBuffer` instance." + } + ] + } + ], + "desc": "

      Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the serializing context to\nserializer.transferArrayBuffer() (or return the id from\nserializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).

      " + }, + { + "textRaw": "`deserializer.getWireFormatVersion()`", + "type": "method", + "name": "getWireFormatVersion", + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Reads the underlying wire format version. Likely mostly to be useful to\nlegacy code reading old wire format versions. May not be called before\n.readHeader().

      " + }, + { + "textRaw": "`deserializer.readUint32()`", + "type": "method", + "name": "readUint32", + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Read a raw 32-bit unsigned integer and return it.\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer.readUint64()`", + "type": "method", + "name": "readUint64", + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer[]}", + "name": "return", + "type": "integer[]" + }, + "params": [] + } + ], + "desc": "

      Read a raw 64-bit unsigned integer and return it as an array [hi, lo]\nwith two 32-bit unsigned integer entries.\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer.readDouble()`", + "type": "method", + "name": "readDouble", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [] + } + ], + "desc": "

      Read a JS number value.\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer.readRawBytes(length)`", + "type": "method", + "name": "readRawBytes", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + } + ] + } + ], + "desc": "

      Read raw bytes from the deserializer’s internal buffer. The length parameter\nmust correspond to the length of the buffer that was passed to\nserializer.writeRawBytes().\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer._readHostObject()`", + "type": "method", + "name": "_readHostObject", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This method is called to read some kind of host object, i.e. an object that is\ncreated by native C++ bindings. If it is not possible to deserialize the data,\na suitable exception should be thrown.

      \n

      This method is not present on the Deserializer class itself but can be\nprovided by subclasses.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serializer.releaseBuffer()`][].", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A buffer returned by [`serializer.releaseBuffer()`][]." + } + ], + "desc": "

      Creates a new Deserializer object.

      " + } + ] + }, + { + "textRaw": "Class: `v8.DefaultSerializer`", + "type": "class", + "name": "v8.DefaultSerializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      A subclass of Serializer that serializes TypedArray\n(in particular Buffer) and DataView objects as host objects, and only\nstores the part of their underlying ArrayBuffers that they are referring to.

      " + }, + { + "textRaw": "Class: `v8.DefaultDeserializer`", + "type": "class", + "name": "v8.DefaultDeserializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      A subclass of Deserializer corresponding to the format written by\nDefaultSerializer.

      " + } + ], + "type": "module", + "displayName": "Serialization API" + } + ], + "type": "module", + "displayName": "V8" + }, + { + "textRaw": "VM (executing JavaScript)", + "name": "vm", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/vm.js

      \n

      The vm module enables compiling and running code within V8 Virtual\nMachine contexts. The vm module is not a security mechanism. Do\nnot use it to run untrusted code.

      \n

      JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.

      \n

      A common use case is to run the code in a different V8 Context. This means\ninvoked code has a different global object than the invoking code.

      \n

      One can provide the context by contextifying an\nobject. The invoked code treats any property in the context like a\nglobal variable. Any changes to global variables caused by the invoked\ncode are reflected in the context object.

      \n
      const vm = require('vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\nvm.createContext(context); // Contextify the object.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the context.\n// Initially, x has the value 2 because that is the value of context.x.\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
      ", + "classes": [ + { + "textRaw": "Class: `vm.Script`", + "type": "class", + "name": "vm.Script", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [] + }, + "desc": "

      Instances of the vm.Script class contain precompiled scripts that can be\nexecuted in specific contexts.

      ", + "methods": [ + { + "textRaw": "`script.createCachedData()`", + "type": "method", + "name": "createCachedData", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [] + } + ], + "desc": "

      Creates a code cache that can be used with the Script constructor's\ncachedData option. Returns a Buffer. This method may be called at any\ntime and any number of times.

      \n
      const script = new vm.Script(`\nfunction add(a, b) {\n  return a + b;\n}\n\nconst x = add(1, 2);\n`);\n\nconst cacheWithoutX = script.createCachedData();\n\nscript.runInThisContext();\n\nconst cacheWithX = script.createCachedData();\n
      " + }, + { + "textRaw": "`script.runInContext(contextifiedObject[, options])`", + "type": "method", + "name": "runInContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`contextifiedObject` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", + "name": "contextifiedObject", + "type": "Object", + "desc": "A [contextified][] object as returned by the `vm.createContext()` method." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + } + ] + } + ] + } + ], + "desc": "

      Runs the compiled code contained by the vm.Script object within the given\ncontextifiedObject and returns the result. Running code does not have access\nto local scope.

      \n

      The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the context object.

      \n
      const vm = require('vm');\n\nconst context = {\n  animal: 'cat',\n  count: 2\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nvm.createContext(context);\nfor (let i = 0; i < 10; ++i) {\n  script.runInContext(context);\n}\n\nconsole.log(context);\n// Prints: { animal: 'cat', count: 12, name: 'kitty' }\n
      \n

      Using the timeout or breakOnSigint options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.

      " + }, + { + "textRaw": "`script.runInNewContext([contextObject[, options]])`", + "type": "method", + "name": "runInNewContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19016", + "description": "The `contextCodeGeneration` option is supported now." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", + "name": "contextObject", + "type": "Object", + "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", + "name": "contextName", + "type": "string", + "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", + "desc": "Human-readable name of the newly created context." + }, + { + "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", + "name": "contextOrigin", + "type": "string", + "default": "`''`", + "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." + }, + { + "textRaw": "`contextCodeGeneration` {Object}", + "name": "contextCodeGeneration", + "type": "Object", + "options": [ + { + "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", + "name": "strings", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." + }, + { + "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", + "name": "wasm", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." + } + ] + } + ] + } + ] + } + ], + "desc": "

      First contextifies the given contextObject, runs the compiled code contained\nby the vm.Script object within the created context, and returns the result.\nRunning code does not have access to local scope.

      \n

      The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual context.

      \n
      const vm = require('vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst contexts = [{}, {}, {}];\ncontexts.forEach((context) => {\n  script.runInNewContext(context);\n});\n\nconsole.log(contexts);\n// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
      " + }, + { + "textRaw": "`script.runInThisContext([options])`", + "type": "method", + "name": "runInThisContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + } + ] + } + ] + } + ], + "desc": "

      Runs the compiled code contained by the vm.Script within the context of the\ncurrent global object. Running code does not have access to local scope, but\ndoes have access to the current global object.

      \n

      The following example compiles code that increments a global variable then\nexecutes that code multiple times:

      \n
      const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ], + "desc": "

      If options is a string, then it specifies the filename.

      \n

      Creating a new vm.Script object compiles code but does not run it. The\ncompiled vm.Script can be run later multiple times. The code is not bound to\nany global object; rather, it is bound before each run, just for that run.

      " + } + ] + }, + { + "textRaw": "Class: `vm.Module`", + "type": "class", + "name": "vm.Module", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      This feature is only available with the --experimental-vm-modules command\nflag enabled.

      \n

      The vm.Module class provides a low-level interface for using\nECMAScript modules in VM contexts. It is the counterpart of the vm.Script\nclass that closely mirrors Module Records as defined in the ECMAScript\nspecification.

      \n

      Unlike vm.Script however, every vm.Module object is bound to a context from\nits creation. Operations on vm.Module objects are intrinsically asynchronous,\nin contrast with the synchronous nature of vm.Script objects. The use of\n'async' functions can help with manipulating vm.Module objects.

      \n

      Using a vm.Module object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.

      \n

      This implementation lies at a lower level than the ECMAScript Module\nloader. There is also no way to interact with the Loader yet, though\nsupport is planned.

      \n
      const vm = require('vm');\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\n(async () => {\n  // Step 1\n  //\n  // Create a Module by constructing a new `vm.SourceTextModule` object. This\n  // parses the provided source text, throwing a `SyntaxError` if anything goes\n  // wrong. By default, a Module is created in the top context. But here, we\n  // specify `contextifiedObject` as the context this Module belongs to.\n  //\n  // Here, we attempt to obtain the default export from the module \"foo\", and\n  // put it into local binding \"secret\".\n\n  const bar = new vm.SourceTextModule(`\n    import s from 'foo';\n    s;\n  `, { context: contextifiedObject });\n\n  // Step 2\n  //\n  // \"Link\" the imported dependencies of this Module to it.\n  //\n  // The provided linking callback (the \"linker\") accepts two arguments: the\n  // parent module (`bar` in this case) and the string that is the specifier of\n  // the imported module. The callback is expected to return a Module that\n  // corresponds to the provided specifier, with certain requirements documented\n  // in `module.link()`.\n  //\n  // If linking has not started for the returned Module, the same linker\n  // callback will be called on the returned Module.\n  //\n  // Even top-level Modules without dependencies must be explicitly linked. The\n  // callback provided would never be called, however.\n  //\n  // The link() method returns a Promise that will be resolved when all the\n  // Promises returned by the linker resolve.\n  //\n  // Note: This is a contrived example in that the linker function creates a new\n  // \"foo\" module every time it is called. In a full-fledged module system, a\n  // cache would probably be used to avoid duplicated modules.\n\n  async function linker(specifier, referencingModule) {\n    if (specifier === 'foo') {\n      return new vm.SourceTextModule(`\n        // The \"secret\" variable refers to the global variable we added to\n        // \"contextifiedObject\" when creating the context.\n        export default secret;\n      `, { context: referencingModule.context });\n\n      // Using `contextifiedObject` instead of `referencingModule.context`\n      // here would work as well.\n    }\n    throw new Error(`Unable to resolve dependency: ${specifier}`);\n  }\n  await bar.link(linker);\n\n  // Step 3\n  //\n  // Evaluate the Module. The evaluate() method returns a Promise with a single\n  // property \"result\" that contains the result of the very last statement\n  // executed in the Module. In the case of `bar`, it is `s;`, which refers to\n  // the default export of the `foo` module, the `secret` we set in the\n  // beginning to 42.\n\n  const { result } = await bar.evaluate();\n\n  console.log(result);\n  // Prints 42.\n})();\n
      ", + "properties": [ + { + "textRaw": "`dependencySpecifiers` {string[]}", + "type": "string[]", + "name": "dependencySpecifiers", + "desc": "

      The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.

      \n

      Corresponds to the [[RequestedModules]] field of Cyclic Module Records in\nthe ECMAScript specification.

      " + }, + { + "textRaw": "`error` {any}", + "type": "any", + "name": "error", + "desc": "

      If the module.status is 'errored', this property contains the exception\nthrown by the module during evaluation. If the status is anything else,\naccessing this property will result in a thrown exception.

      \n

      The value undefined cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with throw undefined;.

      \n

      Corresponds to the [[EvaluationError]] field of Cyclic Module Records\nin the ECMAScript specification.

      " + }, + { + "textRaw": "`namespace` {Object}", + "type": "Object", + "name": "namespace", + "desc": "

      The namespace object of the module. This is only available after linking\n(module.link()) has completed.

      \n

      Corresponds to the GetModuleNamespace abstract operation in the ECMAScript\nspecification.

      " + }, + { + "textRaw": "`status` {string}", + "type": "string", + "name": "status", + "desc": "

      The current status of the module. Will be one of:

      \n
        \n
      • \n

        'unlinked': module.link() has not yet been called.

        \n
      • \n
      • \n

        'linking': module.link() has been called, but not all Promises returned\nby the linker function have been resolved yet.

        \n
      • \n
      • \n

        'linked': The module has been linked successfully, and all of its\ndependencies are linked, but module.evaluate() has not yet been called.

        \n
      • \n
      • \n

        'evaluating': The module is being evaluated through a module.evaluate() on\nitself or a parent module.

        \n
      • \n
      • \n

        'evaluated': The module has been successfully evaluated.

        \n
      • \n
      • \n

        'errored': The module has been evaluated, but an exception was thrown.

        \n
      • \n
      \n

      Other than 'errored', this status string corresponds to the specification's\nCyclic Module Record's [[Status]] field. 'errored' corresponds to\n'evaluated' in the specification, but with [[EvaluationError]] set to a\nvalue that is not undefined.

      " + }, + { + "textRaw": "`identifier` {string}", + "type": "string", + "name": "identifier", + "desc": "

      The identifier of the current module, as set in the constructor.

      " + } + ], + "methods": [ + { + "textRaw": "`module.evaluate([options])`", + "type": "method", + "name": "evaluate", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is interrupted, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is interrupted, an [`Error`][] will be thrown." + } + ] + } + ] + } + ], + "desc": "

      Evaluate the module.

      \n

      This must be called after the module has been linked; otherwise it will\nthrow an error. It could be called also when the module has already been\nevaluated, in which case it will do one of the following two things:

      \n
        \n
      • return undefined if the initial evaluation ended in success (module.status\nis 'evaluated')
      • \n
      • rethrow the same exception the initial evaluation threw if the initial\nevaluation ended in an error (module.status is 'errored')
      • \n
      \n

      This method cannot be called while the module is being evaluated\n(module.status is 'evaluating') to prevent infinite recursion.

      \n

      Corresponds to the Evaluate() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.

      " + }, + { + "textRaw": "`module.link(linker)`", + "type": "method", + "name": "link", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`linker` {Function}", + "name": "linker", + "type": "Function", + "options": [ + { + "textRaw": "`specifier` {string} The specifier of the requested module:```js import foo from 'foo'; // ^^^^^ the module specifier ```", + "name": "specifier", + "type": "string", + "desc": "The specifier of the requested module:```js import foo from 'foo'; // ^^^^^ the module specifier ```" + }, + { + "textRaw": "`referencingModule` {vm.Module} The `Module` object `link()` is called on.", + "name": "referencingModule", + "type": "vm.Module", + "desc": "The `Module` object `link()` is called on." + }, + { + "textRaw": "Returns: {vm.Module|Promise}", + "name": "return", + "type": "vm.Module|Promise" + } + ] + } + ] + } + ], + "desc": "

      Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.

      \n

      The function is expected to return a Module object or a Promise that\neventually resolves to a Module object. The returned Module must satisfy the\nfollowing two invariants:

      \n
        \n
      • It must belong to the same context as the parent Module.
      • \n
      • Its status must not be 'errored'.
      • \n
      \n

      If the returned Module's status is 'unlinked', this method will be\nrecursively called on the returned Module with the same provided linker\nfunction.

      \n

      link() returns a Promise that will either get resolved when all linking\ninstances resolve to a valid Module, or rejected if the linker function either\nthrows an exception or returns an invalid Module.

      \n

      The linker function roughly corresponds to the implementation-defined\nHostResolveImportedModule abstract operation in the ECMAScript\nspecification, with a few key differences:

      \n\n

      The actual HostResolveImportedModule implementation used during module\nlinking is one that returns the modules linked during linking. Since at\nthat point all modules would have been fully linked already, the\nHostResolveImportedModule implementation is fully synchronous per\nspecification.

      \n

      Corresponds to the Link() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.

      " + } + ] + }, + { + "textRaw": "Class: `vm.SourceTextModule`", + "type": "class", + "name": "vm.SourceTextModule", + "meta": { + "added": [ + "v9.6.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      This feature is only available with the --experimental-vm-modules command\nflag enabled.

      \n\n

      The vm.SourceTextModule class provides the Source Text Module Record as\ndefined in the ECMAScript specification.

      ", + "methods": [ + { + "textRaw": "`sourceTextModule.createCachedData()`", + "type": "method", + "name": "createCachedData", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [] + } + ], + "desc": "

      Creates a code cache that can be used with the SourceTextModule constructor's\ncachedData option. Returns a Buffer. This method may be called any number\nof times before the module has been evaluated.

      \n
      // Create an initial module\nconst module = new vm.SourceTextModule('const a = 1;');\n\n// Create cached data from this module\nconst cachedData = module.createCachedData();\n\n// Create a new module using the cached data. The code must be the same.\nconst module2 = new vm.SourceTextModule('const a = 1;', { cachedData });\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {string} JavaScript Module code to parse", + "name": "code", + "type": "string", + "desc": "JavaScript Module code to parse" + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", + "name": "identifier", + "type": "string", + "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", + "desc": "String used in stack traces." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created." + }, + { + "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", + "name": "context", + "type": "Object", + "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." + }, + { + "textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", + "name": "lineOffset", + "type": "integer", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`." + }, + { + "textRaw": "`columnOffset` {integer} Specifies the column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", + "name": "columnOffset", + "type": "integer", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this `Module`." + }, + { + "textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.", + "name": "initializeImportMeta", + "type": "Function", + "desc": "Called during evaluation of this `Module` to initialize the `import.meta`.", + "options": [ + { + "textRaw": "`meta` {import.meta}", + "name": "meta", + "type": "import.meta" + }, + { + "textRaw": "`module` {vm.SourceTextModule}", + "name": "module", + "type": "vm.SourceTextModule" + } + ] + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ], + "desc": "

      Creates a new SourceTextModule instance.

      \n

      Properties assigned to the import.meta object that are objects may\nallow the module to access information outside the specified context. Use\nvm.runInContext() to create objects in a specific context.

      \n
      const vm = require('vm');\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\n(async () => {\n  const module = new vm.SourceTextModule(\n    'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n    {\n      initializeImportMeta(meta) {\n        // Note: this object is created in the top context. As such,\n        // Object.getPrototypeOf(import.meta.prop) points to the\n        // Object.prototype in the top context rather than that in\n        // the contextified object.\n        meta.prop = {};\n      }\n    });\n  // Since module has no dependencies, the linker function will never be called.\n  await module.link(() => {});\n  await module.evaluate();\n\n  // Now, Object.prototype.secret will be equal to 42.\n  //\n  // To fix this problem, replace\n  //     meta.prop = {};\n  // above with\n  //     meta.prop = vm.runInContext('{}', contextifiedObject);\n})();\n
      " + } + ] + }, + { + "textRaw": "Class: `vm.SyntheticModule`", + "type": "class", + "name": "vm.SyntheticModule", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      This feature is only available with the --experimental-vm-modules command\nflag enabled.

      \n\n

      The vm.SyntheticModule class provides the Synthetic Module Record as\ndefined in the WebIDL specification. The purpose of synthetic modules is to\nprovide a generic interface for exposing non-JavaScript sources to ECMAScript\nmodule graphs.

      \n
      const vm = require('vm');\n\nconst source = '{ \"a\": 1 }';\nconst module = new vm.SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `module` in linking...\n
      ", + "methods": [ + { + "textRaw": "`syntheticModule.setExport(name, value)`", + "type": "method", + "name": "setExport", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string} Name of the export to set.", + "name": "name", + "type": "string", + "desc": "Name of the export to set." + }, + { + "textRaw": "`value` {any} The value to set the export to.", + "name": "value", + "type": "any", + "desc": "The value to set the export to." + } + ] + } + ], + "desc": "

      This method is used after the module is linked to set the values of exports. If\nit is called before the module is linked, an ERR_VM_MODULE_STATUS error\nwill be thrown.

      \n
      const vm = require('vm');\n\n(async () => {\n  const m = new vm.SyntheticModule(['x'], () => {\n    m.setExport('x', 1);\n  });\n\n  await m.link(() => {});\n  await m.evaluate();\n\n  assert.strictEqual(m.namespace.x, 1);\n})();\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`exportNames` {string[]} Array of names that will be exported from the module.", + "name": "exportNames", + "type": "string[]", + "desc": "Array of names that will be exported from the module." + }, + { + "textRaw": "`evaluateCallback` {Function} Called when the module is evaluated.", + "name": "evaluateCallback", + "type": "Function", + "desc": "Called when the module is evaluated." + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", + "name": "identifier", + "type": "string", + "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", + "desc": "String used in stack traces." + }, + { + "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", + "name": "context", + "type": "Object", + "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." + } + ] + } + ], + "desc": "

      Creates a new SyntheticModule instance.

      \n

      Objects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified context. Use\nvm.runInContext() to create objects in a specific context.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`vm.compileFunction(code[, params[, options]])`", + "type": "method", + "name": "compileFunction", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function}", + "name": "return", + "type": "Function" + }, + "params": [ + { + "textRaw": "`code` {string} The body of the function to compile.", + "name": "code", + "type": "string", + "desc": "The body of the function to compile." + }, + { + "textRaw": "`params` {string[]} An array of strings containing all parameters for the function.", + "name": "params", + "type": "string[]", + "desc": "An array of strings containing all parameters for the function." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `''`.", + "name": "filename", + "type": "string", + "default": "`''`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." + }, + { + "textRaw": "`produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "Specifies whether to produce new cache data." + }, + { + "textRaw": "`parsingContext` {Object} The [contextified][] object in which the said function should be compiled in.", + "name": "parsingContext", + "type": "Object", + "desc": "The [contextified][] object in which the said function should be compiled in." + }, + { + "textRaw": "`contextExtensions` {Object[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`.", + "name": "contextExtensions", + "type": "Object[]", + "default": "`[]`", + "desc": "An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling." + } + ] + } + ] + } + ], + "desc": "

      Compiles the given code into the provided context (if no context is\nsupplied, the current context is used), and returns it wrapped inside a\nfunction with the given params.

      " + }, + { + "textRaw": "`vm.createContext([contextObject[, options]])`", + "type": "method", + "name": "createContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19398", + "description": "The first argument can no longer be a function." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19016", + "description": "The `codeGeneration` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} contextified object.", + "name": "return", + "type": "Object", + "desc": "contextified object." + }, + "params": [ + { + "textRaw": "`contextObject` {Object}", + "name": "contextObject", + "type": "Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`name` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", + "name": "name", + "type": "string", + "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", + "desc": "Human-readable name of the newly created context." + }, + { + "textRaw": "`origin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", + "name": "origin", + "type": "string", + "default": "`''`", + "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." + }, + { + "textRaw": "`codeGeneration` {Object}", + "name": "codeGeneration", + "type": "Object", + "options": [ + { + "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", + "name": "strings", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." + }, + { + "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", + "name": "wasm", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." + } + ] + } + ] + } + ] + } + ], + "desc": "

      If given a contextObject, the vm.createContext() method will prepare\nthat object so that it can be used in calls to\nvm.runInContext() or script.runInContext(). Inside such scripts,\nthe contextObject will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.

      \n
      const vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\nvm.createContext(context);\n\nvm.runInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n
      \n

      If contextObject is omitted (or passed explicitly as undefined), a new,\nempty contextified object will be returned.

      \n

      The vm.createContext() method is primarily useful for creating a single\ncontext that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single context representing a\nwindow's global object, then run all <script> tags together within that\ncontext.

      \n

      The provided name and origin of the context are made visible through the\nInspector API.

      " + }, + { + "textRaw": "`vm.isContext(object)`", + "type": "method", + "name": "isContext", + "meta": { + "added": [ + "v0.11.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {Object}", + "name": "object", + "type": "Object" + } + ] + } + ], + "desc": "

      Returns true if the given oject object has been contextified using\nvm.createContext().

      " + }, + { + "textRaw": "`vm.runInContext(code, contextifiedObject[, options])`", + "type": "method", + "name": "runInContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile and run.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile and run." + }, + { + "textRaw": "`contextifiedObject` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.", + "name": "contextifiedObject", + "type": "Object", + "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ] + } + ], + "desc": "

      The vm.runInContext() method compiles code, runs it within the context of\nthe contextifiedObject, then returns the result. Running code does not have\naccess to the local scope. The contextifiedObject object must have been\npreviously contextified using the vm.createContext() method.

      \n

      If options is a string, then it specifies the filename.

      \n

      The following example compiles and executes different scripts using a single\ncontextified object:

      \n
      const vm = require('vm');\n\nconst contextObject = { globalVar: 1 };\nvm.createContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  vm.runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n
      " + }, + { + "textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`", + "type": "method", + "name": "runInNewContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19016", + "description": "The `contextCodeGeneration` option is supported now." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile and run.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile and run." + }, + { + "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", + "name": "contextObject", + "type": "Object", + "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", + "name": "contextName", + "type": "string", + "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", + "desc": "Human-readable name of the newly created context." + }, + { + "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", + "name": "contextOrigin", + "type": "string", + "default": "`''`", + "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." + }, + { + "textRaw": "`contextCodeGeneration` {Object}", + "name": "contextCodeGeneration", + "type": "Object", + "options": [ + { + "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", + "name": "strings", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." + }, + { + "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", + "name": "wasm", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." + } + ] + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ] + } + ], + "desc": "

      The vm.runInNewContext() first contextifies the given contextObject (or\ncreates a new contextObject if passed as undefined), compiles the code,\nruns it within the created context, then returns the result. Running code\ndoes not have access to the local scope.

      \n

      If options is a string, then it specifies the filename.

      \n

      The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the contextObject.

      \n
      const vm = require('vm');\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n
      " + }, + { + "textRaw": "`vm.runInThisContext(code[, options])`", + "type": "method", + "name": "runInThisContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile and run.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile and run." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ] + } + ], + "desc": "

      vm.runInThisContext() compiles code, runs it within the context of the\ncurrent global and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global object.

      \n

      If options is a string, then it specifies the filename.

      \n

      The following example illustrates using both vm.runInThisContext() and\nthe JavaScript eval() function to run the same code:

      \n\n
      const vm = require('vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = \"vm\";');\nconsole.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);\n// Prints: vmResult: 'vm', localVar: 'initial value'\n\nconst evalResult = eval('localVar = \"eval\";');\nconsole.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);\n// Prints: evalResult: 'eval', localVar: 'eval'\n
      \n

      Because vm.runInThisContext() does not have access to the local scope,\nlocalVar is unchanged. In contrast, eval() does have access to the\nlocal scope, so the value localVar is changed. In this way\nvm.runInThisContext() is much like an indirect eval() call, e.g.\n(0,eval)('code').

      \n

      Example: Running an HTTP server within a VM

      \n

      When using either script.runInThisContext() or\nvm.runInThisContext(), the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.

      \n

      In order to run a simple web server using the http module the code passed to\nthe context must either call require('http') on its own, or have a reference\nto the http module passed to it. For instance:

      \n
      'use strict';\nconst vm = require('vm');\n\nconst code = `\n((require) => {\n  const http = require('http');\n\n  http.createServer((request, response) => {\n    response.writeHead(200, { 'Content-Type': 'text/plain' });\n    response.end('Hello World\\\\n');\n  }).listen(8124);\n\n  console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n
      \n

      The require() in the above case shares the state with the context it is\npassed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.

      " + } + ], + "modules": [ + { + "textRaw": "What does it mean to \"contextify\" an object?", + "name": "what_does_it_mean_to_\"contextify\"_an_object?", + "desc": "

      All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the V8 Embedder's Guide:

      \n
      \n

      In V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.

      \n
      \n

      When the method vm.createContext() is called, the contextObject argument\n(or a newly-created object if contextObject is undefined) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode run using the vm module's methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the contextObject is what this document refers to as\n\"contextifying\" the object.

      ", + "type": "module", + "displayName": "What does it mean to \"contextify\" an object?" + }, + { + "textRaw": "Timeout limitations when using `process.nextTick()`, promises, and `queueMicrotask()`", + "name": "timeout_limitations_when_using_`process.nexttick()`,_promises,_and_`queuemicrotask()`", + "desc": "

      Because of the internal mechanics of how the process.nextTick() queue and\nthe microtask queue that underlies Promises are implemented within V8 and\nNode.js, it is possible for code running within a context to \"escape\" the\ntimeout set using vm.runInContext(), vm.runInNewContext(), and\nvm.runInThisContext().

      \n

      For example, the following code executed by vm.runInNewContext() with a\ntimeout of 5 milliseconds schedules an infinite loop to run after a promise\nresolves. The scheduled loop is never interrupted by the timeout:

      \n
      const vm = require('vm');\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n  'Promise.resolve().then(loop);',\n  { loop, console },\n  { timeout: 5 }\n);\n
      \n

      This issue also occurs when the loop() call is scheduled using\nthe process.nextTick() and queueMicrotask() functions.

      \n

      This issue occurs because all contexts share the same microtask and nextTick\nqueues.

      ", + "type": "module", + "displayName": "Timeout limitations when using `process.nextTick()`, promises, and `queueMicrotask()`" + } + ], + "type": "module", + "displayName": "vm" + }, + { + "textRaw": "WebAssembly System Interface (WASI)", + "name": "webassembly_system_interface_(wasi)", + "introduced_in": "v12.16.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/wasi.js

      \n

      The WASI API provides an implementation of the WebAssembly System Interface\nspecification. WASI gives sandboxed WebAssembly applications access to the\nunderlying operating system via a collection of POSIX-like functions.

      \n
      'use strict';\nconst fs = require('fs');\nconst { WASI } = require('wasi');\nconst wasi = new WASI({\n  args: process.argv,\n  env: process.env,\n  preopens: {\n    '/sandbox': '/some/real/path/that/wasm/can/access'\n  }\n});\nconst importObject = { wasi_snapshot_preview1: wasi.wasiImport };\n\n(async () => {\n  const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));\n  const instance = await WebAssembly.instantiate(wasm, importObject);\n\n  wasi.start(instance);\n})();\n
      \n

      To run the above example, create a new WebAssembly text format file named\ndemo.wat:

      \n
      (module\n    ;; Import the required fd_write WASI function which will write the given io vectors to stdout\n    ;; The function signature for fd_write is:\n    ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written\n    (import \"wasi_snapshot_preview1\" \"fd_write\" (func $fd_write (param i32 i32 i32 i32) (result i32)))\n\n    (memory 1)\n    (export \"memory\" (memory 0))\n\n    ;; Write 'hello world\\n' to memory at an offset of 8 bytes\n    ;; Note the trailing newline which is required for the text to appear\n    (data (i32.const 8) \"hello world\\n\")\n\n    (func $main (export \"_start\")\n        ;; Creating a new io vector within linear memory\n        (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\\n' string\n        (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\\n' string\n\n        (call $fd_write\n            (i32.const 1) ;; file_descriptor - 1 for stdout\n            (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0\n            (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.\n            (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written\n        )\n        drop ;; Discard the number of bytes written from the top of the stack\n    )\n)\n
      \n

      Use wabt to compile .wat to .wasm

      \n
      $ wat2wasm demo.wat\n
      \n

      The --experimental-wasi-unstable-preview1 and --experimental-wasm-bigint\nCLI arguments are needed for this example to run.

      ", + "classes": [ + { + "textRaw": "Class: `WASI`", + "type": "class", + "name": "WASI", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      The WASI class provides the WASI system call API and additional convenience\nmethods for working with WASI-based applications. Each WASI instance\nrepresents a distinct sandbox environment. For security purposes, each WASI\ninstance must have its command line arguments, environment variables, and\nsandbox directory structure configured explicitly.

      ", + "methods": [ + { + "textRaw": "`wasi.start(instance)`", + "type": "method", + "name": "start", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`instance` {WebAssembly.Instance}", + "name": "instance", + "type": "WebAssembly.Instance" + } + ] + } + ], + "desc": "

      Attempt to begin execution of instance as a WASI command by invoking its\n_start() export. If instance does not contain a _start() export, or if\ninstance contains an _initialize() export, then an exception is thrown.

      \n

      start() requires that instance exports a WebAssembly.Memory named\nmemory. If instance does not have a memory export an exception is thrown.

      \n

      If start() is called more than once, an exception is thrown.

      " + }, + { + "textRaw": "`wasi.initialize(instance)`", + "type": "method", + "name": "initialize", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`instance` {WebAssembly.Instance}", + "name": "instance", + "type": "WebAssembly.Instance" + } + ] + } + ], + "desc": "

      Attempt to initialize instance as a WASI reactor by invoking its\n_initialize() export, if it is present. If instance contains a _start()\nexport, then an exception is thrown.

      \n

      initialize() requires that instance exports a WebAssembly.Memory named\nmemory. If instance does not have a memory export an exception is thrown.

      \n

      If initialize() is called more than once, an exception is thrown.

      " + } + ], + "properties": [ + { + "textRaw": "`wasiImport` {Object}", + "type": "Object", + "name": "wasiImport", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      wasiImport is an object that implements the WASI system call API. This object\nshould be passed as the wasi_snapshot_preview1 import during the instantiation\nof a WebAssembly.Instance.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`args` {Array} An array of strings that the WebAssembly application will see as command line arguments. The first argument is the virtual path to the WASI command itself. **Default:** `[]`.", + "name": "args", + "type": "Array", + "default": "`[]`", + "desc": "An array of strings that the WebAssembly application will see as command line arguments. The first argument is the virtual path to the WASI command itself." + }, + { + "textRaw": "`env` {Object} An object similar to `process.env` that the WebAssembly application will see as its environment. **Default:** `{}`.", + "name": "env", + "type": "Object", + "default": "`{}`", + "desc": "An object similar to `process.env` that the WebAssembly application will see as its environment." + }, + { + "textRaw": "`preopens` {Object} This object represents the WebAssembly application's sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine.", + "name": "preopens", + "type": "Object", + "desc": "This object represents the WebAssembly application's sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine." + }, + { + "textRaw": "`returnOnExit` {boolean} By default, WASI applications terminate the Node.js process via the `__wasi_proc_exit()` function. Setting this option to `true` causes `wasi.start()` to return the exit code rather than terminate the process. **Default:** `false`.", + "name": "returnOnExit", + "type": "boolean", + "default": "`false`", + "desc": "By default, WASI applications terminate the Node.js process via the `__wasi_proc_exit()` function. Setting this option to `true` causes `wasi.start()` to return the exit code rather than terminate the process." + }, + { + "textRaw": "`stdin` {integer} The file descriptor used as standard input in the WebAssembly application. **Default:** `0`.", + "name": "stdin", + "type": "integer", + "default": "`0`", + "desc": "The file descriptor used as standard input in the WebAssembly application." + }, + { + "textRaw": "`stdout` {integer} The file descriptor used as standard output in the WebAssembly application. **Default:** `1`.", + "name": "stdout", + "type": "integer", + "default": "`1`", + "desc": "The file descriptor used as standard output in the WebAssembly application." + }, + { + "textRaw": "`stderr` {integer} The file descriptor used as standard error in the WebAssembly application. **Default:** `2`.", + "name": "stderr", + "type": "integer", + "default": "`2`", + "desc": "The file descriptor used as standard error in the WebAssembly application." + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "WebAssembly System Interface (WASI)" + }, + { + "textRaw": "Worker threads", + "name": "worker_threads", + "introduced_in": "v10.5.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/worker_threads.js

      \n

      The worker_threads module enables the use of threads that execute JavaScript\nin parallel. To access it:

      \n
      const worker = require('worker_threads');\n
      \n

      Workers (threads) are useful for performing CPU-intensive JavaScript operations.\nThey will not help much with I/O-intensive work. Node.js’s built-in asynchronous\nI/O operations are more efficient than Workers can be.

      \n

      Unlike child_process or cluster, worker_threads can share memory. They do\nso by transferring ArrayBuffer instances or sharing SharedArrayBuffer\ninstances.

      \n
      const {\n  Worker, isMainThread, parentPort, workerData\n} = require('worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script\n      });\n      worker.on('message', resolve);\n      worker.on('error', reject);\n      worker.on('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n
      \n

      The above example spawns a Worker thread for each parse() call. In actual\npractice, use a pool of Workers instead for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.

      \n

      When implementing a worker pool, use the AsyncResource API to inform\ndiagnostic tools (e.g. in order to provide asynchronous stack traces) about the\ncorrelation between tasks and their outcomes. See\n\"Using AsyncResource for a Worker thread pool\"\nin the async_hooks documentation for an example implementation.

      \n

      Worker threads inherit non-process-specific options by default. Refer to\nWorker constructor options to know how to customize worker thread options,\nspecifically argv and execArgv options.

      ", + "properties": [ + { + "textRaw": "`isMainThread` {boolean}", + "type": "boolean", + "name": "isMainThread", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      Is true if this code is not running inside of a Worker thread.

      \n
      const { Worker, isMainThread } = require('worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n
      " + }, + { + "textRaw": "`parentPort` {null|MessagePort}", + "type": "null|MessagePort", + "name": "parentPort", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      If this thread was spawned as a Worker, this will be a MessagePort\nallowing communication with the parent thread. Messages sent using\nparentPort.postMessage() will be available in the parent thread\nusing worker.on('message'), and messages sent from the parent thread\nusing worker.postMessage() will be available in this thread using\nparentPort.on('message').

      \n
      const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n
      " + }, + { + "textRaw": "`resourceLimits` {Object}", + "type": "Object", + "name": "resourceLimits", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "options": [ + { + "textRaw": "`maxYoungGenerationSizeMb` {number}", + "name": "maxYoungGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`maxOldGenerationSizeMb` {number}", + "name": "maxOldGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`codeRangeSizeMb` {number}", + "name": "codeRangeSizeMb", + "type": "number" + }, + { + "textRaw": "`stackSizeMb` {number}", + "name": "stackSizeMb", + "type": "number" + } + ], + "desc": "

      Provides the set of JS engine resource constraints inside this Worker thread.\nIf the resourceLimits option was passed to the Worker constructor,\nthis matches its values.

      \n

      If this is used in the main thread, its value is an empty object.

      " + }, + { + "textRaw": "`SHARE_ENV` {symbol}", + "type": "symbol", + "name": "SHARE_ENV", + "meta": { + "added": [ + "v11.14.0" + ], + "changes": [] + }, + "desc": "

      A special value that can be passed as the env option of the Worker\nconstructor, to indicate that the current thread and the Worker thread should\nshare read and write access to the same set of environment variables.

      \n
      const { Worker, SHARE_ENV } = require('worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .on('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n
      " + }, + { + "textRaw": "`threadId` {integer}", + "type": "integer", + "name": "threadId", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      An integer identifier for the current thread. On the corresponding worker object\n(if there is any), it is available as worker.threadId.\nThis value is unique for each Worker instance inside a single process.

      " + }, + { + "textRaw": "`worker.workerData`", + "name": "workerData", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      An arbitrary JavaScript value that contains a clone of the data passed\nto this thread’s Worker constructor.

      \n

      The data is cloned as if using postMessage(),\naccording to the HTML structured clone algorithm.

      \n
      const { Worker, isMainThread, workerData } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n
      " + } + ], + "methods": [ + { + "textRaw": "`worker.markAsUntransferable(object)`", + "type": "method", + "name": "markAsUntransferable", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Mark an object as not transferable. If object occurs in the transfer list of\na port.postMessage() call, it will be ignored.

      \n

      In particular, this makes sense for objects that can be cloned, rather than\ntransferred, and which are used by other objects on the sending side.\nFor example, Node.js marks the ArrayBuffers it uses for its\nBuffer pool with this.

      \n

      This operation cannot be undone.

      \n
      const { MessageChannel, markAsUntransferable } = require('worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\nport1.postMessage(typedArray1, [ typedArray1.buffer ]);\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has been cloned, not transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n
      \n

      There is no equivalent to this API in browsers.

      " + }, + { + "textRaw": "`worker.moveMessagePortToContext(port, contextifiedSandbox)`", + "type": "method", + "name": "moveMessagePortToContext", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {MessagePort}", + "name": "return", + "type": "MessagePort" + }, + "params": [ + { + "textRaw": "`port` {MessagePort} The message port which will be transferred.", + "name": "port", + "type": "MessagePort", + "desc": "The message port which will be transferred." + }, + { + "textRaw": "`contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", + "name": "contextifiedSandbox", + "type": "Object", + "desc": "A [contextified][] object as returned by the `vm.createContext()` method." + } + ] + } + ], + "desc": "

      Transfer a MessagePort to a different vm Context. The original port\nobject will be rendered unusable, and the returned MessagePort instance will\ntake its place.

      \n

      The returned MessagePort will be an object in the target context, and will\ninherit from its global Object class. Objects passed to the\nport.onmessage() listener will also be created in the target context\nand inherit from its global Object class.

      \n

      However, the created MessagePort will no longer inherit from\nEventEmitter, and only port.onmessage() can be used to receive\nevents using it.

      " + }, + { + "textRaw": "`worker.receiveMessageOnPort(port)`", + "type": "method", + "name": "receiveMessageOnPort", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object|undefined}", + "name": "return", + "type": "Object|undefined" + }, + "params": [ + { + "textRaw": "`port` {MessagePort}", + "name": "port", + "type": "MessagePort" + } + ] + } + ], + "desc": "

      Receive a single message from a given MessagePort. If no message is available,\nundefined is returned, otherwise an object with a single message property\nthat contains the message payload, corresponding to the oldest message in the\nMessagePort’s queue.

      \n
      const { MessageChannel, receiveMessageOnPort } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n
      \n

      When this function is used, no 'message' event will be emitted and the\nonmessage listener will not be invoked.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `MessageChannel`", + "type": "class", + "name": "MessageChannel", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      Instances of the worker.MessageChannel class represent an asynchronous,\ntwo-way communications channel.\nThe MessageChannel has no methods of its own. new MessageChannel()\nyields an object with port1 and port2 properties, which refer to linked\nMessagePort instances.

      \n
      const { MessageChannel } = require('worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n
      " + }, + { + "textRaw": "Class: `MessagePort`", + "type": "class", + "name": "MessagePort", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of the worker.MessagePort class represent one end of an\nasynchronous, two-way communications channel. It can be used to transfer\nstructured data, memory regions and other MessagePorts between different\nWorkers.

      \n

      With the exception of MessagePorts being EventEmitters rather\nthan EventTargets, this implementation matches browser MessagePorts.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted once either side of the channel has been\ndisconnected.

      \n
      const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.on('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n
      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`value` {any} The transmitted value", + "name": "value", + "type": "any", + "desc": "The transmitted value" + } + ], + "desc": "

      The 'message' event is emitted for any incoming message, containing the cloned\ninput of port.postMessage().

      \n

      Listeners on this event will receive a clone of the value parameter as passed\nto postMessage() and no further arguments.

      " + }, + { + "textRaw": "Event: `'messageerror'`", + "type": "event", + "name": "messageerror", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error} An Error object", + "name": "error", + "type": "Error", + "desc": "An Error object" + } + ], + "desc": "

      The 'messageerror' event is emitted when deserializing a message failed.

      " + } + ], + "methods": [ + { + "textRaw": "`port.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disables further sending of messages on either side of the connection.\nThis method can be called when no further communication will happen over this\nMessagePort.

      \n

      The 'close' event will be emitted on both MessagePort instances that\nare part of the channel.

      " + }, + { + "textRaw": "`port.postMessage(value[, transferList])`", + "type": "method", + "name": "postMessage", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33360", + "description": "Added `KeyObject` to the list of cloneable types." + }, + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33772", + "description": "Added `FileHandle` to the list of transferable types." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + }, + { + "textRaw": "`transferList` {Object[]}", + "name": "transferList", + "type": "Object[]" + } + ] + } + ], + "desc": "

      Sends a JavaScript value to the receiving side of this channel.\nvalue will be transferred in a way which is compatible with\nthe HTML structured clone algorithm.

      \n

      In particular, the significant differences to JSON are:

      \n
        \n
      • value may contain circular references.
      • \n
      • value may contain instances of builtin JS types such as RegExps,\nBigInts, Maps, Sets, etc.
      • \n
      • value may contain typed arrays, both using ArrayBuffers\nand SharedArrayBuffers.
      • \n
      • value may contain WebAssembly.Module instances.
      • \n
      • value may not contain native (C++-backed) objects other than MessagePorts,\nFileHandles, and KeyObjects.
      • \n
      \n
      const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n
      \n

      transferList may be a list of ArrayBuffer, MessagePort and\nFileHandle objects.\nAfter transferring, they will not be usable on the sending side of the channel\nanymore (even if they are not contained in value). Unlike with\nchild processes, transferring handles such as network sockets is currently\nnot supported.

      \n

      If value contains SharedArrayBuffer instances, those will be accessible\nfrom either thread. They cannot be listed in transferList.

      \n

      value may still contain ArrayBuffer instances that are not in\ntransferList; in that case, the underlying memory is copied rather than moved.

      \n
      const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` will be accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);\n
      \n

      Because the object cloning uses the structured clone algorithm,\nnon-enumerable properties, property accessors, and object prototypes are\nnot preserved. In particular, Buffer objects will be read as\nplain Uint8Arrays on the receiving side.

      \n

      The message object will be cloned immediately, and can be modified after\nposting without having side effects.

      \n

      For more information on the serialization and deserialization mechanisms\nbehind this API, see the serialization API of the v8 module.

      ", + "modules": [ + { + "textRaw": "Considerations when transferring TypedArrays and Buffers", + "name": "considerations_when_transferring_typedarrays_and_buffers", + "desc": "

      All TypedArray and Buffer instances are views over an underlying\nArrayBuffer. That is, it is the ArrayBuffer that actually stores\nthe raw data while the TypedArray and Buffer objects provide a\nway of viewing and manipulating the data. It is possible and common\nfor multiple views to be created over the same ArrayBuffer instance.\nGreat care must be taken when using a transfer list to transfer an\nArrayBuffer as doing so will cause all TypedArray and Buffer\ninstances that share that same ArrayBuffer to become unusable.

      \n
      const ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0\n
      \n

      For Buffer instances, specifically, whether the underlying\nArrayBuffer can be transferred or cloned depends entirely on how\ninstances were created, which often cannot be reliably determined.

      \n

      An ArrayBuffer can be marked with markAsUntransferable() to indicate\nthat it should always be cloned and never transferred.

      \n

      Depending on how a Buffer instance was created, it may or may\nnot own its underlying ArrayBuffer. An ArrayBuffer must not\nbe transferred unless it is known that the Buffer instance\nowns it. In particular, for Buffers created from the internal\nBuffer pool (using, for instance Buffer.from() or Buffer.alloc()),\ntransferring them is not possible and they will always be cloned,\nwhich sends a copy of the entire Buffer pool.\nThis behavior may come with unintended higher memory\nusage and possible security concerns.

      \n

      See Buffer.allocUnsafe() for more details on Buffer pooling.

      \n

      The ArrayBuffers for Buffer instances created using\nBuffer.alloc() or Buffer.allocUnsafeSlow() can always be\ntransferred but doing so will render all other existing views of\nthose ArrayBuffers unusable.

      ", + "type": "module", + "displayName": "Considerations when transferring TypedArrays and Buffers" + } + ] + }, + { + "textRaw": "`port.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Opposite of unref(). Calling ref() on a previously unref()ed port will\nnot let the program exit if it's the only active handle left (the default\nbehavior). If the port is ref()ed, calling ref() again will have no effect.

      \n

      If listeners are attached or removed using .on('message'), the port will\nbe ref()ed and unref()ed automatically depending on whether\nlisteners for the event exist.

      " + }, + { + "textRaw": "`port.start()`", + "type": "method", + "name": "start", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts receiving messages on this MessagePort. When using this port\nas an event emitter, this will be called automatically once 'message'\nlisteners are attached.

      \n

      This method exists for parity with the Web MessagePort API. In Node.js,\nit is only useful for ignoring messages when no event listener is present.\nNode.js also diverges in its handling of .onmessage. Setting it will\nautomatically call .start(), but unsetting it will let messages queue up\nuntil a new handler is set or the port is discarded.

      " + }, + { + "textRaw": "`port.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calling unref() on a port will allow the thread to exit if this is the only\nactive handle in the event system. If the port is already unref()ed calling\nunref() again will have no effect.

      \n

      If listeners are attached or removed using .on('message'), the port will\nbe ref()ed and unref()ed automatically depending on whether\nlisteners for the event exist.

      " + } + ] + }, + { + "textRaw": "Class: `Worker`", + "type": "class", + "name": "Worker", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "\n

      The Worker class represents an independent JavaScript execution thread.\nMost Node.js APIs are available inside of it.

      \n

      Notable differences inside a Worker environment are:

      \n\n

      Creating Worker instances inside of other Workers is possible.

      \n

      Like Web Workers and the cluster module, two-way communication can be\nachieved through inter-thread message passing. Internally, a Worker has a\nbuilt-in pair of MessagePorts that are already associated with each other\nwhen the Worker is created. While the MessagePort object on the parent side\nis not directly exposed, its functionalities are exposed through\nworker.postMessage() and the worker.on('message') event\non the Worker object for the parent thread.

      \n

      To create custom messaging channels (which is encouraged over using the default\nglobal channel because it facilitates separation of concerns), users can create\na MessageChannel object on either thread and pass one of the\nMessagePorts on that MessageChannel to the other thread through a\npre-existing channel, such as the global one.

      \n

      See port.postMessage() for more information on how messages are passed,\nand what kind of JavaScript values can be successfully transported through\nthe thread barrier.

      \n
      const assert = require('assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort\n} = require('worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n
      ", + "events": [ + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted if the worker thread throws an uncaught\nexception. In that case, the worker will be terminated.

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`exitCode` {integer}", + "name": "exitCode", + "type": "integer" + } + ], + "desc": "

      The 'exit' event is emitted once the worker has stopped. If the worker\nexited by calling process.exit(), the exitCode parameter will be the\npassed exit code. If the worker was terminated, the exitCode parameter will\nbe 1.

      \n

      This is the final event emitted by any Worker instance.

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`value` {any} The transmitted value", + "name": "value", + "type": "any", + "desc": "The transmitted value" + } + ], + "desc": "

      The 'message' event is emitted when the worker thread has invoked\nrequire('worker_threads').parentPort.postMessage().\nSee the port.on('message') event for more details.

      \n

      All messages sent from the worker thread will be emitted before the\n'exit' event is emitted on the Worker object.

      " + }, + { + "textRaw": "Event: `'messageerror'`", + "type": "event", + "name": "messageerror", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error} An Error object", + "name": "error", + "type": "Error", + "desc": "An Error object" + } + ], + "desc": "

      The 'messageerror' event is emitted when deserializing a message failed.

      " + }, + { + "textRaw": "Event: `'online'`", + "type": "event", + "name": "online", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'online' event is emitted when the worker thread has started executing\nJavaScript code.

      " + } + ], + "methods": [ + { + "textRaw": "`worker.getHeapSnapshot()`", + "type": "method", + "name": "getHeapSnapshot", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot", + "name": "return", + "type": "Promise", + "desc": "A promise for a Readable Stream containing a V8 heap snapshot" + }, + "params": [] + } + ], + "desc": "

      Returns a readable stream for a V8 snapshot of the current state of the Worker.\nSee v8.getHeapSnapshot() for more details.

      \n

      If the Worker thread is no longer running, which may occur before the\n'exit' event is emitted, the returned Promise will be rejected\nimmediately with an ERR_WORKER_NOT_RUNNING error.

      " + }, + { + "textRaw": "`worker.postMessage(value[, transferList])`", + "type": "method", + "name": "postMessage", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + }, + { + "textRaw": "`transferList` {Object[]}", + "name": "transferList", + "type": "Object[]" + } + ] + } + ], + "desc": "

      Send a message to the worker that will be received via\nrequire('worker_threads').parentPort.on('message').\nSee port.postMessage() for more details.

      " + }, + { + "textRaw": "`worker.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Opposite of unref(), calling ref() on a previously unref()ed worker will\nnot let the program exit if it's the only active handle left (the default\nbehavior). If the worker is ref()ed, calling ref() again will have\nno effect.

      " + }, + { + "textRaw": "`worker.terminate()`", + "type": "method", + "name": "terminate", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.5.0", + "pr-url": "https://github.com/nodejs/node/pull/28021", + "description": "This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Stop all JavaScript execution in the worker thread as soon as possible.\nReturns a Promise for the exit code that is fulfilled when the\n'exit' event is emitted.

      " + }, + { + "textRaw": "`worker.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calling unref() on a worker will allow the thread to exit if this is the only\nactive handle in the event system. If the worker is already unref()ed calling\nunref() again will have no effect.

      " + } + ], + "properties": [ + { + "textRaw": "`worker.performance`", + "name": "performance", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "desc": "

      An object that can be used to query performance information from a worker\ninstance. Similar to perf_hooks.performance.

      ", + "methods": [ + { + "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", + "type": "method", + "name": "eventLoopUtilization", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`idle` {number}", + "name": "idle", + "type": "number" + }, + { + "textRaw": "`active` {number}", + "name": "active", + "type": "number" + }, + { + "textRaw": "`utilization` {number}", + "name": "utilization", + "type": "number" + } + ] + }, + "params": [ + { + "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", + "name": "utilization1", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()`." + }, + { + "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", + "name": "utilization2", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." + } + ] + } + ], + "desc": "

      The same call as perf_hooks eventLoopUtilization(), except the values\nof the worker instance are returned.

      \n

      One difference is that, unlike the main thread, bootstrapping within a worker\nis done within the event loop. So the event loop utilization will be\nimmediately available once the worker's script begins execution.

      \n

      An idle time that does not increase does not indicate that the worker is\nstuck in bootstrap. The following examples shows how the worker's entire\nlifetime will never accumulate any idle time, but is still be able to process\nmessages.

      \n
      const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n  return;\n}\n\nparentPort.on('message', () => console.log('msg')).unref();\n(function r(n) {\n  if (--n < 0) return;\n  const t = Date.now();\n  while (Date.now() - t < 300);\n  setImmediate(r, n);\n})(10);\n
      \n

      The event loop utilization of a worker is available only after the 'online'\nevent emitted, and if called before this, or after the 'exit'\nevent, then all properties have the value of 0.

      " + } + ] + }, + { + "textRaw": "`resourceLimits` {Object}", + "type": "Object", + "name": "resourceLimits", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "options": [ + { + "textRaw": "`maxYoungGenerationSizeMb` {number}", + "name": "maxYoungGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`maxOldGenerationSizeMb` {number}", + "name": "maxOldGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`codeRangeSizeMb` {number}", + "name": "codeRangeSizeMb", + "type": "number" + }, + { + "textRaw": "`stackSizeMb` {number}", + "name": "stackSizeMb", + "type": "number" + } + ], + "desc": "

      Provides the set of JS engine resource constraints for this Worker thread.\nIf the resourceLimits option was passed to the Worker constructor,\nthis matches its values.

      \n

      If the worker has stopped, the return value is an empty object.

      " + }, + { + "textRaw": "`stderr` {stream.Readable}", + "type": "stream.Readable", + "name": "stderr", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      This is a readable stream which contains data written to process.stderr\ninside the worker thread. If stderr: true was not passed to the\nWorker constructor, then data will be piped to the parent thread's\nprocess.stderr stream.

      " + }, + { + "textRaw": "`stdin` {null|stream.Writable}", + "type": "null|stream.Writable", + "name": "stdin", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      If stdin: true was passed to the Worker constructor, this is a\nwritable stream. The data written to this stream will be made available in\nthe worker thread as process.stdin.

      " + }, + { + "textRaw": "`stdout` {stream.Readable}", + "type": "stream.Readable", + "name": "stdout", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      This is a readable stream which contains data written to process.stdout\ninside the worker thread. If stdout: true was not passed to the\nWorker constructor, then data will be piped to the parent thread's\nprocess.stdout stream.

      " + }, + { + "textRaw": "`threadId` {integer}", + "type": "integer", + "name": "threadId", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

      An integer identifier for the referenced thread. Inside the worker thread,\nit is available as require('worker_threads').threadId.\nThis value is unique for each Worker instance inside a single process.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`filename` {string|URL} The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` protocol. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path.", + "name": "filename", + "type": "string|URL", + "desc": "The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` protocol. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`argv` {any[]} List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values will be available on the global `process.argv` as if they were passed as CLI options to the script.", + "name": "argv", + "type": "any[]", + "desc": "List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values will be available on the global `process.argv` as if they were passed as CLI options to the script." + }, + { + "textRaw": "`env` {Object} If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object will affect the other thread as well. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object will affect the other thread as well." + }, + { + "textRaw": "`eval` {boolean} If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online.", + "name": "eval", + "type": "boolean", + "desc": "If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online." + }, + { + "textRaw": "`execArgv` {string[]} List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread.", + "name": "execArgv", + "type": "string[]", + "desc": "List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread." + }, + { + "textRaw": "`stdin` {boolean} If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will appear as `process.stdin` inside the Worker. By default, no data is provided.", + "name": "stdin", + "type": "boolean", + "desc": "If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will appear as `process.stdin` inside the Worker. By default, no data is provided." + }, + { + "textRaw": "`stdout` {boolean} If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent.", + "name": "stdout", + "type": "boolean", + "desc": "If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent." + }, + { + "textRaw": "`stderr` {boolean} If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent.", + "name": "stderr", + "type": "boolean", + "desc": "If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent." + }, + { + "textRaw": "`workerData` {any} Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s).", + "name": "workerData", + "type": "any", + "desc": "Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s)." + }, + { + "textRaw": "`trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker will track raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default**: `false`.", + "name": "trackUnmanagedFds", + "type": "boolean", + "desc": "If this is set to `true`, then the Worker will track raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default**: `false`." + }, + { + "textRaw": "`transferList` {Object[]} If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown. See [`port.postMessage()`][] for more information.", + "name": "transferList", + "type": "Object[]", + "desc": "If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown. See [`port.postMessage()`][] for more information." + }, + { + "textRaw": "`resourceLimits` {Object} An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", + "name": "resourceLimits", + "type": "Object", + "desc": "An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", + "options": [ + { + "textRaw": "`maxOldGenerationSizeMb` {number} The maximum size of the main heap in MB.", + "name": "maxOldGenerationSizeMb", + "type": "number", + "desc": "The maximum size of the main heap in MB." + }, + { + "textRaw": "`maxYoungGenerationSizeMb` {number} The maximum size of a heap space for recently created objects.", + "name": "maxYoungGenerationSizeMb", + "type": "number", + "desc": "The maximum size of a heap space for recently created objects." + }, + { + "textRaw": "`codeRangeSizeMb` {number} The size of a pre-allocated memory range used for generated code.", + "name": "codeRangeSizeMb", + "type": "number", + "desc": "The size of a pre-allocated memory range used for generated code." + }, + { + "textRaw": "`stackSizeMb` {number} The default maximum stack size for the thread. Small values may lead to unusable Worker instances. **Default:** `4`.", + "name": "stackSizeMb", + "type": "number", + "default": "`4`", + "desc": "The default maximum stack size for the thread. Small values may lead to unusable Worker instances." + } + ] + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Worker threads" + }, + { + "textRaw": "Zlib", + "name": "zlib", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/zlib.js

      \n

      The zlib module provides compression functionality implemented using Gzip,\nDeflate/Inflate, and Brotli.

      \n

      To access it:

      \n
      const zlib = require('zlib');\n
      \n

      Compression and decompression are built around the Node.js Streams API.

      \n

      Compressing or decompressing a stream (such as a file) can be accomplished by\npiping the source stream through a zlib Transform stream into a destination\nstream:

      \n
      const { createGzip } = require('zlib');\nconst { pipeline } = require('stream');\nconst {\n  createReadStream,\n  createWriteStream\n} = require('fs');\n\nconst gzip = createGzip();\nconst source = createReadStream('input.txt');\nconst destination = createWriteStream('input.txt.gz');\n\npipeline(source, gzip, destination, (err) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n});\n\n// Or, Promisified\n\nconst { promisify } = require('util');\nconst pipe = promisify(pipeline);\n\nasync function do_gzip(input, output) {\n  const gzip = createGzip();\n  const source = createReadStream(input);\n  const destination = createWriteStream(output);\n  await pipe(source, gzip, destination);\n}\n\ndo_gzip('input.txt', 'input.txt.gz')\n  .catch((err) => {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  });\n
      \n

      It is also possible to compress or decompress data in a single step:

      \n
      const { deflate, unzip } = require('zlib');\n\nconst input = '.................................';\ndeflate(input, (err, buffer) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n  console.log(buffer.toString('base64'));\n});\n\nconst buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');\nunzip(buffer, (err, buffer) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n  console.log(buffer.toString());\n});\n\n// Or, Promisified\n\nconst { promisify } = require('util');\nconst do_unzip = promisify(unzip);\n\ndo_unzip(buffer)\n  .then((buf) => console.log(buf.toString()))\n  .catch((err) => {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  });\n
      ", + "modules": [ + { + "textRaw": "Threadpool usage and performance considerations", + "name": "threadpool_usage_and_performance_considerations", + "desc": "

      All zlib APIs, except those that are explicitly synchronous, use the Node.js\ninternal threadpool. This can lead to surprising effects and performance\nlimitations in some applications.

      \n

      Creating and using a large number of zlib objects simultaneously can cause\nsignificant memory fragmentation.

      \n
      const zlib = require('zlib');\n\nconst payload = Buffer.from('This is some data');\n\n// WARNING: DO NOT DO THIS!\nfor (let i = 0; i < 30000; ++i) {\n  zlib.deflate(payload, (err, buffer) => {});\n}\n
      \n

      In the preceding example, 30,000 deflate instances are created concurrently.\nBecause of how some operating systems handle memory allocation and\ndeallocation, this may lead to to significant memory fragmentation.

      \n

      It is strongly recommended that the results of compression\noperations be cached to avoid duplication of effort.

      ", + "type": "module", + "displayName": "Threadpool usage and performance considerations" + }, + { + "textRaw": "Compressing HTTP requests and responses", + "name": "compressing_http_requests_and_responses", + "desc": "

      The zlib module can be used to implement support for the gzip, deflate\nand br content-encoding mechanisms defined by\nHTTP.

      \n

      The HTTP Accept-Encoding header is used within an http request to identify\nthe compression encodings accepted by the client. The Content-Encoding\nheader is used to identify the compression encodings actually applied to a\nmessage.

      \n

      The examples given below are drastically simplified to show the basic concept.\nUsing zlib encoding can be expensive, and the results ought to be cached.\nSee Memory usage tuning for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.

      \n
      // Client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst { pipeline } = require('stream');\n\nconst request = http.get({ host: 'example.com',\n                           path: '/',\n                           port: 80,\n                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });\nrequest.on('response', (response) => {\n  const output = fs.createWriteStream('example.com_index.html');\n\n  const onError = (err) => {\n    if (err) {\n      console.error('An error occurred:', err);\n      process.exitCode = 1;\n    }\n  };\n\n  switch (response.headers['content-encoding']) {\n    case 'br':\n      pipeline(response, zlib.createBrotliDecompress(), output, onError);\n      break;\n    // Or, just use zlib.createUnzip() to handle both of the following cases:\n    case 'gzip':\n      pipeline(response, zlib.createGunzip(), output, onError);\n      break;\n    case 'deflate':\n      pipeline(response, zlib.createInflate(), output, onError);\n      break;\n    default:\n      pipeline(response, output, onError);\n      break;\n  }\n});\n
      \n
      // server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst { pipeline } = require('stream');\n\nhttp.createServer((request, response) => {\n  const raw = fs.createReadStream('index.html');\n  // Store both a compressed and an uncompressed version of the resource.\n  response.setHeader('Vary', 'Accept-Encoding');\n  let acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  const onError = (err) => {\n    if (err) {\n      // If an error occurs, there's not much we can do because\n      // the server has already sent the 200 response code and\n      // some amount of data has already been sent to the client.\n      // The best we can do is terminate the response immediately\n      // and log the error.\n      response.end();\n      console.error('An error occurred:', err);\n    }\n  };\n\n  // Note: This is not a conformant accept-encoding parser.\n  // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (/\\bdeflate\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'deflate' });\n    pipeline(raw, zlib.createDeflate(), response, onError);\n  } else if (/\\bgzip\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'gzip' });\n    pipeline(raw, zlib.createGzip(), response, onError);\n  } else if (/\\bbr\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'br' });\n    pipeline(raw, zlib.createBrotliCompress(), response, onError);\n  } else {\n    response.writeHead(200, {});\n    pipeline(raw, response, onError);\n  }\n}).listen(1337);\n
      \n

      By default, the zlib methods will throw an error when decompressing\ntruncated data. However, if it is known that the data is incomplete, or\nthe desire is to inspect only the beginning of a compressed file, it is\npossible to suppress the default error handling by changing the flushing\nmethod that is used to decompress the last chunk of input data:

      \n
      // This is a truncated version of the buffer from the above examples\nconst buffer = Buffer.from('eJzT0yMA', 'base64');\n\nzlib.unzip(\n  buffer,\n  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.\n  { finishFlush: zlib.constants.Z_SYNC_FLUSH },\n  (err, buffer) => {\n    if (err) {\n      console.error('An error occurred:', err);\n      process.exitCode = 1;\n    }\n    console.log(buffer.toString());\n  });\n
      \n

      This will not change the behavior in other error-throwing situations, e.g.\nwhen the input data has an invalid format. Using this method, it will not be\npossible to determine whether the input ended prematurely or lacks the\nintegrity checks, making it necessary to manually check that the\ndecompressed result is valid.

      ", + "type": "module", + "displayName": "Compressing HTTP requests and responses" + }, + { + "textRaw": "Flushing", + "name": "flushing", + "desc": "

      Calling .flush() on a compression stream will make zlib return as much\noutput as currently possible. This may come at the cost of degraded compression\nquality, but can be useful when data needs to be available as soon as possible.

      \n

      In the following example, flush() is used to write a compressed partial\nHTTP response to the client:

      \n
      const zlib = require('zlib');\nconst http = require('http');\nconst { pipeline } = require('stream');\n\nhttp.createServer((request, response) => {\n  // For the sake of simplicity, the Accept-Encoding checks are omitted.\n  response.writeHead(200, { 'content-encoding': 'gzip' });\n  const output = zlib.createGzip();\n  let i;\n\n  pipeline(output, response, (err) => {\n    if (err) {\n      // If an error occurs, there's not much we can do because\n      // the server has already sent the 200 response code and\n      // some amount of data has already been sent to the client.\n      // The best we can do is terminate the response immediately\n      // and log the error.\n      clearInterval(i);\n      response.end();\n      console.error('An error occurred:', err);\n    }\n  });\n\n  i = setInterval(() => {\n    output.write(`The current time is ${Date()}\\n`, () => {\n      // The data has been passed to zlib, but the compression algorithm may\n      // have decided to buffer the data for more efficient compression.\n      // Calling .flush() will make the data available as soon as the client\n      // is ready to receive it.\n      output.flush();\n    });\n  }, 1000);\n}).listen(1337);\n
      ", + "type": "module", + "displayName": "Flushing" + } + ], + "miscs": [ + { + "textRaw": "Memory usage tuning", + "name": "Memory usage tuning", + "type": "misc", + "miscs": [ + { + "textRaw": "For zlib-based streams", + "name": "for_zlib-based_streams", + "desc": "

      From zlib/zconf.h, modified for Node.js usage:

      \n

      The memory requirements for deflate are (in bytes):

      \n\n
      (1 << (windowBits + 2)) + (1 << (memLevel + 9))\n
      \n

      That is: 128K for windowBits = 15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.

      \n

      For example, to reduce the default memory requirements from 256K to 128K, the\noptions should be set to:

      \n
      const options = { windowBits: 14, memLevel: 7 };\n
      \n

      This will, however, generally degrade compression.

      \n

      The memory requirements for inflate are (in bytes) 1 << windowBits.\nThat is, 32K for windowBits = 15 (default value) plus a few kilobytes\nfor small objects.

      \n

      This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.

      \n

      The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.

      \n

      In general, greater memory usage options will mean that Node.js has to make\nfewer calls to zlib because it will be able to process more data on\neach write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.

      ", + "type": "misc", + "displayName": "For zlib-based streams" + }, + { + "textRaw": "For Brotli-based streams", + "name": "for_brotli-based_streams", + "desc": "

      There are equivalents to the zlib options for Brotli-based streams, although\nthese options have different ranges than the zlib ones:

      \n
        \n
      • zlib’s level option matches Brotli’s BROTLI_PARAM_QUALITY option.
      • \n
      • zlib’s windowBits option matches Brotli’s BROTLI_PARAM_LGWIN option.
      • \n
      \n

      See below for more details on Brotli-specific options.

      ", + "type": "misc", + "displayName": "For Brotli-based streams" + } + ] + }, + { + "textRaw": "Constants", + "name": "Constants", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "type": "misc", + "miscs": [ + { + "textRaw": "zlib constants", + "name": "zlib_constants", + "desc": "

      All of the constants defined in zlib.h are also defined on\nrequire('zlib').constants. In the normal course of operations, it will not be\nnecessary to use these constants. They are documented so that their presence is\nnot surprising. This section is taken almost directly from the\nzlib documentation.

      \n

      Previously, the constants were available directly from require('zlib'), for\ninstance zlib.Z_NO_FLUSH. Accessing the constants directly from the module is\ncurrently still possible but is deprecated.

      \n

      Allowed flush values.

      \n
        \n
      • zlib.constants.Z_NO_FLUSH
      • \n
      • zlib.constants.Z_PARTIAL_FLUSH
      • \n
      • zlib.constants.Z_SYNC_FLUSH
      • \n
      • zlib.constants.Z_FULL_FLUSH
      • \n
      • zlib.constants.Z_FINISH
      • \n
      • zlib.constants.Z_BLOCK
      • \n
      • zlib.constants.Z_TREES
      • \n
      \n

      Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.

      \n
        \n
      • zlib.constants.Z_OK
      • \n
      • zlib.constants.Z_STREAM_END
      • \n
      • zlib.constants.Z_NEED_DICT
      • \n
      • zlib.constants.Z_ERRNO
      • \n
      • zlib.constants.Z_STREAM_ERROR
      • \n
      • zlib.constants.Z_DATA_ERROR
      • \n
      • zlib.constants.Z_MEM_ERROR
      • \n
      • zlib.constants.Z_BUF_ERROR
      • \n
      • zlib.constants.Z_VERSION_ERROR
      • \n
      \n

      Compression levels.

      \n
        \n
      • zlib.constants.Z_NO_COMPRESSION
      • \n
      • zlib.constants.Z_BEST_SPEED
      • \n
      • zlib.constants.Z_BEST_COMPRESSION
      • \n
      • zlib.constants.Z_DEFAULT_COMPRESSION
      • \n
      \n

      Compression strategy.

      \n
        \n
      • zlib.constants.Z_FILTERED
      • \n
      • zlib.constants.Z_HUFFMAN_ONLY
      • \n
      • zlib.constants.Z_RLE
      • \n
      • zlib.constants.Z_FIXED
      • \n
      • zlib.constants.Z_DEFAULT_STRATEGY
      • \n
      ", + "type": "misc", + "displayName": "zlib constants" + }, + { + "textRaw": "Brotli constants", + "name": "brotli_constants", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      There are several options and other constants available for Brotli-based\nstreams:

      ", + "modules": [ + { + "textRaw": "Flush operations", + "name": "flush_operations", + "desc": "

      The following values are valid flush operations for Brotli-based streams:

      \n
        \n
      • zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)
      • \n
      • zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())
      • \n
      • zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)
      • \n
      • zlib.constants.BROTLI_OPERATION_EMIT_METADATA\n
          \n
        • This particular operation may be hard to use in a Node.js context,\nas the streaming layer makes it hard to know which data will end up\nin this frame. Also, there is currently no way to consume this data through\nthe Node.js API.
        • \n
        \n
      • \n
      ", + "type": "module", + "displayName": "Flush operations" + }, + { + "textRaw": "Compressor options", + "name": "compressor_options", + "desc": "

      There are several options that can be set on Brotli encoders, affecting\ncompression efficiency and speed. Both the keys and the values can be accessed\nas properties of the zlib.constants object.

      \n

      The most important options are:

      \n
        \n
      • BROTLI_PARAM_MODE\n
          \n
        • BROTLI_MODE_GENERIC (default)
        • \n
        • BROTLI_MODE_TEXT, adjusted for UTF-8 text
        • \n
        • BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts
        • \n
        \n
      • \n
      • BROTLI_PARAM_QUALITY\n
          \n
        • Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY,\nwith a default of BROTLI_DEFAULT_QUALITY.
        • \n
        \n
      • \n
      • BROTLI_PARAM_SIZE_HINT\n
          \n
        • Integer value representing the expected input size;\ndefaults to 0 for an unknown input size.
        • \n
        \n
      • \n
      \n

      The following flags can be set for advanced control over the compression\nalgorithm and memory usage tuning:

      \n
        \n
      • BROTLI_PARAM_LGWIN\n
          \n
        • Ranges from BROTLI_MIN_WINDOW_BITS to BROTLI_MAX_WINDOW_BITS,\nwith a default of BROTLI_DEFAULT_WINDOW, or up to\nBROTLI_LARGE_MAX_WINDOW_BITS if the BROTLI_PARAM_LARGE_WINDOW flag\nis set.
        • \n
        \n
      • \n
      • BROTLI_PARAM_LGBLOCK\n
          \n
        • Ranges from BROTLI_MIN_INPUT_BLOCK_BITS to BROTLI_MAX_INPUT_BLOCK_BITS.
        • \n
        \n
      • \n
      • BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING\n
          \n
        • Boolean flag that decreases compression ratio in favour of\ndecompression speed.
        • \n
        \n
      • \n
      • BROTLI_PARAM_LARGE_WINDOW\n
          \n
        • Boolean flag enabling “Large Window Brotli†mode (not compatible with the\nBrotli format as standardized in RFC 7932).
        • \n
        \n
      • \n
      • BROTLI_PARAM_NPOSTFIX\n
          \n
        • Ranges from 0 to BROTLI_MAX_NPOSTFIX.
        • \n
        \n
      • \n
      • BROTLI_PARAM_NDIRECT\n
          \n
        • Ranges from 0 to 15 << NPOSTFIX in steps of 1 << NPOSTFIX.
        • \n
        \n
      • \n
      ", + "type": "module", + "displayName": "Compressor options" + }, + { + "textRaw": "Decompressor options", + "name": "decompressor_options", + "desc": "

      These advanced options are available for controlling decompression:

      \n
        \n
      • BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION\n
          \n
        • Boolean flag that affects internal memory allocation patterns.
        • \n
        \n
      • \n
      • BROTLI_DECODER_PARAM_LARGE_WINDOW\n
          \n
        • Boolean flag enabling “Large Window Brotli†mode (not compatible with the\nBrotli format as standardized in RFC 7932).
        • \n
        \n
      • \n
      ", + "type": "module", + "displayName": "Decompressor options" + } + ], + "type": "misc", + "displayName": "Brotli constants" + } + ] + }, + { + "textRaw": "Class: `Options`", + "type": "misc", + "name": "Options", + "meta": { + "added": [ + "v0.11.1" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33516", + "description": "The `maxOutputLength` option is supported now." + }, + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `dictionary` option can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `dictionary` option can be an `Uint8Array` now." + }, + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/6069", + "description": "The `finishFlush` option is supported now." + } + ] + }, + "desc": "

      Each zlib-based class takes an options object. No options are required.

      \n

      Some options are only relevant when compressing and are\nignored by the decompression classes.

      \n\n

      See the deflateInit2 and inflateInit2 documentation for more\ninformation.

      " + }, + { + "textRaw": "Class: `BrotliOptions`", + "type": "misc", + "name": "BrotliOptions", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33516", + "description": "The `maxOutputLength` option is supported now." + } + ] + }, + "desc": "

      Each Brotli-based class takes an options object. All options are optional.

      \n\n

      For example:

      \n
      const stream = zlib.createBrotliCompress({\n  chunkSize: 32 * 1024,\n  params: {\n    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,\n    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,\n    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size\n  }\n});\n
      " + }, + { + "textRaw": "Convenience methods", + "name": "Convenience methods", + "type": "misc", + "desc": "

      All of these take a Buffer, TypedArray, DataView,\nArrayBuffer or string as the first argument, an optional second argument\nto supply options to the zlib classes and will call the supplied callback\nwith callback(error, result).

      \n

      Every method has a *Sync counterpart, which accept the same arguments, but\nwithout a callback.

      ", + "methods": [ + { + "textRaw": "`zlib.brotliCompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliCompressSync(buffer[, options])`", + "type": "method", + "name": "brotliCompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with BrotliCompress.

      " + }, + { + "textRaw": "`zlib.brotliDecompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliDecompressSync(buffer[, options])`", + "type": "method", + "name": "brotliDecompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with BrotliDecompress.

      " + }, + { + "textRaw": "`zlib.deflate(buffer[, options], callback)`", + "type": "method", + "name": "deflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateSync(buffer[, options])`", + "type": "method", + "name": "deflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with Deflate.

      " + }, + { + "textRaw": "`zlib.deflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "deflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateRawSync(buffer[, options])`", + "type": "method", + "name": "deflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with DeflateRaw.

      " + }, + { + "textRaw": "`zlib.gunzip(buffer[, options], callback)`", + "type": "method", + "name": "gunzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gunzipSync(buffer[, options])`", + "type": "method", + "name": "gunzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with Gunzip.

      " + }, + { + "textRaw": "`zlib.gzip(buffer[, options], callback)`", + "type": "method", + "name": "gzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gzipSync(buffer[, options])`", + "type": "method", + "name": "gzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with Gzip.

      " + }, + { + "textRaw": "`zlib.inflate(buffer[, options], callback)`", + "type": "method", + "name": "inflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateSync(buffer[, options])`", + "type": "method", + "name": "inflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with Inflate.

      " + }, + { + "textRaw": "`zlib.inflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "inflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateRawSync(buffer[, options])`", + "type": "method", + "name": "inflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with InflateRaw.

      " + }, + { + "textRaw": "`zlib.unzip(buffer[, options], callback)`", + "type": "method", + "name": "unzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.unzipSync(buffer[, options])`", + "type": "method", + "name": "unzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with Unzip.

      " + } + ] + } + ], + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "classes": [ + { + "textRaw": "Class: `zlib.BrotliCompress`", + "type": "class", + "name": "zlib.BrotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      Compress data using the Brotli algorithm.

      " + }, + { + "textRaw": "Class: `zlib.BrotliDecompress`", + "type": "class", + "name": "zlib.BrotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      Decompress data using the Brotli algorithm.

      " + }, + { + "textRaw": "Class: `zlib.Deflate`", + "type": "class", + "name": "zlib.Deflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      Compress data using deflate.

      " + }, + { + "textRaw": "Class: `zlib.DeflateRaw`", + "type": "class", + "name": "zlib.DeflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      Compress data using deflate, and do not append a zlib header.

      " + }, + { + "textRaw": "Class: `zlib.Gunzip`", + "type": "class", + "name": "zlib.Gunzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5883", + "description": "Trailing garbage at the end of the input stream will now result in an `'error'` event." + }, + { + "version": "v5.9.0", + "pr-url": "https://github.com/nodejs/node/pull/5120", + "description": "Multiple concatenated gzip file members are supported now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2595", + "description": "A truncated input stream will now result in an `'error'` event." + } + ] + }, + "desc": "

      Decompress a gzip stream.

      " + }, + { + "textRaw": "Class: `zlib.Gzip`", + "type": "class", + "name": "zlib.Gzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      Compress data using gzip.

      " + }, + { + "textRaw": "Class: `zlib.Inflate`", + "type": "class", + "name": "zlib.Inflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2595", + "description": "A truncated input stream will now result in an `'error'` event." + } + ] + }, + "desc": "

      Decompress a deflate stream.

      " + }, + { + "textRaw": "Class: `zlib.InflateRaw`", + "type": "class", + "name": "zlib.InflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v6.8.0", + "pr-url": "https://github.com/nodejs/node/pull/8512", + "description": "Custom dictionaries are now supported by `InflateRaw`." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2595", + "description": "A truncated input stream will now result in an `'error'` event." + } + ] + }, + "desc": "

      Decompress a raw deflate stream.

      " + }, + { + "textRaw": "Class: `zlib.Unzip`", + "type": "class", + "name": "zlib.Unzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.

      " + }, + { + "textRaw": "Class: `zlib.ZlibBase`", + "type": "class", + "name": "zlib.ZlibBase", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/24939", + "description": "This class was renamed from `Zlib` to `ZlibBase`." + } + ] + }, + "desc": "

      Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.

      \n

      This class inherits from stream.Transform, allowing zlib objects to be\nused in pipes and similar stream operations.

      ", + "properties": [ + { + "textRaw": "`bytesRead` {number}", + "type": "number", + "name": "bytesRead", + "meta": { + "added": [ + "v8.1.0" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`zlib.bytesWritten`][] instead.", + "desc": "

      Deprecated alias for zlib.bytesWritten. This original name was chosen\nbecause it also made sense to interpret the value as the number of bytes\nread by the engine, but is inconsistent with other streams in Node.js that\nexpose values under these names.

      " + }, + { + "textRaw": "`bytesWritten` {number}", + "type": "number", + "name": "bytesWritten", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      The zlib.bytesWritten property specifies the number of bytes written to\nthe engine, before the bytes are processed (compressed or decompressed,\nas appropriate for the derived class).

      " + } + ], + "methods": [ + { + "textRaw": "`zlib.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Close the underlying handle.

      " + }, + { + "textRaw": "`zlib.flush([kind, ]callback)`", + "type": "method", + "name": "flush", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.", + "name": "kind", + "default": "`zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.

      \n

      Calling this only flushes data from the internal zlib state, and does not\nperform flushing of any kind on the streams level. Rather, it behaves like a\nnormal call to .write(), i.e. it will be queued up behind other pending\nwrites and will only produce output when data is being read from the stream.

      " + }, + { + "textRaw": "`zlib.params(level, strategy, callback)`", + "type": "method", + "name": "params", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`level` {integer}", + "name": "level", + "type": "integer" + }, + { + "textRaw": "`strategy` {integer}", + "name": "strategy", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      This function is only available for zlib-based streams, i.e. not Brotli.

      \n

      Dynamically update the compression level and compression strategy.\nOnly applicable to deflate algorithm.

      " + }, + { + "textRaw": "`zlib.reset()`", + "type": "method", + "name": "reset", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.

      " + } + ] + } + ], + "properties": [ + { + "textRaw": "`zlib.constants`", + "name": "constants", + "meta": { + "added": [ + "v7.0.0" + ], + "changes": [] + }, + "desc": "

      Provides an object enumerating Zlib-related constants.

      " + } + ], + "methods": [ + { + "textRaw": "`zlib.createBrotliCompress([options])`", + "type": "method", + "name": "createBrotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

      Creates and returns a new BrotliCompress object.

      " + }, + { + "textRaw": "`zlib.createBrotliDecompress([options])`", + "type": "method", + "name": "createBrotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

      Creates and returns a new BrotliDecompress object.

      " + }, + { + "textRaw": "`zlib.createDeflate([options])`", + "type": "method", + "name": "createDeflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new Deflate object.

      " + }, + { + "textRaw": "`zlib.createDeflateRaw([options])`", + "type": "method", + "name": "createDeflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new DeflateRaw object.

      \n

      An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits\nis set to 8 for raw deflate streams. zlib would automatically set windowBits\nto 9 if was initially set to 8. Newer versions of zlib will throw an exception,\nso Node.js restored the original behavior of upgrading a value of 8 to 9,\nsince passing windowBits = 9 to zlib actually results in a compressed stream\nthat effectively uses an 8-bit window only.

      " + }, + { + "textRaw": "`zlib.createGunzip([options])`", + "type": "method", + "name": "createGunzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new Gunzip object.

      " + }, + { + "textRaw": "`zlib.createGzip([options])`", + "type": "method", + "name": "createGzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new Gzip object.\nSee example.

      " + }, + { + "textRaw": "`zlib.createInflate([options])`", + "type": "method", + "name": "createInflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new Inflate object.

      " + }, + { + "textRaw": "`zlib.createInflateRaw([options])`", + "type": "method", + "name": "createInflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new InflateRaw object.

      " + }, + { + "textRaw": "`zlib.createUnzip([options])`", + "type": "method", + "name": "createUnzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Creates and returns a new Unzip object.

      " + }, + { + "textRaw": "`zlib.brotliCompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliCompressSync(buffer[, options])`", + "type": "method", + "name": "brotliCompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with BrotliCompress.

      " + }, + { + "textRaw": "`zlib.brotliDecompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliDecompressSync(buffer[, options])`", + "type": "method", + "name": "brotliDecompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with BrotliDecompress.

      " + }, + { + "textRaw": "`zlib.deflate(buffer[, options], callback)`", + "type": "method", + "name": "deflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateSync(buffer[, options])`", + "type": "method", + "name": "deflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with Deflate.

      " + }, + { + "textRaw": "`zlib.deflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "deflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateRawSync(buffer[, options])`", + "type": "method", + "name": "deflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with DeflateRaw.

      " + }, + { + "textRaw": "`zlib.gunzip(buffer[, options], callback)`", + "type": "method", + "name": "gunzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gunzipSync(buffer[, options])`", + "type": "method", + "name": "gunzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with Gunzip.

      " + }, + { + "textRaw": "`zlib.gzip(buffer[, options], callback)`", + "type": "method", + "name": "gzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gzipSync(buffer[, options])`", + "type": "method", + "name": "gzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Compress a chunk of data with Gzip.

      " + }, + { + "textRaw": "`zlib.inflate(buffer[, options], callback)`", + "type": "method", + "name": "inflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateSync(buffer[, options])`", + "type": "method", + "name": "inflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with Inflate.

      " + }, + { + "textRaw": "`zlib.inflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "inflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateRawSync(buffer[, options])`", + "type": "method", + "name": "inflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with InflateRaw.

      " + }, + { + "textRaw": "`zlib.unzip(buffer[, options], callback)`", + "type": "method", + "name": "unzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.unzipSync(buffer[, options])`", + "type": "method", + "name": "unzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

      Decompress a chunk of data with Unzip.

      " + } + ], + "type": "module", + "displayName": "Zlib" + } + ], + "classes": [ + { + "textRaw": "Class: `Error`", + "type": "class", + "name": "Error", + "desc": "

      A generic JavaScript <Error> object that does not denote any specific\ncircumstance of why the error occurred. Error objects capture a \"stack trace\"\ndetailing the point in the code at which the Error was instantiated, and may\nprovide a text description of the error.

      \n

      All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

      ", + "methods": [ + { + "textRaw": "`Error.captureStackTrace(targetObject[, constructorOpt])`", + "type": "method", + "name": "captureStackTrace", + "signatures": [ + { + "params": [ + { + "textRaw": "`targetObject` {Object}", + "name": "targetObject", + "type": "Object" + }, + { + "textRaw": "`constructorOpt` {Function}", + "name": "constructorOpt", + "type": "Function" + } + ] + } + ], + "desc": "

      Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

      \n
      const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack;  // Similar to `new Error().stack`\n
      \n

      The first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.

      \n

      The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

      \n

      The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:

      \n
      function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
      " + } + ], + "properties": [ + { + "textRaw": "`stackTraceLimit` {number}", + "type": "number", + "name": "stackTraceLimit", + "desc": "

      The Error.stackTraceLimit property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack or\nError.captureStackTrace(obj)).

      \n

      The default value is 10 but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.

      \n

      If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string label that identifies the kind of error.\nerror.code is the most stable way to identify an error. It will only change\nbetween major versions of Node.js. In contrast, error.message strings may\nchange between any versions of Node.js. See Node.js error codes for details\nabout specific codes.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      The error.message property is the string description of the error as set by\ncalling new Error(message). The message passed to the constructor will also\nappear in the first line of the stack trace of the Error, however changing\nthis property after the Error object is created may not change the first\nline of the stack trace (for example, when error.stack is read before this\nproperty is changed).

      \n
      const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
      " + }, + { + "textRaw": "`stack` {string}", + "type": "string", + "name": "stack", + "desc": "

      The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.

      \n
      Error: Things keep happening!\n   at /home/gbusey/file.js:525:2\n   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n   at increaseSynergy (/home/gbusey/actors.js:701:6)\n
      \n

      The first line is formatted as <error class name>: <error message>, and\nis followed by a series of stack frames (each line beginning with \"at \").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.

      \n

      Frames are only generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called cheetahify which\nitself calls a JavaScript function, the frame representing the cheetahify call\nwill not be present in the stack traces:

      \n
      const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n  // `cheetahify()` *synchronously* calls speedy.\n  cheetahify(function speedy() {\n    throw new Error('oh no!');\n  });\n}\n\nmakeFaster();\n// will throw:\n//   /home/gbusey/file.js:6\n//       throw new Error('oh no!');\n//           ^\n//   Error: oh no!\n//       at speedy (/home/gbusey/file.js:6:11)\n//       at makeFaster (/home/gbusey/file.js:5:3)\n//       at Object.<anonymous> (/home/gbusey/file.js:10:1)\n//       at Module._compile (module.js:456:26)\n//       at Object.Module._extensions..js (module.js:474:10)\n//       at Module.load (module.js:356:32)\n//       at Function.Module._load (module.js:312:12)\n//       at Function.Module.runMain (module.js:497:10)\n//       at startup (node.js:119:16)\n//       at node.js:906:3\n
      \n

      The location information will be one of:

      \n
        \n
      • native, if the frame represents a call internal to V8 (as in [].forEach).
      • \n
      • plain-filename.js:line:column, if the frame represents a call internal\nto Node.js.
      • \n
      • /absolute/path/to/file.js:line:column, if the frame represents a call in\na user program, or its dependencies.
      • \n
      \n

      The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

      \n

      The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit or the number of available frames on the current event\nloop tick.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ], + "desc": "

      Creates a new Error object and sets the error.message property to the\nprovided text message. If an object is passed as message, the text message\nis generated by calling message.toString(). The error.stack property will\nrepresent the point in the code at which new Error() was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit, whichever is smaller.

      " + } + ] + }, + { + "textRaw": "Class: `AssertionError`", + "type": "class", + "name": "AssertionError", + "desc": "\n

      Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.

      " + }, + { + "textRaw": "Class: `RangeError`", + "type": "class", + "name": "RangeError", + "desc": "\n

      Indicates that a provided argument was not within the set or range of\nacceptable values for a function; whether that is a numeric range, or\noutside the set of options for a given function parameter.

      \n
      require('net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n
      \n

      Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

      " + }, + { + "textRaw": "Class: `ReferenceError`", + "type": "class", + "name": "ReferenceError", + "desc": "\n

      Indicates that an attempt is being made to access a variable that is not\ndefined. Such errors commonly indicate typos in code, or an otherwise broken\nprogram.

      \n

      While client code may generate and propagate these errors, in practice, only V8\nwill do so.

      \n
      doesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n
      \n

      Unless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.

      " + }, + { + "textRaw": "Class: `SyntaxError`", + "type": "class", + "name": "SyntaxError", + "desc": "\n

      Indicates that a program is not valid JavaScript. These errors may only be\ngenerated and propagated as a result of code evaluation. Code evaluation may\nhappen as a result of eval, Function, require, or vm. These errors\nare almost always indicative of a broken program.

      \n
      try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n  // 'err' will be a SyntaxError.\n}\n
      \n

      SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

      " + }, + { + "textRaw": "Class: `SystemError`", + "type": "class", + "name": "SystemError", + "desc": "\n

      Node.js generates system errors when exceptions occur within its runtime\nenvironment. These usually occur when an application violates an operating\nsystem constraint. For example, a system error will occur if an application\nattempts to read a file that does not exist.

      \n
        \n
      • address <string> If present, the address to which a network connection\nfailed
      • \n
      • code <string> The string error code
      • \n
      • dest <string> If present, the file path destination when reporting a file\nsystem error
      • \n
      • errno <number> | <string> The system-provided error number
      • \n
      • info <Object> If present, extra details about the error condition
      • \n
      • message <string> A system-provided human-readable description of the error
      • \n
      • path <string> If present, the file path when reporting a file system error
      • \n
      • port <number> If present, the network connection port that is not available
      • \n
      • syscall <string> The name of the system call that triggered the error
      • \n
      ", + "properties": [ + { + "textRaw": "`address` {string}", + "type": "string", + "name": "address", + "desc": "

      If present, error.address is a string describing the address to which a\nnetwork connection failed.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string representing the error code.

      " + }, + { + "textRaw": "`dest` {string}", + "type": "string", + "name": "dest", + "desc": "

      If present, error.dest is the file path destination when reporting a file\nsystem error.

      " + }, + { + "textRaw": "`errno` {string|number}", + "type": "string|number", + "name": "errno", + "desc": "

      The error.errno property is a number or a string. If it is a number, it is a\nnegative value which corresponds to the error code defined in\nlibuv Error handling. See the libuv errno.h header file\n(deps/uv/include/uv/errno.h in the Node.js source tree) for details. In case\nof a string, it is the same as error.code.

      " + }, + { + "textRaw": "`info` {Object}", + "type": "Object", + "name": "info", + "desc": "

      If present, error.info is an object with details about the error condition.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      error.message is a system-provided human-readable description of the error.

      " + }, + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "desc": "

      If present, error.path is a string containing a relevant invalid pathname.

      " + }, + { + "textRaw": "`port` {number}", + "type": "number", + "name": "port", + "desc": "

      If present, error.port is the network connection port that is not available.

      " + }, + { + "textRaw": "`syscall` {string}", + "type": "string", + "name": "syscall", + "desc": "

      The error.syscall property is a string describing the syscall that failed.

      " + } + ], + "modules": [ + { + "textRaw": "Common system errors", + "name": "common_system_errors", + "desc": "

      This is a list of system errors commonly-encountered when writing a Node.js\nprogram. For a comprehensive list, see the errno(3) man page.

      \n
        \n
      • \n

        EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.

        \n
      • \n
      • \n

        EADDRINUSE (Address already in use): An attempt to bind a server\n(net, http, or https) to a local address failed due to\nanother server on the local system already occupying that address.

        \n
      • \n
      • \n

        ECONNREFUSED (Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.

        \n
      • \n
      • \n

        ECONNRESET (Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http\nand net modules.

        \n
      • \n
      • \n

        EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.

        \n
      • \n
      • \n

        EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.

        \n
      • \n
      • \n

        EMFILE (Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, macOS) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048 in the same shell that will run the Node.js process.

        \n
      • \n
      • \n

        ENOENT (No such file or directory): Commonly raised by fs operations\nto indicate that a component of the specified pathname does not exist. No\nentity (file or directory) could be found by the given path.

        \n
      • \n
      • \n

        ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.

        \n
      • \n
      • \n

        ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.

        \n
      • \n
      • \n

        ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

        \n
      • \n
      • \n

        EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.

        \n
      • \n
      • \n

        EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net and\nhttp layers, indicative that the remote side of the stream being\nwritten to has been closed.

        \n
      • \n
      • \n

        ETIMEDOUT (Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http or net. Often a sign that a socket.end()\nwas not properly called.

        \n
      • \n
      ", + "type": "module", + "displayName": "Common system errors" + } + ] + }, + { + "textRaw": "Class: `TypeError`", + "type": "class", + "name": "TypeError", + "desc": "\n

      Indicates that a provided argument is not an allowable type. For example,\npassing a function to a parameter which expects a string would be a TypeError.

      \n
      require('url').parse(() => { });\n// Throws TypeError, since it expected a string.\n
      \n

      Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

      " + } + ], + "globals": [ + { + "textRaw": "Class: `Buffer`", + "type": "global", + "name": "Buffer", + "meta": { + "added": [ + "v0.1.103" + ], + "changes": [] + }, + "desc": "\n

      Used to handle binary data. See the buffer section.

      " + }, + { + "textRaw": "`clearImmediate(immediateObject)`", + "type": "global", + "name": "clearImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      clearImmediate is described in the timers section.

      " + }, + { + "textRaw": "`clearInterval(intervalObject)`", + "type": "global", + "name": "clearInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearInterval is described in the timers section.

      " + }, + { + "textRaw": "`clearTimeout(timeoutObject)`", + "type": "global", + "name": "clearTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearTimeout is described in the timers section.

      " + }, + { + "textRaw": "`console`", + "name": "`console`", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      Used to print to stdout and stderr. See the console section.

      " + }, + { + "textRaw": "`global`", + "name": "`global`", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "type": "global", + "desc": "
        \n
      • <Object> The global namespace object.
      • \n
      \n

      In browsers, the top-level scope is the global scope. This means that\nwithin the browser var something will define a new global variable. In\nNode.js this is different. The top-level scope is not the global scope;\nvar something inside a Node.js module will be local to that module.

      " + }, + { + "textRaw": "`process`", + "name": "`process`", + "meta": { + "added": [ + "v0.1.7" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The process object. See the process object section.

      " + }, + { + "textRaw": "`queueMicrotask(callback)`", + "type": "global", + "name": "queueMicrotask", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "desc": "\n

      The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.

      \n

      The microtask queue is managed by V8 and may be used in a similar manner to\nthe process.nextTick() queue, which is managed by Node.js. The\nprocess.nextTick() queue is always processed before the microtask queue\nwithin each turn of the Node.js event loop.

      \n
      // Here, `queueMicrotask()` is used to ensure the 'load' event is always\n// emitted asynchronously, and therefore consistently. Using\n// `process.nextTick()` here would result in the 'load' event always emitting\n// before any other promise jobs.\n\nDataHandler.prototype.load = async function load(key) {\n  const hit = this._cache.get(url);\n  if (hit !== undefined) {\n    queueMicrotask(() => {\n      this.emit('load', hit);\n    });\n    return;\n  }\n\n  const data = await fetchData(key);\n  this._cache.set(url, data);\n  this.emit('load', data);\n};\n
      " + }, + { + "textRaw": "`setImmediate(callback[, ...args])`", + "type": "global", + "name": "setImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      setImmediate is described in the timers section.

      " + }, + { + "textRaw": "`setInterval(callback, delay[, ...args])`", + "type": "global", + "name": "setInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setInterval is described in the timers section.

      " + }, + { + "textRaw": "`setTimeout(callback, delay[, ...args])`", + "type": "global", + "name": "setTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setTimeout is described in the timers section.

      " + }, + { + "textRaw": "`TextDecoder`", + "name": "`TextDecoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextDecoder class. See the TextDecoder section.

      " + }, + { + "textRaw": "`TextEncoder`", + "name": "`TextEncoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextEncoder class. See the TextEncoder section.

      " + }, + { + "textRaw": "`URL`", + "name": "`URL`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URL class. See the URL section.

      " + }, + { + "textRaw": "`URLSearchParams`", + "name": "`URLSearchParams`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URLSearchParams class. See the URLSearchParams section.

      " + }, + { + "textRaw": "`WebAssembly`", + "name": "`WebAssembly`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.

      " + }, + { + "textRaw": "Process", + "name": "Process", + "introduced_in": "v0.10.0", + "type": "global", + "desc": "

      Source Code: lib/process.js

      \n

      The process object is a global that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require(). It can also be explicitly\naccessed using require():

      \n
      const process = require('process');\n
      ", + "modules": [ + { + "textRaw": "Process events", + "name": "process_events", + "desc": "

      The process object is an instance of EventEmitter.

      ", + "events": [ + { + "textRaw": "Event: `'beforeExit'`", + "type": "event", + "name": "beforeExit", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'beforeExit' event is emitted when Node.js empties its event loop and has\nno additional work to schedule. Normally, the Node.js process will exit when\nthere is no work scheduled, but a listener registered on the 'beforeExit'\nevent can make asynchronous calls, and thereby cause the Node.js process to\ncontinue.

      \n

      The listener callback function is invoked with the value of\nprocess.exitCode passed as the only argument.

      \n

      The 'beforeExit' event is not emitted for conditions causing explicit\ntermination, such as calling process.exit() or uncaught exceptions.

      \n

      The 'beforeExit' should not be used as an alternative to the 'exit' event\nunless the intention is to schedule additional work.

      \n
      process.on('beforeExit', (code) => {\n  console.log('Process beforeExit event with code: ', code);\n});\n\nprocess.on('exit', (code) => {\n  console.log('Process exit event with code: ', code);\n});\n\nconsole.log('This message is displayed first.');\n\n// Prints:\n// This message is displayed first.\n// Process beforeExit event with code: 0\n// Process exit event with code: 0\n
      " + }, + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'disconnect' event will be emitted when\nthe IPC channel is closed.

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.1.7" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {integer}", + "name": "code", + "type": "integer" + } + ], + "desc": "

      The 'exit' event is emitted when the Node.js process is about to exit as a\nresult of either:

      \n
        \n
      • The process.exit() method being called explicitly;
      • \n
      • The Node.js event loop no longer having any additional work to perform.
      • \n
      \n

      There is no way to prevent the exiting of the event loop at this point, and once\nall 'exit' listeners have finished running the Node.js process will terminate.

      \n

      The listener callback function is invoked with the exit code specified either\nby the process.exitCode property, or the exitCode argument passed to the\nprocess.exit() method.

      \n
      process.on('exit', (code) => {\n  console.log(`About to exit with code: ${code}`);\n});\n
      \n

      Listener functions must only perform synchronous operations. The Node.js\nprocess will exit immediately after calling the 'exit' event listeners\ncausing any additional work still queued in the event loop to be abandoned.\nIn the following example, for instance, the timeout will never occur:

      \n
      process.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`message` { Object | boolean | number | string | null } a parsed JSON object or a serializable primitive value.", + "name": "message", + "type": " Object | boolean | number | string | null ", + "desc": "a parsed JSON object or a serializable primitive value." + }, + { + "textRaw": "`sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] object, or undefined.", + "name": "sendHandle", + "type": "net.Server|net.Socket", + "desc": "a [`net.Server`][] or [`net.Socket`][] object, or undefined." + } + ], + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'message' event is emitted whenever a\nmessage sent by a parent process using childprocess.send() is received by\nthe child process.

      \n

      The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.

      \n

      If the serialization option was set to advanced used when spawning the\nprocess, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for child_process for more details.

      " + }, + { + "textRaw": "Event: `'multipleResolves'`", + "type": "event", + "name": "multipleResolves", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`type` {string} The resolution type. One of `'resolve'` or `'reject'`.", + "name": "type", + "type": "string", + "desc": "The resolution type. One of `'resolve'` or `'reject'`." + }, + { + "textRaw": "`promise` {Promise} The promise that resolved or rejected more than once.", + "name": "promise", + "type": "Promise", + "desc": "The promise that resolved or rejected more than once." + }, + { + "textRaw": "`value` {any} The value with which the promise was either resolved or rejected after the original resolve.", + "name": "value", + "type": "any", + "desc": "The value with which the promise was either resolved or rejected after the original resolve." + } + ], + "desc": "

      The 'multipleResolves' event is emitted whenever a Promise has been either:

      \n
        \n
      • Resolved more than once.
      • \n
      • Rejected more than once.
      • \n
      • Rejected after resolve.
      • \n
      • Resolved after reject.
      • \n
      \n

      This is useful for tracking potential errors in an application while using the\nPromise constructor, as multiple resolutions are silently swallowed. However,\nthe occurrence of this event does not necessarily indicate an error. For\nexample, Promise.race() can trigger a 'multipleResolves' event.

      \n
      process.on('multipleResolves', (type, promise, reason) => {\n  console.error(type, promise, reason);\n  setImmediate(() => process.exit(1));\n});\n\nasync function main() {\n  try {\n    return await new Promise((resolve, reject) => {\n      resolve('First call');\n      resolve('Swallowed resolve');\n      reject(new Error('Swallowed reject'));\n    });\n  } catch {\n    throw new Error('Failed');\n  }\n}\n\nmain().then(console.log);\n// resolve: Promise { 'First call' } 'Swallowed resolve'\n// reject: Promise { 'First call' } Error: Swallowed reject\n//     at Promise (*)\n//     at new Promise (<anonymous>)\n//     at main (*)\n// First call\n
      " + }, + { + "textRaw": "Event: `'rejectionHandled'`", + "type": "event", + "name": "rejectionHandled", + "meta": { + "added": [ + "v1.4.1" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`promise` {Promise} The late handled promise.", + "name": "promise", + "type": "Promise", + "desc": "The late handled promise." + } + ], + "desc": "

      The 'rejectionHandled' event is emitted whenever a Promise has been rejected\nand an error handler was attached to it (using promise.catch(), for\nexample) later than one turn of the Node.js event loop.

      \n

      The Promise object would have previously been emitted in an\n'unhandledRejection' event, but during the course of processing gained a\nrejection handler.

      \n

      There is no notion of a top level for a Promise chain at which rejections can\nalways be handled. Being inherently asynchronous in nature, a Promise\nrejection can be handled at a future point in time, possibly much later than\nthe event loop turn it takes for the 'unhandledRejection' event to be emitted.

      \n

      Another way of stating this is that, unlike in synchronous code where there is\nan ever-growing list of unhandled exceptions, with Promises there can be a\ngrowing-and-shrinking list of unhandled rejections.

      \n

      In synchronous code, the 'uncaughtException' event is emitted when the list of\nunhandled exceptions grows.

      \n

      In asynchronous code, the 'unhandledRejection' event is emitted when the list\nof unhandled rejections grows, and the 'rejectionHandled' event is emitted\nwhen the list of unhandled rejections shrinks.

      \n
      const unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, promise) => {\n  unhandledRejections.set(promise, reason);\n});\nprocess.on('rejectionHandled', (promise) => {\n  unhandledRejections.delete(promise);\n});\n
      \n

      In this example, the unhandledRejections Map will grow and shrink over time,\nreflecting rejections that start unhandled and then become handled. It is\npossible to record such errors in an error log, either periodically (which is\nlikely best for long-running application) or upon process exit (which is likely\nmost convenient for scripts).

      " + }, + { + "textRaw": "Event: `'uncaughtException'`", + "type": "event", + "name": "uncaughtException", + "meta": { + "added": [ + "v0.1.18" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26599", + "description": "Added the `origin` argument." + } + ] + }, + "params": [ + { + "textRaw": "`err` {Error} The uncaught exception.", + "name": "err", + "type": "Error", + "desc": "The uncaught exception." + }, + { + "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` and an unhandled rejection.", + "name": "origin", + "type": "string", + "desc": "Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` and an unhandled rejection." + } + ], + "desc": "

      The 'uncaughtException' event is emitted when an uncaught JavaScript\nexception bubbles all the way back to the event loop. By default, Node.js\nhandles such exceptions by printing the stack trace to stderr and exiting\nwith code 1, overriding any previously set process.exitCode.\nAdding a handler for the 'uncaughtException' event overrides this default\nbehavior. Alternatively, change the process.exitCode in the\n'uncaughtException' handler which will result in the process exiting with the\nprovided exit code. Otherwise, in the presence of such handler the process will\nexit with 0.

      \n
      process.on('uncaughtException', (err, origin) => {\n  fs.writeSync(\n    process.stderr.fd,\n    `Caught exception: ${err}\\n` +\n    `Exception origin: ${origin}`\n  );\n});\n\nsetTimeout(() => {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
      \n

      It is possible to monitor 'uncaughtException' events without overriding the\ndefault behavior to exit the process by installing a\n'uncaughtExceptionMonitor' listener.

      ", + "modules": [ + { + "textRaw": "Warning: Using `'uncaughtException'` correctly", + "name": "warning:_using_`'uncaughtexception'`_correctly", + "desc": "

      'uncaughtException' is a crude mechanism for exception handling\nintended to be used only as a last resort. The event should not be used as\nan equivalent to On Error Resume Next. Unhandled exceptions inherently mean\nthat an application is in an undefined state. Attempting to resume application\ncode without properly recovering from the exception can cause additional\nunforeseen and unpredictable issues.

      \n

      Exceptions thrown from within the event handler will not be caught. Instead the\nprocess will exit with a non-zero exit code and the stack trace will be printed.\nThis is to avoid infinite recursion.

      \n

      Attempting to resume normally after an uncaught exception can be similar to\npulling out the power cord when upgrading a computer. Nine out of ten\ntimes, nothing happens. But the tenth time, the system becomes corrupted.

      \n

      The correct use of 'uncaughtException' is to perform synchronous cleanup\nof allocated resources (e.g. file descriptors, handles, etc) before shutting\ndown the process. It is not safe to resume normal operation after\n'uncaughtException'.

      \n

      To restart a crashed application in a more reliable way, whether\n'uncaughtException' is emitted or not, an external monitor should be employed\nin a separate process to detect application failures and recover or restart as\nneeded.

      ", + "type": "module", + "displayName": "Warning: Using `'uncaughtException'` correctly" + } + ] + }, + { + "textRaw": "Event: `'uncaughtExceptionMonitor'`", + "type": "event", + "name": "uncaughtExceptionMonitor", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`err` {Error} The uncaught exception.", + "name": "err", + "type": "Error", + "desc": "The uncaught exception." + }, + { + "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`.", + "name": "origin", + "type": "string", + "desc": "Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`." + } + ], + "desc": "

      The 'uncaughtExceptionMonitor' event is emitted before an\n'uncaughtException' event is emitted or a hook installed via\nprocess.setUncaughtExceptionCaptureCallback() is called.

      \n

      Installing an 'uncaughtExceptionMonitor' listener does not change the behavior\nonce an 'uncaughtException' event is emitted. The process will\nstill crash if no 'uncaughtException' listener is installed.

      \n
      process.on('uncaughtExceptionMonitor', (err, origin) => {\n  MyMonitoringTool.logSync(err, origin);\n});\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\n// Still crashes Node.js\n
      " + }, + { + "textRaw": "Event: `'unhandledRejection'`", + "type": "event", + "name": "unhandledRejection", + "meta": { + "added": [ + "v1.4.1" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8217", + "description": "Not handling `Promise` rejections is deprecated." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8223", + "description": "Unhandled `Promise` rejections will now emit a process warning." + } + ] + }, + "params": [ + { + "textRaw": "`reason` {Error|any} The object with which the promise was rejected (typically an [`Error`][] object).", + "name": "reason", + "type": "Error|any", + "desc": "The object with which the promise was rejected (typically an [`Error`][] object)." + }, + { + "textRaw": "`promise` {Promise} The rejected promise.", + "name": "promise", + "type": "Promise", + "desc": "The rejected promise." + } + ], + "desc": "

      The 'unhandledRejection' event is emitted whenever a Promise is rejected and\nno error handler is attached to the promise within a turn of the event loop.\nWhen programming with Promises, exceptions are encapsulated as \"rejected\npromises\". Rejections can be caught and handled using promise.catch() and\nare propagated through a Promise chain. The 'unhandledRejection' event is\nuseful for detecting and keeping track of promises that were rejected whose\nrejections have not yet been handled.

      \n
      process.on('unhandledRejection', (reason, promise) => {\n  console.log('Unhandled Rejection at:', promise, 'reason:', reason);\n  // Application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)\n}); // No `.catch()` or `.then()`\n
      \n

      The following will also trigger the 'unhandledRejection' event to be\nemitted:

      \n
      function SomeResource() {\n  // Initially set the loaded status to a rejected promise\n  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));\n}\n\nconst resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn\n
      \n

      In this example case, it is possible to track the rejection as a developer error\nas would typically be the case for other 'unhandledRejection' events. To\naddress such failures, a non-operational\n.catch(() => { }) handler may be attached to\nresource.loaded, which would prevent the 'unhandledRejection' event from\nbeing emitted.

      " + }, + { + "textRaw": "Event: `'warning'`", + "type": "event", + "name": "warning", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`warning` {Error} Key properties of the warning are:", + "name": "warning", + "type": "Error", + "desc": "Key properties of the warning are:", + "options": [ + { + "textRaw": "`name` {string} The name of the warning. **Default:** `'Warning'`.", + "name": "name", + "type": "string", + "default": "`'Warning'`", + "desc": "The name of the warning." + }, + { + "textRaw": "`message` {string} A system-provided description of the warning.", + "name": "message", + "type": "string", + "desc": "A system-provided description of the warning." + }, + { + "textRaw": "`stack` {string} A stack trace to the location in the code where the warning was issued.", + "name": "stack", + "type": "string", + "desc": "A stack trace to the location in the code where the warning was issued." + } + ] + } + ], + "desc": "

      The 'warning' event is emitted whenever Node.js emits a process warning.

      \n

      A process warning is similar to an error in that it describes exceptional\nconditions that are being brought to the user's attention. However, warnings\nare not part of the normal Node.js and JavaScript error handling flow.\nNode.js can emit warnings whenever it detects bad coding practices that could\nlead to sub-optimal application performance, bugs, or security vulnerabilities.

      \n
      process.on('warning', (warning) => {\n  console.warn(warning.name);    // Print the warning name\n  console.warn(warning.message); // Print the warning message\n  console.warn(warning.stack);   // Print the stack trace\n});\n
      \n

      By default, Node.js will print process warnings to stderr. The --no-warnings\ncommand-line option can be used to suppress the default console output but the\n'warning' event will still be emitted by the process object.

      \n

      The following example illustrates the warning that is printed to stderr when\ntoo many listeners have been added to an event:

      \n
      $ node\n> events.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak\ndetected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit\n
      \n

      In contrast, the following example turns off the default warning output and\nadds a custom handler to the 'warning' event:

      \n
      $ node --no-warnings\n> const p = process.on('warning', (warning) => console.warn('Do not do that!'));\n> events.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> Do not do that!\n
      \n

      The --trace-warnings command-line option can be used to have the default\nconsole output for warnings include the full stack trace of the warning.

      \n

      Launching Node.js using the --throw-deprecation command line flag will\ncause custom deprecation warnings to be thrown as exceptions.

      \n

      Using the --trace-deprecation command line flag will cause the custom\ndeprecation to be printed to stderr along with the stack trace.

      \n

      Using the --no-deprecation command line flag will suppress all reporting\nof the custom deprecation.

      \n

      The *-deprecation command line flags only affect warnings that use the name\n'DeprecationWarning'.

      ", + "modules": [ + { + "textRaw": "Emitting custom warnings", + "name": "emitting_custom_warnings", + "desc": "

      See the process.emitWarning() method for issuing\ncustom or application-specific warnings.

      ", + "type": "module", + "displayName": "Emitting custom warnings" + } + ] + }, + { + "textRaw": "Signal events", + "name": "SIGINT, SIGHUP, etc.", + "type": "event", + "params": [], + "desc": "

      Signal events will be emitted when the Node.js process receives a signal. Please\nrefer to signal(7) for a listing of standard POSIX signal names such as\n'SIGINT', 'SIGHUP', etc.

      \n

      Signals are not available on Worker threads.

      \n

      The signal handler will receive the signal's name ('SIGINT',\n'SIGTERM', etc.) as the first argument.

      \n

      The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT' for SIGINT signals).

      \n
      // Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Received SIGINT. Press Control-D to exit.');\n});\n\n// Using a single function to handle multiple signals\nfunction handle(signal) {\n  console.log(`Received ${signal}`);\n}\n\nprocess.on('SIGINT', handle);\nprocess.on('SIGTERM', handle);\n
      \n
        \n
      • 'SIGUSR1' is reserved by Node.js to start the debugger. It's possible to\ninstall a listener but doing so might interfere with the debugger.
      • \n
      • 'SIGTERM' and 'SIGINT' have default handlers on non-Windows platforms that\nreset the terminal mode before exiting with code 128 + signal number. If one\nof these signals has a listener installed, its default behavior will be\nremoved (Node.js will no longer exit).
      • \n
      • 'SIGPIPE' is ignored by default. It can have a listener installed.
      • \n
      • 'SIGHUP' is generated on Windows when the console window is closed, and on\nother platforms under various similar conditions. See signal(7). It can have a\nlistener installed, however Node.js will be unconditionally terminated by\nWindows about 10 seconds later. On non-Windows platforms, the default\nbehavior of SIGHUP is to terminate Node.js, but once a listener has been\ninstalled its default behavior will be removed.
      • \n
      • 'SIGTERM' is not supported on Windows, it can be listened on.
      • \n
      • 'SIGINT' from the terminal is supported on all platforms, and can usually be\ngenerated with Ctrl+C (though this may be configurable).\nIt is not generated when terminal raw mode is enabled and\nCtrl+C is used.
      • \n
      • 'SIGBREAK' is delivered on Windows when Ctrl+Break is\npressed. On non-Windows platforms, it can be listened on, but there is no way\nto send or generate it.
      • \n
      • 'SIGWINCH' is delivered when the console has been resized. On Windows, this\nwill only happen on write to the console when the cursor is being moved, or\nwhen a readable tty is used in raw mode.
      • \n
      • 'SIGKILL' cannot have a listener installed, it will unconditionally\nterminate Node.js on all platforms.
      • \n
      • 'SIGSTOP' cannot have a listener installed.
      • \n
      • 'SIGBUS', 'SIGFPE', 'SIGSEGV' and 'SIGILL', when not raised\n artificially using kill(2), inherently leave the process in a state from\n which it is not safe to attempt to call JS listeners. Doing so might lead to\n the process hanging in an endless loop, since listeners attached using\n process.on() are called asynchronously and therefore unable to correct the\nunderlying problem.
      • \n
      • 0 can be sent to test for the existence of a process, it has no effect if\nthe process exists, but will throw an error if the process does not exist.
      • \n
      \n

      Windows does not support signals so has no equivalent to termination by signal,\nbut Node.js offers some emulation with process.kill(), and\nsubprocess.kill():

      \n
        \n
      • Sending SIGINT, SIGTERM, and SIGKILL will cause the unconditional\ntermination of the target process, and afterwards, subprocess will report that\nthe process was terminated by signal.
      • \n
      • Sending signal 0 can be used as a platform independent way to test for the\nexistence of a process.
      • \n
      " + } + ], + "type": "module", + "displayName": "Process events" + }, + { + "textRaw": "Exit codes", + "name": "exit_codes", + "desc": "

      Node.js will normally exit with a 0 status code when no more async\noperations are pending. The following status codes are used in other\ncases:

      \n
        \n
      • 1 Uncaught Fatal Exception: There was an uncaught exception,\nand it was not handled by a domain or an 'uncaughtException' event\nhandler.
      • \n
      • 2: Unused (reserved by Bash for builtin misuse)
      • \n
      • 3 Internal JavaScript Parse Error: The JavaScript source code\ninternal in the Node.js bootstrapping process caused a parse error. This\nis extremely rare, and generally can only happen during development\nof Node.js itself.
      • \n
      • 4 Internal JavaScript Evaluation Failure: The JavaScript\nsource code internal in the Node.js bootstrapping process failed to\nreturn a function value when evaluated. This is extremely rare, and\ngenerally can only happen during development of Node.js itself.
      • \n
      • 5 Fatal Error: There was a fatal unrecoverable error in V8.\nTypically a message will be printed to stderr with the prefix FATAL ERROR.
      • \n
      • 6 Non-function Internal Exception Handler: There was an\nuncaught exception, but the internal fatal exception handler\nfunction was somehow set to a non-function, and could not be called.
      • \n
      • 7 Internal Exception Handler Run-Time Failure: There was an\nuncaught exception, and the internal fatal exception handler\nfunction itself threw an error while attempting to handle it. This\ncan happen, for example, if an 'uncaughtException' or\ndomain.on('error') handler throws an error.
      • \n
      • 8: Unused. In previous versions of Node.js, exit code 8 sometimes\nindicated an uncaught exception.
      • \n
      • 9 Invalid Argument: Either an unknown option was specified,\nor an option requiring a value was provided without a value.
      • \n
      • 10 Internal JavaScript Run-Time Failure: The JavaScript\nsource code internal in the Node.js bootstrapping process threw an error\nwhen the bootstrapping function was called. This is extremely rare,\nand generally can only happen during development of Node.js itself.
      • \n
      • 12 Invalid Debug Argument: The --inspect and/or --inspect-brk\noptions were set, but the port number chosen was invalid or unavailable.
      • \n
      • >128 Signal Exits: If Node.js receives a fatal signal such as\nSIGKILL or SIGHUP, then its exit code will be 128 plus the\nvalue of the signal code. This is a standard POSIX practice, since\nexit codes are defined to be 7-bit integers, and signal exits set\nthe high-order bit, and then contain the value of the signal code.\nFor example, signal SIGABRT has value 6, so the expected exit\ncode will be 128 + 6, or 134.
      • \n
      ", + "type": "module", + "displayName": "Exit codes" + } + ], + "methods": [ + { + "textRaw": "`process.abort()`", + "type": "method", + "name": "abort", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The process.abort() method causes the Node.js process to exit immediately and\ngenerate a core file.

      \n

      This feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.chdir(directory)`", + "type": "method", + "name": "chdir", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`directory` {string}", + "name": "directory", + "type": "string" + } + ] + } + ], + "desc": "

      The process.chdir() method changes the current working directory of the\nNode.js process or throws an exception if doing so fails (for instance, if\nthe specified directory does not exist).

      \n
      console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n} catch (err) {\n  console.error(`chdir: ${err}`);\n}\n
      \n

      This feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.cpuUsage([previousValue])`", + "type": "method", + "name": "cpuUsage", + "meta": { + "added": [ + "v6.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`user` {integer}", + "name": "user", + "type": "integer" + }, + { + "textRaw": "`system` {integer}", + "name": "system", + "type": "integer" + } + ] + }, + "params": [ + { + "textRaw": "`previousValue` {Object} A previous return value from calling `process.cpuUsage()`", + "name": "previousValue", + "type": "Object", + "desc": "A previous return value from calling `process.cpuUsage()`" + } + ] + } + ], + "desc": "

      The process.cpuUsage() method returns the user and system CPU time usage of\nthe current process, in an object with properties user and system, whose\nvalues are microsecond values (millionth of a second). These values measure time\nspent in user and system code respectively, and may end up being greater than\nactual elapsed time if multiple CPU cores are performing work for this process.

      \n

      The result of a previous call to process.cpuUsage() can be passed as the\nargument to the function, to get a diff reading.

      \n
      const startUsage = process.cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
      " + }, + { + "textRaw": "`process.cwd()`", + "type": "method", + "name": "cwd", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      The process.cwd() method returns the current working directory of the Node.js\nprocess.

      \n
      console.log(`Current directory: ${process.cwd()}`);\n
      " + }, + { + "textRaw": "`process.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.disconnect() method will close the\nIPC channel to the parent process, allowing the child process to exit gracefully\nonce there are no other connections keeping it alive.

      \n

      The effect of calling process.disconnect() is the same as calling\nChildProcess.disconnect() from the parent process.

      \n

      If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect() will be undefined.

      " + }, + { + "textRaw": "`process.dlopen(module, filename[, flags])`", + "type": "method", + "name": "dlopen", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12794", + "description": "Added support for the `flags` argument." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`module` {Object}", + "name": "module", + "type": "Object" + }, + { + "textRaw": "`filename` {string}", + "name": "filename", + "type": "string" + }, + { + "textRaw": "`flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY`", + "name": "flags", + "type": "os.constants.dlopen", + "default": "`os.constants.dlopen.RTLD_LAZY`" + } + ] + } + ], + "desc": "

      The process.dlopen() method allows to dynamically load shared\nobjects. It is primarily used by require() to load\nC++ Addons, and should not be used directly, except in special\ncases. In other words, require() should be preferred over\nprocess.dlopen(), unless there are specific reasons.

      \n

      The flags argument is an integer that allows to specify dlopen\nbehavior. See the os.constants.dlopen documentation for details.

      \n

      If there are specific reasons to use process.dlopen() (for instance,\nto specify dlopen flags), it's often useful to use require.resolve()\nto look up the module's path.

      \n

      An important drawback when calling process.dlopen() is that the module\ninstance must be passed. Functions exported by the C++ Addon will be accessible\nvia module.exports.

      \n

      The example below shows how to load a C++ Addon, named as binding,\nthat exports a foo function. All the symbols will be loaded before\nthe call returns, by passing the RTLD_NOW constant. In this example\nthe constant is assumed to be available.

      \n
      const os = require('os');\nprocess.dlopen(module, require.resolve('binding'),\n               os.constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
      " + }, + { + "textRaw": "`process.emitWarning(warning[, options])`", + "type": "method", + "name": "emitWarning", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`warning` {string|Error} The warning to emit.", + "name": "warning", + "type": "string|Error", + "desc": "The warning to emit." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", + "name": "type", + "type": "string", + "default": "`'Warning'`", + "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." + }, + { + "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", + "name": "code", + "type": "string", + "desc": "A unique identifier for the warning instance being emitted." + }, + { + "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", + "name": "ctor", + "type": "Function", + "default": "`process.emitWarning`", + "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." + }, + { + "textRaw": "`detail` {string} Additional text to include with the error.", + "name": "detail", + "type": "string", + "desc": "Additional text to include with the error." + } + ] + } + ] + } + ], + "desc": "

      The process.emitWarning() method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\n'warning' event.

      \n
      // Emit a warning with a code and additional detail.\nprocess.emitWarning('Something happened!', {\n  code: 'MY_WARNING',\n  detail: 'This is some additional information'\n});\n// Emits:\n// (node:56338) [MY_WARNING] Warning: Something happened!\n// This is some additional information\n
      \n

      In this example, an Error object is generated internally by\nprocess.emitWarning() and passed through to the\n'warning' handler.

      \n
      process.on('warning', (warning) => {\n  console.warn(warning.name);    // 'Warning'\n  console.warn(warning.message); // 'Something happened!'\n  console.warn(warning.code);    // 'MY_WARNING'\n  console.warn(warning.stack);   // Stack trace\n  console.warn(warning.detail);  // 'This is some additional information'\n});\n
      \n

      If warning is passed as an Error object, the options argument is ignored.

      " + }, + { + "textRaw": "`process.emitWarning(warning[, type[, code]][, ctor])`", + "type": "method", + "name": "emitWarning", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`warning` {string|Error} The warning to emit.", + "name": "warning", + "type": "string|Error", + "desc": "The warning to emit." + }, + { + "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", + "name": "type", + "type": "string", + "default": "`'Warning'`", + "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." + }, + { + "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", + "name": "code", + "type": "string", + "desc": "A unique identifier for the warning instance being emitted." + }, + { + "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", + "name": "ctor", + "type": "Function", + "default": "`process.emitWarning`", + "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." + } + ] + } + ], + "desc": "

      The process.emitWarning() method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\n'warning' event.

      \n
      // Emit a warning using a string.\nprocess.emitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
      \n
      // Emit a warning using a string and a type.\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
      \n
      process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
      \n

      In each of the previous examples, an Error object is generated internally by\nprocess.emitWarning() and passed through to the 'warning'\nhandler.

      \n
      process.on('warning', (warning) => {\n  console.warn(warning.name);\n  console.warn(warning.message);\n  console.warn(warning.code);\n  console.warn(warning.stack);\n});\n
      \n

      If warning is passed as an Error object, it will be passed through to the\n'warning' event handler unmodified (and the optional type,\ncode and ctor arguments will be ignored):

      \n
      // Emit a warning using an Error object.\nconst myWarning = new Error('Something happened!');\n// Use the Error name property to specify the type name\nmyWarning.name = 'CustomWarning';\nmyWarning.code = 'WARN001';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
      \n

      A TypeError is thrown if warning is anything other than a string or Error\nobject.

      \n

      While process warnings use Error objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.

      \n

      The following additional handling is implemented if the warning type is\n'DeprecationWarning':

      \n
        \n
      • If the --throw-deprecation command-line flag is used, the deprecation\nwarning is thrown as an exception rather than being emitted as an event.
      • \n
      • If the --no-deprecation command-line flag is used, the deprecation\nwarning is suppressed.
      • \n
      • If the --trace-deprecation command-line flag is used, the deprecation\nwarning is printed to stderr along with the full stack trace.
      • \n
      ", + "modules": [ + { + "textRaw": "Avoiding duplicate warnings", + "name": "avoiding_duplicate_warnings", + "desc": "

      As a best practice, warnings should be emitted only once per process. To do\nso, it is recommended to place the emitWarning() behind a simple boolean\nflag as illustrated in the example below:

      \n
      function emitMyWarning() {\n  if (!emitMyWarning.warned) {\n    emitMyWarning.warned = true;\n    process.emitWarning('Only warn once!');\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
      ", + "type": "module", + "displayName": "Avoiding duplicate warnings" + } + ] + }, + { + "textRaw": "`process.exit([code])`", + "type": "method", + "name": "exit", + "meta": { + "added": [ + "v0.1.13" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {integer} The exit code. **Default:** `0`.", + "name": "code", + "type": "integer", + "default": "`0`", + "desc": "The exit code." + } + ] + } + ], + "desc": "

      The process.exit() method instructs Node.js to terminate the process\nsynchronously with an exit status of code. If code is omitted, exit uses\neither the 'success' code 0 or the value of process.exitCode if it has been\nset. Node.js will not terminate until all the 'exit' event listeners are\ncalled.

      \n

      To exit with a 'failure' code:

      \n
      process.exit(1);\n
      \n

      The shell that executed Node.js should see the exit code as 1.

      \n

      Calling process.exit() will force the process to exit as quickly as possible\neven if there are still asynchronous operations pending that have not yet\ncompleted fully, including I/O operations to process.stdout and\nprocess.stderr.

      \n

      In most situations, it is not actually necessary to call process.exit()\nexplicitly. The Node.js process will exit on its own if there is no additional\nwork pending in the event loop. The process.exitCode property can be set to\ntell the process which exit code to use when the process exits gracefully.

      \n

      For instance, the following example illustrates a misuse of the\nprocess.exit() method that could lead to data printed to stdout being\ntruncated and lost:

      \n
      // This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exit(1);\n}\n
      \n

      The reason this is problematic is because writes to process.stdout in Node.js\nare sometimes asynchronous and may occur over multiple ticks of the Node.js\nevent loop. Calling process.exit(), however, forces the process to exit\nbefore those additional writes to stdout can be performed.

      \n

      Rather than calling process.exit() directly, the code should set the\nprocess.exitCode and allow the process to exit naturally by avoiding\nscheduling any additional work for the event loop:

      \n
      // How to properly set the exit code while letting\n// the process exit gracefully.\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exitCode = 1;\n}\n
      \n

      If it is necessary to terminate the Node.js process due to an error condition,\nthrowing an uncaught error and allowing the process to terminate accordingly\nis safer than calling process.exit().

      \n

      In Worker threads, this function stops the current thread rather\nthan the current process.

      " + }, + { + "textRaw": "`process.getegid()`", + "type": "method", + "name": "getegid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The process.getegid() method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)

      \n
      if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.geteuid()`", + "type": "method", + "name": "geteuid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      The process.geteuid() method returns the numerical effective user identity of\nthe process. (See geteuid(2).)

      \n
      if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.getgid()`", + "type": "method", + "name": "getgid", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      The process.getgid() method returns the numerical group identity of the\nprocess. (See getgid(2).)

      \n
      if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.getgroups()`", + "type": "method", + "name": "getgroups", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer[]}", + "name": "return", + "type": "integer[]" + }, + "params": [] + } + ], + "desc": "

      The process.getgroups() method returns an array with the supplementary group\nIDs. POSIX leaves it unspecified if the effective group ID is included but\nNode.js ensures it always is.

      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.getuid()`", + "type": "method", + "name": "getuid", + "meta": { + "added": [ + "v0.1.28" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      The process.getuid() method returns the numeric user identity of the process.\n(See getuid(2).)

      \n
      if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.hasUncaughtExceptionCaptureCallback()`", + "type": "method", + "name": "hasUncaughtExceptionCaptureCallback", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Indicates whether a callback has been set using\nprocess.setUncaughtExceptionCaptureCallback().

      " + }, + { + "textRaw": "`process.hrtime([time])`", + "type": "method", + "name": "hrtime", + "meta": { + "added": [ + "v0.7.6" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer[]}", + "name": "return", + "type": "integer[]" + }, + "params": [ + { + "textRaw": "`time` {integer[]} The result of a previous call to `process.hrtime()`", + "name": "time", + "type": "integer[]", + "desc": "The result of a previous call to `process.hrtime()`" + } + ] + } + ], + "desc": "

      This is the legacy version of process.hrtime.bigint()\nbefore bigint was introduced in JavaScript.

      \n

      The process.hrtime() method returns the current high-resolution real time\nin a [seconds, nanoseconds] tuple Array, where nanoseconds is the\nremaining part of the real time that can't be represented in second precision.

      \n

      time is an optional parameter that must be the result of a previous\nprocess.hrtime() call to diff with the current time. If the parameter\npassed in is not a tuple Array, a TypeError will be thrown. Passing in a\nuser-defined array instead of the result of a previous call to\nprocess.hrtime() will lead to undefined behavior.

      \n

      These times are relative to an arbitrary time in the\npast, and not related to the time of day and therefore not subject to clock\ndrift. The primary use is for measuring performance between intervals:

      \n
      const NS_PER_SEC = 1e9;\nconst time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);\n  // Benchmark took 1000000552 nanoseconds\n}, 1000);\n
      " + }, + { + "textRaw": "`process.hrtime.bigint()`", + "type": "method", + "name": "bigint", + "meta": { + "added": [ + "v10.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [] + } + ], + "desc": "

      The bigint version of the process.hrtime() method returning the\ncurrent high-resolution real time in nanoseconds as a bigint.

      \n

      Unlike process.hrtime(), it does not support an additional time\nargument since the difference can just be computed directly\nby subtraction of the two bigints.

      \n
      const start = process.hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n  const end = process.hrtime.bigint();\n  // 191052633396993n\n\n  console.log(`Benchmark took ${end - start} nanoseconds`);\n  // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
      " + }, + { + "textRaw": "`process.initgroups(user, extraGroup)`", + "type": "method", + "name": "initgroups", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`user` {string|number} The user name or numeric identifier.", + "name": "user", + "type": "string|number", + "desc": "The user name or numeric identifier." + }, + { + "textRaw": "`extraGroup` {string|number} A group name or numeric identifier.", + "name": "extraGroup", + "type": "string|number", + "desc": "A group name or numeric identifier." + } + ] + } + ], + "desc": "

      The process.initgroups() method reads the /etc/group file and initializes\nthe group access list, using all groups of which the user is a member. This is\na privileged operation that requires that the Node.js process either have root\naccess or the CAP_SETGID capability.

      \n

      Use care when dropping privileges:

      \n
      console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('nodeuser', 1000);     // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.kill(pid[, signal])`", + "type": "method", + "name": "kill", + "meta": { + "added": [ + "v0.0.6" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`pid` {number} A process ID", + "name": "pid", + "type": "number", + "desc": "A process ID" + }, + { + "textRaw": "`signal` {string|number} The signal to send, either as a string or number. **Default:** `'SIGTERM'`.", + "name": "signal", + "type": "string|number", + "default": "`'SIGTERM'`", + "desc": "The signal to send, either as a string or number." + } + ] + } + ], + "desc": "

      The process.kill() method sends the signal to the process identified by\npid.

      \n

      Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events\nand kill(2) for more information.

      \n

      This method will throw an error if the target pid does not exist. As a special\ncase, a signal of 0 can be used to test for the existence of a process.\nWindows platforms will throw an error if the pid is used to kill a process\ngroup.

      \n

      Even though the name of this function is process.kill(), it is really just a\nsignal sender, like the kill system call. The signal sent may do something\nother than kill the target process.

      \n
      process.on('SIGHUP', () => {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');\n
      \n

      When SIGUSR1 is received by a Node.js process, Node.js will start the\ndebugger. See Signal Events.

      " + }, + { + "textRaw": "`process.memoryUsage()`", + "type": "method", + "name": "memoryUsage", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31550", + "description": "Added `arrayBuffers` to the returned object." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9587", + "description": "Added `external` to the returned object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`rss` {integer}", + "name": "rss", + "type": "integer" + }, + { + "textRaw": "`heapTotal` {integer}", + "name": "heapTotal", + "type": "integer" + }, + { + "textRaw": "`heapUsed` {integer}", + "name": "heapUsed", + "type": "integer" + }, + { + "textRaw": "`external` {integer}", + "name": "external", + "type": "integer" + }, + { + "textRaw": "`arrayBuffers` {integer}", + "name": "arrayBuffers", + "type": "integer" + } + ] + }, + "params": [] + } + ], + "desc": "

      The process.memoryUsage() method returns an object describing the memory usage\nof the Node.js process measured in bytes.

      \n

      For example, the code:

      \n
      console.log(process.memoryUsage());\n
      \n

      Will generate:

      \n\n
      {\n  rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472,\n  external: 49879,\n  arrayBuffers: 9386\n}\n
      \n
        \n
      • heapTotal and heapUsed refer to V8's memory usage.
      • \n
      • external refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8.
      • \n
      • rss, Resident Set Size, is the amount of space occupied in the main\nmemory device (that is a subset of the total allocated memory) for the\nprocess, including all C++ and JavaScript objects and code.
      • \n
      • arrayBuffers refers to memory allocated for ArrayBuffers and\nSharedArrayBuffers, including all Node.js Buffers.\nThis is also included in the external value. When Node.js is used as an\nembedded library, this value may be 0 because allocations for ArrayBuffers\nmay not be tracked in that case.
      • \n
      \n

      When using Worker threads, rss will be a value that is valid for the\nentire process, while the other fields will only refer to the current thread.

      " + }, + { + "textRaw": "`process.nextTick(callback[, ...args])`", + "type": "method", + "name": "nextTick", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [ + { + "version": "v1.8.1", + "pr-url": "https://github.com/nodejs/node/pull/1077", + "description": "Additional arguments after `callback` are now supported." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + }, + { + "textRaw": "`...args` {any} Additional arguments to pass when invoking the `callback`", + "name": "...args", + "type": "any", + "desc": "Additional arguments to pass when invoking the `callback`" + } + ] + } + ], + "desc": "

      process.nextTick() adds callback to the \"next tick queue\". This queue is\nfully drained after the current operation on the JavaScript stack runs to\ncompletion and before the event loop is allowed to continue. It's possible to\ncreate an infinite loop if one were to recursively call process.nextTick().\nSee the Event Loop guide for more background.

      \n
      console.log('start');\nprocess.nextTick(() => {\n  console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
      \n

      This is important when developing APIs in order to give users the opportunity\nto assign event handlers after an object has been constructed but before any\nI/O has occurred:

      \n
      function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
      \n

      It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:

      \n
      // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
      \n

      This API is hazardous because in the following case:

      \n
      const maybeTrue = Math.random() > 0.5;\n\nmaybeSync(maybeTrue, () => {\n  foo();\n});\n\nbar();\n
      \n

      It is not clear whether foo() or bar() will be called first.

      \n

      The following approach is much better:

      \n
      function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
      " + }, + { + "textRaw": "`process.resourceUsage()`", + "type": "method", + "name": "resourceUsage", + "meta": { + "added": [ + "v12.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t].", + "name": "return", + "type": "Object", + "desc": "the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t].", + "options": [ + { + "textRaw": "`userCPUTime` {integer} maps to `ru_utime` computed in microseconds. It is the same value as [`process.cpuUsage().user`][process.cpuUsage].", + "name": "userCPUTime", + "type": "integer", + "desc": "maps to `ru_utime` computed in microseconds. It is the same value as [`process.cpuUsage().user`][process.cpuUsage]." + }, + { + "textRaw": "`systemCPUTime` {integer} maps to `ru_stime` computed in microseconds. It is the same value as [`process.cpuUsage().system`][process.cpuUsage].", + "name": "systemCPUTime", + "type": "integer", + "desc": "maps to `ru_stime` computed in microseconds. It is the same value as [`process.cpuUsage().system`][process.cpuUsage]." + }, + { + "textRaw": "`maxRSS` {integer} maps to `ru_maxrss` which is the maximum resident set size used in kilobytes.", + "name": "maxRSS", + "type": "integer", + "desc": "maps to `ru_maxrss` which is the maximum resident set size used in kilobytes." + }, + { + "textRaw": "`sharedMemorySize` {integer} maps to `ru_ixrss` but is not supported by any platform.", + "name": "sharedMemorySize", + "type": "integer", + "desc": "maps to `ru_ixrss` but is not supported by any platform." + }, + { + "textRaw": "`unsharedDataSize` {integer} maps to `ru_idrss` but is not supported by any platform.", + "name": "unsharedDataSize", + "type": "integer", + "desc": "maps to `ru_idrss` but is not supported by any platform." + }, + { + "textRaw": "`unsharedStackSize` {integer} maps to `ru_isrss` but is not supported by any platform.", + "name": "unsharedStackSize", + "type": "integer", + "desc": "maps to `ru_isrss` but is not supported by any platform." + }, + { + "textRaw": "`minorPageFault` {integer} maps to `ru_minflt` which is the number of minor page faults for the process, see [this article for more details][wikipedia_minor_fault].", + "name": "minorPageFault", + "type": "integer", + "desc": "maps to `ru_minflt` which is the number of minor page faults for the process, see [this article for more details][wikipedia_minor_fault]." + }, + { + "textRaw": "`majorPageFault` {integer} maps to `ru_majflt` which is the number of major page faults for the process, see [this article for more details][wikipedia_major_fault]. This field is not supported on Windows.", + "name": "majorPageFault", + "type": "integer", + "desc": "maps to `ru_majflt` which is the number of major page faults for the process, see [this article for more details][wikipedia_major_fault]. This field is not supported on Windows." + }, + { + "textRaw": "`swappedOut` {integer} maps to `ru_nswap` but is not supported by any platform.", + "name": "swappedOut", + "type": "integer", + "desc": "maps to `ru_nswap` but is not supported by any platform." + }, + { + "textRaw": "`fsRead` {integer} maps to `ru_inblock` which is the number of times the file system had to perform input.", + "name": "fsRead", + "type": "integer", + "desc": "maps to `ru_inblock` which is the number of times the file system had to perform input." + }, + { + "textRaw": "`fsWrite` {integer} maps to `ru_oublock` which is the number of times the file system had to perform output.", + "name": "fsWrite", + "type": "integer", + "desc": "maps to `ru_oublock` which is the number of times the file system had to perform output." + }, + { + "textRaw": "`ipcSent` {integer} maps to `ru_msgsnd` but is not supported by any platform.", + "name": "ipcSent", + "type": "integer", + "desc": "maps to `ru_msgsnd` but is not supported by any platform." + }, + { + "textRaw": "`ipcReceived` {integer} maps to `ru_msgrcv` but is not supported by any platform.", + "name": "ipcReceived", + "type": "integer", + "desc": "maps to `ru_msgrcv` but is not supported by any platform." + }, + { + "textRaw": "`signalsCount` {integer} maps to `ru_nsignals` but is not supported by any platform.", + "name": "signalsCount", + "type": "integer", + "desc": "maps to `ru_nsignals` but is not supported by any platform." + }, + { + "textRaw": "`voluntaryContextSwitches` {integer} maps to `ru_nvcsw` which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows.", + "name": "voluntaryContextSwitches", + "type": "integer", + "desc": "maps to `ru_nvcsw` which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows." + }, + { + "textRaw": "`involuntaryContextSwitches` {integer} maps to `ru_nivcsw` which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows.", + "name": "involuntaryContextSwitches", + "type": "integer", + "desc": "maps to `ru_nivcsw` which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows." + } + ] + }, + "params": [] + } + ], + "desc": "
      console.log(process.resourceUsage());\n/*\n  Will output:\n  {\n    userCPUTime: 82872,\n    systemCPUTime: 4143,\n    maxRSS: 33164,\n    sharedMemorySize: 0,\n    unsharedDataSize: 0,\n    unsharedStackSize: 0,\n    minorPageFault: 2469,\n    majorPageFault: 0,\n    swappedOut: 0,\n    fsRead: 0,\n    fsWrite: 8,\n    ipcSent: 0,\n    ipcReceived: 0,\n    signalsCount: 0,\n    voluntaryContextSwitches: 79,\n    involuntaryContextSwitches: 1\n  }\n*/\n
      " + }, + { + "textRaw": "`process.send(message[, sendHandle[, options]][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {net.Server|net.Socket}", + "name": "sendHandle", + "type": "net.Server|net.Socket" + }, + { + "textRaw": "`options` {Object} used to parameterize the sending of certain types of handles.`options` supports the following properties:", + "name": "options", + "type": "Object", + "desc": "used to parameterize the sending of certain types of handles.`options` supports the following properties:", + "options": [ + { + "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", + "name": "keepOpen", + "type": "boolean", + "default": "`false`", + "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      If Node.js is spawned with an IPC channel, the process.send() method can be\nused to send messages to the parent process. Messages will be received as a\n'message' event on the parent's ChildProcess object.

      \n

      If Node.js was not spawned with an IPC channel, process.send will be\nundefined.

      \n

      The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.

      " + }, + { + "textRaw": "`process.setegid(id)`", + "type": "method", + "name": "setegid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {string|number} A group name or ID", + "name": "id", + "type": "string|number", + "desc": "A group name or ID" + } + ] + } + ], + "desc": "

      The process.setegid() method sets the effective group identity of the process.\n(See setegid(2).) The id can be passed as either a numeric ID or a group\nname string. If a group name is specified, this method blocks while resolving\nthe associated a numeric ID.

      \n
      if (process.getegid && process.setegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n  try {\n    process.setegid(501);\n    console.log(`New gid: ${process.getegid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.seteuid(id)`", + "type": "method", + "name": "seteuid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {string|number} A user name or ID", + "name": "id", + "type": "string|number", + "desc": "A user name or ID" + } + ] + } + ], + "desc": "

      The process.seteuid() method sets the effective user identity of the process.\n(See seteuid(2).) The id can be passed as either a numeric ID or a username\nstring. If a username is specified, the method blocks while resolving the\nassociated numeric ID.

      \n
      if (process.geteuid && process.seteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n  try {\n    process.seteuid(501);\n    console.log(`New uid: ${process.geteuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setgid(id)`", + "type": "method", + "name": "setgid", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {string|number} The group name or ID", + "name": "id", + "type": "string|number", + "desc": "The group name or ID" + } + ] + } + ], + "desc": "

      The process.setgid() method sets the group identity of the process. (See\nsetgid(2).) The id can be passed as either a numeric ID or a group name\nstring. If a group name is specified, this method blocks while resolving the\nassociated numeric ID.

      \n
      if (process.getgid && process.setgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n  try {\n    process.setgid(501);\n    console.log(`New gid: ${process.getgid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setgroups(groups)`", + "type": "method", + "name": "setgroups", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`groups` {integer[]}", + "name": "groups", + "type": "integer[]" + } + ] + } + ], + "desc": "

      The process.setgroups() method sets the supplementary group IDs for the\nNode.js process. This is a privileged operation that requires the Node.js\nprocess to have root or the CAP_SETGID capability.

      \n

      The groups array can contain numeric group IDs, group names or both.

      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setuid(id)`", + "type": "method", + "name": "setuid", + "meta": { + "added": [ + "v0.1.28" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {integer | string}", + "name": "id", + "type": "integer | string" + } + ] + } + ], + "desc": "

      The process.setuid(id) method sets the user identity of the process. (See\nsetuid(2).) The id can be passed as either a numeric ID or a username string.\nIf a username is specified, the method blocks while resolving the associated\nnumeric ID.

      \n
      if (process.getuid && process.setuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n  try {\n    process.setuid(501);\n    console.log(`New uid: ${process.getuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setUncaughtExceptionCaptureCallback(fn)`", + "type": "method", + "name": "setUncaughtExceptionCaptureCallback", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function|null}", + "name": "fn", + "type": "Function|null" + } + ] + } + ], + "desc": "

      The process.setUncaughtExceptionCaptureCallback() function sets a function\nthat will be invoked when an uncaught exception occurs, which will receive the\nexception value itself as its first argument.

      \n

      If such a function is set, the 'uncaughtException' event will\nnot be emitted. If --abort-on-uncaught-exception was passed from the\ncommand line or set through v8.setFlagsFromString(), the process will\nnot abort.

      \n

      To unset the capture function,\nprocess.setUncaughtExceptionCaptureCallback(null) may be used. Calling this\nmethod with a non-null argument while another capture function is set will\nthrow an error.

      \n

      Using this function is mutually exclusive with using the deprecated\ndomain built-in module.

      " + }, + { + "textRaw": "`process.umask()`", + "type": "method", + "name": "umask", + "meta": { + "added": [ + "v0.1.19" + ], + "changes": [ + { + "version": [ + "v12.19.0", + "v14.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/32499", + "description": "Calling `process.umask()` with no arguments is deprecated." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated. Calling `process.umask()` with no argument causes\nthe process-wide umask to be written twice. This introduces a race condition\nbetween threads, and is a potential security vulnerability. There is no safe,\ncross-platform alternative API.", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      process.umask() returns the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process.

      " + }, + { + "textRaw": "`process.umask(mask)`", + "type": "method", + "name": "umask", + "meta": { + "added": [ + "v0.1.19" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`mask` {string|integer}", + "name": "mask", + "type": "string|integer" + } + ] + } + ], + "desc": "

      process.umask(mask) sets the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process. Returns the previous mask.

      \n
      const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
      \n

      In Worker threads, process.umask(mask) will throw an exception.

      " + }, + { + "textRaw": "`process.uptime()`", + "type": "method", + "name": "uptime", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [] + } + ], + "desc": "

      The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.

      \n

      The return value includes fractions of a second. Use Math.floor() to get whole\nseconds.

      " + } + ], + "properties": [ + { + "textRaw": "`allowedNodeEnvironmentFlags` {Set}", + "type": "Set", + "name": "allowedNodeEnvironmentFlags", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      The process.allowedNodeEnvironmentFlags property is a special,\nread-only Set of flags allowable within the NODE_OPTIONS\nenvironment variable.

      \n

      process.allowedNodeEnvironmentFlags extends Set, but overrides\nSet.prototype.has to recognize several different possible flag\nrepresentations. process.allowedNodeEnvironmentFlags.has() will\nreturn true in the following cases:

      \n
        \n
      • Flags may omit leading single (-) or double (--) dashes; e.g.,\ninspect-brk for --inspect-brk, or r for -r.
      • \n
      • Flags passed through to V8 (as listed in --v8-options) may replace\none or more non-leading dashes for an underscore, or vice-versa;\ne.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof,\netc.
      • \n
      • Flags may contain one or more equals (=) characters; all\ncharacters after and including the first equals will be ignored;\ne.g., --stack-trace-limit=100.
      • \n
      • Flags must be allowable within NODE_OPTIONS.
      • \n
      \n

      When iterating over process.allowedNodeEnvironmentFlags, flags will\nappear only once; each will begin with one or more dashes. Flags\npassed through to V8 will contain underscores instead of non-leading\ndashes:

      \n
      process.allowedNodeEnvironmentFlags.forEach((flag) => {\n  // -r\n  // --inspect-brk\n  // --abort_on_uncaught_exception\n  // ...\n});\n
      \n

      The methods add(), clear(), and delete() of\nprocess.allowedNodeEnvironmentFlags do nothing, and will fail\nsilently.

      \n

      If Node.js was compiled without NODE_OPTIONS support (shown in\nprocess.config), process.allowedNodeEnvironmentFlags will\ncontain what would have been allowable.

      " + }, + { + "textRaw": "`arch` {string}", + "type": "string", + "name": "arch", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "desc": "

      The operating system CPU architecture for which the Node.js binary was compiled.\nPossible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc',\n'ppc64', 's390', 's390x', 'x32', and 'x64'.

      \n
      console.log(`This processor architecture is ${process.arch}`);\n
      " + }, + { + "textRaw": "`argv` {string[]}", + "type": "string[]", + "name": "argv", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "desc": "

      The process.argv property returns an array containing the command line\narguments passed when the Node.js process was launched. The first element will\nbe process.execPath. See process.argv0 if access to the original value\nof argv[0] is needed. The second element will be the path to the JavaScript\nfile being executed. The remaining elements will be any additional command line\narguments.

      \n

      For example, assuming the following script for process-args.js:

      \n
      // print process.argv\nprocess.argv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n
      \n

      Launching the Node.js process as:

      \n
      $ node process-args.js one two=three four\n
      \n

      Would generate the output:

      \n
      0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-args.js\n2: one\n3: two=three\n4: four\n
      " + }, + { + "textRaw": "`argv0` {string}", + "type": "string", + "name": "argv0", + "meta": { + "added": [ + "v6.4.0" + ], + "changes": [] + }, + "desc": "

      The process.argv0 property stores a read-only copy of the original value of\nargv[0] passed when Node.js starts.

      \n
      $ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
      " + }, + { + "textRaw": "`channel` {Object}", + "type": "Object", + "name": "channel", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [] + }, + "desc": "

      If the Node.js process was spawned with an IPC channel (see the\nChild Process documentation), the process.channel\nproperty is a reference to the IPC channel. If no IPC channel exists, this\nproperty is undefined.

      " + }, + { + "textRaw": "`config` {Object}", + "type": "Object", + "name": "config", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      The process.config property returns an Object containing the JavaScript\nrepresentation of the configure options used to compile the current Node.js\nexecutable. This is the same as the config.gypi file that was produced when\nrunning the ./configure script.

      \n

      An example of the possible output looks like:

      \n\n
      {\n  target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   {\n     host_arch: 'x64',\n     napi_build_version: 5,\n     node_install_npm: 'true',\n     node_prefix: '',\n     node_shared_cares: 'false',\n     node_shared_http_parser: 'false',\n     node_shared_libuv: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 1\n   }\n}\n
      \n

      The process.config property is not read-only and there are existing\nmodules in the ecosystem that are known to extend, modify, or entirely replace\nthe value of process.config.

      " + }, + { + "textRaw": "`connected` {boolean}", + "type": "boolean", + "name": "connected", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.connected property will return\ntrue so long as the IPC channel is connected and will return false after\nprocess.disconnect() is called.

      \n

      Once process.connected is false, it is no longer possible to send messages\nover the IPC channel using process.send().

      " + }, + { + "textRaw": "`debugPort` {number}", + "type": "number", + "name": "debugPort", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "desc": "

      The port used by the Node.js debugger when enabled.

      \n
      process.debugPort = 5858;\n
      " + }, + { + "textRaw": "`env` {Object}", + "type": "Object", + "name": "env", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26544", + "description": "Worker threads will now use a copy of the parent thread’s `process.env` by default, configurable through the `env` option of the `Worker` constructor." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18990", + "description": "Implicit conversion of variable value to string is deprecated." + } + ] + }, + "desc": "

      The process.env property returns an object containing the user environment.\nSee environ(7).

      \n

      An example of this object looks like:

      \n\n
      {\n  TERM: 'xterm-256color',\n  SHELL: '/usr/local/bin/bash',\n  USER: 'maciej',\n  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n  PWD: '/Users/maciej',\n  EDITOR: 'vim',\n  SHLVL: '1',\n  HOME: '/Users/maciej',\n  LOGNAME: 'maciej',\n  _: '/usr/local/bin/node'\n}\n
      \n

      It is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process, or (unless explicitly requested)\nto other Worker threads.\nIn other words, the following example would not work:

      \n
      $ node -e 'process.env.foo = \"bar\"' && echo $foo\n
      \n

      While the following will:

      \n
      process.env.foo = 'bar';\nconsole.log(process.env.foo);\n
      \n

      Assigning a property on process.env will implicitly convert the value\nto a string. This behavior is deprecated. Future versions of Node.js may\nthrow an error when the value is not a string, number, or boolean.

      \n
      process.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
      \n

      Use delete to delete a property from process.env.

      \n
      process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
      \n

      On Windows operating systems, environment variables are case-insensitive.

      \n
      process.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
      \n

      Unless explicitly specified when creating a Worker instance,\neach Worker thread has its own copy of process.env, based on its\nparent thread’s process.env, or whatever was specified as the env option\nto the Worker constructor. Changes to process.env will not be visible\nacross Worker threads, and only the main thread can make changes that\nare visible to the operating system or to native add-ons.

      " + }, + { + "textRaw": "`execArgv` {string[]}", + "type": "string[]", + "name": "execArgv", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      The process.execArgv property returns the set of Node.js-specific command-line\noptions passed when the Node.js process was launched. These options do not\nappear in the array returned by the process.argv property, and do not\ninclude the Node.js executable, the name of the script, or any options following\nthe script name. These options are useful in order to spawn child processes with\nthe same execution environment as the parent.

      \n
      $ node --harmony script.js --version\n
      \n

      Results in process.execArgv:

      \n\n
      ['--harmony']\n
      \n

      And process.argv:

      \n\n
      ['/usr/local/bin/node', 'script.js', '--version']\n
      " + }, + { + "textRaw": "`execPath` {string}", + "type": "string", + "name": "execPath", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "desc": "

      The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process. Symbolic links, if any, are resolved.

      \n\n
      '/usr/local/bin/node'\n
      " + }, + { + "textRaw": "`exitCode` {integer}", + "type": "integer", + "name": "exitCode", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit() without specifying\na code.

      \n

      Specifying a code to process.exit(code) will override any\nprevious setting of process.exitCode.

      " + }, + { + "textRaw": "`mainModule` {Object}", + "type": "Object", + "name": "mainModule", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "

      The process.mainModule property provides an alternative way of retrieving\nrequire.main. The difference is that if the main module changes at\nruntime, require.main may still refer to the original main module in\nmodules that were required before the change occurred. Generally, it's\nsafe to assume that the two refer to the same module.

      \n

      As with require.main, process.mainModule will be undefined if there\nis no entry script.

      " + }, + { + "textRaw": "`noDeprecation` {boolean}", + "type": "boolean", + "name": "noDeprecation", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      The process.noDeprecation property indicates whether the --no-deprecation\nflag is set on the current Node.js process. See the documentation for\nthe 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

      " + }, + { + "textRaw": "`pid` {integer}", + "type": "integer", + "name": "pid", + "meta": { + "added": [ + "v0.1.15" + ], + "changes": [] + }, + "desc": "

      The process.pid property returns the PID of the process.

      \n
      console.log(`This process is pid ${process.pid}`);\n
      " + }, + { + "textRaw": "`platform` {string}", + "type": "string", + "name": "platform", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The process.platform property returns a string identifying the operating\nsystem platform on which the Node.js process is running.

      \n

      Currently possible values are:

      \n
        \n
      • 'aix'
      • \n
      • 'darwin'
      • \n
      • 'freebsd'
      • \n
      • 'linux'
      • \n
      • 'openbsd'
      • \n
      • 'sunos'
      • \n
      • 'win32'
      • \n
      \n
      console.log(`This platform is ${process.platform}`);\n
      \n

      The value 'android' may also be returned if the Node.js is built on the\nAndroid operating system. However, Android support in Node.js\nis experimental.

      " + }, + { + "textRaw": "`ppid` {integer}", + "type": "integer", + "name": "ppid", + "meta": { + "added": [ + "v9.2.0", + "v8.10.0", + "v6.13.0" + ], + "changes": [] + }, + "desc": "

      The process.ppid property returns the PID of the parent of the\ncurrent process.

      \n
      console.log(`The parent process is pid ${process.ppid}`);\n
      " + }, + { + "textRaw": "`release` {Object}", + "type": "Object", + "name": "release", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [ + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3212", + "description": "The `lts` property is now supported." + } + ] + }, + "desc": "

      The process.release property returns an Object containing metadata related\nto the current release, including URLs for the source tarball and headers-only\ntarball.

      \n

      process.release contains the following properties:

      \n
        \n
      • name <string> A value that will always be 'node' for Node.js. For\nlegacy io.js releases, this will be 'io.js'.
      • \n
      • sourceUrl <string> an absolute URL pointing to a .tar.gz file containing\nthe source code of the current release.
      • \n
      • headersUrl<string> an absolute URL pointing to a .tar.gz file containing\nonly the source header files for the current release. This file is\nsignificantly smaller than the full source file and can be used for compiling\nNode.js native add-ons.
      • \n
      • libUrl <string> an absolute URL pointing to a node.lib file matching the\narchitecture and version of the current release. This file is used for\ncompiling Node.js native add-ons. This property is only present on Windows\nbuilds of Node.js and will be missing on all other platforms.
      • \n
      • lts <string> a string label identifying the LTS label for this release.\nThis property only exists for LTS releases and is undefined for all other\nrelease types, including Current releases.\nValid values include the LTS Release Codenames (including those\nthat are no longer supported). A non-exhaustive example of\nthese codenames includes:\n
          \n
        • 'Dubnium' for the 10.x LTS line beginning with 10.13.0.
        • \n
        • 'Erbium' for the 12.x LTS line beginning with 12.13.0.\nFor other LTS Release Codenames, see Node.js Changelog Archive
        • \n
        \n
      • \n
      \n\n
      {\n  name: 'node',\n  lts: 'Erbium',\n  sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib'\n}\n
      \n

      In custom builds from non-release versions of the source tree, only the\nname property may be present. The additional properties should not be\nrelied upon to exist.

      " + }, + { + "textRaw": "`report` {Object}", + "type": "Object", + "name": "report", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      process.report is an object whose methods are used to generate diagnostic\nreports for the current process. Additional documentation is available in the\nreport documentation.

      ", + "properties": [ + { + "textRaw": "`compact` {boolean}", + "type": "boolean", + "name": "compact", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Write reports in a compact format, single-line JSON, more easily consumable\nby log processing systems than the default multi-line format designed for\nhuman consumption.

      \n
      console.log(`Reports are compact? ${process.report.compact}`);\n
      " + }, + { + "textRaw": "`directory` {string}", + "type": "string", + "name": "directory", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      Directory where the report is written. The default value is the empty string,\nindicating that reports are written to the current working directory of the\nNode.js process.

      \n
      console.log(`Report directory is ${process.report.directory}`);\n
      " + }, + { + "textRaw": "`filename` {string}", + "type": "string", + "name": "filename", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      Filename where the report is written. If set to the empty string, the output\nfilename will be comprised of a timestamp, PID, and sequence number. The default\nvalue is the empty string.

      \n
      console.log(`Report filename is ${process.report.filename}`);\n
      " + }, + { + "textRaw": "`reportOnFatalError` {boolean}", + "type": "boolean", + "name": "reportOnFatalError", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      If true, a diagnostic report is generated on fatal errors, such as out of\nmemory errors or failed C++ assertions.

      \n
      console.log(`Report on fatal error: ${process.report.reportOnFatalError}`);\n
      " + }, + { + "textRaw": "`reportOnSignal` {boolean}", + "type": "boolean", + "name": "reportOnSignal", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      If true, a diagnostic report is generated when the process receives the\nsignal specified by process.report.signal.

      \n
      console.log(`Report on signal: ${process.report.reportOnSignal}`);\n
      " + }, + { + "textRaw": "`reportOnUncaughtException` {boolean}", + "type": "boolean", + "name": "reportOnUncaughtException", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      If true, a diagnostic report is generated on uncaught exception.

      \n
      console.log(`Report on exception: ${process.report.reportOnUncaughtException}`);\n
      " + }, + { + "textRaw": "`signal` {string}", + "type": "string", + "name": "signal", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      The signal used to trigger the creation of a diagnostic report. Defaults to\n'SIGUSR2'.

      \n
      console.log(`Report signal: ${process.report.signal}`);\n
      " + } + ], + "methods": [ + { + "textRaw": "`process.report.getReport([err])`", + "type": "method", + "name": "getReport", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`err` {Error} A custom error used for reporting the JavaScript stack.", + "name": "err", + "type": "Error", + "desc": "A custom error used for reporting the JavaScript stack." + } + ] + } + ], + "desc": "

      Returns a JavaScript Object representation of a diagnostic report for the\nrunning process. The report's JavaScript stack trace is taken from err, if\npresent.

      \n
      const data = process.report.getReport();\nconsole.log(data.header.nodeJsVersion);\n\n// Similar to process.report.writeReport()\nconst fs = require('fs');\nfs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8');\n
      \n

      Additional documentation is available in the report documentation.

      " + }, + { + "textRaw": "`process.report.writeReport([filename][, err])`", + "type": "method", + "name": "writeReport", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} Returns the filename of the generated report.", + "name": "return", + "type": "string", + "desc": "Returns the filename of the generated report." + }, + "params": [ + { + "textRaw": "`filename` {string} Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js process, if unspecified.", + "name": "filename", + "type": "string", + "desc": "Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js process, if unspecified." + }, + { + "textRaw": "`err` {Error} A custom error used for reporting the JavaScript stack.", + "name": "err", + "type": "Error", + "desc": "A custom error used for reporting the JavaScript stack." + } + ] + } + ], + "desc": "

      Writes a diagnostic report to a file. If filename is not provided, the default\nfilename includes the date, time, PID, and a sequence number. The report's\nJavaScript stack trace is taken from err, if present.

      \n
      process.report.writeReport();\n
      \n

      Additional documentation is available in the report documentation.

      " + } + ] + }, + { + "textRaw": "`stderr` {Stream}", + "type": "Stream", + "name": "stderr", + "desc": "

      The process.stderr property returns a stream connected to\nstderr (fd 2). It is a net.Socket (which is a Duplex\nstream) unless fd 2 refers to a file, in which case it is\na Writable stream.

      \n

      process.stderr differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

      ", + "properties": [ + { + "textRaw": "`fd` {number}", + "type": "number", + "name": "fd", + "desc": "

      This property refers to the value of underlying file descriptor of\nprocess.stderr. The value is fixed at 2. In Worker threads,\nthis field does not exist.

      " + } + ] + }, + { + "textRaw": "`stdin` {Stream}", + "type": "Stream", + "name": "stdin", + "desc": "

      The process.stdin property returns a stream connected to\nstdin (fd 0). It is a net.Socket (which is a Duplex\nstream) unless fd 0 refers to a file, in which case it is\na Readable stream.

      \n

      For details of how to read from stdin see readable.read().

      \n

      As a Duplex stream, process.stdin can also be used in \"old\" mode that\nis compatible with scripts written for Node.js prior to v0.10.\nFor more information see Stream compatibility.

      \n

      In \"old\" streams mode the stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it. Note also that calling\nprocess.stdin.resume() itself would switch stream to \"old\" mode.

      ", + "properties": [ + { + "textRaw": "`fd` {number}", + "type": "number", + "name": "fd", + "desc": "

      This property refers to the value of underlying file descriptor of\nprocess.stdin. The value is fixed at 0. In Worker threads,\nthis field does not exist.

      " + } + ] + }, + { + "textRaw": "`stdout` {Stream}", + "type": "Stream", + "name": "stdout", + "desc": "

      The process.stdout property returns a stream connected to\nstdout (fd 1). It is a net.Socket (which is a Duplex\nstream) unless fd 1 refers to a file, in which case it is\na Writable stream.

      \n

      For example, to copy process.stdin to process.stdout:

      \n
      process.stdin.pipe(process.stdout);\n
      \n

      process.stdout differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

      ", + "properties": [ + { + "textRaw": "`fd` {number}", + "type": "number", + "name": "fd", + "desc": "

      This property refers to the value of underlying file descriptor of\nprocess.stdout. The value is fixed at 1. In Worker threads,\nthis field does not exist.

      " + } + ], + "modules": [ + { + "textRaw": "A note on process I/O", + "name": "a_note_on_process_i/o", + "desc": "

      process.stdout and process.stderr differ from other Node.js streams in\nimportant ways:

      \n
        \n
      1. They are used internally by console.log() and console.error(),\nrespectively.
      2. \n
      3. Writes may be synchronous depending on what the stream is connected to\nand whether the system is Windows or POSIX:\n
          \n
        • Files: synchronous on Windows and POSIX
        • \n
        • TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
        • \n
        • Pipes (and sockets): synchronous on Windows, asynchronous on POSIX
        • \n
        \n
      4. \n
      \n

      These behaviors are partly for historical reasons, as changing them would\ncreate backward incompatibility, but they are also expected by some users.

      \n

      Synchronous writes avoid problems such as output written with console.log() or\nconsole.error() being unexpectedly interleaved, or not written at all if\nprocess.exit() is called before an asynchronous write completes. See\nprocess.exit() for more information.

      \n

      Warning: Synchronous writes block the event loop until the write has\ncompleted. This can be near instantaneous in the case of output to a file, but\nunder high system load, pipes that are not being read at the receiving end, or\nwith slow terminals or file systems, its possible for the event loop to be\nblocked often enough and long enough to have severe negative performance\nimpacts. This may not be a problem when writing to an interactive terminal\nsession, but consider this particularly careful when doing production logging to\nthe process output streams.

      \n

      To check if a stream is connected to a TTY context, check the isTTY\nproperty.

      \n

      For instance:

      \n
      $ node -p \"Boolean(process.stdin.isTTY)\"\ntrue\n$ echo \"foo\" | node -p \"Boolean(process.stdin.isTTY)\"\nfalse\n$ node -p \"Boolean(process.stdout.isTTY)\"\ntrue\n$ node -p \"Boolean(process.stdout.isTTY)\" | cat\nfalse\n
      \n

      See the TTY documentation for more information.

      ", + "type": "module", + "displayName": "A note on process I/O" + } + ] + }, + { + "textRaw": "`throwDeprecation` {boolean}", + "type": "boolean", + "name": "throwDeprecation", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "desc": "

      The initial value of process.throwDeprecation indicates whether the\n--throw-deprecation flag is set on the current Node.js process.\nprocess.throwDeprecation is mutable, so whether or not deprecation\nwarnings result in errors may be altered at runtime. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information.

      \n
      $ node --throw-deprecation -p \"process.throwDeprecation\"\ntrue\n$ node -p \"process.throwDeprecation\"\nundefined\n$ node\n> process.emitWarning('test', 'DeprecationWarning');\nundefined\n> (node:26598) DeprecationWarning: test\n> process.throwDeprecation = true;\ntrue\n> process.emitWarning('test', 'DeprecationWarning');\nThrown:\n[DeprecationWarning: test] { name: 'DeprecationWarning' }\n
      " + }, + { + "textRaw": "`title` {string}", + "type": "string", + "name": "title", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "desc": "

      The process.title property returns the current process title (i.e. returns\nthe current value of ps). Assigning a new value to process.title modifies\nthe current value of ps.

      \n

      When a new value is assigned, different platforms will impose different maximum\nlength restrictions on the title. Usually such restrictions are quite limited.\nFor instance, on Linux and macOS, process.title is limited to the size of the\nbinary name plus the length of the command line arguments because setting the\nprocess.title overwrites the argv memory of the process. Node.js v0.8\nallowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure and confusing in some (rather obscure)\ncases.

      \n

      Assigning a value to process.title might not result in an accurate label\nwithin process manager applications such as macOS Activity Monitor or Windows\nServices Manager.

      " + }, + { + "textRaw": "`traceDeprecation` {boolean}", + "type": "boolean", + "name": "traceDeprecation", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      The process.traceDeprecation property indicates whether the\n--trace-deprecation flag is set on the current Node.js process. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

      " + }, + { + "textRaw": "`version` {string}", + "type": "string", + "name": "version", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      The process.version property contains the Node.js version string.

      \n
      console.log(`Version: ${process.version}`);\n// Version: v14.8.0\n
      \n

      To get the version string without the prepended v, use\nprocess.versions.node.

      " + }, + { + "textRaw": "`versions` {Object}", + "type": "Object", + "name": "versions", + "meta": { + "added": [ + "v0.2.0" + ], + "changes": [ + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3102", + "description": "The `icu` property is now supported." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15785", + "description": "The `v8` property now includes a Node.js specific suffix." + } + ] + }, + "desc": "

      The process.versions property returns an object listing the version strings of\nNode.js and its dependencies. process.versions.modules indicates the current\nABI version, which is increased whenever a C++ API changes. Node.js will refuse\nto load modules that were compiled against a different module ABI version.

      \n
      console.log(process.versions);\n
      \n

      Will generate an object similar to:

      \n
      { node: '11.13.0',\n  v8: '7.0.276.38-node.18',\n  uv: '1.27.0',\n  zlib: '1.2.11',\n  brotli: '1.0.7',\n  ares: '1.15.0',\n  modules: '67',\n  nghttp2: '1.34.0',\n  napi: '4',\n  llhttp: '1.1.1',\n  http_parser: '2.8.0',\n  openssl: '1.1.1b',\n  cldr: '34.0',\n  icu: '63.1',\n  tz: '2018e',\n  unicode: '11.0' }\n
      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`require()`", + "type": "method", + "name": "require", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This variable may appear to be global but is not. See require().

      " + } + ] +} diff --git a/doc/api/assert.html b/doc/api/assert.html new file mode 100644 index 0000000000000000000000000000000000000000..1b54df97af1c7e6f911b0f52ffd18cb9742d8f85 --- /dev/null +++ b/doc/api/assert.html @@ -0,0 +1,1506 @@ + + + + + + + Assert | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Assert#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/assert.js

      +

      The assert module provides a set of assertion functions for verifying +invariants.

      +

      Strict assertion mode#

      + +

      In strict assertion mode, non-strict methods behave like their corresponding +strict methods. For example, assert.deepEqual() will behave like +assert.deepStrictEqual().

      +

      In strict assertion mode, error messages for objects display a diff. In legacy +assertion mode, error messages for objects display the objects, often truncated.

      +

      To use strict assertion mode:

      +
      const assert = require('assert').strict;
      +

      Example error diff:

      +
      const assert = require('assert').strict;
      +
      +assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected ... Lines skipped
      +//
      +//   [
      +//     [
      +// ...
      +//       2,
      +// +     3
      +// -     '3'
      +//     ],
      +// ...
      +//     5
      +//   ]
      +

      To deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS +environment variables. This will also deactivate the colors in the REPL. For +more on color support in terminal environments, read the tty +getColorDepth() documentation.

      +

      Legacy assertion mode#

      +

      Legacy assertion mode uses the Abstract Equality Comparison in:

      + +

      To use legacy assertion mode:

      +
      const assert = require('assert');
      +

      Whenever possible, use the strict assertion mode instead. Otherwise, the +Abstract Equality Comparison may cause surprising results. This is +especially true for assert.deepEqual(), where the comparison rules are +lax:

      +
      // WARNING: This does not throw an AssertionError!
      +assert.deepEqual(/a/gi, new Date());
      +

      Class: assert.AssertionError[src]#

      + +

      Indicates the failure of an assertion. All errors thrown by the assert module +will be instances of the AssertionError class.

      +

      new assert.AssertionError(options)#

      + +
        +
      • options <Object> +
          +
        • message <string> If provided, the error message is set to this value.
        • +
        • actual <any> The actual property on the error instance.
        • +
        • expected <any> The expected property on the error instance.
        • +
        • operator <string> The operator property on the error instance.
        • +
        • stackStartFn <Function> If provided, the generated stack trace omits +frames before this function.
        • +
        +
      • +
      +

      A subclass of Error that indicates the failure of an assertion.

      +

      All instances contain the built-in Error properties (message and name) +and:

      +
        +
      • actual <any> Set to the actual argument for methods such as +assert.strictEqual().
      • +
      • expected <any> Set to the expected value for methods such as +assert.strictEqual().
      • +
      • generatedMessage <boolean> Indicates if the message was auto-generated +(true) or not.
      • +
      • code <string> Value is always ERR_ASSERTION to show that the error is an +assertion error.
      • +
      • operator <string> Set to the passed in operator value.
      • +
      +
      const assert = require('assert');
      +
      +// Generate an AssertionError to compare the error message later:
      +const { message } = new assert.AssertionError({
      +  actual: 1,
      +  expected: 2,
      +  operator: 'strictEqual'
      +});
      +
      +// Verify error output:
      +try {
      +  assert.strictEqual(1, 2);
      +} catch (err) {
      +  assert(err instanceof assert.AssertionError);
      +  assert.strictEqual(err.message, message);
      +  assert.strictEqual(err.name, 'AssertionError');
      +  assert.strictEqual(err.actual, 1);
      +  assert.strictEqual(err.expected, 2);
      +  assert.strictEqual(err.code, 'ERR_ASSERTION');
      +  assert.strictEqual(err.operator, 'strictEqual');
      +  assert.strictEqual(err.generatedMessage, true);
      +}
      +

      Class: assert.CallTracker#

      + +

      Stability: 1 - Experimental

      +

      This feature is currently experimental and behavior might still change.

      +

      ### new assert.CallTracker()

      + +

      Creates a new CallTracker object which can be used to track if functions +were called a specific number of times. The tracker.verify() must be called +for the verification to take place. The usual pattern would be to call it in a +process.on('exit') handler.

      +
      const assert = require('assert');
      +
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +// callsfunc() must be called exactly 1 time before tracker.verify().
      +const callsfunc = tracker.calls(func, 1);
      +
      +callsfunc();
      +
      +// Calls tracker.verify() and verifies if all tracker.calls() functions have
      +// been called exact times.
      +process.on('exit', () => {
      +  tracker.verify();
      +});
      +

      tracker.calls([fn][, exact])#

      + + +

      The wrapper function is expected to be called exactly exact times. If the +function has not been called exactly exact times when +tracker.verify() is called, then tracker.verify() will throw an +error.

      +
      const assert = require('assert');
      +
      +// Creates call tracker.
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +// Returns a function that wraps func() that must be called exact times
      +// before tracker.verify().
      +const callsfunc = tracker.calls(func);
      +

      tracker.report()#

      + +
        +
      • Returns: <Array> of objects containing information about the wrapper functions +returned by tracker.calls().
      • +
      • Object <Object> +
          +
        • message <string>
        • +
        • actual <number> The actual number of times the function was called.
        • +
        • expected <number> The number of times the function was expected to be +called.
        • +
        • operator <string> The name of the function that is wrapped.
        • +
        • stack <Object> A stack trace of the function.
        • +
        +
      • +
      +

      The arrays contains information about the expected and actual number of calls of +the functions that have not been called the expected number of times.

      +
      const assert = require('assert');
      +
      +// Creates call tracker.
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +function foo() {}
      +
      +// Returns a function that wraps func() that must be called exact times
      +// before tracker.verify().
      +const callsfunc = tracker.calls(func, 2);
      +
      +// Returns an array containing information on callsfunc()
      +tracker.report();
      +// [
      +//  {
      +//    message: 'Expected the func function to be executed 2 time(s) but was
      +//    executed 0 time(s).',
      +//    actual: 0,
      +//    expected: 2,
      +//    operator: 'func',
      +//    stack: stack trace
      +//  }
      +// ]
      +

      tracker.verify()#

      + +

      Iterates through the list of functions passed to +tracker.calls() and will throw an error for functions that +have not been called the expected number of times.

      +
      const assert = require('assert');
      +
      +// Creates call tracker.
      +const tracker = new assert.CallTracker();
      +
      +function func() {}
      +
      +// Returns a function that wraps func() that must be called exact times
      +// before tracker.verify().
      +const callsfunc = tracker.calls(func, 2);
      +
      +callsfunc();
      +
      +// Will throw an error since callsfunc() was only called once.
      +tracker.verify();
      +

      assert(value[, message])#

      + + +

      An alias of assert.ok().

      +

      assert.deepEqual(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.deepStrictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.deepStrictEqual() instead.

      +

      Tests for deep equality between the actual and expected parameters. Consider +using assert.deepStrictEqual() instead. assert.deepEqual() can have +surprising results.

      +

      Deep equality means that the enumerable "own" properties of child objects +are also recursively evaluated by the following rules.

      +

      Comparison details#

      +
        +
      • Primitive values are compared with the Abstract Equality Comparison +( == ).
      • +
      • Type tags of objects should be the same.
      • +
      • Only enumerable "own" properties are considered.
      • +
      • Error names and messages are always compared, even if these are not +enumerable properties.
      • +
      • Object wrappers are compared both as objects and unwrapped values.
      • +
      • Object properties are compared unordered.
      • +
      • Map keys and Set items are compared unordered.
      • +
      • Recursion stops when both sides differ or both sides encounter a circular +reference.
      • +
      • Implementation does not test the [[Prototype]] of +objects.
      • +
      • Symbol properties are not compared.
      • +
      • WeakMap and WeakSet comparison does not rely on their values.
      • +
      +

      The following example does not throw an AssertionError because the +primitives are considered equal by the Abstract Equality Comparison +( == ).

      +
      // WARNING: This does not throw an AssertionError!
      +assert.deepEqual('+00000000', false);
      +

      "Deep" equality means that the enumerable "own" properties of child objects +are evaluated also:

      +
      const assert = require('assert');
      +
      +const obj1 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj2 = {
      +  a: {
      +    b: 2
      +  }
      +};
      +const obj3 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj4 = Object.create(obj1);
      +
      +assert.deepEqual(obj1, obj1);
      +// OK
      +
      +// Values of b are different:
      +assert.deepEqual(obj1, obj2);
      +// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
      +
      +assert.deepEqual(obj1, obj3);
      +// OK
      +
      +// Prototypes are ignored:
      +assert.deepEqual(obj1, obj4);
      +// AssertionError: { a: { b: 1 } } deepEqual {}
      +

      If the values are not equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.deepStrictEqual(actual, expected[, message])#

      + + +

      Tests for deep equality between the actual and expected parameters. +"Deep" equality means that the enumerable "own" properties of child objects +are recursively evaluated also by the following rules.

      +

      Comparison details#

      + +
      const assert = require('assert').strict;
      +
      +// This fails because 1 !== '1'.
      +assert.deepStrictEqual({ a: 1 }, { a: '1' });
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +//   {
      +// +   a: 1
      +// -   a: '1'
      +//   }
      +
      +// The following objects don't have own properties
      +const date = new Date();
      +const object = {};
      +const fakeDate = {};
      +Object.setPrototypeOf(fakeDate, Date.prototype);
      +
      +// Different [[Prototype]]:
      +assert.deepStrictEqual(object, fakeDate);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + {}
      +// - Date {}
      +
      +// Different type tags:
      +assert.deepStrictEqual(date, fakeDate);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + 2018-04-26T00:49:08.604Z
      +// - Date {}
      +
      +assert.deepStrictEqual(NaN, NaN);
      +// OK, because of the SameValue comparison
      +
      +// Different unwrapped numbers:
      +assert.deepStrictEqual(new Number(1), new Number(2));
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + [Number: 1]
      +// - [Number: 2]
      +
      +assert.deepStrictEqual(new String('foo'), Object('foo'));
      +// OK because the object and the string are identical when unwrapped.
      +
      +assert.deepStrictEqual(-0, -0);
      +// OK
      +
      +// Different zeros using the SameValue Comparison:
      +assert.deepStrictEqual(0, -0);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +// + 0
      +// - -0
      +
      +const symbol1 = Symbol();
      +const symbol2 = Symbol();
      +assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
      +// OK, because it is the same symbol on both objects.
      +
      +assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
      +// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
      +//
      +// {
      +//   [Symbol()]: 1
      +// }
      +
      +const weakMap1 = new WeakMap();
      +const weakMap2 = new WeakMap([[{}, {}]]);
      +const weakMap3 = new WeakMap();
      +weakMap3.unequal = true;
      +
      +assert.deepStrictEqual(weakMap1, weakMap2);
      +// OK, because it is impossible to compare the entries
      +
      +// Fails because weakMap3 has a property that weakMap1 does not contain:
      +assert.deepStrictEqual(weakMap1, weakMap3);
      +// AssertionError: Expected inputs to be strictly deep-equal:
      +// + actual - expected
      +//
      +//   WeakMap {
      +// +   [items unknown]
      +// -   [items unknown],
      +// -   unequal: true
      +//   }
      +

      If the values are not equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.doesNotMatch(string, regexp[, message])#

      + + +

      Stability: 1 - Experimental

      +

      Expects the string input not to match the regular expression.

      +

      This feature is currently experimental and the name might change or it might be +completely removed again.

      +
      const assert = require('assert').strict;
      +
      +assert.doesNotMatch('I will fail', /fail/);
      +// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
      +
      +assert.doesNotMatch(123, /pass/);
      +// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
      +
      +assert.doesNotMatch('I will pass', /different/);
      +// OK
      +

      If the values do match, or if the string argument is of another type than +string, an AssertionError is thrown with a message property set equal +to the value of the message parameter. If the message parameter is +undefined, a default error message is assigned. If the message parameter is an +instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.doesNotReject(asyncFn[, error][, message])#

      + + +

      Awaits the asyncFn promise or, if asyncFn is a function, immediately +calls the function and awaits the returned promise to complete. It will then +check that the promise is not rejected.

      +

      If asyncFn is a function and it throws an error synchronously, +assert.doesNotReject() will return a rejected Promise with that error. If +the function does not return a promise, assert.doesNotReject() will return a +rejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases +the error handler is skipped.

      +

      Using assert.doesNotReject() is actually not useful because there is little +benefit in catching a rejection and then rejecting it again. Instead, consider +adding a comment next to the specific code path that should not reject and keep +error messages as expressive as possible.

      +

      If specified, error can be a Class, RegExp or a validation +function. See assert.throws() for more details.

      +

      Besides the async nature to await the completion behaves identically to +assert.doesNotThrow().

      + +
      (async () => {
      +  await assert.doesNotReject(
      +    async () => {
      +      throw new TypeError('Wrong value');
      +    },
      +    SyntaxError
      +  );
      +})();
      + +
      assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
      +  .then(() => {
      +    // ...
      +  });
      +

      assert.doesNotThrow(fn[, error][, message])#

      + + +

      Asserts that the function fn does not throw an error.

      +

      Using assert.doesNotThrow() is actually not useful because there +is no benefit in catching an error and then rethrowing it. Instead, consider +adding a comment next to the specific code path that should not throw and keep +error messages as expressive as possible.

      +

      When assert.doesNotThrow() is called, it will immediately call the fn +function.

      +

      If an error is thrown and it is the same type as that specified by the error +parameter, then an AssertionError is thrown. If the error is of a +different type, or if the error parameter is undefined, the error is +propagated back to the caller.

      +

      If specified, error can be a Class, RegExp or a validation +function. See assert.throws() for more details.

      +

      The following, for instance, will throw the TypeError because there is no +matching error type in the assertion:

      + +
      assert.doesNotThrow(
      +  () => {
      +    throw new TypeError('Wrong value');
      +  },
      +  SyntaxError
      +);
      +

      However, the following will result in an AssertionError with the message +'Got unwanted exception...':

      + +
      assert.doesNotThrow(
      +  () => {
      +    throw new TypeError('Wrong value');
      +  },
      +  TypeError
      +);
      +

      If an AssertionError is thrown and a value is provided for the message +parameter, the value of message will be appended to the AssertionError +message:

      + +
      assert.doesNotThrow(
      +  () => {
      +    throw new TypeError('Wrong value');
      +  },
      +  /Wrong value/,
      +  'Whoops'
      +);
      +// Throws: AssertionError: Got unwanted exception: Whoops
      +

      assert.equal(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.strictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.strictEqual() instead.

      +

      Tests shallow, coercive equality between the actual and expected parameters +using the Abstract Equality Comparison ( == ).

      +
      const assert = require('assert');
      +
      +assert.equal(1, 1);
      +// OK, 1 == 1
      +assert.equal(1, '1');
      +// OK, 1 == '1'
      +
      +assert.equal(1, 2);
      +// AssertionError: 1 == 2
      +assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
      +// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
      +

      If the values are not equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.fail([message])#

      + + +

      Throws an AssertionError with the provided error message or a default +error message. If the message parameter is an instance of an Error then +it will be thrown instead of the AssertionError.

      +
      const assert = require('assert').strict;
      +
      +assert.fail();
      +// AssertionError [ERR_ASSERTION]: Failed
      +
      +assert.fail('boom');
      +// AssertionError [ERR_ASSERTION]: boom
      +
      +assert.fail(new TypeError('need array'));
      +// TypeError: need array
      +

      Using assert.fail() with more than two arguments is possible but deprecated. +See below for further details.

      +

      assert.fail(actual, expected[, message[, operator[, stackStartFn]]])#

      + +

      Stability: 0 - Deprecated: Use assert.fail([message]) or other assert +functions instead.

      + +

      If message is falsy, the error message is set as the values of actual and +expected separated by the provided operator. If just the two actual and +expected arguments are provided, operator will default to '!='. If +message is provided as third argument it will be used as the error message and +the other arguments will be stored as properties on the thrown object. If +stackStartFn is provided, all stack frames above that function will be +removed from stacktrace (see Error.captureStackTrace). If no arguments are +given, the default message Failed will be used.

      +
      const assert = require('assert').strict;
      +
      +assert.fail('a', 'b');
      +// AssertionError [ERR_ASSERTION]: 'a' != 'b'
      +
      +assert.fail(1, 2, undefined, '>');
      +// AssertionError [ERR_ASSERTION]: 1 > 2
      +
      +assert.fail(1, 2, 'fail');
      +// AssertionError [ERR_ASSERTION]: fail
      +
      +assert.fail(1, 2, 'whoops', '>');
      +// AssertionError [ERR_ASSERTION]: whoops
      +
      +assert.fail(1, 2, new TypeError('need array'));
      +// TypeError: need array
      +

      In the last three cases actual, expected, and operator have no +influence on the error message.

      +

      Example use of stackStartFn for truncating the exception's stacktrace:

      +
      function suppressFrame() {
      +  assert.fail('a', 'b', undefined, '!==', suppressFrame);
      +}
      +suppressFrame();
      +// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
      +//     at repl:1:1
      +//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
      +//     ...
      +

      assert.ifError(value)#

      + + +

      Throws value if value is not undefined or null. This is useful when +testing the error argument in callbacks. The stack trace contains all frames +from the error passed to ifError() including the potential new frames for +ifError() itself.

      +
      const assert = require('assert').strict;
      +
      +assert.ifError(null);
      +// OK
      +assert.ifError(0);
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
      +assert.ifError('error');
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
      +assert.ifError(new Error());
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
      +
      +// Create some random error frames.
      +let err;
      +(function errorFrame() {
      +  err = new Error('test error');
      +})();
      +
      +(function ifErrorFrame() {
      +  assert.ifError(err);
      +})();
      +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
      +//     at ifErrorFrame
      +//     at errorFrame
      +

      assert.match(string, regexp[, message])#

      + + +

      Stability: 1 - Experimental

      +

      Expects the string input to match the regular expression.

      +

      This feature is currently experimental and the name might change or it might be +completely removed again.

      +
      const assert = require('assert').strict;
      +
      +assert.match('I will fail', /pass/);
      +// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
      +
      +assert.match(123, /pass/);
      +// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
      +
      +assert.match('I will pass', /pass/);
      +// OK
      +

      If the values do not match, or if the string argument is of another type than +string, an AssertionError is thrown with a message property set equal +to the value of the message parameter. If the message parameter is +undefined, a default error message is assigned. If the message parameter is an +instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.notDeepEqual(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.notDeepStrictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.notDeepStrictEqual() instead.

      +

      Tests for any deep inequality. Opposite of assert.deepEqual().

      +
      const assert = require('assert');
      +
      +const obj1 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj2 = {
      +  a: {
      +    b: 2
      +  }
      +};
      +const obj3 = {
      +  a: {
      +    b: 1
      +  }
      +};
      +const obj4 = Object.create(obj1);
      +
      +assert.notDeepEqual(obj1, obj1);
      +// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
      +
      +assert.notDeepEqual(obj1, obj2);
      +// OK
      +
      +assert.notDeepEqual(obj1, obj3);
      +// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
      +
      +assert.notDeepEqual(obj1, obj4);
      +// OK
      +

      If the values are deeply equal, an AssertionError is thrown with a +message property set equal to the value of the message parameter. If the +message parameter is undefined, a default error message is assigned. If the +message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.notDeepStrictEqual(actual, expected[, message])#

      + + +

      Tests for deep strict inequality. Opposite of assert.deepStrictEqual().

      +
      const assert = require('assert').strict;
      +
      +assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
      +// OK
      +

      If the values are deeply and strictly equal, an AssertionError is thrown +with a message property set equal to the value of the message parameter. If +the message parameter is undefined, a default error message is assigned. If +the message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.notEqual(actual, expected[, message])#

      + + +

      Strict assertion mode

      +

      An alias of assert.notStrictEqual().

      +

      Legacy assertion mode

      +

      Stability: 0 - Deprecated: Use assert.notStrictEqual() instead.

      +

      Tests shallow, coercive inequality with the Abstract Equality Comparison +( != ).

      +
      const assert = require('assert');
      +
      +assert.notEqual(1, 2);
      +// OK
      +
      +assert.notEqual(1, 1);
      +// AssertionError: 1 != 1
      +
      +assert.notEqual(1, '1');
      +// AssertionError: 1 != '1'
      +

      If the values are equal, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError.

      +

      assert.notStrictEqual(actual, expected[, message])#

      + + +

      Tests strict inequality between the actual and expected parameters as +determined by the SameValue Comparison.

      +
      const assert = require('assert').strict;
      +
      +assert.notStrictEqual(1, 2);
      +// OK
      +
      +assert.notStrictEqual(1, 1);
      +// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
      +//
      +// 1
      +
      +assert.notStrictEqual(1, '1');
      +// OK
      +

      If the values are strictly equal, an AssertionError is thrown with a +message property set equal to the value of the message parameter. If the +message parameter is undefined, a default error message is assigned. If the +message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.ok(value[, message])#

      + + +

      Tests if value is truthy. It is equivalent to +assert.equal(!!value, true, message).

      +

      If value is not truthy, an AssertionError is thrown with a message +property set equal to the value of the message parameter. If the message +parameter is undefined, a default error message is assigned. If the message +parameter is an instance of an Error then it will be thrown instead of the +AssertionError. +If no arguments are passed in at all message will be set to the string: +'No value argument passed to `assert.ok()`'.

      +

      Be aware that in the repl the error message will be different to the one +thrown in a file! See below for further details.

      +
      const assert = require('assert').strict;
      +
      +assert.ok(true);
      +// OK
      +assert.ok(1);
      +// OK
      +
      +assert.ok();
      +// AssertionError: No value argument passed to `assert.ok()`
      +
      +assert.ok(false, 'it\'s false');
      +// AssertionError: it's false
      +
      +// In the repl:
      +assert.ok(typeof 123 === 'string');
      +// AssertionError: false == true
      +
      +// In a file (e.g. test.js):
      +assert.ok(typeof 123 === 'string');
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert.ok(typeof 123 === 'string')
      +
      +assert.ok(false);
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert.ok(false)
      +
      +assert.ok(0);
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert.ok(0)
      +
      +// Using `assert()` works the same:
      +assert(0);
      +// AssertionError: The expression evaluated to a falsy value:
      +//
      +//   assert(0)
      +

      assert.rejects(asyncFn[, error][, message])#

      + + +

      Awaits the asyncFn promise or, if asyncFn is a function, immediately +calls the function and awaits the returned promise to complete. It will then +check that the promise is rejected.

      +

      If asyncFn is a function and it throws an error synchronously, +assert.rejects() will return a rejected Promise with that error. If the +function does not return a promise, assert.rejects() will return a rejected +Promise with an ERR_INVALID_RETURN_VALUE error. In both cases the error +handler is skipped.

      +

      Besides the async nature to await the completion behaves identically to +assert.throws().

      +

      If specified, error can be a Class, RegExp, a validation function, +an object where each property will be tested for, or an instance of error where +each property will be tested for including the non-enumerable message and +name properties.

      +

      If specified, message will be the message provided by the AssertionError +if the asyncFn fails to reject.

      +
      (async () => {
      +  await assert.rejects(
      +    async () => {
      +      throw new TypeError('Wrong value');
      +    },
      +    {
      +      name: 'TypeError',
      +      message: 'Wrong value'
      +    }
      +  );
      +})();
      +
      (async () => {
      +  await assert.rejects(
      +    async () => {
      +      throw new TypeError('Wrong value');
      +    },
      +    (err) => {
      +      assert.strictEqual(err.name, 'TypeError');
      +      assert.strictEqual(err.message, 'Wrong value');
      +      return true;
      +    }
      +  );
      +})();
      +
      assert.rejects(
      +  Promise.reject(new Error('Wrong value')),
      +  Error
      +).then(() => {
      +  // ...
      +});
      +

      error cannot be a string. If a string is provided as the second +argument, then error is assumed to be omitted and the string will be used for +message instead. This can lead to easy-to-miss mistakes. Please read the +example in assert.throws() carefully if using a string as the second +argument gets considered.

      +

      assert.strictEqual(actual, expected[, message])#

      + + +

      Tests strict equality between the actual and expected parameters as +determined by the SameValue Comparison.

      +
      const assert = require('assert').strict;
      +
      +assert.strictEqual(1, 2);
      +// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
      +//
      +// 1 !== 2
      +
      +assert.strictEqual(1, 1);
      +// OK
      +
      +assert.strictEqual('Hello foobar', 'Hello World!');
      +// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
      +// + actual - expected
      +//
      +// + 'Hello foobar'
      +// - 'Hello World!'
      +//          ^
      +
      +const apples = 1;
      +const oranges = 2;
      +assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
      +// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
      +
      +assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
      +// TypeError: Inputs are not identical
      +

      If the values are not strictly equal, an AssertionError is thrown with a +message property set equal to the value of the message parameter. If the +message parameter is undefined, a default error message is assigned. If the +message parameter is an instance of an Error then it will be thrown +instead of the AssertionError.

      +

      assert.throws(fn[, error][, message])#

      + + +

      Expects the function fn to throw an error.

      +

      If specified, error can be a Class, RegExp, a validation function, +a validation object where each property will be tested for strict deep equality, +or an instance of error where each property will be tested for strict deep +equality including the non-enumerable message and name properties. When +using an object, it is also possible to use a regular expression, when +validating against a string property. See below for examples.

      +

      If specified, message will be appended to the message provided by the +AssertionError if the fn call fails to throw or in case the error validation +fails.

      +

      Custom validation object/error instance:

      +
      const err = new TypeError('Wrong value');
      +err.code = 404;
      +err.foo = 'bar';
      +err.info = {
      +  nested: true,
      +  baz: 'text'
      +};
      +err.reg = /abc/i;
      +
      +assert.throws(
      +  () => {
      +    throw err;
      +  },
      +  {
      +    name: 'TypeError',
      +    message: 'Wrong value',
      +    info: {
      +      nested: true,
      +      baz: 'text'
      +    }
      +    // Only properties on the validation object will be tested for.
      +    // Using nested objects requires all properties to be present. Otherwise
      +    // the validation is going to fail.
      +  }
      +);
      +
      +// Using regular expressions to validate error properties:
      +assert.throws(
      +  () => {
      +    throw err;
      +  },
      +  {
      +    // The `name` and `message` properties are strings and using regular
      +    // expressions on those will match against the string. If they fail, an
      +    // error is thrown.
      +    name: /^TypeError$/,
      +    message: /Wrong/,
      +    foo: 'bar',
      +    info: {
      +      nested: true,
      +      // It is not possible to use regular expressions for nested properties!
      +      baz: 'text'
      +    },
      +    // The `reg` property contains a regular expression and only if the
      +    // validation object contains an identical regular expression, it is going
      +    // to pass.
      +    reg: /abc/i
      +  }
      +);
      +
      +// Fails due to the different `message` and `name` properties:
      +assert.throws(
      +  () => {
      +    const otherErr = new Error('Not found');
      +    // Copy all enumerable properties from `err` to `otherErr`.
      +    for (const [key, value] of Object.entries(err)) {
      +      otherErr[key] = value;
      +    }
      +    throw otherErr;
      +  },
      +  // The error's `message` and `name` properties will also be checked when using
      +  // an error as validation object.
      +  err
      +);
      +

      Validate instanceof using constructor:

      +
      assert.throws(
      +  () => {
      +    throw new Error('Wrong value');
      +  },
      +  Error
      +);
      +

      Validate error message using RegExp:

      +

      Using a regular expression runs .toString on the error object, and will +therefore also include the error name.

      +
      assert.throws(
      +  () => {
      +    throw new Error('Wrong value');
      +  },
      +  /^Error: Wrong value$/
      +);
      +

      Custom error validation:

      +

      The function must return true to indicate all internal validations passed. +It will otherwise fail with an AssertionError.

      +
      assert.throws(
      +  () => {
      +    throw new Error('Wrong value');
      +  },
      +  (err) => {
      +    assert(err instanceof Error);
      +    assert(/value/.test(err));
      +    // Avoid returning anything from validation functions besides `true`.
      +    // Otherwise, it's not clear what part of the validation failed. Instead,
      +    // throw an error about the specific validation that failed (as done in this
      +    // example) and add as much helpful debugging information to that error as
      +    // possible.
      +    return true;
      +  },
      +  'unexpected error'
      +);
      +

      error cannot be a string. If a string is provided as the second +argument, then error is assumed to be omitted and the string will be used for +message instead. This can lead to easy-to-miss mistakes. Using the same +message as the thrown error message is going to result in an +ERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using +a string as the second argument gets considered:

      + +
      function throwingFirst() {
      +  throw new Error('First');
      +}
      +
      +function throwingSecond() {
      +  throw new Error('Second');
      +}
      +
      +function notThrowing() {}
      +
      +// The second argument is a string and the input function threw an Error.
      +// The first case will not throw as it does not match for the error message
      +// thrown by the input function!
      +assert.throws(throwingFirst, 'Second');
      +// In the next example the message has no benefit over the message from the
      +// error and since it is not clear if the user intended to actually match
      +// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
      +assert.throws(throwingSecond, 'Second');
      +// TypeError [ERR_AMBIGUOUS_ARGUMENT]
      +
      +// The string is only used (as message) in case the function does not throw:
      +assert.throws(notThrowing, 'Second');
      +// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
      +
      +// If it was intended to match for the error message do this instead:
      +// It does not throw because the error messages match.
      +assert.throws(throwingSecond, /Second$/);
      +
      +// If the error message does not match, an AssertionError is thrown.
      +assert.throws(throwingFirst, /Second$/);
      +// AssertionError [ERR_ASSERTION]
      +

      Due to the confusing error-prone notation, avoid a string as the second +argument.

      + +
      +
      +
      + + diff --git a/doc/api/assert.json b/doc/api/assert.json new file mode 100644 index 0000000000000000000000000000000000000000..6deb47fc96415298ff2de692fe676de1f48e4544 --- /dev/null +++ b/doc/api/assert.json @@ -0,0 +1,1062 @@ +{ + "type": "module", + "source": "doc/api/assert.md", + "modules": [ + { + "textRaw": "Assert", + "name": "assert", + "introduced_in": "v0.1.21", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/assert.js

      \n

      The assert module provides a set of assertion functions for verifying\ninvariants.

      ", + "modules": [ + { + "textRaw": "Strict assertion mode", + "name": "strict_assertion_mode", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [ + { + "version": "v12.16.2", + "description": "Changed \"strict mode\" to \"strict assertion mode\" and \"legacy mode\" to \"legacy assertion mode\" to avoid confusion with the more usual meaning of \"strict mode\"." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17615", + "description": "Added error diffs to the strict assertion mode." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17002", + "description": "Added strict assertion mode to the assert module." + } + ] + }, + "desc": "

      In strict assertion mode, non-strict methods behave like their corresponding\nstrict methods. For example, assert.deepEqual() will behave like\nassert.deepStrictEqual().

      \n

      In strict assertion mode, error messages for objects display a diff. In legacy\nassertion mode, error messages for objects display the objects, often truncated.

      \n

      To use strict assertion mode:

      \n
      const assert = require('assert').strict;\n
      \n

      Example error diff:

      \n
      const assert = require('assert').strict;\n\nassert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected ... Lines skipped\n//\n//   [\n//     [\n// ...\n//       2,\n// +     3\n// -     '3'\n//     ],\n// ...\n//     5\n//   ]\n
      \n

      To deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS\nenvironment variables. This will also deactivate the colors in the REPL. For\nmore on color support in terminal environments, read the tty\ngetColorDepth() documentation.

      ", + "type": "module", + "displayName": "Strict assertion mode" + }, + { + "textRaw": "Legacy assertion mode", + "name": "legacy_assertion_mode", + "desc": "

      Legacy assertion mode uses the Abstract Equality Comparison in:

      \n\n

      To use legacy assertion mode:

      \n
      const assert = require('assert');\n
      \n

      Whenever possible, use the strict assertion mode instead. Otherwise, the\nAbstract Equality Comparison may cause surprising results. This is\nespecially true for assert.deepEqual(), where the comparison rules are\nlax:

      \n
      // WARNING: This does not throw an AssertionError!\nassert.deepEqual(/a/gi, new Date());\n
      ", + "type": "module", + "displayName": "Legacy assertion mode" + } + ], + "classes": [ + { + "textRaw": "Class: assert.AssertionError", + "type": "class", + "name": "assert.AssertionError", + "desc": "\n

      Indicates the failure of an assertion. All errors thrown by the assert module\nwill be instances of the AssertionError class.

      ", + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`message` {string} If provided, the error message is set to this value.", + "name": "message", + "type": "string", + "desc": "If provided, the error message is set to this value." + }, + { + "textRaw": "`actual` {any} The `actual` property on the error instance.", + "name": "actual", + "type": "any", + "desc": "The `actual` property on the error instance." + }, + { + "textRaw": "`expected` {any} The `expected` property on the error instance.", + "name": "expected", + "type": "any", + "desc": "The `expected` property on the error instance." + }, + { + "textRaw": "`operator` {string} The `operator` property on the error instance.", + "name": "operator", + "type": "string", + "desc": "The `operator` property on the error instance." + }, + { + "textRaw": "`stackStartFn` {Function} If provided, the generated stack trace omits frames before this function.", + "name": "stackStartFn", + "type": "Function", + "desc": "If provided, the generated stack trace omits frames before this function." + } + ] + } + ], + "desc": "

      A subclass of Error that indicates the failure of an assertion.

      \n

      All instances contain the built-in Error properties (message and name)\nand:

      \n
        \n
      • actual <any> Set to the actual argument for methods such as\nassert.strictEqual().
      • \n
      • expected <any> Set to the expected value for methods such as\nassert.strictEqual().
      • \n
      • generatedMessage <boolean> Indicates if the message was auto-generated\n(true) or not.
      • \n
      • code <string> Value is always ERR_ASSERTION to show that the error is an\nassertion error.
      • \n
      • operator <string> Set to the passed in operator value.
      • \n
      \n
      const assert = require('assert');\n\n// Generate an AssertionError to compare the error message later:\nconst { message } = new assert.AssertionError({\n  actual: 1,\n  expected: 2,\n  operator: 'strictEqual'\n});\n\n// Verify error output:\ntry {\n  assert.strictEqual(1, 2);\n} catch (err) {\n  assert(err instanceof assert.AssertionError);\n  assert.strictEqual(err.message, message);\n  assert.strictEqual(err.name, 'AssertionError');\n  assert.strictEqual(err.actual, 1);\n  assert.strictEqual(err.expected, 2);\n  assert.strictEqual(err.code, 'ERR_ASSERTION');\n  assert.strictEqual(err.operator, 'strictEqual');\n  assert.strictEqual(err.generatedMessage, true);\n}\n
      " + } + ] + }, + { + "textRaw": "Class: `assert.CallTracker`", + "type": "class", + "name": "assert.CallTracker", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      This feature is currently experimental and behavior might still change.

      \n

      ### new assert.CallTracker()

      \n

      Creates a new CallTracker object which can be used to track if functions\nwere called a specific number of times. The tracker.verify() must be called\nfor the verification to take place. The usual pattern would be to call it in a\nprocess.on('exit') handler.

      \n
      const assert = require('assert');\n\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// callsfunc() must be called exactly 1 time before tracker.verify().\nconst callsfunc = tracker.calls(func, 1);\n\ncallsfunc();\n\n// Calls tracker.verify() and verifies if all tracker.calls() functions have\n// been called exact times.\nprocess.on('exit', () => {\n  tracker.verify();\n});\n
      ", + "methods": [ + { + "textRaw": "`tracker.calls([fn][, exact])`", + "type": "method", + "name": "calls", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} that wraps `fn`.", + "name": "return", + "type": "Function", + "desc": "that wraps `fn`." + }, + "params": [ + { + "textRaw": "`fn` {Function} **Default** A no-op function.", + "name": "fn", + "type": "Function", + "desc": "**Default** A no-op function." + }, + { + "textRaw": "`exact` {number} **Default** `1`.", + "name": "exact", + "type": "number", + "desc": "**Default** `1`." + } + ] + } + ], + "desc": "

      The wrapper function is expected to be called exactly exact times. If the\nfunction has not been called exactly exact times when\ntracker.verify() is called, then tracker.verify() will throw an\nerror.

      \n
      const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func);\n
      " + }, + { + "textRaw": "`tracker.report()`", + "type": "method", + "name": "report", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Array} of objects containing information about the wrapper functions returned by [`tracker.calls()`][].", + "name": "return", + "type": "Array", + "desc": "of objects containing information about the wrapper functions returned by [`tracker.calls()`][]." + }, + "params": [ + { + "textRaw": "Object {Object}", + "name": "Object", + "type": "Object", + "options": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + }, + { + "textRaw": "`actual` {number} The actual number of times the function was called.", + "name": "actual", + "type": "number", + "desc": "The actual number of times the function was called." + }, + { + "textRaw": "`expected` {number} The number of times the function was expected to be called.", + "name": "expected", + "type": "number", + "desc": "The number of times the function was expected to be called." + }, + { + "textRaw": "`operator` {string} The name of the function that is wrapped.", + "name": "operator", + "type": "string", + "desc": "The name of the function that is wrapped." + }, + { + "textRaw": "`stack` {Object} A stack trace of the function.", + "name": "stack", + "type": "Object", + "desc": "A stack trace of the function." + } + ] + } + ] + } + ], + "desc": "

      The arrays contains information about the expected and actual number of calls of\nthe functions that have not been called the expected number of times.

      \n
      const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\nfunction foo() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\n// Returns an array containing information on callsfunc()\ntracker.report();\n// [\n//  {\n//    message: 'Expected the func function to be executed 2 time(s) but was\n//    executed 0 time(s).',\n//    actual: 0,\n//    expected: 2,\n//    operator: 'func',\n//    stack: stack trace\n//  }\n// ]\n
      " + }, + { + "textRaw": "`tracker.verify()`", + "type": "method", + "name": "verify", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Iterates through the list of functions passed to\ntracker.calls() and will throw an error for functions that\nhave not been called the expected number of times.

      \n
      const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\ncallsfunc();\n\n// Will throw an error since callsfunc() was only called once.\ntracker.verify();\n
      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`assert(value[, message])`", + "type": "method", + "name": "assert", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any} The input that is checked for being truthy.", + "name": "value", + "type": "any", + "desc": "The input that is checked for being truthy." + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      An alias of assert.ok().

      " + }, + { + "textRaw": "`assert.deepEqual(actual, expected[, message])`", + "type": "method", + "name": "deepEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25008", + "description": "The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.deepStrictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.deepStrictEqual() instead.

      \n
      \n

      Tests for deep equality between the actual and expected parameters. Consider\nusing assert.deepStrictEqual() instead. assert.deepEqual() can have\nsurprising results.

      \n

      Deep equality means that the enumerable \"own\" properties of child objects\nare also recursively evaluated by the following rules.

      ", + "modules": [ + { + "textRaw": "Comparison details", + "name": "comparison_details", + "desc": "
        \n
      • Primitive values are compared with the Abstract Equality Comparison\n( == ).
      • \n
      • Type tags of objects should be the same.
      • \n
      • Only enumerable \"own\" properties are considered.
      • \n
      • Error names and messages are always compared, even if these are not\nenumerable properties.
      • \n
      • Object wrappers are compared both as objects and unwrapped values.
      • \n
      • Object properties are compared unordered.
      • \n
      • Map keys and Set items are compared unordered.
      • \n
      • Recursion stops when both sides differ or both sides encounter a circular\nreference.
      • \n
      • Implementation does not test the [[Prototype]] of\nobjects.
      • \n
      • Symbol properties are not compared.
      • \n
      • WeakMap and WeakSet comparison does not rely on their values.
      • \n
      \n

      The following example does not throw an AssertionError because the\nprimitives are considered equal by the Abstract Equality Comparison\n( == ).

      \n
      // WARNING: This does not throw an AssertionError!\nassert.deepEqual('+00000000', false);\n
      \n

      \"Deep\" equality means that the enumerable \"own\" properties of child objects\nare evaluated also:

      \n
      const assert = require('assert');\n\nconst obj1 = {\n  a: {\n    b: 1\n  }\n};\nconst obj2 = {\n  a: {\n    b: 2\n  }\n};\nconst obj3 = {\n  a: {\n    b: 1\n  }\n};\nconst obj4 = Object.create(obj1);\n\nassert.deepEqual(obj1, obj1);\n// OK\n\n// Values of b are different:\nassert.deepEqual(obj1, obj2);\n// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }\n\nassert.deepEqual(obj1, obj3);\n// OK\n\n// Prototypes are ignored:\nassert.deepEqual(obj1, obj4);\n// AssertionError: { a: { b: 1 } } deepEqual {}\n
      \n

      If the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      ", + "type": "module", + "displayName": "Comparison details" + } + ] + }, + { + "textRaw": "`assert.deepStrictEqual(actual, expected[, message])`", + "type": "method", + "name": "deepStrictEqual", + "meta": { + "added": [ + "v1.2.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15169", + "description": "Enumerable symbol properties are now compared." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15036", + "description": "The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison." + }, + { + "version": "v8.5.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests for deep equality between the actual and expected parameters.\n\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare recursively evaluated also by the following rules.

      ", + "modules": [ + { + "textRaw": "Comparison details", + "name": "comparison_details", + "desc": "\n
      const assert = require('assert').strict;\n\n// This fails because 1 !== '1'.\nassert.deepStrictEqual({ a: 1 }, { a: '1' });\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n//   {\n// +   a: 1\n// -   a: '1'\n//   }\n\n// The following objects don't have own properties\nconst date = new Date();\nconst object = {};\nconst fakeDate = {};\nObject.setPrototypeOf(fakeDate, Date.prototype);\n\n// Different [[Prototype]]:\nassert.deepStrictEqual(object, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + {}\n// - Date {}\n\n// Different type tags:\nassert.deepStrictEqual(date, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 2018-04-26T00:49:08.604Z\n// - Date {}\n\nassert.deepStrictEqual(NaN, NaN);\n// OK, because of the SameValue comparison\n\n// Different unwrapped numbers:\nassert.deepStrictEqual(new Number(1), new Number(2));\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + [Number: 1]\n// - [Number: 2]\n\nassert.deepStrictEqual(new String('foo'), Object('foo'));\n// OK because the object and the string are identical when unwrapped.\n\nassert.deepStrictEqual(-0, -0);\n// OK\n\n// Different zeros using the SameValue Comparison:\nassert.deepStrictEqual(0, -0);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 0\n// - -0\n\nconst symbol1 = Symbol();\nconst symbol2 = Symbol();\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });\n// OK, because it is the same symbol on both objects.\n\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });\n// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:\n//\n// {\n//   [Symbol()]: 1\n// }\n\nconst weakMap1 = new WeakMap();\nconst weakMap2 = new WeakMap([[{}, {}]]);\nconst weakMap3 = new WeakMap();\nweakMap3.unequal = true;\n\nassert.deepStrictEqual(weakMap1, weakMap2);\n// OK, because it is impossible to compare the entries\n\n// Fails because weakMap3 has a property that weakMap1 does not contain:\nassert.deepStrictEqual(weakMap1, weakMap3);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n//   WeakMap {\n// +   [items unknown]\n// -   [items unknown],\n// -   unequal: true\n//   }\n
      \n

      If the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      ", + "type": "module", + "displayName": "Comparison details" + } + ] + }, + { + "textRaw": "`assert.doesNotMatch(string, regexp[, message])`", + "type": "method", + "name": "doesNotMatch", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`regexp` {RegExp}", + "name": "regexp", + "type": "RegExp" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Expects the string input not to match the regular expression.

      \n

      This feature is currently experimental and the name might change or it might be\ncompletely removed again.

      \n
      const assert = require('assert').strict;\n\nassert.doesNotMatch('I will fail', /fail/);\n// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...\n\nassert.doesNotMatch(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.doesNotMatch('I will pass', /different/);\n// OK\n
      \n

      If the values do match, or if the string argument is of another type than\nstring, an AssertionError is thrown with a message property set equal\nto the value of the message parameter. If the message parameter is\nundefined, a default error message is assigned. If the message parameter is an\ninstance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.doesNotReject(asyncFn[, error][, message])`", + "type": "method", + "name": "doesNotReject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncFn` {Function|Promise}", + "name": "asyncFn", + "type": "Function|Promise" + }, + { + "textRaw": "`error` {RegExp|Function}", + "name": "error", + "type": "RegExp|Function" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Awaits the asyncFn promise or, if asyncFn is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is not rejected.

      \n

      If asyncFn is a function and it throws an error synchronously,\nassert.doesNotReject() will return a rejected Promise with that error. If\nthe function does not return a promise, assert.doesNotReject() will return a\nrejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases\nthe error handler is skipped.

      \n

      Using assert.doesNotReject() is actually not useful because there is little\nbenefit in catching a rejection and then rejecting it again. Instead, consider\nadding a comment next to the specific code path that should not reject and keep\nerror messages as expressive as possible.

      \n

      If specified, error can be a Class, RegExp or a validation\nfunction. See assert.throws() for more details.

      \n

      Besides the async nature to await the completion behaves identically to\nassert.doesNotThrow().

      \n\n
      (async () => {\n  await assert.doesNotReject(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    SyntaxError\n  );\n})();\n
      \n\n
      assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n  .then(() => {\n    // ...\n  });\n
      " + }, + { + "textRaw": "`assert.doesNotThrow(fn[, error][, message])`", + "type": "method", + "name": "doesNotThrow", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v5.11.0, v4.4.5", + "pr-url": "https://github.com/nodejs/node/pull/2407", + "description": "The `message` parameter is respected now." + }, + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3276", + "description": "The `error` parameter can now be an arrow function." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + }, + { + "textRaw": "`error` {RegExp|Function}", + "name": "error", + "type": "RegExp|Function" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Asserts that the function fn does not throw an error.

      \n

      Using assert.doesNotThrow() is actually not useful because there\nis no benefit in catching an error and then rethrowing it. Instead, consider\nadding a comment next to the specific code path that should not throw and keep\nerror messages as expressive as possible.

      \n

      When assert.doesNotThrow() is called, it will immediately call the fn\nfunction.

      \n

      If an error is thrown and it is the same type as that specified by the error\nparameter, then an AssertionError is thrown. If the error is of a\ndifferent type, or if the error parameter is undefined, the error is\npropagated back to the caller.

      \n

      If specified, error can be a Class, RegExp or a validation\nfunction. See assert.throws() for more details.

      \n

      The following, for instance, will throw the TypeError because there is no\nmatching error type in the assertion:

      \n\n
      assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  SyntaxError\n);\n
      \n

      However, the following will result in an AssertionError with the message\n'Got unwanted exception...':

      \n\n
      assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  TypeError\n);\n
      \n

      If an AssertionError is thrown and a value is provided for the message\nparameter, the value of message will be appended to the AssertionError\nmessage:

      \n\n
      assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  /Wrong value/,\n  'Whoops'\n);\n// Throws: AssertionError: Got unwanted exception: Whoops\n
      " + }, + { + "textRaw": "`assert.equal(actual, expected[, message])`", + "type": "method", + "name": "equal", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.strictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.strictEqual() instead.

      \n
      \n

      Tests shallow, coercive equality between the actual and expected parameters\nusing the Abstract Equality Comparison ( == ).

      \n
      const assert = require('assert');\n\nassert.equal(1, 1);\n// OK, 1 == 1\nassert.equal(1, '1');\n// OK, 1 == '1'\n\nassert.equal(1, 2);\n// AssertionError: 1 == 2\nassert.equal({ a: { b: 1 } }, { a: { b: 1 } });\n// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }\n
      \n

      If the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.fail([message])`", + "type": "method", + "name": "fail", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string|Error} **Default:** `'Failed'`", + "name": "message", + "type": "string|Error", + "default": "`'Failed'`" + } + ] + } + ], + "desc": "

      Throws an AssertionError with the provided error message or a default\nerror message. If the message parameter is an instance of an Error then\nit will be thrown instead of the AssertionError.

      \n
      const assert = require('assert').strict;\n\nassert.fail();\n// AssertionError [ERR_ASSERTION]: Failed\n\nassert.fail('boom');\n// AssertionError [ERR_ASSERTION]: boom\n\nassert.fail(new TypeError('need array'));\n// TypeError: need array\n
      \n

      Using assert.fail() with more than two arguments is possible but deprecated.\nSee below for further details.

      " + }, + { + "textRaw": "`assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`", + "type": "method", + "name": "fail", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18418", + "description": "Calling `assert.fail()` with more than one argument is deprecated and emits a warning." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `assert.fail([message])` or other assert\nfunctions instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + }, + { + "textRaw": "`operator` {string} **Default:** `'!='`", + "name": "operator", + "type": "string", + "default": "`'!='`" + }, + { + "textRaw": "`stackStartFn` {Function} **Default:** `assert.fail`", + "name": "stackStartFn", + "type": "Function", + "default": "`assert.fail`" + } + ] + } + ], + "desc": "

      If message is falsy, the error message is set as the values of actual and\nexpected separated by the provided operator. If just the two actual and\nexpected arguments are provided, operator will default to '!='. If\nmessage is provided as third argument it will be used as the error message and\nthe other arguments will be stored as properties on the thrown object. If\nstackStartFn is provided, all stack frames above that function will be\nremoved from stacktrace (see Error.captureStackTrace). If no arguments are\ngiven, the default message Failed will be used.

      \n
      const assert = require('assert').strict;\n\nassert.fail('a', 'b');\n// AssertionError [ERR_ASSERTION]: 'a' != 'b'\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError [ERR_ASSERTION]: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError [ERR_ASSERTION]: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError [ERR_ASSERTION]: whoops\n\nassert.fail(1, 2, new TypeError('need array'));\n// TypeError: need array\n
      \n

      In the last three cases actual, expected, and operator have no\ninfluence on the error message.

      \n

      Example use of stackStartFn for truncating the exception's stacktrace:

      \n
      function suppressFrame() {\n  assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError [ERR_ASSERTION]: 'a' !== 'b'\n//     at repl:1:1\n//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n//     ...\n
      " + }, + { + "textRaw": "`assert.ifError(value)`", + "type": "method", + "name": "ifError", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18247", + "description": "Instead of throwing the original error it is now wrapped into an [`AssertionError`][] that contains the full stack trace." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18247", + "description": "Value may now only be `undefined` or `null`. Before all falsy values were handled the same as `null` and did not throw." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Throws value if value is not undefined or null. This is useful when\ntesting the error argument in callbacks. The stack trace contains all frames\nfrom the error passed to ifError() including the potential new frames for\nifError() itself.

      \n
      const assert = require('assert').strict;\n\nassert.ifError(null);\n// OK\nassert.ifError(0);\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0\nassert.ifError('error');\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'\nassert.ifError(new Error());\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error\n\n// Create some random error frames.\nlet err;\n(function errorFrame() {\n  err = new Error('test error');\n})();\n\n(function ifErrorFrame() {\n  assert.ifError(err);\n})();\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error\n//     at ifErrorFrame\n//     at errorFrame\n
      " + }, + { + "textRaw": "`assert.match(string, regexp[, message])`", + "type": "method", + "name": "match", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`regexp` {RegExp}", + "name": "regexp", + "type": "RegExp" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Expects the string input to match the regular expression.

      \n

      This feature is currently experimental and the name might change or it might be\ncompletely removed again.

      \n
      const assert = require('assert').strict;\n\nassert.match('I will fail', /pass/);\n// AssertionError [ERR_ASSERTION]: The input did not match the regular ...\n\nassert.match(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.match('I will pass', /pass/);\n// OK\n
      \n

      If the values do not match, or if the string argument is of another type than\nstring, an AssertionError is thrown with a message property set equal\nto the value of the message parameter. If the message parameter is\nundefined, a default error message is assigned. If the message parameter is an\ninstance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.notDeepEqual(actual, expected[, message])`", + "type": "method", + "name": "notDeepEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.notDeepStrictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.notDeepStrictEqual() instead.

      \n
      \n

      Tests for any deep inequality. Opposite of assert.deepEqual().

      \n
      const assert = require('assert');\n\nconst obj1 = {\n  a: {\n    b: 1\n  }\n};\nconst obj2 = {\n  a: {\n    b: 2\n  }\n};\nconst obj3 = {\n  a: {\n    b: 1\n  }\n};\nconst obj4 = Object.create(obj1);\n\nassert.notDeepEqual(obj1, obj1);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj2);\n// OK\n\nassert.notDeepEqual(obj1, obj3);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj4);\n// OK\n
      \n

      If the values are deeply equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.notDeepStrictEqual(actual, expected[, message])`", + "type": "method", + "name": "notDeepStrictEqual", + "meta": { + "added": [ + "v1.2.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15398", + "description": "The `-0` and `+0` are not considered equal anymore." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15036", + "description": "The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15001", + "description": "The `Error` names and messages are now properly compared" + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12142", + "description": "The `Set` and `Map` content is also compared" + }, + { + "version": "v6.4.0, v4.7.1", + "pr-url": "https://github.com/nodejs/node/pull/8002", + "description": "Typed array slices are handled correctly now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6432", + "description": "Objects with circular references can be used as inputs now." + }, + { + "version": "v5.10.1, v4.4.3", + "pr-url": "https://github.com/nodejs/node/pull/5910", + "description": "Handle non-`Uint8Array` typed arrays correctly." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests for deep strict inequality. Opposite of assert.deepStrictEqual().

      \n
      const assert = require('assert').strict;\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n
      \n

      If the values are deeply and strictly equal, an AssertionError is thrown\nwith a message property set equal to the value of the message parameter. If\nthe message parameter is undefined, a default error message is assigned. If\nthe message parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.notEqual(actual, expected[, message])`", + "type": "method", + "name": "notEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Strict assertion mode

      \n

      An alias of assert.notStrictEqual().

      \n

      Legacy assertion mode

      \n
      \n

      Stability: 0 - Deprecated: Use assert.notStrictEqual() instead.

      \n
      \n

      Tests shallow, coercive inequality with the Abstract Equality Comparison\n( != ).

      \n
      const assert = require('assert');\n\nassert.notEqual(1, 2);\n// OK\n\nassert.notEqual(1, 1);\n// AssertionError: 1 != 1\n\nassert.notEqual(1, '1');\n// AssertionError: 1 != '1'\n
      \n

      If the values are equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

      " + }, + { + "textRaw": "`assert.notStrictEqual(actual, expected[, message])`", + "type": "method", + "name": "notStrictEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17003", + "description": "Used comparison changed from Strict Equality to `Object.is()`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests strict inequality between the actual and expected parameters as\ndetermined by the SameValue Comparison.

      \n
      const assert = require('assert').strict;\n\nassert.notStrictEqual(1, 2);\n// OK\n\nassert.notStrictEqual(1, 1);\n// AssertionError [ERR_ASSERTION]: Expected \"actual\" to be strictly unequal to:\n//\n// 1\n\nassert.notStrictEqual(1, '1');\n// OK\n
      \n

      If the values are strictly equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.ok(value[, message])`", + "type": "method", + "name": "ok", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18319", + "description": "The `assert.ok()` (no arguments) will now use a predefined error message." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests if value is truthy. It is equivalent to\nassert.equal(!!value, true, message).

      \n

      If value is not truthy, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.\nIf no arguments are passed in at all message will be set to the string:\n'No value argument passed to `assert.ok()`'.

      \n

      Be aware that in the repl the error message will be different to the one\nthrown in a file! See below for further details.

      \n
      const assert = require('assert').strict;\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\n\nassert.ok();\n// AssertionError: No value argument passed to `assert.ok()`\n\nassert.ok(false, 'it\\'s false');\n// AssertionError: it's false\n\n// In the repl:\nassert.ok(typeof 123 === 'string');\n// AssertionError: false == true\n\n// In a file (e.g. test.js):\nassert.ok(typeof 123 === 'string');\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert.ok(typeof 123 === 'string')\n\nassert.ok(false);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert.ok(false)\n\nassert.ok(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert.ok(0)\n\n// Using `assert()` works the same:\nassert(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert(0)\n
      " + }, + { + "textRaw": "`assert.rejects(asyncFn[, error][, message])`", + "type": "method", + "name": "rejects", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncFn` {Function|Promise}", + "name": "asyncFn", + "type": "Function|Promise" + }, + { + "textRaw": "`error` {RegExp|Function|Object|Error}", + "name": "error", + "type": "RegExp|Function|Object|Error" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Awaits the asyncFn promise or, if asyncFn is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is rejected.

      \n

      If asyncFn is a function and it throws an error synchronously,\nassert.rejects() will return a rejected Promise with that error. If the\nfunction does not return a promise, assert.rejects() will return a rejected\nPromise with an ERR_INVALID_RETURN_VALUE error. In both cases the error\nhandler is skipped.

      \n

      Besides the async nature to await the completion behaves identically to\nassert.throws().

      \n

      If specified, error can be a Class, RegExp, a validation function,\nan object where each property will be tested for, or an instance of error where\neach property will be tested for including the non-enumerable message and\nname properties.

      \n

      If specified, message will be the message provided by the AssertionError\nif the asyncFn fails to reject.

      \n
      (async () => {\n  await assert.rejects(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    {\n      name: 'TypeError',\n      message: 'Wrong value'\n    }\n  );\n})();\n
      \n
      (async () => {\n  await assert.rejects(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    (err) => {\n      assert.strictEqual(err.name, 'TypeError');\n      assert.strictEqual(err.message, 'Wrong value');\n      return true;\n    }\n  );\n})();\n
      \n
      assert.rejects(\n  Promise.reject(new Error('Wrong value')),\n  Error\n).then(() => {\n  // ...\n});\n
      \n

      error cannot be a string. If a string is provided as the second\nargument, then error is assumed to be omitted and the string will be used for\nmessage instead. This can lead to easy-to-miss mistakes. Please read the\nexample in assert.throws() carefully if using a string as the second\nargument gets considered.

      " + }, + { + "textRaw": "`assert.strictEqual(actual, expected[, message])`", + "type": "method", + "name": "strictEqual", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17003", + "description": "Used comparison changed from Strict Equality to `Object.is()`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`actual` {any}", + "name": "actual", + "type": "any" + }, + { + "textRaw": "`expected` {any}", + "name": "expected", + "type": "any" + }, + { + "textRaw": "`message` {string|Error}", + "name": "message", + "type": "string|Error" + } + ] + } + ], + "desc": "

      Tests strict equality between the actual and expected parameters as\ndetermined by the SameValue Comparison.

      \n
      const assert = require('assert').strict;\n\nassert.strictEqual(1, 2);\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n//\n// 1 !== 2\n\nassert.strictEqual(1, 1);\n// OK\n\nassert.strictEqual('Hello foobar', 'Hello World!');\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n// + actual - expected\n//\n// + 'Hello foobar'\n// - 'Hello World!'\n//          ^\n\nconst apples = 1;\nconst oranges = 2;\nassert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);\n// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2\n\nassert.strictEqual(1, '1', new TypeError('Inputs are not identical'));\n// TypeError: Inputs are not identical\n
      \n

      If the values are not strictly equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of an Error then it will be thrown\ninstead of the AssertionError.

      " + }, + { + "textRaw": "`assert.throws(fn[, error][, message])`", + "type": "method", + "name": "throws", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20485", + "description": "The `error` parameter can be an object containing regular expressions now." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17584", + "description": "The `error` parameter can now be an object as well." + }, + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3276", + "description": "The `error` parameter can now be an arrow function." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + }, + { + "textRaw": "`error` {RegExp|Function|Object|Error}", + "name": "error", + "type": "RegExp|Function|Object|Error" + }, + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      Expects the function fn to throw an error.

      \n

      If specified, error can be a Class, RegExp, a validation function,\na validation object where each property will be tested for strict deep equality,\nor an instance of error where each property will be tested for strict deep\nequality including the non-enumerable message and name properties. When\nusing an object, it is also possible to use a regular expression, when\nvalidating against a string property. See below for examples.

      \n

      If specified, message will be appended to the message provided by the\nAssertionError if the fn call fails to throw or in case the error validation\nfails.

      \n

      Custom validation object/error instance:

      \n
      const err = new TypeError('Wrong value');\nerr.code = 404;\nerr.foo = 'bar';\nerr.info = {\n  nested: true,\n  baz: 'text'\n};\nerr.reg = /abc/i;\n\nassert.throws(\n  () => {\n    throw err;\n  },\n  {\n    name: 'TypeError',\n    message: 'Wrong value',\n    info: {\n      nested: true,\n      baz: 'text'\n    }\n    // Only properties on the validation object will be tested for.\n    // Using nested objects requires all properties to be present. Otherwise\n    // the validation is going to fail.\n  }\n);\n\n// Using regular expressions to validate error properties:\nassert.throws(\n  () => {\n    throw err;\n  },\n  {\n    // The `name` and `message` properties are strings and using regular\n    // expressions on those will match against the string. If they fail, an\n    // error is thrown.\n    name: /^TypeError$/,\n    message: /Wrong/,\n    foo: 'bar',\n    info: {\n      nested: true,\n      // It is not possible to use regular expressions for nested properties!\n      baz: 'text'\n    },\n    // The `reg` property contains a regular expression and only if the\n    // validation object contains an identical regular expression, it is going\n    // to pass.\n    reg: /abc/i\n  }\n);\n\n// Fails due to the different `message` and `name` properties:\nassert.throws(\n  () => {\n    const otherErr = new Error('Not found');\n    // Copy all enumerable properties from `err` to `otherErr`.\n    for (const [key, value] of Object.entries(err)) {\n      otherErr[key] = value;\n    }\n    throw otherErr;\n  },\n  // The error's `message` and `name` properties will also be checked when using\n  // an error as validation object.\n  err\n);\n
      \n

      Validate instanceof using constructor:

      \n
      assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  Error\n);\n
      \n

      Validate error message using RegExp:

      \n

      Using a regular expression runs .toString on the error object, and will\ntherefore also include the error name.

      \n
      assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  /^Error: Wrong value$/\n);\n
      \n

      Custom error validation:

      \n

      The function must return true to indicate all internal validations passed.\nIt will otherwise fail with an AssertionError.

      \n
      assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  (err) => {\n    assert(err instanceof Error);\n    assert(/value/.test(err));\n    // Avoid returning anything from validation functions besides `true`.\n    // Otherwise, it's not clear what part of the validation failed. Instead,\n    // throw an error about the specific validation that failed (as done in this\n    // example) and add as much helpful debugging information to that error as\n    // possible.\n    return true;\n  },\n  'unexpected error'\n);\n
      \n

      error cannot be a string. If a string is provided as the second\nargument, then error is assumed to be omitted and the string will be used for\nmessage instead. This can lead to easy-to-miss mistakes. Using the same\nmessage as the thrown error message is going to result in an\nERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using\na string as the second argument gets considered:

      \n\n
      function throwingFirst() {\n  throw new Error('First');\n}\n\nfunction throwingSecond() {\n  throw new Error('Second');\n}\n\nfunction notThrowing() {}\n\n// The second argument is a string and the input function threw an Error.\n// The first case will not throw as it does not match for the error message\n// thrown by the input function!\nassert.throws(throwingFirst, 'Second');\n// In the next example the message has no benefit over the message from the\n// error and since it is not clear if the user intended to actually match\n// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.\nassert.throws(throwingSecond, 'Second');\n// TypeError [ERR_AMBIGUOUS_ARGUMENT]\n\n// The string is only used (as message) in case the function does not throw:\nassert.throws(notThrowing, 'Second');\n// AssertionError [ERR_ASSERTION]: Missing expected exception: Second\n\n// If it was intended to match for the error message do this instead:\n// It does not throw because the error messages match.\nassert.throws(throwingSecond, /Second$/);\n\n// If the error message does not match, an AssertionError is thrown.\nassert.throws(throwingFirst, /Second$/);\n// AssertionError [ERR_ASSERTION]\n
      \n

      Due to the confusing error-prone notation, avoid a string as the second\nargument.

      " + } + ], + "type": "module", + "displayName": "Assert" + } + ] +} \ No newline at end of file diff --git a/doc/api/assets/hljs.css b/doc/api/assets/hljs.css new file mode 100644 index 0000000000000000000000000000000000000000..026a93e194efc376c969b7a7bd987d95615bc714 --- /dev/null +++ b/doc/api/assets/hljs.css @@ -0,0 +1,30 @@ +.hljs { + font-weight: normal; + font-style: normal; +} + +.hljs-symbol { + color: #333; +} + +.hljs-attribute, +.hljs-keyword { + color: #338; +} + +.hljs-string, +.hljs-regexp, +.hljs-number { + color: #cf350d; +} + +.hljs-doctag { + color: #040404; +} + +.hljs-doctag .hljs-type, +.hljs-doctag .hljs-variable, +.hljs-comment { + color: #666; + font-weight: lighter; +} diff --git a/doc/api/assets/style.css b/doc/api/assets/style.css new file mode 100644 index 0000000000000000000000000000000000000000..af170888be8f38e0a80e5abc9733c538eda89095 --- /dev/null +++ b/doc/api/assets/style.css @@ -0,0 +1,704 @@ +/*--------------------- Layout and Typography ----------------------------*/ +html { + font-size: 1rem; + overflow-wrap: break-word; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; +} + +* { + box-sizing: border-box; +} + +body { + font-family: Lato, "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Verdana, Tahoma, sans-serif; + margin: 0; + padding: 0; + color: #333; + background-color: #fff; +} + +h1, h1 code { font-size: 2.5rem; } +h2, h2 code { font-size: 2rem; } +h3, h3 code { font-size: 1.75rem; } +h4, h4 code { font-size: 1.5rem; } +h5, h5 code { font-size: 1.25rem; } +h6, h6 code { font-size: 1rem; } + +h1, +h2, +h3, +h4, +h5, +h6 { + font-weight: 700; + line-height: inherit; + position: relative; + margin: 1.5rem 0 1rem; + text-rendering: optimizeLegibility; +} + +h1 code, +h2 code, +h3 code, +h4 code, +h5 code, +h6 code { + color: inherit; + font-family: inherit; +} + +pre, +tt, +code, +.pre, +span.type, +a.type { + font-family: SFMono-Regular, Menlo, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: .9em; +} + +#content { + position: relative; +} + +a:link, +a:active, +a:visited { + color: #43853d; + text-decoration: none; + border-radius: 2px; + padding: 1px 3px; +} + +a:hover, +a:focus { + color: #fff; + background-color: #43853d; + outline: none; +} + +strong { + font-weight: 700; +} + +code a:hover { + background-color: transparent; +} + +em code { + font-style: normal; +} + +#changelog #gtoc { + display: none; +} + +#gtoc { + margin-top: .5rem; + margin-bottom: 1rem; +} + +#gtoc ul { + list-style: none; + margin-left: 0; + line-height: 1.5rem; +} + +#gtoc > ul > li { + display: inline; + border-right: 1px #000 solid; + margin-right: .4rem; + padding-right: .4rem; +} + +#gtoc > ul > li:last-child { + border-right: none; + margin-right: 0; + padding-right: 0; +} + +li.version-picker { + position: relative; +} + +li.version-picker:hover > a { + border-radius: 2px 2px 0 0; +} + +li.version-picker:hover > ol { + display: block; + z-index: 1; +} + +li.version-picker a span { + font-size: .7rem; +} + +ol.version-picker { + background-color: #fff; + border: 1px solid #43853d; + border-radius: 0 0 2px 2px; + display: none; + list-style: none; + position: absolute; + right: 0; + top: 100%; + width: 100%; +} + +#gtoc ol.version-picker li { + display: block; + border-right: 0; + margin-right: 0; +} + +ol.version-picker li a { + border-radius: 0; + display: block; + margin: 0; + padding: .1rem; + padding-left: 1rem; +} + +ol.version-picker li:last-child a { + border-bottom-right-radius: 1px; + border-bottom-left-radius: 1px; +} + +.line { + width: calc(100% - 1rem); + display: block; + padding-bottom: 1px; +} + +.api_stability { + color: #fff !important; + margin: 0 0 1rem; + padding: 1rem; + line-height: 1.5; +} + +.api_stability * { + color: #fff !important; +} + +.api_stability a { + text-decoration: underline; +} + +.api_stability a:hover, +.api_stability a:active, +.api_stability a:focus { + background-color: rgba(255, 255, 255, .4); +} + +.api_stability a code { + background-color: transparent; +} + +.api_stability_0 { + background-color: #d60027; +} + +.api_stability_1 { + background-color: #ca5010; +} + +.api_stability_2 { + background-color: #5a8147; +} + +.api_metadata { + font-size: .85rem; + margin-bottom: 1rem; +} + +.api_metadata span { + margin-right: 1rem; +} + +.api_metadata span:last-child { + margin-right: 0; +} + +ul.plain { + list-style: none; +} + +abbr { + border-bottom: 1px dotted #454545; +} + +p { + text-rendering: optimizeLegibility; + margin: 0 0 1.125rem; + line-height: 1.5; +} + +#apicontent > *:last-child { + margin-bottom: 0; + padding-bottom: 2rem; +} + +table { + border-collapse: collapse; + margin: 0 0 1.5rem; +} + +th, +td { + border: 1px solid #aaa; + padding: .5rem; + vertical-align: top; +} + +th { + text-align: left; +} + +td { + word-break: break-all; /* Fallback if break-word isn't supported */ + word-break: break-word; +} + +@media only screen and (min-width: 600px) { + th, + td { + padding: .75rem 1rem; + } + + td:first-child { + word-break: normal; + } +} + +ol, +ul, +dl { + margin: 0 0 .6rem; + padding: 0; +} + +ol ul, +ol ol, +ol dl, +ul ul, +ul ol, +ul dl, +dl ul, +dl ol, +dl dl { + margin-bottom: 0; +} + +ul, +ol { + margin-left: 2rem; +} + +dl dt { + position: relative; + margin: 1.5rem 0 0; +} + +dl dd { + position: relative; + margin: 0 1rem; +} + +dd + dt.pre { + margin-top: 1.6rem; +} + +#apicontent { + padding-top: 1rem; +} + +#apicontent .line { + width: calc(50% - 1rem); + margin: 1rem 1rem .95rem; + background-color: #ccc; +} + +h2 + h2 { + margin: 0 0 .5rem; +} + +h3 + h3 { + margin: 0 0 .5rem; +} + +h2, +h3, +h4, +h5 { + position: relative; + padding-right: 40px; +} + +.srclink { + float: right; + font-size: smaller; + margin-right: 30px; +} + +h1 span, +h2 span, +h3 span, +h4 span { + position: absolute; + display: block; + top: 0; + right: 0; +} + +h1 span:hover, +h2 span:hover, +h3 span:hover, +h4 span:hover { + opacity: 1; +} + +h1 span a, +h2 span a, +h3 span a, +h4 span a { + color: #000; + text-decoration: none; + font-weight: 700; +} + +pre, +tt, +code { + line-height: 1.5rem; + margin: 0; + padding: 0; +} + +.pre { + line-height: 1.5rem; +} + +pre { + padding: 1rem; + vertical-align: top; + background-color: #f2f2f2; + margin: 1rem; + overflow-x: auto; +} + +pre > code { + padding: 0; +} + +pre + h3 { + margin-top: 2.225rem; +} + +code.pre { + white-space: pre; +} + +#intro { + margin-top: 1.25rem; + margin-left: 1rem; +} + +#intro a { + color: #ddd; + font-weight: 700; +} + +hr { + background-color: transparent; + border: medium none; + border-bottom: 1px solid #7a7a7a; + margin: 0 0 1rem; +} + +#toc h2 { + margin: 1.5rem 0; +} + +#toc p { + margin: 0; +} + +#toc ul a { + text-decoration: none; +} + +#toc ul li { + margin-bottom: .666rem; + list-style: square outside; +} + +#toc li > ul { + margin-top: .666rem; +} + +#toc .stability_0::after { + background-color: #d50027; + color: #fff; + content: "deprecated"; + margin-left: .25rem; + padding: 1px 3px; + border-radius: 3px; +} + +#apicontent li { + margin-bottom: .5rem; +} + +#apicontent li:last-child { + margin-bottom: 0; +} + +tt, +code { + color: #040404; + background-color: #f2f2f2; + border-radius: 2px; + padding: 1px 3px; +} + +.api_stability code { + background-color: rgba(0, 0, 0, .1); +} + +a code { + color: inherit; + background-color: inherit; + padding: 0; +} + +.type { + line-height: 1.5rem; +} + +#column1.interior { + margin-left: 234px; + padding: 0 2rem; + -webkit-padding-start: 1.5rem; +} + +#column2.interior { + width: 234px; + background-color: #333; + position: fixed; + left: 0; + top: 0; + bottom: 0; + overflow-x: hidden; + overflow-y: scroll; +} + +#column2 ul { + list-style: none; + margin: .9rem 0 .5rem; + background-color: #333; +} + +#column2 > :first-child { + margin: 1.25rem; + font-size: 1.5rem; +} + +#column2 > ul:nth-child(2) { + margin: 1.25rem 0 .5rem; +} + +#column2 > ul:last-child { + margin: .9rem 0 1.25rem; +} + +#column2 ul li { + padding-left: 1.25rem; + margin-bottom: .5rem; + padding-bottom: .5rem; +} + +#column2 .line { + margin: 0 .5rem; + border-color: #707070; +} + +#column2 ul li:last-child { + margin-bottom: 0; +} + +#column2 ul li a { + color: #ccc; + border-radius: 0; +} + +#column2 ul li a.active, +#column2 ul li a.active:hover, +#column2 ul li a.active:focus { + font-weight: 700; + color: #fff; + background-color: transparent; +} + +#intro a:hover, +#intro a:focus, +#column2 ul li a:hover, +#column2 ul li a:focus { + color: #fff; + background-color: transparent; +} + +span > .mark, +span > .mark:visited { + color: #707070; + position: absolute; + top: 0; + right: 0; +} + +span > .mark:hover, +span > .mark:focus, +span > .mark:active { + color: #43853d; + background-color: transparent; +} + +th > *:last-child, +td > *:last-child { + margin-bottom: 0; +} + +.changelog > summary { + margin: .5rem 0; + padding: .5rem 0; + cursor: pointer; +} + +/* simpler clearfix */ +.clearfix::after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} + +.github_icon { + vertical-align: middle; + margin: -2px 3px 0 0; +} + +/* API reference sidebar */ +@media only screen and (min-width: 1025px) { + .apidoc #column2 > .line { + pointer-events: none; + } + .apidoc #column2 > :first-child, + .apidoc #column2 > ul, + .apidoc #column2 > ul > li { + margin: 0; + padding: 0; + } + .apidoc #column2 > :first-child > a[href] { + border-radius: 0; + padding: 1.25rem 1.4375rem .625rem; + display: block; + } + .apidoc #column2 > ul > li > a[href] { + padding: .5rem 1.4375rem; + display: block; + } + .apidoc #column2 > ul > :first-child > a[href] { + padding-top: .625rem; + } + .apidoc #column2 > ul > :last-child > a[href] { + padding-bottom: .625rem; + } + .apidoc #column2 > ul:first-of-type > :last-child > a[href] { + padding-bottom: 1rem; + } + .apidoc #column2 > ul:nth-of-type(2) > :first-child > a[href] { + padding-top: .875rem; + } + .apidoc #column2 > ul:nth-of-type(2) > :last-child > a[href] { + padding-bottom: .9375rem; + } + .apidoc #column2 > ul:last-of-type > :first-child > a[href] { + padding-top: 1rem; + } + .apidoc #column2 > ul:last-of-type > :last-child > a[href] { + padding-bottom: 1.75rem; + } +} + +@media only screen and (max-width: 1024px) { + #content { + overflow: visible; + } + #column1.interior { + margin-left: 0; + padding-left: .5rem; + padding-right: .5rem; + width: auto; + overflow-y: visible; + } + #column2 { + display: none; + } +} + +@media print { + html { + height: auto; + font-size: .75em; + } + #column2.interior { + display: none; + } + #column1.interior { + margin-left: 0; + padding: 0; + overflow-y: auto; + } + .api_metadata, + #toc, + .srclink, + #gtoc, + .mark { + display: none; + } + h1 { + font-size: 2rem; + } + h2 { + font-size: 1.75rem; + } + h3 { + font-size: 1.5rem; + } + h4 { + font-size: 1.3rem; + } + h5 { + font-size: 1.2rem; + } + h6 { + font-size: 1.1rem; + } + .api_stability { + display: inline-block; + } + .api_stability a { + text-decoration: none; + } + a { + color: inherit; + } + #apicontent { + overflow: hidden; + } +} diff --git a/doc/api/async_hooks.html b/doc/api/async_hooks.html new file mode 100644 index 0000000000000000000000000000000000000000..4ca7d55db5515229b6ea2bbb59739373aa2992ce --- /dev/null +++ b/doc/api/async_hooks.html @@ -0,0 +1,1154 @@ + + + + + + + Async hooks | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Async hooks#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/async_hooks.js

      +

      The async_hooks module provides an API to track asynchronous resources. It +can be accessed using:

      +
      const async_hooks = require('async_hooks');
      +

      Terminology#

      +

      An asynchronous resource represents an object with an associated callback. +This callback may be called multiple times, for example, the 'connection' +event in net.createServer(), or just a single time like in fs.open(). +A resource can also be closed before the callback is called. AsyncHook does +not explicitly distinguish between these different cases but will represent them +as the abstract concept that is a resource.

      +

      If Workers are used, each thread has an independent async_hooks +interface, and each thread will use a new set of async IDs.

      +

      Public API#

      +

      Overview#

      +

      Following is a simple overview of the public API.

      +
      const async_hooks = require('async_hooks');
      +
      +// Return the ID of the current execution context.
      +const eid = async_hooks.executionAsyncId();
      +
      +// Return the ID of the handle responsible for triggering the callback of the
      +// current execution scope to call.
      +const tid = async_hooks.triggerAsyncId();
      +
      +// Create a new AsyncHook instance. All of these callbacks are optional.
      +const asyncHook =
      +    async_hooks.createHook({ init, before, after, destroy, promiseResolve });
      +
      +// Allow callbacks of this AsyncHook instance to call. This is not an implicit
      +// action after running the constructor, and must be explicitly run to begin
      +// executing callbacks.
      +asyncHook.enable();
      +
      +// Disable listening for new asynchronous events.
      +asyncHook.disable();
      +
      +//
      +// The following are the callbacks that can be passed to createHook().
      +//
      +
      +// init is called during object construction. The resource may not have
      +// completed construction when this callback runs, therefore all fields of the
      +// resource referenced by "asyncId" may not have been populated.
      +function init(asyncId, type, triggerAsyncId, resource) { }
      +
      +// Before is called just before the resource's callback is called. It can be
      +// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
      +// time for requests (e.g. FSReqCallback).
      +function before(asyncId) { }
      +
      +// After is called just after the resource's callback has finished.
      +function after(asyncId) { }
      +
      +// Destroy is called when the resource is destroyed.
      +function destroy(asyncId) { }
      +
      +// promiseResolve is called only for promise resources, when the
      +// `resolve` function passed to the `Promise` constructor is invoked
      +// (either directly or through other means of resolving a promise).
      +function promiseResolve(asyncId) { }
      +

      async_hooks.createHook(callbacks)#

      + + +

      Registers functions to be called for different lifetime events of each async +operation.

      +

      The callbacks init()/before()/after()/destroy() are called for the +respective asynchronous event during a resource's lifetime.

      +

      All callbacks are optional. For example, if only resource cleanup needs to +be tracked, then only the destroy callback needs to be passed. The +specifics of all functions that can be passed to callbacks is in the +Hook Callbacks section.

      +
      const async_hooks = require('async_hooks');
      +
      +const asyncHook = async_hooks.createHook({
      +  init(asyncId, type, triggerAsyncId, resource) { },
      +  destroy(asyncId) { }
      +});
      +

      The callbacks will be inherited via the prototype chain:

      +
      class MyAsyncCallbacks {
      +  init(asyncId, type, triggerAsyncId, resource) { }
      +  destroy(asyncId) {}
      +}
      +
      +class MyAddedCallbacks extends MyAsyncCallbacks {
      +  before(asyncId) { }
      +  after(asyncId) { }
      +}
      +
      +const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
      +
      Error handling#
      +

      If any AsyncHook callbacks throw, the application will print the stack trace +and exit. The exit path does follow that of an uncaught exception, but +all 'uncaughtException' listeners are removed, thus forcing the process to +exit. The 'exit' callbacks will still be called unless the application is run +with --abort-on-uncaught-exception, in which case a stack trace will be +printed and the application exits, leaving a core file.

      +

      The reason for this error handling behavior is that these callbacks are running +at potentially volatile points in an object's lifetime, for example during +class construction and destruction. Because of this, it is deemed necessary to +bring down the process quickly in order to prevent an unintentional abort in the +future. This is subject to change in the future if a comprehensive analysis is +performed to ensure an exception can follow the normal control flow without +unintentional side effects.

      +
      Printing in AsyncHooks callbacks#
      +

      Because printing to the console is an asynchronous operation, console.log() +will cause the AsyncHooks callbacks to be called. Using console.log() or +similar asynchronous operations inside an AsyncHooks callback function will thus +cause an infinite recursion. An easy solution to this when debugging is to use a +synchronous logging operation such as fs.writeFileSync(file, msg, flag). +This will print to the file and will not invoke AsyncHooks recursively because +it is synchronous.

      +
      const fs = require('fs');
      +const util = require('util');
      +
      +function debug(...args) {
      +  // Use a function like this one when debugging inside an AsyncHooks callback
      +  fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
      +}
      +

      If an asynchronous operation is needed for logging, it is possible to keep +track of what caused the asynchronous operation using the information +provided by AsyncHooks itself. The logging should then be skipped when +it was the logging itself that caused AsyncHooks callback to call. By +doing this the otherwise infinite recursion is broken.

      +

      Class: AsyncHook#

      +

      The class AsyncHook exposes an interface for tracking lifetime events +of asynchronous operations.

      +

      asyncHook.enable()#

      + +

      Enable the callbacks for a given AsyncHook instance. If no callbacks are +provided enabling is a noop.

      +

      The AsyncHook instance is disabled by default. If the AsyncHook instance +should be enabled immediately after creation, the following pattern can be used.

      +
      const async_hooks = require('async_hooks');
      +
      +const hook = async_hooks.createHook(callbacks).enable();
      +

      asyncHook.disable()#

      + +

      Disable the callbacks for a given AsyncHook instance from the global pool of +AsyncHook callbacks to be executed. Once a hook has been disabled it will not +be called again until enabled.

      +

      For API consistency disable() also returns the AsyncHook instance.

      +

      Hook callbacks#

      +

      Key events in the lifetime of asynchronous events have been categorized into +four areas: instantiation, before/after the callback is called, and when the +instance is destroyed.

      +
      init(asyncId, type, triggerAsyncId, resource)#
      +
        +
      • asyncId <number> A unique ID for the async resource.
      • +
      • type <string> The type of the async resource.
      • +
      • triggerAsyncId <number> The unique ID of the async resource in whose +execution context this async resource was created.
      • +
      • resource <Object> Reference to the resource representing the async +operation, needs to be released during destroy.
      • +
      +

      Called when a class is constructed that has the possibility to emit an +asynchronous event. This does not mean the instance must call +before/after before destroy is called, only that the possibility +exists.

      +

      This behavior can be observed by doing something like opening a resource then +closing it before the resource can be used. The following snippet demonstrates +this.

      +
      require('net').createServer().listen(function() { this.close(); });
      +// OR
      +clearTimeout(setTimeout(() => {}, 10));
      +

      Every new resource is assigned an ID that is unique within the scope of the +current Node.js instance.

      +
      type#
      +

      The type is a string identifying the type of resource that caused +init to be called. Generally, it will correspond to the name of the +resource's constructor.

      +
      FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
      +HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
      +SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
      +TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
      +RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
      +

      There is also the PROMISE resource type, which is used to track Promise +instances and asynchronous work scheduled by them.

      +

      Users are able to define their own type when using the public embedder API.

      +

      It is possible to have type name collisions. Embedders are encouraged to use +unique prefixes, such as the npm package name, to prevent collisions when +listening to the hooks.

      +
      triggerAsyncId#
      +

      triggerAsyncId is the asyncId of the resource that caused (or "triggered") +the new resource to initialize and that caused init to call. This is different +from async_hooks.executionAsyncId() that only shows when a resource was +created, while triggerAsyncId shows why a resource was created.

      +

      The following is a simple demonstration of triggerAsyncId:

      +
      async_hooks.createHook({
      +  init(asyncId, type, triggerAsyncId) {
      +    const eid = async_hooks.executionAsyncId();
      +    fs.writeSync(
      +      process.stdout.fd,
      +      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
      +  }
      +}).enable();
      +
      +require('net').createServer((conn) => {}).listen(8080);
      +

      Output when hitting the server with nc localhost 8080:

      +
      TCPSERVERWRAP(5): trigger: 1 execution: 1
      +TCPWRAP(7): trigger: 5 execution: 0
      +

      The TCPSERVERWRAP is the server which receives the connections.

      +

      The TCPWRAP is the new connection from the client. When a new +connection is made, the TCPWrap instance is immediately constructed. This +happens outside of any JavaScript stack. (An executionAsyncId() of 0 means +that it is being executed from C++ with no JavaScript stack above it.) With only +that information, it would be impossible to link resources together in +terms of what caused them to be created, so triggerAsyncId is given the task +of propagating what resource is responsible for the new resource's existence.

      +
      resource#
      +

      resource is an object that represents the actual async resource that has +been initialized. This can contain useful information that can vary based on +the value of type. For instance, for the GETADDRINFOREQWRAP resource type, +resource provides the host name used when looking up the IP address for the +host in net.Server.listen(). The API for accessing this information is +not supported, but using the Embedder API, users can provide +and document their own resource objects. For example, such a resource object +could contain the SQL query being executed.

      +

      In the case of Promises, the resource object will have an +isChainedPromise property, set to true if the promise has a parent promise, +and false otherwise. For example, in the case of b = a.then(handler), a is +considered a parent Promise of b. Here, b is considered a chained promise.

      +

      In some cases the resource object is reused for performance reasons, it is +thus not safe to use it as a key in a WeakMap or add properties to it.

      +
      Asynchronous context example#
      +

      The following is an example with additional information about the calls to +init between the before and after calls, specifically what the +callback to listen() will look like. The output formatting is slightly more +elaborate to make calling context easier to see.

      +
      let indent = 0;
      +async_hooks.createHook({
      +  init(asyncId, type, triggerAsyncId) {
      +    const eid = async_hooks.executionAsyncId();
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(
      +      process.stdout.fd,
      +      `${indentStr}${type}(${asyncId}):` +
      +      ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
      +  },
      +  before(asyncId) {
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(process.stdout.fd, `${indentStr}before:  ${asyncId}\n`);
      +    indent += 2;
      +  },
      +  after(asyncId) {
      +    indent -= 2;
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(process.stdout.fd, `${indentStr}after:  ${asyncId}\n`);
      +  },
      +  destroy(asyncId) {
      +    const indentStr = ' '.repeat(indent);
      +    fs.writeSync(process.stdout.fd, `${indentStr}destroy:  ${asyncId}\n`);
      +  },
      +}).enable();
      +
      +require('net').createServer(() => {}).listen(8080, () => {
      +  // Let's wait 10ms before logging the server started.
      +  setTimeout(() => {
      +    console.log('>>>', async_hooks.executionAsyncId());
      +  }, 10);
      +});
      +

      Output from only starting the server:

      +
      TCPSERVERWRAP(5): trigger: 1 execution: 1
      +TickObject(6): trigger: 5 execution: 1
      +before:  6
      +  Timeout(7): trigger: 6 execution: 6
      +after:   6
      +destroy: 6
      +before:  7
      +>>> 7
      +  TickObject(8): trigger: 7 execution: 7
      +after:   7
      +before:  8
      +after:   8
      +

      As illustrated in the example, executionAsyncId() and execution each specify +the value of the current execution context; which is delineated by calls to +before and after.

      +

      Only using execution to graph resource allocation results in the following:

      +
        root(1)
      +     ^
      +     |
      +TickObject(6)
      +     ^
      +     |
      + Timeout(7)
      +

      The TCPSERVERWRAP is not part of this graph, even though it was the reason for +console.log() being called. This is because binding to a port without a host +name is a synchronous operation, but to maintain a completely asynchronous +API the user's callback is placed in a process.nextTick(). Which is why +TickObject is present in the output and is a 'parent' for .listen() +callback.

      +

      The graph only shows when a resource was created, not why, so to track +the why use triggerAsyncId. Which can be represented with the following +graph:

      +
       bootstrap(1)
      +     |
      +     Ë…
      +TCPSERVERWRAP(5)
      +     |
      +     Ë…
      + TickObject(6)
      +     |
      +     Ë…
      +  Timeout(7)
      +
      before(asyncId)#
      + +

      When an asynchronous operation is initiated (such as a TCP server receiving a +new connection) or completes (such as writing data to disk) a callback is +called to notify the user. The before callback is called just before said +callback is executed. asyncId is the unique identifier assigned to the +resource about to execute the callback.

      +

      The before callback will be called 0 to N times. The before callback +will typically be called 0 times if the asynchronous operation was cancelled +or, for example, if no connections are received by a TCP server. Persistent +asynchronous resources like a TCP server will typically call the before +callback multiple times, while other operations like fs.open() will call +it only once.

      +
      after(asyncId)#
      + +

      Called immediately after the callback specified in before is completed.

      +

      If an uncaught exception occurs during execution of the callback, then after +will run after the 'uncaughtException' event is emitted or a domain's +handler runs.

      +
      destroy(asyncId)#
      + +

      Called after the resource corresponding to asyncId is destroyed. It is also +called asynchronously from the embedder API emitDestroy().

      +

      Some resources depend on garbage collection for cleanup, so if a reference is +made to the resource object passed to init it is possible that destroy +will never be called, causing a memory leak in the application. If the resource +does not depend on garbage collection, then this will not be an issue.

      +
      promiseResolve(asyncId)#
      + + +

      Called when the resolve function passed to the Promise constructor is +invoked (either directly or through other means of resolving a promise).

      +

      resolve() does not do any observable synchronous work.

      +

      The Promise is not necessarily fulfilled or rejected at this point if the +Promise was resolved by assuming the state of another Promise.

      +
      new Promise((resolve) => resolve(true)).then((a) => {});
      +

      calls the following callbacks:

      +
      init for PROMISE with id 5, trigger id: 1
      +  promise resolve 5      # corresponds to resolve(true)
      +init for PROMISE with id 6, trigger id: 5  # the Promise returned by then()
      +  before 6               # the then() callback is entered
      +  promise resolve 6      # the then() callback resolves the promise by returning
      +  after 6
      +

      async_hooks.executionAsyncResource()#

      + +
        +
      • Returns: <Object> The resource representing the current execution. +Useful to store data within the resource.
      • +
      +

      Resource objects returned by executionAsyncResource() are most often internal +Node.js handle objects with undocumented APIs. Using any functions or properties +on the object is likely to crash your application and should be avoided.

      +

      Using executionAsyncResource() in the top-level execution context will +return an empty object as there is no handle or request object to use, +but having an object representing the top-level can be helpful.

      +
      const { open } = require('fs');
      +const { executionAsyncId, executionAsyncResource } = require('async_hooks');
      +
      +console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
      +open(__filename, 'r', (err, fd) => {
      +  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
      +});
      +

      This can be used to implement continuation local storage without the +use of a tracking Map to store the metadata:

      +
      const { createServer } = require('http');
      +const {
      +  executionAsyncId,
      +  executionAsyncResource,
      +  createHook
      +} = require('async_hooks');
      +const sym = Symbol('state'); // Private symbol to avoid pollution
      +
      +createHook({
      +  init(asyncId, type, triggerAsyncId, resource) {
      +    const cr = executionAsyncResource();
      +    if (cr) {
      +      resource[sym] = cr[sym];
      +    }
      +  }
      +}).enable();
      +
      +const server = createServer((req, res) => {
      +  executionAsyncResource()[sym] = { state: req.url };
      +  setTimeout(function() {
      +    res.end(JSON.stringify(executionAsyncResource()[sym]));
      +  }, 100);
      +}).listen(3000);
      +

      async_hooks.executionAsyncId()#

      + +
        +
      • Returns: <number> The asyncId of the current execution context. Useful to +track when something calls.
      • +
      +
      const async_hooks = require('async_hooks');
      +
      +console.log(async_hooks.executionAsyncId());  // 1 - bootstrap
      +fs.open(path, 'r', (err, fd) => {
      +  console.log(async_hooks.executionAsyncId());  // 6 - open()
      +});
      +

      The ID returned from executionAsyncId() is related to execution timing, not +causality (which is covered by triggerAsyncId()):

      +
      const server = net.createServer((conn) => {
      +  // Returns the ID of the server, not of the new connection, because the
      +  // callback runs in the execution scope of the server's MakeCallback().
      +  async_hooks.executionAsyncId();
      +
      +}).listen(port, () => {
      +  // Returns the ID of a TickObject (i.e. process.nextTick()) because all
      +  // callbacks passed to .listen() are wrapped in a nextTick().
      +  async_hooks.executionAsyncId();
      +});
      +

      Promise contexts may not get precise executionAsyncIds by default. +See the section on promise execution tracking.

      +

      async_hooks.triggerAsyncId()#

      +
        +
      • Returns: <number> The ID of the resource responsible for calling the callback +that is currently being executed.
      • +
      +
      const server = net.createServer((conn) => {
      +  // The resource that caused (or triggered) this callback to be called
      +  // was that of the new connection. Thus the return value of triggerAsyncId()
      +  // is the asyncId of "conn".
      +  async_hooks.triggerAsyncId();
      +
      +}).listen(port, () => {
      +  // Even though all callbacks passed to .listen() are wrapped in a nextTick()
      +  // the callback itself exists because the call to the server's .listen()
      +  // was made. So the return value would be the ID of the server.
      +  async_hooks.triggerAsyncId();
      +});
      +

      Promise contexts may not get valid triggerAsyncIds by default. See +the section on promise execution tracking.

      +

      Promise execution tracking#

      +

      By default, promise executions are not assigned asyncIds due to the relatively +expensive nature of the promise introspection API provided by +V8. This means that programs using promises or async/await will not get +correct execution and trigger ids for promise callback contexts by default.

      +
      const ah = require('async_hooks');
      +Promise.resolve(1729).then(() => {
      +  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
      +});
      +// produces:
      +// eid 1 tid 0
      +

      Observe that the then() callback claims to have executed in the context of the +outer scope even though there was an asynchronous hop involved. Also, +the triggerAsyncId value is 0, which means that we are missing context about +the resource that caused (triggered) the then() callback to be executed.

      +

      Installing async hooks via async_hooks.createHook enables promise execution +tracking:

      +
      const ah = require('async_hooks');
      +ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
      +Promise.resolve(1729).then(() => {
      +  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
      +});
      +// produces:
      +// eid 7 tid 6
      +

      In this example, adding any actual hook function enabled the tracking of +promises. There are two promises in the example above; the promise created by +Promise.resolve() and the promise returned by the call to then(). In the +example above, the first promise got the asyncId 6 and the latter got +asyncId 7. During the execution of the then() callback, we are executing +in the context of promise with asyncId 7. This promise was triggered by +async resource 6.

      +

      Another subtlety with promises is that before and after callbacks are run +only on chained promises. That means promises not created by then()/catch() +will not have the before and after callbacks fired on them. For more details +see the details of the V8 PromiseHooks API.

      +

      JavaScript embedder API#

      +

      Library developers that handle their own asynchronous resources performing tasks +like I/O, connection pooling, or managing callback queues may use the +AsyncResource JavaScript API so that all the appropriate callbacks are called.

      +

      Class: AsyncResource#

      +

      The class AsyncResource is designed to be extended by the embedder's async +resources. Using this, users can easily trigger the lifetime events of their +own resources.

      +

      The init hook will trigger when an AsyncResource is instantiated.

      +

      The following is an overview of the AsyncResource API.

      +
      const { AsyncResource, executionAsyncId } = require('async_hooks');
      +
      +// AsyncResource() is meant to be extended. Instantiating a
      +// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
      +// async_hook.executionAsyncId() is used.
      +const asyncResource = new AsyncResource(
      +  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
      +);
      +
      +// Run a function in the execution context of the resource. This will
      +// * establish the context of the resource
      +// * trigger the AsyncHooks before callbacks
      +// * call the provided function `fn` with the supplied arguments
      +// * trigger the AsyncHooks after callbacks
      +// * restore the original execution context
      +asyncResource.runInAsyncScope(fn, thisArg, ...args);
      +
      +// Call AsyncHooks destroy callbacks.
      +asyncResource.emitDestroy();
      +
      +// Return the unique ID assigned to the AsyncResource instance.
      +asyncResource.asyncId();
      +
      +// Return the trigger ID for the AsyncResource instance.
      +asyncResource.triggerAsyncId();
      +

      new AsyncResource(type[, options])#

      +
        +
      • type <string> The type of async event.
      • +
      • options <Object> +
          +
        • triggerAsyncId <number> The ID of the execution context that created this +async event. Default: executionAsyncId().
        • +
        • requireManualDestroy <boolean> If set to true, disables emitDestroy +when the object is garbage collected. This usually does not need to be set +(even if emitDestroy is called manually), unless the resource's asyncId +is retrieved and the sensitive API's emitDestroy is called with it. +When set to false, the emitDestroy call on garbage collection +will only take place if there is at least one active destroy hook. +Default: false.
        • +
        +
      • +
      +

      Example usage:

      +
      class DBQuery extends AsyncResource {
      +  constructor(db) {
      +    super('DBQuery');
      +    this.db = db;
      +  }
      +
      +  getInfo(query, callback) {
      +    this.db.get(query, (err, data) => {
      +      this.runInAsyncScope(callback, null, err, data);
      +    });
      +  }
      +
      +  close() {
      +    this.db = null;
      +    this.emitDestroy();
      +  }
      +}
      +

      Static method: AsyncResource.bind(fn[, type])#

      + +
        +
      • fn <Function> The function to bind to the current execution context.
      • +
      • type <string> An optional name to associate with the underlying +AsyncResource.
      • +
      +

      Binds the given function to the current execution context.

      +

      The returned function will have an asyncResource property referencing +the AsyncResource to which the function is bound.

      +

      asyncResource.bind(fn)#

      + +
        +
      • fn <Function> The function to bind to the current AsyncResource.
      • +
      +

      Binds the given function to execute to this AsyncResource's scope.

      +

      The returned function will have an asyncResource property referencing +the AsyncResource to which the function is bound.

      +

      asyncResource.runInAsyncScope(fn[, thisArg, ...args])#

      + +
        +
      • fn <Function> The function to call in the execution context of this async +resource.
      • +
      • thisArg <any> The receiver to be used for the function call.
      • +
      • ...args <any> Optional arguments to pass to the function.
      • +
      +

      Call the provided function with the provided arguments in the execution context +of the async resource. This will establish the context, trigger the AsyncHooks +before callbacks, call the function, trigger the AsyncHooks after callbacks, and +then restore the original execution context.

      +

      asyncResource.emitDestroy()#

      + +

      Call all destroy hooks. This should only ever be called once. An error will +be thrown if it is called more than once. This must be manually called. If +the resource is left to be collected by the GC then the destroy hooks will +never be called.

      +

      asyncResource.asyncId()#

      +
        +
      • Returns: <number> The unique asyncId assigned to the resource.
      • +
      +

      asyncResource.triggerAsyncId()#

      +
        +
      • Returns: <number> The same triggerAsyncId that is passed to the +AsyncResource constructor.
      • +
      +

      +

      Using AsyncResource for a Worker thread pool#

      +

      The following example shows how to use the AsyncResource class to properly +provide async tracking for a Worker pool. Other resource pools, such as +database connection pools, can follow a similar model.

      +

      Assuming that the task is adding two numbers, using a file named +task_processor.js with the following content:

      +
      const { parentPort } = require('worker_threads');
      +parentPort.on('message', (task) => {
      +  parentPort.postMessage(task.a + task.b);
      +});
      +

      a Worker pool around it could use the following structure:

      +
      const { AsyncResource } = require('async_hooks');
      +const { EventEmitter } = require('events');
      +const path = require('path');
      +const { Worker } = require('worker_threads');
      +
      +const kTaskInfo = Symbol('kTaskInfo');
      +const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
      +
      +class WorkerPoolTaskInfo extends AsyncResource {
      +  constructor(callback) {
      +    super('WorkerPoolTaskInfo');
      +    this.callback = callback;
      +  }
      +
      +  done(err, result) {
      +    this.runInAsyncScope(this.callback, null, err, result);
      +    this.emitDestroy();  // `TaskInfo`s are used only once.
      +  }
      +}
      +
      +class WorkerPool extends EventEmitter {
      +  constructor(numThreads) {
      +    super();
      +    this.numThreads = numThreads;
      +    this.workers = [];
      +    this.freeWorkers = [];
      +
      +    for (let i = 0; i < numThreads; i++)
      +      this.addNewWorker();
      +  }
      +
      +  addNewWorker() {
      +    const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));
      +    worker.on('message', (result) => {
      +      // In case of success: Call the callback that was passed to `runTask`,
      +      // remove the `TaskInfo` associated with the Worker, and mark it as free
      +      // again.
      +      worker[kTaskInfo].done(null, result);
      +      worker[kTaskInfo] = null;
      +      this.freeWorkers.push(worker);
      +      this.emit(kWorkerFreedEvent);
      +    });
      +    worker.on('error', (err) => {
      +      // In case of an uncaught exception: Call the callback that was passed to
      +      // `runTask` with the error.
      +      if (worker[kTaskInfo])
      +        worker[kTaskInfo].done(err, null);
      +      else
      +        this.emit('error', err);
      +      // Remove the worker from the list and start a new Worker to replace the
      +      // current one.
      +      this.workers.splice(this.workers.indexOf(worker), 1);
      +      this.addNewWorker();
      +    });
      +    this.workers.push(worker);
      +    this.freeWorkers.push(worker);
      +    this.emit(kWorkerFreedEvent);
      +  }
      +
      +  runTask(task, callback) {
      +    if (this.freeWorkers.length === 0) {
      +      // No free threads, wait until a worker thread becomes free.
      +      this.once(kWorkerFreedEvent, () => this.runTask(task, callback));
      +      return;
      +    }
      +
      +    const worker = this.freeWorkers.pop();
      +    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
      +    worker.postMessage(task);
      +  }
      +
      +  close() {
      +    for (const worker of this.workers) worker.terminate();
      +  }
      +}
      +
      +module.exports = WorkerPool;
      +

      Without the explicit tracking added by the WorkerPoolTaskInfo objects, +it would appear that the callbacks are associated with the individual Worker +objects. However, the creation of the Workers is not associated with the +creation of the tasks and does not provide information about when tasks +were scheduled.

      +

      This pool could be used as follows:

      +
      const WorkerPool = require('./worker_pool.js');
      +const os = require('os');
      +
      +const pool = new WorkerPool(os.cpus().length);
      +
      +let finished = 0;
      +for (let i = 0; i < 10; i++) {
      +  pool.runTask({ a: 42, b: 100 }, (err, result) => {
      +    console.log(i, err, result);
      +    if (++finished === 10)
      +      pool.close();
      +  });
      +}
      +

      Integrating AsyncResource with EventEmitter#

      +

      Event listeners triggered by an EventEmitter may be run in a different +execution context than the one that was active when eventEmitter.on() was +called.

      +

      The following example shows how to use the AsyncResource class to properly +associate an event listener with the correct execution context. The same +approach can be applied to a Stream or a similar event-driven class.

      +
      const { createServer } = require('http');
      +const { AsyncResource, executionAsyncId } = require('async_hooks');
      +
      +const server = createServer((req, res) => {
      +  req.on('close', AsyncResource.bind(() => {
      +    // Execution context is bound to the current outer scope.
      +  }));
      +  req.on('close', () => {
      +    // Execution context is bound to the scope that caused 'close' to emit.
      +  });
      +  res.end();
      +}).listen(3000);
      +

      Class: AsyncLocalStorage#

      + +

      This class is used to create asynchronous state within callbacks and promise +chains. It allows storing data throughout the lifetime of a web request +or any other asynchronous duration. It is similar to thread-local storage +in other languages.

      +

      The following example uses AsyncLocalStorage to build a simple logger +that assigns IDs to incoming HTTP requests and includes them in messages +logged within each request.

      +
      const http = require('http');
      +const { AsyncLocalStorage } = require('async_hooks');
      +
      +const asyncLocalStorage = new AsyncLocalStorage();
      +
      +function logWithId(msg) {
      +  const id = asyncLocalStorage.getStore();
      +  console.log(`${id !== undefined ? id : '-'}:`, msg);
      +}
      +
      +let idSeq = 0;
      +http.createServer((req, res) => {
      +  asyncLocalStorage.run(idSeq++, () => {
      +    logWithId('start');
      +    // Imagine any chain of async operations here
      +    setImmediate(() => {
      +      logWithId('finish');
      +      res.end();
      +    });
      +  });
      +}).listen(8080);
      +
      +http.get('http://localhost:8080');
      +http.get('http://localhost:8080');
      +// Prints:
      +//   0: start
      +//   1: start
      +//   0: finish
      +//   1: finish
      +

      When having multiple instances of AsyncLocalStorage, they are independent +from each other. It is safe to instantiate this class multiple times.

      +

      new AsyncLocalStorage()#

      + +

      Creates a new instance of AsyncLocalStorage. Store is only provided within a +run method call.

      +

      asyncLocalStorage.disable()#

      + +

      This method disables the instance of AsyncLocalStorage. All subsequent calls +to asyncLocalStorage.getStore() will return undefined until +asyncLocalStorage.run() is called again.

      +

      When calling asyncLocalStorage.disable(), all current contexts linked to the +instance will be exited.

      +

      Calling asyncLocalStorage.disable() is required before the +asyncLocalStorage can be garbage collected. This does not apply to stores +provided by the asyncLocalStorage, as those objects are garbage collected +along with the corresponding async resources.

      +

      This method is to be used when the asyncLocalStorage is not in use anymore +in the current process.

      +

      asyncLocalStorage.getStore()#

      + + +

      This method returns the current store. +If this method is called outside of an asynchronous context initialized by +calling asyncLocalStorage.run, it will return undefined.

      +

      asyncLocalStorage.enterWith(store)#

      + + +

      Calling asyncLocalStorage.enterWith(store) will transition into the context +for the remainder of the current synchronous execution and will persist +through any following asynchronous calls.

      +

      Example:

      +
      const store = { id: 1 };
      +asyncLocalStorage.enterWith(store);
      +asyncLocalStorage.getStore(); // Returns the store object
      +someAsyncOperation(() => {
      +  asyncLocalStorage.getStore(); // Returns the same object
      +});
      +

      This transition will continue for the entire synchronous execution. +This means that if, for example, the context is entered within an event +handler subsequent event handlers will also run within that context unless +specifically bound to another context with an AsyncResource.

      +
      const store = { id: 1 };
      +
      +emitter.on('my-event', () => {
      +  asyncLocalStorage.enterWith(store);
      +});
      +emitter.on('my-event', () => {
      +  asyncLocalStorage.getStore(); // Returns the same object
      +});
      +
      +asyncLocalStorage.getStore(); // Returns undefined
      +emitter.emit('my-event');
      +asyncLocalStorage.getStore(); // Returns the same object
      +

      asyncLocalStorage.run(store, callback[, ...args])#

      + + +

      This methods runs a function synchronously within a context and return its +return value. The store is not accessible outside of the callback function or +the asynchronous operations created within the callback.

      +

      Optionally, arguments can be passed to the function. They will be passed to +the callback function.

      +

      If the callback function throws an error, it will be thrown by run too. +The stacktrace will not be impacted by this call and the context will +be exited.

      +

      Example:

      +
      const store = { id: 2 };
      +try {
      +  asyncLocalStorage.run(store, () => {
      +    asyncLocalStorage.getStore(); // Returns the store object
      +    throw new Error();
      +  });
      +} catch (e) {
      +  asyncLocalStorage.getStore(); // Returns undefined
      +  // The error will be caught here
      +}
      +

      asyncLocalStorage.exit(callback[, ...args])#

      + + +

      This methods runs a function synchronously outside of a context and return its +return value. The store is not accessible within the callback function or +the asynchronous operations created within the callback.

      +

      Optionally, arguments can be passed to the function. They will be passed to +the callback function.

      +

      If the callback function throws an error, it will be thrown by exit too. +The stacktrace will not be impacted by this call and +the context will be re-entered.

      +

      Example:

      +
      // Within a call to run
      +try {
      +  asyncLocalStorage.getStore(); // Returns the store object or value
      +  asyncLocalStorage.exit(() => {
      +    asyncLocalStorage.getStore(); // Returns undefined
      +    throw new Error();
      +  });
      +} catch (e) {
      +  asyncLocalStorage.getStore(); // Returns the same object or value
      +  // The error will be caught here
      +}
      +

      Usage with async/await#

      +

      If, within an async function, only one await call is to run within a context, +the following pattern should be used:

      +
      async function fn() {
      +  await asyncLocalStorage.run(new Map(), () => {
      +    asyncLocalStorage.getStore().set('key', value);
      +    return foo(); // The return value of foo will be awaited
      +  });
      +}
      +

      In this example, the store is only available in the callback function and the +functions called by foo. Outside of run, calling getStore will return +undefined.

      +

      Troubleshooting#

      +

      In most cases your application or library code should have no issues with +AsyncLocalStorage. But in rare cases you may face situations when the +current store is lost in one of asynchronous operations. In those cases, +consider the following options.

      +

      If your code is callback-based, it is enough to promisify it with +util.promisify(), so it starts working with native promises.

      +

      If you need to keep using callback-based API, or your code assumes +a custom thenable implementation, use the AsyncResource class +to associate the asynchronous operation with the correct execution context.

      + +
      +
      +
      + + diff --git a/doc/api/async_hooks.json b/doc/api/async_hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..e32022b454939746fd6358abe02a09af3607364f --- /dev/null +++ b/doc/api/async_hooks.json @@ -0,0 +1,761 @@ +{ + "type": "module", + "source": "doc/api/async_hooks.md", + "modules": [ + { + "textRaw": "Async hooks", + "name": "async_hooks", + "introduced_in": "v8.1.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/async_hooks.js

      \n

      The async_hooks module provides an API to track asynchronous resources. It\ncan be accessed using:

      \n
      const async_hooks = require('async_hooks');\n
      ", + "modules": [ + { + "textRaw": "Terminology", + "name": "terminology", + "desc": "

      An asynchronous resource represents an object with an associated callback.\nThis callback may be called multiple times, for example, the 'connection'\nevent in net.createServer(), or just a single time like in fs.open().\nA resource can also be closed before the callback is called. AsyncHook does\nnot explicitly distinguish between these different cases but will represent them\nas the abstract concept that is a resource.

      \n

      If Workers are used, each thread has an independent async_hooks\ninterface, and each thread will use a new set of async IDs.

      ", + "type": "module", + "displayName": "Terminology" + }, + { + "textRaw": "Public API", + "name": "public_api", + "modules": [ + { + "textRaw": "Overview", + "name": "overview", + "desc": "

      Following is a simple overview of the public API.

      \n
      const async_hooks = require('async_hooks');\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init is called during object construction. The resource may not have\n// completed construction when this callback runs, therefore all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// Before is called just before the resource's callback is called. It can be\n// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1\n// time for requests (e.g. FSReqCallback).\nfunction before(asyncId) { }\n\n// After is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// Destroy is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve is called only for promise resources, when the\n// `resolve` function passed to the `Promise` constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n
      ", + "methods": [ + { + "textRaw": "`async_hooks.createHook(callbacks)`", + "type": "method", + "name": "createHook", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncHook} Instance used for disabling and enabling hooks", + "name": "return", + "type": "AsyncHook", + "desc": "Instance used for disabling and enabling hooks" + }, + "params": [ + { + "textRaw": "`callbacks` {Object} The [Hook Callbacks][] to register", + "name": "callbacks", + "type": "Object", + "desc": "The [Hook Callbacks][] to register", + "options": [ + { + "textRaw": "`init` {Function} The [`init` callback][].", + "name": "init", + "type": "Function", + "desc": "The [`init` callback][]." + }, + { + "textRaw": "`before` {Function} The [`before` callback][].", + "name": "before", + "type": "Function", + "desc": "The [`before` callback][]." + }, + { + "textRaw": "`after` {Function} The [`after` callback][].", + "name": "after", + "type": "Function", + "desc": "The [`after` callback][]." + }, + { + "textRaw": "`destroy` {Function} The [`destroy` callback][].", + "name": "destroy", + "type": "Function", + "desc": "The [`destroy` callback][]." + }, + { + "textRaw": "`promiseResolve` {Function} The [`promiseResolve` callback][].", + "name": "promiseResolve", + "type": "Function", + "desc": "The [`promiseResolve` callback][]." + } + ] + } + ] + } + ], + "desc": "

      Registers functions to be called for different lifetime events of each async\noperation.

      \n

      The callbacks init()/before()/after()/destroy() are called for the\nrespective asynchronous event during a resource's lifetime.

      \n

      All callbacks are optional. For example, if only resource cleanup needs to\nbe tracked, then only the destroy callback needs to be passed. The\nspecifics of all functions that can be passed to callbacks is in the\nHook Callbacks section.

      \n
      const async_hooks = require('async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { }\n});\n
      \n

      The callbacks will be inherited via the prototype chain:

      \n
      class MyAsyncCallbacks {\n  init(asyncId, type, triggerAsyncId, resource) { }\n  destroy(asyncId) {}\n}\n\nclass MyAddedCallbacks extends MyAsyncCallbacks {\n  before(asyncId) { }\n  after(asyncId) { }\n}\n\nconst asyncHook = async_hooks.createHook(new MyAddedCallbacks());\n
      ", + "modules": [ + { + "textRaw": "Error handling", + "name": "error_handling", + "desc": "

      If any AsyncHook callbacks throw, the application will print the stack trace\nand exit. The exit path does follow that of an uncaught exception, but\nall 'uncaughtException' listeners are removed, thus forcing the process to\nexit. The 'exit' callbacks will still be called unless the application is run\nwith --abort-on-uncaught-exception, in which case a stack trace will be\nprinted and the application exits, leaving a core file.

      \n

      The reason for this error handling behavior is that these callbacks are running\nat potentially volatile points in an object's lifetime, for example during\nclass construction and destruction. Because of this, it is deemed necessary to\nbring down the process quickly in order to prevent an unintentional abort in the\nfuture. This is subject to change in the future if a comprehensive analysis is\nperformed to ensure an exception can follow the normal control flow without\nunintentional side effects.

      ", + "type": "module", + "displayName": "Error handling" + }, + { + "textRaw": "Printing in AsyncHooks callbacks", + "name": "printing_in_asynchooks_callbacks", + "desc": "

      Because printing to the console is an asynchronous operation, console.log()\nwill cause the AsyncHooks callbacks to be called. Using console.log() or\nsimilar asynchronous operations inside an AsyncHooks callback function will thus\ncause an infinite recursion. An easy solution to this when debugging is to use a\nsynchronous logging operation such as fs.writeFileSync(file, msg, flag).\nThis will print to the file and will not invoke AsyncHooks recursively because\nit is synchronous.

      \n
      const fs = require('fs');\nconst util = require('util');\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHooks callback\n  fs.writeFileSync('log.out', `${util.format(...args)}\\n`, { flag: 'a' });\n}\n
      \n

      If an asynchronous operation is needed for logging, it is possible to keep\ntrack of what caused the asynchronous operation using the information\nprovided by AsyncHooks itself. The logging should then be skipped when\nit was the logging itself that caused AsyncHooks callback to call. By\ndoing this the otherwise infinite recursion is broken.

      ", + "type": "module", + "displayName": "Printing in AsyncHooks callbacks" + } + ] + } + ], + "type": "module", + "displayName": "Overview" + } + ], + "classes": [ + { + "textRaw": "Class: `AsyncHook`", + "type": "class", + "name": "AsyncHook", + "desc": "

      The class AsyncHook exposes an interface for tracking lifetime events\nof asynchronous operations.

      ", + "methods": [ + { + "textRaw": "`asyncHook.enable()`", + "type": "method", + "name": "enable", + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.", + "name": "return", + "type": "AsyncHook", + "desc": "A reference to `asyncHook`." + }, + "params": [] + } + ], + "desc": "

      Enable the callbacks for a given AsyncHook instance. If no callbacks are\nprovided enabling is a noop.

      \n

      The AsyncHook instance is disabled by default. If the AsyncHook instance\nshould be enabled immediately after creation, the following pattern can be used.

      \n
      const async_hooks = require('async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();\n
      " + }, + { + "textRaw": "`asyncHook.disable()`", + "type": "method", + "name": "disable", + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.", + "name": "return", + "type": "AsyncHook", + "desc": "A reference to `asyncHook`." + }, + "params": [] + } + ], + "desc": "

      Disable the callbacks for a given AsyncHook instance from the global pool of\nAsyncHook callbacks to be executed. Once a hook has been disabled it will not\nbe called again until enabled.

      \n

      For API consistency disable() also returns the AsyncHook instance.

      " + }, + { + "textRaw": "`async_hooks.executionAsyncResource()`", + "type": "method", + "name": "executionAsyncResource", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} The resource representing the current execution. Useful to store data within the resource.", + "name": "return", + "type": "Object", + "desc": "The resource representing the current execution. Useful to store data within the resource." + }, + "params": [] + } + ], + "desc": "

      Resource objects returned by executionAsyncResource() are most often internal\nNode.js handle objects with undocumented APIs. Using any functions or properties\non the object is likely to crash your application and should be avoided.

      \n

      Using executionAsyncResource() in the top-level execution context will\nreturn an empty object as there is no handle or request object to use,\nbut having an object representing the top-level can be helpful.

      \n
      const { open } = require('fs');\nconst { executionAsyncId, executionAsyncResource } = require('async_hooks');\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(__filename, 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});\n
      \n

      This can be used to implement continuation local storage without the\nuse of a tracking Map to store the metadata:

      \n
      const { createServer } = require('http');\nconst {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook\n} = require('async_hooks');\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    const cr = executionAsyncResource();\n    if (cr) {\n      resource[sym] = cr[sym];\n    }\n  }\n}).enable();\n\nconst server = createServer((req, res) => {\n  executionAsyncResource()[sym] = { state: req.url };\n  setTimeout(function() {\n    res.end(JSON.stringify(executionAsyncResource()[sym]));\n  }, 100);\n}).listen(3000);\n
      " + }, + { + "textRaw": "`async_hooks.executionAsyncId()`", + "type": "method", + "name": "executionAsyncId", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [ + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Renamed from `currentId`" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The `asyncId` of the current execution context. Useful to track when something calls.", + "name": "return", + "type": "number", + "desc": "The `asyncId` of the current execution context. Useful to track when something calls." + }, + "params": [] + } + ], + "desc": "
      const async_hooks = require('async_hooks');\n\nconsole.log(async_hooks.executionAsyncId());  // 1 - bootstrap\nfs.open(path, 'r', (err, fd) => {\n  console.log(async_hooks.executionAsyncId());  // 6 - open()\n});\n
      \n

      The ID returned from executionAsyncId() is related to execution timing, not\ncausality (which is covered by triggerAsyncId()):

      \n
      const server = net.createServer((conn) => {\n  // Returns the ID of the server, not of the new connection, because the\n  // callback runs in the execution scope of the server's MakeCallback().\n  async_hooks.executionAsyncId();\n\n}).listen(port, () => {\n  // Returns the ID of a TickObject (i.e. process.nextTick()) because all\n  // callbacks passed to .listen() are wrapped in a nextTick().\n  async_hooks.executionAsyncId();\n});\n
      \n

      Promise contexts may not get precise executionAsyncIds by default.\nSee the section on promise execution tracking.

      " + }, + { + "textRaw": "`async_hooks.triggerAsyncId()`", + "type": "method", + "name": "triggerAsyncId", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The ID of the resource responsible for calling the callback that is currently being executed.", + "name": "return", + "type": "number", + "desc": "The ID of the resource responsible for calling the callback that is currently being executed." + }, + "params": [] + } + ], + "desc": "
      const server = net.createServer((conn) => {\n  // The resource that caused (or triggered) this callback to be called\n  // was that of the new connection. Thus the return value of triggerAsyncId()\n  // is the asyncId of \"conn\".\n  async_hooks.triggerAsyncId();\n\n}).listen(port, () => {\n  // Even though all callbacks passed to .listen() are wrapped in a nextTick()\n  // the callback itself exists because the call to the server's .listen()\n  // was made. So the return value would be the ID of the server.\n  async_hooks.triggerAsyncId();\n});\n
      \n

      Promise contexts may not get valid triggerAsyncIds by default. See\nthe section on promise execution tracking.

      " + } + ], + "modules": [ + { + "textRaw": "Hook callbacks", + "name": "hook_callbacks", + "desc": "

      Key events in the lifetime of asynchronous events have been categorized into\nfour areas: instantiation, before/after the callback is called, and when the\ninstance is destroyed.

      ", + "methods": [ + { + "textRaw": "`init(asyncId, type, triggerAsyncId, resource)`", + "type": "method", + "name": "init", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number} A unique ID for the async resource.", + "name": "asyncId", + "type": "number", + "desc": "A unique ID for the async resource." + }, + { + "textRaw": "`type` {string} The type of the async resource.", + "name": "type", + "type": "string", + "desc": "The type of the async resource." + }, + { + "textRaw": "`triggerAsyncId` {number} The unique ID of the async resource in whose execution context this async resource was created.", + "name": "triggerAsyncId", + "type": "number", + "desc": "The unique ID of the async resource in whose execution context this async resource was created." + }, + { + "textRaw": "`resource` {Object} Reference to the resource representing the async operation, needs to be released during _destroy_.", + "name": "resource", + "type": "Object", + "desc": "Reference to the resource representing the async operation, needs to be released during _destroy_." + } + ] + } + ], + "desc": "

      Called when a class is constructed that has the possibility to emit an\nasynchronous event. This does not mean the instance must call\nbefore/after before destroy is called, only that the possibility\nexists.

      \n

      This behavior can be observed by doing something like opening a resource then\nclosing it before the resource can be used. The following snippet demonstrates\nthis.

      \n
      require('net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n
      \n

      Every new resource is assigned an ID that is unique within the scope of the\ncurrent Node.js instance.

      ", + "modules": [ + { + "textRaw": "`type`", + "name": "`type`", + "desc": "

      The type is a string identifying the type of resource that caused\ninit to be called. Generally, it will correspond to the name of the\nresource's constructor.

      \n
      FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,\nHTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,\nSHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,\nTTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,\nRANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject\n
      \n

      There is also the PROMISE resource type, which is used to track Promise\ninstances and asynchronous work scheduled by them.

      \n

      Users are able to define their own type when using the public embedder API.

      \n

      It is possible to have type name collisions. Embedders are encouraged to use\nunique prefixes, such as the npm package name, to prevent collisions when\nlistening to the hooks.

      ", + "type": "module", + "displayName": "`type`" + }, + { + "textRaw": "`triggerAsyncId`", + "name": "`triggerasyncid`", + "desc": "

      triggerAsyncId is the asyncId of the resource that caused (or \"triggered\")\nthe new resource to initialize and that caused init to call. This is different\nfrom async_hooks.executionAsyncId() that only shows when a resource was\ncreated, while triggerAsyncId shows why a resource was created.

      \n

      The following is a simple demonstration of triggerAsyncId:

      \n
      async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    fs.writeSync(\n      process.stdout.fd,\n      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  }\n}).enable();\n\nrequire('net').createServer((conn) => {}).listen(8080);\n
      \n

      Output when hitting the server with nc localhost 8080:

      \n
      TCPSERVERWRAP(5): trigger: 1 execution: 1\nTCPWRAP(7): trigger: 5 execution: 0\n
      \n

      The TCPSERVERWRAP is the server which receives the connections.

      \n

      The TCPWRAP is the new connection from the client. When a new\nconnection is made, the TCPWrap instance is immediately constructed. This\nhappens outside of any JavaScript stack. (An executionAsyncId() of 0 means\nthat it is being executed from C++ with no JavaScript stack above it.) With only\nthat information, it would be impossible to link resources together in\nterms of what caused them to be created, so triggerAsyncId is given the task\nof propagating what resource is responsible for the new resource's existence.

      ", + "type": "module", + "displayName": "`triggerAsyncId`" + }, + { + "textRaw": "`resource`", + "name": "`resource`", + "desc": "

      resource is an object that represents the actual async resource that has\nbeen initialized. This can contain useful information that can vary based on\nthe value of type. For instance, for the GETADDRINFOREQWRAP resource type,\nresource provides the host name used when looking up the IP address for the\nhost in net.Server.listen(). The API for accessing this information is\nnot supported, but using the Embedder API, users can provide\nand document their own resource objects. For example, such a resource object\ncould contain the SQL query being executed.

      \n

      In the case of Promises, the resource object will have an\nisChainedPromise property, set to true if the promise has a parent promise,\nand false otherwise. For example, in the case of b = a.then(handler), a is\nconsidered a parent Promise of b. Here, b is considered a chained promise.

      \n

      In some cases the resource object is reused for performance reasons, it is\nthus not safe to use it as a key in a WeakMap or add properties to it.

      ", + "type": "module", + "displayName": "`resource`" + }, + { + "textRaw": "Asynchronous context example", + "name": "asynchronous_context_example", + "desc": "

      The following is an example with additional information about the calls to\ninit between the before and after calls, specifically what the\ncallback to listen() will look like. The output formatting is slightly more\nelaborate to make calling context easier to see.

      \n
      let indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      process.stdout.fd,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(process.stdout.fd, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(process.stdout.fd, `${indentStr}after:  ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(process.stdout.fd, `${indentStr}destroy:  ${asyncId}\\n`);\n  },\n}).enable();\n\nrequire('net').createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});\n
      \n

      Output from only starting the server:

      \n
      TCPSERVERWRAP(5): trigger: 1 execution: 1\nTickObject(6): trigger: 5 execution: 1\nbefore:  6\n  Timeout(7): trigger: 6 execution: 6\nafter:   6\ndestroy: 6\nbefore:  7\n>>> 7\n  TickObject(8): trigger: 7 execution: 7\nafter:   7\nbefore:  8\nafter:   8\n
      \n

      As illustrated in the example, executionAsyncId() and execution each specify\nthe value of the current execution context; which is delineated by calls to\nbefore and after.

      \n

      Only using execution to graph resource allocation results in the following:

      \n
        root(1)\n     ^\n     |\nTickObject(6)\n     ^\n     |\n Timeout(7)\n
      \n

      The TCPSERVERWRAP is not part of this graph, even though it was the reason for\nconsole.log() being called. This is because binding to a port without a host\nname is a synchronous operation, but to maintain a completely asynchronous\nAPI the user's callback is placed in a process.nextTick(). Which is why\nTickObject is present in the output and is a 'parent' for .listen()\ncallback.

      \n

      The graph only shows when a resource was created, not why, so to track\nthe why use triggerAsyncId. Which can be represented with the following\ngraph:

      \n
       bootstrap(1)\n     |\n     Ë…\nTCPSERVERWRAP(5)\n     |\n     Ë…\n TickObject(6)\n     |\n     Ë…\n  Timeout(7)\n
      ", + "type": "module", + "displayName": "Asynchronous context example" + } + ] + }, + { + "textRaw": "`before(asyncId)`", + "type": "method", + "name": "before", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      When an asynchronous operation is initiated (such as a TCP server receiving a\nnew connection) or completes (such as writing data to disk) a callback is\ncalled to notify the user. The before callback is called just before said\ncallback is executed. asyncId is the unique identifier assigned to the\nresource about to execute the callback.

      \n

      The before callback will be called 0 to N times. The before callback\nwill typically be called 0 times if the asynchronous operation was cancelled\nor, for example, if no connections are received by a TCP server. Persistent\nasynchronous resources like a TCP server will typically call the before\ncallback multiple times, while other operations like fs.open() will call\nit only once.

      " + }, + { + "textRaw": "`after(asyncId)`", + "type": "method", + "name": "after", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      Called immediately after the callback specified in before is completed.

      \n

      If an uncaught exception occurs during execution of the callback, then after\nwill run after the 'uncaughtException' event is emitted or a domain's\nhandler runs.

      " + }, + { + "textRaw": "`destroy(asyncId)`", + "type": "method", + "name": "destroy", + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      Called after the resource corresponding to asyncId is destroyed. It is also\ncalled asynchronously from the embedder API emitDestroy().

      \n

      Some resources depend on garbage collection for cleanup, so if a reference is\nmade to the resource object passed to init it is possible that destroy\nwill never be called, causing a memory leak in the application. If the resource\ndoes not depend on garbage collection, then this will not be an issue.

      " + }, + { + "textRaw": "`promiseResolve(asyncId)`", + "type": "method", + "name": "promiseResolve", + "meta": { + "added": [ + "v8.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`asyncId` {number}", + "name": "asyncId", + "type": "number" + } + ] + } + ], + "desc": "

      Called when the resolve function passed to the Promise constructor is\ninvoked (either directly or through other means of resolving a promise).

      \n

      resolve() does not do any observable synchronous work.

      \n

      The Promise is not necessarily fulfilled or rejected at this point if the\nPromise was resolved by assuming the state of another Promise.

      \n
      new Promise((resolve) => resolve(true)).then((a) => {});\n
      \n

      calls the following callbacks:

      \n
      init for PROMISE with id 5, trigger id: 1\n  promise resolve 5      # corresponds to resolve(true)\ninit for PROMISE with id 6, trigger id: 5  # the Promise returned by then()\n  before 6               # the then() callback is entered\n  promise resolve 6      # the then() callback resolves the promise by returning\n  after 6\n
      " + } + ], + "type": "module", + "displayName": "Hook callbacks" + } + ] + } + ], + "type": "module", + "displayName": "Public API" + }, + { + "textRaw": "Promise execution tracking", + "name": "promise_execution_tracking", + "desc": "

      By default, promise executions are not assigned asyncIds due to the relatively\nexpensive nature of the promise introspection API provided by\nV8. This means that programs using promises or async/await will not get\ncorrect execution and trigger ids for promise callback contexts by default.

      \n
      const ah = require('async_hooks');\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n
      \n

      Observe that the then() callback claims to have executed in the context of the\nouter scope even though there was an asynchronous hop involved. Also,\nthe triggerAsyncId value is 0, which means that we are missing context about\nthe resource that caused (triggered) the then() callback to be executed.

      \n

      Installing async hooks via async_hooks.createHook enables promise execution\ntracking:

      \n
      const ah = require('async_hooks');\nah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n
      \n

      In this example, adding any actual hook function enabled the tracking of\npromises. There are two promises in the example above; the promise created by\nPromise.resolve() and the promise returned by the call to then(). In the\nexample above, the first promise got the asyncId 6 and the latter got\nasyncId 7. During the execution of the then() callback, we are executing\nin the context of promise with asyncId 7. This promise was triggered by\nasync resource 6.

      \n

      Another subtlety with promises is that before and after callbacks are run\nonly on chained promises. That means promises not created by then()/catch()\nwill not have the before and after callbacks fired on them. For more details\nsee the details of the V8 PromiseHooks API.

      ", + "type": "module", + "displayName": "Promise execution tracking" + }, + { + "textRaw": "JavaScript embedder API", + "name": "javascript_embedder_api", + "desc": "

      Library developers that handle their own asynchronous resources performing tasks\nlike I/O, connection pooling, or managing callback queues may use the\nAsyncResource JavaScript API so that all the appropriate callbacks are called.

      ", + "classes": [ + { + "textRaw": "Class: `AsyncResource`", + "type": "class", + "name": "AsyncResource", + "desc": "

      The class AsyncResource is designed to be extended by the embedder's async\nresources. Using this, users can easily trigger the lifetime events of their\nown resources.

      \n

      The init hook will trigger when an AsyncResource is instantiated.

      \n

      The following is an overview of the AsyncResource API.

      \n
      const { AsyncResource, executionAsyncId } = require('async_hooks');\n\n// AsyncResource() is meant to be extended. Instantiating a\n// new AsyncResource() also triggers init. If triggerAsyncId is omitted then\n// async_hook.executionAsyncId() is used.\nconst asyncResource = new AsyncResource(\n  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }\n);\n\n// Run a function in the execution context of the resource. This will\n// * establish the context of the resource\n// * trigger the AsyncHooks before callbacks\n// * call the provided function `fn` with the supplied arguments\n// * trigger the AsyncHooks after callbacks\n// * restore the original execution context\nasyncResource.runInAsyncScope(fn, thisArg, ...args);\n\n// Call AsyncHooks destroy callbacks.\nasyncResource.emitDestroy();\n\n// Return the unique ID assigned to the AsyncResource instance.\nasyncResource.asyncId();\n\n// Return the trigger ID for the AsyncResource instance.\nasyncResource.triggerAsyncId();\n
      ", + "classMethods": [ + { + "textRaw": "Static method: `AsyncResource.bind(fn[, type])`", + "type": "classMethod", + "name": "bind", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} The function to bind to the current execution context.", + "name": "fn", + "type": "Function", + "desc": "The function to bind to the current execution context." + }, + { + "textRaw": "`type` {string} An optional name to associate with the underlying `AsyncResource`.", + "name": "type", + "type": "string", + "desc": "An optional name to associate with the underlying `AsyncResource`." + } + ] + } + ], + "desc": "

      Binds the given function to the current execution context.

      \n

      The returned function will have an asyncResource property referencing\nthe AsyncResource to which the function is bound.

      " + } + ], + "methods": [ + { + "textRaw": "`asyncResource.bind(fn)`", + "type": "method", + "name": "bind", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} The function to bind to the current `AsyncResource`.", + "name": "fn", + "type": "Function", + "desc": "The function to bind to the current `AsyncResource`." + } + ] + } + ], + "desc": "

      Binds the given function to execute to this AsyncResource's scope.

      \n

      The returned function will have an asyncResource property referencing\nthe AsyncResource to which the function is bound.

      " + }, + { + "textRaw": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`", + "type": "method", + "name": "runInAsyncScope", + "meta": { + "added": [ + "v9.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} The function to call in the execution context of this async resource.", + "name": "fn", + "type": "Function", + "desc": "The function to call in the execution context of this async resource." + }, + { + "textRaw": "`thisArg` {any} The receiver to be used for the function call.", + "name": "thisArg", + "type": "any", + "desc": "The receiver to be used for the function call." + }, + { + "textRaw": "`...args` {any} Optional arguments to pass to the function.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass to the function." + } + ] + } + ], + "desc": "

      Call the provided function with the provided arguments in the execution context\nof the async resource. This will establish the context, trigger the AsyncHooks\nbefore callbacks, call the function, trigger the AsyncHooks after callbacks, and\nthen restore the original execution context.

      " + }, + { + "textRaw": "`asyncResource.emitDestroy()`", + "type": "method", + "name": "emitDestroy", + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", + "name": "return", + "type": "AsyncResource", + "desc": "A reference to `asyncResource`." + }, + "params": [] + } + ], + "desc": "

      Call all destroy hooks. This should only ever be called once. An error will\nbe thrown if it is called more than once. This must be manually called. If\nthe resource is left to be collected by the GC then the destroy hooks will\nnever be called.

      " + }, + { + "textRaw": "`asyncResource.asyncId()`", + "type": "method", + "name": "asyncId", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The unique `asyncId` assigned to the resource.", + "name": "return", + "type": "number", + "desc": "The unique `asyncId` assigned to the resource." + }, + "params": [] + } + ] + }, + { + "textRaw": "`asyncResource.triggerAsyncId()`", + "type": "method", + "name": "triggerAsyncId", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.", + "name": "return", + "type": "number", + "desc": "The same `triggerAsyncId` that is passed to the `AsyncResource` constructor." + }, + "params": [] + } + ], + "desc": "

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`type` {string} The type of async event.", + "name": "type", + "type": "string", + "desc": "The type of async event." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`triggerAsyncId` {number} The ID of the execution context that created this async event. **Default:** `executionAsyncId()`.", + "name": "triggerAsyncId", + "type": "number", + "default": "`executionAsyncId()`", + "desc": "The ID of the execution context that created this async event." + }, + { + "textRaw": "`requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if `emitDestroy` is called manually), unless the resource's `asyncId` is retrieved and the sensitive API's `emitDestroy` is called with it. When set to `false`, the `emitDestroy` call on garbage collection will only take place if there is at least one active `destroy` hook. **Default:** `false`.", + "name": "requireManualDestroy", + "type": "boolean", + "default": "`false`", + "desc": "If set to `true`, disables `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if `emitDestroy` is called manually), unless the resource's `asyncId` is retrieved and the sensitive API's `emitDestroy` is called with it. When set to `false`, the `emitDestroy` call on garbage collection will only take place if there is at least one active `destroy` hook." + } + ] + } + ], + "desc": "

      Example usage:

      \n
      class DBQuery extends AsyncResource {\n  constructor(db) {\n    super('DBQuery');\n    this.db = db;\n  }\n\n  getInfo(query, callback) {\n    this.db.get(query, (err, data) => {\n      this.runInAsyncScope(callback, null, err, data);\n    });\n  }\n\n  close() {\n    this.db = null;\n    this.emitDestroy();\n  }\n}\n
      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Using `AsyncResource` for a `Worker` thread pool", + "name": "using_`asyncresource`_for_a_`worker`_thread_pool", + "desc": "

      The following example shows how to use the AsyncResource class to properly\nprovide async tracking for a Worker pool. Other resource pools, such as\ndatabase connection pools, can follow a similar model.

      \n

      Assuming that the task is adding two numbers, using a file named\ntask_processor.js with the following content:

      \n
      const { parentPort } = require('worker_threads');\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
      \n

      a Worker pool around it could use the following structure:

      \n
      const { AsyncResource } = require('async_hooks');\nconst { EventEmitter } = require('events');\nconst path = require('path');\nconst { Worker } = require('worker_threads');\n\nconst kTaskInfo = Symbol('kTaskInfo');\nconst kWorkerFreedEvent = Symbol('kWorkerFreedEvent');\n\nclass WorkerPoolTaskInfo extends AsyncResource {\n  constructor(callback) {\n    super('WorkerPoolTaskInfo');\n    this.callback = callback;\n  }\n\n  done(err, result) {\n    this.runInAsyncScope(this.callback, null, err, result);\n    this.emitDestroy();  // `TaskInfo`s are used only once.\n  }\n}\n\nclass WorkerPool extends EventEmitter {\n  constructor(numThreads) {\n    super();\n    this.numThreads = numThreads;\n    this.workers = [];\n    this.freeWorkers = [];\n\n    for (let i = 0; i < numThreads; i++)\n      this.addNewWorker();\n  }\n\n  addNewWorker() {\n    const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));\n    worker.on('message', (result) => {\n      // In case of success: Call the callback that was passed to `runTask`,\n      // remove the `TaskInfo` associated with the Worker, and mark it as free\n      // again.\n      worker[kTaskInfo].done(null, result);\n      worker[kTaskInfo] = null;\n      this.freeWorkers.push(worker);\n      this.emit(kWorkerFreedEvent);\n    });\n    worker.on('error', (err) => {\n      // In case of an uncaught exception: Call the callback that was passed to\n      // `runTask` with the error.\n      if (worker[kTaskInfo])\n        worker[kTaskInfo].done(err, null);\n      else\n        this.emit('error', err);\n      // Remove the worker from the list and start a new Worker to replace the\n      // current one.\n      this.workers.splice(this.workers.indexOf(worker), 1);\n      this.addNewWorker();\n    });\n    this.workers.push(worker);\n    this.freeWorkers.push(worker);\n    this.emit(kWorkerFreedEvent);\n  }\n\n  runTask(task, callback) {\n    if (this.freeWorkers.length === 0) {\n      // No free threads, wait until a worker thread becomes free.\n      this.once(kWorkerFreedEvent, () => this.runTask(task, callback));\n      return;\n    }\n\n    const worker = this.freeWorkers.pop();\n    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);\n    worker.postMessage(task);\n  }\n\n  close() {\n    for (const worker of this.workers) worker.terminate();\n  }\n}\n\nmodule.exports = WorkerPool;\n
      \n

      Without the explicit tracking added by the WorkerPoolTaskInfo objects,\nit would appear that the callbacks are associated with the individual Worker\nobjects. However, the creation of the Workers is not associated with the\ncreation of the tasks and does not provide information about when tasks\nwere scheduled.

      \n

      This pool could be used as follows:

      \n
      const WorkerPool = require('./worker_pool.js');\nconst os = require('os');\n\nconst pool = new WorkerPool(os.cpus().length);\n\nlet finished = 0;\nfor (let i = 0; i < 10; i++) {\n  pool.runTask({ a: 42, b: 100 }, (err, result) => {\n    console.log(i, err, result);\n    if (++finished === 10)\n      pool.close();\n  });\n}\n
      ", + "type": "module", + "displayName": "Using `AsyncResource` for a `Worker` thread pool" + }, + { + "textRaw": "Integrating `AsyncResource` with `EventEmitter`", + "name": "integrating_`asyncresource`_with_`eventemitter`", + "desc": "

      Event listeners triggered by an EventEmitter may be run in a different\nexecution context than the one that was active when eventEmitter.on() was\ncalled.

      \n

      The following example shows how to use the AsyncResource class to properly\nassociate an event listener with the correct execution context. The same\napproach can be applied to a Stream or a similar event-driven class.

      \n
      const { createServer } = require('http');\nconst { AsyncResource, executionAsyncId } = require('async_hooks');\n\nconst server = createServer((req, res) => {\n  req.on('close', AsyncResource.bind(() => {\n    // Execution context is bound to the current outer scope.\n  }));\n  req.on('close', () => {\n    // Execution context is bound to the scope that caused 'close' to emit.\n  });\n  res.end();\n}).listen(3000);\n
      ", + "type": "module", + "displayName": "Integrating `AsyncResource` with `EventEmitter`" + } + ], + "type": "module", + "displayName": "JavaScript embedder API" + } + ], + "classes": [ + { + "textRaw": "Class: `AsyncLocalStorage`", + "type": "class", + "name": "AsyncLocalStorage", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      This class is used to create asynchronous state within callbacks and promise\nchains. It allows storing data throughout the lifetime of a web request\nor any other asynchronous duration. It is similar to thread-local storage\nin other languages.

      \n

      The following example uses AsyncLocalStorage to build a simple logger\nthat assigns IDs to incoming HTTP requests and includes them in messages\nlogged within each request.

      \n
      const http = require('http');\nconst { AsyncLocalStorage } = require('async_hooks');\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nfunction logWithId(msg) {\n  const id = asyncLocalStorage.getStore();\n  console.log(`${id !== undefined ? id : '-'}:`, msg);\n}\n\nlet idSeq = 0;\nhttp.createServer((req, res) => {\n  asyncLocalStorage.run(idSeq++, () => {\n    logWithId('start');\n    // Imagine any chain of async operations here\n    setImmediate(() => {\n      logWithId('finish');\n      res.end();\n    });\n  });\n}).listen(8080);\n\nhttp.get('http://localhost:8080');\nhttp.get('http://localhost:8080');\n// Prints:\n//   0: start\n//   1: start\n//   0: finish\n//   1: finish\n
      \n

      When having multiple instances of AsyncLocalStorage, they are independent\nfrom each other. It is safe to instantiate this class multiple times.

      ", + "methods": [ + { + "textRaw": "`asyncLocalStorage.disable()`", + "type": "method", + "name": "disable", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This method disables the instance of AsyncLocalStorage. All subsequent calls\nto asyncLocalStorage.getStore() will return undefined until\nasyncLocalStorage.run() is called again.

      \n

      When calling asyncLocalStorage.disable(), all current contexts linked to the\ninstance will be exited.

      \n

      Calling asyncLocalStorage.disable() is required before the\nasyncLocalStorage can be garbage collected. This does not apply to stores\nprovided by the asyncLocalStorage, as those objects are garbage collected\nalong with the corresponding async resources.

      \n

      This method is to be used when the asyncLocalStorage is not in use anymore\nin the current process.

      " + }, + { + "textRaw": "`asyncLocalStorage.getStore()`", + "type": "method", + "name": "getStore", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any}", + "name": "return", + "type": "any" + }, + "params": [] + } + ], + "desc": "

      This method returns the current store.\nIf this method is called outside of an asynchronous context initialized by\ncalling asyncLocalStorage.run, it will return undefined.

      " + }, + { + "textRaw": "`asyncLocalStorage.enterWith(store)`", + "type": "method", + "name": "enterWith", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`store` {any}", + "name": "store", + "type": "any" + } + ] + } + ], + "desc": "

      Calling asyncLocalStorage.enterWith(store) will transition into the context\nfor the remainder of the current synchronous execution and will persist\nthrough any following asynchronous calls.

      \n

      Example:

      \n
      const store = { id: 1 };\nasyncLocalStorage.enterWith(store);\nasyncLocalStorage.getStore(); // Returns the store object\nsomeAsyncOperation(() => {\n  asyncLocalStorage.getStore(); // Returns the same object\n});\n
      \n

      This transition will continue for the entire synchronous execution.\nThis means that if, for example, the context is entered within an event\nhandler subsequent event handlers will also run within that context unless\nspecifically bound to another context with an AsyncResource.

      \n
      const store = { id: 1 };\n\nemitter.on('my-event', () => {\n  asyncLocalStorage.enterWith(store);\n});\nemitter.on('my-event', () => {\n  asyncLocalStorage.getStore(); // Returns the same object\n});\n\nasyncLocalStorage.getStore(); // Returns undefined\nemitter.emit('my-event');\nasyncLocalStorage.getStore(); // Returns the same object\n
      " + }, + { + "textRaw": "`asyncLocalStorage.run(store, callback[, ...args])`", + "type": "method", + "name": "run", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`store` {any}", + "name": "store", + "type": "any" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      This methods runs a function synchronously within a context and return its\nreturn value. The store is not accessible outside of the callback function or\nthe asynchronous operations created within the callback.

      \n

      Optionally, arguments can be passed to the function. They will be passed to\nthe callback function.

      \n

      If the callback function throws an error, it will be thrown by run too.\nThe stacktrace will not be impacted by this call and the context will\nbe exited.

      \n

      Example:

      \n
      const store = { id: 2 };\ntry {\n  asyncLocalStorage.run(store, () => {\n    asyncLocalStorage.getStore(); // Returns the store object\n    throw new Error();\n  });\n} catch (e) {\n  asyncLocalStorage.getStore(); // Returns undefined\n  // The error will be caught here\n}\n
      " + }, + { + "textRaw": "`asyncLocalStorage.exit(callback[, ...args])`", + "type": "method", + "name": "exit", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      This methods runs a function synchronously outside of a context and return its\nreturn value. The store is not accessible within the callback function or\nthe asynchronous operations created within the callback.

      \n

      Optionally, arguments can be passed to the function. They will be passed to\nthe callback function.

      \n

      If the callback function throws an error, it will be thrown by exit too.\nThe stacktrace will not be impacted by this call and\nthe context will be re-entered.

      \n

      Example:

      \n
      // Within a call to run\ntry {\n  asyncLocalStorage.getStore(); // Returns the store object or value\n  asyncLocalStorage.exit(() => {\n    asyncLocalStorage.getStore(); // Returns undefined\n    throw new Error();\n  });\n} catch (e) {\n  asyncLocalStorage.getStore(); // Returns the same object or value\n  // The error will be caught here\n}\n
      " + } + ], + "modules": [ + { + "textRaw": "Usage with `async/await`", + "name": "usage_with_`async/await`", + "desc": "

      If, within an async function, only one await call is to run within a context,\nthe following pattern should be used:

      \n
      async function fn() {\n  await asyncLocalStorage.run(new Map(), () => {\n    asyncLocalStorage.getStore().set('key', value);\n    return foo(); // The return value of foo will be awaited\n  });\n}\n
      \n

      In this example, the store is only available in the callback function and the\nfunctions called by foo. Outside of run, calling getStore will return\nundefined.

      ", + "type": "module", + "displayName": "Usage with `async/await`" + }, + { + "textRaw": "Troubleshooting", + "name": "troubleshooting", + "desc": "

      In most cases your application or library code should have no issues with\nAsyncLocalStorage. But in rare cases you may face situations when the\ncurrent store is lost in one of asynchronous operations. In those cases,\nconsider the following options.

      \n

      If your code is callback-based, it is enough to promisify it with\nutil.promisify(), so it starts working with native promises.

      \n

      If you need to keep using callback-based API, or your code assumes\na custom thenable implementation, use the AsyncResource class\nto associate the asynchronous operation with the correct execution context.

      ", + "type": "module", + "displayName": "Troubleshooting" + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Creates a new instance of AsyncLocalStorage. Store is only provided within a\nrun method call.

      " + } + ] + } + ], + "type": "module", + "displayName": "Async hooks" + } + ] +} \ No newline at end of file diff --git a/doc/api/buffer.html b/doc/api/buffer.html new file mode 100644 index 0000000000000000000000000000000000000000..a61f5d495806f1eaa25139f596fb50c6a7a7bd79 --- /dev/null +++ b/doc/api/buffer.html @@ -0,0 +1,3167 @@ + + + + + + + Buffer | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Buffer#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/buffer.js

      +

      Buffer objects are used to represent a fixed-length sequence of bytes. Many +Node.js APIs support Buffers.

      +

      The Buffer class is a subclass of JavaScript's Uint8Array class and +extends it with methods that cover additional use cases. Node.js APIs accept +plain Uint8Arrays wherever Buffers are supported as well.

      +

      The Buffer class is within the global scope, making it unlikely that one +would need to ever use require('buffer').Buffer.

      +
      // Creates a zero-filled Buffer of length 10.
      +const buf1 = Buffer.alloc(10);
      +
      +// Creates a Buffer of length 10,
      +// filled with bytes which all have the value `1`.
      +const buf2 = Buffer.alloc(10, 1);
      +
      +// Creates an uninitialized buffer of length 10.
      +// This is faster than calling Buffer.alloc() but the returned
      +// Buffer instance might contain old data that needs to be
      +// overwritten using fill(), write(), or other functions that fill the Buffer's
      +// contents.
      +const buf3 = Buffer.allocUnsafe(10);
      +
      +// Creates a Buffer containing the bytes [1, 2, 3].
      +const buf4 = Buffer.from([1, 2, 3]);
      +
      +// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
      +// are all truncated using `(value & 255)` to fit into the range 0–255.
      +const buf5 = Buffer.from([257, 257.5, -255, '1']);
      +
      +// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
      +// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
      +// [116, 195, 169, 115, 116] (in decimal notation)
      +const buf6 = Buffer.from('tést');
      +
      +// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
      +const buf7 = Buffer.from('tést', 'latin1');
      +

      Buffers and character encodings#

      + +

      When converting between Buffers and strings, a character encoding may be +specified. If no character encoding is specified, UTF-8 will be used as the +default.

      +
      const buf = Buffer.from('hello world', 'utf8');
      +
      +console.log(buf.toString('hex'));
      +// Prints: 68656c6c6f20776f726c64
      +console.log(buf.toString('base64'));
      +// Prints: aGVsbG8gd29ybGQ=
      +
      +console.log(Buffer.from('fhqwhgads', 'utf8'));
      +// Prints: <Buffer 66 68 71 77 68 67 61 64 73>
      +console.log(Buffer.from('fhqwhgads', 'utf16le'));
      +// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>
      +

      The character encodings currently supported by Node.js are the following:

      +
        +
      • +

        'utf8': Multi-byte encoded Unicode characters. Many web pages and other +document formats use UTF-8. This is the default character encoding. +When decoding a Buffer into a string that does not exclusively contain +valid UTF-8 data, the Unicode replacement character U+FFFD � will be used +to represent those errors.

        +
      • +
      • +

        'utf16le': Multi-byte encoded Unicode characters. Unlike 'utf8', each +character in the string will be encoded using either 2 or 4 bytes. +Node.js only supports the little-endian variant of UTF-16.

        +
      • +
      • +

        'latin1': Latin-1 stands for ISO-8859-1. This character encoding only +supports the Unicode characters from U+0000 to U+00FF. Each character is +encoded using a single byte. Characters that do not fit into that range are +truncated and will be mapped to characters in that range.

        +
      • +
      +

      Converting a Buffer into a string using one of the above is referred to as +decoding, and converting a string into a Buffer is referred to as encoding.

      +

      Node.js also supports the following two binary-to-text encodings. For +binary-to-text encodings, the naming convention is reversed: Converting a +Buffer into a string is typically referred to as encoding, and converting a +string into a Buffer as decoding.

      +
        +
      • +

        'base64': Base64 encoding. When creating a Buffer from a string, +this encoding will also correctly accept "URL and Filename Safe Alphabet" as +specified in RFC 4648, Section 5. Whitespace characters such as spaces, +tabs, and new lines contained within the base64-encoded string are ignored.

        +
      • +
      • +

        'hex': Encode each byte as two hexadecimal characters. Data truncation +may occur when decoding strings that do exclusively contain valid hexadecimal +characters. See below for an example.

        +
      • +
      +

      The following legacy character encodings are also supported:

      +
        +
      • +

        'ascii': For 7-bit ASCII data only. When encoding a string into a +Buffer, this is equivalent to using 'latin1'. When decoding a Buffer +into a string, using this encoding will additionally unset the highest bit of +each byte before decoding as 'latin1'. +Generally, there should be no reason to use this encoding, as 'utf8' +(or, if the data is known to always be ASCII-only, 'latin1') will be a +better choice when encoding or decoding ASCII-only text. It is only provided +for legacy compatibility.

        +
      • +
      • +

        'binary': Alias for 'latin1'. See binary strings for more background +on this topic. The name of this encoding can be very misleading, as all of the +encodings listed here convert between strings and binary data. For converting +between strings and Buffers, typically 'utf-8' is the right choice.

        +
      • +
      • +

        'ucs2': Alias of 'utf16le'. UCS-2 used to refer to a variant of UTF-16 +that did not support characters that had code points larger than U+FFFF. +In Node.js, these code points are always supported.

        +
      • +
      +
      Buffer.from('1ag', 'hex');
      +// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
      +// ('g') encountered.
      +
      +Buffer.from('1a7g', 'hex');
      +// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
      +
      +Buffer.from('1634', 'hex');
      +// Prints <Buffer 16 34>, all data represented.
      +

      Modern Web browsers follow the WHATWG Encoding Standard which aliases +both 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing +something like http.get(), if the returned charset is one of those listed in +the WHATWG specification it is possible that the server actually returned +'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode +the characters.

      +

      Buffers and TypedArrays#

      + +

      Buffer instances are also JavaScript Uint8Array and TypedArray +instances. All TypedArray methods are available on Buffers. There are, +however, subtle incompatibilities between the Buffer API and the +TypedArray API.

      +

      In particular:

      +
        +
      • While TypedArray#slice() creates a copy of part of the TypedArray, +Buffer#slice() creates a view over the existing Buffer +without copying. This behavior can be surprising, and only exists for legacy +compatibility. TypedArray#subarray() can be used to achieve the behavior +of Buffer#slice() on both Buffers and other +TypedArrays.
      • +
      • buf.toString() is incompatible with its TypedArray equivalent.
      • +
      • A number of methods, e.g. buf.indexOf(), support additional arguments.
      • +
      +

      There are two ways to create new TypedArray instances from a Buffer:

      +
        +
      • Passing a Buffer to a TypedArray constructor will copy the Buffers +contents, interpreted as an array of integers, and not as a byte sequence +of the target type.
      • +
      +
      const buf = Buffer.from([1, 2, 3, 4]);
      +const uint32array = new Uint32Array(buf);
      +
      +console.log(uint32array);
      +
      +// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
      +
        +
      • Passing the Buffers underlying ArrayBuffer will create a +TypedArray that shares its memory with the Buffer.
      • +
      +
      const buf = Buffer.from('hello', 'utf16le');
      +const uint16arr = new Uint16Array(
      +  buf.buffer,
      +  buf.byteOffset,
      +  buf.length / Uint16Array.BYTES_PER_ELEMENT);
      +
      +console.log(uint16array);
      +
      +// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
      +

      It is possible to create a new Buffer that shares the same allocated +memory as a TypedArray instance by using the TypedArray object’s +.buffer property in the same way. Buffer.from() +behaves like new Uint8Array() in this context.

      +
      const arr = new Uint16Array(2);
      +
      +arr[0] = 5000;
      +arr[1] = 4000;
      +
      +// Copies the contents of `arr`.
      +const buf1 = Buffer.from(arr);
      +
      +// Shares memory with `arr`.
      +const buf2 = Buffer.from(arr.buffer);
      +
      +console.log(buf1);
      +// Prints: <Buffer 88 a0>
      +console.log(buf2);
      +// Prints: <Buffer 88 13 a0 0f>
      +
      +arr[1] = 6000;
      +
      +console.log(buf1);
      +// Prints: <Buffer 88 a0>
      +console.log(buf2);
      +// Prints: <Buffer 88 13 70 17>
      +

      When creating a Buffer using a TypedArray's .buffer, it is +possible to use only a portion of the underlying ArrayBuffer by passing in +byteOffset and length parameters.

      +
      const arr = new Uint16Array(20);
      +const buf = Buffer.from(arr.buffer, 0, 16);
      +
      +console.log(buf.length);
      +// Prints: 16
      +

      The Buffer.from() and TypedArray.from() have different signatures and +implementations. Specifically, the TypedArray variants accept a second +argument that is a mapping function that is invoked on every element of the +typed array:

      +
        +
      • TypedArray.from(source[, mapFn[, thisArg]])
      • +
      +

      The Buffer.from() method, however, does not support the use of a mapping +function:

      + +

      Buffers and iteration#

      +

      Buffer instances can be iterated over using for..of syntax:

      +
      const buf = Buffer.from([1, 2, 3]);
      +
      +for (const b of buf) {
      +  console.log(b);
      +}
      +// Prints:
      +//   1
      +//   2
      +//   3
      +

      Additionally, the buf.values(), buf.keys(), and +buf.entries() methods can be used to create iterators.

      +

      Class: Buffer#

      +

      The Buffer class is a global type for dealing with binary data directly. +It can be constructed in a variety of ways.

      +

      Static method: Buffer.alloc(size[, fill[, encoding]])#

      + + +

      Allocates a new Buffer of size bytes. If fill is undefined, the +Buffer will be zero-filled.

      +
      const buf = Buffer.alloc(5);
      +
      +console.log(buf);
      +// Prints: <Buffer 00 00 00 00 00>
      +

      If size is larger than +buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE +is thrown.

      +

      If fill is specified, the allocated Buffer will be initialized by calling +buf.fill(fill).

      +
      const buf = Buffer.alloc(5, 'a');
      +
      +console.log(buf);
      +// Prints: <Buffer 61 61 61 61 61>
      +

      If both fill and encoding are specified, the allocated Buffer will be +initialized by calling buf.fill(fill, encoding).

      +
      const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
      +
      +console.log(buf);
      +// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
      +

      Calling Buffer.alloc() can be measurably slower than the alternative +Buffer.allocUnsafe() but ensures that the newly created Buffer instance +contents will never contain sensitive data from previous allocations, including +data that might not have been allocated for Buffers.

      +

      A TypeError will be thrown if size is not a number.

      +

      Static method: Buffer.allocUnsafe(size)#

      + +
        +
      • size <integer> The desired length of the new Buffer.
      • +
      +

      Allocates a new Buffer of size bytes. If size is larger than +buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE +is thrown.

      +

      The underlying memory for Buffer instances created in this way is not +initialized. The contents of the newly created Buffer are unknown and +may contain sensitive data. Use Buffer.alloc() instead to initialize +Buffer instances with zeroes.

      +
      const buf = Buffer.allocUnsafe(10);
      +
      +console.log(buf);
      +// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
      +
      +buf.fill(0);
      +
      +console.log(buf);
      +// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
      +

      A TypeError will be thrown if size is not a number.

      +

      The Buffer module pre-allocates an internal Buffer instance of +size Buffer.poolSize that is used as a pool for the fast allocation of new +Buffer instances created using Buffer.allocUnsafe(), +Buffer.from(array), Buffer.concat(), and the deprecated +new Buffer(size) constructor only when size is less than or equal +to Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).

      +

      Use of this pre-allocated internal memory pool is a key difference between +calling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill). +Specifically, Buffer.alloc(size, fill) will never use the internal Buffer +pool, while Buffer.allocUnsafe(size).fill(fill) will use the internal +Buffer pool if size is less than or equal to half Buffer.poolSize. The +difference is subtle but can be important when an application requires the +additional performance that Buffer.allocUnsafe() provides.

      +

      Static method: Buffer.allocUnsafeSlow(size)#

      + +
        +
      • size <integer> The desired length of the new Buffer.
      • +
      +

      Allocates a new Buffer of size bytes. If size is larger than +buffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE +is thrown. A zero-length Buffer is created if size is 0.

      +

      The underlying memory for Buffer instances created in this way is not +initialized. The contents of the newly created Buffer are unknown and +may contain sensitive data. Use buf.fill(0) to initialize +such Buffer instances with zeroes.

      +

      When using Buffer.allocUnsafe() to allocate new Buffer instances, +allocations under 4KB are sliced from a single pre-allocated Buffer. This +allows applications to avoid the garbage collection overhead of creating many +individually allocated Buffer instances. This approach improves both +performance and memory usage by eliminating the need to track and clean up as +many individual ArrayBuffer objects.

      +

      However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and +then copying out the relevant bits.

      +
      // Need to keep around a few small chunks of memory.
      +const store = [];
      +
      +socket.on('readable', () => {
      +  let data;
      +  while (null !== (data = readable.read())) {
      +    // Allocate for retained data.
      +    const sb = Buffer.allocUnsafeSlow(10);
      +
      +    // Copy the data into the new allocation.
      +    data.copy(sb, 0, 0, 10);
      +
      +    store.push(sb);
      +  }
      +});
      +

      A TypeError will be thrown if size is not a number.

      +

      Static method: Buffer.byteLength(string[, encoding])#

      + + +

      Returns the byte length of a string when encoded using encoding. +This is not the same as String.prototype.length, which does not account +for the encoding that is used to convert the string into bytes.

      +

      For 'base64' and 'hex', this function assumes valid input. For strings that +contain non-base64/hex-encoded data (e.g. whitespace), the return value might be +greater than the length of a Buffer created from the string.

      +
      const str = '\u00bd + \u00bc = \u00be';
      +
      +console.log(`${str}: ${str.length} characters, ` +
      +            `${Buffer.byteLength(str, 'utf8')} bytes`);
      +// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
      +

      When string is a Buffer/DataView/TypedArray/ArrayBuffer/ +SharedArrayBuffer, the byte length as reported by .byteLength +is returned.

      +

      Static method: Buffer.compare(buf1, buf2)#

      + + +

      Compares buf1 to buf2, typically for the purpose of sorting arrays of +Buffer instances. This is equivalent to calling +buf1.compare(buf2).

      +
      const buf1 = Buffer.from('1234');
      +const buf2 = Buffer.from('0123');
      +const arr = [buf1, buf2];
      +
      +console.log(arr.sort(Buffer.compare));
      +// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
      +// (This result is equal to: [buf2, buf1].)
      +

      Static method: Buffer.concat(list[, totalLength])#

      + + +

      Returns a new Buffer which is the result of concatenating all the Buffer +instances in the list together.

      +

      If the list has no items, or if the totalLength is 0, then a new zero-length +Buffer is returned.

      +

      If totalLength is not provided, it is calculated from the Buffer instances +in list by adding their lengths.

      +

      If totalLength is provided, it is coerced to an unsigned integer. If the +combined length of the Buffers in list exceeds totalLength, the result is +truncated to totalLength.

      +
      // Create a single `Buffer` from a list of three `Buffer` instances.
      +
      +const buf1 = Buffer.alloc(10);
      +const buf2 = Buffer.alloc(14);
      +const buf3 = Buffer.alloc(18);
      +const totalLength = buf1.length + buf2.length + buf3.length;
      +
      +console.log(totalLength);
      +// Prints: 42
      +
      +const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
      +
      +console.log(bufA);
      +// Prints: <Buffer 00 00 00 00 ...>
      +console.log(bufA.length);
      +// Prints: 42
      +

      Buffer.concat() may also use the internal Buffer pool like +Buffer.allocUnsafe() does.

      +

      Static method: Buffer.from(array)#

      + + +

      Allocates a new Buffer using an array of bytes in the range 0 – 255. +Array entries outside that range will be truncated to fit into it.

      +
      // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
      +const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
      +

      A TypeError will be thrown if array is not an Array or another type +appropriate for Buffer.from() variants.

      +

      Buffer.from(array) and Buffer.from(string) may also use the internal +Buffer pool like Buffer.allocUnsafe() does.

      +

      Static method: Buffer.from(arrayBuffer[, byteOffset[, length]])#

      + + +

      This creates a view of the ArrayBuffer without copying the underlying +memory. For example, when passed a reference to the .buffer property of a +TypedArray instance, the newly created Buffer will share the same +allocated memory as the TypedArray.

      +
      const arr = new Uint16Array(2);
      +
      +arr[0] = 5000;
      +arr[1] = 4000;
      +
      +// Shares memory with `arr`.
      +const buf = Buffer.from(arr.buffer);
      +
      +console.log(buf);
      +// Prints: <Buffer 88 13 a0 0f>
      +
      +// Changing the original Uint16Array changes the Buffer also.
      +arr[1] = 6000;
      +
      +console.log(buf);
      +// Prints: <Buffer 88 13 70 17>
      +

      The optional byteOffset and length arguments specify a memory range within +the arrayBuffer that will be shared by the Buffer.

      +
      const ab = new ArrayBuffer(10);
      +const buf = Buffer.from(ab, 0, 2);
      +
      +console.log(buf.length);
      +// Prints: 2
      +

      A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a +SharedArrayBuffer or another type appropriate for Buffer.from() +variants.

      +

      Static method: Buffer.from(buffer)#

      + + +

      Copies the passed buffer data onto a new Buffer instance.

      +
      const buf1 = Buffer.from('buffer');
      +const buf2 = Buffer.from(buf1);
      +
      +buf1[0] = 0x61;
      +
      +console.log(buf1.toString());
      +// Prints: auffer
      +console.log(buf2.toString());
      +// Prints: buffer
      +

      A TypeError will be thrown if buffer is not a Buffer or another type +appropriate for Buffer.from() variants.

      +

      Static method: Buffer.from(object[, offsetOrEncoding[, length]])#

      + + +

      For objects whose valueOf() function returns a value not strictly equal to +object, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

      +
      const buf = Buffer.from(new String('this is a test'));
      +// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
      +

      For objects that support Symbol.toPrimitive, returns +Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).

      +
      class Foo {
      +  [Symbol.toPrimitive]() {
      +    return 'this is a test';
      +  }
      +}
      +
      +const buf = Buffer.from(new Foo(), 'utf8');
      +// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
      +

      A TypeError will be thrown if object does not have the mentioned methods or +is not of another type appropriate for Buffer.from() variants.

      +

      Static method: Buffer.from(string[, encoding])#

      + +
        +
      • string <string> A string to encode.
      • +
      • encoding <string> The encoding of string. Default: 'utf8'.
      • +
      +

      Creates a new Buffer containing string. The encoding parameter identifies +the character encoding to be used when converting string into bytes.

      +
      const buf1 = Buffer.from('this is a tést');
      +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
      +
      +console.log(buf1.toString());
      +// Prints: this is a tést
      +console.log(buf2.toString());
      +// Prints: this is a tést
      +console.log(buf1.toString('latin1'));
      +// Prints: this is a tést
      +

      A TypeError will be thrown if string is not a string or another type +appropriate for Buffer.from() variants.

      +

      Static method: Buffer.isBuffer(obj)#

      + + +

      Returns true if obj is a Buffer, false otherwise.

      +

      Static method: Buffer.isEncoding(encoding)#

      + + +

      Returns true if encoding is the name of a supported character encoding, +or false otherwise.

      +
      console.log(Buffer.isEncoding('utf-8'));
      +// Prints: true
      +
      +console.log(Buffer.isEncoding('hex'));
      +// Prints: true
      +
      +console.log(Buffer.isEncoding('utf/8'));
      +// Prints: false
      +
      +console.log(Buffer.isEncoding(''));
      +// Prints: false
      +

      Class property: Buffer.poolSize#

      + + +

      This is the size (in bytes) of pre-allocated internal Buffer instances used +for pooling. This value may be modified.

      +

      buf[index]#

      + + +

      The index operator [index] can be used to get and set the octet at position +index in buf. The values refer to individual bytes, so the legal value +range is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).

      +

      This operator is inherited from Uint8Array, so its behavior on out-of-bounds +access is the same as Uint8Array. In other words, buf[index] returns +undefined when index is negative or greater or equal to buf.length, and +buf[index] = value does not modify the buffer if index is negative or +>= buf.length.

      +
      // Copy an ASCII string into a `Buffer` one byte at a time.
      +// (This only works for ASCII-only strings. In general, one should use
      +// `Buffer.from()` to perform this conversion.)
      +
      +const str = 'Node.js';
      +const buf = Buffer.allocUnsafe(str.length);
      +
      +for (let i = 0; i < str.length; i++) {
      +  buf[i] = str.charCodeAt(i);
      +}
      +
      +console.log(buf.toString('utf8'));
      +// Prints: Node.js
      +

      buf.buffer#

      +
        +
      • <ArrayBuffer> The underlying ArrayBuffer object based on which this Buffer +object is created.
      • +
      +

      This ArrayBuffer is not guaranteed to correspond exactly to the original +Buffer. See the notes on buf.byteOffset for details.

      +
      const arrayBuffer = new ArrayBuffer(16);
      +const buffer = Buffer.from(arrayBuffer);
      +
      +console.log(buffer.buffer === arrayBuffer);
      +// Prints: true
      +

      buf.byteOffset#

      +
        +
      • <integer> The byteOffset of the Buffers underlying ArrayBuffer object.
      • +
      +

      When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length), +or sometimes when allocating a Buffer smaller than Buffer.poolSize, the +buffer does not start from a zero offset on the underlying ArrayBuffer.

      +

      This can cause problems when accessing the underlying ArrayBuffer directly +using buf.buffer, as other parts of the ArrayBuffer may be unrelated +to the Buffer object itself.

      +

      A common issue when creating a TypedArray object that shares its memory with +a Buffer is that in this case one needs to specify the byteOffset correctly:

      +
      // Create a buffer smaller than `Buffer.poolSize`.
      +const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
      +
      +// When casting the Node.js Buffer to an Int8Array, use the byteOffset
      +// to refer only to the part of `nodeBuffer.buffer` that contains the memory
      +// for `nodeBuffer`.
      +new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
      +

      buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])#

      + +
        +
      • target <Buffer> | <Uint8Array> A Buffer or Uint8Array with which to +compare buf.
      • +
      • targetStart <integer> The offset within target at which to begin +comparison. Default: 0.
      • +
      • targetEnd <integer> The offset within target at which to end comparison +(not inclusive). Default: target.length.
      • +
      • sourceStart <integer> The offset within buf at which to begin comparison. +Default: 0.
      • +
      • sourceEnd <integer> The offset within buf at which to end comparison +(not inclusive). Default: buf.length.
      • +
      • Returns: <integer>
      • +
      +

      Compares buf with target and returns a number indicating whether buf +comes before, after, or is the same as target in sort order. +Comparison is based on the actual sequence of bytes in each Buffer.

      +
        +
      • 0 is returned if target is the same as buf
      • +
      • 1 is returned if target should come before buf when sorted.
      • +
      • -1 is returned if target should come after buf when sorted.
      • +
      +
      const buf1 = Buffer.from('ABC');
      +const buf2 = Buffer.from('BCD');
      +const buf3 = Buffer.from('ABCD');
      +
      +console.log(buf1.compare(buf1));
      +// Prints: 0
      +console.log(buf1.compare(buf2));
      +// Prints: -1
      +console.log(buf1.compare(buf3));
      +// Prints: -1
      +console.log(buf2.compare(buf1));
      +// Prints: 1
      +console.log(buf2.compare(buf3));
      +// Prints: 1
      +console.log([buf1, buf2, buf3].sort(Buffer.compare));
      +// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
      +// (This result is equal to: [buf1, buf3, buf2].)
      +

      The optional targetStart, targetEnd, sourceStart, and sourceEnd +arguments can be used to limit the comparison to specific ranges within target +and buf respectively.

      +
      const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
      +const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
      +
      +console.log(buf1.compare(buf2, 5, 9, 0, 4));
      +// Prints: 0
      +console.log(buf1.compare(buf2, 0, 6, 4));
      +// Prints: -1
      +console.log(buf1.compare(buf2, 5, 6, 5));
      +// Prints: 1
      +

      ERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0, +targetEnd > target.byteLength, or sourceEnd > source.byteLength.

      +

      buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])#

      + +
        +
      • target <Buffer> | <Uint8Array> A Buffer or Uint8Array to copy into.
      • +
      • targetStart <integer> The offset within target at which to begin +writing. Default: 0.
      • +
      • sourceStart <integer> The offset within buf from which to begin copying. +Default: 0.
      • +
      • sourceEnd <integer> The offset within buf at which to stop copying (not +inclusive). Default: buf.length.
      • +
      • Returns: <integer> The number of bytes copied.
      • +
      +

      Copies data from a region of buf to a region in target, even if the target +memory region overlaps with buf.

      +

      TypedArray#set() performs the same operation, and is available for all +TypedArrays, including Node.js Buffers, although it takes different +function arguments.

      +
      // Create two `Buffer` instances.
      +const buf1 = Buffer.allocUnsafe(26);
      +const buf2 = Buffer.allocUnsafe(26).fill('!');
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf1[i] = i + 97;
      +}
      +
      +// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
      +buf1.copy(buf2, 8, 16, 20);
      +// This is equivalent to:
      +// buf2.set(buf1.subarray(16, 20), 8);
      +
      +console.log(buf2.toString('ascii', 0, 25));
      +// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
      +
      // Create a `Buffer` and copy data from one region to an overlapping region
      +// within the same `Buffer`.
      +
      +const buf = Buffer.allocUnsafe(26);
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf[i] = i + 97;
      +}
      +
      +buf.copy(buf, 0, 4, 10);
      +
      +console.log(buf.toString());
      +// Prints: efghijghijklmnopqrstuvwxyz
      +

      buf.entries()#

      + + +

      Creates and returns an iterator of [index, byte] pairs from the contents +of buf.

      +
      // Log the entire contents of a `Buffer`.
      +
      +const buf = Buffer.from('buffer');
      +
      +for (const pair of buf.entries()) {
      +  console.log(pair);
      +}
      +// Prints:
      +//   [0, 98]
      +//   [1, 117]
      +//   [2, 102]
      +//   [3, 102]
      +//   [4, 101]
      +//   [5, 114]
      +

      buf.equals(otherBuffer)#

      + + +

      Returns true if both buf and otherBuffer have exactly the same bytes, +false otherwise. Equivalent to +buf.compare(otherBuffer) === 0.

      +
      const buf1 = Buffer.from('ABC');
      +const buf2 = Buffer.from('414243', 'hex');
      +const buf3 = Buffer.from('ABCD');
      +
      +console.log(buf1.equals(buf2));
      +// Prints: true
      +console.log(buf1.equals(buf3));
      +// Prints: false
      +

      buf.fill(value[, offset[, end]][, encoding])#

      + + +

      Fills buf with the specified value. If the offset and end are not given, +the entire buf will be filled:

      +
      // Fill a `Buffer` with the ASCII character 'h'.
      +
      +const b = Buffer.allocUnsafe(50).fill('h');
      +
      +console.log(b.toString());
      +// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
      +

      value is coerced to a uint32 value if it is not a string, Buffer, or +integer. If the resulting integer is greater than 255 (decimal), buf will be +filled with value & 255.

      +

      If the final write of a fill() operation falls on a multi-byte character, +then only the bytes of that character that fit into buf are written:

      +
      // Fill a `Buffer` with character that takes up two bytes in UTF-8.
      +
      +console.log(Buffer.allocUnsafe(5).fill('\u0222'));
      +// Prints: <Buffer c8 a2 c8 a2 c8>
      +

      If value contains invalid characters, it is truncated; if no valid +fill data remains, an exception is thrown:

      +
      const buf = Buffer.allocUnsafe(5);
      +
      +console.log(buf.fill('a'));
      +// Prints: <Buffer 61 61 61 61 61>
      +console.log(buf.fill('aazz', 'hex'));
      +// Prints: <Buffer aa aa aa aa aa>
      +console.log(buf.fill('zz', 'hex'));
      +// Throws an exception.
      +

      buf.includes(value[, byteOffset][, encoding])#

      + +
        +
      • value <string> | <Buffer> | <Uint8Array> | <integer> What to search for.
      • +
      • byteOffset <integer> Where to begin searching in buf. If negative, then +offset is calculated from the end of buf. Default: 0.
      • +
      • encoding <string> If value is a string, this is its encoding. +Default: 'utf8'.
      • +
      • Returns: <boolean> true if value was found in buf, false otherwise.
      • +
      +

      Equivalent to buf.indexOf() !== -1.

      +
      const buf = Buffer.from('this is a buffer');
      +
      +console.log(buf.includes('this'));
      +// Prints: true
      +console.log(buf.includes('is'));
      +// Prints: true
      +console.log(buf.includes(Buffer.from('a buffer')));
      +// Prints: true
      +console.log(buf.includes(97));
      +// Prints: true (97 is the decimal ASCII value for 'a')
      +console.log(buf.includes(Buffer.from('a buffer example')));
      +// Prints: false
      +console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
      +// Prints: true
      +console.log(buf.includes('this', 4));
      +// Prints: false
      +

      buf.indexOf(value[, byteOffset][, encoding])#

      + +
        +
      • value <string> | <Buffer> | <Uint8Array> | <integer> What to search for.
      • +
      • byteOffset <integer> Where to begin searching in buf. If negative, then +offset is calculated from the end of buf. Default: 0.
      • +
      • encoding <string> If value is a string, this is the encoding used to +determine the binary representation of the string that will be searched for in +buf. Default: 'utf8'.
      • +
      • Returns: <integer> The index of the first occurrence of value in buf, or +-1 if buf does not contain value.
      • +
      +

      If value is:

      +
        +
      • a string, value is interpreted according to the character encoding in +encoding.
      • +
      • a Buffer or Uint8Array, value will be used in its entirety. +To compare a partial Buffer, use buf.slice().
      • +
      • a number, value will be interpreted as an unsigned 8-bit integer +value between 0 and 255.
      • +
      +
      const buf = Buffer.from('this is a buffer');
      +
      +console.log(buf.indexOf('this'));
      +// Prints: 0
      +console.log(buf.indexOf('is'));
      +// Prints: 2
      +console.log(buf.indexOf(Buffer.from('a buffer')));
      +// Prints: 8
      +console.log(buf.indexOf(97));
      +// Prints: 8 (97 is the decimal ASCII value for 'a')
      +console.log(buf.indexOf(Buffer.from('a buffer example')));
      +// Prints: -1
      +console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
      +// Prints: 8
      +
      +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
      +
      +console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
      +// Prints: 4
      +console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
      +// Prints: 6
      +

      If value is not a string, number, or Buffer, this method will throw a +TypeError. If value is a number, it will be coerced to a valid byte value, +an integer between 0 and 255.

      +

      If byteOffset is not a number, it will be coerced to a number. If the result +of coercion is NaN or 0, then the entire buffer will be searched. This +behavior matches String#indexOf().

      +
      const b = Buffer.from('abcdef');
      +
      +// Passing a value that's a number, but not a valid byte.
      +// Prints: 2, equivalent to searching for 99 or 'c'.
      +console.log(b.indexOf(99.9));
      +console.log(b.indexOf(256 + 99));
      +
      +// Passing a byteOffset that coerces to NaN or 0.
      +// Prints: 1, searching the whole buffer.
      +console.log(b.indexOf('b', undefined));
      +console.log(b.indexOf('b', {}));
      +console.log(b.indexOf('b', null));
      +console.log(b.indexOf('b', []));
      +

      If value is an empty string or empty Buffer and byteOffset is less +than buf.length, byteOffset will be returned. If value is empty and +byteOffset is at least buf.length, buf.length will be returned.

      +

      buf.keys()#

      + + +

      Creates and returns an iterator of buf keys (indices).

      +
      const buf = Buffer.from('buffer');
      +
      +for (const key of buf.keys()) {
      +  console.log(key);
      +}
      +// Prints:
      +//   0
      +//   1
      +//   2
      +//   3
      +//   4
      +//   5
      +

      buf.lastIndexOf(value[, byteOffset][, encoding])#

      + +
        +
      • value <string> | <Buffer> | <Uint8Array> | <integer> What to search for.
      • +
      • byteOffset <integer> Where to begin searching in buf. If negative, then +offset is calculated from the end of buf. Default: +buf.length - 1.
      • +
      • encoding <string> If value is a string, this is the encoding used to +determine the binary representation of the string that will be searched for in +buf. Default: 'utf8'.
      • +
      • Returns: <integer> The index of the last occurrence of value in buf, or +-1 if buf does not contain value.
      • +
      +

      Identical to buf.indexOf(), except the last occurrence of value is found +rather than the first occurrence.

      +
      const buf = Buffer.from('this buffer is a buffer');
      +
      +console.log(buf.lastIndexOf('this'));
      +// Prints: 0
      +console.log(buf.lastIndexOf('buffer'));
      +// Prints: 17
      +console.log(buf.lastIndexOf(Buffer.from('buffer')));
      +// Prints: 17
      +console.log(buf.lastIndexOf(97));
      +// Prints: 15 (97 is the decimal ASCII value for 'a')
      +console.log(buf.lastIndexOf(Buffer.from('yolo')));
      +// Prints: -1
      +console.log(buf.lastIndexOf('buffer', 5));
      +// Prints: 5
      +console.log(buf.lastIndexOf('buffer', 4));
      +// Prints: -1
      +
      +const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
      +
      +console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
      +// Prints: 6
      +console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
      +// Prints: 4
      +

      If value is not a string, number, or Buffer, this method will throw a +TypeError. If value is a number, it will be coerced to a valid byte value, +an integer between 0 and 255.

      +

      If byteOffset is not a number, it will be coerced to a number. Any arguments +that coerce to NaN, like {} or undefined, will search the whole buffer. +This behavior matches String#lastIndexOf().

      +
      const b = Buffer.from('abcdef');
      +
      +// Passing a value that's a number, but not a valid byte.
      +// Prints: 2, equivalent to searching for 99 or 'c'.
      +console.log(b.lastIndexOf(99.9));
      +console.log(b.lastIndexOf(256 + 99));
      +
      +// Passing a byteOffset that coerces to NaN.
      +// Prints: 1, searching the whole buffer.
      +console.log(b.lastIndexOf('b', undefined));
      +console.log(b.lastIndexOf('b', {}));
      +
      +// Passing a byteOffset that coerces to 0.
      +// Prints: -1, equivalent to passing 0.
      +console.log(b.lastIndexOf('b', null));
      +console.log(b.lastIndexOf('b', []));
      +

      If value is an empty string or empty Buffer, byteOffset will be returned.

      +

      buf.length#

      + + +

      Returns the number of bytes in buf.

      +
      // Create a `Buffer` and write a shorter string to it using UTF-8.
      +
      +const buf = Buffer.alloc(1234);
      +
      +console.log(buf.length);
      +// Prints: 1234
      +
      +buf.write('some string', 0, 'utf8');
      +
      +console.log(buf.length);
      +// Prints: 1234
      +

      buf.parent#

      + +

      Stability: 0 - Deprecated: Use buf.buffer instead.

      +

      The buf.parent property is a deprecated alias for buf.buffer.

      +

      buf.readBigInt64BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads a signed, big-endian 64-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed +values.

      +

      buf.readBigInt64LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads a signed, little-endian 64-bit integer from buf at the specified +offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed +values.

      +

      buf.readBigUInt64BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads an unsigned, big-endian 64-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
      +
      +console.log(buf.readBigUInt64BE(0));
      +// Prints: 4294967295n
      +

      buf.readBigUInt64LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <bigint>
      • +
      +

      Reads an unsigned, little-endian 64-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
      +
      +console.log(buf.readBigUInt64LE(0));
      +// Prints: 18446744069414584320n
      +

      buf.readDoubleBE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 64-bit, big-endian double from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
      +
      +console.log(buf.readDoubleBE(0));
      +// Prints: 8.20788039913184e-304
      +

      buf.readDoubleLE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 64-bit, little-endian double from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
      +
      +console.log(buf.readDoubleLE(0));
      +// Prints: 5.447603722011605e-270
      +console.log(buf.readDoubleLE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readFloatBE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 32-bit, big-endian float from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4]);
      +
      +console.log(buf.readFloatBE(0));
      +// Prints: 2.387939260590663e-38
      +

      buf.readFloatLE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <number>
      • +
      +

      Reads a 32-bit, little-endian float from buf at the specified offset.

      +
      const buf = Buffer.from([1, 2, 3, 4]);
      +
      +console.log(buf.readFloatLE(0));
      +// Prints: 1.539989614439558e-36
      +console.log(buf.readFloatLE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readInt8([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed 8-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([-1, 5]);
      +
      +console.log(buf.readInt8(0));
      +// Prints: -1
      +console.log(buf.readInt8(1));
      +// Prints: 5
      +console.log(buf.readInt8(2));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readInt16BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, big-endian 16-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 5]);
      +
      +console.log(buf.readInt16BE(0));
      +// Prints: 5
      +

      buf.readInt16LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, little-endian 16-bit integer from buf at the specified +offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 5]);
      +
      +console.log(buf.readInt16LE(0));
      +// Prints: 1280
      +console.log(buf.readInt16LE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readInt32BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, big-endian 32-bit integer from buf at the specified offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 0, 0, 5]);
      +
      +console.log(buf.readInt32BE(0));
      +// Prints: 5
      +

      buf.readInt32LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads a signed, little-endian 32-bit integer from buf at the specified +offset.

      +

      Integers read from a Buffer are interpreted as two's complement signed values.

      +
      const buf = Buffer.from([0, 0, 0, 5]);
      +
      +console.log(buf.readInt32LE(0));
      +// Prints: 83886080
      +console.log(buf.readInt32LE(1));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readIntBE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as a big-endian, two's complement signed value +supporting up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readIntBE(0, 6).toString(16));
      +// Prints: 1234567890ab
      +console.log(buf.readIntBE(1, 6).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +console.log(buf.readIntBE(1, 0).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readIntLE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as a little-endian, two's complement signed value +supporting up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readIntLE(0, 6).toString(16));
      +// Prints: -546f87a9cbee
      +

      buf.readUInt8([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned 8-bit integer from buf at the specified offset.

      +
      const buf = Buffer.from([1, -2]);
      +
      +console.log(buf.readUInt8(0));
      +// Prints: 1
      +console.log(buf.readUInt8(1));
      +// Prints: 254
      +console.log(buf.readUInt8(2));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUInt16BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, big-endian 16-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56]);
      +
      +console.log(buf.readUInt16BE(0).toString(16));
      +// Prints: 1234
      +console.log(buf.readUInt16BE(1).toString(16));
      +// Prints: 3456
      +

      buf.readUInt16LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, little-endian 16-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56]);
      +
      +console.log(buf.readUInt16LE(0).toString(16));
      +// Prints: 3412
      +console.log(buf.readUInt16LE(1).toString(16));
      +// Prints: 5634
      +console.log(buf.readUInt16LE(2).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUInt32BE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, big-endian 32-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
      +
      +console.log(buf.readUInt32BE(0).toString(16));
      +// Prints: 12345678
      +

      buf.readUInt32LE([offset])#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer>
      • +
      +

      Reads an unsigned, little-endian 32-bit integer from buf at the specified +offset.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
      +
      +console.log(buf.readUInt32LE(0).toString(16));
      +// Prints: 78563412
      +console.log(buf.readUInt32LE(1).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUIntBE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as an unsigned big-endian integer supporting +up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readUIntBE(0, 6).toString(16));
      +// Prints: 1234567890ab
      +console.log(buf.readUIntBE(1, 6).toString(16));
      +// Throws ERR_OUT_OF_RANGE.
      +

      buf.readUIntLE(offset, byteLength)#

      + +
        +
      • offset <integer> Number of bytes to skip before starting to read. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to read. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer>
      • +
      +

      Reads byteLength number of bytes from buf at the specified offset +and interprets the result as an unsigned, little-endian integer supporting +up to 48 bits of accuracy.

      +
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
      +
      +console.log(buf.readUIntLE(0, 6).toString(16));
      +// Prints: ab9078563412
      +

      buf.subarray([start[, end]])#

      + + +

      Returns a new Buffer that references the same memory as the original, but +offset and cropped by the start and end indices.

      +

      Specifying end greater than buf.length will return the same result as +that of end equal to buf.length.

      +

      This method is inherited from TypedArray#subarray().

      +

      Modifying the new Buffer slice will modify the memory in the original Buffer +because the allocated memory of the two objects overlap.

      +
      // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
      +// from the original `Buffer`.
      +
      +const buf1 = Buffer.allocUnsafe(26);
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf1[i] = i + 97;
      +}
      +
      +const buf2 = buf1.subarray(0, 3);
      +
      +console.log(buf2.toString('ascii', 0, buf2.length));
      +// Prints: abc
      +
      +buf1[0] = 33;
      +
      +console.log(buf2.toString('ascii', 0, buf2.length));
      +// Prints: !bc
      +

      Specifying negative indexes causes the slice to be generated relative to the +end of buf rather than the beginning.

      +
      const buf = Buffer.from('buffer');
      +
      +console.log(buf.subarray(-6, -1).toString());
      +// Prints: buffe
      +// (Equivalent to buf.subarray(0, 5).)
      +
      +console.log(buf.subarray(-6, -2).toString());
      +// Prints: buff
      +// (Equivalent to buf.subarray(0, 4).)
      +
      +console.log(buf.subarray(-5, -2).toString());
      +// Prints: uff
      +// (Equivalent to buf.subarray(1, 4).)
      +

      buf.slice([start[, end]])#

      + + +

      Returns a new Buffer that references the same memory as the original, but +offset and cropped by the start and end indices.

      +

      This is the same behavior as buf.subarray().

      +

      This method is not compatible with the Uint8Array.prototype.slice(), +which is a superclass of Buffer. To copy the slice, use +Uint8Array.prototype.slice().

      +
      const buf = Buffer.from('buffer');
      +
      +const copiedBuf = Uint8Array.prototype.slice.call(buf);
      +copiedBuf[0]++;
      +console.log(copiedBuf.toString());
      +// Prints: cuffer
      +
      +console.log(buf.toString());
      +// Prints: buffer
      +

      buf.swap16()#

      + +
        +
      • Returns: <Buffer> A reference to buf.
      • +
      +

      Interprets buf as an array of unsigned 16-bit integers and swaps the +byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length +is not a multiple of 2.

      +
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
      +
      +console.log(buf1);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +
      +buf1.swap16();
      +
      +console.log(buf1);
      +// Prints: <Buffer 02 01 04 03 06 05 08 07>
      +
      +const buf2 = Buffer.from([0x1, 0x2, 0x3]);
      +
      +buf2.swap16();
      +// Throws ERR_INVALID_BUFFER_SIZE.
      +

      One convenient use of buf.swap16() is to perform a fast in-place conversion +between UTF-16 little-endian and UTF-16 big-endian:

      +
      const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
      +buf.swap16(); // Convert to big-endian UTF-16 text.
      +

      buf.swap32()#

      + +
        +
      • Returns: <Buffer> A reference to buf.
      • +
      +

      Interprets buf as an array of unsigned 32-bit integers and swaps the +byte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length +is not a multiple of 4.

      +
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
      +
      +console.log(buf1);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +
      +buf1.swap32();
      +
      +console.log(buf1);
      +// Prints: <Buffer 04 03 02 01 08 07 06 05>
      +
      +const buf2 = Buffer.from([0x1, 0x2, 0x3]);
      +
      +buf2.swap32();
      +// Throws ERR_INVALID_BUFFER_SIZE.
      +

      buf.swap64()#

      + +
        +
      • Returns: <Buffer> A reference to buf.
      • +
      +

      Interprets buf as an array of 64-bit numbers and swaps byte order in-place. +Throws ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.

      +
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
      +
      +console.log(buf1);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +
      +buf1.swap64();
      +
      +console.log(buf1);
      +// Prints: <Buffer 08 07 06 05 04 03 02 01>
      +
      +const buf2 = Buffer.from([0x1, 0x2, 0x3]);
      +
      +buf2.swap64();
      +// Throws ERR_INVALID_BUFFER_SIZE.
      +

      buf.toJSON()#

      + + +

      Returns a JSON representation of buf. JSON.stringify() implicitly calls +this function when stringifying a Buffer instance.

      +

      Buffer.from() accepts objects in the format returned from this method. +In particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

      +
      const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
      +const json = JSON.stringify(buf);
      +
      +console.log(json);
      +// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
      +
      +const copy = JSON.parse(json, (key, value) => {
      +  return value && value.type === 'Buffer' ?
      +    Buffer.from(value) :
      +    value;
      +});
      +
      +console.log(copy);
      +// Prints: <Buffer 01 02 03 04 05>
      +

      buf.toString([encoding[, start[, end]]])#

      + +
        +
      • encoding <string> The character encoding to use. Default: 'utf8'.
      • +
      • start <integer> The byte offset to start decoding at. Default: 0.
      • +
      • end <integer> The byte offset to stop decoding at (not inclusive). +Default: buf.length.
      • +
      • Returns: <string>
      • +
      +

      Decodes buf to a string according to the specified character encoding in +encoding. start and end may be passed to decode only a subset of buf.

      +

      If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, +then each invalid byte is replaced with the replacement character U+FFFD.

      +

      The maximum length of a string instance (in UTF-16 code units) is available +as buffer.constants.MAX_STRING_LENGTH.

      +
      const buf1 = Buffer.allocUnsafe(26);
      +
      +for (let i = 0; i < 26; i++) {
      +  // 97 is the decimal ASCII value for 'a'.
      +  buf1[i] = i + 97;
      +}
      +
      +console.log(buf1.toString('utf8'));
      +// Prints: abcdefghijklmnopqrstuvwxyz
      +console.log(buf1.toString('utf8', 0, 5));
      +// Prints: abcde
      +
      +const buf2 = Buffer.from('tést');
      +
      +console.log(buf2.toString('hex'));
      +// Prints: 74c3a97374
      +console.log(buf2.toString('utf8', 0, 3));
      +// Prints: té
      +console.log(buf2.toString(undefined, 0, 3));
      +// Prints: té
      +

      buf.values()#

      + + +

      Creates and returns an iterator for buf values (bytes). This function is +called automatically when a Buffer is used in a for..of statement.

      +
      const buf = Buffer.from('buffer');
      +
      +for (const value of buf.values()) {
      +  console.log(value);
      +}
      +// Prints:
      +//   98
      +//   117
      +//   102
      +//   102
      +//   101
      +//   114
      +
      +for (const value of buf) {
      +  console.log(value);
      +}
      +// Prints:
      +//   98
      +//   117
      +//   102
      +//   102
      +//   101
      +//   114
      +

      buf.write(string[, offset[, length]][, encoding])#

      + +
        +
      • string <string> String to write to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write string. +Default: 0.
      • +
      • length <integer> Maximum number of bytes to write (written bytes will not +exceed buf.length - offset). Default: buf.length - offset.
      • +
      • encoding <string> The character encoding of string. Default: 'utf8'.
      • +
      • Returns: <integer> Number of bytes written.
      • +
      +

      Writes string to buf at offset according to the character encoding in +encoding. The length parameter is the number of bytes to write. If buf did +not contain enough space to fit the entire string, only part of string will be +written. However, partially encoded characters will not be written.

      +
      const buf = Buffer.alloc(256);
      +
      +const len = buf.write('\u00bd + \u00bc = \u00be', 0);
      +
      +console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
      +// Prints: 12 bytes: ½ + ¼ = ¾
      +
      +const buffer = Buffer.alloc(10);
      +
      +const length = buffer.write('abcd', 8);
      +
      +console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
      +// Prints: 2 bytes : ab
      +

      buf.writeBigInt64BE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian.

      +

      value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigInt64BE(0x0102030405060708n, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 01 02 03 04 05 06 07 08>
      +

      buf.writeBigInt64LE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian.

      +

      value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigInt64LE(0x0102030405060708n, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 08 07 06 05 04 03 02 01>
      +

      buf.writeBigUInt64BE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer de ca fa fe ca ce fa de>
      +

      buf.writeBigUInt64LE(value[, offset])#

      + +
        +
      • value <bigint> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy: 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer de fa ce ca fe fa ca de>
      +

      buf.writeDoubleBE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a JavaScript number. Behavior is undefined when value is anything +other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeDoubleBE(123.456, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
      +

      buf.writeDoubleLE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 8. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a JavaScript number. Behavior is undefined when value is anything +other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(8);
      +
      +buf.writeDoubleLE(123.456, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
      +

      buf.writeFloatBE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. Behavior is +undefined when value is anything other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeFloatBE(0xcafebabe, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 4f 4a fe bb>
      +
      +

      buf.writeFloatLE(value[, offset])#

      + +
        +
      • value <number> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. Behavior is +undefined when value is anything other than a JavaScript number.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeFloatLE(0xcafebabe, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer bb fe 4a 4f>
      +

      buf.writeInt8(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset. value must be a valid +signed 8-bit integer. Behavior is undefined when value is anything other than +a signed 8-bit integer.

      +

      value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(2);
      +
      +buf.writeInt8(2, 0);
      +buf.writeInt8(-2, 1);
      +
      +console.log(buf);
      +// Prints: <Buffer 02 fe>
      +

      buf.writeInt16BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid signed 16-bit integer. Behavior is undefined when value is +anything other than a signed 16-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(2);
      +
      +buf.writeInt16BE(0x0102, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 01 02>
      +

      buf.writeInt16LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid signed 16-bit integer. Behavior is undefined when value is +anything other than a signed 16-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(2);
      +
      +buf.writeInt16LE(0x0304, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 04 03>
      +

      buf.writeInt32BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid signed 32-bit integer. Behavior is undefined when value is +anything other than a signed 32-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeInt32BE(0x01020304, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 01 02 03 04>
      +

      buf.writeInt32LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid signed 32-bit integer. Behavior is undefined when value is +anything other than a signed 32-bit integer.

      +

      The value is interpreted and written as a two's complement signed integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeInt32LE(0x05060708, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer 08 07 06 05>
      +

      buf.writeIntBE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when +value is anything other than a signed integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeIntBE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer 12 34 56 78 90 ab>
      +
      +

      buf.writeIntLE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined +when value is anything other than a signed integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeIntLE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer ab 90 78 56 34 12>
      +

      buf.writeUInt8(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 1. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset. value must be a +valid unsigned 8-bit integer. Behavior is undefined when value is anything +other than an unsigned 8-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt8(0x3, 0);
      +buf.writeUInt8(0x4, 1);
      +buf.writeUInt8(0x23, 2);
      +buf.writeUInt8(0x42, 3);
      +
      +console.log(buf);
      +// Prints: <Buffer 03 04 23 42>
      +

      buf.writeUInt16BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid unsigned 16-bit integer. Behavior is undefined when value +is anything other than an unsigned 16-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt16BE(0xdead, 0);
      +buf.writeUInt16BE(0xbeef, 2);
      +
      +console.log(buf);
      +// Prints: <Buffer de ad be ef>
      +

      buf.writeUInt16LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 2. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid unsigned 16-bit integer. Behavior is undefined when value is +anything other than an unsigned 16-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt16LE(0xdead, 0);
      +buf.writeUInt16LE(0xbeef, 2);
      +
      +console.log(buf);
      +// Prints: <Buffer ad de ef be>
      +

      buf.writeUInt32BE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as big-endian. The value +must be a valid unsigned 32-bit integer. Behavior is undefined when value +is anything other than an unsigned 32-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt32BE(0xfeedface, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer fe ed fa ce>
      +

      buf.writeUInt32LE(value[, offset])#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - 4. Default: 0.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes value to buf at the specified offset as little-endian. The value +must be a valid unsigned 32-bit integer. Behavior is undefined when value is +anything other than an unsigned 32-bit integer.

      +
      const buf = Buffer.allocUnsafe(4);
      +
      +buf.writeUInt32LE(0xfeedface, 0);
      +
      +console.log(buf);
      +// Prints: <Buffer ce fa ed fe>
      +

      buf.writeUIntBE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined +when value is anything other than an unsigned integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeUIntBE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer 12 34 56 78 90 ab>
      +

      buf.writeUIntLE(value, offset, byteLength)#

      + +
        +
      • value <integer> Number to be written to buf.
      • +
      • offset <integer> Number of bytes to skip before starting to write. Must +satisfy 0 <= offset <= buf.length - byteLength.
      • +
      • byteLength <integer> Number of bytes to write. Must satisfy +0 < byteLength <= 6.
      • +
      • Returns: <integer> offset plus the number of bytes written.
      • +
      +

      Writes byteLength bytes of value to buf at the specified offset +as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined +when value is anything other than an unsigned integer.

      +
      const buf = Buffer.allocUnsafe(6);
      +
      +buf.writeUIntLE(0x1234567890ab, 0, 6);
      +
      +console.log(buf);
      +// Prints: <Buffer ab 90 78 56 34 12>
      +

      new Buffer(array)#

      + +

      Stability: 0 - Deprecated: Use Buffer.from(array) instead.

      + +

      See Buffer.from(array).

      +

      new Buffer(arrayBuffer[, byteOffset[, length]])#

      + +

      + +

      See +Buffer.from(arrayBuffer[, byteOffset[, length]]).

      +

      new Buffer(buffer)#

      + +

      Stability: 0 - Deprecated: Use Buffer.from(buffer) instead.

      + +

      See Buffer.from(buffer).

      +

      new Buffer(size)#

      + +

      Stability: 0 - Deprecated: Use Buffer.alloc() instead (also see +Buffer.allocUnsafe()).

      +
        +
      • size <integer> The desired length of the new Buffer.
      • +
      +

      See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the +constructor is equivalent to Buffer.alloc().

      +

      new Buffer(string[, encoding])#

      + +

      Stability: 0 - Deprecated: +Use Buffer.from(string[, encoding]) instead.

      +
        +
      • string <string> String to encode.
      • +
      • encoding <string> The encoding of string. Default: 'utf8'.
      • +
      +

      See Buffer.from(string[, encoding]).

      +

      buffer module APIs#

      +

      While, the Buffer object is available as a global, there are additional +Buffer-related APIs that are available only via the buffer module +accessed using require('buffer').

      +

      buffer.INSPECT_MAX_BYTES#

      + + +

      Returns the maximum number of bytes that will be returned when +buf.inspect() is called. This can be overridden by user modules. See +util.inspect() for more details on buf.inspect() behavior.

      +

      buffer.kMaxLength#

      + +
        +
      • <integer> The largest size allowed for a single Buffer instance.
      • +
      +

      An alias for buffer.constants.MAX_LENGTH.

      +

      buffer.transcode(source, fromEnc, toEnc)#

      + + +

      Re-encodes the given Buffer or Uint8Array instance from one character +encoding to another. Returns a new Buffer instance.

      +

      Throws if the fromEnc or toEnc specify invalid character encodings or if +conversion from fromEnc to toEnc is not permitted.

      +

      Encodings supported by buffer.transcode() are: 'ascii', 'utf8', +'utf16le', 'ucs2', 'latin1', and 'binary'.

      +

      The transcoding process will use substitution characters if a given byte +sequence cannot be adequately represented in the target encoding. For instance:

      +
      const buffer = require('buffer');
      +
      +const newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');
      +console.log(newBuf.toString('ascii'));
      +// Prints: '?'
      +

      Because the Euro (€) sign is not representable in US-ASCII, it is replaced +with ? in the transcoded Buffer.

      +

      Class: SlowBuffer#

      + +

      Stability: 0 - Deprecated: Use Buffer.allocUnsafeSlow() instead.

      +

      See Buffer.allocUnsafeSlow(). This was never a class in the sense that +the constructor always returned a Buffer instance, rather than a SlowBuffer +instance.

      +

      new SlowBuffer(size)#

      + +

      Stability: 0 - Deprecated: Use Buffer.allocUnsafeSlow() instead.

      +
        +
      • size <integer> The desired length of the new SlowBuffer.
      • +
      +

      See Buffer.allocUnsafeSlow().

      +

      Buffer constants#

      + +

      buffer.constants.MAX_LENGTH#

      + +
        +
      • <integer> The largest size allowed for a single Buffer instance.
      • +
      +

      On 32-bit architectures, this value currently is 230 - 1 (~1GB). +On 64-bit architectures, this value currently is 231 - 1 (~2GB).

      +

      This value is also available as buffer.kMaxLength.

      +

      buffer.constants.MAX_STRING_LENGTH#

      + +
        +
      • <integer> The largest length allowed for a single string instance.
      • +
      +

      Represents the largest length that a string primitive can have, counted +in UTF-16 code units.

      +

      This value may depend on the JS engine that is being used.

      +

      Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe()#

      +

      In versions of Node.js prior to 6.0.0, Buffer instances were created using the +Buffer constructor function, which allocates the returned Buffer +differently based on what arguments are provided:

      +
        +
      • Passing a number as the first argument to Buffer() (e.g. new Buffer(10)) +allocates a new Buffer object of the specified size. Prior to Node.js 8.0.0, +the memory allocated for such Buffer instances is not initialized and +can contain sensitive data. Such Buffer instances must be subsequently +initialized by using either buf.fill(0) or by writing to the +entire Buffer before reading data from the Buffer. +While this behavior is intentional to improve performance, +development experience has demonstrated that a more explicit distinction is +required between creating a fast-but-uninitialized Buffer versus creating a +slower-but-safer Buffer. Since Node.js 8.0.0, Buffer(num) and new Buffer(num) return a Buffer with initialized memory.
      • +
      • Passing a string, array, or Buffer as the first argument copies the +passed object's data into the Buffer.
      • +
      • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer +that shares allocated memory with the given array buffer.
      • +
      +

      Because the behavior of new Buffer() is different depending on the type of the +first argument, security and reliability issues can be inadvertently introduced +into applications when argument validation or Buffer initialization is not +performed.

      +

      For example, if an attacker can cause an application to receive a number where +a string is expected, the application may call new Buffer(100) +instead of new Buffer("100"), leading it to allocate a 100 byte buffer instead +of allocating a 3 byte buffer with content "100". This is commonly possible +using JSON API calls. Since JSON distinguishes between numeric and string types, +it allows injection of numbers where a naively written application that does not +validate its input sufficiently might expect to always receive a string. +Before Node.js 8.0.0, the 100 byte buffer might contain +arbitrary pre-existing in-memory data, so may be used to expose in-memory +secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot +occur because the data is zero-filled. However, other attacks are still +possible, such as causing very large buffers to be allocated by the server, +leading to performance degradation or crashing on memory exhaustion.

      +

      To make the creation of Buffer instances more reliable and less error-prone, +the various forms of the new Buffer() constructor have been deprecated +and replaced by separate Buffer.from(), Buffer.alloc(), and +Buffer.allocUnsafe() methods.

      +

      Developers should migrate all existing uses of the new Buffer() constructors +to one of these new APIs.

      + +

      Buffer instances returned by Buffer.allocUnsafe() and +Buffer.from(array) may be allocated off a shared internal memory pool +if size is less than or equal to half Buffer.poolSize. Instances +returned by Buffer.allocUnsafeSlow() never use the shared internal +memory pool.

      +

      The --zero-fill-buffers command line option#

      + +

      Node.js can be started using the --zero-fill-buffers command line option to +cause all newly-allocated Buffer instances to be zero-filled upon creation by +default. Without the option, buffers created with Buffer.allocUnsafe(), +Buffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled. +Use of this flag can have a measurable negative impact on performance. Use the +--zero-fill-buffers option only when necessary to enforce that newly allocated +Buffer instances cannot contain old data that is potentially sensitive.

      +
      $ node --zero-fill-buffers
      +> Buffer.allocUnsafe(5);
      +<Buffer 00 00 00 00 00>
      +

      What makes Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() "unsafe"?#

      +

      When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the +segment of allocated memory is uninitialized (it is not zeroed-out). While +this design makes the allocation of memory quite fast, the allocated segment of +memory might contain old data that is potentially sensitive. Using a Buffer +created by Buffer.allocUnsafe() without completely overwriting the +memory can allow this old data to be leaked when the Buffer memory is read.

      +

      While there are clear performance advantages to using +Buffer.allocUnsafe(), extra care must be taken in order to avoid +introducing security vulnerabilities into an application.

      + +
      +
      +
      + + diff --git a/doc/api/buffer.json b/doc/api/buffer.json new file mode 100644 index 0000000000000000000000000000000000000000..0c2adcb2b41948e218394f3835cdfb4a34015a3e --- /dev/null +++ b/doc/api/buffer.json @@ -0,0 +1,3394 @@ +{ + "type": "module", + "source": "doc/api/buffer.md", + "modules": [ + { + "textRaw": "Buffer", + "name": "buffer", + "introduced_in": "v0.1.90", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/buffer.js

      \n

      Buffer objects are used to represent a fixed-length sequence of bytes. Many\nNode.js APIs support Buffers.

      \n

      The Buffer class is a subclass of JavaScript's Uint8Array class and\nextends it with methods that cover additional use cases. Node.js APIs accept\nplain Uint8Arrays wherever Buffers are supported as well.

      \n

      The Buffer class is within the global scope, making it unlikely that one\nwould need to ever use require('buffer').Buffer.

      \n
      // Creates a zero-filled Buffer of length 10.\nconst buf1 = Buffer.alloc(10);\n\n// Creates a Buffer of length 10,\n// filled with bytes which all have the value `1`.\nconst buf2 = Buffer.alloc(10, 1);\n\n// Creates an uninitialized buffer of length 10.\n// This is faster than calling Buffer.alloc() but the returned\n// Buffer instance might contain old data that needs to be\n// overwritten using fill(), write(), or other functions that fill the Buffer's\n// contents.\nconst buf3 = Buffer.allocUnsafe(10);\n\n// Creates a Buffer containing the bytes [1, 2, 3].\nconst buf4 = Buffer.from([1, 2, 3]);\n\n// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries\n// are all truncated using `(value & 255)` to fit into the range 0–255.\nconst buf5 = Buffer.from([257, 257.5, -255, '1']);\n\n// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':\n// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)\n// [116, 195, 169, 115, 116] (in decimal notation)\nconst buf6 = Buffer.from('tést');\n\n// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].\nconst buf7 = Buffer.from('tést', 'latin1');\n
      ", + "modules": [ + { + "textRaw": "Buffers and character encodings", + "name": "buffers_and_character_encodings", + "meta": { + "changes": [ + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7111", + "description": "Introduced `latin1` as an alias for `binary`." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2859", + "description": "Removed the deprecated `raw` and `raws` encodings." + } + ] + }, + "desc": "

      When converting between Buffers and strings, a character encoding may be\nspecified. If no character encoding is specified, UTF-8 will be used as the\ndefault.

      \n
      const buf = Buffer.from('hello world', 'utf8');\n\nconsole.log(buf.toString('hex'));\n// Prints: 68656c6c6f20776f726c64\nconsole.log(buf.toString('base64'));\n// Prints: aGVsbG8gd29ybGQ=\n\nconsole.log(Buffer.from('fhqwhgads', 'utf8'));\n// Prints: <Buffer 66 68 71 77 68 67 61 64 73>\nconsole.log(Buffer.from('fhqwhgads', 'utf16le'));\n// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>\n
      \n

      The character encodings currently supported by Node.js are the following:

      \n
        \n
      • \n

        'utf8': Multi-byte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8. This is the default character encoding.\nWhen decoding a Buffer into a string that does not exclusively contain\nvalid UTF-8 data, the Unicode replacement character U+FFFD � will be used\nto represent those errors.

        \n
      • \n
      • \n

        'utf16le': Multi-byte encoded Unicode characters. Unlike 'utf8', each\ncharacter in the string will be encoded using either 2 or 4 bytes.\nNode.js only supports the little-endian variant of UTF-16.

        \n
      • \n
      • \n

        'latin1': Latin-1 stands for ISO-8859-1. This character encoding only\nsupports the Unicode characters from U+0000 to U+00FF. Each character is\nencoded using a single byte. Characters that do not fit into that range are\ntruncated and will be mapped to characters in that range.

        \n
      • \n
      \n

      Converting a Buffer into a string using one of the above is referred to as\ndecoding, and converting a string into a Buffer is referred to as encoding.

      \n

      Node.js also supports the following two binary-to-text encodings. For\nbinary-to-text encodings, the naming convention is reversed: Converting a\nBuffer into a string is typically referred to as encoding, and converting a\nstring into a Buffer as decoding.

      \n
        \n
      • \n

        'base64': Base64 encoding. When creating a Buffer from a string,\nthis encoding will also correctly accept \"URL and Filename Safe Alphabet\" as\nspecified in RFC 4648, Section 5. Whitespace characters such as spaces,\ntabs, and new lines contained within the base64-encoded string are ignored.

        \n
      • \n
      • \n

        'hex': Encode each byte as two hexadecimal characters. Data truncation\nmay occur when decoding strings that do exclusively contain valid hexadecimal\ncharacters. See below for an example.

        \n
      • \n
      \n

      The following legacy character encodings are also supported:

      \n
        \n
      • \n

        'ascii': For 7-bit ASCII data only. When encoding a string into a\nBuffer, this is equivalent to using 'latin1'. When decoding a Buffer\ninto a string, using this encoding will additionally unset the highest bit of\neach byte before decoding as 'latin1'.\nGenerally, there should be no reason to use this encoding, as 'utf8'\n(or, if the data is known to always be ASCII-only, 'latin1') will be a\nbetter choice when encoding or decoding ASCII-only text. It is only provided\nfor legacy compatibility.

        \n
      • \n
      • \n

        'binary': Alias for 'latin1'. See binary strings for more background\non this topic. The name of this encoding can be very misleading, as all of the\nencodings listed here convert between strings and binary data. For converting\nbetween strings and Buffers, typically 'utf-8' is the right choice.

        \n
      • \n
      • \n

        'ucs2': Alias of 'utf16le'. UCS-2 used to refer to a variant of UTF-16\nthat did not support characters that had code points larger than U+FFFF.\nIn Node.js, these code points are always supported.

        \n
      • \n
      \n
      Buffer.from('1ag', 'hex');\n// Prints <Buffer 1a>, data truncated when first non-hexadecimal value\n// ('g') encountered.\n\nBuffer.from('1a7g', 'hex');\n// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').\n\nBuffer.from('1634', 'hex');\n// Prints <Buffer 16 34>, all data represented.\n
      \n

      Modern Web browsers follow the WHATWG Encoding Standard which aliases\nboth 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing\nsomething like http.get(), if the returned charset is one of those listed in\nthe WHATWG specification it is possible that the server actually returned\n'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode\nthe characters.

      ", + "type": "module", + "displayName": "Buffers and character encodings" + }, + { + "textRaw": "Buffers and TypedArrays", + "name": "buffers_and_typedarrays", + "meta": { + "changes": [ + { + "version": "v3.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2002", + "description": "The `Buffer`s class now inherits from `Uint8Array`." + } + ] + }, + "desc": "

      Buffer instances are also JavaScript Uint8Array and TypedArray\ninstances. All TypedArray methods are available on Buffers. There are,\nhowever, subtle incompatibilities between the Buffer API and the\nTypedArray API.

      \n

      In particular:

      \n
        \n
      • While TypedArray#slice() creates a copy of part of the TypedArray,\nBuffer#slice() creates a view over the existing Buffer\nwithout copying. This behavior can be surprising, and only exists for legacy\ncompatibility. TypedArray#subarray() can be used to achieve the behavior\nof Buffer#slice() on both Buffers and other\nTypedArrays.
      • \n
      • buf.toString() is incompatible with its TypedArray equivalent.
      • \n
      • A number of methods, e.g. buf.indexOf(), support additional arguments.
      • \n
      \n

      There are two ways to create new TypedArray instances from a Buffer:

      \n
        \n
      • Passing a Buffer to a TypedArray constructor will copy the Buffers\ncontents, interpreted as an array of integers, and not as a byte sequence\nof the target type.
      • \n
      \n
      const buf = Buffer.from([1, 2, 3, 4]);\nconst uint32array = new Uint32Array(buf);\n\nconsole.log(uint32array);\n\n// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]\n
      \n
        \n
      • Passing the Buffers underlying ArrayBuffer will create a\nTypedArray that shares its memory with the Buffer.
      • \n
      \n
      const buf = Buffer.from('hello', 'utf16le');\nconst uint16arr = new Uint16Array(\n  buf.buffer,\n  buf.byteOffset,\n  buf.length / Uint16Array.BYTES_PER_ELEMENT);\n\nconsole.log(uint16array);\n\n// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]\n
      \n

      It is possible to create a new Buffer that shares the same allocated\nmemory as a TypedArray instance by using the TypedArray object’s\n.buffer property in the same way. Buffer.from()\nbehaves like new Uint8Array() in this context.

      \n
      const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Copies the contents of `arr`.\nconst buf1 = Buffer.from(arr);\n\n// Shares memory with `arr`.\nconst buf2 = Buffer.from(arr.buffer);\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 a0 0f>\n\narr[1] = 6000;\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 70 17>\n
      \n

      When creating a Buffer using a TypedArray's .buffer, it is\npossible to use only a portion of the underlying ArrayBuffer by passing in\nbyteOffset and length parameters.

      \n
      const arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\nconsole.log(buf.length);\n// Prints: 16\n
      \n

      The Buffer.from() and TypedArray.from() have different signatures and\nimplementations. Specifically, the TypedArray variants accept a second\nargument that is a mapping function that is invoked on every element of the\ntyped array:

      \n
        \n
      • TypedArray.from(source[, mapFn[, thisArg]])
      • \n
      \n

      The Buffer.from() method, however, does not support the use of a mapping\nfunction:

      \n", + "type": "module", + "displayName": "Buffers and TypedArrays" + }, + { + "textRaw": "Buffers and iteration", + "name": "buffers_and_iteration", + "desc": "

      Buffer instances can be iterated over using for..of syntax:

      \n
      const buf = Buffer.from([1, 2, 3]);\n\nfor (const b of buf) {\n  console.log(b);\n}\n// Prints:\n//   1\n//   2\n//   3\n
      \n

      Additionally, the buf.values(), buf.keys(), and\nbuf.entries() methods can be used to create iterators.

      ", + "type": "module", + "displayName": "Buffers and iteration" + }, + { + "textRaw": "`buffer` module APIs", + "name": "`buffer`_module_apis", + "desc": "

      While, the Buffer object is available as a global, there are additional\nBuffer-related APIs that are available only via the buffer module\naccessed using require('buffer').

      ", + "properties": [ + { + "textRaw": "`INSPECT_MAX_BYTES` {integer} **Default:** `50`", + "type": "integer", + "name": "INSPECT_MAX_BYTES", + "meta": { + "added": [ + "v0.5.4" + ], + "changes": [] + }, + "default": "`50`", + "desc": "

      Returns the maximum number of bytes that will be returned when\nbuf.inspect() is called. This can be overridden by user modules. See\nutil.inspect() for more details on buf.inspect() behavior.

      " + }, + { + "textRaw": "`kMaxLength` {integer} The largest size allowed for a single `Buffer` instance.", + "type": "integer", + "name": "kMaxLength", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "desc": "

      An alias for buffer.constants.MAX_LENGTH.

      ", + "shortDesc": "The largest size allowed for a single `Buffer` instance." + } + ], + "methods": [ + { + "textRaw": "`buffer.transcode(source, fromEnc, toEnc)`", + "type": "method", + "name": "transcode", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `source` parameter can now be a `Uint8Array`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`source` {Buffer|Uint8Array} A `Buffer` or `Uint8Array` instance.", + "name": "source", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or `Uint8Array` instance." + }, + { + "textRaw": "`fromEnc` {string} The current encoding.", + "name": "fromEnc", + "type": "string", + "desc": "The current encoding." + }, + { + "textRaw": "`toEnc` {string} To target encoding.", + "name": "toEnc", + "type": "string", + "desc": "To target encoding." + } + ] + } + ], + "desc": "

      Re-encodes the given Buffer or Uint8Array instance from one character\nencoding to another. Returns a new Buffer instance.

      \n

      Throws if the fromEnc or toEnc specify invalid character encodings or if\nconversion from fromEnc to toEnc is not permitted.

      \n

      Encodings supported by buffer.transcode() are: 'ascii', 'utf8',\n'utf16le', 'ucs2', 'latin1', and 'binary'.

      \n

      The transcoding process will use substitution characters if a given byte\nsequence cannot be adequately represented in the target encoding. For instance:

      \n
      const buffer = require('buffer');\n\nconst newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n
      \n

      Because the Euro (€) sign is not representable in US-ASCII, it is replaced\nwith ? in the transcoded Buffer.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `SlowBuffer`", + "type": "class", + "name": "SlowBuffer", + "meta": { + "deprecated": [ + "v6.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.", + "desc": "

      See Buffer.allocUnsafeSlow(). This was never a class in the sense that\nthe constructor always returned a Buffer instance, rather than a SlowBuffer\ninstance.

      ", + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `SlowBuffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `SlowBuffer`." + } + ], + "desc": "

      See Buffer.allocUnsafeSlow().

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Buffer constants", + "name": "buffer_constants", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "properties": [ + { + "textRaw": "`MAX_LENGTH` {integer} The largest size allowed for a single `Buffer` instance.", + "type": "integer", + "name": "MAX_LENGTH", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "desc": "

      On 32-bit architectures, this value currently is 230 - 1 (~1GB).\nOn 64-bit architectures, this value currently is 231 - 1 (~2GB).

      \n

      This value is also available as buffer.kMaxLength.

      ", + "shortDesc": "The largest size allowed for a single `Buffer` instance." + }, + { + "textRaw": "`MAX_STRING_LENGTH` {integer} The largest length allowed for a single `string` instance.", + "type": "integer", + "name": "MAX_STRING_LENGTH", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "desc": "

      Represents the largest length that a string primitive can have, counted\nin UTF-16 code units.

      \n

      This value may depend on the JS engine that is being used.

      ", + "shortDesc": "The largest length allowed for a single `string` instance." + } + ], + "type": "module", + "displayName": "Buffer constants" + } + ], + "type": "module", + "displayName": "`buffer` module APIs" + }, + { + "textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", + "name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`", + "desc": "

      In versions of Node.js prior to 6.0.0, Buffer instances were created using the\nBuffer constructor function, which allocates the returned Buffer\ndifferently based on what arguments are provided:

      \n
        \n
      • Passing a number as the first argument to Buffer() (e.g. new Buffer(10))\nallocates a new Buffer object of the specified size. Prior to Node.js 8.0.0,\nthe memory allocated for such Buffer instances is not initialized and\ncan contain sensitive data. Such Buffer instances must be subsequently\ninitialized by using either buf.fill(0) or by writing to the\nentire Buffer before reading data from the Buffer.\nWhile this behavior is intentional to improve performance,\ndevelopment experience has demonstrated that a more explicit distinction is\nrequired between creating a fast-but-uninitialized Buffer versus creating a\nslower-but-safer Buffer. Since Node.js 8.0.0, Buffer(num) and new Buffer(num) return a Buffer with initialized memory.
      • \n
      • Passing a string, array, or Buffer as the first argument copies the\npassed object's data into the Buffer.
      • \n
      • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer\nthat shares allocated memory with the given array buffer.
      • \n
      \n

      Because the behavior of new Buffer() is different depending on the type of the\nfirst argument, security and reliability issues can be inadvertently introduced\ninto applications when argument validation or Buffer initialization is not\nperformed.

      \n

      For example, if an attacker can cause an application to receive a number where\na string is expected, the application may call new Buffer(100)\ninstead of new Buffer(\"100\"), leading it to allocate a 100 byte buffer instead\nof allocating a 3 byte buffer with content \"100\". This is commonly possible\nusing JSON API calls. Since JSON distinguishes between numeric and string types,\nit allows injection of numbers where a naively written application that does not\nvalidate its input sufficiently might expect to always receive a string.\nBefore Node.js 8.0.0, the 100 byte buffer might contain\narbitrary pre-existing in-memory data, so may be used to expose in-memory\nsecrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot\noccur because the data is zero-filled. However, other attacks are still\npossible, such as causing very large buffers to be allocated by the server,\nleading to performance degradation or crashing on memory exhaustion.

      \n

      To make the creation of Buffer instances more reliable and less error-prone,\nthe various forms of the new Buffer() constructor have been deprecated\nand replaced by separate Buffer.from(), Buffer.alloc(), and\nBuffer.allocUnsafe() methods.

      \n

      Developers should migrate all existing uses of the new Buffer() constructors\nto one of these new APIs.

      \n\n

      Buffer instances returned by Buffer.allocUnsafe() and\nBuffer.from(array) may be allocated off a shared internal memory pool\nif size is less than or equal to half Buffer.poolSize. Instances\nreturned by Buffer.allocUnsafeSlow() never use the shared internal\nmemory pool.

      ", + "modules": [ + { + "textRaw": "The `--zero-fill-buffers` command line option", + "name": "the_`--zero-fill-buffers`_command_line_option", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "desc": "

      Node.js can be started using the --zero-fill-buffers command line option to\ncause all newly-allocated Buffer instances to be zero-filled upon creation by\ndefault. Without the option, buffers created with Buffer.allocUnsafe(),\nBuffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled.\nUse of this flag can have a measurable negative impact on performance. Use the\n--zero-fill-buffers option only when necessary to enforce that newly allocated\nBuffer instances cannot contain old data that is potentially sensitive.

      \n
      $ node --zero-fill-buffers\n> Buffer.allocUnsafe(5);\n<Buffer 00 00 00 00 00>\n
      ", + "type": "module", + "displayName": "The `--zero-fill-buffers` command line option" + }, + { + "textRaw": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?", + "name": "what_makes_`buffer.allocunsafe()`_and_`buffer.allocunsafeslow()`_\"unsafe\"?", + "desc": "

      When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the\nsegment of allocated memory is uninitialized (it is not zeroed-out). While\nthis design makes the allocation of memory quite fast, the allocated segment of\nmemory might contain old data that is potentially sensitive. Using a Buffer\ncreated by Buffer.allocUnsafe() without completely overwriting the\nmemory can allow this old data to be leaked when the Buffer memory is read.

      \n

      While there are clear performance advantages to using\nBuffer.allocUnsafe(), extra care must be taken in order to avoid\nintroducing security vulnerabilities into an application.

      ", + "type": "module", + "displayName": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?" + } + ], + "type": "module", + "displayName": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`" + } + ], + "classes": [ + { + "textRaw": "Class: `Buffer`", + "type": "class", + "name": "Buffer", + "desc": "

      The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.

      ", + "classMethods": [ + { + "textRaw": "Static method: `Buffer.alloc(size[, fill[, encoding]])`", + "type": "classMethod", + "name": "alloc", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18129", + "description": "Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17427", + "description": "Specifying an invalid string for `fill` triggers a thrown exception." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17428", + "description": "Specifying an invalid string for `fill` now results in a zero-filled buffer." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + }, + { + "textRaw": "`fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer` with. **Default:** `0`.", + "name": "fill", + "type": "string|Buffer|Uint8Array|integer", + "default": "`0`", + "desc": "A value to pre-fill the new `Buffer` with." + }, + { + "textRaw": "`encoding` {string} If `fill` is a string, this is its encoding. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `fill` is a string, this is its encoding." + } + ] + } + ], + "desc": "

      Allocates a new Buffer of size bytes. If fill is undefined, the\nBuffer will be zero-filled.

      \n
      const buf = Buffer.alloc(5);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00>\n
      \n

      If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE\nis thrown.

      \n

      If fill is specified, the allocated Buffer will be initialized by calling\nbuf.fill(fill).

      \n
      const buf = Buffer.alloc(5, 'a');\n\nconsole.log(buf);\n// Prints: <Buffer 61 61 61 61 61>\n
      \n

      If both fill and encoding are specified, the allocated Buffer will be\ninitialized by calling buf.fill(fill, encoding).

      \n
      const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\n\nconsole.log(buf);\n// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\n
      \n

      Calling Buffer.alloc() can be measurably slower than the alternative\nBuffer.allocUnsafe() but ensures that the newly created Buffer instance\ncontents will never contain sensitive data from previous allocations, including\ndata that might not have been allocated for Buffers.

      \n

      A TypeError will be thrown if size is not a number.

      " + }, + { + "textRaw": "Static method: `Buffer.allocUnsafe(size)`", + "type": "classMethod", + "name": "allocUnsafe", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7079", + "description": "Passing a negative `size` will now throw an error." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + } + ] + } + ], + "desc": "

      Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE\nis thrown.

      \n

      The underlying memory for Buffer instances created in this way is not\ninitialized. The contents of the newly created Buffer are unknown and\nmay contain sensitive data. Use Buffer.alloc() instead to initialize\nBuffer instances with zeroes.

      \n
      const buf = Buffer.allocUnsafe(10);\n\nconsole.log(buf);\n// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>\n\nbuf.fill(0);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\n
      \n

      A TypeError will be thrown if size is not a number.

      \n

      The Buffer module pre-allocates an internal Buffer instance of\nsize Buffer.poolSize that is used as a pool for the fast allocation of new\nBuffer instances created using Buffer.allocUnsafe(),\nBuffer.from(array), Buffer.concat(), and the deprecated\nnew Buffer(size) constructor only when size is less than or equal\nto Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).

      \n

      Use of this pre-allocated internal memory pool is a key difference between\ncalling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill).\nSpecifically, Buffer.alloc(size, fill) will never use the internal Buffer\npool, while Buffer.allocUnsafe(size).fill(fill) will use the internal\nBuffer pool if size is less than or equal to half Buffer.poolSize. The\ndifference is subtle but can be important when an application requires the\nadditional performance that Buffer.allocUnsafe() provides.

      " + }, + { + "textRaw": "Static method: `Buffer.allocUnsafeSlow(size)`", + "type": "classMethod", + "name": "allocUnsafeSlow", + "meta": { + "added": [ + "v5.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + } + ] + } + ], + "desc": "

      Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_OPT_VALUE\nis thrown. A zero-length Buffer is created if size is 0.

      \n

      The underlying memory for Buffer instances created in this way is not\ninitialized. The contents of the newly created Buffer are unknown and\nmay contain sensitive data. Use buf.fill(0) to initialize\nsuch Buffer instances with zeroes.

      \n

      When using Buffer.allocUnsafe() to allocate new Buffer instances,\nallocations under 4KB are sliced from a single pre-allocated Buffer. This\nallows applications to avoid the garbage collection overhead of creating many\nindividually allocated Buffer instances. This approach improves both\nperformance and memory usage by eliminating the need to track and clean up as\nmany individual ArrayBuffer objects.

      \n

      However, in the case where a developer may need to retain a small chunk of\nmemory from a pool for an indeterminate amount of time, it may be appropriate\nto create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and\nthen copying out the relevant bits.

      \n
      // Need to keep around a few small chunks of memory.\nconst store = [];\n\nsocket.on('readable', () => {\n  let data;\n  while (null !== (data = readable.read())) {\n    // Allocate for retained data.\n    const sb = Buffer.allocUnsafeSlow(10);\n\n    // Copy the data into the new allocation.\n    data.copy(sb, 0, 0, 10);\n\n    store.push(sb);\n  }\n});\n
      \n

      A TypeError will be thrown if size is not a number.

      " + }, + { + "textRaw": "Static method: `Buffer.byteLength(string[, encoding])`", + "type": "classMethod", + "name": "byteLength", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8946", + "description": "Passing invalid input will now throw an error." + }, + { + "version": "v5.10.0", + "pr-url": "https://github.com/nodejs/node/pull/5255", + "description": "The `string` parameter can now be any `TypedArray`, `DataView` or `ArrayBuffer`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The number of bytes contained within `string`.", + "name": "return", + "type": "integer", + "desc": "The number of bytes contained within `string`." + }, + "params": [ + { + "textRaw": "`string` {string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer} A value to calculate the length of.", + "name": "string", + "type": "string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer", + "desc": "A value to calculate the length of." + }, + { + "textRaw": "`encoding` {string} If `string` is a string, this is its encoding. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `string` is a string, this is its encoding." + } + ] + } + ], + "desc": "

      Returns the byte length of a string when encoded using encoding.\nThis is not the same as String.prototype.length, which does not account\nfor the encoding that is used to convert the string into bytes.

      \n

      For 'base64' and 'hex', this function assumes valid input. For strings that\ncontain non-base64/hex-encoded data (e.g. whitespace), the return value might be\ngreater than the length of a Buffer created from the string.

      \n
      const str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(`${str}: ${str.length} characters, ` +\n            `${Buffer.byteLength(str, 'utf8')} bytes`);\n// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes\n
      \n

      When string is a Buffer/DataView/TypedArray/ArrayBuffer/\nSharedArrayBuffer, the byte length as reported by .byteLength\nis returned.

      " + }, + { + "textRaw": "Static method: `Buffer.compare(buf1, buf2)`", + "type": "classMethod", + "name": "compare", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The arguments can now be `Uint8Array`s." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details.", + "name": "return", + "type": "integer", + "desc": "Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details." + }, + "params": [ + { + "textRaw": "`buf1` {Buffer|Uint8Array}", + "name": "buf1", + "type": "Buffer|Uint8Array" + }, + { + "textRaw": "`buf2` {Buffer|Uint8Array}", + "name": "buf2", + "type": "Buffer|Uint8Array" + } + ] + } + ], + "desc": "

      Compares buf1 to buf2, typically for the purpose of sorting arrays of\nBuffer instances. This is equivalent to calling\nbuf1.compare(buf2).

      \n
      const buf1 = Buffer.from('1234');\nconst buf2 = Buffer.from('0123');\nconst arr = [buf1, buf2];\n\nconsole.log(arr.sort(Buffer.compare));\n// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]\n// (This result is equal to: [buf2, buf1].)\n
      " + }, + { + "textRaw": "Static method: `Buffer.concat(list[, totalLength])`", + "type": "classMethod", + "name": "concat", + "meta": { + "added": [ + "v0.7.11" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The elements of `list` can now be `Uint8Array`s." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`][] instances to concatenate.", + "name": "list", + "type": "Buffer[] | Uint8Array[]", + "desc": "List of `Buffer` or [`Uint8Array`][] instances to concatenate." + }, + { + "textRaw": "`totalLength` {integer} Total length of the `Buffer` instances in `list` when concatenated.", + "name": "totalLength", + "type": "integer", + "desc": "Total length of the `Buffer` instances in `list` when concatenated." + } + ] + } + ], + "desc": "

      Returns a new Buffer which is the result of concatenating all the Buffer\ninstances in the list together.

      \n

      If the list has no items, or if the totalLength is 0, then a new zero-length\nBuffer is returned.

      \n

      If totalLength is not provided, it is calculated from the Buffer instances\nin list by adding their lengths.

      \n

      If totalLength is provided, it is coerced to an unsigned integer. If the\ncombined length of the Buffers in list exceeds totalLength, the result is\ntruncated to totalLength.

      \n
      // Create a single `Buffer` from a list of three `Buffer` instances.\n\nconst buf1 = Buffer.alloc(10);\nconst buf2 = Buffer.alloc(14);\nconst buf3 = Buffer.alloc(18);\nconst totalLength = buf1.length + buf2.length + buf3.length;\n\nconsole.log(totalLength);\n// Prints: 42\n\nconst bufA = Buffer.concat([buf1, buf2, buf3], totalLength);\n\nconsole.log(bufA);\n// Prints: <Buffer 00 00 00 00 ...>\nconsole.log(bufA.length);\n// Prints: 42\n
      \n

      Buffer.concat() may also use the internal Buffer pool like\nBuffer.allocUnsafe() does.

      " + }, + { + "textRaw": "Static method: `Buffer.from(array)`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`array` {integer[]}", + "name": "array", + "type": "integer[]" + } + ] + } + ], + "desc": "

      Allocates a new Buffer using an array of bytes in the range 0 – 255.\nArray entries outside that range will be truncated to fit into it.

      \n
      // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.\nconst buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
      \n

      A TypeError will be thrown if array is not an Array or another type\nappropriate for Buffer.from() variants.

      \n

      Buffer.from(array) and Buffer.from(string) may also use the internal\nBuffer pool like Buffer.allocUnsafe() does.

      " + }, + { + "textRaw": "Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a [`TypedArray`][].", + "name": "arrayBuffer", + "type": "ArrayBuffer|SharedArrayBuffer", + "desc": "An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a [`TypedArray`][]." + }, + { + "textRaw": "`byteOffset` {integer} Index of first byte to expose. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Index of first byte to expose." + }, + { + "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`.", + "name": "length", + "type": "integer", + "default": "`arrayBuffer.byteLength - byteOffset`", + "desc": "Number of bytes to expose." + } + ] + } + ], + "desc": "

      This creates a view of the ArrayBuffer without copying the underlying\nmemory. For example, when passed a reference to the .buffer property of a\nTypedArray instance, the newly created Buffer will share the same\nallocated memory as the TypedArray.

      \n
      const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`.\nconst buf = Buffer.from(arr.buffer);\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 a0 0f>\n\n// Changing the original Uint16Array changes the Buffer also.\narr[1] = 6000;\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 70 17>\n
      \n

      The optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.

      \n
      const ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\nconsole.log(buf.length);\n// Prints: 2\n
      \n

      A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a\nSharedArrayBuffer or another type appropriate for Buffer.from()\nvariants.

      " + }, + { + "textRaw": "Static method: `Buffer.from(buffer)`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from which to copy data.", + "name": "buffer", + "type": "Buffer|Uint8Array", + "desc": "An existing `Buffer` or [`Uint8Array`][] from which to copy data." + } + ] + } + ], + "desc": "

      Copies the passed buffer data onto a new Buffer instance.

      \n
      const buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\n\nconsole.log(buf1.toString());\n// Prints: auffer\nconsole.log(buf2.toString());\n// Prints: buffer\n
      \n

      A TypeError will be thrown if buffer is not a Buffer or another type\nappropriate for Buffer.from() variants.

      " + }, + { + "textRaw": "Static method: `Buffer.from(object[, offsetOrEncoding[, length]])`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`object` {Object} An object supporting `Symbol.toPrimitive` or `valueOf()`.", + "name": "object", + "type": "Object", + "desc": "An object supporting `Symbol.toPrimitive` or `valueOf()`." + }, + { + "textRaw": "`offsetOrEncoding` {integer|string} A byte-offset or encoding.", + "name": "offsetOrEncoding", + "type": "integer|string", + "desc": "A byte-offset or encoding." + }, + { + "textRaw": "`length` {integer} A length.", + "name": "length", + "type": "integer", + "desc": "A length." + } + ] + } + ], + "desc": "

      For objects whose valueOf() function returns a value not strictly equal to\nobject, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

      \n
      const buf = Buffer.from(new String('this is a test'));\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n
      \n

      For objects that support Symbol.toPrimitive, returns\nBuffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).

      \n
      class Foo {\n  [Symbol.toPrimitive]() {\n    return 'this is a test';\n  }\n}\n\nconst buf = Buffer.from(new Foo(), 'utf8');\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n
      \n

      A TypeError will be thrown if object does not have the mentioned methods or\nis not of another type appropriate for Buffer.from() variants.

      " + }, + { + "textRaw": "Static method: `Buffer.from(string[, encoding])`", + "type": "classMethod", + "name": "from", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string} A string to encode.", + "name": "string", + "type": "string", + "desc": "A string to encode." + }, + { + "textRaw": "`encoding` {string} The encoding of `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding of `string`." + } + ] + } + ], + "desc": "

      Creates a new Buffer containing string. The encoding parameter identifies\nthe character encoding to be used when converting string into bytes.

      \n
      const buf1 = Buffer.from('this is a tést');\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\n\nconsole.log(buf1.toString());\n// Prints: this is a tést\nconsole.log(buf2.toString());\n// Prints: this is a tést\nconsole.log(buf1.toString('latin1'));\n// Prints: this is a tést\n
      \n

      A TypeError will be thrown if string is not a string or another type\nappropriate for Buffer.from() variants.

      " + }, + { + "textRaw": "Static method: `Buffer.isBuffer(obj)`", + "type": "classMethod", + "name": "isBuffer", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`obj` {Object}", + "name": "obj", + "type": "Object" + } + ] + } + ], + "desc": "

      Returns true if obj is a Buffer, false otherwise.

      " + }, + { + "textRaw": "Static method: `Buffer.isEncoding(encoding)`", + "type": "classMethod", + "name": "isEncoding", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`encoding` {string} A character encoding name to check.", + "name": "encoding", + "type": "string", + "desc": "A character encoding name to check." + } + ] + } + ], + "desc": "

      Returns true if encoding is the name of a supported character encoding,\nor false otherwise.

      \n
      console.log(Buffer.isEncoding('utf-8'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('hex'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('utf/8'));\n// Prints: false\n\nconsole.log(Buffer.isEncoding(''));\n// Prints: false\n
      " + } + ], + "properties": [ + { + "textRaw": "`poolSize` {integer} **Default:** `8192`", + "type": "integer", + "name": "poolSize", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "default": "`8192`", + "desc": "

      This is the size (in bytes) of pre-allocated internal Buffer instances used\nfor pooling. This value may be modified.

      " + }, + { + "textRaw": "`[index]` `index` {integer}", + "type": "integer", + "name": "index", + "meta": { + "type": "property", + "name": [ + "index" + ], + "changes": [] + }, + "desc": "

      The index operator [index] can be used to get and set the octet at position\nindex in buf. The values refer to individual bytes, so the legal value\nrange is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).

      \n

      This operator is inherited from Uint8Array, so its behavior on out-of-bounds\naccess is the same as Uint8Array. In other words, buf[index] returns\nundefined when index is negative or greater or equal to buf.length, and\nbuf[index] = value does not modify the buffer if index is negative or\n>= buf.length.

      \n
      // Copy an ASCII string into a `Buffer` one byte at a time.\n// (This only works for ASCII-only strings. In general, one should use\n// `Buffer.from()` to perform this conversion.)\n\nconst str = 'Node.js';\nconst buf = Buffer.allocUnsafe(str.length);\n\nfor (let i = 0; i < str.length; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf.toString('utf8'));\n// Prints: Node.js\n
      " + }, + { + "textRaw": "`buffer` {ArrayBuffer} The underlying `ArrayBuffer` object based on which this `Buffer` object is created.", + "type": "ArrayBuffer", + "name": "buffer", + "desc": "

      This ArrayBuffer is not guaranteed to correspond exactly to the original\nBuffer. See the notes on buf.byteOffset for details.

      \n
      const arrayBuffer = new ArrayBuffer(16);\nconst buffer = Buffer.from(arrayBuffer);\n\nconsole.log(buffer.buffer === arrayBuffer);\n// Prints: true\n
      ", + "shortDesc": "The underlying `ArrayBuffer` object based on which this `Buffer` object is created." + }, + { + "textRaw": "`byteOffset` {integer} The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object.", + "type": "integer", + "name": "byteOffset", + "desc": "

      When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length),\nor sometimes when allocating a Buffer smaller than Buffer.poolSize, the\nbuffer does not start from a zero offset on the underlying ArrayBuffer.

      \n

      This can cause problems when accessing the underlying ArrayBuffer directly\nusing buf.buffer, as other parts of the ArrayBuffer may be unrelated\nto the Buffer object itself.

      \n

      A common issue when creating a TypedArray object that shares its memory with\na Buffer is that in this case one needs to specify the byteOffset correctly:

      \n
      // Create a buffer smaller than `Buffer.poolSize`.\nconst nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n\n// When casting the Node.js Buffer to an Int8Array, use the byteOffset\n// to refer only to the part of `nodeBuffer.buffer` that contains the memory\n// for `nodeBuffer`.\nnew Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);\n
      ", + "shortDesc": "The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object." + }, + { + "textRaw": "`length` {integer}", + "type": "integer", + "name": "length", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      Returns the number of bytes in buf.

      \n
      // Create a `Buffer` and write a shorter string to it using UTF-8.\n\nconst buf = Buffer.alloc(1234);\n\nconsole.log(buf.length);\n// Prints: 1234\n\nbuf.write('some string', 0, 'utf8');\n\nconsole.log(buf.length);\n// Prints: 1234\n
      " + }, + { + "textRaw": "`buf.parent`", + "name": "parent", + "meta": { + "deprecated": [ + "v8.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`buf.buffer`][] instead.", + "desc": "

      The buf.parent property is a deprecated alias for buf.buffer.

      " + } + ], + "methods": [ + { + "textRaw": "`buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`", + "type": "method", + "name": "compare", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `target` parameter can now be a `Uint8Array`." + }, + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/5880", + "description": "Additional parameters for specifying offsets are supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to compare `buf`.", + "name": "target", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or [`Uint8Array`][] with which to compare `buf`." + }, + { + "textRaw": "`targetStart` {integer} The offset within `target` at which to begin comparison. **Default:** `0`.", + "name": "targetStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `target` at which to begin comparison." + }, + { + "textRaw": "`targetEnd` {integer} The offset within `target` at which to end comparison (not inclusive). **Default:** `target.length`.", + "name": "targetEnd", + "type": "integer", + "default": "`target.length`", + "desc": "The offset within `target` at which to end comparison (not inclusive)." + }, + { + "textRaw": "`sourceStart` {integer} The offset within `buf` at which to begin comparison. **Default:** `0`.", + "name": "sourceStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `buf` at which to begin comparison." + }, + { + "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to end comparison (not inclusive). **Default:** [`buf.length`][].", + "name": "sourceEnd", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "The offset within `buf` at which to end comparison (not inclusive)." + } + ] + } + ], + "desc": "

      Compares buf with target and returns a number indicating whether buf\ncomes before, after, or is the same as target in sort order.\nComparison is based on the actual sequence of bytes in each Buffer.

      \n
        \n
      • 0 is returned if target is the same as buf
      • \n
      • 1 is returned if target should come before buf when sorted.
      • \n
      • -1 is returned if target should come after buf when sorted.
      • \n
      \n
      const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.compare(buf1));\n// Prints: 0\nconsole.log(buf1.compare(buf2));\n// Prints: -1\nconsole.log(buf1.compare(buf3));\n// Prints: -1\nconsole.log(buf2.compare(buf1));\n// Prints: 1\nconsole.log(buf2.compare(buf3));\n// Prints: 1\nconsole.log([buf1, buf2, buf3].sort(Buffer.compare));\n// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]\n// (This result is equal to: [buf1, buf3, buf2].)\n
      \n

      The optional targetStart, targetEnd, sourceStart, and sourceEnd\narguments can be used to limit the comparison to specific ranges within target\nand buf respectively.

      \n
      const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);\n\nconsole.log(buf1.compare(buf2, 5, 9, 0, 4));\n// Prints: 0\nconsole.log(buf1.compare(buf2, 0, 6, 4));\n// Prints: -1\nconsole.log(buf1.compare(buf2, 5, 6, 5));\n// Prints: 1\n
      \n

      ERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0,\ntargetEnd > target.byteLength, or sourceEnd > source.byteLength.

      " + }, + { + "textRaw": "`buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`", + "type": "method", + "name": "copy", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The number of bytes copied.", + "name": "return", + "type": "integer", + "desc": "The number of bytes copied." + }, + "params": [ + { + "textRaw": "`target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] to copy into.", + "name": "target", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or [`Uint8Array`][] to copy into." + }, + { + "textRaw": "`targetStart` {integer} The offset within `target` at which to begin writing. **Default:** `0`.", + "name": "targetStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `target` at which to begin writing." + }, + { + "textRaw": "`sourceStart` {integer} The offset within `buf` from which to begin copying. **Default:** `0`.", + "name": "sourceStart", + "type": "integer", + "default": "`0`", + "desc": "The offset within `buf` from which to begin copying." + }, + { + "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to stop copying (not inclusive). **Default:** [`buf.length`][].", + "name": "sourceEnd", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "The offset within `buf` at which to stop copying (not inclusive)." + } + ] + } + ], + "desc": "

      Copies data from a region of buf to a region in target, even if the target\nmemory region overlaps with buf.

      \n

      TypedArray#set() performs the same operation, and is available for all\nTypedArrays, including Node.js Buffers, although it takes different\nfunction arguments.

      \n
      // Create two `Buffer` instances.\nconst buf1 = Buffer.allocUnsafe(26);\nconst buf2 = Buffer.allocUnsafe(26).fill('!');\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf1[i] = i + 97;\n}\n\n// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.\nbuf1.copy(buf2, 8, 16, 20);\n// This is equivalent to:\n// buf2.set(buf1.subarray(16, 20), 8);\n\nconsole.log(buf2.toString('ascii', 0, 25));\n// Prints: !!!!!!!!qrst!!!!!!!!!!!!!\n
      \n
      // Create a `Buffer` and copy data from one region to an overlapping region\n// within the same `Buffer`.\n\nconst buf = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf[i] = i + 97;\n}\n\nbuf.copy(buf, 0, 4, 10);\n\nconsole.log(buf.toString());\n// Prints: efghijghijklmnopqrstuvwxyz\n
      " + }, + { + "textRaw": "`buf.entries()`", + "type": "method", + "name": "entries", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Creates and returns an iterator of [index, byte] pairs from the contents\nof buf.

      \n
      // Log the entire contents of a `Buffer`.\n\nconst buf = Buffer.from('buffer');\n\nfor (const pair of buf.entries()) {\n  console.log(pair);\n}\n// Prints:\n//   [0, 98]\n//   [1, 117]\n//   [2, 102]\n//   [3, 102]\n//   [4, 101]\n//   [5, 114]\n
      " + }, + { + "textRaw": "`buf.equals(otherBuffer)`", + "type": "method", + "name": "equals", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The arguments can now be `Uint8Array`s." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`otherBuffer` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to compare `buf`.", + "name": "otherBuffer", + "type": "Buffer|Uint8Array", + "desc": "A `Buffer` or [`Uint8Array`][] with which to compare `buf`." + } + ] + } + ], + "desc": "

      Returns true if both buf and otherBuffer have exactly the same bytes,\nfalse otherwise. Equivalent to\nbuf.compare(otherBuffer) === 0.

      \n
      const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.equals(buf2));\n// Prints: true\nconsole.log(buf1.equals(buf3));\n// Prints: false\n
      " + }, + { + "textRaw": "`buf.fill(value[, offset[, end]][, encoding])`", + "type": "method", + "name": "fill", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22969", + "description": "Throws `ERR_OUT_OF_RANGE` instead of `ERR_INDEX_OUT_OF_RANGE`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18790", + "description": "Negative `end` values throw an `ERR_INDEX_OUT_OF_RANGE` error." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18129", + "description": "Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17427", + "description": "Specifying an invalid string for `value` triggers a thrown exception." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4935", + "description": "The `encoding` parameter is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "The value with which to fill `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to fill `buf`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to fill `buf`." + }, + { + "textRaw": "`end` {integer} Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "Where to stop filling `buf` (not inclusive)." + }, + { + "textRaw": "`encoding` {string} The encoding for `value` if `value` is a string. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding for `value` if `value` is a string." + } + ] + } + ], + "desc": "

      Fills buf with the specified value. If the offset and end are not given,\nthe entire buf will be filled:

      \n
      // Fill a `Buffer` with the ASCII character 'h'.\n\nconst b = Buffer.allocUnsafe(50).fill('h');\n\nconsole.log(b.toString());\n// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\n
      \n

      value is coerced to a uint32 value if it is not a string, Buffer, or\ninteger. If the resulting integer is greater than 255 (decimal), buf will be\nfilled with value & 255.

      \n

      If the final write of a fill() operation falls on a multi-byte character,\nthen only the bytes of that character that fit into buf are written:

      \n
      // Fill a `Buffer` with character that takes up two bytes in UTF-8.\n\nconsole.log(Buffer.allocUnsafe(5).fill('\\u0222'));\n// Prints: <Buffer c8 a2 c8 a2 c8>\n
      \n

      If value contains invalid characters, it is truncated; if no valid\nfill data remains, an exception is thrown:

      \n
      const buf = Buffer.allocUnsafe(5);\n\nconsole.log(buf.fill('a'));\n// Prints: <Buffer 61 61 61 61 61>\nconsole.log(buf.fill('aazz', 'hex'));\n// Prints: <Buffer aa aa aa aa aa>\nconsole.log(buf.fill('zz', 'hex'));\n// Throws an exception.\n
      " + }, + { + "textRaw": "`buf.includes(value[, byteOffset][, encoding])`", + "type": "method", + "name": "includes", + "meta": { + "added": [ + "v5.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if `value` was found in `buf`, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if `value` was found in `buf`, `false` otherwise." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "What to search for." + }, + { + "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`." + }, + { + "textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `value` is a string, this is its encoding." + } + ] + } + ], + "desc": "

      Equivalent to buf.indexOf() !== -1.

      \n
      const buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.includes('this'));\n// Prints: true\nconsole.log(buf.includes('is'));\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n// Prints: true\nconsole.log(buf.includes(97));\n// Prints: true (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: true\nconsole.log(buf.includes('this', 4));\n// Prints: false\n
      " + }, + { + "textRaw": "`buf.indexOf(value[, byteOffset][, encoding])`", + "type": "method", + "name": "indexOf", + "meta": { + "added": [ + "v1.5.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `value` can now be a `Uint8Array`." + }, + { + "version": "v5.7.0, v4.4.0", + "pr-url": "https://github.com/nodejs/node/pull/4803", + "description": "When `encoding` is being passed, the `byteOffset` parameter is no longer required." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.", + "name": "return", + "type": "integer", + "desc": "The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "What to search for." + }, + { + "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`." + }, + { + "textRaw": "`encoding` {string} If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`." + } + ] + } + ], + "desc": "

      If value is:

      \n
        \n
      • a string, value is interpreted according to the character encoding in\nencoding.
      • \n
      • a Buffer or Uint8Array, value will be used in its entirety.\nTo compare a partial Buffer, use buf.slice().
      • \n
      • a number, value will be interpreted as an unsigned 8-bit integer\nvalue between 0 and 255.
      • \n
      \n
      const buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.indexOf('this'));\n// Prints: 0\nconsole.log(buf.indexOf('is'));\n// Prints: 2\nconsole.log(buf.indexOf(Buffer.from('a buffer')));\n// Prints: 8\nconsole.log(buf.indexOf(97));\n// Prints: 8 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.indexOf(Buffer.from('a buffer example')));\n// Prints: -1\nconsole.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: 8\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.indexOf('\\u03a3', 0, 'utf16le'));\n// Prints: 4\nconsole.log(utf16Buffer.indexOf('\\u03a3', -4, 'utf16le'));\n// Prints: 6\n
      \n

      If value is not a string, number, or Buffer, this method will throw a\nTypeError. If value is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.

      \n

      If byteOffset is not a number, it will be coerced to a number. If the result\nof coercion is NaN or 0, then the entire buffer will be searched. This\nbehavior matches String#indexOf().

      \n
      const b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.indexOf(99.9));\nconsole.log(b.indexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN or 0.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.indexOf('b', undefined));\nconsole.log(b.indexOf('b', {}));\nconsole.log(b.indexOf('b', null));\nconsole.log(b.indexOf('b', []));\n
      \n

      If value is an empty string or empty Buffer and byteOffset is less\nthan buf.length, byteOffset will be returned. If value is empty and\nbyteOffset is at least buf.length, buf.length will be returned.

      " + }, + { + "textRaw": "`buf.keys()`", + "type": "method", + "name": "keys", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Creates and returns an iterator of buf keys (indices).

      \n
      const buf = Buffer.from('buffer');\n\nfor (const key of buf.keys()) {\n  console.log(key);\n}\n// Prints:\n//   0\n//   1\n//   2\n//   3\n//   4\n//   5\n
      " + }, + { + "textRaw": "`buf.lastIndexOf(value[, byteOffset][, encoding])`", + "type": "method", + "name": "lastIndexOf", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10236", + "description": "The `value` can now be a `Uint8Array`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.", + "name": "return", + "type": "integer", + "desc": "The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`." + }, + "params": [ + { + "textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.", + "name": "value", + "type": "string|Buffer|Uint8Array|integer", + "desc": "What to search for." + }, + { + "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `buf.length - 1`.", + "name": "byteOffset", + "type": "integer", + "default": "`buf.length - 1`", + "desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`." + }, + { + "textRaw": "`encoding` {string} If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`." + } + ] + } + ], + "desc": "

      Identical to buf.indexOf(), except the last occurrence of value is found\nrather than the first occurrence.

      \n
      const buf = Buffer.from('this buffer is a buffer');\n\nconsole.log(buf.lastIndexOf('this'));\n// Prints: 0\nconsole.log(buf.lastIndexOf('buffer'));\n// Prints: 17\nconsole.log(buf.lastIndexOf(Buffer.from('buffer')));\n// Prints: 17\nconsole.log(buf.lastIndexOf(97));\n// Prints: 15 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.lastIndexOf(Buffer.from('yolo')));\n// Prints: -1\nconsole.log(buf.lastIndexOf('buffer', 5));\n// Prints: 5\nconsole.log(buf.lastIndexOf('buffer', 4));\n// Prints: -1\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', undefined, 'utf16le'));\n// Prints: 6\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', -5, 'utf16le'));\n// Prints: 4\n
      \n

      If value is not a string, number, or Buffer, this method will throw a\nTypeError. If value is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.

      \n

      If byteOffset is not a number, it will be coerced to a number. Any arguments\nthat coerce to NaN, like {} or undefined, will search the whole buffer.\nThis behavior matches String#lastIndexOf().

      \n
      const b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.lastIndexOf(99.9));\nconsole.log(b.lastIndexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.lastIndexOf('b', undefined));\nconsole.log(b.lastIndexOf('b', {}));\n\n// Passing a byteOffset that coerces to 0.\n// Prints: -1, equivalent to passing 0.\nconsole.log(b.lastIndexOf('b', null));\nconsole.log(b.lastIndexOf('b', []));\n
      \n

      If value is an empty string or empty Buffer, byteOffset will be returned.

      " + }, + { + "textRaw": "`buf.readBigInt64BE([offset])`", + "type": "method", + "name": "readBigInt64BE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a signed, big-endian 64-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed\nvalues.

      " + }, + { + "textRaw": "`buf.readBigInt64LE([offset])`", + "type": "method", + "name": "readBigInt64LE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a signed, little-endian 64-bit integer from buf at the specified\noffset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed\nvalues.

      " + }, + { + "textRaw": "`buf.readBigUInt64BE([offset])`", + "type": "method", + "name": "readBigUInt64BE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.readBigUint64BE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads an unsigned, big-endian 64-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64BE(0));\n// Prints: 4294967295n\n
      " + }, + { + "textRaw": "`buf.readBigUInt64LE([offset])`", + "type": "method", + "name": "readBigUInt64LE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.readBigUint64LE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads an unsigned, little-endian 64-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64LE(0));\n// Prints: 18446744069414584320n\n
      " + }, + { + "textRaw": "`buf.readDoubleBE([offset])`", + "type": "method", + "name": "readDoubleBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a 64-bit, big-endian double from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleBE(0));\n// Prints: 8.20788039913184e-304\n
      " + }, + { + "textRaw": "`buf.readDoubleLE([offset])`", + "type": "method", + "name": "readDoubleLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Reads a 64-bit, little-endian double from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleLE(0));\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readFloatBE([offset])`", + "type": "method", + "name": "readFloatBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a 32-bit, big-endian float from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatBE(0));\n// Prints: 2.387939260590663e-38\n
      " + }, + { + "textRaw": "`buf.readFloatLE([offset])`", + "type": "method", + "name": "readFloatLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a 32-bit, little-endian float from buf at the specified offset.

      \n
      const buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatLE(0));\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readInt8([offset])`", + "type": "method", + "name": "readInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Reads a signed 8-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([-1, 5]);\n\nconsole.log(buf.readInt8(0));\n// Prints: -1\nconsole.log(buf.readInt8(1));\n// Prints: 5\nconsole.log(buf.readInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readInt16BE([offset])`", + "type": "method", + "name": "readInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads a signed, big-endian 16-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16BE(0));\n// Prints: 5\n
      " + }, + { + "textRaw": "`buf.readInt16LE([offset])`", + "type": "method", + "name": "readInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads a signed, little-endian 16-bit integer from buf at the specified\noffset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16LE(0));\n// Prints: 1280\nconsole.log(buf.readInt16LE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readInt32BE([offset])`", + "type": "method", + "name": "readInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a signed, big-endian 32-bit integer from buf at the specified offset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32BE(0));\n// Prints: 5\n
      " + }, + { + "textRaw": "`buf.readInt32LE([offset])`", + "type": "method", + "name": "readInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads a signed, little-endian 32-bit integer from buf at the specified\noffset.

      \n

      Integers read from a Buffer are interpreted as two's complement signed values.

      \n
      const buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32LE(0));\n// Prints: 83886080\nconsole.log(buf.readInt32LE(1));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readIntBE(offset, byteLength)`", + "type": "method", + "name": "readIntBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a big-endian, two's complement signed value\nsupporting up to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\nconsole.log(buf.readIntBE(1, 0).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readIntLE(offset, byteLength)`", + "type": "method", + "name": "readIntLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a little-endian, two's complement signed value\nsupporting up to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntLE(0, 6).toString(16));\n// Prints: -546f87a9cbee\n
      " + }, + { + "textRaw": "`buf.readUInt8([offset])`", + "type": "method", + "name": "readUInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint8()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Reads an unsigned 8-bit integer from buf at the specified offset.

      \n
      const buf = Buffer.from([1, -2]);\n\nconsole.log(buf.readUInt8(0));\n// Prints: 1\nconsole.log(buf.readUInt8(1));\n// Prints: 254\nconsole.log(buf.readUInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUInt16BE([offset])`", + "type": "method", + "name": "readUInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint16BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads an unsigned, big-endian 16-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16BE(0).toString(16));\n// Prints: 1234\nconsole.log(buf.readUInt16BE(1).toString(16));\n// Prints: 3456\n
      " + }, + { + "textRaw": "`buf.readUInt16LE([offset])`", + "type": "method", + "name": "readUInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint16LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Reads an unsigned, little-endian 16-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16LE(0).toString(16));\n// Prints: 3412\nconsole.log(buf.readUInt16LE(1).toString(16));\n// Prints: 5634\nconsole.log(buf.readUInt16LE(2).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUInt32BE([offset])`", + "type": "method", + "name": "readUInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint32BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads an unsigned, big-endian 32-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32BE(0).toString(16));\n// Prints: 12345678\n
      " + }, + { + "textRaw": "`buf.readUInt32LE([offset])`", + "type": "method", + "name": "readUInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUint32LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Reads an unsigned, little-endian 32-bit integer from buf at the specified\noffset.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32LE(0).toString(16));\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(1).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUIntBE(offset, byteLength)`", + "type": "method", + "name": "readUIntBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUintBE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned big-endian integer supporting\nup to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n
      " + }, + { + "textRaw": "`buf.readUIntLE(offset, byteLength)`", + "type": "method", + "name": "readUIntLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.readUintLE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned, little-endian integer supporting\nup to 48 bits of accuracy.

      \n
      const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n// Prints: ab9078563412\n
      " + }, + { + "textRaw": "`buf.subarray([start[, end]])`", + "type": "method", + "name": "subarray", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`start` {integer} Where the new `Buffer` will start. **Default:** `0`.", + "name": "start", + "type": "integer", + "default": "`0`", + "desc": "Where the new `Buffer` will start." + }, + { + "textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "Where the new `Buffer` will end (not inclusive)." + } + ] + } + ], + "desc": "

      Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

      \n

      Specifying end greater than buf.length will return the same result as\nthat of end equal to buf.length.

      \n

      This method is inherited from TypedArray#subarray().

      \n

      Modifying the new Buffer slice will modify the memory in the original Buffer\nbecause the allocated memory of the two objects overlap.

      \n
      // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte\n// from the original `Buffer`.\n\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf1[i] = i + 97;\n}\n\nconst buf2 = buf1.subarray(0, 3);\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: abc\n\nbuf1[0] = 33;\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: !bc\n
      \n

      Specifying negative indexes causes the slice to be generated relative to the\nend of buf rather than the beginning.

      \n
      const buf = Buffer.from('buffer');\n\nconsole.log(buf.subarray(-6, -1).toString());\n// Prints: buffe\n// (Equivalent to buf.subarray(0, 5).)\n\nconsole.log(buf.subarray(-6, -2).toString());\n// Prints: buff\n// (Equivalent to buf.subarray(0, 4).)\n\nconsole.log(buf.subarray(-5, -2).toString());\n// Prints: uff\n// (Equivalent to buf.subarray(1, 4).)\n
      " + }, + { + "textRaw": "`buf.slice([start[, end]])`", + "type": "method", + "name": "slice", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v7.1.0, v6.9.2", + "pr-url": "https://github.com/nodejs/node/pull/9341", + "description": "Coercing the offsets to integers now handles values outside the 32-bit integer range properly." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9101", + "description": "All offsets are now coerced to integers before doing any calculations with them." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`start` {integer} Where the new `Buffer` will start. **Default:** `0`.", + "name": "start", + "type": "integer", + "default": "`0`", + "desc": "Where the new `Buffer` will start." + }, + { + "textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "Where the new `Buffer` will end (not inclusive)." + } + ] + } + ], + "desc": "

      Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

      \n

      This is the same behavior as buf.subarray().

      \n

      This method is not compatible with the Uint8Array.prototype.slice(),\nwhich is a superclass of Buffer. To copy the slice, use\nUint8Array.prototype.slice().

      \n
      const buf = Buffer.from('buffer');\n\nconst copiedBuf = Uint8Array.prototype.slice.call(buf);\ncopiedBuf[0]++;\nconsole.log(copiedBuf.toString());\n// Prints: cuffer\n\nconsole.log(buf.toString());\n// Prints: buffer\n
      " + }, + { + "textRaw": "`buf.swap16()`", + "type": "method", + "name": "swap16", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [] + } + ], + "desc": "

      Interprets buf as an array of unsigned 16-bit integers and swaps the\nbyte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length\nis not a multiple of 2.

      \n
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap16();\n\nconsole.log(buf1);\n// Prints: <Buffer 02 01 04 03 06 05 08 07>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap16();\n// Throws ERR_INVALID_BUFFER_SIZE.\n
      \n

      One convenient use of buf.swap16() is to perform a fast in-place conversion\nbetween UTF-16 little-endian and UTF-16 big-endian:

      \n
      const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');\nbuf.swap16(); // Convert to big-endian UTF-16 text.\n
      " + }, + { + "textRaw": "`buf.swap32()`", + "type": "method", + "name": "swap32", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [] + } + ], + "desc": "

      Interprets buf as an array of unsigned 32-bit integers and swaps the\nbyte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length\nis not a multiple of 4.

      \n
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap32();\n\nconsole.log(buf1);\n// Prints: <Buffer 04 03 02 01 08 07 06 05>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap32();\n// Throws ERR_INVALID_BUFFER_SIZE.\n
      " + }, + { + "textRaw": "`buf.swap64()`", + "type": "method", + "name": "swap64", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A reference to `buf`.", + "name": "return", + "type": "Buffer", + "desc": "A reference to `buf`." + }, + "params": [] + } + ], + "desc": "

      Interprets buf as an array of 64-bit numbers and swaps byte order in-place.\nThrows ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.

      \n
      const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap64();\n\nconsole.log(buf1);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap64();\n// Throws ERR_INVALID_BUFFER_SIZE.\n
      " + }, + { + "textRaw": "`buf.toJSON()`", + "type": "method", + "name": "toJSON", + "meta": { + "added": [ + "v0.9.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns a JSON representation of buf. JSON.stringify() implicitly calls\nthis function when stringifying a Buffer instance.

      \n

      Buffer.from() accepts objects in the format returned from this method.\nIn particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

      \n
      const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);\nconst json = JSON.stringify(buf);\n\nconsole.log(json);\n// Prints: {\"type\":\"Buffer\",\"data\":[1,2,3,4,5]}\n\nconst copy = JSON.parse(json, (key, value) => {\n  return value && value.type === 'Buffer' ?\n    Buffer.from(value) :\n    value;\n});\n\nconsole.log(copy);\n// Prints: <Buffer 01 02 03 04 05>\n
      " + }, + { + "textRaw": "`buf.toString([encoding[, start[, end]]])`", + "type": "method", + "name": "toString", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The character encoding to use. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The character encoding to use." + }, + { + "textRaw": "`start` {integer} The byte offset to start decoding at. **Default:** `0`.", + "name": "start", + "type": "integer", + "default": "`0`", + "desc": "The byte offset to start decoding at." + }, + { + "textRaw": "`end` {integer} The byte offset to stop decoding at (not inclusive). **Default:** [`buf.length`][].", + "name": "end", + "type": "integer", + "default": "[`buf.length`][]", + "desc": "The byte offset to stop decoding at (not inclusive)." + } + ] + } + ], + "desc": "

      Decodes buf to a string according to the specified character encoding in\nencoding. start and end may be passed to decode only a subset of buf.

      \n

      If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8,\nthen each invalid byte is replaced with the replacement character U+FFFD.

      \n

      The maximum length of a string instance (in UTF-16 code units) is available\nas buffer.constants.MAX_STRING_LENGTH.

      \n
      const buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n  // 97 is the decimal ASCII value for 'a'.\n  buf1[i] = i + 97;\n}\n\nconsole.log(buf1.toString('utf8'));\n// Prints: abcdefghijklmnopqrstuvwxyz\nconsole.log(buf1.toString('utf8', 0, 5));\n// Prints: abcde\n\nconst buf2 = Buffer.from('tést');\n\nconsole.log(buf2.toString('hex'));\n// Prints: 74c3a97374\nconsole.log(buf2.toString('utf8', 0, 3));\n// Prints: té\nconsole.log(buf2.toString(undefined, 0, 3));\n// Prints: té\n
      " + }, + { + "textRaw": "`buf.values()`", + "type": "method", + "name": "values", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Creates and returns an iterator for buf values (bytes). This function is\ncalled automatically when a Buffer is used in a for..of statement.

      \n
      const buf = Buffer.from('buffer');\n\nfor (const value of buf.values()) {\n  console.log(value);\n}\n// Prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\n\nfor (const value of buf) {\n  console.log(value);\n}\n// Prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\n
      " + }, + { + "textRaw": "`buf.write(string[, offset[, length]][, encoding])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} Number of bytes written.", + "name": "return", + "type": "integer", + "desc": "Number of bytes written." + }, + "params": [ + { + "textRaw": "`string` {string} String to write to `buf`.", + "name": "string", + "type": "string", + "desc": "String to write to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write `string`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write `string`." + }, + { + "textRaw": "`length` {integer} Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). **Default:** `buf.length - offset`.", + "name": "length", + "type": "integer", + "default": "`buf.length - offset`", + "desc": "Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`)." + }, + { + "textRaw": "`encoding` {string} The character encoding of `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The character encoding of `string`." + } + ] + } + ], + "desc": "

      Writes string to buf at offset according to the character encoding in\nencoding. The length parameter is the number of bytes to write. If buf did\nnot contain enough space to fit the entire string, only part of string will be\nwritten. However, partially encoded characters will not be written.

      \n
      const buf = Buffer.alloc(256);\n\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\n\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n// Prints: 12 bytes: ½ + ¼ = ¾\n\nconst buffer = Buffer.alloc(10);\n\nconst length = buffer.write('abcd', 8);\n\nconsole.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);\n// Prints: 2 bytes : ab\n
      " + }, + { + "textRaw": "`buf.writeBigInt64BE(value[, offset])`", + "type": "method", + "name": "writeBigInt64BE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian.

      \n

      value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64BE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n
      " + }, + { + "textRaw": "`buf.writeBigInt64LE(value[, offset])`", + "type": "method", + "name": "writeBigInt64LE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian.

      \n

      value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64LE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n
      " + }, + { + "textRaw": "`buf.writeBigUInt64BE(value[, offset])`", + "type": "method", + "name": "writeBigUInt64BE", + "meta": { + "added": [ + "v12.0.0", + "v10.20.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.writeBigUint64BE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64BE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de ca fa fe ca ce fa de>\n
      " + }, + { + "textRaw": "`buf.writeBigUInt64LE(value[, offset])`", + "type": "method", + "name": "writeBigUInt64LE", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34960", + "description": "This function is also available as `buf.writeBigUint64LE()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {bigint} Number to be written to `buf`.", + "name": "value", + "type": "bigint", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64LE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de fa ce ca fe fa ca de>\n
      " + }, + { + "textRaw": "`buf.writeDoubleBE(value[, offset])`", + "type": "method", + "name": "writeDoubleBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a JavaScript number. Behavior is undefined when value is anything\nother than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>\n
      " + }, + { + "textRaw": "`buf.writeDoubleLE(value[, offset])`", + "type": "method", + "name": "writeDoubleLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a JavaScript number. Behavior is undefined when value is anything\nother than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleLE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>\n
      " + }, + { + "textRaw": "`buf.writeFloatBE(value[, offset])`", + "type": "method", + "name": "writeFloatBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. Behavior is\nundefined when value is anything other than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 4f 4a fe bb>\n\n
      " + }, + { + "textRaw": "`buf.writeFloatLE(value[, offset])`", + "type": "method", + "name": "writeFloatLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {number} Number to be written to `buf`.", + "name": "value", + "type": "number", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. Behavior is\nundefined when value is anything other than a JavaScript number.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer bb fe 4a 4f>\n
      " + }, + { + "textRaw": "`buf.writeInt8(value[, offset])`", + "type": "method", + "name": "writeInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset. value must be a valid\nsigned 8-bit integer. Behavior is undefined when value is anything other than\na signed 8-bit integer.

      \n

      value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\n\nconsole.log(buf);\n// Prints: <Buffer 02 fe>\n
      " + }, + { + "textRaw": "`buf.writeInt16BE(value[, offset])`", + "type": "method", + "name": "writeInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid signed 16-bit integer. Behavior is undefined when value is\nanything other than a signed 16-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16BE(0x0102, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02>\n
      " + }, + { + "textRaw": "`buf.writeInt16LE(value[, offset])`", + "type": "method", + "name": "writeInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid signed 16-bit integer. Behavior is undefined when value is\nanything other than a signed 16-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16LE(0x0304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 04 03>\n
      " + }, + { + "textRaw": "`buf.writeInt32BE(value[, offset])`", + "type": "method", + "name": "writeInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid signed 32-bit integer. Behavior is undefined when value is\nanything other than a signed 32-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32BE(0x01020304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04>\n
      " + }, + { + "textRaw": "`buf.writeInt32LE(value[, offset])`", + "type": "method", + "name": "writeInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid signed 32-bit integer. Behavior is undefined when value is\nanything other than a signed 32-bit integer.

      \n

      The value is interpreted and written as a two's complement signed integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32LE(0x05060708, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05>\n
      " + }, + { + "textRaw": "`buf.writeIntBE(value, offset, byteLength)`", + "type": "method", + "name": "writeIntBE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when\nvalue is anything other than a signed integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n\n
      " + }, + { + "textRaw": "`buf.writeIntLE(value, offset, byteLength)`", + "type": "method", + "name": "writeIntLE", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas little-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than a signed integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n
      " + }, + { + "textRaw": "`buf.writeUInt8(value[, offset])`", + "type": "method", + "name": "writeUInt8", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint8()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset. value must be a\nvalid unsigned 8-bit integer. Behavior is undefined when value is anything\nother than an unsigned 8-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n// Prints: <Buffer 03 04 23 42>\n
      " + }, + { + "textRaw": "`buf.writeUInt16BE(value[, offset])`", + "type": "method", + "name": "writeUInt16BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint16BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid unsigned 16-bit integer. Behavior is undefined when value\nis anything other than an unsigned 16-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer de ad be ef>\n
      " + }, + { + "textRaw": "`buf.writeUInt16LE(value[, offset])`", + "type": "method", + "name": "writeUInt16LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint16LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid unsigned 16-bit integer. Behavior is undefined when value is\nanything other than an unsigned 16-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer ad de ef be>\n
      " + }, + { + "textRaw": "`buf.writeUInt32BE(value[, offset])`", + "type": "method", + "name": "writeUInt32BE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint32BE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as big-endian. The value\nmust be a valid unsigned 32-bit integer. Behavior is undefined when value\nis anything other than an unsigned 32-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer fe ed fa ce>\n
      " + }, + { + "textRaw": "`buf.writeUInt32LE(value[, offset])`", + "type": "method", + "name": "writeUInt32LE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUint32LE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.", + "name": "offset", + "type": "integer", + "default": "`0`", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`." + } + ] + } + ], + "desc": "

      Writes value to buf at the specified offset as little-endian. The value\nmust be a valid unsigned 32-bit integer. Behavior is undefined when value is\nanything other than an unsigned 32-bit integer.

      \n
      const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer ce fa ed fe>\n
      " + }, + { + "textRaw": "`buf.writeUIntBE(value, offset, byteLength)`", + "type": "method", + "name": "writeUIntBE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUintBE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas big-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than an unsigned integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n
      " + }, + { + "textRaw": "`buf.writeUIntLE(value, offset, byteLength)`", + "type": "method", + "name": "writeUIntLE", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34729", + "description": "This function is also available as `buf.writeUintLE()`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", + "name": "return", + "type": "integer", + "desc": "`offset` plus the number of bytes written." + }, + "params": [ + { + "textRaw": "`value` {integer} Number to be written to `buf`.", + "name": "value", + "type": "integer", + "desc": "Number to be written to `buf`." + }, + { + "textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.", + "name": "offset", + "type": "integer", + "desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`." + }, + { + "textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.", + "name": "byteLength", + "type": "integer", + "desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`." + } + ] + } + ], + "desc": "

      Writes byteLength bytes of value to buf at the specified offset\nas little-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than an unsigned integer.

      \n
      const buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`array` {integer[]} An array of bytes to copy from.", + "name": "array", + "type": "integer[]", + "desc": "An array of bytes to copy from." + } + ], + "desc": "

      See Buffer.from(array).

      " + }, + { + "params": [ + { + "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].", + "name": "arrayBuffer", + "type": "ArrayBuffer|SharedArrayBuffer", + "desc": "An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][]." + }, + { + "textRaw": "`byteOffset` {integer} Index of first byte to expose. **Default:** `0`.", + "name": "byteOffset", + "type": "integer", + "default": "`0`", + "desc": "Index of first byte to expose." + }, + { + "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`.", + "name": "length", + "type": "integer", + "default": "`arrayBuffer.byteLength - byteOffset`", + "desc": "Number of bytes to expose." + } + ], + "desc": "

      See\nBuffer.from(arrayBuffer[, byteOffset[, length]]).

      " + }, + { + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from which to copy data.", + "name": "buffer", + "type": "Buffer|Uint8Array", + "desc": "An existing `Buffer` or [`Uint8Array`][] from which to copy data." + } + ], + "desc": "

      See Buffer.from(buffer).

      " + }, + { + "params": [ + { + "textRaw": "`size` {integer} The desired length of the new `Buffer`.", + "name": "size", + "type": "integer", + "desc": "The desired length of the new `Buffer`." + } + ], + "desc": "

      See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the\nconstructor is equivalent to Buffer.alloc().

      " + }, + { + "params": [ + { + "textRaw": "`string` {string} String to encode.", + "name": "string", + "type": "string", + "desc": "String to encode." + }, + { + "textRaw": "`encoding` {string} The encoding of `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding of `string`." + } + ], + "desc": "

      See Buffer.from(string[, encoding]).

      " + } + ] + } + ], + "type": "module", + "displayName": "Buffer" + } + ] +} \ No newline at end of file diff --git a/doc/api/child_process.html b/doc/api/child_process.html new file mode 100644 index 0000000000000000000000000000000000000000..dab73f9836d87e10b241b59e415560b3eab29ba0 --- /dev/null +++ b/doc/api/child_process.html @@ -0,0 +1,1584 @@ + + + + + + + Child process | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Child process#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/child_process.js

      +

      The child_process module provides the ability to spawn child processes in +a manner that is similar, but not identical, to popen(3). This capability +is primarily provided by the child_process.spawn() function:

      +
      const { spawn } = require('child_process');
      +const ls = spawn('ls', ['-lh', '/usr']);
      +
      +ls.stdout.on('data', (data) => {
      +  console.log(`stdout: ${data}`);
      +});
      +
      +ls.stderr.on('data', (data) => {
      +  console.error(`stderr: ${data}`);
      +});
      +
      +ls.on('close', (code) => {
      +  console.log(`child process exited with code ${code}`);
      +});
      +

      By default, pipes for stdin, stdout, and stderr are established between +the parent Node.js process and the spawned child. These pipes have +limited (and platform-specific) capacity. If the child process writes to +stdout in excess of that limit without the output being captured, the child +process will block waiting for the pipe buffer to accept more data. This is +identical to the behavior of pipes in the shell. Use the { stdio: 'ignore' } +option if the output will not be consumed.

      +

      The command lookup will be performed using options.env.PATH environment +variable if passed in options object, otherwise process.env.PATH will be +used. To account for the fact that Windows environment variables are +case-insensitive Node.js will lexicographically sort all env keys and choose +the first one case-insensitively matching PATH to perform command lookup. +This may lead to issues on Windows when passing objects to env option that +have multiple variants of PATH variable.

      +

      The child_process.spawn() method spawns the child process asynchronously, +without blocking the Node.js event loop. The child_process.spawnSync() +function provides equivalent functionality in a synchronous manner that blocks +the event loop until the spawned process either exits or is terminated.

      +

      For convenience, the child_process module provides a handful of synchronous +and asynchronous alternatives to child_process.spawn() and +child_process.spawnSync(). Each of these alternatives are implemented on +top of child_process.spawn() or child_process.spawnSync().

      + +

      For certain use cases, such as automating shell scripts, the +synchronous counterparts may be more convenient. In many cases, however, +the synchronous methods can have significant impact on performance due to +stalling the event loop while spawned processes complete.

      +

      Asynchronous process creation#

      +

      The child_process.spawn(), child_process.fork(), child_process.exec(), +and child_process.execFile() methods all follow the idiomatic asynchronous +programming pattern typical of other Node.js APIs.

      +

      Each of the methods returns a ChildProcess instance. These objects +implement the Node.js EventEmitter API, allowing the parent process to +register listener functions that are called when certain events occur during +the life cycle of the child process.

      +

      The child_process.exec() and child_process.execFile() methods +additionally allow for an optional callback function to be specified that is +invoked when the child process terminates.

      +

      Spawning .bat and .cmd files on Windows#

      +

      The importance of the distinction between child_process.exec() and +child_process.execFile() can vary based on platform. On Unix-type +operating systems (Unix, Linux, macOS) child_process.execFile() can be +more efficient because it does not spawn a shell by default. On Windows, +however, .bat and .cmd files are not executable on their own without a +terminal, and therefore cannot be launched using child_process.execFile(). +When running on Windows, .bat and .cmd files can be invoked using +child_process.spawn() with the shell option set, with +child_process.exec(), or by spawning cmd.exe and passing the .bat or +.cmd file as an argument (which is what the shell option and +child_process.exec() do). In any case, if the script filename contains +spaces it needs to be quoted.

      +
      // On Windows Only...
      +const { spawn } = require('child_process');
      +const bat = spawn('cmd.exe', ['/c', 'my.bat']);
      +
      +bat.stdout.on('data', (data) => {
      +  console.log(data.toString());
      +});
      +
      +bat.stderr.on('data', (data) => {
      +  console.error(data.toString());
      +});
      +
      +bat.on('exit', (code) => {
      +  console.log(`Child exited with code ${code}`);
      +});
      +
      // OR...
      +const { exec, spawn } = require('child_process');
      +exec('my.bat', (err, stdout, stderr) => {
      +  if (err) {
      +    console.error(err);
      +    return;
      +  }
      +  console.log(stdout);
      +});
      +
      +// Script with spaces in the filename:
      +const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
      +// or:
      +exec('"my script.cmd" a b', (err, stdout, stderr) => {
      +  // ...
      +});
      +

      child_process.exec(command[, options][, callback])#

      + + +

      Spawns a shell then executes the command within that shell, buffering any +generated output. The command string passed to the exec function is processed +directly by the shell and special characters (vary based on +shell) +need to be dealt with accordingly:

      +
      exec('"/path/to/test file/test.sh" arg1 arg2');
      +// Double quotes are used so that the space in the path is not interpreted as
      +// a delimiter of multiple arguments.
      +
      +exec('echo "The \\$HOME variable is $HOME"');
      +// The $HOME variable is escaped in the first instance, but not in the second.
      +

      Never pass unsanitized user input to this function. Any input containing shell +metacharacters may be used to trigger arbitrary command execution.

      +

      If a callback function is provided, it is called with the arguments +(error, stdout, stderr). On success, error will be null. On error, +error will be an instance of Error. The error.code property will be +the exit code of the process. By convention, any exit code other than 0 +indicates an error. error.signal will be the signal that terminated the +process.

      +

      The stdout and stderr arguments passed to the callback will contain the +stdout and stderr output of the child process. By default, Node.js will decode +the output as UTF-8 and pass strings to the callback. The encoding option +can be used to specify the character encoding used to decode the stdout and +stderr output. If encoding is 'buffer', or an unrecognized character +encoding, Buffer objects will be passed to the callback instead.

      +
      const { exec } = require('child_process');
      +exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
      +  if (error) {
      +    console.error(`exec error: ${error}`);
      +    return;
      +  }
      +  console.log(`stdout: ${stdout}`);
      +  console.error(`stderr: ${stderr}`);
      +});
      +

      If timeout is greater than 0, the parent will send the signal +identified by the killSignal property (the default is 'SIGTERM') if the +child runs longer than timeout milliseconds.

      +

      Unlike the exec(3) POSIX system call, child_process.exec() does not replace +the existing process and uses a shell to execute the command.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with stdout and stderr properties. The returned +ChildProcess instance is attached to the Promise as a child property. In +case of an error (including any error resulting in an exit code other than 0), a +rejected promise is returned, with the same error object given in the +callback, but with two additional properties stdout and stderr.

      +
      const util = require('util');
      +const exec = util.promisify(require('child_process').exec);
      +
      +async function lsExample() {
      +  const { stdout, stderr } = await exec('ls');
      +  console.log('stdout:', stdout);
      +  console.error('stderr:', stderr);
      +}
      +lsExample();
      +

      child_process.execFile(file[, args][, options][, callback])#

      + +
        +
      • file <string> The name or path of the executable file to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • encoding <string> Default: 'utf8'
        • +
        • timeout <number> Default: 0
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated and any output is +truncated. See caveat at maxBuffer and Unicode. +Default: 1024 * 1024.
        • +
        • killSignal <string> | <integer> Default: 'SIGTERM'
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. Default: false.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        +
      • +
      • callback <Function> Called with the output when process terminates. + +
      • +
      • Returns: <ChildProcess>
      • +
      +

      The child_process.execFile() function is similar to child_process.exec() +except that it does not spawn a shell by default. Rather, the specified +executable file is spawned directly as a new process making it slightly more +efficient than child_process.exec().

      +

      The same options as child_process.exec() are supported. Since a shell is +not spawned, behaviors such as I/O redirection and file globbing are not +supported.

      +
      const { execFile } = require('child_process');
      +const child = execFile('node', ['--version'], (error, stdout, stderr) => {
      +  if (error) {
      +    throw error;
      +  }
      +  console.log(stdout);
      +});
      +

      The stdout and stderr arguments passed to the callback will contain the +stdout and stderr output of the child process. By default, Node.js will decode +the output as UTF-8 and pass strings to the callback. The encoding option +can be used to specify the character encoding used to decode the stdout and +stderr output. If encoding is 'buffer', or an unrecognized character +encoding, Buffer objects will be passed to the callback instead.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with stdout and stderr properties. The returned +ChildProcess instance is attached to the Promise as a child property. In +case of an error (including any error resulting in an exit code other than 0), a +rejected promise is returned, with the same error object given in the +callback, but with two additional properties stdout and stderr.

      +
      const util = require('util');
      +const execFile = util.promisify(require('child_process').execFile);
      +async function getVersion() {
      +  const { stdout } = await execFile('node', ['--version']);
      +  console.log(stdout);
      +}
      +getVersion();
      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      child_process.fork(modulePath[, args][, options])#

      + +
        +
      • modulePath <string> The module to run in the child.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • detached <boolean> Prepare child to run independently of its parent +process. Specific behavior depends on the platform, see +options.detached).
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • execPath <string> Executable used to create the child process.
        • +
        • execArgv <string[]> List of string arguments passed to the executable. +Default: process.execArgv.
        • +
        • serialization <string> Specify the kind of serialization used for sending +messages between processes. Possible values are 'json' and 'advanced'. +See Advanced serialization for more details. Default: 'json'.
        • +
        • silent <boolean> If true, stdin, stdout, and stderr of the child will be +piped to the parent, otherwise they will be inherited from the parent, see +the 'pipe' and 'inherit' options for child_process.spawn()'s +stdio for more details. Default: false.
        • +
        • stdio <Array> | <string> See child_process.spawn()'s stdio. +When this option is provided, it overrides silent. If the array variant +is used, it must contain exactly one item with value 'ipc' or an error +will be thrown. For instance [0, 1, 2, 'ipc'].
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. Default: false.
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        +
      • +
      • Returns: <ChildProcess>
      • +
      +

      The child_process.fork() method is a special case of +child_process.spawn() used specifically to spawn new Node.js processes. +Like child_process.spawn(), a ChildProcess object is returned. The +returned ChildProcess will have an additional communication channel +built-in that allows messages to be passed back and forth between the parent and +child. See subprocess.send() for details.

      +

      Keep in mind that spawned Node.js child processes are +independent of the parent with exception of the IPC communication channel +that is established between the two. Each process has its own memory, with +their own V8 instances. Because of the additional resource allocations +required, spawning a large number of child Node.js processes is not +recommended.

      +

      By default, child_process.fork() will spawn new Node.js instances using the +process.execPath of the parent process. The execPath property in the +options object allows for an alternative execution path to be used.

      +

      Node.js processes launched with a custom execPath will communicate with the +parent process using the file descriptor (fd) identified using the +environment variable NODE_CHANNEL_FD on the child process.

      +

      Unlike the fork(2) POSIX system call, child_process.fork() does not clone the +current process.

      +

      The shell option available in child_process.spawn() is not supported by +child_process.fork() and will be ignored if set.

      +

      child_process.spawn(command[, args][, options])#

      + +
        +
      • command <string> The command to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • argv0 <string> Explicitly set the value of argv[0] sent to the child +process. This will be set to command if not specified.
        • +
        • stdio <Array> | <string> Child's stdio configuration (see +options.stdio).
        • +
        • detached <boolean> Prepare child to run independently of its parent +process. Specific behavior depends on the platform, see +options.detached).
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • serialization <string> Specify the kind of serialization used for sending +messages between processes. Possible values are 'json' and 'advanced'. +See Advanced serialization for more details. Default: 'json'.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. This is set to true automatically +when shell is specified and is CMD. Default: false.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      • Returns: <ChildProcess>
      • +
      +

      The child_process.spawn() method spawns a new process using the given +command, with command line arguments in args. If omitted, args defaults +to an empty array.

      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      A third argument may be used to specify additional options, with these defaults:

      +
      const defaults = {
      +  cwd: undefined,
      +  env: process.env
      +};
      +

      Use cwd to specify the working directory from which the process is spawned. +If not given, the default is to inherit the current working directory.

      +

      Use env to specify environment variables that will be visible to the new +process, the default is process.env.

      +

      undefined values in env will be ignored.

      +

      Example of running ls -lh /usr, capturing stdout, stderr, and the +exit code:

      +
      const { spawn } = require('child_process');
      +const ls = spawn('ls', ['-lh', '/usr']);
      +
      +ls.stdout.on('data', (data) => {
      +  console.log(`stdout: ${data}`);
      +});
      +
      +ls.stderr.on('data', (data) => {
      +  console.error(`stderr: ${data}`);
      +});
      +
      +ls.on('close', (code) => {
      +  console.log(`child process exited with code ${code}`);
      +});
      +

      Example: A very elaborate way to run ps ax | grep ssh

      +
      const { spawn } = require('child_process');
      +const ps = spawn('ps', ['ax']);
      +const grep = spawn('grep', ['ssh']);
      +
      +ps.stdout.on('data', (data) => {
      +  grep.stdin.write(data);
      +});
      +
      +ps.stderr.on('data', (data) => {
      +  console.error(`ps stderr: ${data}`);
      +});
      +
      +ps.on('close', (code) => {
      +  if (code !== 0) {
      +    console.log(`ps process exited with code ${code}`);
      +  }
      +  grep.stdin.end();
      +});
      +
      +grep.stdout.on('data', (data) => {
      +  console.log(data.toString());
      +});
      +
      +grep.stderr.on('data', (data) => {
      +  console.error(`grep stderr: ${data}`);
      +});
      +
      +grep.on('close', (code) => {
      +  if (code !== 0) {
      +    console.log(`grep process exited with code ${code}`);
      +  }
      +});
      +

      Example of checking for failed spawn:

      +
      const { spawn } = require('child_process');
      +const subprocess = spawn('bad_command');
      +
      +subprocess.on('error', (err) => {
      +  console.error('Failed to start subprocess.');
      +});
      +

      Certain platforms (macOS, Linux) will use the value of argv[0] for the process +title while others (Windows, SunOS) will use command.

      +

      Node.js currently overwrites argv[0] with process.execPath on startup, so +process.argv[0] in a Node.js child process will not match the argv0 +parameter passed to spawn from the parent, retrieve it with the +process.argv0 property instead.

      +

      options.detached#

      + +

      On Windows, setting options.detached to true makes it possible for the +child process to continue running after the parent exits. The child will have +its own console window. Once enabled for a child process, it cannot be +disabled.

      +

      On non-Windows platforms, if options.detached is set to true, the child +process will be made the leader of a new process group and session. Child +processes may continue running after the parent exits regardless of whether +they are detached or not. See setsid(2) for more information.

      +

      By default, the parent will wait for the detached child to exit. To prevent the +parent from waiting for a given subprocess to exit, use the +subprocess.unref() method. Doing so will cause the parent's event loop to not +include the child in its reference count, allowing the parent to exit +independently of the child, unless there is an established IPC channel between +the child and the parent.

      +

      When using the detached option to start a long-running process, the process +will not stay running in the background after the parent exits unless it is +provided with a stdio configuration that is not connected to the parent. +If the parent's stdio is inherited, the child will remain attached to the +controlling terminal.

      +

      Example of a long-running process, by detaching and also ignoring its parent +stdio file descriptors, in order to ignore the parent's termination:

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn(process.argv[0], ['child_program.js'], {
      +  detached: true,
      +  stdio: 'ignore'
      +});
      +
      +subprocess.unref();
      +

      Alternatively one can redirect the child process' output into files:

      +
      const fs = require('fs');
      +const { spawn } = require('child_process');
      +const out = fs.openSync('./out.log', 'a');
      +const err = fs.openSync('./out.log', 'a');
      +
      +const subprocess = spawn('prg', [], {
      +  detached: true,
      +  stdio: [ 'ignore', out, err ]
      +});
      +
      +subprocess.unref();
      +

      options.stdio#

      + +

      The options.stdio option is used to configure the pipes that are established +between the parent and child process. By default, the child's stdin, stdout, +and stderr are redirected to corresponding subprocess.stdin, +subprocess.stdout, and subprocess.stderr streams on the +ChildProcess object. This is equivalent to setting the options.stdio +equal to ['pipe', 'pipe', 'pipe'].

      +

      For convenience, options.stdio may be one of the following strings:

      +
        +
      • 'pipe': equivalent to ['pipe', 'pipe', 'pipe'] (the default)
      • +
      • 'ignore': equivalent to ['ignore', 'ignore', 'ignore']
      • +
      • 'inherit': equivalent to ['inherit', 'inherit', 'inherit'] or [0, 1, 2]
      • +
      +

      Otherwise, the value of options.stdio is an array where each index corresponds +to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout, +and stderr, respectively. Additional fds can be specified to create additional +pipes between the parent and child. The value is one of the following:

      +
        +
      1. +

        'pipe': Create a pipe between the child process and the parent process. +The parent end of the pipe is exposed to the parent as a property on the +child_process object as subprocess.stdio[fd]. Pipes +created for fds 0, 1, and 2 are also available as subprocess.stdin, +subprocess.stdout and subprocess.stderr, respectively.

        +
      2. +
      3. +

        'ipc': Create an IPC channel for passing messages/file descriptors +between parent and child. A ChildProcess may have at most one IPC +stdio file descriptor. Setting this option enables the +subprocess.send() method. If the child is a Node.js process, the +presence of an IPC channel will enable process.send() and +process.disconnect() methods, as well as 'disconnect' and +'message' events within the child.

        +

        Accessing the IPC channel fd in any way other than process.send() +or using the IPC channel with a child process that is not a Node.js instance +is not supported.

        +
      4. +
      5. +

        'ignore': Instructs Node.js to ignore the fd in the child. While Node.js +will always open fds 0, 1, and 2 for the processes it spawns, setting the fd +to 'ignore' will cause Node.js to open /dev/null and attach it to the +child's fd.

        +
      6. +
      7. +

        'inherit': Pass through the corresponding stdio stream to/from the +parent process. In the first three positions, this is equivalent to +process.stdin, process.stdout, and process.stderr, respectively. In +any other position, equivalent to 'ignore'.

        +
      8. +
      9. +

        <Stream> object: Share a readable or writable stream that refers to a tty, +file, socket, or a pipe with the child process. The stream's underlying +file descriptor is duplicated in the child process to the fd that +corresponds to the index in the stdio array. The stream must have an +underlying descriptor (file streams do not until the 'open' event has +occurred).

        +
      10. +
      11. +

        Positive integer: The integer value is interpreted as a file descriptor +that is currently open in the parent process. It is shared with the child +process, similar to how <Stream> objects can be shared. Passing sockets +is not supported on Windows.

        +
      12. +
      13. +

        null, undefined: Use default value. For stdio fds 0, 1, and 2 (in other +words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the +default is 'ignore'.

        +
      14. +
      +
      const { spawn } = require('child_process');
      +
      +// Child will use parent's stdios.
      +spawn('prg', [], { stdio: 'inherit' });
      +
      +// Spawn child sharing only stderr.
      +spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
      +
      +// Open an extra fd=4, to interact with programs presenting a
      +// startd-style interface.
      +spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
      +

      It is worth noting that when an IPC channel is established between the +parent and child processes, and the child is a Node.js process, the child +is launched with the IPC channel unreferenced (using unref()) until the +child registers an event handler for the 'disconnect' event +or the 'message' event. This allows the child to exit +normally without the process being held open by the open IPC channel.

      +

      On Unix-like operating systems, the child_process.spawn() method +performs memory operations synchronously before decoupling the event loop +from the child. Applications with a large memory footprint may find frequent +child_process.spawn() calls to be a bottleneck. For more information, +see V8 issue 7381.

      +

      See also: child_process.exec() and child_process.fork().

      +

      Synchronous process creation#

      +

      The child_process.spawnSync(), child_process.execSync(), and +child_process.execFileSync() methods are synchronous and will block the +Node.js event loop, pausing execution of any additional code until the spawned +process exits.

      +

      Blocking calls like these are mostly useful for simplifying general-purpose +scripting tasks and for simplifying the loading/processing of application +configuration at startup.

      +

      child_process.execFileSync(file[, args][, options])#

      + +
        +
      • file <string> The name or path of the executable file to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • input <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed +as stdin to the spawned process. Supplying this value will override +stdio[0].
        • +
        • stdio <string> | <Array> Child's stdio configuration. stderr by default will +be output to the parent process' stderr unless stdio is specified. +Default: 'pipe'.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • timeout <number> In milliseconds the maximum amount of time the process +is allowed to run. Default: undefined.
        • +
        • killSignal <string> | <integer> The signal value to be used when the spawned +process will be killed. Default: 'SIGTERM'.
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated. See caveat at +maxBuffer and Unicode. Default: 1024 * 1024.
        • +
        • encoding <string> The encoding used for all stdio inputs and outputs. +Default: 'buffer'.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        +
      • +
      • Returns: <Buffer> | <string> The stdout from the command.
      • +
      +

      The child_process.execFileSync() method is generally identical to +child_process.execFile() with the exception that the method will not +return until the child process has fully closed. When a timeout has been +encountered and killSignal is sent, the method won't return until the process +has completely exited.

      +

      If the child process intercepts and handles the SIGTERM signal and +does not exit, the parent process will still wait until the child process has +exited.

      +

      If the process times out or has a non-zero exit code, this method will throw an +Error that will include the full result of the underlying +child_process.spawnSync().

      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      child_process.execSync(command[, options])#

      + +
        +
      • command <string> The command to run.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • input <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed +as stdin to the spawned process. Supplying this value will override +stdio[0].
        • +
        • stdio <string> | <Array> Child's stdio configuration. stderr by default will +be output to the parent process' stderr unless stdio is specified. +Default: 'pipe'.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • shell <string> Shell to execute the command with. See +Shell requirements and Default Windows shell. Default: +'/bin/sh' on Unix, process.env.ComSpec on Windows.
        • +
        • uid <number> Sets the user identity of the process. (See setuid(2)).
        • +
        • gid <number> Sets the group identity of the process. (See setgid(2)).
        • +
        • timeout <number> In milliseconds the maximum amount of time the process +is allowed to run. Default: undefined.
        • +
        • killSignal <string> | <integer> The signal value to be used when the spawned +process will be killed. Default: 'SIGTERM'.
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated and any output is +truncated. See caveat at maxBuffer and Unicode. +Default: 1024 * 1024.
        • +
        • encoding <string> The encoding used for all stdio inputs and outputs. +Default: 'buffer'.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      • Returns: <Buffer> | <string> The stdout from the command.
      • +
      +

      The child_process.execSync() method is generally identical to +child_process.exec() with the exception that the method will not return +until the child process has fully closed. When a timeout has been encountered +and killSignal is sent, the method won't return until the process has +completely exited. If the child process intercepts and handles the SIGTERM +signal and doesn't exit, the parent process will wait until the child process +has exited.

      +

      If the process times out or has a non-zero exit code, this method will throw. +The Error object will contain the entire result from +child_process.spawnSync().

      +

      Never pass unsanitized user input to this function. Any input containing shell +metacharacters may be used to trigger arbitrary command execution.

      +

      child_process.spawnSync(command[, args][, options])#

      + +
        +
      • command <string> The command to run.
      • +
      • args <string[]> List of string arguments.
      • +
      • options <Object> +
          +
        • cwd <string> Current working directory of the child process.
        • +
        • input <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed +as stdin to the spawned process. Supplying this value will override +stdio[0].
        • +
        • argv0 <string> Explicitly set the value of argv[0] sent to the child +process. This will be set to command if not specified.
        • +
        • stdio <string> | <Array> Child's stdio configuration.
        • +
        • env <Object> Environment key-value pairs. Default: process.env.
        • +
        • uid <number> Sets the user identity of the process (see setuid(2)).
        • +
        • gid <number> Sets the group identity of the process (see setgid(2)).
        • +
        • timeout <number> In milliseconds the maximum amount of time the process +is allowed to run. Default: undefined.
        • +
        • killSignal <string> | <integer> The signal value to be used when the spawned +process will be killed. Default: 'SIGTERM'.
        • +
        • maxBuffer <number> Largest amount of data in bytes allowed on stdout or +stderr. If exceeded, the child process is terminated and any output is +truncated. See caveat at maxBuffer and Unicode. +Default: 1024 * 1024.
        • +
        • encoding <string> The encoding used for all stdio inputs and outputs. +Default: 'buffer'.
        • +
        • shell <boolean> | <string> If true, runs command inside of a shell. Uses +'/bin/sh' on Unix, and process.env.ComSpec on Windows. A different +shell can be specified as a string. See Shell requirements and +Default Windows shell. Default: false (no shell).
        • +
        • windowsVerbatimArguments <boolean> No quoting or escaping of arguments is +done on Windows. Ignored on Unix. This is set to true automatically +when shell is specified and is CMD. Default: false.
        • +
        • windowsHide <boolean> Hide the subprocess console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      • Returns: <Object> +
          +
        • pid <number> Pid of the child process.
        • +
        • output <Array> Array of results from stdio output.
        • +
        • stdout <Buffer> | <string> The contents of output[1].
        • +
        • stderr <Buffer> | <string> The contents of output[2].
        • +
        • status <number> | <null> The exit code of the subprocess, or null if the +subprocess terminated due to a signal.
        • +
        • signal <string> | <null> The signal used to kill the subprocess, or null if +the subprocess did not terminate due to a signal.
        • +
        • error <Error> The error object if the child process failed or timed out.
        • +
        +
      • +
      +

      The child_process.spawnSync() method is generally identical to +child_process.spawn() with the exception that the function will not return +until the child process has fully closed. When a timeout has been encountered +and killSignal is sent, the method won't return until the process has +completely exited. If the process intercepts and handles the SIGTERM signal +and doesn't exit, the parent process will wait until the child process has +exited.

      +

      If the shell option is enabled, do not pass unsanitized user input to this +function. Any input containing shell metacharacters may be used to trigger +arbitrary command execution.

      +

      Class: ChildProcess#

      + + +

      Instances of the ChildProcess represent spawned child processes.

      +

      Instances of ChildProcess are not intended to be created directly. Rather, +use the child_process.spawn(), child_process.exec(), +child_process.execFile(), or child_process.fork() methods to create +instances of ChildProcess.

      +

      Event: 'close'#

      + +
        +
      • code <number> The exit code if the child exited on its own.
      • +
      • signal <string> The signal by which the child process was terminated.
      • +
      +

      The 'close' event is emitted when the stdio streams of a child process have +been closed. This is distinct from the 'exit' event, since multiple +processes might share the same stdio streams.

      +
      const { spawn } = require('child_process');
      +const ls = spawn('ls', ['-lh', '/usr']);
      +
      +ls.stdout.on('data', (data) => {
      +  console.log(`stdout: ${data}`);
      +});
      +
      +ls.on('close', (code) => {
      +  console.log(`child process close all stdio with code ${code}`);
      +});
      +
      +ls.on('exit', (code) => {
      +  console.log(`child process exited with code ${code}`);
      +});
      +

      Event: 'disconnect'#

      + +

      The 'disconnect' event is emitted after calling the +subprocess.disconnect() method in parent process or +process.disconnect() in child process. After disconnecting it is no longer +possible to send or receive messages, and the subprocess.connected +property is false.

      +

      Event: 'error'#

      + +

      The 'error' event is emitted whenever:

      +
        +
      1. The process could not be spawned, or
      2. +
      3. The process could not be killed, or
      4. +
      5. Sending a message to the child process failed.
      6. +
      +

      The 'exit' event may or may not fire after an error has occurred. When +listening to both the 'exit' and 'error' events, guard +against accidentally invoking handler functions multiple times.

      +

      See also subprocess.kill() and subprocess.send().

      +

      Event: 'exit'#

      + +
        +
      • code <number> The exit code if the child exited on its own.
      • +
      • signal <string> The signal by which the child process was terminated.
      • +
      +

      The 'exit' event is emitted after the child process ends. If the process +exited, code is the final exit code of the process, otherwise null. If the +process terminated due to receipt of a signal, signal is the string name of +the signal, otherwise null. One of the two will always be non-null.

      +

      When the 'exit' event is triggered, child process stdio streams might still be +open.

      +

      Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js +processes will not terminate immediately due to receipt of those signals. +Rather, Node.js will perform a sequence of cleanup actions and then will +re-raise the handled signal.

      +

      See waitpid(2).

      +

      Event: 'message'#

      + + +

      The 'message' event is triggered when a child process uses +process.send() to send messages.

      +

      The message goes through serialization and parsing. The resulting +message might not be the same as what is originally sent.

      +

      If the serialization option was set to 'advanced' used when spawning the +child process, the message argument can contain data that JSON is not able +to represent. +See Advanced serialization for more details.

      +

      subprocess.channel#

      + +
        +
      • <Object> A pipe representing the IPC channel to the child process.
      • +
      +

      The subprocess.channel property is a reference to the child's IPC channel. If +no IPC channel currently exists, this property is undefined.

      +

      subprocess.connected#

      + +
        +
      • <boolean> Set to false after subprocess.disconnect() is called.
      • +
      +

      The subprocess.connected property indicates whether it is still possible to +send and receive messages from a child process. When subprocess.connected is +false, it is no longer possible to send or receive messages.

      +

      subprocess.disconnect()#

      + +

      Closes the IPC channel between parent and child, allowing the child to exit +gracefully once there are no other connections keeping it alive. After calling +this method the subprocess.connected and process.connected properties in +both the parent and child (respectively) will be set to false, and it will be +no longer possible to pass messages between the processes.

      +

      The 'disconnect' event will be emitted when there are no messages in the +process of being received. This will most often be triggered immediately after +calling subprocess.disconnect().

      +

      When the child process is a Node.js instance (e.g. spawned using +child_process.fork()), the process.disconnect() method can be invoked +within the child process to close the IPC channel as well.

      +

      subprocess.exitCode#

      + +

      The subprocess.exitCode property indicates the exit code of the child process. +If the child process is still running, the field will be null.

      +

      subprocess.kill([signal])#

      + + +

      The subprocess.kill() method sends a signal to the child process. If no +argument is given, the process will be sent the 'SIGTERM' signal. See +signal(7) for a list of available signals. This function returns true if +kill(2) succeeds, and false otherwise.

      +
      const { spawn } = require('child_process');
      +const grep = spawn('grep', ['ssh']);
      +
      +grep.on('close', (code, signal) => {
      +  console.log(
      +    `child process terminated due to receipt of signal ${signal}`);
      +});
      +
      +// Send SIGHUP to process.
      +grep.kill('SIGHUP');
      +

      The ChildProcess object may emit an 'error' event if the signal +cannot be delivered. Sending a signal to a child process that has already exited +is not an error but may have unforeseen consequences. Specifically, if the +process identifier (PID) has been reassigned to another process, the signal will +be delivered to that process instead which can have unexpected results.

      +

      While the function is called kill, the signal delivered to the child process +may not actually terminate the process.

      +

      See kill(2) for reference.

      +

      On Linux, child processes of child processes will not be terminated +when attempting to kill their parent. This is likely to happen when running a +new process in a shell or with the use of the shell option of ChildProcess:

      +
      'use strict';
      +const { spawn } = require('child_process');
      +
      +const subprocess = spawn(
      +  'sh',
      +  [
      +    '-c',
      +    `node -e "setInterval(() => {
      +      console.log(process.pid, 'is alive')
      +    }, 500);"`
      +  ], {
      +    stdio: ['inherit', 'inherit', 'inherit']
      +  }
      +);
      +
      +setTimeout(() => {
      +  subprocess.kill(); // Does not terminate the Node.js process in the shell.
      +}, 2000);
      +

      subprocess.killed#

      + +
        +
      • <boolean> Set to true after subprocess.kill() is used to successfully +send a signal to the child process.
      • +
      +

      The subprocess.killed property indicates whether the child process +successfully received a signal from subprocess.kill(). The killed property +does not indicate that the child process has been terminated.

      +

      subprocess.pid#

      + + +

      Returns the process identifier (PID) of the child process.

      +
      const { spawn } = require('child_process');
      +const grep = spawn('grep', ['ssh']);
      +
      +console.log(`Spawned child pid: ${grep.pid}`);
      +grep.stdin.end();
      +

      subprocess.ref()#

      + +

      Calling subprocess.ref() after making a call to subprocess.unref() will +restore the removed reference count for the child process, forcing the parent +to wait for the child to exit before exiting itself.

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn(process.argv[0], ['child_program.js'], {
      +  detached: true,
      +  stdio: 'ignore'
      +});
      +
      +subprocess.unref();
      +subprocess.ref();
      +

      subprocess.send(message[, sendHandle[, options]][, callback])#

      + +
        +
      • message <Object>
      • +
      • sendHandle <Handle>
      • +
      • options <Object> The options argument, if present, is an object used to +parameterize the sending of certain types of handles. options supports +the following properties: +
          +
        • keepOpen <boolean> A value that can be used when passing instances of +net.Socket. When true, the socket is kept open in the sending process. +Default: false.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <boolean>
      • +
      +

      When an IPC channel has been established between the parent and child ( +i.e. when using child_process.fork()), the subprocess.send() method can +be used to send messages to the child process. When the child process is a +Node.js instance, these messages can be received via the 'message' event.

      +

      The message goes through serialization and parsing. The resulting +message might not be the same as what is originally sent.

      +

      For example, in the parent script:

      +
      const cp = require('child_process');
      +const n = cp.fork(`${__dirname}/sub.js`);
      +
      +n.on('message', (m) => {
      +  console.log('PARENT got message:', m);
      +});
      +
      +// Causes the child to print: CHILD got message: { hello: 'world' }
      +n.send({ hello: 'world' });
      +

      And then the child script, 'sub.js' might look like this:

      +
      process.on('message', (m) => {
      +  console.log('CHILD got message:', m);
      +});
      +
      +// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
      +process.send({ foo: 'bar', baz: NaN });
      +

      Child Node.js processes will have a process.send() method of their own +that allows the child to send messages back to the parent.

      +

      There is a special case when sending a {cmd: 'NODE_foo'} message. Messages +containing a NODE_ prefix in the cmd property are reserved for use within +Node.js core and will not be emitted in the child's 'message' +event. Rather, such messages are emitted using the +'internalMessage' event and are consumed internally by Node.js. +Applications should avoid using such messages or listening for +'internalMessage' events as it is subject to change without notice.

      +

      The optional sendHandle argument that may be passed to subprocess.send() is +for passing a TCP server or socket object to the child process. The child will +receive the object as the second argument passed to the callback function +registered on the 'message' event. Any data that is received +and buffered in the socket will not be sent to the child.

      +

      The optional callback is a function that is invoked after the message is +sent but before the child may have received it. The function is called with a +single argument: null on success, or an Error object on failure.

      +

      If no callback function is provided and the message cannot be sent, an +'error' event will be emitted by the ChildProcess object. This can +happen, for instance, when the child process has already exited.

      +

      subprocess.send() will return false if the channel has closed or when the +backlog of unsent messages exceeds a threshold that makes it unwise to send +more. Otherwise, the method returns true. The callback function can be +used to implement flow control.

      +

      Example: sending a server object#

      +

      The sendHandle argument can be used, for instance, to pass the handle of +a TCP server object to the child process as illustrated in the example below:

      +
      const subprocess = require('child_process').fork('subprocess.js');
      +
      +// Open up the server object and send the handle.
      +const server = require('net').createServer();
      +server.on('connection', (socket) => {
      +  socket.end('handled by parent');
      +});
      +server.listen(1337, () => {
      +  subprocess.send('server', server);
      +});
      +

      The child would then receive the server object as:

      +
      process.on('message', (m, server) => {
      +  if (m === 'server') {
      +    server.on('connection', (socket) => {
      +      socket.end('handled by child');
      +    });
      +  }
      +});
      +

      Once the server is now shared between the parent and child, some connections +can be handled by the parent and some by the child.

      +

      While the example above uses a server created using the net module, dgram +module servers use exactly the same workflow with the exceptions of listening on +a 'message' event instead of 'connection' and using server.bind() instead +of server.listen(). This is, however, currently only supported on Unix +platforms.

      +

      Example: sending a socket object#

      +

      Similarly, the sendHandler argument can be used to pass the handle of a +socket to the child process. The example below spawns two children that each +handle connections with "normal" or "special" priority:

      +
      const { fork } = require('child_process');
      +const normal = fork('subprocess.js', ['normal']);
      +const special = fork('subprocess.js', ['special']);
      +
      +// Open up the server and send sockets to child. Use pauseOnConnect to prevent
      +// the sockets from being read before they are sent to the child process.
      +const server = require('net').createServer({ pauseOnConnect: true });
      +server.on('connection', (socket) => {
      +
      +  // If this is special priority...
      +  if (socket.remoteAddress === '74.125.127.100') {
      +    special.send('socket', socket);
      +    return;
      +  }
      +  // This is normal priority.
      +  normal.send('socket', socket);
      +});
      +server.listen(1337);
      +

      The subprocess.js would receive the socket handle as the second argument +passed to the event callback function:

      +
      process.on('message', (m, socket) => {
      +  if (m === 'socket') {
      +    if (socket) {
      +      // Check that the client socket exists.
      +      // It is possible for the socket to be closed between the time it is
      +      // sent and the time it is received in the child process.
      +      socket.end(`Request handled with ${process.argv[2]} priority`);
      +    }
      +  }
      +});
      +

      Do not use .maxConnections on a socket that has been passed to a subprocess. +The parent cannot track when the socket is destroyed.

      +

      Any 'message' handlers in the subprocess should verify that socket exists, +as the connection may have been closed during the time it takes to send the +connection to the child.

      +

      subprocess.signalCode#

      + +

      The subprocess.signalCode property indicates the signal number received by +the child process if any, else null.

      +

      subprocess.spawnargs#

      + +

      The subprocess.spawnargs property represents the full list of command line +arguments the child process was launched with.

      +

      subprocess.spawnfile#

      + +

      The subprocess.spawnfile property indicates the executable file name of +the child process that is launched.

      +

      For child_process.fork(), its value will be equal to +process.execPath. +For child_process.spawn(), its value will be the name of +the executable file. +For child_process.exec(), its value will be the name of the shell +in which the child process is launched.

      +

      subprocess.stderr#

      + + +

      A Readable Stream that represents the child process's stderr.

      +

      If the child was spawned with stdio[2] set to anything other than 'pipe', +then this will be null.

      +

      subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will +refer to the same value.

      +

      subprocess.stdin#

      + + +

      A Writable Stream that represents the child process's stdin.

      +

      If a child process waits to read all of its input, the child will not continue +until this stream has been closed via end().

      +

      If the child was spawned with stdio[0] set to anything other than 'pipe', +then this will be null.

      +

      subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will +refer to the same value.

      +

      subprocess.stdio#

      + + +

      A sparse array of pipes to the child process, corresponding with positions in +the stdio option passed to child_process.spawn() that have been set +to the value 'pipe'. subprocess.stdio[0], subprocess.stdio[1], and +subprocess.stdio[2] are also available as subprocess.stdin, +subprocess.stdout, and subprocess.stderr, respectively.

      +

      In the following example, only the child's fd 1 (stdout) is configured as a +pipe, so only the parent's subprocess.stdio[1] is a stream, all other values +in the array are null.

      +
      const assert = require('assert');
      +const fs = require('fs');
      +const child_process = require('child_process');
      +
      +const subprocess = child_process.spawn('ls', {
      +  stdio: [
      +    0, // Use parent's stdin for child.
      +    'pipe', // Pipe child's stdout to parent.
      +    fs.openSync('err.out', 'w') // Direct child's stderr to a file.
      +  ]
      +});
      +
      +assert.strictEqual(subprocess.stdio[0], null);
      +assert.strictEqual(subprocess.stdio[0], subprocess.stdin);
      +
      +assert(subprocess.stdout);
      +assert.strictEqual(subprocess.stdio[1], subprocess.stdout);
      +
      +assert.strictEqual(subprocess.stdio[2], null);
      +assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
      +

      subprocess.stdout#

      + + +

      A Readable Stream that represents the child process's stdout.

      +

      If the child was spawned with stdio[1] set to anything other than 'pipe', +then this will be null.

      +

      subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will +refer to the same value.

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn('ls');
      +
      +subprocess.stdout.on('data', (data) => {
      +  console.log(`Received chunk ${data}`);
      +});
      +

      subprocess.unref()#

      + +

      By default, the parent will wait for the detached child to exit. To prevent the +parent from waiting for a given subprocess to exit, use the +subprocess.unref() method. Doing so will cause the parent's event loop to not +include the child in its reference count, allowing the parent to exit +independently of the child, unless there is an established IPC channel between +the child and the parent.

      +
      const { spawn } = require('child_process');
      +
      +const subprocess = spawn(process.argv[0], ['child_program.js'], {
      +  detached: true,
      +  stdio: 'ignore'
      +});
      +
      +subprocess.unref();
      +

      maxBuffer and Unicode#

      +

      The maxBuffer option specifies the largest number of bytes allowed on stdout +or stderr. If this value is exceeded, then the child process is terminated. +This impacts output that includes multibyte character encodings such as UTF-8 or +UTF-16. For instance, console.log('中文测试') will send 13 UTF-8 encoded bytes +to stdout although there are only 4 characters.

      +

      Shell requirements#

      +

      The shell should understand the -c switch. If the shell is 'cmd.exe', it +should understand the /d /s /c switches and command line parsing should be +compatible.

      +

      Default Windows shell#

      +

      Although Microsoft specifies %COMSPEC% must contain the path to +'cmd.exe' in the root environment, child processes are not always subject to +the same requirement. Thus, in child_process functions where a shell can be +spawned, 'cmd.exe' is used as a fallback if process.env.ComSpec is +unavailable.

      +

      Advanced serialization#

      + +

      Child processes support a serialization mechanism for IPC that is based on the +serialization API of the v8 module, based on the +HTML structured clone algorithm. This is generally more powerful and +supports more built-in JavaScript object types, such as BigInt, Map +and Set, ArrayBuffer and TypedArray, Buffer, Error, RegExp etc.

      +

      However, this format is not a full superset of JSON, and e.g. properties set on +objects of such built-in types will not be passed on through the serialization +step. Additionally, performance may not be equivalent to that of JSON, depending +on the structure of the passed data. +Therefore, this feature requires opting in by setting the +serialization option to 'advanced' when calling child_process.spawn() +or child_process.fork().

      + +
      +
      +
      + + diff --git a/doc/api/child_process.json b/doc/api/child_process.json new file mode 100644 index 0000000000000000000000000000000000000000..586c68dbdf95128d5e8592de54ccf61ea9ee28f5 --- /dev/null +++ b/doc/api/child_process.json @@ -0,0 +1,1521 @@ +{ + "type": "module", + "source": "doc/api/child_process.md", + "modules": [ + { + "textRaw": "Child process", + "name": "child_process", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/child_process.js

      \n

      The child_process module provides the ability to spawn child processes in\na manner that is similar, but not identical, to popen(3). This capability\nis primarily provided by the child_process.spawn() function:

      \n
      const { spawn } = require('child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n  console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n  console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n  console.log(`child process exited with code ${code}`);\n});\n
      \n

      By default, pipes for stdin, stdout, and stderr are established between\nthe parent Node.js process and the spawned child. These pipes have\nlimited (and platform-specific) capacity. If the child process writes to\nstdout in excess of that limit without the output being captured, the child\nprocess will block waiting for the pipe buffer to accept more data. This is\nidentical to the behavior of pipes in the shell. Use the { stdio: 'ignore' }\noption if the output will not be consumed.

      \n

      The command lookup will be performed using options.env.PATH environment\nvariable if passed in options object, otherwise process.env.PATH will be\nused. To account for the fact that Windows environment variables are\ncase-insensitive Node.js will lexicographically sort all env keys and choose\nthe first one case-insensitively matching PATH to perform command lookup.\nThis may lead to issues on Windows when passing objects to env option that\nhave multiple variants of PATH variable.

      \n

      The child_process.spawn() method spawns the child process asynchronously,\nwithout blocking the Node.js event loop. The child_process.spawnSync()\nfunction provides equivalent functionality in a synchronous manner that blocks\nthe event loop until the spawned process either exits or is terminated.

      \n

      For convenience, the child_process module provides a handful of synchronous\nand asynchronous alternatives to child_process.spawn() and\nchild_process.spawnSync(). Each of these alternatives are implemented on\ntop of child_process.spawn() or child_process.spawnSync().

      \n\n

      For certain use cases, such as automating shell scripts, the\nsynchronous counterparts may be more convenient. In many cases, however,\nthe synchronous methods can have significant impact on performance due to\nstalling the event loop while spawned processes complete.

      ", + "modules": [ + { + "textRaw": "Asynchronous process creation", + "name": "asynchronous_process_creation", + "desc": "

      The child_process.spawn(), child_process.fork(), child_process.exec(),\nand child_process.execFile() methods all follow the idiomatic asynchronous\nprogramming pattern typical of other Node.js APIs.

      \n

      Each of the methods returns a ChildProcess instance. These objects\nimplement the Node.js EventEmitter API, allowing the parent process to\nregister listener functions that are called when certain events occur during\nthe life cycle of the child process.

      \n

      The child_process.exec() and child_process.execFile() methods\nadditionally allow for an optional callback function to be specified that is\ninvoked when the child process terminates.

      ", + "modules": [ + { + "textRaw": "Spawning `.bat` and `.cmd` files on Windows", + "name": "spawning_`.bat`_and_`.cmd`_files_on_windows", + "desc": "

      The importance of the distinction between child_process.exec() and\nchild_process.execFile() can vary based on platform. On Unix-type\noperating systems (Unix, Linux, macOS) child_process.execFile() can be\nmore efficient because it does not spawn a shell by default. On Windows,\nhowever, .bat and .cmd files are not executable on their own without a\nterminal, and therefore cannot be launched using child_process.execFile().\nWhen running on Windows, .bat and .cmd files can be invoked using\nchild_process.spawn() with the shell option set, with\nchild_process.exec(), or by spawning cmd.exe and passing the .bat or\n.cmd file as an argument (which is what the shell option and\nchild_process.exec() do). In any case, if the script filename contains\nspaces it needs to be quoted.

      \n
      // On Windows Only...\nconst { spawn } = require('child_process');\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\nbat.stdout.on('data', (data) => {\n  console.log(data.toString());\n});\n\nbat.stderr.on('data', (data) => {\n  console.error(data.toString());\n});\n\nbat.on('exit', (code) => {\n  console.log(`Child exited with code ${code}`);\n});\n
      \n
      // OR...\nconst { exec, spawn } = require('child_process');\nexec('my.bat', (err, stdout, stderr) => {\n  if (err) {\n    console.error(err);\n    return;\n  }\n  console.log(stdout);\n});\n\n// Script with spaces in the filename:\nconst bat = spawn('\"my script.cmd\"', ['a', 'b'], { shell: true });\n// or:\nexec('\"my script.cmd\" a b', (err, stdout, stderr) => {\n  // ...\n});\n
      ", + "type": "module", + "displayName": "Spawning `.bat` and `.cmd` files on Windows" + } + ], + "methods": [ + { + "textRaw": "`child_process.exec(command[, options][, callback])`", + "type": "method", + "name": "exec", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`command` {string} The command to run, with space-separated arguments.", + "name": "command", + "type": "string", + "desc": "The command to run, with space-separated arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process. **Default:** `null`.", + "name": "cwd", + "type": "string", + "default": "`null`", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`shell` {string} Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.", + "name": "shell", + "type": "string", + "default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows", + "desc": "Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`timeout` {number} **Default:** `0`", + "name": "timeout", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`" + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + }, + { + "textRaw": "`callback` {Function} called with the output when process terminates.", + "name": "callback", + "type": "Function", + "desc": "called with the output when process terminates.", + "options": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {string|Buffer}", + "name": "stdout", + "type": "string|Buffer" + }, + { + "textRaw": "`stderr` {string|Buffer}", + "name": "stderr", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Spawns a shell then executes the command within that shell, buffering any\ngenerated output. The command string passed to the exec function is processed\ndirectly by the shell and special characters (vary based on\nshell)\nneed to be dealt with accordingly:

      \n
      exec('\"/path/to/test file/test.sh\" arg1 arg2');\n// Double quotes are used so that the space in the path is not interpreted as\n// a delimiter of multiple arguments.\n\nexec('echo \"The \\\\$HOME variable is $HOME\"');\n// The $HOME variable is escaped in the first instance, but not in the second.\n
      \n

      Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.

      \n

      If a callback function is provided, it is called with the arguments\n(error, stdout, stderr). On success, error will be null. On error,\nerror will be an instance of Error. The error.code property will be\nthe exit code of the process. By convention, any exit code other than 0\nindicates an error. error.signal will be the signal that terminated the\nprocess.

      \n

      The stdout and stderr arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding is 'buffer', or an unrecognized character\nencoding, Buffer objects will be passed to the callback instead.

      \n
      const { exec } = require('child_process');\nexec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {\n  if (error) {\n    console.error(`exec error: ${error}`);\n    return;\n  }\n  console.log(`stdout: ${stdout}`);\n  console.error(`stderr: ${stderr}`);\n});\n
      \n

      If timeout is greater than 0, the parent will send the signal\nidentified by the killSignal property (the default is 'SIGTERM') if the\nchild runs longer than timeout milliseconds.

      \n

      Unlike the exec(3) POSIX system call, child_process.exec() does not replace\nthe existing process and uses a shell to execute the command.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with stdout and stderr properties. The returned\nChildProcess instance is attached to the Promise as a child property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error object given in the\ncallback, but with two additional properties stdout and stderr.

      \n
      const util = require('util');\nconst exec = util.promisify(require('child_process').exec);\n\nasync function lsExample() {\n  const { stdout, stderr } = await exec('ls');\n  console.log('stdout:', stdout);\n  console.error('stderr:', stderr);\n}\nlsExample();\n
      " + }, + { + "textRaw": "`child_process.execFile(file[, args][, options][, callback])`", + "type": "method", + "name": "execFile", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [ + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`file` {string} The name or path of the executable file to run.", + "name": "file", + "type": "string", + "desc": "The name or path of the executable file to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`timeout` {number} **Default:** `0`", + "name": "timeout", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`" + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + } + ] + }, + { + "textRaw": "`callback` {Function} Called with the output when process terminates.", + "name": "callback", + "type": "Function", + "desc": "Called with the output when process terminates.", + "options": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + }, + { + "textRaw": "`stdout` {string|Buffer}", + "name": "stdout", + "type": "string|Buffer" + }, + { + "textRaw": "`stderr` {string|Buffer}", + "name": "stderr", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      The child_process.execFile() function is similar to child_process.exec()\nexcept that it does not spawn a shell by default. Rather, the specified\nexecutable file is spawned directly as a new process making it slightly more\nefficient than child_process.exec().

      \n

      The same options as child_process.exec() are supported. Since a shell is\nnot spawned, behaviors such as I/O redirection and file globbing are not\nsupported.

      \n
      const { execFile } = require('child_process');\nconst child = execFile('node', ['--version'], (error, stdout, stderr) => {\n  if (error) {\n    throw error;\n  }\n  console.log(stdout);\n});\n
      \n

      The stdout and stderr arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding is 'buffer', or an unrecognized character\nencoding, Buffer objects will be passed to the callback instead.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with stdout and stderr properties. The returned\nChildProcess instance is attached to the Promise as a child property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error object given in the\ncallback, but with two additional properties stdout and stderr.

      \n
      const util = require('util');\nconst execFile = util.promisify(require('child_process').execFile);\nasync function getVersion() {\n  const { stdout } = await execFile('node', ['--version']);\n  console.log(stdout);\n}\ngetVersion();\n
      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      " + }, + { + "textRaw": "`child_process.fork(modulePath[, args][, options])`", + "type": "method", + "name": "fork", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30162", + "description": "The `serialization` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10866", + "description": "The `stdio` option can now be a string." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7811", + "description": "The `stdio` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`modulePath` {string} The module to run in the child.", + "name": "modulePath", + "type": "string", + "desc": "The module to run in the child." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).", + "name": "detached", + "type": "boolean", + "desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][])." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`execPath` {string} Executable used to create the child process.", + "name": "execPath", + "type": "string", + "desc": "Executable used to create the child process." + }, + { + "textRaw": "`execArgv` {string[]} List of string arguments passed to the executable. **Default:** `process.execArgv`.", + "name": "execArgv", + "type": "string[]", + "default": "`process.execArgv`", + "desc": "List of string arguments passed to the executable." + }, + { + "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details. **Default:** `'json'`.", + "name": "serialization", + "type": "string", + "default": "`'json'`", + "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details." + }, + { + "textRaw": "`silent` {boolean} If `true`, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s [`stdio`][] for more details. **Default:** `false`.", + "name": "silent", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s [`stdio`][] for more details." + }, + { + "textRaw": "`stdio` {Array|string} See [`child_process.spawn()`][]'s [`stdio`][]. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`.", + "name": "stdio", + "type": "Array|string", + "desc": "See [`child_process.spawn()`][]'s [`stdio`][]. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + } + ] + } + ] + } + ], + "desc": "

      The child_process.fork() method is a special case of\nchild_process.spawn() used specifically to spawn new Node.js processes.\nLike child_process.spawn(), a ChildProcess object is returned. The\nreturned ChildProcess will have an additional communication channel\nbuilt-in that allows messages to be passed back and forth between the parent and\nchild. See subprocess.send() for details.

      \n

      Keep in mind that spawned Node.js child processes are\nindependent of the parent with exception of the IPC communication channel\nthat is established between the two. Each process has its own memory, with\ntheir own V8 instances. Because of the additional resource allocations\nrequired, spawning a large number of child Node.js processes is not\nrecommended.

      \n

      By default, child_process.fork() will spawn new Node.js instances using the\nprocess.execPath of the parent process. The execPath property in the\noptions object allows for an alternative execution path to be used.

      \n

      Node.js processes launched with a custom execPath will communicate with the\nparent process using the file descriptor (fd) identified using the\nenvironment variable NODE_CHANNEL_FD on the child process.

      \n

      Unlike the fork(2) POSIX system call, child_process.fork() does not clone the\ncurrent process.

      \n

      The shell option available in child_process.spawn() is not supported by\nchild_process.fork() and will be ignored if set.

      " + }, + { + "textRaw": "`child_process.spawn(command[, args][, options])`", + "type": "method", + "name": "spawn", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30162", + "description": "The `serialization` option is supported now." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7696", + "description": "The `argv0` option is supported now." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4598", + "description": "The `shell` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ChildProcess}", + "name": "return", + "type": "ChildProcess" + }, + "params": [ + { + "textRaw": "`command` {string} The command to run.", + "name": "command", + "type": "string", + "desc": "The command to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.", + "name": "argv0", + "type": "string", + "desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified." + }, + { + "textRaw": "`stdio` {Array|string} Child's stdio configuration (see [`options.stdio`][`stdio`]).", + "name": "stdio", + "type": "Array|string", + "desc": "Child's stdio configuration (see [`options.stdio`][`stdio`])." + }, + { + "textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).", + "name": "detached", + "type": "boolean", + "desc": "Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][])." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details. **Default:** `'json'`.", + "name": "serialization", + "type": "string", + "default": "`'json'`", + "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization][] for more details." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + } + ] + } + ], + "desc": "

      The child_process.spawn() method spawns a new process using the given\ncommand, with command line arguments in args. If omitted, args defaults\nto an empty array.

      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      \n

      A third argument may be used to specify additional options, with these defaults:

      \n
      const defaults = {\n  cwd: undefined,\n  env: process.env\n};\n
      \n

      Use cwd to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory.

      \n

      Use env to specify environment variables that will be visible to the new\nprocess, the default is process.env.

      \n

      undefined values in env will be ignored.

      \n

      Example of running ls -lh /usr, capturing stdout, stderr, and the\nexit code:

      \n
      const { spawn } = require('child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n  console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n  console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n  console.log(`child process exited with code ${code}`);\n});\n
      \n

      Example: A very elaborate way to run ps ax | grep ssh

      \n
      const { spawn } = require('child_process');\nconst ps = spawn('ps', ['ax']);\nconst grep = spawn('grep', ['ssh']);\n\nps.stdout.on('data', (data) => {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', (data) => {\n  console.error(`ps stderr: ${data}`);\n});\n\nps.on('close', (code) => {\n  if (code !== 0) {\n    console.log(`ps process exited with code ${code}`);\n  }\n  grep.stdin.end();\n});\n\ngrep.stdout.on('data', (data) => {\n  console.log(data.toString());\n});\n\ngrep.stderr.on('data', (data) => {\n  console.error(`grep stderr: ${data}`);\n});\n\ngrep.on('close', (code) => {\n  if (code !== 0) {\n    console.log(`grep process exited with code ${code}`);\n  }\n});\n
      \n

      Example of checking for failed spawn:

      \n
      const { spawn } = require('child_process');\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n  console.error('Failed to start subprocess.');\n});\n
      \n

      Certain platforms (macOS, Linux) will use the value of argv[0] for the process\ntitle while others (Windows, SunOS) will use command.

      \n

      Node.js currently overwrites argv[0] with process.execPath on startup, so\nprocess.argv[0] in a Node.js child process will not match the argv0\nparameter passed to spawn from the parent, retrieve it with the\nprocess.argv0 property instead.

      ", + "properties": [ + { + "textRaw": "`options.detached`", + "name": "detached", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "desc": "

      On Windows, setting options.detached to true makes it possible for the\nchild process to continue running after the parent exits. The child will have\nits own console window. Once enabled for a child process, it cannot be\ndisabled.

      \n

      On non-Windows platforms, if options.detached is set to true, the child\nprocess will be made the leader of a new process group and session. Child\nprocesses may continue running after the parent exits regardless of whether\nthey are detached or not. See setsid(2) for more information.

      \n

      By default, the parent will wait for the detached child to exit. To prevent the\nparent from waiting for a given subprocess to exit, use the\nsubprocess.unref() method. Doing so will cause the parent's event loop to not\ninclude the child in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent.

      \n

      When using the detached option to start a long-running process, the process\nwill not stay running in the background after the parent exits unless it is\nprovided with a stdio configuration that is not connected to the parent.\nIf the parent's stdio is inherited, the child will remain attached to the\ncontrolling terminal.

      \n

      Example of a long-running process, by detaching and also ignoring its parent\nstdio file descriptors, in order to ignore the parent's termination:

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\n
      \n

      Alternatively one can redirect the child process' output into files:

      \n
      const fs = require('fs');\nconst { spawn } = require('child_process');\nconst out = fs.openSync('./out.log', 'a');\nconst err = fs.openSync('./out.log', 'a');\n\nconst subprocess = spawn('prg', [], {\n  detached: true,\n  stdio: [ 'ignore', out, err ]\n});\n\nsubprocess.unref();\n
      " + }, + { + "textRaw": "`options.stdio`", + "name": "stdio", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [ + { + "version": "v3.3.1", + "pr-url": "https://github.com/nodejs/node/pull/2727", + "description": "The value `0` is now accepted as a file descriptor." + } + ] + }, + "desc": "

      The options.stdio option is used to configure the pipes that are established\nbetween the parent and child process. By default, the child's stdin, stdout,\nand stderr are redirected to corresponding subprocess.stdin,\nsubprocess.stdout, and subprocess.stderr streams on the\nChildProcess object. This is equivalent to setting the options.stdio\nequal to ['pipe', 'pipe', 'pipe'].

      \n

      For convenience, options.stdio may be one of the following strings:

      \n
        \n
      • 'pipe': equivalent to ['pipe', 'pipe', 'pipe'] (the default)
      • \n
      • 'ignore': equivalent to ['ignore', 'ignore', 'ignore']
      • \n
      • 'inherit': equivalent to ['inherit', 'inherit', 'inherit'] or [0, 1, 2]
      • \n
      \n

      Otherwise, the value of options.stdio is an array where each index corresponds\nto an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,\nand stderr, respectively. Additional fds can be specified to create additional\npipes between the parent and child. The value is one of the following:

      \n
        \n
      1. \n

        'pipe': Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as subprocess.stdio[fd]. Pipes\ncreated for fds 0, 1, and 2 are also available as subprocess.stdin,\nsubprocess.stdout and subprocess.stderr, respectively.

        \n
      2. \n
      3. \n

        'ipc': Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC\nstdio file descriptor. Setting this option enables the\nsubprocess.send() method. If the child is a Node.js process, the\npresence of an IPC channel will enable process.send() and\nprocess.disconnect() methods, as well as 'disconnect' and\n'message' events within the child.

        \n

        Accessing the IPC channel fd in any way other than process.send()\nor using the IPC channel with a child process that is not a Node.js instance\nis not supported.

        \n
      4. \n
      5. \n

        'ignore': Instructs Node.js to ignore the fd in the child. While Node.js\nwill always open fds 0, 1, and 2 for the processes it spawns, setting the fd\nto 'ignore' will cause Node.js to open /dev/null and attach it to the\nchild's fd.

        \n
      6. \n
      7. \n

        'inherit': Pass through the corresponding stdio stream to/from the\nparent process. In the first three positions, this is equivalent to\nprocess.stdin, process.stdout, and process.stderr, respectively. In\nany other position, equivalent to 'ignore'.

        \n
      8. \n
      9. \n

        <Stream> object: Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that\ncorresponds to the index in the stdio array. The stream must have an\nunderlying descriptor (file streams do not until the 'open' event has\noccurred).

        \n
      10. \n
      11. \n

        Positive integer: The integer value is interpreted as a file descriptor\nthat is currently open in the parent process. It is shared with the child\nprocess, similar to how <Stream> objects can be shared. Passing sockets\nis not supported on Windows.

        \n
      12. \n
      13. \n

        null, undefined: Use default value. For stdio fds 0, 1, and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.

        \n
      14. \n
      \n
      const { spawn } = require('child_process');\n\n// Child will use parent's stdios.\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr.\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs presenting a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });\n
      \n

      It is worth noting that when an IPC channel is established between the\nparent and child processes, and the child is a Node.js process, the child\nis launched with the IPC channel unreferenced (using unref()) until the\nchild registers an event handler for the 'disconnect' event\nor the 'message' event. This allows the child to exit\nnormally without the process being held open by the open IPC channel.

      \n

      On Unix-like operating systems, the child_process.spawn() method\nperforms memory operations synchronously before decoupling the event loop\nfrom the child. Applications with a large memory footprint may find frequent\nchild_process.spawn() calls to be a bottleneck. For more information,\nsee V8 issue 7381.

      \n

      See also: child_process.exec() and child_process.fork().

      " + } + ] + } + ], + "type": "module", + "displayName": "Asynchronous process creation" + }, + { + "textRaw": "Synchronous process creation", + "name": "synchronous_process_creation", + "desc": "

      The child_process.spawnSync(), child_process.execSync(), and\nchild_process.execFileSync() methods are synchronous and will block the\nNode.js event loop, pausing execution of any additional code until the spawned\nprocess exits.

      \n

      Blocking calls like these are mostly useful for simplifying general-purpose\nscripting tasks and for simplifying the loading/processing of application\nconfiguration at startup.

      ", + "methods": [ + { + "textRaw": "`child_process.execFileSync(file[, args][, options])`", + "type": "method", + "name": "execFileSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22409", + "description": "The `input` option can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10653", + "description": "The `input` option can now be a `Uint8Array`." + }, + { + "version": "v6.2.1, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6939", + "description": "The `encoding` option can now explicitly be set to `buffer`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|string} The stdout from the command.", + "name": "return", + "type": "Buffer|string", + "desc": "The stdout from the command." + }, + "params": [ + { + "textRaw": "`file` {string} The name or path of the executable file to run.", + "name": "file", + "type": "string", + "desc": "The name or path of the executable file to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`.", + "name": "input", + "type": "string|Buffer|TypedArray|DataView", + "desc": "The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`." + }, + { + "textRaw": "`stdio` {string|Array} Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.", + "name": "stdio", + "type": "string|Array", + "default": "`'pipe'`", + "desc": "Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", + "name": "timeout", + "type": "number", + "default": "`undefined`", + "desc": "In milliseconds the maximum amount of time the process is allowed to run." + }, + { + "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`", + "desc": "The signal value to be used when the spawned process will be killed." + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", + "name": "encoding", + "type": "string", + "default": "`'buffer'`", + "desc": "The encoding used for all stdio inputs and outputs." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + } + ] + } + ] + } + ], + "desc": "

      The child_process.execFileSync() method is generally identical to\nchild_process.execFile() with the exception that the method will not\nreturn until the child process has fully closed. When a timeout has been\nencountered and killSignal is sent, the method won't return until the process\nhas completely exited.

      \n

      If the child process intercepts and handles the SIGTERM signal and\ndoes not exit, the parent process will still wait until the child process has\nexited.

      \n

      If the process times out or has a non-zero exit code, this method will throw an\nError that will include the full result of the underlying\nchild_process.spawnSync().

      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      " + }, + { + "textRaw": "`child_process.execSync(command[, options])`", + "type": "method", + "name": "execSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22409", + "description": "The `input` option can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10653", + "description": "The `input` option can now be a `Uint8Array`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|string} The stdout from the command.", + "name": "return", + "type": "Buffer|string", + "desc": "The stdout from the command." + }, + "params": [ + { + "textRaw": "`command` {string} The command to run.", + "name": "command", + "type": "string", + "desc": "The command to run." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`.", + "name": "input", + "type": "string|Buffer|TypedArray|DataView", + "desc": "The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`." + }, + { + "textRaw": "`stdio` {string|Array} Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.", + "name": "stdio", + "type": "string|Array", + "default": "`'pipe'`", + "desc": "Child's stdio configuration. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`shell` {string} Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.", + "name": "shell", + "type": "string", + "default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows", + "desc": "Shell to execute the command with. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process. (See setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process. (See setgid(2))." + }, + { + "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", + "name": "timeout", + "type": "number", + "default": "`undefined`", + "desc": "In milliseconds the maximum amount of time the process is allowed to run." + }, + { + "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`", + "desc": "The signal value to be used when the spawned process will be killed." + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", + "name": "encoding", + "type": "string", + "default": "`'buffer'`", + "desc": "The encoding used for all stdio inputs and outputs." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + } + ] + } + ], + "desc": "

      The child_process.execSync() method is generally identical to\nchild_process.exec() with the exception that the method will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal is sent, the method won't return until the process has\ncompletely exited. If the child process intercepts and handles the SIGTERM\nsignal and doesn't exit, the parent process will wait until the child process\nhas exited.

      \n

      If the process times out or has a non-zero exit code, this method will throw.\nThe Error object will contain the entire result from\nchild_process.spawnSync().

      \n

      Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.

      " + }, + { + "textRaw": "`child_process.spawnSync(command[, args][, options])`", + "type": "method", + "name": "spawnSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22409", + "description": "The `input` option can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v8.8.0", + "pr-url": "https://github.com/nodejs/node/pull/15380", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10653", + "description": "The `input` option can now be a `Uint8Array`." + }, + { + "version": "v6.2.1, v4.5.0", + "pr-url": "https://github.com/nodejs/node/pull/6939", + "description": "The `encoding` option can now explicitly be set to `buffer`." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4598", + "description": "The `shell` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`pid` {number} Pid of the child process.", + "name": "pid", + "type": "number", + "desc": "Pid of the child process." + }, + { + "textRaw": "`output` {Array} Array of results from stdio output.", + "name": "output", + "type": "Array", + "desc": "Array of results from stdio output." + }, + { + "textRaw": "`stdout` {Buffer|string} The contents of `output[1]`.", + "name": "stdout", + "type": "Buffer|string", + "desc": "The contents of `output[1]`." + }, + { + "textRaw": "`stderr` {Buffer|string} The contents of `output[2]`.", + "name": "stderr", + "type": "Buffer|string", + "desc": "The contents of `output[2]`." + }, + { + "textRaw": "`status` {number|null} The exit code of the subprocess, or `null` if the subprocess terminated due to a signal.", + "name": "status", + "type": "number|null", + "desc": "The exit code of the subprocess, or `null` if the subprocess terminated due to a signal." + }, + { + "textRaw": "`signal` {string|null} The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal.", + "name": "signal", + "type": "string|null", + "desc": "The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal." + }, + { + "textRaw": "`error` {Error} The error object if the child process failed or timed out.", + "name": "error", + "type": "Error", + "desc": "The error object if the child process failed or timed out." + } + ] + }, + "params": [ + { + "textRaw": "`command` {string} The command to run.", + "name": "command", + "type": "string", + "desc": "The command to run." + }, + { + "textRaw": "`args` {string[]} List of string arguments.", + "name": "args", + "type": "string[]", + "desc": "List of string arguments." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cwd` {string} Current working directory of the child process.", + "name": "cwd", + "type": "string", + "desc": "Current working directory of the child process." + }, + { + "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`.", + "name": "input", + "type": "string|Buffer|TypedArray|DataView", + "desc": "The value which will be passed as stdin to the spawned process. Supplying this value will override `stdio[0]`." + }, + { + "textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.", + "name": "argv0", + "type": "string", + "desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified." + }, + { + "textRaw": "`stdio` {string|Array} Child's stdio configuration.", + "name": "stdio", + "type": "string|Array", + "desc": "Child's stdio configuration." + }, + { + "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "Environment key-value pairs." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process (see setuid(2)).", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process (see setuid(2))." + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process (see setgid(2)).", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process (see setgid(2))." + }, + { + "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", + "name": "timeout", + "type": "number", + "default": "`undefined`", + "desc": "In milliseconds the maximum amount of time the process is allowed to run." + }, + { + "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", + "name": "killSignal", + "type": "string|integer", + "default": "`'SIGTERM'`", + "desc": "The signal value to be used when the spawned process will be killed." + }, + { + "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.", + "name": "maxBuffer", + "type": "number", + "default": "`1024 * 1024`", + "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at [`maxBuffer` and Unicode][]." + }, + { + "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", + "name": "encoding", + "type": "string", + "default": "`'buffer'`", + "desc": "The encoding used for all stdio inputs and outputs." + }, + { + "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]. **Default:** `false` (no shell).", + "name": "shell", + "type": "boolean|string", + "default": "`false` (no shell)", + "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See [Shell requirements][] and [Default Windows shell][]." + }, + { + "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.", + "name": "windowsVerbatimArguments", + "type": "boolean", + "default": "`false`", + "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the subprocess console window that would normally be created on Windows systems." + } + ] + } + ] + } + ], + "desc": "

      The child_process.spawnSync() method is generally identical to\nchild_process.spawn() with the exception that the function will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal is sent, the method won't return until the process has\ncompletely exited. If the process intercepts and handles the SIGTERM signal\nand doesn't exit, the parent process will wait until the child process has\nexited.

      \n

      If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.

      " + } + ], + "type": "module", + "displayName": "Synchronous process creation" + }, + { + "textRaw": "`maxBuffer` and Unicode", + "name": "`maxbuffer`_and_unicode", + "desc": "

      The maxBuffer option specifies the largest number of bytes allowed on stdout\nor stderr. If this value is exceeded, then the child process is terminated.\nThis impacts output that includes multibyte character encodings such as UTF-8 or\nUTF-16. For instance, console.log('中文测试') will send 13 UTF-8 encoded bytes\nto stdout although there are only 4 characters.

      ", + "type": "module", + "displayName": "`maxBuffer` and Unicode" + }, + { + "textRaw": "Shell requirements", + "name": "shell_requirements", + "desc": "

      The shell should understand the -c switch. If the shell is 'cmd.exe', it\nshould understand the /d /s /c switches and command line parsing should be\ncompatible.

      ", + "type": "module", + "displayName": "Shell requirements" + }, + { + "textRaw": "Default Windows shell", + "name": "default_windows_shell", + "desc": "

      Although Microsoft specifies %COMSPEC% must contain the path to\n'cmd.exe' in the root environment, child processes are not always subject to\nthe same requirement. Thus, in child_process functions where a shell can be\nspawned, 'cmd.exe' is used as a fallback if process.env.ComSpec is\nunavailable.

      ", + "type": "module", + "displayName": "Default Windows shell" + }, + { + "textRaw": "Advanced serialization", + "name": "advanced_serialization", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Child processes support a serialization mechanism for IPC that is based on the\nserialization API of the v8 module, based on the\nHTML structured clone algorithm. This is generally more powerful and\nsupports more built-in JavaScript object types, such as BigInt, Map\nand Set, ArrayBuffer and TypedArray, Buffer, Error, RegExp etc.

      \n

      However, this format is not a full superset of JSON, and e.g. properties set on\nobjects of such built-in types will not be passed on through the serialization\nstep. Additionally, performance may not be equivalent to that of JSON, depending\non the structure of the passed data.\nTherefore, this feature requires opting in by setting the\nserialization option to 'advanced' when calling child_process.spawn()\nor child_process.fork().

      ", + "type": "module", + "displayName": "Advanced serialization" + } + ], + "classes": [ + { + "textRaw": "Class: `ChildProcess`", + "type": "class", + "name": "ChildProcess", + "meta": { + "added": [ + "v2.2.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of the ChildProcess represent spawned child processes.

      \n

      Instances of ChildProcess are not intended to be created directly. Rather,\nuse the child_process.spawn(), child_process.exec(),\nchild_process.execFile(), or child_process.fork() methods to create\ninstances of ChildProcess.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {number} The exit code if the child exited on its own.", + "name": "code", + "type": "number", + "desc": "The exit code if the child exited on its own." + }, + { + "textRaw": "`signal` {string} The signal by which the child process was terminated.", + "name": "signal", + "type": "string", + "desc": "The signal by which the child process was terminated." + } + ], + "desc": "

      The 'close' event is emitted when the stdio streams of a child process have\nbeen closed. This is distinct from the 'exit' event, since multiple\nprocesses might share the same stdio streams.

      \n
      const { spawn } = require('child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n  console.log(`stdout: ${data}`);\n});\n\nls.on('close', (code) => {\n  console.log(`child process close all stdio with code ${code}`);\n});\n\nls.on('exit', (code) => {\n  console.log(`child process exited with code ${code}`);\n});\n
      " + }, + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'disconnect' event is emitted after calling the\nsubprocess.disconnect() method in parent process or\nprocess.disconnect() in child process. After disconnecting it is no longer\npossible to send or receive messages, and the subprocess.connected\nproperty is false.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "params": [ + { + "textRaw": "`err` {Error} The error.", + "name": "err", + "type": "Error", + "desc": "The error." + } + ], + "desc": "

      The 'error' event is emitted whenever:

      \n
        \n
      1. The process could not be spawned, or
      2. \n
      3. The process could not be killed, or
      4. \n
      5. Sending a message to the child process failed.
      6. \n
      \n

      The 'exit' event may or may not fire after an error has occurred. When\nlistening to both the 'exit' and 'error' events, guard\nagainst accidentally invoking handler functions multiple times.

      \n

      See also subprocess.kill() and subprocess.send().

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {number} The exit code if the child exited on its own.", + "name": "code", + "type": "number", + "desc": "The exit code if the child exited on its own." + }, + { + "textRaw": "`signal` {string} The signal by which the child process was terminated.", + "name": "signal", + "type": "string", + "desc": "The signal by which the child process was terminated." + } + ], + "desc": "

      The 'exit' event is emitted after the child process ends. If the process\nexited, code is the final exit code of the process, otherwise null. If the\nprocess terminated due to receipt of a signal, signal is the string name of\nthe signal, otherwise null. One of the two will always be non-null.

      \n

      When the 'exit' event is triggered, child process stdio streams might still be\nopen.

      \n

      Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js\nprocesses will not terminate immediately due to receipt of those signals.\nRather, Node.js will perform a sequence of cleanup actions and then will\nre-raise the handled signal.

      \n

      See waitpid(2).

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`message` {Object} A parsed JSON object or primitive value.", + "name": "message", + "type": "Object", + "desc": "A parsed JSON object or primitive value." + }, + { + "textRaw": "`sendHandle` {Handle} A [`net.Socket`][] or [`net.Server`][] object, or undefined.", + "name": "sendHandle", + "type": "Handle", + "desc": "A [`net.Socket`][] or [`net.Server`][] object, or undefined." + } + ], + "desc": "

      The 'message' event is triggered when a child process uses\nprocess.send() to send messages.

      \n

      The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.

      \n

      If the serialization option was set to 'advanced' used when spawning the\nchild process, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for more details.

      " + } + ], + "properties": [ + { + "textRaw": "`channel` {Object} A pipe representing the IPC channel to the child process.", + "type": "Object", + "name": "channel", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [] + }, + "desc": "

      The subprocess.channel property is a reference to the child's IPC channel. If\nno IPC channel currently exists, this property is undefined.

      ", + "shortDesc": "A pipe representing the IPC channel to the child process." + }, + { + "textRaw": "`connected` {boolean} Set to `false` after `subprocess.disconnect()` is called.", + "type": "boolean", + "name": "connected", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "desc": "

      The subprocess.connected property indicates whether it is still possible to\nsend and receive messages from a child process. When subprocess.connected is\nfalse, it is no longer possible to send or receive messages.

      ", + "shortDesc": "Set to `false` after `subprocess.disconnect()` is called." + }, + { + "textRaw": "`exitCode` {integer}", + "type": "integer", + "name": "exitCode", + "desc": "

      The subprocess.exitCode property indicates the exit code of the child process.\nIf the child process is still running, the field will be null.

      " + }, + { + "textRaw": "`killed` {boolean} Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process.", + "type": "boolean", + "name": "killed", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "desc": "

      The subprocess.killed property indicates whether the child process\nsuccessfully received a signal from subprocess.kill(). The killed property\ndoes not indicate that the child process has been terminated.

      ", + "shortDesc": "Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process." + }, + { + "textRaw": "`pid` {integer}", + "type": "integer", + "name": "pid", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      Returns the process identifier (PID) of the child process.

      \n
      const { spawn } = require('child_process');\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n
      " + }, + { + "textRaw": "`signalCode` {integer}", + "type": "integer", + "name": "signalCode", + "desc": "

      The subprocess.signalCode property indicates the signal number received by\nthe child process if any, else null.

      " + }, + { + "textRaw": "`spawnargs` {Array}", + "type": "Array", + "name": "spawnargs", + "desc": "

      The subprocess.spawnargs property represents the full list of command line\narguments the child process was launched with.

      " + }, + { + "textRaw": "`spawnfile` {string}", + "type": "string", + "name": "spawnfile", + "desc": "

      The subprocess.spawnfile property indicates the executable file name of\nthe child process that is launched.

      \n

      For child_process.fork(), its value will be equal to\nprocess.execPath.\nFor child_process.spawn(), its value will be the name of\nthe executable file.\nFor child_process.exec(), its value will be the name of the shell\nin which the child process is launched.

      " + }, + { + "textRaw": "`stderr` {stream.Readable}", + "type": "stream.Readable", + "name": "stderr", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      A Readable Stream that represents the child process's stderr.

      \n

      If the child was spawned with stdio[2] set to anything other than 'pipe',\nthen this will be null.

      \n

      subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will\nrefer to the same value.

      " + }, + { + "textRaw": "`stdin` {stream.Writable}", + "type": "stream.Writable", + "name": "stdin", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      A Writable Stream that represents the child process's stdin.

      \n

      If a child process waits to read all of its input, the child will not continue\nuntil this stream has been closed via end().

      \n

      If the child was spawned with stdio[0] set to anything other than 'pipe',\nthen this will be null.

      \n

      subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will\nrefer to the same value.

      " + }, + { + "textRaw": "`stdio` {Array}", + "type": "Array", + "name": "stdio", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "desc": "

      A sparse array of pipes to the child process, corresponding with positions in\nthe stdio option passed to child_process.spawn() that have been set\nto the value 'pipe'. subprocess.stdio[0], subprocess.stdio[1], and\nsubprocess.stdio[2] are also available as subprocess.stdin,\nsubprocess.stdout, and subprocess.stderr, respectively.

      \n

      In the following example, only the child's fd 1 (stdout) is configured as a\npipe, so only the parent's subprocess.stdio[1] is a stream, all other values\nin the array are null.

      \n
      const assert = require('assert');\nconst fs = require('fs');\nconst child_process = require('child_process');\n\nconst subprocess = child_process.spawn('ls', {\n  stdio: [\n    0, // Use parent's stdin for child.\n    'pipe', // Pipe child's stdout to parent.\n    fs.openSync('err.out', 'w') // Direct child's stderr to a file.\n  ]\n});\n\nassert.strictEqual(subprocess.stdio[0], null);\nassert.strictEqual(subprocess.stdio[0], subprocess.stdin);\n\nassert(subprocess.stdout);\nassert.strictEqual(subprocess.stdio[1], subprocess.stdout);\n\nassert.strictEqual(subprocess.stdio[2], null);\nassert.strictEqual(subprocess.stdio[2], subprocess.stderr);\n
      " + }, + { + "textRaw": "`stdout` {stream.Readable}", + "type": "stream.Readable", + "name": "stdout", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      A Readable Stream that represents the child process's stdout.

      \n

      If the child was spawned with stdio[1] set to anything other than 'pipe',\nthen this will be null.

      \n

      subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will\nrefer to the same value.

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn('ls');\n\nsubprocess.stdout.on('data', (data) => {\n  console.log(`Received chunk ${data}`);\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`subprocess.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Closes the IPC channel between parent and child, allowing the child to exit\ngracefully once there are no other connections keeping it alive. After calling\nthis method the subprocess.connected and process.connected properties in\nboth the parent and child (respectively) will be set to false, and it will be\nno longer possible to pass messages between the processes.

      \n

      The 'disconnect' event will be emitted when there are no messages in the\nprocess of being received. This will most often be triggered immediately after\ncalling subprocess.disconnect().

      \n

      When the child process is a Node.js instance (e.g. spawned using\nchild_process.fork()), the process.disconnect() method can be invoked\nwithin the child process to close the IPC channel as well.

      " + }, + { + "textRaw": "`subprocess.kill([signal])`", + "type": "method", + "name": "kill", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`signal` {number|string}", + "name": "signal", + "type": "number|string" + } + ] + } + ], + "desc": "

      The subprocess.kill() method sends a signal to the child process. If no\nargument is given, the process will be sent the 'SIGTERM' signal. See\nsignal(7) for a list of available signals. This function returns true if\nkill(2) succeeds, and false otherwise.

      \n
      const { spawn } = require('child_process');\nconst grep = spawn('grep', ['ssh']);\n\ngrep.on('close', (code, signal) => {\n  console.log(\n    `child process terminated due to receipt of signal ${signal}`);\n});\n\n// Send SIGHUP to process.\ngrep.kill('SIGHUP');\n
      \n

      The ChildProcess object may emit an 'error' event if the signal\ncannot be delivered. Sending a signal to a child process that has already exited\nis not an error but may have unforeseen consequences. Specifically, if the\nprocess identifier (PID) has been reassigned to another process, the signal will\nbe delivered to that process instead which can have unexpected results.

      \n

      While the function is called kill, the signal delivered to the child process\nmay not actually terminate the process.

      \n

      See kill(2) for reference.

      \n

      On Linux, child processes of child processes will not be terminated\nwhen attempting to kill their parent. This is likely to happen when running a\nnew process in a shell or with the use of the shell option of ChildProcess:

      \n
      'use strict';\nconst { spawn } = require('child_process');\n\nconst subprocess = spawn(\n  'sh',\n  [\n    '-c',\n    `node -e \"setInterval(() => {\n      console.log(process.pid, 'is alive')\n    }, 500);\"`\n  ], {\n    stdio: ['inherit', 'inherit', 'inherit']\n  }\n);\n\nsetTimeout(() => {\n  subprocess.kill(); // Does not terminate the Node.js process in the shell.\n}, 2000);\n
      " + }, + { + "textRaw": "`subprocess.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calling subprocess.ref() after making a call to subprocess.unref() will\nrestore the removed reference count for the child process, forcing the parent\nto wait for the child to exit before exiting itself.

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\nsubprocess.ref();\n
      " + }, + { + "textRaw": "`subprocess.send(message[, sendHandle[, options]][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [ + { + "version": "v5.8.0", + "pr-url": "https://github.com/nodejs/node/pull/5283", + "description": "The `options` parameter, and the `keepOpen` option in particular, is supported now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3516", + "description": "This method returns a boolean for flow control now." + }, + { + "version": "v4.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2620", + "description": "The `callback` parameter is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle}", + "name": "sendHandle", + "type": "Handle" + }, + { + "textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "name": "options", + "type": "Object", + "desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "options": [ + { + "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", + "name": "keepOpen", + "type": "boolean", + "default": "`false`", + "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      When an IPC channel has been established between the parent and child (\ni.e. when using child_process.fork()), the subprocess.send() method can\nbe used to send messages to the child process. When the child process is a\nNode.js instance, these messages can be received via the 'message' event.

      \n

      The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.

      \n

      For example, in the parent script:

      \n
      const cp = require('child_process');\nconst n = cp.fork(`${__dirname}/sub.js`);\n\nn.on('message', (m) => {\n  console.log('PARENT got message:', m);\n});\n\n// Causes the child to print: CHILD got message: { hello: 'world' }\nn.send({ hello: 'world' });\n
      \n

      And then the child script, 'sub.js' might look like this:

      \n
      process.on('message', (m) => {\n  console.log('CHILD got message:', m);\n});\n\n// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }\nprocess.send({ foo: 'bar', baz: NaN });\n
      \n

      Child Node.js processes will have a process.send() method of their own\nthat allows the child to send messages back to the parent.

      \n

      There is a special case when sending a {cmd: 'NODE_foo'} message. Messages\ncontaining a NODE_ prefix in the cmd property are reserved for use within\nNode.js core and will not be emitted in the child's 'message'\nevent. Rather, such messages are emitted using the\n'internalMessage' event and are consumed internally by Node.js.\nApplications should avoid using such messages or listening for\n'internalMessage' events as it is subject to change without notice.

      \n

      The optional sendHandle argument that may be passed to subprocess.send() is\nfor passing a TCP server or socket object to the child process. The child will\nreceive the object as the second argument passed to the callback function\nregistered on the 'message' event. Any data that is received\nand buffered in the socket will not be sent to the child.

      \n

      The optional callback is a function that is invoked after the message is\nsent but before the child may have received it. The function is called with a\nsingle argument: null on success, or an Error object on failure.

      \n

      If no callback function is provided and the message cannot be sent, an\n'error' event will be emitted by the ChildProcess object. This can\nhappen, for instance, when the child process has already exited.

      \n

      subprocess.send() will return false if the channel has closed or when the\nbacklog of unsent messages exceeds a threshold that makes it unwise to send\nmore. Otherwise, the method returns true. The callback function can be\nused to implement flow control.

      \n

      Example: sending a server object

      \n

      The sendHandle argument can be used, for instance, to pass the handle of\na TCP server object to the child process as illustrated in the example below:

      \n
      const subprocess = require('child_process').fork('subprocess.js');\n\n// Open up the server object and send the handle.\nconst server = require('net').createServer();\nserver.on('connection', (socket) => {\n  socket.end('handled by parent');\n});\nserver.listen(1337, () => {\n  subprocess.send('server', server);\n});\n
      \n

      The child would then receive the server object as:

      \n
      process.on('message', (m, server) => {\n  if (m === 'server') {\n    server.on('connection', (socket) => {\n      socket.end('handled by child');\n    });\n  }\n});\n
      \n

      Once the server is now shared between the parent and child, some connections\ncan be handled by the parent and some by the child.

      \n

      While the example above uses a server created using the net module, dgram\nmodule servers use exactly the same workflow with the exceptions of listening on\na 'message' event instead of 'connection' and using server.bind() instead\nof server.listen(). This is, however, currently only supported on Unix\nplatforms.

      \n

      Example: sending a socket object

      \n

      Similarly, the sendHandler argument can be used to pass the handle of a\nsocket to the child process. The example below spawns two children that each\nhandle connections with \"normal\" or \"special\" priority:

      \n
      const { fork } = require('child_process');\nconst normal = fork('subprocess.js', ['normal']);\nconst special = fork('subprocess.js', ['special']);\n\n// Open up the server and send sockets to child. Use pauseOnConnect to prevent\n// the sockets from being read before they are sent to the child process.\nconst server = require('net').createServer({ pauseOnConnect: true });\nserver.on('connection', (socket) => {\n\n  // If this is special priority...\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // This is normal priority.\n  normal.send('socket', socket);\n});\nserver.listen(1337);\n
      \n

      The subprocess.js would receive the socket handle as the second argument\npassed to the event callback function:

      \n
      process.on('message', (m, socket) => {\n  if (m === 'socket') {\n    if (socket) {\n      // Check that the client socket exists.\n      // It is possible for the socket to be closed between the time it is\n      // sent and the time it is received in the child process.\n      socket.end(`Request handled with ${process.argv[2]} priority`);\n    }\n  }\n});\n
      \n

      Do not use .maxConnections on a socket that has been passed to a subprocess.\nThe parent cannot track when the socket is destroyed.

      \n

      Any 'message' handlers in the subprocess should verify that socket exists,\nas the connection may have been closed during the time it takes to send the\nconnection to the child.

      " + }, + { + "textRaw": "`subprocess.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.7.10" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      By default, the parent will wait for the detached child to exit. To prevent the\nparent from waiting for a given subprocess to exit, use the\nsubprocess.unref() method. Doing so will cause the parent's event loop to not\ninclude the child in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent.

      \n
      const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\n
      " + } + ] + } + ], + "type": "module", + "displayName": "Child process" + } + ] +} \ No newline at end of file diff --git a/doc/api/cli.html b/doc/api/cli.html new file mode 100644 index 0000000000000000000000000000000000000000..1801f0046acbe352aeb63d5f73d2245a9ebc886c --- /dev/null +++ b/doc/api/cli.html @@ -0,0 +1,1466 @@ + + + + + + + Command line options | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Command line options#

      + + +

      Node.js comes with a variety of CLI options. These options expose built-in +debugging, multiple ways to execute scripts, and other helpful runtime options.

      +

      To view this documentation as a manual page in a terminal, run man node.

      +

      Synopsis#

      +

      node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]

      +

      node inspect [script.js | -e "script" | <host>:<port>] …

      +

      node --v8-options

      +

      Execute without arguments to start the REPL.

      +

      For more info about node inspect, please see the debugger documentation.

      +

      Options#

      + +

      All options, including V8 options, allow words to be separated by both +dashes (-) or underscores (_).

      +

      For example, --pending-deprecation is equivalent to --pending_deprecation.

      +

      If an option that takes a single value, for example --max-http-header-size, +is passed more than once, then the last passed value will be used. Options +from the command line take precedence over options passed through the +NODE_OPTIONS environment variable.

      +

      -#

      + +

      Alias for stdin. Analogous to the use of - in other command line utilities, +meaning that the script will be read from stdin, and the rest of the options +are passed to that script.

      +

      --#

      + +

      Indicate the end of node options. Pass the rest of the arguments to the script. +If no script filename or eval/print script is supplied prior to this, then +the next argument will be used as a script filename.

      +

      --abort-on-uncaught-exception#

      + +

      Aborting instead of exiting causes a core file to be generated for post-mortem +analysis using a debugger (such as lldb, gdb, and mdb).

      +

      If this flag is passed, the behavior can still be set to not abort through +process.setUncaughtExceptionCaptureCallback() (and through usage of the +domain module that uses it).

      +

      --completion-bash#

      + +

      Print source-able bash completion script for Node.js.

      +
      $ node --completion-bash > node_bash_completion
      +$ source node_bash_completion
      +

      --conditions=condition#

      + +

      Stability: 1 - Experimental

      +

      Enable experimental support for custom conditional exports resolution +conditions.

      +

      Any number of custom string condition names are permitted.

      +

      The default Node.js conditions of "node", "default", "import", and +"require" will always apply as defined.

      +

      --cpu-prof#

      + +

      Stability: 1 - Experimental

      +

      Starts the V8 CPU profiler on start up, and writes the CPU profile to disk +before exit.

      +

      If --cpu-prof-dir is not specified, the generated profile will be placed +in the current working directory.

      +

      If --cpu-prof-name is not specified, the generated profile will be +named CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.

      +
      $ node --cpu-prof index.js
      +$ ls *.cpuprofile
      +CPU.20190409.202950.15293.0.0.cpuprofile
      +

      --cpu-prof-dir#

      + +

      Stability: 1 - Experimental

      +

      Specify the directory where the CPU profiles generated by --cpu-prof will +be placed.

      +

      The default value is controlled by the +--diagnostic-dir command line option.

      +

      --cpu-prof-interval#

      + +

      Stability: 1 - Experimental

      +

      Specify the sampling interval in microseconds for the CPU profiles generated +by --cpu-prof. The default is 1000 microseconds.

      +

      --cpu-prof-name#

      + +

      Stability: 1 - Experimental

      +

      Specify the file name of the CPU profile generated by --cpu-prof.

      +

      --diagnostic-dir=directory#

      +

      Set the directory to which all diagnostic output files will be written to. +Defaults to current working directory.

      +

      Affects the default output directory of:

      + +

      --disable-proto=mode#

      + +

      Disable the Object.prototype.__proto__ property. If mode is delete, the +property will be removed entirely. If mode is throw, accesses to the +property will throw an exception with the code ERR_PROTO_ACCESS.

      +

      --disallow-code-generation-from-strings#

      + +

      Make built-in language features like eval and new Function that generate +code from strings throw an exception instead. This does not affect the Node.js +vm module.

      +

      --enable-fips#

      + +

      Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with +./configure --openssl-fips.)

      +

      --enable-source-maps#

      + +

      Stability: 1 - Experimental

      +

      Enable experimental Source Map v3 support for stack traces.

      +

      Currently, overriding Error.prepareStackTrace is ignored when the +--enable-source-maps flag is set.

      +

      --experimental-import-meta-resolve#

      + +

      Enable experimental import.meta.resolve() support.

      +

      --experimental-json-modules#

      + +

      Enable experimental JSON support for the ES Module loader.

      +

      --experimental-loader=module#

      + +

      Specify the module of a custom experimental ECMAScript Module loader. +module may be either a path to a file, or an ECMAScript Module name.

      +

      --experimental-modules#

      + +

      Enable latest experimental modules features (deprecated).

      +

      --experimental-policy#

      + +

      Use the specified file as a security policy.

      +

      --experimental-repl-await#

      + +

      Enable experimental top-level await keyword support in REPL.

      +

      --experimental-specifier-resolution=mode#

      + +

      Sets the resolution algorithm for resolving ES module specifiers. Valid options +are explicit and node.

      +

      The default is explicit, which requires providing the full path to a +module. The node mode will enable support for optional file extensions and +the ability to import a directory that has an index file.

      +

      Please see customizing ESM specifier resolution for example usage.

      +

      --experimental-vm-modules#

      + +

      Enable experimental ES Module support in the vm module.

      +

      --experimental-wasi-unstable-preview1#

      + +

      Enable experimental WebAssembly System Interface (WASI) support.

      +

      --experimental-wasm-modules#

      + +

      --force-context-aware#

      + +

      Disable loading native addons that are not context-aware.

      +

      Enable experimental WebAssembly module support.

      +

      --force-fips#

      + +

      Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) +(Same requirements as --enable-fips.)

      +

      --frozen-intrinsics#

      + +

      Stability: 1 - Experimental

      +

      Enable experimental frozen intrinsics like Array and Object.

      +

      Support is currently only provided for the root context and no guarantees are +currently provided that global.Array is indeed the default intrinsic +reference. Code may break under this flag.

      +

      --require runs prior to freezing intrinsics in order to allow polyfills to +be added.

      +

      --heapsnapshot-signal=signal#

      + +

      Enables a signal handler that causes the Node.js process to write a heap dump +when the specified signal is received. signal must be a valid signal name. +Disabled by default.

      +
      $ node --heapsnapshot-signal=SIGUSR2 index.js &
      +$ ps aux
      +USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
      +node         1  5.5  6.1 787252 247004 ?       Ssl  16:43   0:02 node --heapsnapshot-signal=SIGUSR2 index.js
      +$ kill -USR2 1
      +$ ls
      +Heap.20190718.133405.15554.0.001.heapsnapshot
      +

      --heap-prof#

      + +

      Stability: 1 - Experimental

      +

      Starts the V8 heap profiler on start up, and writes the heap profile to disk +before exit.

      +

      If --heap-prof-dir is not specified, the generated profile will be placed +in the current working directory.

      +

      If --heap-prof-name is not specified, the generated profile will be +named Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.

      +
      $ node --heap-prof index.js
      +$ ls *.heapprofile
      +Heap.20190409.202950.15293.0.001.heapprofile
      +

      --heap-prof-dir#

      + +

      Stability: 1 - Experimental

      +

      Specify the directory where the heap profiles generated by --heap-prof will +be placed.

      +

      The default value is controlled by the +--diagnostic-dir command line option.

      +

      --heap-prof-interval#

      + +

      Stability: 1 - Experimental

      +

      Specify the average sampling interval in bytes for the heap profiles generated +by --heap-prof. The default is 512 * 1024 bytes.

      +

      --heap-prof-name#

      + +

      Stability: 1 - Experimental

      +

      Specify the file name of the heap profile generated by --heap-prof.

      +

      --http-parser=library#

      + +

      Chooses an HTTP parser library. Available values are:

      + +

      The default is llhttp, unless otherwise specified when building Node.js.

      +

      The legacy HTTP parser is deprecated and will emit a deprecation warning.

      +

      This flag exists to aid in experimentation with the internal implementation of +the Node.js http parser. +This flag is likely to become a no-op and removed at some point in the future.

      +

      --http-server-default-timeout=milliseconds#

      + +

      Overrides the default value of http, https and http2 server socket +timeout. Setting the value to 0 disables server socket timeout. Unless +provided, http server sockets timeout after 120s (2 minutes). Programmatic +setting of the timeout takes precedence over the value set through this +flag.

      +

      --icu-data-dir=file#

      + +

      Specify ICU data load path. (Overrides NODE_ICU_DATA.)

      +

      --input-type=type#

      + +

      This configures Node.js to interpret string input as CommonJS or as an ES +module. String input is input via --eval, --print, or STDIN.

      +

      Valid values are "commonjs" and "module". The default is "commonjs".

      +

      --inspect-brk[=[host:]port]#

      + +

      Activate inspector on host:port and break at start of user script. +Default host:port is 127.0.0.1:9229.

      +

      --inspect-port=[host:]port#

      + +

      Set the host:port to be used when the inspector is activated. +Useful when activating the inspector by sending the SIGUSR1 signal.

      +

      Default host is 127.0.0.1.

      +

      See the security warning below regarding the host +parameter usage.

      +

      --inspect[=[host:]port]#

      + +

      Activate inspector on host:port. Default is 127.0.0.1:9229.

      +

      V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug +and profile Node.js instances. The tools attach to Node.js instances via a +tcp port and communicate using the Chrome DevTools Protocol.

      +

      +

      Warning: binding inspector to a public IP:port combination is insecure#

      +

      Binding the inspector to a public IP (including 0.0.0.0) with an open port is +insecure, as it allows external hosts to connect to the inspector and perform +a remote code execution attack.

      +

      If specifying a host, make sure that either:

      +
        +
      • The host is not accessible from public networks.
      • +
      • A firewall disallows unwanted connections on the port.
      • +
      +

      More specifically, --inspect=0.0.0.0 is insecure if the port (9229 by +default) is not firewall-protected.

      +

      See the debugging security implications section for more information.

      +

      --inspect-publish-uid=stderr,http#

      +

      Specify ways of the inspector web socket url exposure.

      +

      By default inspector websocket url is available in stderr and under /json/list +endpoint on http://host:port/json/list.

      +

      --insecure-http-parser#

      + +

      Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow +interoperability with non-conformant HTTP implementations. It may also allow +request smuggling and other HTTP attacks that rely on invalid headers being +accepted. Avoid using this option.

      +

      --jitless#

      + +

      Disable runtime allocation of executable memory. This may be +required on some platforms for security reasons. It can also reduce attack +surface on other platforms, but the performance impact may be severe.

      +

      This flag is inherited from V8 and is subject to change upstream. It may +disappear in a non-semver-major release.

      +

      --max-http-header-size=size#

      + +

      Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB.

      +

      --napi-modules#

      + +

      This option is a no-op. It is kept for compatibility.

      +

      --no-deprecation#

      + +

      Silence deprecation warnings.

      +

      --no-force-async-hooks-checks#

      + +

      Disables runtime checks for async_hooks. These will still be enabled +dynamically when async_hooks is enabled.

      +

      --no-warnings#

      + +

      Silence all process warnings (including deprecations).

      +

      --openssl-config=file#

      + +

      Load an OpenSSL configuration file on startup. Among other uses, this can be +used to enable FIPS-compliant crypto if Node.js is built with +./configure --openssl-fips.

      +

      --pending-deprecation#

      + +

      Emit pending deprecation warnings.

      +

      Pending deprecations are generally identical to a runtime deprecation with the +notable exception that they are turned off by default and will not be emitted +unless either the --pending-deprecation command line flag, or the +NODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations +are used to provide a kind of selective "early warning" mechanism that +developers may leverage to detect deprecated API usage.

      +

      --policy-integrity=sri#

      + +

      Stability: 1 - Experimental

      +

      Instructs Node.js to error prior to running any code if the policy does not have +the specified integrity. It expects a Subresource Integrity string as a +parameter.

      +

      --preserve-symlinks#

      + +

      Instructs the module loader to preserve symbolic links when resolving and +caching modules.

      +

      By default, when Node.js loads a module from a path that is symbolically linked +to a different on-disk location, Node.js will dereference the link and use the +actual on-disk "real path" of the module as both an identifier and as a root +path to locate other dependency modules. In most cases, this default behavior +is acceptable. However, when using symbolically linked peer dependencies, as +illustrated in the example below, the default behavior causes an exception to +be thrown if moduleA attempts to require moduleB as a peer dependency:

      +
      {appDir}
      + ├── app
      + │   ├── index.js
      + │   └── node_modules
      + │       ├── moduleA -> {appDir}/moduleA
      + │       └── moduleB
      + │           ├── index.js
      + │           └── package.json
      + └── moduleA
      +     ├── index.js
      +     └── package.json
      +

      The --preserve-symlinks command line flag instructs Node.js to use the +symlink path for modules as opposed to the real path, allowing symbolically +linked peer dependencies to be found.

      +

      Note, however, that using --preserve-symlinks can have other side effects. +Specifically, symbolically linked native modules can fail to load if those +are linked from more than one location in the dependency tree (Node.js would +see those as two separate modules and would attempt to load the module multiple +times, causing an exception to be thrown).

      +

      The --preserve-symlinks flag does not apply to the main module, which allows +node --preserve-symlinks node_module/.bin/<foo> to work. To apply the same +behavior for the main module, also use --preserve-symlinks-main.

      +

      --preserve-symlinks-main#

      + +

      Instructs the module loader to preserve symbolic links when resolving and +caching the main module (require.main).

      +

      This flag exists so that the main module can be opted-in to the same behavior +that --preserve-symlinks gives to all other imports; they are separate flags, +however, for backward compatibility with older Node.js versions.

      +

      --preserve-symlinks-main does not imply --preserve-symlinks; it +is expected that --preserve-symlinks-main will be used in addition to +--preserve-symlinks when it is not desirable to follow symlinks before +resolving relative paths.

      +

      See --preserve-symlinks for more information.

      +

      --prof#

      + +

      Generate V8 profiler output.

      +

      --prof-process#

      + +

      Process V8 profiler output generated using the V8 option --prof.

      +

      --redirect-warnings=file#

      + +

      Write process warnings to the given file instead of printing to stderr. The +file will be created if it does not exist, and will be appended to if it does. +If an error occurs while attempting to write the warning to the file, the +warning will be written to stderr instead.

      +

      The file name may be an absolute path. If it is not, the default directory it +will be written to is controlled by the +--diagnostic-dir command line option.

      +

      --report-compact#

      + +

      Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption.

      +

      --report-dir=directory, report-directory=directory#

      + +

      Location at which the report will be generated.

      +

      --report-filename=filename#

      + +

      Name of the file to which the report will be written.

      +

      --report-on-fatalerror#

      + +

      Enables the report to be triggered on fatal errors (internal errors within +the Node.js runtime such as out of memory) that lead to termination of the +application. Useful to inspect various diagnostic data elements such as heap, +stack, event loop state, resource consumption etc. to reason about the fatal +error.

      +

      --report-on-signal#

      + +

      Enables report to be generated upon receiving the specified (or predefined) +signal to the running Node.js process. The signal to trigger the report is +specified through --report-signal.

      +

      --report-signal=signal#

      + +

      Sets or resets the signal for report generation (not supported on Windows). +Default signal is SIGUSR2.

      +

      --report-uncaught-exception#

      + +

      Enables report to be generated on uncaught exceptions. Useful when inspecting +the JavaScript stack in conjunction with native stack and other runtime +environment data.

      +

      --throw-deprecation#

      + +

      Throw errors for deprecations.

      +

      --title=title#

      + +

      Set process.title on startup.

      +

      --tls-cipher-list=list#

      + +

      Specify an alternative default TLS cipher list. Requires Node.js to be built +with crypto support (default).

      +

      --tls-keylog=file#

      + +

      Log TLS key material to a file. The key material is in NSS SSLKEYLOGFILE +format and can be used by software (such as Wireshark) to decrypt the TLS +traffic.

      +

      --tls-max-v1.2#

      + +

      Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for +TLSv1.3.

      +

      --tls-max-v1.3#

      + +

      Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support +for TLSv1.3.

      +

      --tls-min-v1.0#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with +old TLS clients or servers.

      +

      --tls-min-v1.1#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility +with old TLS clients or servers.

      +

      --tls-min-v1.2#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.2'. This is the default for +12.x and later, but the option is supported for compatibility with older Node.js +versions.

      +

      --tls-min-v1.3#

      + +

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support +for TLSv1.2, which is not as secure as TLSv1.3.

      +

      --trace-deprecation#

      + +

      Print stack traces for deprecations.

      +

      --trace-event-categories#

      + +

      A comma separated list of categories that should be traced when trace event +tracing is enabled using --trace-events-enabled.

      +

      --trace-event-file-pattern#

      + +

      Template string specifying the filepath for the trace event data, it +supports ${rotation} and ${pid}.

      +

      --trace-events-enabled#

      + +

      Enables the collection of trace event tracing information.

      +

      --trace-exit#

      + +

      Prints a stack trace whenever an environment is exited proactively, +i.e. invoking process.exit().

      +

      --trace-sigint#

      + +

      Prints a stack trace on SIGINT.

      +

      --trace-sync-io#

      + +

      Prints a stack trace whenever synchronous I/O is detected after the first turn +of the event loop.

      +

      --trace-tls#

      + +

      Prints TLS packet trace information to stderr. This can be used to debug TLS +connection problems.

      +

      --trace-uncaught#

      + +

      Print stack traces for uncaught exceptions; usually, the stack trace associated +with the creation of an Error is printed, whereas this makes Node.js also +print the stack trace associated with throwing the value (which does not need +to be an Error instance).

      +

      Enabling this option may affect garbage collection behavior negatively.

      +

      --trace-warnings#

      + +

      Print stack traces for process warnings (including deprecations).

      +

      --track-heap-objects#

      + +

      Track heap object allocations for heap snapshots.

      +

      --unhandled-rejections=mode#

      + +

      By default all unhandled rejections trigger a warning plus a deprecation warning +for the very first unhandled rejection in case no unhandledRejection hook +is used.

      +

      Using this flag allows to change what should happen when an unhandled rejection +occurs. One of three modes can be chosen:

      +
        +
      • strict: Raise the unhandled rejection as an uncaught exception.
      • +
      • warn: Always trigger a warning, no matter if the unhandledRejection +hook is set or not but do not print the deprecation warning.
      • +
      • none: Silence all warnings.
      • +
      +

      --use-bundled-ca, --use-openssl-ca#

      + +

      Use bundled Mozilla CA store as supplied by current Node.js version +or use OpenSSL's default CA store. The default store is selectable +at build-time.

      +

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store +that is fixed at release time. It is identical on all supported platforms.

      +

      Using OpenSSL store allows for external modifications of the store. For most +Linux and BSD distributions, this store is maintained by the distribution +maintainers and system administrators. OpenSSL CA store location is dependent on +configuration of the OpenSSL library but this can be altered at runtime using +environment variables.

      +

      See SSL_CERT_DIR and SSL_CERT_FILE.

      +

      --use-largepages=mode#

      + +

      Re-map the Node.js static code to large memory pages at startup. If supported on +the target system, this will cause the Node.js static code to be moved onto 2 +MiB pages instead of 4 KiB pages.

      +

      The following values are valid for mode:

      +
        +
      • off: No mapping will be attempted. This is the default.
      • +
      • on: If supported by the OS, mapping will be attempted. Failure to map will +be ignored and a message will be printed to standard error.
      • +
      • silent: If supported by the OS, mapping will be attempted. Failure to map +will be ignored and will not be reported.
      • +
      +

      --v8-options#

      + +

      Print V8 command line options.

      +

      --v8-pool-size=num#

      + +

      Set V8's thread pool size which will be used to allocate background jobs.

      +

      If set to 0 then V8 will choose an appropriate size of the thread pool based +on the number of online processors.

      +

      If the value provided is larger than V8's maximum, then the largest value +will be chosen.

      +

      --zero-fill-buffers#

      + +

      Automatically zero-fills all newly allocated Buffer and SlowBuffer +instances.

      +

      -c, --check#

      + +

      Syntax check the script without executing.

      +

      -e, --eval "script"#

      + +

      Evaluate the following argument as JavaScript. The modules which are +predefined in the REPL can also be used in script.

      +

      On Windows, using cmd.exe a single quote will not work correctly because it +only recognizes double " for quoting. In Powershell or Git bash, both ' +and " are usable.

      +

      -h, --help#

      + +

      Print node command line options. +The output of this option is less detailed than this document.

      +

      -i, --interactive#

      + +

      Opens the REPL even if stdin does not appear to be a terminal.

      +

      -p, --print "script"#

      + +

      Identical to -e but prints the result.

      +

      -r, --require module#

      + +

      Preload the specified module at startup.

      +

      Follows require()'s module resolution +rules. module may be either a path to a file, or a node module name.

      +

      -v, --version#

      + +

      Print node's version.

      +

      Environment variables#

      +

      NODE_DEBUG=module[,…]#

      + +

      ','-separated list of core modules that should print debug information.

      +

      NODE_DEBUG_NATIVE=module[,…]#

      +

      ','-separated list of core C++ modules that should print debug information.

      +

      NODE_DISABLE_COLORS=1#

      + +

      When set, colors will not be used in the REPL.

      +

      NODE_EXTRA_CA_CERTS=file#

      + +

      When set, the well known "root" CAs (like VeriSign) will be extended with the +extra certificates in file. The file should consist of one or more trusted +certificates in PEM format. A message will be emitted (once) with +process.emitWarning() if the file is missing or +malformed, but any errors are otherwise ignored.

      +

      Neither the well known nor extra certificates are used when the ca +options property is explicitly specified for a TLS or HTTPS client or server.

      +

      This environment variable is ignored when node runs as setuid root or +has Linux file capabilities set.

      +

      NODE_ICU_DATA=file#

      + +

      Data path for ICU (Intl object) data. Will extend linked-in data when compiled +with small-icu support.

      +

      NODE_NO_WARNINGS=1#

      + +

      When set to 1, process warnings are silenced.

      +

      NODE_OPTIONS=options...#

      + +

      A space-separated list of command line options. options... are interpreted +before command line options, so command line options will override or +compound after anything in options.... Node.js will exit with an error if +an option that is not allowed in the environment is used, such as -p or a +script file.

      +

      In case an option value happens to contain a space (for example a path listed +in --require), it must be escaped using double quotes. For example:

      +
      NODE_OPTIONS='--require "./my path/file.js"'
      +

      A singleton flag passed as a command line option will override the same flag +passed into NODE_OPTIONS:

      +
      # The inspector will be available on port 5555
      +NODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555
      +

      A flag that can be passed multiple times will be treated as if its +NODE_OPTIONS instances were passed first, and then its command line +instances afterwards:

      +
      NODE_OPTIONS='--require "./a.js"' node --require "./b.js"
      +# is equivalent to:
      +node --require "./a.js" --require "./b.js"
      +

      Node.js options that are allowed are:

      + +
        +
      • --conditions
      • +
      • --diagnostic-dir
      • +
      • --disable-proto
      • +
      • --enable-fips
      • +
      • --enable-source-maps
      • +
      • --experimental-import-meta-resolve
      • +
      • --experimental-json-modules
      • +
      • --experimental-loader
      • +
      • --experimental-modules
      • +
      • --experimental-policy
      • +
      • --experimental-repl-await
      • +
      • --experimental-specifier-resolution
      • +
      • --experimental-vm-modules
      • +
      • --experimental-wasi-unstable-preview1
      • +
      • --experimental-wasm-modules
      • +
      • --force-context-aware
      • +
      • --force-fips
      • +
      • --frozen-intrinsics
      • +
      • --heapsnapshot-signal
      • +
      • --http-parser
      • +
      • --http-server-default-timeout
      • +
      • --icu-data-dir
      • +
      • --input-type
      • +
      • --insecure-http-parser
      • +
      • --inspect-brk
      • +
      • --inspect-port, --debug-port
      • +
      • --inspect-publish-uid
      • +
      • --inspect
      • +
      • --max-http-header-size
      • +
      • --napi-modules
      • +
      • --no-deprecation
      • +
      • --no-force-async-hooks-checks
      • +
      • --no-warnings
      • +
      • --openssl-config
      • +
      • --pending-deprecation
      • +
      • --policy-integrity
      • +
      • --preserve-symlinks-main
      • +
      • --preserve-symlinks
      • +
      • --prof-process
      • +
      • --redirect-warnings
      • +
      • --report-compact
      • +
      • --report-dir, --report-directory
      • +
      • --report-filename
      • +
      • --report-on-fatalerror
      • +
      • --report-on-signal
      • +
      • --report-signal
      • +
      • --report-uncaught-exception
      • +
      • --require, -r
      • +
      • --throw-deprecation
      • +
      • --title
      • +
      • --tls-cipher-list
      • +
      • --tls-keylog
      • +
      • --tls-max-v1.2
      • +
      • --tls-max-v1.3
      • +
      • --tls-min-v1.0
      • +
      • --tls-min-v1.1
      • +
      • --tls-min-v1.2
      • +
      • --tls-min-v1.3
      • +
      • --trace-deprecation
      • +
      • --trace-event-categories
      • +
      • --trace-event-file-pattern
      • +
      • --trace-events-enabled
      • +
      • --trace-exit
      • +
      • --trace-sigint
      • +
      • --trace-sync-io
      • +
      • --trace-tls
      • +
      • --trace-uncaught
      • +
      • --trace-warnings
      • +
      • --track-heap-objects
      • +
      • --unhandled-rejections
      • +
      • --use-bundled-ca
      • +
      • --use-largepages
      • +
      • --use-openssl-ca
      • +
      • --v8-pool-size
      • +
      • --zero-fill-buffers + +
      • +
      +

      V8 options that are allowed are:

      + +
        +
      • --abort-on-uncaught-exception
      • +
      • --disallow-code-generation-from-strings
      • +
      • --huge-max-old-generation-size
      • +
      • --interpreted-frames-native-stack
      • +
      • --jitless
      • +
      • --max-old-space-size
      • +
      • --perf-basic-prof-only-functions
      • +
      • --perf-basic-prof
      • +
      • --perf-prof-unwinding-info
      • +
      • --perf-prof
      • +
      • --stack-trace-limit + +
      • +
      +

      --perf-basic-prof-only-functions, --perf-basic-prof, +--perf-prof-unwinding-info, and --perf-prof are only available on Linux.

      +

      NODE_PATH=path[:…]#

      + +

      ':'-separated list of directories prefixed to the module search path.

      +

      On Windows, this is a ';'-separated list instead.

      +

      NODE_PENDING_DEPRECATION=1#

      + +

      When set to 1, emit pending deprecation warnings.

      +

      Pending deprecations are generally identical to a runtime deprecation with the +notable exception that they are turned off by default and will not be emitted +unless either the --pending-deprecation command line flag, or the +NODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations +are used to provide a kind of selective "early warning" mechanism that +developers may leverage to detect deprecated API usage.

      +

      NODE_PENDING_PIPE_INSTANCES=instances#

      +

      Set the number of pending pipe instance handles when the pipe server is waiting +for connections. This setting applies to Windows only.

      +

      NODE_PRESERVE_SYMLINKS=1#

      + +

      When set to 1, instructs the module loader to preserve symbolic links when +resolving and caching modules.

      +

      NODE_REDIRECT_WARNINGS=file#

      + +

      When set, process warnings will be emitted to the given file instead of +printing to stderr. The file will be created if it does not exist, and will be +appended to if it does. If an error occurs while attempting to write the +warning to the file, the warning will be written to stderr instead. This is +equivalent to using the --redirect-warnings=file command-line flag.

      +

      NODE_REPL_HISTORY=file#

      + +

      Path to the file used to store the persistent REPL history. The default path is +~/.node_repl_history, which is overridden by this variable. Setting the value +to an empty string ('' or ' ') disables persistent REPL history.

      +

      NODE_REPL_EXTERNAL_MODULE=file#

      + +

      Path to a Node.js module which will be loaded in place of the built-in REPL. +Overriding this value to an empty string ('') will use the built-in REPL.

      +

      NODE_TLS_REJECT_UNAUTHORIZED=value#

      +

      If value equals '0', certificate validation is disabled for TLS connections. +This makes TLS, and HTTPS by extension, insecure. The use of this environment +variable is strongly discouraged.

      +

      NODE_V8_COVERAGE=dir#

      +

      When set, Node.js will begin outputting V8 JavaScript code coverage and +Source Map data to the directory provided as an argument (coverage +information is written as JSON to files with a coverage prefix).

      +

      NODE_V8_COVERAGE will automatically propagate to subprocesses, making it +easier to instrument applications that call the child_process.spawn() family +of functions. NODE_V8_COVERAGE can be set to an empty string, to prevent +propagation.

      +

      Coverage output#

      +

      Coverage is output as an array of ScriptCoverage objects on the top-level +key result:

      +
      {
      +  "result": [
      +    {
      +      "scriptId": "67",
      +      "url": "internal/tty.js",
      +      "functions": []
      +    }
      +  ]
      +}
      +

      Source map cache#

      +

      Stability: 1 - Experimental

      +

      If found, source map data is appended to the top-level key source-map-cache +on the JSON coverage object.

      +

      source-map-cache is an object with keys representing the files source maps +were extracted from, and values which include the raw source-map URL +(in the key url), the parsed Source Map v3 information (in the key data), +and the line lengths of the source file (in the key lineLengths).

      +
      {
      +  "result": [
      +    {
      +      "scriptId": "68",
      +      "url": "file:///absolute/path/to/source.js",
      +      "functions": []
      +    }
      +  ],
      +  "source-map-cache": {
      +    "file:///absolute/path/to/source.js": {
      +      "url": "./path-to-map.json",
      +      "data": {
      +        "version": 3,
      +        "sources": [
      +          "file:///absolute/path/to/original.js"
      +        ],
      +        "names": [
      +          "Foo",
      +          "console",
      +          "info"
      +        ],
      +        "mappings": "MAAMA,IACJC,YAAaC",
      +        "sourceRoot": "./"
      +      },
      +      "lineLengths": [
      +        13,
      +        62,
      +        38,
      +        27
      +      ]
      +    }
      +  }
      +}
      +

      OPENSSL_CONF=file#

      + +

      Load an OpenSSL configuration file on startup. Among other uses, this can be +used to enable FIPS-compliant crypto if Node.js is built with ./configure --openssl-fips.

      +

      If the --openssl-config command line option is used, the environment +variable is ignored.

      +

      SSL_CERT_DIR=dir#

      + +

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory +containing trusted certificates.

      +

      Be aware that unless the child environment is explicitly set, this environment +variable will be inherited by any child processes, and if they use OpenSSL, it +may cause them to trust the same CAs as node.

      +

      SSL_CERT_FILE=file#

      + +

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file +containing trusted certificates.

      +

      Be aware that unless the child environment is explicitly set, this environment +variable will be inherited by any child processes, and if they use OpenSSL, it +may cause them to trust the same CAs as node.

      +

      UV_THREADPOOL_SIZE=size#

      +

      Set the number of threads used in libuv's threadpool to size threads.

      +

      Asynchronous system APIs are used by Node.js whenever possible, but where they +do not exist, libuv's threadpool is used to create asynchronous node APIs based +on synchronous system APIs. Node.js APIs that use the threadpool are:

      +
        +
      • all fs APIs, other than the file watcher APIs and those that are explicitly +synchronous
      • +
      • asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(), +crypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
      • +
      • dns.lookup()
      • +
      • all zlib APIs, other than those that are explicitly synchronous
      • +
      +

      Because libuv's threadpool has a fixed size, it means that if for whatever +reason any of these APIs takes a long time, other (seemingly unrelated) APIs +that run in libuv's threadpool will experience degraded performance. In order to +mitigate this issue, one potential solution is to increase the size of libuv's +threadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value +greater than 4 (its current default value). For more information, see the +libuv threadpool documentation.

      +

      Useful V8 options#

      +

      V8 has its own set of CLI options. Any V8 CLI option that is provided to node +will be passed on to V8 to handle. V8's options have no stability guarantee. +The V8 team themselves don't consider them to be part of their formal API, +and reserve the right to change them at any time. Likewise, they are not +covered by the Node.js stability guarantees. Many of the V8 +options are of interest only to V8 developers. Despite this, there is a small +set of V8 options that are widely applicable to Node.js, and they are +documented here:

      +

      --max-old-space-size=SIZE (in megabytes)#

      +

      Sets the max memory size of V8's old memory section. As memory +consumption approaches the limit, V8 will spend more time on +garbage collection in an effort to free unused memory.

      +

      On a machine with 2GB of memory, consider setting this to +1536 (1.5GB) to leave some memory for other uses and avoid swapping.

      +
      $ node --max-old-space-size=1536 index.js
      + +
      +
      +
      + + diff --git a/doc/api/cli.json b/doc/api/cli.json new file mode 100644 index 0000000000000000000000000000000000000000..3fd741eee833f2810a1955c02eb3a82015a337d9 --- /dev/null +++ b/doc/api/cli.json @@ -0,0 +1,1666 @@ +{ + "type": "module", + "source": "doc/api/cli.md", + "introduced_in": "v5.9.1", + "miscs": [ + { + "textRaw": "Command line options", + "name": "Command line options", + "introduced_in": "v5.9.1", + "type": "misc", + "desc": "

      Node.js comes with a variety of CLI options. These options expose built-in\ndebugging, multiple ways to execute scripts, and other helpful runtime options.

      \n

      To view this documentation as a manual page in a terminal, run man node.

      ", + "miscs": [ + { + "textRaw": "Synopsis", + "name": "synopsis", + "desc": "

      node [options] [V8 options] [script.js | -e \"script\" | -] [--] [arguments]

      \n

      node inspect [script.js | -e \"script\" | <host>:<port>] …

      \n

      node --v8-options

      \n

      Execute without arguments to start the REPL.

      \n

      For more info about node inspect, please see the debugger documentation.

      ", + "type": "misc", + "displayName": "Synopsis" + }, + { + "textRaw": "Options", + "name": "options", + "meta": { + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/23020", + "description": "Underscores instead of dashes are now allowed for Node.js options as well, in addition to V8 options." + } + ] + }, + "desc": "

      All options, including V8 options, allow words to be separated by both\ndashes (-) or underscores (_).

      \n

      For example, --pending-deprecation is equivalent to --pending_deprecation.

      \n

      If an option that takes a single value, for example --max-http-header-size,\nis passed more than once, then the last passed value will be used. Options\nfrom the command line take precedence over options passed through the\nNODE_OPTIONS environment variable.

      ", + "modules": [ + { + "textRaw": "`-`", + "name": "`-`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Alias for stdin. Analogous to the use of - in other command line utilities,\nmeaning that the script will be read from stdin, and the rest of the options\nare passed to that script.

      ", + "type": "module", + "displayName": "`-`" + }, + { + "textRaw": "`--`", + "name": "`--`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      Indicate the end of node options. Pass the rest of the arguments to the script.\nIf no script filename or eval/print script is supplied prior to this, then\nthe next argument will be used as a script filename.

      ", + "type": "module", + "displayName": "`--`" + }, + { + "textRaw": "`--abort-on-uncaught-exception`", + "name": "`--abort-on-uncaught-exception`", + "meta": { + "added": [ + "v0.10.8" + ], + "changes": [] + }, + "desc": "

      Aborting instead of exiting causes a core file to be generated for post-mortem\nanalysis using a debugger (such as lldb, gdb, and mdb).

      \n

      If this flag is passed, the behavior can still be set to not abort through\nprocess.setUncaughtExceptionCaptureCallback() (and through usage of the\ndomain module that uses it).

      ", + "type": "module", + "displayName": "`--abort-on-uncaught-exception`" + }, + { + "textRaw": "`--completion-bash`", + "name": "`--completion-bash`", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "desc": "

      Print source-able bash completion script for Node.js.

      \n
      $ node --completion-bash > node_bash_completion\n$ source node_bash_completion\n
      ", + "type": "module", + "displayName": "`--completion-bash`" + }, + { + "textRaw": "`--conditions=condition`", + "name": "`--conditions=condition`", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Enable experimental support for custom conditional exports resolution\nconditions.

      \n

      Any number of custom string condition names are permitted.

      \n

      The default Node.js conditions of \"node\", \"default\", \"import\", and\n\"require\" will always apply as defined.

      ", + "type": "module", + "displayName": "`--conditions=condition`" + }, + { + "textRaw": "`--cpu-prof`", + "name": "`--cpu-prof`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Starts the V8 CPU profiler on start up, and writes the CPU profile to disk\nbefore exit.

      \n

      If --cpu-prof-dir is not specified, the generated profile will be placed\nin the current working directory.

      \n

      If --cpu-prof-name is not specified, the generated profile will be\nnamed CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.

      \n
      $ node --cpu-prof index.js\n$ ls *.cpuprofile\nCPU.20190409.202950.15293.0.0.cpuprofile\n
      ", + "type": "module", + "displayName": "`--cpu-prof`" + }, + { + "textRaw": "`--cpu-prof-dir`", + "name": "`--cpu-prof-dir`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the directory where the CPU profiles generated by --cpu-prof will\nbe placed.

      \n

      The default value is controlled by the\n--diagnostic-dir command line option.

      ", + "type": "module", + "displayName": "`--cpu-prof-dir`" + }, + { + "textRaw": "`--cpu-prof-interval`", + "name": "`--cpu-prof-interval`", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the sampling interval in microseconds for the CPU profiles generated\nby --cpu-prof. The default is 1000 microseconds.

      ", + "type": "module", + "displayName": "`--cpu-prof-interval`" + }, + { + "textRaw": "`--cpu-prof-name`", + "name": "`--cpu-prof-name`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the file name of the CPU profile generated by --cpu-prof.

      ", + "type": "module", + "displayName": "`--cpu-prof-name`" + }, + { + "textRaw": "`--diagnostic-dir=directory`", + "name": "`--diagnostic-dir=directory`", + "desc": "

      Set the directory to which all diagnostic output files will be written to.\nDefaults to current working directory.

      \n

      Affects the default output directory of:

      \n", + "type": "module", + "displayName": "`--diagnostic-dir=directory`" + }, + { + "textRaw": "`--disable-proto=mode`", + "name": "`--disable-proto=mode`", + "desc": "\n

      Disable the Object.prototype.__proto__ property. If mode is delete, the\nproperty will be removed entirely. If mode is throw, accesses to the\nproperty will throw an exception with the code ERR_PROTO_ACCESS.

      ", + "type": "module", + "displayName": "`--disable-proto=mode`" + }, + { + "textRaw": "`--disallow-code-generation-from-strings`", + "name": "`--disallow-code-generation-from-strings`", + "meta": { + "added": [ + "v9.8.0" + ], + "changes": [] + }, + "desc": "

      Make built-in language features like eval and new Function that generate\ncode from strings throw an exception instead. This does not affect the Node.js\nvm module.

      ", + "type": "module", + "displayName": "`--disallow-code-generation-from-strings`" + }, + { + "textRaw": "`--enable-fips`", + "name": "`--enable-fips`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with\n./configure --openssl-fips.)

      ", + "type": "module", + "displayName": "`--enable-fips`" + }, + { + "textRaw": "`--enable-source-maps`", + "name": "`--enable-source-maps`", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Enable experimental Source Map v3 support for stack traces.

      \n

      Currently, overriding Error.prepareStackTrace is ignored when the\n--enable-source-maps flag is set.

      ", + "type": "module", + "displayName": "`--enable-source-maps`" + }, + { + "textRaw": "`--experimental-import-meta-resolve`", + "name": "`--experimental-import-meta-resolve`", + "meta": { + "added": [ + "v12.16.2" + ], + "changes": [] + }, + "desc": "

      Enable experimental import.meta.resolve() support.

      ", + "type": "module", + "displayName": "`--experimental-import-meta-resolve`" + }, + { + "textRaw": "`--experimental-json-modules`", + "name": "`--experimental-json-modules`", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental JSON support for the ES Module loader.

      ", + "type": "module", + "displayName": "`--experimental-json-modules`" + }, + { + "textRaw": "`--experimental-loader=module`", + "name": "`--experimental-loader=module`", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "desc": "

      Specify the module of a custom experimental ECMAScript Module loader.\nmodule may be either a path to a file, or an ECMAScript Module name.

      ", + "type": "module", + "displayName": "`--experimental-loader=module`" + }, + { + "textRaw": "`--experimental-modules`", + "name": "`--experimental-modules`", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      Enable latest experimental modules features (deprecated).

      ", + "type": "module", + "displayName": "`--experimental-modules`" + }, + { + "textRaw": "`--experimental-policy`", + "name": "`--experimental-policy`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [] + }, + "desc": "

      Use the specified file as a security policy.

      ", + "type": "module", + "displayName": "`--experimental-policy`" + }, + { + "textRaw": "`--experimental-repl-await`", + "name": "`--experimental-repl-await`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental top-level await keyword support in REPL.

      ", + "type": "module", + "displayName": "`--experimental-repl-await`" + }, + { + "textRaw": "`--experimental-specifier-resolution=mode`", + "name": "`--experimental-specifier-resolution=mode`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Sets the resolution algorithm for resolving ES module specifiers. Valid options\nare explicit and node.

      \n

      The default is explicit, which requires providing the full path to a\nmodule. The node mode will enable support for optional file extensions and\nthe ability to import a directory that has an index file.

      \n

      Please see customizing ESM specifier resolution for example usage.

      ", + "type": "module", + "displayName": "`--experimental-specifier-resolution=mode`" + }, + { + "textRaw": "`--experimental-vm-modules`", + "name": "`--experimental-vm-modules`", + "meta": { + "added": [ + "v9.6.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental ES Module support in the vm module.

      ", + "type": "module", + "displayName": "`--experimental-vm-modules`" + }, + { + "textRaw": "`--experimental-wasi-unstable-preview1`", + "name": "`--experimental-wasi-unstable-preview1`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Enable experimental WebAssembly System Interface (WASI) support.

      ", + "type": "module", + "displayName": "`--experimental-wasi-unstable-preview1`" + }, + { + "textRaw": "`--experimental-wasm-modules`", + "name": "`--experimental-wasm-modules`", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "type": "module", + "displayName": "`--experimental-wasm-modules`" + }, + { + "textRaw": "`--force-context-aware`", + "name": "`--force-context-aware`", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      Disable loading native addons that are not context-aware.

      \n

      Enable experimental WebAssembly module support.

      ", + "type": "module", + "displayName": "`--force-context-aware`" + }, + { + "textRaw": "`--force-fips`", + "name": "`--force-fips`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)\n(Same requirements as --enable-fips.)

      ", + "type": "module", + "displayName": "`--force-fips`" + }, + { + "textRaw": "`--frozen-intrinsics`", + "name": "`--frozen-intrinsics`", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Enable experimental frozen intrinsics like Array and Object.

      \n

      Support is currently only provided for the root context and no guarantees are\ncurrently provided that global.Array is indeed the default intrinsic\nreference. Code may break under this flag.

      \n

      --require runs prior to freezing intrinsics in order to allow polyfills to\nbe added.

      ", + "type": "module", + "displayName": "`--frozen-intrinsics`" + }, + { + "textRaw": "`--heapsnapshot-signal=signal`", + "name": "`--heapsnapshot-signal=signal`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Enables a signal handler that causes the Node.js process to write a heap dump\nwhen the specified signal is received. signal must be a valid signal name.\nDisabled by default.

      \n
      $ node --heapsnapshot-signal=SIGUSR2 index.js &\n$ ps aux\nUSER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND\nnode         1  5.5  6.1 787252 247004 ?       Ssl  16:43   0:02 node --heapsnapshot-signal=SIGUSR2 index.js\n$ kill -USR2 1\n$ ls\nHeap.20190718.133405.15554.0.001.heapsnapshot\n
      ", + "type": "module", + "displayName": "`--heapsnapshot-signal=signal`" + }, + { + "textRaw": "`--heap-prof`", + "name": "`--heap-prof`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Starts the V8 heap profiler on start up, and writes the heap profile to disk\nbefore exit.

      \n

      If --heap-prof-dir is not specified, the generated profile will be placed\nin the current working directory.

      \n

      If --heap-prof-name is not specified, the generated profile will be\nnamed Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.

      \n
      $ node --heap-prof index.js\n$ ls *.heapprofile\nHeap.20190409.202950.15293.0.001.heapprofile\n
      ", + "type": "module", + "displayName": "`--heap-prof`" + }, + { + "textRaw": "`--heap-prof-dir`", + "name": "`--heap-prof-dir`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the directory where the heap profiles generated by --heap-prof will\nbe placed.

      \n

      The default value is controlled by the\n--diagnostic-dir command line option.

      ", + "type": "module", + "displayName": "`--heap-prof-dir`" + }, + { + "textRaw": "`--heap-prof-interval`", + "name": "`--heap-prof-interval`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the average sampling interval in bytes for the heap profiles generated\nby --heap-prof. The default is 512 * 1024 bytes.

      ", + "type": "module", + "displayName": "`--heap-prof-interval`" + }, + { + "textRaw": "`--heap-prof-name`", + "name": "`--heap-prof-name`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Specify the file name of the heap profile generated by --heap-prof.

      ", + "type": "module", + "displayName": "`--heap-prof-name`" + }, + { + "textRaw": "`--http-parser=library`", + "name": "`--http-parser=library`", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [ + { + "version": "v12.22.0", + "pr-url": "https://github.com/nodejs/node/pull/37603", + "description": "The legacy HTTP parser will emit a deprecation warning." + } + ] + }, + "desc": "

      Chooses an HTTP parser library. Available values are:

      \n\n

      The default is llhttp, unless otherwise specified when building Node.js.

      \n

      The legacy HTTP parser is deprecated and will emit a deprecation warning.

      \n

      This flag exists to aid in experimentation with the internal implementation of\nthe Node.js http parser.\nThis flag is likely to become a no-op and removed at some point in the future.

      ", + "type": "module", + "displayName": "`--http-parser=library`" + }, + { + "textRaw": "`--http-server-default-timeout=milliseconds`", + "name": "`--http-server-default-timeout=milliseconds`", + "meta": { + "added": [ + "v12.4.0" + ], + "changes": [] + }, + "desc": "

      Overrides the default value of http, https and http2 server socket\ntimeout. Setting the value to 0 disables server socket timeout. Unless\nprovided, http server sockets timeout after 120s (2 minutes). Programmatic\nsetting of the timeout takes precedence over the value set through this\nflag.

      ", + "type": "module", + "displayName": "`--http-server-default-timeout=milliseconds`" + }, + { + "textRaw": "`--icu-data-dir=file`", + "name": "`--icu-data-dir=file`", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      Specify ICU data load path. (Overrides NODE_ICU_DATA.)

      ", + "type": "module", + "displayName": "`--icu-data-dir=file`" + }, + { + "textRaw": "`--input-type=type`", + "name": "`--input-type=type`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      This configures Node.js to interpret string input as CommonJS or as an ES\nmodule. String input is input via --eval, --print, or STDIN.

      \n

      Valid values are \"commonjs\" and \"module\". The default is \"commonjs\".

      ", + "type": "module", + "displayName": "`--input-type=type`" + }, + { + "textRaw": "`--inspect-brk[=[host:]port]`", + "name": "`--inspect-brk[=[host:]port]`", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "desc": "

      Activate inspector on host:port and break at start of user script.\nDefault host:port is 127.0.0.1:9229.

      ", + "type": "module", + "displayName": "`--inspect-brk[=[host:]port]`" + }, + { + "textRaw": "`--inspect-port=[host:]port`", + "name": "`--inspect-port=[host:]port`", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "desc": "

      Set the host:port to be used when the inspector is activated.\nUseful when activating the inspector by sending the SIGUSR1 signal.

      \n

      Default host is 127.0.0.1.

      \n

      See the security warning below regarding the host\nparameter usage.

      ", + "type": "module", + "displayName": "`--inspect-port=[host:]port`" + }, + { + "textRaw": "`--inspect[=[host:]port]`", + "name": "`--inspect[=[host:]port]`", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "

      Activate inspector on host:port. Default is 127.0.0.1:9229.

      \n

      V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug\nand profile Node.js instances. The tools attach to Node.js instances via a\ntcp port and communicate using the Chrome DevTools Protocol.

      \n

      ", + "modules": [ + { + "textRaw": "Warning: binding inspector to a public IP:port combination is insecure", + "name": "warning:_binding_inspector_to_a_public_ip:port_combination_is_insecure", + "desc": "

      Binding the inspector to a public IP (including 0.0.0.0) with an open port is\ninsecure, as it allows external hosts to connect to the inspector and perform\na remote code execution attack.

      \n

      If specifying a host, make sure that either:

      \n
        \n
      • The host is not accessible from public networks.
      • \n
      • A firewall disallows unwanted connections on the port.
      • \n
      \n

      More specifically, --inspect=0.0.0.0 is insecure if the port (9229 by\ndefault) is not firewall-protected.

      \n

      See the debugging security implications section for more information.

      ", + "type": "module", + "displayName": "Warning: binding inspector to a public IP:port combination is insecure" + } + ], + "type": "module", + "displayName": "`--inspect[=[host:]port]`" + }, + { + "textRaw": "`--inspect-publish-uid=stderr,http`", + "name": "`--inspect-publish-uid=stderr,http`", + "desc": "

      Specify ways of the inspector web socket url exposure.

      \n

      By default inspector websocket url is available in stderr and under /json/list\nendpoint on http://host:port/json/list.

      ", + "type": "module", + "displayName": "`--inspect-publish-uid=stderr,http`" + }, + { + "textRaw": "`--insecure-http-parser`", + "name": "`--insecure-http-parser`", + "meta": { + "added": [ + "v12.15.0" + ], + "changes": [] + }, + "desc": "

      Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow\ninteroperability with non-conformant HTTP implementations. It may also allow\nrequest smuggling and other HTTP attacks that rely on invalid headers being\naccepted. Avoid using this option.

      ", + "type": "module", + "displayName": "`--insecure-http-parser`" + }, + { + "textRaw": "`--jitless`", + "name": "`--jitless`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Disable runtime allocation of executable memory. This may be\nrequired on some platforms for security reasons. It can also reduce attack\nsurface on other platforms, but the performance impact may be severe.

      \n

      This flag is inherited from V8 and is subject to change upstream. It may\ndisappear in a non-semver-major release.

      ", + "type": "module", + "displayName": "`--jitless`" + }, + { + "textRaw": "`--max-http-header-size=size`", + "name": "`--max-http-header-size=size`", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB.

      ", + "type": "module", + "displayName": "`--max-http-header-size=size`" + }, + { + "textRaw": "`--napi-modules`", + "name": "`--napi-modules`", + "meta": { + "added": [ + "v7.10.0" + ], + "changes": [] + }, + "desc": "

      This option is a no-op. It is kept for compatibility.

      ", + "type": "module", + "displayName": "`--napi-modules`" + }, + { + "textRaw": "`--no-deprecation`", + "name": "`--no-deprecation`", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      Silence deprecation warnings.

      ", + "type": "module", + "displayName": "`--no-deprecation`" + }, + { + "textRaw": "`--no-force-async-hooks-checks`", + "name": "`--no-force-async-hooks-checks`", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "desc": "

      Disables runtime checks for async_hooks. These will still be enabled\ndynamically when async_hooks is enabled.

      ", + "type": "module", + "displayName": "`--no-force-async-hooks-checks`" + }, + { + "textRaw": "`--no-warnings`", + "name": "`--no-warnings`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Silence all process warnings (including deprecations).

      ", + "type": "module", + "displayName": "`--no-warnings`" + }, + { + "textRaw": "`--openssl-config=file`", + "name": "`--openssl-config=file`", + "meta": { + "added": [ + "v6.9.0" + ], + "changes": [] + }, + "desc": "

      Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built with\n./configure --openssl-fips.

      ", + "type": "module", + "displayName": "`--openssl-config=file`" + }, + { + "textRaw": "`--pending-deprecation`", + "name": "`--pending-deprecation`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Emit pending deprecation warnings.

      \n

      Pending deprecations are generally identical to a runtime deprecation with the\nnotable exception that they are turned off by default and will not be emitted\nunless either the --pending-deprecation command line flag, or the\nNODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations\nare used to provide a kind of selective \"early warning\" mechanism that\ndevelopers may leverage to detect deprecated API usage.

      ", + "type": "module", + "displayName": "`--pending-deprecation`" + }, + { + "textRaw": "`--policy-integrity=sri`", + "name": "`--policy-integrity=sri`", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Instructs Node.js to error prior to running any code if the policy does not have\nthe specified integrity. It expects a Subresource Integrity string as a\nparameter.

      ", + "type": "module", + "displayName": "`--policy-integrity=sri`" + }, + { + "textRaw": "`--preserve-symlinks`", + "name": "`--preserve-symlinks`", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "

      Instructs the module loader to preserve symbolic links when resolving and\ncaching modules.

      \n

      By default, when Node.js loads a module from a path that is symbolically linked\nto a different on-disk location, Node.js will dereference the link and use the\nactual on-disk \"real path\" of the module as both an identifier and as a root\npath to locate other dependency modules. In most cases, this default behavior\nis acceptable. However, when using symbolically linked peer dependencies, as\nillustrated in the example below, the default behavior causes an exception to\nbe thrown if moduleA attempts to require moduleB as a peer dependency:

      \n
      {appDir}\n ├── app\n │   ├── index.js\n │   └── node_modules\n │       ├── moduleA -> {appDir}/moduleA\n │       └── moduleB\n │           ├── index.js\n │           └── package.json\n └── moduleA\n     ├── index.js\n     └── package.json\n
      \n

      The --preserve-symlinks command line flag instructs Node.js to use the\nsymlink path for modules as opposed to the real path, allowing symbolically\nlinked peer dependencies to be found.

      \n

      Note, however, that using --preserve-symlinks can have other side effects.\nSpecifically, symbolically linked native modules can fail to load if those\nare linked from more than one location in the dependency tree (Node.js would\nsee those as two separate modules and would attempt to load the module multiple\ntimes, causing an exception to be thrown).

      \n

      The --preserve-symlinks flag does not apply to the main module, which allows\nnode --preserve-symlinks node_module/.bin/<foo> to work. To apply the same\nbehavior for the main module, also use --preserve-symlinks-main.

      ", + "type": "module", + "displayName": "`--preserve-symlinks`" + }, + { + "textRaw": "`--preserve-symlinks-main`", + "name": "`--preserve-symlinks-main`", + "meta": { + "added": [ + "v10.2.0" + ], + "changes": [] + }, + "desc": "

      Instructs the module loader to preserve symbolic links when resolving and\ncaching the main module (require.main).

      \n

      This flag exists so that the main module can be opted-in to the same behavior\nthat --preserve-symlinks gives to all other imports; they are separate flags,\nhowever, for backward compatibility with older Node.js versions.

      \n

      --preserve-symlinks-main does not imply --preserve-symlinks; it\nis expected that --preserve-symlinks-main will be used in addition to\n--preserve-symlinks when it is not desirable to follow symlinks before\nresolving relative paths.

      \n

      See --preserve-symlinks for more information.

      ", + "type": "module", + "displayName": "`--preserve-symlinks-main`" + }, + { + "textRaw": "`--prof`", + "name": "`--prof`", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "desc": "

      Generate V8 profiler output.

      ", + "type": "module", + "displayName": "`--prof`" + }, + { + "textRaw": "`--prof-process`", + "name": "`--prof-process`", + "meta": { + "added": [ + "v5.2.0" + ], + "changes": [] + }, + "desc": "

      Process V8 profiler output generated using the V8 option --prof.

      ", + "type": "module", + "displayName": "`--prof-process`" + }, + { + "textRaw": "`--redirect-warnings=file`", + "name": "`--redirect-warnings=file`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Write process warnings to the given file instead of printing to stderr. The\nfile will be created if it does not exist, and will be appended to if it does.\nIf an error occurs while attempting to write the warning to the file, the\nwarning will be written to stderr instead.

      \n

      The file name may be an absolute path. If it is not, the default directory it\nwill be written to is controlled by the\n--diagnostic-dir command line option.

      ", + "type": "module", + "displayName": "`--redirect-warnings=file`" + }, + { + "textRaw": "`--report-compact`", + "name": "`--report-compact`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Write reports in a compact format, single-line JSON, more easily consumable\nby log processing systems than the default multi-line format designed for\nhuman consumption.

      ", + "type": "module", + "displayName": "`--report-compact`" + }, + { + "textRaw": "`--report-dir=directory`, `report-directory=directory`", + "name": "`--report-dir=directory`,_`report-directory=directory`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "Changed from `--diagnostic-report-directory` to `--report-directory`" + } + ] + }, + "desc": "

      Location at which the report will be generated.

      ", + "type": "module", + "displayName": "`--report-dir=directory`, `report-directory=directory`" + }, + { + "textRaw": "`--report-filename=filename`", + "name": "`--report-filename=filename`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-filename` to `--report-filename`" + } + ] + }, + "desc": "

      Name of the file to which the report will be written.

      ", + "type": "module", + "displayName": "`--report-filename=filename`" + }, + { + "textRaw": "`--report-on-fatalerror`", + "name": "`--report-on-fatalerror`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32496", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-on-fatalerror` to `--report-on-fatalerror`" + } + ] + }, + "desc": "

      Enables the report to be triggered on fatal errors (internal errors within\nthe Node.js runtime such as out of memory) that lead to termination of the\napplication. Useful to inspect various diagnostic data elements such as heap,\nstack, event loop state, resource consumption etc. to reason about the fatal\nerror.

      ", + "type": "module", + "displayName": "`--report-on-fatalerror`" + }, + { + "textRaw": "`--report-on-signal`", + "name": "`--report-on-signal`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-on-signal` to `--report-on-signal`" + } + ] + }, + "desc": "

      Enables report to be generated upon receiving the specified (or predefined)\nsignal to the running Node.js process. The signal to trigger the report is\nspecified through --report-signal.

      ", + "type": "module", + "displayName": "`--report-on-signal`" + }, + { + "textRaw": "`--report-signal=signal`", + "name": "`--report-signal=signal`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-signal` to `--report-signal`" + } + ] + }, + "desc": "

      Sets or resets the signal for report generation (not supported on Windows).\nDefault signal is SIGUSR2.

      ", + "type": "module", + "displayName": "`--report-signal=signal`" + }, + { + "textRaw": "`--report-uncaught-exception`", + "name": "`--report-uncaught-exception`", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This option is no longer experimental." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27312", + "description": "changed from `--diagnostic-report-uncaught-exception` to `--report-uncaught-exception`" + } + ] + }, + "desc": "

      Enables report to be generated on uncaught exceptions. Useful when inspecting\nthe JavaScript stack in conjunction with native stack and other runtime\nenvironment data.

      ", + "type": "module", + "displayName": "`--report-uncaught-exception`" + }, + { + "textRaw": "`--throw-deprecation`", + "name": "`--throw-deprecation`", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "desc": "

      Throw errors for deprecations.

      ", + "type": "module", + "displayName": "`--throw-deprecation`" + }, + { + "textRaw": "`--title=title`", + "name": "`--title=title`", + "meta": { + "added": [ + "v10.7.0" + ], + "changes": [] + }, + "desc": "

      Set process.title on startup.

      ", + "type": "module", + "displayName": "`--title=title`" + }, + { + "textRaw": "`--tls-cipher-list=list`", + "name": "`--tls-cipher-list=list`", + "meta": { + "added": [ + "v4.0.0" + ], + "changes": [] + }, + "desc": "

      Specify an alternative default TLS cipher list. Requires Node.js to be built\nwith crypto support (default).

      ", + "type": "module", + "displayName": "`--tls-cipher-list=list`" + }, + { + "textRaw": "`--tls-keylog=file`", + "name": "`--tls-keylog=file`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Log TLS key material to a file. The key material is in NSS SSLKEYLOGFILE\nformat and can be used by software (such as Wireshark) to decrypt the TLS\ntraffic.

      ", + "type": "module", + "displayName": "`--tls-keylog=file`" + }, + { + "textRaw": "`--tls-max-v1.2`", + "name": "`--tls-max-v1.2`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for\nTLSv1.3.

      ", + "type": "module", + "displayName": "`--tls-max-v1.2`" + }, + { + "textRaw": "`--tls-max-v1.3`", + "name": "`--tls-max-v1.3`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support\nfor TLSv1.3.

      ", + "type": "module", + "displayName": "`--tls-max-v1.3`" + }, + { + "textRaw": "`--tls-min-v1.0`", + "name": "`--tls-min-v1.0`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with\nold TLS clients or servers.

      ", + "type": "module", + "displayName": "`--tls-min-v1.0`" + }, + { + "textRaw": "`--tls-min-v1.1`", + "name": "`--tls-min-v1.1`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility\nwith old TLS clients or servers.

      ", + "type": "module", + "displayName": "`--tls-min-v1.1`" + }, + { + "textRaw": "`--tls-min-v1.2`", + "name": "`--tls-min-v1.2`", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.2'. This is the default for\n12.x and later, but the option is supported for compatibility with older Node.js\nversions.

      ", + "type": "module", + "displayName": "`--tls-min-v1.2`" + }, + { + "textRaw": "`--tls-min-v1.3`", + "name": "`--tls-min-v1.3`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support\nfor TLSv1.2, which is not as secure as TLSv1.3.

      ", + "type": "module", + "displayName": "`--tls-min-v1.3`" + }, + { + "textRaw": "`--trace-deprecation`", + "name": "`--trace-deprecation`", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      Print stack traces for deprecations.

      ", + "type": "module", + "displayName": "`--trace-deprecation`" + }, + { + "textRaw": "`--trace-event-categories`", + "name": "`--trace-event-categories`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      A comma separated list of categories that should be traced when trace event\ntracing is enabled using --trace-events-enabled.

      ", + "type": "module", + "displayName": "`--trace-event-categories`" + }, + { + "textRaw": "`--trace-event-file-pattern`", + "name": "`--trace-event-file-pattern`", + "meta": { + "added": [ + "v9.8.0" + ], + "changes": [] + }, + "desc": "

      Template string specifying the filepath for the trace event data, it\nsupports ${rotation} and ${pid}.

      ", + "type": "module", + "displayName": "`--trace-event-file-pattern`" + }, + { + "textRaw": "`--trace-events-enabled`", + "name": "`--trace-events-enabled`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      Enables the collection of trace event tracing information.

      ", + "type": "module", + "displayName": "`--trace-events-enabled`" + }, + { + "textRaw": "`--trace-exit`", + "name": "`--trace-exit`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Prints a stack trace whenever an environment is exited proactively,\ni.e. invoking process.exit().

      ", + "type": "module", + "displayName": "`--trace-exit`" + }, + { + "textRaw": "`--trace-sigint`", + "name": "`--trace-sigint`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Prints a stack trace on SIGINT.

      ", + "type": "module", + "displayName": "`--trace-sigint`" + }, + { + "textRaw": "`--trace-sync-io`", + "name": "`--trace-sync-io`", + "meta": { + "added": [ + "v2.1.0" + ], + "changes": [] + }, + "desc": "

      Prints a stack trace whenever synchronous I/O is detected after the first turn\nof the event loop.

      ", + "type": "module", + "displayName": "`--trace-sync-io`" + }, + { + "textRaw": "`--trace-tls`", + "name": "`--trace-tls`", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "desc": "

      Prints TLS packet trace information to stderr. This can be used to debug TLS\nconnection problems.

      ", + "type": "module", + "displayName": "`--trace-tls`" + }, + { + "textRaw": "`--trace-uncaught`", + "name": "`--trace-uncaught`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Print stack traces for uncaught exceptions; usually, the stack trace associated\nwith the creation of an Error is printed, whereas this makes Node.js also\nprint the stack trace associated with throwing the value (which does not need\nto be an Error instance).

      \n

      Enabling this option may affect garbage collection behavior negatively.

      ", + "type": "module", + "displayName": "`--trace-uncaught`" + }, + { + "textRaw": "`--trace-warnings`", + "name": "`--trace-warnings`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Print stack traces for process warnings (including deprecations).

      ", + "type": "module", + "displayName": "`--trace-warnings`" + }, + { + "textRaw": "`--track-heap-objects`", + "name": "`--track-heap-objects`", + "meta": { + "added": [ + "v2.4.0" + ], + "changes": [] + }, + "desc": "

      Track heap object allocations for heap snapshots.

      ", + "type": "module", + "displayName": "`--track-heap-objects`" + }, + { + "textRaw": "`--unhandled-rejections=mode`", + "name": "`--unhandled-rejections=mode`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "desc": "

      By default all unhandled rejections trigger a warning plus a deprecation warning\nfor the very first unhandled rejection in case no unhandledRejection hook\nis used.

      \n

      Using this flag allows to change what should happen when an unhandled rejection\noccurs. One of three modes can be chosen:

      \n
        \n
      • strict: Raise the unhandled rejection as an uncaught exception.
      • \n
      • warn: Always trigger a warning, no matter if the unhandledRejection\nhook is set or not but do not print the deprecation warning.
      • \n
      • none: Silence all warnings.
      • \n
      ", + "type": "module", + "displayName": "`--unhandled-rejections=mode`" + }, + { + "textRaw": "`--use-bundled-ca`, `--use-openssl-ca`", + "name": "`--use-bundled-ca`,_`--use-openssl-ca`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      Use bundled Mozilla CA store as supplied by current Node.js version\nor use OpenSSL's default CA store. The default store is selectable\nat build-time.

      \n

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store\nthat is fixed at release time. It is identical on all supported platforms.

      \n

      Using OpenSSL store allows for external modifications of the store. For most\nLinux and BSD distributions, this store is maintained by the distribution\nmaintainers and system administrators. OpenSSL CA store location is dependent on\nconfiguration of the OpenSSL library but this can be altered at runtime using\nenvironment variables.

      \n

      See SSL_CERT_DIR and SSL_CERT_FILE.

      ", + "type": "module", + "displayName": "`--use-bundled-ca`, `--use-openssl-ca`" + }, + { + "textRaw": "`--use-largepages=mode`", + "name": "`--use-largepages=mode`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Re-map the Node.js static code to large memory pages at startup. If supported on\nthe target system, this will cause the Node.js static code to be moved onto 2\nMiB pages instead of 4 KiB pages.

      \n

      The following values are valid for mode:

      \n
        \n
      • off: No mapping will be attempted. This is the default.
      • \n
      • on: If supported by the OS, mapping will be attempted. Failure to map will\nbe ignored and a message will be printed to standard error.
      • \n
      • silent: If supported by the OS, mapping will be attempted. Failure to map\nwill be ignored and will not be reported.
      • \n
      ", + "type": "module", + "displayName": "`--use-largepages=mode`" + }, + { + "textRaw": "`--v8-options`", + "name": "`--v8-options`", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      Print V8 command line options.

      ", + "type": "module", + "displayName": "`--v8-options`" + }, + { + "textRaw": "`--v8-pool-size=num`", + "name": "`--v8-pool-size=num`", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "desc": "

      Set V8's thread pool size which will be used to allocate background jobs.

      \n

      If set to 0 then V8 will choose an appropriate size of the thread pool based\non the number of online processors.

      \n

      If the value provided is larger than V8's maximum, then the largest value\nwill be chosen.

      ", + "type": "module", + "displayName": "`--v8-pool-size=num`" + }, + { + "textRaw": "`--zero-fill-buffers`", + "name": "`--zero-fill-buffers`", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      Automatically zero-fills all newly allocated Buffer and SlowBuffer\ninstances.

      ", + "type": "module", + "displayName": "`--zero-fill-buffers`" + }, + { + "textRaw": "`-c`, `--check`", + "name": "`-c`,_`--check`", + "meta": { + "added": [ + "v5.0.0", + "v4.2.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19600", + "description": "The `--require` option is now supported when checking a file." + } + ] + }, + "desc": "

      Syntax check the script without executing.

      ", + "type": "module", + "displayName": "`-c`, `--check`" + }, + { + "textRaw": "`-e`, `--eval \"script\"`", + "name": "`-e`,_`--eval_\"script\"`", + "meta": { + "added": [ + "v0.5.2" + ], + "changes": [ + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Built-in libraries are now available as predefined variables." + } + ] + }, + "desc": "

      Evaluate the following argument as JavaScript. The modules which are\npredefined in the REPL can also be used in script.

      \n

      On Windows, using cmd.exe a single quote will not work correctly because it\nonly recognizes double \" for quoting. In Powershell or Git bash, both '\nand \" are usable.

      ", + "type": "module", + "displayName": "`-e`, `--eval \"script\"`" + }, + { + "textRaw": "`-h`, `--help`", + "name": "`-h`,_`--help`", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      Print node command line options.\nThe output of this option is less detailed than this document.

      ", + "type": "module", + "displayName": "`-h`, `--help`" + }, + { + "textRaw": "`-i`, `--interactive`", + "name": "`-i`,_`--interactive`", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      Opens the REPL even if stdin does not appear to be a terminal.

      ", + "type": "module", + "displayName": "`-i`, `--interactive`" + }, + { + "textRaw": "`-p`, `--print \"script\"`", + "name": "`-p`,_`--print_\"script\"`", + "meta": { + "added": [ + "v0.6.4" + ], + "changes": [ + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Built-in libraries are now available as predefined variables." + } + ] + }, + "desc": "

      Identical to -e but prints the result.

      ", + "type": "module", + "displayName": "`-p`, `--print \"script\"`" + }, + { + "textRaw": "`-r`, `--require module`", + "name": "`-r`,_`--require_module`", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "desc": "

      Preload the specified module at startup.

      \n

      Follows require()'s module resolution\nrules. module may be either a path to a file, or a node module name.

      ", + "type": "module", + "displayName": "`-r`, `--require module`" + }, + { + "textRaw": "`-v`, `--version`", + "name": "`-v`,_`--version`", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      Print node's version.

      ", + "type": "module", + "displayName": "`-v`, `--version`" + } + ], + "type": "misc", + "displayName": "Options" + }, + { + "textRaw": "Environment variables", + "name": "environment_variables", + "modules": [ + { + "textRaw": "`NODE_DEBUG=module[,…]`", + "name": "`node_debug=module[,…]`", + "meta": { + "added": [ + "v0.1.32" + ], + "changes": [] + }, + "desc": "

      ','-separated list of core modules that should print debug information.

      ", + "type": "module", + "displayName": "`NODE_DEBUG=module[,…]`" + }, + { + "textRaw": "`NODE_DEBUG_NATIVE=module[,…]`", + "name": "`node_debug_native=module[,…]`", + "desc": "

      ','-separated list of core C++ modules that should print debug information.

      ", + "type": "module", + "displayName": "`NODE_DEBUG_NATIVE=module[,…]`" + }, + { + "textRaw": "`NODE_DISABLE_COLORS=1`", + "name": "`node_disable_colors=1`", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      When set, colors will not be used in the REPL.

      ", + "type": "module", + "displayName": "`NODE_DISABLE_COLORS=1`" + }, + { + "textRaw": "`NODE_EXTRA_CA_CERTS=file`", + "name": "`node_extra_ca_certs=file`", + "meta": { + "added": [ + "v7.3.0" + ], + "changes": [] + }, + "desc": "

      When set, the well known \"root\" CAs (like VeriSign) will be extended with the\nextra certificates in file. The file should consist of one or more trusted\ncertificates in PEM format. A message will be emitted (once) with\nprocess.emitWarning() if the file is missing or\nmalformed, but any errors are otherwise ignored.

      \n

      Neither the well known nor extra certificates are used when the ca\noptions property is explicitly specified for a TLS or HTTPS client or server.

      \n

      This environment variable is ignored when node runs as setuid root or\nhas Linux file capabilities set.

      ", + "type": "module", + "displayName": "`NODE_EXTRA_CA_CERTS=file`" + }, + { + "textRaw": "`NODE_ICU_DATA=file`", + "name": "`node_icu_data=file`", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      Data path for ICU (Intl object) data. Will extend linked-in data when compiled\nwith small-icu support.

      ", + "type": "module", + "displayName": "`NODE_ICU_DATA=file`" + }, + { + "textRaw": "`NODE_NO_WARNINGS=1`", + "name": "`node_no_warnings=1`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      When set to 1, process warnings are silenced.

      ", + "type": "module", + "displayName": "`NODE_NO_WARNINGS=1`" + }, + { + "textRaw": "`NODE_OPTIONS=options...`", + "name": "`node_options=options...`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      A space-separated list of command line options. options... are interpreted\nbefore command line options, so command line options will override or\ncompound after anything in options.... Node.js will exit with an error if\nan option that is not allowed in the environment is used, such as -p or a\nscript file.

      \n

      In case an option value happens to contain a space (for example a path listed\nin --require), it must be escaped using double quotes. For example:

      \n
      NODE_OPTIONS='--require \"./my path/file.js\"'\n
      \n

      A singleton flag passed as a command line option will override the same flag\npassed into NODE_OPTIONS:

      \n
      # The inspector will be available on port 5555\nNODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555\n
      \n

      A flag that can be passed multiple times will be treated as if its\nNODE_OPTIONS instances were passed first, and then its command line\ninstances afterwards:

      \n
      NODE_OPTIONS='--require \"./a.js\"' node --require \"./b.js\"\n# is equivalent to:\nnode --require \"./a.js\" --require \"./b.js\"\n
      \n

      Node.js options that are allowed are:

      \n\n
        \n
      • --conditions
      • \n
      • --diagnostic-dir
      • \n
      • --disable-proto
      • \n
      • --enable-fips
      • \n
      • --enable-source-maps
      • \n
      • --experimental-import-meta-resolve
      • \n
      • --experimental-json-modules
      • \n
      • --experimental-loader
      • \n
      • --experimental-modules
      • \n
      • --experimental-policy
      • \n
      • --experimental-repl-await
      • \n
      • --experimental-specifier-resolution
      • \n
      • --experimental-vm-modules
      • \n
      • --experimental-wasi-unstable-preview1
      • \n
      • --experimental-wasm-modules
      • \n
      • --force-context-aware
      • \n
      • --force-fips
      • \n
      • --frozen-intrinsics
      • \n
      • --heapsnapshot-signal
      • \n
      • --http-parser
      • \n
      • --http-server-default-timeout
      • \n
      • --icu-data-dir
      • \n
      • --input-type
      • \n
      • --insecure-http-parser
      • \n
      • --inspect-brk
      • \n
      • --inspect-port, --debug-port
      • \n
      • --inspect-publish-uid
      • \n
      • --inspect
      • \n
      • --max-http-header-size
      • \n
      • --napi-modules
      • \n
      • --no-deprecation
      • \n
      • --no-force-async-hooks-checks
      • \n
      • --no-warnings
      • \n
      • --openssl-config
      • \n
      • --pending-deprecation
      • \n
      • --policy-integrity
      • \n
      • --preserve-symlinks-main
      • \n
      • --preserve-symlinks
      • \n
      • --prof-process
      • \n
      • --redirect-warnings
      • \n
      • --report-compact
      • \n
      • --report-dir, --report-directory
      • \n
      • --report-filename
      • \n
      • --report-on-fatalerror
      • \n
      • --report-on-signal
      • \n
      • --report-signal
      • \n
      • --report-uncaught-exception
      • \n
      • --require, -r
      • \n
      • --throw-deprecation
      • \n
      • --title
      • \n
      • --tls-cipher-list
      • \n
      • --tls-keylog
      • \n
      • --tls-max-v1.2
      • \n
      • --tls-max-v1.3
      • \n
      • --tls-min-v1.0
      • \n
      • --tls-min-v1.1
      • \n
      • --tls-min-v1.2
      • \n
      • --tls-min-v1.3
      • \n
      • --trace-deprecation
      • \n
      • --trace-event-categories
      • \n
      • --trace-event-file-pattern
      • \n
      • --trace-events-enabled
      • \n
      • --trace-exit
      • \n
      • --trace-sigint
      • \n
      • --trace-sync-io
      • \n
      • --trace-tls
      • \n
      • --trace-uncaught
      • \n
      • --trace-warnings
      • \n
      • --track-heap-objects
      • \n
      • --unhandled-rejections
      • \n
      • --use-bundled-ca
      • \n
      • --use-largepages
      • \n
      • --use-openssl-ca
      • \n
      • --v8-pool-size
      • \n
      • --zero-fill-buffers\n\n
      • \n
      \n

      V8 options that are allowed are:

      \n\n
        \n
      • --abort-on-uncaught-exception
      • \n
      • --disallow-code-generation-from-strings
      • \n
      • --huge-max-old-generation-size
      • \n
      • --interpreted-frames-native-stack
      • \n
      • --jitless
      • \n
      • --max-old-space-size
      • \n
      • --perf-basic-prof-only-functions
      • \n
      • --perf-basic-prof
      • \n
      • --perf-prof-unwinding-info
      • \n
      • --perf-prof
      • \n
      • --stack-trace-limit\n\n
      • \n
      \n

      --perf-basic-prof-only-functions, --perf-basic-prof,\n--perf-prof-unwinding-info, and --perf-prof are only available on Linux.

      ", + "type": "module", + "displayName": "`NODE_OPTIONS=options...`" + }, + { + "textRaw": "`NODE_PATH=path[:…]`", + "name": "`node_path=path[:…]`", + "meta": { + "added": [ + "v0.1.32" + ], + "changes": [] + }, + "desc": "

      ':'-separated list of directories prefixed to the module search path.

      \n

      On Windows, this is a ';'-separated list instead.

      ", + "type": "module", + "displayName": "`NODE_PATH=path[:…]`" + }, + { + "textRaw": "`NODE_PENDING_DEPRECATION=1`", + "name": "`node_pending_deprecation=1`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      When set to 1, emit pending deprecation warnings.

      \n

      Pending deprecations are generally identical to a runtime deprecation with the\nnotable exception that they are turned off by default and will not be emitted\nunless either the --pending-deprecation command line flag, or the\nNODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations\nare used to provide a kind of selective \"early warning\" mechanism that\ndevelopers may leverage to detect deprecated API usage.

      ", + "type": "module", + "displayName": "`NODE_PENDING_DEPRECATION=1`" + }, + { + "textRaw": "`NODE_PENDING_PIPE_INSTANCES=instances`", + "name": "`node_pending_pipe_instances=instances`", + "desc": "

      Set the number of pending pipe instance handles when the pipe server is waiting\nfor connections. This setting applies to Windows only.

      ", + "type": "module", + "displayName": "`NODE_PENDING_PIPE_INSTANCES=instances`" + }, + { + "textRaw": "`NODE_PRESERVE_SYMLINKS=1`", + "name": "`node_preserve_symlinks=1`", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [] + }, + "desc": "

      When set to 1, instructs the module loader to preserve symbolic links when\nresolving and caching modules.

      ", + "type": "module", + "displayName": "`NODE_PRESERVE_SYMLINKS=1`" + }, + { + "textRaw": "`NODE_REDIRECT_WARNINGS=file`", + "name": "`node_redirect_warnings=file`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      When set, process warnings will be emitted to the given file instead of\nprinting to stderr. The file will be created if it does not exist, and will be\nappended to if it does. If an error occurs while attempting to write the\nwarning to the file, the warning will be written to stderr instead. This is\nequivalent to using the --redirect-warnings=file command-line flag.

      ", + "type": "module", + "displayName": "`NODE_REDIRECT_WARNINGS=file`" + }, + { + "textRaw": "`NODE_REPL_HISTORY=file`", + "name": "`node_repl_history=file`", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "desc": "

      Path to the file used to store the persistent REPL history. The default path is\n~/.node_repl_history, which is overridden by this variable. Setting the value\nto an empty string ('' or ' ') disables persistent REPL history.

      ", + "type": "module", + "displayName": "`NODE_REPL_HISTORY=file`" + }, + { + "textRaw": "`NODE_REPL_EXTERNAL_MODULE=file`", + "name": "`node_repl_external_module=file`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Path to a Node.js module which will be loaded in place of the built-in REPL.\nOverriding this value to an empty string ('') will use the built-in REPL.

      ", + "type": "module", + "displayName": "`NODE_REPL_EXTERNAL_MODULE=file`" + }, + { + "textRaw": "`NODE_TLS_REJECT_UNAUTHORIZED=value`", + "name": "`node_tls_reject_unauthorized=value`", + "desc": "

      If value equals '0', certificate validation is disabled for TLS connections.\nThis makes TLS, and HTTPS by extension, insecure. The use of this environment\nvariable is strongly discouraged.

      ", + "type": "module", + "displayName": "`NODE_TLS_REJECT_UNAUTHORIZED=value`" + }, + { + "textRaw": "`NODE_V8_COVERAGE=dir`", + "name": "`node_v8_coverage=dir`", + "desc": "

      When set, Node.js will begin outputting V8 JavaScript code coverage and\nSource Map data to the directory provided as an argument (coverage\ninformation is written as JSON to files with a coverage prefix).

      \n

      NODE_V8_COVERAGE will automatically propagate to subprocesses, making it\neasier to instrument applications that call the child_process.spawn() family\nof functions. NODE_V8_COVERAGE can be set to an empty string, to prevent\npropagation.

      ", + "modules": [ + { + "textRaw": "Coverage output", + "name": "coverage_output", + "desc": "

      Coverage is output as an array of ScriptCoverage objects on the top-level\nkey result:

      \n
      {\n  \"result\": [\n    {\n      \"scriptId\": \"67\",\n      \"url\": \"internal/tty.js\",\n      \"functions\": []\n    }\n  ]\n}\n
      ", + "type": "module", + "displayName": "Coverage output" + }, + { + "textRaw": "Source map cache", + "name": "source_map_cache", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      If found, source map data is appended to the top-level key source-map-cache\non the JSON coverage object.

      \n

      source-map-cache is an object with keys representing the files source maps\nwere extracted from, and values which include the raw source-map URL\n(in the key url), the parsed Source Map v3 information (in the key data),\nand the line lengths of the source file (in the key lineLengths).

      \n
      {\n  \"result\": [\n    {\n      \"scriptId\": \"68\",\n      \"url\": \"file:///absolute/path/to/source.js\",\n      \"functions\": []\n    }\n  ],\n  \"source-map-cache\": {\n    \"file:///absolute/path/to/source.js\": {\n      \"url\": \"./path-to-map.json\",\n      \"data\": {\n        \"version\": 3,\n        \"sources\": [\n          \"file:///absolute/path/to/original.js\"\n        ],\n        \"names\": [\n          \"Foo\",\n          \"console\",\n          \"info\"\n        ],\n        \"mappings\": \"MAAMA,IACJC,YAAaC\",\n        \"sourceRoot\": \"./\"\n      },\n      \"lineLengths\": [\n        13,\n        62,\n        38,\n        27\n      ]\n    }\n  }\n}\n
      ", + "type": "module", + "displayName": "Source map cache" + } + ], + "type": "module", + "displayName": "`NODE_V8_COVERAGE=dir`" + }, + { + "textRaw": "`OPENSSL_CONF=file`", + "name": "`openssl_conf=file`", + "meta": { + "added": [ + "v6.11.0" + ], + "changes": [] + }, + "desc": "

      Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built with ./configure --openssl-fips.

      \n

      If the --openssl-config command line option is used, the environment\nvariable is ignored.

      ", + "type": "module", + "displayName": "`OPENSSL_CONF=file`" + }, + { + "textRaw": "`SSL_CERT_DIR=dir`", + "name": "`ssl_cert_dir=dir`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory\ncontaining trusted certificates.

      \n

      Be aware that unless the child environment is explicitly set, this environment\nvariable will be inherited by any child processes, and if they use OpenSSL, it\nmay cause them to trust the same CAs as node.

      ", + "type": "module", + "displayName": "`SSL_CERT_DIR=dir`" + }, + { + "textRaw": "`SSL_CERT_FILE=file`", + "name": "`ssl_cert_file=file`", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "desc": "

      If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file\ncontaining trusted certificates.

      \n

      Be aware that unless the child environment is explicitly set, this environment\nvariable will be inherited by any child processes, and if they use OpenSSL, it\nmay cause them to trust the same CAs as node.

      ", + "type": "module", + "displayName": "`SSL_CERT_FILE=file`" + }, + { + "textRaw": "`UV_THREADPOOL_SIZE=size`", + "name": "`uv_threadpool_size=size`", + "desc": "

      Set the number of threads used in libuv's threadpool to size threads.

      \n

      Asynchronous system APIs are used by Node.js whenever possible, but where they\ndo not exist, libuv's threadpool is used to create asynchronous node APIs based\non synchronous system APIs. Node.js APIs that use the threadpool are:

      \n
        \n
      • all fs APIs, other than the file watcher APIs and those that are explicitly\nsynchronous
      • \n
      • asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(),\ncrypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
      • \n
      • dns.lookup()
      • \n
      • all zlib APIs, other than those that are explicitly synchronous
      • \n
      \n

      Because libuv's threadpool has a fixed size, it means that if for whatever\nreason any of these APIs takes a long time, other (seemingly unrelated) APIs\nthat run in libuv's threadpool will experience degraded performance. In order to\nmitigate this issue, one potential solution is to increase the size of libuv's\nthreadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value\ngreater than 4 (its current default value). For more information, see the\nlibuv threadpool documentation.

      ", + "type": "module", + "displayName": "`UV_THREADPOOL_SIZE=size`" + } + ], + "type": "misc", + "displayName": "Environment variables" + }, + { + "textRaw": "Useful V8 options", + "name": "useful_v8_options", + "desc": "

      V8 has its own set of CLI options. Any V8 CLI option that is provided to node\nwill be passed on to V8 to handle. V8's options have no stability guarantee.\nThe V8 team themselves don't consider them to be part of their formal API,\nand reserve the right to change them at any time. Likewise, they are not\ncovered by the Node.js stability guarantees. Many of the V8\noptions are of interest only to V8 developers. Despite this, there is a small\nset of V8 options that are widely applicable to Node.js, and they are\ndocumented here:

      ", + "modules": [ + { + "textRaw": "`--max-old-space-size=SIZE` (in megabytes)", + "name": "`--max-old-space-size=size`_(in_megabytes)", + "desc": "

      Sets the max memory size of V8's old memory section. As memory\nconsumption approaches the limit, V8 will spend more time on\ngarbage collection in an effort to free unused memory.

      \n

      On a machine with 2GB of memory, consider setting this to\n1536 (1.5GB) to leave some memory for other uses and avoid swapping.

      \n
      $ node --max-old-space-size=1536 index.js\n
      ", + "type": "module", + "displayName": "`--max-old-space-size=SIZE` (in megabytes)" + } + ], + "type": "misc", + "displayName": "Useful V8 options" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/cli.md b/doc/api/cli.md index e6d49feef624c062a29767a266bc6694e95759a5..86635f267b383d1287140c6eed618d9b5607e89d 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -383,6 +383,10 @@ Specify the file name of the heap profile generated by `--heap-prof`. ### `--http-parser=library` Chooses an HTTP parser library. Available values are: @@ -392,6 +396,8 @@ Chooses an HTTP parser library. Available values are: The default is `llhttp`, unless otherwise specified when building Node.js. +The `legacy` HTTP parser is deprecated and will emit a deprecation warning. + This flag exists to aid in experimentation with the internal implementation of the Node.js http parser. This flag is likely to become a no-op and removed at some point in the future. diff --git a/doc/api/cluster.html b/doc/api/cluster.html new file mode 100644 index 0000000000000000000000000000000000000000..4cfc08f4d4f13fb2ba6dec2121f6c42333896887 --- /dev/null +++ b/doc/api/cluster.html @@ -0,0 +1,915 @@ + + + + + + + Cluster | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Cluster#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/cluster.js

      +

      A single instance of Node.js runs in a single thread. To take advantage of +multi-core systems, the user will sometimes want to launch a cluster of Node.js +processes to handle the load.

      +

      The cluster module allows easy creation of child processes that all share +server ports.

      +
      const cluster = require('cluster');
      +const http = require('http');
      +const numCPUs = require('os').cpus().length;
      +
      +if (cluster.isMaster) {
      +  console.log(`Master ${process.pid} is running`);
      +
      +  // Fork workers.
      +  for (let i = 0; i < numCPUs; i++) {
      +    cluster.fork();
      +  }
      +
      +  cluster.on('exit', (worker, code, signal) => {
      +    console.log(`worker ${worker.process.pid} died`);
      +  });
      +} else {
      +  // Workers can share any TCP connection
      +  // In this case it is an HTTP server
      +  http.createServer((req, res) => {
      +    res.writeHead(200);
      +    res.end('hello world\n');
      +  }).listen(8000);
      +
      +  console.log(`Worker ${process.pid} started`);
      +}
      +

      Running Node.js will now share port 8000 between the workers:

      +
      $ node server.js
      +Master 3596 is running
      +Worker 4324 started
      +Worker 4520 started
      +Worker 6056 started
      +Worker 5644 started
      +

      On Windows, it is not yet possible to set up a named pipe server in a worker.

      +

      How it works#

      + +

      The worker processes are spawned using the child_process.fork() method, +so that they can communicate with the parent via IPC and pass server +handles back and forth.

      +

      The cluster module supports two methods of distributing incoming +connections.

      +

      The first one (and the default one on all platforms except Windows), +is the round-robin approach, where the master process listens on a +port, accepts new connections and distributes them across the workers +in a round-robin fashion, with some built-in smarts to avoid +overloading a worker process.

      +

      The second approach is where the master process creates the listen +socket and sends it to interested workers. The workers then accept +incoming connections directly.

      +

      The second approach should, in theory, give the best performance. +In practice however, distribution tends to be very unbalanced due +to operating system scheduler vagaries. Loads have been observed +where over 70% of all connections ended up in just two processes, +out of a total of eight.

      +

      Because server.listen() hands off most of the work to the master +process, there are three cases where the behavior between a normal +Node.js process and a cluster worker differs:

      +
        +
      1. server.listen({fd: 7}) Because the message is passed to the master, +file descriptor 7 in the parent will be listened on, and the +handle passed to the worker, rather than listening to the worker's +idea of what the number 7 file descriptor references.
      2. +
      3. server.listen(handle) Listening on handles explicitly will cause +the worker to use the supplied handle, rather than talk to the master +process.
      4. +
      5. server.listen(0) Normally, this will cause servers to listen on a +random port. However, in a cluster, each worker will receive the +same "random" port each time they do listen(0). In essence, the +port is random the first time, but predictable thereafter. To listen +on a unique port, generate a port number based on the cluster worker ID.
      6. +
      +

      Node.js does not provide routing logic. It is, therefore important to design an +application such that it does not rely too heavily on in-memory data objects for +things like sessions and login.

      +

      Because workers are all separate processes, they can be killed or +re-spawned depending on a program's needs, without affecting other +workers. As long as there are some workers still alive, the server will +continue to accept connections. If no workers are alive, existing connections +will be dropped and new connections will be refused. Node.js does not +automatically manage the number of workers, however. It is the application's +responsibility to manage the worker pool based on its own needs.

      +

      Although a primary use case for the cluster module is networking, it can +also be used for other use cases requiring worker processes.

      +

      Class: Worker#

      + + +

      A Worker object contains all public information and method about a worker. +In the master it can be obtained using cluster.workers. In a worker +it can be obtained using cluster.worker.

      +

      Event: 'disconnect'#

      + +

      Similar to the cluster.on('disconnect') event, but specific to this worker.

      +
      cluster.fork().on('disconnect', () => {
      +  // Worker has disconnected
      +});
      +

      Event: 'error'#

      + +

      This event is the same as the one provided by child_process.fork().

      +

      Within a worker, process.on('error') may also be used.

      +

      Event: 'exit'#

      + +
        +
      • code <number> The exit code, if it exited normally.
      • +
      • signal <string> The name of the signal (e.g. 'SIGHUP') that caused +the process to be killed.
      • +
      +

      Similar to the cluster.on('exit') event, but specific to this worker.

      +
      const worker = cluster.fork();
      +worker.on('exit', (code, signal) => {
      +  if (signal) {
      +    console.log(`worker was killed by signal: ${signal}`);
      +  } else if (code !== 0) {
      +    console.log(`worker exited with error code: ${code}`);
      +  } else {
      +    console.log('worker success!');
      +  }
      +});
      +

      Event: 'listening'#

      + + +

      Similar to the cluster.on('listening') event, but specific to this worker.

      +
      cluster.fork().on('listening', (address) => {
      +  // Worker is listening
      +});
      +

      It is not emitted in the worker.

      +

      Event: 'message'#

      + + +

      Similar to the 'message' event of cluster, but specific to this worker.

      +

      Within a worker, process.on('message') may also be used.

      +

      See process event: 'message'.

      +

      Here is an example using the message system. It keeps a count in the master +process of the number of HTTP requests received by the workers:

      +
      const cluster = require('cluster');
      +const http = require('http');
      +
      +if (cluster.isMaster) {
      +
      +  // Keep track of http requests
      +  let numReqs = 0;
      +  setInterval(() => {
      +    console.log(`numReqs = ${numReqs}`);
      +  }, 1000);
      +
      +  // Count requests
      +  function messageHandler(msg) {
      +    if (msg.cmd && msg.cmd === 'notifyRequest') {
      +      numReqs += 1;
      +    }
      +  }
      +
      +  // Start workers and listen for messages containing notifyRequest
      +  const numCPUs = require('os').cpus().length;
      +  for (let i = 0; i < numCPUs; i++) {
      +    cluster.fork();
      +  }
      +
      +  for (const id in cluster.workers) {
      +    cluster.workers[id].on('message', messageHandler);
      +  }
      +
      +} else {
      +
      +  // Worker processes have a http server.
      +  http.Server((req, res) => {
      +    res.writeHead(200);
      +    res.end('hello world\n');
      +
      +    // Notify master about the request
      +    process.send({ cmd: 'notifyRequest' });
      +  }).listen(8000);
      +}
      +

      Event: 'online'#

      + +

      Similar to the cluster.on('online') event, but specific to this worker.

      +
      cluster.fork().on('online', () => {
      +  // Worker is online
      +});
      +

      It is not emitted in the worker.

      +

      worker.disconnect()#

      + + +

      In a worker, this function will close all servers, wait for the 'close' event +on those servers, and then disconnect the IPC channel.

      +

      In the master, an internal message is sent to the worker causing it to call +.disconnect() on itself.

      +

      Causes .exitedAfterDisconnect to be set.

      +

      After a server is closed, it will no longer accept new connections, +but connections may be accepted by any other listening worker. Existing +connections will be allowed to close as usual. When no more connections exist, +see server.close(), the IPC channel to the worker will close allowing it +to die gracefully.

      +

      The above applies only to server connections, client connections are not +automatically closed by workers, and disconnect does not wait for them to close +before exiting.

      +

      In a worker, process.disconnect exists, but it is not this function; +it is disconnect().

      +

      Because long living server connections may block workers from disconnecting, it +may be useful to send a message, so application specific actions may be taken to +close them. It also may be useful to implement a timeout, killing a worker if +the 'disconnect' event has not been emitted after some time.

      +
      if (cluster.isMaster) {
      +  const worker = cluster.fork();
      +  let timeout;
      +
      +  worker.on('listening', (address) => {
      +    worker.send('shutdown');
      +    worker.disconnect();
      +    timeout = setTimeout(() => {
      +      worker.kill();
      +    }, 2000);
      +  });
      +
      +  worker.on('disconnect', () => {
      +    clearTimeout(timeout);
      +  });
      +
      +} else if (cluster.isWorker) {
      +  const net = require('net');
      +  const server = net.createServer((socket) => {
      +    // Connections never end
      +  });
      +
      +  server.listen(8000);
      +
      +  process.on('message', (msg) => {
      +    if (msg === 'shutdown') {
      +      // Initiate graceful close of any connections to server
      +    }
      +  });
      +}
      +

      worker.exitedAfterDisconnect#

      + + +

      This property is true if the worker exited due to .kill() or +.disconnect(). If the worker exited any other way, it is false. If the +worker has not exited, it is undefined.

      +

      The boolean worker.exitedAfterDisconnect allows distinguishing between +voluntary and accidental exit, the master may choose not to respawn a worker +based on this value.

      +
      cluster.on('exit', (worker, code, signal) => {
      +  if (worker.exitedAfterDisconnect === true) {
      +    console.log('Oh, it was just voluntary – no need to worry');
      +  }
      +});
      +
      +// kill worker
      +worker.kill();
      +

      worker.id#

      + + +

      Each new worker is given its own unique id, this id is stored in the +id.

      +

      While a worker is alive, this is the key that indexes it in +cluster.workers.

      +

      worker.isConnected()#

      + +

      This function returns true if the worker is connected to its master via its +IPC channel, false otherwise. A worker is connected to its master after it +has been created. It is disconnected after the 'disconnect' event is emitted.

      +

      worker.isDead()#

      + +

      This function returns true if the worker's process has terminated (either +because of exiting or being signaled). Otherwise, it returns false.

      +
      const cluster = require('cluster');
      +const http = require('http');
      +const numCPUs = require('os').cpus().length;
      +
      +if (cluster.isMaster) {
      +  console.log(`Master ${process.pid} is running`);
      +
      +  // Fork workers.
      +  for (let i = 0; i < numCPUs; i++) {
      +    cluster.fork();
      +  }
      +
      +  cluster.on('fork', (worker) => {
      +    console.log('worker is dead:', worker.isDead());
      +  });
      +
      +  cluster.on('exit', (worker, code, signal) => {
      +    console.log('worker is dead:', worker.isDead());
      +  });
      +} else {
      +  // Workers can share any TCP connection. In this case, it is an HTTP server.
      +  http.createServer((req, res) => {
      +    res.writeHead(200);
      +    res.end(`Current process\n ${process.pid}`);
      +    process.kill(process.pid);
      +  }).listen(8000);
      +}
      +

      worker.kill([signal])#

      + +
        +
      • signal <string> Name of the kill signal to send to the worker +process. Default: 'SIGTERM'
      • +
      +

      This function will kill the worker. In the master, it does this by disconnecting +the worker.process, and once disconnected, killing with signal. In the +worker, it does it by disconnecting the channel, and then exiting with code 0.

      +

      Because kill() attempts to gracefully disconnect the worker process, it is +susceptible to waiting indefinitely for the disconnect to complete. For example, +if the worker enters an infinite loop, a graceful disconnect will never occur. +If the graceful disconnect behavior is not needed, use worker.process.kill().

      +

      Causes .exitedAfterDisconnect to be set.

      +

      This method is aliased as worker.destroy() for backward compatibility.

      +

      In a worker, process.kill() exists, but it is not this function; +it is kill().

      +

      worker.process#

      + + +

      All workers are created using child_process.fork(), the returned object +from this function is stored as .process. In a worker, the global process +is stored.

      +

      See: Child Process module.

      +

      Workers will call process.exit(0) if the 'disconnect' event occurs +on process and .exitedAfterDisconnect is not true. This protects against +accidental disconnection.

      +

      worker.send(message[, sendHandle[, options]][, callback])#

      + +
        +
      • message <Object>
      • +
      • sendHandle <Handle>
      • +
      • options <Object> The options argument, if present, is an object used to +parameterize the sending of certain types of handles. options supports +the following properties: +
          +
        • keepOpen <boolean> A value that can be used when passing instances of +net.Socket. When true, the socket is kept open in the sending process. +Default: false.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <boolean>
      • +
      +

      Send a message to a worker or master, optionally with a handle.

      +

      In the master this sends a message to a specific worker. It is identical to +ChildProcess.send().

      +

      In a worker this sends a message to the master. It is identical to +process.send().

      +

      This example will echo back all messages from the master:

      +
      if (cluster.isMaster) {
      +  const worker = cluster.fork();
      +  worker.send('hi there');
      +
      +} else if (cluster.isWorker) {
      +  process.on('message', (msg) => {
      +    process.send(msg);
      +  });
      +}
      +

      Event: 'disconnect'#

      + + +

      Emitted after the worker IPC channel has disconnected. This can occur when a +worker exits gracefully, is killed, or is disconnected manually (such as with +worker.disconnect()).

      +

      There may be a delay between the 'disconnect' and 'exit' events. These +events can be used to detect if the process is stuck in a cleanup or if there +are long-living connections.

      +
      cluster.on('disconnect', (worker) => {
      +  console.log(`The worker #${worker.id} has disconnected`);
      +});
      +

      Event: 'exit'#

      + +
        +
      • worker <cluster.Worker>
      • +
      • code <number> The exit code, if it exited normally.
      • +
      • signal <string> The name of the signal (e.g. 'SIGHUP') that caused +the process to be killed.
      • +
      +

      When any of the workers die the cluster module will emit the 'exit' event.

      +

      This can be used to restart the worker by calling .fork() again.

      +
      cluster.on('exit', (worker, code, signal) => {
      +  console.log('worker %d died (%s). restarting...',
      +              worker.process.pid, signal || code);
      +  cluster.fork();
      +});
      +

      See child_process event: 'exit'.

      +

      Event: 'fork'#

      + + +

      When a new worker is forked the cluster module will emit a 'fork' event. +This can be used to log worker activity, and create a custom timeout.

      +
      const timeouts = [];
      +function errorMsg() {
      +  console.error('Something must be wrong with the connection ...');
      +}
      +
      +cluster.on('fork', (worker) => {
      +  timeouts[worker.id] = setTimeout(errorMsg, 2000);
      +});
      +cluster.on('listening', (worker, address) => {
      +  clearTimeout(timeouts[worker.id]);
      +});
      +cluster.on('exit', (worker, code, signal) => {
      +  clearTimeout(timeouts[worker.id]);
      +  errorMsg();
      +});
      +

      Event: 'listening'#

      + + +

      After calling listen() from a worker, when the 'listening' event is emitted +on the server a 'listening' event will also be emitted on cluster in the +master.

      +

      The event handler is executed with two arguments, the worker contains the +worker object and the address object contains the following connection +properties: address, port and addressType. This is very useful if the +worker is listening on more than one address.

      +
      cluster.on('listening', (worker, address) => {
      +  console.log(
      +    `A worker is now connected to ${address.address}:${address.port}`);
      +});
      +

      The addressType is one of:

      +
        +
      • 4 (TCPv4)
      • +
      • 6 (TCPv6)
      • +
      • -1 (Unix domain socket)
      • +
      • 'udp4' or 'udp6' (UDP v4 or v6)
      • +
      +

      Event: 'message'#

      + + +

      Emitted when the cluster master receives a message from any worker.

      +

      See child_process event: 'message'.

      +

      Event: 'online'#

      + + +

      After forking a new worker, the worker should respond with an online message. +When the master receives an online message it will emit this event. +The difference between 'fork' and 'online' is that fork is emitted when the +master forks a worker, and 'online' is emitted when the worker is running.

      +
      cluster.on('online', (worker) => {
      +  console.log('Yay, the worker responded after it was forked');
      +});
      +

      Event: 'setup'#

      + + +

      Emitted every time .setupMaster() is called.

      +

      The settings object is the cluster.settings object at the time +.setupMaster() was called and is advisory only, since multiple calls to +.setupMaster() can be made in a single tick.

      +

      If accuracy is important, use cluster.settings.

      +

      cluster.disconnect([callback])#

      + +
        +
      • callback <Function> Called when all workers are disconnected and handles are +closed.
      • +
      +

      Calls .disconnect() on each worker in cluster.workers.

      +

      When they are disconnected all internal handles will be closed, allowing the +master process to die gracefully if no other event is waiting.

      +

      The method takes an optional callback argument which will be called when +finished.

      +

      This can only be called from the master process.

      +

      cluster.fork([env])#

      + + +

      Spawn a new worker process.

      +

      This can only be called from the master process.

      +

      cluster.isMaster#

      + + +

      True if the process is a master. This is determined +by the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is +undefined, then isMaster is true.

      +

      cluster.isWorker#

      + + +

      True if the process is not a master (it is the negation of cluster.isMaster).

      +

      cluster.schedulingPolicy#

      + +

      The scheduling policy, either cluster.SCHED_RR for round-robin or +cluster.SCHED_NONE to leave it to the operating system. This is a +global setting and effectively frozen once either the first worker is spawned, +or .setupMaster() is called, whichever comes first.

      +

      SCHED_RR is the default on all operating systems except Windows. +Windows will change to SCHED_RR once libuv is able to effectively +distribute IOCP handles without incurring a large performance hit.

      +

      cluster.schedulingPolicy can also be set through the +NODE_CLUSTER_SCHED_POLICY environment variable. Valid +values are 'rr' and 'none'.

      +

      cluster.settings#

      + +
        +
      • <Object> +
          +
        • execArgv <string[]> List of string arguments passed to the Node.js +executable. Default: process.execArgv.
        • +
        • exec <string> File path to worker file. Default: process.argv[1].
        • +
        • args <string[]> String arguments passed to worker. +Default: process.argv.slice(2).
        • +
        • cwd <string> Current working directory of the worker process. Default: +undefined (inherits from parent process).
        • +
        • serialization <string> Specify the kind of serialization used for sending +messages between processes. Possible values are 'json' and 'advanced'. +See Advanced serialization for child_process for more details. +Default: false.
        • +
        • silent <boolean> Whether or not to send output to parent's stdio. +Default: false.
        • +
        • stdio <Array> Configures the stdio of forked processes. Because the +cluster module relies on IPC to function, this configuration must contain an +'ipc' entry. When this option is provided, it overrides silent.
        • +
        • uid <number> Sets the user identity of the process. (See setuid(2).)
        • +
        • gid <number> Sets the group identity of the process. (See setgid(2).)
        • +
        • inspectPort <number> | <Function> Sets inspector port of worker. +This can be a number, or a function that takes no arguments and returns a +number. By default each worker gets its own port, incremented from the +master's process.debugPort.
        • +
        • windowsHide <boolean> Hide the forked processes console window that would +normally be created on Windows systems. Default: false.
        • +
        +
      • +
      +

      After calling .setupMaster() (or .fork()) this settings object will +contain the settings, including the default values.

      +

      This object is not intended to be changed or set manually.

      +

      cluster.setupMaster([settings])#

      + + +

      setupMaster is used to change the default 'fork' behavior. Once called, +the settings will be present in cluster.settings.

      +

      Any settings changes only affect future calls to .fork() and have no +effect on workers that are already running.

      +

      The only attribute of a worker that cannot be set via .setupMaster() is +the env passed to .fork().

      +

      The defaults above apply to the first call only; the defaults for later +calls are the current values at the time of cluster.setupMaster() is called.

      +
      const cluster = require('cluster');
      +cluster.setupMaster({
      +  exec: 'worker.js',
      +  args: ['--use', 'https'],
      +  silent: true
      +});
      +cluster.fork(); // https worker
      +cluster.setupMaster({
      +  exec: 'worker.js',
      +  args: ['--use', 'http']
      +});
      +cluster.fork(); // http worker
      +

      This can only be called from the master process.

      +

      cluster.worker#

      + + +

      A reference to the current worker object. Not available in the master process.

      +
      const cluster = require('cluster');
      +
      +if (cluster.isMaster) {
      +  console.log('I am master');
      +  cluster.fork();
      +  cluster.fork();
      +} else if (cluster.isWorker) {
      +  console.log(`I am worker #${cluster.worker.id}`);
      +}
      +

      cluster.workers#

      + + +

      A hash that stores the active worker objects, keyed by id field. Makes it +easy to loop through all the workers. It is only available in the master +process.

      +

      A worker is removed from cluster.workers after the worker has disconnected +and exited. The order between these two events cannot be determined in +advance. However, it is guaranteed that the removal from the cluster.workers +list happens before last 'disconnect' or 'exit' event is emitted.

      +
      // Go through all workers
      +function eachWorker(callback) {
      +  for (const id in cluster.workers) {
      +    callback(cluster.workers[id]);
      +  }
      +}
      +eachWorker((worker) => {
      +  worker.send('big announcement to all workers');
      +});
      +

      Using the worker's unique id is the easiest way to locate the worker.

      +
      socket.on('data', (id) => {
      +  const worker = cluster.workers[id];
      +});
      + +
      +
      +
      + + diff --git a/doc/api/cluster.json b/doc/api/cluster.json new file mode 100644 index 0000000000000000000000000000000000000000..03fb922476a2673abd340e9e9c9195383b32ab6c --- /dev/null +++ b/doc/api/cluster.json @@ -0,0 +1,761 @@ +{ + "type": "module", + "source": "doc/api/cluster.md", + "modules": [ + { + "textRaw": "Cluster", + "name": "cluster", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/cluster.js

      \n

      A single instance of Node.js runs in a single thread. To take advantage of\nmulti-core systems, the user will sometimes want to launch a cluster of Node.js\nprocesses to handle the load.

      \n

      The cluster module allows easy creation of child processes that all share\nserver ports.

      \n
      const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', (worker, code, signal) => {\n    console.log(`worker ${worker.process.pid} died`);\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case it is an HTTP server\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end('hello world\\n');\n  }).listen(8000);\n\n  console.log(`Worker ${process.pid} started`);\n}\n
      \n

      Running Node.js will now share port 8000 between the workers:

      \n
      $ node server.js\nMaster 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n
      \n

      On Windows, it is not yet possible to set up a named pipe server in a worker.

      ", + "miscs": [ + { + "textRaw": "How it works", + "name": "How it works", + "type": "misc", + "desc": "

      The worker processes are spawned using the child_process.fork() method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.

      \n

      The cluster module supports two methods of distributing incoming\nconnections.

      \n

      The first one (and the default one on all platforms except Windows),\nis the round-robin approach, where the master process listens on a\nport, accepts new connections and distributes them across the workers\nin a round-robin fashion, with some built-in smarts to avoid\noverloading a worker process.

      \n

      The second approach is where the master process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.

      \n

      The second approach should, in theory, give the best performance.\nIn practice however, distribution tends to be very unbalanced due\nto operating system scheduler vagaries. Loads have been observed\nwhere over 70% of all connections ended up in just two processes,\nout of a total of eight.

      \n

      Because server.listen() hands off most of the work to the master\nprocess, there are three cases where the behavior between a normal\nNode.js process and a cluster worker differs:

      \n
        \n
      1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
      2. \n
      3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess.
      4. \n
      5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame \"random\" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. To listen\non a unique port, generate a port number based on the cluster worker ID.
      6. \n
      \n

      Node.js does not provide routing logic. It is, therefore important to design an\napplication such that it does not rely too heavily on in-memory data objects for\nthings like sessions and login.

      \n

      Because workers are all separate processes, they can be killed or\nre-spawned depending on a program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. If no workers are alive, existing connections\nwill be dropped and new connections will be refused. Node.js does not\nautomatically manage the number of workers, however. It is the application's\nresponsibility to manage the worker pool based on its own needs.

      \n

      Although a primary use case for the cluster module is networking, it can\nalso be used for other use cases requiring worker processes.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `Worker`", + "type": "class", + "name": "Worker", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "\n

      A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.

      ", + "events": [ + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      Similar to the cluster.on('disconnect') event, but specific to this worker.

      \n
      cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n
      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.7.3" + ], + "changes": [] + }, + "params": [], + "desc": "

      This event is the same as the one provided by child_process.fork().

      \n

      Within a worker, process.on('error') may also be used.

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {number} The exit code, if it exited normally.", + "name": "code", + "type": "number", + "desc": "The exit code, if it exited normally." + }, + { + "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.", + "name": "signal", + "type": "string", + "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed." + } + ], + "desc": "

      Similar to the cluster.on('exit') event, but specific to this worker.

      \n
      const worker = cluster.fork();\nworker.on('exit', (code, signal) => {\n  if (signal) {\n    console.log(`worker was killed by signal: ${signal}`);\n  } else if (code !== 0) {\n    console.log(`worker exited with error code: ${code}`);\n  } else {\n    console.log('worker success!');\n  }\n});\n
      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`address` {Object}", + "name": "address", + "type": "Object" + } + ], + "desc": "

      Similar to the cluster.on('listening') event, but specific to this worker.

      \n
      cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n
      \n

      It is not emitted in the worker.

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`handle` {undefined|Object}", + "name": "handle", + "type": "undefined|Object" + } + ], + "desc": "

      Similar to the 'message' event of cluster, but specific to this worker.

      \n

      Within a worker, process.on('message') may also be used.

      \n

      See process event: 'message'.

      \n

      Here is an example using the message system. It keeps a count in the master\nprocess of the number of HTTP requests received by the workers:

      \n
      const cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  let numReqs = 0;\n  setInterval(() => {\n    console.log(`numReqs = ${numReqs}`);\n  }, 1000);\n\n  // Count requests\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd === 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  const numCPUs = require('os').cpus().length;\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  for (const id in cluster.workers) {\n    cluster.workers[id].on('message', messageHandler);\n  }\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server((req, res) => {\n    res.writeHead(200);\n    res.end('hello world\\n');\n\n    // Notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n
      " + }, + { + "textRaw": "Event: `'online'`", + "type": "event", + "name": "online", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Similar to the cluster.on('online') event, but specific to this worker.

      \n
      cluster.fork().on('online', () => {\n  // Worker is online\n});\n
      \n

      It is not emitted in the worker.

      " + } + ], + "methods": [ + { + "textRaw": "`worker.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v7.3.0", + "pr-url": "https://github.com/nodejs/node/pull/10019", + "description": "This method now returns a reference to `worker`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {cluster.Worker} A reference to `worker`.", + "name": "return", + "type": "cluster.Worker", + "desc": "A reference to `worker`." + }, + "params": [] + } + ], + "desc": "

      In a worker, this function will close all servers, wait for the 'close' event\non those servers, and then disconnect the IPC channel.

      \n

      In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.

      \n

      Causes .exitedAfterDisconnect to be set.

      \n

      After a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker will close allowing it\nto die gracefully.

      \n

      The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.

      \n

      In a worker, process.disconnect exists, but it is not this function;\nit is disconnect().

      \n

      Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe 'disconnect' event has not been emitted after some time.

      \n
      if (cluster.isMaster) {\n  const worker = cluster.fork();\n  let timeout;\n\n  worker.on('listening', (address) => {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(() => {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', () => {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  const net = require('net');\n  const server = net.createServer((socket) => {\n    // Connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', (msg) => {\n    if (msg === 'shutdown') {\n      // Initiate graceful close of any connections to server\n    }\n  });\n}\n
      " + }, + { + "textRaw": "`worker.isConnected()`", + "type": "method", + "name": "isConnected", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This function returns true if the worker is connected to its master via its\nIPC channel, false otherwise. A worker is connected to its master after it\nhas been created. It is disconnected after the 'disconnect' event is emitted.

      " + }, + { + "textRaw": "`worker.isDead()`", + "type": "method", + "name": "isDead", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.

      \n
      const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} is running`);\n\n  // Fork workers.\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('fork', (worker) => {\n    console.log('worker is dead:', worker.isDead());\n  });\n\n  cluster.on('exit', (worker, code, signal) => {\n    console.log('worker is dead:', worker.isDead());\n  });\n} else {\n  // Workers can share any TCP connection. In this case, it is an HTTP server.\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end(`Current process\\n ${process.pid}`);\n    process.kill(process.pid);\n  }).listen(8000);\n}\n
      " + }, + { + "textRaw": "`worker.kill([signal])`", + "type": "method", + "name": "kill", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`signal` {string} Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`", + "name": "signal", + "type": "string", + "desc": "Name of the kill signal to send to the worker process. **Default**: `'SIGTERM'`" + } + ] + } + ], + "desc": "

      This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.

      \n

      Because kill() attempts to gracefully disconnect the worker process, it is\nsusceptible to waiting indefinitely for the disconnect to complete. For example,\nif the worker enters an infinite loop, a graceful disconnect will never occur.\nIf the graceful disconnect behavior is not needed, use worker.process.kill().

      \n

      Causes .exitedAfterDisconnect to be set.

      \n

      This method is aliased as worker.destroy() for backward compatibility.

      \n

      In a worker, process.kill() exists, but it is not this function;\nit is kill().

      " + }, + { + "textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [ + { + "version": "v4.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2620", + "description": "The `callback` parameter is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {Handle}", + "name": "sendHandle", + "type": "Handle" + }, + { + "textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "name": "options", + "type": "Object", + "desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:", + "options": [ + { + "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", + "name": "keepOpen", + "type": "boolean", + "default": "`false`", + "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Send a message to a worker or master, optionally with a handle.

      \n

      In the master this sends a message to a specific worker. It is identical to\nChildProcess.send().

      \n

      In a worker this sends a message to the master. It is identical to\nprocess.send().

      \n

      This example will echo back all messages from the master:

      \n
      if (cluster.isMaster) {\n  const worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', (msg) => {\n    process.send(msg);\n  });\n}\n
      " + } + ], + "properties": [ + { + "textRaw": "`exitedAfterDisconnect` {boolean}", + "type": "boolean", + "name": "exitedAfterDisconnect", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "desc": "

      This property is true if the worker exited due to .kill() or\n.disconnect(). If the worker exited any other way, it is false. If the\nworker has not exited, it is undefined.

      \n

      The boolean worker.exitedAfterDisconnect allows distinguishing between\nvoluntary and accidental exit, the master may choose not to respawn a worker\nbased on this value.

      \n
      cluster.on('exit', (worker, code, signal) => {\n  if (worker.exitedAfterDisconnect === true) {\n    console.log('Oh, it was just voluntary – no need to worry');\n  }\n});\n\n// kill worker\nworker.kill();\n
      " + }, + { + "textRaw": "`id` {number}", + "type": "number", + "name": "id", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      Each new worker is given its own unique id, this id is stored in the\nid.

      \n

      While a worker is alive, this is the key that indexes it in\ncluster.workers.

      " + }, + { + "textRaw": "`process` {ChildProcess}", + "type": "ChildProcess", + "name": "process", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "

      All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.

      \n

      See: Child Process module.

      \n

      Workers will call process.exit(0) if the 'disconnect' event occurs\non process and .exitedAfterDisconnect is not true. This protects against\naccidental disconnection.

      " + } + ] + } + ], + "events": [ + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.9" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + } + ], + "desc": "

      Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).

      \n

      There may be a delay between the 'disconnect' and 'exit' events. These\nevents can be used to detect if the process is stuck in a cleanup or if there\nare long-living connections.

      \n
      cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n
      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.7.9" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + }, + { + "textRaw": "`code` {number} The exit code, if it exited normally.", + "name": "code", + "type": "number", + "desc": "The exit code, if it exited normally." + }, + { + "textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.", + "name": "signal", + "type": "string", + "desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed." + } + ], + "desc": "

      When any of the workers die the cluster module will emit the 'exit' event.

      \n

      This can be used to restart the worker by calling .fork() again.

      \n
      cluster.on('exit', (worker, code, signal) => {\n  console.log('worker %d died (%s). restarting...',\n              worker.process.pid, signal || code);\n  cluster.fork();\n});\n
      \n

      See child_process event: 'exit'.

      " + }, + { + "textRaw": "Event: `'fork'`", + "type": "event", + "name": "fork", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + } + ], + "desc": "

      When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create a custom timeout.

      \n
      const timeouts = [];\nfunction errorMsg() {\n  console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});\n
      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + }, + { + "textRaw": "`address` {Object}", + "name": "address", + "type": "Object" + } + ], + "desc": "

      After calling listen() from a worker, when the 'listening' event is emitted\non the server a 'listening' event will also be emitted on cluster in the\nmaster.

      \n

      The event handler is executed with two arguments, the worker contains the\nworker object and the address object contains the following connection\nproperties: address, port and addressType. This is very useful if the\nworker is listening on more than one address.

      \n
      cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});\n
      \n

      The addressType is one of:

      \n
        \n
      • 4 (TCPv4)
      • \n
      • 6 (TCPv6)
      • \n
      • -1 (Unix domain socket)
      • \n
      • 'udp4' or 'udp6' (UDP v4 or v6)
      • \n
      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v2.5.0" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5361", + "description": "The `worker` parameter is passed now; see below for details." + } + ] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + }, + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`handle` {undefined|Object}", + "name": "handle", + "type": "undefined|Object" + } + ], + "desc": "

      Emitted when the cluster master receives a message from any worker.

      \n

      See child_process event: 'message'.

      " + }, + { + "textRaw": "Event: `'online'`", + "type": "event", + "name": "online", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`worker` {cluster.Worker}", + "name": "worker", + "type": "cluster.Worker" + } + ], + "desc": "

      After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.

      \n
      cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});\n
      " + }, + { + "textRaw": "Event: `'setup'`", + "type": "event", + "name": "setup", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`settings` {Object}", + "name": "settings", + "type": "Object" + } + ], + "desc": "

      Emitted every time .setupMaster() is called.

      \n

      The settings object is the cluster.settings object at the time\n.setupMaster() was called and is advisory only, since multiple calls to\n.setupMaster() can be made in a single tick.

      \n

      If accuracy is important, use cluster.settings.

      " + } + ], + "methods": [ + { + "textRaw": "`cluster.disconnect([callback])`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} Called when all workers are disconnected and handles are closed.", + "name": "callback", + "type": "Function", + "desc": "Called when all workers are disconnected and handles are closed." + } + ] + } + ], + "desc": "

      Calls .disconnect() on each worker in cluster.workers.

      \n

      When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.

      \n

      The method takes an optional callback argument which will be called when\nfinished.

      \n

      This can only be called from the master process.

      " + }, + { + "textRaw": "`cluster.fork([env])`", + "type": "method", + "name": "fork", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {cluster.Worker}", + "name": "return", + "type": "cluster.Worker" + }, + "params": [ + { + "textRaw": "`env` {Object} Key/value pairs to add to worker process environment.", + "name": "env", + "type": "Object", + "desc": "Key/value pairs to add to worker process environment." + } + ] + } + ], + "desc": "

      Spawn a new worker process.

      \n

      This can only be called from the master process.

      " + }, + { + "textRaw": "`cluster.setupMaster([settings])`", + "type": "method", + "name": "setupMaster", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [ + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7838", + "description": "The `stdio` option is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`settings` {Object} See [`cluster.settings`][].", + "name": "settings", + "type": "Object", + "desc": "See [`cluster.settings`][]." + } + ] + } + ], + "desc": "

      setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.

      \n

      Any settings changes only affect future calls to .fork() and have no\neffect on workers that are already running.

      \n

      The only attribute of a worker that cannot be set via .setupMaster() is\nthe env passed to .fork().

      \n

      The defaults above apply to the first call only; the defaults for later\ncalls are the current values at the time of cluster.setupMaster() is called.

      \n
      const cluster = require('cluster');\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true\n});\ncluster.fork(); // https worker\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'http']\n});\ncluster.fork(); // http worker\n
      \n

      This can only be called from the master process.

      " + } + ], + "properties": [ + { + "textRaw": "`isMaster` {boolean}", + "type": "boolean", + "name": "isMaster", + "meta": { + "added": [ + "v0.8.1" + ], + "changes": [] + }, + "desc": "

      True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.

      " + }, + { + "textRaw": "`isWorker` {boolean}", + "type": "boolean", + "name": "isWorker", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "desc": "

      True if the process is not a master (it is the negation of cluster.isMaster).

      " + }, + { + "textRaw": "`cluster.schedulingPolicy`", + "name": "schedulingPolicy", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "desc": "

      The scheduling policy, either cluster.SCHED_RR for round-robin or\ncluster.SCHED_NONE to leave it to the operating system. This is a\nglobal setting and effectively frozen once either the first worker is spawned,\nor .setupMaster() is called, whichever comes first.

      \n

      SCHED_RR is the default on all operating systems except Windows.\nWindows will change to SCHED_RR once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.

      \n

      cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are 'rr' and 'none'.

      " + }, + { + "textRaw": "`settings` {Object}", + "type": "Object", + "name": "settings", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30162", + "description": "The `serialization` option is supported now." + }, + { + "version": "v9.5.0", + "pr-url": "https://github.com/nodejs/node/pull/18399", + "description": "The `cwd` option is supported now." + }, + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/17412", + "description": "The `windowsHide` option is supported now." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/14140", + "description": "The `inspectPort` option is supported now." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7838", + "description": "The `stdio` option is supported now." + } + ] + }, + "options": [ + { + "textRaw": "`execArgv` {string[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`.", + "name": "execArgv", + "type": "string[]", + "default": "`process.execArgv`", + "desc": "List of string arguments passed to the Node.js executable." + }, + { + "textRaw": "`exec` {string} File path to worker file. **Default:** `process.argv[1]`.", + "name": "exec", + "type": "string", + "default": "`process.argv[1]`", + "desc": "File path to worker file." + }, + { + "textRaw": "`args` {string[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`.", + "name": "args", + "type": "string[]", + "default": "`process.argv.slice(2)`", + "desc": "String arguments passed to worker." + }, + { + "textRaw": "`cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process).", + "name": "cwd", + "type": "string", + "default": "`undefined` (inherits from parent process)", + "desc": "Current working directory of the worker process." + }, + { + "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization for `child_process`][] for more details. **Default:** `false`.", + "name": "serialization", + "type": "string", + "default": "`false`", + "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See [Advanced serialization for `child_process`][] for more details." + }, + { + "textRaw": "`silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false`.", + "name": "silent", + "type": "boolean", + "default": "`false`", + "desc": "Whether or not to send output to parent's stdio." + }, + { + "textRaw": "`stdio` {Array} Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`.", + "name": "stdio", + "type": "Array", + "desc": "Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`." + }, + { + "textRaw": "`uid` {number} Sets the user identity of the process. (See setuid(2).)", + "name": "uid", + "type": "number", + "desc": "Sets the user identity of the process. (See setuid(2).)" + }, + { + "textRaw": "`gid` {number} Sets the group identity of the process. (See setgid(2).)", + "name": "gid", + "type": "number", + "desc": "Sets the group identity of the process. (See setgid(2).)" + }, + { + "textRaw": "`inspectPort` {number|Function} Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`.", + "name": "inspectPort", + "type": "number|Function", + "desc": "Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's `process.debugPort`." + }, + { + "textRaw": "`windowsHide` {boolean} Hide the forked processes console window that would normally be created on Windows systems. **Default:** `false`.", + "name": "windowsHide", + "type": "boolean", + "default": "`false`", + "desc": "Hide the forked processes console window that would normally be created on Windows systems." + } + ], + "desc": "

      After calling .setupMaster() (or .fork()) this settings object will\ncontain the settings, including the default values.

      \n

      This object is not intended to be changed or set manually.

      " + }, + { + "textRaw": "`worker` {Object}", + "type": "Object", + "name": "worker", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "

      A reference to the current worker object. Not available in the master process.

      \n
      const cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n
      " + }, + { + "textRaw": "`workers` {Object}", + "type": "Object", + "name": "workers", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "desc": "

      A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.

      \n

      A worker is removed from cluster.workers after the worker has disconnected\nand exited. The order between these two events cannot be determined in\nadvance. However, it is guaranteed that the removal from the cluster.workers\nlist happens before last 'disconnect' or 'exit' event is emitted.

      \n
      // Go through all workers\nfunction eachWorker(callback) {\n  for (const id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\n});\n
      \n

      Using the worker's unique id is the easiest way to locate the worker.

      \n
      socket.on('data', (id) => {\n  const worker = cluster.workers[id];\n});\n
      " + } + ], + "type": "module", + "displayName": "Cluster" + } + ] +} \ No newline at end of file diff --git a/doc/api/console.html b/doc/api/console.html new file mode 100644 index 0000000000000000000000000000000000000000..72c8f5de4223b7c2cd84a67273bc3699cad3af6d --- /dev/null +++ b/doc/api/console.html @@ -0,0 +1,652 @@ + + + + + + + Console | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Console#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/console.js

      +

      The console module provides a simple debugging console that is similar to the +JavaScript console mechanism provided by web browsers.

      +

      The module exports two specific components:

      +
        +
      • A Console class with methods such as console.log(), console.error() and +console.warn() that can be used to write to any Node.js stream.
      • +
      • A global console instance configured to write to process.stdout and +process.stderr. The global console can be used without calling +require('console').
      • +
      +

      Warning: The global console object's methods are neither consistently +synchronous like the browser APIs they resemble, nor are they consistently +asynchronous like all other Node.js streams. See the note on process I/O for +more information.

      +

      Example using the global console:

      +
      console.log('hello world');
      +// Prints: hello world, to stdout
      +console.log('hello %s', 'world');
      +// Prints: hello world, to stdout
      +console.error(new Error('Whoops, something bad happened'));
      +// Prints: [Error: Whoops, something bad happened], to stderr
      +
      +const name = 'Will Robinson';
      +console.warn(`Danger ${name}! Danger!`);
      +// Prints: Danger Will Robinson! Danger!, to stderr
      +

      Example using the Console class:

      +
      const out = getStreamSomehow();
      +const err = getStreamSomehow();
      +const myConsole = new console.Console(out, err);
      +
      +myConsole.log('hello world');
      +// Prints: hello world, to out
      +myConsole.log('hello %s', 'world');
      +// Prints: hello world, to out
      +myConsole.error(new Error('Whoops, something bad happened'));
      +// Prints: [Error: Whoops, something bad happened], to err
      +
      +const name = 'Will Robinson';
      +myConsole.warn(`Danger ${name}! Danger!`);
      +// Prints: Danger Will Robinson! Danger!, to err
      +

      Class: Console#

      + + +

      The Console class can be used to create a simple logger with configurable +output streams and can be accessed using either require('console').Console +or console.Console (or their destructured counterparts):

      +
      const { Console } = require('console');
      +
      const { Console } = console;
      +

      new Console(stdout[, stderr][, ignoreErrors])#

      +

      new Console(options)#

      + +
        +
      • options <Object> +
          +
        • stdout <stream.Writable>
        • +
        • stderr <stream.Writable>
        • +
        • ignoreErrors <boolean> Ignore errors when writing to the underlying +streams. Default: true.
        • +
        • colorMode <boolean> | <string> Set color support for this Console instance. +Setting to true enables coloring while inspecting values. Setting to +false disables coloring while inspecting values. Setting to +'auto' makes color support depend on the value of the isTTY property +and the value returned by getColorDepth() on the respective stream. This +option can not be used, if inspectOptions.colors is set as well. +Default: 'auto'.
        • +
        • inspectOptions <Object> Specifies options that are passed along to +util.inspect().
        • +
        • groupIndentation <number> Set group indentation. +Default: 2.
        • +
        +
      • +
      +

      Creates a new Console with one or two writable stream instances. stdout is a +writable stream to print log or info output. stderr is used for warning or +error output. If stderr is not provided, stdout is used for stderr.

      +
      const output = fs.createWriteStream('./stdout.log');
      +const errorOutput = fs.createWriteStream('./stderr.log');
      +// Custom simple logger
      +const logger = new Console({ stdout: output, stderr: errorOutput });
      +// use it like console
      +const count = 5;
      +logger.log('count: %d', count);
      +// In stdout.log: count 5
      +

      The global console is a special Console whose output is sent to +process.stdout and process.stderr. It is equivalent to calling:

      +
      new Console({ stdout: process.stdout, stderr: process.stderr });
      +

      console.assert(value[, ...message])#

      + +
        +
      • value <any> The value tested for being truthy.
      • +
      • ...message <any> All arguments besides value are used as error message.
      • +
      +

      console.assert() writes a message if value is falsy or omitted. It only +writes a message and does not otherwise affect execution. The output always +starts with "Assertion failed". If provided, message is formatted using +util.format().

      +

      If value is truthy, nothing happens.

      +
      console.assert(true, 'does nothing');
      +
      +console.assert(false, 'Whoops %s work', 'didn\'t');
      +// Assertion failed: Whoops didn't work
      +
      +console.assert();
      +// Assertion failed
      +

      console.clear()#

      + +

      When stdout is a TTY, calling console.clear() will attempt to clear the +TTY. When stdout is not a TTY, this method does nothing.

      +

      The specific operation of console.clear() can vary across operating systems +and terminal types. For most Linux operating systems, console.clear() +operates similarly to the clear shell command. On Windows, console.clear() +will clear only the output in the current terminal viewport for the Node.js +binary.

      +

      console.count([label])#

      + +
        +
      • label <string> The display label for the counter. Default: 'default'.
      • +
      +

      Maintains an internal counter specific to label and outputs to stdout the +number of times console.count() has been called with the given label.

      + +
      > console.count()
      +default: 1
      +undefined
      +> console.count('default')
      +default: 2
      +undefined
      +> console.count('abc')
      +abc: 1
      +undefined
      +> console.count('xyz')
      +xyz: 1
      +undefined
      +> console.count('abc')
      +abc: 2
      +undefined
      +> console.count()
      +default: 3
      +undefined
      +>
      +

      console.countReset([label])#

      + +
        +
      • label <string> The display label for the counter. Default: 'default'.
      • +
      +

      Resets the internal counter specific to label.

      + +
      > console.count('abc');
      +abc: 1
      +undefined
      +> console.countReset('abc');
      +undefined
      +> console.count('abc');
      +abc: 1
      +undefined
      +>
      +

      console.debug(data[, ...args])#

      + + +

      The console.debug() function is an alias for console.log().

      +

      console.dir(obj[, options])#

      + +
        +
      • obj <any>
      • +
      • options <Object> +
          +
        • showHidden <boolean> If true then the object's non-enumerable and symbol +properties will be shown too. Default: false.
        • +
        • depth <number> Tells util.inspect() how many times to recurse while +formatting the object. This is useful for inspecting large complicated +objects. To make it recurse indefinitely, pass null. Default: 2.
        • +
        • colors <boolean> If true, then the output will be styled with ANSI color +codes. Colors are customizable; +see customizing util.inspect() colors. Default: false.
        • +
        +
      • +
      +

      Uses util.inspect() on obj and prints the resulting string to stdout. +This function bypasses any custom inspect() function defined on obj.

      +

      console.dirxml(...data)#

      + + +

      This method calls console.log() passing it the arguments received. +This method does not produce any XML formatting.

      +

      console.error([data][, ...args])#

      + + +

      Prints to stderr with newline. Multiple arguments can be passed, with the +first used as the primary message and all additional used as substitution +values similar to printf(3) (the arguments are all passed to +util.format()).

      +
      const code = 5;
      +console.error('error #%d', code);
      +// Prints: error #5, to stderr
      +console.error('error', code);
      +// Prints: error 5, to stderr
      +

      If formatting elements (e.g. %d) are not found in the first string then +util.inspect() is called on each argument and the resulting string +values are concatenated. See util.format() for more information.

      +

      console.group([...label])#

      + + +

      Increases indentation of subsequent lines by spaces for groupIndentation +length.

      +

      If one or more labels are provided, those are printed first without the +additional indentation.

      +

      console.groupCollapsed()#

      + +

      An alias for console.group().

      +

      console.groupEnd()#

      + +

      Decreases indentation of subsequent lines by spaces for groupIndentation +length.

      +

      console.info([data][, ...args])#

      + + +

      The console.info() function is an alias for console.log().

      +

      console.log([data][, ...args])#

      + + +

      Prints to stdout with newline. Multiple arguments can be passed, with the +first used as the primary message and all additional used as substitution +values similar to printf(3) (the arguments are all passed to +util.format()).

      +
      const count = 5;
      +console.log('count: %d', count);
      +// Prints: count: 5, to stdout
      +console.log('count:', count);
      +// Prints: count: 5, to stdout
      +

      See util.format() for more information.

      +

      console.table(tabularData[, properties])#

      + +
        +
      • tabularData <any>
      • +
      • properties <string[]> Alternate properties for constructing the table.
      • +
      +

      Try to construct a table with the columns of the properties of tabularData +(or use properties) and rows of tabularData and log it. Falls back to just +logging the argument if it can’t be parsed as tabular.

      +
      // These can't be parsed as tabular data
      +console.table(Symbol());
      +// Symbol()
      +
      +console.table(undefined);
      +// undefined
      +
      +console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
      +// ┌─────────┬─────┬─────â”
      +// │ (index) │  a  │  b  │
      +// ├─────────┼─────┼─────┤
      +// │    0    │  1  │ 'Y' │
      +// │    1    │ 'Z' │  2  │
      +// └─────────┴─────┴─────┘
      +
      +console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
      +// ┌─────────┬─────â”
      +// │ (index) │  a  │
      +// ├─────────┼─────┤
      +// │    0    │  1  │
      +// │    1    │ 'Z' │
      +// └─────────┴─────┘
      +

      console.time([label])#

      + + +

      Starts a timer that can be used to compute the duration of an operation. Timers +are identified by a unique label. Use the same label when calling +console.timeEnd() to stop the timer and output the elapsed time in +milliseconds to stdout. Timer durations are accurate to the sub-millisecond.

      +

      console.timeEnd([label])#

      + + +

      Stops a timer that was previously started by calling console.time() and +prints the result to stdout:

      +
      console.time('100-elements');
      +for (let i = 0; i < 100; i++) {}
      +console.timeEnd('100-elements');
      +// prints 100-elements: 225.438ms
      +

      console.timeLog([label][, ...data])#

      + + +

      For a timer that was previously started by calling console.time(), prints +the elapsed time and other data arguments to stdout:

      +
      console.time('process');
      +const value = expensiveProcess1(); // Returns 42
      +console.timeLog('process', value);
      +// Prints "process: 365.227ms 42".
      +doExpensiveProcess2(value);
      +console.timeEnd('process');
      +

      console.trace([message][, ...args])#

      + + +

      Prints to stderr the string 'Trace: ', followed by the util.format() +formatted message and stack trace to the current position in the code.

      +
      console.trace('Show me');
      +// Prints: (stack trace will vary based on where trace is called)
      +//  Trace: Show me
      +//    at repl:2:9
      +//    at REPLServer.defaultEval (repl.js:248:27)
      +//    at bound (domain.js:287:14)
      +//    at REPLServer.runBound [as eval] (domain.js:300:12)
      +//    at REPLServer.<anonymous> (repl.js:412:12)
      +//    at emitOne (events.js:82:20)
      +//    at REPLServer.emit (events.js:169:7)
      +//    at REPLServer.Interface._onLine (readline.js:210:10)
      +//    at REPLServer.Interface._line (readline.js:549:8)
      +//    at REPLServer.Interface._ttyWrite (readline.js:826:14)
      +

      console.warn([data][, ...args])#

      + + +

      The console.warn() function is an alias for console.error().

      +

      Inspector only methods#

      +

      The following methods are exposed by the V8 engine in the general API but do +not display anything unless used in conjunction with the inspector +(--inspect flag).

      +

      console.profile([label])#

      + + +

      This method does not display anything unless used in the inspector. The +console.profile() method starts a JavaScript CPU profile with an optional +label until console.profileEnd() is called. The profile is then added to +the Profile panel of the inspector.

      +
      console.profile('MyLabel');
      +// Some code
      +console.profileEnd('MyLabel');
      +// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
      +

      console.profileEnd([label])#

      + + +

      This method does not display anything unless used in the inspector. Stops the +current JavaScript CPU profiling session if one has been started and prints +the report to the Profiles panel of the inspector. See +console.profile() for an example.

      +

      If this method is called without a label, the most recently started profile is +stopped.

      +

      console.timeStamp([label])#

      + + +

      This method does not display anything unless used in the inspector. The +console.timeStamp() method adds an event with the label 'label' to the +Timeline panel of the inspector.

      + +
      +
      +
      + + diff --git a/doc/api/console.json b/doc/api/console.json new file mode 100644 index 0000000000000000000000000000000000000000..8e2a2c4ffe03e7a59640361d89e72c1688f2b1a2 --- /dev/null +++ b/doc/api/console.json @@ -0,0 +1,741 @@ +{ + "type": "module", + "source": "doc/api/console.md", + "modules": [ + { + "textRaw": "Console", + "name": "console", + "introduced_in": "v0.10.13", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/console.js

      \n

      The console module provides a simple debugging console that is similar to the\nJavaScript console mechanism provided by web browsers.

      \n

      The module exports two specific components:

      \n
        \n
      • A Console class with methods such as console.log(), console.error() and\nconsole.warn() that can be used to write to any Node.js stream.
      • \n
      • A global console instance configured to write to process.stdout and\nprocess.stderr. The global console can be used without calling\nrequire('console').
      • \n
      \n

      Warning: The global console object's methods are neither consistently\nsynchronous like the browser APIs they resemble, nor are they consistently\nasynchronous like all other Node.js streams. See the note on process I/O for\nmore information.

      \n

      Example using the global console:

      \n
      console.log('hello world');\n// Prints: hello world, to stdout\nconsole.log('hello %s', 'world');\n// Prints: hello world, to stdout\nconsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to stderr\n\nconst name = 'Will Robinson';\nconsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to stderr\n
      \n

      Example using the Console class:

      \n
      const out = getStreamSomehow();\nconst err = getStreamSomehow();\nconst myConsole = new console.Console(out, err);\n\nmyConsole.log('hello world');\n// Prints: hello world, to out\nmyConsole.log('hello %s', 'world');\n// Prints: hello world, to out\nmyConsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to err\n\nconst name = 'Will Robinson';\nmyConsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to err\n
      ", + "classes": [ + { + "textRaw": "Class: `Console`", + "type": "class", + "name": "Console", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9744", + "description": "Errors that occur while writing to the underlying streams will now be ignored by default." + } + ] + }, + "desc": "

      The Console class can be used to create a simple logger with configurable\noutput streams and can be accessed using either require('console').Console\nor console.Console (or their destructured counterparts):

      \n
      const { Console } = require('console');\n
      \n
      const { Console } = console;\n
      ", + "methods": [ + { + "textRaw": "`console.assert(value[, ...message])`", + "type": "method", + "name": "assert", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17706", + "description": "The implementation is now spec compliant and does not throw anymore." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any} The value tested for being truthy.", + "name": "value", + "type": "any", + "desc": "The value tested for being truthy." + }, + { + "textRaw": "`...message` {any} All arguments besides `value` are used as error message.", + "name": "...message", + "type": "any", + "desc": "All arguments besides `value` are used as error message." + } + ] + } + ], + "desc": "

      console.assert() writes a message if value is falsy or omitted. It only\nwrites a message and does not otherwise affect execution. The output always\nstarts with \"Assertion failed\". If provided, message is formatted using\nutil.format().

      \n

      If value is truthy, nothing happens.

      \n
      console.assert(true, 'does nothing');\n\nconsole.assert(false, 'Whoops %s work', 'didn\\'t');\n// Assertion failed: Whoops didn't work\n\nconsole.assert();\n// Assertion failed\n
      " + }, + { + "textRaw": "`console.clear()`", + "type": "method", + "name": "clear", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      When stdout is a TTY, calling console.clear() will attempt to clear the\nTTY. When stdout is not a TTY, this method does nothing.

      \n

      The specific operation of console.clear() can vary across operating systems\nand terminal types. For most Linux operating systems, console.clear()\noperates similarly to the clear shell command. On Windows, console.clear()\nwill clear only the output in the current terminal viewport for the Node.js\nbinary.

      " + }, + { + "textRaw": "`console.count([label])`", + "type": "method", + "name": "count", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} The display label for the counter. **Default:** `'default'`.", + "name": "label", + "type": "string", + "default": "`'default'`", + "desc": "The display label for the counter." + } + ] + } + ], + "desc": "

      Maintains an internal counter specific to label and outputs to stdout the\nnumber of times console.count() has been called with the given label.

      \n\n
      > console.count()\ndefault: 1\nundefined\n> console.count('default')\ndefault: 2\nundefined\n> console.count('abc')\nabc: 1\nundefined\n> console.count('xyz')\nxyz: 1\nundefined\n> console.count('abc')\nabc: 2\nundefined\n> console.count()\ndefault: 3\nundefined\n>\n
      " + }, + { + "textRaw": "`console.countReset([label])`", + "type": "method", + "name": "countReset", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} The display label for the counter. **Default:** `'default'`.", + "name": "label", + "type": "string", + "default": "`'default'`", + "desc": "The display label for the counter." + } + ] + } + ], + "desc": "

      Resets the internal counter specific to label.

      \n\n
      > console.count('abc');\nabc: 1\nundefined\n> console.countReset('abc');\nundefined\n> console.count('abc');\nabc: 1\nundefined\n>\n
      " + }, + { + "textRaw": "`console.debug(data[, ...args])`", + "type": "method", + "name": "debug", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [ + { + "version": "v8.10.0", + "pr-url": "https://github.com/nodejs/node/pull/17033", + "description": "`console.debug` is now an alias for `console.log`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      The console.debug() function is an alias for console.log().

      " + }, + { + "textRaw": "`console.dir(obj[, options])`", + "type": "method", + "name": "dir", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`obj` {any}", + "name": "obj", + "type": "any" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`showHidden` {boolean} If `true` then the object's non-enumerable and symbol properties will be shown too. **Default:** `false`.", + "name": "showHidden", + "type": "boolean", + "default": "`false`", + "desc": "If `true` then the object's non-enumerable and symbol properties will be shown too." + }, + { + "textRaw": "`depth` {number} Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`. **Default:** `2`.", + "name": "depth", + "type": "number", + "default": "`2`", + "desc": "Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`." + }, + { + "textRaw": "`colors` {boolean} If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]. **Default:** `false`.", + "name": "colors", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]." + } + ] + } + ] + } + ], + "desc": "

      Uses util.inspect() on obj and prints the resulting string to stdout.\nThis function bypasses any custom inspect() function defined on obj.

      " + }, + { + "textRaw": "`console.dirxml(...data)`", + "type": "method", + "name": "dirxml", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [ + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/17152", + "description": "`console.dirxml` now calls `console.log` for its arguments." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...data` {any}", + "name": "...data", + "type": "any" + } + ] + } + ], + "desc": "

      This method calls console.log() passing it the arguments received.\nThis method does not produce any XML formatting.

      " + }, + { + "textRaw": "`console.error([data][, ...args])`", + "type": "method", + "name": "error", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Prints to stderr with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()).

      \n
      const code = 5;\nconsole.error('error #%d', code);\n// Prints: error #5, to stderr\nconsole.error('error', code);\n// Prints: error 5, to stderr\n
      \n

      If formatting elements (e.g. %d) are not found in the first string then\nutil.inspect() is called on each argument and the resulting string\nvalues are concatenated. See util.format() for more information.

      " + }, + { + "textRaw": "`console.group([...label])`", + "type": "method", + "name": "group", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...label` {any}", + "name": "...label", + "type": "any" + } + ] + } + ], + "desc": "

      Increases indentation of subsequent lines by spaces for groupIndentation\nlength.

      \n

      If one or more labels are provided, those are printed first without the\nadditional indentation.

      " + }, + { + "textRaw": "`console.groupCollapsed()`", + "type": "method", + "name": "groupCollapsed", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      An alias for console.group().

      " + }, + { + "textRaw": "`console.groupEnd()`", + "type": "method", + "name": "groupEnd", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Decreases indentation of subsequent lines by spaces for groupIndentation\nlength.

      " + }, + { + "textRaw": "`console.info([data][, ...args])`", + "type": "method", + "name": "info", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      The console.info() function is an alias for console.log().

      " + }, + { + "textRaw": "`console.log([data][, ...args])`", + "type": "method", + "name": "log", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Prints to stdout with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()).

      \n
      const count = 5;\nconsole.log('count: %d', count);\n// Prints: count: 5, to stdout\nconsole.log('count:', count);\n// Prints: count: 5, to stdout\n
      \n

      See util.format() for more information.

      " + }, + { + "textRaw": "`console.table(tabularData[, properties])`", + "type": "method", + "name": "table", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`tabularData` {any}", + "name": "tabularData", + "type": "any" + }, + { + "textRaw": "`properties` {string[]} Alternate properties for constructing the table.", + "name": "properties", + "type": "string[]", + "desc": "Alternate properties for constructing the table." + } + ] + } + ], + "desc": "

      Try to construct a table with the columns of the properties of tabularData\n(or use properties) and rows of tabularData and log it. Falls back to just\nlogging the argument if it can’t be parsed as tabular.

      \n
      // These can't be parsed as tabular data\nconsole.table(Symbol());\n// Symbol()\n\nconsole.table(undefined);\n// undefined\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);\n// ┌─────────┬─────┬─────â”\n// │ (index) │  a  │  b  │\n// ├─────────┼─────┼─────┤\n// │    0    │  1  │ 'Y' │\n// │    1    │ 'Z' │  2  │\n// └─────────┴─────┴─────┘\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);\n// ┌─────────┬─────â”\n// │ (index) │  a  │\n// ├─────────┼─────┤\n// │    0    │  1  │\n// │    1    │ 'Z' │\n// └─────────┴─────┘\n
      " + }, + { + "textRaw": "`console.time([label])`", + "type": "method", + "name": "time", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} **Default:** `'default'`", + "name": "label", + "type": "string", + "default": "`'default'`" + } + ] + } + ], + "desc": "

      Starts a timer that can be used to compute the duration of an operation. Timers\nare identified by a unique label. Use the same label when calling\nconsole.timeEnd() to stop the timer and output the elapsed time in\nmilliseconds to stdout. Timer durations are accurate to the sub-millisecond.

      " + }, + { + "textRaw": "`console.timeEnd([label])`", + "type": "method", + "name": "timeEnd", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5901", + "description": "This method no longer supports multiple calls that don’t map to individual `console.time()` calls; see below for details." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} **Default:** `'default'`", + "name": "label", + "type": "string", + "default": "`'default'`" + } + ] + } + ], + "desc": "

      Stops a timer that was previously started by calling console.time() and\nprints the result to stdout:

      \n
      console.time('100-elements');\nfor (let i = 0; i < 100; i++) {}\nconsole.timeEnd('100-elements');\n// prints 100-elements: 225.438ms\n
      " + }, + { + "textRaw": "`console.timeLog([label][, ...data])`", + "type": "method", + "name": "timeLog", + "meta": { + "added": [ + "v10.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string} **Default:** `'default'`", + "name": "label", + "type": "string", + "default": "`'default'`" + }, + { + "textRaw": "`...data` {any}", + "name": "...data", + "type": "any" + } + ] + } + ], + "desc": "

      For a timer that was previously started by calling console.time(), prints\nthe elapsed time and other data arguments to stdout:

      \n
      console.time('process');\nconst value = expensiveProcess1(); // Returns 42\nconsole.timeLog('process', value);\n// Prints \"process: 365.227ms 42\".\ndoExpensiveProcess2(value);\nconsole.timeEnd('process');\n
      " + }, + { + "textRaw": "`console.trace([message][, ...args])`", + "type": "method", + "name": "trace", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {any}", + "name": "message", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Prints to stderr the string 'Trace: ', followed by the util.format()\nformatted message and stack trace to the current position in the code.

      \n
      console.trace('Show me');\n// Prints: (stack trace will vary based on where trace is called)\n//  Trace: Show me\n//    at repl:2:9\n//    at REPLServer.defaultEval (repl.js:248:27)\n//    at bound (domain.js:287:14)\n//    at REPLServer.runBound [as eval] (domain.js:300:12)\n//    at REPLServer.<anonymous> (repl.js:412:12)\n//    at emitOne (events.js:82:20)\n//    at REPLServer.emit (events.js:169:7)\n//    at REPLServer.Interface._onLine (readline.js:210:10)\n//    at REPLServer.Interface._line (readline.js:549:8)\n//    at REPLServer.Interface._ttyWrite (readline.js:826:14)\n
      " + }, + { + "textRaw": "`console.warn([data][, ...args])`", + "type": "method", + "name": "warn", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {any}", + "name": "data", + "type": "any" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      The console.warn() function is an alias for console.error().

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`stdout` {stream.Writable}", + "name": "stdout", + "type": "stream.Writable" + }, + { + "textRaw": "`stderr` {stream.Writable}", + "name": "stderr", + "type": "stream.Writable" + }, + { + "textRaw": "`ignoreErrors` {boolean} Ignore errors when writing to the underlying streams. **Default:** `true`.", + "name": "ignoreErrors", + "type": "boolean", + "default": "`true`", + "desc": "Ignore errors when writing to the underlying streams." + }, + { + "textRaw": "`colorMode` {boolean|string} Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well. **Default:** `'auto'`.", + "name": "colorMode", + "type": "boolean|string", + "default": "`'auto'`", + "desc": "Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well." + }, + { + "textRaw": "`inspectOptions` {Object} Specifies options that are passed along to [`util.inspect()`][].", + "name": "inspectOptions", + "type": "Object", + "desc": "Specifies options that are passed along to [`util.inspect()`][]." + }, + { + "textRaw": "`groupIndentation` {number} Set group indentation. **Default:** `2`.", + "name": "groupIndentation", + "type": "number", + "default": "`2`", + "desc": "Set group indentation." + } + ] + } + ], + "desc": "

      Creates a new Console with one or two writable stream instances. stdout is a\nwritable stream to print log or info output. stderr is used for warning or\nerror output. If stderr is not provided, stdout is used for stderr.

      \n
      const output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n
      \n

      The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:

      \n
      new Console({ stdout: process.stdout, stderr: process.stderr });\n
      " + }, + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`stdout` {stream.Writable}", + "name": "stdout", + "type": "stream.Writable" + }, + { + "textRaw": "`stderr` {stream.Writable}", + "name": "stderr", + "type": "stream.Writable" + }, + { + "textRaw": "`ignoreErrors` {boolean} Ignore errors when writing to the underlying streams. **Default:** `true`.", + "name": "ignoreErrors", + "type": "boolean", + "default": "`true`", + "desc": "Ignore errors when writing to the underlying streams." + }, + { + "textRaw": "`colorMode` {boolean|string} Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well. **Default:** `'auto'`.", + "name": "colorMode", + "type": "boolean|string", + "default": "`'auto'`", + "desc": "Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well." + }, + { + "textRaw": "`inspectOptions` {Object} Specifies options that are passed along to [`util.inspect()`][].", + "name": "inspectOptions", + "type": "Object", + "desc": "Specifies options that are passed along to [`util.inspect()`][]." + }, + { + "textRaw": "`groupIndentation` {number} Set group indentation. **Default:** `2`.", + "name": "groupIndentation", + "type": "number", + "default": "`2`", + "desc": "Set group indentation." + } + ] + } + ], + "desc": "

      Creates a new Console with one or two writable stream instances. stdout is a\nwritable stream to print log or info output. stderr is used for warning or\nerror output. If stderr is not provided, stdout is used for stderr.

      \n
      const output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n
      \n

      The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:

      \n
      new Console({ stdout: process.stdout, stderr: process.stderr });\n
      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Inspector only methods", + "name": "inspector_only_methods", + "desc": "

      The following methods are exposed by the V8 engine in the general API but do\nnot display anything unless used in conjunction with the inspector\n(--inspect flag).

      ", + "methods": [ + { + "textRaw": "`console.profile([label])`", + "type": "method", + "name": "profile", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string}", + "name": "label", + "type": "string" + } + ] + } + ], + "desc": "

      This method does not display anything unless used in the inspector. The\nconsole.profile() method starts a JavaScript CPU profile with an optional\nlabel until console.profileEnd() is called. The profile is then added to\nthe Profile panel of the inspector.

      \n
      console.profile('MyLabel');\n// Some code\nconsole.profileEnd('MyLabel');\n// Adds the profile 'MyLabel' to the Profiles panel of the inspector.\n
      " + }, + { + "textRaw": "`console.profileEnd([label])`", + "type": "method", + "name": "profileEnd", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string}", + "name": "label", + "type": "string" + } + ] + } + ], + "desc": "

      This method does not display anything unless used in the inspector. Stops the\ncurrent JavaScript CPU profiling session if one has been started and prints\nthe report to the Profiles panel of the inspector. See\nconsole.profile() for an example.

      \n

      If this method is called without a label, the most recently started profile is\nstopped.

      " + }, + { + "textRaw": "`console.timeStamp([label])`", + "type": "method", + "name": "timeStamp", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`label` {string}", + "name": "label", + "type": "string" + } + ] + } + ], + "desc": "

      This method does not display anything unless used in the inspector. The\nconsole.timeStamp() method adds an event with the label 'label' to the\nTimeline panel of the inspector.

      " + } + ], + "type": "module", + "displayName": "Inspector only methods" + } + ], + "type": "module", + "displayName": "Console" + } + ] +} \ No newline at end of file diff --git a/doc/api/crypto.html b/doc/api/crypto.html new file mode 100644 index 0000000000000000000000000000000000000000..752a4db2e32424687e147311201062a518e087c9 --- /dev/null +++ b/doc/api/crypto.html @@ -0,0 +1,3552 @@ + + + + + + + Crypto | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Crypto#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/crypto.js

      +

      The crypto module provides cryptographic functionality that includes a set of +wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

      +

      Use require('crypto') to access this module.

      +
      const crypto = require('crypto');
      +
      +const secret = 'abcdefg';
      +const hash = crypto.createHmac('sha256', secret)
      +                   .update('I love cupcakes')
      +                   .digest('hex');
      +console.log(hash);
      +// Prints:
      +//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
      +

      Determining if crypto support is unavailable#

      +

      It is possible for Node.js to be built without including support for the +crypto module. In such cases, calling require('crypto') will result in an +error being thrown.

      +
      let crypto;
      +try {
      +  crypto = require('crypto');
      +} catch (err) {
      +  console.log('crypto support is disabled!');
      +}
      +

      Class: Certificate#

      + +

      SPKAC is a Certificate Signing Request mechanism originally implemented by +Netscape and was specified formally as part of HTML5's keygen element.

      +

      <keygen> is deprecated since HTML 5.2 and new projects +should not use this element anymore.

      +

      The crypto module provides the Certificate class for working with SPKAC +data. The most common usage is handling output generated by the HTML5 +<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.

      +

      Certificate.exportChallenge(spkac)#

      + + +
      const { Certificate } = require('crypto');
      +const spkac = getSpkacSomehow();
      +const challenge = Certificate.exportChallenge(spkac);
      +console.log(challenge.toString('utf8'));
      +// Prints: the challenge as a UTF8 string
      +

      Certificate.exportPublicKey(spkac[, encoding])#

      + + +
      const { Certificate } = require('crypto');
      +const spkac = getSpkacSomehow();
      +const publicKey = Certificate.exportPublicKey(spkac);
      +console.log(publicKey);
      +// Prints: the public key as <Buffer ...>
      +

      Certificate.verifySpkac(spkac)#

      + + +
      const { Certificate } = require('crypto');
      +const spkac = getSpkacSomehow();
      +console.log(Certificate.verifySpkac(Buffer.from(spkac)));
      +// Prints: true or false
      +

      Legacy API#

      +

      As a still supported legacy interface, it is possible to create new instances of +the crypto.Certificate class as illustrated in the examples below.

      +

      new crypto.Certificate()#

      +

      Instances of the Certificate class can be created using the new keyword +or by calling crypto.Certificate() as a function:

      +
      const crypto = require('crypto');
      +
      +const cert1 = new crypto.Certificate();
      +const cert2 = crypto.Certificate();
      +

      certificate.exportChallenge(spkac)#

      + + +
      const cert = require('crypto').Certificate();
      +const spkac = getSpkacSomehow();
      +const challenge = cert.exportChallenge(spkac);
      +console.log(challenge.toString('utf8'));
      +// Prints: the challenge as a UTF8 string
      +

      certificate.exportPublicKey(spkac)#

      + + +
      const cert = require('crypto').Certificate();
      +const spkac = getSpkacSomehow();
      +const publicKey = cert.exportPublicKey(spkac);
      +console.log(publicKey);
      +// Prints: the public key as <Buffer ...>
      +

      certificate.verifySpkac(spkac)#

      + + +
      const cert = require('crypto').Certificate();
      +const spkac = getSpkacSomehow();
      +console.log(cert.verifySpkac(Buffer.from(spkac)));
      +// Prints: true or false
      +

      Class: Cipher#

      + + +

      Instances of the Cipher class are used to encrypt data. The class can be +used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where plain unencrypted +data is written to produce encrypted data on the readable side, or
      • +
      • Using the cipher.update() and cipher.final() methods to produce +the encrypted data.
      • +
      +

      The crypto.createCipher() or crypto.createCipheriv() methods are +used to create Cipher instances. Cipher objects are not to be created +directly using the new keyword.

      +

      Example: Using Cipher objects as streams:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Key length is dependent on the algorithm. In this case for aes192, it is
      +// 24 bytes (192 bits).
      +// Use async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
      +// shown here.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const cipher = crypto.createCipheriv(algorithm, key, iv);
      +
      +let encrypted = '';
      +cipher.on('readable', () => {
      +  let chunk;
      +  while (null !== (chunk = cipher.read())) {
      +    encrypted += chunk.toString('hex');
      +  }
      +});
      +cipher.on('end', () => {
      +  console.log(encrypted);
      +  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
      +});
      +
      +cipher.write('some clear text data');
      +cipher.end();
      +

      Example: Using Cipher and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
      +// shown here.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const cipher = crypto.createCipheriv(algorithm, key, iv);
      +
      +const input = fs.createReadStream('test.js');
      +const output = fs.createWriteStream('test.enc');
      +
      +input.pipe(cipher).pipe(output);
      +

      Example: Using the cipher.update() and cipher.final() methods:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// Use `crypto.randomBytes` to generate a random iv instead of the static iv
      +// shown here.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const cipher = crypto.createCipheriv(algorithm, key, iv);
      +
      +let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
      +encrypted += cipher.final('hex');
      +console.log(encrypted);
      +// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
      +

      cipher.final([outputEncoding])#

      + +
        +
      • outputEncoding <string> The encoding of the return value.
      • +
      • Returns: <Buffer> | <string> Any remaining enciphered contents. +If outputEncoding is specified, a string is +returned. If an outputEncoding is not provided, a Buffer is returned.
      • +
      +

      Once the cipher.final() method has been called, the Cipher object can no +longer be used to encrypt data. Attempts to call cipher.final() more than +once will result in an error being thrown.

      +

      cipher.setAAD(buffer[, options])#

      + + +

      When using an authenticated encryption mode (GCM, CCM and OCB are +currently supported), the cipher.setAAD() method sets the value used for the +additional authenticated data (AAD) input parameter.

      +

      The options argument is optional for GCM and OCB. When using CCM, the +plaintextLength option must be specified and its value must match the length +of the plaintext in bytes. See CCM mode.

      +

      The cipher.setAAD() method must be called before cipher.update().

      +

      cipher.getAuthTag()#

      + +
        +
      • Returns: <Buffer> When using an authenticated encryption mode (GCM, CCM +and OCB are currently supported), the cipher.getAuthTag() method returns a +Buffer containing the authentication tag that has been computed from +the given data.
      • +
      +

      The cipher.getAuthTag() method should only be called after encryption has +been completed using the cipher.final() method.

      +

      cipher.setAutoPadding([autoPadding])#

      + + +

      When using block encryption algorithms, the Cipher class will automatically +add padding to the input data to the appropriate block size. To disable the +default padding call cipher.setAutoPadding(false).

      +

      When autoPadding is false, the length of the entire input data must be a +multiple of the cipher's block size or cipher.final() will throw an error. +Disabling automatic padding is useful for non-standard padding, for instance +using 0x0 instead of PKCS padding.

      +

      The cipher.setAutoPadding() method must be called before +cipher.final().

      +

      cipher.update(data[, inputEncoding][, outputEncoding])#

      + + +

      Updates the cipher with data. If the inputEncoding argument is given, +the data +argument is a string using the specified encoding. If the inputEncoding +argument is not given, data must be a Buffer, TypedArray, or +DataView. If data is a Buffer, TypedArray, or DataView, then +inputEncoding is ignored.

      +

      The outputEncoding specifies the output format of the enciphered +data. If the outputEncoding +is specified, a string using the specified encoding is returned. If no +outputEncoding is provided, a Buffer is returned.

      +

      The cipher.update() method can be called multiple times with new data until +cipher.final() is called. Calling cipher.update() after +cipher.final() will result in an error being thrown.

      +

      Class: Decipher#

      + + +

      Instances of the Decipher class are used to decrypt data. The class can be +used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where plain encrypted +data is written to produce unencrypted data on the readable side, or
      • +
      • Using the decipher.update() and decipher.final() methods to +produce the unencrypted data.
      • +
      +

      The crypto.createDecipher() or crypto.createDecipheriv() methods are +used to create Decipher instances. Decipher objects are not to be created +directly using the new keyword.

      +

      Example: Using Decipher objects as streams:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Key length is dependent on the algorithm. In this case for aes192, it is
      +// 24 bytes (192 bits).
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// The IV is usually passed along with the ciphertext.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const decipher = crypto.createDecipheriv(algorithm, key, iv);
      +
      +let decrypted = '';
      +decipher.on('readable', () => {
      +  while (null !== (chunk = decipher.read())) {
      +    decrypted += chunk.toString('utf8');
      +  }
      +});
      +decipher.on('end', () => {
      +  console.log(decrypted);
      +  // Prints: some clear text data
      +});
      +
      +// Encrypted with same algorithm, key and iv.
      +const encrypted =
      +  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
      +decipher.write(encrypted, 'hex');
      +decipher.end();
      +

      Example: Using Decipher and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// The IV is usually passed along with the ciphertext.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const decipher = crypto.createDecipheriv(algorithm, key, iv);
      +
      +const input = fs.createReadStream('test.enc');
      +const output = fs.createWriteStream('test.js');
      +
      +input.pipe(decipher).pipe(output);
      +

      Example: Using the decipher.update() and decipher.final() methods:

      +
      const crypto = require('crypto');
      +
      +const algorithm = 'aes-192-cbc';
      +const password = 'Password used to generate key';
      +// Use the async `crypto.scrypt()` instead.
      +const key = crypto.scryptSync(password, 'salt', 24);
      +// The IV is usually passed along with the ciphertext.
      +const iv = Buffer.alloc(16, 0); // Initialization vector.
      +
      +const decipher = crypto.createDecipheriv(algorithm, key, iv);
      +
      +// Encrypted using same algorithm, key and iv.
      +const encrypted =
      +  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
      +let decrypted = decipher.update(encrypted, 'hex', 'utf8');
      +decrypted += decipher.final('utf8');
      +console.log(decrypted);
      +// Prints: some clear text data
      +

      decipher.final([outputEncoding])#

      + +
        +
      • outputEncoding <string> The encoding of the return value.
      • +
      • Returns: <Buffer> | <string> Any remaining deciphered contents. +If outputEncoding is specified, a string is +returned. If an outputEncoding is not provided, a Buffer is returned.
      • +
      +

      Once the decipher.final() method has been called, the Decipher object can +no longer be used to decrypt data. Attempts to call decipher.final() more +than once will result in an error being thrown.

      +

      decipher.setAAD(buffer[, options])#

      + + +

      When using an authenticated encryption mode (GCM, CCM and OCB are +currently supported), the decipher.setAAD() method sets the value used for the +additional authenticated data (AAD) input parameter.

      +

      The options argument is optional for GCM. When using CCM, the +plaintextLength option must be specified and its value must match the length +of the ciphertext in bytes. See CCM mode.

      +

      The decipher.setAAD() method must be called before decipher.update().

      +

      decipher.setAuthTag(buffer)#

      + + +

      When using an authenticated encryption mode (GCM, CCM and OCB are +currently supported), the decipher.setAuthTag() method is used to pass in the +received authentication tag. If no tag is provided, or if the cipher text +has been tampered with, decipher.final() will throw, indicating that the +cipher text should be discarded due to failed authentication. If the tag length +is invalid according to NIST SP 800-38D or does not match the value of the +authTagLength option, decipher.setAuthTag() will throw an error.

      +

      The decipher.setAuthTag() method must be called before decipher.update() +for CCM mode or before decipher.final() for GCM and OCB modes. +decipher.setAuthTag() can only be called once.

      +

      decipher.setAutoPadding([autoPadding])#

      + + +

      When data has been encrypted without standard block padding, calling +decipher.setAutoPadding(false) will disable automatic padding to prevent +decipher.final() from checking for and removing padding.

      +

      Turning auto padding off will only work if the input data's length is a +multiple of the ciphers block size.

      +

      The decipher.setAutoPadding() method must be called before +decipher.final().

      +

      decipher.update(data[, inputEncoding][, outputEncoding])#

      + + +

      Updates the decipher with data. If the inputEncoding argument is given, +the data +argument is a string using the specified encoding. If the inputEncoding +argument is not given, data must be a Buffer. If data is a +Buffer then inputEncoding is ignored.

      +

      The outputEncoding specifies the output format of the enciphered +data. If the outputEncoding +is specified, a string using the specified encoding is returned. If no +outputEncoding is provided, a Buffer is returned.

      +

      The decipher.update() method can be called multiple times with new data until +decipher.final() is called. Calling decipher.update() after +decipher.final() will result in an error being thrown.

      +

      Class: DiffieHellman#

      + +

      The DiffieHellman class is a utility for creating Diffie-Hellman key +exchanges.

      +

      Instances of the DiffieHellman class can be created using the +crypto.createDiffieHellman() function.

      +
      const crypto = require('crypto');
      +const assert = require('assert');
      +
      +// Generate Alice's keys...
      +const alice = crypto.createDiffieHellman(2048);
      +const aliceKey = alice.generateKeys();
      +
      +// Generate Bob's keys...
      +const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
      +const bobKey = bob.generateKeys();
      +
      +// Exchange and generate the secret...
      +const aliceSecret = alice.computeSecret(bobKey);
      +const bobSecret = bob.computeSecret(aliceKey);
      +
      +// OK
      +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
      +

      diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#

      + + +

      Computes the shared secret using otherPublicKey as the other +party's public key and returns the computed shared secret. The supplied +key is interpreted using the specified inputEncoding, and secret is +encoded using specified outputEncoding. +If the inputEncoding is not +provided, otherPublicKey is expected to be a Buffer, +TypedArray, or DataView.

      +

      If outputEncoding is given a string is returned; otherwise, a +Buffer is returned.

      +

      diffieHellman.generateKeys([encoding])#

      + + +

      Generates private and public Diffie-Hellman key values, and returns +the public key in the specified encoding. This key should be +transferred to the other party. +If encoding is provided a string is returned; otherwise a +Buffer is returned.

      +

      diffieHellman.getGenerator([encoding])#

      + + +

      Returns the Diffie-Hellman generator in the specified encoding. +If encoding is provided a string is +returned; otherwise a Buffer is returned.

      +

      diffieHellman.getPrime([encoding])#

      + + +

      Returns the Diffie-Hellman prime in the specified encoding. +If encoding is provided a string is +returned; otherwise a Buffer is returned.

      +

      diffieHellman.getPrivateKey([encoding])#

      + + +

      Returns the Diffie-Hellman private key in the specified encoding. +If encoding is provided a +string is returned; otherwise a Buffer is returned.

      +

      diffieHellman.getPublicKey([encoding])#

      + + +

      Returns the Diffie-Hellman public key in the specified encoding. +If encoding is provided a +string is returned; otherwise a Buffer is returned.

      +

      diffieHellman.setPrivateKey(privateKey[, encoding])#

      + + +

      Sets the Diffie-Hellman private key. If the encoding argument is provided, +privateKey is expected +to be a string. If no encoding is provided, privateKey is expected +to be a Buffer, TypedArray, or DataView.

      +

      diffieHellman.setPublicKey(publicKey[, encoding])#

      + + +

      Sets the Diffie-Hellman public key. If the encoding argument is provided, +publicKey is expected +to be a string. If no encoding is provided, publicKey is expected +to be a Buffer, TypedArray, or DataView.

      +

      diffieHellman.verifyError#

      + +

      A bit field containing any warnings and/or errors resulting from a check +performed during initialization of the DiffieHellman object.

      +

      The following values are valid for this property (as defined in constants +module):

      +
        +
      • DH_CHECK_P_NOT_SAFE_PRIME
      • +
      • DH_CHECK_P_NOT_PRIME
      • +
      • DH_UNABLE_TO_CHECK_GENERATOR
      • +
      • DH_NOT_SUITABLE_GENERATOR
      • +
      +

      Class: DiffieHellmanGroup#

      + +

      The DiffieHellmanGroup class takes a well-known modp group as its argument but +otherwise works the same as DiffieHellman.

      +
      const name = 'modp1';
      +const dh = crypto.createDiffieHellmanGroup(name);
      +

      name is taken from RFC 2412 (modp1 and 2) and RFC 3526:

      +
      $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
      +modp1  #  768 bits
      +modp2  # 1024 bits
      +modp5  # 1536 bits
      +modp14 # 2048 bits
      +modp15 # etc.
      +modp16
      +modp17
      +modp18
      +

      Class: ECDH#

      + +

      The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) +key exchanges.

      +

      Instances of the ECDH class can be created using the +crypto.createECDH() function.

      +
      const crypto = require('crypto');
      +const assert = require('assert');
      +
      +// Generate Alice's keys...
      +const alice = crypto.createECDH('secp521r1');
      +const aliceKey = alice.generateKeys();
      +
      +// Generate Bob's keys...
      +const bob = crypto.createECDH('secp521r1');
      +const bobKey = bob.generateKeys();
      +
      +// Exchange and generate the secret...
      +const aliceSecret = alice.computeSecret(bobKey);
      +const bobSecret = bob.computeSecret(aliceKey);
      +
      +assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
      +// OK
      +

      Static method: ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])#

      + + +

      Converts the EC Diffie-Hellman public key specified by key and curve to the +format specified by format. The format argument specifies point encoding +and can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is +interpreted using the specified inputEncoding, and the returned key is encoded +using the specified outputEncoding.

      +

      Use crypto.getCurves() to obtain a list of available curve names. +On recent OpenSSL releases, openssl ecparam -list_curves will also display +the name and description of each available elliptic curve.

      +

      If format is not specified the point will be returned in 'uncompressed' +format.

      +

      If the inputEncoding is not provided, key is expected to be a Buffer, +TypedArray, or DataView.

      +

      Example (uncompressing a key):

      +
      const { createECDH, ECDH } = require('crypto');
      +
      +const ecdh = createECDH('secp256k1');
      +ecdh.generateKeys();
      +
      +const compressedKey = ecdh.getPublicKey('hex', 'compressed');
      +
      +const uncompressedKey = ECDH.convertKey(compressedKey,
      +                                        'secp256k1',
      +                                        'hex',
      +                                        'hex',
      +                                        'uncompressed');
      +
      +// The converted key and the uncompressed public key should be the same
      +console.log(uncompressedKey === ecdh.getPublicKey('hex'));
      +

      ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#

      + + +

      Computes the shared secret using otherPublicKey as the other +party's public key and returns the computed shared secret. The supplied +key is interpreted using specified inputEncoding, and the returned secret +is encoded using the specified outputEncoding. +If the inputEncoding is not +provided, otherPublicKey is expected to be a Buffer, TypedArray, or +DataView.

      +

      If outputEncoding is given a string will be returned; otherwise a +Buffer is returned.

      +

      ecdh.computeSecret will throw an +ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey +lies outside of the elliptic curve. Since otherPublicKey is +usually supplied from a remote user over an insecure network, +be sure to handle this exception accordingly.

      +

      ecdh.generateKeys([encoding[, format]])#

      + + +

      Generates private and public EC Diffie-Hellman key values, and returns +the public key in the specified format and encoding. This key should be +transferred to the other party.

      +

      The format argument specifies point encoding and can be 'compressed' or +'uncompressed'. If format is not specified, the point will be returned in +'uncompressed' format.

      +

      If encoding is provided a string is returned; otherwise a Buffer +is returned.

      +

      ecdh.getPrivateKey([encoding])#

      + + +

      If encoding is specified, a string is returned; otherwise a Buffer is +returned.

      +

      ecdh.getPublicKey([encoding][, format])#

      + + +

      The format argument specifies point encoding and can be 'compressed' or +'uncompressed'. If format is not specified the point will be returned in +'uncompressed' format.

      +

      If encoding is specified, a string is returned; otherwise a Buffer is +returned.

      +

      ecdh.setPrivateKey(privateKey[, encoding])#

      + + +

      Sets the EC Diffie-Hellman private key. +If encoding is provided, privateKey is expected +to be a string; otherwise privateKey is expected to be a Buffer, +TypedArray, or DataView.

      +

      If privateKey is not valid for the curve specified when the ECDH object was +created, an error is thrown. Upon setting the private key, the associated +public point (key) is also generated and set in the ECDH object.

      +

      ecdh.setPublicKey(publicKey[, encoding])#

      + +

      Stability: 0 - Deprecated

      + +

      Sets the EC Diffie-Hellman public key. +If encoding is provided publicKey is expected to +be a string; otherwise a Buffer, TypedArray, or DataView is expected.

      +

      There is not normally a reason to call this method because ECDH +only requires a private key and the other party's public key to compute the +shared secret. Typically either ecdh.generateKeys() or +ecdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method +attempts to generate the public point/key associated with the private key being +set.

      +

      Example (obtaining a shared secret):

      +
      const crypto = require('crypto');
      +const alice = crypto.createECDH('secp256k1');
      +const bob = crypto.createECDH('secp256k1');
      +
      +// This is a shortcut way of specifying one of Alice's previous private
      +// keys. It would be unwise to use such a predictable private key in a real
      +// application.
      +alice.setPrivateKey(
      +  crypto.createHash('sha256').update('alice', 'utf8').digest()
      +);
      +
      +// Bob uses a newly generated cryptographically strong
      +// pseudorandom key pair
      +bob.generateKeys();
      +
      +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
      +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
      +
      +// aliceSecret and bobSecret should be the same shared secret value
      +console.log(aliceSecret === bobSecret);
      +

      Class: Hash#

      + + +

      The Hash class is a utility for creating hash digests of data. It can be +used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where data is written +to produce a computed hash digest on the readable side, or
      • +
      • Using the hash.update() and hash.digest() methods to produce the +computed hash.
      • +
      +

      The crypto.createHash() method is used to create Hash instances. Hash +objects are not to be created directly using the new keyword.

      +

      Example: Using Hash objects as streams:

      +
      const crypto = require('crypto');
      +const hash = crypto.createHash('sha256');
      +
      +hash.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = hash.read();
      +  if (data) {
      +    console.log(data.toString('hex'));
      +    // Prints:
      +    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
      +  }
      +});
      +
      +hash.write('some data to hash');
      +hash.end();
      +

      Example: Using Hash and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +const hash = crypto.createHash('sha256');
      +
      +const input = fs.createReadStream('test.js');
      +input.pipe(hash).pipe(process.stdout);
      +

      Example: Using the hash.update() and hash.digest() methods:

      +
      const crypto = require('crypto');
      +const hash = crypto.createHash('sha256');
      +
      +hash.update('some data to hash');
      +console.log(hash.digest('hex'));
      +// Prints:
      +//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
      +

      hash.copy([options])#

      + + +

      Creates a new Hash object that contains a deep copy of the internal state +of the current Hash object.

      +

      The optional options argument controls stream behavior. For XOF hash +functions such as 'shake256', the outputLength option can be used to +specify the desired output length in bytes.

      +

      An error is thrown when an attempt is made to copy the Hash object after +its hash.digest() method has been called.

      +
      // Calculate a rolling hash.
      +const crypto = require('crypto');
      +const hash = crypto.createHash('sha256');
      +
      +hash.update('one');
      +console.log(hash.copy().digest('hex'));
      +
      +hash.update('two');
      +console.log(hash.copy().digest('hex'));
      +
      +hash.update('three');
      +console.log(hash.copy().digest('hex'));
      +
      +// Etc.
      +

      hash.digest([encoding])#

      + + +

      Calculates the digest of all of the data passed to be hashed (using the +hash.update() method). +If encoding is provided a string will be returned; otherwise +a Buffer is returned.

      +

      The Hash object can not be used again after hash.digest() method has been +called. Multiple calls will cause an error to be thrown.

      +

      hash.update(data[, inputEncoding])#

      + + +

      Updates the hash content with the given data, the encoding of which +is given in inputEncoding. +If encoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      Class: Hmac#

      + + +

      The Hmac class is a utility for creating cryptographic HMAC digests. It can +be used in one of two ways:

      +
        +
      • As a stream that is both readable and writable, where data is written +to produce a computed HMAC digest on the readable side, or
      • +
      • Using the hmac.update() and hmac.digest() methods to produce the +computed HMAC digest.
      • +
      +

      The crypto.createHmac() method is used to create Hmac instances. Hmac +objects are not to be created directly using the new keyword.

      +

      Example: Using Hmac objects as streams:

      +
      const crypto = require('crypto');
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +hmac.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = hmac.read();
      +  if (data) {
      +    console.log(data.toString('hex'));
      +    // Prints:
      +    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
      +  }
      +});
      +
      +hmac.write('some data to hash');
      +hmac.end();
      +

      Example: Using Hmac and piped streams:

      +
      const crypto = require('crypto');
      +const fs = require('fs');
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +const input = fs.createReadStream('test.js');
      +input.pipe(hmac).pipe(process.stdout);
      +

      Example: Using the hmac.update() and hmac.digest() methods:

      +
      const crypto = require('crypto');
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +hmac.update('some data to hash');
      +console.log(hmac.digest('hex'));
      +// Prints:
      +//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
      +

      hmac.digest([encoding])#

      + + +

      Calculates the HMAC digest of all of the data passed using hmac.update(). +If encoding is +provided a string is returned; otherwise a Buffer is returned;

      +

      The Hmac object can not be used again after hmac.digest() has been +called. Multiple calls to hmac.digest() will result in an error being thrown.

      +

      hmac.update(data[, inputEncoding])#

      + + +

      Updates the Hmac content with the given data, the encoding of which +is given in inputEncoding. +If encoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      Class: KeyObject#

      + +

      Node.js uses a KeyObject class to represent a symmetric or asymmetric key, +and each kind of key exposes different functions. The +crypto.createSecretKey(), crypto.createPublicKey() and +crypto.createPrivateKey() methods are used to create KeyObject +instances. KeyObject objects are not to be created directly using the new +keyword.

      +

      Most applications should consider using the new KeyObject API instead of +passing keys as strings or Buffers due to improved security features.

      +

      KeyObject instances can be passed to other threads via postMessage(). +The receiver obtains a cloned KeyObject, and the KeyObject does not need to +be listed in the transferList argument.

      +

      keyObject.asymmetricKeyType#

      + + +

      For asymmetric keys, this property represents the type of the key. Supported key +types are:

      +
        +
      • 'rsa' (OID 1.2.840.113549.1.1.1)
      • +
      • 'rsa-pss' (OID 1.2.840.113549.1.1.10)
      • +
      • 'dsa' (OID 1.2.840.10040.4.1)
      • +
      • 'ec' (OID 1.2.840.10045.2.1)
      • +
      • 'x25519' (OID 1.3.101.110)
      • +
      • 'x448' (OID 1.3.101.111)
      • +
      • 'ed25519' (OID 1.3.101.112)
      • +
      • 'ed448' (OID 1.3.101.113)
      • +
      • 'dh' (OID 1.2.840.113549.1.3.1)
      • +
      +

      This property is undefined for unrecognized KeyObject types and symmetric +keys.

      +

      keyObject.export([options])#

      + + +

      For symmetric keys, this function allocates a Buffer containing the key +material and ignores any options.

      +

      For asymmetric keys, the options parameter is used to determine the export +format.

      +

      For public keys, the following encoding options can be used:

      +
        +
      • type: <string> Must be one of 'pkcs1' (RSA only) or 'spki'.
      • +
      • format: <string> Must be 'pem' or 'der'.
      • +
      +

      For private keys, the following encoding options can be used:

      +
        +
      • type: <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or +'sec1' (EC only).
      • +
      • format: <string> Must be 'pem' or 'der'.
      • +
      • cipher: <string> If specified, the private key will be encrypted with + the given cipher and passphrase using PKCS#5 v2.0 password based +encryption.
      • +
      • passphrase: <string> | <Buffer> The passphrase to use for encryption, see +cipher.
      • +
      +

      When PEM encoding was selected, the result will be a string, otherwise it will +be a buffer containing the data encoded as DER.

      +

      PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of +the cipher and format options. The PKCS#8 type can be used with any +format to encrypt any key algorithm (RSA, EC, or DH) by specifying a +cipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher +when the PEM format is used. For maximum compatibility, use PKCS#8 for +encrypted private keys. Since PKCS#8 defines its own +encryption mechanism, PEM-level encryption is not supported when encrypting +a PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for +PKCS#1 and SEC1 encryption.

      +

      keyObject.symmetricKeySize#

      + + +

      For secret keys, this property represents the size of the key in bytes. This +property is undefined for asymmetric keys.

      +

      keyObject.type#

      + + +

      Depending on the type of this KeyObject, this property is either +'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys +or 'private' for private (asymmetric) keys.

      +

      Class: Sign#

      + + +

      The Sign class is a utility for generating signatures. It can be used in one +of two ways:

      +
        +
      • As a writable stream, where data to be signed is written and the +sign.sign() method is used to generate and return the signature, or
      • +
      • Using the sign.update() and sign.sign() methods to produce the +signature.
      • +
      +

      The crypto.createSign() method is used to create Sign instances. The +argument is the string name of the hash function to use. Sign objects are not +to be created directly using the new keyword.

      +

      Example: Using Sign and Verify objects as streams:

      +
      const crypto = require('crypto');
      +
      +const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
      +  namedCurve: 'sect239k1'
      +});
      +
      +const sign = crypto.createSign('SHA256');
      +sign.write('some data to sign');
      +sign.end();
      +const signature = sign.sign(privateKey, 'hex');
      +
      +const verify = crypto.createVerify('SHA256');
      +verify.write('some data to sign');
      +verify.end();
      +console.log(verify.verify(publicKey, signature, 'hex'));
      +// Prints: true
      +

      Example: Using the sign.update() and verify.update() methods:

      +
      const crypto = require('crypto');
      +
      +const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
      +  modulusLength: 2048,
      +});
      +
      +const sign = crypto.createSign('SHA256');
      +sign.update('some data to sign');
      +sign.end();
      +const signature = sign.sign(privateKey);
      +
      +const verify = crypto.createVerify('SHA256');
      +verify.update('some data to sign');
      +verify.end();
      +console.log(verify.verify(publicKey, signature));
      +// Prints: true
      +

      sign.sign(privateKey[, outputEncoding])#

      + + +

      Calculates the signature on all the data passed through using either +sign.update() or sign.write().

      +

      If privateKey is not a KeyObject, this function behaves as if +privateKey had been passed to crypto.createPrivateKey(). If it is an +object, the following additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to sign the message as specified in section 3.1 of RFC 4055, unless +an MGF1 hash function has been specified as part of the key in compliance with +section 3.3 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the +maximum permissible value.

        +
      • +
      +

      If outputEncoding is provided a string is returned; otherwise a Buffer +is returned.

      +

      The Sign object can not be again used after sign.sign() method has been +called. Multiple calls to sign.sign() will result in an error being thrown.

      +

      sign.update(data[, inputEncoding])#

      + + +

      Updates the Sign content with the given data, the encoding of which +is given in inputEncoding. +If encoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      Class: Verify#

      + + +

      The Verify class is a utility for verifying signatures. It can be used in one +of two ways:

      +
        +
      • As a writable stream where written data is used to validate against the +supplied signature, or
      • +
      • Using the verify.update() and verify.verify() methods to verify +the signature.
      • +
      +

      The crypto.createVerify() method is used to create Verify instances. +Verify objects are not to be created directly using the new keyword.

      +

      See Sign for examples.

      +

      verify.update(data[, inputEncoding])#

      + + +

      Updates the Verify content with the given data, the encoding of which +is given in inputEncoding. +If inputEncoding is not provided, and the data is a string, an +encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or +DataView, then inputEncoding is ignored.

      +

      This can be called many times with new data as it is streamed.

      +

      verify.verify(object, signature[, signatureEncoding])#

      + + +

      Verifies the provided data using the given object and signature.

      +

      If object is not a KeyObject, this function behaves as if +object had been passed to crypto.createPublicKey(). If it is an +object, the following additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to verify the message as specified in section 3.1 of RFC 4055, unless +an MGF1 hash function has been specified as part of the key in compliance with +section 3.3 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be +determined automatically.

        +
      • +
      +

      The signature argument is the previously calculated signature for the data, in +the signatureEncoding. +If a signatureEncoding is specified, the signature is expected to be a +string; otherwise signature is expected to be a Buffer, +TypedArray, or DataView.

      +

      The verify object can not be used again after verify.verify() has been +called. Multiple calls to verify.verify() will result in an error being +thrown.

      +

      Because public keys can be derived from private keys, a private key may +be passed instead of a public key.

      +

      crypto module methods and properties#

      +

      crypto.constants#

      + +
        +
      • Returns: <Object> An object containing commonly used constants for crypto and +security related operations. The specific constants currently defined are +described in Crypto constants.
      • +
      +

      crypto.DEFAULT_ENCODING#

      + +

      Stability: 0 - Deprecated

      +

      The default encoding to use for functions that can take either strings +or buffers. The default value is 'buffer', which makes methods +default to Buffer objects.

      +

      The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility +with legacy programs that expect 'latin1' to be the default encoding.

      +

      New applications should expect the default to be 'buffer'.

      +

      This property is deprecated.

      +

      crypto.fips#

      + +

      Stability: 0 - Deprecated

      +

      Property for checking and controlling whether a FIPS compliant crypto provider +is currently in use. Setting to true requires a FIPS build of Node.js.

      +

      This property is deprecated. Please use crypto.setFips() and +crypto.getFips() instead.

      +

      crypto.createCipher(algorithm, password[, options])#

      + +

      Stability: 0 - Deprecated: Use crypto.createCipheriv() instead.

      + +

      Creates and returns a Cipher object that uses the given algorithm and +password.

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength +option is not required but can be used to set the length of the authentication +tag that will be returned by getAuthTag() and defaults to 16 bytes.

      +

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On +recent OpenSSL releases, openssl list -cipher-algorithms +(openssl list-cipher-algorithms for older versions of OpenSSL) will +display the available cipher algorithms.

      +

      The password is used to derive the cipher key and initialization vector (IV). +The value must be either a 'latin1' encoded string, a Buffer, a +TypedArray, or a DataView.

      +

      The implementation of crypto.createCipher() derives keys using the OpenSSL +function EVP_BytesToKey with the digest algorithm set to MD5, one +iteration, and no salt. The lack of salt allows dictionary attacks as the same +password always creates the same key. The low iteration count and +non-cryptographically secure hash algorithm allow passwords to be tested very +rapidly.

      +

      In line with OpenSSL's recommendation to use a more modern algorithm instead of +EVP_BytesToKey it is recommended that developers derive a key and IV on +their own using crypto.scrypt() and to use crypto.createCipheriv() +to create the Cipher object. Users should not use ciphers with counter mode +(e.g. CTR, GCM, or CCM) in crypto.createCipher(). A warning is emitted when +they are used in order to avoid the risk of IV reuse that causes +vulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting +Adversaries for details.

      +

      crypto.createCipheriv(algorithm, key, iv[, options])#

      + + +

      Creates and returns a Cipher object, with the given algorithm, key and +initialization vector (iv).

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength +option is not required but can be used to set the length of the authentication +tag that will be returned by getAuthTag() and defaults to 16 bytes.

      +

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On +recent OpenSSL releases, openssl list -cipher-algorithms +(openssl list-cipher-algorithms for older versions of OpenSSL) will +display the available cipher algorithms.

      +

      The key is the raw key used by the algorithm and iv is an +initialization vector. Both arguments must be 'utf8' encoded strings, +Buffers, TypedArray, or DataViews. The key may optionally be +a KeyObject of type secret. If the cipher does not need +an initialization vector, iv may be null.

      +

      Initialization vectors should be unpredictable and unique; ideally, they will be +cryptographically random. They do not have to be secret: IVs are typically just +added to ciphertext messages unencrypted. It may sound contradictory that +something has to be unpredictable and unique, but does not have to be secret; +remember that an attacker must not be able to predict ahead of time what a +given IV will be.

      +

      crypto.createDecipher(algorithm, password[, options])#

      + +

      Stability: 0 - Deprecated: Use crypto.createDecipheriv() instead.

      + +

      Creates and returns a Decipher object that uses the given algorithm and +password (key).

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode.

      +

      The implementation of crypto.createDecipher() derives keys using the OpenSSL +function EVP_BytesToKey with the digest algorithm set to MD5, one +iteration, and no salt. The lack of salt allows dictionary attacks as the same +password always creates the same key. The low iteration count and +non-cryptographically secure hash algorithm allow passwords to be tested very +rapidly.

      +

      In line with OpenSSL's recommendation to use a more modern algorithm instead of +EVP_BytesToKey it is recommended that developers derive a key and IV on +their own using crypto.scrypt() and to use crypto.createDecipheriv() +to create the Decipher object.

      +

      crypto.createDecipheriv(algorithm, key, iv[, options])#

      + + +

      Creates and returns a Decipher object that uses the given algorithm, key +and initialization vector (iv).

      +

      The options argument controls stream behavior and is optional except when a +cipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the +authTagLength option is required and specifies the length of the +authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength +option is not required but can be used to restrict accepted authentication tags +to those with the specified length.

      +

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On +recent OpenSSL releases, openssl list -cipher-algorithms +(openssl list-cipher-algorithms for older versions of OpenSSL) will +display the available cipher algorithms.

      +

      The key is the raw key used by the algorithm and iv is an +initialization vector. Both arguments must be 'utf8' encoded strings, +Buffers, TypedArray, or DataViews. The key may optionally be +a KeyObject of type secret. If the cipher does not need +an initialization vector, iv may be null.

      +

      Initialization vectors should be unpredictable and unique; ideally, they will be +cryptographically random. They do not have to be secret: IVs are typically just +added to ciphertext messages unencrypted. It may sound contradictory that +something has to be unpredictable and unique, but does not have to be secret; +remember that an attacker must not be able to predict ahead of time what a given +IV will be.

      +

      crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])#

      + + +

      Creates a DiffieHellman key exchange object using the supplied prime and an +optional specific generator.

      +

      The generator argument can be a number, string, or Buffer. If +generator is not specified, the value 2 is used.

      +

      If primeEncoding is specified, prime is expected to be a string; otherwise +a Buffer, TypedArray, or DataView is expected.

      +

      If generatorEncoding is specified, generator is expected to be a string; +otherwise a number, Buffer, TypedArray, or DataView is expected.

      +

      crypto.createDiffieHellman(primeLength[, generator])#

      + + +

      Creates a DiffieHellman key exchange object and generates a prime of +primeLength bits using an optional specific numeric generator. +If generator is not specified, the value 2 is used.

      +

      crypto.createDiffieHellmanGroup(name)#

      + + +

      An alias for crypto.getDiffieHellman()

      +

      crypto.createECDH(curveName)#

      + + +

      Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a +predefined curve specified by the curveName string. Use +crypto.getCurves() to obtain a list of available curve names. On recent +OpenSSL releases, openssl ecparam -list_curves will also display the name +and description of each available elliptic curve.

      +

      crypto.createHash(algorithm[, options])#

      + + +

      Creates and returns a Hash object that can be used to generate hash digests +using the given algorithm. Optional options argument controls stream +behavior. For XOF hash functions such as 'shake256', the outputLength option +can be used to specify the desired output length in bytes.

      +

      The algorithm is dependent on the available algorithms supported by the +version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. +On recent releases of OpenSSL, openssl list -digest-algorithms +(openssl list-message-digest-algorithms for older versions of OpenSSL) will +display the available digest algorithms.

      +

      Example: generating the sha256 sum of a file

      +
      const filename = process.argv[2];
      +const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const hash = crypto.createHash('sha256');
      +
      +const input = fs.createReadStream(filename);
      +input.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = input.read();
      +  if (data)
      +    hash.update(data);
      +  else {
      +    console.log(`${hash.digest('hex')} ${filename}`);
      +  }
      +});
      +

      crypto.createHmac(algorithm, key[, options])#

      + + +

      Creates and returns an Hmac object that uses the given algorithm and key. +Optional options argument controls stream behavior.

      +

      The algorithm is dependent on the available algorithms supported by the +version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. +On recent releases of OpenSSL, openssl list -digest-algorithms +(openssl list-message-digest-algorithms for older versions of OpenSSL) will +display the available digest algorithms.

      +

      The key is the HMAC key used to generate the cryptographic HMAC hash. If it is +a KeyObject, its type must be secret.

      +

      Example: generating the sha256 HMAC of a file

      +
      const filename = process.argv[2];
      +const crypto = require('crypto');
      +const fs = require('fs');
      +
      +const hmac = crypto.createHmac('sha256', 'a secret');
      +
      +const input = fs.createReadStream(filename);
      +input.on('readable', () => {
      +  // Only one element is going to be produced by the
      +  // hash stream.
      +  const data = input.read();
      +  if (data)
      +    hmac.update(data);
      +  else {
      +    console.log(`${hmac.digest('hex')} ${filename}`);
      +  }
      +});
      +

      crypto.createPrivateKey(key)#

      + + +

      Creates and returns a new key object containing a private key. If key is a +string or Buffer, format is assumed to be 'pem'; otherwise, key +must be an object with the properties described above.

      +

      If the private key is encrypted, a passphrase must be specified. The length +of the passphrase is limited to 1024 bytes.

      +

      crypto.createPublicKey(key)#

      + + +

      Creates and returns a new key object containing a public key. If key is a +string or Buffer, format is assumed to be 'pem'; if key is a KeyObject +with type 'private', the public key is derived from the given private key; +otherwise, key must be an object with the properties described above.

      +

      If the format is 'pem', the 'key' may also be an X.509 certificate.

      +

      Because public keys can be derived from private keys, a private key may be +passed instead of a public key. In that case, this function behaves as if +crypto.createPrivateKey() had been called, except that the type of the +returned KeyObject will be 'public' and that the private key cannot be +extracted from the returned KeyObject. Similarly, if a KeyObject with type +'private' is given, a new KeyObject with type 'public' will be returned +and it will be impossible to extract the private key from the returned object.

      +

      crypto.createSecretKey(key)#

      + + +

      Creates and returns a new key object containing a secret key for symmetric +encryption or Hmac.

      +

      crypto.createSign(algorithm[, options])#

      + + +

      Creates and returns a Sign object that uses the given algorithm. Use +crypto.getHashes() to obtain the names of the available digest algorithms. +Optional options argument controls the stream.Writable behavior.

      +

      In some cases, a Sign instance can be created using the name of a signature +algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use +the corresponding digest algorithm. This does not work for all signature +algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest +algorithm names.

      +

      crypto.createVerify(algorithm[, options])#

      + + +

      Creates and returns a Verify object that uses the given algorithm. +Use crypto.getHashes() to obtain an array of names of the available +signing algorithms. Optional options argument controls the +stream.Writable behavior.

      +

      In some cases, a Verify instance can be created using the name of a signature +algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use +the corresponding digest algorithm. This does not work for all signature +algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest +algorithm names.

      +

      crypto.diffieHellman(options)#

      + + +

      Computes the Diffie-Hellman secret based on a privateKey and a publicKey. +Both keys must have the same asymmetricKeyType, which must be one of 'dh' +(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).

      +

      crypto.generateKeyPair(type, options, callback)#

      + + +

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported.

      +

      If a publicKeyEncoding or privateKeyEncoding was specified, this function +behaves as if keyObject.export() had been called on its result. Otherwise, +the respective part of the key is returned as a KeyObject.

      +

      It is recommended to encode public keys as 'spki' and private keys as +'pkcs8' with encryption for long-term storage:

      +
      const { generateKeyPair } = require('crypto');
      +generateKeyPair('rsa', {
      +  modulusLength: 4096,
      +  publicKeyEncoding: {
      +    type: 'spki',
      +    format: 'pem'
      +  },
      +  privateKeyEncoding: {
      +    type: 'pkcs8',
      +    format: 'pem',
      +    cipher: 'aes-256-cbc',
      +    passphrase: 'top secret'
      +  }
      +}, (err, publicKey, privateKey) => {
      +  // Handle errors and use the generated key pair.
      +});
      +

      On completion, callback will be called with err set to undefined and +publicKey / privateKey representing the generated key pair.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with publicKey and privateKey properties.

      +

      crypto.generateKeyPairSync(type, options)#

      + + +

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519, +Ed448, X25519, X448, and DH are currently supported.

      +

      If a publicKeyEncoding or privateKeyEncoding was specified, this function +behaves as if keyObject.export() had been called on its result. Otherwise, +the respective part of the key is returned as a KeyObject.

      +

      When encoding public keys, it is recommended to use 'spki'. When encoding +private keys, it is recommended to use 'pkcs8' with a strong passphrase, +and to keep the passphrase confidential.

      +
      const { generateKeyPairSync } = require('crypto');
      +const { publicKey, privateKey } = generateKeyPairSync('rsa', {
      +  modulusLength: 4096,
      +  publicKeyEncoding: {
      +    type: 'spki',
      +    format: 'pem'
      +  },
      +  privateKeyEncoding: {
      +    type: 'pkcs8',
      +    format: 'pem',
      +    cipher: 'aes-256-cbc',
      +    passphrase: 'top secret'
      +  }
      +});
      +

      The return value { publicKey, privateKey } represents the generated key pair. +When PEM encoding was selected, the respective key will be a string, otherwise +it will be a buffer containing the data encoded as DER.

      +

      crypto.getCiphers()#

      + +
        +
      • Returns: <string[]> An array with the names of the supported cipher +algorithms.
      • +
      +
      const ciphers = crypto.getCiphers();
      +console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
      +

      crypto.getCurves()#

      + +
        +
      • Returns: <string[]> An array with the names of the supported elliptic curves.
      • +
      +
      const curves = crypto.getCurves();
      +console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
      +

      crypto.getDiffieHellman(groupName)#

      + + +

      Creates a predefined DiffieHellmanGroup key exchange object. The +supported groups are: 'modp1', 'modp2', 'modp5' (defined in +RFC 2412, but see Caveats) and 'modp14', 'modp15', +'modp16', 'modp17', 'modp18' (defined in RFC 3526). The +returned object mimics the interface of objects created by +crypto.createDiffieHellman(), but will not allow changing +the keys (with diffieHellman.setPublicKey(), for example). The +advantage of using this method is that the parties do not have to +generate nor exchange a group modulus beforehand, saving both processor +and communication time.

      +

      Example (obtaining a shared secret):

      +
      const crypto = require('crypto');
      +const alice = crypto.getDiffieHellman('modp14');
      +const bob = crypto.getDiffieHellman('modp14');
      +
      +alice.generateKeys();
      +bob.generateKeys();
      +
      +const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
      +const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
      +
      +/* aliceSecret and bobSecret should be the same */
      +console.log(aliceSecret === bobSecret);
      +

      crypto.getFips()#

      + +
        +
      • Returns: <number> 1 if and only if a FIPS compliant crypto provider is +currently in use, 0 otherwise. A future semver-major release may change +the return type of this API to a <boolean>.
      • +
      +

      crypto.getHashes()#

      + +
        +
      • Returns: <string[]> An array of the names of the supported hash algorithms, +such as 'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.
      • +
      +
      const hashes = crypto.getHashes();
      +console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
      +

      crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)#

      + + +

      Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) +implementation. A selected HMAC digest algorithm specified by digest is +applied to derive a key of the requested byte length (keylen) from the +password, salt and iterations.

      +

      The supplied callback function is called with two arguments: err and +derivedKey. If an error occurs while deriving the key, err will be set; +otherwise err will be null. By default, the successfully generated +derivedKey will be passed to the callback as a Buffer. An error will be +thrown if any of the input arguments specify invalid values or types.

      +

      If digest is null, 'sha1' will be used. This behavior is deprecated, +please specify a digest explicitly.

      +

      The iterations argument must be a number set as high as possible. The +higher the number of iterations, the more secure the derived key will be, +but will take a longer amount of time to complete.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +
      const crypto = require('crypto');
      +crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
      +});
      +

      The crypto.DEFAULT_ENCODING property can be used to change the way the +derivedKey is passed to the callback. This property, however, has been +deprecated and use should be avoided.

      +
      const crypto = require('crypto');
      +crypto.DEFAULT_ENCODING = 'hex';
      +crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey);  // '3745e48...aa39b34'
      +});
      +

      An array of supported digest functions can be retrieved using +crypto.getHashes().

      +

      This API uses libuv's threadpool, which can have surprising and +negative performance implications for some applications; see the +UV_THREADPOOL_SIZE documentation for more information.

      +

      crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)#

      + + +

      Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) +implementation. A selected HMAC digest algorithm specified by digest is +applied to derive a key of the requested byte length (keylen) from the +password, salt and iterations.

      +

      If an error occurs an Error will be thrown, otherwise the derived key will be +returned as a Buffer.

      +

      If digest is null, 'sha1' will be used. This behavior is deprecated, +please specify a digest explicitly.

      +

      The iterations argument must be a number set as high as possible. The +higher the number of iterations, the more secure the derived key will be, +but will take a longer amount of time to complete.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +
      const crypto = require('crypto');
      +const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
      +console.log(key.toString('hex'));  // '3745e48...08d59ae'
      +

      The crypto.DEFAULT_ENCODING property may be used to change the way the +derivedKey is returned. This property, however, is deprecated and use +should be avoided.

      +
      const crypto = require('crypto');
      +crypto.DEFAULT_ENCODING = 'hex';
      +const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
      +console.log(key);  // '3745e48...aa39b34'
      +

      An array of supported digest functions can be retrieved using +crypto.getHashes().

      +

      crypto.privateDecrypt(privateKey, buffer)#

      + + +

      Decrypts buffer with privateKey. buffer was previously encrypted using +the corresponding public key, for example using crypto.publicEncrypt().

      +

      If privateKey is not a KeyObject, this function behaves as if +privateKey had been passed to crypto.createPrivateKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_OAEP_PADDING.

      +

      crypto.privateEncrypt(privateKey, buffer)#

      + + +

      Encrypts buffer with privateKey. The returned data can be decrypted using +the corresponding public key, for example using crypto.publicDecrypt().

      +

      If privateKey is not a KeyObject, this function behaves as if +privateKey had been passed to crypto.createPrivateKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_PADDING.

      +

      crypto.publicDecrypt(key, buffer)#

      + + +

      Decrypts buffer with key.buffer was previously encrypted using +the corresponding private key, for example using crypto.privateEncrypt().

      +

      If key is not a KeyObject, this function behaves as if +key had been passed to crypto.createPublicKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_PADDING.

      +

      Because RSA public keys can be derived from private keys, a private key may +be passed instead of a public key.

      +

      crypto.publicEncrypt(key, buffer)#

      + + +

      Encrypts the content of buffer with key and returns a new +Buffer with encrypted content. The returned data can be decrypted using +the corresponding private key, for example using crypto.privateDecrypt().

      +

      If key is not a KeyObject, this function behaves as if +key had been passed to crypto.createPublicKey(). If it is an +object, the padding property can be passed. Otherwise, this function uses +RSA_PKCS1_OAEP_PADDING.

      +

      Because RSA public keys can be derived from private keys, a private key may +be passed instead of a public key.

      +

      crypto.randomBytes(size[, callback])#

      + + +

      Generates cryptographically strong pseudo-random data. The size argument +is a number indicating the number of bytes to generate.

      +

      If a callback function is provided, the bytes are generated asynchronously +and the callback function is invoked with two arguments: err and buf. +If an error occurs, err will be an Error object; otherwise it is null. The +buf argument is a Buffer containing the generated bytes.

      +
      // Asynchronous
      +const crypto = require('crypto');
      +crypto.randomBytes(256, (err, buf) => {
      +  if (err) throw err;
      +  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
      +});
      +

      If the callback function is not provided, the random bytes are generated +synchronously and returned as a Buffer. An error will be thrown if +there is a problem generating the bytes.

      +
      // Synchronous
      +const buf = crypto.randomBytes(256);
      +console.log(
      +  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
      +

      The crypto.randomBytes() method will not complete until there is +sufficient entropy available. +This should normally never take longer than a few milliseconds. The only time +when generating the random bytes may conceivably block for a longer period of +time is right after boot, when the whole system is still low on entropy.

      +

      This API uses libuv's threadpool, which can have surprising and +negative performance implications for some applications; see the +UV_THREADPOOL_SIZE documentation for more information.

      +

      The asynchronous version of crypto.randomBytes() is carried out in a single +threadpool request. To minimize threadpool task length variation, partition +large randomBytes requests when doing so as part of fulfilling a client +request.

      +

      crypto.randomFillSync(buffer[, offset][, size])#

      + + +

      Synchronous version of crypto.randomFill().

      +
      const buf = Buffer.alloc(10);
      +console.log(crypto.randomFillSync(buf).toString('hex'));
      +
      +crypto.randomFillSync(buf, 5);
      +console.log(buf.toString('hex'));
      +
      +// The above is equivalent to the following:
      +crypto.randomFillSync(buf, 5, 5);
      +console.log(buf.toString('hex'));
      +

      Any TypedArray or DataView instance may be passed as buffer.

      +
      const a = new Uint32Array(10);
      +console.log(Buffer.from(crypto.randomFillSync(a).buffer,
      +                        a.byteOffset, a.byteLength).toString('hex'));
      +
      +const b = new Float64Array(10);
      +console.log(Buffer.from(crypto.randomFillSync(b).buffer,
      +                        b.byteOffset, b.byteLength).toString('hex'));
      +
      +const c = new DataView(new ArrayBuffer(10));
      +console.log(Buffer.from(crypto.randomFillSync(c).buffer,
      +                        c.byteOffset, c.byteLength).toString('hex'));
      +

      crypto.randomFill(buffer[, offset][, size], callback)#

      + + +

      This function is similar to crypto.randomBytes() but requires the first +argument to be a Buffer that will be filled. It also +requires that a callback is passed in.

      +

      If the callback function is not provided, an error will be thrown.

      +
      const buf = Buffer.alloc(10);
      +crypto.randomFill(buf, (err, buf) => {
      +  if (err) throw err;
      +  console.log(buf.toString('hex'));
      +});
      +
      +crypto.randomFill(buf, 5, (err, buf) => {
      +  if (err) throw err;
      +  console.log(buf.toString('hex'));
      +});
      +
      +// The above is equivalent to the following:
      +crypto.randomFill(buf, 5, 5, (err, buf) => {
      +  if (err) throw err;
      +  console.log(buf.toString('hex'));
      +});
      +

      Any TypedArray or DataView instance may be passed as buffer.

      +
      const a = new Uint32Array(10);
      +crypto.randomFill(a, (err, buf) => {
      +  if (err) throw err;
      +  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
      +    .toString('hex'));
      +});
      +
      +const b = new Float64Array(10);
      +crypto.randomFill(b, (err, buf) => {
      +  if (err) throw err;
      +  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
      +    .toString('hex'));
      +});
      +
      +const c = new DataView(new ArrayBuffer(10));
      +crypto.randomFill(c, (err, buf) => {
      +  if (err) throw err;
      +  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
      +    .toString('hex'));
      +});
      +

      This API uses libuv's threadpool, which can have surprising and +negative performance implications for some applications; see the +UV_THREADPOOL_SIZE documentation for more information.

      +

      The asynchronous version of crypto.randomFill() is carried out in a single +threadpool request. To minimize threadpool task length variation, partition +large randomFill requests when doing so as part of fulfilling a client +request.

      +

      crypto.randomInt([min, ]max[, callback])#

      + +
        +
      • min <integer> Start of random range (inclusive). Default: 0.
      • +
      • max <integer> End of random range (exclusive).
      • +
      • callback <Function> function(err, n) {}.
      • +
      +

      Return a random integer n such that min <= n < max. This +implementation avoids modulo bias.

      +

      The range (max - min) must be less than 248. min and max must +be safe integers.

      +

      If the callback function is not provided, the random integer is +generated synchronously.

      +
      // Asynchronous
      +crypto.randomInt(3, (err, n) => {
      +  if (err) throw err;
      +  console.log(`Random number chosen from (0, 1, 2): ${n}`);
      +});
      +
      // Synchronous
      +const n = crypto.randomInt(3);
      +console.log(`Random number chosen from (0, 1, 2): ${n}`);
      +
      // With `min` argument
      +const n = crypto.randomInt(1, 7);
      +console.log(`The dice rolled: ${n}`);
      +

      crypto.scrypt(password, salt, keylen[, options], callback)#

      + + +

      Provides an asynchronous scrypt implementation. Scrypt is a password-based +key derivation function that is designed to be expensive computationally and +memory-wise in order to make brute-force attacks unrewarding.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +

      The callback function is called with two arguments: err and derivedKey. +err is an exception object when key derivation fails, otherwise err is +null. derivedKey is passed to the callback as a Buffer.

      +

      An exception is thrown when any of the input arguments specify invalid values +or types.

      +
      const crypto = require('crypto');
      +// Using the factory defaults.
      +crypto.scrypt('secret', 'salt', 64, (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
      +});
      +// Using a custom N parameter. Must be a power of two.
      +crypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
      +  if (err) throw err;
      +  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
      +});
      +

      crypto.scryptSync(password, salt, keylen[, options])#

      + + +

      Provides a synchronous scrypt implementation. Scrypt is a password-based +key derivation function that is designed to be expensive computationally and +memory-wise in order to make brute-force attacks unrewarding.

      +

      The salt should be as unique as possible. It is recommended that a salt is +random and at least 16 bytes long. See NIST SP 800-132 for details.

      +

      An exception is thrown when key derivation fails, otherwise the derived key is +returned as a Buffer.

      +

      An exception is thrown when any of the input arguments specify invalid values +or types.

      +
      const crypto = require('crypto');
      +// Using the factory defaults.
      +const key1 = crypto.scryptSync('secret', 'salt', 64);
      +console.log(key1.toString('hex'));  // '3745e48...08d59ae'
      +// Using a custom N parameter. Must be a power of two.
      +const key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 });
      +console.log(key2.toString('hex'));  // '3745e48...aa39b34'
      +

      crypto.setEngine(engine[, flags])#

      + + +

      Load and set the engine for some or all OpenSSL functions (selected by flags).

      +

      engine could be either an id or a path to the engine's shared library.

      +

      The optional flags argument uses ENGINE_METHOD_ALL by default. The flags +is a bit field taking one of or a mix of the following flags (defined in +crypto.constants):

      +
        +
      • crypto.constants.ENGINE_METHOD_RSA
      • +
      • crypto.constants.ENGINE_METHOD_DSA
      • +
      • crypto.constants.ENGINE_METHOD_DH
      • +
      • crypto.constants.ENGINE_METHOD_RAND
      • +
      • crypto.constants.ENGINE_METHOD_EC
      • +
      • crypto.constants.ENGINE_METHOD_CIPHERS
      • +
      • crypto.constants.ENGINE_METHOD_DIGESTS
      • +
      • crypto.constants.ENGINE_METHOD_PKEY_METHS
      • +
      • crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
      • +
      • crypto.constants.ENGINE_METHOD_ALL
      • +
      • crypto.constants.ENGINE_METHOD_NONE
      • +
      +

      The flags below are deprecated in OpenSSL-1.1.0.

      +
        +
      • crypto.constants.ENGINE_METHOD_ECDH
      • +
      • crypto.constants.ENGINE_METHOD_ECDSA
      • +
      • crypto.constants.ENGINE_METHOD_STORE
      • +
      +

      crypto.setFips(bool)#

      + + +

      Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. +Throws an error if FIPS mode is not available.

      +

      crypto.sign(algorithm, data, key)#

      + + +

      Calculates and returns the signature for data using the given private key and +algorithm. If algorithm is null or undefined, then the algorithm is +dependent upon the key type (especially Ed25519 and Ed448).

      +

      If key is not a KeyObject, this function behaves as if key had been +passed to crypto.createPrivateKey(). If it is an object, the following +additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to sign the message as specified in section 3.1 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the +maximum permissible value.

        +
      • +
      +

      crypto.timingSafeEqual(a, b)#

      + + +

      This function is based on a constant-time algorithm. +Returns true if a is equal to b, without leaking timing information that +would allow an attacker to guess one of the values. This is suitable for +comparing HMAC digests or secret values like authentication cookies or +capability urls.

      +

      a and b must both be Buffers, TypedArrays, or DataViews, and they +must have the same length.

      +

      Use of crypto.timingSafeEqual does not guarantee that the surrounding code +is timing-safe. Care should be taken to ensure that the surrounding code does +not introduce timing vulnerabilities.

      +

      crypto.verify(algorithm, data, key, signature)#

      + + +

      Verifies the given signature for data using the given key and algorithm. If +algorithm is null or undefined, then the algorithm is dependent upon the +key type (especially Ed25519 and Ed448).

      +

      If key is not a KeyObject, this function behaves as if key had been +passed to crypto.createPublicKey(). If it is an object, the following +additional properties can be passed:

      +
        +
      • +

        dsaEncoding <string> For DSA and ECDSA, this option specifies the +format of the generated signature. It can be one of the following:

        +
          +
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • +
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • +
        +
      • +
      • +

        padding <integer> Optional padding value for RSA, one of the following:

        +
          +
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • +
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • +
        +

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function +used to sign the message as specified in section 3.1 of RFC 4055.

        +
      • +
      • +

        saltLength <integer> Salt length for when padding is +RSA_PKCS1_PSS_PADDING. The special value +crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest +size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the +maximum permissible value.

        +
      • +
      +

      The signature argument is the previously calculated signature for the data.

      +

      Because public keys can be derived from private keys, a private key or a public +key may be passed for key.

      +

      Notes#

      +

      Legacy Streams API (prior to Node.js 0.10)#

      +

      The Crypto module was added to Node.js before there was the concept of a +unified Stream API, and before there were Buffer objects for handling +binary data. As such, the many of the crypto defined classes have methods not +typically found on other Node.js classes that implement the streams +API (e.g. update(), final(), or digest()). Also, many methods accepted +and returned 'latin1' encoded strings by default rather than Buffers. This +default was changed after Node.js v0.8 to use Buffer objects by default +instead.

      +

      Recent ECDH changes#

      +

      Usage of ECDH with non-dynamically generated key pairs has been simplified. +Now, ecdh.setPrivateKey() can be called with a preselected private key +and the associated public point (key) will be computed and stored in the object. +This allows code to only store and provide the private part of the EC key pair. +ecdh.setPrivateKey() now also validates that the private key is valid for +the selected curve.

      +

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the +API is not useful. Either a previously stored private key should be set, which +automatically generates the associated public key, or ecdh.generateKeys() +should be called. The main drawback of using ecdh.setPublicKey() is that +it can be used to put the ECDH key pair into an inconsistent state.

      +

      Support for weak or compromised algorithms#

      +

      The crypto module still supports some algorithms which are already +compromised and are not currently recommended for use. The API also allows +the use of ciphers and hashes with a small key size that are too weak for safe +use.

      +

      Users should take full responsibility for selecting the crypto +algorithm and key size according to their security requirements.

      +

      Based on the recommendations of NIST SP 800-131A:

      +
        +
      • MD5 and SHA-1 are no longer acceptable where collision resistance is +required such as digital signatures.
      • +
      • The key used with RSA, DSA, and DH algorithms is recommended to have +at least 2048 bits and that of the curve of ECDSA and ECDH at least +224 bits, to be safe to use for several years.
      • +
      • The DH groups of modp1, modp2 and modp5 have a key size +smaller than 2048 bits and are not recommended.
      • +
      +

      See the reference for other recommendations and details.

      +

      CCM mode#

      +

      CCM is one of the supported AEAD algorithms. Applications which use this +mode must adhere to certain restrictions when using the cipher API:

      +
        +
      • The authentication tag length must be specified during cipher creation by +setting the authTagLength option and must be one of 4, 6, 8, 10, 12, 14 or +16 bytes.
      • +
      • The length of the initialization vector (nonce) N must be between 7 and 13 +bytes (7 ≤ N ≤ 13).
      • +
      • The length of the plaintext is limited to 2 ** (8 * (15 - N)) bytes.
      • +
      • When decrypting, the authentication tag must be set via setAuthTag() before +calling update(). +Otherwise, decryption will fail and final() will throw an error in +compliance with section 2.6 of RFC 3610.
      • +
      • Using stream methods such as write(data), end(data) or pipe() in CCM +mode might fail as CCM cannot handle more than one chunk of data per instance.
      • +
      • When passing additional authenticated data (AAD), the length of the actual +message in bytes must be passed to setAAD() via the plaintextLength +option. +Many crypto libraries include the authentication tag in the ciphertext, +which means that they produce ciphertexts of the length +plaintextLength + authTagLength. Node.js does not include the authentication +tag, so the ciphertext length is always plaintextLength. +This is not necessary if no AAD is used.
      • +
      • As CCM processes the whole message at once, update() can only be called +once.
      • +
      • Even though calling update() is sufficient to encrypt/decrypt the message, +applications must call final() to compute or verify the +authentication tag.
      • +
      +
      const crypto = require('crypto');
      +
      +const key = 'keykeykeykeykeykeykeykey';
      +const nonce = crypto.randomBytes(12);
      +
      +const aad = Buffer.from('0123456789', 'hex');
      +
      +const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {
      +  authTagLength: 16
      +});
      +const plaintext = 'Hello world';
      +cipher.setAAD(aad, {
      +  plaintextLength: Buffer.byteLength(plaintext)
      +});
      +const ciphertext = cipher.update(plaintext, 'utf8');
      +cipher.final();
      +const tag = cipher.getAuthTag();
      +
      +// Now transmit { ciphertext, nonce, tag }.
      +
      +const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {
      +  authTagLength: 16
      +});
      +decipher.setAuthTag(tag);
      +decipher.setAAD(aad, {
      +  plaintextLength: ciphertext.length
      +});
      +const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
      +
      +try {
      +  decipher.final();
      +} catch (err) {
      +  console.error('Authentication failed!');
      +  return;
      +}
      +
      +console.log(receivedPlaintext);
      +

      Crypto constants#

      +

      The following constants exported by crypto.constants apply to various uses of +the crypto, tls, and https modules and are generally specific to OpenSSL.

      +

      OpenSSL options#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. See + https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html + for detail.
      SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode + for TLS v1.3
      SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched + clients or servers. See + https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CIPHER_SERVER_PREFERENCEAttempts to use the server's preferences instead of the client's when + selecting a cipher. Behavior depends on protocol version. See + https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER.
      SSL_OP_COOKIE_EXCHANGEInstructs OpenSSL to turn on cookie exchange.
      SSL_OP_CRYPTOPRO_TLSEXT_BUGInstructs OpenSSL to add server-hello extension from an early version + of the cryptopro draft.
      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability + workaround added in OpenSSL 0.9.6d.
      SSL_OP_EPHEMERAL_RSAInstructs OpenSSL to always use the tmp_rsa key when performing RSA + operations.
      SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
      SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
      SSL_OP_MICROSOFT_SESS_ID_BUG
      SSL_OP_MSIE_SSLV2_RSA_PADDINGInstructs OpenSSL to disable the workaround for a man-in-the-middle + protocol-version vulnerability in the SSL 2.0 server implementation.
      SSL_OP_NETSCAPE_CA_DN_BUG
      SSL_OP_NETSCAPE_CHALLENGE_BUG
      SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
      SSL_OP_NO_COMPRESSIONInstructs OpenSSL to disable support for SSL/TLS compression.
      SSL_OP_NO_ENCRYPT_THEN_MACInstructs OpenSSL to disable encrypt-then-MAC.
      SSL_OP_NO_QUERY_MTU
      SSL_OP_NO_RENEGOTIATIONInstructs OpenSSL to disable renegotiation.
      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATIONInstructs OpenSSL to always start a new session when performing + renegotiation.
      SSL_OP_NO_SSLv2Instructs OpenSSL to turn off SSL v2
      SSL_OP_NO_SSLv3Instructs OpenSSL to turn off SSL v3
      SSL_OP_NO_TICKETInstructs OpenSSL to disable use of RFC4507bis tickets.
      SSL_OP_NO_TLSv1Instructs OpenSSL to turn off TLS v1
      SSL_OP_NO_TLSv1_1Instructs OpenSSL to turn off TLS v1.1
      SSL_OP_NO_TLSv1_2Instructs OpenSSL to turn off TLS v1.2
      SSL_OP_NO_TLSv1_3Instructs OpenSSL to turn off TLS v1.3
      SSL_OP_PKCS1_CHECK_1
      SSL_OP_PKCS1_CHECK_2
      SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20Poly1305 + when client does. + This option has no effect if + SSL_OP_CIPHER_SERVER_PREFERENCE + is not enabled.
      SSL_OP_SINGLE_DH_USEInstructs OpenSSL to always create a new key when using + temporary/ephemeral DH parameters.
      SSL_OP_SINGLE_ECDH_USEInstructs OpenSSL to always create a new key when using + temporary/ephemeral ECDH parameters.
      SSL_OP_SSLEAY_080_CLIENT_DH_BUG
      SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
      SSL_OP_TLS_BLOCK_PADDING_BUG
      SSL_OP_TLS_D5_BUG
      SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.
      +

      OpenSSL engine constants#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      ENGINE_METHOD_RSALimit engine usage to RSA
      ENGINE_METHOD_DSALimit engine usage to DSA
      ENGINE_METHOD_DHLimit engine usage to DH
      ENGINE_METHOD_RANDLimit engine usage to RAND
      ENGINE_METHOD_ECLimit engine usage to EC
      ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
      ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
      ENGINE_METHOD_PKEY_METHSLimit engine usage to PKEY_METHDS
      ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
      ENGINE_METHOD_ALL
      ENGINE_METHOD_NONE
      +

      Other OpenSSL constants#

      +

      See the list of SSL OP Flags for details.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      DH_CHECK_P_NOT_SAFE_PRIME
      DH_CHECK_P_NOT_PRIME
      DH_UNABLE_TO_CHECK_GENERATOR
      DH_NOT_SUITABLE_GENERATOR
      ALPN_ENABLED
      RSA_PKCS1_PADDING
      RSA_SSLV23_PADDING
      RSA_NO_PADDING
      RSA_PKCS1_OAEP_PADDING
      RSA_X931_PADDING
      RSA_PKCS1_PSS_PADDING
      RSA_PSS_SALTLEN_DIGESTSets the salt length for RSA_PKCS1_PSS_PADDING to the + digest size when signing or verifying.
      RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the + maximum permissible value when signing data.
      RSA_PSS_SALTLEN_AUTOCauses the salt length for RSA_PKCS1_PSS_PADDING to be + determined automatically when verifying a signature.
      POINT_CONVERSION_COMPRESSED
      POINT_CONVERSION_UNCOMPRESSED
      POINT_CONVERSION_HYBRID
      +

      Node.js crypto constants#

      + + + + + + + + + + + + + +
      ConstantDescription
      defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
      defaultCipherListSpecifies the active default cipher list used by the current Node.js + process.
      + +
      +
      +
      + + diff --git a/doc/api/crypto.json b/doc/api/crypto.json new file mode 100644 index 0000000000000000000000000000000000000000..a3a19ea6a9e01f965ee7394da7728f3aac434689 --- /dev/null +++ b/doc/api/crypto.json @@ -0,0 +1,3954 @@ +{ + "type": "module", + "source": "doc/api/crypto.md", + "modules": [ + { + "textRaw": "Crypto", + "name": "crypto", + "introduced_in": "v0.3.6", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/crypto.js

      \n

      The crypto module provides cryptographic functionality that includes a set of\nwrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

      \n

      Use require('crypto') to access this module.

      \n
      const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n                   .update('I love cupcakes')\n                   .digest('hex');\nconsole.log(hash);\n// Prints:\n//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
      ", + "modules": [ + { + "textRaw": "Determining if crypto support is unavailable", + "name": "determining_if_crypto_support_is_unavailable", + "desc": "

      It is possible for Node.js to be built without including support for the\ncrypto module. In such cases, calling require('crypto') will result in an\nerror being thrown.

      \n
      let crypto;\ntry {\n  crypto = require('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\n
      ", + "type": "module", + "displayName": "Determining if crypto support is unavailable" + }, + { + "textRaw": "`crypto` module methods and properties", + "name": "`crypto`_module_methods_and_properties", + "properties": [ + { + "textRaw": "`constants` Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][].", + "type": "Object", + "name": "return", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][]." + }, + { + "textRaw": "`crypto.DEFAULT_ENCODING`", + "name": "DEFAULT_ENCODING", + "meta": { + "added": [ + "v0.9.3" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes methods\ndefault to Buffer objects.

      \n

      The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.

      \n

      New applications should expect the default to be 'buffer'.

      \n

      This property is deprecated.

      " + }, + { + "textRaw": "`crypto.fips`", + "name": "fips", + "meta": { + "added": [ + "v6.0.0" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Property for checking and controlling whether a FIPS compliant crypto provider\nis currently in use. Setting to true requires a FIPS build of Node.js.

      \n

      This property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.

      " + } + ], + "methods": [ + { + "textRaw": "`crypto.createCipher(algorithm, password[, options])`", + "type": "method", + "name": "createCipher", + "meta": { + "added": [ + "v0.1.94" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + }, + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20235", + "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`crypto.createCipheriv()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher}", + "name": "return", + "type": "Cipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`password` {string | Buffer | TypedArray | DataView}", + "name": "password", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Cipher object that uses the given algorithm and\npassword.

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.

      \n

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

      \n

      The password is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'latin1' encoded string, a Buffer, a\nTypedArray, or a DataView.

      \n

      The implementation of crypto.createCipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

      \n

      In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createCipheriv()\nto create the Cipher object. Users should not use ciphers with counter mode\n(e.g. CTR, GCM, or CCM) in crypto.createCipher(). A warning is emitted when\nthey are used in order to avoid the risk of IV reuse that causes\nvulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting\nAdversaries for details.

      " + }, + { + "textRaw": "`crypto.createCipheriv(algorithm, key, iv[, options])`", + "type": "method", + "name": "createCipheriv", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `key` argument can now be a `KeyObject`." + }, + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/24081", + "description": "The cipher `chacha20-poly1305` is now supported." + }, + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + }, + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20235", + "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18644", + "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher}", + "name": "return", + "type": "Cipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView | KeyObject}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView | KeyObject" + }, + { + "textRaw": "`iv` {string | Buffer | TypedArray | DataView | null}", + "name": "iv", + "type": "string | Buffer | TypedArray | DataView | null" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.

      \n

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

      \n

      The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.

      \n

      Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a\ngiven IV will be.

      " + }, + { + "textRaw": "`crypto.createDecipher(algorithm, password[, options])`", + "type": "method", + "name": "createDecipher", + "meta": { + "added": [ + "v0.1.94" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`crypto.createDecipheriv()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher}", + "name": "return", + "type": "Decipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`password` {string | Buffer | TypedArray | DataView}", + "name": "password", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Decipher object that uses the given algorithm and\npassword (key).

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.

      \n

      The implementation of crypto.createDecipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

      \n

      In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createDecipheriv()\nto create the Decipher object.

      " + }, + { + "textRaw": "`crypto.createDecipheriv(algorithm, key, iv[, options])`", + "type": "method", + "name": "createDecipheriv", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `key` argument can now be a `KeyObject`." + }, + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/24081", + "description": "The cipher `chacha20-poly1305` is now supported." + }, + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/21447", + "description": "Ciphers in OCB mode are now supported." + }, + { + "version": "v10.2.0", + "pr-url": "https://github.com/nodejs/node/pull/20039", + "description": "The `authTagLength` option can now be used to restrict accepted GCM authentication tag lengths." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18644", + "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher}", + "name": "return", + "type": "Decipher" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView | KeyObject}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView | KeyObject" + }, + { + "textRaw": "`iv` {string | Buffer | TypedArray | DataView | null}", + "name": "iv", + "type": "string | Buffer | TypedArray | DataView | null" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).

      \n

      The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to restrict accepted authentication tags\nto those with the specified length.

      \n

      The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

      \n

      The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.

      \n

      Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a given\nIV will be.

      " + }, + { + "textRaw": "`crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])`", + "type": "method", + "name": "createDiffieHellman", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `prime` argument can be any `TypedArray` or `DataView` now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11983", + "description": "The `prime` argument can be a `Uint8Array` now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default for the encoding parameters changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellman}", + "name": "return", + "type": "DiffieHellman" + }, + "params": [ + { + "textRaw": "`prime` {string | Buffer | TypedArray | DataView}", + "name": "prime", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`primeEncoding` {string} The [encoding][] of the `prime` string.", + "name": "primeEncoding", + "type": "string", + "desc": "The [encoding][] of the `prime` string." + }, + { + "textRaw": "`generator` {number | string | Buffer | TypedArray | DataView} **Default:** `2`", + "name": "generator", + "type": "number | string | Buffer | TypedArray | DataView", + "default": "`2`" + }, + { + "textRaw": "`generatorEncoding` {string} The [encoding][] of the `generator` string.", + "name": "generatorEncoding", + "type": "string", + "desc": "The [encoding][] of the `generator` string." + } + ] + } + ], + "desc": "

      Creates a DiffieHellman key exchange object using the supplied prime and an\noptional specific generator.

      \n

      The generator argument can be a number, string, or Buffer. If\ngenerator is not specified, the value 2 is used.

      \n

      If primeEncoding is specified, prime is expected to be a string; otherwise\na Buffer, TypedArray, or DataView is expected.

      \n

      If generatorEncoding is specified, generator is expected to be a string;\notherwise a number, Buffer, TypedArray, or DataView is expected.

      " + }, + { + "textRaw": "`crypto.createDiffieHellman(primeLength[, generator])`", + "type": "method", + "name": "createDiffieHellman", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellman}", + "name": "return", + "type": "DiffieHellman" + }, + "params": [ + { + "textRaw": "`primeLength` {number}", + "name": "primeLength", + "type": "number" + }, + { + "textRaw": "`generator` {number} **Default:** `2`", + "name": "generator", + "type": "number", + "default": "`2`" + } + ] + } + ], + "desc": "

      Creates a DiffieHellman key exchange object and generates a prime of\nprimeLength bits using an optional specific numeric generator.\nIf generator is not specified, the value 2 is used.

      " + }, + { + "textRaw": "`crypto.createDiffieHellmanGroup(name)`", + "type": "method", + "name": "createDiffieHellmanGroup", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellmanGroup}", + "name": "return", + "type": "DiffieHellmanGroup" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      An alias for crypto.getDiffieHellman()

      " + }, + { + "textRaw": "`crypto.createECDH(curveName)`", + "type": "method", + "name": "createECDH", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ECDH}", + "name": "return", + "type": "ECDH" + }, + "params": [ + { + "textRaw": "`curveName` {string}", + "name": "curveName", + "type": "string" + } + ] + } + ], + "desc": "

      Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curveName string. Use\ncrypto.getCurves() to obtain a list of available curve names. On recent\nOpenSSL releases, openssl ecparam -list_curves will also display the name\nand description of each available elliptic curve.

      " + }, + { + "textRaw": "`crypto.createHash(algorithm[, options])`", + "type": "method", + "name": "createHash", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28805", + "description": "The `outputLength` option was added for XOF hash functions." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Hash}", + "name": "return", + "type": "Hash" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm. Optional options argument controls stream\nbehavior. For XOF hash functions such as 'shake256', the outputLength option\ncan be used to specify the desired output length in bytes.

      \n

      The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

      \n

      Example: generating the sha256 sum of a file

      \n
      const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hash.update(data);\n  else {\n    console.log(`${hash.digest('hex')} ${filename}`);\n  }\n});\n
      " + }, + { + "textRaw": "`crypto.createHmac(algorithm, key[, options])`", + "type": "method", + "name": "createHmac", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `key` argument can now be a `KeyObject`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Hmac}", + "name": "return", + "type": "Hmac" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView | KeyObject}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView | KeyObject" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates and returns an Hmac object that uses the given algorithm and key.\nOptional options argument controls stream behavior.

      \n

      The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

      \n

      The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret.

      \n

      Example: generating the sha256 HMAC of a file

      \n
      const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hmac.update(data);\n  else {\n    console.log(`${hmac.digest('hex')} ${filename}`);\n  }\n});\n
      " + }, + { + "textRaw": "`crypto.createPrivateKey(key)`", + "type": "method", + "name": "createPrivateKey", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {KeyObject}", + "name": "return", + "type": "KeyObject" + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer}", + "name": "key", + "type": "Object | string | Buffer", + "options": [ + { + "textRaw": "`key`: {string | Buffer} The key material, either in PEM or DER format.", + "name": "key", + "type": "string | Buffer", + "desc": "The key material, either in PEM or DER format." + }, + { + "textRaw": "`format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`.", + "name": "format", + "type": "string", + "default": "`'pem'`", + "desc": "Must be `'pem'` or `'der'`." + }, + { + "textRaw": "`type`: {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored if it is `'pem'`.", + "name": "type", + "type": "string", + "desc": "Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored if it is `'pem'`." + }, + { + "textRaw": "`passphrase`: {string | Buffer} The passphrase to use for decryption.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "The passphrase to use for decryption." + } + ] + } + ] + } + ], + "desc": "

      Creates and returns a new key object containing a private key. If key is a\nstring or Buffer, format is assumed to be 'pem'; otherwise, key\nmust be an object with the properties described above.

      \n

      If the private key is encrypted, a passphrase must be specified. The length\nof the passphrase is limited to 1024 bytes.

      " + }, + { + "textRaw": "`crypto.createPublicKey(key)`", + "type": "method", + "name": "createPublicKey", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [ + { + "version": "v11.13.0", + "pr-url": "https://github.com/nodejs/node/pull/26278", + "description": "The `key` argument can now be a `KeyObject` with type `private`." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25217", + "description": "The `key` argument can now be a private key." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {KeyObject}", + "name": "return", + "type": "KeyObject" + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`key`: {string | Buffer}", + "name": "key", + "type": "string | Buffer" + }, + { + "textRaw": "`format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`.", + "name": "format", + "type": "string", + "default": "`'pem'`", + "desc": "Must be `'pem'` or `'der'`." + }, + { + "textRaw": "`type`: {string} Must be `'pkcs1'` or `'spki'`. This option is required only if the `format` is `'der'`.", + "name": "type", + "type": "string", + "desc": "Must be `'pkcs1'` or `'spki'`. This option is required only if the `format` is `'der'`." + } + ] + } + ] + } + ], + "desc": "

      Creates and returns a new key object containing a public key. If key is a\nstring or Buffer, format is assumed to be 'pem'; if key is a KeyObject\nwith type 'private', the public key is derived from the given private key;\notherwise, key must be an object with the properties described above.

      \n

      If the format is 'pem', the 'key' may also be an X.509 certificate.

      \n

      Because public keys can be derived from private keys, a private key may be\npassed instead of a public key. In that case, this function behaves as if\ncrypto.createPrivateKey() had been called, except that the type of the\nreturned KeyObject will be 'public' and that the private key cannot be\nextracted from the returned KeyObject. Similarly, if a KeyObject with type\n'private' is given, a new KeyObject with type 'public' will be returned\nand it will be impossible to extract the private key from the returned object.

      " + }, + { + "textRaw": "`crypto.createSecretKey(key)`", + "type": "method", + "name": "createSecretKey", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {KeyObject}", + "name": "return", + "type": "KeyObject" + }, + "params": [ + { + "textRaw": "`key` {Buffer}", + "name": "key", + "type": "Buffer" + } + ] + } + ], + "desc": "

      Creates and returns a new key object containing a secret key for symmetric\nencryption or Hmac.

      " + }, + { + "textRaw": "`crypto.createSign(algorithm[, options])`", + "type": "method", + "name": "createSign", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Sign}", + "name": "return", + "type": "Sign" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`options` {Object} [`stream.Writable` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.Writable` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Sign object that uses the given algorithm. Use\ncrypto.getHashes() to obtain the names of the available digest algorithms.\nOptional options argument controls the stream.Writable behavior.

      \n

      In some cases, a Sign instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.

      " + }, + { + "textRaw": "`crypto.createVerify(algorithm[, options])`", + "type": "method", + "name": "createVerify", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Verify}", + "name": "return", + "type": "Verify" + }, + "params": [ + { + "textRaw": "`algorithm` {string}", + "name": "algorithm", + "type": "string" + }, + { + "textRaw": "`options` {Object} [`stream.Writable` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.Writable` options][]" + } + ] + } + ], + "desc": "

      Creates and returns a Verify object that uses the given algorithm.\nUse crypto.getHashes() to obtain an array of names of the available\nsigning algorithms. Optional options argument controls the\nstream.Writable behavior.

      \n

      In some cases, a Verify instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.

      " + }, + { + "textRaw": "`crypto.diffieHellman(options)`", + "type": "method", + "name": "diffieHellman", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`privateKey`: {KeyObject}", + "name": "privateKey", + "type": "KeyObject" + }, + { + "textRaw": "`publicKey`: {KeyObject}", + "name": "publicKey", + "type": "KeyObject" + } + ] + } + ] + } + ], + "desc": "

      Computes the Diffie-Hellman secret based on a privateKey and a publicKey.\nBoth keys must have the same asymmetricKeyType, which must be one of 'dh'\n(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).

      " + }, + { + "textRaw": "`crypto.generateKeyPair(type, options, callback)`", + "type": "method", + "name": "generateKeyPair", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31178", + "description": "Add support for Diffie-Hellman." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26774", + "description": "Add ability to generate X25519 and X448 key pairs." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26554", + "description": "Add ability to generate Ed25519 and Ed448 key pairs." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", + "name": "type", + "type": "string", + "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." + }, + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", + "name": "modulusLength", + "type": "number", + "desc": "Key size in bits (RSA, DSA)." + }, + { + "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", + "name": "publicExponent", + "type": "number", + "default": "`0x10001`", + "desc": "Public exponent (RSA)." + }, + { + "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", + "name": "divisorLength", + "type": "number", + "desc": "Size of `q` in bits (DSA)." + }, + { + "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", + "name": "namedCurve", + "type": "string", + "desc": "Name of the curve to use (EC)." + }, + { + "textRaw": "`prime`: {Buffer} The prime parameter (DH).", + "name": "prime", + "type": "Buffer", + "desc": "The prime parameter (DH)." + }, + { + "textRaw": "`primeLength`: {number} Prime length in bits (DH).", + "name": "primeLength", + "type": "number", + "desc": "Prime length in bits (DH)." + }, + { + "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", + "name": "generator", + "type": "number", + "default": "`2`", + "desc": "Custom generator (DH)." + }, + { + "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", + "name": "groupName", + "type": "string", + "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." + }, + { + "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "publicKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + }, + { + "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "privateKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + } + ] + }, + { + "textRaw": "`callback`: {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err`: {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`publicKey`: {string | Buffer | KeyObject}", + "name": "publicKey", + "type": "string | Buffer | KeyObject" + }, + { + "textRaw": "`privateKey`: {string | Buffer | KeyObject}", + "name": "privateKey", + "type": "string | Buffer | KeyObject" + } + ] + } + ] + } + ], + "desc": "

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

      \n

      If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.

      \n

      It is recommended to encode public keys as 'spki' and private keys as\n'pkcs8' with encryption for long-term storage:

      \n
      const { generateKeyPair } = require('crypto');\ngenerateKeyPair('rsa', {\n  modulusLength: 4096,\n  publicKeyEncoding: {\n    type: 'spki',\n    format: 'pem'\n  },\n  privateKeyEncoding: {\n    type: 'pkcs8',\n    format: 'pem',\n    cipher: 'aes-256-cbc',\n    passphrase: 'top secret'\n  }\n}, (err, publicKey, privateKey) => {\n  // Handle errors and use the generated key pair.\n});\n
      \n

      On completion, callback will be called with err set to undefined and\npublicKey / privateKey representing the generated key pair.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with publicKey and privateKey properties.

      " + }, + { + "textRaw": "`crypto.generateKeyPairSync(type, options)`", + "type": "method", + "name": "generateKeyPairSync", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31178", + "description": "Add support for Diffie-Hellman." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26554", + "description": "Add ability to generate Ed25519 and Ed448 key pairs." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`publicKey`: {string | Buffer | KeyObject}", + "name": "publicKey", + "type": "string | Buffer | KeyObject" + }, + { + "textRaw": "`privateKey`: {string | Buffer | KeyObject}", + "name": "privateKey", + "type": "string | Buffer | KeyObject" + } + ] + }, + "params": [ + { + "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", + "name": "type", + "type": "string", + "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." + }, + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", + "name": "modulusLength", + "type": "number", + "desc": "Key size in bits (RSA, DSA)." + }, + { + "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", + "name": "publicExponent", + "type": "number", + "default": "`0x10001`", + "desc": "Public exponent (RSA)." + }, + { + "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", + "name": "divisorLength", + "type": "number", + "desc": "Size of `q` in bits (DSA)." + }, + { + "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", + "name": "namedCurve", + "type": "string", + "desc": "Name of the curve to use (EC)." + }, + { + "textRaw": "`prime`: {Buffer} The prime parameter (DH).", + "name": "prime", + "type": "Buffer", + "desc": "The prime parameter (DH)." + }, + { + "textRaw": "`primeLength`: {number} Prime length in bits (DH).", + "name": "primeLength", + "type": "number", + "desc": "Prime length in bits (DH)." + }, + { + "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", + "name": "generator", + "type": "number", + "default": "`2`", + "desc": "Custom generator (DH)." + }, + { + "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", + "name": "groupName", + "type": "string", + "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." + }, + { + "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "publicKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + }, + { + "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", + "name": "privateKeyEncoding", + "type": "Object", + "desc": "See [`keyObject.export()`][]." + } + ] + } + ] + } + ], + "desc": "

      Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

      \n

      If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.

      \n

      When encoding public keys, it is recommended to use 'spki'. When encoding\nprivate keys, it is recommended to use 'pkcs8' with a strong passphrase,\nand to keep the passphrase confidential.

      \n
      const { generateKeyPairSync } = require('crypto');\nconst { publicKey, privateKey } = generateKeyPairSync('rsa', {\n  modulusLength: 4096,\n  publicKeyEncoding: {\n    type: 'spki',\n    format: 'pem'\n  },\n  privateKeyEncoding: {\n    type: 'pkcs8',\n    format: 'pem',\n    cipher: 'aes-256-cbc',\n    passphrase: 'top secret'\n  }\n});\n
      \n

      The return value { publicKey, privateKey } represents the generated key pair.\nWhen PEM encoding was selected, the respective key will be a string, otherwise\nit will be a buffer containing the data encoded as DER.

      " + }, + { + "textRaw": "`crypto.getCiphers()`", + "type": "method", + "name": "getCiphers", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]} An array with the names of the supported cipher algorithms.", + "name": "return", + "type": "string[]", + "desc": "An array with the names of the supported cipher algorithms." + }, + "params": [] + } + ], + "desc": "
      const ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
      " + }, + { + "textRaw": "`crypto.getCurves()`", + "type": "method", + "name": "getCurves", + "meta": { + "added": [ + "v2.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]} An array with the names of the supported elliptic curves.", + "name": "return", + "type": "string[]", + "desc": "An array with the names of the supported elliptic curves." + }, + "params": [] + } + ], + "desc": "
      const curves = crypto.getCurves();\nconsole.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
      " + }, + { + "textRaw": "`crypto.getDiffieHellman(groupName)`", + "type": "method", + "name": "getDiffieHellman", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {DiffieHellmanGroup}", + "name": "return", + "type": "DiffieHellmanGroup" + }, + "params": [ + { + "textRaw": "`groupName` {string}", + "name": "groupName", + "type": "string" + } + ] + } + ], + "desc": "

      Creates a predefined DiffieHellmanGroup key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in\nRFC 2412, but see Caveats) and 'modp14', 'modp15',\n'modp16', 'modp17', 'modp18' (defined in RFC 3526). The\nreturned object mimics the interface of objects created by\ncrypto.createDiffieHellman(), but will not allow changing\nthe keys (with diffieHellman.setPublicKey(), for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.

      \n

      Example (obtaining a shared secret):

      \n
      const crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
      " + }, + { + "textRaw": "`crypto.getFips()`", + "type": "method", + "name": "getFips", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.", + "name": "return", + "type": "number", + "desc": "`1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}." + }, + "params": [] + } + ] + }, + { + "textRaw": "`crypto.getHashes()`", + "type": "method", + "name": "getHashes", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]} An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms.", + "name": "return", + "type": "string[]", + "desc": "An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms." + }, + "params": [] + } + ], + "desc": "
      const hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
      " + }, + { + "textRaw": "`crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`", + "type": "method", + "name": "pbkdf2", + "meta": { + "added": [ + "v0.5.5" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11305", + "description": "The `digest` parameter is always required now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4047", + "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`iterations` {number}", + "name": "iterations", + "type": "number" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`digest` {string}", + "name": "digest", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`derivedKey` {Buffer}", + "name": "derivedKey", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest is\napplied to derive a key of the requested byte length (keylen) from the\npassword, salt and iterations.

      \n

      The supplied callback function is called with two arguments: err and\nderivedKey. If an error occurs while deriving the key, err will be set;\notherwise err will be null. By default, the successfully generated\nderivedKey will be passed to the callback as a Buffer. An error will be\nthrown if any of the input arguments specify invalid values or types.

      \n

      If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

      \n

      The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n
      const crypto = require('crypto');\ncrypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'\n});\n
      \n

      The crypto.DEFAULT_ENCODING property can be used to change the way the\nderivedKey is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.

      \n
      const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey);  // '3745e48...aa39b34'\n});\n
      \n

      An array of supported digest functions can be retrieved using\ncrypto.getHashes().

      \n

      This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.

      " + }, + { + "textRaw": "`crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)`", + "type": "method", + "name": "pbkdf2Sync", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4047", + "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`iterations` {number}", + "name": "iterations", + "type": "number" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`digest` {string}", + "name": "digest", + "type": "string" + } + ] + } + ], + "desc": "

      Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest is\napplied to derive a key of the requested byte length (keylen) from the\npassword, salt and iterations.

      \n

      If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a Buffer.

      \n

      If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

      \n

      The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n
      const crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...08d59ae'\n
      \n

      The crypto.DEFAULT_ENCODING property may be used to change the way the\nderivedKey is returned. This property, however, is deprecated and use\nshould be avoided.

      \n
      const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key);  // '3745e48...aa39b34'\n
      \n

      An array of supported digest functions can be retrieved using\ncrypto.getHashes().

      " + }, + { + "textRaw": "`crypto.privateDecrypt(privateKey, buffer)`", + "type": "method", + "name": "privateDecrypt", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29489", + "description": "The `oaepLabel` option was added." + }, + { + "version": "v12.9.0", + "pr-url": "https://github.com/nodejs/node/pull/28335", + "description": "The `oaepHash` option was added." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the decrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the decrypted content." + }, + "params": [ + { + "textRaw": "`privateKey` {Object | string | Buffer | KeyObject}", + "name": "privateKey", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'`", + "name": "oaepHash", + "type": "string", + "default": "`'sha1'`", + "desc": "The hash function to use for OAEP padding and MGF1." + }, + { + "textRaw": "`oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP padding. If not specified, no label is used.", + "name": "oaepLabel", + "type": "Buffer | TypedArray | DataView", + "desc": "The label to use for OAEP padding. If not specified, no label is used." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Decrypts buffer with privateKey. buffer was previously encrypted using\nthe corresponding public key, for example using crypto.publicEncrypt().

      \n

      If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.

      " + }, + { + "textRaw": "`crypto.privateEncrypt(privateKey, buffer)`", + "type": "method", + "name": "privateEncrypt", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the encrypted content." + }, + "params": [ + { + "textRaw": "`privateKey` {Object | string | Buffer | KeyObject}", + "name": "privateKey", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`key` {string | Buffer | KeyObject} A PEM encoded private key.", + "name": "key", + "type": "string | Buffer | KeyObject", + "desc": "A PEM encoded private key." + }, + { + "textRaw": "`passphrase` {string | Buffer} An optional passphrase for the private key.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "An optional passphrase for the private key." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Encrypts buffer with privateKey. The returned data can be decrypted using\nthe corresponding public key, for example using crypto.publicDecrypt().

      \n

      If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.

      " + }, + { + "textRaw": "`crypto.publicDecrypt(key, buffer)`", + "type": "method", + "name": "publicDecrypt", + "meta": { + "added": [ + "v1.1.0" + ], + "changes": [ + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the decrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the decrypted content." + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`passphrase` {string | Buffer} An optional passphrase for the private key.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "An optional passphrase for the private key." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Decrypts buffer with key.buffer was previously encrypted using\nthe corresponding private key, for example using crypto.privateEncrypt().

      \n

      If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.

      \n

      Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

      " + }, + { + "textRaw": "`crypto.publicEncrypt(key, buffer)`", + "type": "method", + "name": "publicEncrypt", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29489", + "description": "The `oaepLabel` option was added." + }, + { + "version": "v12.9.0", + "pr-url": "https://github.com/nodejs/node/pull/28335", + "description": "The `oaepHash` option was added." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", + "name": "return", + "type": "Buffer", + "desc": "A new `Buffer` with the encrypted content." + }, + "params": [ + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`key` {string | Buffer | KeyObject} A PEM encoded public or private key.", + "name": "key", + "type": "string | Buffer | KeyObject", + "desc": "A PEM encoded public or private key." + }, + { + "textRaw": "`oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'`", + "name": "oaepHash", + "type": "string", + "default": "`'sha1'`", + "desc": "The hash function to use for OAEP padding and MGF1." + }, + { + "textRaw": "`oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP padding. If not specified, no label is used.", + "name": "oaepLabel", + "type": "Buffer | TypedArray | DataView", + "desc": "The label to use for OAEP padding. If not specified, no label is used." + }, + { + "textRaw": "`passphrase` {string | Buffer} An optional passphrase for the private key.", + "name": "passphrase", + "type": "string | Buffer", + "desc": "An optional passphrase for the private key." + }, + { + "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", + "name": "padding", + "type": "crypto.constants", + "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." + } + ] + }, + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Encrypts the content of buffer with key and returns a new\nBuffer with encrypted content. The returned data can be decrypted using\nthe corresponding private key, for example using crypto.privateDecrypt().

      \n

      If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.

      \n

      Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

      " + }, + { + "textRaw": "`crypto.randomBytes(size[, callback])`", + "type": "method", + "name": "randomBytes", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16454", + "description": "Passing `null` as the `callback` argument now throws `ERR_INVALID_CALLBACK`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", + "name": "return", + "type": "Buffer", + "desc": "if the `callback` function is not provided." + }, + "params": [ + { + "textRaw": "`size` {number}", + "name": "size", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`buf` {Buffer}", + "name": "buf", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Generates cryptographically strong pseudo-random data. The size argument\nis a number indicating the number of bytes to generate.

      \n

      If a callback function is provided, the bytes are generated asynchronously\nand the callback function is invoked with two arguments: err and buf.\nIf an error occurs, err will be an Error object; otherwise it is null. The\nbuf argument is a Buffer containing the generated bytes.

      \n
      // Asynchronous\nconst crypto = require('crypto');\ncrypto.randomBytes(256, (err, buf) => {\n  if (err) throw err;\n  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n
      \n

      If the callback function is not provided, the random bytes are generated\nsynchronously and returned as a Buffer. An error will be thrown if\nthere is a problem generating the bytes.

      \n
      // Synchronous\nconst buf = crypto.randomBytes(256);\nconsole.log(\n  `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
      \n

      The crypto.randomBytes() method will not complete until there is\nsufficient entropy available.\nThis should normally never take longer than a few milliseconds. The only time\nwhen generating the random bytes may conceivably block for a longer period of\ntime is right after boot, when the whole system is still low on entropy.

      \n

      This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.

      \n

      The asynchronous version of crypto.randomBytes() is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomBytes requests when doing so as part of fulfilling a client\nrequest.

      " + }, + { + "textRaw": "`crypto.randomFillSync(buffer[, offset][, size])`", + "type": "method", + "name": "randomFillSync", + "meta": { + "added": [ + "v7.10.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15231", + "description": "The `buffer` argument may be any `TypedArray` or `DataView`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|TypedArray|DataView} The object passed as `buffer` argument.", + "name": "return", + "type": "Buffer|TypedArray|DataView", + "desc": "The object passed as `buffer` argument." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} Must be supplied.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "Must be supplied." + }, + { + "textRaw": "`offset` {number} **Default:** `0`", + "name": "offset", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`size` {number} **Default:** `buffer.length - offset`", + "name": "size", + "type": "number", + "default": "`buffer.length - offset`" + } + ] + } + ], + "desc": "

      Synchronous version of crypto.randomFill().

      \n
      const buf = Buffer.alloc(10);\nconsole.log(crypto.randomFillSync(buf).toString('hex'));\n\ncrypto.randomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\ncrypto.randomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
      \n

      Any TypedArray or DataView instance may be passed as buffer.

      \n
      const a = new Uint32Array(10);\nconsole.log(Buffer.from(crypto.randomFillSync(a).buffer,\n                        a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new Float64Array(10);\nconsole.log(Buffer.from(crypto.randomFillSync(b).buffer,\n                        b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(crypto.randomFillSync(c).buffer,\n                        c.byteOffset, c.byteLength).toString('hex'));\n
      " + }, + { + "textRaw": "`crypto.randomFill(buffer[, offset][, size], callback)`", + "type": "method", + "name": "randomFill", + "meta": { + "added": [ + "v7.10.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15231", + "description": "The `buffer` argument may be any `TypedArray` or `DataView`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} Must be supplied.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "Must be supplied." + }, + { + "textRaw": "`offset` {number} **Default:** `0`", + "name": "offset", + "type": "number", + "default": "`0`" + }, + { + "textRaw": "`size` {number} **Default:** `buffer.length - offset`", + "name": "size", + "type": "number", + "default": "`buffer.length - offset`" + }, + { + "textRaw": "`callback` {Function} `function(err, buf) {}`.", + "name": "callback", + "type": "Function", + "desc": "`function(err, buf) {}`." + } + ] + } + ], + "desc": "

      This function is similar to crypto.randomBytes() but requires the first\nargument to be a Buffer that will be filled. It also\nrequires that a callback is passed in.

      \n

      If the callback function is not provided, an error will be thrown.

      \n
      const buf = Buffer.alloc(10);\ncrypto.randomFill(buf, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\ncrypto.randomFill(buf, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\ncrypto.randomFill(buf, 5, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n
      \n

      Any TypedArray or DataView instance may be passed as buffer.

      \n
      const a = new Uint32Array(10);\ncrypto.randomFill(a, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst b = new Float64Array(10);\ncrypto.randomFill(b, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst c = new DataView(new ArrayBuffer(10));\ncrypto.randomFill(c, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n
      \n

      This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.

      \n

      The asynchronous version of crypto.randomFill() is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomFill requests when doing so as part of fulfilling a client\nrequest.

      " + }, + { + "textRaw": "`crypto.randomInt([min, ]max[, callback])`", + "type": "method", + "name": "randomInt", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`min` {integer} Start of random range (inclusive). **Default**: `0`.", + "name": "min", + "type": "integer", + "desc": "Start of random range (inclusive). **Default**: `0`." + }, + { + "textRaw": "`max` {integer} End of random range (exclusive).", + "name": "max", + "type": "integer", + "desc": "End of random range (exclusive)." + }, + { + "textRaw": "`callback` {Function} `function(err, n) {}`.", + "name": "callback", + "type": "Function", + "desc": "`function(err, n) {}`." + } + ] + } + ], + "desc": "

      Return a random integer n such that min <= n < max. This\nimplementation avoids modulo bias.

      \n

      The range (max - min) must be less than 248. min and max must\nbe safe integers.

      \n

      If the callback function is not provided, the random integer is\ngenerated synchronously.

      \n
      // Asynchronous\ncrypto.randomInt(3, (err, n) => {\n  if (err) throw err;\n  console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n
      \n
      // Synchronous\nconst n = crypto.randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
      \n
      // With `min` argument\nconst n = crypto.randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
      " + }, + { + "textRaw": "`crypto.scrypt(password, salt, keylen[, options], callback)`", + "type": "method", + "name": "scrypt", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28799", + "description": "The `maxmem` value can now be any safe integer." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21525", + "description": "The `cost`, `blockSize` and `parallelization` option names have been added." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", + "name": "cost", + "type": "number", + "default": "`16384`", + "desc": "CPU/memory cost parameter. Must be a power of two greater than one." + }, + { + "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", + "name": "blockSize", + "type": "number", + "default": "`8`", + "desc": "Block size parameter." + }, + { + "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", + "name": "parallelization", + "type": "number", + "default": "`1`", + "desc": "Parallelization parameter." + }, + { + "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", + "name": "N", + "type": "number", + "desc": "Alias for `cost`. Only one of both may be specified." + }, + { + "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", + "name": "r", + "type": "number", + "desc": "Alias for `blockSize`. Only one of both may be specified." + }, + { + "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", + "name": "p", + "type": "number", + "desc": "Alias for `parallelization`. Only one of both may be specified." + }, + { + "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", + "name": "maxmem", + "type": "number", + "default": "`32 * 1024 * 1024`", + "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`derivedKey` {Buffer}", + "name": "derivedKey", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Provides an asynchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n

      The callback function is called with two arguments: err and derivedKey.\nerr is an exception object when key derivation fails, otherwise err is\nnull. derivedKey is passed to the callback as a Buffer.

      \n

      An exception is thrown when any of the input arguments specify invalid values\nor types.

      \n
      const crypto = require('crypto');\n// Using the factory defaults.\ncrypto.scrypt('secret', 'salt', 64, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\ncrypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'\n});\n
      " + }, + { + "textRaw": "`crypto.scryptSync(password, salt, keylen[, options])`", + "type": "method", + "name": "scryptSync", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28799", + "description": "The `maxmem` value can now be any safe integer." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21525", + "description": "The `cost`, `blockSize` and `parallelization` option names have been added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`password` {string|Buffer|TypedArray|DataView}", + "name": "password", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", + "name": "salt", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`keylen` {number}", + "name": "keylen", + "type": "number" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", + "name": "cost", + "type": "number", + "default": "`16384`", + "desc": "CPU/memory cost parameter. Must be a power of two greater than one." + }, + { + "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", + "name": "blockSize", + "type": "number", + "default": "`8`", + "desc": "Block size parameter." + }, + { + "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", + "name": "parallelization", + "type": "number", + "default": "`1`", + "desc": "Parallelization parameter." + }, + { + "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", + "name": "N", + "type": "number", + "desc": "Alias for `cost`. Only one of both may be specified." + }, + { + "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", + "name": "r", + "type": "number", + "desc": "Alias for `blockSize`. Only one of both may be specified." + }, + { + "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", + "name": "p", + "type": "number", + "desc": "Alias for `parallelization`. Only one of both may be specified." + }, + { + "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", + "name": "maxmem", + "type": "number", + "default": "`32 * 1024 * 1024`", + "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." + } + ] + } + ] + } + ], + "desc": "

      Provides a synchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.

      \n

      The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.

      \n

      An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.

      \n

      An exception is thrown when any of the input arguments specify invalid values\nor types.

      \n
      const crypto = require('crypto');\n// Using the factory defaults.\nconst key1 = crypto.scryptSync('secret', 'salt', 64);\nconsole.log(key1.toString('hex'));  // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex'));  // '3745e48...aa39b34'\n
      " + }, + { + "textRaw": "`crypto.setEngine(engine[, flags])`", + "type": "method", + "name": "setEngine", + "meta": { + "added": [ + "v0.11.11" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`engine` {string}", + "name": "engine", + "type": "string" + }, + { + "textRaw": "`flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`", + "name": "flags", + "type": "crypto.constants", + "default": "`crypto.constants.ENGINE_METHOD_ALL`" + } + ] + } + ], + "desc": "

      Load and set the engine for some or all OpenSSL functions (selected by flags).

      \n

      engine could be either an id or a path to the engine's shared library.

      \n

      The optional flags argument uses ENGINE_METHOD_ALL by default. The flags\nis a bit field taking one of or a mix of the following flags (defined in\ncrypto.constants):

      \n
        \n
      • crypto.constants.ENGINE_METHOD_RSA
      • \n
      • crypto.constants.ENGINE_METHOD_DSA
      • \n
      • crypto.constants.ENGINE_METHOD_DH
      • \n
      • crypto.constants.ENGINE_METHOD_RAND
      • \n
      • crypto.constants.ENGINE_METHOD_EC
      • \n
      • crypto.constants.ENGINE_METHOD_CIPHERS
      • \n
      • crypto.constants.ENGINE_METHOD_DIGESTS
      • \n
      • crypto.constants.ENGINE_METHOD_PKEY_METHS
      • \n
      • crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
      • \n
      • crypto.constants.ENGINE_METHOD_ALL
      • \n
      • crypto.constants.ENGINE_METHOD_NONE
      • \n
      \n

      The flags below are deprecated in OpenSSL-1.1.0.

      \n
        \n
      • crypto.constants.ENGINE_METHOD_ECDH
      • \n
      • crypto.constants.ENGINE_METHOD_ECDSA
      • \n
      • crypto.constants.ENGINE_METHOD_STORE
      • \n
      " + }, + { + "textRaw": "`crypto.setFips(bool)`", + "type": "method", + "name": "setFips", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`bool` {boolean} `true` to enable FIPS mode.", + "name": "bool", + "type": "boolean", + "desc": "`true` to enable FIPS mode." + } + ] + } + ], + "desc": "

      Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.\nThrows an error if FIPS mode is not available.

      " + }, + { + "textRaw": "`crypto.sign(algorithm, data, key)`", + "type": "method", + "name": "sign", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`algorithm` {string | null | undefined}", + "name": "algorithm", + "type": "string | null | undefined" + }, + { + "textRaw": "`data` {Buffer | TypedArray | DataView}", + "name": "data", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject" + } + ] + } + ], + "desc": "

      Calculates and returns the signature for data using the given private key and\nalgorithm. If algorithm is null or undefined, then the algorithm is\ndependent upon the key type (especially Ed25519 and Ed448).

      \n

      If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPrivateKey(). If it is an object, the following\nadditional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.

        \n
      • \n
      " + }, + { + "textRaw": "`crypto.timingSafeEqual(a, b)`", + "type": "method", + "name": "timingSafeEqual", + "meta": { + "added": [ + "v6.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`a` {Buffer | TypedArray | DataView}", + "name": "a", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`b` {Buffer | TypedArray | DataView}", + "name": "b", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      This function is based on a constant-time algorithm.\nReturns true if a is equal to b, without leaking timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.

      \n

      a and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same length.

      \n

      Use of crypto.timingSafeEqual does not guarantee that the surrounding code\nis timing-safe. Care should be taken to ensure that the surrounding code does\nnot introduce timing vulnerabilities.

      " + }, + { + "textRaw": "`crypto.verify(algorithm, data, key, signature)`", + "type": "method", + "name": "verify", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`algorithm` {string | null | undefined}", + "name": "algorithm", + "type": "string | null | undefined" + }, + { + "textRaw": "`data` {Buffer | TypedArray | DataView}", + "name": "data", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`key` {Object | string | Buffer | KeyObject}", + "name": "key", + "type": "Object | string | Buffer | KeyObject" + }, + { + "textRaw": "`signature` {Buffer | TypedArray | DataView}", + "name": "signature", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      Verifies the given signature for data using the given key and algorithm. If\nalgorithm is null or undefined, then the algorithm is dependent upon the\nkey type (especially Ed25519 and Ed448).

      \n

      If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPublicKey(). If it is an object, the following\nadditional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.

        \n
      • \n
      \n

      The signature argument is the previously calculated signature for the data.

      \n

      Because public keys can be derived from private keys, a private key or a public\nkey may be passed for key.

      " + } + ], + "type": "module", + "displayName": "`crypto` module methods and properties" + }, + { + "textRaw": "Notes", + "name": "notes", + "modules": [ + { + "textRaw": "Legacy Streams API (prior to Node.js 0.10)", + "name": "legacy_streams_api_(prior_to_node.js_0.10)", + "desc": "

      The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data. As such, the many of the crypto defined classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update(), final(), or digest()). Also, many methods accepted\nand returned 'latin1' encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use Buffer objects by default\ninstead.

      ", + "type": "module", + "displayName": "Legacy Streams API (prior to Node.js 0.10)" + }, + { + "textRaw": "Recent ECDH changes", + "name": "recent_ecdh_changes", + "desc": "

      Usage of ECDH with non-dynamically generated key pairs has been simplified.\nNow, ecdh.setPrivateKey() can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\necdh.setPrivateKey() now also validates that the private key is valid for\nthe selected curve.

      \n

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful. Either a previously stored private key should be set, which\nautomatically generates the associated public key, or ecdh.generateKeys()\nshould be called. The main drawback of using ecdh.setPublicKey() is that\nit can be used to put the ECDH key pair into an inconsistent state.

      ", + "type": "module", + "displayName": "Recent ECDH changes" + }, + { + "textRaw": "Support for weak or compromised algorithms", + "name": "support_for_weak_or_compromised_algorithms", + "desc": "

      The crypto module still supports some algorithms which are already\ncompromised and are not currently recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are too weak for safe\nuse.

      \n

      Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.

      \n

      Based on the recommendations of NIST SP 800-131A:

      \n
        \n
      • MD5 and SHA-1 are no longer acceptable where collision resistance is\nrequired such as digital signatures.
      • \n
      • The key used with RSA, DSA, and DH algorithms is recommended to have\nat least 2048 bits and that of the curve of ECDSA and ECDH at least\n224 bits, to be safe to use for several years.
      • \n
      • The DH groups of modp1, modp2 and modp5 have a key size\nsmaller than 2048 bits and are not recommended.
      • \n
      \n

      See the reference for other recommendations and details.

      ", + "type": "module", + "displayName": "Support for weak or compromised algorithms" + }, + { + "textRaw": "CCM mode", + "name": "ccm_mode", + "desc": "

      CCM is one of the supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:

      \n
        \n
      • The authentication tag length must be specified during cipher creation by\nsetting the authTagLength option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.
      • \n
      • The length of the initialization vector (nonce) N must be between 7 and 13\nbytes (7 ≤ N ≤ 13).
      • \n
      • The length of the plaintext is limited to 2 ** (8 * (15 - N)) bytes.
      • \n
      • When decrypting, the authentication tag must be set via setAuthTag() before\ncalling update().\nOtherwise, decryption will fail and final() will throw an error in\ncompliance with section 2.6 of RFC 3610.
      • \n
      • Using stream methods such as write(data), end(data) or pipe() in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.
      • \n
      • When passing additional authenticated data (AAD), the length of the actual\nmessage in bytes must be passed to setAAD() via the plaintextLength\noption.\nMany crypto libraries include the authentication tag in the ciphertext,\nwhich means that they produce ciphertexts of the length\nplaintextLength + authTagLength. Node.js does not include the authentication\ntag, so the ciphertext length is always plaintextLength.\nThis is not necessary if no AAD is used.
      • \n
      • As CCM processes the whole message at once, update() can only be called\nonce.
      • \n
      • Even though calling update() is sufficient to encrypt/decrypt the message,\napplications must call final() to compute or verify the\nauthentication tag.
      • \n
      \n
      const crypto = require('crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = crypto.randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n  plaintextLength: Buffer.byteLength(plaintext)\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n  plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n  decipher.final();\n} catch (err) {\n  console.error('Authentication failed!');\n  return;\n}\n\nconsole.log(receivedPlaintext);\n
      ", + "type": "module", + "displayName": "CCM mode" + } + ], + "type": "module", + "displayName": "Notes" + }, + { + "textRaw": "Crypto constants", + "name": "crypto_constants", + "desc": "

      The following constants exported by crypto.constants apply to various uses of\nthe crypto, tls, and https modules and are generally specific to OpenSSL.

      ", + "modules": [ + { + "textRaw": "OpenSSL options", + "name": "openssl_options", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\n for detail.
      SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode\n for TLS v1.3
      SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CIPHER_SERVER_PREFERENCEAttempts to use the server's preferences instead of the client's when\n selecting a cipher. Behavior depends on protocol version. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
      SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's \"speshul\" version of DTLS_BAD_VER.
      SSL_OP_COOKIE_EXCHANGEInstructs OpenSSL to turn on cookie exchange.
      SSL_OP_CRYPTOPRO_TLSEXT_BUGInstructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft.
      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d.
      SSL_OP_EPHEMERAL_RSAInstructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations.
      SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
      SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
      SSL_OP_MICROSOFT_SESS_ID_BUG
      SSL_OP_MSIE_SSLV2_RSA_PADDINGInstructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation.
      SSL_OP_NETSCAPE_CA_DN_BUG
      SSL_OP_NETSCAPE_CHALLENGE_BUG
      SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
      SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
      SSL_OP_NO_COMPRESSIONInstructs OpenSSL to disable support for SSL/TLS compression.
      SSL_OP_NO_ENCRYPT_THEN_MACInstructs OpenSSL to disable encrypt-then-MAC.
      SSL_OP_NO_QUERY_MTU
      SSL_OP_NO_RENEGOTIATIONInstructs OpenSSL to disable renegotiation.
      SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATIONInstructs OpenSSL to always start a new session when performing\n renegotiation.
      SSL_OP_NO_SSLv2Instructs OpenSSL to turn off SSL v2
      SSL_OP_NO_SSLv3Instructs OpenSSL to turn off SSL v3
      SSL_OP_NO_TICKETInstructs OpenSSL to disable use of RFC4507bis tickets.
      SSL_OP_NO_TLSv1Instructs OpenSSL to turn off TLS v1
      SSL_OP_NO_TLSv1_1Instructs OpenSSL to turn off TLS v1.1
      SSL_OP_NO_TLSv1_2Instructs OpenSSL to turn off TLS v1.2
      SSL_OP_NO_TLSv1_3Instructs OpenSSL to turn off TLS v1.3
      SSL_OP_PKCS1_CHECK_1
      SSL_OP_PKCS1_CHECK_2
      SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20Poly1305\n when client does.\n This option has no effect if\n SSL_OP_CIPHER_SERVER_PREFERENCE\n is not enabled.
      SSL_OP_SINGLE_DH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters.
      SSL_OP_SINGLE_ECDH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters.
      SSL_OP_SSLEAY_080_CLIENT_DH_BUG
      SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
      SSL_OP_TLS_BLOCK_PADDING_BUG
      SSL_OP_TLS_D5_BUG
      SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.
      ", + "type": "module", + "displayName": "OpenSSL options" + }, + { + "textRaw": "OpenSSL engine constants", + "name": "openssl_engine_constants", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      ENGINE_METHOD_RSALimit engine usage to RSA
      ENGINE_METHOD_DSALimit engine usage to DSA
      ENGINE_METHOD_DHLimit engine usage to DH
      ENGINE_METHOD_RANDLimit engine usage to RAND
      ENGINE_METHOD_ECLimit engine usage to EC
      ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
      ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
      ENGINE_METHOD_PKEY_METHSLimit engine usage to PKEY_METHDS
      ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
      ENGINE_METHOD_ALL
      ENGINE_METHOD_NONE
      ", + "type": "module", + "displayName": "OpenSSL engine constants" + }, + { + "textRaw": "Other OpenSSL constants", + "name": "other_openssl_constants", + "desc": "

      See the list of SSL OP Flags for details.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      DH_CHECK_P_NOT_SAFE_PRIME
      DH_CHECK_P_NOT_PRIME
      DH_UNABLE_TO_CHECK_GENERATOR
      DH_NOT_SUITABLE_GENERATOR
      ALPN_ENABLED
      RSA_PKCS1_PADDING
      RSA_SSLV23_PADDING
      RSA_NO_PADDING
      RSA_PKCS1_OAEP_PADDING
      RSA_X931_PADDING
      RSA_PKCS1_PSS_PADDING
      RSA_PSS_SALTLEN_DIGESTSets the salt length for RSA_PKCS1_PSS_PADDING to the\n digest size when signing or verifying.
      RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the\n maximum permissible value when signing data.
      RSA_PSS_SALTLEN_AUTOCauses the salt length for RSA_PKCS1_PSS_PADDING to be\n determined automatically when verifying a signature.
      POINT_CONVERSION_COMPRESSED
      POINT_CONVERSION_UNCOMPRESSED
      POINT_CONVERSION_HYBRID
      ", + "type": "module", + "displayName": "Other OpenSSL constants" + }, + { + "textRaw": "Node.js crypto constants", + "name": "node.js_crypto_constants", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
      defaultCipherListSpecifies the active default cipher list used by the current Node.js\n process.
      ", + "type": "module", + "displayName": "Node.js crypto constants" + } + ], + "type": "module", + "displayName": "Crypto constants" + } + ], + "classes": [ + { + "textRaw": "Class: `Certificate`", + "type": "class", + "name": "Certificate", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen element.

      \n

      <keygen> is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.

      \n

      The crypto module provides the Certificate class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.

      ", + "methods": [ + { + "textRaw": "`Certificate.exportChallenge(spkac)`", + "type": "method", + "name": "exportChallenge", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
      " + }, + { + "textRaw": "`Certificate.exportPublicKey(spkac[, encoding])`", + "type": "method", + "name": "exportPublicKey", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `spkac` string." + } + ] + } + ], + "desc": "
      const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
      " + }, + { + "textRaw": "`Certificate.verifySpkac(spkac)`", + "type": "method", + "name": "verifySpkac", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if the given `spkac` data structure is valid, `false` otherwise." + }, + "params": [ + { + "textRaw": "`spkac` {Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
      " + } + ], + "modules": [ + { + "textRaw": "Legacy API", + "name": "legacy_api", + "desc": "

      As a still supported legacy interface, it is possible to create new instances of\nthe crypto.Certificate class as illustrated in the examples below.

      ", + "ctors": [ + { + "textRaw": "`new crypto.Certificate()`", + "type": "ctor", + "name": "crypto.Certificate", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:

      \n
      const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n
      " + } + ], + "methods": [ + { + "textRaw": "`certificate.exportChallenge(spkac)`", + "type": "method", + "name": "exportChallenge", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
      " + }, + { + "textRaw": "`certificate.exportPublicKey(spkac)`", + "type": "method", + "name": "exportPublicKey", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.", + "name": "return", + "type": "Buffer", + "desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge." + }, + "params": [ + { + "textRaw": "`spkac` {string | Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "string | Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
      " + }, + { + "textRaw": "`certificate.verifySpkac(spkac)`", + "type": "method", + "name": "verifySpkac", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if the given `spkac` data structure is valid, `false` otherwise." + }, + "params": [ + { + "textRaw": "`spkac` {Buffer | TypedArray | DataView}", + "name": "spkac", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "
      const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
      " + } + ], + "type": "module", + "displayName": "Legacy API" + } + ] + }, + { + "textRaw": "Class: `Cipher`", + "type": "class", + "name": "Cipher", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "desc": "\n

      Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where plain unencrypted\ndata is written to produce encrypted data on the readable side, or
      • \n
      • Using the cipher.update() and cipher.final() methods to produce\nthe encrypted data.
      • \n
      \n

      The crypto.createCipher() or crypto.createCipheriv() methods are\nused to create Cipher instances. Cipher objects are not to be created\ndirectly using the new keyword.

      \n

      Example: Using Cipher objects as streams:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes()` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nlet encrypted = '';\ncipher.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = cipher.read())) {\n    encrypted += chunk.toString('hex');\n  }\n});\ncipher.on('end', () => {\n  console.log(encrypted);\n  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa\n});\n\ncipher.write('some clear text data');\ncipher.end();\n
      \n

      Example: Using Cipher and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes()` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nconst input = fs.createReadStream('test.js');\nconst output = fs.createWriteStream('test.enc');\n\ninput.pipe(cipher).pipe(output);\n
      \n

      Example: Using the cipher.update() and cipher.final() methods:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nlet encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa\n
      ", + "methods": [ + { + "textRaw": "`cipher.final([outputEncoding])`", + "type": "method", + "name": "final", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.", + "name": "return", + "type": "Buffer | string", + "desc": "Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned." + }, + "params": [ + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Once the cipher.final() method has been called, the Cipher object can no\nlonger be used to encrypt data. Attempts to call cipher.final() more than\nonce will result in an error being thrown.

      " + }, + { + "textRaw": "`cipher.setAAD(buffer[, options])`", + "type": "method", + "name": "setAAD", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher} for method chaining.", + "name": "return", + "type": "Cipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]", + "options": [ + { + "textRaw": "`plaintextLength` {number}", + "name": "plaintextLength", + "type": "number" + } + ] + } + ] + } + ], + "desc": "

      When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

      \n

      The options argument is optional for GCM and OCB. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the plaintext in bytes. See CCM mode.

      \n

      The cipher.setAAD() method must be called before cipher.update().

      " + }, + { + "textRaw": "`cipher.getAuthTag()`", + "type": "method", + "name": "getAuthTag", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data.", + "name": "return", + "type": "Buffer", + "desc": "When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data." + }, + "params": [] + } + ], + "desc": "

      The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.

      " + }, + { + "textRaw": "`cipher.setAutoPadding([autoPadding])`", + "type": "method", + "name": "setAutoPadding", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Cipher} for method chaining.", + "name": "return", + "type": "Cipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`autoPadding` {boolean} **Default:** `true`", + "name": "autoPadding", + "type": "boolean", + "default": "`true`" + } + ] + } + ], + "desc": "

      When using block encryption algorithms, the Cipher class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false).

      \n

      When autoPadding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or cipher.final() will throw an error.\nDisabling automatic padding is useful for non-standard padding, for instance\nusing 0x0 instead of PKCS padding.

      \n

      The cipher.setAutoPadding() method must be called before\ncipher.final().

      " + }, + { + "textRaw": "`cipher.update(data[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the data.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the data." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Updates the cipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer, TypedArray, or\nDataView. If data is a Buffer, TypedArray, or DataView, then\ninputEncoding is ignored.

      \n

      The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.

      \n

      The cipher.update() method can be called multiple times with new data until\ncipher.final() is called. Calling cipher.update() after\ncipher.final() will result in an error being thrown.

      " + } + ] + }, + { + "textRaw": "Class: `Decipher`", + "type": "class", + "name": "Decipher", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "desc": "\n

      Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where plain encrypted\ndata is written to produce unencrypted data on the readable side, or
      • \n
      • Using the decipher.update() and decipher.final() methods to\nproduce the unencrypted data.
      • \n
      \n

      The crypto.createDecipher() or crypto.createDecipheriv() methods are\nused to create Decipher instances. Decipher objects are not to be created\ndirectly using the new keyword.

      \n

      Example: Using Decipher objects as streams:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n  while (null !== (chunk = decipher.read())) {\n    decrypted += chunk.toString('utf8');\n  }\n});\ndecipher.on('end', () => {\n  console.log(decrypted);\n  // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
      \n

      Example: Using Decipher and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\nconst input = fs.createReadStream('test.enc');\nconst output = fs.createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n
      \n

      Example: Using the decipher.update() and decipher.final() methods:

      \n
      const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = crypto.createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
      ", + "methods": [ + { + "textRaw": "`decipher.final([outputEncoding])`", + "type": "method", + "name": "final", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.", + "name": "return", + "type": "Buffer | string", + "desc": "Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned." + }, + "params": [ + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Once the decipher.final() method has been called, the Decipher object can\nno longer be used to decrypt data. Attempts to call decipher.final() more\nthan once will result in an error being thrown.

      " + }, + { + "textRaw": "`decipher.setAAD(buffer[, options])`", + "type": "method", + "name": "setAAD", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9398", + "description": "This method now returns a reference to `decipher`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher} for method chaining.", + "name": "return", + "type": "Decipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + }, + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]", + "options": [ + { + "textRaw": "`plaintextLength` {number}", + "name": "plaintextLength", + "type": "number" + } + ] + } + ] + } + ], + "desc": "

      When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

      \n

      The options argument is optional for GCM. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the ciphertext in bytes. See CCM mode.

      \n

      The decipher.setAAD() method must be called before decipher.update().

      " + }, + { + "textRaw": "`decipher.setAuthTag(buffer)`", + "type": "method", + "name": "setAuthTag", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17825", + "description": "This method now throws if the GCM tag length is invalid." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9398", + "description": "This method now returns a reference to `decipher`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher} for method chaining.", + "name": "return", + "type": "Decipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`buffer` {Buffer | TypedArray | DataView}", + "name": "buffer", + "type": "Buffer | TypedArray | DataView" + } + ] + } + ], + "desc": "

      When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAuthTag() method is used to pass in the\nreceived authentication tag. If no tag is provided, or if the cipher text\nhas been tampered with, decipher.final() will throw, indicating that the\ncipher text should be discarded due to failed authentication. If the tag length\nis invalid according to NIST SP 800-38D or does not match the value of the\nauthTagLength option, decipher.setAuthTag() will throw an error.

      \n

      The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes.\ndecipher.setAuthTag() can only be called once.

      " + }, + { + "textRaw": "`decipher.setAutoPadding([autoPadding])`", + "type": "method", + "name": "setAutoPadding", + "meta": { + "added": [ + "v0.7.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Decipher} for method chaining.", + "name": "return", + "type": "Decipher", + "desc": "for method chaining." + }, + "params": [ + { + "textRaw": "`autoPadding` {boolean} **Default:** `true`", + "name": "autoPadding", + "type": "boolean", + "default": "`true`" + } + ] + } + ], + "desc": "

      When data has been encrypted without standard block padding, calling\ndecipher.setAutoPadding(false) will disable automatic padding to prevent\ndecipher.final() from checking for and removing padding.

      \n

      Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.

      \n

      The decipher.setAutoPadding() method must be called before\ndecipher.final().

      " + }, + { + "textRaw": "`decipher.update(data[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Updates the decipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then inputEncoding is ignored.

      \n

      The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.

      \n

      The decipher.update() method can be called multiple times with new data until\ndecipher.final() is called. Calling decipher.update() after\ndecipher.final() will result in an error being thrown.

      " + } + ] + }, + { + "textRaw": "Class: `DiffieHellman`", + "type": "class", + "name": "DiffieHellman", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "desc": "

      The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.

      \n

      Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.

      \n
      const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
      ", + "methods": [ + { + "textRaw": "`diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "computeSecret", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`otherPublicKey` {string | Buffer | TypedArray | DataView}", + "name": "otherPublicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of an `otherPublicKey` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of an `otherPublicKey` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified inputEncoding, and secret is\nencoded using specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.generateKeys([encoding])`", + "type": "method", + "name": "generateKeys", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party.\nIf encoding is provided a string is returned; otherwise a\nBuffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getGenerator([encoding])`", + "type": "method", + "name": "getGenerator", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getPrime([encoding])`", + "type": "method", + "name": "getPrime", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getPrivateKey([encoding])`", + "type": "method", + "name": "getPrivateKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.getPublicKey([encoding])`", + "type": "method", + "name": "getPublicKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

      " + }, + { + "textRaw": "`diffieHellman.setPrivateKey(privateKey[, encoding])`", + "type": "method", + "name": "setPrivateKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`privateKey` {string | Buffer | TypedArray | DataView}", + "name": "privateKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `privateKey` string." + } + ] + } + ], + "desc": "

      Sets the Diffie-Hellman private key. If the encoding argument is provided,\nprivateKey is expected\nto be a string. If no encoding is provided, privateKey is expected\nto be a Buffer, TypedArray, or DataView.

      " + }, + { + "textRaw": "`diffieHellman.setPublicKey(publicKey[, encoding])`", + "type": "method", + "name": "setPublicKey", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`publicKey` {string | Buffer | TypedArray | DataView}", + "name": "publicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `publicKey` string." + } + ] + } + ], + "desc": "

      Sets the Diffie-Hellman public key. If the encoding argument is provided,\npublicKey is expected\nto be a string. If no encoding is provided, publicKey is expected\nto be a Buffer, TypedArray, or DataView.

      " + } + ], + "properties": [ + { + "textRaw": "`diffieHellman.verifyError`", + "name": "verifyError", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [] + }, + "desc": "

      A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.

      \n

      The following values are valid for this property (as defined in constants\nmodule):

      \n
        \n
      • DH_CHECK_P_NOT_SAFE_PRIME
      • \n
      • DH_CHECK_P_NOT_PRIME
      • \n
      • DH_UNABLE_TO_CHECK_GENERATOR
      • \n
      • DH_NOT_SUITABLE_GENERATOR
      • \n
      " + } + ] + }, + { + "textRaw": "Class: `DiffieHellmanGroup`", + "type": "class", + "name": "DiffieHellmanGroup", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "desc": "

      The DiffieHellmanGroup class takes a well-known modp group as its argument but\notherwise works the same as DiffieHellman.

      \n
      const name = 'modp1';\nconst dh = crypto.createDiffieHellmanGroup(name);\n
      \n

      name is taken from RFC 2412 (modp1 and 2) and RFC 3526:

      \n
      $ perl -ne 'print \"$1\\n\" if /\"(modp\\d+)\"/' src/node_crypto_groups.h\nmodp1  #  768 bits\nmodp2  # 1024 bits\nmodp5  # 1536 bits\nmodp14 # 2048 bits\nmodp15 # etc.\nmodp16\nmodp17\nmodp18\n
      " + }, + { + "textRaw": "Class: `ECDH`", + "type": "class", + "name": "ECDH", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "desc": "

      The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.

      \n

      Instances of the ECDH class can be created using the\ncrypto.createECDH() function.

      \n
      const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n
      ", + "classMethods": [ + { + "textRaw": "Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])`", + "type": "classMethod", + "name": "convertKey", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`key` {string | Buffer | TypedArray | DataView}", + "name": "key", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`curve` {string}", + "name": "curve", + "type": "string" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `key` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `key` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + }, + { + "textRaw": "`format` {string} **Default:** `'uncompressed'`", + "name": "format", + "type": "string", + "default": "`'uncompressed'`" + } + ] + } + ], + "desc": "

      Converts the EC Diffie-Hellman public key specified by key and curve to the\nformat specified by format. The format argument specifies point encoding\nand can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is\ninterpreted using the specified inputEncoding, and the returned key is encoded\nusing the specified outputEncoding.

      \n

      Use crypto.getCurves() to obtain a list of available curve names.\nOn recent OpenSSL releases, openssl ecparam -list_curves will also display\nthe name and description of each available elliptic curve.

      \n

      If format is not specified the point will be returned in 'uncompressed'\nformat.

      \n

      If the inputEncoding is not provided, key is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      Example (uncompressing a key):

      \n
      const { createECDH, ECDH } = require('crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n                                        'secp256k1',\n                                        'hex',\n                                        'hex',\n                                        'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
      " + } + ], + "methods": [ + { + "textRaw": "`ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`", + "type": "method", + "name": "computeSecret", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`" + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16849", + "description": "Changed error format to better support invalid public key error" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`otherPublicKey` {string | Buffer | TypedArray | DataView}", + "name": "otherPublicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `otherPublicKey` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `otherPublicKey` string." + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified inputEncoding, and the returned secret\nis encoded using the specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer, TypedArray, or\nDataView.

      \n

      If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.

      \n

      ecdh.computeSecret will throw an\nERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey\nlies outside of the elliptic curve. Since otherPublicKey is\nusually supplied from a remote user over an insecure network,\nbe sure to handle this exception accordingly.

      " + }, + { + "textRaw": "`ecdh.generateKeys([encoding[, format]])`", + "type": "method", + "name": "generateKeys", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + }, + { + "textRaw": "`format` {string} **Default:** `'uncompressed'`", + "name": "format", + "type": "string", + "default": "`'uncompressed'`" + } + ] + } + ], + "desc": "

      Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format and encoding. This key should be\ntransferred to the other party.

      \n

      The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified, the point will be returned in\n'uncompressed' format.

      \n

      If encoding is provided a string is returned; otherwise a Buffer\nis returned.

      " + }, + { + "textRaw": "`ecdh.getPrivateKey([encoding])`", + "type": "method", + "name": "getPrivateKey", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.", + "name": "return", + "type": "Buffer | string", + "desc": "The EC Diffie-Hellman in the specified `encoding`." + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

      " + }, + { + "textRaw": "`ecdh.getPublicKey([encoding][, format])`", + "type": "method", + "name": "getPublicKey", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified `encoding` and `format`.", + "name": "return", + "type": "Buffer | string", + "desc": "The EC Diffie-Hellman public key in the specified `encoding` and `format`." + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + }, + { + "textRaw": "`format` {string} **Default:** `'uncompressed'`", + "name": "format", + "type": "string", + "default": "`'uncompressed'`" + } + ] + } + ], + "desc": "

      The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified the point will be returned in\n'uncompressed' format.

      \n

      If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

      " + }, + { + "textRaw": "`ecdh.setPrivateKey(privateKey[, encoding])`", + "type": "method", + "name": "setPrivateKey", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`privateKey` {string | Buffer | TypedArray | DataView}", + "name": "privateKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `privateKey` string." + } + ] + } + ], + "desc": "

      Sets the EC Diffie-Hellman private key.\nIf encoding is provided, privateKey is expected\nto be a string; otherwise privateKey is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      If privateKey is not valid for the curve specified when the ECDH object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH object.

      " + }, + { + "textRaw": "`ecdh.setPublicKey(publicKey[, encoding])`", + "type": "method", + "name": "setPublicKey", + "meta": { + "added": [ + "v0.11.14" + ], + "deprecated": [ + "v5.2.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "signatures": [ + { + "params": [ + { + "textRaw": "`publicKey` {string | Buffer | TypedArray | DataView}", + "name": "publicKey", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the `publicKey` string." + } + ] + } + ], + "desc": "

      Sets the EC Diffie-Hellman public key.\nIf encoding is provided publicKey is expected to\nbe a string; otherwise a Buffer, TypedArray, or DataView is expected.

      \n

      There is not normally a reason to call this method because ECDH\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys() or\necdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method\nattempts to generate the public point/key associated with the private key being\nset.

      \n

      Example (obtaining a shared secret):

      \n
      const crypto = require('crypto');\nconst alice = crypto.createECDH('secp256k1');\nconst bob = crypto.createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n  crypto.createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
      " + } + ] + }, + { + "textRaw": "Class: `Hash`", + "type": "class", + "name": "Hash", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "desc": "\n

      The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where data is written\nto produce a computed hash digest on the readable side, or
      • \n
      • Using the hash.update() and hash.digest() methods to produce the\ncomputed hash.
      • \n
      \n

      The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.

      \n

      Example: Using Hash objects as streams:

      \n
      const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = hash.read();\n  if (data) {\n    console.log(data.toString('hex'));\n    // Prints:\n    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n  }\n});\n\nhash.write('some data to hash');\nhash.end();\n
      \n

      Example: Using Hash and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hash).pipe(process.stdout);\n
      \n

      Example: Using the hash.update() and hash.digest() methods:

      \n
      const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
      ", + "methods": [ + { + "textRaw": "`hash.copy([options])`", + "type": "method", + "name": "copy", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Hash}", + "name": "return", + "type": "Hash" + }, + "params": [ + { + "textRaw": "`options` {Object} [`stream.transform` options][]", + "name": "options", + "type": "Object", + "desc": "[`stream.transform` options][]" + } + ] + } + ], + "desc": "

      Creates a new Hash object that contains a deep copy of the internal state\nof the current Hash object.

      \n

      The optional options argument controls stream behavior. For XOF hash\nfunctions such as 'shake256', the outputLength option can be used to\nspecify the desired output length in bytes.

      \n

      An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.

      \n
      // Calculate a rolling hash.\nconst crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n
      " + }, + { + "textRaw": "`hash.digest([encoding])`", + "type": "method", + "name": "digest", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method).\nIf encoding is provided a string will be returned; otherwise\na Buffer is returned.

      \n

      The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.

      " + }, + { + "textRaw": "`hash.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the hash content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + } + ] + }, + { + "textRaw": "Class: `Hmac`", + "type": "class", + "name": "Hmac", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "desc": "\n

      The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:

      \n
        \n
      • As a stream that is both readable and writable, where data is written\nto produce a computed HMAC digest on the readable side, or
      • \n
      • Using the hmac.update() and hmac.digest() methods to produce the\ncomputed HMAC digest.
      • \n
      \n

      The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.

      \n

      Example: Using Hmac objects as streams:

      \n
      const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = hmac.read();\n  if (data) {\n    console.log(data.toString('hex'));\n    // Prints:\n    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n  }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
      \n

      Example: Using Hmac and piped streams:

      \n
      const crypto = require('crypto');\nconst fs = require('fs');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hmac).pipe(process.stdout);\n
      \n

      Example: Using the hmac.update() and hmac.digest() methods:

      \n
      const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
      ", + "methods": [ + { + "textRaw": "`hmac.digest([encoding])`", + "type": "method", + "name": "digest", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`encoding` {string} The [encoding][] of the return value.", + "name": "encoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Calculates the HMAC digest of all of the data passed using hmac.update().\nIf encoding is\nprovided a string is returned; otherwise a Buffer is returned;

      \n

      The Hmac object can not be used again after hmac.digest() has been\ncalled. Multiple calls to hmac.digest() will result in an error being thrown.

      " + }, + { + "textRaw": "`hmac.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the Hmac content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + } + ] + }, + { + "textRaw": "Class: `KeyObject`", + "type": "class", + "name": "KeyObject", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33360", + "description": "Instances of this class can now be passed to worker threads using `postMessage`." + }, + { + "version": "v11.13.0", + "pr-url": "https://github.com/nodejs/node/pull/26438", + "description": "This class is now exported." + } + ] + }, + "desc": "

      Node.js uses a KeyObject class to represent a symmetric or asymmetric key,\nand each kind of key exposes different functions. The\ncrypto.createSecretKey(), crypto.createPublicKey() and\ncrypto.createPrivateKey() methods are used to create KeyObject\ninstances. KeyObject objects are not to be created directly using the new\nkeyword.

      \n

      Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.

      \n

      KeyObject instances can be passed to other threads via postMessage().\nThe receiver obtains a cloned KeyObject, and the KeyObject does not need to\nbe listed in the transferList argument.

      ", + "properties": [ + { + "textRaw": "`asymmetricKeyType` {string}", + "type": "string", + "name": "asymmetricKeyType", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31178", + "description": "Added support for `'dh'`." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26960", + "description": "Added support for `'rsa-pss'`" + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26786", + "description": "This property now returns `undefined` for KeyObject instances of unrecognized type instead of aborting." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26774", + "description": "Added support for `'x25519'` and `'x448'`" + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26319", + "description": "Added support for `'ed25519'` and `'ed448'`." + } + ] + }, + "desc": "

      For asymmetric keys, this property represents the type of the key. Supported key\ntypes are:

      \n
        \n
      • 'rsa' (OID 1.2.840.113549.1.1.1)
      • \n
      • 'rsa-pss' (OID 1.2.840.113549.1.1.10)
      • \n
      • 'dsa' (OID 1.2.840.10040.4.1)
      • \n
      • 'ec' (OID 1.2.840.10045.2.1)
      • \n
      • 'x25519' (OID 1.3.101.110)
      • \n
      • 'x448' (OID 1.3.101.111)
      • \n
      • 'ed25519' (OID 1.3.101.112)
      • \n
      • 'ed448' (OID 1.3.101.113)
      • \n
      • 'dh' (OID 1.2.840.113549.1.3.1)
      • \n
      \n

      This property is undefined for unrecognized KeyObject types and symmetric\nkeys.

      " + }, + { + "textRaw": "`symmetricKeySize` {number}", + "type": "number", + "name": "symmetricKeySize", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.

      " + }, + { + "textRaw": "`type` {string}", + "type": "string", + "name": "type", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      Depending on the type of this KeyObject, this property is either\n'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys\nor 'private' for private (asymmetric) keys.

      " + } + ], + "methods": [ + { + "textRaw": "`keyObject.export([options])`", + "type": "method", + "name": "export", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string | Buffer}", + "name": "return", + "type": "string | Buffer" + }, + "params": [ + { + "textRaw": "`options`: {Object}", + "name": "options", + "type": "Object" + } + ] + } + ], + "desc": "

      For symmetric keys, this function allocates a Buffer containing the key\nmaterial and ignores any options.

      \n

      For asymmetric keys, the options parameter is used to determine the export\nformat.

      \n

      For public keys, the following encoding options can be used:

      \n
        \n
      • type: <string> Must be one of 'pkcs1' (RSA only) or 'spki'.
      • \n
      • format: <string> Must be 'pem' or 'der'.
      • \n
      \n

      For private keys, the following encoding options can be used:

      \n
        \n
      • type: <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or\n'sec1' (EC only).
      • \n
      • format: <string> Must be 'pem' or 'der'.
      • \n
      • cipher: <string> If specified, the private key will be encrypted with\n the given cipher and passphrase using PKCS#5 v2.0 password based\nencryption.
      • \n
      • passphrase: <string> | <Buffer> The passphrase to use for encryption, see\ncipher.
      • \n
      \n

      When PEM encoding was selected, the result will be a string, otherwise it will\nbe a buffer containing the data encoded as DER.

      \n

      PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of\nthe cipher and format options. The PKCS#8 type can be used with any\nformat to encrypt any key algorithm (RSA, EC, or DH) by specifying a\ncipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher\nwhen the PEM format is used. For maximum compatibility, use PKCS#8 for\nencrypted private keys. Since PKCS#8 defines its own\nencryption mechanism, PEM-level encryption is not supported when encrypting\na PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for\nPKCS#1 and SEC1 encryption.

      " + } + ] + }, + { + "textRaw": "Class: `Sign`", + "type": "class", + "name": "Sign", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "desc": "\n

      The Sign class is a utility for generating signatures. It can be used in one\nof two ways:

      \n
        \n
      • As a writable stream, where data to be signed is written and the\nsign.sign() method is used to generate and return the signature, or
      • \n
      • Using the sign.update() and sign.sign() methods to produce the\nsignature.
      • \n
      \n

      The crypto.createSign() method is used to create Sign instances. The\nargument is the string name of the hash function to use. Sign objects are not\nto be created directly using the new keyword.

      \n

      Example: Using Sign and Verify objects as streams:

      \n
      const crypto = require('crypto');\n\nconst { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {\n  namedCurve: 'sect239k1'\n});\n\nconst sign = crypto.createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = crypto.createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n
      \n

      Example: Using the sign.update() and verify.update() methods:

      \n
      const crypto = require('crypto');\n\nconst { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {\n  modulusLength: 2048,\n});\n\nconst sign = crypto.createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = crypto.createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n
      ", + "methods": [ + { + "textRaw": "`sign.sign(privateKey[, outputEncoding])`", + "type": "method", + "name": "sign", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26960", + "description": "This function now supports RSA-PSS keys." + }, + { + "version": "v11.6.0", + "pr-url": "https://github.com/nodejs/node/pull/24234", + "description": "This function now supports key objects." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11705", + "description": "Support for RSASSA-PSS and additional options was added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer | string}", + "name": "return", + "type": "Buffer | string" + }, + "params": [ + { + "textRaw": "`privateKey` {Object | string | Buffer | KeyObject}", + "name": "privateKey", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`dsaEncoding` {string}", + "name": "dsaEncoding", + "type": "string" + }, + { + "textRaw": "`padding` {integer}", + "name": "padding", + "type": "integer" + }, + { + "textRaw": "`saltLength` {integer}", + "name": "saltLength", + "type": "integer" + } + ] + }, + { + "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", + "name": "outputEncoding", + "type": "string", + "desc": "The [encoding][] of the return value." + } + ] + } + ], + "desc": "

      Calculates the signature on all the data passed through using either\nsign.update() or sign.write().

      \n

      If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the following additional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.

        \n
      • \n
      \n

      If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.

      \n

      The Sign object can not be again used after sign.sign() method has been\ncalled. Multiple calls to sign.sign() will result in an error being thrown.

      " + }, + { + "textRaw": "`sign.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the Sign content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + } + ] + }, + { + "textRaw": "Class: `Verify`", + "type": "class", + "name": "Verify", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "desc": "\n

      The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:

      \n
        \n
      • As a writable stream where written data is used to validate against the\nsupplied signature, or
      • \n
      • Using the verify.update() and verify.verify() methods to verify\nthe signature.
      • \n
      \n

      The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.

      \n

      See Sign for examples.

      ", + "methods": [ + { + "textRaw": "`verify.update(data[, inputEncoding])`", + "type": "method", + "name": "update", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5522", + "description": "The default `inputEncoding` changed from `binary` to `utf8`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string | Buffer | TypedArray | DataView}", + "name": "data", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", + "name": "inputEncoding", + "type": "string", + "desc": "The [encoding][] of the `data` string." + } + ] + } + ], + "desc": "

      Updates the Verify content with the given data, the encoding of which\nis given in inputEncoding.\nIf inputEncoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

      \n

      This can be called many times with new data as it is streamed.

      " + }, + { + "textRaw": "`verify.verify(object, signature[, signatureEncoding])`", + "type": "method", + "name": "verify", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26960", + "description": "This function now supports RSA-PSS keys." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25217", + "description": "The key can now be a private key." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11705", + "description": "Support for RSASSA-PSS and additional options was added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key.", + "name": "return", + "type": "boolean", + "desc": "`true` or `false` depending on the validity of the signature for the data and public key." + }, + "params": [ + { + "textRaw": "`object` {Object | string | Buffer | KeyObject}", + "name": "object", + "type": "Object | string | Buffer | KeyObject", + "options": [ + { + "textRaw": "`dsaEncoding` {string}", + "name": "dsaEncoding", + "type": "string" + }, + { + "textRaw": "`padding` {integer}", + "name": "padding", + "type": "integer" + }, + { + "textRaw": "`saltLength` {integer}", + "name": "saltLength", + "type": "integer" + } + ] + }, + { + "textRaw": "`signature` {string | Buffer | TypedArray | DataView}", + "name": "signature", + "type": "string | Buffer | TypedArray | DataView" + }, + { + "textRaw": "`signatureEncoding` {string} The [encoding][] of the `signature` string.", + "name": "signatureEncoding", + "type": "string", + "desc": "The [encoding][] of the `signature` string." + } + ] + } + ], + "desc": "

      Verifies the provided data using the given object and signature.

      \n

      If object is not a KeyObject, this function behaves as if\nobject had been passed to crypto.createPublicKey(). If it is an\nobject, the following additional properties can be passed:

      \n
        \n
      • \n

        dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

        \n
          \n
        • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
        • \n
        • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
        • \n
        \n
      • \n
      • \n

        padding <integer> Optional padding value for RSA, one of the following:

        \n
          \n
        • crypto.constants.RSA_PKCS1_PADDING (default)
        • \n
        • crypto.constants.RSA_PKCS1_PSS_PADDING
        • \n
        \n

        RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to verify the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.

        \n
      • \n
      • \n

        saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be\ndetermined automatically.

        \n
      • \n
      \n

      The signature argument is the previously calculated signature for the data, in\nthe signatureEncoding.\nIf a signatureEncoding is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer,\nTypedArray, or DataView.

      \n

      The verify object can not be used again after verify.verify() has been\ncalled. Multiple calls to verify.verify() will result in an error being\nthrown.

      \n

      Because public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

      " + } + ] + } + ], + "type": "module", + "displayName": "Crypto" + } + ] +} \ No newline at end of file diff --git a/doc/api/debugger.html b/doc/api/debugger.html new file mode 100644 index 0000000000000000000000000000000000000000..02fe34ddc4c7a467cc9d8e0576eb21e9ba6b8f4e --- /dev/null +++ b/doc/api/debugger.html @@ -0,0 +1,321 @@ + + + + + + + Debugger | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Debugger#

      + +

      Stability: 2 - Stable

      + +

      Node.js includes an out-of-process debugging utility accessible via a +V8 Inspector and built-in debugging client. To use it, start Node.js +with the inspect argument followed by the path to the script to debug; a +prompt will be displayed indicating successful launch of the debugger:

      +
      $ node inspect myscript.js
      +< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
      +< For help, see: https://nodejs.org/en/docs/inspector
      +< Debugger attached.
      +Break on start in myscript.js:1
      +> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
      +  2 setTimeout(() => {
      +  3   console.log('world');
      +debug>
      +

      The Node.js debugger client is not a full-featured debugger, but simple step and +inspection are possible.

      +

      Inserting the statement debugger; into the source code of a script will +enable a breakpoint at that position in the code:

      + +
      // myscript.js
      +global.x = 5;
      +setTimeout(() => {
      +  debugger;
      +  console.log('world');
      +}, 1000);
      +console.log('hello');
      +

      Once the debugger is run, a breakpoint will occur at line 3:

      +
      $ node inspect myscript.js
      +< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
      +< For help, see: https://nodejs.org/en/docs/inspector
      +< Debugger attached.
      +Break on start in myscript.js:1
      +> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
      +  2 setTimeout(() => {
      +  3   debugger;
      +debug> cont
      +< hello
      +break in myscript.js:3
      +  1 (function (exports, require, module, __filename, __dirname) { global.x = 5;
      +  2 setTimeout(() => {
      +> 3   debugger;
      +  4   console.log('world');
      +  5 }, 1000);
      +debug> next
      +break in myscript.js:4
      +  2 setTimeout(() => {
      +  3   debugger;
      +> 4   console.log('world');
      +  5 }, 1000);
      +  6 console.log('hello');
      +debug> repl
      +Press Ctrl + C to leave debug repl
      +> x
      +5
      +> 2 + 2
      +4
      +debug> next
      +< world
      +break in myscript.js:5
      +  3   debugger;
      +  4   console.log('world');
      +> 5 }, 1000);
      +  6 console.log('hello');
      +  7
      +debug> .exit
      +

      The repl command allows code to be evaluated remotely. The next command +steps to the next line. Type help to see what other commands are available.

      +

      Pressing enter without typing a command will repeat the previous debugger +command.

      +

      Watchers#

      +

      It is possible to watch expression and variable values while debugging. On +every breakpoint, each expression from the watchers list will be evaluated +in the current context and displayed immediately before the breakpoint's +source code listing.

      +

      To begin watching an expression, type watch('my_expression'). The command +watchers will print the active watchers. To remove a watcher, type +unwatch('my_expression').

      +

      Command reference#

      +

      Stepping#

      +
        +
      • cont, c: Continue execution
      • +
      • next, n: Step next
      • +
      • step, s: Step in
      • +
      • out, o: Step out
      • +
      • pause: Pause running code (like pause button in Developer Tools)
      • +
      +

      Breakpoints#

      +
        +
      • setBreakpoint(), sb(): Set breakpoint on current line
      • +
      • setBreakpoint(line), sb(line): Set breakpoint on specific line
      • +
      • setBreakpoint('fn()'), sb(...): Set breakpoint on a first statement in +functions body
      • +
      • setBreakpoint('script.js', 1), sb(...): Set breakpoint on first line of +script.js
      • +
      • clearBreakpoint('script.js', 1), cb(...): Clear breakpoint in script.js +on line 1
      • +
      +

      It is also possible to set a breakpoint in a file (module) that +is not loaded yet:

      +
      $ node inspect main.js
      +< Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd
      +< For help, see: https://nodejs.org/en/docs/inspector
      +< Debugger attached.
      +Break on start in main.js:1
      +> 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js');
      +  2 mod.hello();
      +  3 mod.hello();
      +debug> setBreakpoint('mod.js', 22)
      +Warning: script 'mod.js' was not loaded yet.
      +debug> c
      +break in mod.js:22
      + 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
      + 21
      +>22 exports.hello = function() {
      + 23   return 'hello from module';
      + 24 };
      +debug>
      +

      Information#

      +
        +
      • backtrace, bt: Print backtrace of current execution frame
      • +
      • list(5): List scripts source code with 5 line context (5 lines before and +after)
      • +
      • watch(expr): Add expression to watch list
      • +
      • unwatch(expr): Remove expression from watch list
      • +
      • watchers: List all watchers and their values (automatically listed on each +breakpoint)
      • +
      • repl: Open debugger's repl for evaluation in debugging script's context
      • +
      • exec expr: Execute an expression in debugging script's context
      • +
      +

      Execution control#

      +
        +
      • run: Run script (automatically runs on debugger's start)
      • +
      • restart: Restart script
      • +
      • kill: Kill script
      • +
      +

      Various#

      +
        +
      • scripts: List all loaded scripts
      • +
      • version: Display V8's version
      • +
      +

      Advanced usage#

      +

      V8 inspector integration for Node.js#

      +

      V8 Inspector integration allows attaching Chrome DevTools to Node.js +instances for debugging and profiling. It uses the +Chrome DevTools Protocol.

      +

      V8 Inspector can be enabled by passing the --inspect flag when starting a +Node.js application. It is also possible to supply a custom port with that flag, +e.g. --inspect=9222 will accept DevTools connections on port 9222.

      +

      To break on the first line of the application code, pass the --inspect-brk +flag instead of --inspect.

      +
      $ node --inspect index.js
      +Debugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
      +For help, see: https://nodejs.org/en/docs/inspector
      +

      (In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29 +at the end of the URL is generated on the fly, it varies in different +debugging sessions.)

      +

      If the Chrome browser is older than 66.0.3345.0, +use inspector.html instead of js_app.html in the above URL.

      +

      Chrome DevTools doesn't support debugging worker threads yet. +ndb can be used to debug them.

      + +
      +
      +
      + + diff --git a/doc/api/debugger.json b/doc/api/debugger.json new file mode 100644 index 0000000000000000000000000000000000000000..68310a31d5269aac6c08c737d60b0a5cdfefd163 --- /dev/null +++ b/doc/api/debugger.json @@ -0,0 +1,85 @@ +{ + "type": "module", + "source": "doc/api/debugger.md", + "introduced_in": "v0.9.12", + "stability": 2, + "stabilityText": "Stable", + "miscs": [ + { + "textRaw": "Debugger", + "name": "Debugger", + "introduced_in": "v0.9.12", + "stability": 2, + "stabilityText": "Stable", + "type": "misc", + "desc": "

      Node.js includes an out-of-process debugging utility accessible via a\nV8 Inspector and built-in debugging client. To use it, start Node.js\nwith the inspect argument followed by the path to the script to debug; a\nprompt will be displayed indicating successful launch of the debugger:

      \n
      $ node inspect myscript.js\n< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba\n< For help, see: https://nodejs.org/en/docs/inspector\n< Debugger attached.\nBreak on start in myscript.js:1\n> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;\n  2 setTimeout(() => {\n  3   console.log('world');\ndebug>\n
      \n

      The Node.js debugger client is not a full-featured debugger, but simple step and\ninspection are possible.

      \n

      Inserting the statement debugger; into the source code of a script will\nenable a breakpoint at that position in the code:

      \n\n
      // myscript.js\nglobal.x = 5;\nsetTimeout(() => {\n  debugger;\n  console.log('world');\n}, 1000);\nconsole.log('hello');\n
      \n

      Once the debugger is run, a breakpoint will occur at line 3:

      \n
      $ node inspect myscript.js\n< Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba\n< For help, see: https://nodejs.org/en/docs/inspector\n< Debugger attached.\nBreak on start in myscript.js:1\n> 1 (function (exports, require, module, __filename, __dirname) { global.x = 5;\n  2 setTimeout(() => {\n  3   debugger;\ndebug> cont\n< hello\nbreak in myscript.js:3\n  1 (function (exports, require, module, __filename, __dirname) { global.x = 5;\n  2 setTimeout(() => {\n> 3   debugger;\n  4   console.log('world');\n  5 }, 1000);\ndebug> next\nbreak in myscript.js:4\n  2 setTimeout(() => {\n  3   debugger;\n> 4   console.log('world');\n  5 }, 1000);\n  6 console.log('hello');\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2 + 2\n4\ndebug> next\n< world\nbreak in myscript.js:5\n  3   debugger;\n  4   console.log('world');\n> 5 }, 1000);\n  6 console.log('hello');\n  7\ndebug> .exit\n
      \n

      The repl command allows code to be evaluated remotely. The next command\nsteps to the next line. Type help to see what other commands are available.

      \n

      Pressing enter without typing a command will repeat the previous debugger\ncommand.

      ", + "miscs": [ + { + "textRaw": "Watchers", + "name": "watchers", + "desc": "

      It is possible to watch expression and variable values while debugging. On\nevery breakpoint, each expression from the watchers list will be evaluated\nin the current context and displayed immediately before the breakpoint's\nsource code listing.

      \n

      To begin watching an expression, type watch('my_expression'). The command\nwatchers will print the active watchers. To remove a watcher, type\nunwatch('my_expression').

      ", + "type": "misc", + "displayName": "Watchers" + }, + { + "textRaw": "Command reference", + "name": "command_reference", + "modules": [ + { + "textRaw": "Stepping", + "name": "stepping", + "desc": "
        \n
      • cont, c: Continue execution
      • \n
      • next, n: Step next
      • \n
      • step, s: Step in
      • \n
      • out, o: Step out
      • \n
      • pause: Pause running code (like pause button in Developer Tools)
      • \n
      ", + "type": "module", + "displayName": "Stepping" + }, + { + "textRaw": "Breakpoints", + "name": "breakpoints", + "desc": "
        \n
      • setBreakpoint(), sb(): Set breakpoint on current line
      • \n
      • setBreakpoint(line), sb(line): Set breakpoint on specific line
      • \n
      • setBreakpoint('fn()'), sb(...): Set breakpoint on a first statement in\nfunctions body
      • \n
      • setBreakpoint('script.js', 1), sb(...): Set breakpoint on first line of\nscript.js
      • \n
      • clearBreakpoint('script.js', 1), cb(...): Clear breakpoint in script.js\non line 1
      • \n
      \n

      It is also possible to set a breakpoint in a file (module) that\nis not loaded yet:

      \n
      $ node inspect main.js\n< Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd\n< For help, see: https://nodejs.org/en/docs/inspector\n< Debugger attached.\nBreak on start in main.js:1\n> 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 22)\nWarning: script 'mod.js' was not loaded yet.\ndebug> c\nbreak in mod.js:22\n 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.\n 21\n>22 exports.hello = function() {\n 23   return 'hello from module';\n 24 };\ndebug>\n
      ", + "type": "module", + "displayName": "Breakpoints" + }, + { + "textRaw": "Information", + "name": "information", + "desc": "
        \n
      • backtrace, bt: Print backtrace of current execution frame
      • \n
      • list(5): List scripts source code with 5 line context (5 lines before and\nafter)
      • \n
      • watch(expr): Add expression to watch list
      • \n
      • unwatch(expr): Remove expression from watch list
      • \n
      • watchers: List all watchers and their values (automatically listed on each\nbreakpoint)
      • \n
      • repl: Open debugger's repl for evaluation in debugging script's context
      • \n
      • exec expr: Execute an expression in debugging script's context
      • \n
      ", + "type": "module", + "displayName": "Information" + }, + { + "textRaw": "Execution control", + "name": "execution_control", + "desc": "
        \n
      • run: Run script (automatically runs on debugger's start)
      • \n
      • restart: Restart script
      • \n
      • kill: Kill script
      • \n
      ", + "type": "module", + "displayName": "Execution control" + }, + { + "textRaw": "Various", + "name": "various", + "desc": "
        \n
      • scripts: List all loaded scripts
      • \n
      • version: Display V8's version
      • \n
      ", + "type": "module", + "displayName": "Various" + } + ], + "type": "misc", + "displayName": "Command reference" + }, + { + "textRaw": "Advanced usage", + "name": "advanced_usage", + "modules": [ + { + "textRaw": "V8 inspector integration for Node.js", + "name": "v8_inspector_integration_for_node.js", + "desc": "

      V8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling. It uses the\nChrome DevTools Protocol.

      \n

      V8 Inspector can be enabled by passing the --inspect flag when starting a\nNode.js application. It is also possible to supply a custom port with that flag,\ne.g. --inspect=9222 will accept DevTools connections on port 9222.

      \n

      To break on the first line of the application code, pass the --inspect-brk\nflag instead of --inspect.

      \n
      $ node --inspect index.js\nDebugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29\nFor help, see: https://nodejs.org/en/docs/inspector\n
      \n

      (In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29\nat the end of the URL is generated on the fly, it varies in different\ndebugging sessions.)

      \n

      If the Chrome browser is older than 66.0.3345.0,\nuse inspector.html instead of js_app.html in the above URL.

      \n

      Chrome DevTools doesn't support debugging worker threads yet.\nndb can be used to debug them.

      ", + "type": "module", + "displayName": "V8 inspector integration for Node.js" + } + ], + "type": "misc", + "displayName": "Advanced usage" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/deprecations.html b/doc/api/deprecations.html new file mode 100644 index 0000000000000000000000000000000000000000..5bcc5e1795e24681ebe6e7d215069c7e124f8043 --- /dev/null +++ b/doc/api/deprecations.html @@ -0,0 +1,2585 @@ + + + + + + + Deprecated APIs | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Deprecated APIs#

      + + +

      Node.js may deprecate APIs for any of the following reasons:

      +
        +
      • Use of the API is unsafe.
      • +
      • An improved alternative API is available.
      • +
      • Breaking changes to the API are expected in a future major release.
      • +
      +

      Node.js utilizes three kinds of Deprecations:

      +
        +
      • Documentation-only
      • +
      • Runtime
      • +
      • End-of-Life
      • +
      +

      A Documentation-only deprecation is one that is expressed only within the +Node.js API docs. These generate no side-effects while running Node.js. +Some Documentation-only deprecations trigger a runtime warning when launched +with --pending-deprecation flag (or its alternative, +NODE_PENDING_DEPRECATION=1 environment variable), similarly to Runtime +deprecations below. Documentation-only deprecations that support that flag +are explicitly labeled as such in the +list of Deprecated APIs.

      +

      A Runtime deprecation will, by default, generate a process warning that will +be printed to stderr the first time the deprecated API is used. When the +--throw-deprecation command-line flag is used, a Runtime deprecation will +cause an error to be thrown.

      +

      An End-of-Life deprecation is used when functionality is or will soon be removed +from Node.js.

      +

      Revoking deprecations#

      +

      Occasionally, the deprecation of an API may be reversed. In such situations, +this document will be updated with information relevant to the decision. +However, the deprecation identifier will not be modified.

      +

      List of deprecated APIs#

      +

      +

      DEP0001: http.OutgoingMessage.prototype.flush#

      + +

      Type: Runtime

      +

      The OutgoingMessage.prototype.flush() method is deprecated. Use +OutgoingMessage.prototype.flushHeaders() instead.

      +

      +

      DEP0002: require('_linklist')#

      + +

      Type: End-of-Life

      +

      The _linklist module is deprecated. Please use a userland alternative.

      +

      +

      DEP0003: _writableState.buffer#

      + +

      Type: Runtime

      +

      The _writableState.buffer property is deprecated. Use the +_writableState.getBuffer() method instead.

      +

      +

      DEP0004: CryptoStream.prototype.readyState#

      + +

      Type: End-of-Life

      +

      The CryptoStream.prototype.readyState property was removed.

      +

      +

      DEP0005: Buffer() constructor#

      + +

      Type: Runtime (supports --pending-deprecation)

      +

      The Buffer() function and new Buffer() constructor are deprecated due to +API usability issues that can lead to accidental security issues.

      +

      As an alternative, use one of the following methods of constructing Buffer +objects:

      + +

      Without --pending-deprecation, runtime warnings occur only for code not in +node_modules. This means there will not be deprecation warnings for +Buffer() usage in dependencies. With --pending-deprecation, a runtime +warning results no matter where the Buffer() usage occurs.

      +

      +

      DEP0006: child_process options.customFds#

      + +

      Type: End-of-Life

      +

      Within the child_process module's spawn(), fork(), and exec() +methods, the options.customFds option is deprecated. The options.stdio +option should be used instead.

      +

      +

      DEP0007: Replace cluster worker.suicide with worker.exitedAfterDisconnect#

      + +

      Type: End-of-Life

      +

      In an earlier version of the Node.js cluster, a boolean property with the name +suicide was added to the Worker object. The intent of this property was to +provide an indication of how and why the Worker instance exited. In Node.js +6.0.0, the old property was deprecated and replaced with a new +worker.exitedAfterDisconnect property. The old property name did not +precisely describe the actual semantics and was unnecessarily emotion-laden.

      +

      +

      DEP0008: require('constants')#

      + +

      Type: Documentation-only

      +

      The constants module is deprecated. When requiring access to constants +relevant to specific Node.js builtin modules, developers should instead refer +to the constants property exposed by the relevant module. For instance, +require('fs').constants and require('os').constants.

      +

      +

      DEP0009: crypto.pbkdf2 without digest#

      + +

      Type: Runtime

      +

      Use of the crypto.pbkdf2() API without specifying a digest was deprecated +in Node.js 6.0 because the method defaulted to using the non-recommended +'SHA1' digest. Previously, a deprecation warning was printed. Starting in +Node.js 8.0.0, calling crypto.pbkdf2() or crypto.pbkdf2Sync() with +digest set to undefined will throw a TypeError.

      +

      Beginning in Node.js v11.0.0, calling these functions with digest set to +null will print a deprecation warning to align with the behavior when digest +is undefined.

      +

      +

      DEP0010: crypto.createCredentials#

      + +

      Type: End-of-Life

      +

      The crypto.createCredentials() API was removed. Please use +tls.createSecureContext() instead.

      +

      +

      DEP0011: crypto.Credentials#

      + +

      Type: End-of-Life

      +

      The crypto.Credentials class was removed. Please use tls.SecureContext +instead.

      +

      +

      DEP0012: Domain.dispose#

      + +

      Type: End-of-Life

      +

      Domain.dispose() has been removed. Recover from failed I/O actions +explicitly via error event handlers set on the domain instead.

      +

      +

      DEP0013: fs asynchronous function without callback#

      + +

      Type: End-of-Life

      +

      Calling an asynchronous function without a callback throws a TypeError +in Node.js 10.0.0 onwards. See https://github.com/nodejs/node/pull/12562.

      +

      +

      DEP0014: fs.read legacy String interface#

      + +

      Type: End-of-Life

      +

      The fs.read() legacy String interface is deprecated. Use the Buffer +API as mentioned in the documentation instead.

      +

      +

      DEP0015: fs.readSync legacy String interface#

      + +

      Type: End-of-Life

      +

      The fs.readSync() legacy String interface is deprecated. Use the +Buffer API as mentioned in the documentation instead.

      +

      +

      DEP0016: GLOBAL/root#

      + +

      Type: Runtime

      +

      The GLOBAL and root aliases for the global property are deprecated +and should no longer be used.

      +

      +

      DEP0017: Intl.v8BreakIterator#

      + +

      Type: End-of-Life

      +

      Intl.v8BreakIterator was a non-standard extension and has been removed. +See Intl.Segmenter.

      +

      +

      DEP0018: Unhandled promise rejections#

      + +

      Type: Runtime

      +

      Unhandled promise rejections are deprecated. In the future, promise rejections +that are not handled will terminate the Node.js process with a non-zero exit +code.

      +

      +

      DEP0019: require('.') resolved outside directory#

      + +

      Type: End-of-Life

      +

      In certain cases, require('.') could resolve outside the package directory. +This behavior has been removed.

      +

      +

      DEP0020: Server.connections#

      + +

      Type: Runtime

      +

      The Server.connections property is deprecated. Please use the +Server.getConnections() method instead.

      +

      +

      DEP0021: Server.listenFD#

      + +

      Type: End-of-Life

      +

      The Server.listenFD() method was deprecated and removed. Please use +Server.listen({fd: <number>}) instead.

      +

      +

      DEP0022: os.tmpDir()#

      + +

      Type: Runtime

      +

      The os.tmpDir() API is deprecated. Please use os.tmpdir() instead.

      +

      +

      DEP0023: os.getNetworkInterfaces()#

      + +

      Type: End-of-Life

      +

      The os.getNetworkInterfaces() method is deprecated. Please use the +os.networkInterfaces() method instead.

      +

      +

      DEP0024: REPLServer.prototype.convertToContext()#

      + +

      Type: End-of-Life

      +

      The REPLServer.prototype.convertToContext() API has been removed.

      +

      +

      DEP0025: require('sys')#

      + +

      Type: Runtime

      +

      The sys module is deprecated. Please use the util module instead.

      +

      +

      DEP0026: util.print()#

      + +

      Type: End-of-Life

      +

      util.print() has been removed. Please use console.log() instead.

      +

      +

      DEP0027: util.puts()#

      + +

      Type: End-of-Life

      +

      util.puts() has been removed. Please use console.log() instead.

      +

      +

      DEP0028: util.debug()#

      + +

      Type: End-of-Life

      +

      util.debug() has been removed. Please use console.error() instead.

      +

      +

      DEP0029: util.error()#

      + +

      Type: End-of-Life

      +

      util.error() has been removed. Please use console.error() instead.

      +

      +

      DEP0030: SlowBuffer#

      + +

      Type: Documentation-only

      +

      The SlowBuffer class is deprecated. Please use +Buffer.allocUnsafeSlow(size) instead.

      +

      +

      DEP0031: ecdh.setPublicKey()#

      + +

      Type: Documentation-only

      +

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the +API is not useful.

      +

      +

      DEP0032: domain module#

      + +

      Type: Documentation-only

      +

      The domain module is deprecated and should not be used.

      +

      +

      DEP0033: EventEmitter.listenerCount()#

      + +

      Type: Documentation-only

      +

      The EventEmitter.listenerCount(emitter, eventName) API is +deprecated. Please use emitter.listenerCount(eventName) instead.

      +

      +

      DEP0034: fs.exists(path, callback)#

      + +

      Type: Documentation-only

      +

      The fs.exists(path, callback) API is deprecated. Please use +fs.stat() or fs.access() instead.

      +

      +

      DEP0035: fs.lchmod(path, mode, callback)#

      + +

      Type: Documentation-only

      +

      The fs.lchmod(path, mode, callback) API is deprecated.

      +

      +

      DEP0036: fs.lchmodSync(path, mode)#

      + +

      Type: Documentation-only

      +

      The fs.lchmodSync(path, mode) API is deprecated.

      +

      +

      DEP0037: fs.lchown(path, uid, gid, callback)#

      + +

      Type: Deprecation revoked

      +

      The fs.lchown(path, uid, gid, callback) API was deprecated. The +deprecation was revoked because the requisite supporting APIs were added in +libuv.

      +

      +

      DEP0038: fs.lchownSync(path, uid, gid)#

      + +

      Type: Deprecation revoked

      +

      The fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was +revoked because the requisite supporting APIs were added in libuv.

      +

      +

      DEP0039: require.extensions#

      + +

      Type: Documentation-only

      +

      The require.extensions property is deprecated.

      +

      +

      DEP0040: punycode module#

      + +

      Type: Documentation-only

      +

      The punycode module is deprecated. Please use a userland alternative +instead.

      +

      +

      DEP0041: NODE_REPL_HISTORY_FILE environment variable#

      + +

      Type: End-of-Life

      +

      The NODE_REPL_HISTORY_FILE environment variable was removed. Please use +NODE_REPL_HISTORY instead.

      +

      +

      DEP0042: tls.CryptoStream#

      + +

      Type: End-of-Life

      +

      The tls.CryptoStream class was removed. Please use +tls.TLSSocket instead.

      +

      +

      DEP0043: tls.SecurePair#

      + +

      Type: Documentation-only

      +

      The tls.SecurePair class is deprecated. Please use +tls.TLSSocket instead.

      +

      +

      DEP0044: util.isArray()#

      + +

      Type: Documentation-only

      +

      The util.isArray() API is deprecated. Please use Array.isArray() +instead.

      +

      +

      DEP0045: util.isBoolean()#

      + +

      Type: Documentation-only

      +

      The util.isBoolean() API is deprecated.

      +

      +

      DEP0046: util.isBuffer()#

      + +

      Type: Documentation-only

      +

      The util.isBuffer() API is deprecated. Please use +Buffer.isBuffer() instead.

      +

      +

      DEP0047: util.isDate()#

      + +

      Type: Documentation-only

      +

      The util.isDate() API is deprecated.

      +

      +

      DEP0048: util.isError()#

      + +

      Type: Documentation-only

      +

      The util.isError() API is deprecated.

      +

      +

      DEP0049: util.isFunction()#

      + +

      Type: Documentation-only

      +

      The util.isFunction() API is deprecated.

      +

      +

      DEP0050: util.isNull()#

      + +

      Type: Documentation-only

      +

      The util.isNull() API is deprecated.

      +

      +

      DEP0051: util.isNullOrUndefined()#

      + +

      Type: Documentation-only

      +

      The util.isNullOrUndefined() API is deprecated.

      +

      +

      DEP0052: util.isNumber()#

      + +

      Type: Documentation-only

      +

      The util.isNumber() API is deprecated.

      +

      +

      DEP0053 util.isObject()#

      + +

      Type: Documentation-only

      +

      The util.isObject() API is deprecated.

      +

      +

      DEP0054: util.isPrimitive()#

      + +

      Type: Documentation-only

      +

      The util.isPrimitive() API is deprecated.

      +

      +

      DEP0055: util.isRegExp()#

      + +

      Type: Documentation-only

      +

      The util.isRegExp() API is deprecated.

      +

      +

      DEP0056: util.isString()#

      + +

      Type: Documentation-only

      +

      The util.isString() API is deprecated.

      +

      +

      DEP0057: util.isSymbol()#

      + +

      Type: Documentation-only

      +

      The util.isSymbol() API is deprecated.

      +

      +

      DEP0058: util.isUndefined()#

      + +

      Type: Documentation-only

      +

      The util.isUndefined() API is deprecated.

      +

      +

      DEP0059: util.log()#

      + +

      Type: Documentation-only

      +

      The util.log() API is deprecated.

      +

      +

      DEP0060: util._extend()#

      + +

      Type: Documentation-only

      +

      The util._extend() API is deprecated.

      +

      +

      DEP0061: fs.SyncWriteStream#

      + +

      Type: End-of-Life

      +

      The fs.SyncWriteStream class was never intended to be a publicly accessible +API and has been removed. No alternative API is available. Please use a userland +alternative.

      +

      +

      DEP0062: node --debug#

      + +

      Type: End-of-Life

      +

      --debug activates the legacy V8 debugger interface, which was removed as +of V8 5.8. It is replaced by Inspector which is activated with --inspect +instead.

      +

      +

      DEP0063: ServerResponse.prototype.writeHeader()#

      + +

      Type: Documentation-only

      +

      The http module ServerResponse.prototype.writeHeader() API is +deprecated. Please use ServerResponse.prototype.writeHead() instead.

      +

      The ServerResponse.prototype.writeHeader() method was never documented as an +officially supported API.

      +

      +

      DEP0064: tls.createSecurePair()#

      + +

      Type: Runtime

      +

      The tls.createSecurePair() API was deprecated in documentation in Node.js +0.11.3. Users should use tls.Socket instead.

      +

      +

      DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic#

      + +

      Type: End-of-Life

      +

      The repl module's REPL_MODE_MAGIC constant, used for replMode option, has +been removed. Its behavior has been functionally identical to that of +REPL_MODE_SLOPPY since Node.js 6.0.0, when V8 5.0 was imported. Please use +REPL_MODE_SLOPPY instead.

      +

      The NODE_REPL_MODE environment variable is used to set the underlying +replMode of an interactive node session. Its value, magic, is also +removed. Please use sloppy instead.

      +

      +

      DEP0066: OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames#

      + +

      Type: Runtime

      +

      The http module OutgoingMessage.prototype._headers and +OutgoingMessage.prototype._headerNames properties are deprecated. Use one of +the public methods (e.g. OutgoingMessage.prototype.getHeader(), +OutgoingMessage.prototype.getHeaders(), +OutgoingMessage.prototype.getHeaderNames(), +OutgoingMessage.prototype.hasHeader(), +OutgoingMessage.prototype.removeHeader(), +OutgoingMessage.prototype.setHeader()) for working with outgoing headers.

      +

      The OutgoingMessage.prototype._headers and +OutgoingMessage.prototype._headerNames properties were never documented as +officially supported properties.

      +

      +

      DEP0067: OutgoingMessage.prototype._renderHeaders#

      + +

      Type: Documentation-only

      +

      The http module OutgoingMessage.prototype._renderHeaders() API is +deprecated.

      +

      The OutgoingMessage.prototype._renderHeaders property was never documented as +an officially supported API.

      +

      +

      DEP0068: node debug#

      + +

      Type: Runtime

      +

      node debug corresponds to the legacy CLI debugger which has been replaced with +a V8-inspector based CLI debugger available through node inspect.

      +

      +

      DEP0069: vm.runInDebugContext(string)#

      + +

      Type: End-of-Life

      +

      DebugContext has been removed in V8 and is not available in Node.js 10+.

      +

      DebugContext was an experimental API.

      +

      +

      DEP0070: async_hooks.currentId()#

      + +

      Type: End-of-Life

      +

      async_hooks.currentId() was renamed to async_hooks.executionAsyncId() for +clarity.

      +

      This change was made while async_hooks was an experimental API.

      +

      +

      DEP0071: async_hooks.triggerId()#

      + +

      Type: End-of-Life

      +

      async_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for +clarity.

      +

      This change was made while async_hooks was an experimental API.

      +

      +

      DEP0072: async_hooks.AsyncResource.triggerId()#

      + +

      Type: End-of-Life

      +

      async_hooks.AsyncResource.triggerId() was renamed to +async_hooks.AsyncResource.triggerAsyncId() for clarity.

      +

      This change was made while async_hooks was an experimental API.

      +

      +

      DEP0073: Several internal properties of net.Server#

      + +

      Type: End-of-Life

      +

      Accessing several internal, undocumented properties of net.Server instances +with inappropriate names is deprecated.

      +

      As the original API was undocumented and not generally useful for non-internal +code, no replacement API is provided.

      +

      +

      DEP0074: REPLServer.bufferedCommand#

      + +

      Type: Runtime

      +

      The REPLServer.bufferedCommand property was deprecated in favor of +REPLServer.clearBufferedCommand().

      +

      +

      DEP0075: REPLServer.parseREPLKeyword()#

      + +

      Type: Runtime

      +

      REPLServer.parseREPLKeyword() was removed from userland visibility.

      +

      +

      DEP0076: tls.parseCertString()#

      + +

      Type: Runtime

      +

      tls.parseCertString() is a trivial parsing helper that was made public by +mistake. This function can usually be replaced with:

      +
      const querystring = require('querystring');
      +querystring.parse(str, '\n', '=');
      +

      This function is not completely equivalent to querystring.parse(). One +difference is that querystring.parse() does url decoding:

      +
      > querystring.parse('%E5%A5%BD=1', '\n', '=');
      +{ '好': '1' }
      +> tls.parseCertString('%E5%A5%BD=1');
      +{ '%E5%A5%BD': '1' }
      +

      +

      DEP0077: Module._debug()#

      + +

      Type: Runtime

      +

      Module._debug() is deprecated.

      +

      The Module._debug() function was never documented as an officially +supported API.

      +

      +

      DEP0078: REPLServer.turnOffEditorMode()#

      + +

      Type: Runtime

      +

      REPLServer.turnOffEditorMode() was removed from userland visibility.

      +

      +

      DEP0079: Custom inspection function on objects via .inspect()#

      + +

      Type: End-of-Life

      +

      Using a property named inspect on an object to specify a custom inspection +function for util.inspect() is deprecated. Use util.inspect.custom +instead. For backward compatibility with Node.js prior to version 6.4.0, both +may be specified.

      +

      +

      DEP0080: path._makeLong()#

      + +

      Type: Documentation-only

      +

      The internal path._makeLong() was not intended for public use. However, +userland modules have found it useful. The internal API is deprecated +and replaced with an identical, public path.toNamespacedPath() method.

      +

      +

      DEP0081: fs.truncate() using a file descriptor#

      + +

      Type: Runtime

      +

      fs.truncate() fs.truncateSync() usage with a file descriptor is +deprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with +file descriptors.

      +

      +

      DEP0082: REPLServer.prototype.memory()#

      + +

      Type: Runtime

      +

      REPLServer.prototype.memory() is only necessary for the internal mechanics of +the REPLServer itself. Do not use this function.

      +

      +

      DEP0083: Disabling ECDH by setting ecdhCurve to false#

      + +

      Type: End-of-Life.

      +

      The ecdhCurve option to tls.createSecureContext() and tls.TLSSocket could +be set to false to disable ECDH entirely on the server only. This mode was +deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with +the client and is now unsupported. Use the ciphers parameter instead.

      +

      +

      DEP0084: requiring bundled internal dependencies#

      + +

      Type: End-of-Life

      +

      Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for +internal usage were mistakenly exposed to user code through require(). These +modules were:

      +
        +
      • v8/tools/codemap
      • +
      • v8/tools/consarray
      • +
      • v8/tools/csvparser
      • +
      • v8/tools/logreader
      • +
      • v8/tools/profile_view
      • +
      • v8/tools/profile
      • +
      • v8/tools/SourceMap
      • +
      • v8/tools/splaytree
      • +
      • v8/tools/tickprocessor-driver
      • +
      • v8/tools/tickprocessor
      • +
      • node-inspect/lib/_inspect (from 7.6.0)
      • +
      • node-inspect/lib/internal/inspect_client (from 7.6.0)
      • +
      • node-inspect/lib/internal/inspect_repl (from 7.6.0)
      • +
      +

      The v8/* modules do not have any exports, and if not imported in a specific +order would in fact throw errors. As such there are virtually no legitimate use +cases for importing them through require().

      +

      On the other hand, node-inspect may be installed locally through a package +manager, as it is published on the npm registry under the same name. No source +code modification is necessary if that is done.

      +

      +

      DEP0085: AsyncHooks sensitive API#

      + +

      Type: End-of-Life

      +

      The AsyncHooks sensitive API was never documented and had various minor issues. +Use the AsyncResource API instead. See +https://github.com/nodejs/node/issues/15572.

      +

      +

      DEP0086: Remove runInAsyncIdScope#

      + +

      Type: End-of-Life

      +

      runInAsyncIdScope doesn't emit the 'before' or 'after' event and can thus +cause a lot of issues. See https://github.com/nodejs/node/issues/14328.

      +

      +

      DEP0089: require('assert')#

      + +

      Type: Deprecation revoked

      +

      Importing assert directly was not recommended as the exposed functions use +loose equality checks. The deprecation was revoked because use of the assert +module is not discouraged, and the deprecation caused developer confusion.

      +

      +

      DEP0090: Invalid GCM authentication tag lengths#

      + +

      Type: End-of-Life

      +

      Node.js used to support all GCM authentication tag lengths which are accepted by +OpenSSL when calling decipher.setAuthTag(). Beginning with Node.js +v11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32 +bits are allowed. Authentication tags of other lengths are invalid per +NIST SP 800-38D.

      +

      +

      DEP0091: crypto.DEFAULT_ENCODING#

      + +

      Type: Runtime

      +

      The crypto.DEFAULT_ENCODING property is deprecated.

      +

      +

      DEP0092: Top-level this bound to module.exports#

      + +

      Type: Documentation-only

      +

      Assigning properties to the top-level this as an alternative +to module.exports is deprecated. Developers should use exports +or module.exports instead.

      +

      +

      DEP0093: crypto.fips is deprecated and replaced.#

      + +

      Type: Documentation-only

      +

      The crypto.fips property is deprecated. Please use crypto.setFips() +and crypto.getFips() instead.

      +

      +

      DEP0094: Using assert.fail() with more than one argument.#

      + +

      Type: Runtime

      +

      Using assert.fail() with more than one argument is deprecated. Use +assert.fail() with only one argument or use a different assert module +method.

      +

      +

      DEP0095: timers.enroll()#

      + +

      Type: Runtime

      +

      timers.enroll() is deprecated. Please use the publicly documented +setTimeout() or setInterval() instead.

      +

      +

      DEP0096: timers.unenroll()#

      + +

      Type: Runtime

      +

      timers.unenroll() is deprecated. Please use the publicly documented +clearTimeout() or clearInterval() instead.

      +

      +

      DEP0097: MakeCallback with domain property#

      + +

      Type: Runtime

      +

      Users of MakeCallback that add the domain property to carry context, +should start using the async_context variant of MakeCallback or +CallbackScope, or the high-level AsyncResource class.

      +

      +

      DEP0098: AsyncHooks embedder AsyncResource.emitBefore and AsyncResource.emitAfter APIs#

      + +

      Type: End-of-Life

      +

      The embedded API provided by AsyncHooks exposes .emitBefore() and +.emitAfter() methods which are very easy to use incorrectly which can lead +to unrecoverable errors.

      +

      Use asyncResource.runInAsyncScope() API instead which provides a much +safer, and more convenient, alternative. See +https://github.com/nodejs/node/pull/18513.

      +

      +

      DEP0099: Async context-unaware node::MakeCallback C++ APIs#

      + +

      Type: Compile-time

      +

      Certain versions of node::MakeCallback APIs available to native modules are +deprecated. Please use the versions of the API that accept an async_context +parameter.

      +

      +

      DEP0100: process.assert()#

      + +

      Type: Runtime

      +

      process.assert() is deprecated. Please use the assert module instead.

      +

      This was never a documented feature.

      +

      +

      DEP0101: --with-lttng#

      + +

      Type: End-of-Life

      +

      The --with-lttng compile-time option has been removed.

      +

      +

      DEP0102: Using noAssert in Buffer#(read|write) operations.#

      + +

      Type: End-of-Life

      +

      Using the noAssert argument has no functionality anymore. All input is going +to be verified, no matter if it is set to true or not. Skipping the verification +could lead to hard to find errors and crashes.

      +

      +

      DEP0103: process.binding('util').is[...] typechecks#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      Using process.binding() in general should be avoided. The type checking +methods in particular can be replaced by using util.types.

      +

      This deprecation has been superseded by the deprecation of the +process.binding() API (DEP0111).

      +

      +

      DEP0104: process.env string coercion#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      When assigning a non-string property to process.env, the assigned value is +implicitly converted to a string. This behavior is deprecated if the assigned +value is not a string, boolean, or number. In the future, such assignment may +result in a thrown error. Please convert the property to a string before +assigning it to process.env.

      +

      +

      DEP0105: decipher.finaltol#

      + +

      Type: End-of-Life

      +

      decipher.finaltol() has never been documented and was an alias for +decipher.final(). This API has been removed, and it is recommended to use +decipher.final() instead.

      +

      +

      DEP0106: crypto.createCipher and crypto.createDecipher#

      + +

      Type: Runtime

      +

      Using crypto.createCipher() and crypto.createDecipher() should be +avoided as they use a weak key derivation function (MD5 with no salt) and static +initialization vectors. It is recommended to derive a key using +crypto.pbkdf2() or crypto.scrypt() and to use +crypto.createCipheriv() and crypto.createDecipheriv() to obtain the +Cipher and Decipher objects respectively.

      +

      +

      DEP0107: tls.convertNPNProtocols()#

      + +

      Type: End-of-Life

      +

      This was an undocumented helper function not intended for use outside Node.js +core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.

      +

      +

      DEP0108: zlib.bytesRead#

      + +

      Type: Runtime

      +

      Deprecated alias for zlib.bytesWritten. This original name was chosen +because it also made sense to interpret the value as the number of bytes +read by the engine, but is inconsistent with other streams in Node.js that +expose values under these names.

      +

      +

      DEP0109: http, https, and tls support for invalid URLs#

      + +

      Type: Runtime

      +

      Some previously supported (but strictly invalid) URLs were accepted through the +http.request(), http.get(), https.request(), +https.get(), and tls.checkServerIdentity() APIs because those were +accepted by the legacy url.parse() API. The mentioned APIs now use the WHATWG +URL parser that requires strictly valid URLs. Passing an invalid URL is +deprecated and support will be removed in the future.

      +

      +

      DEP0110: vm.Script cached data#

      + +

      Type: Documentation-only

      +

      The produceCachedData option is deprecated. Use +script.createCachedData() instead.

      +

      +

      DEP0111: process.binding()#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      process.binding() is for use by Node.js internal code only.

      +

      +

      DEP0112: dgram private APIs#

      + +

      Type: Runtime

      +

      The dgram module previously contained several APIs that were never meant to +accessed outside of Node.js core: Socket.prototype._handle, +Socket.prototype._receiving, Socket.prototype._bindState, +Socket.prototype._queue, Socket.prototype._reuseAddr, +Socket.prototype._healthCheck(), Socket.prototype._stopReceiving(), and +dgram._createSocketHandle().

      +

      +

      DEP0113: Cipher.setAuthTag(), Decipher.getAuthTag()#

      + +

      Type: End-of-Life

      +

      Cipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They +were never documented and would throw when called.

      +

      +

      DEP0114: crypto._toBuf()#

      + +

      Type: End-of-Life

      +

      The crypto._toBuf() function was not designed to be used by modules outside +of Node.js core and was removed.

      +

      +

      DEP0115: crypto.prng(), crypto.pseudoRandomBytes(), crypto.rng()#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      In recent versions of Node.js, there is no difference between +crypto.randomBytes() and crypto.pseudoRandomBytes(). The latter is +deprecated along with the undocumented aliases crypto.prng() and +crypto.rng() in favor of crypto.randomBytes() and may be removed in a +future release.

      +

      +

      DEP0116: Legacy URL API#

      + +

      Type: Documentation-only

      +

      The Legacy URL API is deprecated. This includes url.format(), +url.parse(), url.resolve(), and the legacy urlObject. Please +use the WHATWG URL API instead.

      +

      +

      DEP0117: Native crypto handles#

      + +

      Type: End-of-Life

      +

      Previous versions of Node.js exposed handles to internal native objects through +the _handle property of the Cipher, Decipher, DiffieHellman, +DiffieHellmanGroup, ECDH, Hash, Hmac, Sign, and Verify classes. +The _handle property has been removed because improper use of the native +object can lead to crashing the application.

      +

      +

      DEP0118: dns.lookup() support for a falsy host name#

      + +

      Type: Runtime

      +

      Previous versions of Node.js supported dns.lookup() with a falsy host name +like dns.lookup(false) due to backward compatibility. +This behavior is undocumented and is thought to be unused in real world apps. +It will become an error in future versions of Node.js.

      +

      +

      DEP0119: process.binding('uv').errname() private API#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      process.binding('uv').errname() is deprecated. Please use +util.getSystemErrorName() instead.

      +

      +

      DEP0120: Windows Performance Counter support#

      + +

      Type: End-of-Life

      +

      Windows Performance Counter support has been removed from Node.js. The +undocumented COUNTER_NET_SERVER_CONNECTION(), +COUNTER_NET_SERVER_CONNECTION_CLOSE(), COUNTER_HTTP_SERVER_REQUEST(), +COUNTER_HTTP_SERVER_RESPONSE(), COUNTER_HTTP_CLIENT_REQUEST(), and +COUNTER_HTTP_CLIENT_RESPONSE() functions have been deprecated.

      +

      +

      DEP0121: net._setSimultaneousAccepts()#

      + +

      Type: Runtime

      +

      The undocumented net._setSimultaneousAccepts() function was originally +intended for debugging and performance tuning when using the child_process +and cluster modules on Windows. The function is not generally useful and +is being removed. See discussion here: +https://github.com/nodejs/node/issues/18391

      +

      +

      DEP0122: tls Server.prototype.setOptions()#

      + +

      Type: Runtime

      +

      Please use Server.prototype.setSecureContext() instead.

      +

      +

      DEP0123: setting the TLS ServerName to an IP address#

      + +

      Type: Runtime

      +

      Setting the TLS ServerName to an IP address is not permitted by +RFC 6066. This will be ignored in a future version.

      +

      +

      DEP0124: using REPLServer.rli#

      + +

      Type: Runtime

      +

      This property is a reference to the instance itself.

      +

      +

      DEP0125: require('_stream_wrap')#

      + +

      Type: Runtime

      +

      The _stream_wrap module is deprecated.

      +

      +

      DEP0126: timers.active()#

      + +

      Type: Runtime

      +

      The previously undocumented timers.active() is deprecated. +Please use the publicly documented timeout.refresh() instead. +If re-referencing the timeout is necessary, timeout.ref() can be used +with no performance impact since Node.js 10.

      +

      +

      DEP0127: timers._unrefActive()#

      + +

      Type: Runtime

      +

      The previously undocumented and "private" timers._unrefActive() is deprecated. +Please use the publicly documented timeout.refresh() instead. +If unreferencing the timeout is necessary, timeout.unref() can be used +with no performance impact since Node.js 10.

      +

      +

      DEP0128: modules with an invalid main entry and an index.js file#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      Modules that have an invalid main entry (e.g., ./does-not-exist.js) and +also have an index.js file in the top level directory will resolve the +index.js file. That is deprecated and is going to throw an error in future +Node.js versions.

      +

      +

      DEP0129: ChildProcess._channel#

      + +

      Type: Documentation-only

      +

      The _channel property of child process objects returned by spawn() and +similar functions is not intended for public use. Use ChildProcess.channel +instead.

      +

      +

      DEP0130: Module.createRequireFromPath()#

      + +

      Type: Documentation-only

      +

      Module.createRequireFromPath() is deprecated. Please use module.createRequire() instead.

      +

      +

      DEP0131: Legacy HTTP parser#

      + +

      Type: Runtime

      +

      The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0, +is deprecated. This deprecation applies to users of the +--http-parser=legacy command-line flag.

      +

      +

      DEP0132: worker.terminate() with callback#

      + +

      Type: Runtime

      +

      Passing a callback to worker.terminate() is deprecated. Use the returned +Promise instead, or a listener to the worker’s 'exit' event.

      +

      +

      DEP0133: http connection#

      + +

      Type: Documentation-only

      +

      Prefer response.socket over response.connection and +request.socket over request.connection.

      +

      +

      DEP0134: process._tickCallback#

      + +

      Type: Documentation-only (supports --pending-deprecation)

      +

      The process._tickCallback property was never documented as +an officially supported API.

      +

      +

      DEP0136: http finished#

      + +

      Type: Documentation-only

      +

      response.finished indicates whether response.end() has been +called, not whether 'finish' has been emitted and the underlying data +is flushed.

      +

      Use response.writableFinished or response.writableEnded +accordingly instead to avoid the ambigiuty.

      +

      To maintain existing behaviour response.finished should be replaced with +response.writableEnded.

      +

      +

      DEP0139: process.umask() with no arguments#

      + +

      Type: Documentation-only

      +

      Calling process.umask() with no argument causes the process-wide umask to be +written twice. This introduces a race condition between threads, and is a +potential security vulnerability. There is no safe, cross-platform alternative +API.

      +

      +

      DEP0144: module.parent#

      + +

      Type: Documentation-only

      +

      A CommonJS module can access the first module that required it using +module.parent. This feature is deprecated because it does not work +consistently in the presence of ECMAScript modules and because it gives an +inaccurate representation of the CommonJS module graph.

      +

      Some modules use it to check if they are the entry point of the current process. +Instead, it is recommended to compare require.main and module:

      +
      if (require.main === module) {
      +  // Code section that will run only if current file is the entry point.
      +}
      +

      When looking for the CommonJS modules that have required the current one, +require.cache and module.children can be used:

      +
      const moduleParents = Object.values(require.cache)
      +  .filter((m) => m.children.includes(module));
      + +
      +
      +
      + + diff --git a/doc/api/deprecations.json b/doc/api/deprecations.json new file mode 100644 index 0000000000000000000000000000000000000000..14ab9454c809944c4a4671bdd2679b819b197955 --- /dev/null +++ b/doc/api/deprecations.json @@ -0,0 +1,3007 @@ +{ + "type": "module", + "source": "doc/api/deprecations.md", + "introduced_in": "v7.7.0", + "miscs": [ + { + "textRaw": "Deprecated APIs", + "name": "Deprecated APIs", + "introduced_in": "v7.7.0", + "type": "misc", + "desc": "

      Node.js may deprecate APIs for any of the following reasons:

      \n
        \n
      • Use of the API is unsafe.
      • \n
      • An improved alternative API is available.
      • \n
      • Breaking changes to the API are expected in a future major release.
      • \n
      \n

      Node.js utilizes three kinds of Deprecations:

      \n
        \n
      • Documentation-only
      • \n
      • Runtime
      • \n
      • End-of-Life
      • \n
      \n

      A Documentation-only deprecation is one that is expressed only within the\nNode.js API docs. These generate no side-effects while running Node.js.\nSome Documentation-only deprecations trigger a runtime warning when launched\nwith --pending-deprecation flag (or its alternative,\nNODE_PENDING_DEPRECATION=1 environment variable), similarly to Runtime\ndeprecations below. Documentation-only deprecations that support that flag\nare explicitly labeled as such in the\nlist of Deprecated APIs.

      \n

      A Runtime deprecation will, by default, generate a process warning that will\nbe printed to stderr the first time the deprecated API is used. When the\n--throw-deprecation command-line flag is used, a Runtime deprecation will\ncause an error to be thrown.

      \n

      An End-of-Life deprecation is used when functionality is or will soon be removed\nfrom Node.js.

      ", + "miscs": [ + { + "textRaw": "Revoking deprecations", + "name": "revoking_deprecations", + "desc": "

      Occasionally, the deprecation of an API may be reversed. In such situations,\nthis document will be updated with information relevant to the decision.\nHowever, the deprecation identifier will not be modified.

      ", + "type": "misc", + "displayName": "Revoking deprecations" + }, + { + "textRaw": "List of deprecated APIs", + "name": "list_of_deprecated_apis", + "desc": "

      ", + "modules": [ + { + "textRaw": "DEP0001: `http.OutgoingMessage.prototype.flush`", + "name": "dep0001:_`http.outgoingmessage.prototype.flush`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.6.0", + "pr-url": "https://github.com/nodejs/node/pull/1156", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The OutgoingMessage.prototype.flush() method is deprecated. Use\nOutgoingMessage.prototype.flushHeaders() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0001: `http.OutgoingMessage.prototype.flush`" + }, + { + "textRaw": "DEP0002: `require('_linklist')`", + "name": "dep0002:_`require('_linklist')`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12113", + "description": "End-of-Life." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3078", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The _linklist module is deprecated. Please use a userland alternative.

      \n

      ", + "type": "module", + "displayName": "DEP0002: `require('_linklist')`" + }, + { + "textRaw": "DEP0003: `_writableState.buffer`", + "name": "dep0003:_`_writablestate.buffer`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.15", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/8826", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The _writableState.buffer property is deprecated. Use the\n_writableState.getBuffer() method instead.

      \n

      ", + "type": "module", + "displayName": "DEP0003: `_writableState.buffer`" + }, + { + "textRaw": "DEP0004: `CryptoStream.prototype.readyState`", + "name": "dep0004:_`cryptostream.prototype.readystate`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17882", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "0.4.0", + "commit": "9c7f89bf56abd37a796fea621ad2e47dd33d2b82", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The CryptoStream.prototype.readyState property was removed.

      \n

      ", + "type": "module", + "displayName": "DEP0004: `CryptoStream.prototype.readyState`" + }, + { + "textRaw": "DEP0005: `Buffer()` constructor", + "name": "dep0005:_`buffer()`_constructor", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19524", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4682", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime (supports --pending-deprecation)

      \n

      The Buffer() function and new Buffer() constructor are deprecated due to\nAPI usability issues that can lead to accidental security issues.

      \n

      As an alternative, use one of the following methods of constructing Buffer\nobjects:

      \n\n

      Without --pending-deprecation, runtime warnings occur only for code not in\nnode_modules. This means there will not be deprecation warnings for\nBuffer() usage in dependencies. With --pending-deprecation, a runtime\nwarning results no matter where the Buffer() usage occurs.

      \n

      ", + "type": "module", + "displayName": "DEP0005: `Buffer()` constructor" + }, + { + "textRaw": "DEP0006: `child_process` `options.customFds`", + "name": "dep0006:_`child_process`_`options.customfds`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25279", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.14", + "description": "Runtime deprecation." + }, + { + "version": "v0.5.11", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Within the child_process module's spawn(), fork(), and exec()\nmethods, the options.customFds option is deprecated. The options.stdio\noption should be used instead.

      \n

      ", + "type": "module", + "displayName": "DEP0006: `child_process` `options.customFds`" + }, + { + "textRaw": "DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`", + "name": "dep0007:_replace_`cluster`_`worker.suicide`_with_`worker.exitedafterdisconnect`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13702", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3747", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3743", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      In an earlier version of the Node.js cluster, a boolean property with the name\nsuicide was added to the Worker object. The intent of this property was to\nprovide an indication of how and why the Worker instance exited. In Node.js\n6.0.0, the old property was deprecated and replaced with a new\nworker.exitedAfterDisconnect property. The old property name did not\nprecisely describe the actual semantics and was unnecessarily emotion-laden.

      \n

      ", + "type": "module", + "displayName": "DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`" + }, + { + "textRaw": "DEP0008: `require('constants')`", + "name": "dep0008:_`require('constants')`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6534", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The constants module is deprecated. When requiring access to constants\nrelevant to specific Node.js builtin modules, developers should instead refer\nto the constants property exposed by the relevant module. For instance,\nrequire('fs').constants and require('os').constants.

      \n

      ", + "type": "module", + "displayName": "DEP0008: `require('constants')`" + }, + { + "textRaw": "DEP0009: `crypto.pbkdf2` without digest", + "name": "dep0009:_`crypto.pbkdf2`_without_digest", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22861", + "description": "Runtime deprecation (for `digest === null`)." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11305", + "description": "End-of-Life (for `digest === undefined`)." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4047", + "description": "Runtime deprecation (for `digest === undefined`)." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Use of the crypto.pbkdf2() API without specifying a digest was deprecated\nin Node.js 6.0 because the method defaulted to using the non-recommended\n'SHA1' digest. Previously, a deprecation warning was printed. Starting in\nNode.js 8.0.0, calling crypto.pbkdf2() or crypto.pbkdf2Sync() with\ndigest set to undefined will throw a TypeError.

      \n

      Beginning in Node.js v11.0.0, calling these functions with digest set to\nnull will print a deprecation warning to align with the behavior when digest\nis undefined.

      \n

      ", + "type": "module", + "displayName": "DEP0009: `crypto.pbkdf2` without digest" + }, + { + "textRaw": "DEP0010: `crypto.createCredentials`", + "name": "dep0010:_`crypto.createcredentials`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/21153", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.13", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7265", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The crypto.createCredentials() API was removed. Please use\ntls.createSecureContext() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0010: `crypto.createCredentials`" + }, + { + "textRaw": "DEP0011: `crypto.Credentials`", + "name": "dep0011:_`crypto.credentials`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/21153", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.13", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7265", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The crypto.Credentials class was removed. Please use tls.SecureContext\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0011: `crypto.Credentials`" + }, + { + "textRaw": "DEP0012: `Domain.dispose`", + "name": "dep0012:_`domain.dispose`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15412", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.7", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/5021", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Domain.dispose() has been removed. Recover from failed I/O actions\nexplicitly via error event handlers set on the domain instead.

      \n

      ", + "type": "module", + "displayName": "DEP0012: `Domain.dispose`" + }, + { + "textRaw": "DEP0013: `fs` asynchronous function without callback", + "name": "dep0013:_`fs`_asynchronous_function_without_callback", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18668", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Calling an asynchronous function without a callback throws a TypeError\nin Node.js 10.0.0 onwards. See https://github.com/nodejs/node/pull/12562.

      \n

      ", + "type": "module", + "displayName": "DEP0013: `fs` asynchronous function without callback" + }, + { + "textRaw": "DEP0014: `fs.read` legacy String interface", + "name": "dep0014:_`fs.read`_legacy_string_interface", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9683", + "description": "End-of-Life." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4525", + "description": "Runtime deprecation." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.1.96", + "commit": "c93e0aaf062081db3ec40ac45b3e2c979d5759d6", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The fs.read() legacy String interface is deprecated. Use the Buffer\nAPI as mentioned in the documentation instead.

      \n

      ", + "type": "module", + "displayName": "DEP0014: `fs.read` legacy String interface" + }, + { + "textRaw": "DEP0015: `fs.readSync` legacy String interface", + "name": "dep0015:_`fs.readsync`_legacy_string_interface", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9683", + "description": "End-of-Life." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4525", + "description": "Runtime deprecation." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.1.96", + "commit": "c93e0aaf062081db3ec40ac45b3e2c979d5759d6", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The fs.readSync() legacy String interface is deprecated. Use the\nBuffer API as mentioned in the documentation instead.

      \n

      ", + "type": "module", + "displayName": "DEP0015: `fs.readSync` legacy String interface" + }, + { + "textRaw": "DEP0016: `GLOBAL`/`root`", + "name": "dep0016:_`global`/`root`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/1838", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The GLOBAL and root aliases for the global property are deprecated\nand should no longer be used.

      \n

      ", + "type": "module", + "displayName": "DEP0016: `GLOBAL`/`root`" + }, + { + "textRaw": "DEP0017: `Intl.v8BreakIterator`", + "name": "dep0017:_`intl.v8breakiterator`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15238", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8908", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Intl.v8BreakIterator was a non-standard extension and has been removed.\nSee Intl.Segmenter.

      \n

      ", + "type": "module", + "displayName": "DEP0017: `Intl.v8BreakIterator`" + }, + { + "textRaw": "DEP0018: Unhandled promise rejections", + "name": "dep0018:_unhandled_promise_rejections", + "meta": { + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8217", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Unhandled promise rejections are deprecated. In the future, promise rejections\nthat are not handled will terminate the Node.js process with a non-zero exit\ncode.

      \n

      ", + "type": "module", + "displayName": "DEP0018: Unhandled promise rejections" + }, + { + "textRaw": "DEP0019: `require('.')` resolved outside directory", + "name": "dep0019:_`require('.')`_resolved_outside_directory", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26973", + "description": "Removed functionality." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.8.1", + "pr-url": "https://github.com/nodejs/node/pull/1363", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      In certain cases, require('.') could resolve outside the package directory.\nThis behavior has been removed.

      \n

      ", + "type": "module", + "displayName": "DEP0019: `require('.')` resolved outside directory" + }, + { + "textRaw": "DEP0020: `Server.connections`", + "name": "dep0020:_`server.connections`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.9.7", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/4595", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The Server.connections property is deprecated. Please use the\nServer.getConnections() method instead.

      \n

      ", + "type": "module", + "displayName": "DEP0020: `Server.connections`" + }, + { + "textRaw": "DEP0021: `Server.listenFD`", + "name": "dep0021:_`server.listenfd`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27127", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.7.12", + "commit": "41421ff9da1288aa241a5e9dcf915b685ade1c23", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The Server.listenFD() method was deprecated and removed. Please use\nServer.listen({fd: <number>}) instead.

      \n

      ", + "type": "module", + "displayName": "DEP0021: `Server.listenFD`" + }, + { + "textRaw": "DEP0022: `os.tmpDir()`", + "name": "dep0022:_`os.tmpdir()`", + "meta": { + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6739", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The os.tmpDir() API is deprecated. Please use os.tmpdir() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0022: `os.tmpDir()`" + }, + { + "textRaw": "DEP0023: `os.getNetworkInterfaces()`", + "name": "dep0023:_`os.getnetworkinterfaces()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25280", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.6.0", + "commit": "37bb37d151fb6ee4696730e63ff28bb7a4924f97", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The os.getNetworkInterfaces() method is deprecated. Please use the\nos.networkInterfaces() method instead.

      \n

      ", + "type": "module", + "displayName": "DEP0023: `os.getNetworkInterfaces()`" + }, + { + "textRaw": "DEP0024: `REPLServer.prototype.convertToContext()`", + "name": "dep0024:_`replserver.prototype.converttocontext()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13434", + "description": "End-of-Life." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7829", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The REPLServer.prototype.convertToContext() API has been removed.

      \n

      ", + "type": "module", + "displayName": "DEP0024: `REPLServer.prototype.convertToContext()`" + }, + { + "textRaw": "DEP0025: `require('sys')`", + "name": "dep0025:_`require('sys')`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.0.0", + "pr-url": "https://github.com/nodejs/node/pull/317", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The sys module is deprecated. Please use the util module instead.

      \n

      ", + "type": "module", + "displayName": "DEP0025: `require('sys')`" + }, + { + "textRaw": "DEP0026: `util.print()`", + "name": "dep0026:_`util.print()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.print() has been removed. Please use console.log() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0026: `util.print()`" + }, + { + "textRaw": "DEP0027: `util.puts()`", + "name": "dep0027:_`util.puts()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.puts() has been removed. Please use console.log() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0027: `util.puts()`" + }, + { + "textRaw": "DEP0028: `util.debug()`", + "name": "dep0028:_`util.debug()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.debug() has been removed. Please use console.error() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0028: `util.debug()`" + }, + { + "textRaw": "DEP0029: `util.error()`", + "name": "dep0029:_`util.error()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25377", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      util.error() has been removed. Please use console.error() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0029: `util.error()`" + }, + { + "textRaw": "DEP0030: `SlowBuffer`", + "name": "dep0030:_`slowbuffer`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5833", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The SlowBuffer class is deprecated. Please use\nBuffer.allocUnsafeSlow(size) instead.

      \n

      ", + "type": "module", + "displayName": "DEP0030: `SlowBuffer`" + }, + { + "textRaw": "DEP0031: `ecdh.setPublicKey()`", + "name": "dep0031:_`ecdh.setpublickey()`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v5.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3511", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful.

      \n

      ", + "type": "module", + "displayName": "DEP0031: `ecdh.setPublicKey()`" + }, + { + "textRaw": "DEP0032: `domain` module", + "name": "dep0032:_`domain`_module", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.4.2", + "pr-url": "https://github.com/nodejs/node/pull/943", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The domain module is deprecated and should not be used.

      \n

      ", + "type": "module", + "displayName": "DEP0032: `domain` module" + }, + { + "textRaw": "DEP0033: `EventEmitter.listenerCount()`", + "name": "dep0033:_`eventemitter.listenercount()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v3.2.0", + "pr-url": "https://github.com/nodejs/node/pull/2349", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The EventEmitter.listenerCount(emitter, eventName) API is\ndeprecated. Please use emitter.listenerCount(eventName) instead.

      \n

      ", + "type": "module", + "displayName": "DEP0033: `EventEmitter.listenerCount()`" + }, + { + "textRaw": "DEP0034: `fs.exists(path, callback)`", + "name": "dep0034:_`fs.exists(path,_callback)`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v1.0.0", + "pr-url": "https://github.com/iojs/io.js/pull/166", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The fs.exists(path, callback) API is deprecated. Please use\nfs.stat() or fs.access() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0034: `fs.exists(path, callback)`" + }, + { + "textRaw": "DEP0035: `fs.lchmod(path, mode, callback)`", + "name": "dep0035:_`fs.lchmod(path,_mode,_callback)`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The fs.lchmod(path, mode, callback) API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0035: `fs.lchmod(path, mode, callback)`" + }, + { + "textRaw": "DEP0036: `fs.lchmodSync(path, mode)`", + "name": "dep0036:_`fs.lchmodsync(path,_mode)`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The fs.lchmodSync(path, mode) API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0036: `fs.lchmodSync(path, mode)`" + }, + { + "textRaw": "DEP0037: `fs.lchown(path, uid, gid, callback)`", + "name": "dep0037:_`fs.lchown(path,_uid,_gid,_callback)`", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "Deprecation revoked." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Deprecation revoked

      \n

      The fs.lchown(path, uid, gid, callback) API was deprecated. The\ndeprecation was revoked because the requisite supporting APIs were added in\nlibuv.

      \n

      ", + "type": "module", + "displayName": "DEP0037: `fs.lchown(path, uid, gid, callback)`" + }, + { + "textRaw": "DEP0038: `fs.lchownSync(path, uid, gid)`", + "name": "dep0038:_`fs.lchownsync(path,_uid,_gid)`", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "Deprecation revoked." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Deprecation revoked

      \n

      The fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was\nrevoked because the requisite supporting APIs were added in libuv.

      \n

      ", + "type": "module", + "displayName": "DEP0038: `fs.lchownSync(path, uid, gid)`" + }, + { + "textRaw": "DEP0039: `require.extensions`", + "name": "dep0039:_`require.extensions`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.10.6", + "commit": "7bd8a5a2a60b75266f89f9a32877d55294a3881c", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The require.extensions property is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0039: `require.extensions`" + }, + { + "textRaw": "DEP0040: `punycode` module", + "name": "dep0040:_`punycode`_module", + "meta": { + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7941", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The punycode module is deprecated. Please use a userland alternative\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0040: `punycode` module" + }, + { + "textRaw": "DEP0041: `NODE_REPL_HISTORY_FILE` environment variable", + "name": "dep0041:_`node_repl_history_file`_environment_variable", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13876", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v3.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2224", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The NODE_REPL_HISTORY_FILE environment variable was removed. Please use\nNODE_REPL_HISTORY instead.

      \n

      ", + "type": "module", + "displayName": "DEP0041: `NODE_REPL_HISTORY_FILE` environment variable" + }, + { + "textRaw": "DEP0042: `tls.CryptoStream`", + "name": "dep0042:_`tls.cryptostream`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17882", + "description": "End-of-Life." + }, + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v0.11.3", + "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The tls.CryptoStream class was removed. Please use\ntls.TLSSocket instead.

      \n

      ", + "type": "module", + "displayName": "DEP0042: `tls.CryptoStream`" + }, + { + "textRaw": "DEP0043: `tls.SecurePair`", + "name": "dep0043:_`tls.securepair`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11349", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6063", + "description": "Documentation-only deprecation." + }, + { + "version": "v0.11.15", + "pr-url": [ + "https://github.com/nodejs/node-v0.x-archive/pull/8695", + "https://github.com/nodejs/node-v0.x-archive/pull/8700" + ], + "description": "Deprecation revoked." + }, + { + "version": "v0.11.3", + "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The tls.SecurePair class is deprecated. Please use\ntls.TLSSocket instead.

      \n

      ", + "type": "module", + "displayName": "DEP0043: `tls.SecurePair`" + }, + { + "textRaw": "DEP0044: `util.isArray()`", + "name": "dep0044:_`util.isarray()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isArray() API is deprecated. Please use Array.isArray()\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0044: `util.isArray()`" + }, + { + "textRaw": "DEP0045: `util.isBoolean()`", + "name": "dep0045:_`util.isboolean()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isBoolean() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0045: `util.isBoolean()`" + }, + { + "textRaw": "DEP0046: `util.isBuffer()`", + "name": "dep0046:_`util.isbuffer()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isBuffer() API is deprecated. Please use\nBuffer.isBuffer() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0046: `util.isBuffer()`" + }, + { + "textRaw": "DEP0047: `util.isDate()`", + "name": "dep0047:_`util.isdate()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isDate() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0047: `util.isDate()`" + }, + { + "textRaw": "DEP0048: `util.isError()`", + "name": "dep0048:_`util.iserror()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isError() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0048: `util.isError()`" + }, + { + "textRaw": "DEP0049: `util.isFunction()`", + "name": "dep0049:_`util.isfunction()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isFunction() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0049: `util.isFunction()`" + }, + { + "textRaw": "DEP0050: `util.isNull()`", + "name": "dep0050:_`util.isnull()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isNull() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0050: `util.isNull()`" + }, + { + "textRaw": "DEP0051: `util.isNullOrUndefined()`", + "name": "dep0051:_`util.isnullorundefined()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isNullOrUndefined() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0051: `util.isNullOrUndefined()`" + }, + { + "textRaw": "DEP0052: `util.isNumber()`", + "name": "dep0052:_`util.isnumber()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isNumber() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0052: `util.isNumber()`" + }, + { + "textRaw": "DEP0053 `util.isObject()`", + "name": "dep0053_`util.isobject()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isObject() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0053 `util.isObject()`" + }, + { + "textRaw": "DEP0054: `util.isPrimitive()`", + "name": "dep0054:_`util.isprimitive()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isPrimitive() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0054: `util.isPrimitive()`" + }, + { + "textRaw": "DEP0055: `util.isRegExp()`", + "name": "dep0055:_`util.isregexp()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isRegExp() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0055: `util.isRegExp()`" + }, + { + "textRaw": "DEP0056: `util.isString()`", + "name": "dep0056:_`util.isstring()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isString() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0056: `util.isString()`" + }, + { + "textRaw": "DEP0057: `util.isSymbol()`", + "name": "dep0057:_`util.issymbol()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isSymbol() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0057: `util.isSymbol()`" + }, + { + "textRaw": "DEP0058: `util.isUndefined()`", + "name": "dep0058:_`util.isundefined()`", + "meta": { + "changes": [ + { + "version": [ + "v4.8.6", + "v6.12.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": [ + "v3.3.1", + "v4.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/2447", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.isUndefined() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0058: `util.isUndefined()`" + }, + { + "textRaw": "DEP0059: `util.log()`", + "name": "dep0059:_`util.log()`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6161", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util.log() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0059: `util.log()`" + }, + { + "textRaw": "DEP0060: `util._extend()`", + "name": "dep0060:_`util._extend()`", + "meta": { + "changes": [ + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4903", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The util._extend() API is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0060: `util._extend()`" + }, + { + "textRaw": "DEP0061: `fs.SyncWriteStream`", + "name": "dep0061:_`fs.syncwritestream`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20735", + "description": "End-of-Life." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10467", + "description": "Runtime deprecation." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6749", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The fs.SyncWriteStream class was never intended to be a publicly accessible\nAPI and has been removed. No alternative API is available. Please use a userland\nalternative.

      \n

      ", + "type": "module", + "displayName": "DEP0061: `fs.SyncWriteStream`" + }, + { + "textRaw": "DEP0062: `node --debug`", + "name": "dep0062:_`node_--debug`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10970", + "description": "Runtime deprecation." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25828", + "description": "End-of-Life." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      --debug activates the legacy V8 debugger interface, which was removed as\nof V8 5.8. It is replaced by Inspector which is activated with --inspect\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0062: `node --debug`" + }, + { + "textRaw": "DEP0063: `ServerResponse.prototype.writeHeader()`", + "name": "dep0063:_`serverresponse.prototype.writeheader()`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11355", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The http module ServerResponse.prototype.writeHeader() API is\ndeprecated. Please use ServerResponse.prototype.writeHead() instead.

      \n

      The ServerResponse.prototype.writeHeader() method was never documented as an\nofficially supported API.

      \n

      ", + "type": "module", + "displayName": "DEP0063: `ServerResponse.prototype.writeHeader()`" + }, + { + "textRaw": "DEP0064: `tls.createSecurePair()`", + "name": "dep0064:_`tls.createsecurepair()`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11349", + "description": "Runtime deprecation." + }, + { + "version": "v6.12.0", + "pr-url": "https://github.com/nodejs/node/pull/10116", + "description": "A deprecation code has been assigned." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6063", + "description": "Documentation-only deprecation." + }, + { + "version": "v0.11.15", + "pr-url": [ + "https://github.com/nodejs/node-v0.x-archive/pull/8695", + "https://github.com/nodejs/node-v0.x-archive/pull/8700" + ], + "description": "Deprecation revoked." + }, + { + "version": "v0.11.3", + "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The tls.createSecurePair() API was deprecated in documentation in Node.js\n0.11.3. Users should use tls.Socket instead.

      \n

      ", + "type": "module", + "displayName": "DEP0064: `tls.createSecurePair()`" + }, + { + "textRaw": "DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`", + "name": "dep0065:_`repl.repl_mode_magic`_and_`node_repl_mode=magic`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19187", + "description": "End-of-Life." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11599", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The repl module's REPL_MODE_MAGIC constant, used for replMode option, has\nbeen removed. Its behavior has been functionally identical to that of\nREPL_MODE_SLOPPY since Node.js 6.0.0, when V8 5.0 was imported. Please use\nREPL_MODE_SLOPPY instead.

      \n

      The NODE_REPL_MODE environment variable is used to set the underlying\nreplMode of an interactive node session. Its value, magic, is also\nremoved. Please use sloppy instead.

      \n

      ", + "type": "module", + "displayName": "DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`" + }, + { + "textRaw": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`", + "name": "dep0066:_`outgoingmessage.prototype._headers,_outgoingmessage.prototype._headernames`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24167", + "description": "Runtime deprecation." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10941", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The http module OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties are deprecated. Use one of\nthe public methods (e.g. OutgoingMessage.prototype.getHeader(),\nOutgoingMessage.prototype.getHeaders(),\nOutgoingMessage.prototype.getHeaderNames(),\nOutgoingMessage.prototype.hasHeader(),\nOutgoingMessage.prototype.removeHeader(),\nOutgoingMessage.prototype.setHeader()) for working with outgoing headers.

      \n

      The OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties were never documented as\nofficially supported properties.

      \n

      ", + "type": "module", + "displayName": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`" + }, + { + "textRaw": "DEP0067: `OutgoingMessage.prototype._renderHeaders`", + "name": "dep0067:_`outgoingmessage.prototype._renderheaders`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10941", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The http module OutgoingMessage.prototype._renderHeaders() API is\ndeprecated.

      \n

      The OutgoingMessage.prototype._renderHeaders property was never documented as\nan officially supported API.

      \n

      ", + "type": "module", + "displayName": "DEP0067: `OutgoingMessage.prototype._renderHeaders`" + }, + { + "textRaw": "DEP0068: `node debug`", + "name": "dep0068:_`node_debug`", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11441", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      node debug corresponds to the legacy CLI debugger which has been replaced with\na V8-inspector based CLI debugger available through node inspect.

      \n

      ", + "type": "module", + "displayName": "DEP0068: `node debug`" + }, + { + "textRaw": "DEP0069: `vm.runInDebugContext(string)`", + "name": "dep0069:_`vm.runindebugcontext(string)`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13295", + "description": "End-of-Life." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12815", + "description": "Runtime deprecation." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12243", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      DebugContext has been removed in V8 and is not available in Node.js 10+.

      \n

      DebugContext was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0069: `vm.runInDebugContext(string)`" + }, + { + "textRaw": "DEP0070: `async_hooks.currentId()`", + "name": "dep0070:_`async_hooks.currentid()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14414", + "description": "End-of-Life." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      async_hooks.currentId() was renamed to async_hooks.executionAsyncId() for\nclarity.

      \n

      This change was made while async_hooks was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0070: `async_hooks.currentId()`" + }, + { + "textRaw": "DEP0071: `async_hooks.triggerId()`", + "name": "dep0071:_`async_hooks.triggerid()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14414", + "description": "End-of-Life." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      async_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for\nclarity.

      \n

      This change was made while async_hooks was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0071: `async_hooks.triggerId()`" + }, + { + "textRaw": "DEP0072: `async_hooks.AsyncResource.triggerId()`", + "name": "dep0072:_`async_hooks.asyncresource.triggerid()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14414", + "description": "End-of-Life." + }, + { + "version": "v8.2.0", + "pr-url": "https://github.com/nodejs/node/pull/13490", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      async_hooks.AsyncResource.triggerId() was renamed to\nasync_hooks.AsyncResource.triggerAsyncId() for clarity.

      \n

      This change was made while async_hooks was an experimental API.

      \n

      ", + "type": "module", + "displayName": "DEP0072: `async_hooks.AsyncResource.triggerId()`" + }, + { + "textRaw": "DEP0073: Several internal properties of `net.Server`", + "name": "dep0073:_several_internal_properties_of_`net.server`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17141", + "description": "End-of-Life." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14449", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Accessing several internal, undocumented properties of net.Server instances\nwith inappropriate names is deprecated.

      \n

      As the original API was undocumented and not generally useful for non-internal\ncode, no replacement API is provided.

      \n

      ", + "type": "module", + "displayName": "DEP0073: Several internal properties of `net.Server`" + }, + { + "textRaw": "DEP0074: `REPLServer.bufferedCommand`", + "name": "dep0074:_`replserver.bufferedcommand`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13687", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The REPLServer.bufferedCommand property was deprecated in favor of\nREPLServer.clearBufferedCommand().

      \n

      ", + "type": "module", + "displayName": "DEP0074: `REPLServer.bufferedCommand`" + }, + { + "textRaw": "DEP0075: `REPLServer.parseREPLKeyword()`", + "name": "dep0075:_`replserver.parsereplkeyword()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14223", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      REPLServer.parseREPLKeyword() was removed from userland visibility.

      \n

      ", + "type": "module", + "displayName": "DEP0075: `REPLServer.parseREPLKeyword()`" + }, + { + "textRaw": "DEP0076: `tls.parseCertString()`", + "name": "dep0076:_`tls.parsecertstring()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14249", + "description": "Runtime deprecation." + }, + { + "version": "v8.6.0", + "pr-url": "https://github.com/nodejs/node/pull/14245", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      tls.parseCertString() is a trivial parsing helper that was made public by\nmistake. This function can usually be replaced with:

      \n
      const querystring = require('querystring');\nquerystring.parse(str, '\\n', '=');\n
      \n

      This function is not completely equivalent to querystring.parse(). One\ndifference is that querystring.parse() does url decoding:

      \n
      > querystring.parse('%E5%A5%BD=1', '\\n', '=');\n{ '好': '1' }\n> tls.parseCertString('%E5%A5%BD=1');\n{ '%E5%A5%BD': '1' }\n
      \n

      ", + "type": "module", + "displayName": "DEP0076: `tls.parseCertString()`" + }, + { + "textRaw": "DEP0077: `Module._debug()`", + "name": "dep0077:_`module._debug()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13948", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Module._debug() is deprecated.

      \n

      The Module._debug() function was never documented as an officially\nsupported API.

      \n

      ", + "type": "module", + "displayName": "DEP0077: `Module._debug()`" + }, + { + "textRaw": "DEP0078: `REPLServer.turnOffEditorMode()`", + "name": "dep0078:_`replserver.turnoffeditormode()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15136", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      REPLServer.turnOffEditorMode() was removed from userland visibility.

      \n

      ", + "type": "module", + "displayName": "DEP0078: `REPLServer.turnOffEditorMode()`" + }, + { + "textRaw": "DEP0079: Custom inspection function on objects via `.inspect()`", + "name": "dep0079:_custom_inspection_function_on_objects_via_`.inspect()`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20722", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16393", + "description": "Runtime deprecation." + }, + { + "version": "v8.7.0", + "pr-url": "https://github.com/nodejs/node/pull/15631", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Using a property named inspect on an object to specify a custom inspection\nfunction for util.inspect() is deprecated. Use util.inspect.custom\ninstead. For backward compatibility with Node.js prior to version 6.4.0, both\nmay be specified.

      \n

      ", + "type": "module", + "displayName": "DEP0079: Custom inspection function on objects via `.inspect()`" + }, + { + "textRaw": "DEP0080: `path._makeLong()`", + "name": "dep0080:_`path._makelong()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/14956", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The internal path._makeLong() was not intended for public use. However,\nuserland modules have found it useful. The internal API is deprecated\nand replaced with an identical, public path.toNamespacedPath() method.

      \n

      ", + "type": "module", + "displayName": "DEP0080: `path._makeLong()`" + }, + { + "textRaw": "DEP0081: `fs.truncate()` using a file descriptor", + "name": "dep0081:_`fs.truncate()`_using_a_file_descriptor", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15990", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      fs.truncate() fs.truncateSync() usage with a file descriptor is\ndeprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with\nfile descriptors.

      \n

      ", + "type": "module", + "displayName": "DEP0081: `fs.truncate()` using a file descriptor" + }, + { + "textRaw": "DEP0082: `REPLServer.prototype.memory()`", + "name": "dep0082:_`replserver.prototype.memory()`", + "meta": { + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16242", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      REPLServer.prototype.memory() is only necessary for the internal mechanics of\nthe REPLServer itself. Do not use this function.

      \n

      ", + "type": "module", + "displayName": "DEP0082: `REPLServer.prototype.memory()`" + }, + { + "textRaw": "DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`", + "name": "dep0083:_disabling_ecdh_by_setting_`ecdhcurve`_to_`false`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19794", + "description": "End-of-Life." + }, + { + "version": "v9.2.0", + "pr-url": "https://github.com/nodejs/node/pull/16130", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life.

      \n

      The ecdhCurve option to tls.createSecureContext() and tls.TLSSocket could\nbe set to false to disable ECDH entirely on the server only. This mode was\ndeprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with\nthe client and is now unsupported. Use the ciphers parameter instead.

      \n

      ", + "type": "module", + "displayName": "DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`" + }, + { + "textRaw": "DEP0084: requiring bundled internal dependencies", + "name": "dep0084:_requiring_bundled_internal_dependencies", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25138", + "description": "This functionality has been removed." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16392", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for\ninternal usage were mistakenly exposed to user code through require(). These\nmodules were:

      \n
        \n
      • v8/tools/codemap
      • \n
      • v8/tools/consarray
      • \n
      • v8/tools/csvparser
      • \n
      • v8/tools/logreader
      • \n
      • v8/tools/profile_view
      • \n
      • v8/tools/profile
      • \n
      • v8/tools/SourceMap
      • \n
      • v8/tools/splaytree
      • \n
      • v8/tools/tickprocessor-driver
      • \n
      • v8/tools/tickprocessor
      • \n
      • node-inspect/lib/_inspect (from 7.6.0)
      • \n
      • node-inspect/lib/internal/inspect_client (from 7.6.0)
      • \n
      • node-inspect/lib/internal/inspect_repl (from 7.6.0)
      • \n
      \n

      The v8/* modules do not have any exports, and if not imported in a specific\norder would in fact throw errors. As such there are virtually no legitimate use\ncases for importing them through require().

      \n

      On the other hand, node-inspect may be installed locally through a package\nmanager, as it is published on the npm registry under the same name. No source\ncode modification is necessary if that is done.

      \n

      ", + "type": "module", + "displayName": "DEP0084: requiring bundled internal dependencies" + }, + { + "textRaw": "DEP0085: AsyncHooks sensitive API", + "name": "dep0085:_asynchooks_sensitive_api", + "meta": { + "changes": [ + { + "version": "10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17147", + "description": "End-of-Life." + }, + { + "version": [ + "v8.10.0", + "v9.4.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/16972", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The AsyncHooks sensitive API was never documented and had various minor issues.\nUse the AsyncResource API instead. See\nhttps://github.com/nodejs/node/issues/15572.

      \n

      ", + "type": "module", + "displayName": "DEP0085: AsyncHooks sensitive API" + }, + { + "textRaw": "DEP0086: Remove `runInAsyncIdScope`", + "name": "dep0086:_remove_`runinasyncidscope`", + "meta": { + "changes": [ + { + "version": "10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17147", + "description": "End-of-Life." + }, + { + "version": [ + "v8.10.0", + "v9.4.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/16972", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      runInAsyncIdScope doesn't emit the 'before' or 'after' event and can thus\ncause a lot of issues. See https://github.com/nodejs/node/issues/14328.

      \n

      ", + "type": "module", + "displayName": "DEP0086: Remove `runInAsyncIdScope`" + }, + { + "textRaw": "DEP0089: `require('assert')`", + "name": "dep0089:_`require('assert')`", + "meta": { + "changes": [ + { + "version": "v12.8.0", + "pr-url": "https://github.com/nodejs/node/pull/28892", + "description": "Deprecation revoked." + }, + { + "version": [ + "v9.9.0", + "v10.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/17002", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Deprecation revoked

      \n

      Importing assert directly was not recommended as the exposed functions use\nloose equality checks. The deprecation was revoked because use of the assert\nmodule is not discouraged, and the deprecation caused developer confusion.

      \n

      ", + "type": "module", + "displayName": "DEP0089: `require('assert')`" + }, + { + "textRaw": "DEP0090: Invalid GCM authentication tag lengths", + "name": "dep0090:_invalid_gcm_authentication_tag_lengths", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17825", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18017", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Node.js used to support all GCM authentication tag lengths which are accepted by\nOpenSSL when calling decipher.setAuthTag(). Beginning with Node.js\nv11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32\nbits are allowed. Authentication tags of other lengths are invalid per\nNIST SP 800-38D.

      \n

      ", + "type": "module", + "displayName": "DEP0090: Invalid GCM authentication tag lengths" + }, + { + "textRaw": "DEP0091: `crypto.DEFAULT_ENCODING`", + "name": "dep0091:_`crypto.default_encoding`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18333", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The crypto.DEFAULT_ENCODING property is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0091: `crypto.DEFAULT_ENCODING`" + }, + { + "textRaw": "DEP0092: Top-level `this` bound to `module.exports`", + "name": "dep0092:_top-level_`this`_bound_to_`module.exports`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16878", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Assigning properties to the top-level this as an alternative\nto module.exports is deprecated. Developers should use exports\nor module.exports instead.

      \n

      ", + "type": "module", + "displayName": "DEP0092: Top-level `this` bound to `module.exports`" + }, + { + "textRaw": "DEP0093: `crypto.fips` is deprecated and replaced.", + "name": "dep0093:_`crypto.fips`_is_deprecated_and_replaced.", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18335", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The crypto.fips property is deprecated. Please use crypto.setFips()\nand crypto.getFips() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0093: `crypto.fips` is deprecated and replaced." + }, + { + "textRaw": "DEP0094: Using `assert.fail()` with more than one argument.", + "name": "dep0094:_using_`assert.fail()`_with_more_than_one_argument.", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18418", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Using assert.fail() with more than one argument is deprecated. Use\nassert.fail() with only one argument or use a different assert module\nmethod.

      \n

      ", + "type": "module", + "displayName": "DEP0094: Using `assert.fail()` with more than one argument." + }, + { + "textRaw": "DEP0095: `timers.enroll()`", + "name": "dep0095:_`timers.enroll()`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18066", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      timers.enroll() is deprecated. Please use the publicly documented\nsetTimeout() or setInterval() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0095: `timers.enroll()`" + }, + { + "textRaw": "DEP0096: `timers.unenroll()`", + "name": "dep0096:_`timers.unenroll()`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18066", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      timers.unenroll() is deprecated. Please use the publicly documented\nclearTimeout() or clearInterval() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0096: `timers.unenroll()`" + }, + { + "textRaw": "DEP0097: `MakeCallback` with `domain` property", + "name": "dep0097:_`makecallback`_with_`domain`_property", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17417", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Users of MakeCallback that add the domain property to carry context,\nshould start using the async_context variant of MakeCallback or\nCallbackScope, or the high-level AsyncResource class.

      \n

      ", + "type": "module", + "displayName": "DEP0097: `MakeCallback` with `domain` property" + }, + { + "textRaw": "DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs", + "name": "dep0098:_asynchooks_embedder_`asyncresource.emitbefore`_and_`asyncresource.emitafter`_apis", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26530", + "description": "End-of-Life" + }, + { + "version": [ + "v8.12.0", + "v9.6.0", + "v10.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/18632", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The embedded API provided by AsyncHooks exposes .emitBefore() and\n.emitAfter() methods which are very easy to use incorrectly which can lead\nto unrecoverable errors.

      \n

      Use asyncResource.runInAsyncScope() API instead which provides a much\nsafer, and more convenient, alternative. See\nhttps://github.com/nodejs/node/pull/18513.

      \n

      ", + "type": "module", + "displayName": "DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs" + }, + { + "textRaw": "DEP0099: Async context-unaware `node::MakeCallback` C++ APIs", + "name": "dep0099:_async_context-unaware_`node::makecallback`_c++_apis", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18632", + "description": "Compile-time deprecation." + } + ] + }, + "desc": "

      Type: Compile-time

      \n

      Certain versions of node::MakeCallback APIs available to native modules are\ndeprecated. Please use the versions of the API that accept an async_context\nparameter.

      \n

      ", + "type": "module", + "displayName": "DEP0099: Async context-unaware `node::MakeCallback` C++ APIs" + }, + { + "textRaw": "DEP0100: `process.assert()`", + "name": "dep0100:_`process.assert()`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18666", + "description": "Runtime deprecation." + }, + { + "version": "v0.3.7", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      process.assert() is deprecated. Please use the assert module instead.

      \n

      This was never a documented feature.

      \n

      ", + "type": "module", + "displayName": "DEP0100: `process.assert()`" + }, + { + "textRaw": "DEP0101: `--with-lttng`", + "name": "dep0101:_`--with-lttng`", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18982", + "description": "End-of-Life." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The --with-lttng compile-time option has been removed.

      \n

      ", + "type": "module", + "displayName": "DEP0101: `--with-lttng`" + }, + { + "textRaw": "DEP0102: Using `noAssert` in `Buffer#(read|write)` operations.", + "name": "dep0102:_using_`noassert`_in_`buffer#(read|write)`_operations.", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18395", + "description": "End-of-Life." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Using the noAssert argument has no functionality anymore. All input is going\nto be verified, no matter if it is set to true or not. Skipping the verification\ncould lead to hard to find errors and crashes.

      \n

      ", + "type": "module", + "displayName": "DEP0102: Using `noAssert` in `Buffer#(read|write)` operations." + }, + { + "textRaw": "DEP0103: `process.binding('util').is[...]` typechecks", + "name": "dep0103:_`process.binding('util').is[...]`_typechecks", + "meta": { + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/22004", + "description": "Superseded by [DEP0111](#DEP0111)." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18415", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      Using process.binding() in general should be avoided. The type checking\nmethods in particular can be replaced by using util.types.

      \n

      This deprecation has been superseded by the deprecation of the\nprocess.binding() API (DEP0111).

      \n

      ", + "type": "module", + "displayName": "DEP0103: `process.binding('util').is[...]` typechecks" + }, + { + "textRaw": "DEP0104: `process.env` string coercion", + "name": "dep0104:_`process.env`_string_coercion", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18990", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      When assigning a non-string property to process.env, the assigned value is\nimplicitly converted to a string. This behavior is deprecated if the assigned\nvalue is not a string, boolean, or number. In the future, such assignment may\nresult in a thrown error. Please convert the property to a string before\nassigning it to process.env.

      \n

      ", + "type": "module", + "displayName": "DEP0104: `process.env` string coercion" + }, + { + "textRaw": "DEP0105: `decipher.finaltol`", + "name": "dep0105:_`decipher.finaltol`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19941", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19353", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      decipher.finaltol() has never been documented and was an alias for\ndecipher.final(). This API has been removed, and it is recommended to use\ndecipher.final() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0105: `decipher.finaltol`" + }, + { + "textRaw": "DEP0106: `crypto.createCipher` and `crypto.createDecipher`", + "name": "dep0106:_`crypto.createcipher`_and_`crypto.createdecipher`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22089", + "description": "Runtime deprecation." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19343", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Using crypto.createCipher() and crypto.createDecipher() should be\navoided as they use a weak key derivation function (MD5 with no salt) and static\ninitialization vectors. It is recommended to derive a key using\ncrypto.pbkdf2() or crypto.scrypt() and to use\ncrypto.createCipheriv() and crypto.createDecipheriv() to obtain the\nCipher and Decipher objects respectively.

      \n

      ", + "type": "module", + "displayName": "DEP0106: `crypto.createCipher` and `crypto.createDecipher`" + }, + { + "textRaw": "DEP0107: `tls.convertNPNProtocols()`", + "name": "dep0107:_`tls.convertnpnprotocols()`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20736", + "description": "End-of-Life." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19403", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      This was an undocumented helper function not intended for use outside Node.js\ncore and obsoleted by the removal of NPN (Next Protocol Negotiation) support.

      \n

      ", + "type": "module", + "displayName": "DEP0107: `tls.convertNPNProtocols()`" + }, + { + "textRaw": "DEP0108: `zlib.bytesRead`", + "name": "dep0108:_`zlib.bytesread`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23308", + "description": "Runtime deprecation." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19414", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Deprecated alias for zlib.bytesWritten. This original name was chosen\nbecause it also made sense to interpret the value as the number of bytes\nread by the engine, but is inconsistent with other streams in Node.js that\nexpose values under these names.

      \n

      ", + "type": "module", + "displayName": "DEP0108: `zlib.bytesRead`" + }, + { + "textRaw": "DEP0109: `http`, `https`, and `tls` support for invalid URLs", + "name": "dep0109:_`http`,_`https`,_and_`tls`_support_for_invalid_urls", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20270", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Some previously supported (but strictly invalid) URLs were accepted through the\nhttp.request(), http.get(), https.request(),\nhttps.get(), and tls.checkServerIdentity() APIs because those were\naccepted by the legacy url.parse() API. The mentioned APIs now use the WHATWG\nURL parser that requires strictly valid URLs. Passing an invalid URL is\ndeprecated and support will be removed in the future.

      \n

      ", + "type": "module", + "displayName": "DEP0109: `http`, `https`, and `tls` support for invalid URLs" + }, + { + "textRaw": "DEP0110: `vm.Script` cached data", + "name": "dep0110:_`vm.script`_cached_data", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/20300", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The produceCachedData option is deprecated. Use\nscript.createCachedData() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0110: `vm.Script` cached data" + }, + { + "textRaw": "DEP0111: `process.binding()`", + "name": "dep0111:_`process.binding()`", + "meta": { + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/22004", + "description": "Documentation-only deprecation." + }, + { + "version": "v11.12.0", + "pr-url": "https://github.com/nodejs/node/pull/26500", + "description": "Added support for `--pending-deprecation`." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      process.binding() is for use by Node.js internal code only.

      \n

      ", + "type": "module", + "displayName": "DEP0111: `process.binding()`" + }, + { + "textRaw": "DEP0112: `dgram` private APIs", + "name": "dep0112:_`dgram`_private_apis", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22011", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The dgram module previously contained several APIs that were never meant to\naccessed outside of Node.js core: Socket.prototype._handle,\nSocket.prototype._receiving, Socket.prototype._bindState,\nSocket.prototype._queue, Socket.prototype._reuseAddr,\nSocket.prototype._healthCheck(), Socket.prototype._stopReceiving(), and\ndgram._createSocketHandle().

      \n

      ", + "type": "module", + "displayName": "DEP0112: `dgram` private APIs" + }, + { + "textRaw": "DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`", + "name": "dep0113:_`cipher.setauthtag()`,_`decipher.getauthtag()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26249", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22126", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Cipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They\nwere never documented and would throw when called.

      \n

      ", + "type": "module", + "displayName": "DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`" + }, + { + "textRaw": "DEP0114: `crypto._toBuf()`", + "name": "dep0114:_`crypto._tobuf()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25338", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22501", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      The crypto._toBuf() function was not designed to be used by modules outside\nof Node.js core and was removed.

      \n

      ", + "type": "module", + "displayName": "DEP0114: `crypto._toBuf()`" + }, + { + "textRaw": "DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`", + "name": "dep0115:_`crypto.prng()`,_`crypto.pseudorandombytes()`,_`crypto.rng()`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": [ + "https://github.com/nodejs/node/pull/22519", + "https://github.com/nodejs/node/pull/23017" + ], + "description": "Added documentation-only deprecation with `--pending-deprecation` support." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      In recent versions of Node.js, there is no difference between\ncrypto.randomBytes() and crypto.pseudoRandomBytes(). The latter is\ndeprecated along with the undocumented aliases crypto.prng() and\ncrypto.rng() in favor of crypto.randomBytes() and may be removed in a\nfuture release.

      \n

      ", + "type": "module", + "displayName": "DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`" + }, + { + "textRaw": "DEP0116: Legacy URL API", + "name": "dep0116:_legacy_url_api", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The Legacy URL API is deprecated. This includes url.format(),\nurl.parse(), url.resolve(), and the legacy urlObject. Please\nuse the WHATWG URL API instead.

      \n

      ", + "type": "module", + "displayName": "DEP0116: Legacy URL API" + }, + { + "textRaw": "DEP0117: Native crypto handles", + "name": "dep0117:_native_crypto_handles", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27011", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22747", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Previous versions of Node.js exposed handles to internal native objects through\nthe _handle property of the Cipher, Decipher, DiffieHellman,\nDiffieHellmanGroup, ECDH, Hash, Hmac, Sign, and Verify classes.\nThe _handle property has been removed because improper use of the native\nobject can lead to crashing the application.

      \n

      ", + "type": "module", + "displayName": "DEP0117: Native crypto handles" + }, + { + "textRaw": "DEP0118: `dns.lookup()` support for a falsy host name", + "name": "dep0118:_`dns.lookup()`_support_for_a_falsy_host_name", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23173", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Previous versions of Node.js supported dns.lookup() with a falsy host name\nlike dns.lookup(false) due to backward compatibility.\nThis behavior is undocumented and is thought to be unused in real world apps.\nIt will become an error in future versions of Node.js.

      \n

      ", + "type": "module", + "displayName": "DEP0118: `dns.lookup()` support for a falsy host name" + }, + { + "textRaw": "DEP0119: `process.binding('uv').errname()` private API", + "name": "dep0119:_`process.binding('uv').errname()`_private_api", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23597", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      process.binding('uv').errname() is deprecated. Please use\nutil.getSystemErrorName() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0119: `process.binding('uv').errname()` private API" + }, + { + "textRaw": "DEP0120: Windows Performance Counter support", + "name": "dep0120:_windows_performance_counter_support", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24862", + "description": "End-of-Life." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22485", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: End-of-Life

      \n

      Windows Performance Counter support has been removed from Node.js. The\nundocumented COUNTER_NET_SERVER_CONNECTION(),\nCOUNTER_NET_SERVER_CONNECTION_CLOSE(), COUNTER_HTTP_SERVER_REQUEST(),\nCOUNTER_HTTP_SERVER_RESPONSE(), COUNTER_HTTP_CLIENT_REQUEST(), and\nCOUNTER_HTTP_CLIENT_RESPONSE() functions have been deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0120: Windows Performance Counter support" + }, + { + "textRaw": "DEP0121: `net._setSimultaneousAccepts()`", + "name": "dep0121:_`net._setsimultaneousaccepts()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23760", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The undocumented net._setSimultaneousAccepts() function was originally\nintended for debugging and performance tuning when using the child_process\nand cluster modules on Windows. The function is not generally useful and\nis being removed. See discussion here:\nhttps://github.com/nodejs/node/issues/18391

      \n

      ", + "type": "module", + "displayName": "DEP0121: `net._setSimultaneousAccepts()`" + }, + { + "textRaw": "DEP0122: `tls` `Server.prototype.setOptions()`", + "name": "dep0122:_`tls`_`server.prototype.setoptions()`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23820", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Please use Server.prototype.setSecureContext() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0122: `tls` `Server.prototype.setOptions()`" + }, + { + "textRaw": "DEP0123: setting the TLS ServerName to an IP address", + "name": "dep0123:_setting_the_tls_servername_to_an_ip_address", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23329", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Setting the TLS ServerName to an IP address is not permitted by\nRFC 6066. This will be ignored in a future version.

      \n

      ", + "type": "module", + "displayName": "DEP0123: setting the TLS ServerName to an IP address" + }, + { + "textRaw": "DEP0124: using `REPLServer.rli`", + "name": "dep0124:_using_`replserver.rli`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26260", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      This property is a reference to the instance itself.

      \n

      ", + "type": "module", + "displayName": "DEP0124: using `REPLServer.rli`" + }, + { + "textRaw": "DEP0125: `require('_stream_wrap')`", + "name": "dep0125:_`require('_stream_wrap')`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26245", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The _stream_wrap module is deprecated.

      \n

      ", + "type": "module", + "displayName": "DEP0125: `require('_stream_wrap')`" + }, + { + "textRaw": "DEP0126: `timers.active()`", + "name": "dep0126:_`timers.active()`", + "meta": { + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26760", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The previously undocumented timers.active() is deprecated.\nPlease use the publicly documented timeout.refresh() instead.\nIf re-referencing the timeout is necessary, timeout.ref() can be used\nwith no performance impact since Node.js 10.

      \n

      ", + "type": "module", + "displayName": "DEP0126: `timers.active()`" + }, + { + "textRaw": "DEP0127: `timers._unrefActive()`", + "name": "dep0127:_`timers._unrefactive()`", + "meta": { + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26760", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The previously undocumented and \"private\" timers._unrefActive() is deprecated.\nPlease use the publicly documented timeout.refresh() instead.\nIf unreferencing the timeout is necessary, timeout.unref() can be used\nwith no performance impact since Node.js 10.

      \n

      ", + "type": "module", + "displayName": "DEP0127: `timers._unrefActive()`" + }, + { + "textRaw": "DEP0128: modules with an invalid `main` entry and an `index.js` file", + "name": "dep0128:_modules_with_an_invalid_`main`_entry_and_an_`index.js`_file", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26823", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      Modules that have an invalid main entry (e.g., ./does-not-exist.js) and\nalso have an index.js file in the top level directory will resolve the\nindex.js file. That is deprecated and is going to throw an error in future\nNode.js versions.

      \n

      ", + "type": "module", + "displayName": "DEP0128: modules with an invalid `main` entry and an `index.js` file" + }, + { + "textRaw": "DEP0129: `ChildProcess._channel`", + "name": "dep0129:_`childprocess._channel`", + "meta": { + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26982", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      The _channel property of child process objects returned by spawn() and\nsimilar functions is not intended for public use. Use ChildProcess.channel\ninstead.

      \n

      ", + "type": "module", + "displayName": "DEP0129: `ChildProcess._channel`" + }, + { + "textRaw": "DEP0130: `Module.createRequireFromPath()`", + "name": "dep0130:_`module.createrequirefrompath()`", + "meta": { + "changes": [ + { + "version": "v12.2.0", + "pr-url": "https://github.com/nodejs/node/pull/27405", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Module.createRequireFromPath() is deprecated. Please use module.createRequire() instead.

      \n

      ", + "type": "module", + "displayName": "DEP0130: `Module.createRequireFromPath()`" + }, + { + "textRaw": "DEP0131: Legacy HTTP parser", + "name": "dep0131:_legacy_http_parser", + "meta": { + "changes": [ + { + "version": "v12.22.0", + "pr-url": "https://github.com/nodejs/node/pull/37603", + "description": "Runtime deprecation." + }, + { + "version": "v12.3.0", + "pr-url": "https://github.com/nodejs/node/pull/27498", + "description": "Documentation-only." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0,\nis deprecated. This deprecation applies to users of the\n--http-parser=legacy command-line flag.

      \n

      ", + "type": "module", + "displayName": "DEP0131: Legacy HTTP parser" + }, + { + "textRaw": "DEP0132: `worker.terminate()` with callback", + "name": "dep0132:_`worker.terminate()`_with_callback", + "meta": { + "changes": [ + { + "version": "v12.5.0", + "pr-url": "https://github.com/nodejs/node/pull/28021", + "description": "Runtime deprecation." + } + ] + }, + "desc": "

      Type: Runtime

      \n

      Passing a callback to worker.terminate() is deprecated. Use the returned\nPromise instead, or a listener to the worker’s 'exit' event.

      \n

      ", + "type": "module", + "displayName": "DEP0132: `worker.terminate()` with callback" + }, + { + "textRaw": "DEP0133: `http` `connection`", + "name": "dep0133:_`http`_`connection`", + "meta": { + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29015", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Prefer response.socket over response.connection and\nrequest.socket over request.connection.

      \n

      ", + "type": "module", + "displayName": "DEP0133: `http` `connection`" + }, + { + "textRaw": "DEP0134: `process._tickCallback`", + "name": "dep0134:_`process._tickcallback`", + "meta": { + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29781", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only (supports --pending-deprecation)

      \n

      The process._tickCallback property was never documented as\nan officially supported API.

      \n

      ", + "type": "module", + "displayName": "DEP0134: `process._tickCallback`" + }, + { + "textRaw": "DEP0136: `http` `finished`", + "name": "dep0136:_`http`_`finished`", + "meta": { + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/28679", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      response.finished indicates whether response.end() has been\ncalled, not whether 'finish' has been emitted and the underlying data\nis flushed.

      \n

      Use response.writableFinished or response.writableEnded\naccordingly instead to avoid the ambigiuty.

      \n

      To maintain existing behaviour response.finished should be replaced with\nresponse.writableEnded.

      \n

      ", + "type": "module", + "displayName": "DEP0136: `http` `finished`" + }, + { + "textRaw": "DEP0139: `process.umask()` with no arguments", + "name": "dep0139:_`process.umask()`_with_no_arguments", + "meta": { + "changes": [ + { + "version": [ + "v12.19.0", + "v14.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/32499", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      Calling process.umask() with no argument causes the process-wide umask to be\nwritten twice. This introduces a race condition between threads, and is a\npotential security vulnerability. There is no safe, cross-platform alternative\nAPI.

      \n

      ", + "type": "module", + "displayName": "DEP0139: `process.umask()` with no arguments" + }, + { + "textRaw": "DEP0144: `module.parent`", + "name": "dep0144:_`module.parent`", + "meta": { + "changes": [ + { + "version": [ + "v12.19.0", + "v14.6.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/32217", + "description": "Documentation-only deprecation." + } + ] + }, + "desc": "

      Type: Documentation-only

      \n

      A CommonJS module can access the first module that required it using\nmodule.parent. This feature is deprecated because it does not work\nconsistently in the presence of ECMAScript modules and because it gives an\ninaccurate representation of the CommonJS module graph.

      \n

      Some modules use it to check if they are the entry point of the current process.\nInstead, it is recommended to compare require.main and module:

      \n
      if (require.main === module) {\n  // Code section that will run only if current file is the entry point.\n}\n
      \n

      When looking for the CommonJS modules that have required the current one,\nrequire.cache and module.children can be used:

      \n
      const moduleParents = Object.values(require.cache)\n  .filter((m) => m.children.includes(module));\n
      ", + "type": "module", + "displayName": "DEP0144: `module.parent`" + } + ], + "type": "misc", + "displayName": "List of deprecated APIs" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 8333597513a7569e49342c3ba0acd805d7b738d6..59df3c52cce6f452826c00e58598756f7073cbfe 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -2469,12 +2469,15 @@ Module.createRequireFromPath() is deprecated. Please use [`module.createRequire( ### DEP0131: Legacy HTTP parser -Type: Documentation-only +Type: Runtime The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0, is deprecated. This deprecation applies to users of the diff --git a/doc/api/dgram.html b/doc/api/dgram.html new file mode 100644 index 0000000000000000000000000000000000000000..fc4d9c904aba81f69bbc68a18d1d28f16c246dba --- /dev/null +++ b/doc/api/dgram.html @@ -0,0 +1,857 @@ + + + + + + + UDP/datagram sockets | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      UDP/datagram sockets#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/dgram.js

      +

      The dgram module provides an implementation of UDP datagram sockets.

      +
      const dgram = require('dgram');
      +const server = dgram.createSocket('udp4');
      +
      +server.on('error', (err) => {
      +  console.log(`server error:\n${err.stack}`);
      +  server.close();
      +});
      +
      +server.on('message', (msg, rinfo) => {
      +  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
      +});
      +
      +server.on('listening', () => {
      +  const address = server.address();
      +  console.log(`server listening ${address.address}:${address.port}`);
      +});
      +
      +server.bind(41234);
      +// Prints: server listening 0.0.0.0:41234
      +

      Class: dgram.Socket#

      + + +

      Encapsulates the datagram functionality.

      +

      New instances of dgram.Socket are created using dgram.createSocket(). +The new keyword is not to be used to create dgram.Socket instances.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted after a socket is closed with close(). +Once triggered, no new 'message' events will be emitted on this socket.

      +

      Event: 'connect'#

      + +

      The 'connect' event is emitted after a socket is associated to a remote +address as a result of a successful connect() call.

      +

      Event: 'error'#

      + + +

      The 'error' event is emitted whenever any error occurs. The event handler +function is passed a single Error object.

      +

      Event: 'listening'#

      + +

      The 'listening' event is emitted once the dgram.Socket is addressable and +can receive data. This happens either explicitly with socket.bind() or +implicitly the first time data is sent using socket.send(). +Until the dgram.Socket is listening, the underlying system resources do not +exist and calls such as socket.address() and socket.setTTL() will fail.

      +

      Event: 'message'#

      + +

      The 'message' event is emitted when a new datagram is available on a socket. +The event handler function is passed two arguments: msg and rinfo.

      + +

      If the source address of the incoming packet is an IPv6 link-local +address, the interface name is added to the address. For +example, a packet received on the en0 interface might have the +address field set to 'fe80::2618:1234:ab11:3b9c%en0', where '%en0' +is the interface name as a zone ID suffix.

      +

      socket.addMembership(multicastAddress[, multicastInterface])#

      + + +

      Tells the kernel to join a multicast group at the given multicastAddress and +multicastInterface using the IP_ADD_MEMBERSHIP socket option. If the +multicastInterface argument is not specified, the operating system will choose +one interface and will add membership to it. To add membership to every +available interface, call addMembership multiple times, once per interface.

      +

      When called on an unbound socket, this method will implicitly bind to a random +port, listening on all interfaces.

      +

      When sharing a UDP socket across multiple cluster workers, the +socket.addMembership() function must be called only once or an +EADDRINUSE error will occur:

      +
      const cluster = require('cluster');
      +const dgram = require('dgram');
      +if (cluster.isMaster) {
      +  cluster.fork(); // Works ok.
      +  cluster.fork(); // Fails with EADDRINUSE.
      +} else {
      +  const s = dgram.createSocket('udp4');
      +  s.bind(1234, () => {
      +    s.addMembership('224.0.0.114');
      +  });
      +}
      +

      socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])#

      + + +

      Tells the kernel to join a source-specific multicast channel at the given +sourceAddress and groupAddress, using the multicastInterface with the +IP_ADD_SOURCE_MEMBERSHIP socket option. If the multicastInterface argument +is not specified, the operating system will choose one interface and will add +membership to it. To add membership to every available interface, call +socket.addSourceSpecificMembership() multiple times, once per interface.

      +

      When called on an unbound socket, this method will implicitly bind to a random +port, listening on all interfaces.

      +

      socket.address()#

      + + +

      Returns an object containing the address information for a socket. +For UDP sockets, this object will contain address, family and port +properties.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.bind([port][, address][, callback])#

      + + +

      For UDP sockets, causes the dgram.Socket to listen for datagram +messages on a named port and optional address. If port is not +specified or is 0, the operating system will attempt to bind to a +random port. If address is not specified, the operating system will +attempt to listen on all addresses. Once binding is complete, a +'listening' event is emitted and the optional callback function is +called.

      +

      Specifying both a 'listening' event listener and passing a +callback to the socket.bind() method is not harmful but not very +useful.

      +

      A bound datagram socket keeps the Node.js process running to receive +datagram messages.

      +

      If binding fails, an 'error' event is generated. In rare case (e.g. +attempting to bind with a closed socket), an Error may be thrown.

      +

      Example of a UDP server listening on port 41234:

      +
      const dgram = require('dgram');
      +const server = dgram.createSocket('udp4');
      +
      +server.on('error', (err) => {
      +  console.log(`server error:\n${err.stack}`);
      +  server.close();
      +});
      +
      +server.on('message', (msg, rinfo) => {
      +  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
      +});
      +
      +server.on('listening', () => {
      +  const address = server.address();
      +  console.log(`server listening ${address.address}:${address.port}`);
      +});
      +
      +server.bind(41234);
      +// Prints: server listening 0.0.0.0:41234
      +

      socket.bind(options[, callback])#

      + + +

      For UDP sockets, causes the dgram.Socket to listen for datagram +messages on a named port and optional address that are passed as +properties of an options object passed as the first argument. If +port is not specified or is 0, the operating system will attempt +to bind to a random port. If address is not specified, the operating +system will attempt to listen on all addresses. Once binding is +complete, a 'listening' event is emitted and the optional callback +function is called.

      +

      The options object may contain a fd property. When a fd greater +than 0 is set, it will wrap around an existing socket with the given +file descriptor. In this case, the properties of port and address +will be ignored.

      +

      Specifying both a 'listening' event listener and passing a +callback to the socket.bind() method is not harmful but not very +useful.

      +

      The options object may contain an additional exclusive property that is +used when using dgram.Socket objects with the cluster module. When +exclusive is set to false (the default), cluster workers will use the same +underlying socket handle allowing connection handling duties to be shared. +When exclusive is true, however, the handle is not shared and attempted +port sharing results in an error.

      +

      A bound datagram socket keeps the Node.js process running to receive +datagram messages.

      +

      If binding fails, an 'error' event is generated. In rare case (e.g. +attempting to bind with a closed socket), an Error may be thrown.

      +

      An example socket listening on an exclusive port is shown below.

      +
      socket.bind({
      +  address: 'localhost',
      +  port: 8000,
      +  exclusive: true
      +});
      +

      socket.close([callback])#

      + +
        +
      • callback <Function> Called when the socket has been closed.
      • +
      +

      Close the underlying socket and stop listening for data on it. If a callback is +provided, it is added as a listener for the 'close' event.

      +

      socket.connect(port[, address][, callback])#

      + + +

      Associates the dgram.Socket to a remote address and port. Every +message sent by this handle is automatically sent to that destination. Also, +the socket will only receive messages from that remote peer. +Trying to call connect() on an already connected socket will result +in an ERR_SOCKET_DGRAM_IS_CONNECTED exception. If address is not +provided, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets) +will be used by default. Once the connection is complete, a 'connect' event +is emitted and the optional callback function is called. In case of failure, +the callback is called or, failing this, an 'error' event is emitted.

      +

      socket.disconnect()#

      + +

      A synchronous function that disassociates a connected dgram.Socket from +its remote address. Trying to call disconnect() on an unbound or already +disconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED +exception.

      +

      socket.dropMembership(multicastAddress[, multicastInterface])#

      + + +

      Instructs the kernel to leave a multicast group at multicastAddress using the +IP_DROP_MEMBERSHIP socket option. This method is automatically called by the +kernel when the socket is closed or the process terminates, so most apps will +never have reason to call this.

      +

      If multicastInterface is not specified, the operating system will attempt to +drop membership on all valid interfaces.

      +

      socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])#

      + + +

      Instructs the kernel to leave a source-specific multicast channel at the given +sourceAddress and groupAddress using the IP_DROP_SOURCE_MEMBERSHIP +socket option. This method is automatically called by the kernel when the +socket is closed or the process terminates, so most apps will never have +reason to call this.

      +

      If multicastInterface is not specified, the operating system will attempt to +drop membership on all valid interfaces.

      +

      socket.getRecvBufferSize()#

      + +
        +
      • Returns: <number> the SO_RCVBUF socket receive buffer size in bytes.
      • +
      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.getSendBufferSize()#

      + +
        +
      • Returns: <number> the SO_SNDBUF socket send buffer size in bytes.
      • +
      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.ref()#

      + + +

      By default, binding a socket will cause it to block the Node.js process from +exiting as long as the socket is open. The socket.unref() method can be used +to exclude the socket from the reference counting that keeps the Node.js +process active. The socket.ref() method adds the socket back to the reference +counting and restores the default behavior.

      +

      Calling socket.ref() multiples times will have no additional effect.

      +

      The socket.ref() method returns a reference to the socket so calls can be +chained.

      +

      socket.remoteAddress()#

      + + +

      Returns an object containing the address, family, and port of the remote +endpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED exception +if the socket is not connected.

      +

      socket.send(msg[, offset, length][, port][, address][, callback])#

      + + +

      Broadcasts a datagram on the socket. +For connectionless sockets, the destination port and address must be +specified. Connected sockets, on the other hand, will use their associated +remote endpoint, so the port and address arguments must not be set.

      +

      The msg argument contains the message to be sent. +Depending on its type, different behavior can apply. If msg is a Buffer, +any TypedArray or a DataView, +the offset and length specify the offset within the Buffer where the +message begins and the number of bytes in the message, respectively. +If msg is a String, then it is automatically converted to a Buffer +with 'utf8' encoding. With messages that +contain multi-byte characters, offset and length will be calculated with +respect to byte length and not the character position. +If msg is an array, offset and length must not be specified.

      +

      The address argument is a string. If the value of address is a host name, +DNS will be used to resolve the address of the host. If address is not +provided or otherwise falsy, '127.0.0.1' (for udp4 sockets) or '::1' +(for udp6 sockets) will be used by default.

      +

      If the socket has not been previously bound with a call to bind, the socket +is assigned a random port number and is bound to the "all interfaces" address +('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

      +

      An optional callback function may be specified to as a way of reporting +DNS errors or for determining when it is safe to reuse the buf object. +DNS lookups delay the time to send for at least one tick of the +Node.js event loop.

      +

      The only way to know for sure that the datagram has been sent is by using a +callback. If an error occurs and a callback is given, the error will be +passed as the first argument to the callback. If a callback is not given, +the error is emitted as an 'error' event on the socket object.

      +

      Offset and length are optional but both must be set if either are used. +They are supported only when the first argument is a Buffer, a TypedArray, +or a DataView.

      +

      This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.

      +

      Example of sending a UDP packet to a port on localhost;

      +
      const dgram = require('dgram');
      +const message = Buffer.from('Some bytes');
      +const client = dgram.createSocket('udp4');
      +client.send(message, 41234, 'localhost', (err) => {
      +  client.close();
      +});
      +

      Example of sending a UDP packet composed of multiple buffers to a port on +127.0.0.1;

      +
      const dgram = require('dgram');
      +const buf1 = Buffer.from('Some ');
      +const buf2 = Buffer.from('bytes');
      +const client = dgram.createSocket('udp4');
      +client.send([buf1, buf2], 41234, (err) => {
      +  client.close();
      +});
      +

      Sending multiple buffers might be faster or slower depending on the +application and operating system. Run benchmarks to +determine the optimal strategy on a case-by-case basis. Generally speaking, +however, sending multiple buffers is faster.

      +

      Example of sending a UDP packet using a socket connected to a port on +localhost:

      +
      const dgram = require('dgram');
      +const message = Buffer.from('Some bytes');
      +const client = dgram.createSocket('udp4');
      +client.connect(41234, 'localhost', (err) => {
      +  client.send(message, (err) => {
      +    client.close();
      +  });
      +});
      +

      Note about UDP datagram size#

      +

      The maximum size of an IPv4/v6 datagram depends on the MTU +(Maximum Transmission Unit) and on the Payload Length field size.

      +
        +
      • +

        The Payload Length field is 16 bits wide, which means that a normal +payload cannot exceed 64K octets including the internet header and data +(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); +this is generally true for loopback interfaces, but such long datagram +messages are impractical for most hosts and networks.

        +
      • +
      • +

        The MTU is the largest size a given link layer technology can support for +datagram messages. For any link, IPv4 mandates a minimum MTU of 68 +octets, while the recommended MTU for IPv4 is 576 (typically recommended +as the MTU for dial-up type applications), whether they arrive whole or in +fragments.

        +

        For IPv6, the minimum MTU is 1280 octets. However, the mandatory minimum +fragment reassembly buffer size is 1500 octets. The value of 68 octets is +very small, since most current link layer technologies, like Ethernet, have a +minimum MTU of 1500.

        +
      • +
      +

      It is impossible to know in advance the MTU of each link through which +a packet might travel. Sending a datagram greater than the receiver MTU will +not work because the packet will get silently dropped without informing the +source that the data did not reach its intended recipient.

      +

      socket.setBroadcast(flag)#

      + + +

      Sets or clears the SO_BROADCAST socket option. When set to true, UDP +packets may be sent to a local interface's broadcast address.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.setMulticastInterface(multicastInterface)#

      + + +

      All references to scope in this section are referring to +IPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP +with a scope index is written as 'IP%scope' where scope is an interface name +or interface number.

      +

      Sets the default outgoing multicast interface of the socket to a chosen +interface or back to system interface selection. The multicastInterface must +be a valid string representation of an IP from the socket's family.

      +

      For IPv4 sockets, this should be the IP configured for the desired physical +interface. All packets sent to multicast on the socket will be sent on the +interface determined by the most recent successful use of this call.

      +

      For IPv6 sockets, multicastInterface should include a scope to indicate the +interface as in the examples that follow. In IPv6, individual send calls can +also use explicit scope in addresses, so only packets sent to a multicast +address without specifying an explicit scope are affected by the most recent +successful use of this call.

      +

      This method throws EBADF if called on an unbound socket.

      +

      Example: IPv6 outgoing multicast interface#

      +

      On most systems, where scope format uses the interface name:

      +
      const socket = dgram.createSocket('udp6');
      +
      +socket.bind(1234, () => {
      +  socket.setMulticastInterface('::%eth1');
      +});
      +

      On Windows, where scope format uses an interface number:

      +
      const socket = dgram.createSocket('udp6');
      +
      +socket.bind(1234, () => {
      +  socket.setMulticastInterface('::%2');
      +});
      +

      Example: IPv4 outgoing multicast interface#

      +

      All systems use an IP of the host on the desired physical interface:

      +
      const socket = dgram.createSocket('udp4');
      +
      +socket.bind(1234, () => {
      +  socket.setMulticastInterface('10.0.0.2');
      +});
      +

      Call results#

      +

      A call on a socket that is not ready to send or no longer open may throw a Not +running Error.

      +

      If multicastInterface can not be parsed into an IP then an EINVAL +System Error is thrown.

      +

      On IPv4, if multicastInterface is a valid address but does not match any +interface, or if the address does not match the family then +a System Error such as EADDRNOTAVAIL or EPROTONOSUP is thrown.

      +

      On IPv6, most errors with specifying or omitting scope will result in the socket +continuing to use (or returning to) the system's default interface selection.

      +

      A socket's address family's ANY address (IPv4 '0.0.0.0' or IPv6 '::') can be +used to return control of the sockets default outgoing interface to the system +for future multicast packets.

      +

      socket.setMulticastLoopback(flag)#

      + + +

      Sets or clears the IP_MULTICAST_LOOP socket option. When set to true, +multicast packets will also be received on the local interface.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.setMulticastTTL(ttl)#

      + + +

      Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for +"Time to Live", in this context it specifies the number of IP hops that a +packet is allowed to travel through, specifically for multicast traffic. Each +router or gateway that forwards a packet decrements the TTL. If the TTL is +decremented to 0 by a router, it will not be forwarded.

      +

      The ttl argument may be between 0 and 255. The default on most systems is 1.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.setRecvBufferSize(size)#

      + + +

      Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer +in bytes.

      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.setSendBufferSize(size)#

      + + +

      Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer +in bytes.

      +

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      +

      socket.setTTL(ttl)#

      + + +

      Sets the IP_TTL socket option. While TTL generally stands for "Time to Live", +in this context it specifies the number of IP hops that a packet is allowed to +travel through. Each router or gateway that forwards a packet decrements the +TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. +Changing TTL values is typically done for network probes or when multicasting.

      +

      The ttl argument may be between between 1 and 255. The default on most systems +is 64.

      +

      This method throws EBADF if called on an unbound socket.

      +

      socket.unref()#

      + + +

      By default, binding a socket will cause it to block the Node.js process from +exiting as long as the socket is open. The socket.unref() method can be used +to exclude the socket from the reference counting that keeps the Node.js +process active, allowing the process to exit even if the socket is still +listening.

      +

      Calling socket.unref() multiple times will have no addition effect.

      +

      The socket.unref() method returns a reference to the socket so calls can be +chained.

      +

      dgram module functions#

      +

      dgram.createSocket(options[, callback])#

      + +
        +
      • options <Object> Available options are: +
          +
        • type <string> The family of socket. Must be either 'udp4' or 'udp6'. +Required.
        • +
        • reuseAddr <boolean> When true socket.bind() will reuse the +address, even if another process has already bound a socket on it. +Default: false.
        • +
        • ipv6Only <boolean> Setting ipv6Only to true will +disable dual-stack support, i.e., binding to address :: won't make +0.0.0.0 be bound. Default: false.
        • +
        • recvBufferSize <number> Sets the SO_RCVBUF socket value.
        • +
        • sendBufferSize <number> Sets the SO_SNDBUF socket value.
        • +
        • lookup <Function> Custom lookup function. Default: dns.lookup().
        • +
        +
      • +
      • callback <Function> Attached as a listener for 'message' events. Optional.
      • +
      • Returns: <dgram.Socket>
      • +
      +

      Creates a dgram.Socket object. Once the socket is created, calling +socket.bind() will instruct the socket to begin listening for datagram +messages. When address and port are not passed to socket.bind() the +method will bind the socket to the "all interfaces" address on a random port +(it does the right thing for both udp4 and udp6 sockets). The bound address +and port can be retrieved using socket.address().address and +socket.address().port.

      +

      dgram.createSocket(type[, callback])#

      + + +

      Creates a dgram.Socket object of the specified type.

      +

      Once the socket is created, calling socket.bind() will instruct the +socket to begin listening for datagram messages. When address and port are +not passed to socket.bind() the method will bind the socket to the "all +interfaces" address on a random port (it does the right thing for both udp4 +and udp6 sockets). The bound address and port can be retrieved using +socket.address().address and socket.address().port.

      + +
      +
      +
      + + diff --git a/doc/api/dgram.json b/doc/api/dgram.json new file mode 100644 index 0000000000000000000000000000000000000000..906d0d65f989fa06ecb108768801626538e222bf --- /dev/null +++ b/doc/api/dgram.json @@ -0,0 +1,927 @@ +{ + "type": "module", + "source": "doc/api/dgram.md", + "modules": [ + { + "textRaw": "UDP/datagram sockets", + "name": "dgram", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/dgram.js

      \n

      The dgram module provides an implementation of UDP datagram sockets.

      \n
      const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
      ", + "classes": [ + { + "textRaw": "Class: `dgram.Socket`", + "type": "class", + "name": "dgram.Socket", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "desc": "\n

      Encapsulates the datagram functionality.

      \n

      New instances of dgram.Socket are created using dgram.createSocket().\nThe new keyword is not to be used to create dgram.Socket instances.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted after a socket is closed with close().\nOnce triggered, no new 'message' events will be emitted on this socket.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'connect' event is emitted after a socket is associated to a remote\naddress as a result of a successful connect() call.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`exception` {Error}", + "name": "exception", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.

      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'listening' event is emitted once the dgram.Socket is addressable and\ncan receive data. This happens either explicitly with socket.bind() or\nimplicitly the first time data is sent using socket.send().\nUntil the dgram.Socket is listening, the underlying system resources do not\nexist and calls such as socket.address() and socket.setTTL() will fail.

      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'message' event is emitted when a new datagram is available on a socket.\nThe event handler function is passed two arguments: msg and rinfo.

      \n\n

      If the source address of the incoming packet is an IPv6 link-local\naddress, the interface name is added to the address. For\nexample, a packet received on the en0 interface might have the\naddress field set to 'fe80::2618:1234:ab11:3b9c%en0', where '%en0'\nis the interface name as a zone ID suffix.

      " + } + ], + "methods": [ + { + "textRaw": "`socket.addMembership(multicastAddress[, multicastInterface])`", + "type": "method", + "name": "addMembership", + "meta": { + "added": [ + "v0.6.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` {string}", + "name": "multicastAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Tells the kernel to join a multicast group at the given multicastAddress and\nmulticastInterface using the IP_ADD_MEMBERSHIP socket option. If the\nmulticastInterface argument is not specified, the operating system will choose\none interface and will add membership to it. To add membership to every\navailable interface, call addMembership multiple times, once per interface.

      \n

      When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.

      \n

      When sharing a UDP socket across multiple cluster workers, the\nsocket.addMembership() function must be called only once or an\nEADDRINUSE error will occur:

      \n
      const cluster = require('cluster');\nconst dgram = require('dgram');\nif (cluster.isMaster) {\n  cluster.fork(); // Works ok.\n  cluster.fork(); // Fails with EADDRINUSE.\n} else {\n  const s = dgram.createSocket('udp4');\n  s.bind(1234, () => {\n    s.addMembership('224.0.0.114');\n  });\n}\n
      " + }, + { + "textRaw": "`socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`", + "type": "method", + "name": "addSourceSpecificMembership", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`sourceAddress` {string}", + "name": "sourceAddress", + "type": "string" + }, + { + "textRaw": "`groupAddress` {string}", + "name": "groupAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Tells the kernel to join a source-specific multicast channel at the given\nsourceAddress and groupAddress, using the multicastInterface with the\nIP_ADD_SOURCE_MEMBERSHIP socket option. If the multicastInterface argument\nis not specified, the operating system will choose one interface and will add\nmembership to it. To add membership to every available interface, call\nsocket.addSourceSpecificMembership() multiple times, once per interface.

      \n

      When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.

      " + }, + { + "textRaw": "`socket.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address, family and port\nproperties.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.bind([port][, address][, callback])`", + "type": "method", + "name": "bind", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [ + { + "version": "v0.10", + "description": "The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`port` {integer}", + "name": "port", + "type": "integer" + }, + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`callback` {Function} with no parameters. Called when binding is complete.", + "name": "callback", + "type": "Function", + "desc": "with no parameters. Called when binding is complete." + } + ] + } + ], + "desc": "

      For UDP sockets, causes the dgram.Socket to listen for datagram\nmessages on a named port and optional address. If port is not\nspecified or is 0, the operating system will attempt to bind to a\nrandom port. If address is not specified, the operating system will\nattempt to listen on all addresses. Once binding is complete, a\n'listening' event is emitted and the optional callback function is\ncalled.

      \n

      Specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

      \n

      A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

      \n

      If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

      \n

      Example of a UDP server listening on port 41234:

      \n
      const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
      " + }, + { + "textRaw": "`socket.bind(options[, callback])`", + "type": "method", + "name": "bind", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Required. Supports the following properties:", + "name": "options", + "type": "Object", + "desc": "Required. Supports the following properties:", + "options": [ + { + "textRaw": "`port` {integer}", + "name": "port", + "type": "integer" + }, + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`exclusive` {boolean}", + "name": "exclusive", + "type": "boolean" + }, + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      For UDP sockets, causes the dgram.Socket to listen for datagram\nmessages on a named port and optional address that are passed as\nproperties of an options object passed as the first argument. If\nport is not specified or is 0, the operating system will attempt\nto bind to a random port. If address is not specified, the operating\nsystem will attempt to listen on all addresses. Once binding is\ncomplete, a 'listening' event is emitted and the optional callback\nfunction is called.

      \n

      The options object may contain a fd property. When a fd greater\nthan 0 is set, it will wrap around an existing socket with the given\nfile descriptor. In this case, the properties of port and address\nwill be ignored.

      \n

      Specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

      \n

      The options object may contain an additional exclusive property that is\nused when using dgram.Socket objects with the cluster module. When\nexclusive is set to false (the default), cluster workers will use the same\nunderlying socket handle allowing connection handling duties to be shared.\nWhen exclusive is true, however, the handle is not shared and attempted\nport sharing results in an error.

      \n

      A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

      \n

      If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

      \n

      An example socket listening on an exclusive port is shown below.

      \n
      socket.bind({\n  address: 'localhost',\n  port: 8000,\n  exclusive: true\n});\n
      " + }, + { + "textRaw": "`socket.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} Called when the socket has been closed.", + "name": "callback", + "type": "Function", + "desc": "Called when the socket has been closed." + } + ] + } + ], + "desc": "

      Close the underlying socket and stop listening for data on it. If a callback is\nprovided, it is added as a listener for the 'close' event.

      " + }, + { + "textRaw": "`socket.connect(port[, address][, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`port` {integer}", + "name": "port", + "type": "integer" + }, + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`callback` {Function} Called when the connection is completed or on error.", + "name": "callback", + "type": "Function", + "desc": "Called when the connection is completed or on error." + } + ] + } + ], + "desc": "

      Associates the dgram.Socket to a remote address and port. Every\nmessage sent by this handle is automatically sent to that destination. Also,\nthe socket will only receive messages from that remote peer.\nTrying to call connect() on an already connected socket will result\nin an ERR_SOCKET_DGRAM_IS_CONNECTED exception. If address is not\nprovided, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets)\nwill be used by default. Once the connection is complete, a 'connect' event\nis emitted and the optional callback function is called. In case of failure,\nthe callback is called or, failing this, an 'error' event is emitted.

      " + }, + { + "textRaw": "`socket.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      A synchronous function that disassociates a connected dgram.Socket from\nits remote address. Trying to call disconnect() on an unbound or already\ndisconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED\nexception.

      " + }, + { + "textRaw": "`socket.dropMembership(multicastAddress[, multicastInterface])`", + "type": "method", + "name": "dropMembership", + "meta": { + "added": [ + "v0.6.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastAddress` {string}", + "name": "multicastAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Instructs the kernel to leave a multicast group at multicastAddress using the\nIP_DROP_MEMBERSHIP socket option. This method is automatically called by the\nkernel when the socket is closed or the process terminates, so most apps will\nnever have reason to call this.

      \n

      If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

      " + }, + { + "textRaw": "`socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`", + "type": "method", + "name": "dropSourceSpecificMembership", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`sourceAddress` {string}", + "name": "sourceAddress", + "type": "string" + }, + { + "textRaw": "`groupAddress` {string}", + "name": "groupAddress", + "type": "string" + }, + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      Instructs the kernel to leave a source-specific multicast channel at the given\nsourceAddress and groupAddress using the IP_DROP_SOURCE_MEMBERSHIP\nsocket option. This method is automatically called by the kernel when the\nsocket is closed or the process terminates, so most apps will never have\nreason to call this.

      \n

      If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

      " + }, + { + "textRaw": "`socket.getRecvBufferSize()`", + "type": "method", + "name": "getRecvBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} the `SO_RCVBUF` socket receive buffer size in bytes.", + "name": "return", + "type": "number", + "desc": "the `SO_RCVBUF` socket receive buffer size in bytes." + }, + "params": [] + } + ], + "desc": "

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.getSendBufferSize()`", + "type": "method", + "name": "getSendBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} the `SO_SNDBUF` socket send buffer size in bytes.", + "name": "return", + "type": "number", + "desc": "the `SO_SNDBUF` socket send buffer size in bytes." + }, + "params": [] + } + ], + "desc": "

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [] + } + ], + "desc": "

      By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref() method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active. The socket.ref() method adds the socket back to the reference\ncounting and restores the default behavior.

      \n

      Calling socket.ref() multiples times will have no additional effect.

      \n

      The socket.ref() method returns a reference to the socket so calls can be\nchained.

      " + }, + { + "textRaw": "`socket.remoteAddress()`", + "type": "method", + "name": "remoteAddress", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing the address, family, and port of the remote\nendpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED exception\nif the socket is not connected.

      " + }, + { + "textRaw": "`socket.send(msg[, offset, length][, port][, address][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/22413", + "description": "The `msg` parameter can now be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11985", + "description": "The `msg` parameter can be an `Uint8Array` now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10473", + "description": "The `address` parameter is always optional now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5929", + "description": "On success, `callback` will now be called with an `error` argument of `null` rather than `0`." + }, + { + "version": "v5.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4374", + "description": "The `msg` parameter can be an array now. Also, the `offset` and `length` parameters are optional now." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26871", + "description": "Added support for sending data on connected sockets." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`msg` {Buffer|TypedArray|DataView|string|Array} Message to be sent.", + "name": "msg", + "type": "Buffer|TypedArray|DataView|string|Array", + "desc": "Message to be sent." + }, + { + "textRaw": "`offset` {integer} Offset in the buffer where the message starts.", + "name": "offset", + "type": "integer", + "desc": "Offset in the buffer where the message starts." + }, + { + "textRaw": "`length` {integer} Number of bytes in the message.", + "name": "length", + "type": "integer", + "desc": "Number of bytes in the message." + }, + { + "textRaw": "`port` {integer} Destination port.", + "name": "port", + "type": "integer", + "desc": "Destination port." + }, + { + "textRaw": "`address` {string} Destination host name or IP address.", + "name": "address", + "type": "string", + "desc": "Destination host name or IP address." + }, + { + "textRaw": "`callback` {Function} Called when the message has been sent.", + "name": "callback", + "type": "Function", + "desc": "Called when the message has been sent." + } + ] + } + ], + "desc": "

      Broadcasts a datagram on the socket.\nFor connectionless sockets, the destination port and address must be\nspecified. Connected sockets, on the other hand, will use their associated\nremote endpoint, so the port and address arguments must not be set.

      \n

      The msg argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg is a Buffer,\nany TypedArray or a DataView,\nthe offset and length specify the offset within the Buffer where the\nmessage begins and the number of bytes in the message, respectively.\nIf msg is a String, then it is automatically converted to a Buffer\nwith 'utf8' encoding. With messages that\ncontain multi-byte characters, offset and length will be calculated with\nrespect to byte length and not the character position.\nIf msg is an array, offset and length must not be specified.

      \n

      The address argument is a string. If the value of address is a host name,\nDNS will be used to resolve the address of the host. If address is not\nprovided or otherwise falsy, '127.0.0.1' (for udp4 sockets) or '::1'\n(for udp6 sockets) will be used by default.

      \n

      If the socket has not been previously bound with a call to bind, the socket\nis assigned a random port number and is bound to the \"all interfaces\" address\n('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

      \n

      An optional callback function may be specified to as a way of reporting\nDNS errors or for determining when it is safe to reuse the buf object.\nDNS lookups delay the time to send for at least one tick of the\nNode.js event loop.

      \n

      The only way to know for sure that the datagram has been sent is by using a\ncallback. If an error occurs and a callback is given, the error will be\npassed as the first argument to the callback. If a callback is not given,\nthe error is emitted as an 'error' event on the socket object.

      \n

      Offset and length are optional but both must be set if either are used.\nThey are supported only when the first argument is a Buffer, a TypedArray,\nor a DataView.

      \n

      This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.

      \n

      Example of sending a UDP packet to a port on localhost;

      \n
      const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n  client.close();\n});\n
      \n

      Example of sending a UDP packet composed of multiple buffers to a port on\n127.0.0.1;

      \n
      const dgram = require('dgram');\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, (err) => {\n  client.close();\n});\n
      \n

      Sending multiple buffers might be faster or slower depending on the\napplication and operating system. Run benchmarks to\ndetermine the optimal strategy on a case-by-case basis. Generally speaking,\nhowever, sending multiple buffers is faster.

      \n

      Example of sending a UDP packet using a socket connected to a port on\nlocalhost:

      \n
      const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.connect(41234, 'localhost', (err) => {\n  client.send(message, (err) => {\n    client.close();\n  });\n});\n
      ", + "modules": [ + { + "textRaw": "Note about UDP datagram size", + "name": "note_about_udp_datagram_size", + "desc": "

      The maximum size of an IPv4/v6 datagram depends on the MTU\n(Maximum Transmission Unit) and on the Payload Length field size.

      \n
        \n
      • \n

        The Payload Length field is 16 bits wide, which means that a normal\npayload cannot exceed 64K octets including the internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagram\nmessages are impractical for most hosts and networks.

        \n
      • \n
      • \n

        The MTU is the largest size a given link layer technology can support for\ndatagram messages. For any link, IPv4 mandates a minimum MTU of 68\noctets, while the recommended MTU for IPv4 is 576 (typically recommended\nas the MTU for dial-up type applications), whether they arrive whole or in\nfragments.

        \n

        For IPv6, the minimum MTU is 1280 octets. However, the mandatory minimum\nfragment reassembly buffer size is 1500 octets. The value of 68 octets is\nvery small, since most current link layer technologies, like Ethernet, have a\nminimum MTU of 1500.

        \n
      • \n
      \n

      It is impossible to know in advance the MTU of each link through which\na packet might travel. Sending a datagram greater than the receiver MTU will\nnot work because the packet will get silently dropped without informing the\nsource that the data did not reach its intended recipient.

      ", + "type": "module", + "displayName": "Note about UDP datagram size" + } + ] + }, + { + "textRaw": "`socket.setBroadcast(flag)`", + "type": "method", + "name": "setBroadcast", + "meta": { + "added": [ + "v0.6.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` {boolean}", + "name": "flag", + "type": "boolean" + } + ] + } + ], + "desc": "

      Sets or clears the SO_BROADCAST socket option. When set to true, UDP\npackets may be sent to a local interface's broadcast address.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setMulticastInterface(multicastInterface)`", + "type": "method", + "name": "setMulticastInterface", + "meta": { + "added": [ + "v8.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`multicastInterface` {string}", + "name": "multicastInterface", + "type": "string" + } + ] + } + ], + "desc": "

      All references to scope in this section are referring to\nIPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP\nwith a scope index is written as 'IP%scope' where scope is an interface name\nor interface number.

      \n

      Sets the default outgoing multicast interface of the socket to a chosen\ninterface or back to system interface selection. The multicastInterface must\nbe a valid string representation of an IP from the socket's family.

      \n

      For IPv4 sockets, this should be the IP configured for the desired physical\ninterface. All packets sent to multicast on the socket will be sent on the\ninterface determined by the most recent successful use of this call.

      \n

      For IPv6 sockets, multicastInterface should include a scope to indicate the\ninterface as in the examples that follow. In IPv6, individual send calls can\nalso use explicit scope in addresses, so only packets sent to a multicast\naddress without specifying an explicit scope are affected by the most recent\nsuccessful use of this call.

      \n

      This method throws EBADF if called on an unbound socket.

      \n

      Example: IPv6 outgoing multicast interface

      \n

      On most systems, where scope format uses the interface name:

      \n
      const socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('::%eth1');\n});\n
      \n

      On Windows, where scope format uses an interface number:

      \n
      const socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('::%2');\n});\n
      \n

      Example: IPv4 outgoing multicast interface

      \n

      All systems use an IP of the host on the desired physical interface:

      \n
      const socket = dgram.createSocket('udp4');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('10.0.0.2');\n});\n
      ", + "modules": [ + { + "textRaw": "Call results", + "name": "call_results", + "desc": "

      A call on a socket that is not ready to send or no longer open may throw a Not\nrunning Error.

      \n

      If multicastInterface can not be parsed into an IP then an EINVAL\nSystem Error is thrown.

      \n

      On IPv4, if multicastInterface is a valid address but does not match any\ninterface, or if the address does not match the family then\na System Error such as EADDRNOTAVAIL or EPROTONOSUP is thrown.

      \n

      On IPv6, most errors with specifying or omitting scope will result in the socket\ncontinuing to use (or returning to) the system's default interface selection.

      \n

      A socket's address family's ANY address (IPv4 '0.0.0.0' or IPv6 '::') can be\nused to return control of the sockets default outgoing interface to the system\nfor future multicast packets.

      ", + "type": "module", + "displayName": "Call results" + } + ] + }, + { + "textRaw": "`socket.setMulticastLoopback(flag)`", + "type": "method", + "name": "setMulticastLoopback", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` {boolean}", + "name": "flag", + "type": "boolean" + } + ] + } + ], + "desc": "

      Sets or clears the IP_MULTICAST_LOOP socket option. When set to true,\nmulticast packets will also be received on the local interface.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setMulticastTTL(ttl)`", + "type": "method", + "name": "setMulticastTTL", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` {integer}", + "name": "ttl", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for\n\"Time to Live\", in this context it specifies the number of IP hops that a\npacket is allowed to travel through, specifically for multicast traffic. Each\nrouter or gateway that forwards a packet decrements the TTL. If the TTL is\ndecremented to 0 by a router, it will not be forwarded.

      \n

      The ttl argument may be between 0 and 255. The default on most systems is 1.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setRecvBufferSize(size)`", + "type": "method", + "name": "setRecvBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer}", + "name": "size", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer\nin bytes.

      \n

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setSendBufferSize(size)`", + "type": "method", + "name": "setSendBufferSize", + "meta": { + "added": [ + "v8.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {integer}", + "name": "size", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer\nin bytes.

      \n

      This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.setTTL(ttl)`", + "type": "method", + "name": "setTTL", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ttl` {integer}", + "name": "ttl", + "type": "integer" + } + ] + } + ], + "desc": "

      Sets the IP_TTL socket option. While TTL generally stands for \"Time to Live\",\nin this context it specifies the number of IP hops that a packet is allowed to\ntravel through. Each router or gateway that forwards a packet decrements the\nTTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\nChanging TTL values is typically done for network probes or when multicasting.

      \n

      The ttl argument may be between between 1 and 255. The default on most systems\nis 64.

      \n

      This method throws EBADF if called on an unbound socket.

      " + }, + { + "textRaw": "`socket.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [] + } + ], + "desc": "

      By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref() method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active, allowing the process to exit even if the socket is still\nlistening.

      \n

      Calling socket.unref() multiple times will have no addition effect.

      \n

      The socket.unref() method returns a reference to the socket so calls can be\nchained.

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "`dgram` module functions", + "name": "`dgram`_module_functions", + "methods": [ + { + "textRaw": "`dgram.createSocket(options[, callback])`", + "type": "method", + "name": "createSocket", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v8.6.0", + "pr-url": "https://github.com/nodejs/node/pull/14560", + "description": "The `lookup` option is supported." + }, + { + "version": "v8.7.0", + "pr-url": "https://github.com/nodejs/node/pull/13623", + "description": "The `recvBufferSize` and `sendBufferSize` options are supported now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/23798", + "description": "The `ipv6Only` option is supported." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [ + { + "textRaw": "`options` {Object} Available options are:", + "name": "options", + "type": "Object", + "desc": "Available options are:", + "options": [ + { + "textRaw": "`type` {string} The family of socket. Must be either `'udp4'` or `'udp6'`. Required.", + "name": "type", + "type": "string", + "desc": "The family of socket. Must be either `'udp4'` or `'udp6'`. Required." + }, + { + "textRaw": "`reuseAddr` {boolean} When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it. **Default:** `false`.", + "name": "reuseAddr", + "type": "boolean", + "default": "`false`", + "desc": "When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it." + }, + { + "textRaw": "`ipv6Only` {boolean} Setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to address `::` won't make `0.0.0.0` be bound. **Default:** `false`.", + "name": "ipv6Only", + "type": "boolean", + "default": "`false`", + "desc": "Setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to address `::` won't make `0.0.0.0` be bound." + }, + { + "textRaw": "`recvBufferSize` {number} Sets the `SO_RCVBUF` socket value.", + "name": "recvBufferSize", + "type": "number", + "desc": "Sets the `SO_RCVBUF` socket value." + }, + { + "textRaw": "`sendBufferSize` {number} Sets the `SO_SNDBUF` socket value.", + "name": "sendBufferSize", + "type": "number", + "desc": "Sets the `SO_SNDBUF` socket value." + }, + { + "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", + "name": "lookup", + "type": "Function", + "default": "[`dns.lookup()`][]", + "desc": "Custom lookup function." + } + ] + }, + { + "textRaw": "`callback` {Function} Attached as a listener for `'message'` events. Optional.", + "name": "callback", + "type": "Function", + "desc": "Attached as a listener for `'message'` events. Optional." + } + ] + } + ], + "desc": "

      Creates a dgram.Socket object. Once the socket is created, calling\nsocket.bind() will instruct the socket to begin listening for datagram\nmessages. When address and port are not passed to socket.bind() the\nmethod will bind the socket to the \"all interfaces\" address on a random port\n(it does the right thing for both udp4 and udp6 sockets). The bound address\nand port can be retrieved using socket.address().address and\nsocket.address().port.

      " + }, + { + "textRaw": "`dgram.createSocket(type[, callback])`", + "type": "method", + "name": "createSocket", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {dgram.Socket}", + "name": "return", + "type": "dgram.Socket" + }, + "params": [ + { + "textRaw": "`type` {string} Either `'udp4'` or `'udp6'`.", + "name": "type", + "type": "string", + "desc": "Either `'udp4'` or `'udp6'`." + }, + { + "textRaw": "`callback` {Function} Attached as a listener to `'message'` events.", + "name": "callback", + "type": "Function", + "desc": "Attached as a listener to `'message'` events." + } + ] + } + ], + "desc": "

      Creates a dgram.Socket object of the specified type.

      \n

      Once the socket is created, calling socket.bind() will instruct the\nsocket to begin listening for datagram messages. When address and port are\nnot passed to socket.bind() the method will bind the socket to the \"all\ninterfaces\" address on a random port (it does the right thing for both udp4\nand udp6 sockets). The bound address and port can be retrieved using\nsocket.address().address and socket.address().port.

      " + } + ], + "type": "module", + "displayName": "`dgram` module functions" + } + ], + "type": "module", + "displayName": "dgram" + } + ] +} \ No newline at end of file diff --git a/doc/api/dns.html b/doc/api/dns.html new file mode 100644 index 0000000000000000000000000000000000000000..4238c3ae847cb6d80e0f1a3206be270d905f2973 --- /dev/null +++ b/doc/api/dns.html @@ -0,0 +1,1495 @@ + + + + + + + DNS | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      DNS#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/dns.js

      +

      The dns module enables name resolution. For example, use it to look up IP +addresses of host names.

      +

      Although named for the Domain Name System (DNS), it does not always use the +DNS protocol for lookups. dns.lookup() uses the operating system +facilities to perform name resolution. It may not need to perform any network +communication. To perform name resolution the way other applications on the same +system do, use dns.lookup().

      +
      const dns = require('dns');
      +
      +dns.lookup('example.org', (err, address, family) => {
      +  console.log('address: %j family: IPv%s', address, family);
      +});
      +// address: "93.184.216.34" family: IPv4
      +

      All other functions in the dns module connect to an actual DNS server to +perform name resolution. They will always use the network to perform DNS +queries. These functions do not use the same set of configuration files used by +dns.lookup() (e.g. /etc/hosts). Use these functions to always perform +DNS queries, bypassing other name-resolution facilities.

      +
      const dns = require('dns');
      +
      +dns.resolve4('archive.org', (err, addresses) => {
      +  if (err) throw err;
      +
      +  console.log(`addresses: ${JSON.stringify(addresses)}`);
      +
      +  addresses.forEach((a) => {
      +    dns.reverse(a, (err, hostnames) => {
      +      if (err) {
      +        throw err;
      +      }
      +      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
      +    });
      +  });
      +});
      +

      See the Implementation considerations section for more information.

      +

      Class: dns.Resolver#

      + +

      An independent resolver for DNS requests.

      +

      Creating a new resolver uses the default server settings. Setting +the servers used for a resolver using +resolver.setServers() does not affect +other resolvers:

      +
      const { Resolver } = require('dns');
      +const resolver = new Resolver();
      +resolver.setServers(['4.4.4.4']);
      +
      +// This request will use the server at 4.4.4.4, independent of global settings.
      +resolver.resolve4('example.org', (err, addresses) => {
      +  // ...
      +});
      +

      The following methods from the dns module are available:

      + +

      Resolver([options])#

      + +

      Create a new resolver.

      +
        +
      • options <Object> +
          +
        • timeout <integer> Query timeout in milliseconds, or -1 to use the +default timeout.
        • +
        +
      • +
      +

      resolver.cancel()#

      + +

      Cancel all outstanding DNS queries made by this resolver. The corresponding +callbacks will be called with an error with code ECANCELLED.

      +

      dns.getServers()#

      + + +

      Returns an array of IP address strings, formatted according to RFC 5952, +that are currently configured for DNS resolution. A string will include a port +section if a custom port is used.

      + +
      [
      +  '4.4.4.4',
      +  '2001:4860:4860::8888',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]
      +

      dns.lookup(hostname[, options], callback)#

      + +
        +
      • hostname <string>
      • +
      • options <integer> | <Object> +
          +
        • family <integer> The record family. Must be 4, 6, or 0. The value +0 indicates that IPv4 and IPv6 addresses are both returned. Default: +0.
        • +
        • hints <number> One or more supported getaddrinfo flags. Multiple +flags may be passed by bitwise ORing their values.
        • +
        • all <boolean> When true, the callback returns all resolved addresses in +an array. Otherwise, returns a single address. Default: false.
        • +
        • verbatim <boolean> When true, the callback receives IPv4 and IPv6 +addresses in the order the DNS resolver returned them. When false, +IPv4 addresses are placed before IPv6 addresses. +Default: currently false (addresses are reordered) but this is +expected to change in the not too distant future. +New code should use { verbatim: true }.
        • +
        +
      • +
      • callback <Function> +
          +
        • err <Error>
        • +
        • address <string> A string representation of an IPv4 or IPv6 address.
        • +
        • family <integer> 4 or 6, denoting the family of address, or 0 if +the address is not an IPv4 or IPv6 address. 0 is a likely indicator of a +bug in the name resolution service used by the operating system.
        • +
        +
      • +
      +

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or +AAAA (IPv6) record. All option properties are optional. If options is an +integer, then it must be 4 or 6 – if options is not provided, then IPv4 +and IPv6 addresses are both returned if found.

      +

      With the all option set to true, the arguments for callback change to +(err, addresses), with addresses being an array of objects with the +properties address and family.

      +

      On error, err is an Error object, where err.code is the error code. +Keep in mind that err.code will be set to 'ENOTFOUND' not only when +the host name does not exist but also when the lookup fails in other ways +such as no available file descriptors.

      +

      dns.lookup() does not necessarily have anything to do with the DNS protocol. +The implementation uses an operating system facility that can associate names +with addresses, and vice versa. This implementation can have subtle but +important consequences on the behavior of any Node.js program. Please take some +time to consult the Implementation considerations section before using +dns.lookup().

      +

      Example usage:

      +
      const dns = require('dns');
      +const options = {
      +  family: 6,
      +  hints: dns.ADDRCONFIG | dns.V4MAPPED,
      +};
      +dns.lookup('example.com', options, (err, address, family) =>
      +  console.log('address: %j family: IPv%s', address, family));
      +// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
      +
      +// When options.all is true, the result will be an Array.
      +options.all = true;
      +dns.lookup('example.com', options, (err, addresses) =>
      +  console.log('addresses: %j', addresses));
      +// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
      +

      If this method is invoked as its util.promisify()ed version, and all +is not set to true, it returns a Promise for an Object with address and +family properties.

      +

      Supported getaddrinfo flags#

      + +

      The following flags can be passed as hints to dns.lookup().

      +
        +
      • dns.ADDRCONFIG: Limits returned address types to the types of non-loopback +addresses configured on the system. For example, IPv4 addresses are only +returned if the current system has at least one IPv4 address configured.
      • +
      • dns.V4MAPPED: If the IPv6 family was specified, but no IPv6 addresses were +found, then return IPv4 mapped IPv6 addresses. It is not supported +on some operating systems (e.g FreeBSD 10.1).
      • +
      • dns.ALL: If dns.V4MAPPED is specified, return resolved IPv6 addresses as +well as IPv4 mapped IPv6 addresses.
      • +
      +

      dns.lookupService(address, port, callback)#

      + + +

      Resolves the given address and port into a host name and service using +the operating system's underlying getnameinfo implementation.

      +

      If address is not a valid IP address, a TypeError will be thrown. +The port will be coerced to a number. If it is not a legal port, a TypeError +will be thrown.

      +

      On an error, err is an Error object, where err.code is the error code.

      +
      const dns = require('dns');
      +dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
      +  console.log(hostname, service);
      +  // Prints: localhost ssh
      +});
      +

      If this method is invoked as its util.promisify()ed version, it returns a +Promise for an Object with hostname and service properties.

      +

      dns.resolve(hostname[, rrtype], callback)#

      + + +

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array +of the resource records. The callback function has arguments +(err, records). When successful, records will be an array of resource +records. The type and structure of individual results varies based on rrtype:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dns.resolve4()
      'AAAA'IPv6 addresses<string>dns.resolve6()
      'ANY'any records<Object>dns.resolveAny()
      'CNAME'canonical name records<string>dns.resolveCname()
      'MX'mail exchange records<Object>dns.resolveMx()
      'NAPTR'name authority pointer records<Object>dns.resolveNaptr()
      'NS'name server records<string>dns.resolveNs()
      'PTR'pointer records<string>dns.resolvePtr()
      'SOA'start of authority records<Object>dns.resolveSoa()
      'SRV'service records<Object>dns.resolveSrv()
      'TXT'text records<string[]>dns.resolveTxt()
      +

      On error, err is an Error object, where err.code is one of the +DNS error codes.

      +

      dns.resolve4(hostname[, options], callback)#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the callback receives an array of +{ address: '1.2.3.4', ttl: 60 } objects rather than an array of strings, +with the TTL expressed in seconds.
        • +
        +
      • +
      • callback <Function> + +
      • +
      +

      Uses the DNS protocol to resolve a IPv4 addresses (A records) for the +hostname. The addresses argument passed to the callback function +will contain an array of IPv4 addresses (e.g. +['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      +

      dns.resolve6(hostname[, options], callback)#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the callback receives an array of +{ address: '0:1:2:3:4:5:6:7', ttl: 60 } objects rather than an array of +strings, with the TTL expressed in seconds.
        • +
        +
      • +
      • callback <Function> + +
      • +
      +

      Uses the DNS protocol to resolve a IPv6 addresses (AAAA records) for the +hostname. The addresses argument passed to the callback function +will contain an array of IPv6 addresses.

      +

      dns.resolveAny(hostname, callback)#

      + +

      Uses the DNS protocol to resolve all records (also known as ANY or * query). +The ret argument passed to the callback function will be an array containing +various types of records. Each object has a property type that indicates the +type of the current record. And depending on the type, additional properties +will be present on the object:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dns.resolveMx()
      'NAPTR'Refer to dns.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dns.resolveSoa()
      'SRV'Refer to dns.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      +

      Here is an example of the ret object passed to the callback:

      + +
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },
      +  { type: 'CNAME', value: 'example.com' },
      +  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
      +  { type: 'NS', value: 'ns1.example.com' },
      +  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
      +  { type: 'SOA',
      +    nsname: 'ns1.example.com',
      +    hostmaster: 'admin.example.com',
      +    serial: 156696742,
      +    refresh: 900,
      +    retry: 900,
      +    expire: 1800,
      +    minttl: 60 } ]
      +

      DNS server operators may choose not to respond to ANY +queries. It may be better to call individual methods like dns.resolve4(), +dns.resolveMx(), and so on. For more details, see RFC 8482.

      +

      dns.resolveCname(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve CNAME records for the hostname. The +addresses argument passed to the callback function +will contain an array of canonical name records available for the hostname +(e.g. ['bar.example.com']).

      +

      dns.resolveMx(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve mail exchange records (MX records) for the +hostname. The addresses argument passed to the callback function will +contain an array of objects containing both a priority and exchange +property (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).

      +

      dns.resolveNaptr(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve regular expression based records (NAPTR +records) for the hostname. The addresses argument passed to the callback +function will contain an array of objects with the following properties:

      +
        +
      • flags
      • +
      • service
      • +
      • regexp
      • +
      • replacement
      • +
      • order
      • +
      • preference
      • +
      + +
      {
      +  flags: 's',
      +  service: 'SIP+D2U',
      +  regexp: '',
      +  replacement: '_sip._udp.example.com',
      +  order: 30,
      +  preference: 100
      +}
      +

      dns.resolveNs(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve name server records (NS records) for the +hostname. The addresses argument passed to the callback function will +contain an array of name server records available for hostname +(e.g. ['ns1.example.com', 'ns2.example.com']).

      +

      dns.resolvePtr(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve pointer records (PTR records) for the +hostname. The addresses argument passed to the callback function will +be an array of strings containing the reply records.

      +

      dns.resolveSoa(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve a start of authority record (SOA record) for +the hostname. The address argument passed to the callback function will +be an object with the following properties:

      +
        +
      • nsname
      • +
      • hostmaster
      • +
      • serial
      • +
      • refresh
      • +
      • retry
      • +
      • expire
      • +
      • minttl
      • +
      + +
      {
      +  nsname: 'ns.example.com',
      +  hostmaster: 'root.example.com',
      +  serial: 2013101809,
      +  refresh: 10000,
      +  retry: 2400,
      +  expire: 604800,
      +  minttl: 3600
      +}
      +

      dns.resolveSrv(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve service records (SRV records) for the +hostname. The addresses argument passed to the callback function will +be an array of objects with the following properties:

      +
        +
      • priority
      • +
      • weight
      • +
      • port
      • +
      • name
      • +
      + +
      {
      +  priority: 10,
      +  weight: 5,
      +  port: 21223,
      +  name: 'service.example.com'
      +}
      +

      dns.resolveTxt(hostname, callback)#

      + + +

      Uses the DNS protocol to resolve text queries (TXT records) for the +hostname. The records argument passed to the callback function is a +two-dimensional array of the text records available for hostname (e.g. +[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of +one record. Depending on the use case, these could be either joined together or +treated separately.

      +

      dns.reverse(ip, callback)#

      + + +

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an +array of host names.

      +

      On error, err is an Error object, where err.code is +one of the DNS error codes.

      +

      dns.setServers(servers)#

      + + +

      Sets the IP address and port of servers to be used when performing DNS +resolution. The servers argument is an array of RFC 5952 formatted +addresses. If the port is the IANA default DNS port (53) it can be omitted.

      +
      dns.setServers([
      +  '4.4.4.4',
      +  '[2001:4860:4860::8888]',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]);
      +

      An error will be thrown if an invalid address is provided.

      +

      The dns.setServers() method must not be called while a DNS query is in +progress.

      +

      The dns.setServers() method affects only dns.resolve(), +dns.resolve*() and dns.reverse() (and specifically not +dns.lookup()).

      +

      This method works much like +resolve.conf. +That is, if attempting to resolve with the first server provided results in a +NOTFOUND error, the resolve() method will not attempt to resolve with +subsequent servers provided. Fallback DNS servers will only be used if the +earlier ones time out or result in some other error.

      +

      DNS promises API#

      +

      The dns.promises API provides an alternative set of asynchronous DNS methods +that return Promise objects rather than using callbacks. The API is accessible +via require('dns').promises.

      +

      Class: dnsPromises.Resolver#

      + +

      An independent resolver for DNS requests.

      +

      Creating a new resolver uses the default server settings. Setting +the servers used for a resolver using +resolver.setServers() does not affect +other resolvers:

      +
      const { Resolver } = require('dns').promises;
      +const resolver = new Resolver();
      +resolver.setServers(['4.4.4.4']);
      +
      +// This request will use the server at 4.4.4.4, independent of global settings.
      +resolver.resolve4('example.org').then((addresses) => {
      +  // ...
      +});
      +
      +// Alternatively, the same code can be written using async-await style.
      +(async function() {
      +  const addresses = await resolver.resolve4('example.org');
      +})();
      +

      The following methods from the dnsPromises API are available:

      + +

      dnsPromises.getServers()#

      + + +

      Returns an array of IP address strings, formatted according to RFC 5952, +that are currently configured for DNS resolution. A string will include a port +section if a custom port is used.

      + +
      [
      +  '4.4.4.4',
      +  '2001:4860:4860::8888',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]
      +

      dnsPromises.lookup(hostname[, options])#

      + +
        +
      • hostname <string>
      • +
      • options <integer> | <Object> +
          +
        • family <integer> The record family. Must be 4, 6, or 0. The value +0 indicates that IPv4 and IPv6 addresses are both returned. Default: +0.
        • +
        • hints <number> One or more supported getaddrinfo flags. Multiple +flags may be passed by bitwise ORing their values.
        • +
        • all <boolean> When true, the Promise is resolved with all addresses in +an array. Otherwise, returns a single address. Default: false.
        • +
        • verbatim <boolean> When true, the Promise is resolved with IPv4 and +IPv6 addresses in the order the DNS resolver returned them. When false, +IPv4 addresses are placed before IPv6 addresses. +Default: currently false (addresses are reordered) but this is +expected to change in the not too distant future. +New code should use { verbatim: true }.
        • +
        +
      • +
      +

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or +AAAA (IPv6) record. All option properties are optional. If options is an +integer, then it must be 4 or 6 – if options is not provided, then IPv4 +and IPv6 addresses are both returned if found.

      +

      With the all option set to true, the Promise is resolved with addresses +being an array of objects with the properties address and family.

      +

      On error, the Promise is rejected with an Error object, where err.code +is the error code. +Keep in mind that err.code will be set to 'ENOTFOUND' not only when +the host name does not exist but also when the lookup fails in other ways +such as no available file descriptors.

      +

      dnsPromises.lookup() does not necessarily have anything to do with the DNS +protocol. The implementation uses an operating system facility that can +associate names with addresses, and vice versa. This implementation can have +subtle but important consequences on the behavior of any Node.js program. Please +take some time to consult the Implementation considerations section before +using dnsPromises.lookup().

      +

      Example usage:

      +
      const dns = require('dns');
      +const dnsPromises = dns.promises;
      +const options = {
      +  family: 6,
      +  hints: dns.ADDRCONFIG | dns.V4MAPPED,
      +};
      +
      +dnsPromises.lookup('example.com', options).then((result) => {
      +  console.log('address: %j family: IPv%s', result.address, result.family);
      +  // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
      +});
      +
      +// When options.all is true, the result will be an Array.
      +options.all = true;
      +dnsPromises.lookup('example.com', options).then((result) => {
      +  console.log('addresses: %j', result);
      +  // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
      +});
      +

      dnsPromises.lookupService(address, port)#

      + + +

      Resolves the given address and port into a host name and service using +the operating system's underlying getnameinfo implementation.

      +

      If address is not a valid IP address, a TypeError will be thrown. +The port will be coerced to a number. If it is not a legal port, a TypeError +will be thrown.

      +

      On error, the Promise is rejected with an Error object, where err.code +is the error code.

      +
      const dnsPromises = require('dns').promises;
      +dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
      +  console.log(result.hostname, result.service);
      +  // Prints: localhost ssh
      +});
      +

      dnsPromises.resolve(hostname[, rrtype])#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • rrtype <string> Resource record type. Default: 'A'.
      • +
      +

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array +of the resource records. When successful, the Promise is resolved with an +array of resource records. The type and structure of individual results vary +based on rrtype:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dnsPromises.resolve4()
      'AAAA'IPv6 addresses<string>dnsPromises.resolve6()
      'ANY'any records<Object>dnsPromises.resolveAny()
      'CNAME'canonical name records<string>dnsPromises.resolveCname()
      'MX'mail exchange records<Object>dnsPromises.resolveMx()
      'NAPTR'name authority pointer records<Object>dnsPromises.resolveNaptr()
      'NS'name server records<string>dnsPromises.resolveNs()
      'PTR'pointer records<string>dnsPromises.resolvePtr()
      'SOA'start of authority records<Object>dnsPromises.resolveSoa()
      'SRV'service records<Object>dnsPromises.resolveSrv()
      'TXT'text records<string[]>dnsPromises.resolveTxt()
      +

      On error, the Promise is rejected with an Error object, where err.code +is one of the DNS error codes.

      +

      dnsPromises.resolve4(hostname[, options])#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the Promise is resolved with an array of +{ address: '1.2.3.4', ttl: 60 } objects rather than an array of strings, +with the TTL expressed in seconds.
        • +
        +
      • +
      +

      Uses the DNS protocol to resolve IPv4 addresses (A records) for the +hostname. On success, the Promise is resolved with an array of IPv4 +addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      +

      dnsPromises.resolve6(hostname[, options])#

      + +
        +
      • hostname <string> Host name to resolve.
      • +
      • options <Object> +
          +
        • ttl <boolean> Retrieve the Time-To-Live value (TTL) of each record. +When true, the Promise is resolved with an array of +{ address: '0:1:2:3:4:5:6:7', ttl: 60 } objects rather than an array of +strings, with the TTL expressed in seconds.
        • +
        +
      • +
      +

      Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the +hostname. On success, the Promise is resolved with an array of IPv6 +addresses.

      +

      dnsPromises.resolveAny(hostname)#

      + + +

      Uses the DNS protocol to resolve all records (also known as ANY or * query). +On success, the Promise is resolved with an array containing various types of +records. Each object has a property type that indicates the type of the +current record. And depending on the type, additional properties will be +present on the object:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dnsPromises.resolveMx()
      'NAPTR'Refer to dnsPromises.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dnsPromises.resolveSoa()
      'SRV'Refer to dnsPromises.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      +

      Here is an example of the result object:

      + +
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },
      +  { type: 'CNAME', value: 'example.com' },
      +  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
      +  { type: 'NS', value: 'ns1.example.com' },
      +  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
      +  { type: 'SOA',
      +    nsname: 'ns1.example.com',
      +    hostmaster: 'admin.example.com',
      +    serial: 156696742,
      +    refresh: 900,
      +    retry: 900,
      +    expire: 1800,
      +    minttl: 60 } ]
      +

      dnsPromises.resolveCname(hostname)#

      + + +

      Uses the DNS protocol to resolve CNAME records for the hostname. On success, +the Promise is resolved with an array of canonical name records available for +the hostname (e.g. ['bar.example.com']).

      +

      dnsPromises.resolveMx(hostname)#

      + + +

      Uses the DNS protocol to resolve mail exchange records (MX records) for the +hostname. On success, the Promise is resolved with an array of objects +containing both a priority and exchange property (e.g. +[{priority: 10, exchange: 'mx.example.com'}, ...]).

      +

      dnsPromises.resolveNaptr(hostname)#

      + + +

      Uses the DNS protocol to resolve regular expression based records (NAPTR +records) for the hostname. On success, the Promise is resolved with an array +of objects with the following properties:

      +
        +
      • flags
      • +
      • service
      • +
      • regexp
      • +
      • replacement
      • +
      • order
      • +
      • preference
      • +
      + +
      {
      +  flags: 's',
      +  service: 'SIP+D2U',
      +  regexp: '',
      +  replacement: '_sip._udp.example.com',
      +  order: 30,
      +  preference: 100
      +}
      +

      dnsPromises.resolveNs(hostname)#

      + + +

      Uses the DNS protocol to resolve name server records (NS records) for the +hostname. On success, the Promise is resolved with an array of name server +records available for hostname (e.g. +['ns1.example.com', 'ns2.example.com']).

      +

      dnsPromises.resolvePtr(hostname)#

      + + +

      Uses the DNS protocol to resolve pointer records (PTR records) for the +hostname. On success, the Promise is resolved with an array of strings +containing the reply records.

      +

      dnsPromises.resolveSoa(hostname)#

      + + +

      Uses the DNS protocol to resolve a start of authority record (SOA record) for +the hostname. On success, the Promise is resolved with an object with the +following properties:

      +
        +
      • nsname
      • +
      • hostmaster
      • +
      • serial
      • +
      • refresh
      • +
      • retry
      • +
      • expire
      • +
      • minttl
      • +
      + +
      {
      +  nsname: 'ns.example.com',
      +  hostmaster: 'root.example.com',
      +  serial: 2013101809,
      +  refresh: 10000,
      +  retry: 2400,
      +  expire: 604800,
      +  minttl: 3600
      +}
      +

      dnsPromises.resolveSrv(hostname)#

      + + +

      Uses the DNS protocol to resolve service records (SRV records) for the +hostname. On success, the Promise is resolved with an array of objects with +the following properties:

      +
        +
      • priority
      • +
      • weight
      • +
      • port
      • +
      • name
      • +
      + +
      {
      +  priority: 10,
      +  weight: 5,
      +  port: 21223,
      +  name: 'service.example.com'
      +}
      +

      dnsPromises.resolveTxt(hostname)#

      + + +

      Uses the DNS protocol to resolve text queries (TXT records) for the +hostname. On success, the Promise is resolved with a two-dimensional array +of the text records available for hostname (e.g. +[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of +one record. Depending on the use case, these could be either joined together or +treated separately.

      +

      dnsPromises.reverse(ip)#

      + + +

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an +array of host names.

      +

      On error, the Promise is rejected with an Error object, where err.code +is one of the DNS error codes.

      +

      dnsPromises.setServers(servers)#

      + + +

      Sets the IP address and port of servers to be used when performing DNS +resolution. The servers argument is an array of RFC 5952 formatted +addresses. If the port is the IANA default DNS port (53) it can be omitted.

      +
      dnsPromises.setServers([
      +  '4.4.4.4',
      +  '[2001:4860:4860::8888]',
      +  '4.4.4.4:1053',
      +  '[2001:4860:4860::8888]:1053'
      +]);
      +

      An error will be thrown if an invalid address is provided.

      +

      The dnsPromises.setServers() method must not be called while a DNS query is in +progress.

      +

      This method works much like +resolve.conf. +That is, if attempting to resolve with the first server provided results in a +NOTFOUND error, the resolve() method will not attempt to resolve with +subsequent servers provided. Fallback DNS servers will only be used if the +earlier ones time out or result in some other error.

      +

      Error codes#

      +

      Each DNS query can return one of the following error codes:

      +
        +
      • dns.NODATA: DNS server returned answer with no data.
      • +
      • dns.FORMERR: DNS server claims query was misformatted.
      • +
      • dns.SERVFAIL: DNS server returned general failure.
      • +
      • dns.NOTFOUND: Domain name not found.
      • +
      • dns.NOTIMP: DNS server does not implement requested operation.
      • +
      • dns.REFUSED: DNS server refused query.
      • +
      • dns.BADQUERY: Misformatted DNS query.
      • +
      • dns.BADNAME: Misformatted host name.
      • +
      • dns.BADFAMILY: Unsupported address family.
      • +
      • dns.BADRESP: Misformatted DNS reply.
      • +
      • dns.CONNREFUSED: Could not contact DNS servers.
      • +
      • dns.TIMEOUT: Timeout while contacting DNS servers.
      • +
      • dns.EOF: End of file.
      • +
      • dns.FILE: Error reading file.
      • +
      • dns.NOMEM: Out of memory.
      • +
      • dns.DESTRUCTION: Channel is being destroyed.
      • +
      • dns.BADSTR: Misformatted string.
      • +
      • dns.BADFLAGS: Illegal flags specified.
      • +
      • dns.NONAME: Given host name is not numeric.
      • +
      • dns.BADHINTS: Illegal hints flags specified.
      • +
      • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
      • +
      • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
      • +
      • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
      • +
      • dns.CANCELLED: DNS query cancelled.
      • +
      +

      Implementation considerations#

      +

      Although dns.lookup() and the various dns.resolve*()/dns.reverse() +functions have the same goal of associating a network name with a network +address (or vice versa), their behavior is quite different. These differences +can have subtle but significant consequences on the behavior of Node.js +programs.

      +

      dns.lookup()#

      +

      Under the hood, dns.lookup() uses the same operating system facilities +as most other programs. For instance, dns.lookup() will almost always +resolve a given name the same way as the ping command. On most POSIX-like +operating systems, the behavior of the dns.lookup() function can be +modified by changing settings in nsswitch.conf(5) and/or resolv.conf(5), +but changing these files will change the behavior of all other +programs running on the same operating system.

      +

      Though the call to dns.lookup() will be asynchronous from JavaScript's +perspective, it is implemented as a synchronous call to getaddrinfo(3) that runs +on libuv's threadpool. This can have surprising negative performance +implications for some applications, see the UV_THREADPOOL_SIZE +documentation for more information.

      +

      Various networking APIs will call dns.lookup() internally to resolve +host names. If that is an issue, consider resolving the host name to an address +using dns.resolve() and using the address instead of a host name. Also, some +networking APIs (such as socket.connect() and dgram.createSocket()) +allow the default resolver, dns.lookup(), to be replaced.

      +

      dns.resolve(), dns.resolve*() and dns.reverse()#

      +

      These functions are implemented quite differently than dns.lookup(). They +do not use getaddrinfo(3) and they always perform a DNS query on the +network. This network communication is always done asynchronously, and does not +use libuv's threadpool.

      +

      As a result, these functions cannot have the same negative impact on other +processing that happens on libuv's threadpool that dns.lookup() can have.

      +

      They do not use the same set of configuration files than what dns.lookup() +uses. For instance, they do not use the configuration from /etc/hosts.

      + +
      +
      +
      + + diff --git a/doc/api/dns.json b/doc/api/dns.json new file mode 100644 index 0000000000000000000000000000000000000000..872f2b84e2fb2b38011390fc1441271ba6907fff --- /dev/null +++ b/doc/api/dns.json @@ -0,0 +1,1371 @@ +{ + "type": "module", + "source": "doc/api/dns.md", + "modules": [ + { + "textRaw": "DNS", + "name": "dns", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/dns.js

      \n

      The dns module enables name resolution. For example, use it to look up IP\naddresses of host names.

      \n

      Although named for the Domain Name System (DNS), it does not always use the\nDNS protocol for lookups. dns.lookup() uses the operating system\nfacilities to perform name resolution. It may not need to perform any network\ncommunication. To perform name resolution the way other applications on the same\nsystem do, use dns.lookup().

      \n
      const dns = require('dns');\n\ndns.lookup('example.org', (err, address, family) => {\n  console.log('address: %j family: IPv%s', address, family);\n});\n// address: \"93.184.216.34\" family: IPv4\n
      \n

      All other functions in the dns module connect to an actual DNS server to\nperform name resolution. They will always use the network to perform DNS\nqueries. These functions do not use the same set of configuration files used by\ndns.lookup() (e.g. /etc/hosts). Use these functions to always perform\nDNS queries, bypassing other name-resolution facilities.

      \n
      const dns = require('dns');\n\ndns.resolve4('archive.org', (err, addresses) => {\n  if (err) throw err;\n\n  console.log(`addresses: ${JSON.stringify(addresses)}`);\n\n  addresses.forEach((a) => {\n    dns.reverse(a, (err, hostnames) => {\n      if (err) {\n        throw err;\n      }\n      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);\n    });\n  });\n});\n
      \n

      See the Implementation considerations section for more information.

      ", + "classes": [ + { + "textRaw": "Class: `dns.Resolver`", + "type": "class", + "name": "dns.Resolver", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "desc": "

      An independent resolver for DNS requests.

      \n

      Creating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:

      \n
      const { Resolver } = require('dns');\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org', (err, addresses) => {\n  // ...\n});\n
      \n

      The following methods from the dns module are available:

      \n", + "methods": [ + { + "textRaw": "`Resolver([options])`", + "type": "method", + "name": "Resolver", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [ + { + "version": "v12.18.3", + "pr-url": "https://github.com/nodejs/node/pull/33472", + "description": "The constructor now accepts an `options` object. The single supported option is `timeout`." + } + ] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Create a new resolver.

      \n
        \n
      • options <Object>\n
          \n
        • timeout <integer> Query timeout in milliseconds, or -1 to use the\ndefault timeout.
        • \n
        \n
      • \n
      " + }, + { + "textRaw": "`resolver.cancel()`", + "type": "method", + "name": "cancel", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Cancel all outstanding DNS queries made by this resolver. The corresponding\ncallbacks will be called with an error with code ECANCELLED.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`dns.getServers()`", + "type": "method", + "name": "getServers", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array of IP address strings, formatted according to RFC 5952,\nthat are currently configured for DNS resolution. A string will include a port\nsection if a custom port is used.

      \n\n
      [\n  '4.4.4.4',\n  '2001:4860:4860::8888',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]\n
      " + }, + { + "textRaw": "`dns.lookup(hostname[, options], callback)`", + "type": "method", + "name": "lookup", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v8.5.0", + "pr-url": "https://github.com/nodejs/node/pull/14731", + "description": "The `verbatim` option is supported now." + }, + { + "version": "v1.2.0", + "pr-url": "https://github.com/nodejs/node/pull/744", + "description": "The `all` option is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`options` {integer | Object}", + "name": "options", + "type": "integer | Object", + "options": [ + { + "textRaw": "`family` {integer} The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:** `0`.", + "name": "family", + "type": "integer", + "default": "`0`", + "desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned." + }, + { + "textRaw": "`hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values.", + "name": "hints", + "type": "number", + "desc": "One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values." + }, + { + "textRaw": "`all` {boolean} When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. **Default:** `false`.", + "name": "all", + "type": "boolean", + "default": "`false`", + "desc": "When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address." + }, + { + "textRaw": "`verbatim` {boolean} When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. **Default:** currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`.", + "name": "verbatim", + "type": "boolean", + "default": "currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`", + "desc": "When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`address` {string} A string representation of an IPv4 or IPv6 address.", + "name": "address", + "type": "string", + "desc": "A string representation of an IPv4 or IPv6 address." + }, + { + "textRaw": "`family` {integer} `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a bug in the name resolution service used by the operating system.", + "name": "family", + "type": "integer", + "desc": "`4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a bug in the name resolution service used by the operating system." + } + ] + } + ] + } + ], + "desc": "

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. All option properties are optional. If options is an\ninteger, then it must be 4 or 6 – if options is not provided, then IPv4\nand IPv6 addresses are both returned if found.

      \n

      With the all option set to true, the arguments for callback change to\n(err, addresses), with addresses being an array of objects with the\nproperties address and family.

      \n

      On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOTFOUND' not only when\nthe host name does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.

      \n

      dns.lookup() does not necessarily have anything to do with the DNS protocol.\nThe implementation uses an operating system facility that can associate names\nwith addresses, and vice versa. This implementation can have subtle but\nimportant consequences on the behavior of any Node.js program. Please take some\ntime to consult the Implementation considerations section before using\ndns.lookup().

      \n

      Example usage:

      \n
      const dns = require('dns');\nconst options = {\n  family: 6,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\ndns.lookup('example.com', options, (err, address, family) =>\n  console.log('address: %j family: IPv%s', address, family));\n// address: \"2606:2800:220:1:248:1893:25c8:1946\" family: IPv6\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndns.lookup('example.com', options, (err, addresses) =>\n  console.log('addresses: %j', addresses));\n// addresses: [{\"address\":\"2606:2800:220:1:248:1893:25c8:1946\",\"family\":6}]\n
      \n

      If this method is invoked as its util.promisify()ed version, and all\nis not set to true, it returns a Promise for an Object with address and\nfamily properties.

      ", + "modules": [ + { + "textRaw": "Supported getaddrinfo flags", + "name": "supported_getaddrinfo_flags", + "meta": { + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32183", + "description": "Added support for the `dns.ALL` flag." + } + ] + }, + "desc": "

      The following flags can be passed as hints to dns.lookup().

      \n
        \n
      • dns.ADDRCONFIG: Limits returned address types to the types of non-loopback\naddresses configured on the system. For example, IPv4 addresses are only\nreturned if the current system has at least one IPv4 address configured.
      • \n
      • dns.V4MAPPED: If the IPv6 family was specified, but no IPv6 addresses were\nfound, then return IPv4 mapped IPv6 addresses. It is not supported\non some operating systems (e.g FreeBSD 10.1).
      • \n
      • dns.ALL: If dns.V4MAPPED is specified, return resolved IPv6 addresses as\nwell as IPv4 mapped IPv6 addresses.
      • \n
      ", + "type": "module", + "displayName": "Supported getaddrinfo flags" + } + ] + }, + { + "textRaw": "`dns.lookupService(address, port, callback)`", + "type": "method", + "name": "lookupService", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`hostname` {string} e.g. `example.com`", + "name": "hostname", + "type": "string", + "desc": "e.g. `example.com`" + }, + { + "textRaw": "`service` {string} e.g. `http`", + "name": "service", + "type": "string", + "desc": "e.g. `http`" + } + ] + } + ] + } + ], + "desc": "

      Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.

      \n

      If address is not a valid IP address, a TypeError will be thrown.\nThe port will be coerced to a number. If it is not a legal port, a TypeError\nwill be thrown.

      \n

      On an error, err is an Error object, where err.code is the error code.

      \n
      const dns = require('dns');\ndns.lookupService('127.0.0.1', 22, (err, hostname, service) => {\n  console.log(hostname, service);\n  // Prints: localhost ssh\n});\n
      \n

      If this method is invoked as its util.promisify()ed version, it returns a\nPromise for an Object with hostname and service properties.

      " + }, + { + "textRaw": "`dns.resolve(hostname[, rrtype], callback)`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`rrtype` {string} Resource record type. **Default:** `'A'`.", + "name": "rrtype", + "type": "string", + "default": "`'A'`", + "desc": "Resource record type." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`records` {string[] | Object[] | Object}", + "name": "records", + "type": "string[] | Object[] | Object" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array\nof the resource records. The callback function has arguments\n(err, records). When successful, records will be an array of resource\nrecords. The type and structure of individual results varies based on rrtype:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dns.resolve4()
      'AAAA'IPv6 addresses<string>dns.resolve6()
      'ANY'any records<Object>dns.resolveAny()
      'CNAME'canonical name records<string>dns.resolveCname()
      'MX'mail exchange records<Object>dns.resolveMx()
      'NAPTR'name authority pointer records<Object>dns.resolveNaptr()
      'NS'name server records<string>dns.resolveNs()
      'PTR'pointer records<string>dns.resolvePtr()
      'SOA'start of authority records<Object>dns.resolveSoa()
      'SRV'service records<Object>dns.resolveSrv()
      'TXT'text records<string[]>dns.resolveTxt()
      \n

      On error, err is an Error object, where err.code is one of the\nDNS error codes.

      " + }, + { + "textRaw": "`dns.resolve4(hostname[, options], callback)`", + "type": "method", + "name": "resolve4", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9296", + "description": "This method now supports passing `options`, specifically `options.ttl`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[] | Object[]}", + "name": "addresses", + "type": "string[] | Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a IPv4 addresses (A records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      " + }, + { + "textRaw": "`dns.resolve6(hostname[, options], callback)`", + "type": "method", + "name": "resolve6", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9296", + "description": "This method now supports passing `options`, specifically `options.ttl`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[] | Object[]}", + "name": "addresses", + "type": "string[] | Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a IPv6 addresses (AAAA records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv6 addresses.

      " + }, + { + "textRaw": "`dns.resolveAny(hostname, callback)`", + "type": "method", + "name": "resolveAny", + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`ret` {Object[]}", + "name": "ret", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve all records (also known as ANY or * query).\nThe ret argument passed to the callback function will be an array containing\nvarious types of records. Each object has a property type that indicates the\ntype of the current record. And depending on the type, additional properties\nwill be present on the object:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dns.resolveMx()
      'NAPTR'Refer to dns.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dns.resolveSoa()
      'SRV'Refer to dns.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      \n

      Here is an example of the ret object passed to the callback:

      \n\n
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },\n  { type: 'CNAME', value: 'example.com' },\n  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },\n  { type: 'NS', value: 'ns1.example.com' },\n  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },\n  { type: 'SOA',\n    nsname: 'ns1.example.com',\n    hostmaster: 'admin.example.com',\n    serial: 156696742,\n    refresh: 900,\n    retry: 900,\n    expire: 1800,\n    minttl: 60 } ]\n
      \n

      DNS server operators may choose not to respond to ANY\nqueries. It may be better to call individual methods like dns.resolve4(),\ndns.resolveMx(), and so on. For more details, see RFC 8482.

      " + }, + { + "textRaw": "`dns.resolveCname(hostname, callback)`", + "type": "method", + "name": "resolveCname", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[]}", + "name": "addresses", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve CNAME records for the hostname. The\naddresses argument passed to the callback function\nwill contain an array of canonical name records available for the hostname\n(e.g. ['bar.example.com']).

      " + }, + { + "textRaw": "`dns.resolveMx(hostname, callback)`", + "type": "method", + "name": "resolveMx", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {Object[]}", + "name": "addresses", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve mail exchange records (MX records) for the\nhostname. The addresses argument passed to the callback function will\ncontain an array of objects containing both a priority and exchange\nproperty (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).

      " + }, + { + "textRaw": "`dns.resolveNaptr(hostname, callback)`", + "type": "method", + "name": "resolveNaptr", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {Object[]}", + "name": "addresses", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve regular expression based records (NAPTR\nrecords) for the hostname. The addresses argument passed to the callback\nfunction will contain an array of objects with the following properties:

      \n
        \n
      • flags
      • \n
      • service
      • \n
      • regexp
      • \n
      • replacement
      • \n
      • order
      • \n
      • preference
      • \n
      \n\n
      {\n  flags: 's',\n  service: 'SIP+D2U',\n  regexp: '',\n  replacement: '_sip._udp.example.com',\n  order: 30,\n  preference: 100\n}\n
      " + }, + { + "textRaw": "`dns.resolveNs(hostname, callback)`", + "type": "method", + "name": "resolveNs", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[]}", + "name": "addresses", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve name server records (NS records) for the\nhostname. The addresses argument passed to the callback function will\ncontain an array of name server records available for hostname\n(e.g. ['ns1.example.com', 'ns2.example.com']).

      " + }, + { + "textRaw": "`dns.resolvePtr(hostname, callback)`", + "type": "method", + "name": "resolvePtr", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {string[]}", + "name": "addresses", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve pointer records (PTR records) for the\nhostname. The addresses argument passed to the callback function will\nbe an array of strings containing the reply records.

      " + }, + { + "textRaw": "`dns.resolveSoa(hostname, callback)`", + "type": "method", + "name": "resolveSoa", + "meta": { + "added": [ + "v0.11.10" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`address` {Object}", + "name": "address", + "type": "Object" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. The address argument passed to the callback function will\nbe an object with the following properties:

      \n
        \n
      • nsname
      • \n
      • hostmaster
      • \n
      • serial
      • \n
      • refresh
      • \n
      • retry
      • \n
      • expire
      • \n
      • minttl
      • \n
      \n\n
      {\n  nsname: 'ns.example.com',\n  hostmaster: 'root.example.com',\n  serial: 2013101809,\n  refresh: 10000,\n  retry: 2400,\n  expire: 604800,\n  minttl: 3600\n}\n
      " + }, + { + "textRaw": "`dns.resolveSrv(hostname, callback)`", + "type": "method", + "name": "resolveSrv", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`addresses` {Object[]}", + "name": "addresses", + "type": "Object[]" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve service records (SRV records) for the\nhostname. The addresses argument passed to the callback function will\nbe an array of objects with the following properties:

      \n
        \n
      • priority
      • \n
      • weight
      • \n
      • port
      • \n
      • name
      • \n
      \n\n
      {\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
      " + }, + { + "textRaw": "`dns.resolveTxt(hostname, callback)`", + "type": "method", + "name": "resolveTxt", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`records` <string[][]>", + "name": "records", + "desc": "<string[][]>" + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. The records argument passed to the callback function is a\ntwo-dimensional array of the text records available for hostname (e.g.\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.

      " + }, + { + "textRaw": "`dns.reverse(ip, callback)`", + "type": "method", + "name": "reverse", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ip` {string}", + "name": "ip", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`hostnames` {string[]}", + "name": "hostnames", + "type": "string[]" + } + ] + } + ] + } + ], + "desc": "

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.

      \n

      On error, err is an Error object, where err.code is\none of the DNS error codes.

      " + }, + { + "textRaw": "`dns.setServers(servers)`", + "type": "method", + "name": "setServers", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`servers` {string[]} array of [RFC 5952][] formatted addresses", + "name": "servers", + "type": "string[]", + "desc": "array of [RFC 5952][] formatted addresses" + } + ] + } + ], + "desc": "

      Sets the IP address and port of servers to be used when performing DNS\nresolution. The servers argument is an array of RFC 5952 formatted\naddresses. If the port is the IANA default DNS port (53) it can be omitted.

      \n
      dns.setServers([\n  '4.4.4.4',\n  '[2001:4860:4860::8888]',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]);\n
      \n

      An error will be thrown if an invalid address is provided.

      \n

      The dns.setServers() method must not be called while a DNS query is in\nprogress.

      \n

      The dns.setServers() method affects only dns.resolve(),\ndns.resolve*() and dns.reverse() (and specifically not\ndns.lookup()).

      \n

      This method works much like\nresolve.conf.\nThat is, if attempting to resolve with the first server provided results in a\nNOTFOUND error, the resolve() method will not attempt to resolve with\nsubsequent servers provided. Fallback DNS servers will only be used if the\nearlier ones time out or result in some other error.

      " + } + ], + "modules": [ + { + "textRaw": "DNS promises API", + "name": "dns_promises_api", + "desc": "

      The dns.promises API provides an alternative set of asynchronous DNS methods\nthat return Promise objects rather than using callbacks. The API is accessible\nvia require('dns').promises.

      ", + "classes": [ + { + "textRaw": "Class: `dnsPromises.Resolver`", + "type": "class", + "name": "dnsPromises.Resolver", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "desc": "

      An independent resolver for DNS requests.

      \n

      Creating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:

      \n
      const { Resolver } = require('dns').promises;\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org').then((addresses) => {\n  // ...\n});\n\n// Alternatively, the same code can be written using async-await style.\n(async function() {\n  const addresses = await resolver.resolve4('example.org');\n})();\n
      \n

      The following methods from the dnsPromises API are available:

      \n" + } + ], + "methods": [ + { + "textRaw": "`dnsPromises.getServers()`", + "type": "method", + "name": "getServers", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array of IP address strings, formatted according to RFC 5952,\nthat are currently configured for DNS resolution. A string will include a port\nsection if a custom port is used.

      \n\n
      [\n  '4.4.4.4',\n  '2001:4860:4860::8888',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]\n
      " + }, + { + "textRaw": "`dnsPromises.lookup(hostname[, options])`", + "type": "method", + "name": "lookup", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + }, + { + "textRaw": "`options` {integer | Object}", + "name": "options", + "type": "integer | Object", + "options": [ + { + "textRaw": "`family` {integer} The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:** `0`.", + "name": "family", + "type": "integer", + "default": "`0`", + "desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned." + }, + { + "textRaw": "`hints` {number} One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values.", + "name": "hints", + "type": "number", + "desc": "One or more [supported `getaddrinfo` flags][]. Multiple flags may be passed by bitwise `OR`ing their values." + }, + { + "textRaw": "`all` {boolean} When `true`, the `Promise` is resolved with all addresses in an array. Otherwise, returns a single address. **Default:** `false`.", + "name": "all", + "type": "boolean", + "default": "`false`", + "desc": "When `true`, the `Promise` is resolved with all addresses in an array. Otherwise, returns a single address." + }, + { + "textRaw": "`verbatim` {boolean} When `true`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. **Default:** currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`.", + "name": "verbatim", + "type": "boolean", + "default": "currently `false` (addresses are reordered) but this is expected to change in the not too distant future. New code should use `{ verbatim: true }`", + "desc": "When `true`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses." + } + ] + } + ] + } + ], + "desc": "

      Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. All option properties are optional. If options is an\ninteger, then it must be 4 or 6 – if options is not provided, then IPv4\nand IPv6 addresses are both returned if found.

      \n

      With the all option set to true, the Promise is resolved with addresses\nbeing an array of objects with the properties address and family.

      \n

      On error, the Promise is rejected with an Error object, where err.code\nis the error code.\nKeep in mind that err.code will be set to 'ENOTFOUND' not only when\nthe host name does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.

      \n

      dnsPromises.lookup() does not necessarily have anything to do with the DNS\nprotocol. The implementation uses an operating system facility that can\nassociate names with addresses, and vice versa. This implementation can have\nsubtle but important consequences on the behavior of any Node.js program. Please\ntake some time to consult the Implementation considerations section before\nusing dnsPromises.lookup().

      \n

      Example usage:

      \n
      const dns = require('dns');\nconst dnsPromises = dns.promises;\nconst options = {\n  family: 6,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\n\ndnsPromises.lookup('example.com', options).then((result) => {\n  console.log('address: %j family: IPv%s', result.address, result.family);\n  // address: \"2606:2800:220:1:248:1893:25c8:1946\" family: IPv6\n});\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndnsPromises.lookup('example.com', options).then((result) => {\n  console.log('addresses: %j', result);\n  // addresses: [{\"address\":\"2606:2800:220:1:248:1893:25c8:1946\",\"family\":6}]\n});\n
      " + }, + { + "textRaw": "`dnsPromises.lookupService(address, port)`", + "type": "method", + "name": "lookupService", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`address` {string}", + "name": "address", + "type": "string" + }, + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + } + ] + } + ], + "desc": "

      Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.

      \n

      If address is not a valid IP address, a TypeError will be thrown.\nThe port will be coerced to a number. If it is not a legal port, a TypeError\nwill be thrown.

      \n

      On error, the Promise is rejected with an Error object, where err.code\nis the error code.

      \n
      const dnsPromises = require('dns').promises;\ndnsPromises.lookupService('127.0.0.1', 22).then((result) => {\n  console.log(result.hostname, result.service);\n  // Prints: localhost ssh\n});\n
      " + }, + { + "textRaw": "`dnsPromises.resolve(hostname[, rrtype])`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`rrtype` {string} Resource record type. **Default:** `'A'`.", + "name": "rrtype", + "type": "string", + "default": "`'A'`", + "desc": "Resource record type." + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array\nof the resource records. When successful, the Promise is resolved with an\narray of resource records. The type and structure of individual results vary\nbased on rrtype:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      rrtyperecords containsResult typeShorthand method
      'A'IPv4 addresses (default)<string>dnsPromises.resolve4()
      'AAAA'IPv6 addresses<string>dnsPromises.resolve6()
      'ANY'any records<Object>dnsPromises.resolveAny()
      'CNAME'canonical name records<string>dnsPromises.resolveCname()
      'MX'mail exchange records<Object>dnsPromises.resolveMx()
      'NAPTR'name authority pointer records<Object>dnsPromises.resolveNaptr()
      'NS'name server records<string>dnsPromises.resolveNs()
      'PTR'pointer records<string>dnsPromises.resolvePtr()
      'SOA'start of authority records<Object>dnsPromises.resolveSoa()
      'SRV'service records<Object>dnsPromises.resolveSrv()
      'TXT'text records<string[]>dnsPromises.resolveTxt()
      \n

      On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.

      " + }, + { + "textRaw": "`dnsPromises.resolve4(hostname[, options])`", + "type": "method", + "name": "resolve4", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve IPv4 addresses (A records) for the\nhostname. On success, the Promise is resolved with an array of IPv4\naddresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).

      " + }, + { + "textRaw": "`dnsPromises.resolve6(hostname[, options])`", + "type": "method", + "name": "resolve6", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} Host name to resolve.", + "name": "hostname", + "type": "string", + "desc": "Host name to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", + "name": "ttl", + "type": "boolean", + "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." + } + ] + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the\nhostname. On success, the Promise is resolved with an array of IPv6\naddresses.

      " + }, + { + "textRaw": "`dnsPromises.resolveAny(hostname)`", + "type": "method", + "name": "resolveAny", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve all records (also known as ANY or * query).\nOn success, the Promise is resolved with an array containing various types of\nrecords. Each object has a property type that indicates the type of the\ncurrent record. And depending on the type, additional properties will be\npresent on the object:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      TypeProperties
      'A'address/ttl
      'AAAA'address/ttl
      'CNAME'value
      'MX'Refer to dnsPromises.resolveMx()
      'NAPTR'Refer to dnsPromises.resolveNaptr()
      'NS'value
      'PTR'value
      'SOA'Refer to dnsPromises.resolveSoa()
      'SRV'Refer to dnsPromises.resolveSrv()
      'TXT'This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
      \n

      Here is an example of the result object:

      \n\n
      [ { type: 'A', address: '127.0.0.1', ttl: 299 },\n  { type: 'CNAME', value: 'example.com' },\n  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },\n  { type: 'NS', value: 'ns1.example.com' },\n  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },\n  { type: 'SOA',\n    nsname: 'ns1.example.com',\n    hostmaster: 'admin.example.com',\n    serial: 156696742,\n    refresh: 900,\n    retry: 900,\n    expire: 1800,\n    minttl: 60 } ]\n
      " + }, + { + "textRaw": "`dnsPromises.resolveCname(hostname)`", + "type": "method", + "name": "resolveCname", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve CNAME records for the hostname. On success,\nthe Promise is resolved with an array of canonical name records available for\nthe hostname (e.g. ['bar.example.com']).

      " + }, + { + "textRaw": "`dnsPromises.resolveMx(hostname)`", + "type": "method", + "name": "resolveMx", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve mail exchange records (MX records) for the\nhostname. On success, the Promise is resolved with an array of objects\ncontaining both a priority and exchange property (e.g.\n[{priority: 10, exchange: 'mx.example.com'}, ...]).

      " + }, + { + "textRaw": "`dnsPromises.resolveNaptr(hostname)`", + "type": "method", + "name": "resolveNaptr", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve regular expression based records (NAPTR\nrecords) for the hostname. On success, the Promise is resolved with an array\nof objects with the following properties:

      \n
        \n
      • flags
      • \n
      • service
      • \n
      • regexp
      • \n
      • replacement
      • \n
      • order
      • \n
      • preference
      • \n
      \n\n
      {\n  flags: 's',\n  service: 'SIP+D2U',\n  regexp: '',\n  replacement: '_sip._udp.example.com',\n  order: 30,\n  preference: 100\n}\n
      " + }, + { + "textRaw": "`dnsPromises.resolveNs(hostname)`", + "type": "method", + "name": "resolveNs", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve name server records (NS records) for the\nhostname. On success, the Promise is resolved with an array of name server\nrecords available for hostname (e.g.\n['ns1.example.com', 'ns2.example.com']).

      " + }, + { + "textRaw": "`dnsPromises.resolvePtr(hostname)`", + "type": "method", + "name": "resolvePtr", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve pointer records (PTR records) for the\nhostname. On success, the Promise is resolved with an array of strings\ncontaining the reply records.

      " + }, + { + "textRaw": "`dnsPromises.resolveSoa(hostname)`", + "type": "method", + "name": "resolveSoa", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. On success, the Promise is resolved with an object with the\nfollowing properties:

      \n
        \n
      • nsname
      • \n
      • hostmaster
      • \n
      • serial
      • \n
      • refresh
      • \n
      • retry
      • \n
      • expire
      • \n
      • minttl
      • \n
      \n\n
      {\n  nsname: 'ns.example.com',\n  hostmaster: 'root.example.com',\n  serial: 2013101809,\n  refresh: 10000,\n  retry: 2400,\n  expire: 604800,\n  minttl: 3600\n}\n
      " + }, + { + "textRaw": "`dnsPromises.resolveSrv(hostname)`", + "type": "method", + "name": "resolveSrv", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve service records (SRV records) for the\nhostname. On success, the Promise is resolved with an array of objects with\nthe following properties:

      \n
        \n
      • priority
      • \n
      • weight
      • \n
      • port
      • \n
      • name
      • \n
      \n\n
      {\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
      " + }, + { + "textRaw": "`dnsPromises.resolveTxt(hostname)`", + "type": "method", + "name": "resolveTxt", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string}", + "name": "hostname", + "type": "string" + } + ] + } + ], + "desc": "

      Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. On success, the Promise is resolved with a two-dimensional array\nof the text records available for hostname (e.g.\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.

      " + }, + { + "textRaw": "`dnsPromises.reverse(ip)`", + "type": "method", + "name": "reverse", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`ip` {string}", + "name": "ip", + "type": "string" + } + ] + } + ], + "desc": "

      Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.

      \n

      On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.

      " + }, + { + "textRaw": "`dnsPromises.setServers(servers)`", + "type": "method", + "name": "setServers", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`servers` {string[]} array of [RFC 5952][] formatted addresses", + "name": "servers", + "type": "string[]", + "desc": "array of [RFC 5952][] formatted addresses" + } + ] + } + ], + "desc": "

      Sets the IP address and port of servers to be used when performing DNS\nresolution. The servers argument is an array of RFC 5952 formatted\naddresses. If the port is the IANA default DNS port (53) it can be omitted.

      \n
      dnsPromises.setServers([\n  '4.4.4.4',\n  '[2001:4860:4860::8888]',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053'\n]);\n
      \n

      An error will be thrown if an invalid address is provided.

      \n

      The dnsPromises.setServers() method must not be called while a DNS query is in\nprogress.

      \n

      This method works much like\nresolve.conf.\nThat is, if attempting to resolve with the first server provided results in a\nNOTFOUND error, the resolve() method will not attempt to resolve with\nsubsequent servers provided. Fallback DNS servers will only be used if the\nearlier ones time out or result in some other error.

      " + } + ], + "type": "module", + "displayName": "DNS promises API" + }, + { + "textRaw": "Error codes", + "name": "error_codes", + "desc": "

      Each DNS query can return one of the following error codes:

      \n
        \n
      • dns.NODATA: DNS server returned answer with no data.
      • \n
      • dns.FORMERR: DNS server claims query was misformatted.
      • \n
      • dns.SERVFAIL: DNS server returned general failure.
      • \n
      • dns.NOTFOUND: Domain name not found.
      • \n
      • dns.NOTIMP: DNS server does not implement requested operation.
      • \n
      • dns.REFUSED: DNS server refused query.
      • \n
      • dns.BADQUERY: Misformatted DNS query.
      • \n
      • dns.BADNAME: Misformatted host name.
      • \n
      • dns.BADFAMILY: Unsupported address family.
      • \n
      • dns.BADRESP: Misformatted DNS reply.
      • \n
      • dns.CONNREFUSED: Could not contact DNS servers.
      • \n
      • dns.TIMEOUT: Timeout while contacting DNS servers.
      • \n
      • dns.EOF: End of file.
      • \n
      • dns.FILE: Error reading file.
      • \n
      • dns.NOMEM: Out of memory.
      • \n
      • dns.DESTRUCTION: Channel is being destroyed.
      • \n
      • dns.BADSTR: Misformatted string.
      • \n
      • dns.BADFLAGS: Illegal flags specified.
      • \n
      • dns.NONAME: Given host name is not numeric.
      • \n
      • dns.BADHINTS: Illegal hints flags specified.
      • \n
      • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
      • \n
      • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
      • \n
      • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
      • \n
      • dns.CANCELLED: DNS query cancelled.
      • \n
      ", + "type": "module", + "displayName": "Error codes" + }, + { + "textRaw": "Implementation considerations", + "name": "implementation_considerations", + "desc": "

      Although dns.lookup() and the various dns.resolve*()/dns.reverse()\nfunctions have the same goal of associating a network name with a network\naddress (or vice versa), their behavior is quite different. These differences\ncan have subtle but significant consequences on the behavior of Node.js\nprograms.

      ", + "methods": [ + { + "textRaw": "`dns.lookup()`", + "type": "method", + "name": "lookup", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Under the hood, dns.lookup() uses the same operating system facilities\nas most other programs. For instance, dns.lookup() will almost always\nresolve a given name the same way as the ping command. On most POSIX-like\noperating systems, the behavior of the dns.lookup() function can be\nmodified by changing settings in nsswitch.conf(5) and/or resolv.conf(5),\nbut changing these files will change the behavior of all other\nprograms running on the same operating system.

      \n

      Though the call to dns.lookup() will be asynchronous from JavaScript's\nperspective, it is implemented as a synchronous call to getaddrinfo(3) that runs\non libuv's threadpool. This can have surprising negative performance\nimplications for some applications, see the UV_THREADPOOL_SIZE\ndocumentation for more information.

      \n

      Various networking APIs will call dns.lookup() internally to resolve\nhost names. If that is an issue, consider resolving the host name to an address\nusing dns.resolve() and using the address instead of a host name. Also, some\nnetworking APIs (such as socket.connect() and dgram.createSocket())\nallow the default resolver, dns.lookup(), to be replaced.

      " + } + ], + "modules": [ + { + "textRaw": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`", + "name": "`dns.resolve()`,_`dns.resolve*()`_and_`dns.reverse()`", + "desc": "

      These functions are implemented quite differently than dns.lookup(). They\ndo not use getaddrinfo(3) and they always perform a DNS query on the\nnetwork. This network communication is always done asynchronously, and does not\nuse libuv's threadpool.

      \n

      As a result, these functions cannot have the same negative impact on other\nprocessing that happens on libuv's threadpool that dns.lookup() can have.

      \n

      They do not use the same set of configuration files than what dns.lookup()\nuses. For instance, they do not use the configuration from /etc/hosts.

      ", + "type": "module", + "displayName": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`" + } + ], + "type": "module", + "displayName": "Implementation considerations" + } + ], + "type": "module", + "displayName": "DNS" + } + ] +} \ No newline at end of file diff --git a/doc/api/documentation.html b/doc/api/documentation.html new file mode 100644 index 0000000000000000000000000000000000000000..a9f34d711baff56141069d43c201aea0f6c45232 --- /dev/null +++ b/doc/api/documentation.html @@ -0,0 +1,187 @@ + + + + + + + About this documentation | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      About this documentation#

      + + +

      Welcome to the official API reference documentation for Node.js!

      +

      Node.js is a JavaScript runtime built on the V8 JavaScript engine.

      +

      Contributing#

      +

      Report errors in this documentation in the issue tracker. See +the contributing guide for directions on how to submit pull requests.

      +

      Stability index#

      + +

      Throughout the documentation are indications of a section's stability. Some APIs +are so proven and so relied upon that they are unlikely to ever change at all. +Others are brand new and experimental, or known to be hazardous.

      +

      The stability indices are as follows:

      +

      Stability: 0 - Deprecated. The feature may emit warnings. Backward +compatibility is not guaranteed.

      + +

      Stability: 1 - Experimental. The feature is not subject to +Semantic Versioning rules. Non-backward compatible changes or removal may +occur in any future release. Use of the feature is not recommended in +production environments.

      + +

      Stability: 2 - Stable. Compatibility with the npm ecosystem is a high +priority.

      +

      Use caution when making use of Experimental features, particularly within +modules. Users may not be aware that experimental features are being used. +Bugs or behavior changes may surprise users when Experimental API +modifications occur. To avoid surprises, use of an Experimental feature may need +a command-line flag. Experimental features may also emit a warning.

      +

      JSON output#

      + +

      Every .html document has a corresponding .json document. This is for IDEs +and other utilities that consume the documentation.

      +

      System calls and man pages#

      +

      Node.js functions which wrap a system call will document that. The docs link +to the corresponding man pages which describe how the system call works.

      +

      Most Unix system calls have Windows analogues. Still, behavior differences may +be unavoidable.

      + +
      +
      +
      + + diff --git a/doc/api/documentation.json b/doc/api/documentation.json new file mode 100644 index 0000000000000000000000000000000000000000..522292f754a171fdb3db3e47aa68a8256a6d449f --- /dev/null +++ b/doc/api/documentation.json @@ -0,0 +1,49 @@ +{ + "type": "module", + "source": "doc/api/documentation.md", + "introduced_in": "v0.10.0", + "miscs": [ + { + "textRaw": "About this documentation", + "name": "About this documentation", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      Welcome to the official API reference documentation for Node.js!

      \n

      Node.js is a JavaScript runtime built on the V8 JavaScript engine.

      ", + "miscs": [ + { + "textRaw": "Contributing", + "name": "contributing", + "desc": "

      Report errors in this documentation in the issue tracker. See\nthe contributing guide for directions on how to submit pull requests.

      ", + "type": "misc", + "displayName": "Contributing" + }, + { + "textRaw": "Stability index", + "name": "Stability index", + "type": "misc", + "desc": "

      Throughout the documentation are indications of a section's stability. Some APIs\nare so proven and so relied upon that they are unlikely to ever change at all.\nOthers are brand new and experimental, or known to be hazardous.

      \n

      The stability indices are as follows:

      \n
      \n

      Stability: 0 - Deprecated. The feature may emit warnings. Backward\ncompatibility is not guaranteed.

      \n
      \n\n
      \n

      Stability: 1 - Experimental. The feature is not subject to\nSemantic Versioning rules. Non-backward compatible changes or removal may\noccur in any future release. Use of the feature is not recommended in\nproduction environments.

      \n
      \n\n
      \n

      Stability: 2 - Stable. Compatibility with the npm ecosystem is a high\npriority.

      \n
      \n

      Use caution when making use of Experimental features, particularly within\nmodules. Users may not be aware that experimental features are being used.\nBugs or behavior changes may surprise users when Experimental API\nmodifications occur. To avoid surprises, use of an Experimental feature may need\na command-line flag. Experimental features may also emit a warning.

      " + }, + { + "textRaw": "JSON output", + "name": "json_output", + "meta": { + "added": [ + "v0.6.12" + ], + "changes": [] + }, + "desc": "

      Every .html document has a corresponding .json document. This is for IDEs\nand other utilities that consume the documentation.

      ", + "type": "misc", + "displayName": "JSON output" + }, + { + "textRaw": "System calls and man pages", + "name": "system_calls_and_man_pages", + "desc": "

      Node.js functions which wrap a system call will document that. The docs link\nto the corresponding man pages which describe how the system call works.

      \n

      Most Unix system calls have Windows analogues. Still, behavior differences may\nbe unavoidable.

      ", + "type": "misc", + "displayName": "System calls and man pages" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/domain.html b/doc/api/domain.html new file mode 100644 index 0000000000000000000000000000000000000000..d7c1ad6cbebe3e4e1c47030d4cfbdd2ada8d02c8 --- /dev/null +++ b/doc/api/domain.html @@ -0,0 +1,564 @@ + + + + + + + Domain | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Domain#

      + + +

      Stability: 0 - Deprecated

      +

      Source Code: lib/domain.js

      +

      This module is pending deprecation. Once a replacement API has been +finalized, this module will be fully deprecated. Most developers should +not have cause to use this module. Users who absolutely must have +the functionality that domains provide may rely on it for the time being +but should expect to have to migrate to a different solution +in the future.

      +

      Domains provide a way to handle multiple different IO operations as a +single group. If any of the event emitters or callbacks registered to a +domain emit an 'error' event, or throw an error, then the domain object +will be notified, rather than losing the context of the error in the +process.on('uncaughtException') handler, or causing the program to +exit immediately with an error code.

      +

      Warning: Don't ignore errors!#

      + +

      Domain error handlers are not a substitute for closing down a +process when an error occurs.

      +

      By the very nature of how throw works in JavaScript, there is almost +never any way to safely "pick up where it left off", without leaking +references, or creating some other sort of undefined brittle state.

      +

      The safest way to respond to a thrown error is to shut down the +process. Of course, in a normal web server, there may be many +open connections, and it is not reasonable to abruptly shut those down +because an error was triggered by someone else.

      +

      The better approach is to send an error response to the request that +triggered the error, while letting the others finish in their normal +time, and stop listening for new requests in that worker.

      +

      In this way, domain usage goes hand-in-hand with the cluster module, +since the master process can fork a new worker when a worker +encounters an error. For Node.js programs that scale to multiple +machines, the terminating proxy or service registry can take note of +the failure, and react accordingly.

      +

      For example, this is not a good idea:

      +
      // XXX WARNING! BAD IDEA!
      +
      +const d = require('domain').create();
      +d.on('error', (er) => {
      +  // The error won't crash the process, but what it does is worse!
      +  // Though we've prevented abrupt process restarting, we are leaking
      +  // resources like crazy if this ever happens.
      +  // This is no better than process.on('uncaughtException')!
      +  console.log(`error, but oh well ${er.message}`);
      +});
      +d.run(() => {
      +  require('http').createServer((req, res) => {
      +    handleRequest(req, res);
      +  }).listen(PORT);
      +});
      +

      By using the context of a domain, and the resilience of separating our +program into multiple worker processes, we can react more +appropriately, and handle errors with much greater safety.

      +
      // Much better!
      +
      +const cluster = require('cluster');
      +const PORT = +process.env.PORT || 1337;
      +
      +if (cluster.isMaster) {
      +  // A more realistic scenario would have more than 2 workers,
      +  // and perhaps not put the master and worker in the same file.
      +  //
      +  // It is also possible to get a bit fancier about logging, and
      +  // implement whatever custom logic is needed to prevent DoS
      +  // attacks and other bad behavior.
      +  //
      +  // See the options in the cluster documentation.
      +  //
      +  // The important thing is that the master does very little,
      +  // increasing our resilience to unexpected errors.
      +
      +  cluster.fork();
      +  cluster.fork();
      +
      +  cluster.on('disconnect', (worker) => {
      +    console.error('disconnect!');
      +    cluster.fork();
      +  });
      +
      +} else {
      +  // the worker
      +  //
      +  // This is where we put our bugs!
      +
      +  const domain = require('domain');
      +
      +  // See the cluster documentation for more details about using
      +  // worker processes to serve requests. How it works, caveats, etc.
      +
      +  const server = require('http').createServer((req, res) => {
      +    const d = domain.create();
      +    d.on('error', (er) => {
      +      console.error(`error ${er.stack}`);
      +
      +      // We're in dangerous territory!
      +      // By definition, something unexpected occurred,
      +      // which we probably didn't want.
      +      // Anything can happen now! Be very careful!
      +
      +      try {
      +        // Make sure we close down within 30 seconds
      +        const killtimer = setTimeout(() => {
      +          process.exit(1);
      +        }, 30000);
      +        // But don't keep the process open just for that!
      +        killtimer.unref();
      +
      +        // Stop taking new requests.
      +        server.close();
      +
      +        // Let the master know we're dead. This will trigger a
      +        // 'disconnect' in the cluster master, and then it will fork
      +        // a new worker.
      +        cluster.worker.disconnect();
      +
      +        // Try to send an error to the request that triggered the problem
      +        res.statusCode = 500;
      +        res.setHeader('content-type', 'text/plain');
      +        res.end('Oops, there was a problem!\n');
      +      } catch (er2) {
      +        // Oh well, not much we can do at this point.
      +        console.error(`Error sending 500! ${er2.stack}`);
      +      }
      +    });
      +
      +    // Because req and res were created before this domain existed,
      +    // we need to explicitly add them.
      +    // See the explanation of implicit vs explicit binding below.
      +    d.add(req);
      +    d.add(res);
      +
      +    // Now run the handler function in the domain.
      +    d.run(() => {
      +      handleRequest(req, res);
      +    });
      +  });
      +  server.listen(PORT);
      +}
      +
      +// This part is not important. Just an example routing thing.
      +// Put fancy application logic here.
      +function handleRequest(req, res) {
      +  switch (req.url) {
      +    case '/error':
      +      // We do some async stuff, and then...
      +      setTimeout(() => {
      +        // Whoops!
      +        flerb.bark();
      +      }, timeout);
      +      break;
      +    default:
      +      res.end('ok');
      +  }
      +}
      +

      Additions to Error objects#

      + +

      Any time an Error object is routed through a domain, a few extra fields +are added to it.

      +
        +
      • error.domain The domain that first handled the error.
      • +
      • error.domainEmitter The event emitter that emitted an 'error' event +with the error object.
      • +
      • error.domainBound The callback function which was bound to the +domain, and passed an error as its first argument.
      • +
      • error.domainThrown A boolean indicating whether the error was +thrown, emitted, or passed to a bound callback function.
      • +
      +

      Implicit binding#

      + +

      If domains are in use, then all new EventEmitter objects (including +Stream objects, requests, responses, etc.) will be implicitly bound to +the active domain at the time of their creation.

      +

      Additionally, callbacks passed to lowlevel event loop requests (such as +to fs.open(), or other callback-taking methods) will automatically be +bound to the active domain. If they throw, then the domain will catch +the error.

      +

      In order to prevent excessive memory usage, Domain objects themselves +are not implicitly added as children of the active domain. If they +were, then it would be too easy to prevent request and response objects +from being properly garbage collected.

      +

      To nest Domain objects as children of a parent Domain they must be +explicitly added.

      +

      Implicit binding routes thrown errors and 'error' events to the +Domain's 'error' event, but does not register the EventEmitter on the +Domain. +Implicit binding only takes care of thrown errors and 'error' events.

      +

      Explicit binding#

      + +

      Sometimes, the domain in use is not the one that ought to be used for a +specific event emitter. Or, the event emitter could have been created +in the context of one domain, but ought to instead be bound to some +other domain.

      +

      For example, there could be one domain in use for an HTTP server, but +perhaps we would like to have a separate domain to use for each request.

      +

      That is possible via explicit binding.

      +
      // Create a top-level domain for the server
      +const domain = require('domain');
      +const http = require('http');
      +const serverDomain = domain.create();
      +
      +serverDomain.run(() => {
      +  // Server is created in the scope of serverDomain
      +  http.createServer((req, res) => {
      +    // Req and res are also created in the scope of serverDomain
      +    // however, we'd prefer to have a separate domain for each request.
      +    // create it first thing, and add req and res to it.
      +    const reqd = domain.create();
      +    reqd.add(req);
      +    reqd.add(res);
      +    reqd.on('error', (er) => {
      +      console.error('Error', er, req.url);
      +      try {
      +        res.writeHead(500);
      +        res.end('Error occurred, sorry.');
      +      } catch (er2) {
      +        console.error('Error sending 500', er2, req.url);
      +      }
      +    });
      +  }).listen(1337);
      +});
      +

      domain.create()#

      + +

      Class: Domain#

      + +

      The Domain class encapsulates the functionality of routing errors and +uncaught exceptions to the active Domain object.

      +

      To handle the errors that it catches, listen to its 'error' event.

      +

      domain.members#

      + +

      An array of timers and event emitters that have been explicitly added +to the domain.

      +

      domain.add(emitter)#

      + +

      Explicitly adds an emitter to the domain. If any event handlers called by +the emitter throw an error, or if the emitter emits an 'error' event, it +will be routed to the domain's 'error' event, just like with implicit +binding.

      +

      This also works with timers that are returned from setInterval() and +setTimeout(). If their callback function throws, it will be caught by +the domain 'error' handler.

      +

      If the Timer or EventEmitter was already bound to a domain, it is removed +from that one, and bound to this one instead.

      +

      domain.bind(callback)#

      + +

      The returned function will be a wrapper around the supplied callback +function. When the returned function is called, any errors that are +thrown will be routed to the domain's 'error' event.

      +
      const d = domain.create();
      +
      +function readSomeFile(filename, cb) {
      +  fs.readFile(filename, 'utf8', d.bind((er, data) => {
      +    // If this throws, it will also be passed to the domain.
      +    return cb(er, data ? JSON.parse(data) : null);
      +  }));
      +}
      +
      +d.on('error', (er) => {
      +  // An error occurred somewhere. If we throw it now, it will crash the program
      +  // with the normal line number and stack message.
      +});
      +

      domain.enter()#

      +

      The enter() method is plumbing used by the run(), bind(), and +intercept() methods to set the active domain. It sets domain.active and +process.domain to the domain, and implicitly pushes the domain onto the domain +stack managed by the domain module (see domain.exit() for details on the +domain stack). The call to enter() delimits the beginning of a chain of +asynchronous calls and I/O operations bound to a domain.

      +

      Calling enter() changes only the active domain, and does not alter the domain +itself. enter() and exit() can be called an arbitrary number of times on a +single domain.

      +

      domain.exit()#

      +

      The exit() method exits the current domain, popping it off the domain stack. +Any time execution is going to switch to the context of a different chain of +asynchronous calls, it's important to ensure that the current domain is exited. +The call to exit() delimits either the end of or an interruption to the chain +of asynchronous calls and I/O operations bound to a domain.

      +

      If there are multiple, nested domains bound to the current execution context, +exit() will exit any domains nested within this domain.

      +

      Calling exit() changes only the active domain, and does not alter the domain +itself. enter() and exit() can be called an arbitrary number of times on a +single domain.

      +

      domain.intercept(callback)#

      + +

      This method is almost identical to domain.bind(callback). However, in +addition to catching thrown errors, it will also intercept Error +objects sent as the first argument to the function.

      +

      In this way, the common if (err) return callback(err); pattern can be replaced +with a single error handler in a single place.

      +
      const d = domain.create();
      +
      +function readSomeFile(filename, cb) {
      +  fs.readFile(filename, 'utf8', d.intercept((data) => {
      +    // Note, the first argument is never passed to the
      +    // callback since it is assumed to be the 'Error' argument
      +    // and thus intercepted by the domain.
      +
      +    // If this throws, it will also be passed to the domain
      +    // so the error-handling logic can be moved to the 'error'
      +    // event on the domain instead of being repeated throughout
      +    // the program.
      +    return cb(null, JSON.parse(data));
      +  }));
      +}
      +
      +d.on('error', (er) => {
      +  // An error occurred somewhere. If we throw it now, it will crash the program
      +  // with the normal line number and stack message.
      +});
      +

      domain.remove(emitter)#

      + +

      The opposite of domain.add(emitter). Removes domain handling from the +specified emitter.

      +

      domain.run(fn[, ...args])#

      + +

      Run the supplied function in the context of the domain, implicitly +binding all event emitters, timers, and lowlevel requests that are +created in that context. Optionally, arguments can be passed to +the function.

      +

      This is the most basic way to use a domain.

      +
      const domain = require('domain');
      +const fs = require('fs');
      +const d = domain.create();
      +d.on('error', (er) => {
      +  console.error('Caught error!', er);
      +});
      +d.run(() => {
      +  process.nextTick(() => {
      +    setTimeout(() => { // Simulating some various async stuff
      +      fs.open('non-existent file', 'r', (er, fd) => {
      +        if (er) throw er;
      +        // proceed...
      +      });
      +    }, 100);
      +  });
      +});
      +

      In this example, the d.on('error') handler will be triggered, rather +than crashing the program.

      +

      Domains and promises#

      +

      As of Node.js 8.0.0, the handlers of promises are run inside the domain in +which the call to .then() or .catch() itself was made:

      +
      const d1 = domain.create();
      +const d2 = domain.create();
      +
      +let p;
      +d1.run(() => {
      +  p = Promise.resolve(42);
      +});
      +
      +d2.run(() => {
      +  p.then((v) => {
      +    // running in d2
      +  });
      +});
      +

      A callback may be bound to a specific domain using domain.bind(callback):

      +
      const d1 = domain.create();
      +const d2 = domain.create();
      +
      +let p;
      +d1.run(() => {
      +  p = Promise.resolve(42);
      +});
      +
      +d2.run(() => {
      +  p.then(p.domain.bind((v) => {
      +    // running in d1
      +  }));
      +});
      +

      Domains will not interfere with the error handling mechanisms for +promises. In other words, no 'error' event will be emitted for unhandled +Promise rejections.

      + +
      +
      +
      + + diff --git a/doc/api/domain.json b/doc/api/domain.json new file mode 100644 index 0000000000000000000000000000000000000000..47e42a7d6700dc51c9e6fb55debbfeea18be20c5 --- /dev/null +++ b/doc/api/domain.json @@ -0,0 +1,230 @@ +{ + "type": "module", + "source": "doc/api/domain.md", + "modules": [ + { + "textRaw": "Domain", + "name": "domain", + "meta": { + "deprecated": [ + "v1.4.2" + ], + "changes": [ + { + "version": "v8.8.0", + "description": "Any `Promise`s created in VM contexts no longer have a `.domain` property. Their handlers are still executed in the proper domain, however, and `Promise`s created in the main context still possess a `.domain` property." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12489", + "description": "Handlers for `Promise`s are now invoked in the domain in which the first promise of a chain was created." + } + ] + }, + "introduced_in": "v0.10.0", + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Source Code: lib/domain.js

      \n

      This module is pending deprecation. Once a replacement API has been\nfinalized, this module will be fully deprecated. Most developers should\nnot have cause to use this module. Users who absolutely must have\nthe functionality that domains provide may rely on it for the time being\nbut should expect to have to migrate to a different solution\nin the future.

      \n

      Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an 'error' event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.

      ", + "miscs": [ + { + "textRaw": "Warning: Don't ignore errors!", + "name": "Warning: Don't ignore errors!", + "type": "misc", + "desc": "

      Domain error handlers are not a substitute for closing down a\nprocess when an error occurs.

      \n

      By the very nature of how throw works in JavaScript, there is almost\nnever any way to safely \"pick up where it left off\", without leaking\nreferences, or creating some other sort of undefined brittle state.

      \n

      The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, there may be many\nopen connections, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.

      \n

      The better approach is to send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.

      \n

      In this way, domain usage goes hand-in-hand with the cluster module,\nsince the master process can fork a new worker when a worker\nencounters an error. For Node.js programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.

      \n

      For example, this is not a good idea:

      \n
      // XXX WARNING! BAD IDEA!\n\nconst d = require('domain').create();\nd.on('error', (er) => {\n  // The error won't crash the process, but what it does is worse!\n  // Though we've prevented abrupt process restarting, we are leaking\n  // resources like crazy if this ever happens.\n  // This is no better than process.on('uncaughtException')!\n  console.log(`error, but oh well ${er.message}`);\n});\nd.run(() => {\n  require('http').createServer((req, res) => {\n    handleRequest(req, res);\n  }).listen(PORT);\n});\n
      \n

      By using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.

      \n
      // Much better!\n\nconst cluster = require('cluster');\nconst PORT = +process.env.PORT || 1337;\n\nif (cluster.isMaster) {\n  // A more realistic scenario would have more than 2 workers,\n  // and perhaps not put the master and worker in the same file.\n  //\n  // It is also possible to get a bit fancier about logging, and\n  // implement whatever custom logic is needed to prevent DoS\n  // attacks and other bad behavior.\n  //\n  // See the options in the cluster documentation.\n  //\n  // The important thing is that the master does very little,\n  // increasing our resilience to unexpected errors.\n\n  cluster.fork();\n  cluster.fork();\n\n  cluster.on('disconnect', (worker) => {\n    console.error('disconnect!');\n    cluster.fork();\n  });\n\n} else {\n  // the worker\n  //\n  // This is where we put our bugs!\n\n  const domain = require('domain');\n\n  // See the cluster documentation for more details about using\n  // worker processes to serve requests. How it works, caveats, etc.\n\n  const server = require('http').createServer((req, res) => {\n    const d = domain.create();\n    d.on('error', (er) => {\n      console.error(`error ${er.stack}`);\n\n      // We're in dangerous territory!\n      // By definition, something unexpected occurred,\n      // which we probably didn't want.\n      // Anything can happen now! Be very careful!\n\n      try {\n        // Make sure we close down within 30 seconds\n        const killtimer = setTimeout(() => {\n          process.exit(1);\n        }, 30000);\n        // But don't keep the process open just for that!\n        killtimer.unref();\n\n        // Stop taking new requests.\n        server.close();\n\n        // Let the master know we're dead. This will trigger a\n        // 'disconnect' in the cluster master, and then it will fork\n        // a new worker.\n        cluster.worker.disconnect();\n\n        // Try to send an error to the request that triggered the problem\n        res.statusCode = 500;\n        res.setHeader('content-type', 'text/plain');\n        res.end('Oops, there was a problem!\\n');\n      } catch (er2) {\n        // Oh well, not much we can do at this point.\n        console.error(`Error sending 500! ${er2.stack}`);\n      }\n    });\n\n    // Because req and res were created before this domain existed,\n    // we need to explicitly add them.\n    // See the explanation of implicit vs explicit binding below.\n    d.add(req);\n    d.add(res);\n\n    // Now run the handler function in the domain.\n    d.run(() => {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part is not important. Just an example routing thing.\n// Put fancy application logic here.\nfunction handleRequest(req, res) {\n  switch (req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(() => {\n        // Whoops!\n        flerb.bark();\n      }, timeout);\n      break;\n    default:\n      res.end('ok');\n  }\n}\n
      " + }, + { + "textRaw": "Additions to `Error` objects", + "name": "Additions to `Error` objects", + "type": "misc", + "desc": "

      Any time an Error object is routed through a domain, a few extra fields\nare added to it.

      \n
        \n
      • error.domain The domain that first handled the error.
      • \n
      • error.domainEmitter The event emitter that emitted an 'error' event\nwith the error object.
      • \n
      • error.domainBound The callback function which was bound to the\ndomain, and passed an error as its first argument.
      • \n
      • error.domainThrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
      • \n
      " + }, + { + "textRaw": "Implicit binding", + "name": "Implicit binding", + "type": "misc", + "desc": "

      If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.

      \n

      Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open(), or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.

      \n

      In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.

      \n

      To nest Domain objects as children of a parent Domain they must be\nexplicitly added.

      \n

      Implicit binding routes thrown errors and 'error' events to the\nDomain's 'error' event, but does not register the EventEmitter on the\nDomain.\nImplicit binding only takes care of thrown errors and 'error' events.

      " + }, + { + "textRaw": "Explicit binding", + "name": "Explicit binding", + "type": "misc", + "desc": "

      Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.

      \n

      For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.

      \n

      That is possible via explicit binding.

      \n
      // Create a top-level domain for the server\nconst domain = require('domain');\nconst http = require('http');\nconst serverDomain = domain.create();\n\nserverDomain.run(() => {\n  // Server is created in the scope of serverDomain\n  http.createServer((req, res) => {\n    // Req and res are also created in the scope of serverDomain\n    // however, we'd prefer to have a separate domain for each request.\n    // create it first thing, and add req and res to it.\n    const reqd = domain.create();\n    reqd.add(req);\n    reqd.add(res);\n    reqd.on('error', (er) => {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er2) {\n        console.error('Error sending 500', er2, req.url);\n      }\n    });\n  }).listen(1337);\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`domain.create()`", + "type": "method", + "name": "create", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Domain}", + "name": "return", + "type": "Domain" + }, + "params": [] + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: `Domain`", + "type": "class", + "name": "Domain", + "desc": "\n

      The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.

      \n

      To handle the errors that it catches, listen to its 'error' event.

      ", + "properties": [ + { + "textRaw": "`members` {Array}", + "type": "Array", + "name": "members", + "desc": "

      An array of timers and event emitters that have been explicitly added\nto the domain.

      " + } + ], + "methods": [ + { + "textRaw": "`domain.add(emitter)`", + "type": "method", + "name": "add", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be added to the domain", + "name": "emitter", + "type": "EventEmitter|Timer", + "desc": "emitter or timer to be added to the domain" + } + ] + } + ], + "desc": "

      Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an 'error' event, it\nwill be routed to the domain's 'error' event, just like with implicit\nbinding.

      \n

      This also works with timers that are returned from setInterval() and\nsetTimeout(). If their callback function throws, it will be caught by\nthe domain 'error' handler.

      \n

      If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.

      " + }, + { + "textRaw": "`domain.bind(callback)`", + "type": "method", + "name": "bind", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The bound function", + "name": "return", + "type": "Function", + "desc": "The bound function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's 'error' event.

      \n
      const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind((er, data) => {\n    // If this throws, it will also be passed to the domain.\n    return cb(er, data ? JSON.parse(data) : null);\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n
      " + }, + { + "textRaw": "`domain.enter()`", + "type": "method", + "name": "enter", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The enter() method is plumbing used by the run(), bind(), and\nintercept() methods to set the active domain. It sets domain.active and\nprocess.domain to the domain, and implicitly pushes the domain onto the domain\nstack managed by the domain module (see domain.exit() for details on the\ndomain stack). The call to enter() delimits the beginning of a chain of\nasynchronous calls and I/O operations bound to a domain.

      \n

      Calling enter() changes only the active domain, and does not alter the domain\nitself. enter() and exit() can be called an arbitrary number of times on a\nsingle domain.

      " + }, + { + "textRaw": "`domain.exit()`", + "type": "method", + "name": "exit", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The exit() method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit() delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.

      \n

      If there are multiple, nested domains bound to the current execution context,\nexit() will exit any domains nested within this domain.

      \n

      Calling exit() changes only the active domain, and does not alter the domain\nitself. enter() and exit() can be called an arbitrary number of times on a\nsingle domain.

      " + }, + { + "textRaw": "`domain.intercept(callback)`", + "type": "method", + "name": "intercept", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The intercepted function", + "name": "return", + "type": "Function", + "desc": "The intercepted function" + }, + "params": [ + { + "textRaw": "`callback` {Function} The callback function", + "name": "callback", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.

      \n

      In this way, the common if (err) return callback(err); pattern can be replaced\nwith a single error handler in a single place.

      \n
      const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept((data) => {\n    // Note, the first argument is never passed to the\n    // callback since it is assumed to be the 'Error' argument\n    // and thus intercepted by the domain.\n\n    // If this throws, it will also be passed to the domain\n    // so the error-handling logic can be moved to the 'error'\n    // event on the domain instead of being repeated throughout\n    // the program.\n    return cb(null, JSON.parse(data));\n  }));\n}\n\nd.on('error', (er) => {\n  // An error occurred somewhere. If we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n
      " + }, + { + "textRaw": "`domain.remove(emitter)`", + "type": "method", + "name": "remove", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be removed from the domain", + "name": "emitter", + "type": "EventEmitter|Timer", + "desc": "emitter or timer to be removed from the domain" + } + ] + } + ], + "desc": "

      The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.

      " + }, + { + "textRaw": "`domain.run(fn[, ...args])`", + "type": "method", + "name": "run", + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context. Optionally, arguments can be passed to\nthe function.

      \n

      This is the most basic way to use a domain.

      \n
      const domain = require('domain');\nconst fs = require('fs');\nconst d = domain.create();\nd.on('error', (er) => {\n  console.error('Caught error!', er);\n});\nd.run(() => {\n  process.nextTick(() => {\n    setTimeout(() => { // Simulating some various async stuff\n      fs.open('non-existent file', 'r', (er, fd) => {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});\n
      \n

      In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Domains and promises", + "name": "domains_and_promises", + "desc": "

      As of Node.js 8.0.0, the handlers of promises are run inside the domain in\nwhich the call to .then() or .catch() itself was made:

      \n
      const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then((v) => {\n    // running in d2\n  });\n});\n
      \n

      A callback may be bound to a specific domain using domain.bind(callback):

      \n
      const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n  p = Promise.resolve(42);\n});\n\nd2.run(() => {\n  p.then(p.domain.bind((v) => {\n    // running in d1\n  }));\n});\n
      \n

      Domains will not interfere with the error handling mechanisms for\npromises. In other words, no 'error' event will be emitted for unhandled\nPromise rejections.

      ", + "type": "module", + "displayName": "Domains and promises" + } + ], + "type": "module", + "displayName": "Domain" + } + ] +} \ No newline at end of file diff --git a/doc/api/embedding.html b/doc/api/embedding.html new file mode 100644 index 0000000000000000000000000000000000000000..c7296f303040fb09daade78a4d2b2464b5850224 --- /dev/null +++ b/doc/api/embedding.html @@ -0,0 +1,341 @@ + + + + + + + C++ Embedder API | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      C++ Embedder API#

      + +

      Node.js provides a number of C++ APIs that can be used to execute JavaScript +in a Node.js environment from other C++ software.

      +

      The documentation for these APIs can be found in src/node.h in the Node.js +source tree. In addition to the APIs exposed by Node.js, some required concepts +are provided by the V8 embedder API.

      +

      Because using Node.js as an embedded library is different from writing code +that is executed by Node.js, breaking changes do not follow typical Node.js +deprecation policy and may occur on each semver-major release without prior +warning.

      +

      Example embedding application#

      +

      The following sections will provide an overview over how to use these APIs +to create an application from scratch that will perform the equivalent of +node -e <code>, i.e. that will take a piece of JavaScript and run it in +a Node.js-specific environment.

      +

      The full code can be found in the Node.js source tree.

      +

      Setting up per-process state#

      +

      Node.js requires some per-process state management in order to run:

      +
        +
      • Arguments parsing for Node.js CLI options,
      • +
      • V8 per-process requirements, such as a v8::Platform instance.
      • +
      +

      The following example shows how these can be set up. Some class names are from +the node and v8 C++ namespaces, respectively.

      +
      int main(int argc, char** argv) {
      +  argv = uv_setup_args(argc, argv);
      +  std::vector<std::string> args(argv, argv + argc);
      +  std::vector<std::string> exec_args;
      +  std::vector<std::string> errors;
      +  // Parse Node.js CLI options, and print any errors that have occurred while
      +  // trying to parse them.
      +  int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);
      +  for (const std::string& error : errors)
      +    fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
      +  if (exit_code != 0) {
      +    return exit_code;
      +  }
      +
      +  // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way
      +  // to create a v8::Platform instance that Node.js can use when creating
      +  // Worker threads. When no `MultiIsolatePlatform` instance is present,
      +  // Worker threads are disabled.
      +  std::unique_ptr<MultiIsolatePlatform> platform =
      +      MultiIsolatePlatform::Create(4);
      +  V8::InitializePlatform(platform.get());
      +  V8::Initialize();
      +
      +  // See below for the contents of this function.
      +  int ret = RunNodeInstance(platform.get(), args, exec_args);
      +
      +  V8::Dispose();
      +  V8::ShutdownPlatform();
      +  return ret;
      +}
      +

      Per-instance state#

      +

      Node.js has a concept of a “Node.js instanceâ€, that is commonly being referred +to as node::Environment. Each node::Environment is associated with:

      +
        +
      • Exactly one v8::Isolate, i.e. one JS Engine instance,
      • +
      • Exactly one uv_loop_t, i.e. one event loop, and
      • +
      • A number of v8::Contexts, but exactly one main v8::Context.
      • +
      • One node::IsolateData instance that contains information that could be +shared by multiple node::Environments that use the same v8::Isolate. +Currently, no testing if performed for this scenario.
      • +
      +

      In order to set up a v8::Isolate, an v8::ArrayBuffer::Allocator needs +to be provided. One possible choice is the default Node.js allocator, which +can be created through node::ArrayBufferAllocator::Create(). Using the Node.js +allocator allows minor performance optimizations when addons use the Node.js +C++ Buffer API, and is required in order to track ArrayBuffer memory in +process.memoryUsage().

      +

      Additionally, each v8::Isolate that is used for a Node.js instance needs to +be registered and unregistered with the MultiIsolatePlatform instance, if one +is being used, in order for the platform to know which event loop to use +for tasks scheduled by the v8::Isolate.

      +

      The node::NewIsolate() helper function creates a v8::Isolate, +sets it up with some Node.js-specific hooks (e.g. the Node.js error handler), +and registers it with the platform automatically.

      +
      int RunNodeInstance(MultiIsolatePlatform* platform,
      +                    const std::vector<std::string>& args,
      +                    const std::vector<std::string>& exec_args) {
      +  int exit_code = 0;
      +  // Set up a libuv event loop.
      +  uv_loop_t loop;
      +  int ret = uv_loop_init(&loop);
      +  if (ret != 0) {
      +    fprintf(stderr, "%s: Failed to initialize loop: %s\n",
      +            args[0].c_str(),
      +            uv_err_name(ret));
      +    return 1;
      +  }
      +
      +  std::shared_ptr<ArrayBufferAllocator> allocator =
      +      ArrayBufferAllocator::Create();
      +
      +  Isolate* isolate = NewIsolate(allocator, &loop, platform);
      +  if (isolate == nullptr) {
      +    fprintf(stderr, "%s: Failed to initialize V8 Isolate\n", args[0].c_str());
      +    return 1;
      +  }
      +
      +  {
      +    Locker locker(isolate);
      +    Isolate::Scope isolate_scope(isolate);
      +
      +    // Create a node::IsolateData instance that will later be released using
      +    // node::FreeIsolateData().
      +    std::unique_ptr<IsolateData, decltype(&node::FreeIsolateData)> isolate_data(
      +        node::CreateIsolateData(isolate, &loop, platform, allocator.get()),
      +        node::FreeIsolateData);
      +
      +    // Set up a new v8::Context.
      +    HandleScope handle_scope(isolate);
      +    Local<Context> context = node::NewContext(isolate);
      +    if (context.IsEmpty()) {
      +      fprintf(stderr, "%s: Failed to initialize V8 Context\n", args[0].c_str());
      +      return 1;
      +    }
      +
      +    // The v8::Context needs to be entered when node::CreateEnvironment() and
      +    // node::LoadEnvironment() are being called.
      +    Context::Scope context_scope(context);
      +
      +    // Create a node::Environment instance that will later be released using
      +    // node::FreeEnvironment().
      +    std::unique_ptr<Environment, decltype(&node::FreeEnvironment)> env(
      +        node::CreateEnvironment(isolate_data.get(), context, args, exec_args),
      +        node::FreeEnvironment);
      +
      +    // Set up the Node.js instance for execution, and run code inside of it.
      +    // There is also a variant that takes a callback and provides it with
      +    // the `require` and `process` objects, so that it can manually compile
      +    // and run scripts as needed.
      +    // The `require` function inside this script does *not* access the file
      +    // system, and can only load built-in Node.js modules.
      +    // `module.createRequire()` is being used to create one that is able to
      +    // load files from the disk, and uses the standard CommonJS file loader
      +    // instead of the internal-only `require` function.
      +    MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(
      +        env.get(),
      +        "const publicRequire ="
      +        "  require('module').createRequire(process.cwd() + '/');"
      +        "globalThis.require = publicRequire;"
      +        "require('vm').runInThisContext(process.argv[1]);");
      +
      +    if (loadenv_ret.IsEmpty())  // There has been a JS exception.
      +      return 1;
      +
      +    {
      +      // SealHandleScope protects against handle leaks from callbacks.
      +      SealHandleScope seal(isolate);
      +      bool more;
      +      do {
      +        uv_run(&loop, UV_RUN_DEFAULT);
      +
      +        // V8 tasks on background threads may end up scheduling new tasks in the
      +        // foreground, which in turn can keep the event loop going. For example,
      +        // WebAssembly.compile() may do so.
      +        platform->DrainTasks(isolate);
      +
      +        // If there are new tasks, continue.
      +        more = uv_loop_alive(&loop);
      +        if (more) continue;
      +
      +        // node::EmitBeforeExit() is used to emit the 'beforeExit' event on
      +        // the `process` object.
      +        node::EmitBeforeExit(env.get());
      +
      +        // 'beforeExit' can also schedule new work that keeps the event loop
      +        // running.
      +        more = uv_loop_alive(&loop);
      +      } while (more == true);
      +    }
      +
      +    // node::EmitExit() returns the current exit code.
      +    exit_code = node::EmitExit(env.get());
      +
      +    // node::Stop() can be used to explicitly stop the event loop and keep
      +    // further JavaScript from running. It can be called from any thread,
      +    // and will act like worker.terminate() if called from another thread.
      +    node::Stop(env.get());
      +  }
      +
      +  // Unregister the Isolate with the platform and add a listener that is called
      +  // when the Platform is done cleaning up any state it had associated with
      +  // the Isolate.
      +  bool platform_finished = false;
      +  platform->AddIsolateFinishedCallback(isolate, [](void* data) {
      +    *static_cast<bool*>(data) = true;
      +  }, &platform_finished);
      +  platform->UnregisterIsolate(isolate);
      +  isolate->Dispose();
      +
      +  // Wait until the platform has cleaned up all relevant resources.
      +  while (!platform_finished)
      +    uv_run(&loop, UV_RUN_ONCE);
      +  int err = uv_loop_close(&loop);
      +  assert(err == 0);
      +
      +  return exit_code;
      +}
      + +
      +
      +
      + + diff --git a/doc/api/embedding.json b/doc/api/embedding.json new file mode 100644 index 0000000000000000000000000000000000000000..c96833f8feab6a31ae78f01067b2027630649cbc --- /dev/null +++ b/doc/api/embedding.json @@ -0,0 +1,30 @@ +{ + "type": "module", + "source": "doc/api/embedding.md", + "modules": [ + { + "textRaw": "C++ Embedder API", + "name": "c++_embedder_api", + "introduced_in": "v12.19.0", + "desc": "

      Node.js provides a number of C++ APIs that can be used to execute JavaScript\nin a Node.js environment from other C++ software.

      \n

      The documentation for these APIs can be found in src/node.h in the Node.js\nsource tree. In addition to the APIs exposed by Node.js, some required concepts\nare provided by the V8 embedder API.

      \n

      Because using Node.js as an embedded library is different from writing code\nthat is executed by Node.js, breaking changes do not follow typical Node.js\ndeprecation policy and may occur on each semver-major release without prior\nwarning.

      \n

      Example embedding application

      \n

      The following sections will provide an overview over how to use these APIs\nto create an application from scratch that will perform the equivalent of\nnode -e <code>, i.e. that will take a piece of JavaScript and run it in\na Node.js-specific environment.

      \n

      The full code can be found in the Node.js source tree.

      ", + "modules": [ + { + "textRaw": "Setting up per-process state", + "name": "setting_up_per-process_state", + "desc": "

      Node.js requires some per-process state management in order to run:

      \n
        \n
      • Arguments parsing for Node.js CLI options,
      • \n
      • V8 per-process requirements, such as a v8::Platform instance.
      • \n
      \n

      The following example shows how these can be set up. Some class names are from\nthe node and v8 C++ namespaces, respectively.

      \n
      int main(int argc, char** argv) {\n  argv = uv_setup_args(argc, argv);\n  std::vector<std::string> args(argv, argv + argc);\n  std::vector<std::string> exec_args;\n  std::vector<std::string> errors;\n  // Parse Node.js CLI options, and print any errors that have occurred while\n  // trying to parse them.\n  int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);\n  for (const std::string& error : errors)\n    fprintf(stderr, \"%s: %s\\n\", args[0].c_str(), error.c_str());\n  if (exit_code != 0) {\n    return exit_code;\n  }\n\n  // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way\n  // to create a v8::Platform instance that Node.js can use when creating\n  // Worker threads. When no `MultiIsolatePlatform` instance is present,\n  // Worker threads are disabled.\n  std::unique_ptr<MultiIsolatePlatform> platform =\n      MultiIsolatePlatform::Create(4);\n  V8::InitializePlatform(platform.get());\n  V8::Initialize();\n\n  // See below for the contents of this function.\n  int ret = RunNodeInstance(platform.get(), args, exec_args);\n\n  V8::Dispose();\n  V8::ShutdownPlatform();\n  return ret;\n}\n
      ", + "type": "module", + "displayName": "Setting up per-process state" + }, + { + "textRaw": "Per-instance state", + "name": "per-instance_state", + "desc": "

      Node.js has a concept of a “Node.js instanceâ€, that is commonly being referred\nto as node::Environment. Each node::Environment is associated with:

      \n
        \n
      • Exactly one v8::Isolate, i.e. one JS Engine instance,
      • \n
      • Exactly one uv_loop_t, i.e. one event loop, and
      • \n
      • A number of v8::Contexts, but exactly one main v8::Context.
      • \n
      • One node::IsolateData instance that contains information that could be\nshared by multiple node::Environments that use the same v8::Isolate.\nCurrently, no testing if performed for this scenario.
      • \n
      \n

      In order to set up a v8::Isolate, an v8::ArrayBuffer::Allocator needs\nto be provided. One possible choice is the default Node.js allocator, which\ncan be created through node::ArrayBufferAllocator::Create(). Using the Node.js\nallocator allows minor performance optimizations when addons use the Node.js\nC++ Buffer API, and is required in order to track ArrayBuffer memory in\nprocess.memoryUsage().

      \n

      Additionally, each v8::Isolate that is used for a Node.js instance needs to\nbe registered and unregistered with the MultiIsolatePlatform instance, if one\nis being used, in order for the platform to know which event loop to use\nfor tasks scheduled by the v8::Isolate.

      \n

      The node::NewIsolate() helper function creates a v8::Isolate,\nsets it up with some Node.js-specific hooks (e.g. the Node.js error handler),\nand registers it with the platform automatically.

      \n
      int RunNodeInstance(MultiIsolatePlatform* platform,\n                    const std::vector<std::string>& args,\n                    const std::vector<std::string>& exec_args) {\n  int exit_code = 0;\n  // Set up a libuv event loop.\n  uv_loop_t loop;\n  int ret = uv_loop_init(&loop);\n  if (ret != 0) {\n    fprintf(stderr, \"%s: Failed to initialize loop: %s\\n\",\n            args[0].c_str(),\n            uv_err_name(ret));\n    return 1;\n  }\n\n  std::shared_ptr<ArrayBufferAllocator> allocator =\n      ArrayBufferAllocator::Create();\n\n  Isolate* isolate = NewIsolate(allocator, &loop, platform);\n  if (isolate == nullptr) {\n    fprintf(stderr, \"%s: Failed to initialize V8 Isolate\\n\", args[0].c_str());\n    return 1;\n  }\n\n  {\n    Locker locker(isolate);\n    Isolate::Scope isolate_scope(isolate);\n\n    // Create a node::IsolateData instance that will later be released using\n    // node::FreeIsolateData().\n    std::unique_ptr<IsolateData, decltype(&node::FreeIsolateData)> isolate_data(\n        node::CreateIsolateData(isolate, &loop, platform, allocator.get()),\n        node::FreeIsolateData);\n\n    // Set up a new v8::Context.\n    HandleScope handle_scope(isolate);\n    Local<Context> context = node::NewContext(isolate);\n    if (context.IsEmpty()) {\n      fprintf(stderr, \"%s: Failed to initialize V8 Context\\n\", args[0].c_str());\n      return 1;\n    }\n\n    // The v8::Context needs to be entered when node::CreateEnvironment() and\n    // node::LoadEnvironment() are being called.\n    Context::Scope context_scope(context);\n\n    // Create a node::Environment instance that will later be released using\n    // node::FreeEnvironment().\n    std::unique_ptr<Environment, decltype(&node::FreeEnvironment)> env(\n        node::CreateEnvironment(isolate_data.get(), context, args, exec_args),\n        node::FreeEnvironment);\n\n    // Set up the Node.js instance for execution, and run code inside of it.\n    // There is also a variant that takes a callback and provides it with\n    // the `require` and `process` objects, so that it can manually compile\n    // and run scripts as needed.\n    // The `require` function inside this script does *not* access the file\n    // system, and can only load built-in Node.js modules.\n    // `module.createRequire()` is being used to create one that is able to\n    // load files from the disk, and uses the standard CommonJS file loader\n    // instead of the internal-only `require` function.\n    MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(\n        env.get(),\n        \"const publicRequire =\"\n        \"  require('module').createRequire(process.cwd() + '/');\"\n        \"globalThis.require = publicRequire;\"\n        \"require('vm').runInThisContext(process.argv[1]);\");\n\n    if (loadenv_ret.IsEmpty())  // There has been a JS exception.\n      return 1;\n\n    {\n      // SealHandleScope protects against handle leaks from callbacks.\n      SealHandleScope seal(isolate);\n      bool more;\n      do {\n        uv_run(&loop, UV_RUN_DEFAULT);\n\n        // V8 tasks on background threads may end up scheduling new tasks in the\n        // foreground, which in turn can keep the event loop going. For example,\n        // WebAssembly.compile() may do so.\n        platform->DrainTasks(isolate);\n\n        // If there are new tasks, continue.\n        more = uv_loop_alive(&loop);\n        if (more) continue;\n\n        // node::EmitBeforeExit() is used to emit the 'beforeExit' event on\n        // the `process` object.\n        node::EmitBeforeExit(env.get());\n\n        // 'beforeExit' can also schedule new work that keeps the event loop\n        // running.\n        more = uv_loop_alive(&loop);\n      } while (more == true);\n    }\n\n    // node::EmitExit() returns the current exit code.\n    exit_code = node::EmitExit(env.get());\n\n    // node::Stop() can be used to explicitly stop the event loop and keep\n    // further JavaScript from running. It can be called from any thread,\n    // and will act like worker.terminate() if called from another thread.\n    node::Stop(env.get());\n  }\n\n  // Unregister the Isolate with the platform and add a listener that is called\n  // when the Platform is done cleaning up any state it had associated with\n  // the Isolate.\n  bool platform_finished = false;\n  platform->AddIsolateFinishedCallback(isolate, [](void* data) {\n    *static_cast<bool*>(data) = true;\n  }, &platform_finished);\n  platform->UnregisterIsolate(isolate);\n  isolate->Dispose();\n\n  // Wait until the platform has cleaned up all relevant resources.\n  while (!platform_finished)\n    uv_run(&loop, UV_RUN_ONCE);\n  int err = uv_loop_close(&loop);\n  assert(err == 0);\n\n  return exit_code;\n}\n
      ", + "type": "module", + "displayName": "Per-instance state" + } + ], + "type": "module", + "displayName": "C++ Embedder API" + } + ] +} \ No newline at end of file diff --git a/doc/api/errors.html b/doc/api/errors.html new file mode 100644 index 0000000000000000000000000000000000000000..b89052dfeaba1f4128fe12f04e710505e0912c22 --- /dev/null +++ b/doc/api/errors.html @@ -0,0 +1,2247 @@ + + + + + + + Errors | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Errors#

      + + +

      Applications running in Node.js will generally experience four categories of +errors:

      +
        +
      • Standard JavaScript errors such as <EvalError>, <SyntaxError>, <RangeError>, +<ReferenceError>, <TypeError>, and <URIError>.
      • +
      • System errors triggered by underlying operating system constraints such +as attempting to open a file that does not exist or attempting to send data +over a closed socket.
      • +
      • User-specified errors triggered by application code.
      • +
      • AssertionErrors are a special class of error that can be triggered when +Node.js detects an exceptional logic violation that should never occur. These +are raised typically by the assert module.
      • +
      +

      All JavaScript and system errors raised by Node.js inherit from, or are +instances of, the standard JavaScript <Error> class and are guaranteed +to provide at least the properties available on that class.

      +

      Error propagation and interception#

      + +

      Node.js supports several mechanisms for propagating and handling errors that +occur while an application is running. How these errors are reported and +handled depends entirely on the type of Error and the style of the API that is +called.

      +

      All JavaScript errors are handled as exceptions that immediately generate +and throw an error using the standard JavaScript throw mechanism. These +are handled using the try…catch construct provided by the +JavaScript language.

      +
      // Throws with a ReferenceError because z is not defined.
      +try {
      +  const m = 1;
      +  const n = m + z;
      +} catch (err) {
      +  // Handle the error here.
      +}
      +

      Any use of the JavaScript throw mechanism will raise an exception that +must be handled using try…catch or the Node.js process will exit +immediately.

      +

      With few exceptions, Synchronous APIs (any blocking method that does not +accept a callback function, such as fs.readFileSync), will use throw +to report errors.

      +

      Errors that occur within Asynchronous APIs may be reported in multiple ways:

      +
        +
      • Most asynchronous methods that accept a callback function will accept an +Error object passed as the first argument to that function. If that first +argument is not null and is an instance of Error, then an error occurred +that should be handled.
      • +
      + +
      const fs = require('fs');
      +fs.readFile('a file that does not exist', (err, data) => {
      +  if (err) {
      +    console.error('There was an error reading the file!', err);
      +    return;
      +  }
      +  // Otherwise handle the data
      +});
      +
        +
      • +

        When an asynchronous method is called on an object that is an +EventEmitter, errors can be routed to that object's 'error' event.

        +
        const net = require('net');
        +const connection = net.connect('localhost');
        +
        +// Adding an 'error' event handler to a stream:
        +connection.on('error', (err) => {
        +  // If the connection is reset by the server, or if it can't
        +  // connect at all, or on any sort of error encountered by
        +  // the connection, the error will be sent here.
        +  console.error(err);
        +});
        +
        +connection.pipe(process.stdout);
        +
      • +
      • +

        A handful of typically asynchronous methods in the Node.js API may still +use the throw mechanism to raise exceptions that must be handled using +try…catch. There is no comprehensive list of such methods; please +refer to the documentation of each method to determine the appropriate +error handling mechanism required.

        +
      • +
      +

      The use of the 'error' event mechanism is most common for stream-based +and event emitter-based APIs, which themselves represent a series of +asynchronous operations over time (as opposed to a single operation that may +pass or fail).

      +

      For all EventEmitter objects, if an 'error' event handler is not +provided, the error will be thrown, causing the Node.js process to report an +uncaught exception and crash unless either: The domain module is +used appropriately or a handler has been registered for the +'uncaughtException' event.

      +
      const EventEmitter = require('events');
      +const ee = new EventEmitter();
      +
      +setImmediate(() => {
      +  // This will crash the process because no 'error' event
      +  // handler has been added.
      +  ee.emit('error', new Error('This will crash'));
      +});
      +

      Errors generated in this way cannot be intercepted using try…catch as +they are thrown after the calling code has already exited.

      +

      Developers must refer to the documentation for each method to determine +exactly how errors raised by those methods are propagated.

      +

      Error-first callbacks#

      + +

      Most asynchronous methods exposed by the Node.js core API follow an idiomatic +pattern referred to as an error-first callback. With this pattern, a callback +function is passed to the method as an argument. When the operation either +completes or an error is raised, the callback function is called with the +Error object (if any) passed as the first argument. If no error was raised, +the first argument will be passed as null.

      +
      const fs = require('fs');
      +
      +function errorFirstCallback(err, data) {
      +  if (err) {
      +    console.error('There was an error', err);
      +    return;
      +  }
      +  console.log(data);
      +}
      +
      +fs.readFile('/some/file/that/does-not-exist', errorFirstCallback);
      +fs.readFile('/some/file/that/does-exist', errorFirstCallback);
      +

      The JavaScript try…catch mechanism cannot be used to intercept errors +generated by asynchronous APIs. A common mistake for beginners is to try to +use throw inside an error-first callback:

      +
      // THIS WILL NOT WORK:
      +const fs = require('fs');
      +
      +try {
      +  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
      +    // Mistaken assumption: throwing here...
      +    if (err) {
      +      throw err;
      +    }
      +  });
      +} catch (err) {
      +  // This will not catch the throw!
      +  console.error(err);
      +}
      +

      This will not work because the callback function passed to fs.readFile() is +called asynchronously. By the time the callback has been called, the +surrounding code, including the try…catch block, will have already exited. +Throwing an error inside the callback can crash the Node.js process in most +cases. If domains are enabled, or a handler has been registered with +process.on('uncaughtException'), such errors can be intercepted.

      +

      Class: Error#

      + +

      A generic JavaScript <Error> object that does not denote any specific +circumstance of why the error occurred. Error objects capture a "stack trace" +detailing the point in the code at which the Error was instantiated, and may +provide a text description of the error.

      +

      All errors generated by Node.js, including all system and JavaScript errors, +will either be instances of, or inherit from, the Error class.

      +

      new Error(message)#

      + +

      Creates a new Error object and sets the error.message property to the +provided text message. If an object is passed as message, the text message +is generated by calling message.toString(). The error.stack property will +represent the point in the code at which new Error() was called. Stack traces +are dependent on V8's stack trace API. Stack traces extend only to either +(a) the beginning of synchronous code execution, or (b) the number of frames +given by the property Error.stackTraceLimit, whichever is smaller.

      +

      Error.captureStackTrace(targetObject[, constructorOpt])#

      + +

      Creates a .stack property on targetObject, which when accessed returns +a string representing the location in the code at which +Error.captureStackTrace() was called.

      +
      const myObject = {};
      +Error.captureStackTrace(myObject);
      +myObject.stack;  // Similar to `new Error().stack`
      +

      The first line of the trace will be prefixed with +${myObject.name}: ${myObject.message}.

      +

      The optional constructorOpt argument accepts a function. If given, all frames +above constructorOpt, including constructorOpt, will be omitted from the +generated stack trace.

      +

      The constructorOpt argument is useful for hiding implementation +details of error generation from the user. For instance:

      +
      function MyError() {
      +  Error.captureStackTrace(this, MyError);
      +}
      +
      +// Without passing MyError to captureStackTrace, the MyError
      +// frame would show up in the .stack property. By passing
      +// the constructor, we omit that frame, and retain all frames below it.
      +new MyError().stack;
      +

      Error.stackTraceLimit#

      + +

      The Error.stackTraceLimit property specifies the number of stack frames +collected by a stack trace (whether generated by new Error().stack or +Error.captureStackTrace(obj)).

      +

      The default value is 10 but may be set to any valid JavaScript number. Changes +will affect any stack trace captured after the value has been changed.

      +

      If set to a non-number value, or set to a negative number, stack traces will +not capture any frames.

      +

      error.code#

      + +

      The error.code property is a string label that identifies the kind of error. +error.code is the most stable way to identify an error. It will only change +between major versions of Node.js. In contrast, error.message strings may +change between any versions of Node.js. See Node.js error codes for details +about specific codes.

      +

      error.message#

      + +

      The error.message property is the string description of the error as set by +calling new Error(message). The message passed to the constructor will also +appear in the first line of the stack trace of the Error, however changing +this property after the Error object is created may not change the first +line of the stack trace (for example, when error.stack is read before this +property is changed).

      +
      const err = new Error('The message');
      +console.error(err.message);
      +// Prints: The message
      +

      error.stack#

      + +

      The error.stack property is a string describing the point in the code at which +the Error was instantiated.

      +
      Error: Things keep happening!
      +   at /home/gbusey/file.js:525:2
      +   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
      +   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
      +   at increaseSynergy (/home/gbusey/actors.js:701:6)
      +

      The first line is formatted as <error class name>: <error message>, and +is followed by a series of stack frames (each line beginning with "at "). +Each frame describes a call site within the code that lead to the error being +generated. V8 attempts to display a name for each function (by variable name, +function name, or object method name), but occasionally it will not be able to +find a suitable name. If V8 cannot determine a name for the function, only +location information will be displayed for that frame. Otherwise, the +determined function name will be displayed with location information appended +in parentheses.

      +

      Frames are only generated for JavaScript functions. If, for example, execution +synchronously passes through a C++ addon function called cheetahify which +itself calls a JavaScript function, the frame representing the cheetahify call +will not be present in the stack traces:

      +
      const cheetahify = require('./native-binding.node');
      +
      +function makeFaster() {
      +  // `cheetahify()` *synchronously* calls speedy.
      +  cheetahify(function speedy() {
      +    throw new Error('oh no!');
      +  });
      +}
      +
      +makeFaster();
      +// will throw:
      +//   /home/gbusey/file.js:6
      +//       throw new Error('oh no!');
      +//           ^
      +//   Error: oh no!
      +//       at speedy (/home/gbusey/file.js:6:11)
      +//       at makeFaster (/home/gbusey/file.js:5:3)
      +//       at Object.<anonymous> (/home/gbusey/file.js:10:1)
      +//       at Module._compile (module.js:456:26)
      +//       at Object.Module._extensions..js (module.js:474:10)
      +//       at Module.load (module.js:356:32)
      +//       at Function.Module._load (module.js:312:12)
      +//       at Function.Module.runMain (module.js:497:10)
      +//       at startup (node.js:119:16)
      +//       at node.js:906:3
      +

      The location information will be one of:

      +
        +
      • native, if the frame represents a call internal to V8 (as in [].forEach).
      • +
      • plain-filename.js:line:column, if the frame represents a call internal +to Node.js.
      • +
      • /absolute/path/to/file.js:line:column, if the frame represents a call in +a user program, or its dependencies.
      • +
      +

      The string representing the stack trace is lazily generated when the +error.stack property is accessed.

      +

      The number of frames captured by the stack trace is bounded by the smaller of +Error.stackTraceLimit or the number of available frames on the current event +loop tick.

      +

      Class: AssertionError#

      + +

      Indicates the failure of an assertion. For details, see +Class: assert.AssertionError.

      +

      Class: RangeError#

      + +

      Indicates that a provided argument was not within the set or range of +acceptable values for a function; whether that is a numeric range, or +outside the set of options for a given function parameter.

      +
      require('net').connect(-1);
      +// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"
      +

      Node.js will generate and throw RangeError instances immediately as a form +of argument validation.

      +

      Class: ReferenceError#

      + +

      Indicates that an attempt is being made to access a variable that is not +defined. Such errors commonly indicate typos in code, or an otherwise broken +program.

      +

      While client code may generate and propagate these errors, in practice, only V8 +will do so.

      +
      doesNotExist;
      +// Throws ReferenceError, doesNotExist is not a variable in this program.
      +

      Unless an application is dynamically generating and running code, +ReferenceError instances indicate a bug in the code or its dependencies.

      +

      Class: SyntaxError#

      + +

      Indicates that a program is not valid JavaScript. These errors may only be +generated and propagated as a result of code evaluation. Code evaluation may +happen as a result of eval, Function, require, or vm. These errors +are almost always indicative of a broken program.

      +
      try {
      +  require('vm').runInThisContext('binary ! isNotOk');
      +} catch (err) {
      +  // 'err' will be a SyntaxError.
      +}
      +

      SyntaxError instances are unrecoverable in the context that created them – +they may only be caught by other contexts.

      +

      Class: SystemError#

      + +

      Node.js generates system errors when exceptions occur within its runtime +environment. These usually occur when an application violates an operating +system constraint. For example, a system error will occur if an application +attempts to read a file that does not exist.

      +
        +
      • address <string> If present, the address to which a network connection +failed
      • +
      • code <string> The string error code
      • +
      • dest <string> If present, the file path destination when reporting a file +system error
      • +
      • errno <number> | <string> The system-provided error number
      • +
      • info <Object> If present, extra details about the error condition
      • +
      • message <string> A system-provided human-readable description of the error
      • +
      • path <string> If present, the file path when reporting a file system error
      • +
      • port <number> If present, the network connection port that is not available
      • +
      • syscall <string> The name of the system call that triggered the error
      • +
      +

      error.address#

      + +

      If present, error.address is a string describing the address to which a +network connection failed.

      +

      error.code#

      + +

      The error.code property is a string representing the error code.

      +

      error.dest#

      + +

      If present, error.dest is the file path destination when reporting a file +system error.

      +

      error.errno#

      + +

      The error.errno property is a number or a string. If it is a number, it is a +negative value which corresponds to the error code defined in +libuv Error handling. See the libuv errno.h header file +(deps/uv/include/uv/errno.h in the Node.js source tree) for details. In case +of a string, it is the same as error.code.

      +

      error.info#

      + +

      If present, error.info is an object with details about the error condition.

      +

      error.message#

      + +

      error.message is a system-provided human-readable description of the error.

      +

      error.path#

      + +

      If present, error.path is a string containing a relevant invalid pathname.

      +

      error.port#

      + +

      If present, error.port is the network connection port that is not available.

      +

      error.syscall#

      + +

      The error.syscall property is a string describing the syscall that failed.

      +

      Common system errors#

      +

      This is a list of system errors commonly-encountered when writing a Node.js +program. For a comprehensive list, see the errno(3) man page.

      +
        +
      • +

        EACCES (Permission denied): An attempt was made to access a file in a way +forbidden by its file access permissions.

        +
      • +
      • +

        EADDRINUSE (Address already in use): An attempt to bind a server +(net, http, or https) to a local address failed due to +another server on the local system already occupying that address.

        +
      • +
      • +

        ECONNREFUSED (Connection refused): No connection could be made because the +target machine actively refused it. This usually results from trying to +connect to a service that is inactive on the foreign host.

        +
      • +
      • +

        ECONNRESET (Connection reset by peer): A connection was forcibly closed by +a peer. This normally results from a loss of the connection on the remote +socket due to a timeout or reboot. Commonly encountered via the http +and net modules.

        +
      • +
      • +

        EEXIST (File exists): An existing file was the target of an operation that +required that the target not exist.

        +
      • +
      • +

        EISDIR (Is a directory): An operation expected a file, but the given +pathname was a directory.

        +
      • +
      • +

        EMFILE (Too many open files in system): Maximum number of +file descriptors allowable on the system has been reached, and +requests for another descriptor cannot be fulfilled until at least one +has been closed. This is encountered when opening many files at once in +parallel, especially on systems (in particular, macOS) where there is a low +file descriptor limit for processes. To remedy a low limit, run +ulimit -n 2048 in the same shell that will run the Node.js process.

        +
      • +
      • +

        ENOENT (No such file or directory): Commonly raised by fs operations +to indicate that a component of the specified pathname does not exist. No +entity (file or directory) could be found by the given path.

        +
      • +
      • +

        ENOTDIR (Not a directory): A component of the given pathname existed, but +was not a directory as expected. Commonly raised by fs.readdir.

        +
      • +
      • +

        ENOTEMPTY (Directory not empty): A directory with entries was the target +of an operation that requires an empty directory, usually fs.unlink.

        +
      • +
      • +

        ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either +EAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

        +
      • +
      • +

        EPERM (Operation not permitted): An attempt was made to perform an +operation that requires elevated privileges.

        +
      • +
      • +

        EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is +no process to read the data. Commonly encountered at the net and +http layers, indicative that the remote side of the stream being +written to has been closed.

        +
      • +
      • +

        ETIMEDOUT (Operation timed out): A connect or send request failed because +the connected party did not properly respond after a period of time. Usually +encountered by http or net. Often a sign that a socket.end() +was not properly called.

        +
      • +
      +

      Class: TypeError#

      + +

      Indicates that a provided argument is not an allowable type. For example, +passing a function to a parameter which expects a string would be a TypeError.

      +
      require('url').parse(() => { });
      +// Throws TypeError, since it expected a string.
      +

      Node.js will generate and throw TypeError instances immediately as a form +of argument validation.

      +

      Exceptions vs. errors#

      + +

      A JavaScript exception is a value that is thrown as a result of an invalid +operation or as the target of a throw statement. While it is not required +that these values are instances of Error or classes which inherit from +Error, all exceptions thrown by Node.js or the JavaScript runtime will be +instances of Error.

      +

      Some exceptions are unrecoverable at the JavaScript layer. Such exceptions +will always cause the Node.js process to crash. Examples include assert() +checks or abort() calls in the C++ layer.

      +

      OpenSSL errors#

      +

      Errors originating in crypto or tls are of class Error, and in addition to +the standard .code and .message properties, may have some additional +OpenSSL-specific properties.

      +

      error.opensslErrorStack#

      +

      An array of errors that can give context to where in the OpenSSL library an +error originates from.

      +

      error.function#

      +

      The OpenSSL function the error originates in.

      +

      error.library#

      +

      The OpenSSL library the error originates in.

      +

      error.reason#

      +

      A human-readable string describing the reason for the error.

      +

      +

      Node.js error codes#

      +

      +

      ERR_AMBIGUOUS_ARGUMENT#

      +

      A function argument is being used in a way that suggests that the function +signature may be misunderstood. This is thrown by the assert module when the +message parameter in assert.throws(block, message) matches the error message +thrown by block because that usage suggests that the user believes message +is the expected message rather than the message the AssertionError will +display if block does not throw.

      +

      +

      ERR_ARG_NOT_ITERABLE#

      +

      An iterable argument (i.e. a value that works with for...of loops) was +required, but not provided to a Node.js API.

      +

      +

      ERR_ASSERTION#

      +

      A special type of error that can be triggered whenever Node.js detects an +exceptional logic violation that should never occur. These are raised typically +by the assert module.

      +

      +

      ERR_ASYNC_CALLBACK#

      +

      An attempt was made to register something that is not a function as an +AsyncHooks callback.

      +

      +

      ERR_ASYNC_TYPE#

      +

      The type of an asynchronous resource was invalid. Users are also able +to define their own types if using the public embedder API.

      +

      +

      ERR_BROTLI_COMPRESSION_FAILED#

      +

      Data passed to a Brotli stream was not successfully compressed.

      +

      +

      ERR_BROTLI_INVALID_PARAM#

      +

      An invalid parameter key was passed during construction of a Brotli stream.

      +

      +

      ERR_BUFFER_CONTEXT_NOT_AVAILABLE#

      +

      An attempt was made to create a Node.js Buffer instance from addon or embedder +code, while in a JS engine Context that is not associated with a Node.js +instance. The data passed to the Buffer method will have been released +by the time the method returns.

      +

      When encountering this error, a possible alternative to creating a Buffer +instance is to create a normal Uint8Array, which only differs in the +prototype of the resulting object. Uint8Arrays are generally accepted in all +Node.js core APIs where Buffers are; they are available in all Contexts.

      +

      +

      ERR_BUFFER_OUT_OF_BOUNDS#

      +

      An operation outside the bounds of a Buffer was attempted.

      +

      +

      ERR_BUFFER_TOO_LARGE#

      +

      An attempt has been made to create a Buffer larger than the maximum allowed +size.

      +

      +

      ERR_CANNOT_WATCH_SIGINT#

      +

      Node.js was unable to watch for the SIGINT signal.

      +

      +

      ERR_CHILD_CLOSED_BEFORE_REPLY#

      +

      A child process was closed before the parent received a reply.

      +

      +

      ERR_CHILD_PROCESS_IPC_REQUIRED#

      +

      Used when a child process is being forked without specifying an IPC channel.

      +

      +

      ERR_CHILD_PROCESS_STDIO_MAXBUFFER#

      +

      Used when the main process is trying to read data from the child process's +STDERR/STDOUT, and the data's length is longer than the maxBuffer option.

      +

      +

      ERR_CONSOLE_WRITABLE_STREAM#

      +

      Console was instantiated without stdout stream, or Console has a +non-writable stdout or stderr stream.

      +

      +

      ERR_CONSTRUCT_CALL_REQUIRED#

      +

      A constructor for a class was called without new.

      +

      +

      ERR_CONSTRUCT_CALL_INVALID#

      + +

      A class constructor was called that is not callable.

      +

      +

      ERR_CPU_USAGE#

      +

      The native call from process.cpuUsage could not be processed.

      +

      +

      ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED#

      +

      A client certificate engine was requested that is not supported by the version +of OpenSSL being used.

      +

      +

      ERR_CRYPTO_ECDH_INVALID_FORMAT#

      +

      An invalid value for the format argument was passed to the crypto.ECDH() +class getPublicKey() method.

      +

      +

      ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY#

      +

      An invalid value for the key argument has been passed to the +crypto.ECDH() class computeSecret() method. It means that the public +key lies outside of the elliptic curve.

      +

      +

      ERR_CRYPTO_ENGINE_UNKNOWN#

      +

      An invalid crypto engine identifier was passed to +require('crypto').setEngine().

      +

      +

      ERR_CRYPTO_FIPS_FORCED#

      +

      The --force-fips command-line argument was used but there was an attempt +to enable or disable FIPS mode in the crypto module.

      +

      +

      ERR_CRYPTO_FIPS_UNAVAILABLE#

      +

      An attempt was made to enable or disable FIPS mode, but FIPS mode was not +available.

      +

      +

      ERR_CRYPTO_HASH_FINALIZED#

      +

      hash.digest() was called multiple times. The hash.digest() method must +be called no more than one time per instance of a Hash object.

      +

      +

      ERR_CRYPTO_HASH_UPDATE_FAILED#

      +

      hash.update() failed for any reason. This should rarely, if ever, happen.

      +

      +

      ERR_CRYPTO_INCOMPATIBLE_KEY#

      +

      The given crypto keys are incompatible with the attempted operation.

      +

      +

      ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS#

      +

      The selected public or private key encoding is incompatible with other options.

      +

      +

      ERR_CRYPTO_INVALID_DIGEST#

      +

      An invalid crypto digest algorithm was specified.

      +

      +

      ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE#

      +

      The given crypto key object's type is invalid for the attempted operation.

      +

      +

      ERR_CRYPTO_INVALID_STATE#

      +

      A crypto method was used on an object that was in an invalid state. For +instance, calling cipher.getAuthTag() before calling cipher.final().

      +

      +

      ERR_CRYPTO_PBKDF2_ERROR#

      +

      The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide +more details and therefore neither does Node.js.

      +

      +

      ERR_CRYPTO_SCRYPT_INVALID_PARAMETER#

      +

      One or more crypto.scrypt() or crypto.scryptSync() parameters are +outside their legal range.

      +

      +

      ERR_CRYPTO_SCRYPT_NOT_SUPPORTED#

      +

      Node.js was compiled without scrypt support. Not possible with the official +release binaries but can happen with custom builds, including distro builds.

      +

      +

      ERR_CRYPTO_SIGN_KEY_REQUIRED#

      +

      A signing key was not provided to the sign.sign() method.

      +

      +

      ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH#

      +

      crypto.timingSafeEqual() was called with Buffer, TypedArray, or +DataView arguments of different lengths.

      +

      +

      ERR_CRYPTO_UNKNOWN_CIPHER#

      +

      An unknown cipher was specified.

      +

      +

      ERR_CRYPTO_UNKNOWN_DH_GROUP#

      +

      An unknown Diffie-Hellman group name was given. See +crypto.getDiffieHellman() for a list of valid group names.

      +

      +

      ERR_DIR_CLOSED#

      +

      The fs.Dir was previously closed.

      +

      +

      ERR_DIR_CONCURRENT_OPERATION#

      + +

      A synchronous read or close call was attempted on an fs.Dir which has +ongoing asynchronous operations.

      +

      +

      ERR_DNS_SET_SERVERS_FAILED#

      +

      c-ares failed to set the DNS server.

      +

      +

      ERR_DOMAIN_CALLBACK_NOT_AVAILABLE#

      +

      The domain module was not usable since it could not establish the required +error handling hooks, because +process.setUncaughtExceptionCaptureCallback() had been called at an +earlier point in time.

      +

      +

      ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE#

      +

      process.setUncaughtExceptionCaptureCallback() could not be called +because the domain module has been loaded at an earlier point in time.

      +

      The stack trace is extended to include the point in time at which the +domain module had been loaded.

      +

      +

      ERR_ENCODING_INVALID_ENCODED_DATA#

      +

      Data provided to TextDecoder() API was invalid according to the encoding +provided.

      +

      +

      ERR_ENCODING_NOT_SUPPORTED#

      +

      Encoding provided to TextDecoder() API was not one of the +WHATWG Supported Encodings.

      +

      +

      ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE#

      +

      The JS execution context is not associated with a Node.js environment. +This may occur when Node.js is used as an embedded library and some hooks +for the JS engine are not set up properly.

      +

      +

      ERR_FALSY_VALUE_REJECTION#

      +

      A Promise that was callbackified via util.callbackify() was rejected with a +falsy value.

      +

      +

      ERR_FS_FILE_TOO_LARGE#

      +

      An attempt has been made to read a file whose size is larger than the maximum +allowed size for a Buffer.

      +

      +

      ERR_FS_INVALID_SYMLINK_TYPE#

      +

      An invalid symlink type was passed to the fs.symlink() or +fs.symlinkSync() methods.

      +

      +

      ERR_HTTP_HEADERS_SENT#

      +

      An attempt was made to add more headers after the headers had already been sent.

      +

      +

      ERR_HTTP_INVALID_HEADER_VALUE#

      +

      An invalid HTTP header value was specified.

      +

      +

      ERR_HTTP_INVALID_STATUS_CODE#

      +

      Status code was outside the regular status code range (100-999).

      +

      +

      ERR_HTTP_TRAILER_INVALID#

      +

      The Trailer header was set even though the transfer encoding does not support +that.

      +

      +

      ERR_HTTP2_ALTSVC_INVALID_ORIGIN#

      +

      HTTP/2 ALTSVC frames require a valid origin.

      +

      +

      ERR_HTTP2_ALTSVC_LENGTH#

      +

      HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

      +

      +

      ERR_HTTP2_CONNECT_AUTHORITY#

      +

      For HTTP/2 requests using the CONNECT method, the :authority pseudo-header +is required.

      +

      +

      ERR_HTTP2_CONNECT_PATH#

      +

      For HTTP/2 requests using the CONNECT method, the :path pseudo-header is +forbidden.

      +

      +

      ERR_HTTP2_CONNECT_SCHEME#

      +

      For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is +forbidden.

      +

      +

      ERR_HTTP2_ERROR#

      +

      A non-specific HTTP/2 error has occurred.

      +

      +

      ERR_HTTP2_GOAWAY_SESSION#

      +

      New HTTP/2 Streams may not be opened after the Http2Session has received a +GOAWAY frame from the connected peer.

      +

      +

      ERR_HTTP2_HEADERS_AFTER_RESPOND#

      +

      An additional headers was specified after an HTTP/2 response was initiated.

      +

      +

      ERR_HTTP2_HEADERS_SENT#

      +

      An attempt was made to send multiple response headers.

      +

      +

      ERR_HTTP2_HEADER_SINGLE_VALUE#

      +

      Multiple values were provided for an HTTP/2 header field that was required to +have only a single value.

      +

      +

      ERR_HTTP2_INFO_STATUS_NOT_ALLOWED#

      +

      Informational HTTP status codes (1xx) may not be set as the response status +code on HTTP/2 responses.

      +

      +

      ERR_HTTP2_INVALID_CONNECTION_HEADERS#

      +

      HTTP/1 connection specific headers are forbidden to be used in HTTP/2 +requests and responses.

      +

      +

      ERR_HTTP2_INVALID_HEADER_VALUE#

      +

      An invalid HTTP/2 header value was specified.

      +

      +

      ERR_HTTP2_INVALID_INFO_STATUS#

      +

      An invalid HTTP informational status code has been specified. Informational +status codes must be an integer between 100 and 199 (inclusive).

      +

      +

      ERR_HTTP2_INVALID_ORIGIN#

      +

      HTTP/2 ORIGIN frames require a valid origin.

      +

      +

      ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH#

      +

      Input Buffer and Uint8Array instances passed to the +http2.getUnpackedSettings() API must have a length that is a multiple of +six.

      +

      +

      ERR_HTTP2_INVALID_PSEUDOHEADER#

      +

      Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme, +and :method) may be used.

      +

      +

      ERR_HTTP2_INVALID_SESSION#

      +

      An action was performed on an Http2Session object that had already been +destroyed.

      +

      +

      ERR_HTTP2_INVALID_SETTING_VALUE#

      +

      An invalid value has been specified for an HTTP/2 setting.

      +

      +

      ERR_HTTP2_INVALID_STREAM#

      +

      An operation was performed on a stream that had already been destroyed.

      +

      +

      ERR_HTTP2_MAX_PENDING_SETTINGS_ACK#

      +

      Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is +required to send an acknowledgment that it has received and applied the new +SETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may +be sent at any given time. This error code is used when that limit has been +reached.

      +

      +

      ERR_HTTP2_NESTED_PUSH#

      +

      An attempt was made to initiate a new push stream from within a push stream. +Nested push streams are not permitted.

      +

      +

      ERR_HTTP2_NO_SOCKET_MANIPULATION#

      +

      An attempt was made to directly manipulate (read, write, pause, resume, etc.) a +socket attached to an Http2Session.

      +

      +

      ERR_HTTP2_ORIGIN_LENGTH#

      +

      HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

      +

      +

      ERR_HTTP2_OUT_OF_STREAMS#

      +

      The number of streams created on a single HTTP/2 session reached the maximum +limit.

      +

      +

      ERR_HTTP2_PAYLOAD_FORBIDDEN#

      +

      A message payload was specified for an HTTP response code for which a payload is +forbidden.

      +

      +

      ERR_HTTP2_PING_CANCEL#

      +

      An HTTP/2 ping was canceled.

      +

      +

      ERR_HTTP2_PING_LENGTH#

      +

      HTTP/2 ping payloads must be exactly 8 bytes in length.

      +

      +

      ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED#

      +

      An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header +key names that begin with the : prefix.

      +

      +

      ERR_HTTP2_PUSH_DISABLED#

      +

      An attempt was made to create a push stream, which had been disabled by the +client.

      +

      +

      ERR_HTTP2_SEND_FILE#

      +

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to +send a directory.

      +

      +

      ERR_HTTP2_SEND_FILE_NOSEEK#

      +

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to +send something other than a regular file, but offset or length options were +provided.

      +

      +

      ERR_HTTP2_SESSION_ERROR#

      +

      The Http2Session closed with a non-zero error code.

      +

      +

      ERR_HTTP2_SETTINGS_CANCEL#

      +

      The Http2Session settings canceled.

      +

      +

      ERR_HTTP2_SOCKET_BOUND#

      +

      An attempt was made to connect a Http2Session object to a net.Socket or +tls.TLSSocket that had already been bound to another Http2Session object.

      +

      +

      ERR_HTTP2_SOCKET_UNBOUND#

      +

      An attempt was made to use the socket property of an Http2Session that +has already been closed.

      +

      +

      ERR_HTTP2_STATUS_101#

      +

      Use of the 101 Informational status code is forbidden in HTTP/2.

      +

      +

      ERR_HTTP2_STATUS_INVALID#

      +

      An invalid HTTP status code has been specified. Status codes must be an integer +between 100 and 599 (inclusive).

      +

      +

      ERR_HTTP2_STREAM_CANCEL#

      +

      An Http2Stream was destroyed before any data was transmitted to the connected +peer.

      +

      +

      ERR_HTTP2_STREAM_ERROR#

      +

      A non-zero error code was been specified in an RST_STREAM frame.

      +

      +

      ERR_HTTP2_STREAM_SELF_DEPENDENCY#

      +

      When setting the priority for an HTTP/2 stream, the stream may be marked as +a dependency for a parent stream. This error code is used when an attempt is +made to mark a stream and dependent of itself.

      +

      +

      ERR_HTTP2_TRAILERS_ALREADY_SENT#

      +

      Trailing headers have already been sent on the Http2Stream.

      +

      +

      ERR_HTTP2_TRAILERS_NOT_READY#

      +

      The http2stream.sendTrailers() method cannot be called until after the +'wantTrailers' event is emitted on an Http2Stream object. The +'wantTrailers' event will only be emitted if the waitForTrailers option +is set for the Http2Stream.

      +

      +

      ERR_HTTP2_UNSUPPORTED_PROTOCOL#

      +

      http2.connect() was passed a URL that uses any protocol other than http: or +https:.

      +

      +

      ERR_INTERNAL_ASSERTION#

      +

      There was a bug in Node.js or incorrect usage of Node.js internals. +To fix the error, open an issue at https://github.com/nodejs/node/issues.

      +

      +

      ERR_INCOMPATIBLE_OPTION_PAIR#

      +

      An option pair is incompatible with each other and cannot be used at the same +time.

      +

      +

      ERR_INPUT_TYPE_NOT_ALLOWED#

      +

      Stability: 1 - Experimental

      +

      The --input-type flag was used to attempt to execute a file. This flag can +only be used with input via --eval, --print or STDIN.

      +

      +

      ERR_INSPECTOR_ALREADY_ACTIVATED#

      +

      While using the inspector module, an attempt was made to activate the +inspector when it already started to listen on a port. Use inspector.close() +before activating it on a different address.

      +

      +

      ERR_INSPECTOR_ALREADY_CONNECTED#

      +

      While using the inspector module, an attempt was made to connect when the +inspector was already connected.

      +

      +

      ERR_INSPECTOR_CLOSED#

      +

      While using the inspector module, an attempt was made to use the inspector +after the session had already closed.

      +

      +

      ERR_INSPECTOR_COMMAND#

      +

      An error occurred while issuing a command via the inspector module.

      +

      +

      ERR_INSPECTOR_NOT_ACTIVE#

      +

      The inspector is not active when inspector.waitForDebugger() is called.

      +

      +

      ERR_INSPECTOR_NOT_AVAILABLE#

      +

      The inspector module is not available for use.

      +

      +

      ERR_INSPECTOR_NOT_CONNECTED#

      +

      While using the inspector module, an attempt was made to use the inspector +before it was connected.

      +

      +

      ERR_INSPECTOR_NOT_WORKER#

      +

      An API was called on the main thread that can only be used from +the worker thread.

      +

      +

      ERR_INVALID_ADDRESS_FAMILY#

      +

      The provided address family is not understood by the Node.js API.

      +

      +

      ERR_INVALID_ARG_TYPE#

      +

      An argument of the wrong type was passed to a Node.js API.

      +

      +

      ERR_INVALID_ARG_VALUE#

      +

      An invalid or unsupported value was passed for a given argument.

      +

      +

      ERR_INVALID_ASYNC_ID#

      +

      An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id +less than -1 should never happen.

      +

      +

      ERR_INVALID_BUFFER_SIZE#

      +

      A swap was performed on a Buffer but its size was not compatible with the +operation.

      +

      +

      ERR_INVALID_CALLBACK#

      +

      A callback function was required but was not been provided to a Node.js API.

      +

      +

      ERR_INVALID_CHAR#

      +

      Invalid characters were detected in headers.

      +

      +

      ERR_INVALID_CURSOR_POS#

      +

      A cursor on a given stream cannot be moved to a specified row without a +specified column.

      +

      +

      ERR_INVALID_FD#

      +

      A file descriptor ('fd') was not valid (e.g. it was a negative value).

      +

      +

      ERR_INVALID_FD_TYPE#

      +

      A file descriptor ('fd') type was not valid.

      +

      +

      ERR_INVALID_FILE_URL_HOST#

      +

      A Node.js API that consumes file: URLs (such as certain functions in the +fs module) encountered a file URL with an incompatible host. This +situation can only occur on Unix-like systems where only localhost or an empty +host is supported.

      +

      +

      ERR_INVALID_FILE_URL_PATH#

      +

      A Node.js API that consumes file: URLs (such as certain functions in the +fs module) encountered a file URL with an incompatible path. The exact +semantics for determining whether a path can be used is platform-dependent.

      +

      +

      ERR_INVALID_HANDLE_TYPE#

      +

      An attempt was made to send an unsupported "handle" over an IPC communication +channel to a child process. See subprocess.send() and process.send() +for more information.

      +

      +

      ERR_INVALID_HTTP_TOKEN#

      +

      An invalid HTTP token was supplied.

      +

      +

      ERR_INVALID_IP_ADDRESS#

      +

      An IP address is not valid.

      +

      +

      ERR_INVALID_MODULE_SPECIFIER#

      +

      The imported module string is an invalid URL, package name, or package subpath +specifier.

      +

      +

      ERR_INVALID_OPT_VALUE#

      +

      An invalid or unexpected value was passed in an options object.

      +

      +

      ERR_INVALID_OPT_VALUE_ENCODING#

      +

      An invalid or unknown file encoding was passed.

      +

      +

      ERR_INVALID_PACKAGE_CONFIG#

      +

      An invalid package.json file was found which failed parsing.

      +

      +

      ERR_INVALID_PACKAGE_TARGET#

      +

      The package.json "exports" field contains an invalid target mapping +value for the attempted module resolution.

      +

      +

      ERR_INVALID_PERFORMANCE_MARK#

      +

      While using the Performance Timing API (perf_hooks), a performance mark is +invalid.

      +

      +

      ERR_INVALID_PROTOCOL#

      +

      An invalid options.protocol was passed to http.request().

      +

      +

      ERR_INVALID_REPL_EVAL_CONFIG#

      +

      Both breakEvalOnSigint and eval options were set in the REPL config, +which is not supported.

      +

      +

      ERR_INVALID_REPL_INPUT#

      +

      The input may not be used in the REPL. All prohibited inputs are +documented in the REPL's documentation.

      +

      +

      ERR_INVALID_RETURN_PROPERTY#

      +

      Thrown in case a function option does not provide a valid value for one of its +returned object properties on execution.

      +

      +

      ERR_INVALID_RETURN_PROPERTY_VALUE#

      +

      Thrown in case a function option does not provide an expected value +type for one of its returned object properties on execution.

      +

      +

      ERR_INVALID_RETURN_VALUE#

      +

      Thrown in case a function option does not return an expected value +type on execution, such as when a function is expected to return a promise.

      +

      +

      ERR_INVALID_SYNC_FORK_INPUT#

      +

      A Buffer, TypedArray, DataView or string was provided as stdio input to +an asynchronous fork. See the documentation for the child_process module +for more information.

      +

      +

      ERR_INVALID_THIS#

      +

      A Node.js API function was called with an incompatible this value.

      +
      const urlSearchParams = new URLSearchParams('foo=bar&baz=new');
      +
      +const buf = Buffer.alloc(1);
      +urlSearchParams.has.call(buf, 'foo');
      +// Throws a TypeError with code 'ERR_INVALID_THIS'
      +

      +

      ERR_INVALID_TRANSFER_OBJECT#

      +

      An invalid transfer object was passed to postMessage().

      +

      +

      ERR_INVALID_TUPLE#

      +

      An element in the iterable provided to the WHATWG +URLSearchParams constructor did not +represent a [name, value] tuple – that is, if an element is not iterable, or +does not consist of exactly two elements.

      +

      +

      ERR_INVALID_URI#

      +

      An invalid URI was passed.

      +

      +

      ERR_INVALID_URL#

      +

      An invalid URL was passed to the WHATWG +URL constructor to be parsed. The thrown error object +typically has an additional property 'input' that contains the URL that failed +to parse.

      +

      +

      ERR_INVALID_URL_SCHEME#

      +

      An attempt was made to use a URL of an incompatible scheme (protocol) for a +specific purpose. It is only used in the WHATWG URL API support in the +fs module (which only accepts URLs with 'file' scheme), but may be used +in other Node.js APIs as well in the future.

      +

      +

      ERR_IPC_CHANNEL_CLOSED#

      +

      An attempt was made to use an IPC communication channel that was already closed.

      +

      +

      ERR_IPC_DISCONNECTED#

      +

      An attempt was made to disconnect an IPC communication channel that was already +disconnected. See the documentation for the child_process module +for more information.

      +

      +

      ERR_IPC_ONE_PIPE#

      +

      An attempt was made to create a child Node.js process using more than one IPC +communication channel. See the documentation for the child_process module +for more information.

      +

      +

      ERR_IPC_SYNC_FORK#

      +

      An attempt was made to open an IPC communication channel with a synchronously +forked Node.js process. See the documentation for the child_process module +for more information.

      +

      +

      ERR_MANIFEST_ASSERT_INTEGRITY#

      +

      An attempt was made to load a resource, but the resource did not match the +integrity defined by the policy manifest. See the documentation for policy +manifests for more information.

      +

      +

      ERR_MANIFEST_DEPENDENCY_MISSING#

      +

      An attempt was made to load a resource, but the resource was not listed as a +dependency from the location that attempted to load it. See the documentation +for policy manifests for more information.

      +

      +

      ERR_MANIFEST_INTEGRITY_MISMATCH#

      +

      An attempt was made to load a policy manifest, but the manifest had multiple +entries for a resource which did not match each other. Update the manifest +entries to match in order to resolve this error. See the documentation for +policy manifests for more information.

      +

      +

      ERR_MANIFEST_INVALID_RESOURCE_FIELD#

      +

      A policy manifest resource had an invalid value for one of its fields. Update +the manifest entry to match in order to resolve this error. See the +documentation for policy manifests for more information.

      +

      +

      ERR_MANIFEST_PARSE_POLICY#

      +

      An attempt was made to load a policy manifest, but the manifest was unable to +be parsed. See the documentation for policy manifests for more information.

      +

      +

      ERR_MANIFEST_TDZ#

      +

      An attempt was made to read from a policy manifest, but the manifest +initialization has not yet taken place. This is likely a bug in Node.js.

      +

      +

      ERR_MANIFEST_UNKNOWN_ONERROR#

      +

      A policy manifest was loaded, but had an unknown value for its "onerror" +behavior. See the documentation for policy manifests for more information.

      +

      +

      ERR_MEMORY_ALLOCATION_FAILED#

      +

      An attempt was made to allocate memory (usually in the C++ layer) but it +failed.

      +

      +

      ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE#

      + +

      A message posted to a MessagePort could not be deserialized in the target +vm Context. Not all Node.js objects can be successfully instantiated in +any context at this time, and attempting to transfer them using postMessage() +can fail on the receiving side in that case.

      +

      +

      ERR_METHOD_NOT_IMPLEMENTED#

      +

      A method is required but not implemented.

      +

      +

      ERR_MISSING_ARGS#

      +

      A required argument of a Node.js API was not passed. This is only used for +strict compliance with the API specification (which in some cases may accept +func(undefined) but not func()). In most native Node.js APIs, +func(undefined) and func() are treated identically, and the +ERR_INVALID_ARG_TYPE error code may be used instead.

      +

      +

      ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK#

      +

      Stability: 1 - Experimental

      +

      An ES Module loader hook specified format: 'dynamic' but did not provide +a dynamicInstantiate hook.

      +

      +

      ERR_MISSING_OPTION#

      +

      For APIs that accept options objects, some options might be mandatory. This code +is thrown if a required option is missing.

      +

      +

      ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST#

      +

      An object that needs to be explicitly listed in the transferList argument +was found in the object passed to a postMessage() call, but not provided in +the transferList for that call. Usually, this is a MessagePort.

      +

      +

      ERR_MISSING_PASSPHRASE#

      +

      An attempt was made to read an encrypted key without specifying a passphrase.

      +

      +

      ERR_MISSING_PLATFORM_FOR_WORKER#

      +

      The V8 platform used by this instance of Node.js does not support creating +Workers. This is caused by lack of embedder support for Workers. In particular, +this error will not occur with standard builds of Node.js.

      +

      +

      ERR_MODULE_NOT_FOUND#

      +

      Stability: 1 - Experimental

      +

      An ES Module could not be resolved.

      +

      +

      ERR_MULTIPLE_CALLBACK#

      +

      A callback was called more than once.

      +

      A callback is almost always meant to only be called once as the query +can either be fulfilled or rejected but not both at the same time. The latter +would be possible by calling a callback more than once.

      +

      +

      ERR_NAPI_CONS_FUNCTION#

      +

      While using N-API, a constructor passed was not a function.

      +

      +

      ERR_NAPI_INVALID_DATAVIEW_ARGS#

      +

      While calling napi_create_dataview(), a given offset was outside the bounds +of the dataview or offset + length was larger than a length of given buffer.

      +

      +

      ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT#

      +

      While calling napi_create_typedarray(), the provided offset was not a +multiple of the element size.

      +

      +

      ERR_NAPI_INVALID_TYPEDARRAY_LENGTH#

      +

      While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.

      +

      +

      ERR_NAPI_TSFN_CALL_JS#

      +

      An error occurred while invoking the JavaScript portion of the thread-safe +function.

      +

      +

      ERR_NAPI_TSFN_GET_UNDEFINED#

      +

      An error occurred while attempting to retrieve the JavaScript undefined +value.

      +

      +

      ERR_NAPI_TSFN_START_IDLE_LOOP#

      +

      On the main thread, values are removed from the queue associated with the +thread-safe function in an idle loop. This error indicates that an error +has occurred when attempting to start the loop.

      +

      +

      ERR_NAPI_TSFN_STOP_IDLE_LOOP#

      +

      Once no more items are left in the queue, the idle loop must be suspended. This +error indicates that the idle loop has failed to stop.

      +

      +

      ERR_NO_CRYPTO#

      +

      An attempt was made to use crypto features while Node.js was not compiled with +OpenSSL crypto support.

      +

      +

      ERR_NO_ICU#

      +

      An attempt was made to use features that require ICU, but Node.js was not +compiled with ICU support.

      +

      +

      ERR_NON_CONTEXT_AWARE_DISABLED#

      +

      A non-context-aware native addon was loaded in a process that disallows them.

      +

      +

      ERR_OUT_OF_RANGE#

      +

      A given value is out of the accepted range.

      +

      +

      ERR_PACKAGE_IMPORT_NOT_DEFINED#

      +

      The package.json "imports" field does not define the given internal +package specifier mapping.

      +

      +

      ERR_PACKAGE_PATH_NOT_EXPORTED#

      +

      The package.json "exports" field does not export the requested subpath. +Because exports are encapsulated, private internal modules that are not exported +cannot be imported through the package resolution, unless using an absolute URL.

      +

      +

      ERR_PROTO_ACCESS#

      +

      Accessing Object.prototype.__proto__ has been forbidden using +--disable-proto=throw. Object.getPrototypeOf and +Object.setPrototypeOf should be used to get and set the prototype of an +object.

      +

      +

      ERR_REQUIRE_ESM#

      +

      Stability: 1 - Experimental

      +

      An attempt was made to require() an ES Module.

      +

      +

      ERR_SCRIPT_EXECUTION_INTERRUPTED#

      +

      Script execution was interrupted by SIGINT (For example, +Ctrl+C was pressed.)

      +

      +

      ERR_SCRIPT_EXECUTION_TIMEOUT#

      +

      Script execution timed out, possibly due to bugs in the script being executed.

      +

      +

      ERR_SERVER_ALREADY_LISTEN#

      +

      The server.listen() method was called while a net.Server was already +listening. This applies to all instances of net.Server, including HTTP, HTTPS, +and HTTP/2 Server instances.

      +

      +

      ERR_SERVER_NOT_RUNNING#

      +

      The server.close() method was called when a net.Server was not +running. This applies to all instances of net.Server, including HTTP, HTTPS, +and HTTP/2 Server instances.

      +

      +

      ERR_SOCKET_ALREADY_BOUND#

      +

      An attempt was made to bind a socket that has already been bound.

      +

      +

      ERR_SOCKET_BAD_BUFFER_SIZE#

      +

      An invalid (negative) size was passed for either the recvBufferSize or +sendBufferSize options in dgram.createSocket().

      +

      +

      ERR_SOCKET_BAD_PORT#

      +

      An API function expecting a port >= 0 and < 65536 received an invalid value.

      +

      +

      ERR_SOCKET_BAD_TYPE#

      +

      An API function expecting a socket type (udp4 or udp6) received an invalid +value.

      +

      +

      ERR_SOCKET_BUFFER_SIZE#

      +

      While using dgram.createSocket(), the size of the receive or send Buffer +could not be determined.

      +

      +

      ERR_SOCKET_CANNOT_SEND#

      +

      Data could be sent on a socket.

      +

      +

      ERR_SOCKET_CLOSED#

      +

      An attempt was made to operate on an already closed socket.

      +

      +

      ERR_SOCKET_DGRAM_IS_CONNECTED#

      +

      A dgram.connect() call was made on an already connected socket.

      +

      +

      ERR_SOCKET_DGRAM_NOT_CONNECTED#

      +

      A dgram.disconnect() or dgram.remoteAddress() call was made on a +disconnected socket.

      +

      +

      ERR_SOCKET_DGRAM_NOT_RUNNING#

      +

      A call was made and the UDP subsystem was not running.

      +

      +

      ERR_SRI_PARSE#

      +

      A string was provided for a Subresource Integrity check, but was unable to be +parsed. Check the format of integrity attributes by looking at the +Subresource Integrity specification.

      +

      +

      ERR_STREAM_CANNOT_PIPE#

      +

      An attempt was made to call stream.pipe() on a Writable stream.

      +

      +

      ERR_STREAM_DESTROYED#

      +

      A stream method was called that cannot complete because the stream was +destroyed using stream.destroy().

      +

      +

      ERR_STREAM_NULL_VALUES#

      +

      An attempt was made to call stream.write() with a null chunk.

      +

      +

      ERR_STREAM_PREMATURE_CLOSE#

      +

      An error returned by stream.finished() and stream.pipeline(), when a stream +or a pipeline ends non gracefully with no explicit error.

      +

      +

      ERR_STREAM_PUSH_AFTER_EOF#

      +

      An attempt was made to call stream.push() after a null(EOF) had been +pushed to the stream.

      +

      +

      ERR_STREAM_UNSHIFT_AFTER_END_EVENT#

      +

      An attempt was made to call stream.unshift() after the 'end' event was +emitted.

      +

      +

      ERR_STREAM_WRAP#

      +

      Prevents an abort if a string decoder was set on the Socket or if the decoder +is in objectMode.

      +
      const Socket = require('net').Socket;
      +const instance = new Socket();
      +
      +instance.setEncoding('utf8');
      +

      +

      ERR_STREAM_WRITE_AFTER_END#

      +

      An attempt was made to call stream.write() after stream.end() has been +called.

      +

      +

      ERR_STRING_TOO_LONG#

      +

      An attempt has been made to create a string longer than the maximum allowed +length.

      +

      +

      ERR_SYNTHETIC#

      +

      An artificial error object used to capture the call stack for diagnostic +reports.

      +

      +

      ERR_SYSTEM_ERROR#

      +

      An unspecified or non-specific system error has occurred within the Node.js +process. The error object will have an err.info object property with +additional details.

      +

      +

      ERR_TLS_CERT_ALTNAME_INVALID#

      +

      While using TLS, the host name/IP of the peer did not match any of the +subjectAltNames in its certificate.

      +

      +

      ERR_TLS_DH_PARAM_SIZE#

      +

      While using TLS, the parameter offered for the Diffie-Hellman (DH) +key-agreement protocol is too small. By default, the key length must be greater +than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly +recommended to use 2048 bits or larger for stronger security.

      +

      +

      ERR_TLS_HANDSHAKE_TIMEOUT#

      +

      A TLS/SSL handshake timed out. In this case, the server must also abort the +connection.

      +

      +

      ERR_TLS_INVALID_CONTEXT#

      + +

      The context must be a SecureContext.

      +

      +

      ERR_TLS_INVALID_STATE#

      + +

      The TLS socket must be connected and securily established. Ensure the 'secure' +event is emitted before continuing.

      +

      +

      ERR_TLS_INVALID_PROTOCOL_METHOD#

      +

      The specified secureProtocol method is invalid. It is either unknown, or +disabled because it is insecure.

      +

      +

      ERR_TLS_INVALID_PROTOCOL_VERSION#

      +

      Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.

      +

      +

      ERR_TLS_PROTOCOL_VERSION_CONFLICT#

      +

      Attempting to set a TLS protocol minVersion or maxVersion conflicts with an +attempt to set the secureProtocol explicitly. Use one mechanism or the other.

      +

      +

      ERR_TLS_RENEGOTIATION_DISABLED#

      +

      An attempt was made to renegotiate TLS on a socket instance with TLS disabled.

      +

      +

      ERR_TLS_REQUIRED_SERVER_NAME#

      +

      While using TLS, the server.addContext() method was called without providing +a host name in the first parameter.

      +

      +

      ERR_TLS_SESSION_ATTACK#

      +

      An excessive amount of TLS renegotiations is detected, which is a potential +vector for denial-of-service attacks.

      +

      +

      ERR_TLS_SNI_FROM_SERVER#

      +

      An attempt was made to issue Server Name Indication from a TLS server-side +socket, which is only valid from a client.

      +

      +

      ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED#

      +

      Failed to set PSK identity hint. Hint may be too long.

      +

      +

      ERR_TRACE_EVENTS_CATEGORY_REQUIRED#

      +

      The trace_events.createTracing() method requires at least one trace event +category.

      +

      +

      ERR_TRACE_EVENTS_UNAVAILABLE#

      +

      The trace_events module could not be loaded because Node.js was compiled with +the --without-v8-platform flag.

      +

      +

      ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER#

      +

      A SharedArrayBuffer whose memory is not managed by the JavaScript engine +or by Node.js was encountered during serialization. Such a SharedArrayBuffer +cannot be serialized.

      +

      This can only happen when native addons create SharedArrayBuffers in +"externalized" mode, or put existing SharedArrayBuffer into externalized mode.

      +

      +

      ERR_TRANSFORM_ALREADY_TRANSFORMING#

      +

      A Transform stream finished while it was still transforming.

      +

      +

      ERR_TRANSFORM_WITH_LENGTH_0#

      +

      A Transform stream finished with data still in the write buffer.

      +

      +

      ERR_TTY_INIT_FAILED#

      +

      The initialization of a TTY failed due to a system error.

      +

      +

      ERR_UNAVAILABLE_DURING_EXIT#

      +

      Function was called within a process.on('exit') handler that shouldn't be +called within process.on('exit') handler.

      +

      +

      ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET#

      +

      process.setUncaughtExceptionCaptureCallback() was called twice, +without first resetting the callback to null.

      +

      This error is designed to prevent accidentally overwriting a callback registered +from another module.

      +

      +

      ERR_UNESCAPED_CHARACTERS#

      +

      A string that contained unescaped characters was received.

      +

      +

      ERR_UNHANDLED_ERROR#

      +

      An unhandled error occurred (for instance, when an 'error' event is emitted +by an EventEmitter but an 'error' handler is not registered).

      +

      +

      ERR_UNKNOWN_BUILTIN_MODULE#

      +

      Used to identify a specific kind of internal Node.js error that should not +typically be triggered by user code. Instances of this error point to an +internal bug within the Node.js binary itself.

      +

      +

      ERR_UNKNOWN_CREDENTIAL#

      +

      A Unix group or user identifier that does not exist was passed.

      +

      +

      ERR_UNKNOWN_ENCODING#

      +

      An invalid or unknown encoding option was passed to an API.

      +

      +

      ERR_UNKNOWN_FILE_EXTENSION#

      +

      Stability: 1 - Experimental

      +

      An attempt was made to load a module with an unknown or unsupported file +extension.

      +

      +

      ERR_UNKNOWN_MODULE_FORMAT#

      +

      Stability: 1 - Experimental

      +

      An attempt was made to load a module with an unknown or unsupported format.

      +

      +

      ERR_UNKNOWN_SIGNAL#

      +

      An invalid or unknown process signal was passed to an API expecting a valid +signal (such as subprocess.kill()).

      +

      +

      ERR_UNSUPPORTED_DIR_IMPORT#

      +

      import a directory URL is unsupported. Instead, +self-reference a package using its name and define a custom subpath in +the "exports" field of the package.json file.

      + +
      import './'; // unsupported
      +import './index.js'; // supported
      +import 'package-name'; // supported
      +

      +

      ERR_UNSUPPORTED_ESM_URL_SCHEME#

      +

      import with URL schemes other than file and data is unsupported.

      +

      +

      ERR_VALID_PERFORMANCE_ENTRY_TYPE#

      +

      While using the Performance Timing API (perf_hooks), no valid performance +entry types were found.

      +

      +

      ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING#

      +

      A dynamic import callback was not specified.

      +

      +

      ERR_VM_MODULE_ALREADY_LINKED#

      +

      The module attempted to be linked is not eligible for linking, because of one of +the following reasons:

      +
        +
      • It has already been linked (linkingStatus is 'linked')
      • +
      • It is being linked (linkingStatus is 'linking')
      • +
      • Linking has failed for this module (linkingStatus is 'errored')
      • +
      +

      +

      ERR_VM_MODULE_CACHED_DATA_REJECTED#

      +

      The cachedData option passed to a module constructor is invalid.

      +

      +

      ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA#

      +

      Cached data cannot be created for modules which have already been evaluated.

      +

      +

      ERR_VM_MODULE_DIFFERENT_CONTEXT#

      +

      The module being returned from the linker function is from a different context +than the parent module. Linked modules must share the same context.

      +

      +

      ERR_VM_MODULE_LINKING_ERRORED#

      +

      The linker function returned a module for which linking has failed.

      +

      +

      ERR_VM_MODULE_NOT_MODULE#

      +

      The fulfilled value of a linking promise is not a vm.Module object.

      +

      +

      ERR_VM_MODULE_STATUS#

      +

      The current module's status does not allow for this operation. The specific +meaning of the error depends on the specific function.

      +

      +

      ERR_WASI_ALREADY_STARTED#

      +

      The WASI instance has already started.

      +

      +

      ERR_WASI_NOT_STARTED#

      +

      The WASI instance has not been started.

      +

      +

      ERR_WORKER_INIT_FAILED#

      +

      The Worker initialization failed.

      +

      +

      ERR_WORKER_INVALID_EXEC_ARGV#

      +

      The execArgv option passed to the Worker constructor contains +invalid flags.

      +

      +

      ERR_WORKER_NOT_RUNNING#

      +

      An operation failed because the Worker instance is not currently running.

      +

      +

      ERR_WORKER_OUT_OF_MEMORY#

      +

      The Worker instance terminated because it reached its memory limit.

      +

      +

      ERR_WORKER_PATH#

      +

      The path for the main script of a worker is neither an absolute path +nor a relative path starting with ./ or ../.

      +

      +

      ERR_WORKER_UNSERIALIZABLE_ERROR#

      +

      All attempts at serializing an uncaught exception from a worker thread failed.

      +

      +

      ERR_WORKER_UNSUPPORTED_EXTENSION#

      +

      The pathname used for the main script of a worker has an +unknown file extension.

      +

      +

      ERR_WORKER_UNSUPPORTED_OPERATION#

      +

      The requested functionality is not supported in worker threads.

      +

      +

      ERR_ZLIB_INITIALIZATION_FAILED#

      +

      Creation of a zlib object failed due to incorrect configuration.

      +

      +

      HPE_HEADER_OVERFLOW#

      + +

      Too much HTTP header data was received. In order to protect against malicious or +malconfigured clients, if more than 8KB of HTTP header data is received then +HTTP parsing will abort without a request or response object being created, and +an Error with this code will be emitted.

      +

      +

      HPE_UNEXPECTED_CONTENT_LENGTH#

      +

      Server is sending both a Content-Length header and Transfer-Encoding: chunked.

      +

      Transfer-Encoding: chunked allows the server to maintain an HTTP persistent +connection for dynamically generated content. +In this case, the Content-Length HTTP header cannot be used.

      +

      Use Content-Length or Transfer-Encoding: chunked.

      +

      +

      MODULE_NOT_FOUND#

      + +

      A module file could not be resolved while attempting a require() or +import operation.

      +

      Legacy Node.js error codes#

      +

      Stability: 0 - Deprecated. These error codes are either inconsistent, or have +been removed.

      +

      +

      ERR_CANNOT_TRANSFER_OBJECT#

      + +

      The value passed to postMessage() contained an object that is not supported +for transferring.

      +

      +

      ERR_CLOSED_MESSAGE_PORT#

      + +

      There was an attempt to use a MessagePort instance in a closed +state, usually after .close() has been called.

      +

      +

      ERR_CRYPTO_HASH_DIGEST_NO_UTF16#

      + +

      The UTF-16 encoding was used with hash.digest(). While the +hash.digest() method does allow an encoding argument to be passed in, +causing the method to return a string rather than a Buffer, the UTF-16 +encoding (e.g. ucs or utf16le) is not supported.

      +

      +

      ERR_HTTP2_FRAME_ERROR#

      + +

      Used when a failure occurs sending an individual frame on the HTTP/2 +session.

      +

      +

      ERR_HTTP2_HEADERS_OBJECT#

      + +

      Used when an HTTP/2 Headers Object is expected.

      +

      +

      ERR_HTTP2_HEADER_REQUIRED#

      + +

      Used when a required header is missing in an HTTP/2 message.

      +

      +

      ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND#

      + +

      HTTP/2 informational headers must only be sent prior to calling the +Http2Stream.prototype.respond() method.

      +

      +

      ERR_HTTP2_STREAM_CLOSED#

      + +

      Used when an action has been performed on an HTTP/2 Stream that has already +been closed.

      +

      +

      ERR_HTTP_INVALID_CHAR#

      + +

      Used when an invalid character is found in an HTTP response status message +(reason phrase).

      +

      +

      ERR_INDEX_OUT_OF_RANGE#

      + +

      A given index was out of the accepted range (e.g. negative offsets).

      +

      +

      ERR_NAPI_CONS_PROTOTYPE_OBJECT#

      + +

      Used by the N-API when Constructor.prototype is not an object.

      +

      +

      ERR_NO_LONGER_SUPPORTED#

      +

      A Node.js API was called in an unsupported manner, such as +Buffer.write(string, encoding, offset[, length]).

      +

      +

      ERR_OUTOFMEMORY#

      + +

      Used generically to identify that an operation caused an out of memory +condition.

      +

      +

      ERR_PARSE_HISTORY_DATA#

      + +

      The repl module was unable to parse data from the REPL history file.

      +

      +

      ERR_STDERR_CLOSE#

      + +

      An attempt was made to close the process.stderr stream. By design, Node.js +does not allow stdout or stderr streams to be closed by user code.

      +

      +

      ERR_STDOUT_CLOSE#

      + +

      An attempt was made to close the process.stdout stream. By design, Node.js +does not allow stdout or stderr streams to be closed by user code.

      +

      +

      ERR_STREAM_READ_NOT_IMPLEMENTED#

      + +

      Used when an attempt is made to use a readable stream that has not implemented +readable._read().

      +

      +

      ERR_TLS_RENEGOTIATION_FAILED#

      + +

      Used when a TLS renegotiation request has failed in a non-specific way.

      +

      +

      ERR_UNKNOWN_BUILTIN_MODULE#

      + +

      The 'ERR_UNKNOWN_BUILTIN_MODULE' error code is used to identify a specific +kind of internal Node.js error that should not typically be triggered by user +code. Instances of this error point to an internal bug within the Node.js +binary itself.

      +

      +

      ERR_UNKNOWN_STDIN_TYPE#

      + +

      An attempt was made to launch a Node.js process with an unknown stdin file +type. This error is usually an indication of a bug within Node.js itself, +although it is possible for user code to trigger it.

      +

      +

      ERR_UNKNOWN_STREAM_TYPE#

      + +

      An attempt was made to launch a Node.js process with an unknown stdout or +stderr file type. This error is usually an indication of a bug within Node.js +itself, although it is possible for user code to trigger it.

      +

      +

      ERR_V8BREAKITERATOR#

      +

      The V8 BreakIterator API was used but the full ICU data set is not installed.

      +

      +

      ERR_VALUE_OUT_OF_RANGE#

      + +

      Used when a given value is out of the accepted range.

      +

      +

      ERR_VM_MODULE_NOT_LINKED#

      +

      The module must be successfully linked before instantiation.

      +

      +

      ERR_ZLIB_BINDING_CLOSED#

      + +

      Used when an attempt is made to use a zlib object after it has already been +closed.

      + +
      +
      +
      + + diff --git a/doc/api/errors.json b/doc/api/errors.json new file mode 100644 index 0000000000000000000000000000000000000000..638fb72620a53c345af4a06b00e78fccf507efe5 --- /dev/null +++ b/doc/api/errors.json @@ -0,0 +1,2671 @@ +{ + "type": "module", + "source": "doc/api/errors.md", + "introduced_in": "v4.0.0", + "classes": [ + { + "textRaw": "Class: `Error`", + "type": "class", + "name": "Error", + "desc": "

      A generic JavaScript <Error> object that does not denote any specific\ncircumstance of why the error occurred. Error objects capture a \"stack trace\"\ndetailing the point in the code at which the Error was instantiated, and may\nprovide a text description of the error.

      \n

      All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

      ", + "methods": [ + { + "textRaw": "`Error.captureStackTrace(targetObject[, constructorOpt])`", + "type": "method", + "name": "captureStackTrace", + "signatures": [ + { + "params": [ + { + "textRaw": "`targetObject` {Object}", + "name": "targetObject", + "type": "Object" + }, + { + "textRaw": "`constructorOpt` {Function}", + "name": "constructorOpt", + "type": "Function" + } + ] + } + ], + "desc": "

      Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

      \n
      const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack;  // Similar to `new Error().stack`\n
      \n

      The first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.

      \n

      The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

      \n

      The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:

      \n
      function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
      " + } + ], + "properties": [ + { + "textRaw": "`stackTraceLimit` {number}", + "type": "number", + "name": "stackTraceLimit", + "desc": "

      The Error.stackTraceLimit property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack or\nError.captureStackTrace(obj)).

      \n

      The default value is 10 but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.

      \n

      If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string label that identifies the kind of error.\nerror.code is the most stable way to identify an error. It will only change\nbetween major versions of Node.js. In contrast, error.message strings may\nchange between any versions of Node.js. See Node.js error codes for details\nabout specific codes.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      The error.message property is the string description of the error as set by\ncalling new Error(message). The message passed to the constructor will also\nappear in the first line of the stack trace of the Error, however changing\nthis property after the Error object is created may not change the first\nline of the stack trace (for example, when error.stack is read before this\nproperty is changed).

      \n
      const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
      " + }, + { + "textRaw": "`stack` {string}", + "type": "string", + "name": "stack", + "desc": "

      The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.

      \n
      Error: Things keep happening!\n   at /home/gbusey/file.js:525:2\n   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n   at increaseSynergy (/home/gbusey/actors.js:701:6)\n
      \n

      The first line is formatted as <error class name>: <error message>, and\nis followed by a series of stack frames (each line beginning with \"at \").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.

      \n

      Frames are only generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called cheetahify which\nitself calls a JavaScript function, the frame representing the cheetahify call\nwill not be present in the stack traces:

      \n
      const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n  // `cheetahify()` *synchronously* calls speedy.\n  cheetahify(function speedy() {\n    throw new Error('oh no!');\n  });\n}\n\nmakeFaster();\n// will throw:\n//   /home/gbusey/file.js:6\n//       throw new Error('oh no!');\n//           ^\n//   Error: oh no!\n//       at speedy (/home/gbusey/file.js:6:11)\n//       at makeFaster (/home/gbusey/file.js:5:3)\n//       at Object.<anonymous> (/home/gbusey/file.js:10:1)\n//       at Module._compile (module.js:456:26)\n//       at Object.Module._extensions..js (module.js:474:10)\n//       at Module.load (module.js:356:32)\n//       at Function.Module._load (module.js:312:12)\n//       at Function.Module.runMain (module.js:497:10)\n//       at startup (node.js:119:16)\n//       at node.js:906:3\n
      \n

      The location information will be one of:

      \n
        \n
      • native, if the frame represents a call internal to V8 (as in [].forEach).
      • \n
      • plain-filename.js:line:column, if the frame represents a call internal\nto Node.js.
      • \n
      • /absolute/path/to/file.js:line:column, if the frame represents a call in\na user program, or its dependencies.
      • \n
      \n

      The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

      \n

      The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit or the number of available frames on the current event\nloop tick.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ], + "desc": "

      Creates a new Error object and sets the error.message property to the\nprovided text message. If an object is passed as message, the text message\nis generated by calling message.toString(). The error.stack property will\nrepresent the point in the code at which new Error() was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit, whichever is smaller.

      " + } + ] + }, + { + "textRaw": "Class: `AssertionError`", + "type": "class", + "name": "AssertionError", + "desc": "\n

      Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.

      " + }, + { + "textRaw": "Class: `RangeError`", + "type": "class", + "name": "RangeError", + "desc": "\n

      Indicates that a provided argument was not within the set or range of\nacceptable values for a function; whether that is a numeric range, or\noutside the set of options for a given function parameter.

      \n
      require('net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n
      \n

      Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

      " + }, + { + "textRaw": "Class: `ReferenceError`", + "type": "class", + "name": "ReferenceError", + "desc": "\n

      Indicates that an attempt is being made to access a variable that is not\ndefined. Such errors commonly indicate typos in code, or an otherwise broken\nprogram.

      \n

      While client code may generate and propagate these errors, in practice, only V8\nwill do so.

      \n
      doesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n
      \n

      Unless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.

      " + }, + { + "textRaw": "Class: `SyntaxError`", + "type": "class", + "name": "SyntaxError", + "desc": "\n

      Indicates that a program is not valid JavaScript. These errors may only be\ngenerated and propagated as a result of code evaluation. Code evaluation may\nhappen as a result of eval, Function, require, or vm. These errors\nare almost always indicative of a broken program.

      \n
      try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n  // 'err' will be a SyntaxError.\n}\n
      \n

      SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

      " + }, + { + "textRaw": "Class: `SystemError`", + "type": "class", + "name": "SystemError", + "desc": "\n

      Node.js generates system errors when exceptions occur within its runtime\nenvironment. These usually occur when an application violates an operating\nsystem constraint. For example, a system error will occur if an application\nattempts to read a file that does not exist.

      \n
        \n
      • address <string> If present, the address to which a network connection\nfailed
      • \n
      • code <string> The string error code
      • \n
      • dest <string> If present, the file path destination when reporting a file\nsystem error
      • \n
      • errno <number> | <string> The system-provided error number
      • \n
      • info <Object> If present, extra details about the error condition
      • \n
      • message <string> A system-provided human-readable description of the error
      • \n
      • path <string> If present, the file path when reporting a file system error
      • \n
      • port <number> If present, the network connection port that is not available
      • \n
      • syscall <string> The name of the system call that triggered the error
      • \n
      ", + "properties": [ + { + "textRaw": "`address` {string}", + "type": "string", + "name": "address", + "desc": "

      If present, error.address is a string describing the address to which a\nnetwork connection failed.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string representing the error code.

      " + }, + { + "textRaw": "`dest` {string}", + "type": "string", + "name": "dest", + "desc": "

      If present, error.dest is the file path destination when reporting a file\nsystem error.

      " + }, + { + "textRaw": "`errno` {string|number}", + "type": "string|number", + "name": "errno", + "desc": "

      The error.errno property is a number or a string. If it is a number, it is a\nnegative value which corresponds to the error code defined in\nlibuv Error handling. See the libuv errno.h header file\n(deps/uv/include/uv/errno.h in the Node.js source tree) for details. In case\nof a string, it is the same as error.code.

      " + }, + { + "textRaw": "`info` {Object}", + "type": "Object", + "name": "info", + "desc": "

      If present, error.info is an object with details about the error condition.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      error.message is a system-provided human-readable description of the error.

      " + }, + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "desc": "

      If present, error.path is a string containing a relevant invalid pathname.

      " + }, + { + "textRaw": "`port` {number}", + "type": "number", + "name": "port", + "desc": "

      If present, error.port is the network connection port that is not available.

      " + }, + { + "textRaw": "`syscall` {string}", + "type": "string", + "name": "syscall", + "desc": "

      The error.syscall property is a string describing the syscall that failed.

      " + } + ], + "modules": [ + { + "textRaw": "Common system errors", + "name": "common_system_errors", + "desc": "

      This is a list of system errors commonly-encountered when writing a Node.js\nprogram. For a comprehensive list, see the errno(3) man page.

      \n
        \n
      • \n

        EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.

        \n
      • \n
      • \n

        EADDRINUSE (Address already in use): An attempt to bind a server\n(net, http, or https) to a local address failed due to\nanother server on the local system already occupying that address.

        \n
      • \n
      • \n

        ECONNREFUSED (Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.

        \n
      • \n
      • \n

        ECONNRESET (Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http\nand net modules.

        \n
      • \n
      • \n

        EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.

        \n
      • \n
      • \n

        EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.

        \n
      • \n
      • \n

        EMFILE (Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, macOS) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048 in the same shell that will run the Node.js process.

        \n
      • \n
      • \n

        ENOENT (No such file or directory): Commonly raised by fs operations\nto indicate that a component of the specified pathname does not exist. No\nentity (file or directory) could be found by the given path.

        \n
      • \n
      • \n

        ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.

        \n
      • \n
      • \n

        ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.

        \n
      • \n
      • \n

        ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

        \n
      • \n
      • \n

        EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.

        \n
      • \n
      • \n

        EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net and\nhttp layers, indicative that the remote side of the stream being\nwritten to has been closed.

        \n
      • \n
      • \n

        ETIMEDOUT (Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http or net. Often a sign that a socket.end()\nwas not properly called.

        \n
      • \n
      ", + "type": "module", + "displayName": "Common system errors" + } + ] + }, + { + "textRaw": "Class: `TypeError`", + "type": "class", + "name": "TypeError", + "desc": "\n

      Indicates that a provided argument is not an allowable type. For example,\npassing a function to a parameter which expects a string would be a TypeError.

      \n
      require('url').parse(() => { });\n// Throws TypeError, since it expected a string.\n
      \n

      Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

      " + } + ], + "miscs": [ + { + "textRaw": "Errors", + "name": "Errors", + "introduced_in": "v4.0.0", + "type": "misc", + "desc": "

      Applications running in Node.js will generally experience four categories of\nerrors:

      \n
        \n
      • Standard JavaScript errors such as <EvalError>, <SyntaxError>, <RangeError>,\n<ReferenceError>, <TypeError>, and <URIError>.
      • \n
      • System errors triggered by underlying operating system constraints such\nas attempting to open a file that does not exist or attempting to send data\nover a closed socket.
      • \n
      • User-specified errors triggered by application code.
      • \n
      • AssertionErrors are a special class of error that can be triggered when\nNode.js detects an exceptional logic violation that should never occur. These\nare raised typically by the assert module.
      • \n
      \n

      All JavaScript and system errors raised by Node.js inherit from, or are\ninstances of, the standard JavaScript <Error> class and are guaranteed\nto provide at least the properties available on that class.

      ", + "miscs": [ + { + "textRaw": "Error propagation and interception", + "name": "Error propagation and interception", + "type": "misc", + "desc": "

      Node.js supports several mechanisms for propagating and handling errors that\noccur while an application is running. How these errors are reported and\nhandled depends entirely on the type of Error and the style of the API that is\ncalled.

      \n

      All JavaScript errors are handled as exceptions that immediately generate\nand throw an error using the standard JavaScript throw mechanism. These\nare handled using the try…catch construct provided by the\nJavaScript language.

      \n
      // Throws with a ReferenceError because z is not defined.\ntry {\n  const m = 1;\n  const n = m + z;\n} catch (err) {\n  // Handle the error here.\n}\n
      \n

      Any use of the JavaScript throw mechanism will raise an exception that\nmust be handled using try…catch or the Node.js process will exit\nimmediately.

      \n

      With few exceptions, Synchronous APIs (any blocking method that does not\naccept a callback function, such as fs.readFileSync), will use throw\nto report errors.

      \n

      Errors that occur within Asynchronous APIs may be reported in multiple ways:

      \n
        \n
      • Most asynchronous methods that accept a callback function will accept an\nError object passed as the first argument to that function. If that first\nargument is not null and is an instance of Error, then an error occurred\nthat should be handled.
      • \n
      \n\n
      const fs = require('fs');\nfs.readFile('a file that does not exist', (err, data) => {\n  if (err) {\n    console.error('There was an error reading the file!', err);\n    return;\n  }\n  // Otherwise handle the data\n});\n
      \n
        \n
      • \n

        When an asynchronous method is called on an object that is an\nEventEmitter, errors can be routed to that object's 'error' event.

        \n
        const net = require('net');\nconst connection = net.connect('localhost');\n\n// Adding an 'error' event handler to a stream:\nconnection.on('error', (err) => {\n  // If the connection is reset by the server, or if it can't\n  // connect at all, or on any sort of error encountered by\n  // the connection, the error will be sent here.\n  console.error(err);\n});\n\nconnection.pipe(process.stdout);\n
        \n
      • \n
      • \n

        A handful of typically asynchronous methods in the Node.js API may still\nuse the throw mechanism to raise exceptions that must be handled using\ntry…catch. There is no comprehensive list of such methods; please\nrefer to the documentation of each method to determine the appropriate\nerror handling mechanism required.

        \n
      • \n
      \n

      The use of the 'error' event mechanism is most common for stream-based\nand event emitter-based APIs, which themselves represent a series of\nasynchronous operations over time (as opposed to a single operation that may\npass or fail).

      \n

      For all EventEmitter objects, if an 'error' event handler is not\nprovided, the error will be thrown, causing the Node.js process to report an\nuncaught exception and crash unless either: The domain module is\nused appropriately or a handler has been registered for the\n'uncaughtException' event.

      \n
      const EventEmitter = require('events');\nconst ee = new EventEmitter();\n\nsetImmediate(() => {\n  // This will crash the process because no 'error' event\n  // handler has been added.\n  ee.emit('error', new Error('This will crash'));\n});\n
      \n

      Errors generated in this way cannot be intercepted using try…catch as\nthey are thrown after the calling code has already exited.

      \n

      Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.

      ", + "miscs": [ + { + "textRaw": "Error-first callbacks", + "name": "Error-first callbacks", + "type": "misc", + "desc": "

      Most asynchronous methods exposed by the Node.js core API follow an idiomatic\npattern referred to as an error-first callback. With this pattern, a callback\nfunction is passed to the method as an argument. When the operation either\ncompletes or an error is raised, the callback function is called with the\nError object (if any) passed as the first argument. If no error was raised,\nthe first argument will be passed as null.

      \n
      const fs = require('fs');\n\nfunction errorFirstCallback(err, data) {\n  if (err) {\n    console.error('There was an error', err);\n    return;\n  }\n  console.log(data);\n}\n\nfs.readFile('/some/file/that/does-not-exist', errorFirstCallback);\nfs.readFile('/some/file/that/does-exist', errorFirstCallback);\n
      \n

      The JavaScript try…catch mechanism cannot be used to intercept errors\ngenerated by asynchronous APIs. A common mistake for beginners is to try to\nuse throw inside an error-first callback:

      \n
      // THIS WILL NOT WORK:\nconst fs = require('fs');\n\ntry {\n  fs.readFile('/some/file/that/does-not-exist', (err, data) => {\n    // Mistaken assumption: throwing here...\n    if (err) {\n      throw err;\n    }\n  });\n} catch (err) {\n  // This will not catch the throw!\n  console.error(err);\n}\n
      \n

      This will not work because the callback function passed to fs.readFile() is\ncalled asynchronously. By the time the callback has been called, the\nsurrounding code, including the try…catch block, will have already exited.\nThrowing an error inside the callback can crash the Node.js process in most\ncases. If domains are enabled, or a handler has been registered with\nprocess.on('uncaughtException'), such errors can be intercepted.

      " + } + ] + }, + { + "textRaw": "Exceptions vs. errors", + "name": "Exceptions vs. errors", + "type": "misc", + "desc": "

      A JavaScript exception is a value that is thrown as a result of an invalid\noperation or as the target of a throw statement. While it is not required\nthat these values are instances of Error or classes which inherit from\nError, all exceptions thrown by Node.js or the JavaScript runtime will be\ninstances of Error.

      \n

      Some exceptions are unrecoverable at the JavaScript layer. Such exceptions\nwill always cause the Node.js process to crash. Examples include assert()\nchecks or abort() calls in the C++ layer.

      " + }, + { + "textRaw": "OpenSSL errors", + "name": "openssl_errors", + "desc": "

      Errors originating in crypto or tls are of class Error, and in addition to\nthe standard .code and .message properties, may have some additional\nOpenSSL-specific properties.

      ", + "properties": [ + { + "textRaw": "`error.opensslErrorStack`", + "name": "opensslErrorStack", + "desc": "

      An array of errors that can give context to where in the OpenSSL library an\nerror originates from.

      " + }, + { + "textRaw": "`error.function`", + "name": "function", + "desc": "

      The OpenSSL function the error originates in.

      " + }, + { + "textRaw": "`error.library`", + "name": "library", + "desc": "

      The OpenSSL library the error originates in.

      " + }, + { + "textRaw": "`error.reason`", + "name": "reason", + "desc": "

      A human-readable string describing the reason for the error.

      \n

      " + } + ], + "type": "misc", + "displayName": "OpenSSL errors" + }, + { + "textRaw": "Node.js error codes", + "name": "node.js_error_codes", + "desc": "

      ", + "modules": [ + { + "textRaw": "`ERR_AMBIGUOUS_ARGUMENT`", + "name": "`err_ambiguous_argument`", + "desc": "

      A function argument is being used in a way that suggests that the function\nsignature may be misunderstood. This is thrown by the assert module when the\nmessage parameter in assert.throws(block, message) matches the error message\nthrown by block because that usage suggests that the user believes message\nis the expected message rather than the message the AssertionError will\ndisplay if block does not throw.

      \n

      ", + "type": "module", + "displayName": "`ERR_AMBIGUOUS_ARGUMENT`" + }, + { + "textRaw": "`ERR_ARG_NOT_ITERABLE`", + "name": "`err_arg_not_iterable`", + "desc": "

      An iterable argument (i.e. a value that works with for...of loops) was\nrequired, but not provided to a Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_ARG_NOT_ITERABLE`" + }, + { + "textRaw": "`ERR_ASSERTION`", + "name": "`err_assertion`", + "desc": "

      A special type of error that can be triggered whenever Node.js detects an\nexceptional logic violation that should never occur. These are raised typically\nby the assert module.

      \n

      ", + "type": "module", + "displayName": "`ERR_ASSERTION`" + }, + { + "textRaw": "`ERR_ASYNC_CALLBACK`", + "name": "`err_async_callback`", + "desc": "

      An attempt was made to register something that is not a function as an\nAsyncHooks callback.

      \n

      ", + "type": "module", + "displayName": "`ERR_ASYNC_CALLBACK`" + }, + { + "textRaw": "`ERR_ASYNC_TYPE`", + "name": "`err_async_type`", + "desc": "

      The type of an asynchronous resource was invalid. Users are also able\nto define their own types if using the public embedder API.

      \n

      ", + "type": "module", + "displayName": "`ERR_ASYNC_TYPE`" + }, + { + "textRaw": "`ERR_BROTLI_COMPRESSION_FAILED`", + "name": "`err_brotli_compression_failed`", + "desc": "

      Data passed to a Brotli stream was not successfully compressed.

      \n

      ", + "type": "module", + "displayName": "`ERR_BROTLI_COMPRESSION_FAILED`" + }, + { + "textRaw": "`ERR_BROTLI_INVALID_PARAM`", + "name": "`err_brotli_invalid_param`", + "desc": "

      An invalid parameter key was passed during construction of a Brotli stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_BROTLI_INVALID_PARAM`" + }, + { + "textRaw": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`", + "name": "`err_buffer_context_not_available`", + "desc": "

      An attempt was made to create a Node.js Buffer instance from addon or embedder\ncode, while in a JS engine Context that is not associated with a Node.js\ninstance. The data passed to the Buffer method will have been released\nby the time the method returns.

      \n

      When encountering this error, a possible alternative to creating a Buffer\ninstance is to create a normal Uint8Array, which only differs in the\nprototype of the resulting object. Uint8Arrays are generally accepted in all\nNode.js core APIs where Buffers are; they are available in all Contexts.

      \n

      ", + "type": "module", + "displayName": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_BUFFER_OUT_OF_BOUNDS`", + "name": "`err_buffer_out_of_bounds`", + "desc": "

      An operation outside the bounds of a Buffer was attempted.

      \n

      ", + "type": "module", + "displayName": "`ERR_BUFFER_OUT_OF_BOUNDS`" + }, + { + "textRaw": "`ERR_BUFFER_TOO_LARGE`", + "name": "`err_buffer_too_large`", + "desc": "

      An attempt has been made to create a Buffer larger than the maximum allowed\nsize.

      \n

      ", + "type": "module", + "displayName": "`ERR_BUFFER_TOO_LARGE`" + }, + { + "textRaw": "`ERR_CANNOT_WATCH_SIGINT`", + "name": "`err_cannot_watch_sigint`", + "desc": "

      Node.js was unable to watch for the SIGINT signal.

      \n

      ", + "type": "module", + "displayName": "`ERR_CANNOT_WATCH_SIGINT`" + }, + { + "textRaw": "`ERR_CHILD_CLOSED_BEFORE_REPLY`", + "name": "`err_child_closed_before_reply`", + "desc": "

      A child process was closed before the parent received a reply.

      \n

      ", + "type": "module", + "displayName": "`ERR_CHILD_CLOSED_BEFORE_REPLY`" + }, + { + "textRaw": "`ERR_CHILD_PROCESS_IPC_REQUIRED`", + "name": "`err_child_process_ipc_required`", + "desc": "

      Used when a child process is being forked without specifying an IPC channel.

      \n

      ", + "type": "module", + "displayName": "`ERR_CHILD_PROCESS_IPC_REQUIRED`" + }, + { + "textRaw": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`", + "name": "`err_child_process_stdio_maxbuffer`", + "desc": "

      Used when the main process is trying to read data from the child process's\nSTDERR/STDOUT, and the data's length is longer than the maxBuffer option.

      \n

      ", + "type": "module", + "displayName": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`" + }, + { + "textRaw": "`ERR_CONSOLE_WRITABLE_STREAM`", + "name": "`err_console_writable_stream`", + "desc": "

      Console was instantiated without stdout stream, or Console has a\nnon-writable stdout or stderr stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_CONSOLE_WRITABLE_STREAM`" + }, + { + "textRaw": "`ERR_CONSTRUCT_CALL_REQUIRED`", + "name": "`err_construct_call_required`", + "desc": "

      A constructor for a class was called without new.

      \n

      ", + "type": "module", + "displayName": "`ERR_CONSTRUCT_CALL_REQUIRED`" + }, + { + "textRaw": "`ERR_CONSTRUCT_CALL_INVALID`", + "name": "`err_construct_call_invalid`", + "desc": "\n

      A class constructor was called that is not callable.

      \n

      ", + "type": "module", + "displayName": "`ERR_CONSTRUCT_CALL_INVALID`" + }, + { + "textRaw": "`ERR_CPU_USAGE`", + "name": "`err_cpu_usage`", + "desc": "

      The native call from process.cpuUsage could not be processed.

      \n

      ", + "type": "module", + "displayName": "`ERR_CPU_USAGE`" + }, + { + "textRaw": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`", + "name": "`err_crypto_custom_engine_not_supported`", + "desc": "

      A client certificate engine was requested that is not supported by the version\nof OpenSSL being used.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`" + }, + { + "textRaw": "`ERR_CRYPTO_ECDH_INVALID_FORMAT`", + "name": "`err_crypto_ecdh_invalid_format`", + "desc": "

      An invalid value for the format argument was passed to the crypto.ECDH()\nclass getPublicKey() method.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_ECDH_INVALID_FORMAT`" + }, + { + "textRaw": "`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY`", + "name": "`err_crypto_ecdh_invalid_public_key`", + "desc": "

      An invalid value for the key argument has been passed to the\ncrypto.ECDH() class computeSecret() method. It means that the public\nkey lies outside of the elliptic curve.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY`" + }, + { + "textRaw": "`ERR_CRYPTO_ENGINE_UNKNOWN`", + "name": "`err_crypto_engine_unknown`", + "desc": "

      An invalid crypto engine identifier was passed to\nrequire('crypto').setEngine().

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_ENGINE_UNKNOWN`" + }, + { + "textRaw": "`ERR_CRYPTO_FIPS_FORCED`", + "name": "`err_crypto_fips_forced`", + "desc": "

      The --force-fips command-line argument was used but there was an attempt\nto enable or disable FIPS mode in the crypto module.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_FIPS_FORCED`" + }, + { + "textRaw": "`ERR_CRYPTO_FIPS_UNAVAILABLE`", + "name": "`err_crypto_fips_unavailable`", + "desc": "

      An attempt was made to enable or disable FIPS mode, but FIPS mode was not\navailable.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_FIPS_UNAVAILABLE`" + }, + { + "textRaw": "`ERR_CRYPTO_HASH_FINALIZED`", + "name": "`err_crypto_hash_finalized`", + "desc": "

      hash.digest() was called multiple times. The hash.digest() method must\nbe called no more than one time per instance of a Hash object.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_HASH_FINALIZED`" + }, + { + "textRaw": "`ERR_CRYPTO_HASH_UPDATE_FAILED`", + "name": "`err_crypto_hash_update_failed`", + "desc": "

      hash.update() failed for any reason. This should rarely, if ever, happen.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_HASH_UPDATE_FAILED`" + }, + { + "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY`", + "name": "`err_crypto_incompatible_key`", + "desc": "

      The given crypto keys are incompatible with the attempted operation.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY`" + }, + { + "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`", + "name": "`err_crypto_incompatible_key_options`", + "desc": "

      The selected public or private key encoding is incompatible with other options.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`" + }, + { + "textRaw": "`ERR_CRYPTO_INVALID_DIGEST`", + "name": "`err_crypto_invalid_digest`", + "desc": "

      An invalid crypto digest algorithm was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INVALID_DIGEST`" + }, + { + "textRaw": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`", + "name": "`err_crypto_invalid_key_object_type`", + "desc": "

      The given crypto key object's type is invalid for the attempted operation.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`" + }, + { + "textRaw": "`ERR_CRYPTO_INVALID_STATE`", + "name": "`err_crypto_invalid_state`", + "desc": "

      A crypto method was used on an object that was in an invalid state. For\ninstance, calling cipher.getAuthTag() before calling cipher.final().

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_INVALID_STATE`" + }, + { + "textRaw": "`ERR_CRYPTO_PBKDF2_ERROR`", + "name": "`err_crypto_pbkdf2_error`", + "desc": "

      The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide\nmore details and therefore neither does Node.js.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_PBKDF2_ERROR`" + }, + { + "textRaw": "`ERR_CRYPTO_SCRYPT_INVALID_PARAMETER`", + "name": "`err_crypto_scrypt_invalid_parameter`", + "desc": "

      One or more crypto.scrypt() or crypto.scryptSync() parameters are\noutside their legal range.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_SCRYPT_INVALID_PARAMETER`" + }, + { + "textRaw": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`", + "name": "`err_crypto_scrypt_not_supported`", + "desc": "

      Node.js was compiled without scrypt support. Not possible with the official\nrelease binaries but can happen with custom builds, including distro builds.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`" + }, + { + "textRaw": "`ERR_CRYPTO_SIGN_KEY_REQUIRED`", + "name": "`err_crypto_sign_key_required`", + "desc": "

      A signing key was not provided to the sign.sign() method.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_SIGN_KEY_REQUIRED`" + }, + { + "textRaw": "`ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH`", + "name": "`err_crypto_timing_safe_equal_length`", + "desc": "

      crypto.timingSafeEqual() was called with Buffer, TypedArray, or\nDataView arguments of different lengths.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH`" + }, + { + "textRaw": "`ERR_CRYPTO_UNKNOWN_CIPHER`", + "name": "`err_crypto_unknown_cipher`", + "desc": "

      An unknown cipher was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_UNKNOWN_CIPHER`" + }, + { + "textRaw": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`", + "name": "`err_crypto_unknown_dh_group`", + "desc": "

      An unknown Diffie-Hellman group name was given. See\ncrypto.getDiffieHellman() for a list of valid group names.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`" + }, + { + "textRaw": "`ERR_DIR_CLOSED`", + "name": "`err_dir_closed`", + "desc": "

      The fs.Dir was previously closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_DIR_CLOSED`" + }, + { + "textRaw": "`ERR_DIR_CONCURRENT_OPERATION`", + "name": "`err_dir_concurrent_operation`", + "meta": { + "added": [ + "v12.18.1" + ], + "changes": [] + }, + "desc": "

      A synchronous read or close call was attempted on an fs.Dir which has\nongoing asynchronous operations.

      \n

      ", + "type": "module", + "displayName": "`ERR_DIR_CONCURRENT_OPERATION`" + }, + { + "textRaw": "`ERR_DNS_SET_SERVERS_FAILED`", + "name": "`err_dns_set_servers_failed`", + "desc": "

      c-ares failed to set the DNS server.

      \n

      ", + "type": "module", + "displayName": "`ERR_DNS_SET_SERVERS_FAILED`" + }, + { + "textRaw": "`ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`", + "name": "`err_domain_callback_not_available`", + "desc": "

      The domain module was not usable since it could not establish the required\nerror handling hooks, because\nprocess.setUncaughtExceptionCaptureCallback() had been called at an\nearlier point in time.

      \n

      ", + "type": "module", + "displayName": "`ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`", + "name": "`err_domain_cannot_set_uncaught_exception_capture`", + "desc": "

      process.setUncaughtExceptionCaptureCallback() could not be called\nbecause the domain module has been loaded at an earlier point in time.

      \n

      The stack trace is extended to include the point in time at which the\ndomain module had been loaded.

      \n

      ", + "type": "module", + "displayName": "`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`" + }, + { + "textRaw": "`ERR_ENCODING_INVALID_ENCODED_DATA`", + "name": "`err_encoding_invalid_encoded_data`", + "desc": "

      Data provided to TextDecoder() API was invalid according to the encoding\nprovided.

      \n

      ", + "type": "module", + "displayName": "`ERR_ENCODING_INVALID_ENCODED_DATA`" + }, + { + "textRaw": "`ERR_ENCODING_NOT_SUPPORTED`", + "name": "`err_encoding_not_supported`", + "desc": "

      Encoding provided to TextDecoder() API was not one of the\nWHATWG Supported Encodings.

      \n

      ", + "type": "module", + "displayName": "`ERR_ENCODING_NOT_SUPPORTED`" + }, + { + "textRaw": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`", + "name": "`err_execution_environment_not_available`", + "desc": "

      The JS execution context is not associated with a Node.js environment.\nThis may occur when Node.js is used as an embedded library and some hooks\nfor the JS engine are not set up properly.

      \n

      ", + "type": "module", + "displayName": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_FALSY_VALUE_REJECTION`", + "name": "`err_falsy_value_rejection`", + "desc": "

      A Promise that was callbackified via util.callbackify() was rejected with a\nfalsy value.

      \n

      ", + "type": "module", + "displayName": "`ERR_FALSY_VALUE_REJECTION`" + }, + { + "textRaw": "`ERR_FS_FILE_TOO_LARGE`", + "name": "`err_fs_file_too_large`", + "desc": "

      An attempt has been made to read a file whose size is larger than the maximum\nallowed size for a Buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_FS_FILE_TOO_LARGE`" + }, + { + "textRaw": "`ERR_FS_INVALID_SYMLINK_TYPE`", + "name": "`err_fs_invalid_symlink_type`", + "desc": "

      An invalid symlink type was passed to the fs.symlink() or\nfs.symlinkSync() methods.

      \n

      ", + "type": "module", + "displayName": "`ERR_FS_INVALID_SYMLINK_TYPE`" + }, + { + "textRaw": "`ERR_HTTP_HEADERS_SENT`", + "name": "`err_http_headers_sent`", + "desc": "

      An attempt was made to add more headers after the headers had already been sent.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_HEADERS_SENT`" + }, + { + "textRaw": "`ERR_HTTP_INVALID_HEADER_VALUE`", + "name": "`err_http_invalid_header_value`", + "desc": "

      An invalid HTTP header value was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_INVALID_HEADER_VALUE`" + }, + { + "textRaw": "`ERR_HTTP_INVALID_STATUS_CODE`", + "name": "`err_http_invalid_status_code`", + "desc": "

      Status code was outside the regular status code range (100-999).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_INVALID_STATUS_CODE`" + }, + { + "textRaw": "`ERR_HTTP_TRAILER_INVALID`", + "name": "`err_http_trailer_invalid`", + "desc": "

      The Trailer header was set even though the transfer encoding does not support\nthat.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_TRAILER_INVALID`" + }, + { + "textRaw": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`", + "name": "`err_http2_altsvc_invalid_origin`", + "desc": "

      HTTP/2 ALTSVC frames require a valid origin.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`" + }, + { + "textRaw": "`ERR_HTTP2_ALTSVC_LENGTH`", + "name": "`err_http2_altsvc_length`", + "desc": "

      HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ALTSVC_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_CONNECT_AUTHORITY`", + "name": "`err_http2_connect_authority`", + "desc": "

      For HTTP/2 requests using the CONNECT method, the :authority pseudo-header\nis required.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_CONNECT_AUTHORITY`" + }, + { + "textRaw": "`ERR_HTTP2_CONNECT_PATH`", + "name": "`err_http2_connect_path`", + "desc": "

      For HTTP/2 requests using the CONNECT method, the :path pseudo-header is\nforbidden.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_CONNECT_PATH`" + }, + { + "textRaw": "`ERR_HTTP2_CONNECT_SCHEME`", + "name": "`err_http2_connect_scheme`", + "desc": "

      For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is\nforbidden.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_CONNECT_SCHEME`" + }, + { + "textRaw": "`ERR_HTTP2_ERROR`", + "name": "`err_http2_error`", + "desc": "

      A non-specific HTTP/2 error has occurred.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_GOAWAY_SESSION`", + "name": "`err_http2_goaway_session`", + "desc": "

      New HTTP/2 Streams may not be opened after the Http2Session has received a\nGOAWAY frame from the connected peer.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_GOAWAY_SESSION`" + }, + { + "textRaw": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`", + "name": "`err_http2_headers_after_respond`", + "desc": "

      An additional headers was specified after an HTTP/2 response was initiated.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`" + }, + { + "textRaw": "`ERR_HTTP2_HEADERS_SENT`", + "name": "`err_http2_headers_sent`", + "desc": "

      An attempt was made to send multiple response headers.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADERS_SENT`" + }, + { + "textRaw": "`ERR_HTTP2_HEADER_SINGLE_VALUE`", + "name": "`err_http2_header_single_value`", + "desc": "

      Multiple values were provided for an HTTP/2 header field that was required to\nhave only a single value.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADER_SINGLE_VALUE`" + }, + { + "textRaw": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`", + "name": "`err_http2_info_status_not_allowed`", + "desc": "

      Informational HTTP status codes (1xx) may not be set as the response status\ncode on HTTP/2 responses.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`", + "name": "`err_http2_invalid_connection_headers`", + "desc": "

      HTTP/1 connection specific headers are forbidden to be used in HTTP/2\nrequests and responses.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_HEADER_VALUE`", + "name": "`err_http2_invalid_header_value`", + "desc": "

      An invalid HTTP/2 header value was specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_HEADER_VALUE`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_INFO_STATUS`", + "name": "`err_http2_invalid_info_status`", + "desc": "

      An invalid HTTP informational status code has been specified. Informational\nstatus codes must be an integer between 100 and 199 (inclusive).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_INFO_STATUS`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_ORIGIN`", + "name": "`err_http2_invalid_origin`", + "desc": "

      HTTP/2 ORIGIN frames require a valid origin.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_ORIGIN`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH`", + "name": "`err_http2_invalid_packed_settings_length`", + "desc": "

      Input Buffer and Uint8Array instances passed to the\nhttp2.getUnpackedSettings() API must have a length that is a multiple of\nsix.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_PSEUDOHEADER`", + "name": "`err_http2_invalid_pseudoheader`", + "desc": "

      Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme,\nand :method) may be used.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_PSEUDOHEADER`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_SESSION`", + "name": "`err_http2_invalid_session`", + "desc": "

      An action was performed on an Http2Session object that had already been\ndestroyed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_SESSION`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_SETTING_VALUE`", + "name": "`err_http2_invalid_setting_value`", + "desc": "

      An invalid value has been specified for an HTTP/2 setting.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_SETTING_VALUE`" + }, + { + "textRaw": "`ERR_HTTP2_INVALID_STREAM`", + "name": "`err_http2_invalid_stream`", + "desc": "

      An operation was performed on a stream that had already been destroyed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INVALID_STREAM`" + }, + { + "textRaw": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`", + "name": "`err_http2_max_pending_settings_ack`", + "desc": "

      Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is\nrequired to send an acknowledgment that it has received and applied the new\nSETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may\nbe sent at any given time. This error code is used when that limit has been\nreached.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`" + }, + { + "textRaw": "`ERR_HTTP2_NESTED_PUSH`", + "name": "`err_http2_nested_push`", + "desc": "

      An attempt was made to initiate a new push stream from within a push stream.\nNested push streams are not permitted.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_NESTED_PUSH`" + }, + { + "textRaw": "`ERR_HTTP2_NO_SOCKET_MANIPULATION`", + "name": "`err_http2_no_socket_manipulation`", + "desc": "

      An attempt was made to directly manipulate (read, write, pause, resume, etc.) a\nsocket attached to an Http2Session.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_NO_SOCKET_MANIPULATION`" + }, + { + "textRaw": "`ERR_HTTP2_ORIGIN_LENGTH`", + "name": "`err_http2_origin_length`", + "desc": "

      HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_ORIGIN_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_OUT_OF_STREAMS`", + "name": "`err_http2_out_of_streams`", + "desc": "

      The number of streams created on a single HTTP/2 session reached the maximum\nlimit.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_OUT_OF_STREAMS`" + }, + { + "textRaw": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`", + "name": "`err_http2_payload_forbidden`", + "desc": "

      A message payload was specified for an HTTP response code for which a payload is\nforbidden.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`" + }, + { + "textRaw": "`ERR_HTTP2_PING_CANCEL`", + "name": "`err_http2_ping_cancel`", + "desc": "

      An HTTP/2 ping was canceled.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PING_CANCEL`" + }, + { + "textRaw": "`ERR_HTTP2_PING_LENGTH`", + "name": "`err_http2_ping_length`", + "desc": "

      HTTP/2 ping payloads must be exactly 8 bytes in length.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PING_LENGTH`" + }, + { + "textRaw": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`", + "name": "`err_http2_pseudoheader_not_allowed`", + "desc": "

      An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header\nkey names that begin with the : prefix.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`" + }, + { + "textRaw": "`ERR_HTTP2_PUSH_DISABLED`", + "name": "`err_http2_push_disabled`", + "desc": "

      An attempt was made to create a push stream, which had been disabled by the\nclient.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_PUSH_DISABLED`" + }, + { + "textRaw": "`ERR_HTTP2_SEND_FILE`", + "name": "`err_http2_send_file`", + "desc": "

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend a directory.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SEND_FILE`" + }, + { + "textRaw": "`ERR_HTTP2_SEND_FILE_NOSEEK`", + "name": "`err_http2_send_file_noseek`", + "desc": "

      An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend something other than a regular file, but offset or length options were\nprovided.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SEND_FILE_NOSEEK`" + }, + { + "textRaw": "`ERR_HTTP2_SESSION_ERROR`", + "name": "`err_http2_session_error`", + "desc": "

      The Http2Session closed with a non-zero error code.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SESSION_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_SETTINGS_CANCEL`", + "name": "`err_http2_settings_cancel`", + "desc": "

      The Http2Session settings canceled.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SETTINGS_CANCEL`" + }, + { + "textRaw": "`ERR_HTTP2_SOCKET_BOUND`", + "name": "`err_http2_socket_bound`", + "desc": "

      An attempt was made to connect a Http2Session object to a net.Socket or\ntls.TLSSocket that had already been bound to another Http2Session object.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SOCKET_BOUND`" + }, + { + "textRaw": "`ERR_HTTP2_SOCKET_UNBOUND`", + "name": "`err_http2_socket_unbound`", + "desc": "

      An attempt was made to use the socket property of an Http2Session that\nhas already been closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_SOCKET_UNBOUND`" + }, + { + "textRaw": "`ERR_HTTP2_STATUS_101`", + "name": "`err_http2_status_101`", + "desc": "

      Use of the 101 Informational status code is forbidden in HTTP/2.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STATUS_101`" + }, + { + "textRaw": "`ERR_HTTP2_STATUS_INVALID`", + "name": "`err_http2_status_invalid`", + "desc": "

      An invalid HTTP status code has been specified. Status codes must be an integer\nbetween 100 and 599 (inclusive).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STATUS_INVALID`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_CANCEL`", + "name": "`err_http2_stream_cancel`", + "desc": "

      An Http2Stream was destroyed before any data was transmitted to the connected\npeer.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_CANCEL`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_ERROR`", + "name": "`err_http2_stream_error`", + "desc": "

      A non-zero error code was been specified in an RST_STREAM frame.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`", + "name": "`err_http2_stream_self_dependency`", + "desc": "

      When setting the priority for an HTTP/2 stream, the stream may be marked as\na dependency for a parent stream. This error code is used when an attempt is\nmade to mark a stream and dependent of itself.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`" + }, + { + "textRaw": "`ERR_HTTP2_TRAILERS_ALREADY_SENT`", + "name": "`err_http2_trailers_already_sent`", + "desc": "

      Trailing headers have already been sent on the Http2Stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_TRAILERS_ALREADY_SENT`" + }, + { + "textRaw": "`ERR_HTTP2_TRAILERS_NOT_READY`", + "name": "`err_http2_trailers_not_ready`", + "desc": "

      The http2stream.sendTrailers() method cannot be called until after the\n'wantTrailers' event is emitted on an Http2Stream object. The\n'wantTrailers' event will only be emitted if the waitForTrailers option\nis set for the Http2Stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_TRAILERS_NOT_READY`" + }, + { + "textRaw": "`ERR_HTTP2_UNSUPPORTED_PROTOCOL`", + "name": "`err_http2_unsupported_protocol`", + "desc": "

      http2.connect() was passed a URL that uses any protocol other than http: or\nhttps:.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_UNSUPPORTED_PROTOCOL`" + }, + { + "textRaw": "`ERR_INTERNAL_ASSERTION`", + "name": "`err_internal_assertion`", + "desc": "

      There was a bug in Node.js or incorrect usage of Node.js internals.\nTo fix the error, open an issue at https://github.com/nodejs/node/issues.

      \n

      ", + "type": "module", + "displayName": "`ERR_INTERNAL_ASSERTION`" + }, + { + "textRaw": "`ERR_INCOMPATIBLE_OPTION_PAIR`", + "name": "`err_incompatible_option_pair`", + "desc": "

      An option pair is incompatible with each other and cannot be used at the same\ntime.

      \n

      ", + "type": "module", + "displayName": "`ERR_INCOMPATIBLE_OPTION_PAIR`" + }, + { + "textRaw": "`ERR_INPUT_TYPE_NOT_ALLOWED`", + "name": "`err_input_type_not_allowed`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      The --input-type flag was used to attempt to execute a file. This flag can\nonly be used with input via --eval, --print or STDIN.

      \n

      ", + "type": "module", + "displayName": "`ERR_INPUT_TYPE_NOT_ALLOWED`" + }, + { + "textRaw": "`ERR_INSPECTOR_ALREADY_ACTIVATED`", + "name": "`err_inspector_already_activated`", + "desc": "

      While using the inspector module, an attempt was made to activate the\ninspector when it already started to listen on a port. Use inspector.close()\nbefore activating it on a different address.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_ALREADY_ACTIVATED`" + }, + { + "textRaw": "`ERR_INSPECTOR_ALREADY_CONNECTED`", + "name": "`err_inspector_already_connected`", + "desc": "

      While using the inspector module, an attempt was made to connect when the\ninspector was already connected.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_ALREADY_CONNECTED`" + }, + { + "textRaw": "`ERR_INSPECTOR_CLOSED`", + "name": "`err_inspector_closed`", + "desc": "

      While using the inspector module, an attempt was made to use the inspector\nafter the session had already closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_CLOSED`" + }, + { + "textRaw": "`ERR_INSPECTOR_COMMAND`", + "name": "`err_inspector_command`", + "desc": "

      An error occurred while issuing a command via the inspector module.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_COMMAND`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_ACTIVE`", + "name": "`err_inspector_not_active`", + "desc": "

      The inspector is not active when inspector.waitForDebugger() is called.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_ACTIVE`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_AVAILABLE`", + "name": "`err_inspector_not_available`", + "desc": "

      The inspector module is not available for use.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_AVAILABLE`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_CONNECTED`", + "name": "`err_inspector_not_connected`", + "desc": "

      While using the inspector module, an attempt was made to use the inspector\nbefore it was connected.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_CONNECTED`" + }, + { + "textRaw": "`ERR_INSPECTOR_NOT_WORKER`", + "name": "`err_inspector_not_worker`", + "desc": "

      An API was called on the main thread that can only be used from\nthe worker thread.

      \n

      ", + "type": "module", + "displayName": "`ERR_INSPECTOR_NOT_WORKER`" + }, + { + "textRaw": "`ERR_INVALID_ADDRESS_FAMILY`", + "name": "`err_invalid_address_family`", + "desc": "

      The provided address family is not understood by the Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ADDRESS_FAMILY`" + }, + { + "textRaw": "`ERR_INVALID_ARG_TYPE`", + "name": "`err_invalid_arg_type`", + "desc": "

      An argument of the wrong type was passed to a Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ARG_TYPE`" + }, + { + "textRaw": "`ERR_INVALID_ARG_VALUE`", + "name": "`err_invalid_arg_value`", + "desc": "

      An invalid or unsupported value was passed for a given argument.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ARG_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_ASYNC_ID`", + "name": "`err_invalid_async_id`", + "desc": "

      An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id\nless than -1 should never happen.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_ASYNC_ID`" + }, + { + "textRaw": "`ERR_INVALID_BUFFER_SIZE`", + "name": "`err_invalid_buffer_size`", + "desc": "

      A swap was performed on a Buffer but its size was not compatible with the\noperation.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_BUFFER_SIZE`" + }, + { + "textRaw": "`ERR_INVALID_CALLBACK`", + "name": "`err_invalid_callback`", + "desc": "

      A callback function was required but was not been provided to a Node.js API.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_CALLBACK`" + }, + { + "textRaw": "`ERR_INVALID_CHAR`", + "name": "`err_invalid_char`", + "desc": "

      Invalid characters were detected in headers.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_CHAR`" + }, + { + "textRaw": "`ERR_INVALID_CURSOR_POS`", + "name": "`err_invalid_cursor_pos`", + "desc": "

      A cursor on a given stream cannot be moved to a specified row without a\nspecified column.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_CURSOR_POS`" + }, + { + "textRaw": "`ERR_INVALID_FD`", + "name": "`err_invalid_fd`", + "desc": "

      A file descriptor ('fd') was not valid (e.g. it was a negative value).

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FD`" + }, + { + "textRaw": "`ERR_INVALID_FD_TYPE`", + "name": "`err_invalid_fd_type`", + "desc": "

      A file descriptor ('fd') type was not valid.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FD_TYPE`" + }, + { + "textRaw": "`ERR_INVALID_FILE_URL_HOST`", + "name": "`err_invalid_file_url_host`", + "desc": "

      A Node.js API that consumes file: URLs (such as certain functions in the\nfs module) encountered a file URL with an incompatible host. This\nsituation can only occur on Unix-like systems where only localhost or an empty\nhost is supported.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FILE_URL_HOST`" + }, + { + "textRaw": "`ERR_INVALID_FILE_URL_PATH`", + "name": "`err_invalid_file_url_path`", + "desc": "

      A Node.js API that consumes file: URLs (such as certain functions in the\nfs module) encountered a file URL with an incompatible path. The exact\nsemantics for determining whether a path can be used is platform-dependent.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_FILE_URL_PATH`" + }, + { + "textRaw": "`ERR_INVALID_HANDLE_TYPE`", + "name": "`err_invalid_handle_type`", + "desc": "

      An attempt was made to send an unsupported \"handle\" over an IPC communication\nchannel to a child process. See subprocess.send() and process.send()\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_HANDLE_TYPE`" + }, + { + "textRaw": "`ERR_INVALID_HTTP_TOKEN`", + "name": "`err_invalid_http_token`", + "desc": "

      An invalid HTTP token was supplied.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_HTTP_TOKEN`" + }, + { + "textRaw": "`ERR_INVALID_IP_ADDRESS`", + "name": "`err_invalid_ip_address`", + "desc": "

      An IP address is not valid.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_IP_ADDRESS`" + }, + { + "textRaw": "`ERR_INVALID_MODULE_SPECIFIER`", + "name": "`err_invalid_module_specifier`", + "desc": "

      The imported module string is an invalid URL, package name, or package subpath\nspecifier.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_MODULE_SPECIFIER`" + }, + { + "textRaw": "`ERR_INVALID_OPT_VALUE`", + "name": "`err_invalid_opt_value`", + "desc": "

      An invalid or unexpected value was passed in an options object.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_OPT_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_OPT_VALUE_ENCODING`", + "name": "`err_invalid_opt_value_encoding`", + "desc": "

      An invalid or unknown file encoding was passed.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_OPT_VALUE_ENCODING`" + }, + { + "textRaw": "`ERR_INVALID_PACKAGE_CONFIG`", + "name": "`err_invalid_package_config`", + "desc": "

      An invalid package.json file was found which failed parsing.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PACKAGE_CONFIG`" + }, + { + "textRaw": "`ERR_INVALID_PACKAGE_TARGET`", + "name": "`err_invalid_package_target`", + "desc": "

      The package.json \"exports\" field contains an invalid target mapping\nvalue for the attempted module resolution.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PACKAGE_TARGET`" + }, + { + "textRaw": "`ERR_INVALID_PERFORMANCE_MARK`", + "name": "`err_invalid_performance_mark`", + "desc": "

      While using the Performance Timing API (perf_hooks), a performance mark is\ninvalid.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PERFORMANCE_MARK`" + }, + { + "textRaw": "`ERR_INVALID_PROTOCOL`", + "name": "`err_invalid_protocol`", + "desc": "

      An invalid options.protocol was passed to http.request().

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_PROTOCOL`" + }, + { + "textRaw": "`ERR_INVALID_REPL_EVAL_CONFIG`", + "name": "`err_invalid_repl_eval_config`", + "desc": "

      Both breakEvalOnSigint and eval options were set in the REPL config,\nwhich is not supported.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_REPL_EVAL_CONFIG`" + }, + { + "textRaw": "`ERR_INVALID_REPL_INPUT`", + "name": "`err_invalid_repl_input`", + "desc": "

      The input may not be used in the REPL. All prohibited inputs are\ndocumented in the REPL's documentation.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_REPL_INPUT`" + }, + { + "textRaw": "`ERR_INVALID_RETURN_PROPERTY`", + "name": "`err_invalid_return_property`", + "desc": "

      Thrown in case a function option does not provide a valid value for one of its\nreturned object properties on execution.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_RETURN_PROPERTY`" + }, + { + "textRaw": "`ERR_INVALID_RETURN_PROPERTY_VALUE`", + "name": "`err_invalid_return_property_value`", + "desc": "

      Thrown in case a function option does not provide an expected value\ntype for one of its returned object properties on execution.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_RETURN_PROPERTY_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_RETURN_VALUE`", + "name": "`err_invalid_return_value`", + "desc": "

      Thrown in case a function option does not return an expected value\ntype on execution, such as when a function is expected to return a promise.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_RETURN_VALUE`" + }, + { + "textRaw": "`ERR_INVALID_SYNC_FORK_INPUT`", + "name": "`err_invalid_sync_fork_input`", + "desc": "

      A Buffer, TypedArray, DataView or string was provided as stdio input to\nan asynchronous fork. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_SYNC_FORK_INPUT`" + }, + { + "textRaw": "`ERR_INVALID_THIS`", + "name": "`err_invalid_this`", + "desc": "

      A Node.js API function was called with an incompatible this value.

      \n
      const urlSearchParams = new URLSearchParams('foo=bar&baz=new');\n\nconst buf = Buffer.alloc(1);\nurlSearchParams.has.call(buf, 'foo');\n// Throws a TypeError with code 'ERR_INVALID_THIS'\n
      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_THIS`" + }, + { + "textRaw": "`ERR_INVALID_TRANSFER_OBJECT`", + "name": "`err_invalid_transfer_object`", + "desc": "

      An invalid transfer object was passed to postMessage().

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_TRANSFER_OBJECT`" + }, + { + "textRaw": "`ERR_INVALID_TUPLE`", + "name": "`err_invalid_tuple`", + "desc": "

      An element in the iterable provided to the WHATWG\nURLSearchParams constructor did not\nrepresent a [name, value] tuple – that is, if an element is not iterable, or\ndoes not consist of exactly two elements.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_TUPLE`" + }, + { + "textRaw": "`ERR_INVALID_URI`", + "name": "`err_invalid_uri`", + "desc": "

      An invalid URI was passed.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_URI`" + }, + { + "textRaw": "`ERR_INVALID_URL`", + "name": "`err_invalid_url`", + "desc": "

      An invalid URL was passed to the WHATWG\nURL constructor to be parsed. The thrown error object\ntypically has an additional property 'input' that contains the URL that failed\nto parse.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_URL`" + }, + { + "textRaw": "`ERR_INVALID_URL_SCHEME`", + "name": "`err_invalid_url_scheme`", + "desc": "

      An attempt was made to use a URL of an incompatible scheme (protocol) for a\nspecific purpose. It is only used in the WHATWG URL API support in the\nfs module (which only accepts URLs with 'file' scheme), but may be used\nin other Node.js APIs as well in the future.

      \n

      ", + "type": "module", + "displayName": "`ERR_INVALID_URL_SCHEME`" + }, + { + "textRaw": "`ERR_IPC_CHANNEL_CLOSED`", + "name": "`err_ipc_channel_closed`", + "desc": "

      An attempt was made to use an IPC communication channel that was already closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_CHANNEL_CLOSED`" + }, + { + "textRaw": "`ERR_IPC_DISCONNECTED`", + "name": "`err_ipc_disconnected`", + "desc": "

      An attempt was made to disconnect an IPC communication channel that was already\ndisconnected. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_DISCONNECTED`" + }, + { + "textRaw": "`ERR_IPC_ONE_PIPE`", + "name": "`err_ipc_one_pipe`", + "desc": "

      An attempt was made to create a child Node.js process using more than one IPC\ncommunication channel. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_ONE_PIPE`" + }, + { + "textRaw": "`ERR_IPC_SYNC_FORK`", + "name": "`err_ipc_sync_fork`", + "desc": "

      An attempt was made to open an IPC communication channel with a synchronously\nforked Node.js process. See the documentation for the child_process module\nfor more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_IPC_SYNC_FORK`" + }, + { + "textRaw": "`ERR_MANIFEST_ASSERT_INTEGRITY`", + "name": "`err_manifest_assert_integrity`", + "desc": "

      An attempt was made to load a resource, but the resource did not match the\nintegrity defined by the policy manifest. See the documentation for policy\nmanifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_ASSERT_INTEGRITY`" + }, + { + "textRaw": "`ERR_MANIFEST_DEPENDENCY_MISSING`", + "name": "`err_manifest_dependency_missing`", + "desc": "

      An attempt was made to load a resource, but the resource was not listed as a\ndependency from the location that attempted to load it. See the documentation\nfor policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_DEPENDENCY_MISSING`" + }, + { + "textRaw": "`ERR_MANIFEST_INTEGRITY_MISMATCH`", + "name": "`err_manifest_integrity_mismatch`", + "desc": "

      An attempt was made to load a policy manifest, but the manifest had multiple\nentries for a resource which did not match each other. Update the manifest\nentries to match in order to resolve this error. See the documentation for\npolicy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_INTEGRITY_MISMATCH`" + }, + { + "textRaw": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`", + "name": "`err_manifest_invalid_resource_field`", + "desc": "

      A policy manifest resource had an invalid value for one of its fields. Update\nthe manifest entry to match in order to resolve this error. See the\ndocumentation for policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`" + }, + { + "textRaw": "`ERR_MANIFEST_PARSE_POLICY`", + "name": "`err_manifest_parse_policy`", + "desc": "

      An attempt was made to load a policy manifest, but the manifest was unable to\nbe parsed. See the documentation for policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_PARSE_POLICY`" + }, + { + "textRaw": "`ERR_MANIFEST_TDZ`", + "name": "`err_manifest_tdz`", + "desc": "

      An attempt was made to read from a policy manifest, but the manifest\ninitialization has not yet taken place. This is likely a bug in Node.js.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_TDZ`" + }, + { + "textRaw": "`ERR_MANIFEST_UNKNOWN_ONERROR`", + "name": "`err_manifest_unknown_onerror`", + "desc": "

      A policy manifest was loaded, but had an unknown value for its \"onerror\"\nbehavior. See the documentation for policy manifests for more information.

      \n

      ", + "type": "module", + "displayName": "`ERR_MANIFEST_UNKNOWN_ONERROR`" + }, + { + "textRaw": "`ERR_MEMORY_ALLOCATION_FAILED`", + "name": "`err_memory_allocation_failed`", + "desc": "

      An attempt was made to allocate memory (usually in the C++ layer) but it\nfailed.

      \n

      ", + "type": "module", + "displayName": "`ERR_MEMORY_ALLOCATION_FAILED`" + }, + { + "textRaw": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`", + "name": "`err_message_target_context_unavailable`", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      A message posted to a MessagePort could not be deserialized in the target\nvm Context. Not all Node.js objects can be successfully instantiated in\nany context at this time, and attempting to transfer them using postMessage()\ncan fail on the receiving side in that case.

      \n

      ", + "type": "module", + "displayName": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`" + }, + { + "textRaw": "`ERR_METHOD_NOT_IMPLEMENTED`", + "name": "`err_method_not_implemented`", + "desc": "

      A method is required but not implemented.

      \n

      ", + "type": "module", + "displayName": "`ERR_METHOD_NOT_IMPLEMENTED`" + }, + { + "textRaw": "`ERR_MISSING_ARGS`", + "name": "`err_missing_args`", + "desc": "

      A required argument of a Node.js API was not passed. This is only used for\nstrict compliance with the API specification (which in some cases may accept\nfunc(undefined) but not func()). In most native Node.js APIs,\nfunc(undefined) and func() are treated identically, and the\nERR_INVALID_ARG_TYPE error code may be used instead.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_ARGS`" + }, + { + "textRaw": "`ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK`", + "name": "`err_missing_dynamic_instantiate_hook`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An ES Module loader hook specified format: 'dynamic' but did not provide\na dynamicInstantiate hook.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK`" + }, + { + "textRaw": "`ERR_MISSING_OPTION`", + "name": "`err_missing_option`", + "desc": "

      For APIs that accept options objects, some options might be mandatory. This code\nis thrown if a required option is missing.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_OPTION`" + }, + { + "textRaw": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`", + "name": "`err_missing_message_port_in_transfer_list`", + "desc": "

      An object that needs to be explicitly listed in the transferList argument\nwas found in the object passed to a postMessage() call, but not provided in\nthe transferList for that call. Usually, this is a MessagePort.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`" + }, + { + "textRaw": "`ERR_MISSING_PASSPHRASE`", + "name": "`err_missing_passphrase`", + "desc": "

      An attempt was made to read an encrypted key without specifying a passphrase.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_PASSPHRASE`" + }, + { + "textRaw": "`ERR_MISSING_PLATFORM_FOR_WORKER`", + "name": "`err_missing_platform_for_worker`", + "desc": "

      The V8 platform used by this instance of Node.js does not support creating\nWorkers. This is caused by lack of embedder support for Workers. In particular,\nthis error will not occur with standard builds of Node.js.

      \n

      ", + "type": "module", + "displayName": "`ERR_MISSING_PLATFORM_FOR_WORKER`" + }, + { + "textRaw": "`ERR_MODULE_NOT_FOUND`", + "name": "`err_module_not_found`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An ES Module could not be resolved.

      \n

      ", + "type": "module", + "displayName": "`ERR_MODULE_NOT_FOUND`" + }, + { + "textRaw": "`ERR_MULTIPLE_CALLBACK`", + "name": "`err_multiple_callback`", + "desc": "

      A callback was called more than once.

      \n

      A callback is almost always meant to only be called once as the query\ncan either be fulfilled or rejected but not both at the same time. The latter\nwould be possible by calling a callback more than once.

      \n

      ", + "type": "module", + "displayName": "`ERR_MULTIPLE_CALLBACK`" + }, + { + "textRaw": "`ERR_NAPI_CONS_FUNCTION`", + "name": "`err_napi_cons_function`", + "desc": "

      While using N-API, a constructor passed was not a function.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_CONS_FUNCTION`" + }, + { + "textRaw": "`ERR_NAPI_INVALID_DATAVIEW_ARGS`", + "name": "`err_napi_invalid_dataview_args`", + "desc": "

      While calling napi_create_dataview(), a given offset was outside the bounds\nof the dataview or offset + length was larger than a length of given buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_INVALID_DATAVIEW_ARGS`" + }, + { + "textRaw": "`ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT`", + "name": "`err_napi_invalid_typedarray_alignment`", + "desc": "

      While calling napi_create_typedarray(), the provided offset was not a\nmultiple of the element size.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT`" + }, + { + "textRaw": "`ERR_NAPI_INVALID_TYPEDARRAY_LENGTH`", + "name": "`err_napi_invalid_typedarray_length`", + "desc": "

      While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_INVALID_TYPEDARRAY_LENGTH`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_CALL_JS`", + "name": "`err_napi_tsfn_call_js`", + "desc": "

      An error occurred while invoking the JavaScript portion of the thread-safe\nfunction.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_CALL_JS`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_GET_UNDEFINED`", + "name": "`err_napi_tsfn_get_undefined`", + "desc": "

      An error occurred while attempting to retrieve the JavaScript undefined\nvalue.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_GET_UNDEFINED`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_START_IDLE_LOOP`", + "name": "`err_napi_tsfn_start_idle_loop`", + "desc": "

      On the main thread, values are removed from the queue associated with the\nthread-safe function in an idle loop. This error indicates that an error\nhas occurred when attempting to start the loop.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_START_IDLE_LOOP`" + }, + { + "textRaw": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`", + "name": "`err_napi_tsfn_stop_idle_loop`", + "desc": "

      Once no more items are left in the queue, the idle loop must be suspended. This\nerror indicates that the idle loop has failed to stop.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`" + }, + { + "textRaw": "`ERR_NO_CRYPTO`", + "name": "`err_no_crypto`", + "desc": "

      An attempt was made to use crypto features while Node.js was not compiled with\nOpenSSL crypto support.

      \n

      ", + "type": "module", + "displayName": "`ERR_NO_CRYPTO`" + }, + { + "textRaw": "`ERR_NO_ICU`", + "name": "`err_no_icu`", + "desc": "

      An attempt was made to use features that require ICU, but Node.js was not\ncompiled with ICU support.

      \n

      ", + "type": "module", + "displayName": "`ERR_NO_ICU`" + }, + { + "textRaw": "`ERR_NON_CONTEXT_AWARE_DISABLED`", + "name": "`err_non_context_aware_disabled`", + "desc": "

      A non-context-aware native addon was loaded in a process that disallows them.

      \n

      ", + "type": "module", + "displayName": "`ERR_NON_CONTEXT_AWARE_DISABLED`" + }, + { + "textRaw": "`ERR_OUT_OF_RANGE`", + "name": "`err_out_of_range`", + "desc": "

      A given value is out of the accepted range.

      \n

      ", + "type": "module", + "displayName": "`ERR_OUT_OF_RANGE`" + }, + { + "textRaw": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`", + "name": "`err_package_import_not_defined`", + "desc": "

      The package.json \"imports\" field does not define the given internal\npackage specifier mapping.

      \n

      ", + "type": "module", + "displayName": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`" + }, + { + "textRaw": "`ERR_PACKAGE_PATH_NOT_EXPORTED`", + "name": "`err_package_path_not_exported`", + "desc": "

      The package.json \"exports\" field does not export the requested subpath.\nBecause exports are encapsulated, private internal modules that are not exported\ncannot be imported through the package resolution, unless using an absolute URL.

      \n

      ", + "type": "module", + "displayName": "`ERR_PACKAGE_PATH_NOT_EXPORTED`" + }, + { + "textRaw": "`ERR_PROTO_ACCESS`", + "name": "`err_proto_access`", + "desc": "

      Accessing Object.prototype.__proto__ has been forbidden using\n--disable-proto=throw. Object.getPrototypeOf and\nObject.setPrototypeOf should be used to get and set the prototype of an\nobject.

      \n

      ", + "type": "module", + "displayName": "`ERR_PROTO_ACCESS`" + }, + { + "textRaw": "`ERR_REQUIRE_ESM`", + "name": "`err_require_esm`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An attempt was made to require() an ES Module.

      \n

      ", + "type": "module", + "displayName": "`ERR_REQUIRE_ESM`" + }, + { + "textRaw": "`ERR_SCRIPT_EXECUTION_INTERRUPTED`", + "name": "`err_script_execution_interrupted`", + "desc": "

      Script execution was interrupted by SIGINT (For example,\nCtrl+C was pressed.)

      \n

      ", + "type": "module", + "displayName": "`ERR_SCRIPT_EXECUTION_INTERRUPTED`" + }, + { + "textRaw": "`ERR_SCRIPT_EXECUTION_TIMEOUT`", + "name": "`err_script_execution_timeout`", + "desc": "

      Script execution timed out, possibly due to bugs in the script being executed.

      \n

      ", + "type": "module", + "displayName": "`ERR_SCRIPT_EXECUTION_TIMEOUT`" + }, + { + "textRaw": "`ERR_SERVER_ALREADY_LISTEN`", + "name": "`err_server_already_listen`", + "desc": "

      The server.listen() method was called while a net.Server was already\nlistening. This applies to all instances of net.Server, including HTTP, HTTPS,\nand HTTP/2 Server instances.

      \n

      ", + "type": "module", + "displayName": "`ERR_SERVER_ALREADY_LISTEN`" + }, + { + "textRaw": "`ERR_SERVER_NOT_RUNNING`", + "name": "`err_server_not_running`", + "desc": "

      The server.close() method was called when a net.Server was not\nrunning. This applies to all instances of net.Server, including HTTP, HTTPS,\nand HTTP/2 Server instances.

      \n

      ", + "type": "module", + "displayName": "`ERR_SERVER_NOT_RUNNING`" + }, + { + "textRaw": "`ERR_SOCKET_ALREADY_BOUND`", + "name": "`err_socket_already_bound`", + "desc": "

      An attempt was made to bind a socket that has already been bound.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_ALREADY_BOUND`" + }, + { + "textRaw": "`ERR_SOCKET_BAD_BUFFER_SIZE`", + "name": "`err_socket_bad_buffer_size`", + "desc": "

      An invalid (negative) size was passed for either the recvBufferSize or\nsendBufferSize options in dgram.createSocket().

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BAD_BUFFER_SIZE`" + }, + { + "textRaw": "`ERR_SOCKET_BAD_PORT`", + "name": "`err_socket_bad_port`", + "desc": "

      An API function expecting a port >= 0 and < 65536 received an invalid value.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BAD_PORT`" + }, + { + "textRaw": "`ERR_SOCKET_BAD_TYPE`", + "name": "`err_socket_bad_type`", + "desc": "

      An API function expecting a socket type (udp4 or udp6) received an invalid\nvalue.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BAD_TYPE`" + }, + { + "textRaw": "`ERR_SOCKET_BUFFER_SIZE`", + "name": "`err_socket_buffer_size`", + "desc": "

      While using dgram.createSocket(), the size of the receive or send Buffer\ncould not be determined.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_BUFFER_SIZE`" + }, + { + "textRaw": "`ERR_SOCKET_CANNOT_SEND`", + "name": "`err_socket_cannot_send`", + "desc": "

      Data could be sent on a socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_CANNOT_SEND`" + }, + { + "textRaw": "`ERR_SOCKET_CLOSED`", + "name": "`err_socket_closed`", + "desc": "

      An attempt was made to operate on an already closed socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_CLOSED`" + }, + { + "textRaw": "`ERR_SOCKET_DGRAM_IS_CONNECTED`", + "name": "`err_socket_dgram_is_connected`", + "desc": "

      A dgram.connect() call was made on an already connected socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_DGRAM_IS_CONNECTED`" + }, + { + "textRaw": "`ERR_SOCKET_DGRAM_NOT_CONNECTED`", + "name": "`err_socket_dgram_not_connected`", + "desc": "

      A dgram.disconnect() or dgram.remoteAddress() call was made on a\ndisconnected socket.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_DGRAM_NOT_CONNECTED`" + }, + { + "textRaw": "`ERR_SOCKET_DGRAM_NOT_RUNNING`", + "name": "`err_socket_dgram_not_running`", + "desc": "

      A call was made and the UDP subsystem was not running.

      \n

      ", + "type": "module", + "displayName": "`ERR_SOCKET_DGRAM_NOT_RUNNING`" + }, + { + "textRaw": "`ERR_SRI_PARSE`", + "name": "`err_sri_parse`", + "desc": "

      A string was provided for a Subresource Integrity check, but was unable to be\nparsed. Check the format of integrity attributes by looking at the\nSubresource Integrity specification.

      \n

      ", + "type": "module", + "displayName": "`ERR_SRI_PARSE`" + }, + { + "textRaw": "`ERR_STREAM_CANNOT_PIPE`", + "name": "`err_stream_cannot_pipe`", + "desc": "

      An attempt was made to call stream.pipe() on a Writable stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_CANNOT_PIPE`" + }, + { + "textRaw": "`ERR_STREAM_DESTROYED`", + "name": "`err_stream_destroyed`", + "desc": "

      A stream method was called that cannot complete because the stream was\ndestroyed using stream.destroy().

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_DESTROYED`" + }, + { + "textRaw": "`ERR_STREAM_NULL_VALUES`", + "name": "`err_stream_null_values`", + "desc": "

      An attempt was made to call stream.write() with a null chunk.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_NULL_VALUES`" + }, + { + "textRaw": "`ERR_STREAM_PREMATURE_CLOSE`", + "name": "`err_stream_premature_close`", + "desc": "

      An error returned by stream.finished() and stream.pipeline(), when a stream\nor a pipeline ends non gracefully with no explicit error.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_PREMATURE_CLOSE`" + }, + { + "textRaw": "`ERR_STREAM_PUSH_AFTER_EOF`", + "name": "`err_stream_push_after_eof`", + "desc": "

      An attempt was made to call stream.push() after a null(EOF) had been\npushed to the stream.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_PUSH_AFTER_EOF`" + }, + { + "textRaw": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`", + "name": "`err_stream_unshift_after_end_event`", + "desc": "

      An attempt was made to call stream.unshift() after the 'end' event was\nemitted.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`" + }, + { + "textRaw": "`ERR_STREAM_WRAP`", + "name": "`err_stream_wrap`", + "desc": "

      Prevents an abort if a string decoder was set on the Socket or if the decoder\nis in objectMode.

      \n
      const Socket = require('net').Socket;\nconst instance = new Socket();\n\ninstance.setEncoding('utf8');\n
      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_WRAP`" + }, + { + "textRaw": "`ERR_STREAM_WRITE_AFTER_END`", + "name": "`err_stream_write_after_end`", + "desc": "

      An attempt was made to call stream.write() after stream.end() has been\ncalled.

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_WRITE_AFTER_END`" + }, + { + "textRaw": "`ERR_STRING_TOO_LONG`", + "name": "`err_string_too_long`", + "desc": "

      An attempt has been made to create a string longer than the maximum allowed\nlength.

      \n

      ", + "type": "module", + "displayName": "`ERR_STRING_TOO_LONG`" + }, + { + "textRaw": "`ERR_SYNTHETIC`", + "name": "`err_synthetic`", + "desc": "

      An artificial error object used to capture the call stack for diagnostic\nreports.

      \n

      ", + "type": "module", + "displayName": "`ERR_SYNTHETIC`" + }, + { + "textRaw": "`ERR_SYSTEM_ERROR`", + "name": "`err_system_error`", + "desc": "

      An unspecified or non-specific system error has occurred within the Node.js\nprocess. The error object will have an err.info object property with\nadditional details.

      \n

      ", + "type": "module", + "displayName": "`ERR_SYSTEM_ERROR`" + }, + { + "textRaw": "`ERR_TLS_CERT_ALTNAME_INVALID`", + "name": "`err_tls_cert_altname_invalid`", + "desc": "

      While using TLS, the host name/IP of the peer did not match any of the\nsubjectAltNames in its certificate.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_CERT_ALTNAME_INVALID`" + }, + { + "textRaw": "`ERR_TLS_DH_PARAM_SIZE`", + "name": "`err_tls_dh_param_size`", + "desc": "

      While using TLS, the parameter offered for the Diffie-Hellman (DH)\nkey-agreement protocol is too small. By default, the key length must be greater\nthan or equal to 1024 bits to avoid vulnerabilities, even though it is strongly\nrecommended to use 2048 bits or larger for stronger security.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_DH_PARAM_SIZE`" + }, + { + "textRaw": "`ERR_TLS_HANDSHAKE_TIMEOUT`", + "name": "`err_tls_handshake_timeout`", + "desc": "

      A TLS/SSL handshake timed out. In this case, the server must also abort the\nconnection.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_HANDSHAKE_TIMEOUT`" + }, + { + "textRaw": "`ERR_TLS_INVALID_CONTEXT`", + "name": "`err_tls_invalid_context`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      The context must be a SecureContext.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_CONTEXT`" + }, + { + "textRaw": "`ERR_TLS_INVALID_STATE`", + "name": "`err_tls_invalid_state`", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      The TLS socket must be connected and securily established. Ensure the 'secure'\nevent is emitted before continuing.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_STATE`" + }, + { + "textRaw": "`ERR_TLS_INVALID_PROTOCOL_METHOD`", + "name": "`err_tls_invalid_protocol_method`", + "desc": "

      The specified secureProtocol method is invalid. It is either unknown, or\ndisabled because it is insecure.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_PROTOCOL_METHOD`" + }, + { + "textRaw": "`ERR_TLS_INVALID_PROTOCOL_VERSION`", + "name": "`err_tls_invalid_protocol_version`", + "desc": "

      Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_INVALID_PROTOCOL_VERSION`" + }, + { + "textRaw": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`", + "name": "`err_tls_protocol_version_conflict`", + "desc": "

      Attempting to set a TLS protocol minVersion or maxVersion conflicts with an\nattempt to set the secureProtocol explicitly. Use one mechanism or the other.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`" + }, + { + "textRaw": "`ERR_TLS_RENEGOTIATION_DISABLED`", + "name": "`err_tls_renegotiation_disabled`", + "desc": "

      An attempt was made to renegotiate TLS on a socket instance with TLS disabled.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_RENEGOTIATION_DISABLED`" + }, + { + "textRaw": "`ERR_TLS_REQUIRED_SERVER_NAME`", + "name": "`err_tls_required_server_name`", + "desc": "

      While using TLS, the server.addContext() method was called without providing\na host name in the first parameter.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_REQUIRED_SERVER_NAME`" + }, + { + "textRaw": "`ERR_TLS_SESSION_ATTACK`", + "name": "`err_tls_session_attack`", + "desc": "

      An excessive amount of TLS renegotiations is detected, which is a potential\nvector for denial-of-service attacks.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_SESSION_ATTACK`" + }, + { + "textRaw": "`ERR_TLS_SNI_FROM_SERVER`", + "name": "`err_tls_sni_from_server`", + "desc": "

      An attempt was made to issue Server Name Indication from a TLS server-side\nsocket, which is only valid from a client.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_SNI_FROM_SERVER`" + }, + { + "textRaw": "`ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`", + "name": "`err_tls_psk_set_identiy_hint_failed`", + "desc": "

      Failed to set PSK identity hint. Hint may be too long.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`" + }, + { + "textRaw": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`", + "name": "`err_trace_events_category_required`", + "desc": "

      The trace_events.createTracing() method requires at least one trace event\ncategory.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`" + }, + { + "textRaw": "`ERR_TRACE_EVENTS_UNAVAILABLE`", + "name": "`err_trace_events_unavailable`", + "desc": "

      The trace_events module could not be loaded because Node.js was compiled with\nthe --without-v8-platform flag.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRACE_EVENTS_UNAVAILABLE`" + }, + { + "textRaw": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`", + "name": "`err_transferring_externalized_sharedarraybuffer`", + "desc": "

      A SharedArrayBuffer whose memory is not managed by the JavaScript engine\nor by Node.js was encountered during serialization. Such a SharedArrayBuffer\ncannot be serialized.

      \n

      This can only happen when native addons create SharedArrayBuffers in\n\"externalized\" mode, or put existing SharedArrayBuffer into externalized mode.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`" + }, + { + "textRaw": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`", + "name": "`err_transform_already_transforming`", + "desc": "

      A Transform stream finished while it was still transforming.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`" + }, + { + "textRaw": "`ERR_TRANSFORM_WITH_LENGTH_0`", + "name": "`err_transform_with_length_0`", + "desc": "

      A Transform stream finished with data still in the write buffer.

      \n

      ", + "type": "module", + "displayName": "`ERR_TRANSFORM_WITH_LENGTH_0`" + }, + { + "textRaw": "`ERR_TTY_INIT_FAILED`", + "name": "`err_tty_init_failed`", + "desc": "

      The initialization of a TTY failed due to a system error.

      \n

      ", + "type": "module", + "displayName": "`ERR_TTY_INIT_FAILED`" + }, + { + "textRaw": "`ERR_UNAVAILABLE_DURING_EXIT`", + "name": "`err_unavailable_during_exit`", + "desc": "

      Function was called within a process.on('exit') handler that shouldn't be\ncalled within process.on('exit') handler.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNAVAILABLE_DURING_EXIT`" + }, + { + "textRaw": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`", + "name": "`err_uncaught_exception_capture_already_set`", + "desc": "

      process.setUncaughtExceptionCaptureCallback() was called twice,\nwithout first resetting the callback to null.

      \n

      This error is designed to prevent accidentally overwriting a callback registered\nfrom another module.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`" + }, + { + "textRaw": "`ERR_UNESCAPED_CHARACTERS`", + "name": "`err_unescaped_characters`", + "desc": "

      A string that contained unescaped characters was received.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNESCAPED_CHARACTERS`" + }, + { + "textRaw": "`ERR_UNHANDLED_ERROR`", + "name": "`err_unhandled_error`", + "desc": "

      An unhandled error occurred (for instance, when an 'error' event is emitted\nby an EventEmitter but an 'error' handler is not registered).

      \n

      ", + "type": "module", + "displayName": "`ERR_UNHANDLED_ERROR`" + }, + { + "textRaw": "`ERR_UNKNOWN_BUILTIN_MODULE`", + "name": "`err_unknown_builtin_module`", + "desc": "

      Used to identify a specific kind of internal Node.js error that should not\ntypically be triggered by user code. Instances of this error point to an\ninternal bug within the Node.js binary itself.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_BUILTIN_MODULE`" + }, + { + "textRaw": "`ERR_UNKNOWN_CREDENTIAL`", + "name": "`err_unknown_credential`", + "desc": "

      A Unix group or user identifier that does not exist was passed.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_CREDENTIAL`" + }, + { + "textRaw": "`ERR_UNKNOWN_ENCODING`", + "name": "`err_unknown_encoding`", + "desc": "

      An invalid or unknown encoding option was passed to an API.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_ENCODING`" + }, + { + "textRaw": "`ERR_UNKNOWN_FILE_EXTENSION`", + "name": "`err_unknown_file_extension`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An attempt was made to load a module with an unknown or unsupported file\nextension.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_FILE_EXTENSION`" + }, + { + "textRaw": "`ERR_UNKNOWN_MODULE_FORMAT`", + "name": "`err_unknown_module_format`", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      An attempt was made to load a module with an unknown or unsupported format.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_MODULE_FORMAT`" + }, + { + "textRaw": "`ERR_UNKNOWN_SIGNAL`", + "name": "`err_unknown_signal`", + "desc": "

      An invalid or unknown process signal was passed to an API expecting a valid\nsignal (such as subprocess.kill()).

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_SIGNAL`" + }, + { + "textRaw": "`ERR_UNSUPPORTED_DIR_IMPORT`", + "name": "`err_unsupported_dir_import`", + "desc": "

      import a directory URL is unsupported. Instead,\nself-reference a package using its name and define a custom subpath in\nthe \"exports\" field of the package.json file.

      \n\n
      import './'; // unsupported\nimport './index.js'; // supported\nimport 'package-name'; // supported\n
      \n

      ", + "type": "module", + "displayName": "`ERR_UNSUPPORTED_DIR_IMPORT`" + }, + { + "textRaw": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`", + "name": "`err_unsupported_esm_url_scheme`", + "desc": "

      import with URL schemes other than file and data is unsupported.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`" + }, + { + "textRaw": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`", + "name": "`err_valid_performance_entry_type`", + "desc": "

      While using the Performance Timing API (perf_hooks), no valid performance\nentry types were found.

      \n

      ", + "type": "module", + "displayName": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`" + }, + { + "textRaw": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`", + "name": "`err_vm_dynamic_import_callback_missing`", + "desc": "

      A dynamic import callback was not specified.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`" + }, + { + "textRaw": "`ERR_VM_MODULE_ALREADY_LINKED`", + "name": "`err_vm_module_already_linked`", + "desc": "

      The module attempted to be linked is not eligible for linking, because of one of\nthe following reasons:

      \n
        \n
      • It has already been linked (linkingStatus is 'linked')
      • \n
      • It is being linked (linkingStatus is 'linking')
      • \n
      • Linking has failed for this module (linkingStatus is 'errored')
      • \n
      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_ALREADY_LINKED`" + }, + { + "textRaw": "`ERR_VM_MODULE_CACHED_DATA_REJECTED`", + "name": "`err_vm_module_cached_data_rejected`", + "desc": "

      The cachedData option passed to a module constructor is invalid.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_CACHED_DATA_REJECTED`" + }, + { + "textRaw": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`", + "name": "`err_vm_module_cannot_create_cached_data`", + "desc": "

      Cached data cannot be created for modules which have already been evaluated.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`" + }, + { + "textRaw": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`", + "name": "`err_vm_module_different_context`", + "desc": "

      The module being returned from the linker function is from a different context\nthan the parent module. Linked modules must share the same context.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`" + }, + { + "textRaw": "`ERR_VM_MODULE_LINKING_ERRORED`", + "name": "`err_vm_module_linking_errored`", + "desc": "

      The linker function returned a module for which linking has failed.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_LINKING_ERRORED`" + }, + { + "textRaw": "`ERR_VM_MODULE_NOT_MODULE`", + "name": "`err_vm_module_not_module`", + "desc": "

      The fulfilled value of a linking promise is not a vm.Module object.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_NOT_MODULE`" + }, + { + "textRaw": "`ERR_VM_MODULE_STATUS`", + "name": "`err_vm_module_status`", + "desc": "

      The current module's status does not allow for this operation. The specific\nmeaning of the error depends on the specific function.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_STATUS`" + }, + { + "textRaw": "`ERR_WASI_ALREADY_STARTED`", + "name": "`err_wasi_already_started`", + "desc": "

      The WASI instance has already started.

      \n

      ", + "type": "module", + "displayName": "`ERR_WASI_ALREADY_STARTED`" + }, + { + "textRaw": "`ERR_WASI_NOT_STARTED`", + "name": "`err_wasi_not_started`", + "desc": "

      The WASI instance has not been started.

      \n

      ", + "type": "module", + "displayName": "`ERR_WASI_NOT_STARTED`" + }, + { + "textRaw": "`ERR_WORKER_INIT_FAILED`", + "name": "`err_worker_init_failed`", + "desc": "

      The Worker initialization failed.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_INIT_FAILED`" + }, + { + "textRaw": "`ERR_WORKER_INVALID_EXEC_ARGV`", + "name": "`err_worker_invalid_exec_argv`", + "desc": "

      The execArgv option passed to the Worker constructor contains\ninvalid flags.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_INVALID_EXEC_ARGV`" + }, + { + "textRaw": "`ERR_WORKER_NOT_RUNNING`", + "name": "`err_worker_not_running`", + "desc": "

      An operation failed because the Worker instance is not currently running.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_NOT_RUNNING`" + }, + { + "textRaw": "`ERR_WORKER_OUT_OF_MEMORY`", + "name": "`err_worker_out_of_memory`", + "desc": "

      The Worker instance terminated because it reached its memory limit.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_OUT_OF_MEMORY`" + }, + { + "textRaw": "`ERR_WORKER_PATH`", + "name": "`err_worker_path`", + "desc": "

      The path for the main script of a worker is neither an absolute path\nnor a relative path starting with ./ or ../.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_PATH`" + }, + { + "textRaw": "`ERR_WORKER_UNSERIALIZABLE_ERROR`", + "name": "`err_worker_unserializable_error`", + "desc": "

      All attempts at serializing an uncaught exception from a worker thread failed.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_UNSERIALIZABLE_ERROR`" + }, + { + "textRaw": "`ERR_WORKER_UNSUPPORTED_EXTENSION`", + "name": "`err_worker_unsupported_extension`", + "desc": "

      The pathname used for the main script of a worker has an\nunknown file extension.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_UNSUPPORTED_EXTENSION`" + }, + { + "textRaw": "`ERR_WORKER_UNSUPPORTED_OPERATION`", + "name": "`err_worker_unsupported_operation`", + "desc": "

      The requested functionality is not supported in worker threads.

      \n

      ", + "type": "module", + "displayName": "`ERR_WORKER_UNSUPPORTED_OPERATION`" + }, + { + "textRaw": "`ERR_ZLIB_INITIALIZATION_FAILED`", + "name": "`err_zlib_initialization_failed`", + "desc": "

      Creation of a zlib object failed due to incorrect configuration.

      \n

      ", + "type": "module", + "displayName": "`ERR_ZLIB_INITIALIZATION_FAILED`" + }, + { + "textRaw": "`HPE_HEADER_OVERFLOW`", + "name": "`hpe_header_overflow`", + "meta": { + "changes": [ + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/commit/186035243fad247e3955f", + "description": "Max header size in `http_parser` was set to 8KB." + } + ] + }, + "desc": "

      Too much HTTP header data was received. In order to protect against malicious or\nmalconfigured clients, if more than 8KB of HTTP header data is received then\nHTTP parsing will abort without a request or response object being created, and\nan Error with this code will be emitted.

      \n

      ", + "type": "module", + "displayName": "`HPE_HEADER_OVERFLOW`" + }, + { + "textRaw": "`HPE_UNEXPECTED_CONTENT_LENGTH`", + "name": "`hpe_unexpected_content_length`", + "desc": "

      Server is sending both a Content-Length header and Transfer-Encoding: chunked.

      \n

      Transfer-Encoding: chunked allows the server to maintain an HTTP persistent\nconnection for dynamically generated content.\nIn this case, the Content-Length HTTP header cannot be used.

      \n

      Use Content-Length or Transfer-Encoding: chunked.

      \n

      ", + "type": "module", + "displayName": "`HPE_UNEXPECTED_CONTENT_LENGTH`" + }, + { + "textRaw": "`MODULE_NOT_FOUND`", + "name": "`module_not_found`", + "meta": { + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25690", + "description": "Added `requireStack` property." + } + ] + }, + "desc": "

      A module file could not be resolved while attempting a require() or\nimport operation.

      ", + "type": "module", + "displayName": "`MODULE_NOT_FOUND`" + } + ], + "type": "misc", + "displayName": "Node.js error codes" + }, + { + "textRaw": "Legacy Node.js error codes", + "name": "legacy_node.js_error_codes", + "stability": 0, + "stabilityText": "Deprecated. These error codes are either inconsistent, or have\nbeen removed.", + "desc": "

      ", + "modules": [ + { + "textRaw": "`ERR_CANNOT_TRANSFER_OBJECT`", + "name": "`err_cannot_transfer_object`", + "desc": "\n

      The value passed to postMessage() contained an object that is not supported\nfor transferring.

      \n

      ", + "type": "module", + "displayName": "`ERR_CANNOT_TRANSFER_OBJECT`" + }, + { + "textRaw": "`ERR_CLOSED_MESSAGE_PORT`", + "name": "`err_closed_message_port`", + "meta": { + "added": [ + "v10.5.0" + ], + "removed": [ + "v11.12.0" + ], + "changes": [] + }, + "desc": "

      There was an attempt to use a MessagePort instance in a closed\nstate, usually after .close() has been called.

      \n

      ", + "type": "module", + "displayName": "`ERR_CLOSED_MESSAGE_PORT`" + }, + { + "textRaw": "`ERR_CRYPTO_HASH_DIGEST_NO_UTF16`", + "name": "`err_crypto_hash_digest_no_utf16`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      The UTF-16 encoding was used with hash.digest(). While the\nhash.digest() method does allow an encoding argument to be passed in,\ncausing the method to return a string rather than a Buffer, the UTF-16\nencoding (e.g. ucs or utf16le) is not supported.

      \n

      ", + "type": "module", + "displayName": "`ERR_CRYPTO_HASH_DIGEST_NO_UTF16`" + }, + { + "textRaw": "`ERR_HTTP2_FRAME_ERROR`", + "name": "`err_http2_frame_error`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a failure occurs sending an individual frame on the HTTP/2\nsession.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_FRAME_ERROR`" + }, + { + "textRaw": "`ERR_HTTP2_HEADERS_OBJECT`", + "name": "`err_http2_headers_object`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an HTTP/2 Headers Object is expected.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADERS_OBJECT`" + }, + { + "textRaw": "`ERR_HTTP2_HEADER_REQUIRED`", + "name": "`err_http2_header_required`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a required header is missing in an HTTP/2 message.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_HEADER_REQUIRED`" + }, + { + "textRaw": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`", + "name": "`err_http2_info_headers_after_respond`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      HTTP/2 informational headers must only be sent prior to calling the\nHttp2Stream.prototype.respond() method.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`" + }, + { + "textRaw": "`ERR_HTTP2_STREAM_CLOSED`", + "name": "`err_http2_stream_closed`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an action has been performed on an HTTP/2 Stream that has already\nbeen closed.

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP2_STREAM_CLOSED`" + }, + { + "textRaw": "`ERR_HTTP_INVALID_CHAR`", + "name": "`err_http_invalid_char`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an invalid character is found in an HTTP response status message\n(reason phrase).

      \n

      ", + "type": "module", + "displayName": "`ERR_HTTP_INVALID_CHAR`" + }, + { + "textRaw": "`ERR_INDEX_OUT_OF_RANGE`", + "name": "`err_index_out_of_range`", + "meta": { + "added": [ + "v10.0.0" + ], + "removed": [ + "v11.0.0" + ], + "changes": [] + }, + "desc": "

      A given index was out of the accepted range (e.g. negative offsets).

      \n

      ", + "type": "module", + "displayName": "`ERR_INDEX_OUT_OF_RANGE`" + }, + { + "textRaw": "`ERR_NAPI_CONS_PROTOTYPE_OBJECT`", + "name": "`err_napi_cons_prototype_object`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used by the N-API when Constructor.prototype is not an object.

      \n

      ", + "type": "module", + "displayName": "`ERR_NAPI_CONS_PROTOTYPE_OBJECT`" + }, + { + "textRaw": "`ERR_NO_LONGER_SUPPORTED`", + "name": "`err_no_longer_supported`", + "desc": "

      A Node.js API was called in an unsupported manner, such as\nBuffer.write(string, encoding, offset[, length]).

      \n

      ", + "type": "module", + "displayName": "`ERR_NO_LONGER_SUPPORTED`" + }, + { + "textRaw": "`ERR_OUTOFMEMORY`", + "name": "`err_outofmemory`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used generically to identify that an operation caused an out of memory\ncondition.

      \n

      ", + "type": "module", + "displayName": "`ERR_OUTOFMEMORY`" + }, + { + "textRaw": "`ERR_PARSE_HISTORY_DATA`", + "name": "`err_parse_history_data`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      The repl module was unable to parse data from the REPL history file.

      \n

      ", + "type": "module", + "displayName": "`ERR_PARSE_HISTORY_DATA`" + }, + { + "textRaw": "`ERR_STDERR_CLOSE`", + "name": "`err_stderr_close`", + "meta": { + "removed": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/23053", + "description": "Rather than emitting an error, `process.stderr.end()` now only closes the stream side but not the underlying resource, making this error obsolete." + } + ] + }, + "desc": "

      An attempt was made to close the process.stderr stream. By design, Node.js\ndoes not allow stdout or stderr streams to be closed by user code.

      \n

      ", + "type": "module", + "displayName": "`ERR_STDERR_CLOSE`" + }, + { + "textRaw": "`ERR_STDOUT_CLOSE`", + "name": "`err_stdout_close`", + "meta": { + "removed": [ + "v10.12.0" + ], + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/23053", + "description": "Rather than emitting an error, `process.stderr.end()` now only closes the stream side but not the underlying resource, making this error obsolete." + } + ] + }, + "desc": "

      An attempt was made to close the process.stdout stream. By design, Node.js\ndoes not allow stdout or stderr streams to be closed by user code.

      \n

      ", + "type": "module", + "displayName": "`ERR_STDOUT_CLOSE`" + }, + { + "textRaw": "`ERR_STREAM_READ_NOT_IMPLEMENTED`", + "name": "`err_stream_read_not_implemented`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an attempt is made to use a readable stream that has not implemented\nreadable._read().

      \n

      ", + "type": "module", + "displayName": "`ERR_STREAM_READ_NOT_IMPLEMENTED`" + }, + { + "textRaw": "`ERR_TLS_RENEGOTIATION_FAILED`", + "name": "`err_tls_renegotiation_failed`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a TLS renegotiation request has failed in a non-specific way.

      \n

      ", + "type": "module", + "displayName": "`ERR_TLS_RENEGOTIATION_FAILED`" + }, + { + "textRaw": "`ERR_UNKNOWN_BUILTIN_MODULE`", + "name": "`err_unknown_builtin_module`", + "meta": { + "added": [ + "v8.0.0" + ], + "removed": [ + "v9.0.0" + ], + "changes": [] + }, + "desc": "

      The 'ERR_UNKNOWN_BUILTIN_MODULE' error code is used to identify a specific\nkind of internal Node.js error that should not typically be triggered by user\ncode. Instances of this error point to an internal bug within the Node.js\nbinary itself.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_BUILTIN_MODULE`" + }, + { + "textRaw": "`ERR_UNKNOWN_STDIN_TYPE`", + "name": "`err_unknown_stdin_type`", + "meta": { + "added": [ + "v8.0.0" + ], + "removed": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      An attempt was made to launch a Node.js process with an unknown stdin file\ntype. This error is usually an indication of a bug within Node.js itself,\nalthough it is possible for user code to trigger it.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_STDIN_TYPE`" + }, + { + "textRaw": "`ERR_UNKNOWN_STREAM_TYPE`", + "name": "`err_unknown_stream_type`", + "meta": { + "added": [ + "v8.0.0" + ], + "removed": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

      An attempt was made to launch a Node.js process with an unknown stdout or\nstderr file type. This error is usually an indication of a bug within Node.js\nitself, although it is possible for user code to trigger it.

      \n

      ", + "type": "module", + "displayName": "`ERR_UNKNOWN_STREAM_TYPE`" + }, + { + "textRaw": "`ERR_V8BREAKITERATOR`", + "name": "`err_v8breakiterator`", + "desc": "

      The V8 BreakIterator API was used but the full ICU data set is not installed.

      \n

      ", + "type": "module", + "displayName": "`ERR_V8BREAKITERATOR`" + }, + { + "textRaw": "`ERR_VALUE_OUT_OF_RANGE`", + "name": "`err_value_out_of_range`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when a given value is out of the accepted range.

      \n

      ", + "type": "module", + "displayName": "`ERR_VALUE_OUT_OF_RANGE`" + }, + { + "textRaw": "`ERR_VM_MODULE_NOT_LINKED`", + "name": "`err_vm_module_not_linked`", + "desc": "

      The module must be successfully linked before instantiation.

      \n

      ", + "type": "module", + "displayName": "`ERR_VM_MODULE_NOT_LINKED`" + }, + { + "textRaw": "`ERR_ZLIB_BINDING_CLOSED`", + "name": "`err_zlib_binding_closed`", + "meta": { + "added": [ + "v9.0.0" + ], + "removed": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Used when an attempt is made to use a zlib object after it has already been\nclosed.

      ", + "type": "module", + "displayName": "`ERR_ZLIB_BINDING_CLOSED`" + } + ], + "type": "misc", + "displayName": "Legacy Node.js error codes" + } + ], + "classes": [ + { + "textRaw": "Class: `Error`", + "type": "class", + "name": "Error", + "desc": "

      A generic JavaScript <Error> object that does not denote any specific\ncircumstance of why the error occurred. Error objects capture a \"stack trace\"\ndetailing the point in the code at which the Error was instantiated, and may\nprovide a text description of the error.

      \n

      All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

      ", + "methods": [ + { + "textRaw": "`Error.captureStackTrace(targetObject[, constructorOpt])`", + "type": "method", + "name": "captureStackTrace", + "signatures": [ + { + "params": [ + { + "textRaw": "`targetObject` {Object}", + "name": "targetObject", + "type": "Object" + }, + { + "textRaw": "`constructorOpt` {Function}", + "name": "constructorOpt", + "type": "Function" + } + ] + } + ], + "desc": "

      Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

      \n
      const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack;  // Similar to `new Error().stack`\n
      \n

      The first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.

      \n

      The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

      \n

      The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:

      \n
      function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
      " + } + ], + "properties": [ + { + "textRaw": "`stackTraceLimit` {number}", + "type": "number", + "name": "stackTraceLimit", + "desc": "

      The Error.stackTraceLimit property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack or\nError.captureStackTrace(obj)).

      \n

      The default value is 10 but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.

      \n

      If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string label that identifies the kind of error.\nerror.code is the most stable way to identify an error. It will only change\nbetween major versions of Node.js. In contrast, error.message strings may\nchange between any versions of Node.js. See Node.js error codes for details\nabout specific codes.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      The error.message property is the string description of the error as set by\ncalling new Error(message). The message passed to the constructor will also\nappear in the first line of the stack trace of the Error, however changing\nthis property after the Error object is created may not change the first\nline of the stack trace (for example, when error.stack is read before this\nproperty is changed).

      \n
      const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
      " + }, + { + "textRaw": "`stack` {string}", + "type": "string", + "name": "stack", + "desc": "

      The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.

      \n
      Error: Things keep happening!\n   at /home/gbusey/file.js:525:2\n   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n   at increaseSynergy (/home/gbusey/actors.js:701:6)\n
      \n

      The first line is formatted as <error class name>: <error message>, and\nis followed by a series of stack frames (each line beginning with \"at \").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.

      \n

      Frames are only generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called cheetahify which\nitself calls a JavaScript function, the frame representing the cheetahify call\nwill not be present in the stack traces:

      \n
      const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n  // `cheetahify()` *synchronously* calls speedy.\n  cheetahify(function speedy() {\n    throw new Error('oh no!');\n  });\n}\n\nmakeFaster();\n// will throw:\n//   /home/gbusey/file.js:6\n//       throw new Error('oh no!');\n//           ^\n//   Error: oh no!\n//       at speedy (/home/gbusey/file.js:6:11)\n//       at makeFaster (/home/gbusey/file.js:5:3)\n//       at Object.<anonymous> (/home/gbusey/file.js:10:1)\n//       at Module._compile (module.js:456:26)\n//       at Object.Module._extensions..js (module.js:474:10)\n//       at Module.load (module.js:356:32)\n//       at Function.Module._load (module.js:312:12)\n//       at Function.Module.runMain (module.js:497:10)\n//       at startup (node.js:119:16)\n//       at node.js:906:3\n
      \n

      The location information will be one of:

      \n
        \n
      • native, if the frame represents a call internal to V8 (as in [].forEach).
      • \n
      • plain-filename.js:line:column, if the frame represents a call internal\nto Node.js.
      • \n
      • /absolute/path/to/file.js:line:column, if the frame represents a call in\na user program, or its dependencies.
      • \n
      \n

      The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

      \n

      The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit or the number of available frames on the current event\nloop tick.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ], + "desc": "

      Creates a new Error object and sets the error.message property to the\nprovided text message. If an object is passed as message, the text message\nis generated by calling message.toString(). The error.stack property will\nrepresent the point in the code at which new Error() was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit, whichever is smaller.

      " + } + ] + }, + { + "textRaw": "Class: `AssertionError`", + "type": "class", + "name": "AssertionError", + "desc": "\n

      Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.

      " + }, + { + "textRaw": "Class: `RangeError`", + "type": "class", + "name": "RangeError", + "desc": "\n

      Indicates that a provided argument was not within the set or range of\nacceptable values for a function; whether that is a numeric range, or\noutside the set of options for a given function parameter.

      \n
      require('net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n
      \n

      Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

      " + }, + { + "textRaw": "Class: `ReferenceError`", + "type": "class", + "name": "ReferenceError", + "desc": "\n

      Indicates that an attempt is being made to access a variable that is not\ndefined. Such errors commonly indicate typos in code, or an otherwise broken\nprogram.

      \n

      While client code may generate and propagate these errors, in practice, only V8\nwill do so.

      \n
      doesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n
      \n

      Unless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.

      " + }, + { + "textRaw": "Class: `SyntaxError`", + "type": "class", + "name": "SyntaxError", + "desc": "\n

      Indicates that a program is not valid JavaScript. These errors may only be\ngenerated and propagated as a result of code evaluation. Code evaluation may\nhappen as a result of eval, Function, require, or vm. These errors\nare almost always indicative of a broken program.

      \n
      try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n  // 'err' will be a SyntaxError.\n}\n
      \n

      SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

      " + }, + { + "textRaw": "Class: `SystemError`", + "type": "class", + "name": "SystemError", + "desc": "\n

      Node.js generates system errors when exceptions occur within its runtime\nenvironment. These usually occur when an application violates an operating\nsystem constraint. For example, a system error will occur if an application\nattempts to read a file that does not exist.

      \n
        \n
      • address <string> If present, the address to which a network connection\nfailed
      • \n
      • code <string> The string error code
      • \n
      • dest <string> If present, the file path destination when reporting a file\nsystem error
      • \n
      • errno <number> | <string> The system-provided error number
      • \n
      • info <Object> If present, extra details about the error condition
      • \n
      • message <string> A system-provided human-readable description of the error
      • \n
      • path <string> If present, the file path when reporting a file system error
      • \n
      • port <number> If present, the network connection port that is not available
      • \n
      • syscall <string> The name of the system call that triggered the error
      • \n
      ", + "properties": [ + { + "textRaw": "`address` {string}", + "type": "string", + "name": "address", + "desc": "

      If present, error.address is a string describing the address to which a\nnetwork connection failed.

      " + }, + { + "textRaw": "`code` {string}", + "type": "string", + "name": "code", + "desc": "

      The error.code property is a string representing the error code.

      " + }, + { + "textRaw": "`dest` {string}", + "type": "string", + "name": "dest", + "desc": "

      If present, error.dest is the file path destination when reporting a file\nsystem error.

      " + }, + { + "textRaw": "`errno` {string|number}", + "type": "string|number", + "name": "errno", + "desc": "

      The error.errno property is a number or a string. If it is a number, it is a\nnegative value which corresponds to the error code defined in\nlibuv Error handling. See the libuv errno.h header file\n(deps/uv/include/uv/errno.h in the Node.js source tree) for details. In case\nof a string, it is the same as error.code.

      " + }, + { + "textRaw": "`info` {Object}", + "type": "Object", + "name": "info", + "desc": "

      If present, error.info is an object with details about the error condition.

      " + }, + { + "textRaw": "`message` {string}", + "type": "string", + "name": "message", + "desc": "

      error.message is a system-provided human-readable description of the error.

      " + }, + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "desc": "

      If present, error.path is a string containing a relevant invalid pathname.

      " + }, + { + "textRaw": "`port` {number}", + "type": "number", + "name": "port", + "desc": "

      If present, error.port is the network connection port that is not available.

      " + }, + { + "textRaw": "`syscall` {string}", + "type": "string", + "name": "syscall", + "desc": "

      The error.syscall property is a string describing the syscall that failed.

      " + } + ], + "modules": [ + { + "textRaw": "Common system errors", + "name": "common_system_errors", + "desc": "

      This is a list of system errors commonly-encountered when writing a Node.js\nprogram. For a comprehensive list, see the errno(3) man page.

      \n
        \n
      • \n

        EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.

        \n
      • \n
      • \n

        EADDRINUSE (Address already in use): An attempt to bind a server\n(net, http, or https) to a local address failed due to\nanother server on the local system already occupying that address.

        \n
      • \n
      • \n

        ECONNREFUSED (Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.

        \n
      • \n
      • \n

        ECONNRESET (Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http\nand net modules.

        \n
      • \n
      • \n

        EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.

        \n
      • \n
      • \n

        EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.

        \n
      • \n
      • \n

        EMFILE (Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, macOS) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048 in the same shell that will run the Node.js process.

        \n
      • \n
      • \n

        ENOENT (No such file or directory): Commonly raised by fs operations\nto indicate that a component of the specified pathname does not exist. No\nentity (file or directory) could be found by the given path.

        \n
      • \n
      • \n

        ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.

        \n
      • \n
      • \n

        ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.

        \n
      • \n
      • \n

        ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

        \n
      • \n
      • \n

        EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.

        \n
      • \n
      • \n

        EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net and\nhttp layers, indicative that the remote side of the stream being\nwritten to has been closed.

        \n
      • \n
      • \n

        ETIMEDOUT (Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http or net. Often a sign that a socket.end()\nwas not properly called.

        \n
      • \n
      ", + "type": "module", + "displayName": "Common system errors" + } + ] + }, + { + "textRaw": "Class: `TypeError`", + "type": "class", + "name": "TypeError", + "desc": "\n

      Indicates that a provided argument is not an allowable type. For example,\npassing a function to a parameter which expects a string would be a TypeError.

      \n
      require('url').parse(() => { });\n// Throws TypeError, since it expected a string.\n
      \n

      Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

      " + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/esm.html b/doc/api/esm.html new file mode 100644 index 0000000000000000000000000000000000000000..e9a68596ee2fa62be2d378b805346bb62585019d --- /dev/null +++ b/doc/api/esm.html @@ -0,0 +1,1484 @@ + + + + + + + Modules: ECMAScript modules | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Modules: ECMAScript modules#

      + + + +

      Stability: 2 - Stable

      +

      Introduction#

      + +

      ECMAScript modules are the official standard format to package JavaScript +code for reuse. Modules are defined using a variety of import and +export statements.

      +

      The following example of an ES module exports a function:

      +
      // addTwo.mjs
      +function addTwo(num) {
      +  return num + 2;
      +}
      +
      +export { addTwo };
      +

      The following example of an ES module imports the function from addTwo.mjs:

      +
      // app.mjs
      +import { addTwo } from './addTwo.mjs';
      +
      +// Prints: 6
      +console.log(addTwo(4));
      +

      Node.js fully supports ECMAScript modules as they are currently specified and +provides interoperability between them and its original module format, +CommonJS.

      + +

      + +

      +

      Enabling#

      + +

      Node.js treats JavaScript code as CommonJS modules by default. +Authors can tell Node.js to treat JavaScript code as ECMAScript modules +via the .mjs file extension, the package.json "type" field, or the +--input-type flag. See +Modules: Packages for more +details.

      + +

      + + + + + + + + + + + + +

      +

      Packages#

      +

      This section was moved to Modules: Packages.

      +

      import Specifiers#

      +

      Terminology#

      +

      The specifier of an import statement is the string after the from keyword, +e.g. 'path' in import { sep } from 'path'. Specifiers are also used in +export from statements, and as the argument to an import() expression.

      +

      There are four types of specifiers:

      +
        +
      • +

        Bare specifiers like 'some-package'. They refer to an entry point of a +package by the package name.

        +
      • +
      • +

        Deep import specifiers like 'some-package/lib/shuffle.mjs'. They refer to +a path within a package prefixed by the package name.

        +
      • +
      • +

        Relative specifiers like './startup.js' or '../config.mjs'. They refer +to a path relative to the location of the importing file.

        +
      • +
      • +

        Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer +directly and explicitly to a full path.

        +
      • +
      +

      Bare specifiers, and the bare specifier portion of deep import specifiers, are +strings; but everything else in a specifier is a URL.

      +

      file:, node:, and data: URLs are supported. A specifier like +'https://example.com/app.js' may be supported by browsers but it is not +supported in Node.js.

      +

      Specifiers may not begin with / or //. These are reserved for potential +future use. The root of the current volume may be referenced via file:///.

      +

      node: Imports#

      + +

      node: URLs are supported as a means to load Node.js builtin modules. This +URL scheme allows for builtin modules to be referenced by valid absolute URL +strings.

      +
      import fs from 'node:fs/promises';
      +

      data: Imports#

      + +

      data: URLs are supported for importing with the following MIME types:

      +
        +
      • text/javascript for ES Modules
      • +
      • application/json for JSON
      • +
      • application/wasm for Wasm
      • +
      +

      data: URLs only resolve Bare specifiers for builtin modules +and Absolute specifiers. Resolving +Relative specifiers does not work because data: is not a +special scheme. For example, attempting to load ./foo +from data:text/javascript,import "./foo"; fails to resolve because there +is no concept of relative resolution for data: URLs. An example of a data: +URLs being used is:

      +
      import 'data:text/javascript,console.log("hello!");';
      +import _ from 'data:application/json,"world!"';
      +

      import.meta#

      + +

      The import.meta metaproperty is an Object that contains the following +property:

      +
        +
      • url <string> The absolute file: URL of the module.
      • +
      +

      Differences between ES modules and CommonJS#

      +

      Mandatory file extensions#

      +

      A file extension must be provided when using the import keyword. Directory +indexes (e.g. './startup/index.js') must also be fully specified.

      +

      This behavior matches how import behaves in browser environments, assuming a +typically configured server.

      +

      No NODE_PATH#

      +

      NODE_PATH is not part of resolving import specifiers. Please use symlinks +if this behavior is desired.

      +

      No require, exports, module.exports, __filename, __dirname#

      +

      These CommonJS variables are not available in ES modules.

      +

      require can be imported into an ES module using module.createRequire().

      +

      Equivalents of __filename and __dirname can be created inside of each file +via import.meta.url.

      +
      import { fileURLToPath } from 'url';
      +import { dirname } from 'path';
      +
      +const __filename = fileURLToPath(import.meta.url);
      +const __dirname = dirname(__filename);
      +

      No require.resolve#

      +

      Former use cases relying on require.resolve to determine the resolved path +of a module can be supported via import.meta.resolve, which is experimental +and supported via the --experimental-import-meta-resolve flag:

      +
      (async () => {
      +  const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
      +})();
      +

      import.meta.resolve also accepts a second argument which is the parent module +from which to resolve from:

      +
      (async () => {
      +  // Equivalent to import.meta.resolve('./dep')
      +  await import.meta.resolve('./dep', import.meta.url);
      +})();
      +

      This function is asynchronous because the ES module resolver in Node.js is +asynchronous. With the introduction of Top-Level Await, these use cases +will be easier as they won't require an async function wrapper.

      +

      No require.extensions#

      +

      require.extensions is not used by import. The expectation is that loader +hooks can provide this workflow in the future.

      +

      No require.cache#

      +

      require.cache is not used by import. It has a separate cache.

      +

      URL-based paths#

      +

      ES modules are resolved and cached based upon +URL semantics. This means that files containing +special characters such as # and ? need to be escaped.

      +

      Modules are loaded multiple times if the import specifier used to resolve +them has a different query or fragment.

      +
      import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1"
      +import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2"
      +

      For now, only modules using the file: protocol can be loaded.

      +

      Interoperability with CommonJS#

      +

      require#

      +

      require always treats the files it references as CommonJS. This applies +whether require is used the traditional way within a CommonJS environment, or +in an ES module environment using module.createRequire().

      +

      To include an ES module into CommonJS, use import().

      +

      import statements#

      +

      An import statement can reference an ES module or a CommonJS module. +import statements are permitted only in ES modules. For similar functionality +in CommonJS, see import().

      +

      When importing CommonJS modules, the +module.exports object is provided as the default export. Named exports may be +available, provided by static analysis as a convenience for better ecosystem +compatibility.

      +

      Additional experimental flags are available for importing +Wasm modules or +JSON modules. For importing native modules or +JSON modules unflagged, see module.createRequire().

      +

      The specifier of an import statement (the string after the from keyword) +can either be an URL-style relative path like './file.mjs' or a package name +like 'fs'.

      +

      Like in CommonJS, files within packages can be accessed by appending a path to +the package name; unless the package’s package.json contains an +"exports" field, in which case files within packages need to be accessed +via the path defined in "exports".

      +
      import { sin, cos } from 'geometry/trigonometry-functions.mjs';
      +

      import() expressions#

      +

      Dynamic import() is supported in both CommonJS and ES modules. It can be +used to include ES module files from CommonJS code.

      +

      CommonJS Namespaces#

      +

      CommonJS modules consist of a module.exports object which can be of any type.

      +

      When importing a CommonJS module, it can be reliably imported using the ES +module default import or its corresponding sugar syntax:

      + +
      import { default as cjs } from 'cjs';
      +
      +// The following import statement is "syntax sugar" (equivalent but sweeter)
      +// for `{ default as cjsSugar }` in the above import statement:
      +import cjsSugar from 'cjs';
      +
      +console.log(cjs);
      +console.log(cjs === cjsSugar);
      +// Prints:
      +//   <module.exports>
      +//   true
      +

      The ECMAScript Module Namespace representation of a CommonJS module is always +a namespace with a default export key pointing to the CommonJS +module.exports value.

      +

      This Module Namespace Exotic Object can be directly observed either when using +import * as m from 'cjs' or a dynamic import:

      + +
      import * as m from 'cjs';
      +console.log(m);
      +console.log(m === await import('cjs'));
      +// Prints:
      +//   [Module] { default: <module.exports> }
      +//   true
      +

      For better compatibility with existing usage in the JS ecosystem, Node.js +in addition attempts to determine the CommonJS named exports of every imported +CommonJS module to provide them as separate ES module exports using a static +analysis process.

      +

      For example, consider a CommonJS module written:

      +
      // cjs.cjs
      +exports.name = 'exported';
      +

      The preceding module supports named imports in ES modules:

      + +
      import { name } from './cjs.cjs';
      +console.log(name);
      +// Prints: 'exported'
      +
      +import cjs from './cjs.cjs';
      +console.log(cjs);
      +// Prints: { name: 'exported' }
      +
      +import * as m from './cjs.cjs';
      +console.log(m);
      +// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }
      +

      As can be seen from the last example of the Module Namespace Exotic Object being +logged, the name export is copied off of the module.exports object and set +directly on the ES module namespace when the module is imported.

      +

      Live binding updates or new exports added to module.exports are not detected +for these named exports.

      +

      The detection of named exports is based on common syntax patterns but does not +always correctly detect named exports. In these cases, using the default +import form described above can be a better option.

      +

      Named exports detection covers many common export patterns, reexport patterns +and build tool and transpiler outputs. See cjs-module-lexer for the exact +semantics implemented.

      +

      Builtin modules#

      +

      Core modules provide named exports of their public API. A +default export is also provided which is the value of the CommonJS exports. +The default export can be used for, among other things, modifying the named +exports. Named exports of builtin modules are updated only by calling +module.syncBuiltinESMExports().

      +
      import EventEmitter from 'events';
      +const e = new EventEmitter();
      +
      import { readFile } from 'fs';
      +readFile('./foo.txt', (err, source) => {
      +  if (err) {
      +    console.error(err);
      +  } else {
      +    console.log(source);
      +  }
      +});
      +
      import fs, { readFileSync } from 'fs';
      +import { syncBuiltinESMExports } from 'module';
      +
      +fs.readFileSync = () => Buffer.from('Hello, ESM');
      +syncBuiltinESMExports();
      +
      +fs.readFileSync === readFileSync;
      +

      CommonJS, JSON, and native modules#

      +

      CommonJS, JSON, and native modules can be used with +module.createRequire().

      +
      // cjs.cjs
      +module.exports = 'cjs';
      +
      +// esm.mjs
      +import { createRequire } from 'module';
      +
      +const require = createRequire(import.meta.url);
      +
      +const cjs = require('./cjs.cjs');
      +cjs === 'cjs'; // true
      +

      Experimental JSON modules#

      +

      Currently importing JSON modules are only supported in the commonjs mode +and are loaded using the CJS loader. WHATWG JSON modules specification are +still being standardized, and are experimentally supported by including the +additional flag --experimental-json-modules when running Node.js.

      +

      When the --experimental-json-modules flag is included, both the +commonjs and module mode use the new experimental JSON +loader. The imported JSON only exposes a default. There is no +support for named exports. A cache entry is created in the CommonJS +cache to avoid duplication. The same object is returned in +CommonJS if the JSON module has already been imported from the +same path.

      +

      Assuming an index.mjs with

      + +
      import packageConfig from './package.json';
      +

      The --experimental-json-modules flag is needed for the module +to work.

      +
      node index.mjs # fails
      +node --experimental-json-modules index.mjs # works
      +

      Experimental Wasm modules#

      +

      Importing Web Assembly modules is supported under the +--experimental-wasm-modules flag, allowing any .wasm files to be +imported as normal modules while also supporting their module imports.

      +

      This integration is in line with the +ES Module Integration Proposal for Web Assembly.

      +

      For example, an index.mjs containing:

      +
      import * as M from './module.wasm';
      +console.log(M);
      +

      executed under:

      +
      node --experimental-wasm-modules index.mjs
      +

      would provide the exports interface for the instantiation of module.wasm.

      +

      Experimental loaders#

      +

      Note: This API is currently being redesigned and will still change.

      + +

      To customize the default module resolution, loader hooks can optionally be +provided via a --experimental-loader ./loader-name.mjs argument to Node.js.

      +

      When hooks are used they only apply to ES module loading and not to any +CommonJS modules loaded.

      +

      Hooks#

      +

      resolve(specifier, context, defaultResolve)#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The resolve hook returns the resolved file URL for a given module specifier +and parent URL. The module specifier is the string in an import statement or +import() expression, and the parent URL is the URL of the module that imported +this one, or undefined if this is the main entry point for the application.

      +

      The conditions property on the context is an array of conditions for +Conditional exports that apply to this resolution request. They can be used +for looking up conditional mappings elsewhere or to modify the list when calling +the default resolution logic.

      +

      The current package exports conditions are always in +the context.conditions array passed into the hook. To guarantee default +Node.js module specifier resolution behavior when calling defaultResolve, the +context.conditions array passed to it must include all elements of the +context.conditions array originally passed into the resolve hook.

      +
      /**
      + * @param {string} specifier
      + * @param {{
      + *   conditions: !Array<string>,
      + *   parentURL: !(string | undefined),
      + * }} context
      + * @param {Function} defaultResolve
      + * @returns {Promise<{ url: string }>}
      + */
      +export async function resolve(specifier, context, defaultResolve) {
      +  const { parentURL = null } = context;
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all specifiers, do some custom logic for resolving.
      +    // Always return an object of the form {url: <string>}.
      +    return {
      +      url: parentURL ?
      +        new URL(specifier, parentURL).href :
      +        new URL(specifier).href,
      +    };
      +  }
      +  if (Math.random() < 0.5) { // Another condition.
      +    // When calling `defaultResolve`, the arguments can be modified. In this
      +    // case it's adding another value for matching conditional exports.
      +    return defaultResolve(specifier, {
      +      ...context,
      +      conditions: [...context.conditions, 'another-condition'],
      +    });
      +  }
      +  // Defer to Node.js for all other specifiers.
      +  return defaultResolve(specifier, context, defaultResolve);
      +}
      +

      getFormat(url, context, defaultGetFormat)#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The getFormat hook provides a way to define a custom method of determining how +a URL should be interpreted. The format returned also affects what the +acceptable forms of source values are for a module when parsing. This can be one +of the following:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      formatDescriptionAcceptable Types For source Returned by getSource or transformSource
      'builtin'Load a Node.js builtin moduleNot applicable
      'dynamic'Use a dynamic instantiate hookNot applicable
      'commonjs'Load a Node.js CommonJS moduleNot applicable
      'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
      'module'Load an ES module{ string, ArrayBuffer, TypedArray }
      'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
      +

      Note: These types all correspond to classes defined in ECMAScript.

      + +

      Note: If the source value of a text-based format (i.e., 'json', 'module') is +not a string, it is converted to a string using util.TextDecoder.

      +
      /**
      + * @param {string} url
      + * @param {Object} context (currently empty)
      + * @param {Function} defaultGetFormat
      + * @returns {Promise<{ format: string }>}
      + */
      +export async function getFormat(url, context, defaultGetFormat) {
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all URLs, do some custom logic for determining format.
      +    // Always return an object of the form {format: <string>}, where the
      +    // format is one of the strings in the preceding table.
      +    return {
      +      format: 'module',
      +    };
      +  }
      +  // Defer to Node.js for all other URLs.
      +  return defaultGetFormat(url, context, defaultGetFormat);
      +}
      +

      getSource(url, context, defaultGetSource)#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The getSource hook provides a way to define a custom method for retrieving +the source code of an ES module specifier. This would allow a loader to +potentially avoid reading files from disk.

      +
      /**
      + * @param {string} url
      + * @param {{ format: string }} context
      + * @param {Function} defaultGetSource
      + * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
      + */
      +export async function getSource(url, context, defaultGetSource) {
      +  const { format } = context;
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all URLs, do some custom logic for retrieving the source.
      +    // Always return an object of the form {source: <string|buffer>}.
      +    return {
      +      source: '...',
      +    };
      +  }
      +  // Defer to Node.js for all other URLs.
      +  return defaultGetSource(url, context, defaultGetSource);
      +}
      +

      transformSource(source, context, defaultTransformSource)#

      +
      NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js
      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      The transformSource hook provides a way to modify the source code of a loaded +ES module file after the source string has been loaded but before Node.js has +done anything with it.

      +

      If this hook is used to convert unknown-to-Node.js file types into executable +JavaScript, a resolve hook is also necessary in order to register any +unknown-to-Node.js file extensions. See the transpiler loader example below.

      +
      /**
      + * @param {!(string | SharedArrayBuffer | Uint8Array)} source
      + * @param {{
      + *   format: string,
      + *   url: string,
      + * }} context
      + * @param {Function} defaultTransformSource
      + * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
      + */
      +export async function transformSource(source, context, defaultTransformSource) {
      +  const { url, format } = context;
      +  if (Math.random() > 0.5) { // Some condition.
      +    // For some or all URLs, do some custom logic for modifying the source.
      +    // Always return an object of the form {source: <string|buffer>}.
      +    return {
      +      source: '...',
      +    };
      +  }
      +  // Defer to Node.js for all other sources.
      +  return defaultTransformSource(source, context, defaultTransformSource);
      +}
      +

      getGlobalPreloadCode()#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      + +

      Sometimes it might be necessary to run some code inside of the same global scope +that the application runs in. This hook allows the return of a string that is +run as sloppy-mode script on startup.

      +

      Similar to how CommonJS wrappers work, the code runs in an implicit function +scope. The only argument is a require-like function that can be used to load +builtins like "fs": getBuiltin(request: string).

      +

      If the code needs more advanced require features, it has to construct +its own require using module.createRequire().

      +
      /**
      + * @returns {string} Code to run before application startup
      + */
      +export function getGlobalPreloadCode() {
      +  return `\
      +globalThis.someInjectedProperty = 42;
      +console.log('I just set some globals!');
      +
      +const { createRequire } = getBuiltin('module');
      +
      +const require = createRequire(process.cwd() + '/<preload>');
      +// [...]
      +`;
      +}
      +

      dynamicInstantiate hook#

      +
      +

      Note: The loaders API is being redesigned. This hook may disappear or its +signature may change. Do not rely on the API described below.

      +
      +

      To create a custom dynamic module that doesn't correspond to one of the +existing format interpretations, the dynamicInstantiate hook can be used. +This hook is called only for modules that return format: 'dynamic' from +the getFormat hook.

      +
      /**
      + * @param {string} url
      + * @returns {object} response
      + * @returns {array} response.exports
      + * @returns {function} response.execute
      + */
      +export async function dynamicInstantiate(url) {
      +  return {
      +    exports: ['customExportName'],
      +    execute: (exports) => {
      +      // Get and set functions provided for pre-allocated export names
      +      exports.customExportName.set('value');
      +    }
      +  };
      +}
      +

      With the list of module exports provided upfront, the execute function will +then be called at the exact point of module evaluation order for that module +in the import tree.

      +

      Examples#

      +

      The various loader hooks can be used together to accomplish wide-ranging +customizations of Node.js’ code loading and evaluation behaviors.

      +

      HTTPS loader#

      +

      In current Node.js, specifiers starting with https:// are unsupported. The +loader below registers hooks to enable rudimentary support for such specifiers. +While this may seem like a significant improvement to Node.js core +functionality, there are substantial downsides to actually using this loader: +performance is much slower than loading files from disk, there is no caching, +and there is no security.

      +
      // https-loader.mjs
      +import { get } from 'https';
      +
      +export function resolve(specifier, context, defaultResolve) {
      +  const { parentURL = null } = context;
      +
      +  // Normally Node.js would error on specifiers starting with 'https://', so
      +  // this hook intercepts them and converts them into absolute URLs to be
      +  // passed along to the later hooks below.
      +  if (specifier.startsWith('https://')) {
      +    return {
      +      url: specifier
      +    };
      +  } else if (parentURL && parentURL.startsWith('https://')) {
      +    return {
      +      url: new URL(specifier, parentURL).href
      +    };
      +  }
      +
      +  // Let Node.js handle all other specifiers.
      +  return defaultResolve(specifier, context, defaultResolve);
      +}
      +
      +export function getFormat(url, context, defaultGetFormat) {
      +  // This loader assumes all network-provided JavaScript is ES module code.
      +  if (url.startsWith('https://')) {
      +    return {
      +      format: 'module'
      +    };
      +  }
      +
      +  // Let Node.js handle all other URLs.
      +  return defaultGetFormat(url, context, defaultGetFormat);
      +}
      +
      +export function getSource(url, context, defaultGetSource) {
      +  // For JavaScript to be loaded over the network, we need to fetch and
      +  // return it.
      +  if (url.startsWith('https://')) {
      +    return new Promise((resolve, reject) => {
      +      get(url, (res) => {
      +        let data = '';
      +        res.on('data', (chunk) => data += chunk);
      +        res.on('end', () => resolve({ source: data }));
      +      }).on('error', (err) => reject(err));
      +    });
      +  }
      +
      +  // Let Node.js handle all other URLs.
      +  return defaultGetSource(url, context, defaultGetSource);
      +}
      +
      // main.mjs
      +import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
      +
      +console.log(VERSION);
      +

      With the preceding loader, running +node --experimental-loader ./https-loader.mjs ./main.mjs +prints the current version of CoffeeScript per the module at the URL in +main.mjs.

      +

      Transpiler loader#

      +

      Sources that are in formats Node.js doesn’t understand can be converted into +JavaScript using the transformSource hook. Before that hook gets called, +however, other hooks need to tell Node.js not to throw an error on unknown file +types; and to tell Node.js how to load this new file type.

      +

      This is less performant than transpiling source files before running +Node.js; a transpiler loader should only be used for development and testing +purposes.

      +
      // coffeescript-loader.mjs
      +import { URL, pathToFileURL } from 'url';
      +import CoffeeScript from 'coffeescript';
      +
      +const baseURL = pathToFileURL(`${process.cwd()}/`).href;
      +
      +// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.
      +const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;
      +
      +export function resolve(specifier, context, defaultResolve) {
      +  const { parentURL = baseURL } = context;
      +
      +  // Node.js normally errors on unknown file extensions, so return a URL for
      +  // specifiers ending in the CoffeeScript file extensions.
      +  if (extensionsRegex.test(specifier)) {
      +    return {
      +      url: new URL(specifier, parentURL).href
      +    };
      +  }
      +
      +  // Let Node.js handle all other specifiers.
      +  return defaultResolve(specifier, context, defaultResolve);
      +}
      +
      +export function getFormat(url, context, defaultGetFormat) {
      +  // Now that we patched resolve to let CoffeeScript URLs through, we need to
      +  // tell Node.js what format such URLs should be interpreted as. For the
      +  // purposes of this loader, all CoffeeScript URLs are ES modules.
      +  if (extensionsRegex.test(url)) {
      +    return {
      +      format: 'module'
      +    };
      +  }
      +
      +  // Let Node.js handle all other URLs.
      +  return defaultGetFormat(url, context, defaultGetFormat);
      +}
      +
      +export function transformSource(source, context, defaultTransformSource) {
      +  const { url, format } = context;
      +
      +  if (extensionsRegex.test(url)) {
      +    return {
      +      source: CoffeeScript.compile(source, { bare: true })
      +    };
      +  }
      +
      +  // Let Node.js handle all other sources.
      +  return defaultTransformSource(source, context, defaultTransformSource);
      +}
      +
      # main.coffee
      +import { scream } from './scream.coffee'
      +console.log scream 'hello, world'
      +
      +import { version } from 'process'
      +console.log "Brought to you by Node.js version #{version}"
      +
      # scream.coffee
      +export scream = (str) -> str.toUpperCase()
      +

      With the preceding loader, running +node --experimental-loader ./coffeescript-loader.mjs main.coffee +causes main.coffee to be turned into JavaScript after its source code is +loaded from disk but before Node.js executes it; and so on for any .coffee, +.litcoffee or .coffee.md files referenced via import statements of any +loaded file.

      +

      Resolution algorithm#

      +

      Features#

      +

      The resolver has the following properties:

      +
        +
      • FileURL-based resolution as is used by ES modules
      • +
      • Support for builtin module loading
      • +
      • Relative and absolute URL resolution
      • +
      • No default extensions
      • +
      • No folder mains
      • +
      • Bare specifier package resolution lookup through node_modules
      • +
      +

      Resolver algorithm#

      +

      The algorithm to load an ES module specifier is given through the +ESM_RESOLVE method below. It returns the resolved URL for a +module specifier relative to a parentURL.

      +

      The algorithm to determine the module format of a resolved URL is +provided by ESM_FORMAT, which returns the unique module +format for any file. The "module" format is returned for an ECMAScript +Module, while the "commonjs" format is used to indicate loading through the +legacy CommonJS loader. Additional formats such as "addon" can be extended in +future updates.

      +

      In the following algorithms, all subroutine errors are propagated as errors +of these top-level routines unless stated otherwise.

      +

      defaultConditions is the conditional environment name array, +["node", "import"].

      +

      The resolver can throw the following errors:

      +
        +
      • Invalid Module Specifier: Module specifier is an invalid URL, package name +or package subpath specifier.
      • +
      • Invalid Package Configuration: package.json configuration is invalid or +contains an invalid configuration.
      • +
      • Invalid Package Target: Package exports or imports define a target module +for the package that is an invalid type or string target.
      • +
      • Package Path Not Exported: Package exports do not define or permit a target +subpath in the package for the given module.
      • +
      • Package Import Not Defined: Package imports do not define the specifier.
      • +
      • Module Not Found: The package or module requested does not exist.
      • +
      +

      Resolver Algorithm Specification#

      +

      ESM_RESOLVE(specifier, parentURL)

      +
      +
        +
      1. Let resolved be undefined.
      2. +
      3. If specifier is a valid URL, then +
          +
        1. Set resolved to the result of parsing and reserializing +specifier as a URL.
        2. +
        +
      4. +
      5. Otherwise, if specifier starts with "/", "./" or "../", then +
          +
        1. Set resolved to the URL resolution of specifier relative to +parentURL.
        2. +
        +
      6. +
      7. Otherwise, if specifier starts with "#", then +
          +
        1. Set resolved to the destructured value of the result of +PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, +defaultConditions).
        2. +
        +
      8. +
      9. Otherwise, +
          +
        1. Note: specifier is now a bare specifier.
        2. +
        3. Set resolved the result of +PACKAGE_RESOLVE(specifier, parentURL).
        4. +
        +
      10. +
      11. If resolved contains any percent encodings of "/" or "\" ("%2f" +and "%5C" respectively), then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      12. +
      13. If the file at resolved is a directory, then +
          +
        1. Throw an Unsupported Directory Import error.
        2. +
        +
      14. +
      15. If the file at resolved does not exist, then +
          +
        1. Throw a Module Not Found error.
        2. +
        +
      16. +
      17. Set resolved to the real path of resolved.
      18. +
      19. Let format be the result of ESM_FORMAT(resolved).
      20. +
      21. Load resolved as module format, format.
      22. +
      23. Return resolved.
      24. +
      +
      +

      PACKAGE_RESOLVE(packageSpecifier, parentURL)

      +
      +
        +
      1. Let packageName be undefined.
      2. +
      3. If packageSpecifier is an empty string, then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      4. +
      5. If packageSpecifier does not start with "@", then +
          +
        1. Set packageName to the substring of packageSpecifier until the first +"/" separator or the end of the string.
        2. +
        +
      6. +
      7. Otherwise, +
          +
        1. If packageSpecifier does not contain a "/" separator, then +
            +
          1. Throw an Invalid Module Specifier error.
          2. +
          +
        2. +
        3. Set packageName to the substring of packageSpecifier +until the second "/" separator or the end of the string.
        4. +
        +
      8. +
      9. If packageName starts with "." or contains "\" or "%", then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      10. +
      11. Let packageSubpath be "." concatenated with the substring of +packageSpecifier from the position at the length of packageName.
      12. +
      13. Let selfUrl be the result of +PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
      14. +
      15. If selfUrl is not undefined, return selfUrl.
      16. +
      17. If packageSubpath is "." and packageName is a Node.js builtin +module, then +
          +
        1. Return the string "node:" concatenated with packageSpecifier.
        2. +
        +
      18. +
      19. While parentURL is not the file system root, +
          +
        1. Let packageURL be the URL resolution of "node_modules/" +concatenated with packageSpecifier, relative to parentURL.
        2. +
        3. Set parentURL to the parent folder URL of parentURL.
        4. +
        5. If the folder at packageURL does not exist, then +
            +
          1. Set parentURL to the parent URL path of parentURL.
          2. +
          3. Continue the next loop iteration.
          4. +
          +
        6. +
        7. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        8. +
        9. If pjson is not null and pjson.exports is not null or +undefined, then +
            +
          1. Let exports be pjson.exports.
          2. +
          3. Return the resolved destructured value of the result of +PACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath, +pjson.exports, defaultConditions).
          4. +
          +
        10. +
        11. Otherwise, if packageSubpath is equal to ".", then +
            +
          1. Return the result applying the legacy LOAD_AS_DIRECTORY +CommonJS resolver to packageURL, throwing a Module Not Found +error for no resolution.
          2. +
          +
        12. +
        13. Otherwise, +
            +
          1. Return the URL resolution of packageSubpath in packageURL.
          2. +
          +
        14. +
        +
      20. +
      21. Throw a Module Not Found error.
      22. +
      +
      +

      PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

      +
      +
        +
      1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      2. +
      3. If packageURL is null, then +
          +
        1. Return undefined.
        2. +
        +
      4. +
      5. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
      6. +
      7. If pjson is null or if pjson.exports is null or +undefined, then +
          +
        1. Return undefined.
        2. +
        +
      8. +
      9. If pjson.name is equal to packageName, then +
          +
        1. Return the resolved destructured value of the result of +PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports, +defaultConditions).
        2. +
        +
      10. +
      11. Otherwise, return undefined.
      12. +
      +
      +

      PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

      +
      +
        +
      1. If exports is an Object with both a key starting with "." and a key not +starting with ".", throw an Invalid Package Configuration error.
      2. +
      3. If subpath is equal to ".", then +
          +
        1. Let mainExport be undefined.
        2. +
        3. If exports is a String or Array, or an Object containing no keys +starting with ".", then +
            +
          1. Set mainExport to exports.
          2. +
          +
        4. +
        5. Otherwise if exports is an Object containing a "." property, then +
            +
          1. Set mainExport to exports["."].
          2. +
          +
        6. +
        7. If mainExport is not undefined, then +
            +
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, mainExport, "", false, false, +conditions).
          2. +
          3. If resolved is not null or undefined, then +
              +
            1. Return resolved.
            2. +
            +
          4. +
          +
        8. +
        +
      4. +
      5. Otherwise, if exports is an Object and all keys of exports start with +".", then +
          +
        1. Let matchKey be the string "./" concatenated with subpath.
        2. +
        3. Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE( +matchKey, exports, packageURL, false, conditions).
        4. +
        5. If resolvedMatch.resolve is not null or undefined, then +
            +
          1. Return resolvedMatch.
          2. +
          +
        6. +
        +
      6. +
      7. Throw a Package Path Not Exported error.
      8. +
      +
      +

      PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

      +
      +
        +
      1. Assert: specifier begins with "#".
      2. +
      3. If specifier is exactly equal to "#" or starts with "#/", then +
          +
        1. Throw an Invalid Module Specifier error.
        2. +
        +
      4. +
      5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      6. +
      7. If packageURL is not null, then +
          +
        1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        2. +
        3. If pjson.imports is a non-null Object, then +
            +
          1. Let resolvedMatch be the result of +PACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports, +packageURL, true, conditions).
          2. +
          3. If resolvedMatch.resolve is not null or undefined, then +
              +
            1. Return resolvedMatch.
            2. +
            +
          4. +
          +
        4. +
        +
      8. +
      9. Throw a Package Import Not Defined error.
      10. +
      +
      +

      PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL, +isImports, conditions)

      +
      +
        +
      1. If matchKey is a key of matchObj, and does not end in "*", then +
          +
        1. Let target be the value of matchObj[matchKey].
        2. +
        3. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, target, "", false, isImports, conditions).
        4. +
        5. Return the object { resolved, exact: true }.
        6. +
        +
      2. +
      3. Let expansionKeys be the list of keys of matchObj ending in "/" +or "*", sorted by length descending.
      4. +
      5. For each key expansionKey in expansionKeys, do +
          +
        1. If expansionKey ends in "*" and matchKey starts with but is +not equal to the substring of expansionKey excluding the last "*" +character, then +
            +
          1. Let target be the value of matchObj[expansionKey].
          2. +
          3. Let subpath be the substring of matchKey starting at the +index of the length of expansionKey minus one.
          4. +
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, target, subpath, true, isImports, +conditions).
          6. +
          7. Return the object { resolved, exact: true }.
          8. +
          +
        2. +
        3. If matchKey starts with expansionKey, then +
            +
          1. Let target be the value of matchObj[expansionKey].
          2. +
          3. Let subpath be the substring of matchKey starting at the +index of the length of expansionKey.
          4. +
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, target, subpath, false, isImports, +conditions).
          6. +
          7. Return the object { resolved, exact: false }.
          8. +
          +
        4. +
        +
      6. +
      7. Return the object { resolved: null, exact: true }.
      8. +
      +
      +

      PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern, +internal, conditions)

      +
      +
        +
      1. If target is a String, then +
          +
        1. If pattern is false, subpath has non-zero length and target +does not end with "/", throw an Invalid Module Specifier error.
        2. +
        3. If target does not start with "./", then +
            +
          1. If internal is true and target does not start with "../" or +"/" and is not a valid URL, then +
              +
            1. If pattern is true, then +
                +
              1. Return PACKAGE_RESOLVE(target with every instance of +"*" replaced by subpath, packageURL + "/")_.
              2. +
              +
            2. +
            3. Return PACKAGE_RESOLVE(target + subpath, +packageURL + "/")_.
            4. +
            +
          2. +
          3. Otherwise, throw an Invalid Package Target error.
          4. +
          +
        4. +
        5. If target split on "/" or "\" contains any ".", ".." or +"node_modules" segments after the first segment, throw an +Invalid Package Target error.
        6. +
        7. Let resolvedTarget be the URL resolution of the concatenation of +packageURL and target.
        8. +
        9. Assert: resolvedTarget is contained in packageURL.
        10. +
        11. If subpath split on "/" or "\" contains any ".", ".." or +"node_modules" segments, throw an Invalid Module Specifier error.
        12. +
        13. If pattern is true, then +
            +
          1. Return the URL resolution of resolvedTarget with every instance of +"*" replaced with subpath.
          2. +
          +
        14. +
        15. Otherwise, +
            +
          1. Return the URL resolution of the concatenation of subpath and +resolvedTarget.
          2. +
          +
        16. +
        +
      2. +
      3. Otherwise, if target is a non-null Object, then +
          +
        1. If exports contains any index property keys, as defined in ECMA-262 +6.1.7 Array Index, throw an Invalid Package Configuration error.
        2. +
        3. For each property p of target, in object insertion order as, +
            +
          1. If p equals "default" or conditions contains an entry for p, +then +
              +
            1. Let targetValue be the value of the p property in target.
            2. +
            3. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, targetValue, subpath, pattern, internal, +conditions).
            4. +
            5. If resolved is equal to undefined, continue the loop.
            6. +
            7. Return resolved.
            8. +
            +
          2. +
          +
        4. +
        5. Return undefined.
        6. +
        +
      4. +
      5. Otherwise, if target is an Array, then +
          +
        1. If _target.length is zero, return null.
        2. +
        3. For each item targetValue in target, do +
            +
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE( +packageURL, targetValue, subpath, pattern, internal, +conditions), continuing the loop on any Invalid Package Target +error.
          2. +
          3. If resolved is undefined, continue the loop.
          4. +
          5. Return resolved.
          6. +
          +
        4. +
        5. Return or throw the last fallback resolution null return or error.
        6. +
        +
      6. +
      7. Otherwise, if target is null, return null.
      8. +
      9. Otherwise throw an Invalid Package Target error.
      10. +
      +
      +

      ESM_FORMAT(url)

      +
      +
        +
      1. Assert: url corresponds to an existing file.
      2. +
      3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
      4. +
      5. If url ends in ".mjs", then +
          +
        1. Return "module".
        2. +
        +
      6. +
      7. If url ends in ".cjs", then +
          +
        1. Return "commonjs".
        2. +
        +
      8. +
      9. If pjson?.type exists and is "module", then +
          +
        1. If url ends in ".js", then +
            +
          1. Return "module".
          2. +
          +
        2. +
        3. Throw an Unsupported File Extension error.
        4. +
        +
      10. +
      11. Otherwise, +
          +
        1. Throw an Unsupported File Extension error.
        2. +
        +
      12. +
      +
      +

      READ_PACKAGE_SCOPE(url)

      +
      +
        +
      1. Let scopeURL be url.
      2. +
      3. While scopeURL is not the file system root, +
          +
        1. Set scopeURL to the parent URL of scopeURL.
        2. +
        3. If scopeURL ends in a "node_modules" path segment, return null.
        4. +
        5. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
        6. +
        7. If pjson is not null, then +
            +
          1. Return pjson.
          2. +
          +
        8. +
        +
      4. +
      5. Return null.
      6. +
      +
      +

      READ_PACKAGE_JSON(packageURL)

      +
      +
        +
      1. Let pjsonURL be the resolution of "package.json" within packageURL.
      2. +
      3. If the file at pjsonURL does not exist, then +
          +
        1. Return null.
        2. +
        +
      4. +
      5. If the file at packageURL does not parse as valid JSON, then +
          +
        1. Throw an Invalid Package Configuration error.
        2. +
        +
      6. +
      7. Return the parsed JSON source of the file at pjsonURL.
      8. +
      +
      +

      Customizing ESM specifier resolution algorithm#

      +

      The current specifier resolution does not support all default behavior of +the CommonJS loader. One of the behavior differences is automatic resolution +of file extensions and the ability to import directories that have an index +file.

      +

      The --experimental-specifier-resolution=[mode] flag can be used to customize +the extension resolution algorithm. The default mode is explicit, which +requires the full path to a module be provided to the loader. To enable the +automatic extension resolution and importing from directories that include an +index file use the node mode.

      +
      $ node index.mjs
      +success!
      +$ node index # Failure!
      +Error: Cannot find module
      +$ node --experimental-specifier-resolution=node index
      +success!
      + + +
      +
      +
      + + diff --git a/doc/api/esm.json b/doc/api/esm.json new file mode 100644 index 0000000000000000000000000000000000000000..29fedcf2b046e8bac61aac870fbbd23cc5f2fced --- /dev/null +++ b/doc/api/esm.json @@ -0,0 +1,425 @@ +{ + "type": "module", + "source": "doc/api/esm.md", + "introduced_in": "v8.5.0", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": [ + "v12.22.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/35781", + "description": "Stabilize modules implementation." + }, + { + "version": [ + "v12.20.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/35249", + "description": "Support for detection of CommonJS named exports." + }, + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/31974", + "description": "Remove experimental modules warning." + }, + { + "version": [ + "v12.17.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29866", + "description": "Loading ECMAScript modules no longer requires a command-line flag." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26745", + "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." + } + ] + }, + "stability": 2, + "stabilityText": "Stable", + "properties": [ + { + "textRaw": "`meta` {Object}", + "type": "Object", + "name": "meta", + "desc": "

      The import.meta metaproperty is an Object that contains the following\nproperty:

      \n
        \n
      • url <string> The absolute file: URL of the module.
      • \n
      " + } + ], + "miscs": [ + { + "textRaw": "Modules: ECMAScript modules", + "name": "Modules: ECMAScript modules", + "introduced_in": "v8.5.0", + "type": "misc", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": [ + "v12.22.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/35781", + "description": "Stabilize modules implementation." + }, + { + "version": [ + "v12.20.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/35249", + "description": "Support for detection of CommonJS named exports." + }, + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/31974", + "description": "Remove experimental modules warning." + }, + { + "version": [ + "v12.17.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29866", + "description": "Loading ECMAScript modules no longer requires a command-line flag." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26745", + "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." + } + ] + }, + "stability": 2, + "stabilityText": "Stable", + "miscs": [ + { + "textRaw": "Introduction", + "name": "esm", + "desc": "

      ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import and\nexport statements.

      \n

      The following example of an ES module exports a function:

      \n
      // addTwo.mjs\nfunction addTwo(num) {\n  return num + 2;\n}\n\nexport { addTwo };\n
      \n

      The following example of an ES module imports the function from addTwo.mjs:

      \n
      // app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
      \n

      Node.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.

      \n\n

      \n\n

      ", + "type": "misc", + "displayName": "esm" + }, + { + "textRaw": "Enabling", + "name": "Enabling", + "type": "misc", + "desc": "

      Node.js treats JavaScript code as CommonJS modules by default.\nAuthors can tell Node.js to treat JavaScript code as ECMAScript modules\nvia the .mjs file extension, the package.json \"type\" field, or the\n--input-type flag. See\nModules: Packages for more\ndetails.

      \n\n

      \n\n\n\n\n\n\n\n\n\n\n\n\n

      " + }, + { + "textRaw": "Packages", + "name": "packages", + "desc": "

      This section was moved to Modules: Packages.

      ", + "type": "misc", + "displayName": "Packages" + }, + { + "textRaw": "`import` Specifiers", + "name": "`import`_specifiers", + "modules": [ + { + "textRaw": "Terminology", + "name": "terminology", + "desc": "

      The specifier of an import statement is the string after the from keyword,\ne.g. 'path' in import { sep } from 'path'. Specifiers are also used in\nexport from statements, and as the argument to an import() expression.

      \n

      There are four types of specifiers:

      \n
        \n
      • \n

        Bare specifiers like 'some-package'. They refer to an entry point of a\npackage by the package name.

        \n
      • \n
      • \n

        Deep import specifiers like 'some-package/lib/shuffle.mjs'. They refer to\na path within a package prefixed by the package name.

        \n
      • \n
      • \n

        Relative specifiers like './startup.js' or '../config.mjs'. They refer\nto a path relative to the location of the importing file.

        \n
      • \n
      • \n

        Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer\ndirectly and explicitly to a full path.

        \n
      • \n
      \n

      Bare specifiers, and the bare specifier portion of deep import specifiers, are\nstrings; but everything else in a specifier is a URL.

      \n

      file:, node:, and data: URLs are supported. A specifier like\n'https://example.com/app.js' may be supported by browsers but it is not\nsupported in Node.js.

      \n

      Specifiers may not begin with / or //. These are reserved for potential\nfuture use. The root of the current volume may be referenced via file:///.

      ", + "modules": [ + { + "textRaw": "`node:` Imports", + "name": "`node:`_imports", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "desc": "

      node: URLs are supported as a means to load Node.js builtin modules. This\nURL scheme allows for builtin modules to be referenced by valid absolute URL\nstrings.

      \n
      import fs from 'node:fs/promises';\n
      ", + "type": "module", + "displayName": "`node:` Imports" + }, + { + "textRaw": "`data:` Imports", + "name": "`data:`_imports", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      data: URLs are supported for importing with the following MIME types:

      \n
        \n
      • text/javascript for ES Modules
      • \n
      • application/json for JSON
      • \n
      • application/wasm for Wasm
      • \n
      \n

      data: URLs only resolve Bare specifiers for builtin modules\nand Absolute specifiers. Resolving\nRelative specifiers does not work because data: is not a\nspecial scheme. For example, attempting to load ./foo\nfrom data:text/javascript,import \"./foo\"; fails to resolve because there\nis no concept of relative resolution for data: URLs. An example of a data:\nURLs being used is:

      \n
      import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
      ", + "type": "module", + "displayName": "`data:` Imports" + } + ], + "type": "module", + "displayName": "Terminology" + } + ], + "type": "misc", + "displayName": "`import` Specifiers" + }, + { + "textRaw": "Differences between ES modules and CommonJS", + "name": "differences_between_es_modules_and_commonjs", + "modules": [ + { + "textRaw": "Mandatory file extensions", + "name": "mandatory_file_extensions", + "desc": "

      A file extension must be provided when using the import keyword. Directory\nindexes (e.g. './startup/index.js') must also be fully specified.

      \n

      This behavior matches how import behaves in browser environments, assuming a\ntypically configured server.

      ", + "type": "module", + "displayName": "Mandatory file extensions" + }, + { + "textRaw": "No `NODE_PATH`", + "name": "no_`node_path`", + "desc": "

      NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.

      ", + "type": "module", + "displayName": "No `NODE_PATH`" + }, + { + "textRaw": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`", + "name": "no_`require`,_`exports`,_`module.exports`,_`__filename`,_`__dirname`", + "desc": "

      These CommonJS variables are not available in ES modules.

      \n

      require can be imported into an ES module using module.createRequire().

      \n

      Equivalents of __filename and __dirname can be created inside of each file\nvia import.meta.url.

      \n
      import { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n
      ", + "type": "module", + "displayName": "No `require`, `exports`, `module.exports`, `__filename`, `__dirname`" + }, + { + "textRaw": "No `require.resolve`", + "name": "no_`require.resolve`", + "desc": "

      Former use cases relying on require.resolve to determine the resolved path\nof a module can be supported via import.meta.resolve, which is experimental\nand supported via the --experimental-import-meta-resolve flag:

      \n
      (async () => {\n  const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n})();\n
      \n

      import.meta.resolve also accepts a second argument which is the parent module\nfrom which to resolve from:

      \n
      (async () => {\n  // Equivalent to import.meta.resolve('./dep')\n  await import.meta.resolve('./dep', import.meta.url);\n})();\n
      \n

      This function is asynchronous because the ES module resolver in Node.js is\nasynchronous. With the introduction of Top-Level Await, these use cases\nwill be easier as they won't require an async function wrapper.

      ", + "type": "module", + "displayName": "No `require.resolve`" + }, + { + "textRaw": "No `require.extensions`", + "name": "no_`require.extensions`", + "desc": "

      require.extensions is not used by import. The expectation is that loader\nhooks can provide this workflow in the future.

      ", + "type": "module", + "displayName": "No `require.extensions`" + }, + { + "textRaw": "No `require.cache`", + "name": "no_`require.cache`", + "desc": "

      require.cache is not used by import. It has a separate cache.

      ", + "type": "module", + "displayName": "No `require.cache`" + }, + { + "textRaw": "URL-based paths", + "name": "url-based_paths", + "desc": "

      ES modules are resolved and cached based upon\nURL semantics. This means that files containing\nspecial characters such as # and ? need to be escaped.

      \n

      Modules are loaded multiple times if the import specifier used to resolve\nthem has a different query or fragment.

      \n
      import './foo.mjs?query=1'; // loads ./foo.mjs with query of \"?query=1\"\nimport './foo.mjs?query=2'; // loads ./foo.mjs with query of \"?query=2\"\n
      \n

      For now, only modules using the file: protocol can be loaded.

      ", + "type": "module", + "displayName": "URL-based paths" + } + ], + "type": "misc", + "displayName": "Differences between ES modules and CommonJS" + }, + { + "textRaw": "Interoperability with CommonJS", + "name": "interoperability_with_commonjs", + "modules": [ + { + "textRaw": "`require`", + "name": "`require`", + "desc": "

      require always treats the files it references as CommonJS. This applies\nwhether require is used the traditional way within a CommonJS environment, or\nin an ES module environment using module.createRequire().

      \n

      To include an ES module into CommonJS, use import().

      ", + "type": "module", + "displayName": "`require`" + }, + { + "textRaw": "`import` statements", + "name": "`import`_statements", + "desc": "

      An import statement can reference an ES module or a CommonJS module.\nimport statements are permitted only in ES modules. For similar functionality\nin CommonJS, see import().

      \n

      When importing CommonJS modules, the\nmodule.exports object is provided as the default export. Named exports may be\navailable, provided by static analysis as a convenience for better ecosystem\ncompatibility.

      \n

      Additional experimental flags are available for importing\nWasm modules or\nJSON modules. For importing native modules or\nJSON modules unflagged, see module.createRequire().

      \n

      The specifier of an import statement (the string after the from keyword)\ncan either be an URL-style relative path like './file.mjs' or a package name\nlike 'fs'.

      \n

      Like in CommonJS, files within packages can be accessed by appending a path to\nthe package name; unless the package’s package.json contains an\n\"exports\" field, in which case files within packages need to be accessed\nvia the path defined in \"exports\".

      \n
      import { sin, cos } from 'geometry/trigonometry-functions.mjs';\n
      ", + "type": "module", + "displayName": "`import` statements" + }, + { + "textRaw": "`import()` expressions", + "name": "`import()`_expressions", + "desc": "

      Dynamic import() is supported in both CommonJS and ES modules. It can be\nused to include ES module files from CommonJS code.

      ", + "type": "module", + "displayName": "`import()` expressions" + } + ], + "type": "misc", + "displayName": "Interoperability with CommonJS" + }, + { + "textRaw": "CommonJS Namespaces", + "name": "commonjs_namespaces", + "desc": "

      CommonJS modules consist of a module.exports object which can be of any type.

      \n

      When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:

      \n\n
      import { default as cjs } from 'cjs';\n\n// The following import statement is \"syntax sugar\" (equivalent but sweeter)\n// for `{ default as cjsSugar }` in the above import statement:\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n//   <module.exports>\n//   true\n
      \n

      The ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default export key pointing to the CommonJS\nmodule.exports value.

      \n

      This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:

      \n\n
      import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n//   [Module] { default: <module.exports> }\n//   true\n
      \n

      For better compatibility with existing usage in the JS ecosystem, Node.js\nin addition attempts to determine the CommonJS named exports of every imported\nCommonJS module to provide them as separate ES module exports using a static\nanalysis process.

      \n

      For example, consider a CommonJS module written:

      \n
      // cjs.cjs\nexports.name = 'exported';\n
      \n

      The preceding module supports named imports in ES modules:

      \n\n
      import { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }\n
      \n

      As can be seen from the last example of the Module Namespace Exotic Object being\nlogged, the name export is copied off of the module.exports object and set\ndirectly on the ES module namespace when the module is imported.

      \n

      Live binding updates or new exports added to module.exports are not detected\nfor these named exports.

      \n

      The detection of named exports is based on common syntax patterns but does not\nalways correctly detect named exports. In these cases, using the default\nimport form described above can be a better option.

      \n

      Named exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See cjs-module-lexer for the exact\nsemantics implemented.

      ", + "type": "misc", + "displayName": "CommonJS Namespaces" + }, + { + "textRaw": "Builtin modules", + "name": "builtin_modules", + "desc": "

      Core modules provide named exports of their public API. A\ndefault export is also provided which is the value of the CommonJS exports.\nThe default export can be used for, among other things, modifying the named\nexports. Named exports of builtin modules are updated only by calling\nmodule.syncBuiltinESMExports().

      \n
      import EventEmitter from 'events';\nconst e = new EventEmitter();\n
      \n
      import { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});\n
      \n
      import fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
      ", + "type": "misc", + "displayName": "Builtin modules" + }, + { + "textRaw": "CommonJS, JSON, and native modules", + "name": "commonjs,_json,_and_native_modules", + "desc": "

      CommonJS, JSON, and native modules can be used with\nmodule.createRequire().

      \n
      // cjs.cjs\nmodule.exports = 'cjs';\n\n// esm.mjs\nimport { createRequire } from 'module';\n\nconst require = createRequire(import.meta.url);\n\nconst cjs = require('./cjs.cjs');\ncjs === 'cjs'; // true\n
      ", + "type": "misc", + "displayName": "CommonJS, JSON, and native modules" + }, + { + "textRaw": "Experimental JSON modules", + "name": "experimental_json_modules", + "desc": "

      Currently importing JSON modules are only supported in the commonjs mode\nand are loaded using the CJS loader. WHATWG JSON modules specification are\nstill being standardized, and are experimentally supported by including the\nadditional flag --experimental-json-modules when running Node.js.

      \n

      When the --experimental-json-modules flag is included, both the\ncommonjs and module mode use the new experimental JSON\nloader. The imported JSON only exposes a default. There is no\nsupport for named exports. A cache entry is created in the CommonJS\ncache to avoid duplication. The same object is returned in\nCommonJS if the JSON module has already been imported from the\nsame path.

      \n

      Assuming an index.mjs with

      \n\n
      import packageConfig from './package.json';\n
      \n

      The --experimental-json-modules flag is needed for the module\nto work.

      \n
      node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n
      ", + "type": "misc", + "displayName": "Experimental JSON modules" + }, + { + "textRaw": "Experimental Wasm modules", + "name": "experimental_wasm_modules", + "desc": "

      Importing Web Assembly modules is supported under the\n--experimental-wasm-modules flag, allowing any .wasm files to be\nimported as normal modules while also supporting their module imports.

      \n

      This integration is in line with the\nES Module Integration Proposal for Web Assembly.

      \n

      For example, an index.mjs containing:

      \n
      import * as M from './module.wasm';\nconsole.log(M);\n
      \n

      executed under:

      \n
      node --experimental-wasm-modules index.mjs\n
      \n

      would provide the exports interface for the instantiation of module.wasm.

      ", + "type": "misc", + "displayName": "Experimental Wasm modules" + }, + { + "textRaw": "Experimental loaders", + "name": "Experimental loaders", + "type": "misc", + "desc": "

      Note: This API is currently being redesigned and will still change.

      \n

      To customize the default module resolution, loader hooks can optionally be\nprovided via a --experimental-loader ./loader-name.mjs argument to Node.js.

      \n

      When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.

      ", + "miscs": [ + { + "textRaw": "Hooks", + "name": "hooks", + "methods": [ + { + "textRaw": "`resolve(specifier, context, defaultResolve)`", + "type": "method", + "name": "resolve", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The resolve hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an import statement or\nimport() expression, and the parent URL is the URL of the module that imported\nthis one, or undefined if this is the main entry point for the application.

      \n

      The conditions property on the context is an array of conditions for\nConditional exports that apply to this resolution request. They can be used\nfor looking up conditional mappings elsewhere or to modify the list when calling\nthe default resolution logic.

      \n

      The current package exports conditions are always in\nthe context.conditions array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve, the\ncontext.conditions array passed to it must include all elements of the\ncontext.conditions array originally passed into the resolve hook.

      \n
      /**\n * @param {string} specifier\n * @param {{\n *   conditions: !Array<string>,\n *   parentURL: !(string | undefined),\n * }} context\n * @param {Function} defaultResolve\n * @returns {Promise<{ url: string }>}\n */\nexport async function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all specifiers, do some custom logic for resolving.\n    // Always return an object of the form {url: <string>}.\n    return {\n      url: parentURL ?\n        new URL(specifier, parentURL).href :\n        new URL(specifier).href,\n    };\n  }\n  if (Math.random() < 0.5) { // Another condition.\n    // When calling `defaultResolve`, the arguments can be modified. In this\n    // case it's adding another value for matching conditional exports.\n    return defaultResolve(specifier, {\n      ...context,\n      conditions: [...context.conditions, 'another-condition'],\n    });\n  }\n  // Defer to Node.js for all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n
      " + }, + { + "textRaw": "`getFormat(url, context, defaultGetFormat)`", + "type": "method", + "name": "getFormat", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The getFormat hook provides a way to define a custom method of determining how\na URL should be interpreted. The format returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      formatDescriptionAcceptable Types For source Returned by getSource or transformSource
      'builtin'Load a Node.js builtin moduleNot applicable
      'dynamic'Use a dynamic instantiate hookNot applicable
      'commonjs'Load a Node.js CommonJS moduleNot applicable
      'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
      'module'Load an ES module{ string, ArrayBuffer, TypedArray }
      'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
      \n

      Note: These types all correspond to classes defined in ECMAScript.

      \n\n

      Note: If the source value of a text-based format (i.e., 'json', 'module') is\nnot a string, it is converted to a string using util.TextDecoder.

      \n
      /**\n * @param {string} url\n * @param {Object} context (currently empty)\n * @param {Function} defaultGetFormat\n * @returns {Promise<{ format: string }>}\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for determining format.\n    // Always return an object of the form {format: <string>}, where the\n    // format is one of the strings in the preceding table.\n    return {\n      format: 'module',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n
      " + }, + { + "textRaw": "`getSource(url, context, defaultGetSource)`", + "type": "method", + "name": "getSource", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The getSource hook provides a way to define a custom method for retrieving\nthe source code of an ES module specifier. This would allow a loader to\npotentially avoid reading files from disk.

      \n
      /**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function getSource(url, context, defaultGetSource) {\n  const { format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for retrieving the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
      " + }, + { + "textRaw": "`transformSource(source, context, defaultTransformSource)`", + "type": "method", + "name": "transformSource", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js\n
      \n
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      The transformSource hook provides a way to modify the source code of a loaded\nES module file after the source string has been loaded but before Node.js has\ndone anything with it.

      \n

      If this hook is used to convert unknown-to-Node.js file types into executable\nJavaScript, a resolve hook is also necessary in order to register any\nunknown-to-Node.js file extensions. See the transpiler loader example below.

      \n
      /**\n * @param {!(string | SharedArrayBuffer | Uint8Array)} source\n * @param {{\n *   format: string,\n *   url: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for modifying the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
      " + }, + { + "textRaw": "`getGlobalPreloadCode()`", + "type": "method", + "name": "getGlobalPreloadCode", + "signatures": [ + { + "params": [] + } + ], + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n\n

      Sometimes it might be necessary to run some code inside of the same global scope\nthat the application runs in. This hook allows the return of a string that is\nrun as sloppy-mode script on startup.

      \n

      Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string).

      \n

      If the code needs more advanced require features, it has to construct\nits own require using module.createRequire().

      \n
      /**\n * @returns {string} Code to run before application startup\n */\nexport function getGlobalPreloadCode() {\n  return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\n\nconst require = createRequire(process.cwd() + '/<preload>');\n// [...]\n`;\n}\n
      " + } + ], + "modules": [ + { + "textRaw": "dynamicInstantiate hook", + "name": "dynamicinstantiate_hook", + "desc": "
      \n

      Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

      \n
      \n

      To create a custom dynamic module that doesn't correspond to one of the\nexisting format interpretations, the dynamicInstantiate hook can be used.\nThis hook is called only for modules that return format: 'dynamic' from\nthe getFormat hook.

      \n
      /**\n * @param {string} url\n * @returns {object} response\n * @returns {array} response.exports\n * @returns {function} response.execute\n */\nexport async function dynamicInstantiate(url) {\n  return {\n    exports: ['customExportName'],\n    execute: (exports) => {\n      // Get and set functions provided for pre-allocated export names\n      exports.customExportName.set('value');\n    }\n  };\n}\n
      \n

      With the list of module exports provided upfront, the execute function will\nthen be called at the exact point of module evaluation order for that module\nin the import tree.

      \n

      Examples

      \n

      The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.

      ", + "type": "module", + "displayName": "dynamicInstantiate hook" + }, + { + "textRaw": "HTTPS loader", + "name": "https_loader", + "desc": "

      In current Node.js, specifiers starting with https:// are unsupported. The\nloader below registers hooks to enable rudimentary support for such specifiers.\nWhile this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.

      \n
      // https-loader.mjs\nimport { get } from 'https';\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n\n  // Normally Node.js would error on specifiers starting with 'https://', so\n  // this hook intercepts them and converts them into absolute URLs to be\n  // passed along to the later hooks below.\n  if (specifier.startsWith('https://')) {\n    return {\n      url: specifier\n    };\n  } else if (parentURL && parentURL.startsWith('https://')) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // This loader assumes all network-provided JavaScript is ES module code.\n  if (url.startsWith('https://')) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function getSource(url, context, defaultGetSource) {\n  // For JavaScript to be loaded over the network, we need to fetch and\n  // return it.\n  if (url.startsWith('https://')) {\n    return new Promise((resolve, reject) => {\n      get(url, (res) => {\n        let data = '';\n        res.on('data', (chunk) => data += chunk);\n        res.on('end', () => resolve({ source: data }));\n      }).on('error', (err) => reject(err));\n    });\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
      \n
      // main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
      \n

      With the preceding loader, running\nnode --experimental-loader ./https-loader.mjs ./main.mjs\nprints the current version of CoffeeScript per the module at the URL in\nmain.mjs.

      ", + "type": "module", + "displayName": "HTTPS loader" + }, + { + "textRaw": "Transpiler loader", + "name": "transpiler_loader", + "desc": "

      Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the transformSource hook. Before that hook gets called,\nhowever, other hooks need to tell Node.js not to throw an error on unknown file\ntypes; and to tell Node.js how to load this new file type.

      \n

      This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.

      \n
      // coffeescript-loader.mjs\nimport { URL, pathToFileURL } from 'url';\nimport CoffeeScript from 'coffeescript';\n\nconst baseURL = pathToFileURL(`${process.cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = baseURL } = context;\n\n  // Node.js normally errors on unknown file extensions, so return a URL for\n  // specifiers ending in the CoffeeScript file extensions.\n  if (extensionsRegex.test(specifier)) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // Now that we patched resolve to let CoffeeScript URLs through, we need to\n  // tell Node.js what format such URLs should be interpreted as. For the\n  // purposes of this loader, all CoffeeScript URLs are ES modules.\n  if (extensionsRegex.test(url)) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n\n  if (extensionsRegex.test(url)) {\n    return {\n      source: CoffeeScript.compile(source, { bare: true })\n    };\n  }\n\n  // Let Node.js handle all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
      \n
      # main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
      \n
      # scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
      \n

      With the preceding loader, running\nnode --experimental-loader ./coffeescript-loader.mjs main.coffee\ncauses main.coffee to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any .coffee,\n.litcoffee or .coffee.md files referenced via import statements of any\nloaded file.

      ", + "type": "module", + "displayName": "Transpiler loader" + } + ], + "type": "misc", + "displayName": "Hooks" + } + ] + }, + { + "textRaw": "Resolution algorithm", + "name": "resolution_algorithm", + "modules": [ + { + "textRaw": "Features", + "name": "features", + "desc": "

      The resolver has the following properties:

      \n
        \n
      • FileURL-based resolution as is used by ES modules
      • \n
      • Support for builtin module loading
      • \n
      • Relative and absolute URL resolution
      • \n
      • No default extensions
      • \n
      • No folder mains
      • \n
      • Bare specifier package resolution lookup through node_modules
      • \n
      ", + "type": "module", + "displayName": "Features" + }, + { + "textRaw": "Resolver algorithm", + "name": "resolver_algorithm", + "desc": "

      The algorithm to load an ES module specifier is given through the\nESM_RESOLVE method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.

      \n

      The algorithm to determine the module format of a resolved URL is\nprovided by ESM_FORMAT, which returns the unique module\nformat for any file. The \"module\" format is returned for an ECMAScript\nModule, while the \"commonjs\" format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as \"addon\" can be extended in\nfuture updates.

      \n

      In the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.

      \n

      defaultConditions is the conditional environment name array,\n[\"node\", \"import\"].

      \n

      The resolver can throw the following errors:

      \n
        \n
      • Invalid Module Specifier: Module specifier is an invalid URL, package name\nor package subpath specifier.
      • \n
      • Invalid Package Configuration: package.json configuration is invalid or\ncontains an invalid configuration.
      • \n
      • Invalid Package Target: Package exports or imports define a target module\nfor the package that is an invalid type or string target.
      • \n
      • Package Path Not Exported: Package exports do not define or permit a target\nsubpath in the package for the given module.
      • \n
      • Package Import Not Defined: Package imports do not define the specifier.
      • \n
      • Module Not Found: The package or module requested does not exist.
      • \n
      ", + "type": "module", + "displayName": "Resolver algorithm" + }, + { + "textRaw": "Resolver Algorithm Specification", + "name": "resolver_algorithm_specification", + "desc": "

      ESM_RESOLVE(specifier, parentURL)

      \n
      \n
        \n
      1. Let resolved be undefined.
      2. \n
      3. If specifier is a valid URL, then\n
          \n
        1. Set resolved to the result of parsing and reserializing\nspecifier as a URL.
        2. \n
        \n
      4. \n
      5. Otherwise, if specifier starts with \"/\", \"./\" or \"../\", then\n
          \n
        1. Set resolved to the URL resolution of specifier relative to\nparentURL.
        2. \n
        \n
      6. \n
      7. Otherwise, if specifier starts with \"#\", then\n
          \n
        1. Set resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).
        2. \n
        \n
      8. \n
      9. Otherwise,\n
          \n
        1. Note: specifier is now a bare specifier.
        2. \n
        3. Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
        4. \n
        \n
      10. \n
      11. If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      12. \n
      13. If the file at resolved is a directory, then\n
          \n
        1. Throw an Unsupported Directory Import error.
        2. \n
        \n
      14. \n
      15. If the file at resolved does not exist, then\n
          \n
        1. Throw a Module Not Found error.
        2. \n
        \n
      16. \n
      17. Set resolved to the real path of resolved.
      18. \n
      19. Let format be the result of ESM_FORMAT(resolved).
      20. \n
      21. Load resolved as module format, format.
      22. \n
      23. Return resolved.
      24. \n
      \n
      \n

      PACKAGE_RESOLVE(packageSpecifier, parentURL)

      \n
      \n
        \n
      1. Let packageName be undefined.
      2. \n
      3. If packageSpecifier is an empty string, then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      4. \n
      5. If packageSpecifier does not start with \"@\", then\n
          \n
        1. Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
        2. \n
        \n
      6. \n
      7. Otherwise,\n
          \n
        1. If packageSpecifier does not contain a \"/\" separator, then\n
            \n
          1. Throw an Invalid Module Specifier error.
          2. \n
          \n
        2. \n
        3. Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
        4. \n
        \n
      8. \n
      9. If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      10. \n
      11. Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
      12. \n
      13. Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
      14. \n
      15. If selfUrl is not undefined, return selfUrl.
      16. \n
      17. If packageSubpath is \".\" and packageName is a Node.js builtin\nmodule, then\n
          \n
        1. Return the string \"node:\" concatenated with packageSpecifier.
        2. \n
        \n
      18. \n
      19. While parentURL is not the file system root,\n
          \n
        1. Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.
        2. \n
        3. Set parentURL to the parent folder URL of parentURL.
        4. \n
        5. If the folder at packageURL does not exist, then\n
            \n
          1. Set parentURL to the parent URL path of parentURL.
          2. \n
          3. Continue the next loop iteration.
          4. \n
          \n
        6. \n
        7. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        8. \n
        9. If pjson is not null and pjson.exports is not null or\nundefined, then\n
            \n
          1. Let exports be pjson.exports.
          2. \n
          3. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).
          4. \n
          \n
        10. \n
        11. Otherwise, if packageSubpath is equal to \".\", then\n
            \n
          1. Return the result applying the legacy LOAD_AS_DIRECTORY\nCommonJS resolver to packageURL, throwing a Module Not Found\nerror for no resolution.
          2. \n
          \n
        12. \n
        13. Otherwise,\n
            \n
          1. Return the URL resolution of packageSubpath in packageURL.
          2. \n
          \n
        14. \n
        \n
      20. \n
      21. Throw a Module Not Found error.
      22. \n
      \n
      \n

      PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

      \n
      \n
        \n
      1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      2. \n
      3. If packageURL is null, then\n
          \n
        1. Return undefined.
        2. \n
        \n
      4. \n
      5. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
      6. \n
      7. If pjson is null or if pjson.exports is null or\nundefined, then\n
          \n
        1. Return undefined.
        2. \n
        \n
      8. \n
      9. If pjson.name is equal to packageName, then\n
          \n
        1. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports,\ndefaultConditions).
        2. \n
        \n
      10. \n
      11. Otherwise, return undefined.
      12. \n
      \n
      \n

      PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

      \n
      \n
        \n
      1. If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
      2. \n
      3. If subpath is equal to \".\", then\n
          \n
        1. Let mainExport be undefined.
        2. \n
        3. If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
            \n
          1. Set mainExport to exports.
          2. \n
          \n
        4. \n
        5. Otherwise if exports is an Object containing a \".\" property, then\n
            \n
          1. Set mainExport to exports[\".\"].
          2. \n
          \n
        6. \n
        7. If mainExport is not undefined, then\n
            \n
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, false,\nconditions).
          2. \n
          3. If resolved is not null or undefined, then\n
              \n
            1. Return resolved.
            2. \n
            \n
          4. \n
          \n
        8. \n
        \n
      4. \n
      5. Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
          \n
        1. Let matchKey be the string \"./\" concatenated with subpath.
        2. \n
        3. Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
        4. \n
        5. If resolvedMatch.resolve is not null or undefined, then\n
            \n
          1. Return resolvedMatch.
          2. \n
          \n
        6. \n
        \n
      6. \n
      7. Throw a Package Path Not Exported error.
      8. \n
      \n
      \n

      PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

      \n
      \n
        \n
      1. Assert: specifier begins with \"#\".
      2. \n
      3. If specifier is exactly equal to \"#\" or starts with \"#/\", then\n
          \n
        1. Throw an Invalid Module Specifier error.
        2. \n
        \n
      4. \n
      5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
      6. \n
      7. If packageURL is not null, then\n
          \n
        1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
        2. \n
        3. If pjson.imports is a non-null Object, then\n
            \n
          1. Let resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).
          2. \n
          3. If resolvedMatch.resolve is not null or undefined, then\n
              \n
            1. Return resolvedMatch.
            2. \n
            \n
          4. \n
          \n
        4. \n
        \n
      8. \n
      9. Throw a Package Import Not Defined error.
      10. \n
      \n
      \n

      PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)

      \n
      \n
        \n
      1. If matchKey is a key of matchObj, and does not end in \"*\", then\n
          \n
        1. Let target be the value of matchObj[matchKey].
        2. \n
        3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", false, isImports, conditions).
        4. \n
        5. Return the object { resolved, exact: true }.
        6. \n
        \n
      2. \n
      3. Let expansionKeys be the list of keys of matchObj ending in \"/\"\nor \"*\", sorted by length descending.
      4. \n
      5. For each key expansionKey in expansionKeys, do\n
          \n
        1. If expansionKey ends in \"*\" and matchKey starts with but is\nnot equal to the substring of expansionKey excluding the last \"*\"\ncharacter, then\n
            \n
          1. Let target be the value of matchObj[expansionKey].
          2. \n
          3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey minus one.
          4. \n
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, true, isImports,\nconditions).
          6. \n
          7. Return the object { resolved, exact: true }.
          8. \n
          \n
        2. \n
        3. If matchKey starts with expansionKey, then\n
            \n
          1. Let target be the value of matchObj[expansionKey].
          2. \n
          3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.
          4. \n
          5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, false, isImports,\nconditions).
          6. \n
          7. Return the object { resolved, exact: false }.
          8. \n
          \n
        4. \n
        \n
      6. \n
      7. Return the object { resolved: null, exact: true }.
      8. \n
      \n
      \n

      PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern,\ninternal, conditions)

      \n
      \n
        \n
      1. If target is a String, then\n
          \n
        1. If pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.
        2. \n
        3. If target does not start with \"./\", then\n
            \n
          1. If internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n
              \n
            1. If pattern is true, then\n
                \n
              1. Return PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\")_.
              2. \n
              \n
            2. \n
            3. Return PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\")_.
            4. \n
            \n
          2. \n
          3. Otherwise, throw an Invalid Package Target error.
          4. \n
          \n
        4. \n
        5. If target split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments after the first segment, throw an\nInvalid Package Target error.
        6. \n
        7. Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
        8. \n
        9. Assert: resolvedTarget is contained in packageURL.
        10. \n
        11. If subpath split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments, throw an Invalid Module Specifier error.
        12. \n
        13. If pattern is true, then\n
            \n
          1. Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.
          2. \n
          \n
        14. \n
        15. Otherwise,\n
            \n
          1. Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
          2. \n
          \n
        16. \n
        \n
      2. \n
      3. Otherwise, if target is a non-null Object, then\n
          \n
        1. If exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
        2. \n
        3. For each property p of target, in object insertion order as,\n
            \n
          1. If p equals \"default\" or conditions contains an entry for p,\nthen\n
              \n
            1. Let targetValue be the value of the p property in target.
            2. \n
            3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions).
            4. \n
            5. If resolved is equal to undefined, continue the loop.
            6. \n
            7. Return resolved.
            8. \n
            \n
          2. \n
          \n
        4. \n
        5. Return undefined.
        6. \n
        \n
      4. \n
      5. Otherwise, if target is an Array, then\n
          \n
        1. If _target.length is zero, return null.
        2. \n
        3. For each item targetValue in target, do\n
            \n
          1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions), continuing the loop on any Invalid Package Target\nerror.
          2. \n
          3. If resolved is undefined, continue the loop.
          4. \n
          5. Return resolved.
          6. \n
          \n
        4. \n
        5. Return or throw the last fallback resolution null return or error.
        6. \n
        \n
      6. \n
      7. Otherwise, if target is null, return null.
      8. \n
      9. Otherwise throw an Invalid Package Target error.
      10. \n
      \n
      \n

      ESM_FORMAT(url)

      \n
      \n
        \n
      1. Assert: url corresponds to an existing file.
      2. \n
      3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
      4. \n
      5. If url ends in \".mjs\", then\n
          \n
        1. Return \"module\".
        2. \n
        \n
      6. \n
      7. If url ends in \".cjs\", then\n
          \n
        1. Return \"commonjs\".
        2. \n
        \n
      8. \n
      9. If pjson?.type exists and is \"module\", then\n
          \n
        1. If url ends in \".js\", then\n
            \n
          1. Return \"module\".
          2. \n
          \n
        2. \n
        3. Throw an Unsupported File Extension error.
        4. \n
        \n
      10. \n
      11. Otherwise,\n
          \n
        1. Throw an Unsupported File Extension error.
        2. \n
        \n
      12. \n
      \n
      \n

      READ_PACKAGE_SCOPE(url)

      \n
      \n
        \n
      1. Let scopeURL be url.
      2. \n
      3. While scopeURL is not the file system root,\n
          \n
        1. Set scopeURL to the parent URL of scopeURL.
        2. \n
        3. If scopeURL ends in a \"node_modules\" path segment, return null.
        4. \n
        5. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
        6. \n
        7. If pjson is not null, then\n
            \n
          1. Return pjson.
          2. \n
          \n
        8. \n
        \n
      4. \n
      5. Return null.
      6. \n
      \n
      \n

      READ_PACKAGE_JSON(packageURL)

      \n
      \n
        \n
      1. Let pjsonURL be the resolution of \"package.json\" within packageURL.
      2. \n
      3. If the file at pjsonURL does not exist, then\n
          \n
        1. Return null.
        2. \n
        \n
      4. \n
      5. If the file at packageURL does not parse as valid JSON, then\n
          \n
        1. Throw an Invalid Package Configuration error.
        2. \n
        \n
      6. \n
      7. Return the parsed JSON source of the file at pjsonURL.
      8. \n
      \n
      ", + "type": "module", + "displayName": "Resolver Algorithm Specification" + }, + { + "textRaw": "Customizing ESM specifier resolution algorithm", + "name": "customizing_esm_specifier_resolution_algorithm", + "desc": "

      The current specifier resolution does not support all default behavior of\nthe CommonJS loader. One of the behavior differences is automatic resolution\nof file extensions and the ability to import directories that have an index\nfile.

      \n

      The --experimental-specifier-resolution=[mode] flag can be used to customize\nthe extension resolution algorithm. The default mode is explicit, which\nrequires the full path to a module be provided to the loader. To enable the\nautomatic extension resolution and importing from directories that include an\nindex file use the node mode.

      \n
      $ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n
      \n", + "type": "module", + "displayName": "Customizing ESM specifier resolution algorithm" + } + ], + "type": "misc", + "displayName": "Resolution algorithm" + } + ], + "properties": [ + { + "textRaw": "`meta` {Object}", + "type": "Object", + "name": "meta", + "desc": "

      The import.meta metaproperty is an Object that contains the following\nproperty:

      \n
        \n
      • url <string> The absolute file: URL of the module.
      • \n
      " + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/esm.md b/doc/api/esm.md index f776f458141df5117c35b56ba7cec782fe973435..3c76d1d6cc5cac3a41ac8854aeee5919f74827d8 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -5,6 +5,10 @@ -> Stability: 1 - Experimental +> Stability: 2 - Stable ## Introduction @@ -55,15 +59,9 @@ console.log(addTwo(4)); ``` Node.js fully supports ECMAScript modules as they are currently specified and -provides limited interoperability between them and the existing module format, +provides interoperability between them and its original module format, [CommonJS][]. -Node.js contains support for ES Modules based upon the -[Node.js EP for ES Modules][] and the [ECMAScript-modules implementation][]. - -Expect major changes in the implementation including interoperability support, -specifier resolution, and default behavior. - @@ -1268,9 +1266,7 @@ success! [CommonJS]: modules.html [Conditional exports]: packages.html#packages_conditional_exports [Dynamic `import()`]: https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports -[ECMAScript-modules implementation]: https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md [ES Module Integration Proposal for Web Assembly]: https://github.com/webassembly/esm-integration -[Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md [Terminology]: #esm_terminology [WHATWG JSON modules specification]: https://html.spec.whatwg.org/#creating-a-json-module-script [`data:` URLs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs @@ -1288,7 +1284,7 @@ success! [`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array [dynamic instantiate hook]: #esm_code_dynamicinstantiate_code_hook [`util.TextDecoder`]: util.md#util_class_util_textdecoder -[cjs-module-lexer]: https://github.com/guybedford/cjs-module-lexer/tree/1.0.0 +[cjs-module-lexer]: https://github.com/guybedford/cjs-module-lexer/tree/1.2.1 [special scheme]: https://url.spec.whatwg.org/#special-scheme [the official standard format]: https://tc39.github.io/ecma262/#sec-modules [transpiler loader example]: #esm_transpiler_loader diff --git a/doc/api/events.html b/doc/api/events.html new file mode 100644 index 0000000000000000000000000000000000000000..78cacec65ccf4af40dcfe384f246e3be526dcacc --- /dev/null +++ b/doc/api/events.html @@ -0,0 +1,988 @@ + + + + + + + Events | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Events#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/events.js

      +

      Much of the Node.js core API is built around an idiomatic asynchronous +event-driven architecture in which certain kinds of objects (called "emitters") +emit named events that cause Function objects ("listeners") to be called.

      +

      For instance: a net.Server object emits an event each time a peer +connects to it; a fs.ReadStream emits an event when the file is opened; +a stream emits an event whenever data is available to be read.

      +

      All objects that emit events are instances of the EventEmitter class. These +objects expose an eventEmitter.on() function that allows one or more +functions to be attached to named events emitted by the object. Typically, +event names are camel-cased strings but any valid JavaScript property key +can be used.

      +

      When the EventEmitter object emits an event, all of the functions attached +to that specific event are called synchronously. Any values returned by the +called listeners are ignored and will be discarded.

      +

      The following example shows a simple EventEmitter instance with a single +listener. The eventEmitter.on() method is used to register listeners, while +the eventEmitter.emit() method is used to trigger the event.

      +
      const EventEmitter = require('events');
      +
      +class MyEmitter extends EventEmitter {}
      +
      +const myEmitter = new MyEmitter();
      +myEmitter.on('event', () => {
      +  console.log('an event occurred!');
      +});
      +myEmitter.emit('event');
      +

      Passing arguments and this to listeners#

      +

      The eventEmitter.emit() method allows an arbitrary set of arguments to be +passed to the listener functions. Keep in mind that when +an ordinary listener function is called, the standard this keyword +is intentionally set to reference the EventEmitter instance to which the +listener is attached.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', function(a, b) {
      +  console.log(a, b, this, this === myEmitter);
      +  // Prints:
      +  //   a b MyEmitter {
      +  //     domain: null,
      +  //     _events: { event: [Function] },
      +  //     _eventsCount: 1,
      +  //     _maxListeners: undefined } true
      +});
      +myEmitter.emit('event', 'a', 'b');
      +

      It is possible to use ES6 Arrow Functions as listeners, however, when doing so, +the this keyword will no longer reference the EventEmitter instance:

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', (a, b) => {
      +  console.log(a, b, this);
      +  // Prints: a b {}
      +});
      +myEmitter.emit('event', 'a', 'b');
      +

      Asynchronous vs. synchronous#

      +

      The EventEmitter calls all listeners synchronously in the order in which +they were registered. This ensures the proper sequencing of +events and helps avoid race conditions and logic errors. When appropriate, +listener functions can switch to an asynchronous mode of operation using +the setImmediate() or process.nextTick() methods:

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', (a, b) => {
      +  setImmediate(() => {
      +    console.log('this happens asynchronously');
      +  });
      +});
      +myEmitter.emit('event', 'a', 'b');
      +

      Handling events only once#

      +

      When a listener is registered using the eventEmitter.on() method, that +listener will be invoked every time the named event is emitted.

      +
      const myEmitter = new MyEmitter();
      +let m = 0;
      +myEmitter.on('event', () => {
      +  console.log(++m);
      +});
      +myEmitter.emit('event');
      +// Prints: 1
      +myEmitter.emit('event');
      +// Prints: 2
      +

      Using the eventEmitter.once() method, it is possible to register a listener +that is called at most once for a particular event. Once the event is emitted, +the listener is unregistered and then called.

      +
      const myEmitter = new MyEmitter();
      +let m = 0;
      +myEmitter.once('event', () => {
      +  console.log(++m);
      +});
      +myEmitter.emit('event');
      +// Prints: 1
      +myEmitter.emit('event');
      +// Ignored
      +

      Error events#

      +

      When an error occurs within an EventEmitter instance, the typical action is +for an 'error' event to be emitted. These are treated as special cases +within Node.js.

      +

      If an EventEmitter does not have at least one listener registered for the +'error' event, and an 'error' event is emitted, the error is thrown, a +stack trace is printed, and the Node.js process exits.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.emit('error', new Error('whoops!'));
      +// Throws and crashes Node.js
      +

      To guard against crashing the Node.js process the domain module can be +used. (Note, however, that the domain module is deprecated.)

      +

      As a best practice, listeners should always be added for the 'error' events.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('error', (err) => {
      +  console.error('whoops! there was an error');
      +});
      +myEmitter.emit('error', new Error('whoops!'));
      +// Prints: whoops! there was an error
      +

      It is possible to monitor 'error' events without consuming the emitted error +by installing a listener using the symbol errorMonitor.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on(EventEmitter.errorMonitor, (err) => {
      +  MyMonitoringTool.log(err);
      +});
      +myEmitter.emit('error', new Error('whoops!'));
      +// Still throws and crashes Node.js
      +

      Capture rejections of promises#

      +

      Stability: 1 - captureRejections is experimental.

      +

      Using async functions with event handlers is problematic, because it +can lead to an unhandled rejection in case of a thrown exception:

      +
      const ee = new EventEmitter();
      +ee.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +

      The captureRejections option in the EventEmitter constructor or the global +setting change this behavior, installing a .then(undefined, handler) +handler on the Promise. This handler routes the exception +asynchronously to the Symbol.for('nodejs.rejection') method +if there is one, or to 'error' event handler if there is none.

      +
      const ee1 = new EventEmitter({ captureRejections: true });
      +ee1.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +
      +ee1.on('error', console.log);
      +
      +const ee2 = new EventEmitter({ captureRejections: true });
      +ee2.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +
      +ee2[Symbol.for('nodejs.rejection')] = console.log;
      +

      Setting EventEmitter.captureRejections = true will change the default for all +new instances of EventEmitter.

      +
      EventEmitter.captureRejections = true;
      +const ee1 = new EventEmitter();
      +ee1.on('something', async (value) => {
      +  throw new Error('kaboom');
      +});
      +
      +ee1.on('error', console.log);
      +

      The 'error' events that are generated by the captureRejections behavior +do not have a catch handler to avoid infinite error loops: the +recommendation is to not use async functions as 'error' event handlers.

      +

      Class: EventEmitter#

      + +

      The EventEmitter class is defined and exposed by the events module:

      +
      const EventEmitter = require('events');
      +

      All EventEmitters emit the event 'newListener' when new listeners are +added and 'removeListener' when existing listeners are removed.

      +

      It supports the following option:

      + +

      Event: 'newListener'#

      + + +

      The EventEmitter instance will emit its own 'newListener' event before +a listener is added to its internal array of listeners.

      +

      Listeners registered for the 'newListener' event will be passed the event +name and a reference to the listener being added.

      +

      The fact that the event is triggered before adding the listener has a subtle +but important side effect: any additional listeners registered to the same +name within the 'newListener' callback will be inserted before the +listener that is in the process of being added.

      +
      const myEmitter = new MyEmitter();
      +// Only do this once so we don't loop forever
      +myEmitter.once('newListener', (event, listener) => {
      +  if (event === 'event') {
      +    // Insert a new listener in front
      +    myEmitter.on('event', () => {
      +      console.log('B');
      +    });
      +  }
      +});
      +myEmitter.on('event', () => {
      +  console.log('A');
      +});
      +myEmitter.emit('event');
      +// Prints:
      +//   B
      +//   A
      +

      Event: 'removeListener'#

      + + +

      The 'removeListener' event is emitted after the listener is removed.

      +

      EventEmitter.listenerCount(emitter, eventName)#

      + +

      Stability: 0 - Deprecated: Use emitter.listenerCount() instead.

      + +

      A class method that returns the number of listeners for the given eventName +registered on the given emitter.

      +
      const myEmitter = new MyEmitter();
      +myEmitter.on('event', () => {});
      +myEmitter.on('event', () => {});
      +console.log(EventEmitter.listenerCount(myEmitter, 'event'));
      +// Prints: 2
      +

      EventEmitter.defaultMaxListeners#

      + +

      By default, a maximum of 10 listeners can be registered for any single +event. This limit can be changed for individual EventEmitter instances +using the emitter.setMaxListeners(n) method. To change the default +for all EventEmitter instances, the EventEmitter.defaultMaxListeners +property can be used. If this value is not a positive number, a TypeError +will be thrown.

      +

      Take caution when setting the EventEmitter.defaultMaxListeners because the +change affects all EventEmitter instances, including those created before +the change is made. However, calling emitter.setMaxListeners(n) still has +precedence over EventEmitter.defaultMaxListeners.

      +

      This is not a hard limit. The EventEmitter instance will allow +more listeners to be added but will output a trace warning to stderr indicating +that a "possible EventEmitter memory leak" has been detected. For any single +EventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners() +methods can be used to temporarily avoid this warning:

      +
      emitter.setMaxListeners(emitter.getMaxListeners() + 1);
      +emitter.once('event', () => {
      +  // do stuff
      +  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
      +});
      +

      The --trace-warnings command line flag can be used to display the +stack trace for such warnings.

      +

      The emitted warning can be inspected with process.on('warning') and will +have the additional emitter, type and count properties, referring to +the event emitter instance, the event’s name and the number of attached +listeners, respectively. +Its name property is set to 'MaxListenersExceededWarning'.

      +

      EventEmitter.errorMonitor#

      + +

      This symbol shall be used to install a listener for only monitoring 'error' +events. Listeners installed using this symbol are called before the regular +'error' listeners are called.

      +

      Installing a listener using this symbol does not change the behavior once an +'error' event is emitted, therefore the process will still crash if no +regular 'error' listener is installed.

      +

      emitter.addListener(eventName, listener)#

      + + +

      Alias for emitter.on(eventName, listener).

      +

      emitter.emit(eventName[, ...args])#

      + + +

      Synchronously calls each of the listeners registered for the event named +eventName, in the order they were registered, passing the supplied arguments +to each.

      +

      Returns true if the event had listeners, false otherwise.

      +
      const EventEmitter = require('events');
      +const myEmitter = new EventEmitter();
      +
      +// First listener
      +myEmitter.on('event', function firstListener() {
      +  console.log('Helloooo! first listener');
      +});
      +// Second listener
      +myEmitter.on('event', function secondListener(arg1, arg2) {
      +  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
      +});
      +// Third listener
      +myEmitter.on('event', function thirdListener(...args) {
      +  const parameters = args.join(', ');
      +  console.log(`event with parameters ${parameters} in third listener`);
      +});
      +
      +console.log(myEmitter.listeners('event'));
      +
      +myEmitter.emit('event', 1, 2, 3, 4, 5);
      +
      +// Prints:
      +// [
      +//   [Function: firstListener],
      +//   [Function: secondListener],
      +//   [Function: thirdListener]
      +// ]
      +// Helloooo! first listener
      +// event with parameters 1, 2 in second listener
      +// event with parameters 1, 2, 3, 4, 5 in third listener
      +

      emitter.eventNames()#

      + + +

      Returns an array listing the events for which the emitter has registered +listeners. The values in the array will be strings or Symbols.

      +
      const EventEmitter = require('events');
      +const myEE = new EventEmitter();
      +myEE.on('foo', () => {});
      +myEE.on('bar', () => {});
      +
      +const sym = Symbol('symbol');
      +myEE.on(sym, () => {});
      +
      +console.log(myEE.eventNames());
      +// Prints: [ 'foo', 'bar', Symbol(symbol) ]
      +

      emitter.getMaxListeners()#

      + + +

      Returns the current max listener value for the EventEmitter which is either +set by emitter.setMaxListeners(n) or defaults to +EventEmitter.defaultMaxListeners.

      +

      emitter.listenerCount(eventName)#

      + + +

      Returns the number of listeners listening to the event named eventName.

      +

      emitter.listeners(eventName)#

      + + +

      Returns a copy of the array of listeners for the event named eventName.

      +
      server.on('connection', (stream) => {
      +  console.log('someone connected!');
      +});
      +console.log(util.inspect(server.listeners('connection')));
      +// Prints: [ [Function] ]
      +

      emitter.off(eventName, listener)#

      + + +

      Alias for emitter.removeListener().

      +

      emitter.on(eventName, listener)#

      + + +

      Adds the listener function to the end of the listeners array for the +event named eventName. No checks are made to see if the listener has +already been added. Multiple calls passing the same combination of eventName +and listener will result in the listener being added, and called, multiple +times.

      +
      server.on('connection', (stream) => {
      +  console.log('someone connected!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      By default, event listeners are invoked in the order they are added. The +emitter.prependListener() method can be used as an alternative to add the +event listener to the beginning of the listeners array.

      +
      const myEE = new EventEmitter();
      +myEE.on('foo', () => console.log('a'));
      +myEE.prependListener('foo', () => console.log('b'));
      +myEE.emit('foo');
      +// Prints:
      +//   b
      +//   a
      +

      emitter.once(eventName, listener)#

      + + +

      Adds a one-time listener function for the event named eventName. The +next time eventName is triggered, this listener is removed and then invoked.

      +
      server.once('connection', (stream) => {
      +  console.log('Ah, we have our first user!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      By default, event listeners are invoked in the order they are added. The +emitter.prependOnceListener() method can be used as an alternative to add the +event listener to the beginning of the listeners array.

      +
      const myEE = new EventEmitter();
      +myEE.once('foo', () => console.log('a'));
      +myEE.prependOnceListener('foo', () => console.log('b'));
      +myEE.emit('foo');
      +// Prints:
      +//   b
      +//   a
      +

      emitter.prependListener(eventName, listener)#

      + + +

      Adds the listener function to the beginning of the listeners array for the +event named eventName. No checks are made to see if the listener has +already been added. Multiple calls passing the same combination of eventName +and listener will result in the listener being added, and called, multiple +times.

      +
      server.prependListener('connection', (stream) => {
      +  console.log('someone connected!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.prependOnceListener(eventName, listener)#

      + + +

      Adds a one-time listener function for the event named eventName to the +beginning of the listeners array. The next time eventName is triggered, this +listener is removed, and then invoked.

      +
      server.prependOnceListener('connection', (stream) => {
      +  console.log('Ah, we have our first user!');
      +});
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.removeAllListeners([eventName])#

      + + +

      Removes all listeners, or those of the specified eventName.

      +

      It is bad practice to remove listeners added elsewhere in the code, +particularly when the EventEmitter instance was created by some other +component or module (e.g. sockets or file streams).

      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.removeListener(eventName, listener)#

      + + +

      Removes the specified listener from the listener array for the event named +eventName.

      +
      const callback = (stream) => {
      +  console.log('someone connected!');
      +};
      +server.on('connection', callback);
      +// ...
      +server.removeListener('connection', callback);
      +

      removeListener() will remove, at most, one instance of a listener from the +listener array. If any single listener has been added multiple times to the +listener array for the specified eventName, then removeListener() must be +called multiple times to remove each instance.

      +

      Once an event has been emitted, all listeners attached to it at the +time of emitting will be called in order. This implies that any +removeListener() or removeAllListeners() calls after emitting and +before the last listener finishes execution will not remove them from +emit() in progress. Subsequent events will behave as expected.

      +
      const myEmitter = new MyEmitter();
      +
      +const callbackA = () => {
      +  console.log('A');
      +  myEmitter.removeListener('event', callbackB);
      +};
      +
      +const callbackB = () => {
      +  console.log('B');
      +};
      +
      +myEmitter.on('event', callbackA);
      +
      +myEmitter.on('event', callbackB);
      +
      +// callbackA removes listener callbackB but it will still be called.
      +// Internal listener array at time of emit [callbackA, callbackB]
      +myEmitter.emit('event');
      +// Prints:
      +//   A
      +//   B
      +
      +// callbackB is now removed.
      +// Internal listener array [callbackA]
      +myEmitter.emit('event');
      +// Prints:
      +//   A
      +

      Because listeners are managed using an internal array, calling this will +change the position indices of any listener registered after the listener +being removed. This will not impact the order in which listeners are called, +but it means that any copies of the listener array as returned by +the emitter.listeners() method will need to be recreated.

      +

      When a single function has been added as a handler multiple times for a single +event (as in the example below), removeListener() will remove the most +recently added instance. In the example the once('ping') +listener is removed:

      +
      const ee = new EventEmitter();
      +
      +function pong() {
      +  console.log('pong');
      +}
      +
      +ee.on('ping', pong);
      +ee.once('ping', pong);
      +ee.removeListener('ping', pong);
      +
      +ee.emit('ping');
      +ee.emit('ping');
      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.setMaxListeners(n)#

      + + +

      By default EventEmitters will print a warning if more than 10 listeners are +added for a particular event. This is a useful default that helps finding +memory leaks. The emitter.setMaxListeners() method allows the limit to be +modified for this specific EventEmitter instance. The value can be set to +Infinity (or 0) to indicate an unlimited number of listeners.

      +

      Returns a reference to the EventEmitter, so that calls can be chained.

      +

      emitter.rawListeners(eventName)#

      + + +

      Returns a copy of the array of listeners for the event named eventName, +including any wrappers (such as those created by .once()).

      +
      const emitter = new EventEmitter();
      +emitter.once('log', () => console.log('log once'));
      +
      +// Returns a new Array with a function `onceWrapper` which has a property
      +// `listener` which contains the original listener bound above
      +const listeners = emitter.rawListeners('log');
      +const logFnWrapper = listeners[0];
      +
      +// Logs "log once" to the console and does not unbind the `once` event
      +logFnWrapper.listener();
      +
      +// Logs "log once" to the console and removes the listener
      +logFnWrapper();
      +
      +emitter.on('log', () => console.log('log persistently'));
      +// Will return a new Array with a single function bound by `.on()` above
      +const newListeners = emitter.rawListeners('log');
      +
      +// Logs "log persistently" twice
      +newListeners[0]();
      +emitter.emit('log');
      +

      emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])#

      + +

      Stability: 1 - captureRejections is experimental.

      + +

      The Symbol.for('nodejs.rejection') method is called in case a +promise rejection happens when emitting an event and +captureRejections is enabled on the emitter. +It is possible to use events.captureRejectionSymbol in +place of Symbol.for('nodejs.rejection').

      +
      const { EventEmitter, captureRejectionSymbol } = require('events');
      +
      +class MyClass extends EventEmitter {
      +  constructor() {
      +    super({ captureRejections: true });
      +  }
      +
      +  [captureRejectionSymbol](err, event, ...args) {
      +    console.log('rejection happened for', event, 'with', err, ...args);
      +    this.destroy(err);
      +  }
      +
      +  destroy(err) {
      +    // Tear the resource down here.
      +  }
      +}
      +

      events.once(emitter, name)#

      + + +

      Creates a Promise that is fulfilled when the EventEmitter emits the given +event or that is rejected if the EventEmitter emits 'error' while waiting. +The Promise will resolve with an array of all the arguments emitted to the +given event.

      +

      This method is intentionally generic and works with the web platform +EventTarget interface, which has no special +'error' event semantics and does not listen to the 'error' event.

      +
      const { once, EventEmitter } = require('events');
      +
      +async function run() {
      +  const ee = new EventEmitter();
      +
      +  process.nextTick(() => {
      +    ee.emit('myevent', 42);
      +  });
      +
      +  const [value] = await once(ee, 'myevent');
      +  console.log(value);
      +
      +  const err = new Error('kaboom');
      +  process.nextTick(() => {
      +    ee.emit('error', err);
      +  });
      +
      +  try {
      +    await once(ee, 'myevent');
      +  } catch (err) {
      +    console.log('error happened', err);
      +  }
      +}
      +
      +run();
      +

      The special handling of the 'error' event is only used when events.once() +is used to wait for another event. If events.once() is used to wait for the +'error' event itself, then it is treated as any other kind of event without +special handling:

      +
      const { EventEmitter, once } = require('events');
      +
      +const ee = new EventEmitter();
      +
      +once(ee, 'error')
      +  .then(([err]) => console.log('ok', err.message))
      +  .catch((err) => console.log('error', err.message));
      +
      +ee.emit('error', new Error('boom'));
      +
      +// Prints: ok boom
      +

      Awaiting multiple events emitted on process.nextTick()#

      +

      There is an edge case worth noting when using the events.once() function +to await multiple events emitted on in the same batch of process.nextTick() +operations, or whenever multiple events are emitted synchronously. Specifically, +because the process.nextTick() queue is drained before the Promise microtask +queue, and because EventEmitter emits all events synchronously, it is possible +for events.once() to miss an event.

      +
      const { EventEmitter, once } = require('events');
      +
      +const myEE = new EventEmitter();
      +
      +async function foo() {
      +  await once(myEE, 'bar');
      +  console.log('bar');
      +
      +  // This Promise will never resolve because the 'foo' event will
      +  // have already been emitted before the Promise is created.
      +  await once(myEE, 'foo');
      +  console.log('foo');
      +}
      +
      +process.nextTick(() => {
      +  myEE.emit('bar');
      +  myEE.emit('foo');
      +});
      +
      +foo().then(() => console.log('done'));
      +

      To catch both events, create each of the Promises before awaiting either +of them, then it becomes possible to use Promise.all(), Promise.race(), +or Promise.allSettled():

      +
      const { EventEmitter, once } = require('events');
      +
      +const myEE = new EventEmitter();
      +
      +async function foo() {
      +  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);
      +  console.log('foo', 'bar');
      +}
      +
      +process.nextTick(() => {
      +  myEE.emit('bar');
      +  myEE.emit('foo');
      +});
      +
      +foo().then(() => console.log('done'));
      +

      events.captureRejections#

      + +

      Stability: 1 - captureRejections is experimental.

      +

      Value: <boolean>

      +

      Change the default captureRejections option on all new EventEmitter objects.

      +

      events.captureRejectionSymbol#

      + +

      Stability: 1 - captureRejections is experimental.

      +

      Value: Symbol.for('nodejs.rejection')

      +

      See how to write a custom rejection handler.

      +

      events.on(emitter, eventName)[src]#

      + + +
      const { on, EventEmitter } = require('events');
      +
      +(async () => {
      +  const ee = new EventEmitter();
      +
      +  // Emit later on
      +  process.nextTick(() => {
      +    ee.emit('foo', 'bar');
      +    ee.emit('foo', 42);
      +  });
      +
      +  for await (const event of on(ee, 'foo')) {
      +    // The execution of this inner block is synchronous and it
      +    // processes one event at a time (even with await). Do not use
      +    // if concurrent execution is required.
      +    console.log(event); // prints ['bar'] [42]
      +  }
      +  // Unreachable here
      +})();
      +

      Returns an AsyncIterator that iterates eventName events. It will throw +if the EventEmitter emits 'error'. It removes all listeners when +exiting the loop. The value returned by each iteration is an array +composed of the emitted event arguments.

      + +
      +
      +
      + + diff --git a/doc/api/events.json b/doc/api/events.json new file mode 100644 index 0000000000000000000000000000000000000000..ea26248e603826eb7140b5e329c646e7bd3e429f --- /dev/null +++ b/doc/api/events.json @@ -0,0 +1,777 @@ +{ + "type": "module", + "source": "doc/api/events.md", + "modules": [ + { + "textRaw": "Events", + "name": "Events", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "type": "module", + "desc": "

      Source Code: lib/events.js

      \n

      Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called \"emitters\")\nemit named events that cause Function objects (\"listeners\") to be called.

      \n

      For instance: a net.Server object emits an event each time a peer\nconnects to it; a fs.ReadStream emits an event when the file is opened;\na stream emits an event whenever data is available to be read.

      \n

      All objects that emit events are instances of the EventEmitter class. These\nobjects expose an eventEmitter.on() function that allows one or more\nfunctions to be attached to named events emitted by the object. Typically,\nevent names are camel-cased strings but any valid JavaScript property key\ncan be used.

      \n

      When the EventEmitter object emits an event, all of the functions attached\nto that specific event are called synchronously. Any values returned by the\ncalled listeners are ignored and will be discarded.

      \n

      The following example shows a simple EventEmitter instance with a single\nlistener. The eventEmitter.on() method is used to register listeners, while\nthe eventEmitter.emit() method is used to trigger the event.

      \n
      const EventEmitter = require('events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n  console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
      ", + "modules": [ + { + "textRaw": "Passing arguments and `this` to listeners", + "name": "passing_arguments_and_`this`_to_listeners", + "desc": "

      The eventEmitter.emit() method allows an arbitrary set of arguments to be\npassed to the listener functions. Keep in mind that when\nan ordinary listener function is called, the standard this keyword\nis intentionally set to reference the EventEmitter instance to which the\nlistener is attached.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n  console.log(a, b, this, this === myEmitter);\n  // Prints:\n  //   a b MyEmitter {\n  //     domain: null,\n  //     _events: { event: [Function] },\n  //     _eventsCount: 1,\n  //     _maxListeners: undefined } true\n});\nmyEmitter.emit('event', 'a', 'b');\n
      \n

      It is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this keyword will no longer reference the EventEmitter instance:

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  console.log(a, b, this);\n  // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');\n
      ", + "type": "module", + "displayName": "Passing arguments and `this` to listeners" + }, + { + "textRaw": "Asynchronous vs. synchronous", + "name": "asynchronous_vs._synchronous", + "desc": "

      The EventEmitter calls all listeners synchronously in the order in which\nthey were registered. This ensures the proper sequencing of\nevents and helps avoid race conditions and logic errors. When appropriate,\nlistener functions can switch to an asynchronous mode of operation using\nthe setImmediate() or process.nextTick() methods:

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  setImmediate(() => {\n    console.log('this happens asynchronously');\n  });\n});\nmyEmitter.emit('event', 'a', 'b');\n
      ", + "type": "module", + "displayName": "Asynchronous vs. synchronous" + }, + { + "textRaw": "Handling events only once", + "name": "handling_events_only_once", + "desc": "

      When a listener is registered using the eventEmitter.on() method, that\nlistener will be invoked every time the named event is emitted.

      \n
      const myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.on('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Prints: 2\n
      \n

      Using the eventEmitter.once() method, it is possible to register a listener\nthat is called at most once for a particular event. Once the event is emitted,\nthe listener is unregistered and then called.

      \n
      const myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.once('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Ignored\n
      ", + "type": "module", + "displayName": "Handling events only once" + }, + { + "textRaw": "Error events", + "name": "error_events", + "desc": "

      When an error occurs within an EventEmitter instance, the typical action is\nfor an 'error' event to be emitted. These are treated as special cases\nwithin Node.js.

      \n

      If an EventEmitter does not have at least one listener registered for the\n'error' event, and an 'error' event is emitted, the error is thrown, a\nstack trace is printed, and the Node.js process exits.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n
      \n

      To guard against crashing the Node.js process the domain module can be\nused. (Note, however, that the domain module is deprecated.)

      \n

      As a best practice, listeners should always be added for the 'error' events.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n  console.error('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Prints: whoops! there was an error\n
      \n

      It is possible to monitor 'error' events without consuming the emitted error\nby installing a listener using the symbol errorMonitor.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on(EventEmitter.errorMonitor, (err) => {\n  MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n
      ", + "type": "module", + "displayName": "Error events" + }, + { + "textRaw": "Capture rejections of promises", + "name": "capture_rejections_of_promises", + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "

      Using async functions with event handlers is problematic, because it\ncan lead to an unhandled rejection in case of a thrown exception:

      \n
      const ee = new EventEmitter();\nee.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n
      \n

      The captureRejections option in the EventEmitter constructor or the global\nsetting change this behavior, installing a .then(undefined, handler)\nhandler on the Promise. This handler routes the exception\nasynchronously to the Symbol.for('nodejs.rejection') method\nif there is one, or to 'error' event handler if there is none.

      \n
      const ee1 = new EventEmitter({ captureRejections: true });\nee1.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nconst ee2 = new EventEmitter({ captureRejections: true });\nee2.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee2[Symbol.for('nodejs.rejection')] = console.log;\n
      \n

      Setting EventEmitter.captureRejections = true will change the default for all\nnew instances of EventEmitter.

      \n
      EventEmitter.captureRejections = true;\nconst ee1 = new EventEmitter();\nee1.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n
      \n

      The 'error' events that are generated by the captureRejections behavior\ndo not have a catch handler to avoid infinite error loops: the\nrecommendation is to not use async functions as 'error' event handlers.

      ", + "type": "module", + "displayName": "Capture rejections of promises" + } + ], + "classes": [ + { + "textRaw": "Class: `EventEmitter`", + "type": "class", + "name": "EventEmitter", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/27867", + "description": "Added captureRejections option." + } + ] + }, + "desc": "

      The EventEmitter class is defined and exposed by the events module:

      \n
      const EventEmitter = require('events');\n
      \n

      All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when existing listeners are removed.

      \n

      It supports the following option:

      \n", + "events": [ + { + "textRaw": "Event: 'newListener'", + "type": "event", + "name": "newListener", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event being listened for", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event being listened for" + }, + { + "textRaw": "`listener` {Function} The event handler function", + "name": "listener", + "type": "Function", + "desc": "The event handler function" + } + ], + "desc": "

      The EventEmitter instance will emit its own 'newListener' event before\na listener is added to its internal array of listeners.

      \n

      Listeners registered for the 'newListener' event will be passed the event\nname and a reference to the listener being added.

      \n

      The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any additional listeners registered to the same\nname within the 'newListener' callback will be inserted before the\nlistener that is in the process of being added.

      \n
      const myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n  if (event === 'event') {\n    // Insert a new listener in front\n    myEmitter.on('event', () => {\n      console.log('B');\n    });\n  }\n});\nmyEmitter.on('event', () => {\n  console.log('A');\n});\nmyEmitter.emit('event');\n// Prints:\n//   B\n//   A\n
      " + }, + { + "textRaw": "Event: `'removeListener'`", + "type": "event", + "name": "removeListener", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [ + { + "version": "v6.1.0, v4.7.0", + "pr-url": "https://github.com/nodejs/node/pull/6394", + "description": "For listeners attached using `.once()`, the `listener` argument now yields the original listener function." + } + ] + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The event name", + "name": "eventName", + "type": "string|symbol", + "desc": "The event name" + }, + { + "textRaw": "`listener` {Function} The event handler function", + "name": "listener", + "type": "Function", + "desc": "The event handler function" + } + ], + "desc": "

      The 'removeListener' event is emitted after the listener is removed.

      " + } + ], + "methods": [ + { + "textRaw": "`EventEmitter.listenerCount(emitter, eventName)`", + "type": "method", + "name": "listenerCount", + "meta": { + "added": [ + "v0.9.12" + ], + "deprecated": [ + "v3.2.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`emitter` {EventEmitter} The emitter to query", + "name": "emitter", + "type": "EventEmitter", + "desc": "The emitter to query" + }, + { + "textRaw": "`eventName` {string|symbol} The event name", + "name": "eventName", + "type": "string|symbol", + "desc": "The event name" + } + ] + } + ], + "desc": "

      A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.

      \n
      const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n// Prints: 2\n
      " + }, + { + "textRaw": "`emitter.addListener(eventName, listener)`", + "type": "method", + "name": "addListener", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias for emitter.on(eventName, listener).

      " + }, + { + "textRaw": "`emitter.emit(eventName[, ...args])`", + "type": "method", + "name": "emit", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`...args` {any}", + "name": "...args", + "type": "any" + } + ] + } + ], + "desc": "

      Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.

      \n

      Returns true if the event had listeners, false otherwise.

      \n
      const EventEmitter = require('events');\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n  console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n  const parameters = args.join(', ');\n  console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n//   [Function: firstListener],\n//   [Function: secondListener],\n//   [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n
      " + }, + { + "textRaw": "`emitter.eventNames()`", + "type": "method", + "name": "eventNames", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Array}", + "name": "return", + "type": "Array" + }, + "params": [] + } + ], + "desc": "

      Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array will be strings or Symbols.

      \n
      const EventEmitter = require('events');\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n
      " + }, + { + "textRaw": "`emitter.getMaxListeners()`", + "type": "method", + "name": "getMaxListeners", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nEventEmitter.defaultMaxListeners.

      " + }, + { + "textRaw": "`emitter.listenerCount(eventName)`", + "type": "method", + "name": "listenerCount", + "meta": { + "added": [ + "v3.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event being listened for", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event being listened for" + } + ] + } + ], + "desc": "

      Returns the number of listeners listening to the event named eventName.

      " + }, + { + "textRaw": "`emitter.listeners(eventName)`", + "type": "method", + "name": "listeners", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6881", + "description": "For listeners attached using `.once()` this returns the original listeners instead of wrapper functions now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function[]}", + "name": "return", + "type": "Function[]" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + } + ] + } + ], + "desc": "

      Returns a copy of the array of listeners for the event named eventName.

      \n
      server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n// Prints: [ [Function] ]\n
      " + }, + { + "textRaw": "`emitter.off(eventName, listener)`", + "type": "method", + "name": "off", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias for emitter.removeListener().

      " + }, + { + "textRaw": "`emitter.on(eventName, listener)`", + "type": "method", + "name": "on", + "meta": { + "added": [ + "v0.1.101" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds the listener function to the end of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.

      \n
      server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      \n

      By default, event listeners are invoked in the order they are added. The\nemitter.prependListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.

      \n
      const myEE = new EventEmitter();\nmyEE.on('foo', () => console.log('a'));\nmyEE.prependListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n//   b\n//   a\n
      " + }, + { + "textRaw": "`emitter.once(eventName, listener)`", + "type": "method", + "name": "once", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds a one-time listener function for the event named eventName. The\nnext time eventName is triggered, this listener is removed and then invoked.

      \n
      server.once('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      \n

      By default, event listeners are invoked in the order they are added. The\nemitter.prependOnceListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.

      \n
      const myEE = new EventEmitter();\nmyEE.once('foo', () => console.log('a'));\nmyEE.prependOnceListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n//   b\n//   a\n
      " + }, + { + "textRaw": "`emitter.prependListener(eventName, listener)`", + "type": "method", + "name": "prependListener", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds the listener function to the beginning of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.

      \n
      server.prependListener('connection', (stream) => {\n  console.log('someone connected!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.prependOnceListener(eventName, listener)`", + "type": "method", + "name": "prependOnceListener", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol} The name of the event.", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event." + }, + { + "textRaw": "`listener` {Function} The callback function", + "name": "listener", + "type": "Function", + "desc": "The callback function" + } + ] + } + ], + "desc": "

      Adds a one-time listener function for the event named eventName to the\nbeginning of the listeners array. The next time eventName is triggered, this\nlistener is removed, and then invoked.

      \n
      server.prependOnceListener('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.removeAllListeners([eventName])`", + "type": "method", + "name": "removeAllListeners", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + } + ] + } + ], + "desc": "

      Removes all listeners, or those of the specified eventName.

      \n

      It is bad practice to remove listeners added elsewhere in the code,\nparticularly when the EventEmitter instance was created by some other\ncomponent or module (e.g. sockets or file streams).

      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.removeListener(eventName, listener)`", + "type": "method", + "name": "removeListener", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function" + } + ] + } + ], + "desc": "

      Removes the specified listener from the listener array for the event named\neventName.

      \n
      const callback = (stream) => {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
      \n

      removeListener() will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified eventName, then removeListener() must be\ncalled multiple times to remove each instance.

      \n

      Once an event has been emitted, all listeners attached to it at the\ntime of emitting will be called in order. This implies that any\nremoveListener() or removeAllListeners() calls after emitting and\nbefore the last listener finishes execution will not remove them from\nemit() in progress. Subsequent events will behave as expected.

      \n
      const myEmitter = new MyEmitter();\n\nconst callbackA = () => {\n  console.log('A');\n  myEmitter.removeListener('event', callbackB);\n};\n\nconst callbackB = () => {\n  console.log('B');\n};\n\nmyEmitter.on('event', callbackA);\n\nmyEmitter.on('event', callbackB);\n\n// callbackA removes listener callbackB but it will still be called.\n// Internal listener array at time of emit [callbackA, callbackB]\nmyEmitter.emit('event');\n// Prints:\n//   A\n//   B\n\n// callbackB is now removed.\n// Internal listener array [callbackA]\nmyEmitter.emit('event');\n// Prints:\n//   A\n
      \n

      Because listeners are managed using an internal array, calling this will\nchange the position indices of any listener registered after the listener\nbeing removed. This will not impact the order in which listeners are called,\nbut it means that any copies of the listener array as returned by\nthe emitter.listeners() method will need to be recreated.

      \n

      When a single function has been added as a handler multiple times for a single\nevent (as in the example below), removeListener() will remove the most\nrecently added instance. In the example the once('ping')\nlistener is removed:

      \n
      const ee = new EventEmitter();\n\nfunction pong() {\n  console.log('pong');\n}\n\nee.on('ping', pong);\nee.once('ping', pong);\nee.removeListener('ping', pong);\n\nee.emit('ping');\nee.emit('ping');\n
      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.setMaxListeners(n)`", + "type": "method", + "name": "setMaxListeners", + "meta": { + "added": [ + "v0.3.5" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {EventEmitter}", + "name": "return", + "type": "EventEmitter" + }, + "params": [ + { + "textRaw": "`n` {integer}", + "name": "n", + "type": "integer" + } + ] + } + ], + "desc": "

      By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default that helps finding\nmemory leaks. The emitter.setMaxListeners() method allows the limit to be\nmodified for this specific EventEmitter instance. The value can be set to\nInfinity (or 0) to indicate an unlimited number of listeners.

      \n

      Returns a reference to the EventEmitter, so that calls can be chained.

      " + }, + { + "textRaw": "`emitter.rawListeners(eventName)`", + "type": "method", + "name": "rawListeners", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function[]}", + "name": "return", + "type": "Function[]" + }, + "params": [ + { + "textRaw": "`eventName` {string|symbol}", + "name": "eventName", + "type": "string|symbol" + } + ] + } + ], + "desc": "

      Returns a copy of the array of listeners for the event named eventName,\nincluding any wrappers (such as those created by .once()).

      \n
      const emitter = new EventEmitter();\nemitter.once('log', () => console.log('log once'));\n\n// Returns a new Array with a function `onceWrapper` which has a property\n// `listener` which contains the original listener bound above\nconst listeners = emitter.rawListeners('log');\nconst logFnWrapper = listeners[0];\n\n// Logs \"log once\" to the console and does not unbind the `once` event\nlogFnWrapper.listener();\n\n// Logs \"log once\" to the console and removes the listener\nlogFnWrapper();\n\nemitter.on('log', () => console.log('log persistently'));\n// Will return a new Array with a single function bound by `.on()` above\nconst newListeners = emitter.rawListeners('log');\n\n// Logs \"log persistently\" twice\nnewListeners[0]();\nemitter.emit('log');\n
      " + } + ], + "properties": [ + { + "textRaw": "`EventEmitter.defaultMaxListeners`", + "name": "defaultMaxListeners", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "desc": "

      By default, a maximum of 10 listeners can be registered for any single\nevent. This limit can be changed for individual EventEmitter instances\nusing the emitter.setMaxListeners(n) method. To change the default\nfor all EventEmitter instances, the EventEmitter.defaultMaxListeners\nproperty can be used. If this value is not a positive number, a TypeError\nwill be thrown.

      \n

      Take caution when setting the EventEmitter.defaultMaxListeners because the\nchange affects all EventEmitter instances, including those created before\nthe change is made. However, calling emitter.setMaxListeners(n) still has\nprecedence over EventEmitter.defaultMaxListeners.

      \n

      This is not a hard limit. The EventEmitter instance will allow\nmore listeners to be added but will output a trace warning to stderr indicating\nthat a \"possible EventEmitter memory leak\" has been detected. For any single\nEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()\nmethods can be used to temporarily avoid this warning:

      \n
      emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
      \n

      The --trace-warnings command line flag can be used to display the\nstack trace for such warnings.

      \n

      The emitted warning can be inspected with process.on('warning') and will\nhave the additional emitter, type and count properties, referring to\nthe event emitter instance, the event’s name and the number of attached\nlisteners, respectively.\nIts name property is set to 'MaxListenersExceededWarning'.

      " + }, + { + "textRaw": "`EventEmitter.errorMonitor`", + "name": "errorMonitor", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      This symbol shall be used to install a listener for only monitoring 'error'\nevents. Listeners installed using this symbol are called before the regular\n'error' listeners are called.

      \n

      Installing a listener using this symbol does not change the behavior once an\n'error' event is emitted, therefore the process will still crash if no\nregular 'error' listener is installed.

      " + } + ], + "modules": [ + { + "textRaw": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`", + "name": "`emitter[symbol.for('nodejs.rejection')](err,_eventname[,_...args])`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "\n

      The Symbol.for('nodejs.rejection') method is called in case a\npromise rejection happens when emitting an event and\ncaptureRejections is enabled on the emitter.\nIt is possible to use events.captureRejectionSymbol in\nplace of Symbol.for('nodejs.rejection').

      \n
      const { EventEmitter, captureRejectionSymbol } = require('events');\n\nclass MyClass extends EventEmitter {\n  constructor() {\n    super({ captureRejections: true });\n  }\n\n  [captureRejectionSymbol](err, event, ...args) {\n    console.log('rejection happened for', event, 'with', err, ...args);\n    this.destroy(err);\n  }\n\n  destroy(err) {\n    // Tear the resource down here.\n  }\n}\n
      ", + "type": "module", + "displayName": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`" + } + ] + } + ], + "methods": [ + { + "textRaw": "`events.once(emitter, name)`", + "type": "method", + "name": "once", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`emitter` {EventEmitter}", + "name": "emitter", + "type": "EventEmitter" + }, + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Creates a Promise that is fulfilled when the EventEmitter emits the given\nevent or that is rejected if the EventEmitter emits 'error' while waiting.\nThe Promise will resolve with an array of all the arguments emitted to the\ngiven event.

      \n

      This method is intentionally generic and works with the web platform\nEventTarget interface, which has no special\n'error' event semantics and does not listen to the 'error' event.

      \n
      const { once, EventEmitter } = require('events');\n\nasync function run() {\n  const ee = new EventEmitter();\n\n  process.nextTick(() => {\n    ee.emit('myevent', 42);\n  });\n\n  const [value] = await once(ee, 'myevent');\n  console.log(value);\n\n  const err = new Error('kaboom');\n  process.nextTick(() => {\n    ee.emit('error', err);\n  });\n\n  try {\n    await once(ee, 'myevent');\n  } catch (err) {\n    console.log('error happened', err);\n  }\n}\n\nrun();\n
      \n

      The special handling of the 'error' event is only used when events.once()\nis used to wait for another event. If events.once() is used to wait for the\n'error' event itself, then it is treated as any other kind of event without\nspecial handling:

      \n
      const { EventEmitter, once } = require('events');\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n  .then(([err]) => console.log('ok', err.message))\n  .catch((err) => console.log('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n
      ", + "modules": [ + { + "textRaw": "Awaiting multiple events emitted on `process.nextTick()`", + "name": "awaiting_multiple_events_emitted_on_`process.nexttick()`", + "desc": "

      There is an edge case worth noting when using the events.once() function\nto await multiple events emitted on in the same batch of process.nextTick()\noperations, or whenever multiple events are emitted synchronously. Specifically,\nbecause the process.nextTick() queue is drained before the Promise microtask\nqueue, and because EventEmitter emits all events synchronously, it is possible\nfor events.once() to miss an event.

      \n
      const { EventEmitter, once } = require('events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n  await once(myEE, 'bar');\n  console.log('bar');\n\n  // This Promise will never resolve because the 'foo' event will\n  // have already been emitted before the Promise is created.\n  await once(myEE, 'foo');\n  console.log('foo');\n}\n\nprocess.nextTick(() => {\n  myEE.emit('bar');\n  myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
      \n

      To catch both events, create each of the Promises before awaiting either\nof them, then it becomes possible to use Promise.all(), Promise.race(),\nor Promise.allSettled():

      \n
      const { EventEmitter, once } = require('events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);\n  console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n  myEE.emit('bar');\n  myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
      ", + "type": "module", + "displayName": "Awaiting multiple events emitted on `process.nextTick()`" + } + ] + }, + { + "textRaw": "events.on(emitter, eventName)", + "type": "method", + "name": "on", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter`", + "name": "return", + "type": "AsyncIterator", + "desc": "that iterates `eventName` events emitted by the `emitter`" + }, + "params": [ + { + "textRaw": "`emitter` {EventEmitter}", + "name": "emitter", + "type": "EventEmitter" + }, + { + "textRaw": "`eventName` {string|symbol} The name of the event being listened for", + "name": "eventName", + "type": "string|symbol", + "desc": "The name of the event being listened for" + } + ] + } + ], + "desc": "
      const { on, EventEmitter } = require('events');\n\n(async () => {\n  const ee = new EventEmitter();\n\n  // Emit later on\n  process.nextTick(() => {\n    ee.emit('foo', 'bar');\n    ee.emit('foo', 42);\n  });\n\n  for await (const event of on(ee, 'foo')) {\n    // The execution of this inner block is synchronous and it\n    // processes one event at a time (even with await). Do not use\n    // if concurrent execution is required.\n    console.log(event); // prints ['bar'] [42]\n  }\n  // Unreachable here\n})();\n
      \n

      Returns an AsyncIterator that iterates eventName events. It will throw\nif the EventEmitter emits 'error'. It removes all listeners when\nexiting the loop. The value returned by each iteration is an array\ncomposed of the emitted event arguments.

      " + } + ], + "properties": [ + { + "textRaw": "`events.captureRejections`", + "name": "captureRejections", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "

      Value: <boolean>

      \n

      Change the default captureRejections option on all new EventEmitter objects.

      " + }, + { + "textRaw": "events.captureRejectionSymbol", + "name": "captureRejectionSymbol", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "captureRejections is experimental.", + "desc": "

      Value: Symbol.for('nodejs.rejection')

      \n

      See how to write a custom rejection handler.

      " + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/fs.html b/doc/api/fs.html new file mode 100644 index 0000000000000000000000000000000000000000..87d353e3f1de98629c1ad289c086bbd8b6819617 --- /dev/null +++ b/doc/api/fs.html @@ -0,0 +1,5881 @@ + + + + + + + File system | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      File system#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/fs.js

      +

      The fs module enables interacting with the file system in a +way modeled on standard POSIX functions.

      +

      To use this module:

      +
      const fs = require('fs');
      +

      All file system operations have synchronous, callback, and promise-based +forms.

      +

      Synchronous example#

      +

      The synchronous form blocks the Node.js event loop and further JavaScript +execution until the operation is complete. Exceptions are thrown immediately +and can be handled using try…catch, or can be allowed to bubble up.

      +
      const fs = require('fs');
      +
      +try {
      +  fs.unlinkSync('/tmp/hello');
      +  console.log('successfully deleted /tmp/hello');
      +} catch (err) {
      +  // handle the error
      +}
      +

      Callback example#

      +

      The callback form takes a completion callback function as its last +argument and invokes the operation asynchronously. The arguments passed to +the completion callback depend on the method, but the first argument is always +reserved for an exception. If the operation is completed successfully, then +the first argument is null or undefined.

      +
      const fs = require('fs');
      +
      +fs.unlink('/tmp/hello', (err) => {
      +  if (err) throw err;
      +  console.log('successfully deleted /tmp/hello');
      +});
      +

      Promise example#

      +

      Promise-based operations return a Promise that is resolved when the +asynchronous operation is complete.

      +
      const fs = require('fs').promises;
      +
      +(async function(path) {
      +  try {
      +    await fs.unlink(path);
      +    console.log(`successfully deleted ${path}`);
      +  } catch (error) {
      +    console.error('there was an error:', error.message);
      +  }
      +})('/tmp/hello');
      +

      Ordering of callback and promise-based operations#

      +

      There is no guaranteed ordering when using either the callback or +promise-based methods. For example, the following is prone to error +because the fs.stat() operation might complete before the fs.rename() +operation:

      +
      fs.rename('/tmp/hello', '/tmp/world', (err) => {
      +  if (err) throw err;
      +  console.log('renamed complete');
      +});
      +fs.stat('/tmp/world', (err, stats) => {
      +  if (err) throw err;
      +  console.log(`stats: ${JSON.stringify(stats)}`);
      +});
      +

      To correctly order the operations, move the fs.stat() call into the callback +of the fs.rename() operation:

      +
      fs.rename('/tmp/hello', '/tmp/world', (err) => {
      +  if (err) throw err;
      +  fs.stat('/tmp/world', (err, stats) => {
      +    if (err) throw err;
      +    console.log(`stats: ${JSON.stringify(stats)}`);
      +  });
      +});
      +

      Or, use the promise-based API:

      +
      const fs = require('fs').promises;
      +
      +(async function(from, to) {
      +  try {
      +    await fs.rename(from, to);
      +    const stats = await fs.stat(to);
      +    console.log(`stats: ${JSON.stringify(stats)}`);
      +  } catch (error) {
      +    console.error('there was an error:', error.message);
      +  }
      +})('/tmp/hello', '/tmp/world');
      +

      File paths#

      +

      Most fs operations accept filepaths that may be specified in the form of +a string, a Buffer, or a URL object using the file: protocol.

      +

      String form paths are interpreted as UTF-8 character sequences identifying +the absolute or relative filename. Relative paths will be resolved relative +to the current working directory as determined by calling process.cwd().

      +

      Example using an absolute path on POSIX:

      +
      const fs = require('fs');
      +
      +fs.open('/open/some/file.txt', 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.close(fd, (err) => {
      +    if (err) throw err;
      +  });
      +});
      +

      Example using a relative path on POSIX (relative to process.cwd()):

      +
      fs.open('file.txt', 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.close(fd, (err) => {
      +    if (err) throw err;
      +  });
      +});
      +

      Paths specified using a Buffer are useful primarily on certain POSIX +operating systems that treat file paths as opaque byte sequences. On such +systems, it is possible for a single file path to contain sub-sequences that +use multiple character encodings. As with string paths, Buffer paths may +be relative or absolute:

      +

      Example using an absolute path on POSIX:

      +
      fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.close(fd, (err) => {
      +    if (err) throw err;
      +  });
      +});
      +

      On Windows, Node.js follows the concept of per-drive working directory. This +behavior can be observed when using a drive path without a backslash. For +example fs.readdirSync('C:\\') can potentially return a different result than +fs.readdirSync('C:'). For more information, see +this MSDN page.

      +

      URL object support#

      + +

      For most fs module functions, the path or filename argument may be passed +as a WHATWG URL object. Only URL objects using the file: protocol +are supported.

      +
      const fs = require('fs');
      +const fileUrl = new URL('file:///tmp/hello');
      +
      +fs.readFileSync(fileUrl);
      +

      file: URLs are always absolute paths.

      +

      Using WHATWG URL objects might introduce platform-specific behaviors.

      +

      On Windows, file: URLs with a host name convert to UNC paths, while file: +URLs with drive letters convert to local absolute paths. file: URLs without a +host name nor a drive letter will result in a throw:

      +
      // On Windows :
      +
      +// - WHATWG file URLs with hostname convert to UNC path
      +// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
      +fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
      +
      +// - WHATWG file URLs with drive letters convert to absolute path
      +// file:///C:/tmp/hello => C:\tmp\hello
      +fs.readFileSync(new URL('file:///C:/tmp/hello'));
      +
      +// - WHATWG file URLs without hostname must have a drive letters
      +fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
      +fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
      +// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
      +

      file: URLs with drive letters must use : as a separator just after +the drive letter. Using another separator will result in a throw.

      +

      On all other platforms, file: URLs with a host name are unsupported and will +result in a throw:

      +
      // On other platforms:
      +
      +// - WHATWG file URLs with hostname are unsupported
      +// file://hostname/p/a/t/h/file => throw!
      +fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
      +// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
      +
      +// - WHATWG file URLs convert to absolute path
      +// file:///tmp/hello => /tmp/hello
      +fs.readFileSync(new URL('file:///tmp/hello'));
      +

      A file: URL having encoded slash characters will result in a throw on all +platforms:

      +
      // On Windows
      +fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
      +fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
      +/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
      +\ or / characters */
      +
      +// On POSIX
      +fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
      +fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
      +/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
      +/ characters */
      +

      On Windows, file: URLs having encoded backslash will result in a throw:

      +
      // On Windows
      +fs.readFileSync(new URL('file:///C:/path/%5C'));
      +fs.readFileSync(new URL('file:///C:/path/%5c'));
      +/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
      +\ or / characters */
      +

      File descriptors#

      +

      On POSIX systems, for every process, the kernel maintains a table of currently +open files and resources. Each open file is assigned a simple numeric +identifier called a file descriptor. At the system-level, all file system +operations use these file descriptors to identify and track each specific +file. Windows systems use a different but conceptually similar mechanism for +tracking resources. To simplify things for users, Node.js abstracts away the +specific differences between operating systems and assigns all open files a +numeric file descriptor.

      +

      The fs.open() method is used to allocate a new file descriptor. Once +allocated, the file descriptor may be used to read data from, write data to, +or request information about the file.

      +
      fs.open('/open/some/file.txt', 'r', (err, fd) => {
      +  if (err) throw err;
      +  fs.fstat(fd, (err, stat) => {
      +    if (err) throw err;
      +    // use stat
      +
      +    // always close the file descriptor!
      +    fs.close(fd, (err) => {
      +      if (err) throw err;
      +    });
      +  });
      +});
      +

      Most operating systems limit the number of file descriptors that may be open +at any given time so it is critical to close the descriptor when operations +are completed. Failure to do so will result in a memory leak that will +eventually cause an application to crash.

      +

      Threadpool usage#

      +

      All file system APIs except fs.FSWatcher() and those that are explicitly +synchronous use libuv's threadpool, which can have surprising and negative +performance implications for some applications. See the +UV_THREADPOOL_SIZE documentation for more information.

      +

      Class: fs.Dir#

      + +

      A class representing a directory stream.

      +

      Created by fs.opendir(), fs.opendirSync(), or +fsPromises.opendir().

      +
      const fs = require('fs');
      +
      +async function print(path) {
      +  const dir = await fs.promises.opendir(path);
      +  for await (const dirent of dir) {
      +    console.log(dirent.name);
      +  }
      +}
      +print('./').catch(console.error);
      +

      dir.close()#

      + + +

      Asynchronously close the directory's underlying resource handle. +Subsequent reads will result in errors.

      +

      A Promise is returned that will be resolved after the resource has been +closed.

      +

      dir.close(callback)#

      + + +

      Asynchronously close the directory's underlying resource handle. +Subsequent reads will result in errors.

      +

      The callback will be called after the resource handle has been closed.

      +

      dir.closeSync()#

      + +

      Synchronously close the directory's underlying resource handle. +Subsequent reads will result in errors.

      +

      dir.path#

      + + +

      The read-only path of this directory as was provided to fs.opendir(), +fs.opendirSync(), or fsPromises.opendir().

      +

      dir.read()#

      + + +

      Asynchronously read the next directory entry via readdir(3) as an +fs.Dirent.

      +

      After the read is completed, a Promise is returned that will be resolved with +an fs.Dirent, or null if there are no more directory entries to read.

      +

      Directory entries returned by this function are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      dir.read(callback)#

      + + +

      Asynchronously read the next directory entry via readdir(3) as an +fs.Dirent.

      +

      After the read is completed, the callback will be called with an +fs.Dirent, or null if there are no more directory entries to read.

      +

      Directory entries returned by this function are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      dir.readSync()#

      + + +

      Synchronously read the next directory entry via readdir(3) as an +fs.Dirent.

      +

      If there are no more directory entries to read, null will be returned.

      +

      Directory entries returned by this function are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      dir[Symbol.asyncIterator]()#

      + + +

      Asynchronously iterates over the directory via readdir(3) until all entries have +been read.

      +

      Entries returned by the async iterator are always an fs.Dirent. +The null case from dir.read() is handled internally.

      +

      See fs.Dir for an example.

      +

      Directory entries returned by this iterator are in no particular order as +provided by the operating system's underlying directory mechanisms. +Entries added or removed while iterating over the directory may or may not be +included in the iteration results.

      +

      Class: fs.Dirent#

      + +

      A representation of a directory entry, which can be a file or a subdirectory +within the directory, as returned by reading from an fs.Dir. The +directory entry is a combination of the file name and file type pairs.

      +

      Additionally, when fs.readdir() or fs.readdirSync() is called with +the withFileTypes option set to true, the resulting array is filled with +fs.Dirent objects, rather than strings or Buffers.

      +

      dirent.isBlockDevice()#

      + + +

      Returns true if the fs.Dirent object describes a block device.

      +

      dirent.isCharacterDevice()#

      + + +

      Returns true if the fs.Dirent object describes a character device.

      +

      dirent.isDirectory()#

      + + +

      Returns true if the fs.Dirent object describes a file system +directory.

      +

      dirent.isFIFO()#

      + + +

      Returns true if the fs.Dirent object describes a first-in-first-out +(FIFO) pipe.

      +

      dirent.isFile()#

      + + +

      Returns true if the fs.Dirent object describes a regular file.

      +

      dirent.isSocket()#

      + + +

      Returns true if the fs.Dirent object describes a socket.

      +

      dirent.isSymbolicLink()#

      + + +

      Returns true if the fs.Dirent object describes a symbolic link.

      +

      dirent.name#

      + + +

      The file name that this fs.Dirent object refers to. The type of this +value is determined by the options.encoding passed to fs.readdir() or +fs.readdirSync().

      +

      Class: fs.FSWatcher#

      + + +

      A successful call to fs.watch() method will return a new fs.FSWatcher +object.

      +

      All fs.FSWatcher objects emit a 'change' event whenever a specific watched +file is modified.

      +

      Event: 'change'#

      + +
        +
      • eventType <string> The type of change event that has occurred
      • +
      • filename <string> | <Buffer> The filename that changed (if relevant/available)
      • +
      +

      Emitted when something changes in a watched directory or file. +See more details in fs.watch().

      +

      The filename argument may not be provided depending on operating system +support. If filename is provided, it will be provided as a Buffer if +fs.watch() is called with its encoding option set to 'buffer', otherwise +filename will be a UTF-8 string.

      +
      // Example when handled through fs.watch() listener
      +fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
      +  if (filename) {
      +    console.log(filename);
      +    // Prints: <Buffer ...>
      +  }
      +});
      +

      Event: 'close'#

      + +

      Emitted when the watcher stops watching for changes. The closed +fs.FSWatcher object is no longer usable in the event handler.

      +

      Event: 'error'#

      + + +

      Emitted when an error occurs while watching the file. The errored +fs.FSWatcher object is no longer usable in the event handler.

      +

      watcher.close()#

      + +

      Stop watching for changes on the given fs.FSWatcher. Once stopped, the +fs.FSWatcher object is no longer usable.

      +

      watcher.ref()#

      + + +

      When called, requests that the Node.js event loop not exit so long as the +FSWatcher is active. Calling watcher.ref() multiple times will have +no effect.

      +

      By default, all FSWatcher objects are "ref'ed", making it normally +unnecessary to call watcher.ref() unless watcher.unref() had been +called previously.

      +

      watcher.unref()#

      + + +

      When called, the active FSWatcher object will not require the Node.js +event loop to remain active. If there is no other activity keeping the +event loop running, the process may exit before the FSWatcher object's +callback is invoked. Calling watcher.unref() multiple times will have +no effect.

      +

      Class: fs.StatWatcher#

      + + +

      A successful call to fs.watchFile() method will return a new fs.StatWatcher +object.

      +

      watcher.ref()#

      + + +

      When called, requests that the Node.js event loop not exit so long as the +StatWatcher is active. Calling watcher.ref() multiple times will have +no effect.

      +

      By default, all StatWatcher objects are "ref'ed", making it normally +unnecessary to call watcher.ref() unless watcher.unref() had been +called previously.

      +

      watcher.unref()#

      + + +

      When called, the active StatWatcher object will not require the Node.js +event loop to remain active. If there is no other activity keeping the +event loop running, the process may exit before the StatWatcher object's +callback is invoked. Calling watcher.unref() multiple times will have +no effect.

      +

      Class: fs.ReadStream#

      + + +

      Instances of fs.ReadStream are created and returned using the +fs.createReadStream() function.

      +

      Event: 'close'#

      + +

      Emitted when the fs.ReadStream's underlying file descriptor has been closed.

      +

      Event: 'open'#

      + +
        +
      • fd <integer> Integer file descriptor used by the ReadStream.
      • +
      +

      Emitted when the fs.ReadStream's file descriptor has been opened.

      +

      Event: 'ready'#

      + +

      Emitted when the fs.ReadStream is ready to be used.

      +

      Fires immediately after 'open'.

      +

      readStream.bytesRead#

      + + +

      The number of bytes that have been read so far.

      +

      readStream.path#

      + + +

      The path to the file the stream is reading from as specified in the first +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 Buffer.

      +

      readStream.pending#

      + + +

      This property is true if the underlying file has not been opened yet, +i.e. before the 'ready' event is emitted.

      +

      Class: fs.Stats#

      + +

      A fs.Stats object provides information about a file.

      +

      Objects returned from fs.stat(), fs.lstat() and fs.fstat() and +their synchronous counterparts are of this type. +If bigint in the options passed to those methods is true, the numeric values +will be bigint instead of number, and the object will contain additional +nanosecond-precision properties suffixed with Ns.

      +
      Stats {
      +  dev: 2114,
      +  ino: 48064969,
      +  mode: 33188,
      +  nlink: 1,
      +  uid: 85,
      +  gid: 100,
      +  rdev: 0,
      +  size: 527,
      +  blksize: 4096,
      +  blocks: 8,
      +  atimeMs: 1318289051000.1,
      +  mtimeMs: 1318289051000.1,
      +  ctimeMs: 1318289051000.1,
      +  birthtimeMs: 1318289051000.1,
      +  atime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
      +

      bigint version:

      +
      BigIntStats {
      +  dev: 2114n,
      +  ino: 48064969n,
      +  mode: 33188n,
      +  nlink: 1n,
      +  uid: 85n,
      +  gid: 100n,
      +  rdev: 0n,
      +  size: 527n,
      +  blksize: 4096n,
      +  blocks: 8n,
      +  atimeMs: 1318289051000n,
      +  mtimeMs: 1318289051000n,
      +  ctimeMs: 1318289051000n,
      +  birthtimeMs: 1318289051000n,
      +  atimeNs: 1318289051000000000n,
      +  mtimeNs: 1318289051000000000n,
      +  ctimeNs: 1318289051000000000n,
      +  birthtimeNs: 1318289051000000000n,
      +  atime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
      +  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
      +

      stats.isBlockDevice()#

      + + +

      Returns true if the fs.Stats object describes a block device.

      +

      stats.isCharacterDevice()#

      + + +

      Returns true if the fs.Stats object describes a character device.

      +

      stats.isDirectory()#

      + + +

      Returns true if the fs.Stats object describes a file system directory.

      +

      stats.isFIFO()#

      + + +

      Returns true if the fs.Stats object describes a first-in-first-out (FIFO) +pipe.

      +

      stats.isFile()#

      + + +

      Returns true if the fs.Stats object describes a regular file.

      +

      stats.isSocket()#

      + + +

      Returns true if the fs.Stats object describes a socket.

      +

      stats.isSymbolicLink()#

      + + +

      Returns true if the fs.Stats object describes a symbolic link.

      +

      This method is only valid when using fs.lstat().

      +

      stats.dev#

      + +

      The numeric identifier of the device containing the file.

      +

      stats.ino#

      + +

      The file system specific "Inode" number for the file.

      +

      stats.mode#

      + +

      A bit-field describing the file type and mode.

      +

      stats.nlink#

      + +

      The number of hard-links that exist for the file.

      +

      stats.uid#

      + +

      The numeric user identifier of the user that owns the file (POSIX).

      +

      stats.gid#

      + +

      The numeric group identifier of the group that owns the file (POSIX).

      +

      stats.rdev#

      + +

      A numeric device identifier if the file represents a device.

      +

      stats.size#

      + +

      The size of the file in bytes.

      +

      stats.blksize#

      + +

      The file system block size for i/o operations.

      +

      stats.blocks#

      + +

      The number of blocks allocated for this file.

      +

      stats.atimeMs#

      + + +

      The timestamp indicating the last time this file was accessed expressed in +milliseconds since the POSIX Epoch.

      +

      stats.mtimeMs#

      + + +

      The timestamp indicating the last time this file was modified expressed in +milliseconds since the POSIX Epoch.

      +

      stats.ctimeMs#

      + + +

      The timestamp indicating the last time the file status was changed expressed +in milliseconds since the POSIX Epoch.

      +

      stats.birthtimeMs#

      + + +

      The timestamp indicating the creation time of this file expressed in +milliseconds since the POSIX Epoch.

      +

      stats.atimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the last time this file was accessed expressed in +nanoseconds since the POSIX Epoch.

      +

      stats.mtimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the last time this file was modified expressed in +nanoseconds since the POSIX Epoch.

      +

      stats.ctimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the last time the file status was changed expressed +in nanoseconds since the POSIX Epoch.

      +

      stats.birthtimeNs#

      + + +

      Only present when bigint: true is passed into the method that generates +the object. +The timestamp indicating the creation time of this file expressed in +nanoseconds since the POSIX Epoch.

      +

      stats.atime#

      + + +

      The timestamp indicating the last time this file was accessed.

      +

      stats.mtime#

      + + +

      The timestamp indicating the last time this file was modified.

      +

      stats.ctime#

      + + +

      The timestamp indicating the last time the file status was changed.

      +

      stats.birthtime#

      + + +

      The timestamp indicating the creation time of this file.

      +

      Stat time values#

      +

      The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are +numeric values that hold the corresponding times in milliseconds. Their +precision is platform specific. When bigint: true is passed into the +method that generates the object, the properties will be bigints, +otherwise they will be numbers.

      +

      The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are +bigints that hold the corresponding times in nanoseconds. They are +only present when bigint: true is passed into the method that generates +the object. Their precision is platform specific.

      +

      atime, mtime, ctime, and birthtime are +Date object alternate representations of the various times. The +Date and number values are not connected. Assigning a new number value, or +mutating the Date value, will not be reflected in the corresponding alternate +representation.

      +

      The times in the stat object have the following semantics:

      +
        +
      • atime "Access Time": Time when file data last accessed. Changed +by the mknod(2), utimes(2), and read(2) system calls.
      • +
      • mtime "Modified Time": Time when file data last modified. +Changed by the mknod(2), utimes(2), and write(2) system calls.
      • +
      • ctime "Change Time": Time when file status was last changed +(inode data modification). Changed by the chmod(2), chown(2), +link(2), mknod(2), rename(2), unlink(2), utimes(2), +read(2), and write(2) system calls.
      • +
      • birthtime "Birth Time": Time of file creation. Set once when the +file is created. On filesystems where birthtime is not available, +this field may instead hold either the ctime or +1970-01-01T00:00Z (ie, Unix epoch timestamp 0). This value may be greater +than atime or mtime in this case. On Darwin and other FreeBSD variants, +also set if the atime is explicitly set to an earlier value than the current +birthtime using the utimes(2) system call.
      • +
      +

      Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As +of 0.12, ctime is not "creation time", and on Unix systems, it never was.

      +

      Class: fs.WriteStream#

      + + +

      Instances of fs.WriteStream are created and returned using the +fs.createWriteStream() function.

      +

      Event: 'close'#

      + +

      Emitted when the WriteStream's underlying file descriptor has been closed.

      +

      Event: 'open'#

      + +
        +
      • fd <integer> Integer file descriptor used by the WriteStream.
      • +
      +

      Emitted when the WriteStream's file is opened.

      +

      Event: 'ready'#

      + +

      Emitted when the fs.WriteStream is ready to be used.

      +

      Fires immediately after 'open'.

      +

      writeStream.bytesWritten#

      + +

      The number of bytes written so far. Does not include data that is still queued +for writing.

      +

      writeStream.path#

      + +

      The path to the file the stream is writing to as specified in the first +argument to fs.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 Buffer.

      +

      writeStream.pending#

      + + +

      This property is true if the underlying file has not been opened yet, +i.e. before the 'ready' event is emitted.

      +

      fs.access(path[, mode], callback)#

      + + +

      Tests a user's permissions for the file or directory specified by path. +The mode argument is an optional integer that specifies the accessibility +checks to be performed. Check File access constants for possible values +of mode. It is possible to create a mask consisting of the bitwise OR of +two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      +

      The final argument, callback, is a callback function that is invoked with +a possible error argument. If any of the accessibility checks fail, the error +argument will be an Error object. The following examples check if +package.json exists, and if it is readable or writable.

      +
      const file = 'package.json';
      +
      +// Check if the file exists in the current directory.
      +fs.access(file, fs.constants.F_OK, (err) => {
      +  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
      +});
      +
      +// Check if the file is readable.
      +fs.access(file, fs.constants.R_OK, (err) => {
      +  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
      +});
      +
      +// Check if the file is writable.
      +fs.access(file, fs.constants.W_OK, (err) => {
      +  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
      +});
      +
      +// Check if the file exists in the current directory, and if it is writable.
      +fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
      +  if (err) {
      +    console.error(
      +      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
      +  } else {
      +    console.log(`${file} exists, and it is writable`);
      +  }
      +});
      +

      Do not use fs.access() to check for the accessibility of a file before calling +fs.open(), fs.readFile() or fs.writeFile(). Doing +so introduces a race condition, since other processes may change the file's +state between the two calls. Instead, user code should open/read/write the +file directly and handle the error raised if the file is not accessible.

      +

      write (NOT RECOMMENDED)

      +
      fs.access('myfile', (err) => {
      +  if (!err) {
      +    console.error('myfile already exists');
      +    return;
      +  }
      +
      +  fs.open('myfile', 'wx', (err, fd) => {
      +    if (err) throw err;
      +    writeMyData(fd);
      +  });
      +});
      +

      write (RECOMMENDED)

      +
      fs.open('myfile', 'wx', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'EEXIST') {
      +      console.error('myfile already exists');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  writeMyData(fd);
      +});
      +

      read (NOT RECOMMENDED)

      +
      fs.access('myfile', (err) => {
      +  if (err) {
      +    if (err.code === 'ENOENT') {
      +      console.error('myfile does not exist');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  fs.open('myfile', 'r', (err, fd) => {
      +    if (err) throw err;
      +    readMyData(fd);
      +  });
      +});
      +

      read (RECOMMENDED)

      +
      fs.open('myfile', 'r', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'ENOENT') {
      +      console.error('myfile does not exist');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  readMyData(fd);
      +});
      +

      The "not recommended" examples above check for accessibility and then use the +file; the "recommended" examples are better because they use the file directly +and handle the error, if any.

      +

      In general, check for the accessibility of a file only if the file will not be +used directly, for example when its accessibility is a signal from another +process.

      +

      On Windows, access-control policies (ACLs) on a directory may limit access to +a file or directory. The fs.access() function, however, does not check the +ACL and therefore may report that a path is accessible even if the ACL restricts +the user from reading or writing to it.

      +

      fs.accessSync(path[, mode])#

      + + +

      Synchronously tests a user's permissions for the file or directory specified +by path. The mode argument is an optional integer that specifies the +accessibility checks to be performed. Check File access constants for +possible values of mode. It is possible to create a mask consisting of +the bitwise OR of two or more values +(e.g. fs.constants.W_OK | fs.constants.R_OK).

      +

      If any of the accessibility checks fail, an Error will be thrown. Otherwise, +the method will return undefined.

      +
      try {
      +  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
      +  console.log('can read/write');
      +} catch (err) {
      +  console.error('no access!');
      +}
      +

      fs.appendFile(path, data[, options], callback)#

      + + +

      Asynchronously append data to a file, creating the file if it does not yet +exist. data can be a string or a Buffer.

      +
      fs.appendFile('message.txt', 'data to append', (err) => {
      +  if (err) throw err;
      +  console.log('The "data to append" was appended to file!');
      +});
      +

      If options is a string, then it specifies the encoding:

      +
      fs.appendFile('message.txt', 'data to append', 'utf8', callback);
      +

      The path may be specified as a numeric file descriptor that has been opened +for appending (using fs.open() or fs.openSync()). The file descriptor will +not be closed automatically.

      +
      fs.open('message.txt', 'a', (err, fd) => {
      +  if (err) throw err;
      +  fs.appendFile(fd, 'data to append', 'utf8', (err) => {
      +    fs.close(fd, (err) => {
      +      if (err) throw err;
      +    });
      +    if (err) throw err;
      +  });
      +});
      +

      fs.appendFileSync(path, data[, options])#

      + + +

      Synchronously append data to a file, creating the file if it does not yet +exist. data can be a string or a Buffer.

      +
      try {
      +  fs.appendFileSync('message.txt', 'data to append');
      +  console.log('The "data to append" was appended to file!');
      +} catch (err) {
      +  /* Handle the error */
      +}
      +

      If options is a string, then it specifies the encoding:

      +
      fs.appendFileSync('message.txt', 'data to append', 'utf8');
      +

      The path may be specified as a numeric file descriptor that has been opened +for appending (using fs.open() or fs.openSync()). The file descriptor will +not be closed automatically.

      +
      let fd;
      +
      +try {
      +  fd = fs.openSync('message.txt', 'a');
      +  fs.appendFileSync(fd, 'data to append', 'utf8');
      +} catch (err) {
      +  /* Handle the error */
      +} finally {
      +  if (fd !== undefined)
      +    fs.closeSync(fd);
      +}
      +

      fs.chmod(path, mode, callback)#

      + + +

      Asynchronously changes the permissions of a file. No arguments other than a +possible exception are given to the completion callback.

      +

      See also: chmod(2).

      +
      fs.chmod('my_file.txt', 0o775, (err) => {
      +  if (err) throw err;
      +  console.log('The permissions for file "my_file.txt" have been changed!');
      +});
      +

      File modes#

      +

      The mode argument used in both the fs.chmod() and fs.chmodSync() +methods is a numeric bitmask created using a logical OR of the following +constants:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantOctalDescription
      fs.constants.S_IRUSR0o400read by owner
      fs.constants.S_IWUSR0o200write by owner
      fs.constants.S_IXUSR0o100execute/search by owner
      fs.constants.S_IRGRP0o40read by group
      fs.constants.S_IWGRP0o20write by group
      fs.constants.S_IXGRP0o10execute/search by group
      fs.constants.S_IROTH0o4read by others
      fs.constants.S_IWOTH0o2write by others
      fs.constants.S_IXOTH0o1execute/search by others
      +

      An easier method of constructing the mode is to use a sequence of three +octal digits (e.g. 765). The left-most digit (7 in the example), specifies +the permissions for the file owner. The middle digit (6 in the example), +specifies permissions for the group. The right-most digit (5 in the example), +specifies the permissions for others.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      NumberDescription
      7read, write, and execute
      6read and write
      5read and execute
      4read only
      3write and execute
      2write only
      1execute only
      0no permission
      +

      For example, the octal value 0o765 means:

      +
        +
      • The owner may read, write and execute the file.
      • +
      • The group may read and write the file.
      • +
      • Others may read and execute the file.
      • +
      +

      When using raw numbers where file modes are expected, any value larger than +0o777 may result in platform-specific behaviors that are not supported to work +consistently. Therefore constants like S_ISVTX, S_ISGID or S_ISUID are not +exposed in fs.constants.

      +

      Caveats: on Windows only the write permission can be changed, and the +distinction among the permissions of group, owner or others is not +implemented.

      +

      fs.chmodSync(path, mode)#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.chmod().

      +

      See also: chmod(2).

      +

      fs.chown(path, uid, gid, callback)#

      + + +

      Asynchronously changes owner and group of a file. No arguments other than a +possible exception are given to the completion callback.

      +

      See also: chown(2).

      +

      fs.chownSync(path, uid, gid)#

      + + +

      Synchronously changes owner and group of a file. Returns undefined. +This is the synchronous version of fs.chown().

      +

      See also: chown(2).

      +

      fs.close(fd, callback)#

      + + +

      Asynchronous close(2). No arguments other than a possible exception are given +to the completion callback.

      +

      Calling fs.close() on any file descriptor (fd) that is currently in use +through any other fs operation may lead to undefined behavior.

      +

      fs.closeSync(fd)#

      + + +

      Synchronous close(2). Returns undefined.

      +

      Calling fs.closeSync() on any file descriptor (fd) that is currently in use +through any other fs operation may lead to undefined behavior.

      +

      fs.constants#

      + +

      Returns an object containing commonly used constants for file system +operations. The specific constants currently defined are described in +FS constants.

      +

      fs.copyFile(src, dest[, flags], callback)#

      + + +

      Asynchronously copies src to dest. By default, dest is overwritten if it +already exists. No arguments other than a possible exception are given to the +callback function. Node.js makes no guarantees about the atomicity of the copy +operation. If an error occurs after the destination file has been opened for +writing, Node.js will attempt to remove the destination.

      +

      flags is an optional integer that specifies the behavior +of the copy operation. It is possible to create a mask consisting of the bitwise +OR of two or more values (e.g. +fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      +
        +
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already +exists.
      • +
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a +copy-on-write reflink. If the platform does not support copy-on-write, then a +fallback copy mechanism is used.
      • +
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to +create a copy-on-write reflink. If the platform does not support copy-on-write, +then the operation will fail.
      • +
      +
      const fs = require('fs');
      +
      +// destination.txt will be created or overwritten by default.
      +fs.copyFile('source.txt', 'destination.txt', (err) => {
      +  if (err) throw err;
      +  console.log('source.txt was copied to destination.txt');
      +});
      +

      If the third argument is a number, then it specifies flags:

      +
      const fs = require('fs');
      +const { COPYFILE_EXCL } = fs.constants;
      +
      +// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
      +fs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback);
      +

      fs.copyFileSync(src, dest[, flags])#

      + + +

      Synchronously copies src to dest. By default, dest is overwritten if it +already exists. Returns undefined. Node.js makes no guarantees about the +atomicity of the copy operation. If an error occurs after the destination file +has been opened for writing, Node.js will attempt to remove the destination.

      +

      flags is an optional integer that specifies the behavior +of the copy operation. It is possible to create a mask consisting of the bitwise +OR of two or more values (e.g. +fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      +
        +
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already +exists.
      • +
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a +copy-on-write reflink. If the platform does not support copy-on-write, then a +fallback copy mechanism is used.
      • +
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to +create a copy-on-write reflink. If the platform does not support copy-on-write, +then the operation will fail.
      • +
      +
      const fs = require('fs');
      +
      +// destination.txt will be created or overwritten by default.
      +fs.copyFileSync('source.txt', 'destination.txt');
      +console.log('source.txt was copied to destination.txt');
      +

      If the third argument is a number, then it specifies flags:

      +
      const fs = require('fs');
      +const { COPYFILE_EXCL } = fs.constants;
      +
      +// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
      +fs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL);
      +

      fs.createReadStream(path[, options])#

      + + +

      Unlike the 16 kb default highWaterMark for a readable stream, the stream +returned by this method has a default highWaterMark of 64 kb.

      +

      options can include start and end values to read a range of bytes from +the file instead of the entire file. Both start and end are inclusive and +start counting at 0, allowed values are in the +[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is +omitted or undefined, fs.createReadStream() reads sequentially from the +current file position. The encoding can be any one of those accepted by +Buffer.

      +

      If fd is specified, ReadStream will ignore the path argument and will use +the specified file descriptor. This means that no 'open' event will be +emitted. fd should be blocking; non-blocking fds should be passed to +net.Socket.

      +

      If fd points to a character device that only supports blocking reads +(such as keyboard or sound card), read operations do not finish until data is +available. This can prevent the process from exiting and the stream from +closing naturally.

      +

      By default, the stream will not emit a 'close' event after it has been +destroyed. This is the opposite of the default for other Readable streams. +Set the emitClose option to true to change this behavior.

      +

      By providing the fs option, it is possible to override the corresponding fs +implementations for open, read, and close. When providing the fs option, +overrides for open, read, and close are required.

      +
      const fs = require('fs');
      +// Create a stream from some character device.
      +const stream = fs.createReadStream('/dev/input/event0');
      +setTimeout(() => {
      +  stream.close(); // This may not close the stream.
      +  // Artificially marking end-of-stream, as if the underlying resource had
      +  // indicated end-of-file by itself, allows the stream to close.
      +  // This does not cancel pending read operations, and if there is such an
      +  // operation, the process may still not be able to exit successfully
      +  // until it finishes.
      +  stream.push(null);
      +  stream.read(0);
      +}, 100);
      +

      If autoClose is false, then the file descriptor won't be closed, even if +there's an error. It is the application's responsibility to close it and make +sure there's no file descriptor leak. If autoClose is set to true (default +behavior), on 'error' or 'end' the file descriptor will be closed +automatically.

      +

      mode sets the file mode (permission and sticky bits), but only if the +file was created.

      +

      An example to read the last 10 bytes of a file which is 100 bytes long:

      +
      fs.createReadStream('sample.txt', { start: 90, end: 99 });
      +

      If options is a string, then it specifies the encoding.

      +

      fs.createWriteStream(path[, options])#

      + + +

      options may also include a start option to allow writing data at +some position past the beginning of the file, allowed values are in the +[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather +than replacing it may require a flags mode of r+ rather than the +default mode w. The encoding can be any one of those accepted by +Buffer.

      +

      If autoClose is set to true (default behavior) on 'error' or 'finish' +the file descriptor will be closed automatically. If autoClose is false, +then the file descriptor won't be closed, even if there's an error. +It is the application's responsibility to close it and make sure there's no +file descriptor leak.

      +

      By default, the stream will not emit a 'close' event after it has been +destroyed. This is the opposite of the default for other Writable streams. +Set the emitClose option to true to change this behavior.

      +

      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 performance as some optimizations (_writev()) +will be disabled. When providing the fs option, overrides for open, +close, and at least one of write and writev are required.

      +

      Like ReadStream, if fd is specified, WriteStream will ignore the +path argument and will use the specified file descriptor. This means that no +'open' event will be emitted. fd should be blocking; non-blocking fds +should be passed to net.Socket.

      +

      If options is a string, then it specifies the encoding.

      +

      fs.exists(path, callback)#

      + +

      Stability: 0 - Deprecated: Use fs.stat() or fs.access() instead.

      + +

      Test whether or not the given path exists by checking with the file system. +Then call the callback argument with either true or false:

      +
      fs.exists('/etc/passwd', (exists) => {
      +  console.log(exists ? 'it\'s there' : 'no passwd!');
      +});
      +

      The parameters for this callback are not consistent with other Node.js +callbacks. Normally, the first parameter to a Node.js callback is an err +parameter, optionally followed by other parameters. The fs.exists() callback +has only one boolean parameter. This is one reason fs.access() is recommended +instead of fs.exists().

      +

      Using fs.exists() to check for the existence of a file before calling +fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing +so introduces a race condition, since other processes may change the file's +state between the two calls. Instead, user code should open/read/write the +file directly and handle the error raised if the file does not exist.

      +

      write (NOT RECOMMENDED)

      +
      fs.exists('myfile', (exists) => {
      +  if (exists) {
      +    console.error('myfile already exists');
      +  } else {
      +    fs.open('myfile', 'wx', (err, fd) => {
      +      if (err) throw err;
      +      writeMyData(fd);
      +    });
      +  }
      +});
      +

      write (RECOMMENDED)

      +
      fs.open('myfile', 'wx', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'EEXIST') {
      +      console.error('myfile already exists');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  writeMyData(fd);
      +});
      +

      read (NOT RECOMMENDED)

      +
      fs.exists('myfile', (exists) => {
      +  if (exists) {
      +    fs.open('myfile', 'r', (err, fd) => {
      +      if (err) throw err;
      +      readMyData(fd);
      +    });
      +  } else {
      +    console.error('myfile does not exist');
      +  }
      +});
      +

      read (RECOMMENDED)

      +
      fs.open('myfile', 'r', (err, fd) => {
      +  if (err) {
      +    if (err.code === 'ENOENT') {
      +      console.error('myfile does not exist');
      +      return;
      +    }
      +
      +    throw err;
      +  }
      +
      +  readMyData(fd);
      +});
      +

      The "not recommended" examples above check for existence and then use the +file; the "recommended" examples are better because they use the file directly +and handle the error, if any.

      +

      In general, check for the existence of a file only if the file won’t be +used directly, for example when its existence is a signal from another +process.

      +

      fs.existsSync(path)#

      + + +

      Returns true if the path exists, false otherwise.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.exists().

      +

      fs.exists() is deprecated, but fs.existsSync() is not. The callback +parameter to fs.exists() accepts parameters that are inconsistent with other +Node.js callbacks. fs.existsSync() does not use a callback.

      +
      if (fs.existsSync('/etc/passwd')) {
      +  console.log('The path exists.');
      +}
      +

      fs.fchmod(fd, mode, callback)#

      + + +

      Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback.

      +

      fs.fchmodSync(fd, mode)#

      + + +

      Synchronous fchmod(2). Returns undefined.

      +

      fs.fchown(fd, uid, gid, callback)#

      + + +

      Asynchronous fchown(2). No arguments other than a possible exception are given +to the completion callback.

      +

      fs.fchownSync(fd, uid, gid)#

      + + +

      Synchronous fchown(2). Returns undefined.

      +

      fs.fdatasync(fd, callback)#

      + + +

      Asynchronous fdatasync(2). No arguments other than a possible exception are +given to the completion callback.

      +

      fs.fdatasyncSync(fd)#

      + + +

      Synchronous fdatasync(2). Returns undefined.

      +

      fs.fstat(fd[, options], callback)#

      + + +

      Asynchronous fstat(2). The callback gets two arguments (err, stats) where +stats is an fs.Stats object. fstat() is identical to stat(), +except that the file to be stat-ed is specified by the file descriptor fd.

      +

      fs.fstatSync(fd[, options])#

      + + +

      Synchronous fstat(2).

      +

      fs.fsync(fd, callback)#

      + + +

      Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback.

      +

      fs.fsyncSync(fd)#

      + + +

      Synchronous fsync(2). Returns undefined.

      +

      fs.ftruncate(fd[, len], callback)#

      + + +

      Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback.

      +

      If the file referred to by the file descriptor was larger than len bytes, only +the first len bytes will be retained in the file.

      +

      For example, the following program retains only the first four bytes of the +file:

      +
      console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +// get the file descriptor of the file to be truncated
      +const fd = fs.openSync('temp.txt', 'r+');
      +
      +// Truncate the file to first four bytes
      +fs.ftruncate(fd, 4, (err) => {
      +  assert.ifError(err);
      +  console.log(fs.readFileSync('temp.txt', 'utf8'));
      +});
      +// Prints: Node
      +

      If the file previously was shorter than len bytes, it is extended, and the +extended part is filled with null bytes ('\0'):

      +
      console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +// get the file descriptor of the file to be truncated
      +const fd = fs.openSync('temp.txt', 'r+');
      +
      +// Truncate the file to 10 bytes, whereas the actual size is 7 bytes
      +fs.ftruncate(fd, 10, (err) => {
      +  assert.ifError(err);
      +  console.log(fs.readFileSync('temp.txt'));
      +});
      +// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>
      +// ('Node.js\0\0\0' in UTF8)
      +

      The last three bytes are null bytes ('\0'), to compensate the over-truncation.

      +

      fs.ftruncateSync(fd[, len])#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.ftruncate().

      +

      fs.futimes(fd, atime, mtime, callback)#

      + + +

      Change the file system timestamps of the object referenced by the supplied file +descriptor. See fs.utimes().

      +

      This function does not work on AIX versions before 7.1, it will return the +error UV_ENOSYS.

      +

      fs.futimesSync(fd, atime, mtime)#

      + + +

      Synchronous version of fs.futimes(). Returns undefined.

      +

      fs.lchmod(path, mode, callback)#

      + + +

      Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback.

      +

      Only available on macOS.

      +

      fs.lchmodSync(path, mode)#

      + + +

      Synchronous lchmod(2). Returns undefined.

      +

      fs.lchown(path, uid, gid, callback)#

      + + +

      Asynchronous lchown(2). No arguments other than a possible exception are given +to the completion callback.

      +

      fs.lchownSync(path, uid, gid)#

      + + +

      Synchronous lchown(2). Returns undefined.

      +

      fs.lutimes(path, atime, mtime, callback)#

      + + +

      Changes the access and modification times of a file in the same way as +fs.utimes(), with the difference that if the path refers to a symbolic +link, then the link is not dereferenced: instead, the timestamps of the +symbolic link itself are changed.

      +

      No arguments other than a possible exception are given to the completion +callback.

      +

      fs.lutimesSync(path, atime, mtime)#

      + + +

      Change the file system timestamps of the symbolic link referenced by path. +Returns undefined, or throws an exception when parameters are incorrect or +the operation fails. This is the synchronous version of fs.lutimes().

      +

      fs.link(existingPath, newPath, callback)#

      + + +

      Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback.

      +

      fs.linkSync(existingPath, newPath)#

      + + +

      Synchronous link(2). Returns undefined.

      +

      fs.lstat(path[, options], callback)#

      + + +

      Asynchronous lstat(2). 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 link, then the link itself is stat-ed, +not the file that it refers to.

      +

      fs.lstatSync(path[, options])#

      + + +

      Synchronous lstat(2).

      +

      fs.mkdir(path[, options], callback)#

      + + +

      Asynchronously creates a directory.

      +

      The callback is given a possible exception and, if recursive is true, the +first directory path created, (err, [path]).

      +

      The optional options argument can be an integer specifying mode (permission +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 exists results in an error only +when recursive is false.

      +
      // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
      +fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
      +  if (err) throw err;
      +});
      +

      On Windows, using fs.mkdir() on the root directory even with recursion will +result in an error:

      +
      fs.mkdir('/', { recursive: true }, (err) => {
      +  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
      +});
      +

      See also: mkdir(2).

      +

      fs.mkdirSync(path[, options])#

      + + +

      Synchronously creates a directory. Returns undefined, or if recursive is +true, the first directory path created. +This is the synchronous version of fs.mkdir().

      +

      See also: mkdir(2).

      +

      fs.mkdtemp(prefix[, options], callback)#

      + + +

      Creates a unique temporary directory.

      +

      Generates six random characters to be appended behind a required +prefix to create a unique temporary directory. Due to platform +inconsistencies, avoid trailing X characters in prefix. Some platforms, +notably the BSDs, can return more than six random characters, and replace +trailing X characters in prefix with random characters.

      +

      The created directory path is passed as a string to the callback's second +parameter.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use.

      +
      fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
      +  if (err) throw err;
      +  console.log(directory);
      +  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
      +});
      +

      The fs.mkdtemp() method will append the six randomly selected characters +directly to the prefix string. For instance, given a directory /tmp, if the +intention is to create a temporary directory within /tmp, the prefix +must end with a trailing platform-specific path separator +(require('path').sep).

      +
      // The parent directory for the new temporary directory
      +const tmpDir = os.tmpdir();
      +
      +// This method is *INCORRECT*:
      +fs.mkdtemp(tmpDir, (err, directory) => {
      +  if (err) throw err;
      +  console.log(directory);
      +  // Will print something similar to `/tmpabc123`.
      +  // A new temporary directory is created at the file system root
      +  // rather than *within* the /tmp directory.
      +});
      +
      +// This method is *CORRECT*:
      +const { sep } = require('path');
      +fs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
      +  if (err) throw err;
      +  console.log(directory);
      +  // Will print something similar to `/tmp/abc123`.
      +  // A new temporary directory is created within
      +  // the /tmp directory.
      +});
      +

      fs.mkdtempSync(prefix[, options])#

      + + +

      Returns the created directory path.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.mkdtemp().

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use.

      +

      fs.open(path[, flags[, mode]], callback)#

      + + +

      Asynchronous file open. See open(2).

      +

      mode sets the file mode (permission and sticky bits), but only if the file was +created. On Windows, only the write permission can be manipulated; see +fs.chmod().

      +

      The callback gets two arguments (err, fd).

      +

      Some characters (< > : " / \ | ? *) are reserved under Windows as documented +by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains +a colon, Node.js will open a file system stream, as described by +this MSDN page.

      +

      Functions based on fs.open() exhibit this behavior as well: +fs.writeFile(), fs.readFile(), etc.

      +

      fs.opendir(path[, options], callback)#

      + + +

      Asynchronously open a directory. See opendir(3).

      +

      Creates an fs.Dir, which contains all further functions for reading from +and cleaning up the directory.

      +

      The encoding option sets the encoding for the path while opening the +directory and subsequent read operations.

      +

      fs.opendirSync(path[, options])#

      + +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • encoding <string> | <null> Default: 'utf8'
        • +
        • bufferSize <number> Number of directory entries that are buffered +internally when reading from the directory. Higher values lead to better +performance but higher memory usage. Default: 32
        • +
        +
      • +
      • Returns: <fs.Dir>
      • +
      +

      Synchronously open a directory. See opendir(3).

      +

      Creates an fs.Dir, which contains all further functions for reading from +and cleaning up the directory.

      +

      The encoding option sets the encoding for the path while opening the +directory and subsequent read operations.

      +

      fs.openSync(path[, flags, mode])#

      + + +

      Returns an integer representing the file descriptor.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.open().

      +

      fs.read(fd, buffer, offset, length, position, callback)#

      + + +

      Read data from the file specified by fd.

      +

      buffer is the buffer that the data (read from the fd) will be written to.

      +

      offset is the offset in the buffer to start writing at.

      +

      length is an integer specifying the number of bytes to read.

      +

      position is an argument specifying where to begin reading from in the file. +If position is null, data will be read from the current file position, +and the file position will be updated. +If position is an integer, the file position will remain unchanged.

      +

      The callback is given the three arguments, (err, bytesRead, buffer).

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with bytesRead and buffer properties.

      +

      fs.read(fd, [options,] callback)#

      + + +

      Similar to the above fs.read function, this version takes an optional options object. +If no options object is specified, it will default with the above values.

      +

      fs.readdir(path[, options], callback)#

      + + +

      Asynchronous readdir(3). 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 '..'.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the filenames passed to the callback. If the encoding is set to 'buffer', +the filenames returned will be passed as Buffer objects.

      +

      If options.withFileTypes is set to true, the files array will contain +fs.Dirent objects.

      +

      fs.readdirSync(path[, options])#

      + + +

      Synchronous readdir(3).

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the filenames returned. If the encoding is set to 'buffer', +the filenames returned will be passed as Buffer objects.

      +

      If options.withFileTypes is set to true, the result will contain +fs.Dirent objects.

      +

      fs.readFile(path[, options], callback)#

      + + +

      Asynchronously reads the entire contents of a file.

      +
      fs.readFile('/etc/passwd', (err, data) => {
      +  if (err) throw err;
      +  console.log(data);
      +});
      +

      The callback is passed two arguments (err, data), where data is the +contents of the file.

      +

      If no encoding is specified, then the raw buffer is returned.

      +

      If options is a string, then it specifies the encoding:

      +
      fs.readFile('/etc/passwd', 'utf8', callback);
      +

      When the path is a directory, the behavior of fs.readFile() and +fs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an +error will be returned. On FreeBSD, a representation of the directory's contents +will be returned.

      +
      // macOS, Linux, and Windows
      +fs.readFile('<directory>', (err, data) => {
      +  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
      +});
      +
      +//  FreeBSD
      +fs.readFile('<directory>', (err, data) => {
      +  // => null, <data>
      +});
      +

      The fs.readFile() function buffers the entire file. To minimize memory costs, +when possible prefer streaming via fs.createReadStream().

      +

      File descriptors#

      +
        +
      1. Any specified file descriptor has to support reading.
      2. +
      3. If a file descriptor is specified as the path, it will not be closed +automatically.
      4. +
      5. The reading will begin at the current position. For example, if the file +already had 'Hello World' and six bytes are read with the file descriptor, +the call to fs.readFile() with the same file descriptor, would give +'World', rather than 'Hello World'.
      6. +
      +

      fs.readFileSync(path[, options])#

      + + +

      Returns the contents of the path.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.readFile().

      +

      If the encoding option is specified then this function returns a +string. Otherwise it returns a buffer.

      +

      Similar to fs.readFile(), when the path is a directory, the behavior of +fs.readFileSync() is platform-specific.

      +
      // macOS, Linux, and Windows
      +fs.readFileSync('<directory>');
      +// => [Error: EISDIR: illegal operation on a directory, read <directory>]
      +
      +//  FreeBSD
      +fs.readFileSync('<directory>'); // => <data>
      +

      fs.readlink(path[, options], callback)#

      + + +

      Asynchronous readlink(2). The callback gets two arguments (err, linkString).

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the link path passed to the callback. If the encoding is set to 'buffer', +the link path returned will be passed as a Buffer object.

      +

      fs.readlinkSync(path[, options])#

      + + +

      Synchronous readlink(2). Returns the symbolic link's string value.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the link path returned. If the encoding is set to 'buffer', +the link path returned will be passed as a Buffer object.

      +

      fs.readSync(fd, buffer, offset, length, position)#

      + + +

      Returns the number of bytesRead.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.read().

      +

      fs.readSync(fd, buffer, [options])#

      + + +

      Returns the number of bytesRead.

      +

      Similar to the above fs.readSync function, this version takes an optional options object. +If no options object is specified, it will default with the above values.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.read().

      +

      fs.readv(fd, buffers[, position], callback)#

      + + +

      Read from a file specified by fd and write to an array of ArrayBufferViews +using readv().

      +

      position is the offset from the beginning of the file from where data +should be read. If typeof position !== 'number', the data will be read +from the current position.

      +

      The callback will be given three arguments: err, bytesRead, and +buffers. bytesRead is how many bytes were read from the file.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with bytesRead and buffers properties.

      +

      fs.readvSync(fd, buffers[, position])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.readv().

      +

      fs.realpath(path[, options], callback)#

      + + +

      Asynchronously computes the canonical pathname by resolving ., .. and +symbolic links.

      +

      A canonical pathname is not necessarily unique. Hard links and bind mounts can +expose a file system entity through many pathnames.

      +

      This function behaves like realpath(3), with some exceptions:

      +
        +
      1. +

        No case conversion is performed on case-insensitive file systems.

        +
      2. +
      3. +

        The maximum number of symbolic links is platform-independent and generally +(much) higher than what the native realpath(3) implementation supports.

        +
      4. +
      +

      The callback gets two arguments (err, resolvedPath). May use process.cwd +to resolve relative paths.

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path passed to the callback. If the encoding is set to 'buffer', +the path returned will be passed as a Buffer object.

      +

      If path resolves to a socket or a pipe, the function will return a system +dependent name for that object.

      +

      fs.realpath.native(path[, options], callback)#

      + + +

      Asynchronous realpath(3).

      +

      The callback gets two arguments (err, resolvedPath).

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path passed to the callback. If the encoding is set to 'buffer', +the path returned will be passed as a Buffer object.

      +

      On Linux, when Node.js is linked against musl libc, the procfs file system must +be mounted on /proc in order for this function to work. Glibc does not have +this restriction.

      +

      fs.realpathSync(path[, options])#

      + + +

      Returns the resolved pathname.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.realpath().

      +

      fs.realpathSync.native(path[, options])#

      + + +

      Synchronous realpath(3).

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path returned. If the encoding is set to 'buffer', +the path returned will be passed as a Buffer object.

      +

      On Linux, when Node.js is linked against musl libc, the procfs file system must +be mounted on /proc in order for this function to work. Glibc does not have +this restriction.

      +

      fs.rename(oldPath, newPath, callback)#

      + + +

      Asynchronously rename file at oldPath to the pathname provided +as newPath. In the case that newPath already exists, it will +be overwritten. If there is a directory at newPath, an error will +be raised instead. No arguments other than a possible exception are +given to the completion callback.

      +

      See also: rename(2).

      +
      fs.rename('oldFile.txt', 'newFile.txt', (err) => {
      +  if (err) throw err;
      +  console.log('Rename complete!');
      +});
      +

      fs.renameSync(oldPath, newPath)#

      + + +

      Synchronous rename(2). Returns undefined.

      +

      fs.rmdir(path[, options], callback)#

      + +

      Stability: 1 - Recursive removal is experimental.

      +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or +EPERM error is encountered, Node.js will retry the operation with a linear +backoff wait of retryDelay ms longer on each try. This option represents the +number of retries. This option is ignored if the recursive option is not +true. Default: 0.
        • +
        • recursive <boolean> If true, perform a recursive directory removal. In +recursive mode, errors are not reported if path does not exist, and +operations are retried on failure. Default: false.
        • +
        • retryDelay <integer> The amount of time in milliseconds to wait between +retries. This option is ignored if the recursive option is not true. +Default: 100.
        • +
        +
      • +
      • callback <Function> + +
      • +
      +

      Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback.

      +

      Using fs.rmdir() on a file (not a directory) results in an ENOENT error on +Windows and an ENOTDIR error on POSIX.

      +

      fs.rmdirSync(path[, options])#

      + +

      Stability: 1 - Recursive removal is experimental.

      +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or +EPERM error is encountered, Node.js will retry the operation with a linear +backoff wait of retryDelay ms longer on each try. This option represents the +number of retries. This option is ignored if the recursive option is not +true. Default: 0.
        • +
        • recursive <boolean> If true, perform a recursive directory removal. In +recursive mode, errors are not reported if path does not exist, and +operations are retried on failure. Default: false.
        • +
        • retryDelay <integer> The amount of time in milliseconds to wait between +retries. This option is ignored if the recursive option is not true. +Default: 100.
        • +
        +
      • +
      +

      Synchronous rmdir(2). Returns undefined.

      +

      Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error +on Windows and an ENOTDIR error on POSIX.

      +

      fs.stat(path[, options], callback)#

      + + +

      Asynchronous stat(2). The callback gets two arguments (err, stats) where +stats is an fs.Stats object.

      +

      In case of an error, the err.code will be one of Common System Errors.

      +

      Using fs.stat() to check for the existence of a file before calling +fs.open(), fs.readFile() or fs.writeFile() is not recommended. +Instead, user code should open/read/write the file directly and handle the +error raised if the file is not available.

      +

      To check if a file exists without manipulating it afterwards, fs.access() +is recommended.

      +

      For example, given the following directory structure:

      +
      - txtDir
      +-- file.txt
      +- app.js
      +

      The next program will check for the stats of the given paths:

      +
      const fs = require('fs');
      +
      +const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
      +
      +for (let i = 0; i < pathsToCheck.length; i++) {
      +  fs.stat(pathsToCheck[i], function(err, stats) {
      +    console.log(stats.isDirectory());
      +    console.log(stats);
      +  });
      +}
      +

      The resulting output will resemble:

      +
      true
      +Stats {
      +  dev: 16777220,
      +  mode: 16877,
      +  nlink: 3,
      +  uid: 501,
      +  gid: 20,
      +  rdev: 0,
      +  blksize: 4096,
      +  ino: 14214262,
      +  size: 96,
      +  blocks: 0,
      +  atimeMs: 1561174653071.963,
      +  mtimeMs: 1561174614583.3518,
      +  ctimeMs: 1561174626623.5366,
      +  birthtimeMs: 1561174126937.2893,
      +  atime: 2019-06-22T03:37:33.072Z,
      +  mtime: 2019-06-22T03:36:54.583Z,
      +  ctime: 2019-06-22T03:37:06.624Z,
      +  birthtime: 2019-06-22T03:28:46.937Z
      +}
      +false
      +Stats {
      +  dev: 16777220,
      +  mode: 33188,
      +  nlink: 1,
      +  uid: 501,
      +  gid: 20,
      +  rdev: 0,
      +  blksize: 4096,
      +  ino: 14214074,
      +  size: 8,
      +  blocks: 8,
      +  atimeMs: 1561174616618.8555,
      +  mtimeMs: 1561174614584,
      +  ctimeMs: 1561174614583.8145,
      +  birthtimeMs: 1561174007710.7478,
      +  atime: 2019-06-22T03:36:56.619Z,
      +  mtime: 2019-06-22T03:36:54.584Z,
      +  ctime: 2019-06-22T03:36:54.584Z,
      +  birthtime: 2019-06-22T03:26:47.711Z
      +}
      +

      fs.statSync(path[, options])#

      + + +

      Synchronous stat(2).

      +

      fs.symlink(target, path[, type], callback)#

      + + +

      Asynchronous symlink(2) which creates the link called path pointing to +target. No arguments other than a possible exception are given to the +completion callback.

      +

      The type argument is only available on Windows and ignored on other platforms. +It can be set to 'dir', 'file', or 'junction'. If the type argument is +not set, Node.js will autodetect target type and use 'file' or 'dir'. If +the target does not exist, 'file' will be used. Windows junction points +require the destination path to be absolute. When using 'junction', the +target argument will automatically be normalized to absolute path.

      +

      Relative targets are relative to the link’s parent directory.

      +
      fs.symlink('./mew', './example/mewtwo', callback);
      +

      The above example creates a symbolic link mewtwo in the example which points +to mew in the same directory:

      +
      $ tree example/
      +example/
      +├── mew
      +└── mewtwo -> ./mew
      +

      fs.symlinkSync(target, path[, type])#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.symlink().

      +

      fs.truncate(path[, len], callback)#

      + + +

      Asynchronous truncate(2). No arguments other than a possible exception are +given to the completion callback. A file descriptor can also be passed as the +first argument. In this case, fs.ftruncate() is called.

      +

      Passing a file descriptor is deprecated and may result in an error being thrown +in the future.

      +

      fs.truncateSync(path[, len])#

      + + +

      Synchronous truncate(2). Returns undefined. A file descriptor can also be +passed as the first argument. In this case, fs.ftruncateSync() is called.

      +

      Passing a file descriptor is deprecated and may result in an error being thrown +in the future.

      +

      fs.unlink(path, callback)#

      + + +

      Asynchronously removes a file or symbolic link. No arguments other than a +possible exception are given to the completion callback.

      +
      // Assuming that 'path/file.txt' is a regular file.
      +fs.unlink('path/file.txt', (err) => {
      +  if (err) throw err;
      +  console.log('path/file.txt was deleted');
      +});
      +

      fs.unlink() will not work on a directory, empty or otherwise. To remove a +directory, use fs.rmdir().

      +

      See also: unlink(2).

      +

      fs.unlinkSync(path)#

      + + +

      Synchronous unlink(2). Returns undefined.

      +

      fs.unwatchFile(filename[, listener])#

      + + +

      Stop watching for changes on filename. If listener is specified, only that +particular listener is removed. Otherwise, all listeners are removed, +effectively stopping watching of filename.

      +

      Calling fs.unwatchFile() with a filename that is not being watched is a +no-op, not an error.

      +

      Using fs.watch() is more efficient than fs.watchFile() and +fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() +and fs.unwatchFile() when possible.

      +

      fs.utimes(path, atime, mtime, callback)#

      + + +

      Change the file system timestamps of the object referenced by path.

      +

      The atime and mtime arguments follow these rules:

      +
        +
      • Values can be either numbers representing Unix epoch time in seconds, +Dates, or a numeric string like '123456789.0'.
      • +
      • If the value can not be converted to a number, or is NaN, Infinity or +-Infinity, an Error will be thrown.
      • +
      +

      fs.utimesSync(path, atime, mtime)#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.utimes().

      +

      fs.watch(filename[, options][, listener])#

      + +
        +
      • filename <string> | <Buffer> | <URL>
      • +
      • options <string> | <Object> +
          +
        • persistent <boolean> Indicates whether the process should continue to run +as long as files are being watched. Default: true.
        • +
        • recursive <boolean> Indicates whether all subdirectories should be +watched, or only the current directory. This applies when a directory is +specified, and only on supported platforms (See Caveats). Default: +false.
        • +
        • encoding <string> Specifies the character encoding to be used for the + filename passed to the listener. Default: 'utf8'.
        • +
        +
      • +
      • listener <Function> | <undefined> Default: undefined + +
      • +
      • Returns: <fs.FSWatcher>
      • +
      +

      Watch for changes on filename, where filename is either a file or a +directory.

      +

      The second argument is optional. If options is provided as a string, it +specifies the encoding. Otherwise options should be passed as an object.

      +

      The listener callback gets two arguments (eventType, filename). eventType +is either 'rename' or 'change', and filename is the name of the file +which triggered the event.

      +

      On most platforms, 'rename' is emitted whenever a filename appears or +disappears in the directory.

      +

      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.

      +

      Caveats#

      + +

      The fs.watch API is not 100% consistent across platforms, and is +unavailable in some situations.

      +

      The recursive option is only supported on macOS and Windows.

      +

      On Windows, no events will be emitted if the watched directory is moved or +renamed. An EPERM error is reported when the watched directory is deleted.

      +

      Availability#

      + +

      This feature depends on the underlying operating system providing a way +to be notified of filesystem changes.

      +
        +
      • On Linux systems, this uses inotify(7).
      • +
      • On BSD systems, this uses kqueue(2).
      • +
      • On macOS, this uses kqueue(2) for files and FSEvents for +directories.
      • +
      • On SunOS systems (including Solaris and SmartOS), this uses event ports.
      • +
      • On Windows systems, this feature depends on ReadDirectoryChangesW.
      • +
      • On Aix systems, this feature depends on AHAFS, which must be enabled.
      • +
      • On IBM i systems, this feature is not supported.
      • +
      +

      If the underlying functionality is not available for some reason, then +fs.watch() will not be able to function and may thrown an exception. +For example, watching files or directories can be unreliable, and in some +cases impossible, on network file systems (NFS, SMB, etc) or host file systems +when using virtualization software such as Vagrant or Docker.

      +

      It is still possible to use fs.watchFile(), which uses stat polling, but +this method is slower and less reliable.

      +

      Inodes#

      + +

      On Linux and macOS systems, fs.watch() resolves the path to an inode and +watches the inode. If the watched path is deleted and recreated, it is assigned +a new inode. The watch will emit an event for the delete but will continue +watching the original inode. Events for the new inode will not be emitted. +This is expected behavior.

      +

      AIX files retain the same inode for the lifetime of a file. Saving and closing a +watched file on AIX will result in two notifications (one for adding new +content, and one for truncation).

      +

      Filename argument#

      + +

      Providing filename argument in the callback is only supported on Linux, +macOS, Windows, and AIX. Even on supported platforms, filename is not always +guaranteed to be provided. Therefore, don't assume that filename argument is +always provided in the callback, and have some fallback logic if it is null.

      +
      fs.watch('somedir', (eventType, filename) => {
      +  console.log(`event type is: ${eventType}`);
      +  if (filename) {
      +    console.log(`filename provided: ${filename}`);
      +  } else {
      +    console.log('filename not provided');
      +  }
      +});
      +

      fs.watchFile(filename[, options], listener)#

      + + +

      Watch for changes on filename. The callback listener will be called each +time the file is accessed.

      +

      The options argument may be omitted. If provided, it should be an object. The +options object may contain a boolean named persistent that indicates +whether the process should continue to run as long as files are being watched. +The options object may specify an interval property indicating how often the +target should be polled in milliseconds.

      +

      The listener gets two arguments the current stat object and the previous +stat object:

      +
      fs.watchFile('message.text', (curr, prev) => {
      +  console.log(`the current mtime is: ${curr.mtime}`);
      +  console.log(`the previous mtime was: ${prev.mtime}`);
      +});
      +

      These stat objects are instances of fs.Stat. If the bigint option is true, +the numeric values in these objects are specified as BigInts.

      +

      To be notified when the file was modified, not just accessed, it is necessary +to compare curr.mtime and prev.mtime.

      +

      When an fs.watchFile operation results in an ENOENT error, it +will invoke the listener once, with all the fields zeroed (or, for dates, the +Unix Epoch). If the file is created later on, the listener will be called +again, with the latest stat objects. This is a change in functionality since +v0.10.

      +

      Using fs.watch() is more efficient than fs.watchFile and +fs.unwatchFile. fs.watch should be used instead of fs.watchFile and +fs.unwatchFile when possible.

      +

      When a file being watched by fs.watchFile() disappears and reappears, +then the contents of previous in the second callback event (the file's +reappearance) will be the same as the contents of previous in the first +callback event (its disappearance).

      +

      This happens when:

      +
        +
      • the file is deleted, followed by a restore
      • +
      • the file is renamed and then renamed a second time back to its original name
      • +
      +

      fs.write(fd, buffer[, offset[, length[, position]]], callback)#

      + + +

      Write buffer to the file specified by fd.

      +

      offset determines the part of the buffer to be written, and length is +an integer specifying the number of bytes to write.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position. See pwrite(2).

      +

      The callback will be given three arguments (err, bytesWritten, buffer) where +bytesWritten specifies how many bytes were written from buffer.

      +

      If this method is invoked as its util.promisify()ed version, it returns +a Promise for an Object with bytesWritten and buffer properties.

      +

      It is unsafe to use fs.write() multiple times on the same file without waiting +for the callback. For this scenario, fs.createWriteStream() is +recommended.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      fs.write(fd, string[, position[, encoding]], callback)#

      + + +

      Write string to the file specified by fd. If string is not a string, then +the value will be coerced to one.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If typeof position !== 'number' the data will be written at +the current position. See pwrite(2).

      +

      encoding is the expected string encoding.

      +

      The callback will receive the arguments (err, written, string) where written +specifies how many bytes the passed string required to be written. Bytes +written is not necessarily the same as string characters written. See +Buffer.byteLength.

      +

      It is unsafe to use fs.write() multiple times on the same file without waiting +for the callback. For this scenario, fs.createWriteStream() is +recommended.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      On Windows, if the file descriptor is connected to the console (e.g. fd == 1 +or stdout) a string containing non-ASCII characters will not be rendered +properly by default, regardless of the encoding used. +It is possible to configure the console to render UTF-8 properly by changing the +active codepage with the chcp 65001 command. See the chcp docs for more +details.

      +

      fs.writeFile(file, data[, options], callback)#

      + + +

      When file is a filename, asynchronously writes data to the file, replacing the +file if it already exists. data can be a string or a buffer.

      +

      When file is a file descriptor, the behavior is similar to calling +fs.write() directly (which is recommended). See the notes below on using +a file descriptor.

      +

      The encoding option is ignored if data is a buffer.

      +
      const data = new Uint8Array(Buffer.from('Hello Node.js'));
      +fs.writeFile('message.txt', data, (err) => {
      +  if (err) throw err;
      +  console.log('The file has been saved!');
      +});
      +

      If options is a string, then it specifies the encoding:

      +
      fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
      +

      It is unsafe to use fs.writeFile() multiple times on the same file without +waiting for the callback. For this scenario, fs.createWriteStream() is +recommended.

      +

      Using fs.writeFile() with file descriptors#

      +

      When file is a file descriptor, the behavior is almost identical to directly +calling fs.write() like:

      +
      fs.write(fd, Buffer.from(data, options.encoding), callback);
      +

      The difference from directly calling fs.write() is that under some unusual +conditions, fs.write() may write only part of the buffer and will need to be +retried to write the remaining data, whereas fs.writeFile() will retry until +the data is entirely written (or an error occurs).

      +

      The implications of this are a common source of confusion. In +the file descriptor case, the file is not replaced! The data is not necessarily +written to the beginning of the file, and the file's original data may remain +before and/or after the newly written data.

      +

      For example, if fs.writeFile() is called twice in a row, first to write the +string 'Hello', then to write the string ', World', the file would contain +'Hello, World', and might contain some of the file's original data (depending +on the size of the original file, and the position of the file descriptor). If +a file name had been used instead of a descriptor, the file would be guaranteed +to contain only ', World'.

      +

      fs.writeFileSync(file, data[, options])#

      + + +

      Returns undefined.

      +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.writeFile().

      +

      fs.writeSync(fd, buffer[, offset[, length[, position]]])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.write(fd, buffer...).

      +

      fs.writeSync(fd, string[, position[, encoding]])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.write(fd, string...).

      +

      fs.writev(fd, buffers[, position], callback)#

      + + +

      Write an array of ArrayBufferViews to the file specified by fd using +writev().

      +

      position is the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position.

      +

      The callback will be given three arguments: err, bytesWritten, and +buffers. bytesWritten is how many bytes were written from buffers.

      +

      If this method is util.promisify()ed, it returns a Promise for an +Object with bytesWritten and buffers properties.

      +

      It is unsafe to use fs.writev() multiple times on the same file without +waiting for the callback. For this scenario, use fs.createWriteStream().

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      fs.writevSync(fd, buffers[, position])#

      + + +

      For detailed information, see the documentation of the asynchronous version of +this API: fs.writev().

      +

      fs Promises API#

      +

      The fs.promises API provides an alternative set of asynchronous file system +methods that return Promise objects rather than using callbacks. The +API is accessible via require('fs').promises.

      +

      Class: FileHandle#

      + +

      A FileHandle object is a wrapper for a numeric file descriptor. +Instances of FileHandle are distinct from numeric file descriptors +in that they provide an object oriented API for working with files.

      +

      If a FileHandle is not closed using the +filehandle.close() method, it might automatically close the file descriptor +and will emit a process warning, thereby helping to prevent memory leaks. +Please do not rely on this behavior because it is unreliable and +the file may not be closed. Instead, always explicitly close FileHandles. +Node.js may change this behavior in the future.

      +

      Instances of the FileHandle object are created internally by the +fsPromises.open() method.

      +

      Unlike the callback-based API (fs.fstat(), fs.fchown(), fs.fchmod(), and +so on), a numeric file descriptor is not used by the promise-based API. Instead, +the promise-based API uses the FileHandle class in order to help avoid +accidental leaking of unclosed file descriptors after a Promise is resolved or +rejected.

      +

      filehandle.appendFile(data, options)#

      + + +

      Alias of filehandle.writeFile().

      +

      When operating on file handles, the mode cannot be changed from what it was set +to with fsPromises.open(). Therefore, this is equivalent to +filehandle.writeFile().

      +

      filehandle.chmod(mode)#

      + + +

      Modifies the permissions on the file. The Promise is resolved with no +arguments upon success.

      +

      filehandle.chown(uid, gid)#

      + + +

      Changes the ownership of the file then resolves the Promise with no arguments +upon success.

      +

      filehandle.close()#

      + +
        +
      • Returns: <Promise> A Promise that will be resolved once the underlying +file descriptor is closed, or will be rejected if an error occurs while +closing.
      • +
      +

      Closes the file descriptor.

      +
      const fsPromises = require('fs').promises;
      +async function openAndClose() {
      +  let filehandle;
      +  try {
      +    filehandle = await fsPromises.open('thefile.txt', 'r');
      +  } finally {
      +    if (filehandle !== undefined)
      +      await filehandle.close();
      +  }
      +}
      +

      filehandle.datasync()#

      + + +

      Asynchronous fdatasync(2). The Promise is resolved with no arguments upon +success.

      +

      filehandle.fd#

      + +
        +
      • <number> The numeric file descriptor managed by the FileHandle object.
      • +
      +

      filehandle.read(buffer, offset, length, position)#

      + + +

      Read data from the file.

      +

      buffer is the buffer that the data will be written to.

      +

      offset is the offset in the buffer to start writing at.

      +

      length is an integer specifying the number of bytes to read.

      +

      position is an argument specifying where to begin reading from in the file. +If position is null, data will be read from the current file position, +and the file position will be updated. +If position is an integer, the file position will remain unchanged.

      +

      Following successful read, the Promise is resolved with an object with a +bytesRead property specifying the number of bytes read, and a buffer +property that is a reference to the passed in buffer argument.

      +

      filehandle.read(options)#

      + + +

      filehandle.readFile(options)#

      + + +

      Asynchronously reads the entire contents of a file.

      +

      The Promise is resolved with the contents of the file. If no encoding is +specified (using options.encoding), the data is returned as a Buffer +object. Otherwise, the data will be a string.

      +

      If options is a string, then it specifies the encoding.

      +

      The FileHandle has to support reading.

      +

      If one or more filehandle.read() calls are made on a file handle and then a +filehandle.readFile() call is made, the data will be read from the current +position till the end of the file. It doesn't always read from the beginning +of the file.

      +

      filehandle.readv(buffers[, position])#

      + + +

      Read from a file and write to an array of ArrayBufferViews

      +

      The Promise is resolved with an object containing a bytesRead property +identifying the number of bytes read, and a buffers property containing +a reference to the buffers input.

      +

      position is the offset from the beginning of the file where this data +should be read from. If typeof position !== 'number', the data will be read +from the current position.

      +

      filehandle.stat([options])#

      + + +

      Retrieves the fs.Stats for the file.

      +

      filehandle.sync()#

      + + +

      Asynchronous fsync(2). The Promise is resolved with no arguments upon +success.

      +

      filehandle.truncate(len)#

      + + +

      Truncates the file then resolves the Promise with no arguments upon success.

      +

      If the file was larger than len bytes, only the first len bytes will be +retained in the file.

      +

      For example, the following program retains only the first four bytes of the +file:

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +
      +console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +async function doTruncate() {
      +  let filehandle = null;
      +  try {
      +    filehandle = await fsPromises.open('temp.txt', 'r+');
      +    await filehandle.truncate(4);
      +  } finally {
      +    if (filehandle) {
      +      // Close the file if it is opened.
      +      await filehandle.close();
      +    }
      +  }
      +  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node
      +}
      +
      +doTruncate().catch(console.error);
      +

      If the file previously was shorter than len bytes, it is extended, and the +extended part is filled with null bytes ('\0'):

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +
      +console.log(fs.readFileSync('temp.txt', 'utf8'));
      +// Prints: Node.js
      +
      +async function doTruncate() {
      +  let filehandle = null;
      +  try {
      +    filehandle = await fsPromises.open('temp.txt', 'r+');
      +    await filehandle.truncate(10);
      +  } finally {
      +    if (filehandle) {
      +      // Close the file if it is opened.
      +      await filehandle.close();
      +    }
      +  }
      +  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\0\0\0
      +}
      +
      +doTruncate().catch(console.error);
      +

      The last three bytes are null bytes ('\0'), to compensate the over-truncation.

      +

      filehandle.utimes(atime, mtime)#

      + + +

      Change the file system timestamps of the object referenced by the FileHandle +then resolves the Promise with no arguments upon success.

      +

      This function does not work on AIX versions before 7.1, it will resolve the +Promise with an error using code UV_ENOSYS.

      +

      filehandle.write(buffer[, offset[, length[, position]]])#

      + + +

      Write buffer to the file.

      +

      The Promise is resolved with an object containing a bytesWritten property +identifying the number of bytes written, and a buffer property containing +a reference to the buffer written.

      +

      offset determines the part of the buffer to be written, and length is +an integer specifying the number of bytes to write.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position. See pwrite(2).

      +

      It is unsafe to use filehandle.write() multiple times on the same file +without waiting for the Promise to be resolved (or rejected). For this +scenario, use fs.createWriteStream().

      +

      On Linux, positional writes do not work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      filehandle.write(string[, position[, encoding]])#

      + + +

      Write string to the file. If string is not a string, then +the value will be coerced to one.

      +

      The Promise is resolved with an object containing a bytesWritten property +identifying the number of bytes written, and a buffer property containing +a reference to the string written.

      +

      position refers to the offset from the beginning of the file where this data +should be written. If the type of position is not a number the data +will be written at the current position. See pwrite(2).

      +

      encoding is the expected string encoding.

      +

      It is unsafe to use filehandle.write() multiple times on the same file +without waiting for the Promise to be resolved (or rejected). For this +scenario, use fs.createWriteStream().

      +

      On Linux, positional writes do not work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      filehandle.writeFile(data, options)#

      + + +

      Asynchronously writes data to a file, replacing the file if it already exists. +data can be a string or a buffer. The Promise will be resolved with no +arguments upon success.

      +

      The encoding option is ignored if data is a buffer.

      +

      If options is a string, then it specifies the encoding.

      +

      The FileHandle has to support writing.

      +

      It is unsafe to use filehandle.writeFile() multiple times on the same file +without waiting for the Promise to be resolved (or rejected).

      +

      If one or more filehandle.write() calls are made on a file handle and then a +filehandle.writeFile() call is made, the data will be written from the +current position till the end of the file. It doesn't always write from the +beginning of the file.

      +

      filehandle.writev(buffers[, position])#

      + + +

      Write an array of ArrayBufferViews to the file.

      +

      The Promise is resolved with an object containing a bytesWritten property +identifying the number of bytes written, and a buffers property containing +a reference to the buffers input.

      +

      position is the offset from the beginning of the file where this data +should be written. If typeof position !== 'number', the data will be written +at the current position.

      +

      It is unsafe to call writev() multiple times on the same file without waiting +for the previous operation to complete.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      fsPromises.access(path[, mode])#

      + + +

      Tests a user's permissions for the file or directory specified by path. +The mode argument is an optional integer that specifies the accessibility +checks to be performed. Check File access constants for possible values +of mode. It is possible to create a mask consisting of the bitwise OR of +two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      +

      If the accessibility check is successful, the Promise is resolved with no +value. If any of the accessibility checks fail, the Promise is rejected +with an Error object. The following example checks if the file +/etc/passwd can be read and written by the current process.

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +
      +fsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK)
      +  .then(() => console.log('can access'))
      +  .catch(() => console.error('cannot access'));
      +

      Using fsPromises.access() to check for the accessibility of a file before +calling fsPromises.open() is not recommended. Doing so introduces a race +condition, since other processes may change the file's state between the two +calls. Instead, user code should open/read/write the file directly and handle +the error raised if the file is not accessible.

      +

      fsPromises.appendFile(path, data[, options])#

      + + +

      Asynchronously append data to a file, creating the file if it does not yet +exist. data can be a string or a Buffer. The Promise will be +resolved with no arguments upon success.

      +

      If options is a string, then it specifies the encoding.

      +

      The path may be specified as a FileHandle that has been opened +for appending (using fsPromises.open()).

      +

      fsPromises.chmod(path, mode)#

      + + +

      Changes the permissions of a file then resolves the Promise with no +arguments upon succces.

      +

      fsPromises.chown(path, uid, gid)#

      + + +

      Changes the ownership of a file then resolves the Promise with no arguments +upon success.

      +

      fsPromises.copyFile(src, dest[, flags])#

      + + +

      Asynchronously copies src to dest. By default, dest is overwritten if it +already exists. The Promise will be resolved with no arguments upon success.

      +

      Node.js makes no guarantees about the atomicity of the copy operation. If an +error occurs after the destination file has been opened for writing, Node.js +will attempt to remove the destination.

      +

      flags is an optional integer that specifies the behavior +of the copy operation. It is possible to create a mask consisting of the bitwise +OR of two or more values (e.g. +fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      +
        +
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already +exists.
      • +
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a +copy-on-write reflink. If the platform does not support copy-on-write, then a +fallback copy mechanism is used.
      • +
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to +create a copy-on-write reflink. If the platform does not support copy-on-write, +then the operation will fail.
      • +
      +
      const fsPromises = require('fs').promises;
      +
      +// destination.txt will be created or overwritten by default.
      +fsPromises.copyFile('source.txt', 'destination.txt')
      +  .then(() => console.log('source.txt was copied to destination.txt'))
      +  .catch(() => console.log('The file could not be copied'));
      +

      If the third argument is a number, then it specifies flags:

      +
      const fs = require('fs');
      +const fsPromises = fs.promises;
      +const { COPYFILE_EXCL } = fs.constants;
      +
      +// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
      +fsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL)
      +  .then(() => console.log('source.txt was copied to destination.txt'))
      +  .catch(() => console.log('The file could not be copied'));
      +

      fsPromises.lchmod(path, mode)#

      + + +

      Changes the permissions on a symbolic link then resolves the Promise with +no arguments upon success. This method is only implemented on macOS.

      +

      fsPromises.lchown(path, uid, gid)#

      + + +

      Changes the ownership on a symbolic link then resolves the Promise with +no arguments upon success.

      +

      fsPromises.lutimes(path, atime, mtime)#

      + + +

      Changes the access and modification times of a file in the same way as +fsPromises.utimes(), with the difference that if the path refers to a +symbolic link, then the link is not dereferenced: instead, the timestamps of +the symbolic link itself are changed.

      +

      Upon success, the Promise is resolved without arguments.

      +

      fsPromises.link(existingPath, newPath)#

      + + +

      Asynchronous link(2). The Promise is resolved with no arguments upon success.

      +

      fsPromises.lstat(path[, options])#

      + + +

      Asynchronous lstat(2). The Promise is resolved with the fs.Stats object +for the given symbolic link path.

      +

      fsPromises.mkdir(path[, options])#

      + + +

      Asynchronously creates a directory then resolves the Promise with either no +arguments, or the first directory path created if recursive is true.

      +

      The optional options argument can be an integer specifying mode (permission +and sticky bits), or an object with a mode property and a recursive +property indicating whether parent directories should be created. Calling +fsPromises.mkdir() when path is a directory that exists results in a +rejection only when recursive is false.

      +

      fsPromises.mkdtemp(prefix[, options])#

      + + +

      Creates a unique temporary directory and resolves the Promise with the created +directory path. A unique directory name is generated by appending six random +characters to the end of the provided prefix. Due to platform +inconsistencies, avoid trailing X characters in prefix. Some platforms, +notably the BSDs, can return more than six random characters, and replace +trailing X characters in prefix with random characters.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use.

      +
      fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))
      +  .catch(console.error);
      +

      The fsPromises.mkdtemp() method will append the six randomly selected +characters directly to the prefix string. For instance, given a directory +/tmp, if the intention is to create a temporary directory within /tmp, the +prefix must end with a trailing platform-specific path separator +(require('path').sep).

      +

      fsPromises.open(path, flags[, mode])#

      + + +

      Asynchronous file open that returns a Promise that, when resolved, yields a +FileHandle object. See open(2).

      +

      mode sets the file mode (permission and sticky bits), but only if the file was +created.

      +

      Some characters (< > : " / \ | ? *) are reserved under Windows as documented +by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains +a colon, Node.js will open a file system stream, as described by +this MSDN page.

      +

      fsPromises.opendir(path[, options])#

      + + +

      Asynchronously open a directory. See opendir(3).

      +

      Creates an fs.Dir, which contains all further functions for reading from +and cleaning up the directory.

      +

      The encoding option sets the encoding for the path while opening the +directory and subsequent read operations.

      +

      Example using async iteration:

      +
      const fs = require('fs');
      +
      +async function print(path) {
      +  const dir = await fs.promises.opendir(path);
      +  for await (const dirent of dir) {
      +    console.log(dirent.name);
      +  }
      +}
      +print('./').catch(console.error);
      +

      fsPromises.readdir(path[, options])#

      + + +

      Reads the contents of a directory then resolves the Promise with an array +of the names of the files in the directory excluding '.' and '..'.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the filenames. If the encoding is set to 'buffer', the filenames returned +will be passed as Buffer objects.

      +

      If options.withFileTypes is set to true, the resolved array will contain +fs.Dirent objects.

      +
      const fs = require('fs');
      +
      +async function print(path) {
      +  const files = await fs.promises.readdir(path);
      +  for (const file of files) {
      +    console.log(file);
      +  }
      +}
      +print('./').catch(console.error);
      +

      fsPromises.readFile(path[, options])#

      + + +

      Asynchronously reads the entire contents of a file.

      +

      The Promise is resolved with the contents of the file. If no encoding is +specified (using options.encoding), the data is returned as a Buffer +object. Otherwise, the data will be a string.

      +

      If options is a string, then it specifies the encoding.

      +

      When the path is a directory, the behavior of fsPromises.readFile() is +platform-specific. On macOS, Linux, and Windows, the promise will be rejected +with an error. On FreeBSD, a representation of the directory's contents will be +returned.

      +

      Any specified FileHandle has to support reading.

      +

      fsPromises.readlink(path[, options])#

      + + +

      Asynchronous readlink(2). The Promise is resolved with the linkString upon +success.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the link path returned. If the encoding is set to 'buffer', the link path +returned will be passed as a Buffer object.

      +

      fsPromises.realpath(path[, options])#

      + + +

      Determines the actual location of path using the same semantics as the +fs.realpath.native() function then resolves the Promise with the resolved +path.

      +

      Only paths that can be converted to UTF8 strings are supported.

      +

      The optional options argument can be a string specifying an encoding, or an +object with an encoding property specifying the character encoding to use for +the path. If the encoding is set to 'buffer', the path returned will be +passed as a Buffer object.

      +

      On Linux, when Node.js is linked against musl libc, the procfs file system must +be mounted on /proc in order for this function to work. Glibc does not have +this restriction.

      +

      fsPromises.rename(oldPath, newPath)#

      + + +

      Renames oldPath to newPath and resolves the Promise with no arguments +upon success.

      +

      fsPromises.rmdir(path[, options])#

      + +

      Stability: 1 - Recursive removal is experimental.

      +
        +
      • path <string> | <Buffer> | <URL>
      • +
      • options <Object> +
          +
        • maxRetries <integer> If an EBUSY, EMFILE, ENFILE, ENOTEMPTY, or +EPERM error is encountered, Node.js will retry the operation with a linear +backoff wait of retryDelay ms longer on each try. This option represents the +number of retries. This option is ignored if the recursive option is not +true. Default: 0.
        • +
        • recursive <boolean> If true, perform a recursive directory removal. In +recursive mode, errors are not reported if path does not exist, and +operations are retried on failure. Default: false.
        • +
        • retryDelay <integer> The amount of time in milliseconds to wait between +retries. This option is ignored if the recursive option is not true. +Default: 100.
        • +
        +
      • +
      • Returns: <Promise>
      • +
      +

      Removes the directory identified by path then resolves the Promise with +no arguments upon success.

      +

      Using fsPromises.rmdir() on a file (not a directory) results in the +Promise being rejected with an ENOENT error on Windows and an ENOTDIR +error on POSIX.

      +

      fsPromises.stat(path[, options])#

      + + +

      The Promise is resolved with the fs.Stats object for the given path.

      +

      fsPromises.symlink(target, path[, type])#

      + + +

      Creates a symbolic link then resolves the Promise with no arguments upon +success.

      +

      The type argument is only used on Windows platforms and can be one of 'dir', +'file', or 'junction'. Windows junction points require the destination path +to be absolute. When using 'junction', the target argument will +automatically be normalized to absolute path.

      +

      fsPromises.truncate(path[, len])#

      + + +

      Truncates the path then resolves the Promise with no arguments upon +success. The path must be a string or Buffer.

      +

      fsPromises.unlink(path)#

      + + +

      Asynchronous unlink(2). The Promise is resolved with no arguments upon +success.

      +

      fsPromises.utimes(path, atime, mtime)#

      + + +

      Change the file system timestamps of the object referenced by path then +resolves the Promise with no arguments upon success.

      +

      The atime and mtime arguments follow these rules:

      +
        +
      • Values can be either numbers representing Unix epoch time, Dates, or a +numeric string like '123456789.0'.
      • +
      • If the value can not be converted to a number, or is NaN, Infinity or +-Infinity, an Error will be thrown.
      • +
      +

      fsPromises.writeFile(file, data[, options])#

      + + +

      Asynchronously writes data to a file, replacing the file if it already exists. +data can be a string or a buffer. The Promise will be resolved with no +arguments upon success.

      +

      The encoding option is ignored if data is a buffer.

      +

      If options is a string, then it specifies the encoding.

      +

      Any specified FileHandle has to support writing.

      +

      It is unsafe to use fsPromises.writeFile() multiple times on the same file +without waiting for the Promise to be resolved (or rejected).

      +

      FS constants#

      +

      The following constants are exported by fs.constants.

      +

      Not every constant will be available on every operating system.

      +

      To use more than one constant, use the bitwise OR | operator.

      +

      Example:

      +
      const fs = require('fs');
      +
      +const {
      +  O_RDWR,
      +  O_CREAT,
      +  O_EXCL
      +} = fs.constants;
      +
      +fs.open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
      +  // ...
      +});
      +

      File access constants#

      +

      The following constants are meant for use with fs.access().

      + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      F_OKFlag indicating that the file is visible to the calling process. + This is useful for determining if a file exists, but says nothing + about rwx permissions. Default if no mode is specified.
      R_OKFlag indicating that the file can be read by the calling process.
      W_OKFlag indicating that the file can be written by the calling + process.
      X_OKFlag indicating that the file can be executed by the calling + process. This has no effect on Windows + (will behave like fs.constants.F_OK).
      +

      File copy constants#

      +

      The following constants are meant for use with fs.copyFile().

      + + + + + + + + + + + + + + + + + +
      ConstantDescription
      COPYFILE_EXCLIf present, the copy operation will fail with an error if the + destination path already exists.
      COPYFILE_FICLONEIf present, the copy operation will attempt to create a + copy-on-write reflink. If the underlying platform does not support + copy-on-write, then a fallback copy mechanism is used.
      COPYFILE_FICLONE_FORCEIf present, the copy operation will attempt to create a + copy-on-write reflink. If the underlying platform does not support + copy-on-write, then the operation will fail with an error.
      +

      File open constants#

      +

      The following constants are meant for use with fs.open().

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      O_RDONLYFlag indicating to open a file for read-only access.
      O_WRONLYFlag indicating to open a file for write-only access.
      O_RDWRFlag indicating to open a file for read-write access.
      O_CREATFlag indicating to create the file if it does not already exist.
      O_EXCLFlag indicating that opening a file should fail if the + O_CREAT flag is set and the file already exists.
      O_NOCTTYFlag indicating that if path identifies a terminal device, opening the + path shall not cause that terminal to become the controlling terminal for + the process (if the process does not already have one).
      O_TRUNCFlag 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.
      O_APPENDFlag indicating that data will be appended to the end of the file.
      O_DIRECTORYFlag indicating that the open should fail if the path is not a + directory.
      O_NOATIMEFlag indicating reading accesses to the file system will no longer + result in an update to the atime information associated with + the file. This flag is available on Linux operating systems only.
      O_NOFOLLOWFlag indicating that the open should fail if the path is a symbolic + link.
      O_SYNCFlag indicating that the file is opened for synchronized I/O with write + operations waiting for file integrity.
      O_DSYNCFlag indicating that the file is opened for synchronized I/O with write + operations waiting for data integrity.
      O_SYMLINKFlag indicating to open the symbolic link itself rather than the + resource it is pointing to.
      O_DIRECTWhen set, an attempt will be made to minimize caching effects of file + I/O.
      O_NONBLOCKFlag indicating to open the file in nonblocking mode when possible.
      UV_FS_O_FILEMAPWhen set, a memory file mapping is used to access the file. This flag + is available on Windows operating systems only. On other operating systems, + this flag is ignored.
      +

      File type constants#

      +

      The following constants are meant for use with the fs.Stats object's +mode property for determining a file's type.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      S_IFMTBit mask used to extract the file type code.
      S_IFREGFile type constant for a regular file.
      S_IFDIRFile type constant for a directory.
      S_IFCHRFile type constant for a character-oriented device file.
      S_IFBLKFile type constant for a block-oriented device file.
      S_IFIFOFile type constant for a FIFO/pipe.
      S_IFLNKFile type constant for a symbolic link.
      S_IFSOCKFile type constant for a socket.
      +

      File mode constants#

      +

      The following constants are meant for use with the fs.Stats object's +mode property for determining the access permissions for a file.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      S_IRWXUFile mode indicating readable, writable, and executable by owner.
      S_IRUSRFile mode indicating readable by owner.
      S_IWUSRFile mode indicating writable by owner.
      S_IXUSRFile mode indicating executable by owner.
      S_IRWXGFile mode indicating readable, writable, and executable by group.
      S_IRGRPFile mode indicating readable by group.
      S_IWGRPFile mode indicating writable by group.
      S_IXGRPFile mode indicating executable by group.
      S_IRWXOFile mode indicating readable, writable, and executable by others.
      S_IROTHFile mode indicating readable by others.
      S_IWOTHFile mode indicating writable by others.
      S_IXOTHFile mode indicating executable by others.
      +

      File system flags#

      +

      The following flags are available wherever the flag option takes a +string.

      +
        +
      • +

        'a': Open file for appending. +The file is created if it does not exist.

        +
      • +
      • +

        'ax': Like 'a' but fails if the path exists.

        +
      • +
      • +

        'a+': Open file for reading and appending. +The file is created if it does not exist.

        +
      • +
      • +

        'ax+': Like 'a+' but fails if the path exists.

        +
      • +
      • +

        'as': Open file for appending in synchronous mode. +The file is created if it does not exist.

        +
      • +
      • +

        'as+': Open file for reading and appending in synchronous mode. +The file is created if it does not exist.

        +
      • +
      • +

        'r': Open file for reading. +An exception occurs if the file does not exist.

        +
      • +
      • +

        'r+': Open file for reading and writing. +An exception occurs if the file does not exist.

        +
      • +
      • +

        'rs+': Open file for reading and writing in synchronous mode. Instructs +the operating system to bypass the local file system cache.

        +

        This is primarily useful for opening files on NFS mounts as it allows +skipping the potentially stale local cache. It has a very real impact on +I/O performance so using this flag is not recommended unless it is needed.

        +

        This doesn't turn fs.open() or fsPromises.open() into a synchronous +blocking call. If synchronous operation is desired, something like +fs.openSync() should be used.

        +
      • +
      • +

        'w': Open file for writing. +The file is created (if it does not exist) or truncated (if it exists).

        +
      • +
      • +

        'wx': Like 'w' but fails if the path exists.

        +
      • +
      • +

        'w+': Open file for reading and writing. +The file is created (if it does not exist) or truncated (if it exists).

        +
      • +
      • +

        'wx+': Like 'w+' but fails if the path exists.

        +
      • +
      +

      flag can also be a number as documented by open(2); commonly used constants +are available from fs.constants. On Windows, flags are translated to +their equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE, +or O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.

      +

      The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to +return an error if the path already exists. On POSIX, if the path is a symbolic +link, using O_EXCL returns an error even if the link is to a path that does +not exist. The exclusive flag may or may not work with network file systems.

      +

      On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file.

      +

      Modifying a file rather than replacing it may require a flags mode of 'r+' +rather than the default mode 'w'.

      +

      The behavior of some flags are platform-specific. As such, opening a directory +on macOS and Linux with the 'a+' flag, as in the example below, will return an +error. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle +will be returned.

      +
      // macOS and Linux
      +fs.open('<directory>', 'a+', (err, fd) => {
      +  // => [Error: EISDIR: illegal operation on a directory, open <directory>]
      +});
      +
      +// Windows and FreeBSD
      +fs.open('<directory>', 'a+', (err, fd) => {
      +  // => null, <fd>
      +});
      +

      On Windows, opening an existing hidden file using the 'w' flag (either +through fs.open() or fs.writeFile() or fsPromises.open()) will fail with +EPERM. Existing hidden files can be opened for writing with the 'r+' flag.

      +

      A call to fs.ftruncate() or filehandle.truncate() can be used to reset +the file contents.

      + +
      +
      +
      + + diff --git a/doc/api/fs.json b/doc/api/fs.json new file mode 100644 index 0000000000000000000000000000000000000000..1fe8ce0d8433068029e606225e1f14c6c3569558 --- /dev/null +++ b/doc/api/fs.json @@ -0,0 +1,8141 @@ +{ + "type": "module", + "source": "doc/api/fs.md", + "modules": [ + { + "textRaw": "File system", + "name": "fs", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/fs.js

      \n

      The fs module enables interacting with the file system in a\nway modeled on standard POSIX functions.

      \n

      To use this module:

      \n
      const fs = require('fs');\n
      \n

      All file system operations have synchronous, callback, and promise-based\nforms.

      ", + "modules": [ + { + "textRaw": "Synchronous example", + "name": "synchronous_example", + "desc": "

      The synchronous form blocks the Node.js event loop and further JavaScript\nexecution until the operation is complete. Exceptions are thrown immediately\nand can be handled using try…catch, or can be allowed to bubble up.

      \n
      const fs = require('fs');\n\ntry {\n  fs.unlinkSync('/tmp/hello');\n  console.log('successfully deleted /tmp/hello');\n} catch (err) {\n  // handle the error\n}\n
      ", + "type": "module", + "displayName": "Synchronous example" + }, + { + "textRaw": "Callback example", + "name": "callback_example", + "desc": "

      The callback form takes a completion callback function as its last\nargument and invokes the operation asynchronously. The arguments passed to\nthe completion callback depend on the method, but the first argument is always\nreserved for an exception. If the operation is completed successfully, then\nthe first argument is null or undefined.

      \n
      const fs = require('fs');\n\nfs.unlink('/tmp/hello', (err) => {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});\n
      ", + "type": "module", + "displayName": "Callback example" + }, + { + "textRaw": "Promise example", + "name": "promise_example", + "desc": "

      Promise-based operations return a Promise that is resolved when the\nasynchronous operation is complete.

      \n
      const fs = require('fs').promises;\n\n(async function(path) {\n  try {\n    await fs.unlink(path);\n    console.log(`successfully deleted ${path}`);\n  } catch (error) {\n    console.error('there was an error:', error.message);\n  }\n})('/tmp/hello');\n
      ", + "type": "module", + "displayName": "Promise example" + }, + { + "textRaw": "Ordering of callback and promise-based operations", + "name": "ordering_of_callback_and_promise-based_operations", + "desc": "

      There is no guaranteed ordering when using either the callback or\npromise-based methods. For example, the following is prone to error\nbecause the fs.stat() operation might complete before the fs.rename()\noperation:

      \n
      fs.rename('/tmp/hello', '/tmp/world', (err) => {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', (err, stats) => {\n  if (err) throw err;\n  console.log(`stats: ${JSON.stringify(stats)}`);\n});\n
      \n

      To correctly order the operations, move the fs.stat() call into the callback\nof the fs.rename() operation:

      \n
      fs.rename('/tmp/hello', '/tmp/world', (err) => {\n  if (err) throw err;\n  fs.stat('/tmp/world', (err, stats) => {\n    if (err) throw err;\n    console.log(`stats: ${JSON.stringify(stats)}`);\n  });\n});\n
      \n

      Or, use the promise-based API:

      \n
      const fs = require('fs').promises;\n\n(async function(from, to) {\n  try {\n    await fs.rename(from, to);\n    const stats = await fs.stat(to);\n    console.log(`stats: ${JSON.stringify(stats)}`);\n  } catch (error) {\n    console.error('there was an error:', error.message);\n  }\n})('/tmp/hello', '/tmp/world');\n
      ", + "type": "module", + "displayName": "Ordering of callback and promise-based operations" + }, + { + "textRaw": "File paths", + "name": "file_paths", + "desc": "

      Most fs operations accept filepaths that may be specified in the form of\na string, a Buffer, or a URL object using the file: protocol.

      \n

      String form paths are interpreted as UTF-8 character sequences identifying\nthe absolute or relative filename. Relative paths will be resolved relative\nto the current working directory as determined by calling process.cwd().

      \n

      Example using an absolute path on POSIX:

      \n
      const fs = require('fs');\n\nfs.open('/open/some/file.txt', 'r', (err, fd) => {\n  if (err) throw err;\n  fs.close(fd, (err) => {\n    if (err) throw err;\n  });\n});\n
      \n

      Example using a relative path on POSIX (relative to process.cwd()):

      \n
      fs.open('file.txt', 'r', (err, fd) => {\n  if (err) throw err;\n  fs.close(fd, (err) => {\n    if (err) throw err;\n  });\n});\n
      \n

      Paths specified using a Buffer are useful primarily on certain POSIX\noperating systems that treat file paths as opaque byte sequences. On such\nsystems, it is possible for a single file path to contain sub-sequences that\nuse multiple character encodings. As with string paths, Buffer paths may\nbe relative or absolute:

      \n

      Example using an absolute path on POSIX:

      \n
      fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {\n  if (err) throw err;\n  fs.close(fd, (err) => {\n    if (err) throw err;\n  });\n});\n
      \n

      On Windows, Node.js follows the concept of per-drive working directory. This\nbehavior can be observed when using a drive path without a backslash. For\nexample fs.readdirSync('C:\\\\') can potentially return a different result than\nfs.readdirSync('C:'). For more information, see\nthis MSDN page.

      ", + "modules": [ + { + "textRaw": "URL object support", + "name": "url_object_support", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "desc": "

      For most fs module functions, the path or filename argument may be passed\nas a WHATWG URL object. Only URL objects using the file: protocol\nare supported.

      \n
      const fs = require('fs');\nconst fileUrl = new URL('file:///tmp/hello');\n\nfs.readFileSync(fileUrl);\n
      \n

      file: URLs are always absolute paths.

      \n

      Using WHATWG URL objects might introduce platform-specific behaviors.

      \n

      On Windows, file: URLs with a host name convert to UNC paths, while file:\nURLs with drive letters convert to local absolute paths. file: URLs without a\nhost name nor a drive letter will result in a throw:

      \n
      // On Windows :\n\n// - WHATWG file URLs with hostname convert to UNC path\n// file://hostname/p/a/t/h/file => \\\\hostname\\p\\a\\t\\h\\file\nfs.readFileSync(new URL('file://hostname/p/a/t/h/file'));\n\n// - WHATWG file URLs with drive letters convert to absolute path\n// file:///C:/tmp/hello => C:\\tmp\\hello\nfs.readFileSync(new URL('file:///C:/tmp/hello'));\n\n// - WHATWG file URLs without hostname must have a drive letters\nfs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));\nfs.readFileSync(new URL('file:///c/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute\n
      \n

      file: URLs with drive letters must use : as a separator just after\nthe drive letter. Using another separator will result in a throw.

      \n

      On all other platforms, file: URLs with a host name are unsupported and will\nresult in a throw:

      \n
      // On other platforms:\n\n// - WHATWG file URLs with hostname are unsupported\n// file://hostname/p/a/t/h/file => throw!\nfs.readFileSync(new URL('file://hostname/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute\n\n// - WHATWG file URLs convert to absolute path\n// file:///tmp/hello => /tmp/hello\nfs.readFileSync(new URL('file:///tmp/hello'));\n
      \n

      A file: URL having encoded slash characters will result in a throw on all\nplatforms:

      \n
      // On Windows\nfs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));\nfs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n\n// On POSIX\nfs.readFileSync(new URL('file:///p/a/t/h/%2F'));\nfs.readFileSync(new URL('file:///p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n/ characters */\n
      \n

      On Windows, file: URLs having encoded backslash will result in a throw:

      \n
      // On Windows\nfs.readFileSync(new URL('file:///C:/path/%5C'));\nfs.readFileSync(new URL('file:///C:/path/%5c'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n
      ", + "type": "module", + "displayName": "URL object support" + } + ], + "type": "module", + "displayName": "File paths" + }, + { + "textRaw": "File descriptors", + "name": "file_descriptors", + "desc": "

      On POSIX systems, for every process, the kernel maintains a table of currently\nopen files and resources. Each open file is assigned a simple numeric\nidentifier called a file descriptor. At the system-level, all file system\noperations use these file descriptors to identify and track each specific\nfile. Windows systems use a different but conceptually similar mechanism for\ntracking resources. To simplify things for users, Node.js abstracts away the\nspecific differences between operating systems and assigns all open files a\nnumeric file descriptor.

      \n

      The fs.open() method is used to allocate a new file descriptor. Once\nallocated, the file descriptor may be used to read data from, write data to,\nor request information about the file.

      \n
      fs.open('/open/some/file.txt', 'r', (err, fd) => {\n  if (err) throw err;\n  fs.fstat(fd, (err, stat) => {\n    if (err) throw err;\n    // use stat\n\n    // always close the file descriptor!\n    fs.close(fd, (err) => {\n      if (err) throw err;\n    });\n  });\n});\n
      \n

      Most operating systems limit the number of file descriptors that may be open\nat any given time so it is critical to close the descriptor when operations\nare completed. Failure to do so will result in a memory leak that will\neventually cause an application to crash.

      ", + "type": "module", + "displayName": "File descriptors" + }, + { + "textRaw": "Threadpool usage", + "name": "threadpool_usage", + "desc": "

      All file system APIs except fs.FSWatcher() and those that are explicitly\nsynchronous use libuv's threadpool, which can have surprising and negative\nperformance implications for some applications. See the\nUV_THREADPOOL_SIZE documentation for more information.

      ", + "type": "module", + "displayName": "Threadpool usage" + }, + { + "textRaw": "`fs` Promises API", + "name": "`fs`_promises_api", + "desc": "

      The fs.promises API provides an alternative set of asynchronous file system\nmethods that return Promise objects rather than using callbacks. The\nAPI is accessible via require('fs').promises.

      ", + "classes": [ + { + "textRaw": "Class: `FileHandle`", + "type": "class", + "name": "FileHandle", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      A FileHandle object is a wrapper for a numeric file descriptor.\nInstances of FileHandle are distinct from numeric file descriptors\nin that they provide an object oriented API for working with files.

      \n

      If a FileHandle is not closed using the\nfilehandle.close() method, it might automatically close the file descriptor\nand will emit a process warning, thereby helping to prevent memory leaks.\nPlease do not rely on this behavior because it is unreliable and\nthe file may not be closed. Instead, always explicitly close FileHandles.\nNode.js may change this behavior in the future.

      \n

      Instances of the FileHandle object are created internally by the\nfsPromises.open() method.

      \n

      Unlike the callback-based API (fs.fstat(), fs.fchown(), fs.fchmod(), and\nso on), a numeric file descriptor is not used by the promise-based API. Instead,\nthe promise-based API uses the FileHandle class in order to help avoid\naccidental leaking of unclosed file descriptors after a Promise is resolved or\nrejected.

      ", + "methods": [ + { + "textRaw": "`filehandle.appendFile(data, options)`", + "type": "method", + "name": "appendFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Alias of filehandle.writeFile().

      \n

      When operating on file handles, the mode cannot be changed from what it was set\nto with fsPromises.open(). Therefore, this is equivalent to\nfilehandle.writeFile().

      " + }, + { + "textRaw": "`filehandle.chmod(mode)`", + "type": "method", + "name": "chmod", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + } + ] + } + ], + "desc": "

      Modifies the permissions on the file. The Promise is resolved with no\narguments upon success.

      " + }, + { + "textRaw": "`filehandle.chown(uid, gid)`", + "type": "method", + "name": "chown", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the ownership of the file then resolves the Promise with no arguments\nupon success.

      " + }, + { + "textRaw": "`filehandle.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} A `Promise` that will be resolved once the underlying file descriptor is closed, or will be rejected if an error occurs while closing.", + "name": "return", + "type": "Promise", + "desc": "A `Promise` that will be resolved once the underlying file descriptor is closed, or will be rejected if an error occurs while closing." + }, + "params": [] + } + ], + "desc": "

      Closes the file descriptor.

      \n
      const fsPromises = require('fs').promises;\nasync function openAndClose() {\n  let filehandle;\n  try {\n    filehandle = await fsPromises.open('thefile.txt', 'r');\n  } finally {\n    if (filehandle !== undefined)\n      await filehandle.close();\n  }\n}\n
      " + }, + { + "textRaw": "`filehandle.datasync()`", + "type": "method", + "name": "datasync", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Asynchronous fdatasync(2). The Promise is resolved with no arguments upon\nsuccess.

      " + }, + { + "textRaw": "`filehandle.read(buffer, offset, length, position)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array}", + "name": "buffer", + "type": "Buffer|Uint8Array" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Read data from the file.

      \n

      buffer is the buffer that the data will be written to.

      \n

      offset is the offset in the buffer to start writing at.

      \n

      length is an integer specifying the number of bytes to read.

      \n

      position is an argument specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position,\nand the file position will be updated.\nIf position is an integer, the file position will remain unchanged.

      \n

      Following successful read, the Promise is resolved with an object with a\nbytesRead property specifying the number of bytes read, and a buffer\nproperty that is a reference to the passed in buffer argument.

      " + }, + { + "textRaw": "`filehandle.read(options)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array} **Default:** `Buffer.alloc(16384)`", + "name": "buffer", + "type": "Buffer|Uint8Array", + "default": "`Buffer.alloc(16384)`" + }, + { + "textRaw": "`offset` {integer} **Default:** `0`", + "name": "offset", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`length` {integer} **Default:** `buffer.length`", + "name": "length", + "type": "integer", + "default": "`buffer.length`" + }, + { + "textRaw": "`position` {integer} **Default:** `null`", + "name": "position", + "type": "integer", + "default": "`null`" + } + ] + } + ] + } + ] + }, + { + "textRaw": "`filehandle.readFile(options)`", + "type": "method", + "name": "readFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously reads the entire contents of a file.

      \n

      The Promise is resolved with the contents of the file. If no encoding is\nspecified (using options.encoding), the data is returned as a Buffer\nobject. Otherwise, the data will be a string.

      \n

      If options is a string, then it specifies the encoding.

      \n

      The FileHandle has to support reading.

      \n

      If one or more filehandle.read() calls are made on a file handle and then a\nfilehandle.readFile() call is made, the data will be read from the current\nposition till the end of the file. It doesn't always read from the beginning\nof the file.

      " + }, + { + "textRaw": "`filehandle.readv(buffers[, position])`", + "type": "method", + "name": "readv", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Read from a file and write to an array of ArrayBufferViews

      \n

      The Promise is resolved with an object containing a bytesRead property\nidentifying the number of bytes read, and a buffers property containing\na reference to the buffers input.

      \n

      position is the offset from the beginning of the file where this data\nshould be read from. If typeof position !== 'number', the data will be read\nfrom the current position.

      " + }, + { + "textRaw": "`filehandle.stat([options])`", + "type": "method", + "name": "stat", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Retrieves the fs.Stats for the file.

      " + }, + { + "textRaw": "`filehandle.sync()`", + "type": "method", + "name": "sync", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Asynchronous fsync(2). The Promise is resolved with no arguments upon\nsuccess.

      " + }, + { + "textRaw": "`filehandle.truncate(len)`", + "type": "method", + "name": "truncate", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Truncates the file then resolves the Promise with no arguments upon success.

      \n

      If the file was larger than len bytes, only the first len bytes will be\nretained in the file.

      \n

      For example, the following program retains only the first four bytes of the\nfile:

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\n\nconsole.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\nasync function doTruncate() {\n  let filehandle = null;\n  try {\n    filehandle = await fsPromises.open('temp.txt', 'r+');\n    await filehandle.truncate(4);\n  } finally {\n    if (filehandle) {\n      // Close the file if it is opened.\n      await filehandle.close();\n    }\n  }\n  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node\n}\n\ndoTruncate().catch(console.error);\n
      \n

      If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\n\nconsole.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\nasync function doTruncate() {\n  let filehandle = null;\n  try {\n    filehandle = await fsPromises.open('temp.txt', 'r+');\n    await filehandle.truncate(10);\n  } finally {\n    if (filehandle) {\n      // Close the file if it is opened.\n      await filehandle.close();\n    }\n  }\n  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\\0\\0\\0\n}\n\ndoTruncate().catch(console.error);\n
      \n

      The last three bytes are null bytes ('\\0'), to compensate the over-truncation.

      " + }, + { + "textRaw": "`filehandle.utimes(atime, mtime)`", + "type": "method", + "name": "utimes", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by the FileHandle\nthen resolves the Promise with no arguments upon success.

      \n

      This function does not work on AIX versions before 7.1, it will resolve the\nPromise with an error using code UV_ENOSYS.

      " + }, + { + "textRaw": "`filehandle.write(buffer[, offset[, length[, position]]])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|Uint8Array}", + "name": "buffer", + "type": "Buffer|Uint8Array" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Write buffer to the file.

      \n

      The Promise is resolved with an object containing a bytesWritten property\nidentifying the number of bytes written, and a buffer property containing\na reference to the buffer written.

      \n

      offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position. See pwrite(2).

      \n

      It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected). For this\nscenario, use fs.createWriteStream().

      \n

      On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`filehandle.write(string[, position[, encoding]])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ], + "desc": "

      Write string to the file. If string is not a string, then\nthe value will be coerced to one.

      \n

      The Promise is resolved with an object containing a bytesWritten property\nidentifying the number of bytes written, and a buffer property containing\na reference to the string written.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If the type of position is not a number the data\nwill be written at the current position. See pwrite(2).

      \n

      encoding is the expected string encoding.

      \n

      It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected). For this\nscenario, use fs.createWriteStream().

      \n

      On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`filehandle.writeFile(data, options)`", + "type": "method", + "name": "writeFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer. The Promise will be resolved with no\narguments upon success.

      \n

      The encoding option is ignored if data is a buffer.

      \n

      If options is a string, then it specifies the encoding.

      \n

      The FileHandle has to support writing.

      \n

      It is unsafe to use filehandle.writeFile() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected).

      \n

      If one or more filehandle.write() calls are made on a file handle and then a\nfilehandle.writeFile() call is made, the data will be written from the\ncurrent position till the end of the file. It doesn't always write from the\nbeginning of the file.

      " + }, + { + "textRaw": "`filehandle.writev(buffers[, position])`", + "type": "method", + "name": "writev", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Write an array of ArrayBufferViews to the file.

      \n

      The Promise is resolved with an object containing a bytesWritten property\nidentifying the number of bytes written, and a buffers property containing\na reference to the buffers input.

      \n

      position is the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position.

      \n

      It is unsafe to call writev() multiple times on the same file without waiting\nfor the previous operation to complete.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + } + ], + "properties": [ + { + "textRaw": "`fd` {number} The numeric file descriptor managed by the `FileHandle` object.", + "type": "number", + "name": "fd", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "The numeric file descriptor managed by the `FileHandle` object." + } + ] + } + ], + "methods": [ + { + "textRaw": "`fsPromises.access(path[, mode])`", + "type": "method", + "name": "access", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", + "name": "mode", + "type": "integer", + "default": "`fs.constants.F_OK`" + } + ] + } + ], + "desc": "

      Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. Check File access constants for possible values\nof mode. It is possible to create a mask consisting of the bitwise OR of\ntwo or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      \n

      If the accessibility check is successful, the Promise is resolved with no\nvalue. If any of the accessibility checks fail, the Promise is rejected\nwith an Error object. The following example checks if the file\n/etc/passwd can be read and written by the current process.

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\n\nfsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK)\n  .then(() => console.log('can access'))\n  .catch(() => console.error('cannot access'));\n
      \n

      Using fsPromises.access() to check for the accessibility of a file before\ncalling fsPromises.open() is not recommended. Doing so introduces a race\ncondition, since other processes may change the file's state between the two\ncalls. Instead, user code should open/read/write the file directly and handle\nthe error raised if the file is not accessible.

      " + }, + { + "textRaw": "`fsPromises.appendFile(path, data[, options])`", + "type": "method", + "name": "appendFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|FileHandle} filename or `FileHandle`", + "name": "path", + "type": "string|Buffer|URL|FileHandle", + "desc": "filename or `FileHandle`" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.", + "name": "flag", + "type": "string", + "default": "`'a'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a Buffer. The Promise will be\nresolved with no arguments upon success.

      \n

      If options is a string, then it specifies the encoding.

      \n

      The path may be specified as a FileHandle that has been opened\nfor appending (using fsPromises.open()).

      " + }, + { + "textRaw": "`fsPromises.chmod(path, mode)`", + "type": "method", + "name": "chmod", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + } + ] + } + ], + "desc": "

      Changes the permissions of a file then resolves the Promise with no\narguments upon succces.

      " + }, + { + "textRaw": "`fsPromises.chown(path, uid, gid)`", + "type": "method", + "name": "chown", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the ownership of a file then resolves the Promise with no arguments\nupon success.

      " + }, + { + "textRaw": "`fsPromises.copyFile(src, dest[, flags])`", + "type": "method", + "name": "copyFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v14.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27044", + "description": "Changed 'flags' argument to 'mode' and imposed stricter type validation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`src` {string|Buffer|URL} source filename to copy", + "name": "src", + "type": "string|Buffer|URL", + "desc": "source filename to copy" + }, + { + "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", + "name": "dest", + "type": "string|Buffer|URL", + "desc": "destination filename of the copy operation" + }, + { + "textRaw": "`flags` {number} modifiers for copy operation. **Default:** `0`.", + "name": "flags", + "type": "number", + "default": "`0`", + "desc": "modifiers for copy operation." + } + ] + } + ], + "desc": "

      Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists. The Promise will be resolved with no arguments upon success.

      \n

      Node.js makes no guarantees about the atomicity of the copy operation. If an\nerror occurs after the destination file has been opened for writing, Node.js\nwill attempt to remove the destination.

      \n

      flags is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      \n
        \n
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
      • \n
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.
      • \n
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support copy-on-write,\nthen the operation will fail.
      • \n
      \n
      const fsPromises = require('fs').promises;\n\n// destination.txt will be created or overwritten by default.\nfsPromises.copyFile('source.txt', 'destination.txt')\n  .then(() => console.log('source.txt was copied to destination.txt'))\n  .catch(() => console.log('The file could not be copied'));\n
      \n

      If the third argument is a number, then it specifies flags:

      \n
      const fs = require('fs');\nconst fsPromises = fs.promises;\nconst { COPYFILE_EXCL } = fs.constants;\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\nfsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL)\n  .then(() => console.log('source.txt was copied to destination.txt'))\n  .catch(() => console.log('The file could not be copied'));\n
      " + }, + { + "textRaw": "`fsPromises.lchmod(path, mode)`", + "type": "method", + "name": "lchmod", + "meta": { + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the permissions on a symbolic link then resolves the Promise with\nno arguments upon success. This method is only implemented on macOS.

      " + }, + { + "textRaw": "`fsPromises.lchown(path, uid, gid)`", + "type": "method", + "name": "lchown", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "This API is no longer deprecated." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Changes the ownership on a symbolic link then resolves the Promise with\nno arguments upon success.

      " + }, + { + "textRaw": "`fsPromises.lutimes(path, atime, mtime)`", + "type": "method", + "name": "lutimes", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Changes the access and modification times of a file in the same way as\nfsPromises.utimes(), with the difference that if the path refers to a\nsymbolic link, then the link is not dereferenced: instead, the timestamps of\nthe symbolic link itself are changed.

      \n

      Upon success, the Promise is resolved without arguments.

      " + }, + { + "textRaw": "`fsPromises.link(existingPath, newPath)`", + "type": "method", + "name": "link", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`existingPath` {string|Buffer|URL}", + "name": "existingPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Asynchronous link(2). The Promise is resolved with no arguments upon success.

      " + }, + { + "textRaw": "`fsPromises.lstat(path[, options])`", + "type": "method", + "name": "lstat", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lstat(2). The Promise is resolved with the fs.Stats object\nfor the given symbolic link path.

      " + }, + { + "textRaw": "`fsPromises.mkdir(path[, options])`", + "type": "method", + "name": "mkdir", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object|integer}", + "name": "options", + "type": "Object|integer", + "options": [ + { + "textRaw": "`recursive` {boolean} **Default:** `false`", + "name": "recursive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", + "name": "mode", + "type": "string|integer", + "default": "`0o777`", + "desc": "Not supported on Windows." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously creates a directory then resolves the Promise with either no\narguments, or the first directory path created if recursive is true.

      \n

      The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfsPromises.mkdir() when path is a directory that exists results in a\nrejection only when recursive is false.

      " + }, + { + "textRaw": "`fsPromises.mkdtemp(prefix[, options])`", + "type": "method", + "name": "mkdtemp", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`prefix` {string}", + "name": "prefix", + "type": "string" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Creates a unique temporary directory and resolves the Promise with the created\ndirectory path. A unique directory name is generated by appending six random\ncharacters to the end of the provided prefix. Due to platform\ninconsistencies, avoid trailing X characters in prefix. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing X characters in prefix with random characters.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

      \n
      fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))\n  .catch(console.error);\n
      \n

      The fsPromises.mkdtemp() method will append the six randomly selected\ncharacters directly to the prefix string. For instance, given a directory\n/tmp, if the intention is to create a temporary directory within /tmp, the\nprefix must end with a trailing platform-specific path separator\n(require('path').sep).

      " + }, + { + "textRaw": "`fsPromises.open(path, flags[, mode])`", + "type": "method", + "name": "open", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v11.1.0", + "pr-url": "https://github.com/nodejs/node/pull/23767", + "description": "The `flags` argument is now optional and defaults to `'r'`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`flags` {string|number} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flags", + "type": "string|number", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`mode` {string|integer} **Default:** `0o666` (readable and writable)", + "name": "mode", + "type": "string|integer", + "default": "`0o666` (readable and writable)" + } + ] + } + ], + "desc": "

      Asynchronous file open that returns a Promise that, when resolved, yields a\nFileHandle object. See open(2).

      \n

      mode sets the file mode (permission and sticky bits), but only if the file was\ncreated.

      \n

      Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.

      " + }, + { + "textRaw": "`fsPromises.opendir(path[, options])`", + "type": "method", + "name": "opendir", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30114", + "description": "The `bufferSize` option was introduced." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} containing {fs.Dir}", + "name": "return", + "type": "Promise", + "desc": "containing {fs.Dir}" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`", + "name": "bufferSize", + "type": "number", + "default": "`32`", + "desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously open a directory. See opendir(3).

      \n

      Creates an fs.Dir, which contains all further functions for reading from\nand cleaning up the directory.

      \n

      The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

      \n

      Example using async iteration:

      \n
      const fs = require('fs');\n\nasync function print(path) {\n  const dir = await fs.promises.opendir(path);\n  for await (const dirent of dir) {\n    console.log(dirent.name);\n  }\n}\nprint('./').catch(console.error);\n
      " + }, + { + "textRaw": "`fsPromises.readdir(path[, options])`", + "type": "method", + "name": "readdir", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.11.0", + "pr-url": "https://github.com/nodejs/node/pull/22020", + "description": "New option `withFileTypes` was added." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`withFileTypes` {boolean} **Default:** `false`", + "name": "withFileTypes", + "type": "boolean", + "default": "`false`" + } + ] + } + ] + } + ], + "desc": "

      Reads the contents of a directory then resolves the Promise with an array\nof the names of the files in the directory excluding '.' and '..'.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames. If the encoding is set to 'buffer', the filenames returned\nwill be passed as Buffer objects.

      \n

      If options.withFileTypes is set to true, the resolved array will contain\nfs.Dirent objects.

      \n
      const fs = require('fs');\n\nasync function print(path) {\n  const files = await fs.promises.readdir(path);\n  for (const file of files) {\n    console.log(file);\n  }\n}\nprint('./').catch(console.error);\n
      " + }, + { + "textRaw": "`fsPromises.readFile(path[, options])`", + "type": "method", + "name": "readFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|FileHandle} filename or `FileHandle`", + "name": "path", + "type": "string|Buffer|URL|FileHandle", + "desc": "filename or `FileHandle`" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flag", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously reads the entire contents of a file.

      \n

      The Promise is resolved with the contents of the file. If no encoding is\nspecified (using options.encoding), the data is returned as a Buffer\nobject. Otherwise, the data will be a string.

      \n

      If options is a string, then it specifies the encoding.

      \n

      When the path is a directory, the behavior of fsPromises.readFile() is\nplatform-specific. On macOS, Linux, and Windows, the promise will be rejected\nwith an error. On FreeBSD, a representation of the directory's contents will be\nreturned.

      \n

      Any specified FileHandle has to support reading.

      " + }, + { + "textRaw": "`fsPromises.readlink(path[, options])`", + "type": "method", + "name": "readlink", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous readlink(2). The Promise is resolved with the linkString upon\nsuccess.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer', the link path\nreturned will be passed as a Buffer object.

      " + }, + { + "textRaw": "`fsPromises.realpath(path[, options])`", + "type": "method", + "name": "realpath", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Determines the actual location of path using the same semantics as the\nfs.realpath.native() function then resolves the Promise with the resolved\npath.

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path. If the encoding is set to 'buffer', the path returned will be\npassed as a Buffer object.

      \n

      On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.

      " + }, + { + "textRaw": "`fsPromises.rename(oldPath, newPath)`", + "type": "method", + "name": "rename", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`oldPath` {string|Buffer|URL}", + "name": "oldPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Renames oldPath to newPath and resolves the Promise with no arguments\nupon success.

      " + }, + { + "textRaw": "`fsPromises.rmdir(path[, options])`", + "type": "method", + "name": "rmdir", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30644", + "description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried." + }, + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29168", + "description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported." + } + ] + }, + "stability": 1, + "stabilityText": "Recursive removal is experimental.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", + "name": "maxRetries", + "type": "integer", + "default": "`0`", + "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." + }, + { + "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure. **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure." + }, + { + "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", + "name": "retryDelay", + "type": "integer", + "default": "`100`", + "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." + } + ] + } + ] + } + ], + "desc": "

      Removes the directory identified by path then resolves the Promise with\nno arguments upon success.

      \n

      Using fsPromises.rmdir() on a file (not a directory) results in the\nPromise being rejected with an ENOENT error on Windows and an ENOTDIR\nerror on POSIX.

      " + }, + { + "textRaw": "`fsPromises.stat(path[, options])`", + "type": "method", + "name": "stat", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      The Promise is resolved with the fs.Stats object for the given path.

      " + }, + { + "textRaw": "`fsPromises.symlink(target, path[, type])`", + "type": "method", + "name": "symlink", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`target` {string|Buffer|URL}", + "name": "target", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`type` {string} **Default:** `'file'`", + "name": "type", + "type": "string", + "default": "`'file'`" + } + ] + } + ], + "desc": "

      Creates a symbolic link then resolves the Promise with no arguments upon\nsuccess.

      \n

      The type argument is only used on Windows platforms and can be one of 'dir',\n'file', or 'junction'. Windows junction points require the destination path\nto be absolute. When using 'junction', the target argument will\nautomatically be normalized to absolute path.

      " + }, + { + "textRaw": "`fsPromises.truncate(path[, len])`", + "type": "method", + "name": "truncate", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Truncates the path then resolves the Promise with no arguments upon\nsuccess. The path must be a string or Buffer.

      " + }, + { + "textRaw": "`fsPromises.unlink(path)`", + "type": "method", + "name": "unlink", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Asynchronous unlink(2). The Promise is resolved with no arguments upon\nsuccess.

      " + }, + { + "textRaw": "`fsPromises.utimes(path, atime, mtime)`", + "type": "method", + "name": "utimes", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by path then\nresolves the Promise with no arguments upon success.

      \n

      The atime and mtime arguments follow these rules:

      \n
        \n
      • Values can be either numbers representing Unix epoch time, Dates, or a\nnumeric string like '123456789.0'.
      • \n
      • If the value can not be converted to a number, or is NaN, Infinity or\n-Infinity, an Error will be thrown.
      • \n
      " + }, + { + "textRaw": "`fsPromises.writeFile(file, data[, options])`", + "type": "method", + "name": "writeFile", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`file` {string|Buffer|URL|FileHandle} filename or `FileHandle`", + "name": "file", + "type": "string|Buffer|URL|FileHandle", + "desc": "filename or `FileHandle`" + }, + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flag", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer. The Promise will be resolved with no\narguments upon success.

      \n

      The encoding option is ignored if data is a buffer.

      \n

      If options is a string, then it specifies the encoding.

      \n

      Any specified FileHandle has to support writing.

      \n

      It is unsafe to use fsPromises.writeFile() multiple times on the same file\nwithout waiting for the Promise to be resolved (or rejected).

      " + } + ], + "type": "module", + "displayName": "`fs` Promises API" + }, + { + "textRaw": "FS constants", + "name": "fs_constants", + "desc": "

      The following constants are exported by fs.constants.

      \n

      Not every constant will be available on every operating system.

      \n

      To use more than one constant, use the bitwise OR | operator.

      \n

      Example:

      \n
      const fs = require('fs');\n\nconst {\n  O_RDWR,\n  O_CREAT,\n  O_EXCL\n} = fs.constants;\n\nfs.open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {\n  // ...\n});\n
      ", + "modules": [ + { + "textRaw": "File access constants", + "name": "file_access_constants", + "desc": "

      The following constants are meant for use with fs.access().

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      F_OKFlag indicating that the file is visible to the calling process.\n This is useful for determining if a file exists, but says nothing\n about rwx permissions. Default if no mode is specified.
      R_OKFlag indicating that the file can be read by the calling process.
      W_OKFlag indicating that the file can be written by the calling\n process.
      X_OKFlag indicating that the file can be executed by the calling\n process. This has no effect on Windows\n (will behave like fs.constants.F_OK).
      ", + "type": "module", + "displayName": "File access constants" + }, + { + "textRaw": "File copy constants", + "name": "file_copy_constants", + "desc": "

      The following constants are meant for use with fs.copyFile().

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      COPYFILE_EXCLIf present, the copy operation will fail with an error if the\n destination path already exists.
      COPYFILE_FICLONEIf present, the copy operation will attempt to create a\n copy-on-write reflink. If the underlying platform does not support\n copy-on-write, then a fallback copy mechanism is used.
      COPYFILE_FICLONE_FORCEIf present, the copy operation will attempt to create a\n copy-on-write reflink. If the underlying platform does not support\n copy-on-write, then the operation will fail with an error.
      ", + "type": "module", + "displayName": "File copy constants" + }, + { + "textRaw": "File open constants", + "name": "file_open_constants", + "desc": "

      The following constants are meant for use with fs.open().

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      O_RDONLYFlag indicating to open a file for read-only access.
      O_WRONLYFlag indicating to open a file for write-only access.
      O_RDWRFlag indicating to open a file for read-write access.
      O_CREATFlag indicating to create the file if it does not already exist.
      O_EXCLFlag indicating that opening a file should fail if the\n O_CREAT flag is set and the file already exists.
      O_NOCTTYFlag indicating that if path identifies a terminal device, opening the\n path shall not cause that terminal to become the controlling terminal for\n the process (if the process does not already have one).
      O_TRUNCFlag indicating that if the file exists and is a regular file, and the\n file is opened successfully for write access, its length shall be truncated\n to zero.
      O_APPENDFlag indicating that data will be appended to the end of the file.
      O_DIRECTORYFlag indicating that the open should fail if the path is not a\n directory.
      O_NOATIMEFlag indicating reading accesses to the file system will no longer\n result in an update to the atime information associated with\n the file. This flag is available on Linux operating systems only.
      O_NOFOLLOWFlag indicating that the open should fail if the path is a symbolic\n link.
      O_SYNCFlag indicating that the file is opened for synchronized I/O with write\n operations waiting for file integrity.
      O_DSYNCFlag indicating that the file is opened for synchronized I/O with write\n operations waiting for data integrity.
      O_SYMLINKFlag indicating to open the symbolic link itself rather than the\n resource it is pointing to.
      O_DIRECTWhen set, an attempt will be made to minimize caching effects of file\n I/O.
      O_NONBLOCKFlag indicating to open the file in nonblocking mode when possible.
      UV_FS_O_FILEMAPWhen set, a memory file mapping is used to access the file. This flag\n is available on Windows operating systems only. On other operating systems,\n this flag is ignored.
      ", + "type": "module", + "displayName": "File open constants" + }, + { + "textRaw": "File type constants", + "name": "file_type_constants", + "desc": "

      The following constants are meant for use with the fs.Stats object's\nmode property for determining a file's type.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      S_IFMTBit mask used to extract the file type code.
      S_IFREGFile type constant for a regular file.
      S_IFDIRFile type constant for a directory.
      S_IFCHRFile type constant for a character-oriented device file.
      S_IFBLKFile type constant for a block-oriented device file.
      S_IFIFOFile type constant for a FIFO/pipe.
      S_IFLNKFile type constant for a symbolic link.
      S_IFSOCKFile type constant for a socket.
      ", + "type": "module", + "displayName": "File type constants" + }, + { + "textRaw": "File mode constants", + "name": "file_mode_constants", + "desc": "

      The following constants are meant for use with the fs.Stats object's\nmode property for determining the access permissions for a file.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      S_IRWXUFile mode indicating readable, writable, and executable by owner.
      S_IRUSRFile mode indicating readable by owner.
      S_IWUSRFile mode indicating writable by owner.
      S_IXUSRFile mode indicating executable by owner.
      S_IRWXGFile mode indicating readable, writable, and executable by group.
      S_IRGRPFile mode indicating readable by group.
      S_IWGRPFile mode indicating writable by group.
      S_IXGRPFile mode indicating executable by group.
      S_IRWXOFile mode indicating readable, writable, and executable by others.
      S_IROTHFile mode indicating readable by others.
      S_IWOTHFile mode indicating writable by others.
      S_IXOTHFile mode indicating executable by others.
      ", + "type": "module", + "displayName": "File mode constants" + } + ], + "type": "module", + "displayName": "FS constants" + }, + { + "textRaw": "File system flags", + "name": "file_system_flags", + "desc": "

      The following flags are available wherever the flag option takes a\nstring.

      \n
        \n
      • \n

        'a': Open file for appending.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'ax': Like 'a' but fails if the path exists.

        \n
      • \n
      • \n

        'a+': Open file for reading and appending.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'ax+': Like 'a+' but fails if the path exists.

        \n
      • \n
      • \n

        'as': Open file for appending in synchronous mode.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'as+': Open file for reading and appending in synchronous mode.\nThe file is created if it does not exist.

        \n
      • \n
      • \n

        'r': Open file for reading.\nAn exception occurs if the file does not exist.

        \n
      • \n
      • \n

        'r+': Open file for reading and writing.\nAn exception occurs if the file does not exist.

        \n
      • \n
      • \n

        'rs+': Open file for reading and writing in synchronous mode. Instructs\nthe operating system to bypass the local file system cache.

        \n

        This is primarily useful for opening files on NFS mounts as it allows\nskipping the potentially stale local cache. It has a very real impact on\nI/O performance so using this flag is not recommended unless it is needed.

        \n

        This doesn't turn fs.open() or fsPromises.open() into a synchronous\nblocking call. If synchronous operation is desired, something like\nfs.openSync() should be used.

        \n
      • \n
      • \n

        'w': Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

        \n
      • \n
      • \n

        'wx': Like 'w' but fails if the path exists.

        \n
      • \n
      • \n

        'w+': Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

        \n
      • \n
      • \n

        'wx+': Like 'w+' but fails if the path exists.

        \n
      • \n
      \n

      flag can also be a number as documented by open(2); commonly used constants\nare available from fs.constants. On Windows, flags are translated to\ntheir equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE,\nor O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.

      \n

      The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to\nreturn an error if the path already exists. On POSIX, if the path is a symbolic\nlink, using O_EXCL returns an error even if the link is to a path that does\nnot exist. The exclusive flag may or may not work with network file systems.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      \n

      Modifying a file rather than replacing it may require a flags mode of 'r+'\nrather than the default mode 'w'.

      \n

      The behavior of some flags are platform-specific. As such, opening a directory\non macOS and Linux with the 'a+' flag, as in the example below, will return an\nerror. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle\nwill be returned.

      \n
      // macOS and Linux\nfs.open('<directory>', 'a+', (err, fd) => {\n  // => [Error: EISDIR: illegal operation on a directory, open <directory>]\n});\n\n// Windows and FreeBSD\nfs.open('<directory>', 'a+', (err, fd) => {\n  // => null, <fd>\n});\n
      \n

      On Windows, opening an existing hidden file using the 'w' flag (either\nthrough fs.open() or fs.writeFile() or fsPromises.open()) will fail with\nEPERM. Existing hidden files can be opened for writing with the 'r+' flag.

      \n

      A call to fs.ftruncate() or filehandle.truncate() can be used to reset\nthe file contents.

      ", + "type": "module", + "displayName": "File system flags" + } + ], + "classes": [ + { + "textRaw": "Class: `fs.Dir`", + "type": "class", + "name": "fs.Dir", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      A class representing a directory stream.

      \n

      Created by fs.opendir(), fs.opendirSync(), or\nfsPromises.opendir().

      \n
      const fs = require('fs');\n\nasync function print(path) {\n  const dir = await fs.promises.opendir(path);\n  for await (const dirent of dir) {\n    console.log(dirent.name);\n  }\n}\nprint('./').catch(console.error);\n
      ", + "methods": [ + { + "textRaw": "`dir.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

      Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

      \n

      A Promise is returned that will be resolved after the resource has been\nclosed.

      " + }, + { + "textRaw": "`dir.close(callback)`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

      \n

      The callback will be called after the resource handle has been closed.

      " + }, + { + "textRaw": "`dir.closeSync()`", + "type": "method", + "name": "closeSync", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Synchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

      " + }, + { + "textRaw": "`dir.read()`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} containing {fs.Dirent|null}", + "name": "return", + "type": "Promise", + "desc": "containing {fs.Dirent|null}" + }, + "params": [] + } + ], + "desc": "

      Asynchronously read the next directory entry via readdir(3) as an\nfs.Dirent.

      \n

      After the read is completed, a Promise is returned that will be resolved with\nan fs.Dirent, or null if there are no more directory entries to read.

      \n

      Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + }, + { + "textRaw": "`dir.read(callback)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`dirent` {fs.Dirent|null}", + "name": "dirent", + "type": "fs.Dirent|null" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously read the next directory entry via readdir(3) as an\nfs.Dirent.

      \n

      After the read is completed, the callback will be called with an\nfs.Dirent, or null if there are no more directory entries to read.

      \n

      Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + }, + { + "textRaw": "`dir.readSync()`", + "type": "method", + "name": "readSync", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Dirent|null}", + "name": "return", + "type": "fs.Dirent|null" + }, + "params": [] + } + ], + "desc": "

      Synchronously read the next directory entry via readdir(3) as an\nfs.Dirent.

      \n

      If there are no more directory entries to read, null will be returned.

      \n

      Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + }, + { + "textRaw": "`dir[Symbol.asyncIterator]()`", + "type": "method", + "name": "[Symbol.asyncIterator]", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator} of {fs.Dirent}", + "name": "return", + "type": "AsyncIterator", + "desc": "of {fs.Dirent}" + }, + "params": [] + } + ], + "desc": "

      Asynchronously iterates over the directory via readdir(3) until all entries have\nbeen read.

      \n

      Entries returned by the async iterator are always an fs.Dirent.\nThe null case from dir.read() is handled internally.

      \n

      See fs.Dir for an example.

      \n

      Directory entries returned by this iterator are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory may or may not be\nincluded in the iteration results.

      " + } + ], + "properties": [ + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "desc": "

      The read-only path of this directory as was provided to fs.opendir(),\nfs.opendirSync(), or fsPromises.opendir().

      " + } + ] + }, + { + "textRaw": "Class: `fs.Dirent`", + "type": "class", + "name": "fs.Dirent", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      A representation of a directory entry, which can be a file or a subdirectory\nwithin the directory, as returned by reading from an fs.Dir. The\ndirectory entry is a combination of the file name and file type pairs.

      \n

      Additionally, when fs.readdir() or fs.readdirSync() is called with\nthe withFileTypes option set to true, the resulting array is filled with\nfs.Dirent objects, rather than strings or Buffers.

      ", + "methods": [ + { + "textRaw": "`dirent.isBlockDevice()`", + "type": "method", + "name": "isBlockDevice", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a block device.

      " + }, + { + "textRaw": "`dirent.isCharacterDevice()`", + "type": "method", + "name": "isCharacterDevice", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a character device.

      " + }, + { + "textRaw": "`dirent.isDirectory()`", + "type": "method", + "name": "isDirectory", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a file system\ndirectory.

      " + }, + { + "textRaw": "`dirent.isFIFO()`", + "type": "method", + "name": "isFIFO", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a first-in-first-out\n(FIFO) pipe.

      " + }, + { + "textRaw": "`dirent.isFile()`", + "type": "method", + "name": "isFile", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a regular file.

      " + }, + { + "textRaw": "`dirent.isSocket()`", + "type": "method", + "name": "isSocket", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a socket.

      " + }, + { + "textRaw": "`dirent.isSymbolicLink()`", + "type": "method", + "name": "isSymbolicLink", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Dirent object describes a symbolic link.

      " + } + ], + "properties": [ + { + "textRaw": "`name` {string|Buffer}", + "type": "string|Buffer", + "name": "name", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      The file name that this fs.Dirent object refers to. The type of this\nvalue is determined by the options.encoding passed to fs.readdir() or\nfs.readdirSync().

      " + } + ] + }, + { + "textRaw": "Class: `fs.FSWatcher`", + "type": "class", + "name": "fs.FSWatcher", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "\n

      A successful call to fs.watch() method will return a new fs.FSWatcher\nobject.

      \n

      All fs.FSWatcher objects emit a 'change' event whenever a specific watched\nfile is modified.

      ", + "events": [ + { + "textRaw": "Event: `'change'`", + "type": "event", + "name": "change", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`eventType` {string} The type of change event that has occurred", + "name": "eventType", + "type": "string", + "desc": "The type of change event that has occurred" + }, + { + "textRaw": "`filename` {string|Buffer} The filename that changed (if relevant/available)", + "name": "filename", + "type": "string|Buffer", + "desc": "The filename that changed (if relevant/available)" + } + ], + "desc": "

      Emitted when something changes in a watched directory or file.\nSee more details in fs.watch().

      \n

      The filename argument may not be provided depending on operating system\nsupport. If filename is provided, it will be provided as a Buffer if\nfs.watch() is called with its encoding option set to 'buffer', otherwise\nfilename will be a UTF-8 string.

      \n
      // Example when handled through fs.watch() listener\nfs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {\n  if (filename) {\n    console.log(filename);\n    // Prints: <Buffer ...>\n  }\n});\n
      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the watcher stops watching for changes. The closed\nfs.FSWatcher object is no longer usable in the event handler.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ], + "desc": "

      Emitted when an error occurs while watching the file. The errored\nfs.FSWatcher object is no longer usable in the event handler.

      " + } + ], + "methods": [ + { + "textRaw": "`watcher.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Stop watching for changes on the given fs.FSWatcher. Once stopped, the\nfs.FSWatcher object is no longer usable.

      " + }, + { + "textRaw": "`watcher.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.FSWatcher}", + "name": "return", + "type": "fs.FSWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nFSWatcher is active. Calling watcher.ref() multiple times will have\nno effect.

      \n

      By default, all FSWatcher objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.

      " + }, + { + "textRaw": "`watcher.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.FSWatcher}", + "name": "return", + "type": "fs.FSWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, the active FSWatcher object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the FSWatcher object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.

      " + } + ] + }, + { + "textRaw": "Class: `fs.StatWatcher`", + "type": "class", + "name": "fs.StatWatcher", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "desc": "\n

      A successful call to fs.watchFile() method will return a new fs.StatWatcher\nobject.

      ", + "methods": [ + { + "textRaw": "`watcher.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.StatWatcher}", + "name": "return", + "type": "fs.StatWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nStatWatcher is active. Calling watcher.ref() multiple times will have\nno effect.

      \n

      By default, all StatWatcher objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.

      " + }, + { + "textRaw": "`watcher.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v12.20.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.StatWatcher}", + "name": "return", + "type": "fs.StatWatcher" + }, + "params": [] + } + ], + "desc": "

      When called, the active StatWatcher object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the StatWatcher object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.

      " + } + ] + }, + { + "textRaw": "Class: `fs.ReadStream`", + "type": "class", + "name": "fs.ReadStream", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "\n

      Instances of fs.ReadStream are created and returned using the\nfs.createReadStream() function.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the fs.ReadStream's underlying file descriptor has been closed.

      " + }, + { + "textRaw": "Event: `'open'`", + "type": "event", + "name": "open", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`fd` {integer} Integer file descriptor used by the `ReadStream`.", + "name": "fd", + "type": "integer", + "desc": "Integer file descriptor used by the `ReadStream`." + } + ], + "desc": "

      Emitted when the fs.ReadStream's file descriptor has been opened.

      " + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v9.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the fs.ReadStream is ready to be used.

      \n

      Fires immediately after 'open'.

      " + } + ], + "properties": [ + { + "textRaw": "`bytesRead` {number}", + "type": "number", + "name": "bytesRead", + "meta": { + "added": [ + "v6.4.0" + ], + "changes": [] + }, + "desc": "

      The number of bytes that have been read so far.

      " + }, + { + "textRaw": "`path` {string|Buffer}", + "type": "string|Buffer", + "name": "path", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "

      The path to the file the stream is reading from as specified in the first\nargument to fs.createReadStream(). If path is passed as a string, then\nreadStream.path will be a string. If path is passed as a Buffer, then\nreadStream.path will be a Buffer.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.

      " + } + ] + }, + { + "textRaw": "Class: `fs.Stats`", + "type": "class", + "name": "fs.Stats", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v8.1.0", + "pr-url": "https://github.com/nodejs/node/pull/13173", + "description": "Added times as numbers." + } + ] + }, + "desc": "

      A fs.Stats object provides information about a file.

      \n

      Objects returned from fs.stat(), fs.lstat() and fs.fstat() and\ntheir synchronous counterparts are of this type.\nIf bigint in the options passed to those methods is true, the numeric values\nwill be bigint instead of number, and the object will contain additional\nnanosecond-precision properties suffixed with Ns.

      \n
      Stats {\n  dev: 2114,\n  ino: 48064969,\n  mode: 33188,\n  nlink: 1,\n  uid: 85,\n  gid: 100,\n  rdev: 0,\n  size: 527,\n  blksize: 4096,\n  blocks: 8,\n  atimeMs: 1318289051000.1,\n  mtimeMs: 1318289051000.1,\n  ctimeMs: 1318289051000.1,\n  birthtimeMs: 1318289051000.1,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n
      \n

      bigint version:

      \n
      BigIntStats {\n  dev: 2114n,\n  ino: 48064969n,\n  mode: 33188n,\n  nlink: 1n,\n  uid: 85n,\n  gid: 100n,\n  rdev: 0n,\n  size: 527n,\n  blksize: 4096n,\n  blocks: 8n,\n  atimeMs: 1318289051000n,\n  mtimeMs: 1318289051000n,\n  ctimeMs: 1318289051000n,\n  birthtimeMs: 1318289051000n,\n  atimeNs: 1318289051000000000n,\n  mtimeNs: 1318289051000000000n,\n  ctimeNs: 1318289051000000000n,\n  birthtimeNs: 1318289051000000000n,\n  atime: Mon, 10 Oct 2011 23:24:11 GMT,\n  mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n  ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n
      ", + "methods": [ + { + "textRaw": "`stats.isBlockDevice()`", + "type": "method", + "name": "isBlockDevice", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a block device.

      " + }, + { + "textRaw": "`stats.isCharacterDevice()`", + "type": "method", + "name": "isCharacterDevice", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a character device.

      " + }, + { + "textRaw": "`stats.isDirectory()`", + "type": "method", + "name": "isDirectory", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a file system directory.

      " + }, + { + "textRaw": "`stats.isFIFO()`", + "type": "method", + "name": "isFIFO", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a first-in-first-out (FIFO)\npipe.

      " + }, + { + "textRaw": "`stats.isFile()`", + "type": "method", + "name": "isFile", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a regular file.

      " + }, + { + "textRaw": "`stats.isSocket()`", + "type": "method", + "name": "isSocket", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a socket.

      " + }, + { + "textRaw": "`stats.isSymbolicLink()`", + "type": "method", + "name": "isSymbolicLink", + "meta": { + "added": [ + "v0.1.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Returns true if the fs.Stats object describes a symbolic link.

      \n

      This method is only valid when using fs.lstat().

      " + } + ], + "properties": [ + { + "textRaw": "`dev` {number|bigint}", + "type": "number|bigint", + "name": "dev", + "desc": "

      The numeric identifier of the device containing the file.

      " + }, + { + "textRaw": "`ino` {number|bigint}", + "type": "number|bigint", + "name": "ino", + "desc": "

      The file system specific \"Inode\" number for the file.

      " + }, + { + "textRaw": "`mode` {number|bigint}", + "type": "number|bigint", + "name": "mode", + "desc": "

      A bit-field describing the file type and mode.

      " + }, + { + "textRaw": "`nlink` {number|bigint}", + "type": "number|bigint", + "name": "nlink", + "desc": "

      The number of hard-links that exist for the file.

      " + }, + { + "textRaw": "`uid` {number|bigint}", + "type": "number|bigint", + "name": "uid", + "desc": "

      The numeric user identifier of the user that owns the file (POSIX).

      " + }, + { + "textRaw": "`gid` {number|bigint}", + "type": "number|bigint", + "name": "gid", + "desc": "

      The numeric group identifier of the group that owns the file (POSIX).

      " + }, + { + "textRaw": "`rdev` {number|bigint}", + "type": "number|bigint", + "name": "rdev", + "desc": "

      A numeric device identifier if the file represents a device.

      " + }, + { + "textRaw": "`size` {number|bigint}", + "type": "number|bigint", + "name": "size", + "desc": "

      The size of the file in bytes.

      " + }, + { + "textRaw": "`blksize` {number|bigint}", + "type": "number|bigint", + "name": "blksize", + "desc": "

      The file system block size for i/o operations.

      " + }, + { + "textRaw": "`blocks` {number|bigint}", + "type": "number|bigint", + "name": "blocks", + "desc": "

      The number of blocks allocated for this file.

      " + }, + { + "textRaw": "`atimeMs` {number|bigint}", + "type": "number|bigint", + "name": "atimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was accessed expressed in\nmilliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`mtimeMs` {number|bigint}", + "type": "number|bigint", + "name": "mtimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was modified expressed in\nmilliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`ctimeMs` {number|bigint}", + "type": "number|bigint", + "name": "ctimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time the file status was changed expressed\nin milliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`birthtimeMs` {number|bigint}", + "type": "number|bigint", + "name": "birthtimeMs", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the creation time of this file expressed in\nmilliseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`atimeNs` {bigint}", + "type": "bigint", + "name": "atimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was accessed expressed in\nnanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`mtimeNs` {bigint}", + "type": "bigint", + "name": "mtimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was modified expressed in\nnanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`ctimeNs` {bigint}", + "type": "bigint", + "name": "ctimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time the file status was changed expressed\nin nanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`birthtimeNs` {bigint}", + "type": "bigint", + "name": "birthtimeNs", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the creation time of this file expressed in\nnanoseconds since the POSIX Epoch.

      " + }, + { + "textRaw": "`atime` {Date}", + "type": "Date", + "name": "atime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was accessed.

      " + }, + { + "textRaw": "`mtime` {Date}", + "type": "Date", + "name": "mtime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time this file was modified.

      " + }, + { + "textRaw": "`ctime` {Date}", + "type": "Date", + "name": "ctime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the last time the file status was changed.

      " + }, + { + "textRaw": "`birthtime` {Date}", + "type": "Date", + "name": "birthtime", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "desc": "

      The timestamp indicating the creation time of this file.

      " + } + ], + "modules": [ + { + "textRaw": "Stat time values", + "name": "stat_time_values", + "desc": "

      The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are\nnumeric values that hold the corresponding times in milliseconds. Their\nprecision is platform specific. When bigint: true is passed into the\nmethod that generates the object, the properties will be bigints,\notherwise they will be numbers.

      \n

      The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are\nbigints that hold the corresponding times in nanoseconds. They are\nonly present when bigint: true is passed into the method that generates\nthe object. Their precision is platform specific.

      \n

      atime, mtime, ctime, and birthtime are\nDate object alternate representations of the various times. The\nDate and number values are not connected. Assigning a new number value, or\nmutating the Date value, will not be reflected in the corresponding alternate\nrepresentation.

      \n

      The times in the stat object have the following semantics:

      \n
        \n
      • atime \"Access Time\": Time when file data last accessed. Changed\nby the mknod(2), utimes(2), and read(2) system calls.
      • \n
      • mtime \"Modified Time\": Time when file data last modified.\nChanged by the mknod(2), utimes(2), and write(2) system calls.
      • \n
      • ctime \"Change Time\": Time when file status was last changed\n(inode data modification). Changed by the chmod(2), chown(2),\nlink(2), mknod(2), rename(2), unlink(2), utimes(2),\nread(2), and write(2) system calls.
      • \n
      • birthtime \"Birth Time\": Time of file creation. Set once when the\nfile is created. On filesystems where birthtime is not available,\nthis field may instead hold either the ctime or\n1970-01-01T00:00Z (ie, Unix epoch timestamp 0). This value may be greater\nthan atime or mtime in this case. On Darwin and other FreeBSD variants,\nalso set if the atime is explicitly set to an earlier value than the current\nbirthtime using the utimes(2) system call.
      • \n
      \n

      Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As\nof 0.12, ctime is not \"creation time\", and on Unix systems, it never was.

      ", + "type": "module", + "displayName": "Stat time values" + } + ] + }, + { + "textRaw": "Class: `fs.WriteStream`", + "type": "class", + "name": "fs.WriteStream", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "\n

      Instances of fs.WriteStream are created and returned using the\nfs.createWriteStream() function.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the WriteStream's underlying file descriptor has been closed.

      " + }, + { + "textRaw": "Event: `'open'`", + "type": "event", + "name": "open", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`fd` {integer} Integer file descriptor used by the `WriteStream`.", + "name": "fd", + "type": "integer", + "desc": "Integer file descriptor used by the `WriteStream`." + } + ], + "desc": "

      Emitted when the WriteStream's file is opened.

      " + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v9.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the fs.WriteStream is ready to be used.

      \n

      Fires immediately after 'open'.

      " + } + ], + "properties": [ + { + "textRaw": "`writeStream.bytesWritten`", + "name": "bytesWritten", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [] + }, + "desc": "

      The number of bytes written so far. Does not include data that is still queued\nfor writing.

      " + }, + { + "textRaw": "`writeStream.path`", + "name": "path", + "meta": { + "added": [ + "v0.1.93" + ], + "changes": [] + }, + "desc": "

      The path to the file the stream is writing to as specified in the first\nargument to fs.createWriteStream(). If path is passed as a string, then\nwriteStream.path will be a string. If path is passed as a Buffer, then\nwriteStream.path will be a Buffer.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`fs.access(path[, mode], callback)`", + "type": "method", + "name": "access", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6534", + "description": "The constants like `fs.R_OK`, etc which were present directly on `fs` were moved into `fs.constants` as a soft deprecation. Thus for Node.js `< v6.3.0` use `fs` to access those constants, or do something like `(fs.constants || fs).R_OK` to work with all versions." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", + "name": "mode", + "type": "integer", + "default": "`fs.constants.F_OK`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. Check File access constants for possible values\nof mode. It is possible to create a mask consisting of the bitwise OR of\ntwo or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

      \n

      The final argument, callback, is a callback function that is invoked with\na possible error argument. If any of the accessibility checks fail, the error\nargument will be an Error object. The following examples check if\npackage.json exists, and if it is readable or writable.

      \n
      const file = 'package.json';\n\n// Check if the file exists in the current directory.\nfs.access(file, fs.constants.F_OK, (err) => {\n  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);\n});\n\n// Check if the file is readable.\nfs.access(file, fs.constants.R_OK, (err) => {\n  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);\n});\n\n// Check if the file is writable.\nfs.access(file, fs.constants.W_OK, (err) => {\n  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);\n});\n\n// Check if the file exists in the current directory, and if it is writable.\nfs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {\n  if (err) {\n    console.error(\n      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);\n  } else {\n    console.log(`${file} exists, and it is writable`);\n  }\n});\n
      \n

      Do not use fs.access() to check for the accessibility of a file before calling\nfs.open(), fs.readFile() or fs.writeFile(). Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file is not accessible.

      \n

      write (NOT RECOMMENDED)

      \n
      fs.access('myfile', (err) => {\n  if (!err) {\n    console.error('myfile already exists');\n    return;\n  }\n\n  fs.open('myfile', 'wx', (err, fd) => {\n    if (err) throw err;\n    writeMyData(fd);\n  });\n});\n
      \n

      write (RECOMMENDED)

      \n
      fs.open('myfile', 'wx', (err, fd) => {\n  if (err) {\n    if (err.code === 'EEXIST') {\n      console.error('myfile already exists');\n      return;\n    }\n\n    throw err;\n  }\n\n  writeMyData(fd);\n});\n
      \n

      read (NOT RECOMMENDED)

      \n
      fs.access('myfile', (err) => {\n  if (err) {\n    if (err.code === 'ENOENT') {\n      console.error('myfile does not exist');\n      return;\n    }\n\n    throw err;\n  }\n\n  fs.open('myfile', 'r', (err, fd) => {\n    if (err) throw err;\n    readMyData(fd);\n  });\n});\n
      \n

      read (RECOMMENDED)

      \n
      fs.open('myfile', 'r', (err, fd) => {\n  if (err) {\n    if (err.code === 'ENOENT') {\n      console.error('myfile does not exist');\n      return;\n    }\n\n    throw err;\n  }\n\n  readMyData(fd);\n});\n
      \n

      The \"not recommended\" examples above check for accessibility and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.

      \n

      In general, check for the accessibility of a file only if the file will not be\nused directly, for example when its accessibility is a signal from another\nprocess.

      \n

      On Windows, access-control policies (ACLs) on a directory may limit access to\na file or directory. The fs.access() function, however, does not check the\nACL and therefore may report that a path is accessible even if the ACL restricts\nthe user from reading or writing to it.

      " + }, + { + "textRaw": "`fs.accessSync(path[, mode])`", + "type": "method", + "name": "accessSync", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", + "name": "mode", + "type": "integer", + "default": "`fs.constants.F_OK`" + } + ] + } + ], + "desc": "

      Synchronously tests a user's permissions for the file or directory specified\nby path. The mode argument is an optional integer that specifies the\naccessibility checks to be performed. Check File access constants for\npossible values of mode. It is possible to create a mask consisting of\nthe bitwise OR of two or more values\n(e.g. fs.constants.W_OK | fs.constants.R_OK).

      \n

      If any of the accessibility checks fail, an Error will be thrown. Otherwise,\nthe method will return undefined.

      \n
      try {\n  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);\n  console.log('can read/write');\n} catch (err) {\n  console.error('no access!');\n}\n
      " + }, + { + "textRaw": "`fs.appendFile(path, data[, options], callback)`", + "type": "method", + "name": "appendFile", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|number} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|number", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.", + "name": "flag", + "type": "string", + "default": "`'a'`", + "desc": "See [support of file system `flags`][]." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a Buffer.

      \n
      fs.appendFile('message.txt', 'data to append', (err) => {\n  if (err) throw err;\n  console.log('The \"data to append\" was appended to file!');\n});\n
      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.appendFile('message.txt', 'data to append', 'utf8', callback);\n
      \n

      The path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.

      \n
      fs.open('message.txt', 'a', (err, fd) => {\n  if (err) throw err;\n  fs.appendFile(fd, 'data to append', 'utf8', (err) => {\n    fs.close(fd, (err) => {\n      if (err) throw err;\n    });\n    if (err) throw err;\n  });\n});\n
      " + }, + { + "textRaw": "`fs.appendFileSync(path, data[, options])`", + "type": "method", + "name": "appendFileSync", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|number} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|number", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'a'`.", + "name": "flag", + "type": "string", + "default": "`'a'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Synchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a Buffer.

      \n
      try {\n  fs.appendFileSync('message.txt', 'data to append');\n  console.log('The \"data to append\" was appended to file!');\n} catch (err) {\n  /* Handle the error */\n}\n
      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.appendFileSync('message.txt', 'data to append', 'utf8');\n
      \n

      The path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.

      \n
      let fd;\n\ntry {\n  fd = fs.openSync('message.txt', 'a');\n  fs.appendFileSync(fd, 'data to append', 'utf8');\n} catch (err) {\n  /* Handle the error */\n} finally {\n  if (fd !== undefined)\n    fs.closeSync(fd);\n}\n
      " + }, + { + "textRaw": "`fs.chmod(path, mode, callback)`", + "type": "method", + "name": "chmod", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously changes the permissions of a file. No arguments other than a\npossible exception are given to the completion callback.

      \n

      See also: chmod(2).

      \n
      fs.chmod('my_file.txt', 0o775, (err) => {\n  if (err) throw err;\n  console.log('The permissions for file \"my_file.txt\" have been changed!');\n});\n
      ", + "modules": [ + { + "textRaw": "File modes", + "name": "file_modes", + "desc": "

      The mode argument used in both the fs.chmod() and fs.chmodSync()\nmethods is a numeric bitmask created using a logical OR of the following\nconstants:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      ConstantOctalDescription
      fs.constants.S_IRUSR0o400read by owner
      fs.constants.S_IWUSR0o200write by owner
      fs.constants.S_IXUSR0o100execute/search by owner
      fs.constants.S_IRGRP0o40read by group
      fs.constants.S_IWGRP0o20write by group
      fs.constants.S_IXGRP0o10execute/search by group
      fs.constants.S_IROTH0o4read by others
      fs.constants.S_IWOTH0o2write by others
      fs.constants.S_IXOTH0o1execute/search by others
      \n

      An easier method of constructing the mode is to use a sequence of three\noctal digits (e.g. 765). The left-most digit (7 in the example), specifies\nthe permissions for the file owner. The middle digit (6 in the example),\nspecifies permissions for the group. The right-most digit (5 in the example),\nspecifies the permissions for others.

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      NumberDescription
      7read, write, and execute
      6read and write
      5read and execute
      4read only
      3write and execute
      2write only
      1execute only
      0no permission
      \n

      For example, the octal value 0o765 means:

      \n
        \n
      • The owner may read, write and execute the file.
      • \n
      • The group may read and write the file.
      • \n
      • Others may read and execute the file.
      • \n
      \n

      When using raw numbers where file modes are expected, any value larger than\n0o777 may result in platform-specific behaviors that are not supported to work\nconsistently. Therefore constants like S_ISVTX, S_ISGID or S_ISUID are not\nexposed in fs.constants.

      \n

      Caveats: on Windows only the write permission can be changed, and the\ndistinction among the permissions of group, owner or others is not\nimplemented.

      ", + "type": "module", + "displayName": "File modes" + } + ] + }, + { + "textRaw": "`fs.chmodSync(path, mode)`", + "type": "method", + "name": "chmodSync", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.chmod().

      \n

      See also: chmod(2).

      " + }, + { + "textRaw": "`fs.chown(path, uid, gid, callback)`", + "type": "method", + "name": "chown", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously changes owner and group of a file. No arguments other than a\npossible exception are given to the completion callback.

      \n

      See also: chown(2).

      " + }, + { + "textRaw": "`fs.chownSync(path, uid, gid)`", + "type": "method", + "name": "chownSync", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronously changes owner and group of a file. Returns undefined.\nThis is the synchronous version of fs.chown().

      \n

      See also: chown(2).

      " + }, + { + "textRaw": "`fs.close(fd, callback)`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.

      \n

      Calling fs.close() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.

      " + }, + { + "textRaw": "`fs.closeSync(fd)`", + "type": "method", + "name": "closeSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous close(2). Returns undefined.

      \n

      Calling fs.closeSync() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.

      " + }, + { + "textRaw": "`fs.copyFile(src, dest[, flags], callback)`", + "type": "method", + "name": "copyFile", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": "v14.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27044", + "description": "Changed 'flags' argument to 'mode' and imposed stricter type validation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`src` {string|Buffer|URL} source filename to copy", + "name": "src", + "type": "string|Buffer|URL", + "desc": "source filename to copy" + }, + { + "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", + "name": "dest", + "type": "string|Buffer|URL", + "desc": "destination filename of the copy operation" + }, + { + "textRaw": "`flags` {number} modifiers for copy operation. **Default:** `0`.", + "name": "flags", + "type": "number", + "default": "`0`", + "desc": "modifiers for copy operation." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists. No arguments other than a possible exception are given to the\ncallback function. Node.js makes no guarantees about the atomicity of the copy\noperation. If an error occurs after the destination file has been opened for\nwriting, Node.js will attempt to remove the destination.

      \n

      flags is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      \n
        \n
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
      • \n
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.
      • \n
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support copy-on-write,\nthen the operation will fail.
      • \n
      \n
      const fs = require('fs');\n\n// destination.txt will be created or overwritten by default.\nfs.copyFile('source.txt', 'destination.txt', (err) => {\n  if (err) throw err;\n  console.log('source.txt was copied to destination.txt');\n});\n
      \n

      If the third argument is a number, then it specifies flags:

      \n
      const fs = require('fs');\nconst { COPYFILE_EXCL } = fs.constants;\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\nfs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback);\n
      " + }, + { + "textRaw": "`fs.copyFileSync(src, dest[, flags])`", + "type": "method", + "name": "copyFileSync", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": "v14.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27044", + "description": "Changed 'flags' argument to 'mode' and imposed stricter type validation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`src` {string|Buffer|URL} source filename to copy", + "name": "src", + "type": "string|Buffer|URL", + "desc": "source filename to copy" + }, + { + "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", + "name": "dest", + "type": "string|Buffer|URL", + "desc": "destination filename of the copy operation" + }, + { + "textRaw": "`flags` {number} modifiers for copy operation. **Default:** `0`.", + "name": "flags", + "type": "number", + "default": "`0`", + "desc": "modifiers for copy operation." + } + ] + } + ], + "desc": "

      Synchronously copies src to dest. By default, dest is overwritten if it\nalready exists. Returns undefined. Node.js makes no guarantees about the\natomicity of the copy operation. If an error occurs after the destination file\nhas been opened for writing, Node.js will attempt to remove the destination.

      \n

      flags is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

      \n
        \n
      • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
      • \n
      • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.
      • \n
      • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support copy-on-write,\nthen the operation will fail.
      • \n
      \n
      const fs = require('fs');\n\n// destination.txt will be created or overwritten by default.\nfs.copyFileSync('source.txt', 'destination.txt');\nconsole.log('source.txt was copied to destination.txt');\n
      \n

      If the third argument is a number, then it specifies flags:

      \n
      const fs = require('fs');\nconst { COPYFILE_EXCL } = fs.constants;\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\nfs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL);\n
      " + }, + { + "textRaw": "`fs.createReadStream(path[, options])`", + "type": "method", + "name": "createReadStream", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29212", + "description": "Enable `emitClose` option." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19898", + "description": "Impose new restrictions on `start` and `end`, throwing more appropriate errors in cases when we cannot reasonably handle the input values." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v2.3.0", + "pr-url": "https://github.com/nodejs/node/pull/1845", + "description": "The passed `options` object can be a string now." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/29083", + "description": "The `fs` options allow overriding the used `fs` implementation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.ReadStream} See [Readable Stream][].", + "name": "return", + "type": "fs.ReadStream", + "desc": "See [Readable Stream][]." + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`flags` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flags", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`encoding` {string} **Default:** `null`", + "name": "encoding", + "type": "string", + "default": "`null`" + }, + { + "textRaw": "`fd` {integer} **Default:** `null`", + "name": "fd", + "type": "integer", + "default": "`null`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`autoClose` {boolean} **Default:** `true`", + "name": "autoClose", + "type": "boolean", + "default": "`true`" + }, + { + "textRaw": "`emitClose` {boolean} **Default:** `false`", + "name": "emitClose", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`start` {integer}", + "name": "start", + "type": "integer" + }, + { + "textRaw": "`end` {integer} **Default:** `Infinity`", + "name": "end", + "type": "integer", + "default": "`Infinity`" + }, + { + "textRaw": "`highWaterMark` {integer} **Default:** `64 * 1024`", + "name": "highWaterMark", + "type": "integer", + "default": "`64 * 1024`" + }, + { + "textRaw": "`fs` {Object|null} **Default:** `null`", + "name": "fs", + "type": "Object|null", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      Unlike the 16 kb default highWaterMark for a readable stream, the stream\nreturned by this method has a default highWaterMark of 64 kb.

      \n

      options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart counting at 0, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is\nomitted or undefined, fs.createReadStream() reads sequentially from the\ncurrent file position. The encoding can be any one of those accepted by\nBuffer.

      \n

      If fd is specified, ReadStream will ignore the path argument and will use\nthe specified file descriptor. This means that no 'open' event will be\nemitted. fd should be blocking; non-blocking fds should be passed to\nnet.Socket.

      \n

      If fd points to a character device that only supports blocking reads\n(such as keyboard or sound card), read operations do not finish until data is\navailable. This can prevent the process from exiting and the stream from\nclosing naturally.

      \n

      By default, the stream will not emit a 'close' event after it has been\ndestroyed. This is the opposite of the default for other Readable streams.\nSet the emitClose option to true to change this behavior.

      \n

      By providing the fs option, it is possible to override the corresponding fs\nimplementations for open, read, and close. When providing the fs option,\noverrides for open, read, and close are required.

      \n
      const fs = require('fs');\n// Create a stream from some character device.\nconst stream = fs.createReadStream('/dev/input/event0');\nsetTimeout(() => {\n  stream.close(); // This may not close the stream.\n  // Artificially marking end-of-stream, as if the underlying resource had\n  // indicated end-of-file by itself, allows the stream to close.\n  // This does not cancel pending read operations, and if there is such an\n  // operation, the process may still not be able to exit successfully\n  // until it finishes.\n  stream.push(null);\n  stream.read(0);\n}, 100);\n
      \n

      If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is the application's responsibility to close it and make\nsure there's no file descriptor leak. If autoClose is set to true (default\nbehavior), on 'error' or 'end' the file descriptor will be closed\nautomatically.

      \n

      mode sets the file mode (permission and sticky bits), but only if the\nfile was created.

      \n

      An example to read the last 10 bytes of a file which is 100 bytes long:

      \n
      fs.createReadStream('sample.txt', { start: 90, end: 99 });\n
      \n

      If options is a string, then it specifies the encoding.

      " + }, + { + "textRaw": "`fs.createWriteStream(path[, options])`", + "type": "method", + "name": "createWriteStream", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29212", + "description": "Enable `emitClose` option." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + }, + { + "version": "v5.5.0", + "pr-url": "https://github.com/nodejs/node/pull/3679", + "description": "The `autoClose` option is supported now." + }, + { + "version": "v2.3.0", + "pr-url": "https://github.com/nodejs/node/pull/1845", + "description": "The passed `options` object can be a string now." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/v12.17.0", + "description": "The `fs` options allow overriding the used `fs` implementation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.WriteStream} See [Writable Stream][].", + "name": "return", + "type": "fs.WriteStream", + "desc": "See [Writable Stream][]." + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`flags` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flags", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`fd` {integer} **Default:** `null`", + "name": "fd", + "type": "integer", + "default": "`null`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`autoClose` {boolean} **Default:** `true`", + "name": "autoClose", + "type": "boolean", + "default": "`true`" + }, + { + "textRaw": "`emitClose` {boolean} **Default:** `false`", + "name": "emitClose", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`start` {integer}", + "name": "start", + "type": "integer" + }, + { + "textRaw": "`fs` {Object|null} **Default:** `null`", + "name": "fs", + "type": "Object|null", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      options may also include a start option to allow writing data at\nsome position past the beginning of the file, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w. The encoding can be any one of those accepted by\nBuffer.

      \n

      If autoClose is set to true (default behavior) on 'error' or 'finish'\nthe file descriptor will be closed automatically. If autoClose is false,\nthen the file descriptor won't be closed, even if there's an error.\nIt is the application's responsibility to close it and make sure there's no\nfile descriptor leak.

      \n

      By default, the stream will not emit a 'close' event after it has been\ndestroyed. This is the opposite of the default for other Writable streams.\nSet the emitClose option to true to change this behavior.

      \n

      By providing the fs option it is possible to override the corresponding fs\nimplementations for open, write, writev and close. Overriding write()\nwithout writev() can reduce performance as some optimizations (_writev())\nwill be disabled. When providing the fs option, overrides for open,\nclose, and at least one of write and writev are required.

      \n

      Like ReadStream, if fd is specified, WriteStream will ignore the\npath argument and will use the specified file descriptor. This means that no\n'open' event will be emitted. fd should be blocking; non-blocking fds\nshould be passed to net.Socket.

      \n

      If options is a string, then it specifies the encoding.

      " + }, + { + "textRaw": "`fs.exists(path, callback)`", + "type": "method", + "name": "exists", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ], + "deprecated": [ + "v1.0.0" + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`exists` {boolean}", + "name": "exists", + "type": "boolean" + } + ] + } + ] + } + ], + "desc": "

      Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false:

      \n
      fs.exists('/etc/passwd', (exists) => {\n  console.log(exists ? 'it\\'s there' : 'no passwd!');\n});\n
      \n

      The parameters for this callback are not consistent with other Node.js\ncallbacks. Normally, the first parameter to a Node.js callback is an err\nparameter, optionally followed by other parameters. The fs.exists() callback\nhas only one boolean parameter. This is one reason fs.access() is recommended\ninstead of fs.exists().

      \n

      Using fs.exists() to check for the existence of a file before calling\nfs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file does not exist.

      \n

      write (NOT RECOMMENDED)

      \n
      fs.exists('myfile', (exists) => {\n  if (exists) {\n    console.error('myfile already exists');\n  } else {\n    fs.open('myfile', 'wx', (err, fd) => {\n      if (err) throw err;\n      writeMyData(fd);\n    });\n  }\n});\n
      \n

      write (RECOMMENDED)

      \n
      fs.open('myfile', 'wx', (err, fd) => {\n  if (err) {\n    if (err.code === 'EEXIST') {\n      console.error('myfile already exists');\n      return;\n    }\n\n    throw err;\n  }\n\n  writeMyData(fd);\n});\n
      \n

      read (NOT RECOMMENDED)

      \n
      fs.exists('myfile', (exists) => {\n  if (exists) {\n    fs.open('myfile', 'r', (err, fd) => {\n      if (err) throw err;\n      readMyData(fd);\n    });\n  } else {\n    console.error('myfile does not exist');\n  }\n});\n
      \n

      read (RECOMMENDED)

      \n
      fs.open('myfile', 'r', (err, fd) => {\n  if (err) {\n    if (err.code === 'ENOENT') {\n      console.error('myfile does not exist');\n      return;\n    }\n\n    throw err;\n  }\n\n  readMyData(fd);\n});\n
      \n

      The \"not recommended\" examples above check for existence and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.

      \n

      In general, check for the existence of a file only if the file won’t be\nused directly, for example when its existence is a signal from another\nprocess.

      " + }, + { + "textRaw": "`fs.existsSync(path)`", + "type": "method", + "name": "existsSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Returns true if the path exists, false otherwise.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.exists().

      \n

      fs.exists() is deprecated, but fs.existsSync() is not. The callback\nparameter to fs.exists() accepts parameters that are inconsistent with other\nNode.js callbacks. fs.existsSync() does not use a callback.

      \n
      if (fs.existsSync('/etc/passwd')) {\n  console.log('The path exists.');\n}\n
      " + }, + { + "textRaw": "`fs.fchmod(fd, mode, callback)`", + "type": "method", + "name": "fchmod", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.

      " + }, + { + "textRaw": "`fs.fchmodSync(fd, mode)`", + "type": "method", + "name": "fchmodSync", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`mode` {string|integer}", + "name": "mode", + "type": "string|integer" + } + ] + } + ], + "desc": "

      Synchronous fchmod(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.fchown(fd, uid, gid, callback)`", + "type": "method", + "name": "fchown", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.

      " + }, + { + "textRaw": "`fs.fchownSync(fd, uid, gid)`", + "type": "method", + "name": "fchownSync", + "meta": { + "added": [ + "v0.4.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous fchown(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.fdatasync(fd, callback)`", + "type": "method", + "name": "fdatasync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fdatasync(2). No arguments other than a possible exception are\ngiven to the completion callback.

      " + }, + { + "textRaw": "`fs.fdatasyncSync(fd)`", + "type": "method", + "name": "fdatasyncSync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous fdatasync(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.fstat(fd[, options], callback)`", + "type": "method", + "name": "fstat", + "meta": { + "added": [ + "v0.1.95" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stats` {fs.Stats}", + "name": "stats", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is an fs.Stats object. fstat() is identical to stat(),\nexcept that the file to be stat-ed is specified by the file descriptor fd.

      " + }, + { + "textRaw": "`fs.fstatSync(fd[, options])`", + "type": "method", + "name": "fstatSync", + "meta": { + "added": [ + "v0.1.95" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Stats}", + "name": "return", + "type": "fs.Stats" + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous fstat(2).

      " + }, + { + "textRaw": "`fs.fsync(fd, callback)`", + "type": "method", + "name": "fsync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.

      " + }, + { + "textRaw": "`fs.fsyncSync(fd)`", + "type": "method", + "name": "fsyncSync", + "meta": { + "added": [ + "v0.1.96" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous fsync(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.ftruncate(fd[, len], callback)`", + "type": "method", + "name": "ftruncate", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.

      \n

      If the file referred to by the file descriptor was larger than len bytes, only\nthe first len bytes will be retained in the file.

      \n

      For example, the following program retains only the first four bytes of the\nfile:

      \n
      console.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// Truncate the file to first four bytes\nfs.ftruncate(fd, 4, (err) => {\n  assert.ifError(err);\n  console.log(fs.readFileSync('temp.txt', 'utf8'));\n});\n// Prints: Node\n
      \n

      If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):

      \n
      console.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// Truncate the file to 10 bytes, whereas the actual size is 7 bytes\nfs.ftruncate(fd, 10, (err) => {\n  assert.ifError(err);\n  console.log(fs.readFileSync('temp.txt'));\n});\n// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>\n// ('Node.js\\0\\0\\0' in UTF8)\n
      \n

      The last three bytes are null bytes ('\\0'), to compensate the over-truncation.

      " + }, + { + "textRaw": "`fs.ftruncateSync(fd[, len])`", + "type": "method", + "name": "ftruncateSync", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.ftruncate().

      " + }, + { + "textRaw": "`fs.futimes(fd, atime, mtime, callback)`", + "type": "method", + "name": "futimes", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by the supplied file\ndescriptor. See fs.utimes().

      \n

      This function does not work on AIX versions before 7.1, it will return the\nerror UV_ENOSYS.

      " + }, + { + "textRaw": "`fs.futimesSync(fd, atime, mtime)`", + "type": "method", + "name": "futimesSync", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Synchronous version of fs.futimes(). Returns undefined.

      " + }, + { + "textRaw": "`fs.lchmod(path, mode, callback)`", + "type": "method", + "name": "lchmod", + "meta": { + "deprecated": [ + "v0.4.7" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.

      \n

      Only available on macOS.

      " + }, + { + "textRaw": "`fs.lchmodSync(path, mode)`", + "type": "method", + "name": "lchmodSync", + "meta": { + "deprecated": [ + "v0.4.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`mode` {integer}", + "name": "mode", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous lchmod(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.lchown(path, uid, gid, callback)`", + "type": "method", + "name": "lchown", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "This API is no longer deprecated." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.

      " + }, + { + "textRaw": "`fs.lchownSync(path, uid, gid)`", + "type": "method", + "name": "lchownSync", + "meta": { + "changes": [ + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/21498", + "description": "This API is no longer deprecated." + }, + { + "version": "v0.4.7", + "description": "Documentation-only deprecation." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`uid` {integer}", + "name": "uid", + "type": "integer" + }, + { + "textRaw": "`gid` {integer}", + "name": "gid", + "type": "integer" + } + ] + } + ], + "desc": "

      Synchronous lchown(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.lutimes(path, atime, mtime, callback)`", + "type": "method", + "name": "lutimes", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Changes the access and modification times of a file in the same way as\nfs.utimes(), with the difference that if the path refers to a symbolic\nlink, then the link is not dereferenced: instead, the timestamps of the\nsymbolic link itself are changed.

      \n

      No arguments other than a possible exception are given to the completion\ncallback.

      " + }, + { + "textRaw": "`fs.lutimesSync(path, atime, mtime)`", + "type": "method", + "name": "lutimesSync", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Change the file system timestamps of the symbolic link referenced by path.\nReturns undefined, or throws an exception when parameters are incorrect or\nthe operation fails. This is the synchronous version of fs.lutimes().

      " + }, + { + "textRaw": "`fs.link(existingPath, newPath, callback)`", + "type": "method", + "name": "link", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `existingPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`existingPath` {string|Buffer|URL}", + "name": "existingPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.

      " + }, + { + "textRaw": "`fs.linkSync(existingPath, newPath)`", + "type": "method", + "name": "linkSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `existingPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`existingPath` {string|Buffer|URL}", + "name": "existingPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Synchronous link(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.lstat(path[, options], callback)`", + "type": "method", + "name": "lstat", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stats` {fs.Stats}", + "name": "stats", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(),\nexcept that if path is a symbolic link, then the link itself is stat-ed,\nnot the file that it refers to.

      " + }, + { + "textRaw": "`fs.lstatSync(path[, options])`", + "type": "method", + "name": "lstatSync", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Stats}", + "name": "return", + "type": "fs.Stats" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous lstat(2).

      " + }, + { + "textRaw": "`fs.mkdir(path[, options], callback)`", + "type": "method", + "name": "mkdir", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31530", + "description": "In `recursive` mode, the callback now receives the first created path as an argument." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/21875", + "description": "The second argument can now be an `options` object with `recursive` and `mode` properties." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object|integer}", + "name": "options", + "type": "Object|integer", + "options": [ + { + "textRaw": "`recursive` {boolean} **Default:** `false`", + "name": "recursive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", + "name": "mode", + "type": "string|integer", + "default": "`0o777`", + "desc": "Not supported on Windows." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously creates a directory.

      \n

      The callback is given a possible exception and, if recursive is true, the\nfirst directory path created, (err, [path]).

      \n

      The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfs.mkdir() when path is a directory that exists results in an error only\nwhen recursive is false.

      \n
      // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.\nfs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {\n  if (err) throw err;\n});\n
      \n

      On Windows, using fs.mkdir() on the root directory even with recursion will\nresult in an error:

      \n
      fs.mkdir('/', { recursive: true }, (err) => {\n  // => [Error: EPERM: operation not permitted, mkdir 'C:\\']\n});\n
      \n

      See also: mkdir(2).

      " + }, + { + "textRaw": "`fs.mkdirSync(path[, options])`", + "type": "method", + "name": "mkdirSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31530", + "description": "In `recursive` mode, the first created path is returned now." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/21875", + "description": "The second argument can now be an `options` object with `recursive` and `mode` properties." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|undefined}", + "name": "return", + "type": "string|undefined" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object|integer}", + "name": "options", + "type": "Object|integer", + "options": [ + { + "textRaw": "`recursive` {boolean} **Default:** `false`", + "name": "recursive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", + "name": "mode", + "type": "string|integer", + "default": "`0o777`", + "desc": "Not supported on Windows." + } + ] + } + ] + } + ], + "desc": "

      Synchronously creates a directory. Returns undefined, or if recursive is\ntrue, the first directory path created.\nThis is the synchronous version of fs.mkdir().

      \n

      See also: mkdir(2).

      " + }, + { + "textRaw": "`fs.mkdtemp(prefix[, options], callback)`", + "type": "method", + "name": "mkdtemp", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v6.2.1", + "pr-url": "https://github.com/nodejs/node/pull/6828", + "description": "The `callback` parameter is optional now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`prefix` {string}", + "name": "prefix", + "type": "string" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`directory` {string}", + "name": "directory", + "type": "string" + } + ] + } + ] + } + ], + "desc": "

      Creates a unique temporary directory.

      \n

      Generates six random characters to be appended behind a required\nprefix to create a unique temporary directory. Due to platform\ninconsistencies, avoid trailing X characters in prefix. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing X characters in prefix with random characters.

      \n

      The created directory path is passed as a string to the callback's second\nparameter.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

      \n
      fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {\n  if (err) throw err;\n  console.log(directory);\n  // Prints: /tmp/foo-itXde2 or C:\\Users\\...\\AppData\\Local\\Temp\\foo-itXde2\n});\n
      \n

      The fs.mkdtemp() method will append the six randomly selected characters\ndirectly to the prefix string. For instance, given a directory /tmp, if the\nintention is to create a temporary directory within /tmp, the prefix\nmust end with a trailing platform-specific path separator\n(require('path').sep).

      \n
      // The parent directory for the new temporary directory\nconst tmpDir = os.tmpdir();\n\n// This method is *INCORRECT*:\nfs.mkdtemp(tmpDir, (err, directory) => {\n  if (err) throw err;\n  console.log(directory);\n  // Will print something similar to `/tmpabc123`.\n  // A new temporary directory is created at the file system root\n  // rather than *within* the /tmp directory.\n});\n\n// This method is *CORRECT*:\nconst { sep } = require('path');\nfs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {\n  if (err) throw err;\n  console.log(directory);\n  // Will print something similar to `/tmp/abc123`.\n  // A new temporary directory is created within\n  // the /tmp directory.\n});\n
      " + }, + { + "textRaw": "`fs.mkdtempSync(prefix[, options])`", + "type": "method", + "name": "mkdtempSync", + "meta": { + "added": [ + "v5.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`prefix` {string}", + "name": "prefix", + "type": "string" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Returns the created directory path.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.mkdtemp().

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

      " + }, + { + "textRaw": "`fs.open(path[, flags[, mode]], callback)`", + "type": "method", + "name": "open", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v11.1.0", + "pr-url": "https://github.com/nodejs/node/pull/23767", + "description": "The `flags` argument is now optional and defaults to `'r'`." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18801", + "description": "The `as` and `as+` modes are supported now." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`flags` {string|number} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flags", + "type": "string|number", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + }, + { + "textRaw": "`mode` {string|integer} **Default:** `0o666` (readable and writable)", + "name": "mode", + "type": "string|integer", + "default": "`0o666` (readable and writable)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous file open. See open(2).

      \n

      mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. On Windows, only the write permission can be manipulated; see\nfs.chmod().

      \n

      The callback gets two arguments (err, fd).

      \n

      Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.

      \n

      Functions based on fs.open() exhibit this behavior as well:\nfs.writeFile(), fs.readFile(), etc.

      " + }, + { + "textRaw": "`fs.opendir(path[, options], callback)`", + "type": "method", + "name": "opendir", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30114", + "description": "The `bufferSize` option was introduced." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`", + "name": "bufferSize", + "type": "number", + "default": "`32`", + "desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`dir` {fs.Dir}", + "name": "dir", + "type": "fs.Dir" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously open a directory. See opendir(3).

      \n

      Creates an fs.Dir, which contains all further functions for reading from\nand cleaning up the directory.

      \n

      The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

      " + }, + { + "textRaw": "`fs.opendirSync(path[, options])`", + "type": "method", + "name": "opendirSync", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30114", + "description": "The `bufferSize` option was introduced." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Dir}", + "name": "return", + "type": "fs.Dir" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`", + "name": "bufferSize", + "type": "number", + "default": "`32`", + "desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage." + } + ] + } + ] + } + ], + "desc": "

      Synchronously open a directory. See opendir(3).

      \n

      Creates an fs.Dir, which contains all further functions for reading from\nand cleaning up the directory.

      \n

      The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

      " + }, + { + "textRaw": "`fs.openSync(path[, flags, mode])`", + "type": "method", + "name": "openSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v11.1.0", + "pr-url": "https://github.com/nodejs/node/pull/23767", + "description": "The `flags` argument is now optional and defaults to `'r'`." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/18801", + "description": "The `as` and `as+` modes are supported now." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`flags` {string|number} **Default:** `'r'`. See [support of file system `flags`][].", + "name": "flags", + "type": "string|number", + "default": "`'r'`. See [support of file system `flags`][]" + }, + { + "textRaw": "`mode` {string|integer} **Default:** `0o666`", + "name": "mode", + "type": "string|integer", + "default": "`0o666`" + } + ] + } + ], + "desc": "

      Returns an integer representing the file descriptor.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.open().

      " + }, + { + "textRaw": "`fs.read(fd, buffer, offset, length, position, callback)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray`, or a `DataView`." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `buffer` parameter can now be a `Uint8Array`." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4518", + "description": "The `length` parameter can now be `0`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesRead` {integer}", + "name": "bytesRead", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer}", + "name": "buffer", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Read data from the file specified by fd.

      \n

      buffer is the buffer that the data (read from the fd) will be written to.

      \n

      offset is the offset in the buffer to start writing at.

      \n

      length is an integer specifying the number of bytes to read.

      \n

      position is an argument specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position,\nand the file position will be updated.\nIf position is an integer, the file position will remain unchanged.

      \n

      The callback is given the three arguments, (err, bytesRead, buffer).

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with bytesRead and buffer properties.

      " + }, + { + "textRaw": "`fs.read(fd, [options,] callback)`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31402", + "description": "Options object can be passed in to make Buffer, offset, length and position optional" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)`", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "default": "`Buffer.alloc(16384)`" + }, + { + "textRaw": "`offset` {integer} **Default:** `0`", + "name": "offset", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`length` {integer} **Default:** `buffer.length`", + "name": "length", + "type": "integer", + "default": "`buffer.length`" + }, + { + "textRaw": "`position` {integer} **Default:** `null`", + "name": "position", + "type": "integer", + "default": "`null`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesRead` {integer}", + "name": "bytesRead", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer}", + "name": "buffer", + "type": "Buffer" + } + ] + } + ] + } + ], + "desc": "

      Similar to the above fs.read function, this version takes an optional options object.\nIf no options object is specified, it will default with the above values.

      " + }, + { + "textRaw": "`fs.readdir(path[, options], callback)`", + "type": "method", + "name": "readdir", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22020", + "description": "New option `withFileTypes` was added." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5616", + "description": "The `options` parameter was added." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`withFileTypes` {boolean} **Default:** `false`", + "name": "withFileTypes", + "type": "boolean", + "default": "`false`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`files` {string[]|Buffer[]|fs.Dirent[]}", + "name": "files", + "type": "string[]|Buffer[]|fs.Dirent[]" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames passed to the callback. If the encoding is set to 'buffer',\nthe filenames returned will be passed as Buffer objects.

      \n

      If options.withFileTypes is set to true, the files array will contain\nfs.Dirent objects.

      " + }, + { + "textRaw": "`fs.readdirSync(path[, options])`", + "type": "method", + "name": "readdirSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22020", + "description": "New option `withFileTypes` was added." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]|Buffer[]|fs.Dirent[]}", + "name": "return", + "type": "string[]|Buffer[]|fs.Dirent[]" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`withFileTypes` {boolean} **Default:** `false`", + "name": "withFileTypes", + "type": "boolean", + "default": "`false`" + } + ] + } + ] + } + ], + "desc": "

      Synchronous readdir(3).

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames returned. If the encoding is set to 'buffer',\nthe filenames returned will be passed as Buffer objects.

      \n

      If options.withFileTypes is set to true, the result will contain\nfs.Dirent objects.

      " + }, + { + "textRaw": "`fs.readFile(path[, options], callback)`", + "type": "method", + "name": "readFile", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v5.1.0", + "pr-url": "https://github.com/nodejs/node/pull/3740", + "description": "The `callback` will always be called with `null` as the `error` parameter in case of success." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `path` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|integer} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flag", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously reads the entire contents of a file.

      \n
      fs.readFile('/etc/passwd', (err, data) => {\n  if (err) throw err;\n  console.log(data);\n});\n
      \n

      The callback is passed two arguments (err, data), where data is the\ncontents of the file.

      \n

      If no encoding is specified, then the raw buffer is returned.

      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.readFile('/etc/passwd', 'utf8', callback);\n
      \n

      When the path is a directory, the behavior of fs.readFile() and\nfs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an\nerror will be returned. On FreeBSD, a representation of the directory's contents\nwill be returned.

      \n
      // macOS, Linux, and Windows\nfs.readFile('<directory>', (err, data) => {\n  // => [Error: EISDIR: illegal operation on a directory, read <directory>]\n});\n\n//  FreeBSD\nfs.readFile('<directory>', (err, data) => {\n  // => null, <data>\n});\n
      \n

      The fs.readFile() function buffers the entire file. To minimize memory costs,\nwhen possible prefer streaming via fs.createReadStream().

      ", + "modules": [ + { + "textRaw": "File descriptors", + "name": "file_descriptors", + "desc": "
        \n
      1. Any specified file descriptor has to support reading.
      2. \n
      3. If a file descriptor is specified as the path, it will not be closed\nautomatically.
      4. \n
      5. The reading will begin at the current position. For example, if the file\nalready had 'Hello World' and six bytes are read with the file descriptor,\nthe call to fs.readFile() with the same file descriptor, would give\n'World', rather than 'Hello World'.
      6. \n
      ", + "type": "module", + "displayName": "File descriptors" + } + ] + }, + { + "textRaw": "`fs.readFileSync(path[, options])`", + "type": "method", + "name": "readFileSync", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `path` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL|integer} filename or file descriptor", + "name": "path", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `null`", + "name": "encoding", + "type": "string|null", + "default": "`null`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'r'`.", + "name": "flag", + "type": "string", + "default": "`'r'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Returns the contents of the path.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readFile().

      \n

      If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.

      \n

      Similar to fs.readFile(), when the path is a directory, the behavior of\nfs.readFileSync() is platform-specific.

      \n
      // macOS, Linux, and Windows\nfs.readFileSync('<directory>');\n// => [Error: EISDIR: illegal operation on a directory, read <directory>]\n\n//  FreeBSD\nfs.readFileSync('<directory>'); // => <data>\n
      " + }, + { + "textRaw": "`fs.readlink(path[, options], callback)`", + "type": "method", + "name": "readlink", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`linkString` {string|Buffer}", + "name": "linkString", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous readlink(2). The callback gets two arguments (err, linkString).

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path passed to the callback. If the encoding is set to 'buffer',\nthe link path returned will be passed as a Buffer object.

      " + }, + { + "textRaw": "`fs.readlinkSync(path[, options])`", + "type": "method", + "name": "readlinkSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Synchronous readlink(2). Returns the symbolic link's string value.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer',\nthe link path returned will be passed as a Buffer object.

      " + }, + { + "textRaw": "`fs.readSync(fd, buffer, offset, length, position)`", + "type": "method", + "name": "readSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4518", + "description": "The `length` parameter can now be `0`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      Returns the number of bytesRead.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().

      " + }, + { + "textRaw": "`fs.readSync(fd, buffer, [options])`", + "type": "method", + "name": "readSync", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32460", + "description": "Options object can be passed in to make offset, length and position optional" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`offset` {integer} **Default:** `0`", + "name": "offset", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`length` {integer} **Default:** `buffer.length`", + "name": "length", + "type": "integer", + "default": "`buffer.length`" + }, + { + "textRaw": "`position` {integer} **Default:** `null`", + "name": "position", + "type": "integer", + "default": "`null`" + } + ] + } + ] + } + ], + "desc": "

      Returns the number of bytesRead.

      \n

      Similar to the above fs.readSync function, this version takes an optional options object.\nIf no options object is specified, it will default with the above values.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().

      " + }, + { + "textRaw": "`fs.readv(fd, buffers[, position], callback)`", + "type": "method", + "name": "readv", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesRead` {integer}", + "name": "bytesRead", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + } + ] + } + ] + } + ], + "desc": "

      Read from a file specified by fd and write to an array of ArrayBufferViews\nusing readv().

      \n

      position is the offset from the beginning of the file from where data\nshould be read. If typeof position !== 'number', the data will be read\nfrom the current position.

      \n

      The callback will be given three arguments: err, bytesRead, and\nbuffers. bytesRead is how many bytes were read from the file.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with bytesRead and buffers properties.

      " + }, + { + "textRaw": "`fs.readvSync(fd, buffers[, position])`", + "type": "method", + "name": "readvSync", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes read.", + "name": "return", + "type": "number", + "desc": "The number of bytes read." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readv().

      " + }, + { + "textRaw": "`fs.realpath(path[, options], callback)`", + "type": "method", + "name": "realpath", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13028", + "description": "Pipe/Socket resolve support was added." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7899", + "description": "Calling `realpath` now works again for various edge cases on Windows." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3594", + "description": "The `cache` parameter was removed." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`resolvedPath` {string|Buffer}", + "name": "resolvedPath", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously computes the canonical pathname by resolving ., .. and\nsymbolic links.

      \n

      A canonical pathname is not necessarily unique. Hard links and bind mounts can\nexpose a file system entity through many pathnames.

      \n

      This function behaves like realpath(3), with some exceptions:

      \n
        \n
      1. \n

        No case conversion is performed on case-insensitive file systems.

        \n
      2. \n
      3. \n

        The maximum number of symbolic links is platform-independent and generally\n(much) higher than what the native realpath(3) implementation supports.

        \n
      4. \n
      \n

      The callback gets two arguments (err, resolvedPath). May use process.cwd\nto resolve relative paths.

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a Buffer object.

      \n

      If path resolves to a socket or a pipe, the function will return a system\ndependent name for that object.

      " + }, + { + "textRaw": "`fs.realpath.native(path[, options], callback)`", + "type": "method", + "name": "native", + "meta": { + "added": [ + "v9.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`resolvedPath` {string|Buffer}", + "name": "resolvedPath", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous realpath(3).

      \n

      The callback gets two arguments (err, resolvedPath).

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a Buffer object.

      \n

      On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.

      " + }, + { + "textRaw": "`fs.realpathSync(path[, options])`", + "type": "method", + "name": "realpathSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13028", + "description": "Pipe/Socket resolve support was added." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v6.4.0", + "pr-url": "https://github.com/nodejs/node/pull/7899", + "description": "Calling `realpathSync` now works again for various edge cases on Windows." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3594", + "description": "The `cache` parameter was removed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Returns the resolved pathname.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.realpath().

      " + }, + { + "textRaw": "`fs.realpathSync.native(path[, options])`", + "type": "method", + "name": "native", + "meta": { + "added": [ + "v9.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer}", + "name": "return", + "type": "string|Buffer" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + } + ] + } + ] + } + ], + "desc": "

      Synchronous realpath(3).

      \n

      Only paths that can be converted to UTF8 strings are supported.

      \n

      The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path returned. If the encoding is set to 'buffer',\nthe path returned will be passed as a Buffer object.

      \n

      On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.

      " + }, + { + "textRaw": "`fs.rename(oldPath, newPath, callback)`", + "type": "method", + "name": "rename", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `oldPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`oldPath` {string|Buffer|URL}", + "name": "oldPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously rename file at oldPath to the pathname provided\nas newPath. In the case that newPath already exists, it will\nbe overwritten. If there is a directory at newPath, an error will\nbe raised instead. No arguments other than a possible exception are\ngiven to the completion callback.

      \n

      See also: rename(2).

      \n
      fs.rename('oldFile.txt', 'newFile.txt', (err) => {\n  if (err) throw err;\n  console.log('Rename complete!');\n});\n
      " + }, + { + "textRaw": "`fs.renameSync(oldPath, newPath)`", + "type": "method", + "name": "renameSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `oldPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`oldPath` {string|Buffer|URL}", + "name": "oldPath", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`newPath` {string|Buffer|URL}", + "name": "newPath", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Synchronous rename(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.rmdir(path[, options], callback)`", + "type": "method", + "name": "rmdir", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30644", + "description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried." + }, + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29168", + "description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameters can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "stability": 1, + "stabilityText": "Recursive removal is experimental.", + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", + "name": "maxRetries", + "type": "integer", + "default": "`0`", + "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." + }, + { + "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure. **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure." + }, + { + "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", + "name": "retryDelay", + "type": "integer", + "default": "`100`", + "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.

      \n

      Using fs.rmdir() on a file (not a directory) results in an ENOENT error on\nWindows and an ENOTDIR error on POSIX.

      " + }, + { + "textRaw": "`fs.rmdirSync(path[, options])`", + "type": "method", + "name": "rmdirSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30644", + "description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried." + }, + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/29168", + "description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameters can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "stability": 1, + "stabilityText": "Recursive removal is experimental.", + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", + "name": "maxRetries", + "type": "integer", + "default": "`0`", + "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` ms longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." + }, + { + "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure. **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, perform a recursive directory removal. In recursive mode, errors are not reported if `path` does not exist, and operations are retried on failure." + }, + { + "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", + "name": "retryDelay", + "type": "integer", + "default": "`100`", + "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous rmdir(2). Returns undefined.

      \n

      Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error\non Windows and an ENOTDIR error on POSIX.

      " + }, + { + "textRaw": "`fs.stat(path[, options], callback)`", + "type": "method", + "name": "stat", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stats` {fs.Stats}", + "name": "stats", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is an fs.Stats object.

      \n

      In case of an error, the err.code will be one of Common System Errors.

      \n

      Using fs.stat() to check for the existence of a file before calling\nfs.open(), fs.readFile() or fs.writeFile() is not recommended.\nInstead, user code should open/read/write the file directly and handle the\nerror raised if the file is not available.

      \n

      To check if a file exists without manipulating it afterwards, fs.access()\nis recommended.

      \n

      For example, given the following directory structure:

      \n
      - txtDir\n-- file.txt\n- app.js\n
      \n

      The next program will check for the stats of the given paths:

      \n
      const fs = require('fs');\n\nconst pathsToCheck = ['./txtDir', './txtDir/file.txt'];\n\nfor (let i = 0; i < pathsToCheck.length; i++) {\n  fs.stat(pathsToCheck[i], function(err, stats) {\n    console.log(stats.isDirectory());\n    console.log(stats);\n  });\n}\n
      \n

      The resulting output will resemble:

      \n
      true\nStats {\n  dev: 16777220,\n  mode: 16877,\n  nlink: 3,\n  uid: 501,\n  gid: 20,\n  rdev: 0,\n  blksize: 4096,\n  ino: 14214262,\n  size: 96,\n  blocks: 0,\n  atimeMs: 1561174653071.963,\n  mtimeMs: 1561174614583.3518,\n  ctimeMs: 1561174626623.5366,\n  birthtimeMs: 1561174126937.2893,\n  atime: 2019-06-22T03:37:33.072Z,\n  mtime: 2019-06-22T03:36:54.583Z,\n  ctime: 2019-06-22T03:37:06.624Z,\n  birthtime: 2019-06-22T03:28:46.937Z\n}\nfalse\nStats {\n  dev: 16777220,\n  mode: 33188,\n  nlink: 1,\n  uid: 501,\n  gid: 20,\n  rdev: 0,\n  blksize: 4096,\n  ino: 14214074,\n  size: 8,\n  blocks: 8,\n  atimeMs: 1561174616618.8555,\n  mtimeMs: 1561174614584,\n  ctimeMs: 1561174614583.8145,\n  birthtimeMs: 1561174007710.7478,\n  atime: 2019-06-22T03:36:56.619Z,\n  mtime: 2019-06-22T03:36:54.584Z,\n  ctime: 2019-06-22T03:36:54.584Z,\n  birthtime: 2019-06-22T03:26:47.711Z\n}\n
      " + }, + { + "textRaw": "`fs.statSync(path[, options])`", + "type": "method", + "name": "statSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.Stats}", + "name": "return", + "type": "fs.Stats" + }, + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`. **Default:** `false`.", + "name": "bigint", + "type": "boolean", + "default": "`false`", + "desc": "Whether the numeric values in the returned [`fs.Stats`][] object should be `bigint`." + } + ] + } + ] + } + ], + "desc": "

      Synchronous stat(2).

      " + }, + { + "textRaw": "`fs.symlink(target, path[, type], callback)`", + "type": "method", + "name": "symlink", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `target` and `path` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23724", + "description": "If the `type` argument is left undefined, Node will autodetect `target` type and automatically select `dir` or `file`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`target` {string|Buffer|URL}", + "name": "target", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous symlink(2) which creates the link called path pointing to\ntarget. No arguments other than a possible exception are given to the\ncompletion callback.

      \n

      The type argument is only available on Windows and ignored on other platforms.\nIt can be set to 'dir', 'file', or 'junction'. If the type argument is\nnot set, Node.js will autodetect target type and use 'file' or 'dir'. If\nthe target does not exist, 'file' will be used. Windows junction points\nrequire the destination path to be absolute. When using 'junction', the\ntarget argument will automatically be normalized to absolute path.

      \n

      Relative targets are relative to the link’s parent directory.

      \n
      fs.symlink('./mew', './example/mewtwo', callback);\n
      \n

      The above example creates a symbolic link mewtwo in the example which points\nto mew in the same directory:

      \n
      $ tree example/\nexample/\n├── mew\n└── mewtwo -> ./mew\n
      " + }, + { + "textRaw": "`fs.symlinkSync(target, path[, type])`", + "type": "method", + "name": "symlinkSync", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `target` and `path` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23724", + "description": "If the `type` argument is left undefined, Node will autodetect `target` type and automatically select `dir` or `file`" + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`target` {string|Buffer|URL}", + "name": "target", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.symlink().

      " + }, + { + "textRaw": "`fs.truncate(path[, len], callback)`", + "type": "method", + "name": "truncate", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronous truncate(2). No arguments other than a possible exception are\ngiven to the completion callback. A file descriptor can also be passed as the\nfirst argument. In this case, fs.ftruncate() is called.

      \n

      Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.

      " + }, + { + "textRaw": "`fs.truncateSync(path[, len])`", + "type": "method", + "name": "truncateSync", + "meta": { + "added": [ + "v0.8.6" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`len` {integer} **Default:** `0`", + "name": "len", + "type": "integer", + "default": "`0`" + } + ] + } + ], + "desc": "

      Synchronous truncate(2). Returns undefined. A file descriptor can also be\npassed as the first argument. In this case, fs.ftruncateSync() is called.

      \n

      Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.

      " + }, + { + "textRaw": "`fs.unlink(path, callback)`", + "type": "method", + "name": "unlink", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Asynchronously removes a file or symbolic link. No arguments other than a\npossible exception are given to the completion callback.

      \n
      // Assuming that 'path/file.txt' is a regular file.\nfs.unlink('path/file.txt', (err) => {\n  if (err) throw err;\n  console.log('path/file.txt was deleted');\n});\n
      \n

      fs.unlink() will not work on a directory, empty or otherwise. To remove a\ndirectory, use fs.rmdir().

      \n

      See also: unlink(2).

      " + }, + { + "textRaw": "`fs.unlinkSync(path)`", + "type": "method", + "name": "unlinkSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + } + ] + } + ], + "desc": "

      Synchronous unlink(2). Returns undefined.

      " + }, + { + "textRaw": "`fs.unwatchFile(filename[, listener])`", + "type": "method", + "name": "unwatchFile", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`filename` {string|Buffer|URL}", + "name": "filename", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`listener` {Function} Optional, a listener previously attached using `fs.watchFile()`", + "name": "listener", + "type": "Function", + "desc": "Optional, a listener previously attached using `fs.watchFile()`" + } + ] + } + ], + "desc": "

      Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed,\neffectively stopping watching of filename.

      \n

      Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.

      \n

      Using fs.watch() is more efficient than fs.watchFile() and\nfs.unwatchFile(). fs.watch() should be used instead of fs.watchFile()\nand fs.unwatchFile() when possible.

      " + }, + { + "textRaw": "`fs.utimes(path, atime, mtime, callback)`", + "type": "method", + "name": "utimes", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11919", + "description": "`NaN`, `Infinity`, and `-Infinity` are no longer valid time specifiers." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      Change the file system timestamps of the object referenced by path.

      \n

      The atime and mtime arguments follow these rules:

      \n
        \n
      • Values can be either numbers representing Unix epoch time in seconds,\nDates, or a numeric string like '123456789.0'.
      • \n
      • If the value can not be converted to a number, or is NaN, Infinity or\n-Infinity, an Error will be thrown.
      • \n
      " + }, + { + "textRaw": "`fs.utimesSync(path, atime, mtime)`", + "type": "method", + "name": "utimesSync", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11919", + "description": "`NaN`, `Infinity`, and `-Infinity` are no longer valid time specifiers." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v4.1.0", + "pr-url": "https://github.com/nodejs/node/pull/2387", + "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`atime` {number|string|Date}", + "name": "atime", + "type": "number|string|Date" + }, + { + "textRaw": "`mtime` {number|string|Date}", + "name": "mtime", + "type": "number|string|Date" + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.utimes().

      " + }, + { + "textRaw": "`fs.watch(filename[, options][, listener])`", + "type": "method", + "name": "watch", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [ + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `filename` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7831", + "description": "The passed `options` object will never be modified." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.FSWatcher}", + "name": "return", + "type": "fs.FSWatcher" + }, + "params": [ + { + "textRaw": "`filename` {string|Buffer|URL}", + "name": "filename", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {string|Object}", + "name": "options", + "type": "string|Object", + "options": [ + { + "textRaw": "`persistent` {boolean} Indicates whether the process should continue to run as long as files are being watched. **Default:** `true`.", + "name": "persistent", + "type": "boolean", + "default": "`true`", + "desc": "Indicates whether the process should continue to run as long as files are being watched." + }, + { + "textRaw": "`recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [Caveats][]). **Default:** `false`.", + "name": "recursive", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [Caveats][])." + }, + { + "textRaw": "`encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "Specifies the character encoding to be used for the filename passed to the listener." + } + ] + }, + { + "textRaw": "`listener` {Function|undefined} **Default:** `undefined`", + "name": "listener", + "type": "Function|undefined", + "default": "`undefined`", + "options": [ + { + "textRaw": "`eventType` {string}", + "name": "eventType", + "type": "string" + }, + { + "textRaw": "`filename` {string|Buffer}", + "name": "filename", + "type": "string|Buffer" + } + ] + } + ] + } + ], + "desc": "

      Watch for changes on filename, where filename is either a file or a\ndirectory.

      \n

      The second argument is optional. If options is provided as a string, it\nspecifies the encoding. Otherwise options should be passed as an object.

      \n

      The listener callback gets two arguments (eventType, filename). eventType\nis either 'rename' or 'change', and filename is the name of the file\nwhich triggered the event.

      \n

      On most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.

      \n

      The listener callback is attached to the 'change' event fired by\nfs.FSWatcher, but it is not the same thing as the 'change' value of\neventType.

      ", + "miscs": [ + { + "textRaw": "Caveats", + "name": "Caveats", + "type": "misc", + "desc": "

      The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.

      \n

      The recursive option is only supported on macOS and Windows.

      \n

      On Windows, no events will be emitted if the watched directory is moved or\nrenamed. An EPERM error is reported when the watched directory is deleted.

      ", + "miscs": [ + { + "textRaw": "Availability", + "name": "Availability", + "type": "misc", + "desc": "

      This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.

      \n
        \n
      • On Linux systems, this uses inotify(7).
      • \n
      • On BSD systems, this uses kqueue(2).
      • \n
      • On macOS, this uses kqueue(2) for files and FSEvents for\ndirectories.
      • \n
      • On SunOS systems (including Solaris and SmartOS), this uses event ports.
      • \n
      • On Windows systems, this feature depends on ReadDirectoryChangesW.
      • \n
      • On Aix systems, this feature depends on AHAFS, which must be enabled.
      • \n
      • On IBM i systems, this feature is not supported.
      • \n
      \n

      If the underlying functionality is not available for some reason, then\nfs.watch() will not be able to function and may thrown an exception.\nFor example, watching files or directories can be unreliable, and in some\ncases impossible, on network file systems (NFS, SMB, etc) or host file systems\nwhen using virtualization software such as Vagrant or Docker.

      \n

      It is still possible to use fs.watchFile(), which uses stat polling, but\nthis method is slower and less reliable.

      " + }, + { + "textRaw": "Inodes", + "name": "Inodes", + "type": "misc", + "desc": "

      On Linux and macOS systems, fs.watch() resolves the path to an inode and\nwatches the inode. If the watched path is deleted and recreated, it is assigned\na new inode. The watch will emit an event for the delete but will continue\nwatching the original inode. Events for the new inode will not be emitted.\nThis is expected behavior.

      \n

      AIX files retain the same inode for the lifetime of a file. Saving and closing a\nwatched file on AIX will result in two notifications (one for adding new\ncontent, and one for truncation).

      " + }, + { + "textRaw": "Filename argument", + "name": "Filename argument", + "type": "misc", + "desc": "

      Providing filename argument in the callback is only supported on Linux,\nmacOS, Windows, and AIX. Even on supported platforms, filename is not always\nguaranteed to be provided. Therefore, don't assume that filename argument is\nalways provided in the callback, and have some fallback logic if it is null.

      \n
      fs.watch('somedir', (eventType, filename) => {\n  console.log(`event type is: ${eventType}`);\n  if (filename) {\n    console.log(`filename provided: ${filename}`);\n  } else {\n    console.log('filename not provided');\n  }\n});\n
      " + } + ] + } + ] + }, + { + "textRaw": "`fs.watchFile(filename[, options], listener)`", + "type": "method", + "name": "watchFile", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [ + { + "version": "v10.5.0", + "pr-url": "https://github.com/nodejs/node/pull/20220", + "description": "The `bigint` option is now supported." + }, + { + "version": "v7.6.0", + "pr-url": "https://github.com/nodejs/node/pull/10739", + "description": "The `filename` parameter can be a WHATWG `URL` object using `file:` protocol. Support is currently still *experimental*." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {fs.StatWatcher}", + "name": "return", + "type": "fs.StatWatcher" + }, + "params": [ + { + "textRaw": "`filename` {string|Buffer|URL}", + "name": "filename", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`bigint` {boolean} **Default:** `false`", + "name": "bigint", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`persistent` {boolean} **Default:** `true`", + "name": "persistent", + "type": "boolean", + "default": "`true`" + }, + { + "textRaw": "`interval` {integer} **Default:** `5007`", + "name": "interval", + "type": "integer", + "default": "`5007`" + } + ] + }, + { + "textRaw": "`listener` {Function}", + "name": "listener", + "type": "Function", + "options": [ + { + "textRaw": "`current` {fs.Stats}", + "name": "current", + "type": "fs.Stats" + }, + { + "textRaw": "`previous` {fs.Stats}", + "name": "previous", + "type": "fs.Stats" + } + ] + } + ] + } + ], + "desc": "

      Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.

      \n

      The options argument may be omitted. If provided, it should be an object. The\noptions object may contain a boolean named persistent that indicates\nwhether the process should continue to run as long as files are being watched.\nThe options object may specify an interval property indicating how often the\ntarget should be polled in milliseconds.

      \n

      The listener gets two arguments the current stat object and the previous\nstat object:

      \n
      fs.watchFile('message.text', (curr, prev) => {\n  console.log(`the current mtime is: ${curr.mtime}`);\n  console.log(`the previous mtime was: ${prev.mtime}`);\n});\n
      \n

      These stat objects are instances of fs.Stat. If the bigint option is true,\nthe numeric values in these objects are specified as BigInts.

      \n

      To be notified when the file was modified, not just accessed, it is necessary\nto compare curr.mtime and prev.mtime.

      \n

      When an fs.watchFile operation results in an ENOENT error, it\nwill invoke the listener once, with all the fields zeroed (or, for dates, the\nUnix Epoch). If the file is created later on, the listener will be called\nagain, with the latest stat objects. This is a change in functionality since\nv0.10.

      \n

      Using fs.watch() is more efficient than fs.watchFile and\nfs.unwatchFile. fs.watch should be used instead of fs.watchFile and\nfs.unwatchFile when possible.

      \n

      When a file being watched by fs.watchFile() disappears and reappears,\nthen the contents of previous in the second callback event (the file's\nreappearance) will be the same as the contents of previous in the first\ncallback event (its disappearance).

      \n

      This happens when:

      \n
        \n
      • the file is deleted, followed by a restore
      • \n
      • the file is renamed and then renamed a second time back to its original name
      • \n
      " + }, + { + "textRaw": "`fs.write(fd, buffer[, offset[, length[, position]]], callback)`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.0.2" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`" + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `buffer` parameter can now be a `Uint8Array`." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `offset` and `length` parameters are optional now." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesWritten` {integer}", + "name": "bytesWritten", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + } + ] + } + ] + } + ], + "desc": "

      Write buffer to the file specified by fd.

      \n

      offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position. See pwrite(2).

      \n

      The callback will be given three arguments (err, bytesWritten, buffer) where\nbytesWritten specifies how many bytes were written from buffer.

      \n

      If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with bytesWritten and buffer properties.

      \n

      It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`fs.write(fd, string[, position[, encoding]], callback)`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.11.5" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `position` parameter is optional now." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`written` {integer}", + "name": "written", + "type": "integer" + }, + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ] + } + ], + "desc": "

      Write string to the file specified by fd. If string is not a string, then\nthe value will be coerced to one.

      \n

      position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number' the data will be written at\nthe current position. See pwrite(2).

      \n

      encoding is the expected string encoding.

      \n

      The callback will receive the arguments (err, written, string) where written\nspecifies how many bytes the passed string required to be written. Bytes\nwritten is not necessarily the same as string characters written. See\nBuffer.byteLength.

      \n

      It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      \n

      On Windows, if the file descriptor is connected to the console (e.g. fd == 1\nor stdout) a string containing non-ASCII characters will not be rendered\nproperly by default, regardless of the encoding used.\nIt is possible to configure the console to render UTF-8 properly by changing the\nactive codepage with the chcp 65001 command. See the chcp docs for more\ndetails.

      " + }, + { + "textRaw": "`fs.writeFile(file, data[, options], callback)`", + "type": "method", + "name": "writeFile", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `data` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12562", + "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `data` parameter can now be a `Uint8Array`." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7897", + "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`file` {string|Buffer|URL|integer} filename or file descriptor", + "name": "file", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer|TypedArray|DataView}", + "name": "data", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flag", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      When file is a filename, asynchronously writes data to the file, replacing the\nfile if it already exists. data can be a string or a buffer.

      \n

      When file is a file descriptor, the behavior is similar to calling\nfs.write() directly (which is recommended). See the notes below on using\na file descriptor.

      \n

      The encoding option is ignored if data is a buffer.

      \n
      const data = new Uint8Array(Buffer.from('Hello Node.js'));\nfs.writeFile('message.txt', data, (err) => {\n  if (err) throw err;\n  console.log('The file has been saved!');\n});\n
      \n

      If options is a string, then it specifies the encoding:

      \n
      fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);\n
      \n

      It is unsafe to use fs.writeFile() multiple times on the same file without\nwaiting for the callback. For this scenario, fs.createWriteStream() is\nrecommended.

      ", + "modules": [ + { + "textRaw": "Using `fs.writeFile()` with file descriptors", + "name": "using_`fs.writefile()`_with_file_descriptors", + "desc": "

      When file is a file descriptor, the behavior is almost identical to directly\ncalling fs.write() like:

      \n
      fs.write(fd, Buffer.from(data, options.encoding), callback);\n
      \n

      The difference from directly calling fs.write() is that under some unusual\nconditions, fs.write() may write only part of the buffer and will need to be\nretried to write the remaining data, whereas fs.writeFile() will retry until\nthe data is entirely written (or an error occurs).

      \n

      The implications of this are a common source of confusion. In\nthe file descriptor case, the file is not replaced! The data is not necessarily\nwritten to the beginning of the file, and the file's original data may remain\nbefore and/or after the newly written data.

      \n

      For example, if fs.writeFile() is called twice in a row, first to write the\nstring 'Hello', then to write the string ', World', the file would contain\n'Hello, World', and might contain some of the file's original data (depending\non the size of the original file, and the position of the file descriptor). If\na file name had been used instead of a descriptor, the file would be guaranteed\nto contain only ', World'.

      ", + "type": "module", + "displayName": "Using `fs.writeFile()` with file descriptors" + } + ] + }, + { + "textRaw": "`fs.writeFileSync(file, data[, options])`", + "type": "method", + "name": "writeFileSync", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `data` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `data` parameter can now be a `Uint8Array`." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3163", + "description": "The `file` parameter can be a file descriptor now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`file` {string|Buffer|URL|integer} filename or file descriptor", + "name": "file", + "type": "string|Buffer|URL|integer", + "desc": "filename or file descriptor" + }, + { + "textRaw": "`data` {string|Buffer|TypedArray|DataView}", + "name": "data", + "type": "string|Buffer|TypedArray|DataView" + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", + "name": "encoding", + "type": "string|null", + "default": "`'utf8'`" + }, + { + "textRaw": "`mode` {integer} **Default:** `0o666`", + "name": "mode", + "type": "integer", + "default": "`0o666`" + }, + { + "textRaw": "`flag` {string} See [support of file system `flags`][]. **Default:** `'w'`.", + "name": "flag", + "type": "string", + "default": "`'w'`", + "desc": "See [support of file system `flags`][]." + } + ] + } + ] + } + ], + "desc": "

      Returns undefined.

      \n

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writeFile().

      " + }, + { + "textRaw": "`fs.writeSync(fd, buffer[, offset[, length[, position]]])`", + "type": "method", + "name": "writeSync", + "meta": { + "added": [ + "v0.1.21" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22150", + "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." + }, + { + "version": "v7.4.0", + "pr-url": "https://github.com/nodejs/node/pull/10382", + "description": "The `buffer` parameter can now be a `Uint8Array`." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `offset` and `length` parameters are optional now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes written.", + "name": "return", + "type": "number", + "desc": "The number of bytes written." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + }, + { + "textRaw": "`offset` {integer}", + "name": "offset", + "type": "integer" + }, + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, buffer...).

      " + }, + { + "textRaw": "`fs.writeSync(fd, string[, position[, encoding]])`", + "type": "method", + "name": "writeSync", + "meta": { + "added": [ + "v0.11.5" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/7856", + "description": "The `position` parameter is optional now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes written.", + "name": "return", + "type": "number", + "desc": "The number of bytes written." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, string...).

      " + }, + { + "textRaw": "`fs.writev(fd, buffers[, position], callback)`", + "type": "method", + "name": "writev", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`bytesWritten` {integer}", + "name": "bytesWritten", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + } + ] + } + ] + } + ], + "desc": "

      Write an array of ArrayBufferViews to the file specified by fd using\nwritev().

      \n

      position is the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position.

      \n

      The callback will be given three arguments: err, bytesWritten, and\nbuffers. bytesWritten is how many bytes were written from buffers.

      \n

      If this method is util.promisify()ed, it returns a Promise for an\nObject with bytesWritten and buffers properties.

      \n

      It is unsafe to use fs.writev() multiple times on the same file without\nwaiting for the callback. For this scenario, use fs.createWriteStream().

      \n

      On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.

      " + }, + { + "textRaw": "`fs.writevSync(fd, buffers[, position])`", + "type": "method", + "name": "writevSync", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number} The number of bytes written.", + "name": "return", + "type": "number", + "desc": "The number of bytes written." + }, + "params": [ + { + "textRaw": "`fd` {integer}", + "name": "fd", + "type": "integer" + }, + { + "textRaw": "`buffers` {ArrayBufferView[]}", + "name": "buffers", + "type": "ArrayBufferView[]" + }, + { + "textRaw": "`position` {integer}", + "name": "position", + "type": "integer" + } + ] + } + ], + "desc": "

      For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writev().

      " + } + ], + "properties": [ + { + "textRaw": "`constants` {Object}", + "type": "Object", + "name": "constants", + "desc": "

      Returns an object containing commonly used constants for file system\noperations. The specific constants currently defined are described in\nFS constants.

      " + } + ], + "type": "module", + "displayName": "fs" + } + ] +} \ No newline at end of file diff --git a/doc/api/globals.html b/doc/api/globals.html new file mode 100644 index 0000000000000000000000000000000000000000..31bf6997f2e0dcc3d0521631b9254cd9e663e8ba --- /dev/null +++ b/doc/api/globals.html @@ -0,0 +1,333 @@ + + + + + + + Global objects | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Global objects#

      + + +

      These objects are available in all modules. The following variables may appear +to be global but are not. They exist only in the scope of modules, see the +module system documentation:

      + +

      The objects listed here are specific to Node.js. There are built-in objects +that are part of the JavaScript language itself, which are also globally +accessible.

      +

      Class: Buffer#

      + + + +

      Used to handle binary data. See the buffer section.

      +

      __dirname#

      +

      This variable may appear to be global but is not. See __dirname.

      +

      __filename#

      +

      This variable may appear to be global but is not. See __filename.

      +

      clearImmediate(immediateObject)#

      + + +

      clearImmediate is described in the timers section.

      +

      clearInterval(intervalObject)#

      + + +

      clearInterval is described in the timers section.

      +

      clearTimeout(timeoutObject)#

      + + +

      clearTimeout is described in the timers section.

      +

      console#

      + + + +

      Used to print to stdout and stderr. See the console section.

      +

      exports#

      +

      This variable may appear to be global but is not. See exports.

      +

      global#

      + + +
        +
      • <Object> The global namespace object.
      • +
      +

      In browsers, the top-level scope is the global scope. This means that +within the browser var something will define a new global variable. In +Node.js this is different. The top-level scope is not the global scope; +var something inside a Node.js module will be local to that module.

      +

      module#

      +

      This variable may appear to be global but is not. See module.

      +

      process#

      + + + +

      The process object. See the process object section.

      +

      queueMicrotask(callback)#

      + + + +

      The queueMicrotask() method queues a microtask to invoke callback. If +callback throws an exception, the process object 'uncaughtException' +event will be emitted.

      +

      The microtask queue is managed by V8 and may be used in a similar manner to +the process.nextTick() queue, which is managed by Node.js. The +process.nextTick() queue is always processed before the microtask queue +within each turn of the Node.js event loop.

      +
      // Here, `queueMicrotask()` is used to ensure the 'load' event is always
      +// emitted asynchronously, and therefore consistently. Using
      +// `process.nextTick()` here would result in the 'load' event always emitting
      +// before any other promise jobs.
      +
      +DataHandler.prototype.load = async function load(key) {
      +  const hit = this._cache.get(url);
      +  if (hit !== undefined) {
      +    queueMicrotask(() => {
      +      this.emit('load', hit);
      +    });
      +    return;
      +  }
      +
      +  const data = await fetchData(key);
      +  this._cache.set(url, data);
      +  this.emit('load', data);
      +};
      +

      require()#

      +

      This variable may appear to be global but is not. See require().

      +

      setImmediate(callback[, ...args])#

      + + +

      setImmediate is described in the timers section.

      +

      setInterval(callback, delay[, ...args])#

      + + +

      setInterval is described in the timers section.

      +

      setTimeout(callback, delay[, ...args])#

      + + +

      setTimeout is described in the timers section.

      +

      TextDecoder#

      + + +

      The WHATWG TextDecoder class. See the TextDecoder section.

      +

      TextEncoder#

      + + +

      The WHATWG TextEncoder class. See the TextEncoder section.

      +

      URL#

      + + +

      The WHATWG URL class. See the URL section.

      +

      URLSearchParams#

      + + +

      The WHATWG URLSearchParams class. See the URLSearchParams section.

      +

      WebAssembly#

      + + + +

      The object that acts as the namespace for all W3C +WebAssembly related functionality. See the +Mozilla Developer Network for usage and compatibility.

      + +
      +
      +
      + + diff --git a/doc/api/globals.json b/doc/api/globals.json new file mode 100644 index 0000000000000000000000000000000000000000..63d679c31e6b93cb9fe0e7827696b40024c62160 --- /dev/null +++ b/doc/api/globals.json @@ -0,0 +1,458 @@ +{ + "type": "module", + "source": "doc/api/globals.md", + "introduced_in": "v0.10.0", + "globals": [ + { + "textRaw": "Class: `Buffer`", + "type": "global", + "name": "Buffer", + "meta": { + "added": [ + "v0.1.103" + ], + "changes": [] + }, + "desc": "\n

      Used to handle binary data. See the buffer section.

      " + }, + { + "textRaw": "`clearImmediate(immediateObject)`", + "type": "global", + "name": "clearImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      clearImmediate is described in the timers section.

      " + }, + { + "textRaw": "`clearInterval(intervalObject)`", + "type": "global", + "name": "clearInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearInterval is described in the timers section.

      " + }, + { + "textRaw": "`clearTimeout(timeoutObject)`", + "type": "global", + "name": "clearTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearTimeout is described in the timers section.

      " + }, + { + "textRaw": "`console`", + "name": "`console`", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      Used to print to stdout and stderr. See the console section.

      " + }, + { + "textRaw": "`global`", + "name": "`global`", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "type": "global", + "desc": "
        \n
      • <Object> The global namespace object.
      • \n
      \n

      In browsers, the top-level scope is the global scope. This means that\nwithin the browser var something will define a new global variable. In\nNode.js this is different. The top-level scope is not the global scope;\nvar something inside a Node.js module will be local to that module.

      " + }, + { + "textRaw": "`process`", + "name": "`process`", + "meta": { + "added": [ + "v0.1.7" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The process object. See the process object section.

      " + }, + { + "textRaw": "`queueMicrotask(callback)`", + "type": "global", + "name": "queueMicrotask", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "desc": "\n

      The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.

      \n

      The microtask queue is managed by V8 and may be used in a similar manner to\nthe process.nextTick() queue, which is managed by Node.js. The\nprocess.nextTick() queue is always processed before the microtask queue\nwithin each turn of the Node.js event loop.

      \n
      // Here, `queueMicrotask()` is used to ensure the 'load' event is always\n// emitted asynchronously, and therefore consistently. Using\n// `process.nextTick()` here would result in the 'load' event always emitting\n// before any other promise jobs.\n\nDataHandler.prototype.load = async function load(key) {\n  const hit = this._cache.get(url);\n  if (hit !== undefined) {\n    queueMicrotask(() => {\n      this.emit('load', hit);\n    });\n    return;\n  }\n\n  const data = await fetchData(key);\n  this._cache.set(url, data);\n  this.emit('load', data);\n};\n
      " + }, + { + "textRaw": "`setImmediate(callback[, ...args])`", + "type": "global", + "name": "setImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      setImmediate is described in the timers section.

      " + }, + { + "textRaw": "`setInterval(callback, delay[, ...args])`", + "type": "global", + "name": "setInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setInterval is described in the timers section.

      " + }, + { + "textRaw": "`setTimeout(callback, delay[, ...args])`", + "type": "global", + "name": "setTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setTimeout is described in the timers section.

      " + }, + { + "textRaw": "`TextDecoder`", + "name": "`TextDecoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextDecoder class. See the TextDecoder section.

      " + }, + { + "textRaw": "`TextEncoder`", + "name": "`TextEncoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextEncoder class. See the TextEncoder section.

      " + }, + { + "textRaw": "`URL`", + "name": "`URL`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URL class. See the URL section.

      " + }, + { + "textRaw": "`URLSearchParams`", + "name": "`URLSearchParams`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URLSearchParams class. See the URLSearchParams section.

      " + }, + { + "textRaw": "`WebAssembly`", + "name": "`WebAssembly`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.

      " + } + ], + "methods": [ + { + "textRaw": "`require()`", + "type": "method", + "name": "require", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This variable may appear to be global but is not. See require().

      " + } + ], + "miscs": [ + { + "textRaw": "Global objects", + "name": "Global objects", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      These objects are available in all modules. The following variables may appear\nto be global but are not. They exist only in the scope of modules, see the\nmodule system documentation:

      \n\n

      The objects listed here are specific to Node.js. There are built-in objects\nthat are part of the JavaScript language itself, which are also globally\naccessible.

      ", + "globals": [ + { + "textRaw": "Class: `Buffer`", + "type": "global", + "name": "Buffer", + "meta": { + "added": [ + "v0.1.103" + ], + "changes": [] + }, + "desc": "\n

      Used to handle binary data. See the buffer section.

      " + }, + { + "textRaw": "`clearImmediate(immediateObject)`", + "type": "global", + "name": "clearImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      clearImmediate is described in the timers section.

      " + }, + { + "textRaw": "`clearInterval(intervalObject)`", + "type": "global", + "name": "clearInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearInterval is described in the timers section.

      " + }, + { + "textRaw": "`clearTimeout(timeoutObject)`", + "type": "global", + "name": "clearTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      clearTimeout is described in the timers section.

      " + }, + { + "textRaw": "`console`", + "name": "`console`", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      Used to print to stdout and stderr. See the console section.

      " + }, + { + "textRaw": "`global`", + "name": "`global`", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "type": "global", + "desc": "
        \n
      • <Object> The global namespace object.
      • \n
      \n

      In browsers, the top-level scope is the global scope. This means that\nwithin the browser var something will define a new global variable. In\nNode.js this is different. The top-level scope is not the global scope;\nvar something inside a Node.js module will be local to that module.

      " + }, + { + "textRaw": "`process`", + "name": "`process`", + "meta": { + "added": [ + "v0.1.7" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The process object. See the process object section.

      " + }, + { + "textRaw": "`queueMicrotask(callback)`", + "type": "global", + "name": "queueMicrotask", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "desc": "\n

      The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.

      \n

      The microtask queue is managed by V8 and may be used in a similar manner to\nthe process.nextTick() queue, which is managed by Node.js. The\nprocess.nextTick() queue is always processed before the microtask queue\nwithin each turn of the Node.js event loop.

      \n
      // Here, `queueMicrotask()` is used to ensure the 'load' event is always\n// emitted asynchronously, and therefore consistently. Using\n// `process.nextTick()` here would result in the 'load' event always emitting\n// before any other promise jobs.\n\nDataHandler.prototype.load = async function load(key) {\n  const hit = this._cache.get(url);\n  if (hit !== undefined) {\n    queueMicrotask(() => {\n      this.emit('load', hit);\n    });\n    return;\n  }\n\n  const data = await fetchData(key);\n  this._cache.set(url, data);\n  this.emit('load', data);\n};\n
      " + }, + { + "textRaw": "`setImmediate(callback[, ...args])`", + "type": "global", + "name": "setImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "desc": "

      setImmediate is described in the timers section.

      " + }, + { + "textRaw": "`setInterval(callback, delay[, ...args])`", + "type": "global", + "name": "setInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setInterval is described in the timers section.

      " + }, + { + "textRaw": "`setTimeout(callback, delay[, ...args])`", + "type": "global", + "name": "setTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "desc": "

      setTimeout is described in the timers section.

      " + }, + { + "textRaw": "`TextDecoder`", + "name": "`TextDecoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextDecoder class. See the TextDecoder section.

      " + }, + { + "textRaw": "`TextEncoder`", + "name": "`TextEncoder`", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG TextEncoder class. See the TextEncoder section.

      " + }, + { + "textRaw": "`URL`", + "name": "`URL`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URL class. See the URL section.

      " + }, + { + "textRaw": "`URLSearchParams`", + "name": "`URLSearchParams`", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "

      The WHATWG URLSearchParams class. See the URLSearchParams section.

      " + }, + { + "textRaw": "`WebAssembly`", + "name": "`WebAssembly`", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "type": "global", + "desc": "\n

      The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.

      " + } + ], + "miscs": [ + { + "textRaw": "`__dirname`", + "name": "`__dirname`", + "desc": "

      This variable may appear to be global but is not. See __dirname.

      ", + "type": "misc", + "displayName": "`__dirname`" + }, + { + "textRaw": "`__filename`", + "name": "`__filename`", + "desc": "

      This variable may appear to be global but is not. See __filename.

      ", + "type": "misc", + "displayName": "`__filename`" + }, + { + "textRaw": "`exports`", + "name": "`exports`", + "desc": "

      This variable may appear to be global but is not. See exports.

      ", + "type": "misc", + "displayName": "`exports`" + }, + { + "textRaw": "`module`", + "name": "`module`", + "desc": "

      This variable may appear to be global but is not. See module.

      ", + "type": "misc", + "displayName": "`module`" + } + ], + "methods": [ + { + "textRaw": "`require()`", + "type": "method", + "name": "require", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This variable may appear to be global but is not. See require().

      " + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/http.html b/doc/api/http.html new file mode 100644 index 0000000000000000000000000000000000000000..29039fe7fb5284b8a14d5aed514b89dc4d2a2d8f --- /dev/null +++ b/doc/api/http.html @@ -0,0 +1,2372 @@ + + + + + + + HTTP | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      HTTP#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/http.js

      +

      To use the HTTP server and client one must require('http').

      +

      The HTTP interfaces in Node.js are designed to support many features +of the protocol which have been traditionally difficult to use. +In particular, large, possibly chunk-encoded, messages. The interface is +careful to never buffer entire requests or responses, so the +user is able to stream data.

      +

      HTTP message headers are represented by an object like this:

      + +
      { 'content-length': '123',
      +  'content-type': 'text/plain',
      +  'connection': 'keep-alive',
      +  'host': 'mysite.com',
      +  'accept': '*/*' }
      +

      Keys are lowercased. Values are not modified.

      +

      In order to support the full spectrum of possible HTTP applications, the Node.js +HTTP API is very low-level. It deals with stream handling and message +parsing only. It parses a message into headers and body but it does not +parse the actual headers or the body.

      +

      See message.headers for details on how duplicate headers are handled.

      +

      The raw headers as they were received are retained in the rawHeaders +property, which is an array of [key, value, key2, value2, ...]. For +example, the previous message header object might have a rawHeaders +list like the following:

      + +
      [ 'ConTent-Length', '123456',
      +  'content-LENGTH', '123',
      +  'content-type', 'text/plain',
      +  'CONNECTION', 'keep-alive',
      +  'Host', 'mysite.com',
      +  'accepT', '*/*' ]
      +

      Class: http.Agent#

      + +

      An Agent is responsible for managing connection persistence +and reuse for HTTP clients. It maintains a queue of pending requests +for a given host and port, reusing a single socket connection for each +until the queue is empty, at which time the socket is either destroyed +or put into a pool where it is kept to be used again for requests to the +same host and port. Whether it is destroyed or pooled depends on the +keepAlive option.

      +

      Pooled connections have TCP Keep-Alive enabled for them, but servers may +still close idle connections, in which case they will be removed from the +pool and a new connection will be made when a new HTTP request is made for +that host and port. Servers may also refuse to allow multiple requests +over the same connection, in which case the connection will have to be +remade for every request and cannot be pooled. The Agent will still make +the requests to that server, but each one will occur over a new connection.

      +

      When a connection is closed by the client or the server, it is removed +from the pool. Any unused sockets in the pool will be unrefed so as not +to keep the Node.js process running when there are no outstanding requests. +(see socket.unref()).

      +

      It is good practice, to destroy() an Agent instance when it is no +longer in use, because unused sockets consume OS resources.

      +

      Sockets are removed from an agent when the socket emits either +a 'close' event or an 'agentRemove' event. When intending to keep one +HTTP request open for a long time without keeping it in the agent, something +like the following may be done:

      +
      http.get(options, (res) => {
      +  // Do stuff
      +}).on('socket', (socket) => {
      +  socket.emit('agentRemove');
      +});
      +

      An agent may also be used for an individual request. By providing +{agent: false} as an option to the http.get() or http.request() +functions, a one-time use Agent with default options will be used +for the client connection.

      +

      agent:false:

      +
      http.get({
      +  hostname: 'localhost',
      +  port: 80,
      +  path: '/',
      +  agent: false  // Create a new agent just for this one request
      +}, (res) => {
      +  // Do stuff with response
      +});
      +

      new Agent([options])#

      + +
        +
      • options <Object> Set of configurable options to set on the agent. +Can have the following fields: +
          +
        • keepAlive <boolean> Keep sockets around even when there are no +outstanding requests, so they can be used for future requests without +having to reestablish a TCP connection. Not to be confused with the +keep-alive value of the Connection header. The Connection: keep-alive +header is always sent when using an agent except when the Connection +header is explicitly specified or when the keepAlive and maxSockets +options are respectively set to false and Infinity, in which case +Connection: close will be used. Default: false.
        • +
        • keepAliveMsecs <number> When using the keepAlive option, specifies +the initial delay +for TCP Keep-Alive packets. Ignored when the +keepAlive option is false or undefined. Default: 1000.
        • +
        • maxSockets <number> Maximum number of sockets to allow per +host. Each request will use a new socket until the maximum is reached. +Default: Infinity.
        • +
        • maxTotalSockets <number> Maximum number of sockets allowed for +all hosts in total. Each request will use a new socket +until the maximum is reached. +Default: Infinity.
        • +
        • maxFreeSockets <number> Maximum number of sockets to leave open +in a free state. Only relevant if keepAlive is set to true. +Default: 256.
        • +
        • scheduling <string> Scheduling strategy to apply when picking +the next free socket to use. It can be 'fifo' or 'lifo'. +The main difference between the two scheduling strategies is that 'lifo' +selects the most recently used socket, while 'fifo' selects +the least recently used socket. +In case of a low rate of request per second, the 'lifo' scheduling +will lower the risk of picking a socket that might have been closed +by the server due to inactivity. +In case of a high rate of request per second, +the 'fifo' scheduling will maximize the number of open sockets, +while the 'lifo' scheduling will keep it as low as possible. +Default: 'fifo'.
        • +
        • timeout <number> Socket timeout in milliseconds. +This will set the timeout when the socket is created.
        • +
        +
      • +
      +

      options in socket.connect() are also supported.

      +

      The default http.globalAgent that is used by http.request() has all +of these values set to their respective defaults.

      +

      To configure any of them, a custom http.Agent instance must be created.

      +
      const http = require('http');
      +const keepAliveAgent = new http.Agent({ keepAlive: true });
      +options.agent = keepAliveAgent;
      +http.request(options, onResponseCallback);
      +

      agent.createConnection(options[, callback])#

      + + +

      Produces a socket/stream to be used for HTTP requests.

      +

      By default, this function is the same as net.createConnection(). However, +custom agents may override this method in case greater flexibility is desired.

      +

      A socket/stream can be supplied in one of two ways: by returning the +socket/stream from this function, or by passing the socket/stream to callback.

      +

      This method is guaranteed to return an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      callback has a signature of (err, stream).

      +

      agent.keepSocketAlive(socket)#

      + + +

      Called when socket is detached from a request and could be persisted by the +Agent. Default behavior is to:

      +
      socket.setKeepAlive(true, this.keepAliveMsecs);
      +socket.unref();
      +return true;
      +

      This method can be overridden by a particular Agent subclass. If this +method returns a falsy value, the socket will be destroyed instead of persisting +it for use with the next request.

      +

      The socket argument can be an instance of <net.Socket>, a subclass of +<stream.Duplex>.

      +

      agent.reuseSocket(socket, request)#

      + + +

      Called when socket is attached to request after being persisted because of +the keep-alive options. Default behavior is to:

      +
      socket.ref();
      +

      This method can be overridden by a particular Agent subclass.

      +

      The socket argument can be an instance of <net.Socket>, a subclass of +<stream.Duplex>.

      +

      agent.destroy()#

      + +

      Destroy any sockets that are currently in use by the agent.

      +

      It is usually not necessary to do this. However, if using an +agent with keepAlive enabled, then it is best to explicitly shut down +the agent when it will no longer be used. Otherwise, +sockets may hang open for quite a long time before the server +terminates them.

      +

      agent.freeSockets#

      + + +

      An object which contains arrays of sockets currently awaiting use by +the agent when keepAlive is enabled. Do not modify.

      +

      Sockets in the freeSockets list will be automatically destroyed and +removed from the array on 'timeout'.

      +

      agent.getName(options)#

      + +
        +
      • options <Object> A set of options providing information for name generation +
          +
        • host <string> A domain name or IP address of the server to issue the +request to
        • +
        • port <number> Port of remote server
        • +
        • localAddress <string> Local interface to bind for network connections +when issuing the request
        • +
        • family <integer> Must be 4 or 6 if this doesn't equal undefined.
        • +
        +
      • +
      • Returns: <string>
      • +
      +

      Get a unique name for a set of request options, to determine whether a +connection can be reused. For an HTTP agent, this returns +host:port:localAddress or host:port:localAddress:family. For an HTTPS agent, +the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options +that determine socket reusability.

      +

      agent.maxFreeSockets#

      + + +

      By default set to 256. For agents with keepAlive enabled, this +sets the maximum number of sockets that will be left open in the free +state.

      +

      agent.maxSockets#

      + + +

      By default set to Infinity. Determines how many concurrent sockets the agent +can have open per origin. Origin is the returned value of agent.getName().

      +

      agent.maxTotalSockets#

      + + +

      By default set to Infinity. Determines how many concurrent sockets the agent +can have open. Unlike maxSockets, this parameter applies across all origins.

      +

      agent.requests#

      + + +

      An object which contains queues of requests that have not yet been assigned to +sockets. Do not modify.

      +

      agent.sockets#

      + + +

      An object which contains arrays of sockets currently in use by the +agent. Do not modify.

      +

      Class: http.ClientRequest#

      + + +

      This object is created internally and returned from http.request(). It +represents an in-progress request whose header has already been queued. The +header is still mutable using the setHeader(name, value), +getHeader(name), removeHeader(name) API. The actual header will +be sent along with the first data chunk or when calling request.end().

      +

      To get the response, add a listener for 'response' to the request object. +'response' will be emitted from the request object when the response +headers have been received. The 'response' event is executed with one +argument which is an instance of http.IncomingMessage.

      +

      During the 'response' event, one can add listeners to the +response object; particularly to listen for the 'data' event.

      +

      If no 'response' handler is added, then the response will be +entirely discarded. However, if a 'response' event handler is added, +then the data from the response object must be consumed, either by +calling response.read() whenever there is a 'readable' event, or +by adding a 'data' handler, or by calling the .resume() method. +Until the data is consumed, the 'end' event will not fire. Also, until +the data is read it will consume memory that can eventually lead to a +'process out of memory' error.

      +

      Unlike the request object, if the response closes prematurely, the +response object does not emit an 'error' event but instead emits the +'aborted' event.

      +

      Node.js does not check whether Content-Length and the length of the +body which has been transmitted are equal or not.

      +

      Event: 'abort'#

      + +

      Emitted when the request has been aborted by the client. This event is only +emitted on the first call to abort().

      +

      Event: 'connect'#

      + + +

      Emitted each time a server responds to a request with a CONNECT method. If +this event is not being listened for, clients receiving a CONNECT method will +have their connections closed.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      A client and server pair demonstrating how to listen for the 'connect' event:

      +
      const http = require('http');
      +const net = require('net');
      +const { URL } = require('url');
      +
      +// Create an HTTP tunneling proxy
      +const proxy = http.createServer((req, res) => {
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('okay');
      +});
      +proxy.on('connect', (req, clientSocket, head) => {
      +  // Connect to an origin server
      +  const { port, hostname } = new URL(`http://${req.url}`);
      +  const serverSocket = net.connect(port || 80, hostname, () => {
      +    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
      +                    'Proxy-agent: Node.js-Proxy\r\n' +
      +                    '\r\n');
      +    serverSocket.write(head);
      +    serverSocket.pipe(clientSocket);
      +    clientSocket.pipe(serverSocket);
      +  });
      +});
      +
      +// Now that proxy is running
      +proxy.listen(1337, '127.0.0.1', () => {
      +
      +  // Make a request to a tunneling proxy
      +  const options = {
      +    port: 1337,
      +    host: '127.0.0.1',
      +    method: 'CONNECT',
      +    path: 'www.google.com:80'
      +  };
      +
      +  const req = http.request(options);
      +  req.end();
      +
      +  req.on('connect', (res, socket, head) => {
      +    console.log('got connected!');
      +
      +    // Make a request over an HTTP tunnel
      +    socket.write('GET / HTTP/1.1\r\n' +
      +                 'Host: www.google.com:80\r\n' +
      +                 'Connection: close\r\n' +
      +                 '\r\n');
      +    socket.on('data', (chunk) => {
      +      console.log(chunk.toString());
      +    });
      +    socket.on('end', () => {
      +      proxy.close();
      +    });
      +  });
      +});
      +

      Event: 'continue'#

      + +

      Emitted when the server sends a '100 Continue' HTTP response, usually because +the request contained 'Expect: 100-continue'. This is an instruction that +the client should send the request body.

      +

      Event: 'information'#

      + + +

      Emitted when the server sends a 1xx intermediate response (excluding 101 +Upgrade). The listeners of this event will receive an object containing the +HTTP version, status code, status message, key-value headers object, +and array with the raw header names followed by their respective values.

      +
      const http = require('http');
      +
      +const options = {
      +  host: '127.0.0.1',
      +  port: 8080,
      +  path: '/length_request'
      +};
      +
      +// Make a request
      +const req = http.request(options);
      +req.end();
      +
      +req.on('information', (info) => {
      +  console.log(`Got information prior to main response: ${info.statusCode}`);
      +});
      +

      101 Upgrade statuses do not fire this event due to their break from the +traditional HTTP request/response chain, such as web sockets, in-place TLS +upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the +'upgrade' event instead.

      +

      Event: 'response'#

      + + +

      Emitted when a response is received to this request. This event is emitted only +once.

      +

      Event: 'socket'#

      + + +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      Event: 'timeout'#

      + +

      Emitted when the underlying socket times out from inactivity. This only notifies +that the socket has been idle. The request must be aborted manually.

      +

      See also: request.setTimeout().

      +

      Event: 'upgrade'#

      + + +

      Emitted each time a server responds to a request with an upgrade. If this +event is not being listened for and the response status code is 101 Switching +Protocols, clients receiving an upgrade header will have their connections +closed.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      A client server pair demonstrating how to listen for the 'upgrade' event.

      +
      const http = require('http');
      +
      +// Create an HTTP server
      +const server = http.createServer((req, res) => {
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('okay');
      +});
      +server.on('upgrade', (req, socket, head) => {
      +  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
      +               'Upgrade: WebSocket\r\n' +
      +               'Connection: Upgrade\r\n' +
      +               '\r\n');
      +
      +  socket.pipe(socket); // echo back
      +});
      +
      +// Now that server is running
      +server.listen(1337, '127.0.0.1', () => {
      +
      +  // make a request
      +  const options = {
      +    port: 1337,
      +    host: '127.0.0.1',
      +    headers: {
      +      'Connection': 'Upgrade',
      +      'Upgrade': 'websocket'
      +    }
      +  };
      +
      +  const req = http.request(options);
      +  req.end();
      +
      +  req.on('upgrade', (res, socket, upgradeHead) => {
      +    console.log('got upgraded!');
      +    socket.end();
      +    process.exit(0);
      +  });
      +});
      +

      request.abort()#

      + +

      Marks the request as aborting. Calling this will cause remaining data +in the response to be dropped and the socket to be destroyed.

      +

      request.aborted#

      + + +

      The request.aborted property will be true if the request has +been aborted.

      +

      request.connection#

      + + +

      See request.socket.

      +

      request.end([data[, encoding]][, callback])#

      + + +

      Finishes sending the request. If any parts of the body are +unsent, it will flush them to the stream. If the request is +chunked, this will send the terminating '0\r\n\r\n'.

      +

      If data is specified, it is equivalent to calling +request.write(data, encoding) followed by request.end(callback).

      +

      If callback is specified, it will be called when the request stream +is finished.

      +

      request.finished#

      + +

      + +

      The request.finished property will be true if request.end() +has been called. request.end() will automatically be called if the +request was initiated via http.get().

      +

      request.flushHeaders()#

      + +

      Flushes the request headers.

      +

      For efficiency reasons, Node.js normally buffers the request headers until +request.end() is called or the first chunk of request data is written. It +then tries to pack the request headers and data into a single TCP packet.

      +

      That's usually desired (it saves a TCP round-trip), but not when the first +data is not sent until possibly much later. request.flushHeaders() bypasses +the optimization and kickstarts the request.

      +

      request.getHeader(name)#

      + + +

      Reads out a header on the request. The name is case-insensitive. +The type of the return value depends on the arguments provided to +request.setHeader().

      +
      request.setHeader('content-type', 'text/html');
      +request.setHeader('Content-Length', Buffer.byteLength(body));
      +request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
      +const contentType = request.getHeader('Content-Type');
      +// 'contentType' is 'text/html'
      +const contentLength = request.getHeader('Content-Length');
      +// 'contentLength' is of type number
      +const cookie = request.getHeader('Cookie');
      +// 'cookie' is of type string[]
      +

      request.maxHeadersCount#

      + +

      Limits maximum response headers count. If set to 0, no limit will be applied.

      +

      request.path#

      + + +

      request.method#

      + + +

      request.host#

      + + +

      request.protocol#

      + + +

      request.removeHeader(name)#

      + + +

      Removes a header that's already defined into headers object.

      +
      request.removeHeader('Content-Type');
      +

      request.reusedSocket#

      + +
        +
      • <boolean> Whether the request is send through a reused socket.
      • +
      +

      When sending request through a keep-alive enabled agent, the underlying socket +might be reused. But if server closes connection at unfortunate time, client +may run into a 'ECONNRESET' error.

      +
      const http = require('http');
      +
      +// Server has a 5 seconds keep-alive timeout by default
      +http
      +  .createServer((req, res) => {
      +    res.write('hello\n');
      +    res.end();
      +  })
      +  .listen(3000);
      +
      +setInterval(() => {
      +  // Adapting a keep-alive agent
      +  http.get('http://localhost:3000', { agent }, (res) => {
      +    res.on('data', (data) => {
      +      // Do nothing
      +    });
      +  });
      +}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
      +

      By marking a request whether it reused socket or not, we can do +automatic error retry base on it.

      +
      const http = require('http');
      +const agent = new http.Agent({ keepAlive: true });
      +
      +function retriableRequest() {
      +  const req = http
      +    .get('http://localhost:3000', { agent }, (res) => {
      +      // ...
      +    })
      +    .on('error', (err) => {
      +      // Check if retry is needed
      +      if (req.reusedSocket && err.code === 'ECONNRESET') {
      +        retriableRequest();
      +      }
      +    });
      +}
      +
      +retriableRequest();
      +

      request.setHeader(name, value)#

      + + +

      Sets a single header value for headers object. If this header already exists in +the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name. Non-string values will be +stored without modification. Therefore, request.getHeader() may return +non-string values. However, the non-string values will be converted to strings +for network transmission.

      +
      request.setHeader('Content-Type', 'application/json');
      +

      or

      +
      request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
      +

      request.setNoDelay([noDelay])#

      + + +

      Once a socket is assigned to this request and is connected +socket.setNoDelay() will be called.

      +

      request.setSocketKeepAlive([enable][, initialDelay])#

      + + +

      Once a socket is assigned to this request and is connected +socket.setKeepAlive() will be called.

      +

      request.setTimeout(timeout[, callback])#

      + +
        +
      • timeout <number> Milliseconds before a request times out.
      • +
      • callback <Function> Optional function to be called when a timeout occurs. +Same as binding to the 'timeout' event.
      • +
      • Returns: <http.ClientRequest>
      • +
      +

      Once a socket is assigned to this request and is connected +socket.setTimeout() will be called.

      +

      request.socket#

      + + +

      Reference to the underlying socket. Usually users will not want to access +this property. In particular, the socket will not emit 'readable' events +because of how the protocol parser attaches to the socket. The socket +may also be accessed via request.connection.

      +
      const http = require('http');
      +const options = {
      +  host: 'www.google.com',
      +};
      +const req = http.get(options);
      +req.end();
      +req.once('response', (res) => {
      +  const ip = req.socket.localAddress;
      +  const port = req.socket.localPort;
      +  console.log(`Your IP address is ${ip} and your source port is ${port}.`);
      +  // Consume response object
      +});
      +

      This property is guaranteed to be an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specified a socket +type other than <net.Socket>.

      +

      request.writableEnded#

      + + +

      Is true after request.end() has been called. This property +does not indicate whether the data has been flushed, for this use +request.writableFinished instead.

      +

      request.writableFinished#

      + + +

      Is true if all data has been flushed to the underlying system, immediately +before the 'finish' event is emitted.

      +

      request.write(chunk[, encoding][, callback])#

      + + +

      Sends a chunk of the body. By calling this method +many times, a request body can be sent to a +server. In that case, it is suggested to use the +['Transfer-Encoding', 'chunked'] header line when +creating the request.

      +

      The encoding argument is optional and only applies when chunk is a string. +Defaults to 'utf8'.

      +

      The callback argument is optional and will be called when this chunk of data +is flushed, but only if the chunk is non-empty.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is free again.

      +

      When write function is called with empty string or buffer, it does +nothing and waits for more input.

      +

      Class: http.Server#

      + + +

      Event: 'checkContinue'#

      + + +

      Emitted each time a request with an HTTP Expect: 100-continue is received. +If this event is not listened for, the server will automatically respond +with a 100 Continue as appropriate.

      +

      Handling this event involves calling response.writeContinue() if the +client should continue to send the request body, or generating an appropriate +HTTP response (e.g. 400 Bad Request) if the client should not continue to send +the request body.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'checkExpectation'#

      + + +

      Emitted each time a request with an HTTP Expect header is received, where the +value is not 100-continue. If this event is not listened for, the server will +automatically respond with a 417 Expectation Failed as appropriate.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'clientError'#

      + + +

      If a client connection emits an 'error' event, it will be forwarded here. +Listener of this event is responsible for closing/destroying the underlying +socket. For example, one may wish to more gracefully close the socket with a +custom HTTP response instead of abruptly severing the connection.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      Default behavior is to try close the socket with a HTTP '400 Bad Request', +or a HTTP '431 Request Header Fields Too Large' in the case of a +HPE_HEADER_OVERFLOW error. If the socket is not writable or has already +written data it is immediately destroyed.

      +

      socket is the net.Socket object that the error originated from.

      +
      const http = require('http');
      +
      +const server = http.createServer((req, res) => {
      +  res.end();
      +});
      +server.on('clientError', (err, socket) => {
      +  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
      +});
      +server.listen(8000);
      +

      When the 'clientError' event occurs, there is no request or response +object, so any HTTP response sent, including response headers and payload, +must be written directly to the socket object. Care must be taken to +ensure the response is a properly formatted HTTP response message.

      +

      err is an instance of Error with two extra columns:

      +
        +
      • bytesParsed: the bytes count of request packet that Node.js may have parsed +correctly;
      • +
      • rawPacket: the raw packet of current request.
      • +
      +

      In some cases, the client has already received the response and/or the socket +has already been destroyed, like in case of ECONNRESET errors. Before +trying to send data to the socket, it is better to check that it is still +writable.

      +
      server.on('clientError', (err, socket) => {
      +  if (err.code === 'ECONNRESET' || !socket.writable) {
      +    return;
      +  }
      +
      +  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
      +});
      +

      Event: 'close'#

      + +

      Emitted when the server closes.

      +

      Event: 'connect'#

      + + +

      Emitted each time a client requests an HTTP CONNECT method. If this event is +not listened for, then clients requesting a CONNECT method will have their +connections closed.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      After this event is emitted, the request's socket will not have a 'data' +event listener, meaning it will need to be bound in order to handle data +sent to the server on that socket.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established. socket is +typically an object of type net.Socket. Usually users will not want to +access this event. In particular, the socket will not emit 'readable' events +because of how the protocol parser attaches to the socket. The socket can +also be accessed at request.connection.

      +

      This event can also be explicitly emitted by users to inject connections +into the HTTP server. In that case, any Duplex stream can be passed.

      +

      If socket.setTimeout() is called here, the timeout will be replaced with +server.keepAliveTimeout when the socket has served a request (if +server.keepAliveTimeout is non-zero).

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      Event: 'request'#

      + + +

      Emitted each time there is a request. There may be multiple requests +per connection (in the case of HTTP Keep-Alive connections).

      +

      Event: 'upgrade'#

      + + +

      Emitted each time a client requests an HTTP upgrade. Listening to this event +is optional and clients cannot insist on a protocol change.

      +

      After this event is emitted, the request's socket will not have a 'data' +event listener, meaning it will need to be bound in order to handle data +sent to the server on that socket.

      +

      This event is guaranteed to be passed an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specifies a socket +type other than <net.Socket>.

      +

      server.close([callback])#

      + + +

      Stops the server from accepting new connections. See net.Server.close().

      +

      server.headersTimeout#

      + + +

      Limit the amount of time the parser will wait to receive the complete HTTP +headers.

      +

      In case of inactivity, the rules defined in server.timeout apply. However, +that inactivity based timeout would still allow the connection to be kept open +if the headers are being sent very slowly (by default, up to a byte per 2 +minutes). In order to prevent this, whenever header data arrives an additional +check is made that more than server.headersTimeout milliseconds has not +passed since the connection was established. If the check fails, a 'timeout' +event is emitted on the server object, and (by default) the socket is destroyed. +See server.timeout for more information on how timeout behavior can be +customized.

      +

      A value of 0 will disable the HTTP headers timeout check.

      +

      server.listen()#

      +

      Starts the HTTP server listening for connections. +This method is identical to server.listen() from net.Server.

      +

      server.listening#

      + +
        +
      • <boolean> Indicates whether or not the server is listening for connections.
      • +
      +

      server.maxHeadersCount#

      + + +

      Limits maximum incoming headers count. If set to 0, no limit will be applied.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      Sets the timeout value for sockets, and emits a 'timeout' event on +the Server object, passing the socket as an argument, if a timeout +occurs.

      +

      If there is a 'timeout' event listener on the Server object, then it +will be called with the timed-out socket as an argument.

      +

      By default, the Server's timeout value is 2 minutes, and sockets are +destroyed automatically if they time out. However, if a callback is assigned +to the Server's 'timeout' event, timeouts must be handled explicitly.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      server.timeout#

      + +
        +
      • <number> Timeout in milliseconds. Default: 120000 (2 minutes).
      • +
      +

      The number of milliseconds of inactivity before a socket is presumed +to have timed out.

      +

      A value of 0 will disable the timeout behavior on incoming connections.

      +

      The socket timeout logic is set up on connection, so changing this +value only affects new connections to the server, not any existing connections.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      server.keepAliveTimeout#

      + +
        +
      • <number> Timeout in milliseconds. Default: 5000 (5 seconds).
      • +
      +

      The number of milliseconds of inactivity a server needs to wait for additional +incoming data, after it has finished writing the last response, before a socket +will be destroyed. If the server receives new data before the keep-alive +timeout has fired, it will reset the regular inactivity timeout, i.e., +server.timeout.

      +

      A value of 0 will disable the keep-alive timeout behavior on incoming +connections. +A value of 0 makes the http server behave similarly to Node.js versions prior +to 8.0.0, which did not have a keep-alive timeout.

      +

      The socket timeout logic is set up on connection, so changing this value only +affects new connections to the server, not any existing connections.

      +

      Class: http.ServerResponse#

      + + +

      This object is created internally by an HTTP server, not by the user. It is +passed as the second parameter to the 'request' event.

      +

      Event: 'close'#

      + +

      Indicates that the the response is completed, or its underlying connection was +terminated prematurely (before the response completion).

      +

      Event: 'finish'#

      + +

      Emitted when the response has been sent. More specifically, this event is +emitted when the last segment of the response headers and body have been +handed off to the operating system for transmission over the network. It +does not imply that the client has received anything yet.

      +

      response.addTrailers(headers)#

      + + +

      This method adds HTTP trailing headers (a header but at the end of the +message) to the response.

      +

      Trailers will only be emitted if chunked encoding is used for the +response; if it is not (e.g. if the request was HTTP/1.0), they will +be silently discarded.

      +

      HTTP requires the Trailer header to be sent in order to +emit trailers, with a list of the header fields in its value. E.g.,

      +
      response.writeHead(200, { 'Content-Type': 'text/plain',
      +                          'Trailer': 'Content-MD5' });
      +response.write(fileData);
      +response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
      +response.end();
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.connection#

      + + +

      See response.socket.

      +

      response.cork()#

      + +

      See writable.cork().

      +

      response.end([data[, encoding]][, callback])#

      + + +

      This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, response.end(), MUST be called on each response.

      +

      If data is specified, it is similar in effect to calling +response.write(data, encoding) followed by response.end(callback).

      +

      If callback is specified, it will be called when the response stream +is finished.

      +

      response.finished#

      + +

      + +

      The response.finished property will be true if response.end() +has been called.

      +

      response.flushHeaders()#

      + +

      Flushes the response headers. See also: request.flushHeaders().

      +

      response.getHeader(name)#

      + + +

      Reads out a header that's already been queued but not sent to the client. +The name is case-insensitive. The type of the return value depends +on the arguments provided to response.setHeader().

      +
      response.setHeader('Content-Type', 'text/html');
      +response.setHeader('Content-Length', Buffer.byteLength(body));
      +response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
      +const contentType = response.getHeader('content-type');
      +// contentType is 'text/html'
      +const contentLength = response.getHeader('Content-Length');
      +// contentLength is of type number
      +const setCookie = response.getHeader('set-cookie');
      +// setCookie is of type string[]
      +

      response.getHeaderNames()#

      + + +

      Returns an array containing the unique names of the current outgoing headers. +All header names are lowercase.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headerNames = response.getHeaderNames();
      +// headerNames === ['foo', 'set-cookie']
      +

      response.getHeaders()#

      + + +

      Returns a shallow copy of the current outgoing headers. Since a shallow copy +is used, array values may be mutated without additional calls to various +header-related http module methods. The keys of the returned object are the +header names and the values are the respective header values. All header names +are lowercase.

      +

      The object returned by the response.getHeaders() method does not +prototypically inherit from the JavaScript Object. This means that typical +Object methods such as obj.toString(), obj.hasOwnProperty(), and others +are not defined and will not work.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headers = response.getHeaders();
      +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      +

      response.hasHeader(name)#

      + + +

      Returns true if the header identified by name is currently set in the +outgoing headers. The header name matching is case-insensitive.

      +
      const hasContentType = response.hasHeader('content-type');
      +

      response.headersSent#

      + + +

      Boolean (read-only). True if headers were sent, false otherwise.

      +

      response.removeHeader(name)#

      + + +

      Removes a header that's queued for implicit sending.

      +
      response.removeHeader('Content-Encoding');
      +

      response.sendDate#

      + + +

      When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true.

      +

      This should only be disabled for testing; HTTP requires the Date header +in responses.

      +

      response.setHeader(name, value)#

      + + +

      Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name. Non-string values will be +stored without modification. Therefore, response.getHeader() may return +non-string values. However, the non-string values will be converted to strings +for network transmission.

      +
      response.setHeader('Content-Type', 'text/html');
      +

      or

      +
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +
      // Returns content-type = text/plain
      +const server = http.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('ok');
      +});
      +

      If response.writeHead() method is called and this method has not been +called, it will directly write the supplied header values onto the network +channel without caching internally, and the response.getHeader() on the +header will not yield the expected result. If progressive population of headers +is desired with potential future retrieval and modification, use +response.setHeader() instead of response.writeHead().

      +

      response.setTimeout(msecs[, callback])#

      + + +

      Sets the Socket's timeout value to msecs. If a callback is +provided, then it is added as a listener on the 'timeout' event on +the response object.

      +

      If no 'timeout' listener is added to the request, the response, or +the server, then sockets are destroyed when they time out. If a handler is +assigned to the request, the response, or the server's 'timeout' events, +timed out sockets must be handled explicitly.

      +

      response.socket#

      + + +

      Reference to the underlying socket. Usually users will not want to access +this property. In particular, the socket will not emit 'readable' events +because of how the protocol parser attaches to the socket. After +response.end(), the property is nulled. The socket may also be accessed +via response.connection.

      +
      const http = require('http');
      +const server = http.createServer((req, res) => {
      +  const ip = res.socket.remoteAddress;
      +  const port = res.socket.remotePort;
      +  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
      +}).listen(3000);
      +

      This property is guaranteed to be an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specified a socket +type other than <net.Socket>.

      +

      response.statusCode#

      + + +

      When using implicit headers (not calling response.writeHead() explicitly), +this property controls the status code that will be sent to the client when +the headers get flushed.

      +
      response.statusCode = 404;
      +

      After response header was sent to the client, this property indicates the +status code which was sent out.

      +

      response.statusMessage#

      + + +

      When using implicit headers (not calling response.writeHead() explicitly), +this property controls the status message that will be sent to the client when +the headers get flushed. If this is left as undefined then the standard +message for the status code will be used.

      +
      response.statusMessage = 'Not found';
      +

      After response header was sent to the client, this property indicates the +status message which was sent out.

      +

      response.uncork()#

      + +

      See writable.uncork().

      +

      response.writableEnded#

      + + +

      Is true after response.end() has been called. This property +does not indicate whether the data has been flushed, for this use +response.writableFinished instead.

      +

      response.writableFinished#

      + + +

      Is true if all data has been flushed to the underlying system, immediately +before the 'finish' event is emitted.

      +

      response.write(chunk[, encoding][, callback])#

      + + +

      If this method is called and response.writeHead() has not been called, +it will switch to implicit header mode and flush the implicit headers.

      +

      This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body.

      +

      In the http module, the response body is omitted when the +request is a HEAD request. Similarly, the 204 and 304 responses +must not include a message body.

      +

      chunk can be a string or a buffer. If chunk is a string, +the second parameter specifies how to encode it into a byte stream. +callback will be called when this chunk of data is flushed.

      +

      This is the raw HTTP body and has nothing to do with higher-level multi-part +body encodings that may be used.

      +

      The first time response.write() is called, it will send the buffered +header information and the first chunk of the body to the client. The second +time response.write() is called, Node.js assumes data will be streamed, +and sends the new data separately. That is, the response is buffered up to the +first chunk of the body.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is free again.

      +

      response.writeContinue()#

      + +

      Sends a HTTP/1.1 100 Continue message to the client, indicating that +the request body should be sent. See the 'checkContinue' event on +Server.

      +

      response.writeHead(statusCode[, statusMessage][, headers])#

      + + +

      Sends a response header to the request. The status code is a 3-digit HTTP +status code, like 404. The last argument, headers, are the response headers. +Optionally one can give a human-readable statusMessage as the second +argument.

      +

      Returns a reference to the ServerResponse, so that calls can be chained.

      +
      const body = 'hello world';
      +response
      +  .writeHead(200, {
      +    'Content-Length': Buffer.byteLength(body),
      +    'Content-Type': 'text/plain'
      +  })
      +  .end(body);
      +

      This method must only be called once on a message and it must +be called before response.end() is called.

      +

      If response.write() or response.end() are called before calling +this, the implicit/mutable headers will be calculated and call this function.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +

      If this method is called and response.setHeader() has not been called, +it will directly write the supplied header values onto the network channel +without caching internally, and the response.getHeader() on the header +will not yield the expected result. If progressive population of headers is +desired with potential future retrieval and modification, use +response.setHeader() instead.

      +
      // Returns content-type = text/plain
      +const server = http.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain' });
      +  res.end('ok');
      +});
      +

      Content-Length is given in bytes, not characters. Use +Buffer.byteLength() to determine the length of the body in bytes. Node.js +does not check whether Content-Length and the length of the body which has +been transmitted are equal or not.

      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.writeProcessing()#

      + +

      Sends a HTTP/1.1 102 Processing message to the client, indicating that +the request body should be sent.

      +

      Class: http.IncomingMessage#

      + + +

      An IncomingMessage object is created by http.Server or +http.ClientRequest and passed as the first argument to the 'request' +and 'response' event respectively. It may be used to access response +status, headers and data.

      +

      Event: 'aborted'#

      + +

      Emitted when the request has been aborted.

      +

      Event: 'close'#

      + +

      Indicates that the underlying connection was closed.

      +

      message.aborted#

      + + +

      The message.aborted property will be true if the request has +been aborted.

      +

      message.complete#

      + + +

      The message.complete property will be true if a complete HTTP message has +been received and successfully parsed.

      +

      This property is particularly useful as a means of determining if a client or +server fully transmitted a message before a connection was terminated:

      +
      const req = http.request({
      +  host: '127.0.0.1',
      +  port: 8080,
      +  method: 'POST'
      +}, (res) => {
      +  res.resume();
      +  res.on('end', () => {
      +    if (!res.complete)
      +      console.error(
      +        'The connection was terminated while the message was still being sent');
      +  });
      +});
      +

      message.destroy([error])#

      + + +

      Calls destroy() on the socket that received the IncomingMessage. If error +is provided, an 'error' event is emitted on the socket and error is passed +as an argument to any listeners on the event.

      +

      message.headers#

      + + +

      The request/response headers object.

      +

      Key-value pairs of header names and values. Header names are lower-cased.

      +
      // Prints something like:
      +//
      +// { 'user-agent': 'curl/7.22.0',
      +//   host: '127.0.0.1:8000',
      +//   accept: '*/*' }
      +console.log(request.headers);
      +

      Duplicates in raw headers are handled in the following ways, depending on the +header name:

      +
        +
      • Duplicates of age, authorization, content-length, content-type, +etag, expires, from, host, if-modified-since, if-unmodified-since, +last-modified, location, max-forwards, proxy-authorization, referer, +retry-after, server, or user-agent are discarded.
      • +
      • set-cookie is always an array. Duplicates are added to the array.
      • +
      • For duplicate cookie headers, the values are joined together with '; '.
      • +
      • For all other headers, the values are joined together with ', '.
      • +
      +

      message.httpVersion#

      + + +

      In case of server request, the HTTP version sent by the client. In the case of +client response, the HTTP version of the connected-to server. +Probably either '1.1' or '1.0'.

      +

      Also message.httpVersionMajor is the first integer and +message.httpVersionMinor is the second.

      +

      message.method#

      + + +

      Only valid for request obtained from http.Server.

      +

      The request method as a string. Read only. Examples: 'GET', 'DELETE'.

      +

      message.rawHeaders#

      + + +

      The raw request/response headers list exactly as they were received.

      +

      The keys and values are in the same list. It is not a +list of tuples. So, the even-numbered offsets are key values, and the +odd-numbered offsets are the associated values.

      +

      Header names are not lowercased, and duplicates are not merged.

      +
      // Prints something like:
      +//
      +// [ 'user-agent',
      +//   'this is invalid because there can be only one',
      +//   'User-Agent',
      +//   'curl/7.22.0',
      +//   'Host',
      +//   '127.0.0.1:8000',
      +//   'ACCEPT',
      +//   '*/*' ]
      +console.log(request.rawHeaders);
      +

      message.rawTrailers#

      + + +

      The raw request/response trailer keys and values exactly as they were +received. Only populated at the 'end' event.

      +

      message.setTimeout(msecs[, callback])#

      + + +

      Calls message.connection.setTimeout(msecs, callback).

      +

      message.socket#

      + + +

      The net.Socket object associated with the connection.

      +

      With HTTPS support, use request.socket.getPeerCertificate() to obtain the +client's authentication details.

      +

      This property is guaranteed to be an instance of the <net.Socket> class, +a subclass of <stream.Duplex>, unless the user specified a socket +type other than <net.Socket>.

      +

      message.statusCode#

      + + +

      Only valid for response obtained from http.ClientRequest.

      +

      The 3-digit HTTP response status code. E.G. 404.

      +

      message.statusMessage#

      + + +

      Only valid for response obtained from http.ClientRequest.

      +

      The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

      +

      message.trailers#

      + + +

      The request/response trailers object. Only populated at the 'end' event.

      +

      message.url#

      + + +

      Only valid for request obtained from http.Server.

      +

      Request URL string. This contains only the URL that is present in the actual +HTTP request. Take the following request:

      +
      GET /status?name=ryan HTTP/1.1
      +Accept: text/plain
      +

      To parse the URL into its parts:

      +
      new URL(request.url, `http://${request.headers.host}`);
      +

      When request.url is '/status?name=ryan' and +request.headers.host is 'localhost:3000':

      +
      $ node
      +> new URL(request.url, `http://${request.headers.host}`)
      +URL {
      +  href: 'http://localhost:3000/status?name=ryan',
      +  origin: 'http://localhost:3000',
      +  protocol: 'http:',
      +  username: '',
      +  password: '',
      +  host: 'localhost:3000',
      +  hostname: 'localhost',
      +  port: '3000',
      +  pathname: '/status',
      +  search: '?name=ryan',
      +  searchParams: URLSearchParams { 'name' => 'ryan' },
      +  hash: ''
      +}
      +

      http.METHODS#

      + + +

      A list of the HTTP methods that are supported by the parser.

      +

      http.STATUS_CODES#

      + + +

      A collection of all the standard HTTP response status codes, and the +short description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

      +

      http.createServer([options][, requestListener])#

      + +
        +
      • +

        options <Object>

        +
          +
        • IncomingMessage <http.IncomingMessage> Specifies the IncomingMessage +class to be used. Useful for extending the original IncomingMessage. +Default: IncomingMessage.
        • +
        • ServerResponse <http.ServerResponse> Specifies the ServerResponse class +to be used. Useful for extending the original ServerResponse. Default: +ServerResponse.
        • +
        • insecureHTTPParser <boolean> Use an insecure HTTP parser that accepts +invalid HTTP headers when true. Using the insecure parser should be +avoided. See --insecure-http-parser for more information. +Default: false
        • +
        +
      • +
      • +

        requestListener <Function>

        +
      • +
      • +

        Returns: <http.Server>

        +
      • +
      +

      Returns a new instance of http.Server.

      +

      The requestListener is a function which is automatically +added to the 'request' event.

      +

      http.get(options[, callback])#

      +

      http.get(url[, options][, callback])#

      + + +

      Since most requests are GET requests without bodies, Node.js provides this +convenience method. The only difference between this method and +http.request() is that it sets the method to GET and calls req.end() +automatically. The callback must take care to consume the response +data for reasons stated in http.ClientRequest section.

      +

      The callback is invoked with a single argument that is an instance of +http.IncomingMessage.

      +

      JSON fetching example:

      +
      http.get('http://nodejs.org/dist/index.json', (res) => {
      +  const { statusCode } = res;
      +  const contentType = res.headers['content-type'];
      +
      +  let error;
      +  // Any 2xx status code signals a successful response but
      +  // here we're only checking for 200.
      +  if (statusCode !== 200) {
      +    error = new Error('Request Failed.\n' +
      +                      `Status Code: ${statusCode}`);
      +  } else if (!/^application\/json/.test(contentType)) {
      +    error = new Error('Invalid content-type.\n' +
      +                      `Expected application/json but received ${contentType}`);
      +  }
      +  if (error) {
      +    console.error(error.message);
      +    // Consume response data to free up memory
      +    res.resume();
      +    return;
      +  }
      +
      +  res.setEncoding('utf8');
      +  let rawData = '';
      +  res.on('data', (chunk) => { rawData += chunk; });
      +  res.on('end', () => {
      +    try {
      +      const parsedData = JSON.parse(rawData);
      +      console.log(parsedData);
      +    } catch (e) {
      +      console.error(e.message);
      +    }
      +  });
      +}).on('error', (e) => {
      +  console.error(`Got error: ${e.message}`);
      +});
      +

      http.globalAgent#

      + + +

      Global instance of Agent which is used as the default for all HTTP client +requests.

      +

      http.maxHeaderSize#

      + + +

      Read-only property specifying the maximum allowed size of HTTP headers in bytes. +Defaults to 8KB. Configurable using the --max-http-header-size CLI option.

      +

      http.request(options[, callback])#

      +

      http.request(url[, options][, callback])#

      + +
        +
      • url <string> | <URL>
      • +
      • options <Object> +
          +
        • agent <http.Agent> | <boolean> Controls Agent behavior. Possible +values: +
            +
          • undefined (default): use http.globalAgent for this host and port.
          • +
          • Agent object: explicitly use the passed in Agent.
          • +
          • false: causes a new Agent with default values to be used.
          • +
          +
        • +
        • auth <string> Basic authentication i.e. 'user:password' to compute an +Authorization header.
        • +
        • createConnection <Function> A function that produces a socket/stream to +use for the request when the agent option is not used. This can be used to +avoid creating a custom Agent class just to override the default +createConnection function. See agent.createConnection() for more +details. Any Duplex stream is a valid return value.
        • +
        • defaultPort <number> Default port for the protocol. Default: +agent.defaultPort if an Agent is used, else undefined.
        • +
        • family <number> IP address family to use when resolving host or +hostname. Valid values are 4 or 6. When unspecified, both IP v4 and +v6 will be used.
        • +
        • headers <Object> An object containing request headers.
        • +
        • host <string> A domain name or IP address of the server to issue the +request to. Default: 'localhost'.
        • +
        • hostname <string> Alias for host. To support url.parse(), +hostname will be used if both host and hostname are specified.
        • +
        • insecureHTTPParser <boolean> Use an insecure HTTP parser that accepts +invalid HTTP headers when true. Using the insecure parser should be +avoided. See --insecure-http-parser for more information. +Default: false
        • +
        • localAddress <string> Local interface to bind for network connections.
        • +
        • lookup <Function> Custom lookup function. Default: dns.lookup().
        • +
        • method <string> A string specifying the HTTP request method. Default: +'GET'.
        • +
        • path <string> Request path. Should include query string if any. +E.G. '/index.html?page=12'. An exception is thrown when the request path +contains illegal characters. Currently, only spaces are rejected but that +may change in the future. Default: '/'.
        • +
        • port <number> Port of remote server. Default: defaultPort if set, +else 80.
        • +
        • protocol <string> Protocol to use. Default: 'http:'.
        • +
        • setHost <boolean>: Specifies whether or not to automatically add the +Host header. Defaults to true.
        • +
        • socketPath <string> Unix Domain Socket (cannot be used if one of host +or port is specified, those specify a TCP Socket).
        • +
        • timeout <number>: A number specifying the socket timeout in milliseconds. +This will set the timeout before the socket is connected.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <http.ClientRequest>
      • +
      +

      Node.js maintains several connections per server to make HTTP requests. +This function allows one to transparently issue requests.

      +

      url can be a string or a URL object. If url is a +string, it is automatically parsed with new URL(). If it is a URL +object, it will be automatically converted to an ordinary options object.

      +

      If both url and options are specified, the objects are merged, with the +options properties taking precedence.

      +

      The optional callback parameter will be added as a one-time listener for +the 'response' event.

      +

      http.request() returns an instance of the http.ClientRequest +class. The ClientRequest instance is a writable stream. If one needs to +upload a file with a POST request, then write to the ClientRequest object.

      +
      const postData = querystring.stringify({
      +  'msg': 'Hello World!'
      +});
      +
      +const options = {
      +  hostname: 'www.google.com',
      +  port: 80,
      +  path: '/upload',
      +  method: 'POST',
      +  headers: {
      +    'Content-Type': 'application/x-www-form-urlencoded',
      +    'Content-Length': Buffer.byteLength(postData)
      +  }
      +};
      +
      +const req = http.request(options, (res) => {
      +  console.log(`STATUS: ${res.statusCode}`);
      +  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      +  res.setEncoding('utf8');
      +  res.on('data', (chunk) => {
      +    console.log(`BODY: ${chunk}`);
      +  });
      +  res.on('end', () => {
      +    console.log('No more data in response.');
      +  });
      +});
      +
      +req.on('error', (e) => {
      +  console.error(`problem with request: ${e.message}`);
      +});
      +
      +// Write data to request body
      +req.write(postData);
      +req.end();
      +

      In the example req.end() was called. With http.request() one +must always call req.end() to signify the end of the request - +even if there is no data being written to the request body.

      +

      If any error is encountered during the request (be that with DNS resolution, +TCP level errors, or actual HTTP parse errors) an 'error' event is emitted +on the returned request object. As with all 'error' events, if no listeners +are registered the error will be thrown.

      +

      There are a few special headers that should be noted.

      +
        +
      • +

        Sending a 'Connection: keep-alive' will notify Node.js that the connection to +the server should be persisted until the next request.

        +
      • +
      • +

        Sending a 'Content-Length' header will disable the default chunked encoding.

        +
      • +
      • +

        Sending an 'Expect' header will immediately send the request headers. +Usually, when sending 'Expect: 100-continue', both a timeout and a listener +for the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more +information.

        +
      • +
      • +

        Sending an Authorization header will override using the auth option +to compute basic authentication.

        +
      • +
      +

      Example using a URL as options:

      +
      const options = new URL('http://abc:xyz@example.com');
      +
      +const req = http.request(options, (res) => {
      +  // ...
      +});
      +

      In a successful request, the following events will be emitted in the following +order:

      +
        +
      • 'socket'
      • +
      • 'response' +
          +
        • 'data' any number of times, on the res object +('data' will not be emitted at all if the response body is empty, for +instance, in most redirects)
        • +
        • 'end' on the res object
        • +
        +
      • +
      • 'close'
      • +
      +

      In the case of a connection error, the following events will be emitted:

      +
        +
      • 'socket'
      • +
      • 'error'
      • +
      • 'close'
      • +
      +

      If req.abort() is called before the connection succeeds, the following events +will be emitted in the following order:

      +
        +
      • 'socket'
      • +
      • (req.abort() called here)
      • +
      • 'abort'
      • +
      • 'error' with an error with message 'Error: socket hang up' and code +'ECONNRESET'
      • +
      • 'close'
      • +
      +

      If req.abort() is called after the response is received, the following events +will be emitted in the following order:

      +
        +
      • 'socket'
      • +
      • 'response' +
          +
        • 'data' any number of times, on the res object
        • +
        +
      • +
      • (req.abort() called here)
      • +
      • 'abort'
      • +
      • 'aborted' on the res object
      • +
      • 'close'
      • +
      • 'end' on the res object
      • +
      • 'close' on the res object
      • +
      +

      Setting the timeout option or using the setTimeout() function will +not abort the request or do anything besides add a 'timeout' event.

      + +
      +
      +
      + + diff --git a/doc/api/http.json b/doc/api/http.json new file mode 100644 index 0000000000000000000000000000000000000000..8b6ec78f45c0e47717bf99e7642ee1ecaa5cbf7d --- /dev/null +++ b/doc/api/http.json @@ -0,0 +1,2780 @@ +{ + "type": "module", + "source": "doc/api/http.md", + "modules": [ + { + "textRaw": "HTTP", + "name": "http", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/http.js

      \n

      To use the HTTP server and client one must require('http').

      \n

      The HTTP interfaces in Node.js are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses, so the\nuser is able to stream data.

      \n

      HTTP message headers are represented by an object like this:

      \n\n
      { 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'host': 'mysite.com',\n  'accept': '*/*' }\n
      \n

      Keys are lowercased. Values are not modified.

      \n

      In order to support the full spectrum of possible HTTP applications, the Node.js\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.

      \n

      See message.headers for details on how duplicate headers are handled.

      \n

      The raw headers as they were received are retained in the rawHeaders\nproperty, which is an array of [key, value, key2, value2, ...]. For\nexample, the previous message header object might have a rawHeaders\nlist like the following:

      \n\n
      [ 'ConTent-Length', '123456',\n  'content-LENGTH', '123',\n  'content-type', 'text/plain',\n  'CONNECTION', 'keep-alive',\n  'Host', 'mysite.com',\n  'accepT', '*/*' ]\n
      ", + "classes": [ + { + "textRaw": "Class: `http.Agent`", + "type": "class", + "name": "http.Agent", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "desc": "

      An Agent is responsible for managing connection persistence\nand reuse for HTTP clients. It maintains a queue of pending requests\nfor a given host and port, reusing a single socket connection for each\nuntil the queue is empty, at which time the socket is either destroyed\nor put into a pool where it is kept to be used again for requests to the\nsame host and port. Whether it is destroyed or pooled depends on the\nkeepAlive option.

      \n

      Pooled connections have TCP Keep-Alive enabled for them, but servers may\nstill close idle connections, in which case they will be removed from the\npool and a new connection will be made when a new HTTP request is made for\nthat host and port. Servers may also refuse to allow multiple requests\nover the same connection, in which case the connection will have to be\nremade for every request and cannot be pooled. The Agent will still make\nthe requests to that server, but each one will occur over a new connection.

      \n

      When a connection is closed by the client or the server, it is removed\nfrom the pool. Any unused sockets in the pool will be unrefed so as not\nto keep the Node.js process running when there are no outstanding requests.\n(see socket.unref()).

      \n

      It is good practice, to destroy() an Agent instance when it is no\nlonger in use, because unused sockets consume OS resources.

      \n

      Sockets are removed from an agent when the socket emits either\na 'close' event or an 'agentRemove' event. When intending to keep one\nHTTP request open for a long time without keeping it in the agent, something\nlike the following may be done:

      \n
      http.get(options, (res) => {\n  // Do stuff\n}).on('socket', (socket) => {\n  socket.emit('agentRemove');\n});\n
      \n

      An agent may also be used for an individual request. By providing\n{agent: false} as an option to the http.get() or http.request()\nfunctions, a one-time use Agent with default options will be used\nfor the client connection.

      \n

      agent:false:

      \n
      http.get({\n  hostname: 'localhost',\n  port: 80,\n  path: '/',\n  agent: false  // Create a new agent just for this one request\n}, (res) => {\n  // Do stuff with response\n});\n
      ", + "methods": [ + { + "textRaw": "`agent.createConnection(options[, callback])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Duplex}", + "name": "return", + "type": "stream.Duplex" + }, + "params": [ + { + "textRaw": "`options` {Object} Options containing connection details. Check [`net.createConnection()`][] for the format of the options", + "name": "options", + "type": "Object", + "desc": "Options containing connection details. Check [`net.createConnection()`][] for the format of the options" + }, + { + "textRaw": "`callback` {Function} Callback function that receives the created socket", + "name": "callback", + "type": "Function", + "desc": "Callback function that receives the created socket" + } + ] + } + ], + "desc": "

      Produces a socket/stream to be used for HTTP requests.

      \n

      By default, this function is the same as net.createConnection(). However,\ncustom agents may override this method in case greater flexibility is desired.

      \n

      A socket/stream can be supplied in one of two ways: by returning the\nsocket/stream from this function, or by passing the socket/stream to callback.

      \n

      This method is guaranteed to return an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      callback has a signature of (err, stream).

      " + }, + { + "textRaw": "`agent.keepSocketAlive(socket)`", + "type": "method", + "name": "keepSocketAlive", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ] + } + ], + "desc": "

      Called when socket is detached from a request and could be persisted by the\nAgent. Default behavior is to:

      \n
      socket.setKeepAlive(true, this.keepAliveMsecs);\nsocket.unref();\nreturn true;\n
      \n

      This method can be overridden by a particular Agent subclass. If this\nmethod returns a falsy value, the socket will be destroyed instead of persisting\nit for use with the next request.

      \n

      The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.

      " + }, + { + "textRaw": "`agent.reuseSocket(socket, request)`", + "type": "method", + "name": "reuseSocket", + "meta": { + "added": [ + "v8.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + }, + { + "textRaw": "`request` {http.ClientRequest}", + "name": "request", + "type": "http.ClientRequest" + } + ] + } + ], + "desc": "

      Called when socket is attached to request after being persisted because of\nthe keep-alive options. Default behavior is to:

      \n
      socket.ref();\n
      \n

      This method can be overridden by a particular Agent subclass.

      \n

      The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.

      " + }, + { + "textRaw": "`agent.destroy()`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Destroy any sockets that are currently in use by the agent.

      \n

      It is usually not necessary to do this. However, if using an\nagent with keepAlive enabled, then it is best to explicitly shut down\nthe agent when it will no longer be used. Otherwise,\nsockets may hang open for quite a long time before the server\nterminates them.

      " + }, + { + "textRaw": "`agent.getName(options)`", + "type": "method", + "name": "getName", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`options` {Object} A set of options providing information for name generation", + "name": "options", + "type": "Object", + "desc": "A set of options providing information for name generation", + "options": [ + { + "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to", + "name": "host", + "type": "string", + "desc": "A domain name or IP address of the server to issue the request to" + }, + { + "textRaw": "`port` {number} Port of remote server", + "name": "port", + "type": "number", + "desc": "Port of remote server" + }, + { + "textRaw": "`localAddress` {string} Local interface to bind for network connections when issuing the request", + "name": "localAddress", + "type": "string", + "desc": "Local interface to bind for network connections when issuing the request" + }, + { + "textRaw": "`family` {integer} Must be 4 or 6 if this doesn't equal `undefined`.", + "name": "family", + "type": "integer", + "desc": "Must be 4 or 6 if this doesn't equal `undefined`." + } + ] + } + ] + } + ], + "desc": "

      Get a unique name for a set of request options, to determine whether a\nconnection can be reused. For an HTTP agent, this returns\nhost:port:localAddress or host:port:localAddress:family. For an HTTPS agent,\nthe name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options\nthat determine socket reusability.

      " + } + ], + "properties": [ + { + "textRaw": "`freeSockets` {Object}", + "type": "Object", + "name": "freeSockets", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive is enabled. Do not modify.

      \n

      Sockets in the freeSockets list will be automatically destroyed and\nremoved from the array on 'timeout'.

      " + }, + { + "textRaw": "`maxFreeSockets` {number}", + "type": "number", + "name": "maxFreeSockets", + "meta": { + "added": [ + "v0.11.7" + ], + "changes": [] + }, + "desc": "

      By default set to 256. For agents with keepAlive enabled, this\nsets the maximum number of sockets that will be left open in the free\nstate.

      " + }, + { + "textRaw": "`maxSockets` {number}", + "type": "number", + "name": "maxSockets", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [] + }, + "desc": "

      By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is the returned value of agent.getName().

      " + }, + { + "textRaw": "`maxTotalSockets` {number}", + "type": "number", + "name": "maxTotalSockets", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open. Unlike maxSockets, this parameter applies across all origins.

      " + }, + { + "textRaw": "`requests` {Object}", + "type": "Object", + "name": "requests", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "desc": "

      An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.

      " + }, + { + "textRaw": "`sockets` {Object}", + "type": "Object", + "name": "sockets", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [] + }, + "desc": "

      An object which contains arrays of sockets currently in use by the\nagent. Do not modify.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the following fields:", + "name": "options", + "type": "Object", + "desc": "Set of configurable options to set on the agent. Can have the following fields:", + "options": [ + { + "textRaw": "`keepAlive` {boolean} Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used. **Default:** `false`.", + "name": "keepAlive", + "type": "boolean", + "default": "`false`", + "desc": "Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used." + }, + { + "textRaw": "`keepAliveMsecs` {number} When using the `keepAlive` option, specifies the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. **Default:** `1000`.", + "name": "keepAliveMsecs", + "type": "number", + "default": "`1000`", + "desc": "When using the `keepAlive` option, specifies the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`." + }, + { + "textRaw": "`maxSockets` {number} Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached. **Default:** `Infinity`.", + "name": "maxSockets", + "type": "number", + "default": "`Infinity`", + "desc": "Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached." + }, + { + "textRaw": "`maxTotalSockets` {number} Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. **Default:** `Infinity`.", + "name": "maxTotalSockets", + "type": "number", + "default": "`Infinity`", + "desc": "Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached." + }, + { + "textRaw": "`maxFreeSockets` {number} Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. **Default:** `256`.", + "name": "maxFreeSockets", + "type": "number", + "default": "`256`", + "desc": "Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`." + }, + { + "textRaw": "`scheduling` {string} Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible. **Default:** `'fifo'`.", + "name": "scheduling", + "type": "string", + "default": "`'fifo'`", + "desc": "Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible." + }, + { + "textRaw": "`timeout` {number} Socket timeout in milliseconds. This will set the timeout when the socket is created.", + "name": "timeout", + "type": "number", + "desc": "Socket timeout in milliseconds. This will set the timeout when the socket is created." + } + ] + } + ], + "desc": "

      options in socket.connect() are also supported.

      \n

      The default http.globalAgent that is used by http.request() has all\nof these values set to their respective defaults.

      \n

      To configure any of them, a custom http.Agent instance must be created.

      \n
      const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
      " + } + ] + }, + { + "textRaw": "Class: `http.ClientRequest`", + "type": "class", + "name": "http.ClientRequest", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "\n

      This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value),\ngetHeader(name), removeHeader(name) API. The actual header will\nbe sent along with the first data chunk or when calling request.end().

      \n

      To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.IncomingMessage.

      \n

      During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.

      \n

      If no 'response' handler is added, then the response will be\nentirely discarded. However, if a 'response' event handler is added,\nthen the data from the response object must be consumed, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.

      \n

      Unlike the request object, if the response closes prematurely, the\nresponse object does not emit an 'error' event but instead emits the\n'aborted' event.

      \n

      Node.js does not check whether Content-Length and the length of the\nbody which has been transmitted are equal or not.

      ", + "events": [ + { + "textRaw": "Event: `'abort'`", + "type": "event", + "name": "abort", + "meta": { + "added": [ + "v1.4.1" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`response` {http.IncomingMessage}", + "name": "response", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + }, + { + "textRaw": "`head` {Buffer}", + "name": "head", + "type": "Buffer" + } + ], + "desc": "

      Emitted each time a server responds to a request with a CONNECT method. If\nthis event is not being listened for, clients receiving a CONNECT method will\nhave their connections closed.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      A client and server pair demonstrating how to listen for the 'connect' event:

      \n
      const http = require('http');\nconst net = require('net');\nconst { URL } = require('url');\n\n// Create an HTTP tunneling proxy\nconst proxy = http.createServer((req, res) => {\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('okay');\n});\nproxy.on('connect', (req, clientSocket, head) => {\n  // Connect to an origin server\n  const { port, hostname } = new URL(`http://${req.url}`);\n  const serverSocket = net.connect(port || 80, hostname, () => {\n    clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node.js-Proxy\\r\\n' +\n                    '\\r\\n');\n    serverSocket.write(head);\n    serverSocket.pipe(clientSocket);\n    clientSocket.pipe(serverSocket);\n  });\n});\n\n// Now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n  // Make a request to a tunneling proxy\n  const options = {\n    port: 1337,\n    host: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  const req = http.request(options);\n  req.end();\n\n  req.on('connect', (res, socket, head) => {\n    console.log('got connected!');\n\n    // Make a request over an HTTP tunnel\n    socket.write('GET / HTTP/1.1\\r\\n' +\n                 'Host: www.google.com:80\\r\\n' +\n                 'Connection: close\\r\\n' +\n                 '\\r\\n');\n    socket.on('data', (chunk) => {\n      console.log(chunk.toString());\n    });\n    socket.on('end', () => {\n      proxy.close();\n    });\n  });\n});\n
      " + }, + { + "textRaw": "Event: `'continue'`", + "type": "event", + "name": "continue", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.

      " + }, + { + "textRaw": "Event: `'information'`", + "type": "event", + "name": "information", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`info` {Object}", + "name": "info", + "type": "Object", + "options": [ + { + "textRaw": "`httpVersion` {string}", + "name": "httpVersion", + "type": "string" + }, + { + "textRaw": "`httpVersionMajor` {integer}", + "name": "httpVersionMajor", + "type": "integer" + }, + { + "textRaw": "`httpVersionMinor` {integer}", + "name": "httpVersionMinor", + "type": "integer" + }, + { + "textRaw": "`statusCode` {integer}", + "name": "statusCode", + "type": "integer" + }, + { + "textRaw": "`statusMessage` {string}", + "name": "statusMessage", + "type": "string" + }, + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + }, + { + "textRaw": "`rawHeaders` {string[]}", + "name": "rawHeaders", + "type": "string[]" + } + ] + } + ], + "desc": "

      Emitted when the server sends a 1xx intermediate response (excluding 101\nUpgrade). The listeners of this event will receive an object containing the\nHTTP version, status code, status message, key-value headers object,\nand array with the raw header names followed by their respective values.

      \n
      const http = require('http');\n\nconst options = {\n  host: '127.0.0.1',\n  port: 8080,\n  path: '/length_request'\n};\n\n// Make a request\nconst req = http.request(options);\nreq.end();\n\nreq.on('information', (info) => {\n  console.log(`Got information prior to main response: ${info.statusCode}`);\n});\n
      \n

      101 Upgrade statuses do not fire this event due to their break from the\ntraditional HTTP request/response chain, such as web sockets, in-place TLS\nupgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the\n'upgrade' event instead.

      " + }, + { + "textRaw": "Event: `'response'`", + "type": "event", + "name": "response", + "meta": { + "added": [ + "v0.1.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`response` {http.IncomingMessage}", + "name": "response", + "type": "http.IncomingMessage" + } + ], + "desc": "

      Emitted when a response is received to this request. This event is emitted only\nonce.

      " + }, + { + "textRaw": "Event: `'socket'`", + "type": "event", + "name": "socket", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v0.7.8" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the underlying socket times out from inactivity. This only notifies\nthat the socket has been idle. The request must be aborted manually.

      \n

      See also: request.setTimeout().

      " + }, + { + "textRaw": "Event: `'upgrade'`", + "type": "event", + "name": "upgrade", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`response` {http.IncomingMessage}", + "name": "response", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + }, + { + "textRaw": "`head` {Buffer}", + "name": "head", + "type": "Buffer" + } + ], + "desc": "

      Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for and the response status code is 101 Switching\nProtocols, clients receiving an upgrade header will have their connections\nclosed.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      A client server pair demonstrating how to listen for the 'upgrade' event.

      \n
      const http = require('http');\n\n// Create an HTTP server\nconst server = http.createServer((req, res) => {\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('okay');\n});\nserver.on('upgrade', (req, socket, head) => {\n  socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n               'Upgrade: WebSocket\\r\\n' +\n               'Connection: Upgrade\\r\\n' +\n               '\\r\\n');\n\n  socket.pipe(socket); // echo back\n});\n\n// Now that server is running\nserver.listen(1337, '127.0.0.1', () => {\n\n  // make a request\n  const options = {\n    port: 1337,\n    host: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  const req = http.request(options);\n  req.end();\n\n  req.on('upgrade', (res, socket, upgradeHead) => {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`request.abort()`", + "type": "method", + "name": "abort", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.

      " + }, + { + "textRaw": "`request.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `ClientRequest`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.

      \n

      If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end(callback).

      \n

      If callback is specified, it will be called when the request stream\nis finished.

      " + }, + { + "textRaw": "`request.flushHeaders()`", + "type": "method", + "name": "flushHeaders", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Flushes the request headers.

      \n

      For efficiency reasons, Node.js normally buffers the request headers until\nrequest.end() is called or the first chunk of request data is written. It\nthen tries to pack the request headers and data into a single TCP packet.

      \n

      That's usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. request.flushHeaders() bypasses\nthe optimization and kickstarts the request.

      " + }, + { + "textRaw": "`request.getHeader(name)`", + "type": "method", + "name": "getHeader", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any}", + "name": "return", + "type": "any" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Reads out a header on the request. The name is case-insensitive.\nThe type of the return value depends on the arguments provided to\nrequest.setHeader().

      \n
      request.setHeader('content-type', 'text/html');\nrequest.setHeader('Content-Length', Buffer.byteLength(body));\nrequest.setHeader('Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = request.getHeader('Content-Type');\n// 'contentType' is 'text/html'\nconst contentLength = request.getHeader('Content-Length');\n// 'contentLength' is of type number\nconst cookie = request.getHeader('Cookie');\n// 'cookie' is of type string[]\n
      " + }, + { + "textRaw": "`request.removeHeader(name)`", + "type": "method", + "name": "removeHeader", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Removes a header that's already defined into headers object.

      \n
      request.removeHeader('Content-Type');\n
      " + }, + { + "textRaw": "`request.setHeader(name, value)`", + "type": "method", + "name": "setHeader", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Sets a single header value for headers object. If this header already exists in\nthe to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, request.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission.

      \n
      request.setHeader('Content-Type', 'application/json');\n
      \n

      or

      \n
      request.setHeader('Cookie', ['type=ninja', 'language=javascript']);\n
      " + }, + { + "textRaw": "`request.setNoDelay([noDelay])`", + "type": "method", + "name": "setNoDelay", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`noDelay` {boolean}", + "name": "noDelay", + "type": "boolean" + } + ] + } + ], + "desc": "

      Once a socket is assigned to this request and is connected\nsocket.setNoDelay() will be called.

      " + }, + { + "textRaw": "`request.setSocketKeepAlive([enable][, initialDelay])`", + "type": "method", + "name": "setSocketKeepAlive", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`enable` {boolean}", + "name": "enable", + "type": "boolean" + }, + { + "textRaw": "`initialDelay` {number}", + "name": "initialDelay", + "type": "number" + } + ] + } + ], + "desc": "

      Once a socket is assigned to this request and is connected\nsocket.setKeepAlive() will be called.

      " + }, + { + "textRaw": "`request.setTimeout(timeout[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8895", + "description": "Consistently set socket timeout only when the socket connects." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`timeout` {number} Milliseconds before a request times out.", + "name": "timeout", + "type": "number", + "desc": "Milliseconds before a request times out." + }, + { + "textRaw": "`callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event.", + "name": "callback", + "type": "Function", + "desc": "Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event." + } + ] + } + ], + "desc": "

      Once a socket is assigned to this request and is connected\nsocket.setTimeout() will be called.

      " + }, + { + "textRaw": "`request.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer}", + "name": "chunk", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sends a chunk of the body. By calling this method\nmany times, a request body can be sent to a\nserver. In that case, it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.

      \n

      The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.

      \n

      The callback argument is optional and will be called when this chunk of data\nis flushed, but only if the chunk is non-empty.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.

      \n

      When write function is called with empty string or buffer, it does\nnothing and waits for more input.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20230", + "description": "The `aborted` property is no longer a timestamp number." + } + ] + }, + "desc": "

      The request.aborted property will be true if the request has\nbeen aborted.

      " + }, + { + "textRaw": "`connection` {stream.Duplex}", + "type": "stream.Duplex", + "name": "connection", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      See request.socket.

      " + }, + { + "textRaw": "`finished` {boolean}", + "type": "boolean", + "name": "finished", + "meta": { + "added": [ + "v0.0.1" + ], + "deprecated": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated. Use [`request.writableEnded`][].", + "desc": "

      The request.finished property will be true if request.end()\nhas been called. request.end() will automatically be called if the\nrequest was initiated via http.get().

      " + }, + { + "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", + "type": "number", + "name": "maxHeadersCount", + "default": "`2000`", + "desc": "

      Limits maximum response headers count. If set to 0, no limit will be applied.

      " + }, + { + "textRaw": "`path` {string} The request path.", + "type": "string", + "name": "path", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "desc": "The request path." + }, + { + "textRaw": "`method` {string} The request method.", + "type": "string", + "name": "method", + "meta": { + "added": [ + "v0.1.97" + ], + "changes": [] + }, + "desc": "The request method." + }, + { + "textRaw": "`host` {string} The request host.", + "type": "string", + "name": "host", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "The request host." + }, + { + "textRaw": "`protocol` {string} The request protocol.", + "type": "string", + "name": "protocol", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "The request protocol." + }, + { + "textRaw": "`reusedSocket` {boolean} Whether the request is send through a reused socket.", + "type": "boolean", + "name": "reusedSocket", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      When sending request through a keep-alive enabled agent, the underlying socket\nmight be reused. But if server closes connection at unfortunate time, client\nmay run into a 'ECONNRESET' error.

      \n
      const http = require('http');\n\n// Server has a 5 seconds keep-alive timeout by default\nhttp\n  .createServer((req, res) => {\n    res.write('hello\\n');\n    res.end();\n  })\n  .listen(3000);\n\nsetInterval(() => {\n  // Adapting a keep-alive agent\n  http.get('http://localhost:3000', { agent }, (res) => {\n    res.on('data', (data) => {\n      // Do nothing\n    });\n  });\n}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout\n
      \n

      By marking a request whether it reused socket or not, we can do\nautomatic error retry base on it.

      \n
      const http = require('http');\nconst agent = new http.Agent({ keepAlive: true });\n\nfunction retriableRequest() {\n  const req = http\n    .get('http://localhost:3000', { agent }, (res) => {\n      // ...\n    })\n    .on('error', (err) => {\n      // Check if retry is needed\n      if (req.reusedSocket && err.code === 'ECONNRESET') {\n        retriableRequest();\n      }\n    });\n}\n\nretriableRequest();\n
      ", + "shortDesc": "Whether the request is send through a reused socket." + }, + { + "textRaw": "`socket` {stream.Duplex}", + "type": "stream.Duplex", + "name": "socket", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. The socket\nmay also be accessed via request.connection.

      \n
      const http = require('http');\nconst options = {\n  host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n  const ip = req.socket.localAddress;\n  const port = req.socket.localPort;\n  console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n  // Consume response object\n});\n
      \n

      This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after request.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nrequest.writableFinished instead.

      " + }, + { + "textRaw": "`writableFinished` {boolean}", + "type": "boolean", + "name": "writableFinished", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "desc": "

      Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.

      " + } + ] + }, + { + "textRaw": "Class: `http.Server`", + "type": "class", + "name": "http.Server", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "", + "events": [ + { + "textRaw": "Event: `'checkContinue'`", + "type": "event", + "name": "checkContinue", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage}", + "name": "request", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`response` {http.ServerResponse}", + "name": "response", + "type": "http.ServerResponse" + } + ], + "desc": "

      Emitted each time a request with an HTTP Expect: 100-continue is received.\nIf this event is not listened for, the server will automatically respond\nwith a 100 Continue as appropriate.

      \n

      Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + }, + { + "textRaw": "Event: `'checkExpectation'`", + "type": "event", + "name": "checkExpectation", + "meta": { + "added": [ + "v5.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage}", + "name": "request", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`response` {http.ServerResponse}", + "name": "response", + "type": "http.ServerResponse" + } + ], + "desc": "

      Emitted each time a request with an HTTP Expect header is received, where the\nvalue is not 100-continue. If this event is not listened for, the server will\nautomatically respond with a 417 Expectation Failed as appropriate.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + }, + { + "textRaw": "Event: `'clientError'`", + "type": "event", + "name": "clientError", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/4557", + "description": "The default action of calling `.destroy()` on the `socket` will no longer take place if there are listeners attached for `'clientError'`." + }, + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/17672", + "description": "The `rawPacket` is the current buffer that just parsed. Adding this buffer to the error object of `'clientError'` event is to make it possible that developers can log the broken packet." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/25605", + "description": "The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs." + } + ] + }, + "params": [ + { + "textRaw": "`exception` {Error}", + "name": "exception", + "type": "Error" + }, + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      If a client connection emits an 'error' event, it will be forwarded here.\nListener of this event is responsible for closing/destroying the underlying\nsocket. For example, one may wish to more gracefully close the socket with a\ncustom HTTP response instead of abruptly severing the connection.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      Default behavior is to try close the socket with a HTTP '400 Bad Request',\nor a HTTP '431 Request Header Fields Too Large' in the case of a\nHPE_HEADER_OVERFLOW error. If the socket is not writable or has already\nwritten data it is immediately destroyed.

      \n

      socket is the net.Socket object that the error originated from.

      \n
      const http = require('http');\n\nconst server = http.createServer((req, res) => {\n  res.end();\n});\nserver.on('clientError', (err, socket) => {\n  socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n
      \n

      When the 'clientError' event occurs, there is no request or response\nobject, so any HTTP response sent, including response headers and payload,\nmust be written directly to the socket object. Care must be taken to\nensure the response is a properly formatted HTTP response message.

      \n

      err is an instance of Error with two extra columns:

      \n
        \n
      • bytesParsed: the bytes count of request packet that Node.js may have parsed\ncorrectly;
      • \n
      • rawPacket: the raw packet of current request.
      • \n
      \n

      In some cases, the client has already received the response and/or the socket\nhas already been destroyed, like in case of ECONNRESET errors. Before\ntrying to send data to the socket, it is better to check that it is still\nwritable.

      \n
      server.on('clientError', (err, socket) => {\n  if (err.code === 'ECONNRESET' || !socket.writable) {\n    return;\n  }\n\n  socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\n
      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server closes.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event", + "name": "request", + "type": "http.IncomingMessage", + "desc": "Arguments for the HTTP request, as it is in the [`'request'`][] event" + }, + { + "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", + "name": "socket", + "type": "stream.Duplex", + "desc": "Network socket between the server and client" + }, + { + "textRaw": "`head` {Buffer} The first packet of the tunneling stream (may be empty)", + "name": "head", + "type": "Buffer", + "desc": "The first packet of the tunneling stream (may be empty)" + } + ], + "desc": "

      Emitted each time a client requests an HTTP CONNECT method. If this event is\nnot listened for, then clients requesting a CONNECT method will have their\nconnections closed.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      \n

      After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.

      " + }, + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v0.1.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. The socket can\nalso be accessed at request.connection.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.

      \n

      If socket.setTimeout() is called here, the timeout will be replaced with\nserver.keepAliveTimeout when the socket has served a request (if\nserver.keepAliveTimeout is non-zero).

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "Event: `'request'`", + "type": "event", + "name": "request", + "meta": { + "added": [ + "v0.1.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage}", + "name": "request", + "type": "http.IncomingMessage" + }, + { + "textRaw": "`response` {http.ServerResponse}", + "name": "response", + "type": "http.ServerResponse" + } + ], + "desc": "

      Emitted each time there is a request. There may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).

      " + }, + { + "textRaw": "Event: `'upgrade'`", + "type": "event", + "name": "upgrade", + "meta": { + "added": [ + "v0.1.94" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "v10.0.0", + "description": "Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header." + } + ] + }, + "params": [ + { + "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the [`'request'`][] event", + "name": "request", + "type": "http.IncomingMessage", + "desc": "Arguments for the HTTP request, as it is in the [`'request'`][] event" + }, + { + "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", + "name": "socket", + "type": "stream.Duplex", + "desc": "Network socket between the server and client" + }, + { + "textRaw": "`head` {Buffer} The first packet of the upgraded stream (may be empty)", + "name": "head", + "type": "Buffer", + "desc": "The first packet of the upgraded stream (may be empty)" + } + ], + "desc": "

      Emitted each time a client requests an HTTP upgrade. Listening to this event\nis optional and clients cannot insist on a protocol change.

      \n

      After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.

      \n

      This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

      " + } + ], + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Stops the server from accepting new connections. See net.Server.close().

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts the HTTP server listening for connections.\nThis method is identical to server.listen() from net.Server.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.Server}", + "name": "return", + "type": "http.Server" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.

      \n

      If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.

      \n

      By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if a callback is assigned\nto the Server's 'timeout' event, timeouts must be handled explicitly.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      " + } + ], + "properties": [ + { + "textRaw": "`headersTimeout` {number} **Default:** `60000`", + "type": "number", + "name": "headersTimeout", + "meta": { + "added": [ + "v11.3.0" + ], + "changes": [] + }, + "default": "`60000`", + "desc": "

      Limit the amount of time the parser will wait to receive the complete HTTP\nheaders.

      \n

      In case of inactivity, the rules defined in server.timeout apply. However,\nthat inactivity based timeout would still allow the connection to be kept open\nif the headers are being sent very slowly (by default, up to a byte per 2\nminutes). In order to prevent this, whenever header data arrives an additional\ncheck is made that more than server.headersTimeout milliseconds has not\npassed since the connection was established. If the check fails, a 'timeout'\nevent is emitted on the server object, and (by default) the socket is destroyed.\nSee server.timeout for more information on how timeout behavior can be\ncustomized.

      \n

      A value of 0 will disable the HTTP headers timeout check.

      " + }, + { + "textRaw": "`listening` {boolean} Indicates whether or not the server is listening for connections.", + "type": "boolean", + "name": "listening", + "meta": { + "added": [ + "v5.7.0" + ], + "changes": [] + }, + "desc": "Indicates whether or not the server is listening for connections." + }, + { + "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", + "type": "number", + "name": "maxHeadersCount", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "default": "`2000`", + "desc": "

      Limits maximum incoming headers count. If set to 0, no limit will be applied.

      " + }, + { + "textRaw": "`timeout` {number} Timeout in milliseconds. **Default:** `120000` (2 minutes).", + "type": "number", + "name": "timeout", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "default": "`120000` (2 minutes)", + "desc": "

      The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

      \n

      A value of 0 will disable the timeout behavior on incoming connections.

      \n

      The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      ", + "shortDesc": "Timeout in milliseconds." + }, + { + "textRaw": "`keepAliveTimeout` {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).", + "type": "number", + "name": "keepAliveTimeout", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "default": "`5000` (5 seconds)", + "desc": "

      The number of milliseconds of inactivity a server needs to wait for additional\nincoming data, after it has finished writing the last response, before a socket\nwill be destroyed. If the server receives new data before the keep-alive\ntimeout has fired, it will reset the regular inactivity timeout, i.e.,\nserver.timeout.

      \n

      A value of 0 will disable the keep-alive timeout behavior on incoming\nconnections.\nA value of 0 makes the http server behave similarly to Node.js versions prior\nto 8.0.0, which did not have a keep-alive timeout.

      \n

      The socket timeout logic is set up on connection, so changing this value only\naffects new connections to the server, not any existing connections.

      ", + "shortDesc": "Timeout in milliseconds." + } + ] + }, + { + "textRaw": "Class: `http.ServerResponse`", + "type": "class", + "name": "http.ServerResponse", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "\n

      This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.6.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the the response is completed, or its underlying connection was\nterminated prematurely (before the response completion).

      " + }, + { + "textRaw": "Event: `'finish'`", + "type": "event", + "name": "finish", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.

      " + } + ], + "methods": [ + { + "textRaw": "`response.addTrailers(headers)`", + "type": "method", + "name": "addTrailers", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

      \n

      Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g. if the request was HTTP/1.0), they will\nbe silently discarded.

      \n

      HTTP requires the Trailer header to be sent in order to\nemit trailers, with a list of the header fields in its value. E.g.,

      \n
      response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nresponse.end();\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.cork()`", + "type": "method", + "name": "cork", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      See writable.cork().

      " + }, + { + "textRaw": "`response.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `ServerResponse`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer}", + "name": "data", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.

      \n

      If data is specified, it is similar in effect to calling\nresponse.write(data, encoding) followed by response.end(callback).

      \n

      If callback is specified, it will be called when the response stream\nis finished.

      " + }, + { + "textRaw": "`response.flushHeaders()`", + "type": "method", + "name": "flushHeaders", + "meta": { + "added": [ + "v1.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Flushes the response headers. See also: request.flushHeaders().

      " + }, + { + "textRaw": "`response.getHeader(name)`", + "type": "method", + "name": "getHeader", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any}", + "name": "return", + "type": "any" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Reads out a header that's already been queued but not sent to the client.\nThe name is case-insensitive. The type of the return value depends\non the arguments provided to response.setHeader().

      \n
      response.setHeader('Content-Type', 'text/html');\nresponse.setHeader('Content-Length', Buffer.byteLength(body));\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = response.getHeader('content-type');\n// contentType is 'text/html'\nconst contentLength = response.getHeader('Content-Length');\n// contentLength is of type number\nconst setCookie = response.getHeader('set-cookie');\n// setCookie is of type string[]\n
      " + }, + { + "textRaw": "`response.getHeaderNames()`", + "type": "method", + "name": "getHeaderNames", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
      " + }, + { + "textRaw": "`response.getHeaders()`", + "type": "method", + "name": "getHeaders", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.

      \n

      The object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
      " + }, + { + "textRaw": "`response.hasHeader(name)`", + "type": "method", + "name": "hasHeader", + "meta": { + "added": [ + "v7.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

      \n
      const hasContentType = response.hasHeader('content-type');\n
      " + }, + { + "textRaw": "`response.removeHeader(name)`", + "type": "method", + "name": "removeHeader", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Removes a header that's queued for implicit sending.

      \n
      response.removeHeader('Content-Encoding');\n
      " + }, + { + "textRaw": "`response.setHeader(name, value)`", + "type": "method", + "name": "setHeader", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, response.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission.

      \n
      response.setHeader('Content-Type', 'text/html');\n
      \n

      or

      \n
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n
      // Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('ok');\n});\n
      \n

      If response.writeHead() method is called and this method has not been\ncalled, it will directly write the supplied header values onto the network\nchannel without caching internally, and the response.getHeader() on the\nheader will not yield the expected result. If progressive population of headers\nis desired with potential future retrieval and modification, use\nresponse.setHeader() instead of response.writeHead().

      " + }, + { + "textRaw": "`response.setTimeout(msecs[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ServerResponse}", + "name": "return", + "type": "http.ServerResponse" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.

      \n

      If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If a handler is\nassigned to the request, the response, or the server's 'timeout' events,\ntimed out sockets must be handled explicitly.

      " + }, + { + "textRaw": "`response.uncork()`", + "type": "method", + "name": "uncork", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      See writable.uncork().

      " + }, + { + "textRaw": "`response.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.29" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer}", + "name": "chunk", + "type": "string|Buffer" + }, + { + "textRaw": "`encoding` {string} **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

      \n

      This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

      \n

      In the http module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204 and 304 responses\nmust not include a message body.

      \n

      chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\ncallback will be called when this chunk of data is flushed.

      \n

      This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

      \n

      The first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.

      " + }, + { + "textRaw": "`response.writeContinue()`", + "type": "method", + "name": "writeContinue", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue' event on\nServer.

      " + }, + { + "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", + "type": "method", + "name": "writeHead", + "meta": { + "added": [ + "v0.1.30" + ], + "changes": [ + { + "version": "v11.10.0", + "pr-url": "https://github.com/nodejs/node/pull/25974", + "description": "Return `this` from `writeHead()` to allow chaining with `end()`." + }, + { + "version": "v5.11.0, v4.4.5", + "pr-url": "https://github.com/nodejs/node/pull/6291", + "description": "A `RangeError` is thrown if `statusCode` is not a number in the range `[100, 999]`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ServerResponse}", + "name": "return", + "type": "http.ServerResponse" + }, + "params": [ + { + "textRaw": "`statusCode` {number}", + "name": "statusCode", + "type": "number" + }, + { + "textRaw": "`statusMessage` {string}", + "name": "statusMessage", + "type": "string" + }, + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable statusMessage as the second\nargument.

      \n

      Returns a reference to the ServerResponse, so that calls can be chained.

      \n
      const body = 'hello world';\nresponse\n  .writeHead(200, {\n    'Content-Length': Buffer.byteLength(body),\n    'Content-Type': 'text/plain'\n  })\n  .end(body);\n
      \n

      This method must only be called once on a message and it must\nbe called before response.end() is called.

      \n

      If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n

      If this method is called and response.setHeader() has not been called,\nit will directly write the supplied header values onto the network channel\nwithout caching internally, and the response.getHeader() on the header\nwill not yield the expected result. If progressive population of headers is\ndesired with potential future retrieval and modification, use\nresponse.setHeader() instead.

      \n
      // Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end('ok');\n});\n
      \n

      Content-Length is given in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes. Node.js\ndoes not check whether Content-Length and the length of the body which has\nbeen transmitted are equal or not.

      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.writeProcessing()`", + "type": "method", + "name": "writeProcessing", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sends a HTTP/1.1 102 Processing message to the client, indicating that\nthe request body should be sent.

      " + } + ], + "properties": [ + { + "textRaw": "`connection` {stream.Duplex}", + "type": "stream.Duplex", + "name": "connection", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      See response.socket.

      " + }, + { + "textRaw": "`finished` {boolean}", + "type": "boolean", + "name": "finished", + "meta": { + "added": [ + "v0.0.2" + ], + "deprecated": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated. Use [`response.writableEnded`][].", + "desc": "

      The response.finished property will be true if response.end()\nhas been called.

      " + }, + { + "textRaw": "`headersSent` {boolean}", + "type": "boolean", + "name": "headersSent", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "desc": "

      Boolean (read-only). True if headers were sent, false otherwise.

      " + }, + { + "textRaw": "`sendDate` {boolean}", + "type": "boolean", + "name": "sendDate", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "desc": "

      When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.

      \n

      This should only be disabled for testing; HTTP requires the Date header\nin responses.

      " + }, + { + "textRaw": "`socket` {stream.Duplex}", + "type": "stream.Duplex", + "name": "socket", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. After\nresponse.end(), the property is nulled. The socket may also be accessed\nvia response.connection.

      \n
      const http = require('http');\nconst server = http.createServer((req, res) => {\n  const ip = res.socket.remoteAddress;\n  const port = res.socket.remotePort;\n  res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
      \n

      This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "`statusCode` {number} **Default:** `200`", + "type": "number", + "name": "statusCode", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "default": "`200`", + "desc": "

      When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.

      \n
      response.statusCode = 404;\n
      \n

      After response header was sent to the client, this property indicates the\nstatus code which was sent out.

      " + }, + { + "textRaw": "`statusMessage` {string}", + "type": "string", + "name": "statusMessage", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status message that will be sent to the client when\nthe headers get flushed. If this is left as undefined then the standard\nmessage for the status code will be used.

      \n
      response.statusMessage = 'Not found';\n
      \n

      After response header was sent to the client, this property indicates the\nstatus message which was sent out.

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nresponse.writableFinished instead.

      " + }, + { + "textRaw": "`writableFinished` {boolean}", + "type": "boolean", + "name": "writableFinished", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "desc": "

      Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.

      " + } + ] + }, + { + "textRaw": "Class: `http.IncomingMessage`", + "type": "class", + "name": "http.IncomingMessage", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30135", + "description": "The `readableHighWaterMark` value mirrors that of the socket." + } + ] + }, + "desc": "\n

      An IncomingMessage object is created by http.Server or\nhttp.ClientRequest and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response\nstatus, headers and data.

      ", + "events": [ + { + "textRaw": "Event: `'aborted'`", + "type": "event", + "name": "aborted", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the request has been aborted.

      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.4.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the underlying connection was closed.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v10.1.0" + ], + "changes": [] + }, + "desc": "

      The message.aborted property will be true if the request has\nbeen aborted.

      " + }, + { + "textRaw": "`complete` {boolean}", + "type": "boolean", + "name": "complete", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      The message.complete property will be true if a complete HTTP message has\nbeen received and successfully parsed.

      \n

      This property is particularly useful as a means of determining if a client or\nserver fully transmitted a message before a connection was terminated:

      \n
      const req = http.request({\n  host: '127.0.0.1',\n  port: 8080,\n  method: 'POST'\n}, (res) => {\n  res.resume();\n  res.on('end', () => {\n    if (!res.complete)\n      console.error(\n        'The connection was terminated while the message was still being sent');\n  });\n});\n
      " + }, + { + "textRaw": "`headers` {Object}", + "type": "Object", + "name": "headers", + "meta": { + "added": [ + "v0.1.5" + ], + "changes": [] + }, + "desc": "

      The request/response headers object.

      \n

      Key-value pairs of header names and values. Header names are lower-cased.

      \n
      // Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);\n
      \n

      Duplicates in raw headers are handled in the following ways, depending on the\nheader name:

      \n
        \n
      • Duplicates of age, authorization, content-length, content-type,\netag, expires, from, host, if-modified-since, if-unmodified-since,\nlast-modified, location, max-forwards, proxy-authorization, referer,\nretry-after, server, or user-agent are discarded.
      • \n
      • set-cookie is always an array. Duplicates are added to the array.
      • \n
      • For duplicate cookie headers, the values are joined together with '; '.
      • \n
      • For all other headers, the values are joined together with ', '.
      • \n
      " + }, + { + "textRaw": "`httpVersion` {string}", + "type": "string", + "name": "httpVersion", + "meta": { + "added": [ + "v0.1.1" + ], + "changes": [] + }, + "desc": "

      In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.

      \n

      Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

      " + }, + { + "textRaw": "`method` {string}", + "type": "string", + "name": "method", + "meta": { + "added": [ + "v0.1.1" + ], + "changes": [] + }, + "desc": "

      Only valid for request obtained from http.Server.

      \n

      The request method as a string. Read only. Examples: 'GET', 'DELETE'.

      " + }, + { + "textRaw": "`rawHeaders` {string[]}", + "type": "string[]", + "name": "rawHeaders", + "meta": { + "added": [ + "v0.11.6" + ], + "changes": [] + }, + "desc": "

      The raw request/response headers list exactly as they were received.

      \n

      The keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.

      \n

      Header names are not lowercased, and duplicates are not merged.

      \n
      // Prints something like:\n//\n// [ 'user-agent',\n//   'this is invalid because there can be only one',\n//   'User-Agent',\n//   'curl/7.22.0',\n//   'Host',\n//   '127.0.0.1:8000',\n//   'ACCEPT',\n//   '*/*' ]\nconsole.log(request.rawHeaders);\n
      " + }, + { + "textRaw": "`rawTrailers` {string[]}", + "type": "string[]", + "name": "rawTrailers", + "meta": { + "added": [ + "v0.11.6" + ], + "changes": [] + }, + "desc": "

      The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`socket` {stream.Duplex}", + "type": "stream.Duplex", + "name": "socket", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      The net.Socket object associated with the connection.

      \n

      With HTTPS support, use request.socket.getPeerCertificate() to obtain the\nclient's authentication details.

      \n

      This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.

      " + }, + { + "textRaw": "`statusCode` {number}", + "type": "number", + "name": "statusCode", + "meta": { + "added": [ + "v0.1.1" + ], + "changes": [] + }, + "desc": "

      Only valid for response obtained from http.ClientRequest.

      \n

      The 3-digit HTTP response status code. E.G. 404.

      " + }, + { + "textRaw": "`statusMessage` {string}", + "type": "string", + "name": "statusMessage", + "meta": { + "added": [ + "v0.11.10" + ], + "changes": [] + }, + "desc": "

      Only valid for response obtained from http.ClientRequest.

      \n

      The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

      " + }, + { + "textRaw": "`trailers` {Object}", + "type": "Object", + "name": "trailers", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      The request/response trailers object. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`url` {string}", + "type": "string", + "name": "url", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "

      Only valid for request obtained from http.Server.

      \n

      Request URL string. This contains only the URL that is present in the actual\nHTTP request. Take the following request:

      \n
      GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
      \n

      To parse the URL into its parts:

      \n
      new URL(request.url, `http://${request.headers.host}`);\n
      \n

      When request.url is '/status?name=ryan' and\nrequest.headers.host is 'localhost:3000':

      \n
      $ node\n> new URL(request.url, `http://${request.headers.host}`)\nURL {\n  href: 'http://localhost:3000/status?name=ryan',\n  origin: 'http://localhost:3000',\n  protocol: 'http:',\n  username: '',\n  password: '',\n  host: 'localhost:3000',\n  hostname: 'localhost',\n  port: '3000',\n  pathname: '/status',\n  search: '?name=ryan',\n  searchParams: URLSearchParams { 'name' => 'ryan' },\n  hash: ''\n}\n
      " + } + ], + "methods": [ + { + "textRaw": "`message.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/32789", + "description": "The function returns `this` for consistency with other Readable streams." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      Calls destroy() on the socket that received the IncomingMessage. If error\nis provided, an 'error' event is emitted on the socket and error is passed\nas an argument to any listeners on the event.

      " + }, + { + "textRaw": "`message.setTimeout(msecs[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.IncomingMessage}", + "name": "return", + "type": "http.IncomingMessage" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Calls message.connection.setTimeout(msecs, callback).

      " + } + ] + } + ], + "properties": [ + { + "textRaw": "`METHODS` {string[]}", + "type": "string[]", + "name": "METHODS", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      A list of the HTTP methods that are supported by the parser.

      " + }, + { + "textRaw": "`STATUS_CODES` {Object}", + "type": "Object", + "name": "STATUS_CODES", + "meta": { + "added": [ + "v0.1.22" + ], + "changes": [] + }, + "desc": "

      A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not Found'.

      " + }, + { + "textRaw": "`globalAgent` {http.Agent}", + "type": "http.Agent", + "name": "globalAgent", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "desc": "

      Global instance of Agent which is used as the default for all HTTP client\nrequests.

      " + }, + { + "textRaw": "`maxHeaderSize` {number}", + "type": "number", + "name": "maxHeaderSize", + "meta": { + "added": [ + "v11.6.0" + ], + "changes": [] + }, + "desc": "

      Read-only property specifying the maximum allowed size of HTTP headers in bytes.\nDefaults to 8KB. Configurable using the --max-http-header-size CLI option.

      " + } + ], + "methods": [ + { + "textRaw": "`http.createServer([options][, requestListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.1.13" + ], + "changes": [ + { + "version": "v12.15.0", + "pr-url": "https://github.com/nodejs/node/pull/31448", + "description": "The `insecureHTTPParser` option is supported now." + }, + { + "version": "v9.6.0, v8.12.0", + "pr-url": "https://github.com/nodejs/node/pull/15752", + "description": "The `options` argument is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.Server}", + "name": "return", + "type": "http.Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. **Default:** `IncomingMessage`.", + "name": "IncomingMessage", + "type": "http.IncomingMessage", + "default": "`IncomingMessage`", + "desc": "Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`." + }, + { + "textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. **Default:** `ServerResponse`.", + "name": "ServerResponse", + "type": "http.ServerResponse", + "default": "`ServerResponse`", + "desc": "Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`." + }, + { + "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", + "name": "insecureHTTPParser", + "type": "boolean", + "default": "`false`", + "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." + } + ] + }, + { + "textRaw": "`requestListener` {Function}", + "name": "requestListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Returns a new instance of http.Server.

      \n

      The requestListener is a function which is automatically\nadded to the 'request' event.

      " + }, + { + "textRaw": "`http.get(options[, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object} Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.", + "name": "options", + "type": "Object", + "desc": "Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request() is that it sets the method to GET and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.

      \n

      The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.

      \n

      JSON fetching example:

      \n
      http.get('http://nodejs.org/dist/index.json', (res) => {\n  const { statusCode } = res;\n  const contentType = res.headers['content-type'];\n\n  let error;\n  // Any 2xx status code signals a successful response but\n  // here we're only checking for 200.\n  if (statusCode !== 200) {\n    error = new Error('Request Failed.\\n' +\n                      `Status Code: ${statusCode}`);\n  } else if (!/^application\\/json/.test(contentType)) {\n    error = new Error('Invalid content-type.\\n' +\n                      `Expected application/json but received ${contentType}`);\n  }\n  if (error) {\n    console.error(error.message);\n    // Consume response data to free up memory\n    res.resume();\n    return;\n  }\n\n  res.setEncoding('utf8');\n  let rawData = '';\n  res.on('data', (chunk) => { rawData += chunk; });\n  res.on('end', () => {\n    try {\n      const parsedData = JSON.parse(rawData);\n      console.log(parsedData);\n    } catch (e) {\n      console.error(e.message);\n    }\n  });\n}).on('error', (e) => {\n  console.error(`Got error: ${e.message}`);\n});\n
      " + }, + { + "textRaw": "`http.get(url[, options][, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object} Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.", + "name": "options", + "type": "Object", + "desc": "Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request() is that it sets the method to GET and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.

      \n

      The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.

      \n

      JSON fetching example:

      \n
      http.get('http://nodejs.org/dist/index.json', (res) => {\n  const { statusCode } = res;\n  const contentType = res.headers['content-type'];\n\n  let error;\n  // Any 2xx status code signals a successful response but\n  // here we're only checking for 200.\n  if (statusCode !== 200) {\n    error = new Error('Request Failed.\\n' +\n                      `Status Code: ${statusCode}`);\n  } else if (!/^application\\/json/.test(contentType)) {\n    error = new Error('Invalid content-type.\\n' +\n                      `Expected application/json but received ${contentType}`);\n  }\n  if (error) {\n    console.error(error.message);\n    // Consume response data to free up memory\n    res.resume();\n    return;\n  }\n\n  res.setEncoding('utf8');\n  let rawData = '';\n  res.on('data', (chunk) => { rawData += chunk; });\n  res.on('end', () => {\n    try {\n      const parsedData = JSON.parse(rawData);\n      console.log(parsedData);\n    } catch (e) {\n      console.error(e.message);\n    }\n  });\n}).on('error', (e) => {\n  console.error(`Got error: ${e.message}`);\n});\n
      " + }, + { + "textRaw": "`http.request(options[, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v12.15.0", + "pr-url": "https://github.com/nodejs/node/pull/31448", + "description": "The `insecureHTTPParser` option is supported now." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible values:", + "name": "agent", + "type": "http.Agent | boolean", + "desc": "Controls [`Agent`][] behavior. Possible values:", + "options": [ + { + "textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port.", + "name": "undefined", + "desc": "(default): use [`http.globalAgent`][] for this host and port." + }, + { + "textRaw": "`Agent` object: explicitly use the passed in `Agent`.", + "name": "Agent", + "desc": "object: explicitly use the passed in `Agent`." + }, + { + "textRaw": "`false`: causes a new `Agent` with default values to be used.", + "name": "false", + "desc": "causes a new `Agent` with default values to be used." + } + ] + }, + { + "textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header.", + "name": "auth", + "type": "string", + "desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header." + }, + { + "textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value.", + "name": "createConnection", + "type": "Function", + "desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value." + }, + { + "textRaw": "`defaultPort` {number} Default port for the protocol. **Default:** `agent.defaultPort` if an `Agent` is used, else `undefined`.", + "name": "defaultPort", + "type": "number", + "default": "`agent.defaultPort` if an `Agent` is used, else `undefined`", + "desc": "Default port for the protocol." + }, + { + "textRaw": "`family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.", + "name": "family", + "type": "number", + "desc": "IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used." + }, + { + "textRaw": "`headers` {Object} An object containing request headers.", + "name": "headers", + "type": "Object", + "desc": "An object containing request headers." + }, + { + "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "A domain name or IP address of the server to issue the request to." + }, + { + "textRaw": "`hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified.", + "name": "hostname", + "type": "string", + "desc": "Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified." + }, + { + "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", + "name": "insecureHTTPParser", + "type": "boolean", + "default": "`false`", + "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." + }, + { + "textRaw": "`localAddress` {string} Local interface to bind for network connections.", + "name": "localAddress", + "type": "string", + "desc": "Local interface to bind for network connections." + }, + { + "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", + "name": "lookup", + "type": "Function", + "default": "[`dns.lookup()`][]", + "desc": "Custom lookup function." + }, + { + "textRaw": "`method` {string} A string specifying the HTTP request method. **Default:** `'GET'`.", + "name": "method", + "type": "string", + "default": "`'GET'`", + "desc": "A string specifying the HTTP request method." + }, + { + "textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. **Default:** `'/'`.", + "name": "path", + "type": "string", + "default": "`'/'`", + "desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future." + }, + { + "textRaw": "`port` {number} Port of remote server. **Default:** `defaultPort` if set, else `80`.", + "name": "port", + "type": "number", + "default": "`defaultPort` if set, else `80`", + "desc": "Port of remote server." + }, + { + "textRaw": "`protocol` {string} Protocol to use. **Default:** `'http:'`.", + "name": "protocol", + "type": "string", + "default": "`'http:'`", + "desc": "Protocol to use." + }, + { + "textRaw": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. Defaults to `true`.", + "name": "setHost", + "type": "boolean", + "desc": ": Specifies whether or not to automatically add the `Host` header. Defaults to `true`." + }, + { + "textRaw": "`socketPath` {string} Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket).", + "name": "socketPath", + "type": "string", + "desc": "Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket)." + }, + { + "textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.", + "name": "timeout", + "type": "number", + "desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

      \n

      url can be a string or a URL object. If url is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n

      If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.

      \n

      The optional callback parameter will be added as a one-time listener for\nthe 'response' event.

      \n

      http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.

      \n
      const postData = querystring.stringify({\n  'msg': 'Hello World!'\n});\n\nconst options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/x-www-form-urlencoded',\n    'Content-Length': Buffer.byteLength(postData)\n  }\n};\n\nconst req = http.request(options, (res) => {\n  console.log(`STATUS: ${res.statusCode}`);\n  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n  res.setEncoding('utf8');\n  res.on('data', (chunk) => {\n    console.log(`BODY: ${chunk}`);\n  });\n  res.on('end', () => {\n    console.log('No more data in response.');\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n
      \n

      In the example req.end() was called. With http.request() one\nmust always call req.end() to signify the end of the request -\neven if there is no data being written to the request body.

      \n

      If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object. As with all 'error' events, if no listeners\nare registered the error will be thrown.

      \n

      There are a few special headers that should be noted.

      \n
        \n
      • \n

        Sending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.

        \n
      • \n
      • \n

        Sending a 'Content-Length' header will disable the default chunked encoding.

        \n
      • \n
      • \n

        Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more\ninformation.

        \n
      • \n
      • \n

        Sending an Authorization header will override using the auth option\nto compute basic authentication.

        \n
      • \n
      \n

      Example using a URL as options:

      \n
      const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n  // ...\n});\n
      \n

      In a successful request, the following events will be emitted in the following\norder:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object\n('data' will not be emitted at all if the response body is empty, for\ninstance, in most redirects)
        • \n
        • 'end' on the res object
        • \n
        \n
      • \n
      • 'close'
      • \n
      \n

      In the case of a connection error, the following events will be emitted:

      \n
        \n
      • 'socket'
      • \n
      • 'error'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called before the connection succeeds, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called after the response is received, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object
        • \n
        \n
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'aborted' on the res object
      • \n
      • 'close'
      • \n
      • 'end' on the res object
      • \n
      • 'close' on the res object
      • \n
      \n

      Setting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.

      " + }, + { + "textRaw": "`http.request(url[, options][, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v12.15.0", + "pr-url": "https://github.com/nodejs/node/pull/31448", + "description": "The `insecureHTTPParser` option is supported now." + }, + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http.ClientRequest}", + "name": "return", + "type": "http.ClientRequest" + }, + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`agent` {http.Agent | boolean} Controls [`Agent`][] behavior. Possible values:", + "name": "agent", + "type": "http.Agent | boolean", + "desc": "Controls [`Agent`][] behavior. Possible values:", + "options": [ + { + "textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port.", + "name": "undefined", + "desc": "(default): use [`http.globalAgent`][] for this host and port." + }, + { + "textRaw": "`Agent` object: explicitly use the passed in `Agent`.", + "name": "Agent", + "desc": "object: explicitly use the passed in `Agent`." + }, + { + "textRaw": "`false`: causes a new `Agent` with default values to be used.", + "name": "false", + "desc": "causes a new `Agent` with default values to be used." + } + ] + }, + { + "textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header.", + "name": "auth", + "type": "string", + "desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header." + }, + { + "textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value.", + "name": "createConnection", + "type": "Function", + "desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. Any [`Duplex`][] stream is a valid return value." + }, + { + "textRaw": "`defaultPort` {number} Default port for the protocol. **Default:** `agent.defaultPort` if an `Agent` is used, else `undefined`.", + "name": "defaultPort", + "type": "number", + "default": "`agent.defaultPort` if an `Agent` is used, else `undefined`", + "desc": "Default port for the protocol." + }, + { + "textRaw": "`family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.", + "name": "family", + "type": "number", + "desc": "IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used." + }, + { + "textRaw": "`headers` {Object} An object containing request headers.", + "name": "headers", + "type": "Object", + "desc": "An object containing request headers." + }, + { + "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "A domain name or IP address of the server to issue the request to." + }, + { + "textRaw": "`hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified.", + "name": "hostname", + "type": "string", + "desc": "Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified." + }, + { + "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", + "name": "insecureHTTPParser", + "type": "boolean", + "default": "`false`", + "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." + }, + { + "textRaw": "`localAddress` {string} Local interface to bind for network connections.", + "name": "localAddress", + "type": "string", + "desc": "Local interface to bind for network connections." + }, + { + "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", + "name": "lookup", + "type": "Function", + "default": "[`dns.lookup()`][]", + "desc": "Custom lookup function." + }, + { + "textRaw": "`method` {string} A string specifying the HTTP request method. **Default:** `'GET'`.", + "name": "method", + "type": "string", + "default": "`'GET'`", + "desc": "A string specifying the HTTP request method." + }, + { + "textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. **Default:** `'/'`.", + "name": "path", + "type": "string", + "default": "`'/'`", + "desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future." + }, + { + "textRaw": "`port` {number} Port of remote server. **Default:** `defaultPort` if set, else `80`.", + "name": "port", + "type": "number", + "default": "`defaultPort` if set, else `80`", + "desc": "Port of remote server." + }, + { + "textRaw": "`protocol` {string} Protocol to use. **Default:** `'http:'`.", + "name": "protocol", + "type": "string", + "default": "`'http:'`", + "desc": "Protocol to use." + }, + { + "textRaw": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. Defaults to `true`.", + "name": "setHost", + "type": "boolean", + "desc": ": Specifies whether or not to automatically add the `Host` header. Defaults to `true`." + }, + { + "textRaw": "`socketPath` {string} Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket).", + "name": "socketPath", + "type": "string", + "desc": "Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket)." + }, + { + "textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.", + "name": "timeout", + "type": "number", + "desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

      \n

      url can be a string or a URL object. If url is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n

      If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.

      \n

      The optional callback parameter will be added as a one-time listener for\nthe 'response' event.

      \n

      http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.

      \n
      const postData = querystring.stringify({\n  'msg': 'Hello World!'\n});\n\nconst options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/x-www-form-urlencoded',\n    'Content-Length': Buffer.byteLength(postData)\n  }\n};\n\nconst req = http.request(options, (res) => {\n  console.log(`STATUS: ${res.statusCode}`);\n  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n  res.setEncoding('utf8');\n  res.on('data', (chunk) => {\n    console.log(`BODY: ${chunk}`);\n  });\n  res.on('end', () => {\n    console.log('No more data in response.');\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n
      \n

      In the example req.end() was called. With http.request() one\nmust always call req.end() to signify the end of the request -\neven if there is no data being written to the request body.

      \n

      If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object. As with all 'error' events, if no listeners\nare registered the error will be thrown.

      \n

      There are a few special headers that should be noted.

      \n
        \n
      • \n

        Sending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.

        \n
      • \n
      • \n

        Sending a 'Content-Length' header will disable the default chunked encoding.

        \n
      • \n
      • \n

        Sending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more\ninformation.

        \n
      • \n
      • \n

        Sending an Authorization header will override using the auth option\nto compute basic authentication.

        \n
      • \n
      \n

      Example using a URL as options:

      \n
      const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n  // ...\n});\n
      \n

      In a successful request, the following events will be emitted in the following\norder:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object\n('data' will not be emitted at all if the response body is empty, for\ninstance, in most redirects)
        • \n
        • 'end' on the res object
        • \n
        \n
      • \n
      • 'close'
      • \n
      \n

      In the case of a connection error, the following events will be emitted:

      \n
        \n
      • 'socket'
      • \n
      • 'error'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called before the connection succeeds, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
      • \n
      • 'close'
      • \n
      \n

      If req.abort() is called after the response is received, the following events\nwill be emitted in the following order:

      \n
        \n
      • 'socket'
      • \n
      • 'response'\n
          \n
        • 'data' any number of times, on the res object
        • \n
        \n
      • \n
      • (req.abort() called here)
      • \n
      • 'abort'
      • \n
      • 'aborted' on the res object
      • \n
      • 'close'
      • \n
      • 'end' on the res object
      • \n
      • 'close' on the res object
      • \n
      \n

      Setting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.

      " + } + ], + "type": "module", + "displayName": "HTTP" + } + ] +} \ No newline at end of file diff --git a/doc/api/http2.html b/doc/api/http2.html new file mode 100644 index 0000000000000000000000000000000000000000..66231b1a71b5bf9b3fa37d56f90ea283ef2cbd8d --- /dev/null +++ b/doc/api/http2.html @@ -0,0 +1,3555 @@ + + + + + + + HTTP/2 | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      HTTP/2#

      + + +

      Stability: 2 - Stable

      +

      Source Code: lib/http2.js

      +

      The http2 module provides an implementation of the HTTP/2 protocol. It +can be accessed using:

      +
      const http2 = require('http2');
      +

      Core API#

      +

      The Core API provides a low-level interface designed specifically around +support for HTTP/2 protocol features. It is specifically not designed for +compatibility with the existing HTTP/1 module API. However, +the Compatibility API is.

      +

      The http2 Core API is much more symmetric between client and server than the +http API. For instance, most events, like 'error', 'connect' and +'stream', can be emitted either by client-side code or server-side code.

      +

      Server-side example#

      +

      The following illustrates a simple HTTP/2 server using the Core API. +Since there are no browsers known that support +unencrypted HTTP/2, the use of +http2.createSecureServer() is necessary when communicating +with browser clients.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const server = http2.createSecureServer({
      +  key: fs.readFileSync('localhost-privkey.pem'),
      +  cert: fs.readFileSync('localhost-cert.pem')
      +});
      +server.on('error', (err) => console.error(err));
      +
      +server.on('stream', (stream, headers) => {
      +  // stream is a Duplex
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(8443);
      +

      To generate the certificate and key for this example, run:

      +
      openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
      +  -keyout localhost-privkey.pem -out localhost-cert.pem
      +

      Client-side example#

      +

      The following illustrates an HTTP/2 client:

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +const client = http2.connect('https://localhost:8443', {
      +  ca: fs.readFileSync('localhost-cert.pem')
      +});
      +client.on('error', (err) => console.error(err));
      +
      +const req = client.request({ ':path': '/' });
      +
      +req.on('response', (headers, flags) => {
      +  for (const name in headers) {
      +    console.log(`${name}: ${headers[name]}`);
      +  }
      +});
      +
      +req.setEncoding('utf8');
      +let data = '';
      +req.on('data', (chunk) => { data += chunk; });
      +req.on('end', () => {
      +  console.log(`\n${data}`);
      +  client.close();
      +});
      +req.end();
      +

      Class: Http2Session#

      + + +

      Instances of the http2.Http2Session class represent an active communications +session between an HTTP/2 client and server. Instances of this class are not +intended to be constructed directly by user code.

      +

      Each Http2Session instance will exhibit slightly different behaviors +depending on whether it is operating as a server or a client. The +http2session.type property can be used to determine the mode in which an +Http2Session is operating. On the server side, user code should rarely +have occasion to work with the Http2Session object directly, with most +actions typically taken through interactions with either the Http2Server or +Http2Stream objects.

      +

      User code will not create Http2Session instances directly. Server-side +Http2Session instances are created by the Http2Server instance when a +new HTTP/2 connection is received. Client-side Http2Session instances are +created using the http2.connect() method.

      +

      Http2Session and sockets#

      +

      Every Http2Session instance is associated with exactly one net.Socket or +tls.TLSSocket when it is created. When either the Socket or the +Http2Session are destroyed, both will be destroyed.

      +

      Because of the specific serialization and processing requirements imposed +by the HTTP/2 protocol, it is not recommended for user code to read data from +or write data to a Socket instance bound to a Http2Session. Doing so can +put the HTTP/2 session into an indeterminate state causing the session and +the socket to become unusable.

      +

      Once a Socket has been bound to an Http2Session, user code should rely +solely on the API of the Http2Session.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted once the Http2Session has been destroyed. Its +listener does not expect any arguments.

      +

      Event: 'connect'#

      + + +

      The 'connect' event is emitted once the Http2Session has been successfully +connected to the remote peer and communication may begin.

      +

      User code will typically not listen for this event directly.

      +

      Event: 'error'#

      + + +

      The 'error' event is emitted when an error occurs during the processing of +an Http2Session.

      +

      Event: 'frameError'#

      + +
        +
      • type <integer> The frame type.
      • +
      • code <integer> The error code.
      • +
      • id <integer> The stream id (or 0 if the frame isn't associated with a +stream).
      • +
      +

      The 'frameError' event is emitted when an error occurs while attempting to +send a frame on the session. If the frame that could not be sent is associated +with a specific Http2Stream, an attempt to emit a 'frameError' event on the +Http2Stream is made.

      +

      If the 'frameError' event is associated with a stream, the stream will be +closed and destroyed immediately following the 'frameError' event. If the +event is not associated with a stream, the Http2Session will be shut down +immediately following the 'frameError' event.

      +

      Event: 'goaway'#

      + +
        +
      • errorCode <number> The HTTP/2 error code specified in the GOAWAY frame.
      • +
      • lastStreamID <number> The ID of the last stream the remote peer successfully +processed (or 0 if no ID is specified).
      • +
      • opaqueData <Buffer> If additional opaque data was included in the GOAWAY +frame, a Buffer instance will be passed containing that data.
      • +
      +

      The 'goaway' event is emitted when a GOAWAY frame is received.

      +

      The Http2Session instance will be shut down automatically when the 'goaway' +event is emitted.

      +

      Event: 'localSettings'#

      + + +

      The 'localSettings' event is emitted when an acknowledgment SETTINGS frame +has been received.

      +

      When using http2session.settings() to submit new settings, the modified +settings do not take effect until the 'localSettings' event is emitted.

      +
      session.settings({ enablePush: false });
      +
      +session.on('localSettings', (settings) => {
      +  /* Use the new settings */
      +});
      +

      Event: 'ping'#

      + +
        +
      • payload <Buffer> The PING frame 8-byte payload
      • +
      +

      The 'ping' event is emitted whenever a PING frame is received from the +connected peer.

      +

      Event: 'remoteSettings'#

      + + +

      The 'remoteSettings' event is emitted when a new SETTINGS frame is received +from the connected peer.

      +
      session.on('remoteSettings', (settings) => {
      +  /* Use the new settings */
      +});
      +

      Event: 'stream'#

      + +
        +
      • stream <Http2Stream> A reference to the stream
      • +
      • headers <HTTP/2 Headers Object> An object describing the headers
      • +
      • flags <number> The associated numeric flags
      • +
      • rawHeaders <Array> An array containing the raw header names followed by +their respective values.
      • +
      +

      The 'stream' event is emitted when a new Http2Stream is created.

      +
      const http2 = require('http2');
      +session.on('stream', (stream, headers, flags) => {
      +  const method = headers[':method'];
      +  const path = headers[':path'];
      +  // ...
      +  stream.respond({
      +    ':status': 200,
      +    'content-type': 'text/plain; charset=utf-8'
      +  });
      +  stream.write('hello ');
      +  stream.end('world');
      +});
      +

      On the server side, user code will typically not listen for this event directly, +and would instead register a handler for the 'stream' event emitted by the +net.Server or tls.Server instances returned by http2.createServer() and +http2.createSecureServer(), respectively, as in the example below:

      +
      const http2 = require('http2');
      +
      +// Create an unencrypted HTTP/2 server
      +const server = http2.createServer();
      +
      +server.on('stream', (stream, headers) => {
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.on('error', (error) => console.error(error));
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(80);
      +

      Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, +a network error will destroy each individual stream and must be handled on the +stream level, as shown above.

      +

      Event: 'timeout'#

      + +

      After the http2session.setTimeout() method is used to set the timeout period +for this Http2Session, the 'timeout' event is emitted if there is no +activity on the Http2Session after the configured number of milliseconds. +Its listener does not expect any arguments.

      +
      session.setTimeout(2000);
      +session.on('timeout', () => { /* .. */ });
      +

      http2session.alpnProtocol#

      + + +

      Value will be undefined if the Http2Session is not yet connected to a +socket, h2c if the Http2Session is not connected to a TLSSocket, or +will return the value of the connected TLSSocket's own alpnProtocol +property.

      +

      http2session.close([callback])#

      + + +

      Gracefully closes the Http2Session, allowing any existing streams to +complete on their own and preventing new Http2Stream instances from being +created. Once closed, http2session.destroy() might be called if there +are no open Http2Stream instances.

      +

      If specified, the callback function is registered as a handler for the +'close' event.

      +

      http2session.closed#

      + + +

      Will be true if this Http2Session instance has been closed, otherwise +false.

      +

      http2session.connecting#

      + + +

      Will be true if this Http2Session instance is still connecting, will be set +to false before emitting connect event and/or calling the http2.connect +callback.

      +

      http2session.destroy([error][, code])#

      + +
        +
      • error <Error> An Error object if the Http2Session is being destroyed +due to an error.
      • +
      • code <number> The HTTP/2 error code to send in the final GOAWAY frame. +If unspecified, and error is not undefined, the default is INTERNAL_ERROR, +otherwise defaults to NO_ERROR.
      • +
      +

      Immediately terminates the Http2Session and the associated net.Socket or +tls.TLSSocket.

      +

      Once destroyed, the Http2Session will emit the 'close' event. If error +is not undefined, an 'error' event will be emitted immediately before the +'close' event.

      +

      If there are any remaining open Http2Streams associated with the +Http2Session, those will also be destroyed.

      +

      http2session.destroyed#

      + + +

      Will be true if this Http2Session instance has been destroyed and must no +longer be used, otherwise false.

      +

      http2session.encrypted#

      + + +

      Value is undefined if the Http2Session session socket has not yet been +connected, true if the Http2Session is connected with a TLSSocket, +and false if the Http2Session is connected to any other kind of socket +or stream.

      +

      http2session.goaway([code[, lastStreamID[, opaqueData]]])#

      + +
        +
      • code <number> An HTTP/2 error code
      • +
      • lastStreamID <number> The numeric ID of the last processed Http2Stream
      • +
      • opaqueData <Buffer> | <TypedArray> | <DataView> A TypedArray or DataView +instance containing additional data to be carried within the GOAWAY frame.
      • +
      +

      Transmits a GOAWAY frame to the connected peer without shutting down the +Http2Session.

      +

      http2session.localSettings#

      + + +

      A prototype-less object describing the current local settings of this +Http2Session. The local settings are local to this Http2Session instance.

      +

      http2session.originSet#

      + + +

      If the Http2Session is connected to a TLSSocket, the originSet property +will return an Array of origins for which the Http2Session may be +considered authoritative.

      +

      The originSet property is only available when using a secure TLS connection.

      +

      http2session.pendingSettingsAck#

      + + +

      Indicates whether the Http2Session is currently waiting for acknowledgment of +a sent SETTINGS frame. Will be true after calling the +http2session.settings() method. Will be false once all sent SETTINGS +frames have been acknowledged.

      +

      http2session.ping([payload, ]callback)#

      + + +

      Sends a PING frame to the connected HTTP/2 peer. A callback function must +be provided. The method will return true if the PING was sent, false +otherwise.

      +

      The maximum number of outstanding (unacknowledged) pings is determined by the +maxOutstandingPings configuration option. The default maximum is 10.

      +

      If provided, the payload must be a Buffer, TypedArray, or DataView +containing 8 bytes of data that will be transmitted with the PING and +returned with the ping acknowledgment.

      +

      The callback will be invoked with three arguments: an error argument that will +be null if the PING was successfully acknowledged, a duration argument +that reports the number of milliseconds elapsed since the ping was sent and the +acknowledgment was received, and a Buffer containing the 8-byte PING +payload.

      +
      session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
      +  if (!err) {
      +    console.log(`Ping acknowledged in ${duration} milliseconds`);
      +    console.log(`With payload '${payload.toString()}'`);
      +  }
      +});
      +

      If the payload argument is not specified, the default payload will be the +64-bit timestamp (little endian) marking the start of the PING duration.

      +

      http2session.ref()#

      + +

      Calls ref() on this Http2Session +instance's underlying net.Socket.

      +

      http2session.remoteSettings#

      + + +

      A prototype-less object describing the current remote settings of this +Http2Session. The remote settings are set by the connected HTTP/2 peer.

      +

      http2session.setTimeout(msecs, callback)#

      + + +

      Used to set a callback function that is called when there is no activity on +the Http2Session after msecs milliseconds. The given callback is +registered as a listener on the 'timeout' event.

      +

      http2session.socket#

      + + +

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but +limits available methods to ones safe to use with HTTP/2.

      +

      destroy, emit, end, pause, read, resume, and write will throw +an error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See +Http2Session and Sockets for more information.

      +

      setTimeout method will be called on this Http2Session.

      +

      All other interactions will be routed directly to the socket.

      +

      http2session.state#

      + +

      Provides miscellaneous information about the current state of the +Http2Session.

      +
        +
      • <Object> +
          +
        • effectiveLocalWindowSize <number> The current local (receive) +flow control window size for the Http2Session.
        • +
        • effectiveRecvDataLength <number> The current number of bytes +that have been received since the last flow control WINDOW_UPDATE.
        • +
        • nextStreamID <number> The numeric identifier to be used the +next time a new Http2Stream is created by this Http2Session.
        • +
        • localWindowSize <number> The number of bytes that the remote peer can +send without receiving a WINDOW_UPDATE.
        • +
        • lastProcStreamID <number> The numeric id of the Http2Stream +for which a HEADERS or DATA frame was most recently received.
        • +
        • remoteWindowSize <number> The number of bytes that this Http2Session +may send without receiving a WINDOW_UPDATE.
        • +
        • outboundQueueSize <number> The number of frames currently within the +outbound queue for this Http2Session.
        • +
        • deflateDynamicTableSize <number> The current size in bytes of the +outbound header compression state table.
        • +
        • inflateDynamicTableSize <number> The current size in bytes of the +inbound header compression state table.
        • +
        +
      • +
      +

      An object describing the current status of this Http2Session.

      +

      http2session.settings([settings][, callback])#

      + + +

      Updates the current local settings for this Http2Session and sends a new +SETTINGS frame to the connected HTTP/2 peer.

      +

      Once called, the http2session.pendingSettingsAck property will be true +while the session is waiting for the remote peer to acknowledge the new +settings.

      +

      The new settings will not become effective until the SETTINGS acknowledgment +is received and the 'localSettings' event is emitted. It is possible to send +multiple SETTINGS frames while acknowledgment is still pending.

      +

      http2session.type#

      + + +

      The http2session.type will be equal to +http2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a +server, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a +client.

      +

      http2session.unref()#

      + +

      Calls unref() on this Http2Session +instance's underlying net.Socket.

      +

      Class: ServerHttp2Session#

      + + +

      serverhttp2session.altsvc(alt, originOrStream)#

      + +
        +
      • alt <string> A description of the alternative service configuration as +defined by RFC 7838.
      • +
      • originOrStream <number> | <string> | <URL> | <Object> Either a URL string specifying +the origin (or an Object with an origin property) or the numeric +identifier of an active Http2Stream as given by the http2stream.id +property.
      • +
      +

      Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

      +
      const http2 = require('http2');
      +
      +const server = http2.createServer();
      +server.on('session', (session) => {
      +  // Set altsvc for origin https://example.org:80
      +  session.altsvc('h2=":8000"', 'https://example.org:80');
      +});
      +
      +server.on('stream', (stream) => {
      +  // Set altsvc for a specific stream
      +  stream.session.altsvc('h2=":8000"', stream.id);
      +});
      +

      Sending an ALTSVC frame with a specific stream ID indicates that the alternate +service is associated with the origin of the given Http2Stream.

      +

      The alt and origin string must contain only ASCII bytes and are +strictly interpreted as a sequence of ASCII bytes. The special value 'clear' +may be passed to clear any previously set alternative service for a given +domain.

      +

      When a string is passed for the originOrStream argument, it will be parsed as +a URL and the origin will be derived. For instance, the origin for the +HTTP URL 'https://example.org/foo/bar' is the ASCII string +'https://example.org'. An error will be thrown if either the given string +cannot be parsed as a URL or if a valid origin cannot be derived.

      +

      A URL object, or any object with an origin property, may be passed as +originOrStream, in which case the value of the origin property will be +used. The value of the origin property must be a properly serialized +ASCII origin.

      +

      Specifying alternative services#

      +

      The format of the alt parameter is strictly defined by RFC 7838 as an +ASCII string containing a comma-delimited list of "alternative" protocols +associated with a specific host and port.

      +

      For example, the value 'h2="example.org:81"' indicates that the HTTP/2 +protocol is available on the host 'example.org' on TCP/IP port 81. The +host and port must be contained within the quote (") characters.

      +

      Multiple alternatives may be specified, for instance: 'h2="example.org:81", h2=":82"'.

      +

      The protocol identifier ('h2' in the examples) may be any valid +ALPN Protocol ID.

      +

      The syntax of these values is not validated by the Node.js implementation and +are passed through as provided by the user or received from the peer.

      +

      serverhttp2session.origin(...origins)#

      + + +

      Submits an ORIGIN frame (as defined by RFC 8336) to the connected client +to advertise the set of origins for which the server is capable of providing +authoritative responses.

      +
      const http2 = require('http2');
      +const options = getSecureOptionsSomehow();
      +const server = http2.createSecureServer(options);
      +server.on('stream', (stream) => {
      +  stream.respond();
      +  stream.end('ok');
      +});
      +server.on('session', (session) => {
      +  session.origin('https://example.com', 'https://example.org');
      +});
      +

      When a string is passed as an origin, it will be parsed as a URL and the +origin will be derived. For instance, the origin for the HTTP URL +'https://example.org/foo/bar' is the ASCII string +'https://example.org'. An error will be thrown if either the given string +cannot be parsed as a URL or if a valid origin cannot be derived.

      +

      A URL object, or any object with an origin property, may be passed as +an origin, in which case the value of the origin property will be +used. The value of the origin property must be a properly serialized +ASCII origin.

      +

      Alternatively, the origins option may be used when creating a new HTTP/2 +server using the http2.createSecureServer() method:

      +
      const http2 = require('http2');
      +const options = getSecureOptionsSomehow();
      +options.origins = ['https://example.com', 'https://example.org'];
      +const server = http2.createSecureServer(options);
      +server.on('stream', (stream) => {
      +  stream.respond();
      +  stream.end('ok');
      +});
      +

      Class: ClientHttp2Session#

      + + +

      Event: 'altsvc'#

      + + +

      The 'altsvc' event is emitted whenever an ALTSVC frame is received by +the client. The event is emitted with the ALTSVC value, origin, and stream +ID. If no origin is provided in the ALTSVC frame, origin will +be an empty string.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://example.org');
      +
      +client.on('altsvc', (alt, origin, streamId) => {
      +  console.log(alt);
      +  console.log(origin);
      +  console.log(streamId);
      +});
      +

      Event: 'origin'#

      + + +

      The 'origin' event is emitted whenever an ORIGIN frame is received by +the client. The event is emitted with an array of origin strings. The +http2session.originSet will be updated to include the received +origins.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://example.org');
      +
      +client.on('origin', (origins) => {
      +  for (let n = 0; n < origins.length; n++)
      +    console.log(origins[n]);
      +});
      +

      The 'origin' event is only emitted when using a secure TLS connection.

      +

      clienthttp2session.request(headers[, options])#

      + +
        +
      • +

        headers <HTTP/2 Headers Object>

        +
      • +
      • +

        options <Object>

        +
          +
        • endStream <boolean> true if the Http2Stream writable side should +be closed initially, such as when sending a GET request that should not +expect a payload body.
        • +
        • exclusive <boolean> When true and parent identifies a parent Stream, +the created stream is made the sole direct dependency of the parent, with +all other existing dependents made a dependent of the newly created stream. +Default: false.
        • +
        • parent <number> Specifies the numeric identifier of a stream the newly +created stream is dependent on.
        • +
        • weight <number> Specifies the relative dependency of a stream in relation +to other streams with the same parent. The value is a number between 1 +and 256 (inclusive).
        • +
        • waitForTrailers <boolean> When true, the Http2Stream will emit the +'wantTrailers' event after the final DATA frame has been sent.
        • +
        +
      • +
      • +

        Returns: <ClientHttp2Stream>

        +
      • +
      +

      For HTTP/2 Client Http2Session instances only, the http2session.request() +creates and returns an Http2Stream instance that can be used to send an +HTTP/2 request to the connected server.

      +

      This method is only available if http2session.type is equal to +http2.constants.NGHTTP2_SESSION_CLIENT.

      +
      const http2 = require('http2');
      +const clientSession = http2.connect('https://localhost:1234');
      +const {
      +  HTTP2_HEADER_PATH,
      +  HTTP2_HEADER_STATUS
      +} = http2.constants;
      +
      +const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
      +req.on('response', (headers) => {
      +  console.log(headers[HTTP2_HEADER_STATUS]);
      +  req.on('data', (chunk) => { /* .. */ });
      +  req.on('end', () => { /* .. */ });
      +});
      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +is emitted immediately after queuing the last chunk of payload data to be sent. +The http2stream.sendTrailers() method can then be called to send trailing +headers to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +

      The :method and :path pseudo-headers are not specified within headers, +they respectively default to:

      +
        +
      • :method = 'GET'
      • +
      • :path = /
      • +
      +

      Class: Http2Stream#

      + + +

      Each instance of the Http2Stream class represents a bidirectional HTTP/2 +communications stream over an Http2Session instance. Any single Http2Session +may have up to 231-1 Http2Stream instances over its lifetime.

      +

      User code will not construct Http2Stream instances directly. Rather, these +are created, managed, and provided to user code through the Http2Session +instance. On the server, Http2Stream instances are created either in response +to an incoming HTTP request (and handed off to user code via the 'stream' +event), or in response to a call to the http2stream.pushStream() method. +On the client, Http2Stream instances are created and returned when either the +http2session.request() method is called, or in response to an incoming +'push' event.

      +

      The Http2Stream class is a base for the ServerHttp2Stream and +ClientHttp2Stream classes, each of which is used specifically by either +the Server or Client side, respectively.

      +

      All Http2Stream instances are Duplex streams. The Writable side of the +Duplex is used to send data to the connected peer, while the Readable side +is used to receive data sent by the connected peer.

      +

      The default text character encoding for all Http2Streams is UTF-8. As a best +practice, it is recommended that when using an Http2Stream to send text, +the 'content-type' header should be set and should identify the character +encoding used.

      +
      stream.respond({
      +  'content-type': 'text/html; charset=utf-8',
      +  ':status': 200
      +});
      +

      Http2Stream Lifecycle#

      +
      Creation#
      +

      On the server side, instances of ServerHttp2Stream are created either +when:

      +
        +
      • A new HTTP/2 HEADERS frame with a previously unused stream ID is received;
      • +
      • The http2stream.pushStream() method is called.
      • +
      +

      On the client side, instances of ClientHttp2Stream are created when the +http2session.request() method is called.

      +

      On the client, the Http2Stream instance returned by http2session.request() +may not be immediately ready for use if the parent Http2Session has not yet +been fully established. In such cases, operations called on the Http2Stream +will be buffered until the 'ready' event is emitted. User code should rarely, +if ever, need to handle the 'ready' event directly. The ready status of an +Http2Stream can be determined by checking the value of http2stream.id. If +the value is undefined, the stream is not yet ready for use.

      +
      Destruction#
      +

      All Http2Stream instances are destroyed either when:

      +
        +
      • An RST_STREAM frame for the stream is received by the connected peer, +and (for client streams only) pending data has been read.
      • +
      • The http2stream.close() method is called, and (for client streams only) +pending data has been read.
      • +
      • The http2stream.destroy() or http2session.destroy() methods are called.
      • +
      +

      When an Http2Stream instance is destroyed, an attempt will be made to send an +RST_STREAM frame to the connected peer.

      +

      When the Http2Stream instance is destroyed, the 'close' event will +be emitted. Because Http2Stream is an instance of stream.Duplex, the +'end' event will also be emitted if the stream data is currently flowing. +The 'error' event may also be emitted if http2stream.destroy() was called +with an Error passed as the first argument.

      +

      After the Http2Stream has been destroyed, the http2stream.destroyed +property will be true and the http2stream.rstCode property will specify the +RST_STREAM error code. The Http2Stream instance is no longer usable once +destroyed.

      +

      Event: 'aborted'#

      + +

      The 'aborted' event is emitted whenever a Http2Stream instance is +abnormally aborted in mid-communication. +Its listener does not expect any arguments.

      +

      The 'aborted' event will only be emitted if the Http2Stream writable side +has not been ended.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted when the Http2Stream is destroyed. Once +this event is emitted, the Http2Stream instance is no longer usable.

      +

      The HTTP/2 error code used when closing the stream can be retrieved using +the http2stream.rstCode property. If the code is any value other than +NGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.

      +

      Event: 'error'#

      + + +

      The 'error' event is emitted when an error occurs during the processing of +an Http2Stream.

      +

      Event: 'frameError'#

      + +
        +
      • type <integer> The frame type.
      • +
      • code <integer> The error code.
      • +
      • id <integer> The stream id (or 0 if the frame isn't associated with a +stream).
      • +
      +

      The 'frameError' event is emitted when an error occurs while attempting to +send a frame. When invoked, the handler function will receive an integer +argument identifying the frame type, and an integer argument identifying the +error code. The Http2Stream instance will be destroyed immediately after the +'frameError' event is emitted.

      +

      Event: 'ready'#

      + +

      The 'ready' event is emitted when the Http2Stream has been opened, has +been assigned an id, and can be used. The listener does not expect any +arguments.

      +

      Event: 'timeout'#

      + +

      The 'timeout' event is emitted after no activity is received for this +Http2Stream within the number of milliseconds set using +http2stream.setTimeout(). +Its listener does not expect any arguments.

      +

      Event: 'trailers'#

      + + +

      The 'trailers' event is emitted when a block of headers associated with +trailing header fields is received. The listener callback is passed the +HTTP/2 Headers Object and flags associated with the headers.

      +

      This event might not be emitted if http2stream.end() is called +before trailers are received and the incoming data is not being read or +listened for.

      +
      stream.on('trailers', (headers, flags) => {
      +  console.log(headers);
      +});
      +

      Event: 'wantTrailers'#

      + +

      The 'wantTrailers' event is emitted when the Http2Stream has queued the +final DATA frame to be sent on a frame and the Http2Stream is ready to send +trailing headers. When initiating a request or response, the waitForTrailers +option must be set for this event to be emitted.

      +

      http2stream.aborted#

      + + +

      Set to true if the Http2Stream instance was aborted abnormally. When set, +the 'aborted' event will have been emitted.

      +

      http2stream.bufferSize#

      + + +

      This property shows the number of characters currently buffered to be written. +See net.Socket.bufferSize for details.

      +

      http2stream.close(code[, callback])#

      + +
        +
      • code <number> Unsigned 32-bit integer identifying the error code. +Default: http2.constants.NGHTTP2_NO_ERROR (0x00).
      • +
      • callback <Function> An optional function registered to listen for the +'close' event.
      • +
      +

      Closes the Http2Stream instance by sending an RST_STREAM frame to the +connected HTTP/2 peer.

      +

      http2stream.closed#

      + + +

      Set to true if the Http2Stream instance has been closed.

      +

      http2stream.destroyed#

      + + +

      Set to true if the Http2Stream instance has been destroyed and is no longer +usable.

      +

      http2stream.endAfterHeaders#

      + + +

      Set the true if the END_STREAM flag was set in the request or response +HEADERS frame received, indicating that no additional data should be received +and the readable side of the Http2Stream will be closed.

      +

      http2stream.id#

      + + +

      The numeric stream identifier of this Http2Stream instance. Set to undefined +if the stream identifier has not yet been assigned.

      +

      http2stream.pending#

      + + +

      Set to true if the Http2Stream instance has not yet been assigned a +numeric stream identifier.

      +

      http2stream.priority(options)#

      + +
        +
      • options <Object> +
          +
        • exclusive <boolean> When true and parent identifies a parent Stream, +this stream is made the sole direct dependency of the parent, with +all other existing dependents made a dependent of this stream. Default: +false.
        • +
        • parent <number> Specifies the numeric identifier of a stream this stream +is dependent on.
        • +
        • weight <number> Specifies the relative dependency of a stream in relation +to other streams with the same parent. The value is a number between 1 +and 256 (inclusive).
        • +
        • silent <boolean> When true, changes the priority locally without +sending a PRIORITY frame to the connected peer.
        • +
        +
      • +
      +

      Updates the priority for this Http2Stream instance.

      +

      http2stream.rstCode#

      + + +

      Set to the RST_STREAM error code reported when the Http2Stream is +destroyed after either receiving an RST_STREAM frame from the connected peer, +calling http2stream.close(), or http2stream.destroy(). Will be +undefined if the Http2Stream has not been closed.

      +

      http2stream.sentHeaders#

      + + +

      An object containing the outbound headers sent for this Http2Stream.

      +

      http2stream.sentInfoHeaders#

      + + +

      An array of objects containing the outbound informational (additional) headers +sent for this Http2Stream.

      +

      http2stream.sentTrailers#

      + + +

      An object containing the outbound trailers sent for this HttpStream.

      +

      http2stream.session#

      + + +

      A reference to the Http2Session instance that owns this Http2Stream. The +value will be undefined after the Http2Stream instance is destroyed.

      +

      http2stream.setTimeout(msecs, callback)#

      + + +
      const http2 = require('http2');
      +const client = http2.connect('http://example.org:8000');
      +const { NGHTTP2_CANCEL } = http2.constants;
      +const req = client.request({ ':path': '/' });
      +
      +// Cancel the stream if there's no activity after 5 seconds
      +req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
      +

      http2stream.state#

      + +

      Provides miscellaneous information about the current state of the +Http2Stream.

      +
        +
      • <Object> +
          +
        • localWindowSize <number> The number of bytes the connected peer may send +for this Http2Stream without receiving a WINDOW_UPDATE.
        • +
        • state <number> A flag indicating the low-level current state of the +Http2Stream as determined by nghttp2.
        • +
        • localClose <number> 1 if this Http2Stream has been closed locally.
        • +
        • remoteClose <number> 1 if this Http2Stream has been closed +remotely.
        • +
        • sumDependencyWeight <number> The sum weight of all Http2Stream +instances that depend on this Http2Stream as specified using +PRIORITY frames.
        • +
        • weight <number> The priority weight of this Http2Stream.
        • +
        +
      • +
      +

      A current state of this Http2Stream.

      +

      http2stream.sendTrailers(headers)#

      + + +

      Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method +will cause the Http2Stream to be immediately closed and must only be +called after the 'wantTrailers' event has been emitted. When sending a +request or sending a response, the options.waitForTrailers option must be set +in order to keep the Http2Stream open after the final DATA frame so that +trailers can be sent.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond(undefined, { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ xyz: 'abc' });
      +  });
      +  stream.end('Hello World');
      +});
      +

      The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header +fields (e.g. ':method', ':path', etc).

      +

      Class: ClientHttp2Stream#

      + + +

      The ClientHttp2Stream class is an extension of Http2Stream that is +used exclusively on HTTP/2 Clients. Http2Stream instances on the client +provide events such as 'response' and 'push' that are only relevant on +the client.

      +

      Event: 'continue'#

      + +

      Emitted when the server sends a 100 Continue status, usually because +the request contained Expect: 100-continue. This is an instruction that +the client should send the request body.

      +

      Event: 'headers'#

      + +

      The 'headers' event is emitted when an additional block of headers is received +for a stream, such as when a block of 1xx informational headers is received. +The listener callback is passed the HTTP/2 Headers Object and flags +associated with the headers.

      +
      stream.on('headers', (headers, flags) => {
      +  console.log(headers);
      +});
      +

      Event: 'push'#

      + +

      The 'push' event is emitted when response headers for a Server Push stream +are received. The listener callback is passed the HTTP/2 Headers Object and +flags associated with the headers.

      +
      stream.on('push', (headers, flags) => {
      +  console.log(headers);
      +});
      +

      Event: 'response'#

      + +

      The 'response' event is emitted when a response HEADERS frame has been +received for this stream from the connected HTTP/2 server. The listener is +invoked with two arguments: an Object containing the received +HTTP/2 Headers Object, and flags associated with the headers.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://localhost');
      +const req = client.request({ ':path': '/' });
      +req.on('response', (headers, flags) => {
      +  console.log(headers[':status']);
      +});
      +

      Class: ServerHttp2Stream#

      + + +

      The ServerHttp2Stream class is an extension of Http2Stream that is +used exclusively on HTTP/2 Servers. Http2Stream instances on the server +provide additional methods such as http2stream.pushStream() and +http2stream.respond() that are only relevant on the server.

      +

      http2stream.additionalHeaders(headers)#

      + + +

      Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

      +

      http2stream.headersSent#

      + + +

      True if headers were sent, false otherwise (read-only).

      +

      http2stream.pushAllowed#

      + + +

      Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote +client's most recent SETTINGS frame. Will be true if the remote peer +accepts push streams, false otherwise. Settings are the same for every +Http2Stream in the same Http2Session.

      +

      http2stream.pushStream(headers[, options], callback)#

      + +
        +
      • headers <HTTP/2 Headers Object>
      • +
      • options <Object> +
          +
        • exclusive <boolean> When true and parent identifies a parent Stream, +the created stream is made the sole direct dependency of the parent, with +all other existing dependents made a dependent of the newly created stream. +Default: false.
        • +
        • parent <number> Specifies the numeric identifier of a stream the newly +created stream is dependent on.
        • +
        +
      • +
      • callback <Function> Callback that is called once the push stream has been +initiated. + +
      • +
      +

      Initiates a push stream. The callback is invoked with the new Http2Stream +instance created for the push stream passed as the second argument, or an +Error passed as the first argument.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond({ ':status': 200 });
      +  stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
      +    if (err) throw err;
      +    pushStream.respond({ ':status': 200 });
      +    pushStream.end('some pushed data');
      +  });
      +  stream.end('some data');
      +});
      +

      Setting the weight of a push stream is not allowed in the HEADERS frame. Pass +a weight value to http2stream.priority with the silent option set to +true to enable server-side bandwidth balancing between concurrent streams.

      +

      Calling http2stream.pushStream() from within a pushed stream is not permitted +and will throw an error.

      +

      http2stream.respond([headers[, options]])#

      + +
        +
      • headers <HTTP/2 Headers Object>
      • +
      • options <Object> +
          +
        • endStream <boolean> Set to true to indicate that the response will not +include payload data.
        • +
        • waitForTrailers <boolean> When true, the Http2Stream will emit the +'wantTrailers' event after the final DATA frame has been sent.
        • +
        +
      • +
      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond({ ':status': 200 });
      +  stream.end('some data');
      +});
      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +will be emitted immediately after queuing the last chunk of payload data to be +sent. The http2stream.sendTrailers() method can then be used to sent trailing +header fields to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respond({ ':status': 200 }, { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ ABC: 'some value to send' });
      +  });
      +  stream.end('some data');
      +});
      +

      http2stream.respondWithFD(fd[, headers[, options]])#

      + + +

      Initiates a response whose data is read from the given file descriptor. No +validation is performed on the given file descriptor. If an error occurs while +attempting to read data using the file descriptor, the Http2Stream will be +closed using an RST_STREAM frame using the standard INTERNAL_ERROR code.

      +

      When used, the Http2Stream object's Duplex interface will be closed +automatically.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  const fd = fs.openSync('/some/file', 'r');
      +
      +  const stat = fs.fstatSync(fd);
      +  const headers = {
      +    'content-length': stat.size,
      +    'last-modified': stat.mtime.toUTCString(),
      +    'content-type': 'text/plain; charset=utf-8'
      +  };
      +  stream.respondWithFD(fd, headers);
      +  stream.on('close', () => fs.closeSync(fd));
      +});
      +

      The optional options.statCheck function may be specified to give user code +an opportunity to set additional content headers based on the fs.Stat details +of the given fd. If the statCheck function is provided, the +http2stream.respondWithFD() method will perform an fs.fstat() call to +collect details on the provided file descriptor.

      +

      The offset and length options may be used to limit the response to a +specific range subset. This can be used, for instance, to support HTTP Range +requests.

      +

      The file descriptor or FileHandle is not closed when the stream is closed, +so it will need to be closed manually once it is no longer needed. +Using the same file descriptor concurrently for multiple streams +is not supported and may result in data loss. Re-using a file descriptor +after a stream has finished is supported.

      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +will be emitted immediately after queuing the last chunk of payload data to be +sent. The http2stream.sendTrailers() method can then be used to sent trailing +header fields to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  const fd = fs.openSync('/some/file', 'r');
      +
      +  const stat = fs.fstatSync(fd);
      +  const headers = {
      +    'content-length': stat.size,
      +    'last-modified': stat.mtime.toUTCString(),
      +    'content-type': 'text/plain; charset=utf-8'
      +  };
      +  stream.respondWithFD(fd, headers, { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ ABC: 'some value to send' });
      +  });
      +
      +  stream.on('close', () => fs.closeSync(fd));
      +});
      +

      http2stream.respondWithFile(path[, headers[, options]])#

      + + +

      Sends a regular file as the response. The path must specify a regular file +or an 'error' event will be emitted on the Http2Stream object.

      +

      When used, the Http2Stream object's Duplex interface will be closed +automatically.

      +

      The optional options.statCheck function may be specified to give user code +an opportunity to set additional content headers based on the fs.Stat details +of the given file:

      +

      If an error occurs while attempting to read the file data, the Http2Stream +will be closed using an RST_STREAM frame using the standard INTERNAL_ERROR +code. If the onError callback is defined, then it will be called. Otherwise +the stream will be destroyed.

      +

      Example using a file path:

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  function statCheck(stat, headers) {
      +    headers['last-modified'] = stat.mtime.toUTCString();
      +  }
      +
      +  function onError(err) {
      +    if (err.code === 'ENOENT') {
      +      stream.respond({ ':status': 404 });
      +    } else {
      +      stream.respond({ ':status': 500 });
      +    }
      +    stream.end();
      +  }
      +
      +  stream.respondWithFile('/some/file',
      +                         { 'content-type': 'text/plain; charset=utf-8' },
      +                         { statCheck, onError });
      +});
      +

      The options.statCheck function may also be used to cancel the send operation +by returning false. For instance, a conditional request may check the stat +results to determine if the file has been modified to return an appropriate +304 response:

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  function statCheck(stat, headers) {
      +    // Check the stat here...
      +    stream.respond({ ':status': 304 });
      +    return false; // Cancel the send operation
      +  }
      +  stream.respondWithFile('/some/file',
      +                         { 'content-type': 'text/plain; charset=utf-8' },
      +                         { statCheck });
      +});
      +

      The content-length header field will be automatically set.

      +

      The offset and length options may be used to limit the response to a +specific range subset. This can be used, for instance, to support HTTP Range +requests.

      +

      The options.onError function may also be used to handle all the errors +that could happen before the delivery of the file is initiated. The +default behavior is to destroy the stream.

      +

      When the options.waitForTrailers option is set, the 'wantTrailers' event +will be emitted immediately after queuing the last chunk of payload data to be +sent. The http2stream.sendTrailers() method can then be used to sent trailing +header fields to the peer.

      +

      When options.waitForTrailers is set, the Http2Stream will not automatically +close when the final DATA frame is transmitted. User code must call either +http2stream.sendTrailers() or http2stream.close() to close the +Http2Stream.

      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream) => {
      +  stream.respondWithFile('/some/file',
      +                         { 'content-type': 'text/plain; charset=utf-8' },
      +                         { waitForTrailers: true });
      +  stream.on('wantTrailers', () => {
      +    stream.sendTrailers({ ABC: 'some value to send' });
      +  });
      +});
      +

      Class: Http2Server#

      + + +

      Instances of Http2Server are created using the http2.createServer() +function. The Http2Server class is not exported directly by the http2 +module.

      +

      Event: 'checkContinue'#

      + + +

      If a 'request' listener is registered or http2.createServer() is +supplied a callback function, the 'checkContinue' event is emitted each time +a request with an HTTP Expect: 100-continue is received. If this event is +not listened for, the server will automatically respond with a status +100 Continue as appropriate.

      +

      Handling this event involves calling response.writeContinue() if the +client should continue to send the request body, or generating an appropriate +HTTP response (e.g. 400 Bad Request) if the client should not continue to send +the request body.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established. socket is +typically an object of type net.Socket. Usually users will not want to +access this event.

      +

      This event can also be explicitly emitted by users to inject connections +into the HTTP server. In that case, any Duplex stream can be passed.

      +

      Event: 'request'#

      + + +

      Emitted each time there is a request. There may be multiple requests +per session. See the Compatibility API.

      +

      Event: 'session'#

      + +

      The 'session' event is emitted when a new Http2Session is created by the +Http2Server.

      +

      Event: 'sessionError'#

      + +

      The 'sessionError' event is emitted when an 'error' event is emitted by +an Http2Session object associated with the Http2Server.

      +

      Event: 'stream'#

      + +

      The 'stream' event is emitted when a 'stream' event has been emitted by +an Http2Session associated with the server.

      +
      const http2 = require('http2');
      +const {
      +  HTTP2_HEADER_METHOD,
      +  HTTP2_HEADER_PATH,
      +  HTTP2_HEADER_STATUS,
      +  HTTP2_HEADER_CONTENT_TYPE
      +} = http2.constants;
      +
      +const server = http2.createServer();
      +server.on('stream', (stream, headers, flags) => {
      +  const method = headers[HTTP2_HEADER_METHOD];
      +  const path = headers[HTTP2_HEADER_PATH];
      +  // ...
      +  stream.respond({
      +    [HTTP2_HEADER_STATUS]: 200,
      +    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
      +  });
      +  stream.write('hello ');
      +  stream.end('world');
      +});
      +

      Event: 'timeout'#

      + +

      The 'timeout' event is emitted when there is no activity on the Server for +a given number of milliseconds set using http2server.setTimeout(). +Default: 2 minutes.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      server.close([callback])#

      + + +

      Stops the server from establishing new sessions. This does not prevent new +request streams from being created due to the persistent nature of HTTP/2 +sessions. To gracefully shut down the server, call http2session.close() on +all active sessions.

      +

      If callback is provided, it is not invoked until all active sessions have been +closed, although the server has already stopped allowing new sessions. See +net.Server.close() for more details.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      Used to set the timeout value for http2 server requests, +and sets a callback function that is called when there is no activity +on the Http2Server after msecs milliseconds.

      +

      The given callback is registered as a listener on the 'timeout' event.

      +

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK +error will be thrown.

      +

      To change the default timeout use the --http-server-default-timeout +flag.

      +

      Class: Http2SecureServer#

      + + +

      Instances of Http2SecureServer are created using the +http2.createSecureServer() function. The Http2SecureServer class is not +exported directly by the http2 module.

      +

      Event: 'checkContinue'#

      + + +

      If a 'request' listener is registered or http2.createSecureServer() +is supplied a callback function, the 'checkContinue' event is emitted each +time a request with an HTTP Expect: 100-continue is received. If this event +is not listened for, the server will automatically respond with a status +100 Continue as appropriate.

      +

      Handling this event involves calling response.writeContinue() if the +client should continue to send the request body, or generating an appropriate +HTTP response (e.g. 400 Bad Request) if the client should not continue to send +the request body.

      +

      When this event is emitted and handled, the 'request' event will +not be emitted.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established, before the TLS +handshake begins. socket is typically an object of type net.Socket. +Usually users will not want to access this event.

      +

      This event can also be explicitly emitted by users to inject connections +into the HTTP server. In that case, any Duplex stream can be passed.

      +

      Event: 'request'#

      + + +

      Emitted each time there is a request. There may be multiple requests +per session. See the Compatibility API.

      +

      Event: 'session'#

      + +

      The 'session' event is emitted when a new Http2Session is created by the +Http2SecureServer.

      +

      Event: 'sessionError'#

      + +

      The 'sessionError' event is emitted when an 'error' event is emitted by +an Http2Session object associated with the Http2SecureServer.

      +

      Event: 'stream'#

      + +

      The 'stream' event is emitted when a 'stream' event has been emitted by +an Http2Session associated with the server.

      +
      const http2 = require('http2');
      +const {
      +  HTTP2_HEADER_METHOD,
      +  HTTP2_HEADER_PATH,
      +  HTTP2_HEADER_STATUS,
      +  HTTP2_HEADER_CONTENT_TYPE
      +} = http2.constants;
      +
      +const options = getOptionsSomehow();
      +
      +const server = http2.createSecureServer(options);
      +server.on('stream', (stream, headers, flags) => {
      +  const method = headers[HTTP2_HEADER_METHOD];
      +  const path = headers[HTTP2_HEADER_PATH];
      +  // ...
      +  stream.respond({
      +    [HTTP2_HEADER_STATUS]: 200,
      +    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
      +  });
      +  stream.write('hello ');
      +  stream.end('world');
      +});
      +

      Event: 'timeout'#

      + +

      The 'timeout' event is emitted when there is no activity on the Server for +a given number of milliseconds set using http2secureServer.setTimeout(). +Default: 2 minutes.

      +

      Event: 'unknownProtocol'#

      + +

      The 'unknownProtocol' event is emitted when a connecting client fails to +negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler +receives the socket for handling. If no listener is registered for this event, +the connection is terminated. A timeout may be specified using the +'unknownProtocolTimeout' option passed to http2.createSecureServer(). +See the Compatibility API.

      +

      server.close([callback])#

      + + +

      Stops the server from establishing new sessions. This does not prevent new +request streams from being created due to the persistent nature of HTTP/2 +sessions. To gracefully shut down the server, call http2session.close() on +all active sessions.

      +

      If callback is provided, it is not invoked until all active sessions have been +closed, although the server has already stopped allowing new sessions. See +tls.Server.close() for more details.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      Used to set the timeout value for http2 secure server requests, +and sets a callback function that is called when there is no activity +on the Http2SecureServer after msecs milliseconds.

      +

      The given callback is registered as a listener on the 'timeout' event.

      +

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK +error will be thrown.

      +

      http2.createServer(options[, onRequestHandler])#

      + +
        +
      • options <Object> +
          +
        • maxDeflateDynamicTableSize <number> Sets the maximum dynamic table size +for deflating header fields. Default: 4Kib.
        • +
        • maxSettings <number> Sets the maximum number of settings entries per +SETTINGS frame. The minimum value allowed is 1. Default: 32.
        • +
        • maxSessionMemory<number> Sets the maximum memory that the Http2Session +is permitted to use. The value is expressed in terms of number of megabytes, +e.g. 1 equal 1 megabyte. The minimum value allowed is 1. +This is a credit based limit, existing Http2Streams may cause this +limit to be exceeded, but new Http2Stream instances will be rejected +while this limit is exceeded. The current number of Http2Stream sessions, +the current memory use of the header compression tables, current data +queued to be sent, and unacknowledged PING and SETTINGS frames are all +counted towards the current limit. Default: 10.
        • +
        • maxHeaderListPairs <number> Sets the maximum number of header entries. +This is similar to http.Server#maxHeadersCount or +http.ClientRequest#maxHeadersCount. The minimum value is 4. +Default: 128.
        • +
        • maxOutstandingPings <number> Sets the maximum number of outstanding, +unacknowledged pings. Default: 10.
        • +
        • maxSendHeaderBlockLength <number> Sets the maximum allowed size for a +serialized, compressed block of headers. Attempts to send headers that +exceed this limit will result in a 'frameError' event being emitted +and the stream being closed and destroyed.
        • +
        • paddingStrategy <number> The strategy used for determining the amount of +padding to use for HEADERS and DATA frames. Default: +http2.constants.PADDING_STRATEGY_NONE. Value may be one of: +
            +
          • http2.constants.PADDING_STRATEGY_NONE: Specifies that no padding is +to be applied.
          • +
          • http2.constants.PADDING_STRATEGY_MAX: Specifies that the maximum +amount of padding, as determined by the internal implementation, is to +be applied.
          • +
          • http2.constants.PADDING_STRATEGY_CALLBACK: Specifies that the user +provided options.selectPadding() callback is to be used to determine +the amount of padding.
          • +
          • http2.constants.PADDING_STRATEGY_ALIGNED: Will attempt to apply +enough padding to ensure that the total frame length, including the +9-byte header, is a multiple of 8. For each frame, however, there is a +maximum allowed number of padding bytes that is determined by current +flow control state and settings. If this maximum is less than the +calculated amount needed to ensure alignment, the maximum will be used +and the total frame length will not necessarily be aligned at 8 bytes.
          • +
          +
        • +
        • peerMaxConcurrentStreams <number> Sets the maximum number of concurrent +streams for the remote peer as if a SETTINGS frame had been received. Will +be overridden if the remote peer sets its own value for +maxConcurrentStreams. Default: 100.
        • +
        • maxSessionInvalidFrames <integer> Sets the maximum number of invalid +frames that will be tolerated before the session is closed. +Default: 1000.
        • +
        • maxSessionRejectedStreams <integer> Sets the maximum number of rejected +upon creation streams that will be tolerated before the session is closed. +Each rejection is associated with an NGHTTP2_ENHANCE_YOUR_CALM +error that should tell the peer to not open any more streams, continuing +to open streams is therefore regarded as a sign of a misbehaving peer. +Default: 100.
        • +
        • selectPadding <Function> When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, provides the callback function +used to determine the padding. See Using options.selectPadding().
        • +
        • settings <HTTP/2 Settings Object> The initial settings to send to the +remote peer upon connection.
        • +
        • Http1IncomingMessage <http.IncomingMessage> Specifies the +IncomingMessage class to used for HTTP/1 fallback. Useful for extending +the original http.IncomingMessage. Default: http.IncomingMessage.
        • +
        • Http1ServerResponse <http.ServerResponse> Specifies the ServerResponse +class to used for HTTP/1 fallback. Useful for extending the original +http.ServerResponse. Default: http.ServerResponse.
        • +
        • Http2ServerRequest <http2.Http2ServerRequest> Specifies the +Http2ServerRequest class to use. +Useful for extending the original Http2ServerRequest. +Default: Http2ServerRequest.
        • +
        • Http2ServerResponse <http2.Http2ServerResponse> Specifies the +Http2ServerResponse class to use. +Useful for extending the original Http2ServerResponse. +Default: Http2ServerResponse.
        • +
        • unknownProtocolTimeout <number> Specifies a timeout in milliseconds that +a server should wait when an 'unknownProtocol' is emitted. If the +socket has not been destroyed by that time the server will destroy it. +Default: 10000.
        • +
        • ...: Any net.createServer() option can be provided.
        • +
        +
      • +
      • onRequestHandler <Function> See Compatibility API
      • +
      • Returns: <Http2Server>
      • +
      +

      Returns a net.Server instance that creates and manages Http2Session +instances.

      +

      Since there are no browsers known that support +unencrypted HTTP/2, the use of +http2.createSecureServer() is necessary when communicating +with browser clients.

      +
      const http2 = require('http2');
      +
      +// Create an unencrypted HTTP/2 server.
      +// Since there are no browsers known that support
      +// unencrypted HTTP/2, the use of `http2.createSecureServer()`
      +// is necessary when communicating with browser clients.
      +const server = http2.createServer();
      +
      +server.on('stream', (stream, headers) => {
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(80);
      +

      http2.createSecureServer(options[, onRequestHandler])#

      + +
        +
      • options <Object> +
          +
        • allowHTTP1 <boolean> Incoming client connections that do not support +HTTP/2 will be downgraded to HTTP/1.x when set to true. +See the 'unknownProtocol' event. See ALPN negotiation. +Default: false.
        • +
        • maxDeflateDynamicTableSize <number> Sets the maximum dynamic table size +for deflating header fields. Default: 4Kib.
        • +
        • maxSettings <number> Sets the maximum number of settings entries per +SETTINGS frame. The minimum value allowed is 1. Default: 32.
        • +
        • maxSessionMemory<number> Sets the maximum memory that the Http2Session +is permitted to use. The value is expressed in terms of number of megabytes, +e.g. 1 equal 1 megabyte. The minimum value allowed is 1. This is a +credit based limit, existing Http2Streams may cause this +limit to be exceeded, but new Http2Stream instances will be rejected +while this limit is exceeded. The current number of Http2Stream sessions, +the current memory use of the header compression tables, current data +queued to be sent, and unacknowledged PING and SETTINGS frames are all +counted towards the current limit. Default: 10.
        • +
        • maxHeaderListPairs <number> Sets the maximum number of header entries. +This is similar to http.Server#maxHeadersCount or +http.ClientRequest#maxHeadersCount. The minimum value is 4. +Default: 128.
        • +
        • maxOutstandingPings <number> Sets the maximum number of outstanding, +unacknowledged pings. Default: 10.
        • +
        • maxSendHeaderBlockLength <number> Sets the maximum allowed size for a +serialized, compressed block of headers. Attempts to send headers that +exceed this limit will result in a 'frameError' event being emitted +and the stream being closed and destroyed.
        • +
        • paddingStrategy <number> Strategy used for determining the amount of +padding to use for HEADERS and DATA frames. Default: +http2.constants.PADDING_STRATEGY_NONE. Value may be one of: +
            +
          • http2.constants.PADDING_STRATEGY_NONE: Specifies that no padding is +to be applied.
          • +
          • http2.constants.PADDING_STRATEGY_MAX: Specifies that the maximum +amount of padding, as determined by the internal implementation, is to +be applied.
          • +
          • http2.constants.PADDING_STRATEGY_CALLBACK: Specifies that the user +provided options.selectPadding() callback is to be used to determine +the amount of padding.
          • +
          • http2.constants.PADDING_STRATEGY_ALIGNED: Will attempt to apply +enough padding to ensure that the total frame length, including the +9-byte header, is a multiple of 8. For each frame, however, there is a +maximum allowed number of padding bytes that is determined by current +flow control state and settings. If this maximum is less than the +calculated amount needed to ensure alignment, the maximum will be used +and the total frame length will not necessarily be aligned at 8 bytes.
          • +
          +
        • +
        • peerMaxConcurrentStreams <number> Sets the maximum number of concurrent +streams for the remote peer as if a SETTINGS frame had been received. Will +be overridden if the remote peer sets its own value for +maxConcurrentStreams. Default: 100.
        • +
        • maxSessionInvalidFrames <integer> Sets the maximum number of invalid +frames that will be tolerated before the session is closed. +Default: 1000.
        • +
        • maxSessionRejectedStreams <integer> Sets the maximum number of rejected +upon creation streams that will be tolerated before the session is closed. +Each rejection is associated with an NGHTTP2_ENHANCE_YOUR_CALM +error that should tell the peer to not open any more streams, continuing +to open streams is therefore regarded as a sign of a misbehaving peer. +Default: 100.
        • +
        • selectPadding <Function> When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, provides the callback function +used to determine the padding. See Using options.selectPadding().
        • +
        • settings <HTTP/2 Settings Object> The initial settings to send to the +remote peer upon connection.
        • +
        • ...: Any tls.createServer() options can be provided. For +servers, the identity options (pfx or key/cert) are usually required.
        • +
        • origins <string[]> An array of origin strings to send within an ORIGIN +frame immediately following creation of a new server Http2Session.
        • +
        • unknownProtocolTimeout <number> Specifies a timeout in milliseconds that +a server should wait when an 'unknownProtocol' event is emitted. If +the socket has not been destroyed by that time the server will destroy it. +Default: 10000.
        • +
        +
      • +
      • onRequestHandler <Function> See Compatibility API
      • +
      • Returns: <Http2SecureServer>
      • +
      +

      Returns a tls.Server instance that creates and manages Http2Session +instances.

      +
      const http2 = require('http2');
      +const fs = require('fs');
      +
      +const options = {
      +  key: fs.readFileSync('server-key.pem'),
      +  cert: fs.readFileSync('server-cert.pem')
      +};
      +
      +// Create a secure HTTP/2 server
      +const server = http2.createSecureServer(options);
      +
      +server.on('stream', (stream, headers) => {
      +  stream.respond({
      +    'content-type': 'text/html; charset=utf-8',
      +    ':status': 200
      +  });
      +  stream.end('<h1>Hello World</h1>');
      +});
      +
      +server.listen(80);
      +

      http2.connect(authority[, options][, listener])#

      + +
        +
      • authority <string> | <URL> The remote HTTP/2 server to connect to. This must +be in the form of a minimal, valid URL with the http:// or https:// +prefix, host name, and IP port (if a non-default port is used). Userinfo +(user ID and password), path, querystring, and fragment details in the +URL will be ignored.
      • +
      • options <Object> +
          +
        • maxDeflateDynamicTableSize <number> Sets the maximum dynamic table size +for deflating header fields. Default: 4Kib.
        • +
        • maxSettings <number> Sets the maximum number of settings entries per +SETTINGS frame. The minimum value allowed is 1. Default: 32.
        • +
        • maxSessionMemory<number> Sets the maximum memory that the Http2Session +is permitted to use. The value is expressed in terms of number of megabytes, +e.g. 1 equal 1 megabyte. The minimum value allowed is 1. +This is a credit based limit, existing Http2Streams may cause this +limit to be exceeded, but new Http2Stream instances will be rejected +while this limit is exceeded. The current number of Http2Stream sessions, +the current memory use of the header compression tables, current data +queued to be sent, and unacknowledged PING and SETTINGS frames are all +counted towards the current limit. Default: 10.
        • +
        • maxHeaderListPairs <number> Sets the maximum number of header entries. +This is similar to http.Server#maxHeadersCount or +http.ClientRequest#maxHeadersCount. The minimum value is 1. +Default: 128.
        • +
        • maxOutstandingPings <number> Sets the maximum number of outstanding, +unacknowledged pings. Default: 10.
        • +
        • maxReservedRemoteStreams <number> Sets the maximum number of reserved push +streams the client will accept at any given time. Once the current number of +currently reserved push streams exceeds reaches this limit, new push streams +sent by the server will be automatically rejected. The minimum allowed value +is 0. The maximum allowed value is 232-1. A negative value sets +this option to the maximum allowed value. Default: 200.
        • +
        • maxSendHeaderBlockLength <number> Sets the maximum allowed size for a +serialized, compressed block of headers. Attempts to send headers that +exceed this limit will result in a 'frameError' event being emitted +and the stream being closed and destroyed.
        • +
        • paddingStrategy <number> Strategy used for determining the amount of +padding to use for HEADERS and DATA frames. Default: +http2.constants.PADDING_STRATEGY_NONE. Value may be one of: +
            +
          • http2.constants.PADDING_STRATEGY_NONE: Specifies that no padding is +to be applied.
          • +
          • http2.constants.PADDING_STRATEGY_MAX: Specifies that the maximum +amount of padding, as determined by the internal implementation, is to +be applied.
          • +
          • http2.constants.PADDING_STRATEGY_CALLBACK: Specifies that the user +provided options.selectPadding() callback is to be used to determine +the amount of padding.
          • +
          • http2.constants.PADDING_STRATEGY_ALIGNED: Will attempt to apply +enough padding to ensure that the total frame length, including the +9-byte header, is a multiple of 8. For each frame, however, there is a +maximum allowed number of padding bytes that is determined by current +flow control state and settings. If this maximum is less than the +calculated amount needed to ensure alignment, the maximum will be used +and the total frame length will not necessarily be aligned at 8 bytes.
          • +
          +
        • +
        • peerMaxConcurrentStreams <number> Sets the maximum number of concurrent +streams for the remote peer as if a SETTINGS frame had been received. Will +be overridden if the remote peer sets its own value for +maxConcurrentStreams. Default: 100.
        • +
        • selectPadding <Function> When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, provides the callback function +used to determine the padding. See Using options.selectPadding().
        • +
        • protocol <string> The protocol to connect with, if not set in the +authority. Value may be either 'http:' or 'https:'. Default: +'https:'
        • +
        • settings <HTTP/2 Settings Object> The initial settings to send to the +remote peer upon connection.
        • +
        • createConnection <Function> An optional callback that receives the URL +instance passed to connect and the options object, and returns any +Duplex stream that is to be used as the connection for this session.
        • +
        • ...: Any net.connect() or tls.connect() options can be provided.
        • +
        • unknownProtocolTimeout <number> Specifies a timeout in milliseconds that +a server should wait when an 'unknownProtocol' event is emitted. If +the socket has not been destroyed by that time the server will destroy it. +Default: 10000.
        • +
        +
      • +
      • listener <Function> Will be registered as a one-time listener of the +'connect' event.
      • +
      • Returns: <ClientHttp2Session>
      • +
      +

      Returns a ClientHttp2Session instance.

      +
      const http2 = require('http2');
      +const client = http2.connect('https://localhost:1234');
      +
      +/* Use the client */
      +
      +client.close();
      +

      http2.constants#

      + +

      Error codes for RST_STREAM and GOAWAY#

      +

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ValueNameConstant
      0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
      0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
      0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
      0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
      0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
      0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
      0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
      0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
      0x08Cancelhttp2.constants.NGHTTP2_CANCEL
      0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
      0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
      0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
      0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
      0x0dHTTP/1.1 Requiredhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED
      +

      The 'timeout' event is emitted when there is no activity on the Server for +a given number of milliseconds set using http2server.setTimeout().

      +

      http2.getDefaultSettings()#

      + + +

      Returns an object containing the default settings for an Http2Session +instance. This method returns a new object instance every time it is called +so instances returned may be safely modified for use.

      +

      http2.getPackedSettings([settings])#

      + + +

      Returns a Buffer instance containing serialized representation of the given +HTTP/2 settings as specified in the HTTP/2 specification. This is intended +for use with the HTTP2-Settings header field.

      +
      const http2 = require('http2');
      +
      +const packed = http2.getPackedSettings({ enablePush: false });
      +
      +console.log(packed.toString('base64'));
      +// Prints: AAIAAAAA
      +

      http2.getUnpackedSettings(buf)#

      + + +

      Returns a HTTP/2 Settings Object containing the deserialized settings from +the given Buffer as generated by http2.getPackedSettings().

      +

      Headers object#

      +

      Headers are represented as own-properties on JavaScript objects. The property +keys will be serialized to lower-case. Property values should be strings (if +they are not they will be coerced to strings) or an Array of strings (in order +to send more than one value per header field).

      +
      const headers = {
      +  ':status': '200',
      +  'content-type': 'text-plain',
      +  'ABC': ['has', 'more', 'than', 'one', 'value']
      +};
      +
      +stream.respond(headers);
      +

      Header objects passed to callback functions will have a null prototype. This +means that normal JavaScript object methods such as +Object.prototype.toString() and Object.prototype.hasOwnProperty() will +not work.

      +

      For incoming headers:

      +
        +
      • The :status header is converted to number.
      • +
      • Duplicates of :status, :method, :authority, :scheme, :path, +:protocol, age, authorization, access-control-allow-credentials, +access-control-max-age, access-control-request-method, content-encoding, +content-language, content-length, content-location, content-md5, +content-range, content-type, date, dnt, etag, expires, from, +if-match, if-modified-since, if-none-match, if-range, +if-unmodified-since, last-modified, location, max-forwards, +proxy-authorization, range, referer,retry-after, tk, +upgrade-insecure-requests, user-agent or x-content-type-options are +discarded.
      • +
      • set-cookie is always an array. Duplicates are added to the array.
      • +
      • For duplicate cookie headers, the values are joined together with '; '.
      • +
      • For all other headers, the values are joined together with ', '.
      • +
      +
      const http2 = require('http2');
      +const server = http2.createServer();
      +server.on('stream', (stream, headers) => {
      +  console.log(headers[':path']);
      +  console.log(headers.ABC);
      +});
      +

      Settings object#

      + +

      The http2.getDefaultSettings(), http2.getPackedSettings(), +http2.createServer(), http2.createSecureServer(), +http2session.settings(), http2session.localSettings, and +http2session.remoteSettings APIs either return or receive as input an +object that defines configuration settings for an Http2Session object. +These objects are ordinary JavaScript objects containing the following +properties.

      +
        +
      • headerTableSize <number> Specifies the maximum number of bytes used for +header compression. The minimum allowed value is 0. The maximum allowed value +is 232-1. Default: 4096.
      • +
      • enablePush <boolean> Specifies true if HTTP/2 Push Streams are to be +permitted on the Http2Session instances. Default: true.
      • +
      • initialWindowSize <number> Specifies the sender's initial window size in +bytes for stream-level flow control. The minimum allowed value is 0. The +maximum allowed value is 232-1. Default: 65535.
      • +
      • maxFrameSize <number> Specifies the size in bytes of the largest frame +payload. The minimum allowed value is 16,384. The maximum allowed value is +224-1. Default: 16384.
      • +
      • maxConcurrentStreams <number> Specifies the maximum number of concurrent +streams permitted on an Http2Session. There is no default value which +implies, at least theoretically, 232-1 streams may be open +concurrently at any given time in an Http2Session. The minimum value +is 0. The maximum allowed value is 232-1. Default: +4294967295.
      • +
      • maxHeaderListSize <number> Specifies the maximum size (uncompressed octets) +of header list that will be accepted. The minimum allowed value is 0. The +maximum allowed value is 232-1. Default: 65535.
      • +
      • maxHeaderSize <number> Alias for maxHeaderListSize.
      • +
      • enableConnectProtocol<boolean> Specifies true if the "Extended Connect +Protocol" defined by RFC 8441 is to be enabled. This setting is only +meaningful if sent by the server. Once the enableConnectProtocol setting +has been enabled for a given Http2Session, it cannot be disabled. +Default: false.
      • +
      +

      All additional properties on the settings object are ignored.

      +

      Using options.selectPadding()#

      +

      When options.paddingStrategy is equal to +http2.constants.PADDING_STRATEGY_CALLBACK, the HTTP/2 implementation will +consult the options.selectPadding() callback function, if provided, to +determine the specific amount of padding to use per HEADERS and DATA frame.

      +

      The options.selectPadding() function receives two numeric arguments, +frameLen and maxFrameLen and must return a number N such that +frameLen <= N <= maxFrameLen.

      +
      const http2 = require('http2');
      +const server = http2.createServer({
      +  paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK,
      +  selectPadding(frameLen, maxFrameLen) {
      +    return maxFrameLen;
      +  }
      +});
      +

      The options.selectPadding() function is invoked once for every HEADERS and +DATA frame. This has a definite noticeable impact on performance.

      +

      Error handling#

      +

      There are several types of error conditions that may arise when using the +http2 module:

      +

      Validation errors occur when an incorrect argument, option, or setting value is +passed in. These will always be reported by a synchronous throw.

      +

      State errors occur when an action is attempted at an incorrect time (for +instance, attempting to send data on a stream after it has closed). These will +be reported using either a synchronous throw or via an 'error' event on +the Http2Stream, Http2Session or HTTP/2 Server objects, depending on where +and when the error occurs.

      +

      Internal errors occur when an HTTP/2 session fails unexpectedly. These will be +reported via an 'error' event on the Http2Session or HTTP/2 Server objects.

      +

      Protocol errors occur when various HTTP/2 protocol constraints are violated. +These will be reported using either a synchronous throw or via an 'error' +event on the Http2Stream, Http2Session or HTTP/2 Server objects, depending +on where and when the error occurs.

      +

      Invalid character handling in header names and values#

      +

      The HTTP/2 implementation applies stricter handling of invalid characters in +HTTP header names and values than the HTTP/1 implementation.

      +

      Header field names are case-insensitive and are transmitted over the wire +strictly as lower-case strings. The API provided by Node.js allows header +names to be set as mixed-case strings (e.g. Content-Type) but will convert +those to lower-case (e.g. content-type) upon transmission.

      +

      Header field-names must only contain one or more of the following ASCII +characters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +, +-, ., ^, _, ` (backtick), |, and ~.

      +

      Using invalid characters within an HTTP header field name will cause the +stream to be closed with a protocol error being reported.

      +

      Header field values are handled with more leniency but should not contain +new-line or carriage return characters and should be limited to US-ASCII +characters, per the requirements of the HTTP specification.

      +

      Push streams on the client#

      +

      To receive pushed streams on the client, set a listener for the 'stream' +event on the ClientHttp2Session:

      +
      const http2 = require('http2');
      +
      +const client = http2.connect('http://localhost');
      +
      +client.on('stream', (pushedStream, requestHeaders) => {
      +  pushedStream.on('push', (responseHeaders) => {
      +    // Process response headers
      +  });
      +  pushedStream.on('data', (chunk) => { /* handle pushed data */ });
      +});
      +
      +const req = client.request({ ':path': '/' });
      +

      Supporting the CONNECT method#

      +

      The CONNECT method is used to allow an HTTP/2 server to be used as a proxy +for TCP/IP connections.

      +

      A simple TCP Server:

      +
      const net = require('net');
      +
      +const server = net.createServer((socket) => {
      +  let name = '';
      +  socket.setEncoding('utf8');
      +  socket.on('data', (chunk) => name += chunk);
      +  socket.on('end', () => socket.end(`hello ${name}`));
      +});
      +
      +server.listen(8000);
      +

      An HTTP/2 CONNECT proxy:

      +
      const http2 = require('http2');
      +const { NGHTTP2_REFUSED_STREAM } = http2.constants;
      +const net = require('net');
      +
      +const proxy = http2.createServer();
      +proxy.on('stream', (stream, headers) => {
      +  if (headers[':method'] !== 'CONNECT') {
      +    // Only accept CONNECT requests
      +    stream.close(NGHTTP2_REFUSED_STREAM);
      +    return;
      +  }
      +  const auth = new URL(`tcp://${headers[':authority']}`);
      +  // It's a very good idea to verify that hostname and port are
      +  // things this proxy should be connecting to.
      +  const socket = net.connect(auth.port, auth.hostname, () => {
      +    stream.respond();
      +    socket.pipe(stream);
      +    stream.pipe(socket);
      +  });
      +  socket.on('error', (error) => {
      +    stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);
      +  });
      +});
      +
      +proxy.listen(8001);
      +

      An HTTP/2 CONNECT client:

      +
      const http2 = require('http2');
      +
      +const client = http2.connect('http://localhost:8001');
      +
      +// Must not specify the ':path' and ':scheme' headers
      +// for CONNECT requests or an error will be thrown.
      +const req = client.request({
      +  ':method': 'CONNECT',
      +  ':authority': `localhost:${port}`
      +});
      +
      +req.on('response', (headers) => {
      +  console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);
      +});
      +let data = '';
      +req.setEncoding('utf8');
      +req.on('data', (chunk) => data += chunk);
      +req.on('end', () => {
      +  console.log(`The server says: ${data}`);
      +  client.close();
      +});
      +req.end('Jane');
      +

      The extended CONNECT protocol#

      +

      RFC 8441 defines an "Extended CONNECT Protocol" extension to HTTP/2 that +may be used to bootstrap the use of an Http2Stream using the CONNECT +method as a tunnel for other communication protocols (such as WebSockets).

      +

      The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using +the enableConnectProtocol setting:

      +
      const http2 = require('http2');
      +const settings = { enableConnectProtocol: true };
      +const server = http2.createServer({ settings });
      +

      Once the client receives the SETTINGS frame from the server indicating that +the extended CONNECT may be used, it may send CONNECT requests that use the +':protocol' HTTP/2 pseudo-header:

      +
      const http2 = require('http2');
      +const client = http2.connect('http://localhost:8080');
      +client.on('remoteSettings', (settings) => {
      +  if (settings.enableConnectProtocol) {
      +    const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });
      +    // ...
      +  }
      +});
      +

      Compatibility API#

      +

      The Compatibility API has the goal of providing a similar developer experience +of HTTP/1 when using HTTP/2, making it possible to develop applications +that support both HTTP/1 and HTTP/2. This API targets only the +public API of the HTTP/1. However many modules use internal +methods or state, and those are not supported as it is a completely +different implementation.

      +

      The following example creates an HTTP/2 server using the compatibility +API:

      +
      const http2 = require('http2');
      +const server = http2.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      +  res.end('ok');
      +});
      +

      In order to create a mixed HTTPS and HTTP/2 server, refer to the +ALPN negotiation section. +Upgrading from non-tls HTTP/1 servers is not supported.

      +

      The HTTP/2 compatibility API is composed of Http2ServerRequest and +Http2ServerResponse. They aim at API compatibility with HTTP/1, but +they do not hide the differences between the protocols. As an example, +the status message for HTTP codes is ignored.

      +

      ALPN negotiation#

      +

      ALPN negotiation allows supporting both HTTPS and HTTP/2 over +the same socket. The req and res objects can be either HTTP/1 or +HTTP/2, and an application must restrict itself to the public API of +HTTP/1, and detect if it is possible to use the more advanced +features of HTTP/2.

      +

      The following example creates a server that supports both protocols:

      +
      const { createSecureServer } = require('http2');
      +const { readFileSync } = require('fs');
      +
      +const cert = readFileSync('./cert.pem');
      +const key = readFileSync('./key.pem');
      +
      +const server = createSecureServer(
      +  { cert, key, allowHTTP1: true },
      +  onRequest
      +).listen(4443);
      +
      +function onRequest(req, res) {
      +  // Detects if it is a HTTPS request or HTTP/2
      +  const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?
      +    req.stream.session : req;
      +  res.writeHead(200, { 'content-type': 'application/json' });
      +  res.end(JSON.stringify({
      +    alpnProtocol,
      +    httpVersion: req.httpVersion
      +  }));
      +}
      +

      The 'request' event works identically on both HTTPS and +HTTP/2.

      +

      Class: http2.Http2ServerRequest#

      + + +

      A Http2ServerRequest object is created by http2.Server or +http2.SecureServer and passed as the first argument to the +'request' event. It may be used to access a request status, headers, and +data.

      +

      Event: 'aborted'#

      + +

      The 'aborted' event is emitted whenever a Http2ServerRequest instance is +abnormally aborted in mid-communication.

      +

      The 'aborted' event will only be emitted if the Http2ServerRequest writable +side has not been ended.

      +

      Event: 'close'#

      + +

      Indicates that the underlying Http2Stream was closed. +Just like 'end', this event occurs only once per response.

      +

      request.aborted#

      + + +

      The request.aborted property will be true if the request has +been aborted.

      +

      request.authority#

      + + +

      The request authority pseudo header field. It can also be accessed via +req.headers[':authority'].

      +

      request.complete#

      + + +

      The request.complete property will be true if the request has +been completed, aborted, or destroyed.

      +

      request.destroy([error])#

      + + +

      Calls destroy() on the Http2Stream that received +the Http2ServerRequest. If error is provided, an 'error' event +is emitted and error is passed as an argument to any listeners on the event.

      +

      It does nothing if the stream was already destroyed.

      +

      request.headers#

      + + +

      The request/response headers object.

      +

      Key-value pairs of header names and values. Header names are lower-cased.

      +
      // Prints something like:
      +//
      +// { 'user-agent': 'curl/7.22.0',
      +//   host: '127.0.0.1:8000',
      +//   accept: '*/*' }
      +console.log(request.headers);
      +

      See HTTP/2 Headers Object.

      +

      In HTTP/2, the request path, host name, protocol, and method are represented as +special headers prefixed with the : character (e.g. ':path'). These special +headers will be included in the request.headers object. Care must be taken not +to inadvertently modify these special headers or errors may occur. For instance, +removing all headers from the request will cause errors to occur:

      +
      removeAllHeaders(request.headers);
      +assert(request.url);   // Fails because the :path header has been removed
      +

      request.httpVersion#

      + + +

      In case of server request, the HTTP version sent by the client. In the case of +client response, the HTTP version of the connected-to server. Returns +'2.0'.

      +

      Also message.httpVersionMajor is the first integer and +message.httpVersionMinor is the second.

      +

      request.method#

      + + +

      The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

      +

      request.rawHeaders#

      + + +

      The raw request/response headers list exactly as they were received.

      +

      The keys and values are in the same list. It is not a +list of tuples. So, the even-numbered offsets are key values, and the +odd-numbered offsets are the associated values.

      +

      Header names are not lowercased, and duplicates are not merged.

      +
      // Prints something like:
      +//
      +// [ 'user-agent',
      +//   'this is invalid because there can be only one',
      +//   'User-Agent',
      +//   'curl/7.22.0',
      +//   'Host',
      +//   '127.0.0.1:8000',
      +//   'ACCEPT',
      +//   '*/*' ]
      +console.log(request.rawHeaders);
      +

      request.rawTrailers#

      + + +

      The raw request/response trailer keys and values exactly as they were +received. Only populated at the 'end' event.

      +

      request.scheme#

      + + +

      The request scheme pseudo header field indicating the scheme +portion of the target URL.

      +

      request.setTimeout(msecs, callback)#

      + + +

      Sets the Http2Stream's timeout value to msecs. If a callback is +provided, then it is added as a listener on the 'timeout' event on +the response object.

      +

      If no 'timeout' listener is added to the request, the response, or +the server, then Http2Streams are destroyed when they time out. If a +handler is assigned to the request, the response, or the server's 'timeout' +events, timed out sockets must be handled explicitly.

      +

      request.socket#

      + + +

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but +applies getters, setters, and methods based on HTTP/2 logic.

      +

      destroyed, readable, and writable properties will be retrieved from and +set on request.stream.

      +

      destroy, emit, end, on and once methods will be called on +request.stream.

      +

      setTimeout method will be called on request.stream.session.

      +

      pause, read, resume, and write will throw an error with code +ERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for +more information.

      +

      All other interactions will be routed directly to the socket. With TLS support, +use request.socket.getPeerCertificate() to obtain the client's +authentication details.

      +

      request.stream#

      + + +

      The Http2Stream object backing the request.

      +

      request.trailers#

      + + +

      The request/response trailers object. Only populated at the 'end' event.

      +

      request.url#

      + + +

      Request URL string. This contains only the URL that is present in the actual +HTTP request. If the request is:

      +
      GET /status?name=ryan HTTP/1.1
      +Accept: text/plain
      +

      Then request.url will be:

      + +
      '/status?name=ryan'
      +

      To parse the url into its parts, require('url').parse(request.url) +can be used:

      +
      $ node
      +> require('url').parse('/status?name=ryan')
      +Url {
      +  protocol: null,
      +  slashes: null,
      +  auth: null,
      +  host: null,
      +  port: null,
      +  hostname: null,
      +  hash: null,
      +  search: '?name=ryan',
      +  query: 'name=ryan',
      +  pathname: '/status',
      +  path: '/status?name=ryan',
      +  href: '/status?name=ryan' }
      +

      To obtain the parameters from the query string, use the +require('querystring').parse() function or pass +true as the second argument to require('url').parse().

      +
      $ node
      +> require('url').parse('/status?name=ryan', true)
      +Url {
      +  protocol: null,
      +  slashes: null,
      +  auth: null,
      +  host: null,
      +  port: null,
      +  hostname: null,
      +  hash: null,
      +  search: '?name=ryan',
      +  query: { name: 'ryan' },
      +  pathname: '/status',
      +  path: '/status?name=ryan',
      +  href: '/status?name=ryan' }
      +

      Class: http2.Http2ServerResponse#

      + + +

      This object is created internally by an HTTP server, not by the user. It is +passed as the second parameter to the 'request' event.

      +

      Event: 'close'#

      + +

      Indicates that the underlying Http2Stream was terminated before +response.end() was called or able to flush.

      +

      Event: 'finish'#

      + +

      Emitted when the response has been sent. More specifically, this event is +emitted when the last segment of the response headers and body have been +handed off to the HTTP/2 multiplexing for transmission over the network. It +does not imply that the client has received anything yet.

      +

      After this event, no more events will be emitted on the response object.

      +

      response.addTrailers(headers)#

      + + +

      This method adds HTTP trailing headers (a header but at the end of the +message) to the response.

      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.connection#

      + + +

      See response.socket.

      +

      response.end([data[, encoding]][, callback])#

      + + +

      This method signals to the server that all of the response headers and body +have been sent; that server should consider this message complete. +The method, response.end(), MUST be called on each response.

      +

      If data is specified, it is equivalent to calling +response.write(data, encoding) followed by response.end(callback).

      +

      If callback is specified, it will be called when the response stream +is finished.

      +

      response.finished#

      + +

      + +

      Boolean value that indicates whether the response has completed. Starts +as false. After response.end() executes, the value will be true.

      +

      response.getHeader(name)#

      + + +

      Reads out a header that has already been queued but not sent to the client. +The name is case-insensitive.

      +
      const contentType = response.getHeader('content-type');
      +

      response.getHeaderNames()#

      + + +

      Returns an array containing the unique names of the current outgoing headers. +All header names are lowercase.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headerNames = response.getHeaderNames();
      +// headerNames === ['foo', 'set-cookie']
      +

      response.getHeaders()#

      + + +

      Returns a shallow copy of the current outgoing headers. Since a shallow copy +is used, array values may be mutated without additional calls to various +header-related http module methods. The keys of the returned object are the +header names and the values are the respective header values. All header names +are lowercase.

      +

      The object returned by the response.getHeaders() method does not +prototypically inherit from the JavaScript Object. This means that typical +Object methods such as obj.toString(), obj.hasOwnProperty(), and others +are not defined and will not work.

      +
      response.setHeader('Foo', 'bar');
      +response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
      +
      +const headers = response.getHeaders();
      +// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
      +

      response.hasHeader(name)#

      + + +

      Returns true if the header identified by name is currently set in the +outgoing headers. The header name matching is case-insensitive.

      +
      const hasContentType = response.hasHeader('content-type');
      +

      response.headersSent#

      + + +

      True if headers were sent, false otherwise (read-only).

      +

      response.removeHeader(name)#

      + + +

      Removes a header that has been queued for implicit sending.

      +
      response.removeHeader('Content-Encoding');
      +

      response.sendDate#

      + + +

      When true, the Date header will be automatically generated and sent in +the response if it is not already present in the headers. Defaults to true.

      +

      This should only be disabled for testing; HTTP requires the Date header +in responses.

      +

      response.setHeader(name, value)#

      + + +

      Sets a single header value for implicit headers. If this header already exists +in the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name.

      +
      response.setHeader('Content-Type', 'text/html; charset=utf-8');
      +

      or

      +
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +
      // Returns content-type = text/plain
      +const server = http2.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html; charset=utf-8');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      +  res.end('ok');
      +});
      +

      response.setTimeout(msecs[, callback])#

      + + +

      Sets the Http2Stream's timeout value to msecs. If a callback is +provided, then it is added as a listener on the 'timeout' event on +the response object.

      +

      If no 'timeout' listener is added to the request, the response, or +the server, then Http2Streams are destroyed when they time out. If a +handler is assigned to the request, the response, or the server's 'timeout' +events, timed out sockets must be handled explicitly.

      +

      response.socket#

      + + +

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but +applies getters, setters, and methods based on HTTP/2 logic.

      +

      destroyed, readable, and writable properties will be retrieved from and +set on response.stream.

      +

      destroy, emit, end, on and once methods will be called on +response.stream.

      +

      setTimeout method will be called on response.stream.session.

      +

      pause, read, resume, and write will throw an error with code +ERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for +more information.

      +

      All other interactions will be routed directly to the socket.

      +
      const http2 = require('http2');
      +const server = http2.createServer((req, res) => {
      +  const ip = req.socket.remoteAddress;
      +  const port = req.socket.remotePort;
      +  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
      +}).listen(3000);
      +

      response.statusCode#

      + + +

      When using implicit headers (not calling response.writeHead() explicitly), +this property controls the status code that will be sent to the client when +the headers get flushed.

      +
      response.statusCode = 404;
      +

      After response header was sent to the client, this property indicates the +status code which was sent out.

      +

      response.statusMessage#

      + + +

      Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns +an empty string.

      +

      response.stream#

      + + +

      The Http2Stream object backing the response.

      +

      response.writableEnded#

      + + +

      Is true after response.end() has been called. This property +does not indicate whether the data has been flushed, for this use +writable.writableFinished instead.

      +

      response.write(chunk[, encoding][, callback])#

      + + +

      If this method is called and response.writeHead() has not been called, +it will switch to implicit header mode and flush the implicit headers.

      +

      This sends a chunk of the response body. This method may +be called multiple times to provide successive parts of the body.

      +

      In the http module, the response body is omitted when the +request is a HEAD request. Similarly, the 204 and 304 responses +must not include a message body.

      +

      chunk can be a string or a buffer. If chunk is a string, +the second parameter specifies how to encode it into a byte stream. +By default the encoding is 'utf8'. callback will be called when this chunk +of data is flushed.

      +

      This is the raw HTTP body and has nothing to do with higher-level multi-part +body encodings that may be used.

      +

      The first time response.write() is called, it will send the buffered +header information and the first chunk of the body to the client. The second +time response.write() is called, Node.js assumes data will be streamed, +and sends the new data separately. That is, the response is buffered up to the +first chunk of the body.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is free again.

      +

      response.writeContinue()#

      + +

      Sends a status 100 Continue to the client, indicating that the request body +should be sent. See the 'checkContinue' event on Http2Server and +Http2SecureServer.

      +

      response.writeHead(statusCode[, statusMessage][, headers])#

      + + +

      Sends a response header to the request. The status code is a 3-digit HTTP +status code, like 404. The last argument, headers, are the response headers.

      +

      Returns a reference to the Http2ServerResponse, so that calls can be chained.

      +

      For compatibility with HTTP/1, a human-readable statusMessage may be +passed as the second argument. However, because the statusMessage has no +meaning within HTTP/2, the argument will have no effect and a process warning +will be emitted.

      +
      const body = 'hello world';
      +response.writeHead(200, {
      +  'Content-Length': Buffer.byteLength(body),
      +  'Content-Type': 'text/plain; charset=utf-8' });
      +

      Content-Length is given in bytes not characters. The +Buffer.byteLength() API may be used to determine the number of bytes in a +given encoding. On outbound messages, Node.js does not check if Content-Length +and the length of the body being transmitted are equal or not. However, when +receiving messages, Node.js will automatically reject messages when the +Content-Length does not match the actual payload size.

      +

      This method may be called at most one time on a message before +response.end() is called.

      +

      If response.write() or response.end() are called before calling +this, the implicit/mutable headers will be calculated and call this function.

      +

      When headers have been set with response.setHeader(), they will be merged +with any headers passed to response.writeHead(), with the headers passed +to response.writeHead() given precedence.

      +
      // Returns content-type = text/plain
      +const server = http2.createServer((req, res) => {
      +  res.setHeader('Content-Type', 'text/html; charset=utf-8');
      +  res.setHeader('X-Foo', 'bar');
      +  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
      +  res.end('ok');
      +});
      +

      Attempting to set a header field name or value that contains invalid characters +will result in a TypeError being thrown.

      +

      response.createPushResponse(headers, callback)#

      + +
        +
      • headers <HTTP/2 Headers Object> An object describing the headers
      • +
      • callback <Function> Called once http2stream.pushStream() is finished, +or either when the attempt to create the pushed Http2Stream has failed or +has been rejected, or the state of Http2ServerRequest is closed prior to +calling the http2stream.pushStream() method + +
      • +
      +

      Call http2stream.pushStream() with the given headers, and wrap the +given Http2Stream on a newly created Http2ServerResponse as the callback +parameter if successful. When Http2ServerRequest is closed, the callback is +called with an error ERR_HTTP2_INVALID_STREAM.

      +

      Collecting HTTP/2 performance metrics#

      +

      The Performance Observer API can be used to collect basic performance +metrics for each Http2Session and Http2Stream instance.

      +
      const { PerformanceObserver } = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((items) => {
      +  const entry = items.getEntries()[0];
      +  console.log(entry.entryType);  // prints 'http2'
      +  if (entry.name === 'Http2Session') {
      +    // Entry contains statistics about the Http2Session
      +  } else if (entry.name === 'Http2Stream') {
      +    // Entry contains statistics about the Http2Stream
      +  }
      +});
      +obs.observe({ entryTypes: ['http2'] });
      +

      The entryType property of the PerformanceEntry will be equal to 'http2'.

      +

      The name property of the PerformanceEntry will be equal to either +'Http2Stream' or 'Http2Session'.

      +

      If name is equal to Http2Stream, the PerformanceEntry will contain the +following additional properties:

      +
        +
      • bytesRead <number> The number of DATA frame bytes received for this +Http2Stream.
      • +
      • bytesWritten <number> The number of DATA frame bytes sent for this +Http2Stream.
      • +
      • id <number> The identifier of the associated Http2Stream
      • +
      • timeToFirstByte <number> The number of milliseconds elapsed between the +PerformanceEntry startTime and the reception of the first DATA frame.
      • +
      • timeToFirstByteSent <number> The number of milliseconds elapsed between +the PerformanceEntry startTime and sending of the first DATA frame.
      • +
      • timeToFirstHeader <number> The number of milliseconds elapsed between the +PerformanceEntry startTime and the reception of the first header.
      • +
      +

      If name is equal to Http2Session, the PerformanceEntry will contain the +following additional properties:

      +
        +
      • bytesRead <number> The number of bytes received for this Http2Session.
      • +
      • bytesWritten <number> The number of bytes sent for this Http2Session.
      • +
      • framesReceived <number> The number of HTTP/2 frames received by the +Http2Session.
      • +
      • framesSent <number> The number of HTTP/2 frames sent by the Http2Session.
      • +
      • maxConcurrentStreams <number> The maximum number of streams concurrently +open during the lifetime of the Http2Session.
      • +
      • pingRTT <number> The number of milliseconds elapsed since the transmission +of a PING frame and the reception of its acknowledgment. Only present if +a PING frame has been sent on the Http2Session.
      • +
      • streamAverageDuration <number> The average duration (in milliseconds) for +all Http2Stream instances.
      • +
      • streamCount <number> The number of Http2Stream instances processed by +the Http2Session.
      • +
      • type <string> Either 'server' or 'client' to identify the type of +Http2Session.
      • +
      + +
      +
      +
      + + diff --git a/doc/api/http2.json b/doc/api/http2.json new file mode 100644 index 0000000000000000000000000000000000000000..665721e33ebe7d4f49f87324f1f5c184ae6d8936 --- /dev/null +++ b/doc/api/http2.json @@ -0,0 +1,3780 @@ +{ + "type": "module", + "source": "doc/api/http2.md", + "modules": [ + { + "textRaw": "HTTP/2", + "name": "http/2", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v10.10.0", + "pr-url": "https://github.com/nodejs/node/pull/22466", + "description": "HTTP/2 is now Stable. Previously, it had been Experimental." + } + ] + }, + "introduced_in": "v8.4.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/http2.js

      \n

      The http2 module provides an implementation of the HTTP/2 protocol. It\ncan be accessed using:

      \n
      const http2 = require('http2');\n
      ", + "modules": [ + { + "textRaw": "Core API", + "name": "core_api", + "desc": "

      The Core API provides a low-level interface designed specifically around\nsupport for HTTP/2 protocol features. It is specifically not designed for\ncompatibility with the existing HTTP/1 module API. However,\nthe Compatibility API is.

      \n

      The http2 Core API is much more symmetric between client and server than the\nhttp API. For instance, most events, like 'error', 'connect' and\n'stream', can be emitted either by client-side code or server-side code.

      ", + "modules": [ + { + "textRaw": "Server-side example", + "name": "server-side_example", + "desc": "

      The following illustrates a simple HTTP/2 server using the Core API.\nSince there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createSecureServer({\n  key: fs.readFileSync('localhost-privkey.pem'),\n  cert: fs.readFileSync('localhost-cert.pem')\n});\nserver.on('error', (err) => console.error(err));\n\nserver.on('stream', (stream, headers) => {\n  // stream is a Duplex\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n
      \n

      To generate the certificate and key for this example, run:

      \n
      openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n  -keyout localhost-privkey.pem -out localhost-cert.pem\n
      ", + "type": "module", + "displayName": "Server-side example" + }, + { + "textRaw": "Client-side example", + "name": "client-side_example", + "desc": "

      The following illustrates an HTTP/2 client:

      \n
      const http2 = require('http2');\nconst fs = require('fs');\nconst client = http2.connect('https://localhost:8443', {\n  ca: fs.readFileSync('localhost-cert.pem')\n});\nclient.on('error', (err) => console.error(err));\n\nconst req = client.request({ ':path': '/' });\n\nreq.on('response', (headers, flags) => {\n  for (const name in headers) {\n    console.log(`${name}: ${headers[name]}`);\n  }\n});\n\nreq.setEncoding('utf8');\nlet data = '';\nreq.on('data', (chunk) => { data += chunk; });\nreq.on('end', () => {\n  console.log(`\\n${data}`);\n  client.close();\n});\nreq.end();\n
      ", + "type": "module", + "displayName": "Client-side example" + }, + { + "textRaw": "Headers object", + "name": "headers_object", + "desc": "

      Headers are represented as own-properties on JavaScript objects. The property\nkeys will be serialized to lower-case. Property values should be strings (if\nthey are not they will be coerced to strings) or an Array of strings (in order\nto send more than one value per header field).

      \n
      const headers = {\n  ':status': '200',\n  'content-type': 'text-plain',\n  'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n
      \n

      Header objects passed to callback functions will have a null prototype. This\nmeans that normal JavaScript object methods such as\nObject.prototype.toString() and Object.prototype.hasOwnProperty() will\nnot work.

      \n

      For incoming headers:

      \n
        \n
      • The :status header is converted to number.
      • \n
      • Duplicates of :status, :method, :authority, :scheme, :path,\n:protocol, age, authorization, access-control-allow-credentials,\naccess-control-max-age, access-control-request-method, content-encoding,\ncontent-language, content-length, content-location, content-md5,\ncontent-range, content-type, date, dnt, etag, expires, from,\nif-match, if-modified-since, if-none-match, if-range,\nif-unmodified-since, last-modified, location, max-forwards,\nproxy-authorization, range, referer,retry-after, tk,\nupgrade-insecure-requests, user-agent or x-content-type-options are\ndiscarded.
      • \n
      • set-cookie is always an array. Duplicates are added to the array.
      • \n
      • For duplicate cookie headers, the values are joined together with '; '.
      • \n
      • For all other headers, the values are joined together with ', '.
      • \n
      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream, headers) => {\n  console.log(headers[':path']);\n  console.log(headers.ABC);\n});\n
      ", + "type": "module", + "displayName": "Headers object" + }, + { + "textRaw": "Settings object", + "name": "settings_object", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29833", + "description": "The `maxConcurrentStreams` setting is stricter." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "The `maxHeaderListSize` setting is now strictly enforced." + } + ] + }, + "desc": "

      The http2.getDefaultSettings(), http2.getPackedSettings(),\nhttp2.createServer(), http2.createSecureServer(),\nhttp2session.settings(), http2session.localSettings, and\nhttp2session.remoteSettings APIs either return or receive as input an\nobject that defines configuration settings for an Http2Session object.\nThese objects are ordinary JavaScript objects containing the following\nproperties.

      \n
        \n
      • headerTableSize <number> Specifies the maximum number of bytes used for\nheader compression. The minimum allowed value is 0. The maximum allowed value\nis 232-1. Default: 4096.
      • \n
      • enablePush <boolean> Specifies true if HTTP/2 Push Streams are to be\npermitted on the Http2Session instances. Default: true.
      • \n
      • initialWindowSize <number> Specifies the sender's initial window size in\nbytes for stream-level flow control. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.
      • \n
      • maxFrameSize <number> Specifies the size in bytes of the largest frame\npayload. The minimum allowed value is 16,384. The maximum allowed value is\n224-1. Default: 16384.
      • \n
      • maxConcurrentStreams <number> Specifies the maximum number of concurrent\nstreams permitted on an Http2Session. There is no default value which\nimplies, at least theoretically, 232-1 streams may be open\nconcurrently at any given time in an Http2Session. The minimum value\nis 0. The maximum allowed value is 232-1. Default:\n4294967295.
      • \n
      • maxHeaderListSize <number> Specifies the maximum size (uncompressed octets)\nof header list that will be accepted. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.
      • \n
      • maxHeaderSize <number> Alias for maxHeaderListSize.
      • \n
      • enableConnectProtocol<boolean> Specifies true if the \"Extended Connect\nProtocol\" defined by RFC 8441 is to be enabled. This setting is only\nmeaningful if sent by the server. Once the enableConnectProtocol setting\nhas been enabled for a given Http2Session, it cannot be disabled.\nDefault: false.
      • \n
      \n

      All additional properties on the settings object are ignored.

      ", + "type": "module", + "displayName": "Settings object" + }, + { + "textRaw": "Using `options.selectPadding()`", + "name": "using_`options.selectpadding()`", + "desc": "

      When options.paddingStrategy is equal to\nhttp2.constants.PADDING_STRATEGY_CALLBACK, the HTTP/2 implementation will\nconsult the options.selectPadding() callback function, if provided, to\ndetermine the specific amount of padding to use per HEADERS and DATA frame.

      \n

      The options.selectPadding() function receives two numeric arguments,\nframeLen and maxFrameLen and must return a number N such that\nframeLen <= N <= maxFrameLen.

      \n
      const http2 = require('http2');\nconst server = http2.createServer({\n  paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK,\n  selectPadding(frameLen, maxFrameLen) {\n    return maxFrameLen;\n  }\n});\n
      \n

      The options.selectPadding() function is invoked once for every HEADERS and\nDATA frame. This has a definite noticeable impact on performance.

      ", + "type": "module", + "displayName": "Using `options.selectPadding()`" + }, + { + "textRaw": "Error handling", + "name": "error_handling", + "desc": "

      There are several types of error conditions that may arise when using the\nhttp2 module:

      \n

      Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.

      \n

      State errors occur when an action is attempted at an incorrect time (for\ninstance, attempting to send data on a stream after it has closed). These will\nbe reported using either a synchronous throw or via an 'error' event on\nthe Http2Stream, Http2Session or HTTP/2 Server objects, depending on where\nand when the error occurs.

      \n

      Internal errors occur when an HTTP/2 session fails unexpectedly. These will be\nreported via an 'error' event on the Http2Session or HTTP/2 Server objects.

      \n

      Protocol errors occur when various HTTP/2 protocol constraints are violated.\nThese will be reported using either a synchronous throw or via an 'error'\nevent on the Http2Stream, Http2Session or HTTP/2 Server objects, depending\non where and when the error occurs.

      ", + "type": "module", + "displayName": "Error handling" + }, + { + "textRaw": "Invalid character handling in header names and values", + "name": "invalid_character_handling_in_header_names_and_values", + "desc": "

      The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.

      \n

      Header field names are case-insensitive and are transmitted over the wire\nstrictly as lower-case strings. The API provided by Node.js allows header\nnames to be set as mixed-case strings (e.g. Content-Type) but will convert\nthose to lower-case (e.g. content-type) upon transmission.

      \n

      Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.

      \n

      Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.

      \n

      Header field values are handled with more leniency but should not contain\nnew-line or carriage return characters and should be limited to US-ASCII\ncharacters, per the requirements of the HTTP specification.

      ", + "type": "module", + "displayName": "Invalid character handling in header names and values" + }, + { + "textRaw": "Push streams on the client", + "name": "push_streams_on_the_client", + "desc": "

      To receive pushed streams on the client, set a listener for the 'stream'\nevent on the ClientHttp2Session:

      \n
      const http2 = require('http2');\n\nconst client = http2.connect('http://localhost');\n\nclient.on('stream', (pushedStream, requestHeaders) => {\n  pushedStream.on('push', (responseHeaders) => {\n    // Process response headers\n  });\n  pushedStream.on('data', (chunk) => { /* handle pushed data */ });\n});\n\nconst req = client.request({ ':path': '/' });\n
      ", + "type": "module", + "displayName": "Push streams on the client" + }, + { + "textRaw": "Supporting the `CONNECT` method", + "name": "supporting_the_`connect`_method", + "desc": "

      The CONNECT method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.

      \n

      A simple TCP Server:

      \n
      const net = require('net');\n\nconst server = net.createServer((socket) => {\n  let name = '';\n  socket.setEncoding('utf8');\n  socket.on('data', (chunk) => name += chunk);\n  socket.on('end', () => socket.end(`hello ${name}`));\n});\n\nserver.listen(8000);\n
      \n

      An HTTP/2 CONNECT proxy:

      \n
      const http2 = require('http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('net');\n\nconst proxy = http2.createServer();\nproxy.on('stream', (stream, headers) => {\n  if (headers[':method'] !== 'CONNECT') {\n    // Only accept CONNECT requests\n    stream.close(NGHTTP2_REFUSED_STREAM);\n    return;\n  }\n  const auth = new URL(`tcp://${headers[':authority']}`);\n  // It's a very good idea to verify that hostname and port are\n  // things this proxy should be connecting to.\n  const socket = net.connect(auth.port, auth.hostname, () => {\n    stream.respond();\n    socket.pipe(stream);\n    stream.pipe(socket);\n  });\n  socket.on('error', (error) => {\n    stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);\n  });\n});\n\nproxy.listen(8001);\n
      \n

      An HTTP/2 CONNECT client:

      \n
      const http2 = require('http2');\n\nconst client = http2.connect('http://localhost:8001');\n\n// Must not specify the ':path' and ':scheme' headers\n// for CONNECT requests or an error will be thrown.\nconst req = client.request({\n  ':method': 'CONNECT',\n  ':authority': `localhost:${port}`\n});\n\nreq.on('response', (headers) => {\n  console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);\n});\nlet data = '';\nreq.setEncoding('utf8');\nreq.on('data', (chunk) => data += chunk);\nreq.on('end', () => {\n  console.log(`The server says: ${data}`);\n  client.close();\n});\nreq.end('Jane');\n
      ", + "type": "module", + "displayName": "Supporting the `CONNECT` method" + }, + { + "textRaw": "The extended `CONNECT` protocol", + "name": "the_extended_`connect`_protocol", + "desc": "

      RFC 8441 defines an \"Extended CONNECT Protocol\" extension to HTTP/2 that\nmay be used to bootstrap the use of an Http2Stream using the CONNECT\nmethod as a tunnel for other communication protocols (such as WebSockets).

      \n

      The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:

      \n
      const http2 = require('http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n
      \n

      Once the client receives the SETTINGS frame from the server indicating that\nthe extended CONNECT may be used, it may send CONNECT requests that use the\n':protocol' HTTP/2 pseudo-header:

      \n
      const http2 = require('http2');\nconst client = http2.connect('http://localhost:8080');\nclient.on('remoteSettings', (settings) => {\n  if (settings.enableConnectProtocol) {\n    const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });\n    // ...\n  }\n});\n
      ", + "type": "module", + "displayName": "The extended `CONNECT` protocol" + } + ], + "classes": [ + { + "textRaw": "Class: `Http2Session`", + "type": "class", + "name": "Http2Session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of the http2.Http2Session class represent an active communications\nsession between an HTTP/2 client and server. Instances of this class are not\nintended to be constructed directly by user code.

      \n

      Each Http2Session instance will exhibit slightly different behaviors\ndepending on whether it is operating as a server or a client. The\nhttp2session.type property can be used to determine the mode in which an\nHttp2Session is operating. On the server side, user code should rarely\nhave occasion to work with the Http2Session object directly, with most\nactions typically taken through interactions with either the Http2Server or\nHttp2Stream objects.

      \n

      User code will not create Http2Session instances directly. Server-side\nHttp2Session instances are created by the Http2Server instance when a\nnew HTTP/2 connection is received. Client-side Http2Session instances are\ncreated using the http2.connect() method.

      ", + "modules": [ + { + "textRaw": "`Http2Session` and sockets", + "name": "`http2session`_and_sockets", + "desc": "

      Every Http2Session instance is associated with exactly one net.Socket or\ntls.TLSSocket when it is created. When either the Socket or the\nHttp2Session are destroyed, both will be destroyed.

      \n

      Because of the specific serialization and processing requirements imposed\nby the HTTP/2 protocol, it is not recommended for user code to read data from\nor write data to a Socket instance bound to a Http2Session. Doing so can\nput the HTTP/2 session into an indeterminate state causing the session and\nthe socket to become unusable.

      \n

      Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.

      ", + "type": "module", + "displayName": "`Http2Session` and sockets" + } + ], + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`session` {Http2Session}", + "name": "session", + "type": "Http2Session" + }, + { + "textRaw": "`socket` {net.Socket}", + "name": "socket", + "type": "net.Socket" + } + ], + "desc": "

      The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.

      \n

      User code will typically not listen for this event directly.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted when an error occurs during the processing of\nan Http2Session.

      " + }, + { + "textRaw": "Event: `'frameError'`", + "type": "event", + "name": "frameError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`type` {integer} The frame type.", + "name": "type", + "type": "integer", + "desc": "The frame type." + }, + { + "textRaw": "`code` {integer} The error code.", + "name": "code", + "type": "integer", + "desc": "The error code." + }, + { + "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", + "name": "id", + "type": "integer", + "desc": "The stream id (or `0` if the frame isn't associated with a stream)." + } + ], + "desc": "

      The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame on the session. If the frame that could not be sent is associated\nwith a specific Http2Stream, an attempt to emit a 'frameError' event on the\nHttp2Stream is made.

      \n

      If the 'frameError' event is associated with a stream, the stream will be\nclosed and destroyed immediately following the 'frameError' event. If the\nevent is not associated with a stream, the Http2Session will be shut down\nimmediately following the 'frameError' event.

      " + }, + { + "textRaw": "Event: `'goaway'`", + "type": "event", + "name": "goaway", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame.", + "name": "errorCode", + "type": "number", + "desc": "The HTTP/2 error code specified in the `GOAWAY` frame." + }, + { + "textRaw": "`lastStreamID` {number} The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified).", + "name": "lastStreamID", + "type": "number", + "desc": "The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified)." + }, + { + "textRaw": "`opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data.", + "name": "opaqueData", + "type": "Buffer", + "desc": "If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data." + } + ], + "desc": "

      The 'goaway' event is emitted when a GOAWAY frame is received.

      \n

      The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.

      " + }, + { + "textRaw": "Event: `'localSettings'`", + "type": "event", + "name": "localSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "A copy of the `SETTINGS` frame received." + } + ], + "desc": "

      The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.

      \n

      When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.

      \n
      session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n  /* Use the new settings */\n});\n
      " + }, + { + "textRaw": "Event: `'ping'`", + "type": "event", + "name": "ping", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`payload` {Buffer} The `PING` frame 8-byte payload", + "name": "payload", + "type": "Buffer", + "desc": "The `PING` frame 8-byte payload" + } + ], + "desc": "

      The 'ping' event is emitted whenever a PING frame is received from the\nconnected peer.

      " + }, + { + "textRaw": "Event: `'remoteSettings'`", + "type": "event", + "name": "remoteSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "A copy of the `SETTINGS` frame received." + } + ], + "desc": "

      The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.

      \n
      session.on('remoteSettings', (settings) => {\n  /* Use the new settings */\n});\n
      " + }, + { + "textRaw": "Event: `'stream'`", + "type": "event", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`stream` {Http2Stream} A reference to the stream", + "name": "stream", + "type": "Http2Stream", + "desc": "A reference to the stream" + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "An object describing the headers" + }, + { + "textRaw": "`flags` {number} The associated numeric flags", + "name": "flags", + "type": "number", + "desc": "The associated numeric flags" + }, + { + "textRaw": "`rawHeaders` {Array} An array containing the raw header names followed by their respective values.", + "name": "rawHeaders", + "type": "Array", + "desc": "An array containing the raw header names followed by their respective values." + } + ], + "desc": "

      The 'stream' event is emitted when a new Http2Stream is created.

      \n
      const http2 = require('http2');\nsession.on('stream', (stream, headers, flags) => {\n  const method = headers[':method'];\n  const path = headers[':path'];\n  // ...\n  stream.respond({\n    ':status': 200,\n    'content-type': 'text/plain; charset=utf-8'\n  });\n  stream.write('hello ');\n  stream.end('world');\n});\n
      \n

      On the server side, user code will typically not listen for this event directly,\nand would instead register a handler for the 'stream' event emitted by the\nnet.Server or tls.Server instances returned by http2.createServer() and\nhttp2.createSecureServer(), respectively, as in the example below:

      \n
      const http2 = require('http2');\n\n// Create an unencrypted HTTP/2 server\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.on('error', (error) => console.error(error));\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
      \n

      Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,\na network error will destroy each individual stream and must be handled on the\nstream level, as shown above.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      After the http2session.setTimeout() method is used to set the timeout period\nfor this Http2Session, the 'timeout' event is emitted if there is no\nactivity on the Http2Session after the configured number of milliseconds.\nIts listener does not expect any arguments.

      \n
      session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n
      " + } + ], + "properties": [ + { + "textRaw": "`alpnProtocol` {string|undefined}", + "type": "string|undefined", + "name": "alpnProtocol", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Value will be undefined if the Http2Session is not yet connected to a\nsocket, h2c if the Http2Session is not connected to a TLSSocket, or\nwill return the value of the connected TLSSocket's own alpnProtocol\nproperty.

      " + }, + { + "textRaw": "`closed` {boolean}", + "type": "boolean", + "name": "closed", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Will be true if this Http2Session instance has been closed, otherwise\nfalse.

      " + }, + { + "textRaw": "`connecting` {boolean}", + "type": "boolean", + "name": "connecting", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      Will be true if this Http2Session instance is still connecting, will be set\nto false before emitting connect event and/or calling the http2.connect\ncallback.

      " + }, + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.

      " + }, + { + "textRaw": "`encrypted` {boolean|undefined}", + "type": "boolean|undefined", + "name": "encrypted", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Value is undefined if the Http2Session session socket has not yet been\nconnected, true if the Http2Session is connected with a TLSSocket,\nand false if the Http2Session is connected to any other kind of socket\nor stream.

      " + }, + { + "textRaw": "`localSettings` {HTTP/2 Settings Object}", + "type": "HTTP/2 Settings Object", + "name": "localSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.

      " + }, + { + "textRaw": "`originSet` {string[]|undefined}", + "type": "string[]|undefined", + "name": "originSet", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      If the Http2Session is connected to a TLSSocket, the originSet property\nwill return an Array of origins for which the Http2Session may be\nconsidered authoritative.

      \n

      The originSet property is only available when using a secure TLS connection.

      " + }, + { + "textRaw": "`pendingSettingsAck` {boolean}", + "type": "boolean", + "name": "pendingSettingsAck", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Indicates whether the Http2Session is currently waiting for acknowledgment of\na sent SETTINGS frame. Will be true after calling the\nhttp2session.settings() method. Will be false once all sent SETTINGS\nframes have been acknowledged.

      " + }, + { + "textRaw": "`remoteSettings` {HTTP/2 Settings Object}", + "type": "HTTP/2 Settings Object", + "name": "remoteSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.

      " + }, + { + "textRaw": "`socket` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "socket", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\nlimits available methods to ones safe to use with HTTP/2.

      \n

      destroy, emit, end, pause, read, resume, and write will throw\nan error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See\nHttp2Session and Sockets for more information.

      \n

      setTimeout method will be called on this Http2Session.

      \n

      All other interactions will be routed directly to the socket.

      " + }, + { + "textRaw": "`http2session.state`", + "name": "state", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Provides miscellaneous information about the current state of the\nHttp2Session.

      \n
        \n
      • <Object>\n
          \n
        • effectiveLocalWindowSize <number> The current local (receive)\nflow control window size for the Http2Session.
        • \n
        • effectiveRecvDataLength <number> The current number of bytes\nthat have been received since the last flow control WINDOW_UPDATE.
        • \n
        • nextStreamID <number> The numeric identifier to be used the\nnext time a new Http2Stream is created by this Http2Session.
        • \n
        • localWindowSize <number> The number of bytes that the remote peer can\nsend without receiving a WINDOW_UPDATE.
        • \n
        • lastProcStreamID <number> The numeric id of the Http2Stream\nfor which a HEADERS or DATA frame was most recently received.
        • \n
        • remoteWindowSize <number> The number of bytes that this Http2Session\nmay send without receiving a WINDOW_UPDATE.
        • \n
        • outboundQueueSize <number> The number of frames currently within the\noutbound queue for this Http2Session.
        • \n
        • deflateDynamicTableSize <number> The current size in bytes of the\noutbound header compression state table.
        • \n
        • inflateDynamicTableSize <number> The current size in bytes of the\ninbound header compression state table.
        • \n
        \n
      • \n
      \n

      An object describing the current status of this Http2Session.

      " + }, + { + "textRaw": "`type` {number}", + "type": "number", + "name": "type", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The http2session.type will be equal to\nhttp2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a\nserver, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a\nclient.

      " + } + ], + "methods": [ + { + "textRaw": "`http2session.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Gracefully closes the Http2Session, allowing any existing streams to\ncomplete on their own and preventing new Http2Stream instances from being\ncreated. Once closed, http2session.destroy() might be called if there\nare no open Http2Stream instances.

      \n

      If specified, the callback function is registered as a handler for the\n'close' event.

      " + }, + { + "textRaw": "`http2session.destroy([error][, code])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`error` {Error} An `Error` object if the `Http2Session` is being destroyed due to an error.", + "name": "error", + "type": "Error", + "desc": "An `Error` object if the `Http2Session` is being destroyed due to an error." + }, + { + "textRaw": "`code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`.", + "name": "code", + "type": "number", + "desc": "The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`." + } + ] + } + ], + "desc": "

      Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.

      \n

      Once destroyed, the Http2Session will emit the 'close' event. If error\nis not undefined, an 'error' event will be emitted immediately before the\n'close' event.

      \n

      If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.

      " + }, + { + "textRaw": "`http2session.goaway([code[, lastStreamID[, opaqueData]]])`", + "type": "method", + "name": "goaway", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {number} An HTTP/2 error code", + "name": "code", + "type": "number", + "desc": "An HTTP/2 error code" + }, + { + "textRaw": "`lastStreamID` {number} The numeric ID of the last processed `Http2Stream`", + "name": "lastStreamID", + "type": "number", + "desc": "The numeric ID of the last processed `Http2Stream`" + }, + { + "textRaw": "`opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", + "name": "opaqueData", + "type": "Buffer|TypedArray|DataView", + "desc": "A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame." + } + ] + } + ], + "desc": "

      Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.

      " + }, + { + "textRaw": "`http2session.ping([payload, ]callback)`", + "type": "method", + "name": "ping", + "meta": { + "added": [ + "v8.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`payload` {Buffer|TypedArray|DataView} Optional ping payload.", + "name": "payload", + "type": "Buffer|TypedArray|DataView", + "desc": "Optional ping payload." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sends a PING frame to the connected HTTP/2 peer. A callback function must\nbe provided. The method will return true if the PING was sent, false\notherwise.

      \n

      The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.

      \n

      If provided, the payload must be a Buffer, TypedArray, or DataView\ncontaining 8 bytes of data that will be transmitted with the PING and\nreturned with the ping acknowledgment.

      \n

      The callback will be invoked with three arguments: an error argument that will\nbe null if the PING was successfully acknowledged, a duration argument\nthat reports the number of milliseconds elapsed since the ping was sent and the\nacknowledgment was received, and a Buffer containing the 8-byte PING\npayload.

      \n
      session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {\n  if (!err) {\n    console.log(`Ping acknowledged in ${duration} milliseconds`);\n    console.log(`With payload '${payload.toString()}'`);\n  }\n});\n
      \n

      If the payload argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING duration.

      " + }, + { + "textRaw": "`http2session.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calls ref() on this Http2Session\ninstance's underlying net.Socket.

      " + }, + { + "textRaw": "`http2session.setTimeout(msecs, callback)`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Used to set a callback function that is called when there is no activity on\nthe Http2Session after msecs milliseconds. The given callback is\nregistered as a listener on the 'timeout' event.

      " + }, + { + "textRaw": "`http2session.settings([settings][, callback])`", + "type": "method", + "name": "settings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object}", + "name": "settings", + "type": "HTTP/2 Settings Object" + }, + { + "textRaw": "`callback` {Function} Callback that is called once the session is connected or right away if the session is already connected.", + "name": "callback", + "type": "Function", + "desc": "Callback that is called once the session is connected or right away if the session is already connected.", + "options": [ + { + "textRaw": "`err` {Error|null}", + "name": "err", + "type": "Error|null" + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The updated `settings` object.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The updated `settings` object." + }, + { + "textRaw": "`duration` {integer}", + "name": "duration", + "type": "integer" + } + ] + } + ] + } + ], + "desc": "

      Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.

      \n

      Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.

      \n

      The new settings will not become effective until the SETTINGS acknowledgment\nis received and the 'localSettings' event is emitted. It is possible to send\nmultiple SETTINGS frames while acknowledgment is still pending.

      " + }, + { + "textRaw": "`http2session.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Calls unref() on this Http2Session\ninstance's underlying net.Socket.

      " + } + ] + }, + { + "textRaw": "Class: `ServerHttp2Session`", + "type": "class", + "name": "ServerHttp2Session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "", + "methods": [ + { + "textRaw": "`serverhttp2session.altsvc(alt, originOrStream)`", + "type": "method", + "name": "altsvc", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`alt` {string} A description of the alternative service configuration as defined by [RFC 7838][].", + "name": "alt", + "type": "string", + "desc": "A description of the alternative service configuration as defined by [RFC 7838][]." + }, + { + "textRaw": "`originOrStream` {number|string|URL|Object} Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property.", + "name": "originOrStream", + "type": "number|string|URL|Object", + "desc": "Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property." + } + ] + } + ], + "desc": "

      Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

      \n
      const http2 = require('http2');\n\nconst server = http2.createServer();\nserver.on('session', (session) => {\n  // Set altsvc for origin https://example.org:80\n  session.altsvc('h2=\":8000\"', 'https://example.org:80');\n});\n\nserver.on('stream', (stream) => {\n  // Set altsvc for a specific stream\n  stream.session.altsvc('h2=\":8000\"', stream.id);\n});\n
      \n

      Sending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.

      \n

      The alt and origin string must contain only ASCII bytes and are\nstrictly interpreted as a sequence of ASCII bytes. The special value 'clear'\nmay be passed to clear any previously set alternative service for a given\ndomain.

      \n

      When a string is passed for the originOrStream argument, it will be parsed as\na URL and the origin will be derived. For instance, the origin for the\nHTTP URL 'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.

      \n

      A URL object, or any object with an origin property, may be passed as\noriginOrStream, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.

      " + }, + { + "textRaw": "`serverhttp2session.origin(...origins)`", + "type": "method", + "name": "origin", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`origins` { string | URL | Object } One or more URL Strings passed as separate arguments.", + "name": "origins", + "type": " string | URL | Object ", + "desc": "One or more URL Strings passed as separate arguments." + } + ] + } + ], + "desc": "

      Submits an ORIGIN frame (as defined by RFC 8336) to the connected client\nto advertise the set of origins for which the server is capable of providing\nauthoritative responses.

      \n
      const http2 = require('http2');\nconst options = getSecureOptionsSomehow();\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\nserver.on('session', (session) => {\n  session.origin('https://example.com', 'https://example.org');\n});\n
      \n

      When a string is passed as an origin, it will be parsed as a URL and the\norigin will be derived. For instance, the origin for the HTTP URL\n'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.

      \n

      A URL object, or any object with an origin property, may be passed as\nan origin, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.

      \n

      Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:

      \n
      const http2 = require('http2');\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\n
      " + } + ], + "modules": [ + { + "textRaw": "Specifying alternative services", + "name": "specifying_alternative_services", + "desc": "

      The format of the alt parameter is strictly defined by RFC 7838 as an\nASCII string containing a comma-delimited list of \"alternative\" protocols\nassociated with a specific host and port.

      \n

      For example, the value 'h2=\"example.org:81\"' indicates that the HTTP/2\nprotocol is available on the host 'example.org' on TCP/IP port 81. The\nhost and port must be contained within the quote (\") characters.

      \n

      Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.

      \n

      The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.

      \n

      The syntax of these values is not validated by the Node.js implementation and\nare passed through as provided by the user or received from the peer.

      ", + "type": "module", + "displayName": "Specifying alternative services" + } + ] + }, + { + "textRaw": "Class: `ClientHttp2Session`", + "type": "class", + "name": "ClientHttp2Session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "", + "events": [ + { + "textRaw": "Event: `'altsvc'`", + "type": "event", + "name": "altsvc", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`alt` {string}", + "name": "alt", + "type": "string" + }, + { + "textRaw": "`origin` {string}", + "name": "origin", + "type": "string" + }, + { + "textRaw": "`streamId` {number}", + "name": "streamId", + "type": "number" + } + ], + "desc": "

      The 'altsvc' event is emitted whenever an ALTSVC frame is received by\nthe client. The event is emitted with the ALTSVC value, origin, and stream\nID. If no origin is provided in the ALTSVC frame, origin will\nbe an empty string.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('altsvc', (alt, origin, streamId) => {\n  console.log(alt);\n  console.log(origin);\n  console.log(streamId);\n});\n
      " + }, + { + "textRaw": "Event: `'origin'`", + "type": "event", + "name": "origin", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`origins` {string[]}", + "name": "origins", + "type": "string[]" + } + ], + "desc": "

      The 'origin' event is emitted whenever an ORIGIN frame is received by\nthe client. The event is emitted with an array of origin strings. The\nhttp2session.originSet will be updated to include the received\norigins.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('origin', (origins) => {\n  for (let n = 0; n < origins.length; n++)\n    console.log(origins[n]);\n});\n
      \n

      The 'origin' event is only emitted when using a secure TLS connection.

      " + } + ], + "methods": [ + { + "textRaw": "`clienthttp2session.request(headers[, options])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ClientHttp2Stream}", + "name": "return", + "type": "ClientHttp2Stream" + }, + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`endStream` {boolean} `true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body.", + "name": "endStream", + "type": "boolean", + "desc": "`true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body." + }, + { + "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`.", + "name": "exclusive", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream." + }, + { + "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", + "name": "parent", + "type": "number", + "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." + }, + { + "textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive).", + "name": "weight", + "type": "number", + "desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)." + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + } + ] + } + ] + } + ], + "desc": "

      For HTTP/2 Client Http2Session instances only, the http2session.request()\ncreates and returns an Http2Stream instance that can be used to send an\nHTTP/2 request to the connected server.

      \n

      This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.

      \n
      const http2 = require('http2');\nconst clientSession = http2.connect('https://localhost:1234');\nconst {\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS\n} = http2.constants;\n\nconst req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });\nreq.on('response', (headers) => {\n  console.log(headers[HTTP2_HEADER_STATUS]);\n  req.on('data', (chunk) => { /* .. */ });\n  req.on('end', () => { /* .. */ });\n});\n
      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nis emitted immediately after queuing the last chunk of payload data to be sent.\nThe http2stream.sendTrailers() method can then be called to send trailing\nheaders to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n

      The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:

      \n
        \n
      • :method = 'GET'
      • \n
      • :path = /
      • \n
      " + } + ] + }, + { + "textRaw": "Class: `Http2Stream`", + "type": "class", + "name": "Http2Stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Each instance of the Http2Stream class represents a bidirectional HTTP/2\ncommunications stream over an Http2Session instance. Any single Http2Session\nmay have up to 231-1 Http2Stream instances over its lifetime.

      \n

      User code will not construct Http2Stream instances directly. Rather, these\nare created, managed, and provided to user code through the Http2Session\ninstance. On the server, Http2Stream instances are created either in response\nto an incoming HTTP request (and handed off to user code via the 'stream'\nevent), or in response to a call to the http2stream.pushStream() method.\nOn the client, Http2Stream instances are created and returned when either the\nhttp2session.request() method is called, or in response to an incoming\n'push' event.

      \n

      The Http2Stream class is a base for the ServerHttp2Stream and\nClientHttp2Stream classes, each of which is used specifically by either\nthe Server or Client side, respectively.

      \n

      All Http2Stream instances are Duplex streams. The Writable side of the\nDuplex is used to send data to the connected peer, while the Readable side\nis used to receive data sent by the connected peer.

      \n

      The default text character encoding for all Http2Streams is UTF-8. As a best\npractice, it is recommended that when using an Http2Stream to send text,\nthe 'content-type' header should be set and should identify the character\nencoding used.

      \n
      stream.respond({\n  'content-type': 'text/html; charset=utf-8',\n  ':status': 200\n});\n
      ", + "modules": [ + { + "textRaw": "`Http2Stream` Lifecycle", + "name": "`http2stream`_lifecycle", + "modules": [ + { + "textRaw": "Creation", + "name": "creation", + "desc": "

      On the server side, instances of ServerHttp2Stream are created either\nwhen:

      \n
        \n
      • A new HTTP/2 HEADERS frame with a previously unused stream ID is received;
      • \n
      • The http2stream.pushStream() method is called.
      • \n
      \n

      On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.

      \n

      On the client, the Http2Stream instance returned by http2session.request()\nmay not be immediately ready for use if the parent Http2Session has not yet\nbeen fully established. In such cases, operations called on the Http2Stream\nwill be buffered until the 'ready' event is emitted. User code should rarely,\nif ever, need to handle the 'ready' event directly. The ready status of an\nHttp2Stream can be determined by checking the value of http2stream.id. If\nthe value is undefined, the stream is not yet ready for use.

      ", + "type": "module", + "displayName": "Creation" + }, + { + "textRaw": "Destruction", + "name": "destruction", + "desc": "

      All Http2Stream instances are destroyed either when:

      \n
        \n
      • An RST_STREAM frame for the stream is received by the connected peer,\nand (for client streams only) pending data has been read.
      • \n
      • The http2stream.close() method is called, and (for client streams only)\npending data has been read.
      • \n
      • The http2stream.destroy() or http2session.destroy() methods are called.
      • \n
      \n

      When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame to the connected peer.

      \n

      When the Http2Stream instance is destroyed, the 'close' event will\nbe emitted. Because Http2Stream is an instance of stream.Duplex, the\n'end' event will also be emitted if the stream data is currently flowing.\nThe 'error' event may also be emitted if http2stream.destroy() was called\nwith an Error passed as the first argument.

      \n

      After the Http2Stream has been destroyed, the http2stream.destroyed\nproperty will be true and the http2stream.rstCode property will specify the\nRST_STREAM error code. The Http2Stream instance is no longer usable once\ndestroyed.

      ", + "type": "module", + "displayName": "Destruction" + } + ], + "type": "module", + "displayName": "`Http2Stream` Lifecycle" + } + ], + "events": [ + { + "textRaw": "Event: `'aborted'`", + "type": "event", + "name": "aborted", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.\nIts listener does not expect any arguments.

      \n

      The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.

      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.

      \n

      The HTTP/2 error code used when closing the stream can be retrieved using\nthe http2stream.rstCode property. If the code is any value other than\nNGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted when an error occurs during the processing of\nan Http2Stream.

      " + }, + { + "textRaw": "Event: `'frameError'`", + "type": "event", + "name": "frameError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`type` {integer} The frame type.", + "name": "type", + "type": "integer", + "desc": "The frame type." + }, + { + "textRaw": "`code` {integer} The error code.", + "name": "code", + "type": "integer", + "desc": "The error code." + }, + { + "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", + "name": "id", + "type": "integer", + "desc": "The stream id (or `0` if the frame isn't associated with a stream)." + } + ], + "desc": "

      The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame. When invoked, the handler function will receive an integer\nargument identifying the frame type, and an integer argument identifying the\nerror code. The Http2Stream instance will be destroyed immediately after the\n'frameError' event is emitted.

      " + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'ready' event is emitted when the Http2Stream has been opened, has\nbeen assigned an id, and can be used. The listener does not expect any\narguments.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'timeout' event is emitted after no activity is received for this\nHttp2Stream within the number of milliseconds set using\nhttp2stream.setTimeout().\nIts listener does not expect any arguments.

      " + }, + { + "textRaw": "Event: `'trailers'`", + "type": "event", + "name": "trailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "An object describing the headers" + }, + { + "textRaw": "`flags` {number} The associated numeric flags", + "name": "flags", + "type": "number", + "desc": "The associated numeric flags" + } + ], + "desc": "

      The 'trailers' event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the\nHTTP/2 Headers Object and flags associated with the headers.

      \n

      This event might not be emitted if http2stream.end() is called\nbefore trailers are received and the incoming data is not being read or\nlistened for.

      \n
      stream.on('trailers', (headers, flags) => {\n  console.log(headers);\n});\n
      " + }, + { + "textRaw": "Event: `'wantTrailers'`", + "type": "event", + "name": "wantTrailers", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'wantTrailers' event is emitted when the Http2Stream has queued the\nfinal DATA frame to be sent on a frame and the Http2Stream is ready to send\ntrailing headers. When initiating a request or response, the waitForTrailers\noption must be set for this event to be emitted.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance was aborted abnormally. When set,\nthe 'aborted' event will have been emitted.

      " + }, + { + "textRaw": "`bufferSize` {number}", + "type": "number", + "name": "bufferSize", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This property shows the number of characters currently buffered to be written.\nSee net.Socket.bufferSize for details.

      " + }, + { + "textRaw": "`closed` {boolean}", + "type": "boolean", + "name": "closed", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance has been closed.

      " + }, + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.

      " + }, + { + "textRaw": "`endAfterHeaders` {boolean}", + "type": "boolean", + "name": "endAfterHeaders", + "meta": { + "added": [ + "v10.11.0" + ], + "changes": [] + }, + "desc": "

      Set the true if the END_STREAM flag was set in the request or response\nHEADERS frame received, indicating that no additional data should be received\nand the readable side of the Http2Stream will be closed.

      " + }, + { + "textRaw": "`id` {number|undefined}", + "type": "number|undefined", + "name": "id", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The numeric stream identifier of this Http2Stream instance. Set to undefined\nif the stream identifier has not yet been assigned.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.

      " + }, + { + "textRaw": "`rstCode` {number}", + "type": "number", + "name": "rstCode", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Set to the RST_STREAM error code reported when the Http2Stream is\ndestroyed after either receiving an RST_STREAM frame from the connected peer,\ncalling http2stream.close(), or http2stream.destroy(). Will be\nundefined if the Http2Stream has not been closed.

      " + }, + { + "textRaw": "`sentHeaders` {HTTP/2 Headers Object}", + "type": "HTTP/2 Headers Object", + "name": "sentHeaders", + "meta": { + "added": [ + "v9.5.0" + ], + "changes": [] + }, + "desc": "

      An object containing the outbound headers sent for this Http2Stream.

      " + }, + { + "textRaw": "`sentInfoHeaders` {HTTP/2 Headers Object[]}", + "type": "HTTP/2 Headers Object[]", + "name": "sentInfoHeaders", + "meta": { + "added": [ + "v9.5.0" + ], + "changes": [] + }, + "desc": "

      An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.

      " + }, + { + "textRaw": "`sentTrailers` {HTTP/2 Headers Object}", + "type": "HTTP/2 Headers Object", + "name": "sentTrailers", + "meta": { + "added": [ + "v9.5.0" + ], + "changes": [] + }, + "desc": "

      An object containing the outbound trailers sent for this HttpStream.

      " + }, + { + "textRaw": "`session` {Http2Session}", + "type": "Http2Session", + "name": "session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.

      " + }, + { + "textRaw": "`http2stream.state`", + "name": "state", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Provides miscellaneous information about the current state of the\nHttp2Stream.

      \n
        \n
      • <Object>\n
          \n
        • localWindowSize <number> The number of bytes the connected peer may send\nfor this Http2Stream without receiving a WINDOW_UPDATE.
        • \n
        • state <number> A flag indicating the low-level current state of the\nHttp2Stream as determined by nghttp2.
        • \n
        • localClose <number> 1 if this Http2Stream has been closed locally.
        • \n
        • remoteClose <number> 1 if this Http2Stream has been closed\nremotely.
        • \n
        • sumDependencyWeight <number> The sum weight of all Http2Stream\ninstances that depend on this Http2Stream as specified using\nPRIORITY frames.
        • \n
        • weight <number> The priority weight of this Http2Stream.
        • \n
        \n
      • \n
      \n

      A current state of this Http2Stream.

      " + } + ], + "methods": [ + { + "textRaw": "`http2stream.close(code[, callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {number} Unsigned 32-bit integer identifying the error code. **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).", + "name": "code", + "type": "number", + "default": "`http2.constants.NGHTTP2_NO_ERROR` (`0x00`)", + "desc": "Unsigned 32-bit integer identifying the error code." + }, + { + "textRaw": "`callback` {Function} An optional function registered to listen for the `'close'` event.", + "name": "callback", + "type": "Function", + "desc": "An optional function registered to listen for the `'close'` event." + } + ] + } + ], + "desc": "

      Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.

      " + }, + { + "textRaw": "`http2stream.priority(options)`", + "type": "method", + "name": "priority", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream. **Default:** `false`.", + "name": "exclusive", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream." + }, + { + "textRaw": "`parent` {number} Specifies the numeric identifier of a stream this stream is dependent on.", + "name": "parent", + "type": "number", + "desc": "Specifies the numeric identifier of a stream this stream is dependent on." + }, + { + "textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive).", + "name": "weight", + "type": "number", + "desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)." + }, + { + "textRaw": "`silent` {boolean} When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer.", + "name": "silent", + "type": "boolean", + "desc": "When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer." + } + ] + } + ] + } + ], + "desc": "

      Updates the priority for this Http2Stream instance.

      " + }, + { + "textRaw": "`http2stream.setTimeout(msecs, callback)`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "
      const http2 = require('http2');\nconst client = http2.connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = http2.constants;\nconst req = client.request({ ':path': '/' });\n\n// Cancel the stream if there's no activity after 5 seconds\nreq.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));\n
      " + }, + { + "textRaw": "`http2stream.sendTrailers(headers)`", + "type": "method", + "name": "sendTrailers", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + } + ] + } + ], + "desc": "

      Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method\nwill cause the Http2Stream to be immediately closed and must only be\ncalled after the 'wantTrailers' event has been emitted. When sending a\nrequest or sending a response, the options.waitForTrailers option must be set\nin order to keep the Http2Stream open after the final DATA frame so that\ntrailers can be sent.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond(undefined, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ xyz: 'abc' });\n  });\n  stream.end('Hello World');\n});\n
      \n

      The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).

      " + } + ] + }, + { + "textRaw": "Class: `ClientHttp2Stream`", + "type": "class", + "name": "ClientHttp2Stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      The ClientHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Clients. Http2Stream instances on the client\nprovide events such as 'response' and 'push' that are only relevant on\nthe client.

      ", + "events": [ + { + "textRaw": "Event: `'continue'`", + "type": "event", + "name": "continue", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server sends a 100 Continue status, usually because\nthe request contained Expect: 100-continue. This is an instruction that\nthe client should send the request body.

      " + }, + { + "textRaw": "Event: `'headers'`", + "type": "event", + "name": "headers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'headers' event is emitted when an additional block of headers is received\nfor a stream, such as when a block of 1xx informational headers is received.\nThe listener callback is passed the HTTP/2 Headers Object and flags\nassociated with the headers.

      \n
      stream.on('headers', (headers, flags) => {\n  console.log(headers);\n});\n
      " + }, + { + "textRaw": "Event: `'push'`", + "type": "event", + "name": "push", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'push' event is emitted when response headers for a Server Push stream\nare received. The listener callback is passed the HTTP/2 Headers Object and\nflags associated with the headers.

      \n
      stream.on('push', (headers, flags) => {\n  console.log(headers);\n});\n
      " + }, + { + "textRaw": "Event: `'response'`", + "type": "event", + "name": "response", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'response' event is emitted when a response HEADERS frame has been\nreceived for this stream from the connected HTTP/2 server. The listener is\ninvoked with two arguments: an Object containing the received\nHTTP/2 Headers Object, and flags associated with the headers.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n  console.log(headers[':status']);\n});\n
      " + } + ] + }, + { + "textRaw": "Class: `ServerHttp2Stream`", + "type": "class", + "name": "ServerHttp2Stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      The ServerHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Servers. Http2Stream instances on the server\nprovide additional methods such as http2stream.pushStream() and\nhttp2stream.respond() that are only relevant on the server.

      ", + "methods": [ + { + "textRaw": "`http2stream.additionalHeaders(headers)`", + "type": "method", + "name": "additionalHeaders", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + } + ] + } + ], + "desc": "

      Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

      " + }, + { + "textRaw": "`http2stream.pushStream(headers[, options], callback)`", + "type": "method", + "name": "pushStream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`.", + "name": "exclusive", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream." + }, + { + "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", + "name": "parent", + "type": "number", + "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." + } + ] + }, + { + "textRaw": "`callback` {Function} Callback that is called once the push stream has been initiated.", + "name": "callback", + "type": "Function", + "desc": "Callback that is called once the push stream has been initiated.", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`pushStream` {ServerHttp2Stream} The returned `pushStream` object.", + "name": "pushStream", + "type": "ServerHttp2Stream", + "desc": "The returned `pushStream` object." + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object} Headers object the `pushStream` was initiated with.", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "Headers object the `pushStream` was initiated with." + } + ] + } + ] + } + ], + "desc": "

      Initiates a push stream. The callback is invoked with the new Http2Stream\ninstance created for the push stream passed as the second argument, or an\nError passed as the first argument.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {\n    if (err) throw err;\n    pushStream.respond({ ':status': 200 });\n    pushStream.end('some pushed data');\n  });\n  stream.end('some data');\n});\n
      \n

      Setting the weight of a push stream is not allowed in the HEADERS frame. Pass\na weight value to http2stream.priority with the silent option set to\ntrue to enable server-side bandwidth balancing between concurrent streams.

      \n

      Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.

      " + }, + { + "textRaw": "`http2stream.respond([headers[, options]])`", + "type": "method", + "name": "respond", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33160", + "description": "Allow explicity setting date headers." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`endStream` {boolean} Set to `true` to indicate that the response will not include payload data.", + "name": "endStream", + "type": "boolean", + "desc": "Set to `true` to indicate that the response will not include payload data." + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + } + ] + } + ] + } + ], + "desc": "
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.end('some data');\n});\n
      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 }, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n  stream.end('some data');\n});\n
      " + }, + { + "textRaw": "`http2stream.respondWithFD(fd[, headers[, options]])`", + "type": "method", + "name": "respondWithFD", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33160", + "description": "Allow explicity setting date headers." + }, + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/29876", + "description": "The `fd` option may now be a `FileHandle`." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18936", + "description": "Any readable file descriptor, not necessarily for a regular file, is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fd` {number|FileHandle} A readable file descriptor.", + "name": "fd", + "type": "number|FileHandle", + "desc": "A readable file descriptor." + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`statCheck` {Function}", + "name": "statCheck", + "type": "Function" + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + }, + { + "textRaw": "`offset` {number} The offset position at which to begin reading.", + "name": "offset", + "type": "number", + "desc": "The offset position at which to begin reading." + }, + { + "textRaw": "`length` {number} The amount of data from the fd to send.", + "name": "length", + "type": "number", + "desc": "The amount of data from the fd to send." + } + ] + } + ] + } + ], + "desc": "

      Initiates a response whose data is read from the given file descriptor. No\nvalidation is performed on the given file descriptor. If an error occurs while\nattempting to read data using the file descriptor, the Http2Stream will be\nclosed using an RST_STREAM frame using the standard INTERNAL_ERROR code.

      \n

      When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  const fd = fs.openSync('/some/file', 'r');\n\n  const stat = fs.fstatSync(fd);\n  const headers = {\n    'content-length': stat.size,\n    'last-modified': stat.mtime.toUTCString(),\n    'content-type': 'text/plain; charset=utf-8'\n  };\n  stream.respondWithFD(fd, headers);\n  stream.on('close', () => fs.closeSync(fd));\n});\n
      \n

      The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given fd. If the statCheck function is provided, the\nhttp2stream.respondWithFD() method will perform an fs.fstat() call to\ncollect details on the provided file descriptor.

      \n

      The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.

      \n

      The file descriptor or FileHandle is not closed when the stream is closed,\nso it will need to be closed manually once it is no longer needed.\nUsing the same file descriptor concurrently for multiple streams\nis not supported and may result in data loss. Re-using a file descriptor\nafter a stream has finished is supported.

      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  const fd = fs.openSync('/some/file', 'r');\n\n  const stat = fs.fstatSync(fd);\n  const headers = {\n    'content-length': stat.size,\n    'last-modified': stat.mtime.toUTCString(),\n    'content-type': 'text/plain; charset=utf-8'\n  };\n  stream.respondWithFD(fd, headers, { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n\n  stream.on('close', () => fs.closeSync(fd));\n});\n
      " + }, + { + "textRaw": "`http2stream.respondWithFile(path[, headers[, options]])`", + "type": "method", + "name": "respondWithFile", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33160", + "description": "Allow explicity setting date headers." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18936", + "description": "Any readable file, not necessarily a regular file, is supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`path` {string|Buffer|URL}", + "name": "path", + "type": "string|Buffer|URL" + }, + { + "textRaw": "`headers` {HTTP/2 Headers Object}", + "name": "headers", + "type": "HTTP/2 Headers Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`statCheck` {Function}", + "name": "statCheck", + "type": "Function" + }, + { + "textRaw": "`onError` {Function} Callback function invoked in the case of an error before send.", + "name": "onError", + "type": "Function", + "desc": "Callback function invoked in the case of an error before send." + }, + { + "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", + "name": "waitForTrailers", + "type": "boolean", + "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." + }, + { + "textRaw": "`offset` {number} The offset position at which to begin reading.", + "name": "offset", + "type": "number", + "desc": "The offset position at which to begin reading." + }, + { + "textRaw": "`length` {number} The amount of data from the fd to send.", + "name": "length", + "type": "number", + "desc": "The amount of data from the fd to send." + } + ] + } + ] + } + ], + "desc": "

      Sends a regular file as the response. The path must specify a regular file\nor an 'error' event will be emitted on the Http2Stream object.

      \n

      When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

      \n

      The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given file:

      \n

      If an error occurs while attempting to read the file data, the Http2Stream\nwill be closed using an RST_STREAM frame using the standard INTERNAL_ERROR\ncode. If the onError callback is defined, then it will be called. Otherwise\nthe stream will be destroyed.

      \n

      Example using a file path:

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  function statCheck(stat, headers) {\n    headers['last-modified'] = stat.mtime.toUTCString();\n  }\n\n  function onError(err) {\n    if (err.code === 'ENOENT') {\n      stream.respond({ ':status': 404 });\n    } else {\n      stream.respond({ ':status': 500 });\n    }\n    stream.end();\n  }\n\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain; charset=utf-8' },\n                         { statCheck, onError });\n});\n
      \n

      The options.statCheck function may also be used to cancel the send operation\nby returning false. For instance, a conditional request may check the stat\nresults to determine if the file has been modified to return an appropriate\n304 response:

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  function statCheck(stat, headers) {\n    // Check the stat here...\n    stream.respond({ ':status': 304 });\n    return false; // Cancel the send operation\n  }\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain; charset=utf-8' },\n                         { statCheck });\n});\n
      \n

      The content-length header field will be automatically set.

      \n

      The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.

      \n

      The options.onError function may also be used to handle all the errors\nthat could happen before the delivery of the file is initiated. The\ndefault behavior is to destroy the stream.

      \n

      When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.

      \n

      When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.

      \n
      const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respondWithFile('/some/file',\n                         { 'content-type': 'text/plain; charset=utf-8' },\n                         { waitForTrailers: true });\n  stream.on('wantTrailers', () => {\n    stream.sendTrailers({ ABC: 'some value to send' });\n  });\n});\n
      " + } + ], + "properties": [ + { + "textRaw": "`headersSent` {boolean}", + "type": "boolean", + "name": "headersSent", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      True if headers were sent, false otherwise (read-only).

      " + }, + { + "textRaw": "`pushAllowed` {boolean}", + "type": "boolean", + "name": "pushAllowed", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote\nclient's most recent SETTINGS frame. Will be true if the remote peer\naccepts push streams, false otherwise. Settings are the same for every\nHttp2Stream in the same Http2Session.

      " + } + ] + }, + { + "textRaw": "Class: `Http2Server`", + "type": "class", + "name": "Http2Server", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the http2\nmodule.

      ", + "events": [ + { + "textRaw": "Event: `'checkContinue'`", + "type": "event", + "name": "checkContinue", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      If a 'request' listener is registered or http2.createServer() is\nsupplied a callback function, the 'checkContinue' event is emitted each time\na request with an HTTP Expect: 100-continue is received. If this event is\nnot listened for, the server will automatically respond with a status\n100 Continue as appropriate.

      \n

      Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + } + ] + }, + { + "textRaw": "Class: `Http2SecureServer`", + "type": "class", + "name": "Http2SecureServer", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the http2 module.

      ", + "events": [ + { + "textRaw": "Event: `'checkContinue'`", + "type": "event", + "name": "checkContinue", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      If a 'request' listener is registered or http2.createSecureServer()\nis supplied a callback function, the 'checkContinue' event is emitted each\ntime a request with an HTTP Expect: 100-continue is received. If this event\nis not listened for, the server will automatically respond with a status\n100 Continue as appropriate.

      \n

      Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.

      \n

      When this event is emitted and handled, the 'request' event will\nnot be emitted.

      " + } + ] + } + ], + "events": [ + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.

      ", + "events": [ + { + "textRaw": "Event: `'request'`", + "type": "event", + "name": "request", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

      " + }, + { + "textRaw": "Event: `'session'`", + "type": "event", + "name": "session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.

      " + }, + { + "textRaw": "Event: `'sessionError'`", + "type": "event", + "name": "sessionError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.

      " + }, + { + "textRaw": "Event: `'stream'`", + "type": "event", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

      \n
      const http2 = require('http2');\nconst {\n  HTTP2_HEADER_METHOD,\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n  HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst server = http2.createServer();\nserver.on('stream', (stream, headers, flags) => {\n  const method = headers[HTTP2_HEADER_METHOD];\n  const path = headers[HTTP2_HEADER_PATH];\n  // ...\n  stream.respond({\n    [HTTP2_HEADER_STATUS]: 200,\n    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'\n  });\n  stream.write('hello ');\n  stream.end('world');\n});\n
      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().\nDefault: 2 minutes.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      " + } + ], + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.

      \n

      If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\nnet.Server.close() for more details.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2Server}", + "name": "return", + "type": "Http2Server" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Used to set the timeout value for http2 server requests,\nand sets a callback function that is called when there is no activity\non the Http2Server after msecs milliseconds.

      \n

      The given callback is registered as a listener on the 'timeout' event.

      \n

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK\nerror will be thrown.

      \n

      To change the default timeout use the --http-server-default-timeout\nflag.

      " + } + ] + }, + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established, before the TLS\nhandshake begins. socket is typically an object of type net.Socket.\nUsually users will not want to access this event.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.

      ", + "events": [ + { + "textRaw": "Event: `'request'`", + "type": "event", + "name": "request", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`request` {http2.Http2ServerRequest}", + "name": "request", + "type": "http2.Http2ServerRequest" + }, + { + "textRaw": "`response` {http2.Http2ServerResponse}", + "name": "response", + "type": "http2.Http2ServerResponse" + } + ], + "desc": "

      Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

      " + }, + { + "textRaw": "Event: `'session'`", + "type": "event", + "name": "session", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.

      " + }, + { + "textRaw": "Event: `'sessionError'`", + "type": "event", + "name": "sessionError", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.

      " + }, + { + "textRaw": "Event: `'stream'`", + "type": "event", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

      \n
      const http2 = require('http2');\nconst {\n  HTTP2_HEADER_METHOD,\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n  HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst options = getOptionsSomehow();\n\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream, headers, flags) => {\n  const method = headers[HTTP2_HEADER_METHOD];\n  const path = headers[HTTP2_HEADER_PATH];\n  // ...\n  stream.respond({\n    [HTTP2_HEADER_STATUS]: 200,\n    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'\n  });\n  stream.write('hello ');\n  stream.end('world');\n});\n
      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout().\nDefault: 2 minutes.

      " + }, + { + "textRaw": "Event: `'unknownProtocol'`", + "type": "event", + "name": "unknownProtocol", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'unknownProtocol' event is emitted when a connecting client fails to\nnegotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler\nreceives the socket for handling. If no listener is registered for this event,\nthe connection is terminated. A timeout may be specified using the\n'unknownProtocolTimeout' option passed to http2.createSecureServer().\nSee the Compatibility API.

      " + } + ], + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.

      \n

      If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\ntls.Server.close() for more details.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2SecureServer}", + "name": "return", + "type": "Http2SecureServer" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Used to set the timeout value for http2 secure server requests,\nand sets a callback function that is called when there is no activity\non the Http2SecureServer after msecs milliseconds.

      \n

      The given callback is registered as a listener on the 'timeout' event.

      \n

      In case of no callback function were assigned, a new ERR_INVALID_CALLBACK\nerror will be thrown.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`http2.createServer(options[, onRequestHandler])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.21.0", + "pr-url": "https://github.com/nodejs-private/node-private/pull/250", + "description": "Added `unknownProtocolTimeout` option with a default of 10000." + }, + { + "version": [ + "v12.18.0" + ], + "pr-url": "https://github.com/nodejs-private/node-private/pull/206", + "description": "Added `maxSettings` option with a default of 32." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionRejectedStreams` option with a default of 100." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionInvalidFrames` option with a default of 1000." + }, + { + "version": "v12.4.0", + "pr-url": "https://github.com/nodejs/node/pull/27782", + "description": "The `options` parameter now supports `net.createServer()` options." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17105", + "description": "Added the `maxOutstandingPings` option with a default limit of 10." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." + }, + { + "version": "v9.6.0", + "pr-url": "https://github.com/nodejs/node/pull/15752", + "description": "Added the `Http1IncomingMessage` and `Http1ServerResponse` option." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2Server}", + "name": "return", + "type": "Http2Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", + "name": "maxDeflateDynamicTableSize", + "type": "number", + "default": "`4Kib`", + "desc": "Sets the maximum dynamic table size for deflating header fields." + }, + { + "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", + "name": "maxSettings", + "type": "number", + "default": "`32`", + "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." + }, + { + "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", + "name": "maxSessionMemory", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." + }, + { + "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`. **Default:** `128`.", + "name": "maxHeaderListPairs", + "type": "number", + "default": "`128`", + "desc": "Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`." + }, + { + "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", + "name": "maxOutstandingPings", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum number of outstanding, unacknowledged pings." + }, + { + "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", + "name": "maxSendHeaderBlockLength", + "type": "number", + "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." + }, + { + "textRaw": "`paddingStrategy` {number} The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "name": "paddingStrategy", + "type": "number", + "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "desc": "The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", + "options": [ + { + "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: Specifies that no padding is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_NONE", + "desc": "Specifies that no padding is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_MAX", + "desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK`: Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding.", + "name": "http2.constants.PADDING_STRATEGY_CALLBACK", + "desc": "Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes.", + "name": "http2.constants.PADDING_STRATEGY_ALIGNED", + "desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes." + } + ] + }, + { + "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", + "name": "peerMaxConcurrentStreams", + "type": "number", + "default": "`100`", + "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." + }, + { + "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", + "name": "maxSessionInvalidFrames", + "type": "integer", + "default": "`1000`", + "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." + }, + { + "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", + "name": "maxSessionRejectedStreams", + "type": "integer", + "default": "`100`", + "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." + }, + { + "textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][].", + "name": "selectPadding", + "type": "Function", + "desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][]." + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The initial settings to send to the remote peer upon connection." + }, + { + "textRaw": "`Http1IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`.", + "name": "Http1IncomingMessage", + "type": "http.IncomingMessage", + "default": "`http.IncomingMessage`", + "desc": "Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`." + }, + { + "textRaw": "`Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`. **Default:** `http.ServerResponse`.", + "name": "Http1ServerResponse", + "type": "http.ServerResponse", + "default": "`http.ServerResponse`", + "desc": "Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`." + }, + { + "textRaw": "`Http2ServerRequest` {http2.Http2ServerRequest} Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`. **Default:** `Http2ServerRequest`.", + "name": "Http2ServerRequest", + "type": "http2.Http2ServerRequest", + "default": "`Http2ServerRequest`", + "desc": "Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`." + }, + { + "textRaw": "`Http2ServerResponse` {http2.Http2ServerResponse} Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`. **Default:** `Http2ServerResponse`.", + "name": "Http2ServerResponse", + "type": "http2.Http2ServerResponse", + "default": "`Http2ServerResponse`", + "desc": "Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`." + }, + { + "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", + "name": "unknownProtocolTimeout", + "type": "number", + "default": "`10000`", + "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] is emitted. If the socket has not been destroyed by that time the server will destroy it." + }, + { + "textRaw": "...: Any [`net.createServer()`][] option can be provided.", + "name": "...", + "desc": "Any [`net.createServer()`][] option can be provided." + } + ] + }, + { + "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", + "name": "onRequestHandler", + "type": "Function", + "desc": "See [Compatibility API][]" + } + ] + } + ], + "desc": "

      Returns a net.Server instance that creates and manages Http2Session\ninstances.

      \n

      Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

      \n
      const http2 = require('http2');\n\n// Create an unencrypted HTTP/2 server.\n// Since there are no browsers known that support\n// unencrypted HTTP/2, the use of `http2.createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
      " + }, + { + "textRaw": "`http2.createSecureServer(options[, onRequestHandler])`", + "type": "method", + "name": "createSecureServer", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.21.0", + "pr-url": "https://github.com/nodejs-private/node-private/pull/250", + "description": "Added `unknownProtocolTimeout` option with a default of 10000." + }, + { + "version": [ + "v12.18.0" + ], + "pr-url": "https://github.com/nodejs-private/node-private/pull/206", + "description": "Added `maxSettings` option with a default of 32." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionRejectedStreams` option with a default of 100." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30534", + "description": "Added `maxSessionInvalidFrames` option with a default of 1000." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22956", + "description": "Added the `origins` option to automatically send an `ORIGIN` frame on `Http2Session` startup." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17105", + "description": "Added the `maxOutstandingPings` option with a default limit of 10." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Http2SecureServer}", + "name": "return", + "type": "Http2SecureServer" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`allowHTTP1` {boolean} Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. **Default:** `false`.", + "name": "allowHTTP1", + "type": "boolean", + "default": "`false`", + "desc": "Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]." + }, + { + "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", + "name": "maxDeflateDynamicTableSize", + "type": "number", + "default": "`4Kib`", + "desc": "Sets the maximum dynamic table size for deflating header fields." + }, + { + "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", + "name": "maxSettings", + "type": "number", + "default": "`32`", + "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." + }, + { + "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", + "name": "maxSessionMemory", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." + }, + { + "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`. **Default:** `128`.", + "name": "maxHeaderListPairs", + "type": "number", + "default": "`128`", + "desc": "Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `4`." + }, + { + "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", + "name": "maxOutstandingPings", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum number of outstanding, unacknowledged pings." + }, + { + "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", + "name": "maxSendHeaderBlockLength", + "type": "number", + "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." + }, + { + "textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "name": "paddingStrategy", + "type": "number", + "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", + "options": [ + { + "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: Specifies that no padding is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_NONE", + "desc": "Specifies that no padding is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_MAX", + "desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK`: Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding.", + "name": "http2.constants.PADDING_STRATEGY_CALLBACK", + "desc": "Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes.", + "name": "http2.constants.PADDING_STRATEGY_ALIGNED", + "desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes." + } + ] + }, + { + "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", + "name": "peerMaxConcurrentStreams", + "type": "number", + "default": "`100`", + "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." + }, + { + "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", + "name": "maxSessionInvalidFrames", + "type": "integer", + "default": "`1000`", + "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." + }, + { + "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", + "name": "maxSessionRejectedStreams", + "type": "integer", + "default": "`100`", + "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." + }, + { + "textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][].", + "name": "selectPadding", + "type": "Function", + "desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][]." + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The initial settings to send to the remote peer upon connection." + }, + { + "textRaw": "...: Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required.", + "name": "...", + "desc": "Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required." + }, + { + "textRaw": "`origins` {string[]} An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`.", + "name": "origins", + "type": "string[]", + "desc": "An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`." + }, + { + "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", + "name": "unknownProtocolTimeout", + "type": "number", + "default": "`10000`", + "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it." + } + ] + }, + { + "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", + "name": "onRequestHandler", + "type": "Function", + "desc": "See [Compatibility API][]" + } + ] + } + ], + "desc": "

      Returns a tls.Server instance that creates and manages Http2Session\ninstances.

      \n
      const http2 = require('http2');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem')\n};\n\n// Create a secure HTTP/2 server\nconst server = http2.createSecureServer(options);\n\nserver.on('stream', (stream, headers) => {\n  stream.respond({\n    'content-type': 'text/html; charset=utf-8',\n    ':status': 200\n  });\n  stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
      " + }, + { + "textRaw": "`http2.connect(authority[, options][, listener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v12.21.0", + "pr-url": "https://github.com/nodejs-private/node-private/pull/250", + "description": "Added `unknownProtocolTimeout` option with a default of 10000." + }, + { + "version": [ + "v12.18.0" + ], + "pr-url": "https://github.com/nodejs-private/node-private/pull/206", + "description": "Added `maxSettings` option with a default of 32." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/17105", + "description": "Added the `maxOutstandingPings` option with a default limit of 10." + }, + { + "version": "v8.9.3", + "pr-url": "https://github.com/nodejs/node/pull/16676", + "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {ClientHttp2Session}", + "name": "return", + "type": "ClientHttp2Session" + }, + "params": [ + { + "textRaw": "`authority` {string|URL} The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored.", + "name": "authority", + "type": "string|URL", + "desc": "The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", + "name": "maxDeflateDynamicTableSize", + "type": "number", + "default": "`4Kib`", + "desc": "Sets the maximum dynamic table size for deflating header fields." + }, + { + "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", + "name": "maxSettings", + "type": "number", + "default": "`32`", + "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." + }, + { + "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", + "name": "maxSessionMemory", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." + }, + { + "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `1`. **Default:** `128`.", + "name": "maxHeaderListPairs", + "type": "number", + "default": "`128`", + "desc": "Sets the maximum number of header entries. This is similar to [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. The minimum value is `1`." + }, + { + "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", + "name": "maxOutstandingPings", + "type": "number", + "default": "`10`", + "desc": "Sets the maximum number of outstanding, unacknowledged pings." + }, + { + "textRaw": "`maxReservedRemoteStreams` {number} Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value. **Default:** `200`.", + "name": "maxReservedRemoteStreams", + "type": "number", + "default": "`200`", + "desc": "Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value." + }, + { + "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", + "name": "maxSendHeaderBlockLength", + "type": "number", + "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." + }, + { + "textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "name": "paddingStrategy", + "type": "number", + "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", + "desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", + "options": [ + { + "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: Specifies that no padding is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_NONE", + "desc": "Specifies that no padding is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.", + "name": "http2.constants.PADDING_STRATEGY_MAX", + "desc": "Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_CALLBACK`: Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding.", + "name": "http2.constants.PADDING_STRATEGY_CALLBACK", + "desc": "Specifies that the user provided `options.selectPadding()` callback is to be used to determine the amount of padding." + }, + { + "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes.", + "name": "http2.constants.PADDING_STRATEGY_ALIGNED", + "desc": "Will *attempt* to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will *not* necessarily be aligned at 8 bytes." + } + ] + }, + { + "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", + "name": "peerMaxConcurrentStreams", + "type": "number", + "default": "`100`", + "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." + }, + { + "textRaw": "`selectPadding` {Function} When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][].", + "name": "selectPadding", + "type": "Function", + "desc": "When `options.paddingStrategy` is equal to `http2.constants.PADDING_STRATEGY_CALLBACK`, provides the callback function used to determine the padding. See [Using `options.selectPadding()`][]." + }, + { + "textRaw": "`protocol` {string} The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`. **Default:** `'https:'`", + "name": "protocol", + "type": "string", + "default": "`'https:'`", + "desc": "The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`." + }, + { + "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", + "name": "settings", + "type": "HTTP/2 Settings Object", + "desc": "The initial settings to send to the remote peer upon connection." + }, + { + "textRaw": "`createConnection` {Function} An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any [`Duplex`][] stream that is to be used as the connection for this session.", + "name": "createConnection", + "type": "Function", + "desc": "An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any [`Duplex`][] stream that is to be used as the connection for this session." + }, + { + "textRaw": "...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided.", + "name": "...", + "desc": "Any [`net.connect()`][] or [`tls.connect()`][] options can be provided." + }, + { + "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", + "name": "unknownProtocolTimeout", + "type": "number", + "default": "`10000`", + "desc": "Specifies a timeout in milliseconds that a server should wait when an [`'unknownProtocol'`][] event is emitted. If the socket has not been destroyed by that time the server will destroy it." + } + ] + }, + { + "textRaw": "`listener` {Function} Will be registered as a one-time listener of the [`'connect'`][] event.", + "name": "listener", + "type": "Function", + "desc": "Will be registered as a one-time listener of the [`'connect'`][] event." + } + ] + } + ], + "desc": "

      Returns a ClientHttp2Session instance.

      \n
      const http2 = require('http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n
      " + }, + { + "textRaw": "`http2.getDefaultSettings()`", + "type": "method", + "name": "getDefaultSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {HTTP/2 Settings Object}", + "name": "return", + "type": "HTTP/2 Settings Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing the default settings for an Http2Session\ninstance. This method returns a new object instance every time it is called\nso instances returned may be safely modified for use.

      " + }, + { + "textRaw": "`http2.getPackedSettings([settings])`", + "type": "method", + "name": "getPackedSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`settings` {HTTP/2 Settings Object}", + "name": "settings", + "type": "HTTP/2 Settings Object" + } + ] + } + ], + "desc": "

      Returns a Buffer instance containing serialized representation of the given\nHTTP/2 settings as specified in the HTTP/2 specification. This is intended\nfor use with the HTTP2-Settings header field.

      \n
      const http2 = require('http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
      " + }, + { + "textRaw": "`http2.getUnpackedSettings(buf)`", + "type": "method", + "name": "getUnpackedSettings", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {HTTP/2 Settings Object}", + "name": "return", + "type": "HTTP/2 Settings Object" + }, + "params": [ + { + "textRaw": "`buf` {Buffer|Uint8Array} The packed settings.", + "name": "buf", + "type": "Buffer|Uint8Array", + "desc": "The packed settings." + } + ] + } + ], + "desc": "

      Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().

      " + } + ], + "properties": [ + { + "textRaw": "`http2.constants`", + "name": "constants", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "modules": [ + { + "textRaw": "Error codes for `RST_STREAM` and `GOAWAY`", + "name": "error_codes_for_`rst_stream`_and_`goaway`", + "desc": "

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      ValueNameConstant
      0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
      0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
      0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
      0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
      0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
      0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
      0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
      0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
      0x08Cancelhttp2.constants.NGHTTP2_CANCEL
      0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
      0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
      0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
      0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
      0x0dHTTP/1.1 Requiredhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED
      \n

      The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().

      ", + "type": "module", + "displayName": "Error codes for `RST_STREAM` and `GOAWAY`" + } + ] + } + ], + "type": "module", + "displayName": "Core API" + }, + { + "textRaw": "Compatibility API", + "name": "compatibility_api", + "desc": "

      The Compatibility API has the goal of providing a similar developer experience\nof HTTP/1 when using HTTP/2, making it possible to develop applications\nthat support both HTTP/1 and HTTP/2. This API targets only the\npublic API of the HTTP/1. However many modules use internal\nmethods or state, and those are not supported as it is a completely\ndifferent implementation.

      \n

      The following example creates an HTTP/2 server using the compatibility\nAPI:

      \n
      const http2 = require('http2');\nconst server = http2.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n  res.end('ok');\n});\n
      \n

      In order to create a mixed HTTPS and HTTP/2 server, refer to the\nALPN negotiation section.\nUpgrading from non-tls HTTP/1 servers is not supported.

      \n

      The HTTP/2 compatibility API is composed of Http2ServerRequest and\nHttp2ServerResponse. They aim at API compatibility with HTTP/1, but\nthey do not hide the differences between the protocols. As an example,\nthe status message for HTTP codes is ignored.

      ", + "modules": [ + { + "textRaw": "ALPN negotiation", + "name": "alpn_negotiation", + "desc": "

      ALPN negotiation allows supporting both HTTPS and HTTP/2 over\nthe same socket. The req and res objects can be either HTTP/1 or\nHTTP/2, and an application must restrict itself to the public API of\nHTTP/1, and detect if it is possible to use the more advanced\nfeatures of HTTP/2.

      \n

      The following example creates a server that supports both protocols:

      \n
      const { createSecureServer } = require('http2');\nconst { readFileSync } = require('fs');\n\nconst cert = readFileSync('./cert.pem');\nconst key = readFileSync('./key.pem');\n\nconst server = createSecureServer(\n  { cert, key, allowHTTP1: true },\n  onRequest\n).listen(4443);\n\nfunction onRequest(req, res) {\n  // Detects if it is a HTTPS request or HTTP/2\n  const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?\n    req.stream.session : req;\n  res.writeHead(200, { 'content-type': 'application/json' });\n  res.end(JSON.stringify({\n    alpnProtocol,\n    httpVersion: req.httpVersion\n  }));\n}\n
      \n

      The 'request' event works identically on both HTTPS and\nHTTP/2.

      ", + "type": "module", + "displayName": "ALPN negotiation" + } + ], + "classes": [ + { + "textRaw": "Class: `http2.Http2ServerRequest`", + "type": "class", + "name": "http2.Http2ServerRequest", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      A Http2ServerRequest object is created by http2.Server or\nhttp2.SecureServer and passed as the first argument to the\n'request' event. It may be used to access a request status, headers, and\ndata.

      ", + "events": [ + { + "textRaw": "Event: `'aborted'`", + "type": "event", + "name": "aborted", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.

      \n

      The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.

      " + }, + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.

      " + } + ], + "properties": [ + { + "textRaw": "`aborted` {boolean}", + "type": "boolean", + "name": "aborted", + "meta": { + "added": [ + "v10.1.0" + ], + "changes": [] + }, + "desc": "

      The request.aborted property will be true if the request has\nbeen aborted.

      " + }, + { + "textRaw": "`authority` {string}", + "type": "string", + "name": "authority", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request authority pseudo header field. It can also be accessed via\nreq.headers[':authority'].

      " + }, + { + "textRaw": "`complete` {boolean}", + "type": "boolean", + "name": "complete", + "meta": { + "added": [ + "v12.10.0" + ], + "changes": [] + }, + "desc": "

      The request.complete property will be true if the request has\nbeen completed, aborted, or destroyed.

      " + }, + { + "textRaw": "`headers` {Object}", + "type": "Object", + "name": "headers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request/response headers object.

      \n

      Key-value pairs of header names and values. Header names are lower-cased.

      \n
      // Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);\n
      \n

      See HTTP/2 Headers Object.

      \n

      In HTTP/2, the request path, host name, protocol, and method are represented as\nspecial headers prefixed with the : character (e.g. ':path'). These special\nheaders will be included in the request.headers object. Care must be taken not\nto inadvertently modify these special headers or errors may occur. For instance,\nremoving all headers from the request will cause errors to occur:

      \n
      removeAllHeaders(request.headers);\nassert(request.url);   // Fails because the :path header has been removed\n
      " + }, + { + "textRaw": "`httpVersion` {string}", + "type": "string", + "name": "httpVersion", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server. Returns\n'2.0'.

      \n

      Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

      " + }, + { + "textRaw": "`method` {string}", + "type": "string", + "name": "method", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

      " + }, + { + "textRaw": "`rawHeaders` {string[]}", + "type": "string[]", + "name": "rawHeaders", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The raw request/response headers list exactly as they were received.

      \n

      The keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.

      \n

      Header names are not lowercased, and duplicates are not merged.

      \n
      // Prints something like:\n//\n// [ 'user-agent',\n//   'this is invalid because there can be only one',\n//   'User-Agent',\n//   'curl/7.22.0',\n//   'Host',\n//   '127.0.0.1:8000',\n//   'ACCEPT',\n//   '*/*' ]\nconsole.log(request.rawHeaders);\n
      " + }, + { + "textRaw": "`rawTrailers` {string[]}", + "type": "string[]", + "name": "rawTrailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`scheme` {string}", + "type": "string", + "name": "scheme", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request scheme pseudo header field indicating the scheme\nportion of the target URL.

      " + }, + { + "textRaw": "`socket` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "socket", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.

      \n

      destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.

      \n

      destroy, emit, end, on and once methods will be called on\nrequest.stream.

      \n

      setTimeout method will be called on request.stream.session.

      \n

      pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

      \n

      All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.

      " + }, + { + "textRaw": "`stream` {Http2Stream}", + "type": "Http2Stream", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The Http2Stream object backing the request.

      " + }, + { + "textRaw": "`trailers` {Object}", + "type": "Object", + "name": "trailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The request/response trailers object. Only populated at the 'end' event.

      " + }, + { + "textRaw": "`url` {string}", + "type": "string", + "name": "url", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Request URL string. This contains only the URL that is present in the actual\nHTTP request. If the request is:

      \n
      GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
      \n

      Then request.url will be:

      \n\n
      '/status?name=ryan'\n
      \n

      To parse the url into its parts, require('url').parse(request.url)\ncan be used:

      \n
      $ node\n> require('url').parse('/status?name=ryan')\nUrl {\n  protocol: null,\n  slashes: null,\n  auth: null,\n  host: null,\n  port: null,\n  hostname: null,\n  hash: null,\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status',\n  path: '/status?name=ryan',\n  href: '/status?name=ryan' }\n
      \n

      To obtain the parameters from the query string, use the\nrequire('querystring').parse() function or pass\ntrue as the second argument to require('url').parse().

      \n
      $ node\n> require('url').parse('/status?name=ryan', true)\nUrl {\n  protocol: null,\n  slashes: null,\n  auth: null,\n  host: null,\n  port: null,\n  hostname: null,\n  hash: null,\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status',\n  path: '/status?name=ryan',\n  href: '/status?name=ryan' }\n
      " + } + ], + "methods": [ + { + "textRaw": "`request.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      Calls destroy() on the Http2Stream that received\nthe Http2ServerRequest. If error is provided, an 'error' event\nis emitted and error is passed as an argument to any listeners on the event.

      \n

      It does nothing if the stream was already destroyed.

      " + }, + { + "textRaw": "`request.setTimeout(msecs, callback)`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http2.Http2ServerRequest}", + "name": "return", + "type": "http2.Http2ServerRequest" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.

      \n

      If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.

      " + } + ] + }, + { + "textRaw": "Class: `http2.Http2ServerResponse`", + "type": "class", + "name": "http2.Http2ServerResponse", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "\n

      This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.

      " + }, + { + "textRaw": "Event: `'finish'`", + "type": "event", + "name": "finish", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the HTTP/2 multiplexing for transmission over the network. It\ndoes not imply that the client has received anything yet.

      \n

      After this event, no more events will be emitted on the response object.

      " + } + ], + "methods": [ + { + "textRaw": "`response.addTrailers(headers)`", + "type": "method", + "name": "addTrailers", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `ServerResponse`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.

      \n

      If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).

      \n

      If callback is specified, it will be called when the response stream\nis finished.

      " + }, + { + "textRaw": "`response.getHeader(name)`", + "type": "method", + "name": "getHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Reads out a header that has already been queued but not sent to the client.\nThe name is case-insensitive.

      \n
      const contentType = response.getHeader('content-type');\n
      " + }, + { + "textRaw": "`response.getHeaderNames()`", + "type": "method", + "name": "getHeaderNames", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
      " + }, + { + "textRaw": "`response.getHeaders()`", + "type": "method", + "name": "getHeaders", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.

      \n

      The object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.

      \n
      response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
      " + }, + { + "textRaw": "`response.hasHeader(name)`", + "type": "method", + "name": "hasHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

      \n
      const hasContentType = response.hasHeader('content-type');\n
      " + }, + { + "textRaw": "`response.removeHeader(name)`", + "type": "method", + "name": "removeHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Removes a header that has been queued for implicit sending.

      \n
      response.removeHeader('Content-Encoding');\n
      " + }, + { + "textRaw": "`response.setHeader(name, value)`", + "type": "method", + "name": "setHeader", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {string|string[]}", + "name": "value", + "type": "string|string[]" + } + ] + } + ], + "desc": "

      Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.

      \n
      response.setHeader('Content-Type', 'text/html; charset=utf-8');\n
      \n

      or

      \n
      response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n
      // Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html; charset=utf-8');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n  res.end('ok');\n});\n
      " + }, + { + "textRaw": "`response.setTimeout(msecs[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http2.Http2ServerResponse}", + "name": "return", + "type": "http2.Http2ServerResponse" + }, + "params": [ + { + "textRaw": "`msecs` {number}", + "name": "msecs", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.

      \n

      If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.

      " + }, + { + "textRaw": "`response.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer|Uint8Array}", + "name": "chunk", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

      \n

      This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

      \n

      In the http module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204 and 304 responses\nmust not include a message body.

      \n

      chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'. callback will be called when this chunk\nof data is flushed.

      \n

      This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

      \n

      The first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.

      " + }, + { + "textRaw": "`response.writeContinue()`", + "type": "method", + "name": "writeContinue", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.

      " + }, + { + "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", + "type": "method", + "name": "writeHead", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [ + { + "version": "v11.10.0", + "pr-url": "https://github.com/nodejs/node/pull/25974", + "description": "Return `this` from `writeHead()` to allow chaining with `end()`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {http2.Http2ServerResponse}", + "name": "return", + "type": "http2.Http2ServerResponse" + }, + "params": [ + { + "textRaw": "`statusCode` {number}", + "name": "statusCode", + "type": "number" + }, + { + "textRaw": "`statusMessage` {string}", + "name": "statusMessage", + "type": "string" + }, + { + "textRaw": "`headers` {Object}", + "name": "headers", + "type": "Object" + } + ] + } + ], + "desc": "

      Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.

      \n

      Returns a reference to the Http2ServerResponse, so that calls can be chained.

      \n

      For compatibility with HTTP/1, a human-readable statusMessage may be\npassed as the second argument. However, because the statusMessage has no\nmeaning within HTTP/2, the argument will have no effect and a process warning\nwill be emitted.

      \n
      const body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain; charset=utf-8' });\n
      \n

      Content-Length is given in bytes not characters. The\nBuffer.byteLength() API may be used to determine the number of bytes in a\ngiven encoding. On outbound messages, Node.js does not check if Content-Length\nand the length of the body being transmitted are equal or not. However, when\nreceiving messages, Node.js will automatically reject messages when the\nContent-Length does not match the actual payload size.

      \n

      This method may be called at most one time on a message before\nresponse.end() is called.

      \n

      If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

      \n

      When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.

      \n
      // Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n  res.setHeader('Content-Type', 'text/html; charset=utf-8');\n  res.setHeader('X-Foo', 'bar');\n  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n  res.end('ok');\n});\n
      \n

      Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

      " + }, + { + "textRaw": "`response.createPushResponse(headers, callback)`", + "type": "method", + "name": "createPushResponse", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", + "name": "headers", + "type": "HTTP/2 Headers Object", + "desc": "An object describing the headers" + }, + { + "textRaw": "`callback` {Function} Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", + "name": "callback", + "type": "Function", + "desc": "Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`stream` {ServerHttp2Stream} The newly-created `ServerHttp2Stream` object", + "name": "stream", + "type": "ServerHttp2Stream", + "desc": "The newly-created `ServerHttp2Stream` object" + } + ] + } + ] + } + ], + "desc": "

      Call http2stream.pushStream() with the given headers, and wrap the\ngiven Http2Stream on a newly created Http2ServerResponse as the callback\nparameter if successful. When Http2ServerRequest is closed, the callback is\ncalled with an error ERR_HTTP2_INVALID_STREAM.

      " + } + ], + "properties": [ + { + "textRaw": "`connection` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "connection", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      See response.socket.

      " + }, + { + "textRaw": "`finished` {boolean}", + "type": "boolean", + "name": "finished", + "meta": { + "added": [ + "v8.4.0" + ], + "deprecated": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated. Use [`response.writableEnded`][].", + "desc": "

      Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.

      " + }, + { + "textRaw": "`headersSent` {boolean}", + "type": "boolean", + "name": "headersSent", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      True if headers were sent, false otherwise (read-only).

      " + }, + { + "textRaw": "`sendDate` {boolean}", + "type": "boolean", + "name": "sendDate", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.

      \n

      This should only be disabled for testing; HTTP requires the Date header\nin responses.

      " + }, + { + "textRaw": "`socket` {net.Socket|tls.TLSSocket}", + "type": "net.Socket|tls.TLSSocket", + "name": "socket", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.

      \n

      destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.

      \n

      destroy, emit, end, on and once methods will be called on\nresponse.stream.

      \n

      setTimeout method will be called on response.stream.session.

      \n

      pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

      \n

      All other interactions will be routed directly to the socket.

      \n
      const http2 = require('http2');\nconst server = http2.createServer((req, res) => {\n  const ip = req.socket.remoteAddress;\n  const port = req.socket.remotePort;\n  res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
      " + }, + { + "textRaw": "`statusCode` {number}", + "type": "number", + "name": "statusCode", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.

      \n
      response.statusCode = 404;\n
      \n

      After response header was sent to the client, this property indicates the\nstatus code which was sent out.

      " + }, + { + "textRaw": "`statusMessage` {string}", + "type": "string", + "name": "statusMessage", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns\nan empty string.

      " + }, + { + "textRaw": "`stream` {Http2Stream}", + "type": "Http2Stream", + "name": "stream", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "desc": "

      The Http2Stream object backing the response.

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.

      " + } + ] + } + ], + "type": "module", + "displayName": "Compatibility API" + }, + { + "textRaw": "Collecting HTTP/2 performance metrics", + "name": "collecting_http/2_performance_metrics", + "desc": "

      The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.

      \n
      const { PerformanceObserver } = require('perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n  const entry = items.getEntries()[0];\n  console.log(entry.entryType);  // prints 'http2'\n  if (entry.name === 'Http2Session') {\n    // Entry contains statistics about the Http2Session\n  } else if (entry.name === 'Http2Stream') {\n    // Entry contains statistics about the Http2Stream\n  }\n});\nobs.observe({ entryTypes: ['http2'] });\n
      \n

      The entryType property of the PerformanceEntry will be equal to 'http2'.

      \n

      The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.

      \n

      If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:

      \n
        \n
      • bytesRead <number> The number of DATA frame bytes received for this\nHttp2Stream.
      • \n
      • bytesWritten <number> The number of DATA frame bytes sent for this\nHttp2Stream.
      • \n
      • id <number> The identifier of the associated Http2Stream
      • \n
      • timeToFirstByte <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first DATA frame.
      • \n
      • timeToFirstByteSent <number> The number of milliseconds elapsed between\nthe PerformanceEntry startTime and sending of the first DATA frame.
      • \n
      • timeToFirstHeader <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first header.
      • \n
      \n

      If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:

      \n
        \n
      • bytesRead <number> The number of bytes received for this Http2Session.
      • \n
      • bytesWritten <number> The number of bytes sent for this Http2Session.
      • \n
      • framesReceived <number> The number of HTTP/2 frames received by the\nHttp2Session.
      • \n
      • framesSent <number> The number of HTTP/2 frames sent by the Http2Session.
      • \n
      • maxConcurrentStreams <number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session.
      • \n
      • pingRTT <number> The number of milliseconds elapsed since the transmission\nof a PING frame and the reception of its acknowledgment. Only present if\na PING frame has been sent on the Http2Session.
      • \n
      • streamAverageDuration <number> The average duration (in milliseconds) for\nall Http2Stream instances.
      • \n
      • streamCount <number> The number of Http2Stream instances processed by\nthe Http2Session.
      • \n
      • type <string> Either 'server' or 'client' to identify the type of\nHttp2Session.
      • \n
      ", + "type": "module", + "displayName": "Collecting HTTP/2 performance metrics" + } + ], + "type": "module", + "displayName": "HTTP/2" + } + ] +} \ No newline at end of file diff --git a/doc/api/https.html b/doc/api/https.html new file mode 100644 index 0000000000000000000000000000000000000000..98a8d8942de4667613ddbf87afecde43250ebde0 --- /dev/null +++ b/doc/api/https.html @@ -0,0 +1,559 @@ + + + + + + + HTTPS | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      HTTPS#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/https.js

      +

      HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a +separate module.

      +

      Class: https.Agent#

      + +

      An Agent object for HTTPS similar to http.Agent. See +https.request() for more information.

      +

      new Agent([options])#

      + +
        +
      • +

        options <Object> Set of configurable options to set on the agent. +Can have the same fields as for http.Agent(options), and

        +
          +
        • +

          maxCachedSessions <number> maximum number of TLS cached sessions. +Use 0 to disable TLS session caching. Default: 100.

          +
        • +
        • +

          servername <string> the value of +Server Name Indication extension to be sent to the server. Use +empty string '' to disable sending the extension. +Default: host name of the target server, unless the target server +is specified using an IP address, in which case the default is '' (no +extension).

          +

          See Session Resumption for information about TLS session reuse.

          +
        • +
        +
      • +
      +

      Event: 'keylog'#

      + +
        +
      • line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.
      • +
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance on which it was +generated.
      • +
      +

      The keylog event is emitted when key material is generated or received by a +connection managed by this agent (typically before handshake has completed, but +not necessarily). This keying material can be stored for debugging, as it +allows captured TLS traffic to be decrypted. It may be emitted multiple times +for each socket.

      +

      A typical use case is to append received lines to a common text file, which is +later used by software (such as Wireshark) to decrypt the traffic:

      +
      // ...
      +https.globalAgent.on('keylog', (line, tlsSocket) => {
      +  fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });
      +});
      +

      Class: https.Server#

      + + +

      See http.Server for more information.

      +

      server.close([callback])#

      + + +

      See server.close() from the HTTP module for details.

      +

      server.headersTimeout#

      + + +

      See http.Server#headersTimeout.

      +

      server.listen()#

      +

      Starts the HTTPS server listening for encrypted connections. +This method is identical to server.listen() from net.Server.

      +

      server.maxHeadersCount#

      + +

      See http.Server#maxHeadersCount.

      +

      server.setTimeout([msecs][, callback])#

      + + +

      See http.Server#setTimeout().

      +

      server.timeout#

      + +
        +
      • <number> Default: 120000 (2 minutes)
      • +
      +

      See http.Server#timeout.

      +

      server.keepAliveTimeout#

      + + +

      See http.Server#keepAliveTimeout.

      +

      https.createServer([options][, requestListener])#

      + + +
      // curl -k https://localhost:8000/
      +const https = require('https');
      +const fs = require('fs');
      +
      +const options = {
      +  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      +  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
      +};
      +
      +https.createServer(options, (req, res) => {
      +  res.writeHead(200);
      +  res.end('hello world\n');
      +}).listen(8000);
      +

      Or

      +
      const https = require('https');
      +const fs = require('fs');
      +
      +const options = {
      +  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
      +  passphrase: 'sample'
      +};
      +
      +https.createServer(options, (req, res) => {
      +  res.writeHead(200);
      +  res.end('hello world\n');
      +}).listen(8000);
      +

      https.get(options[, callback])#

      +

      https.get(url[, options][, callback])#

      + + +

      Like http.get() but for HTTPS.

      +

      options can be an object, a string, or a URL object. If options is a +string, it is automatically parsed with new URL(). If it is a URL +object, it will be automatically converted to an ordinary options object.

      +
      const https = require('https');
      +
      +https.get('https://encrypted.google.com/', (res) => {
      +  console.log('statusCode:', res.statusCode);
      +  console.log('headers:', res.headers);
      +
      +  res.on('data', (d) => {
      +    process.stdout.write(d);
      +  });
      +
      +}).on('error', (e) => {
      +  console.error(e);
      +});
      +

      https.globalAgent#

      + +

      Global instance of https.Agent for all HTTPS client requests.

      +

      https.request(options[, callback])#

      +

      https.request(url[, options][, callback])#

      + + +

      Makes a request to a secure web server.

      +

      The following additional options from tls.connect() are also accepted: +ca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve, +honorCipherOrder, key, passphrase, pfx, rejectUnauthorized, +secureOptions, secureProtocol, servername, sessionIdContext.

      +

      options can be an object, a string, or a URL object. If options is a +string, it is automatically parsed with new URL(). If it is a URL +object, it will be automatically converted to an ordinary options object.

      +
      const https = require('https');
      +
      +const options = {
      +  hostname: 'encrypted.google.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET'
      +};
      +
      +const req = https.request(options, (res) => {
      +  console.log('statusCode:', res.statusCode);
      +  console.log('headers:', res.headers);
      +
      +  res.on('data', (d) => {
      +    process.stdout.write(d);
      +  });
      +});
      +
      +req.on('error', (e) => {
      +  console.error(e);
      +});
      +req.end();
      +

      Example using options from tls.connect():

      +
      const options = {
      +  hostname: 'encrypted.google.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET',
      +  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      +  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
      +};
      +options.agent = new https.Agent(options);
      +
      +const req = https.request(options, (res) => {
      +  // ...
      +});
      +

      Alternatively, opt out of connection pooling by not using an Agent.

      +
      const options = {
      +  hostname: 'encrypted.google.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET',
      +  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
      +  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
      +  agent: false
      +};
      +
      +const req = https.request(options, (res) => {
      +  // ...
      +});
      +

      Example using a URL as options:

      +
      const options = new URL('https://abc:xyz@example.com');
      +
      +const req = https.request(options, (res) => {
      +  // ...
      +});
      +

      Example pinning on certificate fingerprint, or the public key (similar to +pin-sha256):

      +
      const tls = require('tls');
      +const https = require('https');
      +const crypto = require('crypto');
      +
      +function sha256(s) {
      +  return crypto.createHash('sha256').update(s).digest('base64');
      +}
      +const options = {
      +  hostname: 'github.com',
      +  port: 443,
      +  path: '/',
      +  method: 'GET',
      +  checkServerIdentity: function(host, cert) {
      +    // Make sure the certificate is issued to the host we are connected to
      +    const err = tls.checkServerIdentity(host, cert);
      +    if (err) {
      +      return err;
      +    }
      +
      +    // Pin the public key, similar to HPKP pin-sha25 pinning
      +    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
      +    if (sha256(cert.pubkey) !== pubkey256) {
      +      const msg = 'Certificate verification error: ' +
      +        `The public key of '${cert.subject.CN}' ` +
      +        'does not match our pinned fingerprint';
      +      return new Error(msg);
      +    }
      +
      +    // Pin the exact certificate, rather than the pub key
      +    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
      +      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
      +    if (cert.fingerprint256 !== cert256) {
      +      const msg = 'Certificate verification error: ' +
      +        `The certificate of '${cert.subject.CN}' ` +
      +        'does not match our pinned fingerprint';
      +      return new Error(msg);
      +    }
      +
      +    // This loop is informational only.
      +    // Print the certificate and public key fingerprints of all certs in the
      +    // chain. Its common to pin the public key of the issuer on the public
      +    // internet, while pinning the public key of the service in sensitive
      +    // environments.
      +    do {
      +      console.log('Subject Common Name:', cert.subject.CN);
      +      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);
      +
      +      hash = crypto.createHash('sha256');
      +      console.log('  Public key ping-sha256:', sha256(cert.pubkey));
      +
      +      lastprint256 = cert.fingerprint256;
      +      cert = cert.issuerCertificate;
      +    } while (cert.fingerprint256 !== lastprint256);
      +
      +  },
      +};
      +
      +options.agent = new https.Agent(options);
      +const req = https.request(options, (res) => {
      +  console.log('All OK. Server matched our pinned cert or public key');
      +  console.log('statusCode:', res.statusCode);
      +  // Print the HPKP values
      +  console.log('headers:', res.headers['public-key-pins']);
      +
      +  res.on('data', (d) => {});
      +});
      +
      +req.on('error', (e) => {
      +  console.error(e.message);
      +});
      +req.end();
      +

      Outputs for example:

      +
      Subject Common Name: github.com
      +  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
      +  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
      +Subject Common Name: DigiCert SHA2 Extended Validation Server CA
      +  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
      +  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
      +Subject Common Name: DigiCert High Assurance EV Root CA
      +  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
      +  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
      +All OK. Server matched our pinned cert or public key
      +statusCode: 200
      +headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
      + +
      +
      +
      + + diff --git a/doc/api/https.json b/doc/api/https.json new file mode 100644 index 0000000000000000000000000000000000000000..3754a5f2c1caaf9e9bda9e605223b8d1db80e668 --- /dev/null +++ b/doc/api/https.json @@ -0,0 +1,478 @@ +{ + "type": "module", + "source": "doc/api/https.md", + "modules": [ + { + "textRaw": "HTTPS", + "name": "https", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/https.js

      \n

      HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.

      ", + "classes": [ + { + "textRaw": "Class: `https.Agent`", + "type": "class", + "name": "https.Agent", + "meta": { + "added": [ + "v0.4.5" + ], + "changes": [ + { + "version": "v2.5.0", + "pr-url": "https://github.com/nodejs/node/pull/2228", + "description": "parameter `maxCachedSessions` added to `options` for TLS sessions reuse." + }, + { + "version": "v5.3.0", + "pr-url": "https://github.com/nodejs/node/pull/4252", + "description": "support `0` `maxCachedSessions` to disable TLS session caching." + } + ] + }, + "desc": "

      An Agent object for HTTPS similar to http.Agent. See\nhttps.request() for more information.

      ", + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the same fields as for [`http.Agent(options)`][], and", + "name": "options", + "type": "Object", + "desc": "Set of configurable options to set on the agent. Can have the same fields as for [`http.Agent(options)`][], and", + "options": [ + { + "textRaw": "`maxCachedSessions` {number} maximum number of TLS cached sessions. Use `0` to disable TLS session caching. **Default:** `100`.", + "name": "maxCachedSessions", + "type": "number", + "default": "`100`", + "desc": "maximum number of TLS cached sessions. Use `0` to disable TLS session caching." + }, + { + "textRaw": "`servername` {string} the value of [Server Name Indication extension][sni wiki] to be sent to the server. Use empty string `''` to disable sending the extension. **Default:** host name of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).See [`Session Resumption`][] for information about TLS session reuse.", + "name": "servername", + "type": "string", + "default": "host name of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).See [`Session Resumption`][] for information about TLS session reuse", + "desc": "the value of [Server Name Indication extension][sni wiki] to be sent to the server. Use empty string `''` to disable sending the extension." + } + ] + } + ] + } + ] + }, + { + "textRaw": "Class: `https.Server`", + "type": "class", + "name": "https.Server", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "desc": "\n

      See http.Server for more information.

      ", + "methods": [ + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {https.Server}", + "name": "return", + "type": "https.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      See server.close() from the HTTP module for details.

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts the HTTPS server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.

      " + }, + { + "textRaw": "`server.setTimeout([msecs][, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {https.Server}", + "name": "return", + "type": "https.Server" + }, + "params": [ + { + "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", + "name": "msecs", + "type": "number", + "default": "`120000` (2 minutes)" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      See http.Server#setTimeout().

      " + } + ], + "properties": [ + { + "textRaw": "`headersTimeout` {number} **Default:** `60000`", + "type": "number", + "name": "headersTimeout", + "meta": { + "added": [ + "v11.3.0" + ], + "changes": [] + }, + "default": "`60000`", + "desc": "

      See http.Server#headersTimeout.

      " + }, + { + "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", + "type": "number", + "name": "maxHeadersCount", + "default": "`2000`", + "desc": "

      See http.Server#maxHeadersCount.

      " + }, + { + "textRaw": "`timeout` {number} **Default:** `120000` (2 minutes)", + "type": "number", + "name": "timeout", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "default": "`120000` (2 minutes)", + "desc": "

      See http.Server#timeout.

      " + }, + { + "textRaw": "`keepAliveTimeout` {number} **Default:** `5000` (5 seconds)", + "type": "number", + "name": "keepAliveTimeout", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "default": "`5000` (5 seconds)", + "desc": "

      See http.Server#keepAliveTimeout.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`https.createServer([options][, requestListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {https.Server}", + "name": "return", + "type": "https.Server" + }, + "params": [ + { + "textRaw": "`options` {Object} Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][].", + "name": "options", + "type": "Object", + "desc": "Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][]." + }, + { + "textRaw": "`requestListener` {Function} A listener to be added to the `'request'` event.", + "name": "requestListener", + "type": "Function", + "desc": "A listener to be added to the `'request'` event." + } + ] + } + ], + "desc": "
      // curl -k https://localhost:8000/\nconst https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, (req, res) => {\n  res.writeHead(200);\n  res.end('hello world\\n');\n}).listen(8000);\n
      \n

      Or

      \n
      const https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),\n  passphrase: 'sample'\n};\n\nhttps.createServer(options, (req, res) => {\n  res.writeHead(200);\n  res.end('hello world\\n');\n}).listen(8000);\n
      " + }, + { + "textRaw": "`https.get(options[, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`.", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Like http.get() but for HTTPS.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nhttps.get('https://encrypted.google.com/', (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n\n}).on('error', (e) => {\n  console.error(e);\n});\n
      " + }, + { + "textRaw": "`https.get(url[, options][, callback])`", + "type": "method", + "name": "get", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`.", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Like http.get() but for HTTPS.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nhttps.get('https://encrypted.google.com/', (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n\n}).on('error', (e) => {\n  console.error(e);\n});\n
      " + }, + { + "textRaw": "`https.request(options[, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts all `options` from [`http.request()`][], with some differences in default values:", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts all `options` from [`http.request()`][], with some differences in default values:", + "options": [ + { + "textRaw": "`protocol` **Default:** `'https:'`", + "name": "protocol", + "default": "`'https:'`" + }, + { + "textRaw": "`port` **Default:** `443`", + "name": "port", + "default": "`443`" + }, + { + "textRaw": "`agent` **Default:** `https.globalAgent`", + "name": "agent", + "default": "`https.globalAgent`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Makes a request to a secure web server.

      \n

      The following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nconst options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nconst req = https.request(options, (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(e);\n});\nreq.end();\n
      \n

      Example using options from tls.connect():

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Alternatively, opt out of connection pooling by not using an Agent.

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example using a URL as options:

      \n
      const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example pinning on certificate fingerprint, or the public key (similar to\npin-sha256):

      \n
      const tls = require('tls');\nconst https = require('https');\nconst crypto = require('crypto');\n\nfunction sha256(s) {\n  return crypto.createHash('sha256').update(s).digest('base64');\n}\nconst options = {\n  hostname: 'github.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  checkServerIdentity: function(host, cert) {\n    // Make sure the certificate is issued to the host we are connected to\n    const err = tls.checkServerIdentity(host, cert);\n    if (err) {\n      return err;\n    }\n\n    // Pin the public key, similar to HPKP pin-sha25 pinning\n    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';\n    if (sha256(cert.pubkey) !== pubkey256) {\n      const msg = 'Certificate verification error: ' +\n        `The public key of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // Pin the exact certificate, rather than the pub key\n    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +\n      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';\n    if (cert.fingerprint256 !== cert256) {\n      const msg = 'Certificate verification error: ' +\n        `The certificate of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // This loop is informational only.\n    // Print the certificate and public key fingerprints of all certs in the\n    // chain. Its common to pin the public key of the issuer on the public\n    // internet, while pinning the public key of the service in sensitive\n    // environments.\n    do {\n      console.log('Subject Common Name:', cert.subject.CN);\n      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);\n\n      hash = crypto.createHash('sha256');\n      console.log('  Public key ping-sha256:', sha256(cert.pubkey));\n\n      lastprint256 = cert.fingerprint256;\n      cert = cert.issuerCertificate;\n    } while (cert.fingerprint256 !== lastprint256);\n\n  },\n};\n\noptions.agent = new https.Agent(options);\nconst req = https.request(options, (res) => {\n  console.log('All OK. Server matched our pinned cert or public key');\n  console.log('statusCode:', res.statusCode);\n  // Print the HPKP values\n  console.log('headers:', res.headers['public-key-pins']);\n\n  res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n  console.error(e.message);\n});\nreq.end();\n
      \n

      Outputs for example:

      \n
      Subject Common Name: github.com\n  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16\n  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\nSubject Common Name: DigiCert SHA2 Extended Validation Server CA\n  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A\n  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\nSubject Common Name: DigiCert High Assurance EV Root CA\n  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF\n  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\nheaders: max-age=0; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\"; pin-sha256=\"k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=\"; pin-sha256=\"K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=\"; pin-sha256=\"IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=\"; pin-sha256=\"iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0=\"; pin-sha256=\"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=\"; includeSubDomains\n
      " + }, + { + "textRaw": "`https.request(url[, options][, callback])`", + "type": "method", + "name": "request", + "meta": { + "added": [ + "v0.3.6" + ], + "changes": [ + { + "version": "v10.9.0", + "pr-url": "https://github.com/nodejs/node/pull/21616", + "description": "The `url` parameter can now be passed along with a separate `options` object." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10638", + "description": "The `options` parameter can be a WHATWG `URL` object." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`url` {string | URL}", + "name": "url", + "type": "string | URL" + }, + { + "textRaw": "`options` {Object | string | URL} Accepts all `options` from [`http.request()`][], with some differences in default values:", + "name": "options", + "type": "Object | string | URL", + "desc": "Accepts all `options` from [`http.request()`][], with some differences in default values:", + "options": [ + { + "textRaw": "`protocol` **Default:** `'https:'`", + "name": "protocol", + "default": "`'https:'`" + }, + { + "textRaw": "`port` **Default:** `443`", + "name": "port", + "default": "`443`" + }, + { + "textRaw": "`agent` **Default:** `https.globalAgent`", + "name": "agent", + "default": "`https.globalAgent`" + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Makes a request to a secure web server.

      \n

      The following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext.

      \n

      options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.

      \n
      const https = require('https');\n\nconst options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nconst req = https.request(options, (res) => {\n  console.log('statusCode:', res.statusCode);\n  console.log('headers:', res.headers);\n\n  res.on('data', (d) => {\n    process.stdout.write(d);\n  });\n});\n\nreq.on('error', (e) => {\n  console.error(e);\n});\nreq.end();\n
      \n

      Example using options from tls.connect():

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Alternatively, opt out of connection pooling by not using an Agent.

      \n
      const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example using a URL as options:

      \n
      const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
      \n

      Example pinning on certificate fingerprint, or the public key (similar to\npin-sha256):

      \n
      const tls = require('tls');\nconst https = require('https');\nconst crypto = require('crypto');\n\nfunction sha256(s) {\n  return crypto.createHash('sha256').update(s).digest('base64');\n}\nconst options = {\n  hostname: 'github.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  checkServerIdentity: function(host, cert) {\n    // Make sure the certificate is issued to the host we are connected to\n    const err = tls.checkServerIdentity(host, cert);\n    if (err) {\n      return err;\n    }\n\n    // Pin the public key, similar to HPKP pin-sha25 pinning\n    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';\n    if (sha256(cert.pubkey) !== pubkey256) {\n      const msg = 'Certificate verification error: ' +\n        `The public key of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // Pin the exact certificate, rather than the pub key\n    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +\n      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';\n    if (cert.fingerprint256 !== cert256) {\n      const msg = 'Certificate verification error: ' +\n        `The certificate of '${cert.subject.CN}' ` +\n        'does not match our pinned fingerprint';\n      return new Error(msg);\n    }\n\n    // This loop is informational only.\n    // Print the certificate and public key fingerprints of all certs in the\n    // chain. Its common to pin the public key of the issuer on the public\n    // internet, while pinning the public key of the service in sensitive\n    // environments.\n    do {\n      console.log('Subject Common Name:', cert.subject.CN);\n      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);\n\n      hash = crypto.createHash('sha256');\n      console.log('  Public key ping-sha256:', sha256(cert.pubkey));\n\n      lastprint256 = cert.fingerprint256;\n      cert = cert.issuerCertificate;\n    } while (cert.fingerprint256 !== lastprint256);\n\n  },\n};\n\noptions.agent = new https.Agent(options);\nconst req = https.request(options, (res) => {\n  console.log('All OK. Server matched our pinned cert or public key');\n  console.log('statusCode:', res.statusCode);\n  // Print the HPKP values\n  console.log('headers:', res.headers['public-key-pins']);\n\n  res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n  console.error(e.message);\n});\nreq.end();\n
      \n

      Outputs for example:

      \n
      Subject Common Name: github.com\n  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16\n  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\nSubject Common Name: DigiCert SHA2 Extended Validation Server CA\n  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A\n  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\nSubject Common Name: DigiCert High Assurance EV Root CA\n  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF\n  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\nheaders: max-age=0; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\"; pin-sha256=\"k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=\"; pin-sha256=\"K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=\"; pin-sha256=\"IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=\"; pin-sha256=\"iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0=\"; pin-sha256=\"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=\"; includeSubDomains\n
      " + } + ], + "properties": [ + { + "textRaw": "`https.globalAgent`", + "name": "globalAgent", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "desc": "

      Global instance of https.Agent for all HTTPS client requests.

      " + } + ], + "type": "module", + "displayName": "HTTPS" + } + ] +} \ No newline at end of file diff --git a/doc/api/index.html b/doc/api/index.html new file mode 100644 index 0000000000000000000000000000000000000000..82a0f63e54f088c22aa494645d2eb054c6470671 --- /dev/null +++ b/doc/api/index.html @@ -0,0 +1,207 @@ + + + + + + + Index | Node.js v12.22.7 Documentation + + + + + + +
      + + + +
      + + diff --git a/doc/api/index.json b/doc/api/index.json new file mode 100644 index 0000000000000000000000000000000000000000..764cbb94071d66499a5445c6140fd6dac9eec551 --- /dev/null +++ b/doc/api/index.json @@ -0,0 +1,4 @@ +{ + "type": "module", + "source": "doc/api/index.md" +} \ No newline at end of file diff --git a/doc/api/inspector.html b/doc/api/inspector.html new file mode 100644 index 0000000000000000000000000000000000000000..0e419bd62b859eed791b41d228ec0a515c2b82db --- /dev/null +++ b/doc/api/inspector.html @@ -0,0 +1,337 @@ + + + + + + + Inspector | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Inspector#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/inspector.js

      +

      The inspector module provides an API for interacting with the V8 inspector.

      +

      It can be accessed using:

      +
      const inspector = require('inspector');
      +

      inspector.close()#

      +

      Deactivate the inspector. Blocks until there are no active connections.

      +

      inspector.console#

      +
        +
      • <Object> An object to send messages to the remote inspector console.
      • +
      +
      require('inspector').console.log('a message');
      +

      The inspector console does not have API parity with Node.js +console.

      +

      inspector.open([port[, host[, wait]]])#

      +
        +
      • port <number> Port to listen on for inspector connections. Optional. +Default: what was specified on the CLI.
      • +
      • host <string> Host to listen on for inspector connections. Optional. +Default: what was specified on the CLI.
      • +
      • wait <boolean> Block until a client has connected. Optional. +Default: false.
      • +
      +

      Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programmatically after node has +started.

      +

      If wait is true, will block until a client has connected to the inspect port +and flow control has been passed to the debugger client.

      +

      See the security warning regarding the host +parameter usage.

      +

      inspector.url()#

      + +

      Return the URL of the active inspector, or undefined if there is none.

      +
      $ node --inspect -p 'inspector.url()'
      +Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
      +For help see https://nodejs.org/en/docs/inspector
      +ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
      +
      +$ node --inspect=localhost:3000 -p 'inspector.url()'
      +Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
      +For help see https://nodejs.org/en/docs/inspector
      +ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
      +
      +$ node -p 'inspector.url()'
      +undefined
      +

      inspector.waitForDebugger()#

      + +

      Blocks until a client (existing or connected later) has sent +Runtime.runIfWaitingForDebugger command.

      +

      An exception will be thrown if there is no active inspector.

      +

      Class: inspector.Session#

      + +

      The inspector.Session is used for dispatching messages to the V8 inspector +back-end and receiving message responses and notifications.

      +

      new inspector.Session()#

      + +

      Create a new instance of the inspector.Session class. The inspector session +needs to be connected through session.connect() before the messages +can be dispatched to the inspector backend.

      +

      Event: 'inspectorNotification'#

      + +
        +
      • <Object> The notification message object
      • +
      +

      Emitted when any notification from the V8 Inspector is received.

      +
      session.on('inspectorNotification', (message) => console.log(message.method));
      +// Debugger.paused
      +// Debugger.resumed
      +

      It is also possible to subscribe only to notifications with specific method:

      +

      Event: <inspector-protocol-method>;#

      + +
        +
      • <Object> The notification message object
      • +
      +

      Emitted when an inspector notification is received that has its method field set +to the <inspector-protocol-method> value.

      +

      The following snippet installs a listener on the 'Debugger.paused' +event, and prints the reason for program suspension whenever program +execution is suspended (through breakpoints, for example):

      +
      session.on('Debugger.paused', ({ params }) => {
      +  console.log(params.hitBreakpoints);
      +});
      +// [ '/the/file/that/has/the/breakpoint.js:11:0' ]
      +

      session.connect()#

      + +

      Connects a session to the inspector back-end.

      +

      session.connectToMainThread()#

      + +

      Connects a session to the main thread inspector back-end. An exception will +be thrown if this API was not called on a Worker thread.

      +

      session.disconnect()#

      + +

      Immediately close the session. All pending message callbacks will be called +with an error. session.connect() will need to be called to be able to send +messages again. Reconnected session will lose all inspector state, such as +enabled agents or configured breakpoints.

      +

      session.post(method[, params][, callback])#

      + + +

      Posts a message to the inspector back-end. callback will be notified when +a response is received. callback is a function that accepts two optional +arguments: error and message-specific result.

      +
      session.post('Runtime.evaluate', { expression: '2 + 2' },
      +             (error, { result }) => console.log(result));
      +// Output: { type: 'number', value: 4, description: '4' }
      +

      The latest version of the V8 inspector protocol is published on the +Chrome DevTools Protocol Viewer.

      +

      Node.js inspector supports all the Chrome DevTools Protocol domains declared +by V8. Chrome DevTools Protocol domain provides an interface for interacting +with one of the runtime agents used to inspect the application state and listen +to the run-time events.

      +

      Example usage#

      +

      Apart from the debugger, various V8 Profilers are available through the DevTools +protocol.

      +

      CPU profiler#

      +

      Here's an example showing how to use the CPU Profiler:

      +
      const inspector = require('inspector');
      +const fs = require('fs');
      +const session = new inspector.Session();
      +session.connect();
      +
      +session.post('Profiler.enable', () => {
      +  session.post('Profiler.start', () => {
      +    // Invoke business logic under measurement here...
      +
      +    // some time later...
      +    session.post('Profiler.stop', (err, { profile }) => {
      +      // Write profile to disk, upload, etc.
      +      if (!err) {
      +        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
      +      }
      +    });
      +  });
      +});
      +

      Heap profiler#

      +

      Here's an example showing how to use the Heap Profiler:

      +
      const inspector = require('inspector');
      +const fs = require('fs');
      +const session = new inspector.Session();
      +
      +const fd = fs.openSync('profile.heapsnapshot', 'w');
      +
      +session.connect();
      +
      +session.on('HeapProfiler.addHeapSnapshotChunk', (m) => {
      +  fs.writeSync(fd, m.params.chunk);
      +});
      +
      +session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
      +  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);
      +  session.disconnect();
      +  fs.closeSync(fd);
      +});
      + +
      +
      +
      + + diff --git a/doc/api/inspector.json b/doc/api/inspector.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab3bdeb9b23b4c870b28d02e79950973338e149 --- /dev/null +++ b/doc/api/inspector.json @@ -0,0 +1,260 @@ +{ + "type": "module", + "source": "doc/api/inspector.md", + "modules": [ + { + "textRaw": "Inspector", + "name": "inspector", + "introduced_in": "v8.0.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/inspector.js

      \n

      The inspector module provides an API for interacting with the V8 inspector.

      \n

      It can be accessed using:

      \n
      const inspector = require('inspector');\n
      ", + "methods": [ + { + "textRaw": "`inspector.close()`", + "type": "method", + "name": "close", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Deactivate the inspector. Blocks until there are no active connections.

      " + }, + { + "textRaw": "`inspector.open([port[, host[, wait]]])`", + "type": "method", + "name": "open", + "signatures": [ + { + "params": [ + { + "textRaw": "`port` {number} Port to listen on for inspector connections. Optional. **Default:** what was specified on the CLI.", + "name": "port", + "type": "number", + "default": "what was specified on the CLI", + "desc": "Port to listen on for inspector connections. Optional." + }, + { + "textRaw": "`host` {string} Host to listen on for inspector connections. Optional. **Default:** what was specified on the CLI.", + "name": "host", + "type": "string", + "default": "what was specified on the CLI", + "desc": "Host to listen on for inspector connections. Optional." + }, + { + "textRaw": "`wait` {boolean} Block until a client has connected. Optional. **Default:** `false`.", + "name": "wait", + "type": "boolean", + "default": "`false`", + "desc": "Block until a client has connected. Optional." + } + ] + } + ], + "desc": "

      Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programmatically after node has\nstarted.

      \n

      If wait is true, will block until a client has connected to the inspect port\nand flow control has been passed to the debugger client.

      \n

      See the security warning regarding the host\nparameter usage.

      " + }, + { + "textRaw": "`inspector.url()`", + "type": "method", + "name": "url", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|undefined}", + "name": "return", + "type": "string|undefined" + }, + "params": [] + } + ], + "desc": "

      Return the URL of the active inspector, or undefined if there is none.

      \n
      $ node --inspect -p 'inspector.url()'\nDebugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34\nFor help see https://nodejs.org/en/docs/inspector\nws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34\n\n$ node --inspect=localhost:3000 -p 'inspector.url()'\nDebugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a\nFor help see https://nodejs.org/en/docs/inspector\nws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a\n\n$ node -p 'inspector.url()'\nundefined\n
      " + }, + { + "textRaw": "`inspector.waitForDebugger()`", + "type": "method", + "name": "waitForDebugger", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Blocks until a client (existing or connected later) has sent\nRuntime.runIfWaitingForDebugger command.

      \n

      An exception will be thrown if there is no active inspector.

      " + } + ], + "properties": [ + { + "textRaw": "`console` {Object} An object to send messages to the remote inspector console.", + "type": "Object", + "name": "console", + "desc": "
      require('inspector').console.log('a message');\n
      \n

      The inspector console does not have API parity with Node.js\nconsole.

      ", + "shortDesc": "An object to send messages to the remote inspector console." + } + ], + "classes": [ + { + "textRaw": "Class: `inspector.Session`", + "type": "class", + "name": "inspector.Session", + "desc": "\n

      The inspector.Session is used for dispatching messages to the V8 inspector\nback-end and receiving message responses and notifications.

      ", + "events": [ + { + "textRaw": "Event: `'inspectorNotification'`", + "type": "event", + "name": "inspectorNotification", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Object} The notification message object", + "type": "Object", + "desc": "The notification message object" + } + ], + "desc": "

      Emitted when any notification from the V8 Inspector is received.

      \n
      session.on('inspectorNotification', (message) => console.log(message.method));\n// Debugger.paused\n// Debugger.resumed\n
      \n

      It is also possible to subscribe only to notifications with specific method:

      " + }, + { + "textRaw": "Event: ``;", + "type": "event", + "name": "`;", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Object} The notification message object", + "type": "Object", + "desc": "The notification message object" + } + ], + "desc": "

      Emitted when an inspector notification is received that has its method field set\nto the <inspector-protocol-method> value.

      \n

      The following snippet installs a listener on the 'Debugger.paused'\nevent, and prints the reason for program suspension whenever program\nexecution is suspended (through breakpoints, for example):

      \n
      session.on('Debugger.paused', ({ params }) => {\n  console.log(params.hitBreakpoints);\n});\n// [ '/the/file/that/has/the/breakpoint.js:11:0' ]\n
      " + } + ], + "methods": [ + { + "textRaw": "`session.connect()`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Connects a session to the inspector back-end.

      " + }, + { + "textRaw": "`session.connectToMainThread()`", + "type": "method", + "name": "connectToMainThread", + "meta": { + "added": [ + "v12.11.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Connects a session to the main thread inspector back-end. An exception will\nbe thrown if this API was not called on a Worker thread.

      " + }, + { + "textRaw": "`session.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Immediately close the session. All pending message callbacks will be called\nwith an error. session.connect() will need to be called to be able to send\nmessages again. Reconnected session will lose all inspector state, such as\nenabled agents or configured breakpoints.

      " + }, + { + "textRaw": "`session.post(method[, params][, callback])`", + "type": "method", + "name": "post", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`method` {string}", + "name": "method", + "type": "string" + }, + { + "textRaw": "`params` {Object}", + "name": "params", + "type": "Object" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Posts a message to the inspector back-end. callback will be notified when\na response is received. callback is a function that accepts two optional\narguments: error and message-specific result.

      \n
      session.post('Runtime.evaluate', { expression: '2 + 2' },\n             (error, { result }) => console.log(result));\n// Output: { type: 'number', value: 4, description: '4' }\n
      \n

      The latest version of the V8 inspector protocol is published on the\nChrome DevTools Protocol Viewer.

      \n

      Node.js inspector supports all the Chrome DevTools Protocol domains declared\nby V8. Chrome DevTools Protocol domain provides an interface for interacting\nwith one of the runtime agents used to inspect the application state and listen\nto the run-time events.

      \n

      Example usage

      \n

      Apart from the debugger, various V8 Profilers are available through the DevTools\nprotocol.

      " + } + ], + "modules": [ + { + "textRaw": "CPU profiler", + "name": "cpu_profiler", + "desc": "

      Here's an example showing how to use the CPU Profiler:

      \n
      const inspector = require('inspector');\nconst fs = require('fs');\nconst session = new inspector.Session();\nsession.connect();\n\nsession.post('Profiler.enable', () => {\n  session.post('Profiler.start', () => {\n    // Invoke business logic under measurement here...\n\n    // some time later...\n    session.post('Profiler.stop', (err, { profile }) => {\n      // Write profile to disk, upload, etc.\n      if (!err) {\n        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));\n      }\n    });\n  });\n});\n
      ", + "type": "module", + "displayName": "CPU profiler" + }, + { + "textRaw": "Heap profiler", + "name": "heap_profiler", + "desc": "

      Here's an example showing how to use the Heap Profiler:

      \n
      const inspector = require('inspector');\nconst fs = require('fs');\nconst session = new inspector.Session();\n\nconst fd = fs.openSync('profile.heapsnapshot', 'w');\n\nsession.connect();\n\nsession.on('HeapProfiler.addHeapSnapshotChunk', (m) => {\n  fs.writeSync(fd, m.params.chunk);\n});\n\nsession.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {\n  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);\n  session.disconnect();\n  fs.closeSync(fd);\n});\n
      ", + "type": "module", + "displayName": "Heap profiler" + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Create a new instance of the inspector.Session class. The inspector session\nneeds to be connected through session.connect() before the messages\ncan be dispatched to the inspector backend.

      " + } + ] + } + ], + "type": "module", + "displayName": "Inspector" + } + ] +} \ No newline at end of file diff --git a/doc/api/intl.html b/doc/api/intl.html new file mode 100644 index 0000000000000000000000000000000000000000..0e0be7fb3dd806b9889917400285fb83bb190872 --- /dev/null +++ b/doc/api/intl.html @@ -0,0 +1,391 @@ + + + + + + + Internationalization support | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Internationalization support#

      + + +

      Node.js has many features that make it easier to write internationalized +programs. Some of them are:

      + +

      Node.js (and its underlying V8 engine) uses ICU to implement these features +in native C/C++ code. However, some of them require a very large ICU data file +in order to support all locales of the world. Because it is expected that most +Node.js users will make use of only a small portion of ICU functionality, only +a subset of the full ICU data set is provided by Node.js by default. Several +options are provided for customizing and expanding the ICU data set either when +building or running Node.js.

      +

      Options for building Node.js#

      +

      To control how ICU is used in Node.js, four configure options are available +during compilation. Additional details on how to compile Node.js are documented +in BUILDING.md.

      +
        +
      • --with-intl=none/--without-intl
      • +
      • --with-intl=system-icu
      • +
      • --with-intl=small-icu (default)
      • +
      • --with-intl=full-icu
      • +
      +

      An overview of available Node.js and JavaScript features for each configure +option:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      nonesystem-icusmall-icufull-icu
      String.prototype.normalize()none (function is no-op)fullfullfull
      String.prototype.to*Case()fullfullfullfull
      Intlnone (object does not exist)partial/full (depends on OS)partial (English-only)full
      String.prototype.localeCompare()partial (not locale-aware)fullfullfull
      String.prototype.toLocale*Case()partial (not locale-aware)fullfullfull
      Number.prototype.toLocaleString()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      Date.prototype.toLocale*String()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      WHATWG URL Parserpartial (no IDN support)fullfullfull
      require('buffer').transcode()none (function does not exist)fullfullfull
      REPLpartial (inaccurate line editing)fullfullfull
      require('util').TextDecoderpartial (basic encodings support)partial/full (depends on OS)partial (Unicode-only)full
      RegExp Unicode Property Escapesnone (invalid RegExp error)fullfullfull
      +

      The "(not locale-aware)" designation denotes that the function carries out its +operation just like the non-Locale version of the function, if one +exists. For example, under none mode, Date.prototype.toLocaleString()'s +operation is identical to that of Date.prototype.toString().

      +

      Disable all internationalization features (none)#

      +

      If this option is chosen, most internationalization features mentioned above +will be unavailable in the resulting node binary.

      +

      Build with a pre-installed ICU (system-icu)#

      +

      Node.js can link against an ICU build already installed on the system. In fact, +most Linux distributions already come with ICU installed, and this option would +make it possible to reuse the same set of data used by other components in the +OS.

      +

      Functionalities that only require the ICU library itself, such as +String.prototype.normalize() and the WHATWG URL parser, are fully +supported under system-icu. Features that require ICU locale data in +addition, such as Intl.DateTimeFormat may be fully or partially +supported, depending on the completeness of the ICU data installed on the +system.

      +

      Embed a limited set of ICU data (small-icu)#

      +

      This option makes the resulting binary link against the ICU library statically, +and includes a subset of ICU data (typically only the English locale) within +the node executable.

      +

      Functionalities that only require the ICU library itself, such as +String.prototype.normalize() and the WHATWG URL parser, are fully +supported under small-icu. Features that require ICU locale data in addition, +such as Intl.DateTimeFormat, generally only work with the English locale:

      +
      const january = new Date(9e8);
      +const english = new Intl.DateTimeFormat('en', { month: 'long' });
      +const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
      +
      +console.log(english.format(january));
      +// Prints "January"
      +console.log(spanish.format(january));
      +// Prints "M01" on small-icu
      +// Should print "enero"
      +

      This mode provides a good balance between features and binary size, and it is +the default behavior if no --with-intl flag is passed. The official binaries +are also built in this mode.

      +

      Providing ICU data at runtime#

      +

      If the small-icu option is used, one can still provide additional locale data +at runtime so that the JS methods would work for all ICU locales. Assuming the +data file is stored at /some/directory, it can be made available to ICU +through either:

      +
        +
      • +

        The NODE_ICU_DATA environment variable:

        +
        env NODE_ICU_DATA=/some/directory node
        +
      • +
      • +

        The --icu-data-dir CLI parameter:

        +
        node --icu-data-dir=/some/directory
        +
      • +
      +

      (If both are specified, the --icu-data-dir CLI parameter takes precedence.)

      +

      ICU is able to automatically find and load a variety of data formats, but the +data must be appropriate for the ICU version, and the file correctly named. +The most common name for the data file is icudt6X[bl].dat, where 6X denotes +the intended ICU version, and b or l indicates the system's endianness. +Check "ICU Data" article in the ICU User Guide for other supported formats +and more details on ICU data in general.

      +

      The full-icu npm module can greatly simplify ICU data installation by +detecting the ICU version of the running node executable and downloading the +appropriate data file. After installing the module through npm i full-icu, +the data file will be available at ./node_modules/full-icu. This path can be +then passed either to NODE_ICU_DATA or --icu-data-dir as shown above to +enable full Intl support.

      +

      Embed the entire ICU (full-icu)#

      +

      This option makes the resulting binary link against ICU statically and include +a full set of ICU data. A binary created this way has no further external +dependencies and supports all locales, but might be rather large. See +BUILDING.md on how to compile a binary using this mode.

      +

      Detecting internationalization support#

      +

      To verify that ICU is enabled at all (system-icu, small-icu, or +full-icu), simply checking the existence of Intl should suffice:

      +
      const hasICU = typeof Intl === 'object';
      +

      Alternatively, checking for process.versions.icu, a property defined only +when ICU is enabled, works too:

      +
      const hasICU = typeof process.versions.icu === 'string';
      +

      To check for support for a non-English locale (i.e. full-icu or +system-icu), Intl.DateTimeFormat can be a good distinguishing factor:

      +
      const hasFullICU = (() => {
      +  try {
      +    const january = new Date(9e8);
      +    const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
      +    return spanish.format(january) === 'enero';
      +  } catch (err) {
      +    return false;
      +  }
      +})();
      +

      For more verbose tests for Intl support, the following resources may be found +to be helpful:

      +
        +
      • btest402: Generally used to check whether Node.js with Intl support is +built correctly.
      • +
      • Test262: ECMAScript's official conformance test suite includes a section +dedicated to ECMA-402.
      • +
      + +
      +
      +
      + + diff --git a/doc/api/intl.json b/doc/api/intl.json new file mode 100644 index 0000000000000000000000000000000000000000..100796808e06fd4f3f3f41152f0200adeb5a4e9a --- /dev/null +++ b/doc/api/intl.json @@ -0,0 +1,69 @@ +{ + "type": "module", + "source": "doc/api/intl.md", + "introduced_in": "v8.2.0", + "miscs": [ + { + "textRaw": "Internationalization support", + "name": "Internationalization support", + "introduced_in": "v8.2.0", + "type": "misc", + "desc": "

      Node.js has many features that make it easier to write internationalized\nprograms. Some of them are:

      \n\n

      Node.js (and its underlying V8 engine) uses ICU to implement these features\nin native C/C++ code. However, some of them require a very large ICU data file\nin order to support all locales of the world. Because it is expected that most\nNode.js users will make use of only a small portion of ICU functionality, only\na subset of the full ICU data set is provided by Node.js by default. Several\noptions are provided for customizing and expanding the ICU data set either when\nbuilding or running Node.js.

      ", + "miscs": [ + { + "textRaw": "Options for building Node.js", + "name": "options_for_building_node.js", + "desc": "

      To control how ICU is used in Node.js, four configure options are available\nduring compilation. Additional details on how to compile Node.js are documented\nin BUILDING.md.

      \n
        \n
      • --with-intl=none/--without-intl
      • \n
      • --with-intl=system-icu
      • \n
      • --with-intl=small-icu (default)
      • \n
      • --with-intl=full-icu
      • \n
      \n

      An overview of available Node.js and JavaScript features for each configure\noption:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      nonesystem-icusmall-icufull-icu
      String.prototype.normalize()none (function is no-op)fullfullfull
      String.prototype.to*Case()fullfullfullfull
      Intlnone (object does not exist)partial/full (depends on OS)partial (English-only)full
      String.prototype.localeCompare()partial (not locale-aware)fullfullfull
      String.prototype.toLocale*Case()partial (not locale-aware)fullfullfull
      Number.prototype.toLocaleString()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      Date.prototype.toLocale*String()partial (not locale-aware)partial/full (depends on OS)partial (English-only)full
      WHATWG URL Parserpartial (no IDN support)fullfullfull
      require('buffer').transcode()none (function does not exist)fullfullfull
      REPLpartial (inaccurate line editing)fullfullfull
      require('util').TextDecoderpartial (basic encodings support)partial/full (depends on OS)partial (Unicode-only)full
      RegExp Unicode Property Escapesnone (invalid RegExp error)fullfullfull
      \n

      The \"(not locale-aware)\" designation denotes that the function carries out its\noperation just like the non-Locale version of the function, if one\nexists. For example, under none mode, Date.prototype.toLocaleString()'s\noperation is identical to that of Date.prototype.toString().

      ", + "modules": [ + { + "textRaw": "Disable all internationalization features (`none`)", + "name": "disable_all_internationalization_features_(`none`)", + "desc": "

      If this option is chosen, most internationalization features mentioned above\nwill be unavailable in the resulting node binary.

      ", + "type": "module", + "displayName": "Disable all internationalization features (`none`)" + }, + { + "textRaw": "Build with a pre-installed ICU (`system-icu`)", + "name": "build_with_a_pre-installed_icu_(`system-icu`)", + "desc": "

      Node.js can link against an ICU build already installed on the system. In fact,\nmost Linux distributions already come with ICU installed, and this option would\nmake it possible to reuse the same set of data used by other components in the\nOS.

      \n

      Functionalities that only require the ICU library itself, such as\nString.prototype.normalize() and the WHATWG URL parser, are fully\nsupported under system-icu. Features that require ICU locale data in\naddition, such as Intl.DateTimeFormat may be fully or partially\nsupported, depending on the completeness of the ICU data installed on the\nsystem.

      ", + "type": "module", + "displayName": "Build with a pre-installed ICU (`system-icu`)" + }, + { + "textRaw": "Embed a limited set of ICU data (`small-icu`)", + "name": "embed_a_limited_set_of_icu_data_(`small-icu`)", + "desc": "

      This option makes the resulting binary link against the ICU library statically,\nand includes a subset of ICU data (typically only the English locale) within\nthe node executable.

      \n

      Functionalities that only require the ICU library itself, such as\nString.prototype.normalize() and the WHATWG URL parser, are fully\nsupported under small-icu. Features that require ICU locale data in addition,\nsuch as Intl.DateTimeFormat, generally only work with the English locale:

      \n
      const january = new Date(9e8);\nconst english = new Intl.DateTimeFormat('en', { month: 'long' });\nconst spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n\nconsole.log(english.format(january));\n// Prints \"January\"\nconsole.log(spanish.format(january));\n// Prints \"M01\" on small-icu\n// Should print \"enero\"\n
      \n

      This mode provides a good balance between features and binary size, and it is\nthe default behavior if no --with-intl flag is passed. The official binaries\nare also built in this mode.

      ", + "modules": [ + { + "textRaw": "Providing ICU data at runtime", + "name": "providing_icu_data_at_runtime", + "desc": "

      If the small-icu option is used, one can still provide additional locale data\nat runtime so that the JS methods would work for all ICU locales. Assuming the\ndata file is stored at /some/directory, it can be made available to ICU\nthrough either:

      \n
        \n
      • \n

        The NODE_ICU_DATA environment variable:

        \n
        env NODE_ICU_DATA=/some/directory node\n
        \n
      • \n
      • \n

        The --icu-data-dir CLI parameter:

        \n
        node --icu-data-dir=/some/directory\n
        \n
      • \n
      \n

      (If both are specified, the --icu-data-dir CLI parameter takes precedence.)

      \n

      ICU is able to automatically find and load a variety of data formats, but the\ndata must be appropriate for the ICU version, and the file correctly named.\nThe most common name for the data file is icudt6X[bl].dat, where 6X denotes\nthe intended ICU version, and b or l indicates the system's endianness.\nCheck \"ICU Data\" article in the ICU User Guide for other supported formats\nand more details on ICU data in general.

      \n

      The full-icu npm module can greatly simplify ICU data installation by\ndetecting the ICU version of the running node executable and downloading the\nappropriate data file. After installing the module through npm i full-icu,\nthe data file will be available at ./node_modules/full-icu. This path can be\nthen passed either to NODE_ICU_DATA or --icu-data-dir as shown above to\nenable full Intl support.

      ", + "type": "module", + "displayName": "Providing ICU data at runtime" + } + ], + "type": "module", + "displayName": "Embed a limited set of ICU data (`small-icu`)" + }, + { + "textRaw": "Embed the entire ICU (`full-icu`)", + "name": "embed_the_entire_icu_(`full-icu`)", + "desc": "

      This option makes the resulting binary link against ICU statically and include\na full set of ICU data. A binary created this way has no further external\ndependencies and supports all locales, but might be rather large. See\nBUILDING.md on how to compile a binary using this mode.

      ", + "type": "module", + "displayName": "Embed the entire ICU (`full-icu`)" + } + ], + "type": "misc", + "displayName": "Options for building Node.js" + }, + { + "textRaw": "Detecting internationalization support", + "name": "detecting_internationalization_support", + "desc": "

      To verify that ICU is enabled at all (system-icu, small-icu, or\nfull-icu), simply checking the existence of Intl should suffice:

      \n
      const hasICU = typeof Intl === 'object';\n
      \n

      Alternatively, checking for process.versions.icu, a property defined only\nwhen ICU is enabled, works too:

      \n
      const hasICU = typeof process.versions.icu === 'string';\n
      \n

      To check for support for a non-English locale (i.e. full-icu or\nsystem-icu), Intl.DateTimeFormat can be a good distinguishing factor:

      \n
      const hasFullICU = (() => {\n  try {\n    const january = new Date(9e8);\n    const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n    return spanish.format(january) === 'enero';\n  } catch (err) {\n    return false;\n  }\n})();\n
      \n

      For more verbose tests for Intl support, the following resources may be found\nto be helpful:

      \n
        \n
      • btest402: Generally used to check whether Node.js with Intl support is\nbuilt correctly.
      • \n
      • Test262: ECMAScript's official conformance test suite includes a section\ndedicated to ECMA-402.
      • \n
      ", + "type": "misc", + "displayName": "Detecting internationalization support" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/module.html b/doc/api/module.html new file mode 100644 index 0000000000000000000000000000000000000000..8c09b9ba67f6123b1b9d6e09b211c42d46b21f3b --- /dev/null +++ b/doc/api/module.html @@ -0,0 +1,317 @@ + + + + + + + Modules: module API | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Modules: module API#

      + +

      The Module object#

      + +

      Provides general utility methods when interacting with instances of +Module, the module variable often seen in CommonJS modules. Accessed +via import 'module' or require('module').

      +

      module.builtinModules#

      + + +

      A list of the names of all modules provided by Node.js. Can be used to verify +if a module is maintained by a third party or not.

      +

      module in this context isn't the same object that's provided +by the module wrapper. To access it, require the Module module:

      +
      // module.mjs
      +// In an ECMAScript module
      +import { builtinModules as builtin } from 'module';
      +
      // module.cjs
      +// In a CommonJS module
      +const builtin = require('module').builtinModules;
      +

      module.createRequire(filename)#

      + +
        +
      • filename <string> | <URL> Filename to be used to construct the require +function. Must be a file URL object, file URL string, or absolute path +string.
      • +
      • Returns: <require> Require function
      • +
      +
      import { createRequire } from 'module';
      +const require = createRequire(import.meta.url);
      +
      +// sibling-module.js is a CommonJS module.
      +const siblingModule = require('./sibling-module');
      +

      module.createRequireFromPath(filename)#

      + +

      Stability: 0 - Deprecated: Please use createRequire() instead.

      +
        +
      • filename <string> Filename to be used to construct the relative require +function.
      • +
      • Returns: <require> Require function
      • +
      +
      const { createRequireFromPath } = require('module');
      +const requireUtil = createRequireFromPath('../src/utils/');
      +
      +// Require `../src/utils/some-tool`
      +requireUtil('./some-tool');
      +

      module.syncBuiltinESMExports()#

      + +

      The module.syncBuiltinESMExports() method updates all the live bindings for +builtin ES Modules to match the properties of the CommonJS exports. It +does not add or remove exported names from the ES Modules.

      +
      const fs = require('fs');
      +const { syncBuiltinESMExports } = require('module');
      +
      +fs.readFile = null;
      +
      +delete fs.readFileSync;
      +
      +fs.newAPI = function newAPI() {
      +  // ...
      +};
      +
      +syncBuiltinESMExports();
      +
      +import('fs').then((esmFS) => {
      +  assert.strictEqual(esmFS.readFile, null);
      +  assert.strictEqual('readFileSync' in fs, true);
      +  assert.strictEqual(esmFS.newAPI, undefined);
      +});
      +

      Source map v3 support#

      + +

      Stability: 1 - Experimental

      +

      Helpers for interacting with the source map cache. This cache is +populated when source map parsing is enabled and +source map include directives are found in a modules' footer.

      +

      To enable source map parsing, Node.js must be run with the flag +--enable-source-maps, or with code coverage enabled by setting +NODE_V8_COVERAGE=dir.

      +
      // module.mjs
      +// In an ECMAScript module
      +import { findSourceMap, SourceMap } from 'module';
      +
      // module.cjs
      +// In a CommonJS module
      +const { findSourceMap, SourceMap } = require('module');
      +

      module.findSourceMap(path[, error])#

      + + +

      path is the resolved path for the file for which a corresponding source map +should be fetched.

      +

      The error instance should be passed as the second parameter to findSourceMap +in exceptional flows, such as when an overridden +Error.prepareStackTrace(error, trace) is invoked. Modules are not added to +the module cache until they are successfully loaded. In these cases, source maps +are associated with the error instance along with the path.

      +

      Class: module.SourceMap#

      + +

      new SourceMap(payload)#

      + +

      Creates a new sourceMap instance.

      +

      payload is an object with keys matching the Source map v3 format:

      + +

      sourceMap.payload#

      + +

      Getter for the payload used to construct the SourceMap instance.

      +

      sourceMap.findEntry(lineNumber, columnNumber)#

      + +

      Given a line number and column number in the generated source file, returns +an object representing the position in the original file. The object returned +consists of the following keys:

      + + +
      +
      +
      + + diff --git a/doc/api/module.json b/doc/api/module.json new file mode 100644 index 0000000000000000000000000000000000000000..e24be3c6a9ddd75dca65d8e5fdcef17583e599f2 --- /dev/null +++ b/doc/api/module.json @@ -0,0 +1,237 @@ +{ + "type": "module", + "source": "doc/api/module.md", + "modules": [ + { + "textRaw": "Modules: `module` API", + "name": "modules:_`module`_api", + "introduced_in": "v0.3.7", + "modules": [ + { + "textRaw": "The `Module` object", + "name": "the_`module`_object", + "desc": "\n

      Provides general utility methods when interacting with instances of\nModule, the module variable often seen in CommonJS modules. Accessed\nvia import 'module' or require('module').

      ", + "properties": [ + { + "textRaw": "`builtinModules` {string[]}", + "type": "string[]", + "name": "builtinModules", + "meta": { + "added": [ + "v9.3.0", + "v8.10.0", + "v6.13.0" + ], + "changes": [] + }, + "desc": "

      A list of the names of all modules provided by Node.js. Can be used to verify\nif a module is maintained by a third party or not.

      \n

      module in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:

      \n
      // module.mjs\n// In an ECMAScript module\nimport { builtinModules as builtin } from 'module';\n
      \n
      // module.cjs\n// In a CommonJS module\nconst builtin = require('module').builtinModules;\n
      " + } + ], + "methods": [ + { + "textRaw": "`module.createRequire(filename)`", + "type": "method", + "name": "createRequire", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {require} Require function", + "name": "return", + "type": "require", + "desc": "Require function" + }, + "params": [ + { + "textRaw": "`filename` {string|URL} Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.", + "name": "filename", + "type": "string|URL", + "desc": "Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string." + } + ] + } + ], + "desc": "
      import { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\n\n// sibling-module.js is a CommonJS module.\nconst siblingModule = require('./sibling-module');\n
      " + }, + { + "textRaw": "`module.createRequireFromPath(filename)`", + "type": "method", + "name": "createRequireFromPath", + "meta": { + "added": [ + "v10.12.0" + ], + "deprecated": [ + "v12.2.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Please use [`createRequire()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {require} Require function", + "name": "return", + "type": "require", + "desc": "Require function" + }, + "params": [ + { + "textRaw": "`filename` {string} Filename to be used to construct the relative require function.", + "name": "filename", + "type": "string", + "desc": "Filename to be used to construct the relative require function." + } + ] + } + ], + "desc": "
      const { createRequireFromPath } = require('module');\nconst requireUtil = createRequireFromPath('../src/utils/');\n\n// Require `../src/utils/some-tool`\nrequireUtil('./some-tool');\n
      " + }, + { + "textRaw": "`module.syncBuiltinESMExports()`", + "type": "method", + "name": "syncBuiltinESMExports", + "meta": { + "added": [ + "v12.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The module.syncBuiltinESMExports() method updates all the live bindings for\nbuiltin ES Modules to match the properties of the CommonJS exports. It\ndoes not add or remove exported names from the ES Modules.

      \n
      const fs = require('fs');\nconst { syncBuiltinESMExports } = require('module');\n\nfs.readFile = null;\n\ndelete fs.readFileSync;\n\nfs.newAPI = function newAPI() {\n  // ...\n};\n\nsyncBuiltinESMExports();\n\nimport('fs').then((esmFS) => {\n  assert.strictEqual(esmFS.readFile, null);\n  assert.strictEqual('readFileSync' in fs, true);\n  assert.strictEqual(esmFS.newAPI, undefined);\n});\n
      " + } + ], + "type": "module", + "displayName": "The `Module` object" + }, + { + "textRaw": "Source map v3 support", + "name": "source_map_v3_support", + "meta": { + "added": [ + "v13.7.0", + "v12.17.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Helpers for interacting with the source map cache. This cache is\npopulated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.

      \n

      To enable source map parsing, Node.js must be run with the flag\n--enable-source-maps, or with code coverage enabled by setting\nNODE_V8_COVERAGE=dir.

      \n
      // module.mjs\n// In an ECMAScript module\nimport { findSourceMap, SourceMap } from 'module';\n
      \n
      // module.cjs\n// In a CommonJS module\nconst { findSourceMap, SourceMap } = require('module');\n
      ", + "methods": [ + { + "textRaw": "`module.findSourceMap(path[, error])`", + "type": "method", + "name": "findSourceMap", + "meta": { + "added": [ + "v13.7.0", + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {module.SourceMap}", + "name": "return", + "type": "module.SourceMap" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + }, + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      path is the resolved path for the file for which a corresponding source map\nshould be fetched.

      \n

      The error instance should be passed as the second parameter to findSourceMap\nin exceptional flows, such as when an overridden\nError.prepareStackTrace(error, trace) is invoked. Modules are not added to\nthe module cache until they are successfully loaded. In these cases, source maps\nare associated with the error instance along with the path.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `module.SourceMap`", + "type": "class", + "name": "module.SourceMap", + "meta": { + "added": [ + "v13.7.0", + "v12.17.0" + ], + "changes": [] + }, + "properties": [ + { + "textRaw": "`payload` Returns: {Object}", + "type": "Object", + "name": "return", + "desc": "

      Getter for the payload used to construct the SourceMap instance.

      " + } + ], + "methods": [ + { + "textRaw": "`sourceMap.findEntry(lineNumber, columnNumber)`", + "type": "method", + "name": "findEntry", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`lineNumber` {number}", + "name": "lineNumber", + "type": "number" + }, + { + "textRaw": "`columnNumber` {number}", + "name": "columnNumber", + "type": "number" + } + ] + } + ], + "desc": "

      Given a line number and column number in the generated source file, returns\nan object representing the position in the original file. The object returned\nconsists of the following keys:

      \n" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`payload` {Object}", + "name": "payload", + "type": "Object" + } + ], + "desc": "

      Creates a new sourceMap instance.

      \n

      payload is an object with keys matching the Source map v3 format:

      \n" + } + ] + } + ], + "type": "module", + "displayName": "Source map v3 support" + } + ], + "type": "module", + "displayName": "Modules: `module` API" + } + ] +} \ No newline at end of file diff --git a/doc/api/modules.html b/doc/api/modules.html new file mode 100644 index 0000000000000000000000000000000000000000..36ef41dca737964332abfcafecbbddb63ce987bf --- /dev/null +++ b/doc/api/modules.html @@ -0,0 +1,960 @@ + + + + + + + Modules: CommonJS modules | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Modules: CommonJS modules#

      + +

      Stability: 2 - Stable

      + +

      In the Node.js module system, each file is treated as a separate module. For +example, consider a file named foo.js:

      +
      const circle = require('./circle.js');
      +console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
      +

      On the first line, foo.js loads the module circle.js that is in the same +directory as foo.js.

      +

      Here are the contents of circle.js:

      +
      const { PI } = Math;
      +
      +exports.area = (r) => PI * r ** 2;
      +
      +exports.circumference = (r) => 2 * PI * r;
      +

      The module circle.js has exported the functions area() and +circumference(). Functions and objects are added to the root of a module +by specifying additional properties on the special exports object.

      +

      Variables local to the module will be private, because the module is wrapped +in a function by Node.js (see module wrapper). +In this example, the variable PI is private to circle.js.

      +

      The module.exports property can be assigned a new value (such as a function +or object).

      +

      Below, bar.js makes use of the square module, which exports a Square class:

      +
      const Square = require('./square.js');
      +const mySquare = new Square(2);
      +console.log(`The area of mySquare is ${mySquare.area()}`);
      +

      The square module is defined in square.js:

      +
      // Assigning to exports will not modify module, must use module.exports
      +module.exports = class Square {
      +  constructor(width) {
      +    this.width = width;
      +  }
      +
      +  area() {
      +    return this.width ** 2;
      +  }
      +};
      +

      The module system is implemented in the require('module') module.

      +

      Accessing the main module#

      + +

      When a file is run directly from Node.js, require.main is set to its +module. That means that it is possible to determine whether a file has been +run directly by testing require.main === module.

      +

      For a file foo.js, this will be true if run via node foo.js, but +false if run by require('./foo').

      +

      Because module provides a filename property (normally equivalent to +__filename), the entry point of the current application can be obtained +by checking require.main.filename.

      +

      Addenda: Package manager tips#

      + +

      The semantics of the Node.js require() function were designed to be general +enough to support reasonable directory structures. Package manager programs +such as dpkg, rpm, and npm will hopefully find it possible to build +native packages from Node.js modules without modification.

      +

      Below we give a suggested directory structure that could work:

      +

      Let's say that we wanted to have the folder at +/usr/lib/node/<some-package>/<some-version> hold the contents of a +specific version of a package.

      +

      Packages can depend on one another. In order to install package foo, it +may be necessary to install a specific version of package bar. The bar +package may itself have dependencies, and in some cases, these may even collide +or form cyclic dependencies.

      +

      Because Node.js looks up the realpath of any modules it loads (that is, it +resolves symlinks) and then looks for their dependencies in node_modules folders, +this situation can be resolved with the following architecture:

      +
        +
      • /usr/lib/node/foo/1.2.3/: Contents of the foo package, version 1.2.3.
      • +
      • /usr/lib/node/bar/4.3.2/: Contents of the bar package that foo depends +on.
      • +
      • /usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to +/usr/lib/node/bar/4.3.2/.
      • +
      • /usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages that +bar depends on.
      • +
      +

      Thus, even if a cycle is encountered, or if there are dependency +conflicts, every module will be able to get a version of its dependency +that it can use.

      +

      When the code in the foo package does require('bar'), it will get the +version that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar. +Then, when the code in the bar package calls require('quux'), it'll get +the version that is symlinked into +/usr/lib/node/bar/4.3.2/node_modules/quux.

      +

      Furthermore, to make the module lookup process even more optimal, rather +than putting packages directly in /usr/lib/node, we could put them in +/usr/lib/node_modules/<name>/<version>. Then Node.js will not bother +looking for missing dependencies in /usr/node_modules or /node_modules.

      +

      In order to make modules available to the Node.js REPL, it might be useful to +also add the /usr/lib/node_modules folder to the $NODE_PATH environment +variable. Since the module lookups using node_modules folders are all +relative, and based on the real path of the files making the calls to +require(), the packages themselves can be anywhere.

      +

      Addenda: The .mjs extension#

      +

      It is not possible to require() files that have the .mjs extension. +Attempting to do so will throw an error. The .mjs extension is +reserved for ECMAScript Modules which cannot be loaded via require(). +See ECMAScript Modules for more details.

      +

      All together...#

      + +

      To get the exact filename that will be loaded when require() is called, use +the require.resolve() function.

      +

      Putting together all of the above, here is the high-level algorithm +in pseudocode of what require() does:

      +
      require(X) from module at path Y
      +1. If X is a core module,
      +   a. return the core module
      +   b. STOP
      +2. If X begins with '/'
      +   a. set Y to be the filesystem root
      +3. If X begins with './' or '/' or '../'
      +   a. LOAD_AS_FILE(Y + X)
      +   b. LOAD_AS_DIRECTORY(Y + X)
      +   c. THROW "not found"
      +4. If X begins with '#'
      +   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
      +5. LOAD_PACKAGE_SELF(X, dirname(Y))
      +6. LOAD_NODE_MODULES(X, dirname(Y))
      +7. THROW "not found"
      +
      +LOAD_AS_FILE(X)
      +1. If X is a file, load X as its file extension format. STOP
      +2. If X.js is a file, load X.js as JavaScript text. STOP
      +3. If X.json is a file, parse X.json to a JavaScript Object. STOP
      +4. If X.node is a file, load X.node as binary addon. STOP
      +
      +LOAD_INDEX(X)
      +1. If X/index.js is a file, load X/index.js as JavaScript text. STOP
      +2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
      +3. If X/index.node is a file, load X/index.node as binary addon. STOP
      +
      +LOAD_AS_DIRECTORY(X)
      +1. If X/package.json is a file,
      +   a. Parse X/package.json, and look for "main" field.
      +   b. If "main" is a falsy value, GOTO 2.
      +   c. let M = X + (json main field)
      +   d. LOAD_AS_FILE(M)
      +   e. LOAD_INDEX(M)
      +   f. LOAD_INDEX(X) DEPRECATED
      +   g. THROW "not found"
      +2. LOAD_INDEX(X)
      +
      +LOAD_NODE_MODULES(X, START)
      +1. let DIRS = NODE_MODULES_PATHS(START)
      +2. for each DIR in DIRS:
      +   a. LOAD_PACKAGE_EXPORTS(X, DIR)
      +   b. LOAD_AS_FILE(DIR/X)
      +   c. LOAD_AS_DIRECTORY(DIR/X)
      +
      +NODE_MODULES_PATHS(START)
      +1. let PARTS = path split(START)
      +2. let I = count of PARTS - 1
      +3. let DIRS = [GLOBAL_FOLDERS]
      +4. while I >= 0,
      +   a. if PARTS[I] = "node_modules" CONTINUE
      +   b. DIR = path join(PARTS[0 .. I] + "node_modules")
      +   c. DIRS = DIRS + DIR
      +   d. let I = I - 1
      +5. return DIRS
      +
      +LOAD_PACKAGE_IMPORTS(X, DIR)
      +1. Find the closest package scope SCOPE to DIR.
      +2. If no scope was found, return.
      +3. If the SCOPE/package.json "imports" is null or undefined, return.
      +4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
      +  ["node", "require"]) defined in the ESM resolver.
      +5. RESOLVE_ESM_MATCH(MATCH).
      +
      +LOAD_PACKAGE_EXPORTS(X, DIR)
      +1. Try to interpret X as a combination of NAME and SUBPATH where the name
      +   may have a @scope/ prefix and the subpath begins with a slash (`/`).
      +2. If X does not match this pattern or DIR/NAME/package.json is not a file,
      +   return.
      +3. Parse DIR/NAME/package.json, and look for "exports" field.
      +4. If "exports" is null or undefined, return.
      +5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
      +   `package.json` "exports", ["node", "require"]) defined in the ESM resolver.
      +6. RESOLVE_ESM_MATCH(MATCH)
      +
      +LOAD_PACKAGE_SELF(X, DIR)
      +1. Find the closest package scope SCOPE to DIR.
      +2. If no scope was found, return.
      +3. If the SCOPE/package.json "exports" is null or undefined, return.
      +4. If the SCOPE/package.json "name" is not the first segment of X, return.
      +5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
      +   "." + X.slice("name".length), `package.json` "exports", ["node", "require"])
      +   defined in the ESM resolver.
      +6. RESOLVE_ESM_MATCH(MATCH)
      +
      +RESOLVE_ESM_MATCH(MATCH)
      +1. let { RESOLVED, EXACT } = MATCH
      +2. let RESOLVED_PATH = fileURLToPath(RESOLVED)
      +3. If EXACT is true,
      +   a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
      +      format. STOP
      +4. Otherwise, if EXACT is false,
      +   a. LOAD_AS_FILE(RESOLVED_PATH)
      +   b. LOAD_AS_DIRECTORY(RESOLVED_PATH)
      +5. THROW "not found"
      +

      Caching#

      + +

      Modules are cached after the first time they are loaded. This means (among other +things) that every call to require('foo') will get exactly the same object +returned, if it would resolve to the same file.

      +

      Provided require.cache is not modified, multiple calls to require('foo') +will not cause the module code to be executed multiple times. This is an +important feature. With it, "partially done" objects can be returned, thus +allowing transitive dependencies to be loaded even when they would cause cycles.

      +

      To have a module execute code multiple times, export a function, and call that +function.

      +

      Module caching caveats#

      + +

      Modules are cached based on their resolved filename. Since modules may resolve +to a different filename based on the location of the calling module (loading +from node_modules folders), it is not a guarantee that require('foo') will +always return the exact same object, if it would resolve to different files.

      +

      Additionally, on case-insensitive file systems or operating systems, different +resolved filenames can point to the same file, but the cache will still treat +them as different modules and will reload the file multiple times. For example, +require('./foo') and require('./FOO') return two different objects, +irrespective of whether or not ./foo and ./FOO are the same file.

      +

      Core modules#

      + +

      Node.js has several modules compiled into the binary. These modules are +described in greater detail elsewhere in this documentation.

      +

      The core modules are defined within the Node.js source and are located in the +lib/ folder.

      +

      Core modules are always preferentially loaded if their identifier is +passed to require(). For instance, require('http') will always +return the built in HTTP module, even if there is a file by that name.

      +

      Cycles#

      + +

      When there are circular require() calls, a module might not have finished +executing when it is returned.

      +

      Consider this situation:

      +

      a.js:

      +
      console.log('a starting');
      +exports.done = false;
      +const b = require('./b.js');
      +console.log('in a, b.done = %j', b.done);
      +exports.done = true;
      +console.log('a done');
      +

      b.js:

      +
      console.log('b starting');
      +exports.done = false;
      +const a = require('./a.js');
      +console.log('in b, a.done = %j', a.done);
      +exports.done = true;
      +console.log('b done');
      +

      main.js:

      +
      console.log('main starting');
      +const a = require('./a.js');
      +const b = require('./b.js');
      +console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
      +

      When main.js loads a.js, then a.js in turn loads b.js. At that +point, b.js tries to load a.js. In order to prevent an infinite +loop, an unfinished copy of the a.js exports object is returned to the +b.js module. b.js then finishes loading, and its exports object is +provided to the a.js module.

      +

      By the time main.js has loaded both modules, they're both finished. +The output of this program would thus be:

      +
      $ node main.js
      +main starting
      +a starting
      +b starting
      +in b, a.done = false
      +b done
      +in a, b.done = true
      +a done
      +in main, a.done = true, b.done = true
      +

      Careful planning is required to allow cyclic module dependencies to work +correctly within an application.

      +

      File modules#

      + +

      If the exact filename is not found, then Node.js will attempt to load the +required filename with the added extensions: .js, .json, and finally +.node.

      +

      .js files are interpreted as JavaScript text files, and .json files are +parsed as JSON text files. .node files are interpreted as compiled addon +modules loaded with process.dlopen().

      +

      A required module prefixed with '/' is an absolute path to the file. For +example, require('/home/marco/foo.js') will load the file at +/home/marco/foo.js.

      +

      A required module prefixed with './' is relative to the file calling +require(). That is, circle.js must be in the same directory as foo.js for +require('./circle') to find it.

      +

      Without a leading '/', './', or '../' to indicate a file, the module must +either be a core module or is loaded from a node_modules folder.

      +

      If the given path does not exist, require() will throw an Error with its +code property set to 'MODULE_NOT_FOUND'.

      +

      Folders as modules#

      + +

      It is convenient to organize programs and libraries into self-contained +directories, and then provide a single entry point to those directories. +There are three ways in which a folder may be passed to require() as +an argument.

      +

      The first is to create a package.json file in the root of the folder, +which specifies a main module. An example package.json file might +look like this:

      +
      { "name" : "some-library",
      +  "main" : "./lib/some-library.js" }
      +

      If this was in a folder at ./some-library, then +require('./some-library') would attempt to load +./some-library/lib/some-library.js.

      +

      This is the extent of the awareness of package.json files within Node.js.

      +

      If there is no package.json file present in the directory, or if the +"main" entry is missing or cannot be resolved, then Node.js +will attempt to load an index.js or index.node file out of that +directory. For example, if there was no package.json file in the previous +example, then require('./some-library') would attempt to load:

      +
        +
      • ./some-library/index.js
      • +
      • ./some-library/index.node
      • +
      +

      If these attempts fail, then Node.js will report the entire module as missing +with the default error:

      +
      Error: Cannot find module 'some-library'
      +

      Loading from node_modules folders#

      + +

      If the module identifier passed to require() is not a +core module, and does not begin with '/', '../', or +'./', then Node.js starts at the parent directory of the current module, and +adds /node_modules, and attempts to load the module from that location. +Node.js will not append node_modules to a path already ending in +node_modules.

      +

      If it is not found there, then it moves to the parent directory, and so +on, until the root of the file system is reached.

      +

      For example, if the file at '/home/ry/projects/foo.js' called +require('bar.js'), then Node.js would look in the following locations, in +this order:

      +
        +
      • /home/ry/projects/node_modules/bar.js
      • +
      • /home/ry/node_modules/bar.js
      • +
      • /home/node_modules/bar.js
      • +
      • /node_modules/bar.js
      • +
      +

      This allows programs to localize their dependencies, so that they do not +clash.

      +

      It is possible to require specific files or sub modules distributed with a +module by including a path suffix after the module name. For instance +require('example-module/path/to/file') would resolve path/to/file +relative to where example-module is located. The suffixed path follows the +same module resolution semantics.

      +

      Loading from the global folders#

      + +

      If the NODE_PATH environment variable is set to a colon-delimited list +of absolute paths, then Node.js will search those paths for modules if they +are not found elsewhere.

      +

      On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

      +

      NODE_PATH was originally created to support loading modules from +varying paths before the current module resolution algorithm was defined.

      +

      NODE_PATH is still supported, but is less necessary now that the Node.js +ecosystem has settled on a convention for locating dependent modules. +Sometimes deployments that rely on NODE_PATH show surprising behavior +when people are unaware that NODE_PATH must be set. Sometimes a +module's dependencies change, causing a different version (or even a +different module) to be loaded as the NODE_PATH is searched.

      +

      Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

      +
        +
      • 1: $HOME/.node_modules
      • +
      • 2: $HOME/.node_libraries
      • +
      • 3: $PREFIX/lib/node
      • +
      +

      Where $HOME is the user's home directory, and $PREFIX is the Node.js +configured node_prefix.

      +

      These are mostly for historic reasons.

      +

      It is strongly encouraged to place dependencies in the local node_modules +folder. These will be loaded faster, and more reliably.

      +

      The module wrapper#

      + +

      Before a module's code is executed, Node.js will wrap it with a function +wrapper that looks like the following:

      +
      (function(exports, require, module, __filename, __dirname) {
      +// Module code actually lives in here
      +});
      +

      By doing this, Node.js achieves a few things:

      +
        +
      • It keeps top-level variables (defined with var, const or let) scoped to +the module rather than the global object.
      • +
      • It helps to provide some global-looking variables that are actually specific +to the module, such as: +
          +
        • The module and exports objects that the implementor can use to export +values from the module.
        • +
        • The convenience variables __filename and __dirname, containing the +module's absolute filename and directory path.
        • +
        +
      • +
      +

      The module scope#

      +

      __dirname#

      + + + +

      The directory name of the current module. This is the same as the +path.dirname() of the __filename.

      +

      Example: running node example.js from /Users/mjr

      +
      console.log(__dirname);
      +// Prints: /Users/mjr
      +console.log(path.dirname(__filename));
      +// Prints: /Users/mjr
      +

      __filename#

      + + + +

      The file name of the current module. This is the current module file's absolute +path with symlinks resolved.

      +

      For a main program this is not necessarily the same as the file name used in the +command line.

      +

      See __dirname for the directory name of the current module.

      +

      Examples:

      +

      Running node example.js from /Users/mjr

      +
      console.log(__filename);
      +// Prints: /Users/mjr/example.js
      +console.log(__dirname);
      +// Prints: /Users/mjr
      +

      Given two modules: a and b, where b is a dependency of +a and there is a directory structure of:

      +
        +
      • /Users/mjr/app/a.js
      • +
      • /Users/mjr/app/node_modules/b/b.js
      • +
      +

      References to __filename within b.js will return +/Users/mjr/app/node_modules/b/b.js while references to __filename within +a.js will return /Users/mjr/app/a.js.

      +

      exports#

      + + + +

      A reference to the module.exports that is shorter to type. +See the section about the exports shortcut for details on when to use +exports and when to use module.exports.

      +

      module#

      + + + +

      A reference to the current module, see the section about the +module object. In particular, module.exports is used for defining what +a module exports and makes available through require().

      +

      require(id)#

      + + +
        +
      • id <string> module name or path
      • +
      • Returns: <any> exported module content
      • +
      +

      Used to import modules, JSON, and local files. Modules can be imported +from node_modules. Local modules and JSON files can be imported using +a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be +resolved against the directory named by __dirname (if defined) or +the current working directory. The relative paths of POSIX style are resolved +in an OS independent fashion, meaning that the examples above will work on +Windows in the same way they would on Unix systems.

      +
      // Importing a local module with a path relative to the `__dirname` or current
      +// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
      +const myLocalModule = require('./path/myLocalModule');
      +
      +// Importing a JSON file:
      +const jsonData = require('./path/filename.json');
      +
      +// Importing a module from node_modules or Node.js built-in module:
      +const crypto = require('crypto');
      +

      require.cache#

      + + +

      Modules are cached in this object when they are required. By deleting a key +value from this object, the next require will reload the module. +This does not apply to native addons, for which reloading will result in an +error.

      +

      Adding or replacing entries is also possible. This cache is checked before +native modules and if a name matching a native module is added to the cache, +no require call is +going to receive the native module anymore. Use with care!

      +

      require.extensions#

      + +

      Stability: 0 - Deprecated

      + +

      Instruct require on how to handle certain file extensions.

      +

      Process files with the extension .sjs as .js:

      +
      require.extensions['.sjs'] = require.extensions['.js'];
      +

      Deprecated. In the past, this list has been used to load non-JavaScript +modules into Node.js by compiling them on-demand. However, in practice, there +are much better ways to do this, such as loading modules via some other Node.js +program, or compiling them to JavaScript ahead of time.

      +

      Avoid using require.extensions. Use could cause subtle bugs and resolving the +extensions gets slower with each registered extension.

      +

      require.main#

      + + +

      The Module object representing the entry script loaded when the Node.js +process launched. +See "Accessing the main module".

      +

      In entry.js script:

      +
      console.log(require.main);
      +
      node entry.js
      + +
      Module {
      +  id: '.',
      +  path: '/absolute/path/to',
      +  exports: {},
      +  parent: null,
      +  filename: '/absolute/path/to/entry.js',
      +  loaded: false,
      +  children: [],
      +  paths:
      +   [ '/absolute/path/to/node_modules',
      +     '/absolute/path/node_modules',
      +     '/absolute/node_modules',
      +     '/node_modules' ] }
      +

      require.resolve(request[, options])#

      + +
        +
      • request <string> The module path to resolve.
      • +
      • options <Object> +
          +
        • paths <string[]> Paths to resolve module location from. If present, these +paths are used instead of the default resolution paths, with the exception +of GLOBAL_FOLDERS like $HOME/.node_modules, which are always +included. Each of these paths is used as a starting point for +the module resolution algorithm, meaning that the node_modules hierarchy +is checked from this location.
        • +
        +
      • +
      • Returns: <string>
      • +
      +

      Use the internal require() machinery to look up the location of a module, +but rather than loading the module, just return the resolved filename.

      +

      If the module can not be found, a MODULE_NOT_FOUND error is thrown.

      +
      require.resolve.paths(request)#
      + + +

      Returns an array containing the paths searched during resolution of request or +null if the request string references a core module, for example http or +fs.

      +

      The module object#

      + + + + +

      In each module, the module free variable is a reference to the object +representing the current module. For convenience, module.exports is +also accessible via the exports module-global. module is not actually +a global but rather local to each module.

      +

      module.children#

      + + +

      The module objects required for the first time by this one.

      +

      module.exports#

      + + +

      The module.exports object is created by the Module system. Sometimes this is +not acceptable; many want their module to be an instance of some class. To do +this, assign the desired export object to module.exports. Assigning +the desired object to exports will simply rebind the local exports variable, +which is probably not what is desired.

      +

      For example, suppose we were making a module called a.js:

      +
      const EventEmitter = require('events');
      +
      +module.exports = new EventEmitter();
      +
      +// Do some work, and after some time emit
      +// the 'ready' event from the module itself.
      +setTimeout(() => {
      +  module.exports.emit('ready');
      +}, 1000);
      +

      Then in another file we could do:

      +
      const a = require('./a');
      +a.on('ready', () => {
      +  console.log('module "a" is ready');
      +});
      +

      Assignment to module.exports must be done immediately. It cannot be +done in any callbacks. This does not work:

      +

      x.js:

      +
      setTimeout(() => {
      +  module.exports = { a: 'hello' };
      +}, 0);
      +

      y.js:

      +
      const x = require('./x');
      +console.log(x.a);
      +

      exports shortcut#

      + +

      The exports variable is available within a module's file-level scope, and is +assigned the value of module.exports before the module is evaluated.

      +

      It allows a shortcut, so that module.exports.f = ... can be written more +succinctly as exports.f = .... However, be aware that like any variable, if a +new value is assigned to exports, it is no longer bound to module.exports:

      +
      module.exports.hello = true; // Exported from require of module
      +exports = { hello: false };  // Not exported, only available in the module
      +

      When the module.exports property is being completely replaced by a new +object, it is common to also reassign exports:

      + +
      module.exports = exports = function Constructor() {
      +  // ... etc.
      +};
      +

      To illustrate the behavior, imagine this hypothetical implementation of +require(), which is quite similar to what is actually done by require():

      +
      function require(/* ... */) {
      +  const module = { exports: {} };
      +  ((module, exports) => {
      +    // Module code here. In this example, define a function.
      +    function someFunc() {}
      +    exports = someFunc;
      +    // At this point, exports is no longer a shortcut to module.exports, and
      +    // this module will still export an empty default object.
      +    module.exports = someFunc;
      +    // At this point, the module will now export someFunc, instead of the
      +    // default object.
      +  })(module, module.exports);
      +  return module.exports;
      +}
      +

      module.filename#

      + + +

      The fully resolved filename of the module.

      +

      module.id#

      + + +

      The identifier for the module. Typically this is the fully resolved +filename.

      +

      module.loaded#

      + + +

      Whether or not the module is done loading, or is in the process of +loading.

      +

      module.parent#

      + +

      Stability: 0 - Deprecated: Please use require.main and +module.children instead.

      + +

      The module that first required this one, or null if the current module is the +entry point of the current process, or undefined if the module was loaded by +something that is not a CommonJS module (E.G.: REPL or import).

      +

      module.path#

      + + +

      The directory name of the module. This is usually the same as the +path.dirname() of the module.id.

      +

      module.paths#

      + + +

      The search paths for the module.

      +

      module.require(id)#

      + + +

      The module.require() method provides a way to load a module as if +require() was called from the original module.

      +

      In order to do this, it is necessary to get a reference to the module object. +Since require() returns the module.exports, and the module is typically +only available within a specific module's code, it must be explicitly exported +in order to be used.

      +

      The Module object#

      +

      This section was moved to +Modules: module core module.

      + + +

      Source map v3 support#

      +

      This section was moved to +Modules: module core module.

      + + + +
      +
      +
      + + diff --git a/doc/api/modules.json b/doc/api/modules.json new file mode 100644 index 0000000000000000000000000000000000000000..14b5b3b1bb7e2f807fa9da66867c19d6ac97b2ab --- /dev/null +++ b/doc/api/modules.json @@ -0,0 +1,471 @@ +{ + "type": "module", + "source": "doc/api/modules.md", + "modules": [ + { + "textRaw": "Modules: CommonJS modules", + "name": "module", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      In the Node.js module system, each file is treated as a separate module. For\nexample, consider a file named foo.js:

      \n
      const circle = require('./circle.js');\nconsole.log(`The area of a circle of radius 4 is ${circle.area(4)}`);\n
      \n

      On the first line, foo.js loads the module circle.js that is in the same\ndirectory as foo.js.

      \n

      Here are the contents of circle.js:

      \n
      const { PI } = Math;\n\nexports.area = (r) => PI * r ** 2;\n\nexports.circumference = (r) => 2 * PI * r;\n
      \n

      The module circle.js has exported the functions area() and\ncircumference(). Functions and objects are added to the root of a module\nby specifying additional properties on the special exports object.

      \n

      Variables local to the module will be private, because the module is wrapped\nin a function by Node.js (see module wrapper).\nIn this example, the variable PI is private to circle.js.

      \n

      The module.exports property can be assigned a new value (such as a function\nor object).

      \n

      Below, bar.js makes use of the square module, which exports a Square class:

      \n
      const Square = require('./square.js');\nconst mySquare = new Square(2);\nconsole.log(`The area of mySquare is ${mySquare.area()}`);\n
      \n

      The square module is defined in square.js:

      \n
      // Assigning to exports will not modify module, must use module.exports\nmodule.exports = class Square {\n  constructor(width) {\n    this.width = width;\n  }\n\n  area() {\n    return this.width ** 2;\n  }\n};\n
      \n

      The module system is implemented in the require('module') module.

      ", + "miscs": [ + { + "textRaw": "Accessing the main module", + "name": "Accessing the main module", + "type": "misc", + "desc": "

      When a file is run directly from Node.js, require.main is set to its\nmodule. That means that it is possible to determine whether a file has been\nrun directly by testing require.main === module.

      \n

      For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').

      \n

      Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.

      " + }, + { + "textRaw": "Addenda: Package manager tips", + "name": "Addenda: Package manager tips", + "type": "misc", + "desc": "

      The semantics of the Node.js require() function were designed to be general\nenough to support reasonable directory structures. Package manager programs\nsuch as dpkg, rpm, and npm will hopefully find it possible to build\nnative packages from Node.js modules without modification.

      \n

      Below we give a suggested directory structure that could work:

      \n

      Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.

      \n

      Packages can depend on one another. In order to install package foo, it\nmay be necessary to install a specific version of package bar. The bar\npackage may itself have dependencies, and in some cases, these may even collide\nor form cyclic dependencies.

      \n

      Because Node.js looks up the realpath of any modules it loads (that is, it\nresolves symlinks) and then looks for their dependencies in node_modules folders,\nthis situation can be resolved with the following architecture:

      \n
        \n
      • /usr/lib/node/foo/1.2.3/: Contents of the foo package, version 1.2.3.
      • \n
      • /usr/lib/node/bar/4.3.2/: Contents of the bar package that foo depends\non.
      • \n
      • /usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to\n/usr/lib/node/bar/4.3.2/.
      • \n
      • /usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages that\nbar depends on.
      • \n
      \n

      Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.

      \n

      When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.

      \n

      Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then Node.js will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.

      \n

      In order to make modules available to the Node.js REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.

      " + }, + { + "textRaw": "All together...", + "name": "All together...", + "type": "misc", + "desc": "

      To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.

      \n

      Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require() does:

      \n
      require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with '/'\n   a. set Y to be the filesystem root\n3. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n   c. THROW \"not found\"\n4. If X begins with '#'\n   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))\n5. LOAD_PACKAGE_SELF(X, dirname(Y))\n6. LOAD_NODE_MODULES(X, dirname(Y))\n7. THROW \"not found\"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as its file extension format. STOP\n2. If X.js is a file, load X.js as JavaScript text. STOP\n3. If X.json is a file, parse X.json to a JavaScript Object. STOP\n4. If X.node is a file, load X.node as binary addon. STOP\n\nLOAD_INDEX(X)\n1. If X/index.js is a file, load X/index.js as JavaScript text. STOP\n2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n3. If X/index.node is a file, load X/index.node as binary addon. STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for \"main\" field.\n   b. If \"main\" is a falsy value, GOTO 2.\n   c. let M = X + (json main field)\n   d. LOAD_AS_FILE(M)\n   e. LOAD_INDEX(M)\n   f. LOAD_INDEX(X) DEPRECATED\n   g. THROW \"not found\"\n2. LOAD_INDEX(X)\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS = NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_PACKAGE_EXPORTS(X, DIR)\n   b. LOAD_AS_FILE(DIR/X)\n   c. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = [GLOBAL_FOLDERS]\n4. while I >= 0,\n   a. if PARTS[I] = \"node_modules\" CONTINUE\n   b. DIR = path join(PARTS[0 .. I] + \"node_modules\")\n   c. DIRS = DIRS + DIR\n   d. let I = I - 1\n5. return DIRS\n\nLOAD_PACKAGE_IMPORTS(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"imports\" is null or undefined, return.\n4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),\n  [\"node\", \"require\"]) defined in the ESM resolver.\n5. RESOLVE_ESM_MATCH(MATCH).\n\nLOAD_PACKAGE_EXPORTS(X, DIR)\n1. Try to interpret X as a combination of NAME and SUBPATH where the name\n   may have a @scope/ prefix and the subpath begins with a slash (`/`).\n2. If X does not match this pattern or DIR/NAME/package.json is not a file,\n   return.\n3. Parse DIR/NAME/package.json, and look for \"exports\" field.\n4. If \"exports\" is null or undefined, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), \".\" + SUBPATH,\n   `package.json` \"exports\", [\"node\", \"require\"]) defined in the ESM resolver.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nLOAD_PACKAGE_SELF(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"exports\" is null or undefined, return.\n4. If the SCOPE/package.json \"name\" is not the first segment of X, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),\n   \".\" + X.slice(\"name\".length), `package.json` \"exports\", [\"node\", \"require\"])\n   defined in the ESM resolver.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nRESOLVE_ESM_MATCH(MATCH)\n1. let { RESOLVED, EXACT } = MATCH\n2. let RESOLVED_PATH = fileURLToPath(RESOLVED)\n3. If EXACT is true,\n   a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension\n      format. STOP\n4. Otherwise, if EXACT is false,\n   a. LOAD_AS_FILE(RESOLVED_PATH)\n   b. LOAD_AS_DIRECTORY(RESOLVED_PATH)\n5. THROW \"not found\"\n
      " + }, + { + "textRaw": "Caching", + "name": "Caching", + "type": "misc", + "desc": "

      Modules are cached after the first time they are loaded. This means (among other\nthings) that every call to require('foo') will get exactly the same object\nreturned, if it would resolve to the same file.

      \n

      Provided require.cache is not modified, multiple calls to require('foo')\nwill not cause the module code to be executed multiple times. This is an\nimportant feature. With it, \"partially done\" objects can be returned, thus\nallowing transitive dependencies to be loaded even when they would cause cycles.

      \n

      To have a module execute code multiple times, export a function, and call that\nfunction.

      ", + "miscs": [ + { + "textRaw": "Module caching caveats", + "name": "Module caching caveats", + "type": "misc", + "desc": "

      Modules are cached based on their resolved filename. Since modules may resolve\nto a different filename based on the location of the calling module (loading\nfrom node_modules folders), it is not a guarantee that require('foo') will\nalways return the exact same object, if it would resolve to different files.

      \n

      Additionally, on case-insensitive file systems or operating systems, different\nresolved filenames can point to the same file, but the cache will still treat\nthem as different modules and will reload the file multiple times. For example,\nrequire('./foo') and require('./FOO') return two different objects,\nirrespective of whether or not ./foo and ./FOO are the same file.

      " + } + ] + }, + { + "textRaw": "Core modules", + "name": "Core modules", + "type": "misc", + "desc": "

      Node.js has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.

      \n

      The core modules are defined within the Node.js source and are located in the\nlib/ folder.

      \n

      Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.

      " + }, + { + "textRaw": "Cycles", + "name": "Cycles", + "type": "misc", + "desc": "

      When there are circular require() calls, a module might not have finished\nexecuting when it is returned.

      \n

      Consider this situation:

      \n

      a.js:

      \n
      console.log('a starting');\nexports.done = false;\nconst b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');\n
      \n

      b.js:

      \n
      console.log('b starting');\nexports.done = false;\nconst a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');\n
      \n

      main.js:

      \n
      console.log('main starting');\nconst a = require('./a.js');\nconst b = require('./b.js');\nconsole.log('in main, a.done = %j, b.done = %j', a.done, b.done);\n
      \n

      When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop, an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.

      \n

      By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:

      \n
      $ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done = true, b.done = true\n
      \n

      Careful planning is required to allow cyclic module dependencies to work\ncorrectly within an application.

      " + }, + { + "textRaw": "File modules", + "name": "File modules", + "type": "misc", + "desc": "

      If the exact filename is not found, then Node.js will attempt to load the\nrequired filename with the added extensions: .js, .json, and finally\n.node.

      \n

      .js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with process.dlopen().

      \n

      A required module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.

      \n

      A required module prefixed with './' is relative to the file calling\nrequire(). That is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.

      \n

      Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules folder.

      \n

      If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.

      " + }, + { + "textRaw": "Folders as modules", + "name": "Folders as modules", + "type": "misc", + "desc": "

      It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to those directories.\nThere are three ways in which a folder may be passed to require() as\nan argument.

      \n

      The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:

      \n
      { \"name\" : \"some-library\",\n  \"main\" : \"./lib/some-library.js\" }\n
      \n

      If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.

      \n

      This is the extent of the awareness of package.json files within Node.js.

      \n

      If there is no package.json file present in the directory, or if the\n\"main\" entry is missing or cannot be resolved, then Node.js\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the previous\nexample, then require('./some-library') would attempt to load:

      \n
        \n
      • ./some-library/index.js
      • \n
      • ./some-library/index.node
      • \n
      \n

      If these attempts fail, then Node.js will report the entire module as missing\nwith the default error:

      \n
      Error: Cannot find module 'some-library'\n
      " + }, + { + "textRaw": "Loading from `node_modules` folders", + "name": "Loading from `node_modules` folders", + "type": "misc", + "desc": "

      If the module identifier passed to require() is not a\ncore module, and does not begin with '/', '../', or\n'./', then Node.js starts at the parent directory of the current module, and\nadds /node_modules, and attempts to load the module from that location.\nNode.js will not append node_modules to a path already ending in\nnode_modules.

      \n

      If it is not found there, then it moves to the parent directory, and so\non, until the root of the file system is reached.

      \n

      For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then Node.js would look in the following locations, in\nthis order:

      \n
        \n
      • /home/ry/projects/node_modules/bar.js
      • \n
      • /home/ry/node_modules/bar.js
      • \n
      • /home/node_modules/bar.js
      • \n
      • /node_modules/bar.js
      • \n
      \n

      This allows programs to localize their dependencies, so that they do not\nclash.

      \n

      It is possible to require specific files or sub modules distributed with a\nmodule by including a path suffix after the module name. For instance\nrequire('example-module/path/to/file') would resolve path/to/file\nrelative to where example-module is located. The suffixed path follows the\nsame module resolution semantics.

      " + }, + { + "textRaw": "Loading from the global folders", + "name": "Loading from the global folders", + "type": "misc", + "desc": "

      If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then Node.js will search those paths for modules if they\nare not found elsewhere.

      \n

      On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

      \n

      NODE_PATH was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was defined.

      \n

      NODE_PATH is still supported, but is less necessary now that the Node.js\necosystem has settled on a convention for locating dependent modules.\nSometimes deployments that rely on NODE_PATH show surprising behavior\nwhen people are unaware that NODE_PATH must be set. Sometimes a\nmodule's dependencies change, causing a different version (or even a\ndifferent module) to be loaded as the NODE_PATH is searched.

      \n

      Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

      \n
        \n
      • 1: $HOME/.node_modules
      • \n
      • 2: $HOME/.node_libraries
      • \n
      • 3: $PREFIX/lib/node
      • \n
      \n

      Where $HOME is the user's home directory, and $PREFIX is the Node.js\nconfigured node_prefix.

      \n

      These are mostly for historic reasons.

      \n

      It is strongly encouraged to place dependencies in the local node_modules\nfolder. These will be loaded faster, and more reliably.

      " + }, + { + "textRaw": "The module wrapper", + "name": "The module wrapper", + "type": "misc", + "desc": "

      Before a module's code is executed, Node.js will wrap it with a function\nwrapper that looks like the following:

      \n
      (function(exports, require, module, __filename, __dirname) {\n// Module code actually lives in here\n});\n
      \n

      By doing this, Node.js achieves a few things:

      \n
        \n
      • It keeps top-level variables (defined with var, const or let) scoped to\nthe module rather than the global object.
      • \n
      • It helps to provide some global-looking variables that are actually specific\nto the module, such as:\n
          \n
        • The module and exports objects that the implementor can use to export\nvalues from the module.
        • \n
        • The convenience variables __filename and __dirname, containing the\nmodule's absolute filename and directory path.
        • \n
        \n
      • \n
      " + } + ], + "modules": [ + { + "textRaw": "Addenda: The `.mjs` extension", + "name": "addenda:_the_`.mjs`_extension", + "desc": "

      It is not possible to require() files that have the .mjs extension.\nAttempting to do so will throw an error. The .mjs extension is\nreserved for ECMAScript Modules which cannot be loaded via require().\nSee ECMAScript Modules for more details.

      ", + "type": "module", + "displayName": "Addenda: The `.mjs` extension" + }, + { + "textRaw": "The module scope", + "name": "the_module_scope", + "vars": [ + { + "textRaw": "`__dirname`", + "name": "`__dirname`", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      The directory name of the current module. This is the same as the\npath.dirname() of the __filename.

      \n

      Example: running node example.js from /Users/mjr

      \n
      console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
      " + }, + { + "textRaw": "`__filename`", + "name": "`__filename`", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      The file name of the current module. This is the current module file's absolute\npath with symlinks resolved.

      \n

      For a main program this is not necessarily the same as the file name used in the\ncommand line.

      \n

      See __dirname for the directory name of the current module.

      \n

      Examples:

      \n

      Running node example.js from /Users/mjr

      \n
      console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
      \n

      Given two modules: a and b, where b is a dependency of\na and there is a directory structure of:

      \n
        \n
      • /Users/mjr/app/a.js
      • \n
      • /Users/mjr/app/node_modules/b/b.js
      • \n
      \n

      References to __filename within b.js will return\n/Users/mjr/app/node_modules/b/b.js while references to __filename within\na.js will return /Users/mjr/app/a.js.

      " + }, + { + "textRaw": "`exports`", + "name": "`exports`", + "meta": { + "added": [ + "v0.1.12" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      A reference to the module.exports that is shorter to type.\nSee the section about the exports shortcut for details on when to use\nexports and when to use module.exports.

      " + }, + { + "textRaw": "`module`", + "name": "`module`", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      A reference to the current module, see the section about the\nmodule object. In particular, module.exports is used for defining what\na module exports and makes available through require().

      " + }, + { + "textRaw": "`require(id)`", + "type": "var", + "name": "require", + "meta": { + "added": [ + "v0.1.13" + ], + "changes": [] + }, + "desc": "
        \n
      • id <string> module name or path
      • \n
      • Returns: <any> exported module content
      • \n
      \n

      Used to import modules, JSON, and local files. Modules can be imported\nfrom node_modules. Local modules and JSON files can be imported using\na relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be\nresolved against the directory named by __dirname (if defined) or\nthe current working directory. The relative paths of POSIX style are resolved\nin an OS independent fashion, meaning that the examples above will work on\nWindows in the same way they would on Unix systems.

      \n
      // Importing a local module with a path relative to the `__dirname` or current\n// working directory. (On Windows, this would resolve to .\\path\\myLocalModule.)\nconst myLocalModule = require('./path/myLocalModule');\n\n// Importing a JSON file:\nconst jsonData = require('./path/filename.json');\n\n// Importing a module from node_modules or Node.js built-in module:\nconst crypto = require('crypto');\n
      ", + "properties": [ + { + "textRaw": "`cache` {Object}", + "type": "Object", + "name": "cache", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "desc": "

      Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\nThis does not apply to native addons, for which reloading will result in an\nerror.

      \n

      Adding or replacing entries is also possible. This cache is checked before\nnative modules and if a name matching a native module is added to the cache,\nno require call is\ngoing to receive the native module anymore. Use with care!

      " + }, + { + "textRaw": "`extensions` {Object}", + "type": "Object", + "name": "extensions", + "meta": { + "added": [ + "v0.3.0" + ], + "deprecated": [ + "v0.10.6" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Instruct require on how to handle certain file extensions.

      \n

      Process files with the extension .sjs as .js:

      \n
      require.extensions['.sjs'] = require.extensions['.js'];\n
      \n

      Deprecated. In the past, this list has been used to load non-JavaScript\nmodules into Node.js by compiling them on-demand. However, in practice, there\nare much better ways to do this, such as loading modules via some other Node.js\nprogram, or compiling them to JavaScript ahead of time.

      \n

      Avoid using require.extensions. Use could cause subtle bugs and resolving the\nextensions gets slower with each registered extension.

      " + }, + { + "textRaw": "`main` {module}", + "type": "module", + "name": "main", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "

      The Module object representing the entry script loaded when the Node.js\nprocess launched.\nSee \"Accessing the main module\".

      \n

      In entry.js script:

      \n
      console.log(require.main);\n
      \n
      node entry.js\n
      \n\n
      Module {\n  id: '.',\n  path: '/absolute/path/to',\n  exports: {},\n  parent: null,\n  filename: '/absolute/path/to/entry.js',\n  loaded: false,\n  children: [],\n  paths:\n   [ '/absolute/path/to/node_modules',\n     '/absolute/path/node_modules',\n     '/absolute/node_modules',\n     '/node_modules' ] }\n
      " + } + ], + "methods": [ + { + "textRaw": "`require.resolve(request[, options])`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v8.9.0", + "pr-url": "https://github.com/nodejs/node/pull/16397", + "description": "The `paths` option is now supported." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`request` {string} The module path to resolve.", + "name": "request", + "type": "string", + "desc": "The module path to resolve." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`paths` {string[]} Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location.", + "name": "paths", + "type": "string[]", + "desc": "Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location." + } + ] + } + ] + } + ], + "desc": "

      Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.

      \n

      If the module can not be found, a MODULE_NOT_FOUND error is thrown.

      ", + "methods": [ + { + "textRaw": "`require.resolve.paths(request)`", + "type": "method", + "name": "paths", + "meta": { + "added": [ + "v8.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]|null}", + "name": "return", + "type": "string[]|null" + }, + "params": [ + { + "textRaw": "`request` {string} The module path whose lookup paths are being retrieved.", + "name": "request", + "type": "string", + "desc": "The module path whose lookup paths are being retrieved." + } + ] + } + ], + "desc": "

      Returns an array containing the paths searched during resolution of request or\nnull if the request string references a core module, for example http or\nfs.

      " + } + ] + } + ] + } + ], + "type": "module", + "displayName": "The module scope" + }, + { + "textRaw": "The `Module` object", + "name": "the_`module`_object", + "desc": "

      This section was moved to\nModules: module core module.

      \n\n", + "type": "module", + "displayName": "The `Module` object" + }, + { + "textRaw": "Source map v3 support", + "name": "source_map_v3_support", + "desc": "

      This section was moved to\nModules: module core module.

      \n\n", + "type": "module", + "displayName": "Source map v3 support" + } + ], + "vars": [ + { + "textRaw": "The `module` object", + "name": "module", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "type": "var", + "desc": "\n

      In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module is not actually\na global but rather local to each module.

      ", + "properties": [ + { + "textRaw": "`children` {module[]}", + "type": "module[]", + "name": "children", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The module objects required for the first time by this one.

      " + }, + { + "textRaw": "`exports` {Object}", + "type": "Object", + "name": "exports", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The module.exports object is created by the Module system. Sometimes this is\nnot acceptable; many want their module to be an instance of some class. To do\nthis, assign the desired export object to module.exports. Assigning\nthe desired object to exports will simply rebind the local exports variable,\nwhich is probably not what is desired.

      \n

      For example, suppose we were making a module called a.js:

      \n
      const EventEmitter = require('events');\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(() => {\n  module.exports.emit('ready');\n}, 1000);\n
      \n

      Then in another file we could do:

      \n
      const a = require('./a');\na.on('ready', () => {\n  console.log('module \"a\" is ready');\n});\n
      \n

      Assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:

      \n

      x.js:

      \n
      setTimeout(() => {\n  module.exports = { a: 'hello' };\n}, 0);\n
      \n

      y.js:

      \n
      const x = require('./x');\nconsole.log(x.a);\n
      ", + "modules": [ + { + "textRaw": "`exports` shortcut", + "name": "`exports`_shortcut", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The exports variable is available within a module's file-level scope, and is\nassigned the value of module.exports before the module is evaluated.

      \n

      It allows a shortcut, so that module.exports.f = ... can be written more\nsuccinctly as exports.f = .... However, be aware that like any variable, if a\nnew value is assigned to exports, it is no longer bound to module.exports:

      \n
      module.exports.hello = true; // Exported from require of module\nexports = { hello: false };  // Not exported, only available in the module\n
      \n

      When the module.exports property is being completely replaced by a new\nobject, it is common to also reassign exports:

      \n\n
      module.exports = exports = function Constructor() {\n  // ... etc.\n};\n
      \n

      To illustrate the behavior, imagine this hypothetical implementation of\nrequire(), which is quite similar to what is actually done by require():

      \n
      function require(/* ... */) {\n  const module = { exports: {} };\n  ((module, exports) => {\n    // Module code here. In this example, define a function.\n    function someFunc() {}\n    exports = someFunc;\n    // At this point, exports is no longer a shortcut to module.exports, and\n    // this module will still export an empty default object.\n    module.exports = someFunc;\n    // At this point, the module will now export someFunc, instead of the\n    // default object.\n  })(module, module.exports);\n  return module.exports;\n}\n
      ", + "type": "module", + "displayName": "`exports` shortcut" + } + ] + }, + { + "textRaw": "`filename` {string}", + "type": "string", + "name": "filename", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The fully resolved filename of the module.

      " + }, + { + "textRaw": "`id` {string}", + "type": "string", + "name": "id", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The identifier for the module. Typically this is the fully resolved\nfilename.

      " + }, + { + "textRaw": "`loaded` {boolean}", + "type": "boolean", + "name": "loaded", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      Whether or not the module is done loading, or is in the process of\nloading.

      " + }, + { + "textRaw": "`parent` {module | null | undefined}", + "type": "module | null | undefined", + "name": "parent", + "meta": { + "added": [ + "v0.1.16" + ], + "deprecated": [ + "v12.19.0", + "v14.6.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Please use [`require.main`][] and\n[`module.children`][] instead.", + "desc": "

      The module that first required this one, or null if the current module is the\nentry point of the current process, or undefined if the module was loaded by\nsomething that is not a CommonJS module (E.G.: REPL or import).

      " + }, + { + "textRaw": "`path` {string}", + "type": "string", + "name": "path", + "meta": { + "added": [ + "v11.14.0" + ], + "changes": [] + }, + "desc": "

      The directory name of the module. This is usually the same as the\npath.dirname() of the module.id.

      " + }, + { + "textRaw": "`paths` {string[]}", + "type": "string[]", + "name": "paths", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "desc": "

      The search paths for the module.

      " + } + ], + "methods": [ + { + "textRaw": "`module.require(id)`", + "type": "method", + "name": "require", + "meta": { + "added": [ + "v0.5.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} exported module content", + "name": "return", + "type": "any", + "desc": "exported module content" + }, + "params": [ + { + "textRaw": "`id` {string}", + "name": "id", + "type": "string" + } + ] + } + ], + "desc": "

      The module.require() method provides a way to load a module as if\nrequire() was called from the original module.

      \n

      In order to do this, it is necessary to get a reference to the module object.\nSince require() returns the module.exports, and the module is typically\nonly available within a specific module's code, it must be explicitly exported\nin order to be used.

      " + } + ] + } + ], + "type": "module", + "displayName": "module" + } + ] +} \ No newline at end of file diff --git a/doc/api/n-api.html b/doc/api/n-api.html new file mode 100644 index 0000000000000000000000000000000000000000..64e4b5251eea313d36964bda5aceed346fc77781 --- /dev/null +++ b/doc/api/n-api.html @@ -0,0 +1,5149 @@ + + + + + + + N-API | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      N-API#

      + + +

      Stability: 2 - Stable

      +

      N-API (pronounced N as in the letter, followed by API) +is an API for building native Addons. It is independent from +the underlying JavaScript runtime (for example, V8) and is maintained as part of +Node.js itself. This API will be Application Binary Interface (ABI) stable +across versions of Node.js. It is intended to insulate Addons from +changes in the underlying JavaScript engine and allow modules +compiled for one major version to run on later major versions of Node.js without +recompilation. The ABI Stability guide provides a more in-depth explanation.

      +

      Addons are built/packaged with the same approach/tools outlined in the section +titled C++ Addons. The only difference is the set of APIs that are used by +the native code. Instead of using the V8 or Native Abstractions for Node.js +APIs, the functions available in the N-API are used.

      +

      APIs exposed by N-API are generally used to create and manipulate +JavaScript values. Concepts and operations generally map to ideas specified +in the ECMA-262 Language Specification. The APIs have the following +properties:

      +
        +
      • All N-API calls return a status code of type napi_status. This +status indicates whether the API call succeeded or failed.
      • +
      • The API's return value is passed via an out parameter.
      • +
      • All JavaScript values are abstracted behind an opaque type named +napi_value.
      • +
      • In case of an error status code, additional information can be obtained +using napi_get_last_error_info. More information can be found in the error +handling section Error handling.
      • +
      +

      The N-API is a C API that ensures ABI stability across Node.js versions +and different compiler levels. A C++ API can be easier to use. +To support using C++, the project maintains a +C++ wrapper module called node-addon-api. +This wrapper provides an inlineable C++ API. Binaries built +with node-addon-api will depend on the symbols for the N-API C-based +functions exported by Node.js. node-addon-api is a more +efficient way to write code that calls N-API. Take, for example, the +following node-addon-api code. The first section shows the +node-addon-api code and the second section shows what actually gets +used in the addon.

      +
      Object obj = Object::New(env);
      +obj["foo"] = String::New(env, "bar");
      +
      napi_status status;
      +napi_value object, string;
      +status = napi_create_object(env, &object);
      +if (status != napi_ok) {
      +  napi_throw_error(env, ...);
      +  return;
      +}
      +
      +status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string);
      +if (status != napi_ok) {
      +  napi_throw_error(env, ...);
      +  return;
      +}
      +
      +status = napi_set_named_property(env, object, "foo", string);
      +if (status != napi_ok) {
      +  napi_throw_error(env, ...);
      +  return;
      +}
      +

      The end result is that the addon only uses the exported C APIs. As a result, +it still gets the benefits of the ABI stability provided by the C API.

      +

      When using node-addon-api instead of the C APIs, start with the API docs +for node-addon-api.

      +

      The N-API Resource offers an +excellent orientation and tips for developers just getting started with N-API +and node-addon-api.

      +

      Implications of ABI stability#

      +

      Although N-API provides an ABI stability guarantee, other parts of Node.js do +not, and any external libraries used from the addon may not. In particular, +none of the following APIs provide an ABI stability guarantee across major +versions:

      +
        +
      • +

        the Node.js C++ APIs available via any of

        +
        #include <node.h>
        +#include <node_buffer.h>
        +#include <node_version.h>
        +#include <node_object_wrap.h>
        +
      • +
      • +

        the libuv APIs which are also included with Node.js and available via

        +
        #include <uv.h>
        +
      • +
      • +

        the V8 API available via

        +
        #include <v8.h>
        +
      • +
      +

      Thus, for an addon to remain ABI-compatible across Node.js major versions, it +must use N-API exclusively by restricting itself to using

      +
      #include <node_api.h>
      +

      and by checking, for all external libraries that it uses, that the external +library makes ABI stability guarantees similar to N-API.

      +

      Building#

      +

      Unlike modules written in JavaScript, developing and deploying Node.js +native addons using N-API requires an additional set of tools. Besides the +basic tools required to develop for Node.js, the native addon developer +requires a toolchain that can compile C and C++ code into a binary. In +addition, depending upon how the native addon is deployed, the user of +the native addon will also need to have a C/C++ toolchain installed.

      +

      For Linux developers, the necessary C/C++ toolchain packages are readily +available. GCC is widely used in the Node.js community to build and +test across a variety of platforms. For many developers, the LLVM +compiler infrastructure is also a good choice.

      +

      For Mac developers, Xcode offers all the required compiler tools. +However, it is not necessary to install the entire Xcode IDE. The following +command installs the necessary toolchain:

      +
      xcode-select --install
      +

      For Windows developers, Visual Studio offers all the required compiler +tools. However, it is not necessary to install the entire Visual Studio +IDE. The following command installs the necessary toolchain:

      +
      npm install --global windows-build-tools
      +

      The sections below describe the additional tools available for developing +and deploying Node.js native addons.

      +

      Build tools#

      +

      Both the tools listed here require that users of the native +addon have a C/C++ toolchain installed in order to successfully install +the native addon.

      +

      node-gyp#

      +

      node-gyp is a build system based on Google's GYP tool and comes +bundled with npm. GYP, and therefore node-gyp, requires that Python be +installed.

      +

      Historically, node-gyp has been the tool of choice for building native +addons. It has widespread adoption and documentation. However, some +developers have run into limitations in node-gyp.

      +

      CMake.js#

      +

      CMake.js is an alternative build system based on CMake.

      +

      CMake.js is a good choice for projects that already use CMake or for +developers affected by limitations in node-gyp.

      +

      Uploading precompiled binaries#

      +

      The three tools listed here permit native addon developers and maintainers +to create and upload binaries to public or private servers. These tools are +typically integrated with CI/CD build systems like Travis CI and +AppVeyor to build and upload binaries for a variety of platforms and +architectures. These binaries are then available for download by users who +do not need to have a C/C++ toolchain installed.

      +

      node-pre-gyp#

      +

      node-pre-gyp is a tool based on node-gyp that adds the ability to +upload binaries to a server of the developer's choice. node-pre-gyp has +particularly good support for uploading binaries to Amazon S3.

      +

      prebuild#

      +

      prebuild is a tool that supports builds using either node-gyp or +CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild +uploads binaries only to GitHub releases. prebuild is a good choice for +GitHub projects using CMake.js.

      +

      prebuildify#

      +

      prebuildify is a tool based on node-gyp. The advantage of prebuildify is +that the built binaries are bundled with the native module when it's +uploaded to npm. The binaries are downloaded from npm and are immediately +available to the module user when the native module is installed.

      +

      Usage#

      +

      In order to use the N-API functions, include the file node_api.h which is +located in the src directory in the node development tree:

      +
      #include <node_api.h>
      +

      This will opt into the default NAPI_VERSION for the given release of Node.js. +In order to ensure compatibility with specific versions of N-API, the version +can be specified explicitly when including the header:

      +
      #define NAPI_VERSION 3
      +#include <node_api.h>
      +

      This restricts the N-API surface to just the functionality that was available in +the specified (and earlier) versions.

      +

      Some of the N-API surface is experimental and requires explicit opt-in:

      +
      #define NAPI_EXPERIMENTAL
      +#include <node_api.h>
      +

      In this case the entire API surface, including any experimental APIs, will be +available to the module code.

      +

      N-API version matrix#

      +

      N-API versions are additive and versioned independently from Node.js. +Version 4 is an extension to version 3 in that it has all of the APIs +from version 3 with some additions. This means that it is not necessary +to recompile for new versions of Node.js which are +listed as supporting a later version.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      123456
      v6.xv6.14.2*
      v8.xv8.0.0*v8.10.0*v8.11.2v8.16.0
      v9.xv9.0.0*v9.3.0*v9.11.0*
      v10.xv10.0.0v10.0.0v10.0.0v10.16.0v10.17.0v10.20.0
      v11.xv11.0.0v11.0.0v11.0.0v11.8.0
      v12.xv12.0.0v12.0.0v12.0.0v12.0.0v12.11.0v12.17.0
      v13.xv13.0.0v13.0.0v13.0.0v13.0.0v13.0.0
      v14.xv14.0.0v14.0.0v14.0.0v14.0.0v14.0.0v14.0.0
      +

      * Indicates that the N-API version was released as experimental

      +

      Each API documented for N-API will have a header named added in:, and APIs +which are stable will have the additional header N-API version:. +APIs are directly usable when using a Node.js version which supports +the N-API version shown in N-API version: or higher. +When using a Node.js version that does not support the +N-API version: listed or if there is no N-API version: listed, +then the API will only be available if +#define NAPI_EXPERIMENTAL precedes the inclusion of node_api.h +or js_native_api.h. If an API appears not to be available on +a version of Node.js which is later than the one shown in added in: then +this is most likely the reason for the apparent absence.

      +

      The N-APIs associated strictly with accessing ECMAScript features from native +code can be found separately in js_native_api.h and js_native_api_types.h. +The APIs defined in these headers are included in node_api.h and +node_api_types.h. The headers are structured in this way in order to allow +implementations of N-API outside of Node.js. For those implementations the +Node.js specific APIs may not be applicable.

      +

      The Node.js-specific parts of an addon can be separated from the code that +exposes the actual functionality to the JavaScript environment so that the +latter may be used with multiple implementations of N-API. In the example below, +addon.c and addon.h refer only to js_native_api.h. This ensures that +addon.c can be reused to compile against either the Node.js implementation of +N-API or any implementation of N-API outside of Node.js.

      +

      addon_node.c is a separate file that contains the Node.js specific entry point +to the addon and which instantiates the addon by calling into addon.c when the +addon is loaded into a Node.js environment.

      +
      // addon.h
      +#ifndef _ADDON_H_
      +#define _ADDON_H_
      +#include <js_native_api.h>
      +napi_value create_addon(napi_env env);
      +#endif  // _ADDON_H_
      +
      // addon.c
      +#include "addon.h"
      +
      +#define NAPI_CALL(env, call)                                      \
      +  do {                                                            \
      +    napi_status status = (call);                                  \
      +    if (status != napi_ok) {                                      \
      +      const napi_extended_error_info* error_info = NULL;          \
      +      napi_get_last_error_info((env), &error_info);               \
      +      bool is_pending;                                            \
      +      napi_is_exception_pending((env), &is_pending);              \
      +      if (!is_pending) {                                          \
      +        const char* message = (error_info->error_message == NULL) \
      +            ? "empty error message"                               \
      +            : error_info->error_message;                          \
      +        napi_throw_error((env), NULL, message);                   \
      +        return NULL;                                              \
      +      }                                                           \
      +    }                                                             \
      +  } while(0)
      +
      +static napi_value
      +DoSomethingUseful(napi_env env, napi_callback_info info) {
      +  // Do something useful.
      +  return NULL;
      +}
      +
      +napi_value create_addon(napi_env env) {
      +  napi_value result;
      +  NAPI_CALL(env, napi_create_object(env, &result));
      +
      +  napi_value exported_function;
      +  NAPI_CALL(env, napi_create_function(env,
      +                                      "doSomethingUseful",
      +                                      NAPI_AUTO_LENGTH,
      +                                      DoSomethingUseful,
      +                                      NULL,
      +                                      &exported_function));
      +
      +  NAPI_CALL(env, napi_set_named_property(env,
      +                                         result,
      +                                         "doSomethingUseful",
      +                                         exported_function));
      +
      +  return result;
      +}
      +
      // addon_node.c
      +#include <node_api.h>
      +#include "addon.h"
      +
      +NAPI_MODULE_INIT() {
      +  // This function body is expected to return a `napi_value`.
      +  // The variables `napi_env env` and `napi_value exports` may be used within
      +  // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.
      +  return create_addon(env);
      +}
      +

      Environment life cycle APIs#

      +

      Section 8.7 of the ECMAScript Language Specification defines the concept +of an "Agent" as a self-contained environment in which JavaScript code runs. +Multiple such Agents may be started and terminated either concurrently or in +sequence by the process.

      +

      A Node.js environment corresponds to an ECMAScript Agent. In the main process, +an environment is created at startup, and additional environments can be created +on separate threads to serve as worker threads. When Node.js is embedded in +another application, the main thread of the application may also construct and +destroy a Node.js environment multiple times during the life cycle of the +application process such that each Node.js environment created by the +application may, in turn, during its life cycle create and destroy additional +environments as worker threads.

      +

      From the perspective of a native addon this means that the bindings it provides +may be called multiple times, from multiple contexts, and even concurrently from +multiple threads.

      +

      Native addons may need to allocate global state which they use during +their entire life cycle such that the state must be unique to each instance of +the addon.

      +

      To this end, N-API provides a way to allocate data such that its life cycle is +tied to the life cycle of the Agent.

      +

      napi_set_instance_data#

      + +
      napi_status napi_set_instance_data(napi_env env,
      +                                   void* data,
      +                                   napi_finalize finalize_cb,
      +                                   void* finalize_hint);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] data: The data item to make available to bindings of this instance.
      • +
      • [in] finalize_cb: The function to call when the environment is being torn +down. The function receives data so that it might free it. +napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API associates data with the currently running Agent. data can later +be retrieved using napi_get_instance_data(). Any existing data associated with +the currently running Agent which was set by means of a previous call to +napi_set_instance_data() will be overwritten. If a finalize_cb was provided +by the previous call, it will not be called.

      +

      napi_get_instance_data#

      + +
      napi_status napi_get_instance_data(napi_env env,
      +                                   void** data);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [out] data: The data item that was previously associated with the currently +running Agent by a call to napi_set_instance_data().
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API retrieves data that was previously associated with the currently +running Agent via napi_set_instance_data(). If no data is set, the call will +succeed and data will be set to NULL.

      +

      Basic N-API data types#

      +

      N-API exposes the following fundamental datatypes as abstractions that are +consumed by the various APIs. These APIs should be treated as opaque, +introspectable only with other N-API calls.

      +

      napi_status#

      + +

      Integral status code indicating the success or failure of a N-API call. +Currently, the following status codes are supported.

      +
      typedef enum {
      +  napi_ok,
      +  napi_invalid_arg,
      +  napi_object_expected,
      +  napi_string_expected,
      +  napi_name_expected,
      +  napi_function_expected,
      +  napi_number_expected,
      +  napi_boolean_expected,
      +  napi_array_expected,
      +  napi_generic_failure,
      +  napi_pending_exception,
      +  napi_cancelled,
      +  napi_escape_called_twice,
      +  napi_handle_scope_mismatch,
      +  napi_callback_scope_mismatch,
      +  napi_queue_full,
      +  napi_closing,
      +  napi_bigint_expected,
      +  napi_date_expected,
      +  napi_arraybuffer_expected,
      +  napi_detachable_arraybuffer_expected,
      +} napi_status;
      +

      If additional information is required upon an API returning a failed status, +it can be obtained by calling napi_get_last_error_info.

      +

      napi_extended_error_info#

      + +
      typedef struct {
      +  const char* error_message;
      +  void* engine_reserved;
      +  uint32_t engine_error_code;
      +  napi_status error_code;
      +} napi_extended_error_info;
      +
        +
      • error_message: UTF8-encoded string containing a VM-neutral description of +the error.
      • +
      • engine_reserved: Reserved for VM-specific error details. This is currently +not implemented for any VM.
      • +
      • engine_error_code: VM-specific error code. This is currently +not implemented for any VM.
      • +
      • error_code: The N-API status code that originated with the last error.
      • +
      +

      See the Error handling section for additional information.

      +

      napi_env#

      +

      napi_env is used to represent a context that the underlying N-API +implementation can use to persist VM-specific state. This structure is passed +to native functions when they're invoked, and it must be passed back when +making N-API calls. Specifically, the same napi_env that was passed in when +the initial native function was called must be passed to any subsequent +nested N-API calls. Caching the napi_env for the purpose of general reuse, +and passing the napi_env between instances of the same addon running on +different Worker threads is not allowed. The napi_env becomes invalid +when an instance of a native addon is unloaded. Notification of this event is +delivered through the callbacks given to napi_add_env_cleanup_hook and +napi_set_instance_data.

      +

      napi_value#

      +

      This is an opaque pointer that is used to represent a JavaScript value.

      +

      napi_threadsafe_function#

      + +

      This is an opaque pointer that represents a JavaScript function which can be +called asynchronously from multiple threads via +napi_call_threadsafe_function().

      +

      napi_threadsafe_function_release_mode#

      + +

      A value to be given to napi_release_threadsafe_function() to indicate whether +the thread-safe function is to be closed immediately (napi_tsfn_abort) or +merely released (napi_tsfn_release) and thus available for subsequent use via +napi_acquire_threadsafe_function() and napi_call_threadsafe_function().

      +
      typedef enum {
      +  napi_tsfn_release,
      +  napi_tsfn_abort
      +} napi_threadsafe_function_release_mode;
      +

      napi_threadsafe_function_call_mode#

      + +

      A value to be given to napi_call_threadsafe_function() to indicate whether +the call should block whenever the queue associated with the thread-safe +function is full.

      +
      typedef enum {
      +  napi_tsfn_nonblocking,
      +  napi_tsfn_blocking
      +} napi_threadsafe_function_call_mode;
      +

      N-API memory management types#

      +

      napi_handle_scope#

      +

      This is an abstraction used to control and modify the lifetime of objects +created within a particular scope. In general, N-API values are created within +the context of a handle scope. When a native method is called from +JavaScript, a default handle scope will exist. If the user does not explicitly +create a new handle scope, N-API values will be created in the default handle +scope. For any invocations of code outside the execution of a native method +(for instance, during a libuv callback invocation), the module is required to +create a scope before invoking any functions that can result in the creation +of JavaScript values.

      +

      Handle scopes are created using napi_open_handle_scope and are destroyed +using napi_close_handle_scope. Closing the scope can indicate to the GC +that all napi_values created during the lifetime of the handle scope are no +longer referenced from the current stack frame.

      +

      For more details, review the Object lifetime management.

      +

      napi_escapable_handle_scope#

      + +

      Escapable handle scopes are a special type of handle scope to return values +created within a particular handle scope to a parent scope.

      +

      napi_ref#

      + +

      This is the abstraction to use to reference a napi_value. This allows for +users to manage the lifetimes of JavaScript values, including defining their +minimum lifetimes explicitly.

      +

      For more details, review the Object lifetime management.

      +

      napi_type_tag#

      + +

      A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID +with which JavaScript objects can be "tagged" in order to ensure that they are +of a certain type. This is a stronger check than napi_instanceof, because +the latter can report a false positive if the object's prototype has been +manipulated. Type-tagging is most useful in conjunction with napi_wrap +because it ensures that the pointer retrieved from a wrapped object can be +safely cast to the native type corresponding to the type tag that had been +previously applied to the JavaScript object.

      +
      typedef struct {
      +  uint64_t lower;
      +  uint64_t upper;
      +} napi_type_tag;
      +

      napi_async_cleanup_hook_handle#

      + +

      An opaque value returned by napi_add_async_cleanup_hook. It must be passed +to napi_remove_async_cleanup_hook when the chain of asynchronous cleanup +events completes.

      +

      N-API callback types#

      +

      napi_callback_info#

      + +

      Opaque datatype that is passed to a callback function. It can be used for +getting additional information about the context in which the callback was +invoked.

      +

      napi_callback#

      + +

      Function pointer type for user-provided native functions which are to be +exposed to JavaScript via N-API. Callback functions should satisfy the +following signature:

      +
      typedef napi_value (*napi_callback)(napi_env, napi_callback_info);
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside a napi_callback is not necessary.

      +

      napi_finalize#

      + +

      Function pointer type for add-on provided functions that allow the user to be +notified when externally-owned data is ready to be cleaned up because the +object with which it was associated with, has been garbage-collected. The user +must provide a function satisfying the following signature which would get +called upon the object's collection. Currently, napi_finalize can be used for +finding out when objects that have external data are collected.

      +
      typedef void (*napi_finalize)(napi_env env,
      +                              void* finalize_data,
      +                              void* finalize_hint);
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside the function body is not necessary.

      +

      napi_async_execute_callback#

      + +

      Function pointer used with functions that support asynchronous +operations. Callback functions must satisfy the following signature:

      +
      typedef void (*napi_async_execute_callback)(napi_env env, void* data);
      +

      Implementations of this function must avoid making N-API calls that execute +JavaScript or interact with JavaScript objects. N-API calls should be in the +napi_async_complete_callback instead. Do not use the napi_env parameter as +it will likely result in execution of JavaScript.

      +

      napi_async_complete_callback#

      + +

      Function pointer used with functions that support asynchronous +operations. Callback functions must satisfy the following signature:

      +
      typedef void (*napi_async_complete_callback)(napi_env env,
      +                                             napi_status status,
      +                                             void* data);
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside the function body is not necessary.

      +

      napi_threadsafe_function_call_js#

      + +

      Function pointer used with asynchronous thread-safe function calls. The callback +will be called on the main thread. Its purpose is to use a data item arriving +via the queue from one of the secondary threads to construct the parameters +necessary for a call into JavaScript, usually via napi_call_function, and then +make the call into JavaScript.

      +

      The data arriving from the secondary thread via the queue is given in the data +parameter and the JavaScript function to call is given in the js_callback +parameter.

      +

      N-API sets up the environment prior to calling this callback, so it is +sufficient to call the JavaScript function via napi_call_function rather than +via napi_make_callback.

      +

      Callback functions must satisfy the following signature:

      +
      typedef void (*napi_threadsafe_function_call_js)(napi_env env,
      +                                                 napi_value js_callback,
      +                                                 void* context,
      +                                                 void* data);
      +
        +
      • [in] env: The environment to use for API calls, or NULL if the thread-safe +function is being torn down and data may need to be freed.
      • +
      • [in] js_callback: The JavaScript function to call, or NULL if the +thread-safe function is being torn down and data may need to be freed. It +may also be NULL if the thread-safe function was created without +js_callback.
      • +
      • [in] context: The optional data with which the thread-safe function was +created.
      • +
      • [in] data: Data created by the secondary thread. It is the responsibility of +the callback to convert this native data to JavaScript values (with N-API +functions) that can be passed as parameters when js_callback is invoked. +This pointer is managed entirely by the threads and this callback. Thus this +callback should free the data.
      • +
      +

      Unless for reasons discussed in Object Lifetime Management, creating a +handle and/or callback scope inside the function body is not necessary.

      +

      napi_async_cleanup_hook#

      + +

      Function pointer used with napi_add_async_cleanup_hook. It will be called +when the environment is being torn down.

      +

      Callback functions must satisfy the following signature:

      +
      typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,
      +                                        void* data);
      + +

      The body of the function should initiate the asynchronous cleanup actions at the +end of which handle must be passed in a call to +napi_remove_async_cleanup_hook.

      +

      Error handling#

      +

      N-API uses both return values and JavaScript exceptions for error handling. +The following sections explain the approach for each case.

      +

      Return values#

      +

      All of the N-API functions share the same error handling pattern. The +return type of all API functions is napi_status.

      +

      The return value will be napi_ok if the request was successful and +no uncaught JavaScript exception was thrown. If an error occurred AND +an exception was thrown, the napi_status value for the error +will be returned. If an exception was thrown, and no error occurred, +napi_pending_exception will be returned.

      +

      In cases where a return value other than napi_ok or +napi_pending_exception is returned, napi_is_exception_pending +must be called to check if an exception is pending. +See the section on exceptions for more details.

      +

      The full set of possible napi_status values is defined +in napi_api_types.h.

      +

      The napi_status return value provides a VM-independent representation of +the error which occurred. In some cases it is useful to be able to get +more detailed information, including a string representing the error as well as +VM (engine)-specific information.

      +

      In order to retrieve this information napi_get_last_error_info +is provided which returns a napi_extended_error_info structure. +The format of the napi_extended_error_info structure is as follows:

      + +
      typedef struct napi_extended_error_info {
      +  const char* error_message;
      +  void* engine_reserved;
      +  uint32_t engine_error_code;
      +  napi_status error_code;
      +};
      +
        +
      • error_message: Textual representation of the error that occurred.
      • +
      • engine_reserved: Opaque handle reserved for engine use only.
      • +
      • engine_error_code: VM specific error code.
      • +
      • error_code: n-api status code for the last error.
      • +
      +

      napi_get_last_error_info returns the information for the last +N-API call that was made.

      +

      Do not rely on the content or format of any of the extended information as it +is not subject to SemVer and may change at any time. It is intended only for +logging purposes.

      +

      napi_get_last_error_info#

      + +
      napi_status
      +napi_get_last_error_info(napi_env env,
      +                         const napi_extended_error_info** result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: The napi_extended_error_info structure with more +information about the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API retrieves a napi_extended_error_info structure with information +about the last error that occurred.

      +

      The content of the napi_extended_error_info returned is only valid up until +an n-api function is called on the same env.

      +

      Do not rely on the content or format of any of the extended information as it +is not subject to SemVer and may change at any time. It is intended only for +logging purposes.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Exceptions#

      +

      Any N-API function call may result in a pending JavaScript exception. This is +the case for any of the API functions, even those that may not cause the +execution of JavaScript.

      +

      If the napi_status returned by a function is napi_ok then no +exception is pending and no additional action is required. If the +napi_status returned is anything other than napi_ok or +napi_pending_exception, in order to try to recover and continue +instead of simply returning immediately, napi_is_exception_pending +must be called in order to determine if an exception is pending or not.

      +

      In many cases when an N-API function is called and an exception is +already pending, the function will return immediately with a +napi_status of napi_pending_exception. However, this is not the case +for all functions. N-API allows a subset of the functions to be +called to allow for some minimal cleanup before returning to JavaScript. +In that case, napi_status will reflect the status for the function. It +will not reflect previous pending exceptions. To avoid confusion, check +the error status after every function call.

      +

      When an exception is pending one of two approaches can be employed.

      +

      The first approach is to do any appropriate cleanup and then return so that +execution will return to JavaScript. As part of the transition back to +JavaScript, the exception will be thrown at the point in the JavaScript +code where the native method was invoked. The behavior of most N-API calls +is unspecified while an exception is pending, and many will simply return +napi_pending_exception, so do as little as possible and then return to +JavaScript where the exception can be handled.

      +

      The second approach is to try to handle the exception. There will be cases +where the native code can catch the exception, take the appropriate action, +and then continue. This is only recommended in specific cases +where it is known that the exception can be safely handled. In these +cases napi_get_and_clear_last_exception can be used to get and +clear the exception. On success, result will contain the handle to +the last JavaScript Object thrown. If it is determined, after +retrieving the exception, the exception cannot be handled after all +it can be re-thrown it with napi_throw where error is the +JavaScript Error object to be thrown.

      +

      The following utility functions are also available in case native code +needs to throw an exception or determine if a napi_value is an instance +of a JavaScript Error object: napi_throw_error, +napi_throw_type_error, napi_throw_range_error and +napi_is_error.

      +

      The following utility functions are also available in case native +code needs to create an Error object: napi_create_error, +napi_create_type_error, and napi_create_range_error, +where result is the napi_value that refers to the newly created +JavaScript Error object.

      +

      The Node.js project is adding error codes to all of the errors +generated internally. The goal is for applications to use these +error codes for all error checking. The associated error messages +will remain, but will only be meant to be used for logging and +display with the expectation that the message can change without +SemVer applying. In order to support this model with N-API, both +in internal functionality and for module specific functionality +(as its good practice), the throw_ and create_ functions +take an optional code parameter which is the string for the code +to be added to the error object. If the optional parameter is NULL +then no code will be associated with the error. If a code is provided, +the name associated with the error is also updated to be:

      +
      originalName [code]
      +

      where originalName is the original name associated with the error +and code is the code that was provided. For example, if the code +is 'ERR_ERROR_1' and a TypeError is being created the name will be:

      +
      TypeError [ERR_ERROR_1]
      +

      napi_throw#

      + +
      NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] error: The JavaScript value to be thrown.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws the JavaScript value provided.

      +

      napi_throw_error#

      + +
      NAPI_EXTERN napi_status napi_throw_error(napi_env env,
      +                                         const char* code,
      +                                         const char* msg);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional error code to be set on the error.
      • +
      • [in] msg: C string representing the text to be associated with the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws a JavaScript Error with the text provided.

      +

      napi_throw_type_error#

      + +
      NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,
      +                                              const char* code,
      +                                              const char* msg);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional error code to be set on the error.
      • +
      • [in] msg: C string representing the text to be associated with the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws a JavaScript TypeError with the text provided.

      +

      napi_throw_range_error#

      + +
      NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,
      +                                               const char* code,
      +                                               const char* msg);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional error code to be set on the error.
      • +
      • [in] msg: C string representing the text to be associated with the error.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API throws a JavaScript RangeError with the text provided.

      +

      napi_is_error#

      + +
      NAPI_EXTERN napi_status napi_is_error(napi_env env,
      +                                      napi_value value,
      +                                      bool* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The napi_value to be checked.
      • +
      • [out] result: Boolean value that is set to true if napi_value represents +an error, false otherwise.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API queries a napi_value to check if it represents an error object.

      +

      napi_create_error#

      + +
      NAPI_EXTERN napi_status napi_create_error(napi_env env,
      +                                          napi_value code,
      +                                          napi_value msg,
      +                                          napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional napi_value with the string for the error code to be +associated with the error.
      • +
      • [in] msg: napi_value that references a JavaScript String to be used as +the message for the Error.
      • +
      • [out] result: napi_value representing the error created.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns a JavaScript Error with the text provided.

      +

      napi_create_type_error#

      + +
      NAPI_EXTERN napi_status napi_create_type_error(napi_env env,
      +                                               napi_value code,
      +                                               napi_value msg,
      +                                               napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional napi_value with the string for the error code to be +associated with the error.
      • +
      • [in] msg: napi_value that references a JavaScript String to be used as +the message for the Error.
      • +
      • [out] result: napi_value representing the error created.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns a JavaScript TypeError with the text provided.

      +

      napi_create_range_error#

      + +
      NAPI_EXTERN napi_status napi_create_range_error(napi_env env,
      +                                                napi_value code,
      +                                                napi_value msg,
      +                                                napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] code: Optional napi_value with the string for the error code to be +associated with the error.
      • +
      • [in] msg: napi_value that references a JavaScript String to be used as +the message for the Error.
      • +
      • [out] result: napi_value representing the error created.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns a JavaScript RangeError with the text provided.

      +

      napi_get_and_clear_last_exception#

      + +
      napi_status napi_get_and_clear_last_exception(napi_env env,
      +                                              napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: The exception if one is pending, NULL otherwise.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_is_exception_pending#

      + +
      napi_status napi_is_exception_pending(napi_env env, bool* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: Boolean value that is set to true if an exception is pending.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_fatal_exception#

      + +
      napi_status napi_fatal_exception(napi_env env, napi_value err);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] err: The error that is passed to 'uncaughtException'.
      • +
      +

      Trigger an 'uncaughtException' in JavaScript. Useful if an async +callback throws an exception with no way to recover.

      +

      Fatal errors#

      +

      In the event of an unrecoverable error in a native module, a fatal error can be +thrown to immediately terminate the process.

      +

      napi_fatal_error#

      + +
      NAPI_NO_RETURN void napi_fatal_error(const char* location,
      +                                                 size_t location_len,
      +                                                 const char* message,
      +                                                 size_t message_len);
      +
        +
      • [in] location: Optional location at which the error occurred.
      • +
      • [in] location_len: The length of the location in bytes, or +NAPI_AUTO_LENGTH if it is null-terminated.
      • +
      • [in] message: The message associated with the error.
      • +
      • [in] message_len: The length of the message in bytes, or NAPI_AUTO_LENGTH +if it is null-terminated.
      • +
      +

      The function call does not return, the process will be terminated.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Object lifetime management#

      +

      As N-API calls are made, handles to objects in the heap for the underlying +VM may be returned as napi_values. These handles must hold the +objects 'live' until they are no longer required by the native code, +otherwise the objects could be collected before the native code was +finished using them.

      +

      As object handles are returned they are associated with a +'scope'. The lifespan for the default scope is tied to the lifespan +of the native method call. The result is that, by default, handles +remain valid and the objects associated with these handles will be +held live for the lifespan of the native method call.

      +

      In many cases, however, it is necessary that the handles remain valid for +either a shorter or longer lifespan than that of the native method. +The sections which follow describe the N-API functions that can be used +to change the handle lifespan from the default.

      +

      Making handle lifespan shorter than that of the native method#

      +

      It is often necessary to make the lifespan of handles shorter than +the lifespan of a native method. For example, consider a native method +that has a loop which iterates through the elements in a large array:

      +
      for (int i = 0; i < 1000000; i++) {
      +  napi_value result;
      +  napi_status status = napi_get_element(env, object, i, &result);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +  // do something with element
      +}
      +

      This would result in a large number of handles being created, consuming +substantial resources. In addition, even though the native code could only +use the most recent handle, all of the associated objects would also be +kept alive since they all share the same scope.

      +

      To handle this case, N-API provides the ability to establish a new 'scope' to +which newly created handles will be associated. Once those handles +are no longer required, the scope can be 'closed' and any handles associated +with the scope are invalidated. The methods available to open/close scopes are +napi_open_handle_scope and napi_close_handle_scope.

      +

      N-API only supports a single nested hierarchy of scopes. There is only one +active scope at any time, and all new handles will be associated with that +scope while it is active. Scopes must be closed in the reverse order from +which they are opened. In addition, all scopes created within a native method +must be closed before returning from that method.

      +

      Taking the earlier example, adding calls to napi_open_handle_scope and +napi_close_handle_scope would ensure that at most a single handle +is valid throughout the execution of the loop:

      +
      for (int i = 0; i < 1000000; i++) {
      +  napi_handle_scope scope;
      +  napi_status status = napi_open_handle_scope(env, &scope);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +  napi_value result;
      +  status = napi_get_element(env, object, i, &result);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +  // do something with element
      +  status = napi_close_handle_scope(env, scope);
      +  if (status != napi_ok) {
      +    break;
      +  }
      +}
      +

      When nesting scopes, there are cases where a handle from an +inner scope needs to live beyond the lifespan of that scope. N-API supports an +'escapable scope' in order to support this case. An escapable scope +allows one handle to be 'promoted' so that it 'escapes' the +current scope and the lifespan of the handle changes from the current +scope to that of the outer scope.

      +

      The methods available to open/close escapable scopes are +napi_open_escapable_handle_scope and +napi_close_escapable_handle_scope.

      +

      The request to promote a handle is made through napi_escape_handle which +can only be called once.

      +

      napi_open_handle_scope#

      + +
      NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,
      +                                               napi_handle_scope* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing the new scope.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API opens a new scope.

      +

      napi_close_handle_scope#

      + +
      NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,
      +                                                napi_handle_scope scope);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: napi_value representing the scope to be closed.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API closes the scope passed in. Scopes must be closed in the +reverse order from which they were created.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_open_escapable_handle_scope#

      + +
      NAPI_EXTERN napi_status
      +    napi_open_escapable_handle_scope(napi_env env,
      +                                     napi_handle_scope* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing the new scope.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API opens a new scope from which one object can be promoted +to the outer scope.

      +

      napi_close_escapable_handle_scope#

      + +
      NAPI_EXTERN napi_status
      +    napi_close_escapable_handle_scope(napi_env env,
      +                                      napi_handle_scope scope);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: napi_value representing the scope to be closed.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API closes the scope passed in. Scopes must be closed in the +reverse order from which they were created.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_escape_handle#

      + +
      napi_status napi_escape_handle(napi_env env,
      +                               napi_escapable_handle_scope scope,
      +                               napi_value escapee,
      +                               napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: napi_value representing the current scope.
      • +
      • [in] escapee: napi_value representing the JavaScript Object to be +escaped.
      • +
      • [out] result: napi_value representing the handle to the escaped Object +in the outer scope.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API promotes the handle to the JavaScript object so that it is valid +for the lifetime of the outer scope. It can only be called once per scope. +If it is called more than once an error will be returned.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      References to objects with a lifespan longer than that of the native method#

      +

      In some cases an addon will need to be able to create and reference objects +with a lifespan longer than that of a single native method invocation. For +example, to create a constructor and later use that constructor +in a request to creates instances, it must be possible to reference +the constructor object across many different instance creation requests. This +would not be possible with a normal handle returned as a napi_value as +described in the earlier section. The lifespan of a normal handle is +managed by scopes and all scopes must be closed before the end of a native +method.

      +

      N-API provides methods to create persistent references to an object. +Each persistent reference has an associated count with a value of 0 +or higher. The count determines if the reference will keep +the corresponding object live. References with a count of 0 do not +prevent the object from being collected and are often called 'weak' +references. Any count greater than 0 will prevent the object +from being collected.

      +

      References can be created with an initial reference count. The count can +then be modified through napi_reference_ref and +napi_reference_unref. If an object is collected while the count +for a reference is 0, all subsequent calls to +get the object associated with the reference napi_get_reference_value +will return NULL for the returned napi_value. An attempt to call +napi_reference_ref for a reference whose object has been collected +will result in an error.

      +

      References must be deleted once they are no longer required by the addon. When +a reference is deleted it will no longer prevent the corresponding object from +being collected. Failure to delete a persistent reference will result in +a 'memory leak' with both the native memory for the persistent reference and +the corresponding object on the heap being retained forever.

      +

      There can be multiple persistent references created which refer to the same +object, each of which will either keep the object live or not based on its +individual count.

      +

      napi_create_reference#

      + +
      NAPI_EXTERN napi_status napi_create_reference(napi_env env,
      +                                              napi_value value,
      +                                              uint32_t initial_refcount,
      +                                              napi_ref* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing the Object to which we want a +reference.
      • +
      • [in] initial_refcount: Initial reference count for the new reference.
      • +
      • [out] result: napi_ref pointing to the new reference.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API create a new reference with the specified reference count +to the Object passed in.

      +

      napi_delete_reference#

      + +
      NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref to be deleted.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API deletes the reference passed in.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_reference_ref#

      + +
      NAPI_EXTERN napi_status napi_reference_ref(napi_env env,
      +                                           napi_ref ref,
      +                                           uint32_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref for which the reference count will be incremented.
      • +
      • [out] result: The new reference count.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API increments the reference count for the reference +passed in and returns the resulting reference count.

      +

      napi_reference_unref#

      + +
      NAPI_EXTERN napi_status napi_reference_unref(napi_env env,
      +                                             napi_ref ref,
      +                                             uint32_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref for which the reference count will be decremented.
      • +
      • [out] result: The new reference count.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API decrements the reference count for the reference +passed in and returns the resulting reference count.

      +

      napi_get_reference_value#

      + +
      NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,
      +                                                 napi_ref ref,
      +                                                 napi_value* result);
      +

      the napi_value passed in or out of these methods is a handle to the +object to which the reference is related.

      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] ref: napi_ref for which we requesting the corresponding Object.
      • +
      • [out] result: The napi_value for the Object referenced by the +napi_ref.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      If still valid, this API returns the napi_value representing the +JavaScript Object associated with the napi_ref. Otherwise, result +will be NULL.

      +

      Cleanup on exit of the current Node.js instance#

      +

      While a Node.js process typically releases all its resources when exiting, +embedders of Node.js, or future Worker support, may require addons to register +clean-up hooks that will be run once the current Node.js instance exits.

      +

      N-API provides functions for registering and un-registering such callbacks. +When those callbacks are run, all resources that are being held by the addon +should be freed up.

      +

      napi_add_env_cleanup_hook#

      + +
      NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,
      +                                                  void (*fun)(void* arg),
      +                                                  void* arg);
      +

      Registers fun as a function to be run with the arg parameter once the +current Node.js environment exits.

      +

      A function can safely be specified multiple times with different +arg values. In that case, it will be called multiple times as well. +Providing the same fun and arg values multiple times is not allowed +and will lead the process to abort.

      +

      The hooks will be called in reverse order, i.e. the most recently added one +will be called first.

      +

      Removing this hook can be done by using napi_remove_env_cleanup_hook. +Typically, that happens when the resource for which this hook was added +is being torn down anyway.

      +

      For asynchronous cleanup, napi_add_async_cleanup_hook is available.

      +

      napi_remove_env_cleanup_hook#

      + +
      NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,
      +                                                     void (*fun)(void* arg),
      +                                                     void* arg);
      +

      Unregisters fun as a function to be run with the arg parameter once the +current Node.js environment exits. Both the argument and the function value +need to be exact matches.

      +

      The function must have originally been registered +with napi_add_env_cleanup_hook, otherwise the process will abort.

      +

      napi_add_async_cleanup_hook#

      + +
      NAPI_EXTERN napi_status napi_add_async_cleanup_hook(
      +    napi_env env,
      +    napi_async_cleanup_hook hook,
      +    void* arg,
      +    napi_async_cleanup_hook_handle* remove_handle);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] hook: The function pointer to call at environment teardown.
      • +
      • [in] arg: The pointer to pass to hook when it gets called.
      • +
      • [out] remove_handle: Optional handle that refers to the asynchronous cleanup +hook.
      • +
      +

      Registers hook, which is a function of type napi_async_cleanup_hook, as +a function to be run with the remove_handle and arg parameters once the +current Node.js environment exits.

      +

      Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.

      +

      Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.

      +

      If remove_handle is not NULL, an opaque value will be stored in it +that must later be passed to napi_remove_async_cleanup_hook, +regardless of whether the hook has already been invoked. +Typically, that happens when the resource for which this hook was added +is being torn down anyway.

      +

      napi_remove_async_cleanup_hook#

      + +
      NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(
      +    napi_async_cleanup_hook_handle remove_handle);
      + +

      Unregisters the cleanup hook corresponding to remove_handle. This will prevent +the hook from being executed, unless it has already started executing. +This must be called on any napi_async_cleanup_hook_handle value obtained +from napi_add_async_cleanup_hook.

      +

      Module registration#

      +

      N-API modules are registered in a manner similar to other modules +except that instead of using the NODE_MODULE macro the following +is used:

      +
      NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
      +

      The next difference is the signature for the Init method. For a N-API +module it is as follows:

      +
      napi_value Init(napi_env env, napi_value exports);
      +

      The return value from Init is treated as the exports object for the module. +The Init method is passed an empty object via the exports parameter as a +convenience. If Init returns NULL, the parameter passed as exports is +exported by the module. N-API modules cannot modify the module object but can +specify anything as the exports property of the module.

      +

      To add the method hello as a function so that it can be called as a method +provided by the addon:

      +
      napi_value Init(napi_env env, napi_value exports) {
      +  napi_status status;
      +  napi_property_descriptor desc = {
      +    "hello",
      +    NULL,
      +    Method,
      +    NULL,
      +    NULL,
      +    NULL,
      +    napi_writable | napi_enumerable | napi_configurable,
      +    NULL
      +  };
      +  status = napi_define_properties(env, exports, 1, &desc);
      +  if (status != napi_ok) return NULL;
      +  return exports;
      +}
      +

      To set a function to be returned by the require() for the addon:

      +
      napi_value Init(napi_env env, napi_value exports) {
      +  napi_value method;
      +  napi_status status;
      +  status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method);
      +  if (status != napi_ok) return NULL;
      +  return method;
      +}
      +

      To define a class so that new instances can be created (often used with +Object wrap):

      +
      // NOTE: partial example, not all referenced code is included
      +napi_value Init(napi_env env, napi_value exports) {
      +  napi_status status;
      +  napi_property_descriptor properties[] = {
      +    { "value", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL },
      +    DECLARE_NAPI_METHOD("plusOne", PlusOne),
      +    DECLARE_NAPI_METHOD("multiply", Multiply),
      +  };
      +
      +  napi_value cons;
      +  status =
      +      napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_create_reference(env, cons, 1, &constructor);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_set_named_property(env, exports, "MyObject", cons);
      +  if (status != napi_ok) return NULL;
      +
      +  return exports;
      +}
      +

      If the module will be loaded multiple times during the lifetime of the Node.js +process, use the NAPI_MODULE_INIT macro to initialize the module:

      +
      NAPI_MODULE_INIT() {
      +  napi_value answer;
      +  napi_status result;
      +
      +  status = napi_create_int64(env, 42, &answer);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_set_named_property(env, exports, "answer", answer);
      +  if (status != napi_ok) return NULL;
      +
      +  return exports;
      +}
      +

      This macro includes NAPI_MODULE, and declares an Init function with a +special name and with visibility beyond the addon. This will allow Node.js to +initialize the module even if it is loaded multiple times.

      +

      There are a few design considerations when declaring a module that may be loaded +multiple times. The documentation of context-aware addons provides more +details.

      +

      The variables env and exports will be available inside the function body +following the macro invocation.

      +

      For more details on setting properties on objects, see the section on +Working with JavaScript properties.

      +

      For more details on building addon modules in general, refer to the existing +API.

      +

      Working with JavaScript values#

      +

      N-API exposes a set of APIs to create all types of JavaScript values. +Some of these types are documented under Section 6 +of the ECMAScript Language Specification.

      +

      Fundamentally, these APIs are used to do one of the following:

      +
        +
      1. Create a new JavaScript object
      2. +
      3. Convert from a primitive C type to an N-API value
      4. +
      5. Convert from N-API value to a primitive C type
      6. +
      7. Get global instances including undefined and null
      8. +
      +

      N-API values are represented by the type napi_value. +Any N-API call that requires a JavaScript value takes in a napi_value. +In some cases, the API does check the type of the napi_value up-front. +However, for better performance, it's better for the caller to make sure that +the napi_value in question is of the JavaScript type expected by the API.

      +

      Enum types#

      +

      napi_key_collection_mode#

      + +
      typedef enum {
      +  napi_key_include_prototypes,
      +  napi_key_own_only
      +} napi_key_collection_mode;
      +

      Describes the Keys/Properties filter enums:

      +

      napi_key_collection_mode limits the range of collected properties.

      +

      napi_key_own_only limits the collected properties to the given +object only. napi_key_include_prototypes will include all keys +of the objects's prototype chain as well.

      +

      napi_key_filter#

      + +
      typedef enum {
      +  napi_key_all_properties = 0,
      +  napi_key_writable = 1,
      +  napi_key_enumerable = 1 << 1,
      +  napi_key_configurable = 1 << 2,
      +  napi_key_skip_strings = 1 << 3,
      +  napi_key_skip_symbols = 1 << 4
      +} napi_key_filter;
      +

      Property filter bits. They can be or'ed to build a composite filter.

      +

      napi_key_conversion#

      + +
      typedef enum {
      +  napi_key_keep_numbers,
      +  napi_key_numbers_to_strings
      +} napi_key_conversion;
      +

      napi_key_numbers_to_strings will convert integer indices to +strings. napi_key_keep_numbers will return numbers for integer +indices.

      +

      napi_valuetype#

      +
      typedef enum {
      +  // ES6 types (corresponds to typeof)
      +  napi_undefined,
      +  napi_null,
      +  napi_boolean,
      +  napi_number,
      +  napi_string,
      +  napi_symbol,
      +  napi_object,
      +  napi_function,
      +  napi_external,
      +  napi_bigint,
      +} napi_valuetype;
      +

      Describes the type of a napi_value. This generally corresponds to the types +described in Section 6.1 of the ECMAScript Language Specification. +In addition to types in that section, napi_valuetype can also represent +Functions and Objects with external data.

      +

      A JavaScript value of type napi_external appears in JavaScript as a plain +object such that no properties can be set on it, and no prototype.

      +

      napi_typedarray_type#

      +
      typedef enum {
      +  napi_int8_array,
      +  napi_uint8_array,
      +  napi_uint8_clamped_array,
      +  napi_int16_array,
      +  napi_uint16_array,
      +  napi_int32_array,
      +  napi_uint32_array,
      +  napi_float32_array,
      +  napi_float64_array,
      +  napi_bigint64_array,
      +  napi_biguint64_array,
      +} napi_typedarray_type;
      +

      This represents the underlying binary scalar datatype of the TypedArray. +Elements of this enum correspond to +Section 22.2 of the ECMAScript Language Specification.

      +

      Object creation functions#

      +

      napi_create_array#

      + +
      napi_status napi_create_array(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [out] result: A napi_value representing a JavaScript Array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript Array type. +JavaScript arrays are described in +Section 22.1 of the ECMAScript Language Specification.

      +

      napi_create_array_with_length#

      + +
      napi_status napi_create_array_with_length(napi_env env,
      +                                          size_t length,
      +                                          napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: The initial length of the Array.
      • +
      • [out] result: A napi_value representing a JavaScript Array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript Array type. +The Array's length property is set to the passed-in length parameter. +However, the underlying buffer is not guaranteed to be pre-allocated by the VM +when the array is created. That behavior is left to the underlying VM +implementation. If the buffer must be a contiguous block of memory that can be +directly read and/or written via C, consider using +napi_create_external_arraybuffer.

      +

      JavaScript arrays are described in +Section 22.1 of the ECMAScript Language Specification.

      +

      napi_create_arraybuffer#

      + +
      napi_status napi_create_arraybuffer(napi_env env,
      +                                    size_t byte_length,
      +                                    void** data,
      +                                    napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: The length in bytes of the array buffer to create.
      • +
      • [out] data: Pointer to the underlying byte buffer of the ArrayBuffer.
      • +
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer. +ArrayBuffers are used to represent fixed-length binary data buffers. They are +normally used as a backing-buffer for TypedArray objects. +The ArrayBuffer allocated will have an underlying byte buffer whose size is +determined by the length parameter that's passed in. +The underlying buffer is optionally returned back to the caller in case the +caller wants to directly manipulate the buffer. This buffer can only be +written to directly from native code. To write to this buffer from JavaScript, +a typed array or DataView object would need to be created.

      +

      JavaScript ArrayBuffer objects are described in +Section 24.1 of the ECMAScript Language Specification.

      +

      napi_create_buffer#

      + +
      napi_status napi_create_buffer(napi_env env,
      +                               size_t size,
      +                               void** data,
      +                               napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] size: Size in bytes of the underlying buffer.
      • +
      • [out] data: Raw pointer to the underlying buffer.
      • +
      • [out] result: A napi_value representing a node::Buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a node::Buffer object. While this is still a +fully-supported data structure, in most cases using a TypedArray will suffice.

      +

      napi_create_buffer_copy#

      + +
      napi_status napi_create_buffer_copy(napi_env env,
      +                                    size_t length,
      +                                    const void* data,
      +                                    void** result_data,
      +                                    napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] size: Size in bytes of the input buffer (should be the same as the size +of the new buffer).
      • +
      • [in] data: Raw pointer to the underlying buffer to copy from.
      • +
      • [out] result_data: Pointer to the new Buffer's underlying data buffer.
      • +
      • [out] result: A napi_value representing a node::Buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a node::Buffer object and initializes it with data copied +from the passed-in buffer. While this is still a fully-supported data +structure, in most cases using a TypedArray will suffice.

      +

      napi_create_date#

      + +
      napi_status napi_create_date(napi_env env,
      +                             double time,
      +                             napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] time: ECMAScript time value in milliseconds since 01 January, 1970 UTC.
      • +
      • [out] result: A napi_value representing a JavaScript Date.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API does not observe leap seconds; they are ignored, as +ECMAScript aligns with POSIX time specification.

      +

      This API allocates a JavaScript Date object.

      +

      JavaScript Date objects are described in +Section 20.3 of the ECMAScript Language Specification.

      +

      napi_create_external#

      + +
      napi_status napi_create_external(napi_env env,
      +                                 void* data,
      +                                 napi_finalize finalize_cb,
      +                                 void* finalize_hint,
      +                                 napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] data: Raw pointer to the external data.
      • +
      • [in] finalize_cb: Optional callback to call when the external value is being +collected. napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      • [out] result: A napi_value representing an external value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a JavaScript value with external data attached to it. This +is used to pass external data through JavaScript code, so it can be retrieved +later by native code using napi_get_value_external.

      +

      The API adds a napi_finalize callback which will be called when the JavaScript +object just created is ready for garbage collection. It is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the object created by the API can be used with napi_wrap().
      • +
      +

      The created value is not an object, and therefore does not support additional +properties. It is considered a distinct value type: calling napi_typeof() with +an external value yields napi_external.

      +

      napi_create_external_arraybuffer#

      + +
      napi_status
      +napi_create_external_arraybuffer(napi_env env,
      +                                 void* external_data,
      +                                 size_t byte_length,
      +                                 napi_finalize finalize_cb,
      +                                 void* finalize_hint,
      +                                 napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] external_data: Pointer to the underlying byte buffer of the +ArrayBuffer.
      • +
      • [in] byte_length: The length in bytes of the underlying buffer.
      • +
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being +collected. napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer. +The underlying byte buffer of the ArrayBuffer is externally allocated and +managed. The caller must ensure that the byte buffer remains valid until the +finalize callback is called.

      +

      The API adds a napi_finalize callback which will be called when the JavaScript +object just created is ready for garbage collection. It is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the object created by the API can be used with napi_wrap().
      • +
      +

      JavaScript ArrayBuffers are described in +Section 24.1 of the ECMAScript Language Specification.

      +

      napi_create_external_buffer#

      + +
      napi_status napi_create_external_buffer(napi_env env,
      +                                        size_t length,
      +                                        void* data,
      +                                        napi_finalize finalize_cb,
      +                                        void* finalize_hint,
      +                                        napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: Size in bytes of the input buffer (should be the same as the +size of the new buffer).
      • +
      • [in] data: Raw pointer to the underlying buffer to expose to JavaScript.
      • +
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being +collected. napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional hint to pass to the finalize callback during +collection.
      • +
      • [out] result: A napi_value representing a node::Buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a node::Buffer object and initializes it with data +backed by the passed in buffer. While this is still a fully-supported data +structure, in most cases using a TypedArray will suffice.

      +

      The API adds a napi_finalize callback which will be called when the JavaScript +object just created is ready for garbage collection. It is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the object created by the API can be used with napi_wrap().
      • +
      +

      For Node.js >=4 Buffers are Uint8Arrays.

      +

      napi_create_object#

      + +
      napi_status napi_create_object(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: A napi_value representing a JavaScript Object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a default JavaScript Object. +It is the equivalent of doing new Object() in JavaScript.

      +

      The JavaScript Object type is described in Section 6.1.7 of the +ECMAScript Language Specification.

      +

      napi_create_symbol#

      + +
      napi_status napi_create_symbol(napi_env env,
      +                               napi_value description,
      +                               napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] description: Optional napi_value which refers to a JavaScript +String to be set as the description for the symbol.
      • +
      • [out] result: A napi_value representing a JavaScript Symbol.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript Symbol object from a UTF8-encoded C string.

      +

      The JavaScript Symbol type is described in Section 19.4 +of the ECMAScript Language Specification.

      +

      napi_create_typedarray#

      + +
      napi_status napi_create_typedarray(napi_env env,
      +                                   napi_typedarray_type type,
      +                                   size_t length,
      +                                   napi_value arraybuffer,
      +                                   size_t byte_offset,
      +                                   napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] type: Scalar datatype of the elements within the TypedArray.
      • +
      • [in] length: Number of elements in the TypedArray.
      • +
      • [in] arraybuffer: ArrayBuffer underlying the typed array.
      • +
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to +start projecting the TypedArray.
      • +
      • [out] result: A napi_value representing a JavaScript TypedArray.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript TypedArray object over an existing +ArrayBuffer. TypedArray objects provide an array-like view over an +underlying data buffer where each element has the same underlying binary scalar +datatype.

      +

      It's required that (length * size_of_element) + byte_offset should +be <= the size in bytes of the array passed in. If not, a RangeError exception +is raised.

      +

      JavaScript TypedArray objects are described in +Section 22.2 of the ECMAScript Language Specification.

      +

      napi_create_dataview#

      + +
      napi_status napi_create_dataview(napi_env env,
      +                                 size_t byte_length,
      +                                 napi_value arraybuffer,
      +                                 size_t byte_offset,
      +                                 napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] length: Number of elements in the DataView.
      • +
      • [in] arraybuffer: ArrayBuffer underlying the DataView.
      • +
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to +start projecting the DataView.
      • +
      • [out] result: A napi_value representing a JavaScript DataView.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript DataView object over an existing ArrayBuffer. +DataView objects provide an array-like view over an underlying data buffer, +but one which allows items of different size and type in the ArrayBuffer.

      +

      It is required that byte_length + byte_offset is less than or equal to the +size in bytes of the array passed in. If not, a RangeError exception is +raised.

      +

      JavaScript DataView objects are described in +Section 24.3 of the ECMAScript Language Specification.

      +

      Functions to convert from C types to N-API#

      +

      napi_create_int32#

      + +
      napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C int32_t type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in +Section 6.1.6 of the ECMAScript Language Specification.

      +

      napi_create_uint32#

      + +
      napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C uint32_t type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in +Section 6.1.6 of the ECMAScript Language Specification.

      +

      napi_create_int64#

      + +
      napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C int64_t type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in Section 6.1.6 +of the ECMAScript Language Specification. Note the complete range of int64_t +cannot be represented with full precision in JavaScript. Integer values +outside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) - +Number.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.

      +

      napi_create_double#

      + +
      napi_status napi_create_double(napi_env env, double value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Double-precision value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to convert from the C double type to the JavaScript +Number type.

      +

      The JavaScript Number type is described in +Section 6.1.6 of the ECMAScript Language Specification.

      +

      napi_create_bigint_int64#

      + +
      napi_status napi_create_bigint_int64(napi_env env,
      +                                     int64_t value,
      +                                     napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript BigInt.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts the C int64_t type to the JavaScript BigInt type.

      +

      napi_create_bigint_uint64#

      + +
      napi_status napi_create_bigint_uint64(napi_env env,
      +                                      uint64_t value,
      +                                      napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • +
      • [out] result: A napi_value representing a JavaScript BigInt.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts the C uint64_t type to the JavaScript BigInt type.

      +

      napi_create_bigint_words#

      + +
      napi_status napi_create_bigint_words(napi_env env,
      +                                     int sign_bit,
      +                                     size_t word_count,
      +                                     const uint64_t* words,
      +                                     napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] sign_bit: Determines if the resulting BigInt will be positive or +negative.
      • +
      • [in] word_count: The length of the words array.
      • +
      • [in] words: An array of uint64_t little-endian 64-bit words.
      • +
      • [out] result: A napi_value representing a JavaScript BigInt.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts an array of unsigned 64-bit words into a single BigInt +value.

      +

      The resulting BigInt is calculated as: (–1)sign_bit (words[0] +× (264)0 + words[1] × (264)1 + …)

      +

      napi_create_string_latin1#

      + +
      napi_status napi_create_string_latin1(napi_env env,
      +                                      const char* str,
      +                                      size_t length,
      +                                      napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] str: Character buffer representing an ISO-8859-1-encoded string.
      • +
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it +is null-terminated.
      • +
      • [out] result: A napi_value representing a JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript String object from an ISO-8859-1-encoded C +string. The native string is copied.

      +

      The JavaScript String type is described in +Section 6.1.4 of the ECMAScript Language Specification.

      +

      napi_create_string_utf16#

      + +
      napi_status napi_create_string_utf16(napi_env env,
      +                                     const char16_t* str,
      +                                     size_t length,
      +                                     napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] str: Character buffer representing a UTF16-LE-encoded string.
      • +
      • [in] length: The length of the string in two-byte code units, or +NAPI_AUTO_LENGTH if it is null-terminated.
      • +
      • [out] result: A napi_value representing a JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript String object from a UTF16-LE-encoded C string. +The native string is copied.

      +

      The JavaScript String type is described in +Section 6.1.4 of the ECMAScript Language Specification.

      +

      napi_create_string_utf8#

      + +
      napi_status napi_create_string_utf8(napi_env env,
      +                                    const char* str,
      +                                    size_t length,
      +                                    napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] str: Character buffer representing a UTF8-encoded string.
      • +
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it +is null-terminated.
      • +
      • [out] result: A napi_value representing a JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a JavaScript String object from a UTF8-encoded C string. +The native string is copied.

      +

      The JavaScript String type is described in +Section 6.1.4 of the ECMAScript Language Specification.

      +

      Functions to convert from N-API to C types#

      +

      napi_get_array_length#

      + +
      napi_status napi_get_array_length(napi_env env,
      +                                  napi_value value,
      +                                  uint32_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing the JavaScript Array whose length is +being queried.
      • +
      • [out] result: uint32 representing length of the array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the length of an array.

      +

      Array length is described in Section 22.1.4.1 of the ECMAScript Language +Specification.

      +

      napi_get_arraybuffer_info#

      + +
      napi_status napi_get_arraybuffer_info(napi_env env,
      +                                      napi_value arraybuffer,
      +                                      void** data,
      +                                      size_t* byte_length)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] arraybuffer: napi_value representing the ArrayBuffer being queried.
      • +
      • [out] data: The underlying data buffer of the ArrayBuffer. If byte_length +is 0, this may be NULL or any other pointer value.
      • +
      • [out] byte_length: Length in bytes of the underlying data buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to retrieve the underlying data buffer of an ArrayBuffer and +its length.

      +

      WARNING: Use caution while using this API. The lifetime of the underlying data +buffer is managed by the ArrayBuffer even after it's returned. A +possible safe way to use this API is in conjunction with +napi_create_reference, which can be used to guarantee control over the +lifetime of the ArrayBuffer. It's also safe to use the returned data buffer +within the same callback as long as there are no calls to other APIs that might +trigger a GC.

      +

      napi_get_buffer_info#

      + +
      napi_status napi_get_buffer_info(napi_env env,
      +                                 napi_value value,
      +                                 void** data,
      +                                 size_t* length)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing the node::Buffer being queried.
      • +
      • [out] data: The underlying data buffer of the node::Buffer. +If length is 0, this may be NULL or any other pointer value.
      • +
      • [out] length: Length in bytes of the underlying data buffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to retrieve the underlying data buffer of a node::Buffer +and it's length.

      +

      Warning: Use caution while using this API since the underlying data buffer's +lifetime is not guaranteed if it's managed by the VM.

      +

      napi_get_prototype#

      + +
      napi_status napi_get_prototype(napi_env env,
      +                               napi_value object,
      +                               napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] object: napi_value representing JavaScript Object whose prototype +to return. This returns the equivalent of Object.getPrototypeOf (which is +not the same as the function's prototype property).
      • +
      • [out] result: napi_value representing prototype of the given object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      napi_get_typedarray_info#

      + +
      napi_status napi_get_typedarray_info(napi_env env,
      +                                     napi_value typedarray,
      +                                     napi_typedarray_type* type,
      +                                     size_t* length,
      +                                     void** data,
      +                                     napi_value* arraybuffer,
      +                                     size_t* byte_offset)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] typedarray: napi_value representing the TypedArray whose +properties to query.
      • +
      • [out] type: Scalar datatype of the elements within the TypedArray.
      • +
      • [out] length: The number of elements in the TypedArray.
      • +
      • [out] data: The data buffer underlying the TypedArray adjusted by +the byte_offset value so that it points to the first element in the +TypedArray. If the length of the array is 0, this may be NULL or +any other pointer value.
      • +
      • [out] arraybuffer: The ArrayBuffer underlying the TypedArray.
      • +
      • [out] byte_offset: The byte offset within the underlying native array +at which the first element of the arrays is located. The value for the data +parameter has already been adjusted so that data points to the first element +in the array. Therefore, the first byte of the native array would be at +data - byte_offset.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns various properties of a typed array.

      +

      Warning: Use caution while using this API since the underlying data buffer +is managed by the VM.

      +

      napi_get_dataview_info#

      + +
      napi_status napi_get_dataview_info(napi_env env,
      +                                   napi_value dataview,
      +                                   size_t* byte_length,
      +                                   void** data,
      +                                   napi_value* arraybuffer,
      +                                   size_t* byte_offset)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] dataview: napi_value representing the DataView whose +properties to query.
      • +
      • [out] byte_length: Number of bytes in the DataView.
      • +
      • [out] data: The data buffer underlying the DataView. +If byte_length is 0, this may be NULL or any other pointer value.
      • +
      • [out] arraybuffer: ArrayBuffer underlying the DataView.
      • +
      • [out] byte_offset: The byte offset within the data buffer from which +to start projecting the DataView.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns various properties of a DataView.

      +

      napi_get_date_value#

      + +
      napi_status napi_get_date_value(napi_env env,
      +                                napi_value value,
      +                                double* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing a JavaScript Date.
      • +
      • [out] result: Time value as a double represented as milliseconds since +midnight at the beginning of 01 January, 1970 UTC.
      • +
      +

      This API does not observe leap seconds; they are ignored, as +ECMAScript aligns with POSIX time specification.

      +

      Returns napi_ok if the API succeeded. If a non-date napi_value is passed +in it returns napi_date_expected.

      +

      This API returns the C double primitive of time value for the given JavaScript +Date.

      +

      napi_get_value_bool#

      + +
      napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Boolean.
      • +
      • [out] result: C boolean primitive equivalent of the given JavaScript +Boolean.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-boolean napi_value is +passed in it returns napi_boolean_expected.

      +

      This API returns the C boolean primitive equivalent of the given JavaScript +Boolean.

      +

      napi_get_value_double#

      + +
      napi_status napi_get_value_double(napi_env env,
      +                                  napi_value value,
      +                                  double* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C double primitive equivalent of the given JavaScript +Number.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value is passed +in it returns napi_number_expected.

      +

      This API returns the C double primitive equivalent of the given JavaScript +Number.

      +

      napi_get_value_bigint_int64#

      + +
      napi_status napi_get_value_bigint_int64(napi_env env,
      +                                        napi_value value,
      +                                        int64_t* result,
      +                                        bool* lossless);
      +
        +
      • [in] env: The environment that the API is invoked under
      • +
      • [in] value: napi_value representing JavaScript BigInt.
      • +
      • [out] result: C int64_t primitive equivalent of the given JavaScript +BigInt.
      • +
      • [out] lossless: Indicates whether the BigInt value was converted +losslessly.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it +returns napi_bigint_expected.

      +

      This API returns the C int64_t primitive equivalent of the given JavaScript +BigInt. If needed it will truncate the value, setting lossless to false.

      +

      napi_get_value_bigint_uint64#

      + +
      napi_status napi_get_value_bigint_uint64(napi_env env,
      +                                        napi_value value,
      +                                        uint64_t* result,
      +                                        bool* lossless);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript BigInt.
      • +
      • [out] result: C uint64_t primitive equivalent of the given JavaScript +BigInt.
      • +
      • [out] lossless: Indicates whether the BigInt value was converted +losslessly.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it +returns napi_bigint_expected.

      +

      This API returns the C uint64_t primitive equivalent of the given JavaScript +BigInt. If needed it will truncate the value, setting lossless to false.

      +

      napi_get_value_bigint_words#

      + +
      napi_status napi_get_value_bigint_words(napi_env env,
      +                                        napi_value value,
      +                                        int* sign_bit,
      +                                        size_t* word_count,
      +                                        uint64_t* words);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript BigInt.
      • +
      • [out] sign_bit: Integer representing if the JavaScript BigInt is positive +or negative.
      • +
      • [in/out] word_count: Must be initialized to the length of the words +array. Upon return, it will be set to the actual number of words that +would be needed to store this BigInt.
      • +
      • [out] words: Pointer to a pre-allocated 64-bit word array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API converts a single BigInt value into a sign bit, 64-bit little-endian +array, and the number of elements in the array. sign_bit and words may be +both set to NULL, in order to get only word_count.

      +

      napi_get_value_external#

      + +
      napi_status napi_get_value_external(napi_env env,
      +                                    napi_value value,
      +                                    void** result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript external value.
      • +
      • [out] result: Pointer to the data wrapped by the JavaScript external value.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-external napi_value is +passed in it returns napi_invalid_arg.

      +

      This API retrieves the external data pointer that was previously passed to +napi_create_external().

      +

      napi_get_value_int32#

      + +
      napi_status napi_get_value_int32(napi_env env,
      +                                 napi_value value,
      +                                 int32_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C int32 primitive equivalent of the given JavaScript +Number.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value +is passed in napi_number_expected.

      +

      This API returns the C int32 primitive equivalent +of the given JavaScript Number.

      +

      If the number exceeds the range of the 32 bit integer, then the result is +truncated to the equivalent of the bottom 32 bits. This can result in a large +positive number becoming a negative number if the value is > 231 - 1.

      +

      Non-finite number values (NaN, +Infinity, or -Infinity) set the +result to zero.

      +

      napi_get_value_int64#

      + +
      napi_status napi_get_value_int64(napi_env env,
      +                                 napi_value value,
      +                                 int64_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C int64 primitive equivalent of the given JavaScript +Number.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value +is passed in it returns napi_number_expected.

      +

      This API returns the C int64 primitive equivalent of the given JavaScript +Number.

      +

      Number values outside the range of Number.MIN_SAFE_INTEGER +-(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose +precision.

      +

      Non-finite number values (NaN, +Infinity, or -Infinity) set the +result to zero.

      +

      napi_get_value_string_latin1#

      + +
      napi_status napi_get_value_string_latin1(napi_env env,
      +                                         napi_value value,
      +                                         char* buf,
      +                                         size_t bufsize,
      +                                         size_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript string.
      • +
      • [in] buf: Buffer to write the ISO-8859-1-encoded string into. If NULL is +passed in, the length of the string (in bytes) is returned.
      • +
      • [in] bufsize: Size of the destination buffer. When this value is +insufficient, the returned string will be truncated.
      • +
      • [out] result: Number of bytes copied into the buffer, excluding the null +terminator.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-String napi_value +is passed in it returns napi_string_expected.

      +

      This API returns the ISO-8859-1-encoded string corresponding the value passed +in.

      +

      napi_get_value_string_utf8#

      + +
      napi_status napi_get_value_string_utf8(napi_env env,
      +                                       napi_value value,
      +                                       char* buf,
      +                                       size_t bufsize,
      +                                       size_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript string.
      • +
      • [in] buf: Buffer to write the UTF8-encoded string into. If NULL is passed +in, the length of the string (in bytes) is returned.
      • +
      • [in] bufsize: Size of the destination buffer. When this value is +insufficient, the returned string will be truncated.
      • +
      • [out] result: Number of bytes copied into the buffer, excluding the null +terminator.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-String napi_value +is passed in it returns napi_string_expected.

      +

      This API returns the UTF8-encoded string corresponding the value passed in.

      +

      napi_get_value_string_utf16#

      + +
      napi_status napi_get_value_string_utf16(napi_env env,
      +                                        napi_value value,
      +                                        char16_t* buf,
      +                                        size_t bufsize,
      +                                        size_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript string.
      • +
      • [in] buf: Buffer to write the UTF16-LE-encoded string into. If NULL is +passed in, the length of the string (in 2-byte code units) is returned.
      • +
      • [in] bufsize: Size of the destination buffer. When this value is +insufficient, the returned string will be truncated.
      • +
      • [out] result: Number of 2-byte code units copied into the buffer, excluding +the null terminator.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-String napi_value +is passed in it returns napi_string_expected.

      +

      This API returns the UTF16-encoded string corresponding the value passed in.

      +

      napi_get_value_uint32#

      + +
      napi_status napi_get_value_uint32(napi_env env,
      +                                  napi_value value,
      +                                  uint32_t* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: napi_value representing JavaScript Number.
      • +
      • [out] result: C primitive equivalent of the given napi_value as a +uint32_t.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-number napi_value +is passed in it returns napi_number_expected.

      +

      This API returns the C primitive equivalent of the given napi_value as a +uint32_t.

      +

      Functions to get global instances#

      +

      napi_get_boolean#

      + +
      napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The value of the boolean to retrieve.
      • +
      • [out] result: napi_value representing JavaScript Boolean singleton to +retrieve.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API is used to return the JavaScript singleton object that is used to +represent the given boolean value.

      +

      napi_get_global#

      + +
      napi_status napi_get_global(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing JavaScript global object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the global object.

      +

      napi_get_null#

      + +
      napi_status napi_get_null(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing JavaScript null object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the null object.

      +

      napi_get_undefined#

      + +
      napi_status napi_get_undefined(napi_env env, napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: napi_value representing JavaScript Undefined value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the Undefined object.

      +

      Working with JavaScript values and abstract operations#

      +

      N-API exposes a set of APIs to perform some abstract operations on JavaScript +values. Some of these operations are documented under Section 7 +of the ECMAScript Language Specification.

      +

      These APIs support doing one of the following:

      +
        +
      1. Coerce JavaScript values to specific JavaScript types (such as Number or +String).
      2. +
      3. Check the type of a JavaScript value.
      4. +
      5. Check for equality between two JavaScript values.
      6. +
      +

      napi_coerce_to_bool#

      + +
      napi_status napi_coerce_to_bool(napi_env env,
      +                                napi_value value,
      +                                napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript Boolean.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToBoolean() as defined in +Section 7.1.2 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_coerce_to_number#

      + +
      napi_status napi_coerce_to_number(napi_env env,
      +                                  napi_value value,
      +                                  napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript Number.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToNumber() as defined in +Section 7.1.3 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_coerce_to_object#

      + +
      napi_status napi_coerce_to_object(napi_env env,
      +                                  napi_value value,
      +                                  napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript Object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToObject() as defined in +Section 7.1.13 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_coerce_to_string#

      + +
      napi_status napi_coerce_to_string(napi_env env,
      +                                  napi_value value,
      +                                  napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to coerce.
      • +
      • [out] result: napi_value representing the coerced JavaScript String.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API implements the abstract operation ToString() as defined in +Section 7.1.13 of the ECMAScript Language Specification. +This API can be re-entrant if getters are defined on the passed-in Object.

      +

      napi_typeof#

      + +
      napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value whose type to query.
      • +
      • [out] result: The type of the JavaScript value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +
        +
      • napi_invalid_arg if the type of value is not a known ECMAScript type and +value is not an External value.
      • +
      +

      This API represents behavior similar to invoking the typeof Operator on +the object as defined in Section 12.5.5 of the ECMAScript Language +Specification. However, there are some differences:

      +
        +
      1. It has support for detecting an External value.
      2. +
      3. It detects null as a separate type, while ECMAScript typeof would detect +object.
      4. +
      +

      If value has a type that is invalid, an error is returned.

      +

      napi_instanceof#

      + +
      napi_status napi_instanceof(napi_env env,
      +                            napi_value object,
      +                            napi_value constructor,
      +                            bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] object: The JavaScript value to check.
      • +
      • [in] constructor: The JavaScript function object of the constructor function +to check against.
      • +
      • [out] result: Boolean that is set to true if object instanceof constructor +is true.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API represents invoking the instanceof Operator on the object as +defined in Section 12.10.4 of the ECMAScript Language Specification.

      +

      napi_is_array#

      + +
      napi_status napi_is_array(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given object is an array.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API represents invoking the IsArray operation on the object +as defined in Section 7.2.2 of the ECMAScript Language Specification.

      +

      napi_is_arraybuffer#

      + +
      napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given object is an ArrayBuffer.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is an array buffer.

      +

      napi_is_buffer#

      + +
      napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a node::Buffer +object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a buffer.

      +

      napi_is_date#

      + +
      napi_status napi_is_date(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a JavaScript Date +object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a date.

      +

      napi_is_error#

      + +
      napi_status napi_is_error(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents an Error object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is an Error.

      +

      napi_is_typedarray#

      + +
      napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a TypedArray.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a typed array.

      +

      napi_is_dataview#

      + +
      napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The JavaScript value to check.
      • +
      • [out] result: Whether the given napi_value represents a DataView.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in is a DataView.

      +

      napi_strict_equals#

      + +
      napi_status napi_strict_equals(napi_env env,
      +                               napi_value lhs,
      +                               napi_value rhs,
      +                               bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] lhs: The JavaScript value to check.
      • +
      • [in] rhs: The JavaScript value to check against.
      • +
      • [out] result: Whether the two napi_value objects are equal.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API represents the invocation of the Strict Equality algorithm as +defined in Section 7.2.14 of the ECMAScript Language Specification.

      +

      napi_detach_arraybuffer#

      + +
      napi_status napi_detach_arraybuffer(napi_env env,
      +                                    napi_value arraybuffer)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] arraybuffer: The JavaScript ArrayBuffer to be detached.
      • +
      +

      Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is +passed in it returns napi_detachable_arraybuffer_expected.

      +

      Generally, an ArrayBuffer is non-detachable if it has been detached before. +The engine may impose additional conditions on whether an ArrayBuffer is +detachable. For example, V8 requires that the ArrayBuffer be external, +that is, created with napi_create_external_arraybuffer.

      +

      This API represents the invocation of the ArrayBuffer detach operation as +defined in Section 24.1.1.3 of the ECMAScript Language Specification.

      +

      napi_is_detached_arraybuffer#

      + +
      napi_status napi_is_detached_arraybuffer(napi_env env,
      +                                         napi_value arraybuffer,
      +                                         bool* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] arraybuffer: The JavaScript ArrayBuffer to be checked.
      • +
      • [out] result: Whether the arraybuffer is detached.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      The ArrayBuffer is considered detached if its internal data is null.

      +

      This API represents the invocation of the ArrayBuffer IsDetachedBuffer +operation as defined in Section 24.1.1.2 of the ECMAScript Language +Specification.

      +

      Working with JavaScript properties#

      +

      N-API exposes a set of APIs to get and set properties on JavaScript +objects. Some of these types are documented under Section 7 of the +ECMAScript Language Specification.

      +

      Properties in JavaScript are represented as a tuple of a key and a value. +Fundamentally, all property keys in N-API can be represented in one of the +following forms:

      +
        +
      • Named: a simple UTF8-encoded string
      • +
      • Integer-Indexed: an index value represented by uint32_t
      • +
      • JavaScript value: these are represented in N-API by napi_value. This can +be a napi_value representing a String, Number, or Symbol.
      • +
      +

      N-API values are represented by the type napi_value. +Any N-API call that requires a JavaScript value takes in a napi_value. +However, it's the caller's responsibility to make sure that the +napi_value in question is of the JavaScript type expected by the API.

      +

      The APIs documented in this section provide a simple interface to +get and set properties on arbitrary JavaScript objects represented by +napi_value.

      +

      For instance, consider the following JavaScript code snippet:

      +
      const obj = {};
      +obj.myProp = 123;
      +

      The equivalent can be done using N-API values with the following snippet:

      +
      napi_status status = napi_generic_failure;
      +
      +// const obj = {}
      +napi_value obj, value;
      +status = napi_create_object(env, &obj);
      +if (status != napi_ok) return status;
      +
      +// Create a napi_value for 123
      +status = napi_create_int32(env, 123, &value);
      +if (status != napi_ok) return status;
      +
      +// obj.myProp = 123
      +status = napi_set_named_property(env, obj, "myProp", value);
      +if (status != napi_ok) return status;
      +

      Indexed properties can be set in a similar manner. Consider the following +JavaScript snippet:

      +
      const arr = [];
      +arr[123] = 'hello';
      +

      The equivalent can be done using N-API values with the following snippet:

      +
      napi_status status = napi_generic_failure;
      +
      +// const arr = [];
      +napi_value arr, value;
      +status = napi_create_array(env, &arr);
      +if (status != napi_ok) return status;
      +
      +// Create a napi_value for 'hello'
      +status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value);
      +if (status != napi_ok) return status;
      +
      +// arr[123] = 'hello';
      +status = napi_set_element(env, arr, 123, value);
      +if (status != napi_ok) return status;
      +

      Properties can be retrieved using the APIs described in this section. +Consider the following JavaScript snippet:

      +
      const arr = [];
      +const value = arr[123];
      +

      The following is the approximate equivalent of the N-API counterpart:

      +
      napi_status status = napi_generic_failure;
      +
      +// const arr = []
      +napi_value arr, value;
      +status = napi_create_array(env, &arr);
      +if (status != napi_ok) return status;
      +
      +// const value = arr[123]
      +status = napi_get_element(env, arr, 123, &value);
      +if (status != napi_ok) return status;
      +

      Finally, multiple properties can also be defined on an object for performance +reasons. Consider the following JavaScript:

      +
      const obj = {};
      +Object.defineProperties(obj, {
      +  'foo': { value: 123, writable: true, configurable: true, enumerable: true },
      +  'bar': { value: 456, writable: true, configurable: true, enumerable: true }
      +});
      +

      The following is the approximate equivalent of the N-API counterpart:

      +
      napi_status status = napi_status_generic_failure;
      +
      +// const obj = {};
      +napi_value obj;
      +status = napi_create_object(env, &obj);
      +if (status != napi_ok) return status;
      +
      +// Create napi_values for 123 and 456
      +napi_value fooValue, barValue;
      +status = napi_create_int32(env, 123, &fooValue);
      +if (status != napi_ok) return status;
      +status = napi_create_int32(env, 456, &barValue);
      +if (status != napi_ok) return status;
      +
      +// Set the properties
      +napi_property_descriptor descriptors[] = {
      +  { "foo", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL },
      +  { "bar", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL }
      +}
      +status = napi_define_properties(env,
      +                                obj,
      +                                sizeof(descriptors) / sizeof(descriptors[0]),
      +                                descriptors);
      +if (status != napi_ok) return status;
      +

      Structures#

      +

      napi_property_attributes#

      + +
      typedef enum {
      +  napi_default = 0,
      +  napi_writable = 1 << 0,
      +  napi_enumerable = 1 << 1,
      +  napi_configurable = 1 << 2,
      +
      +  // Used with napi_define_class to distinguish static properties
      +  // from instance properties. Ignored by napi_define_properties.
      +  napi_static = 1 << 10,
      +
      +  // Default for class methods.
      +  napi_default_method = napi_writable | napi_configurable,
      +
      +  // Default for object properties, like in JS obj[prop].
      +  napi_default_property = napi_writable |
      +                          napi_enumerable |
      +                          napi_configurable,
      +} napi_property_attributes;
      +

      napi_property_attributes are flags used to control the behavior of properties +set on a JavaScript object. Other than napi_static they correspond to the +attributes listed in Section 6.1.7.1 +of the ECMAScript Language Specification. +They can be one or more of the following bitflags:

      +
        +
      • napi_default: No explicit attributes are set on the property. By default, a +property is read only, not enumerable and not configurable.
      • +
      • napi_writable: The property is writable.
      • +
      • napi_enumerable: The property is enumerable.
      • +
      • napi_configurable: The property is configurable as defined in +Section 6.1.7.1 of the ECMAScript Language Specification.
      • +
      • napi_static: The property will be defined as a static property on a class as +opposed to an instance property, which is the default. This is used only by +napi_define_class. It is ignored by napi_define_properties.
      • +
      • napi_default_method: The property is configureable, writeable but not +enumerable like a method in a JS class.
      • +
      • napi_default_property: The property is writable, enumerable and configurable +like a property set via JS code obj.key = value.
      • +
      +

      napi_property_descriptor#

      +
      typedef struct {
      +  // One of utf8name or name should be NULL.
      +  const char* utf8name;
      +  napi_value name;
      +
      +  napi_callback method;
      +  napi_callback getter;
      +  napi_callback setter;
      +  napi_value value;
      +
      +  napi_property_attributes attributes;
      +  void* data;
      +} napi_property_descriptor;
      +
        +
      • utf8name: Optional String describing the key for the property, +encoded as UTF8. One of utf8name or name must be provided for the +property.
      • +
      • name: Optional napi_value that points to a JavaScript string or symbol +to be used as the key for the property. One of utf8name or name must +be provided for the property.
      • +
      • value: The value that's retrieved by a get access of the property if the +property is a data property. If this is passed in, set getter, setter, +method and data to NULL (since these members won't be used).
      • +
      • getter: A function to call when a get access of the property is performed. +If this is passed in, set value and method to NULL (since these members +won't be used). The given function is called implicitly by the runtime when +the property is accessed from JavaScript code (or if a get on the property is +performed using a N-API call). napi_callback provides more details.
      • +
      • setter: A function to call when a set access of the property is performed. +If this is passed in, set value and method to NULL (since these members +won't be used). The given function is called implicitly by the runtime when +the property is set from JavaScript code (or if a set on the property is +performed using a N-API call). napi_callback provides more details.
      • +
      • method: Set this to make the property descriptor object's value +property to be a JavaScript function represented by method. If this is +passed in, set value, getter and setter to NULL (since these members +won't be used). napi_callback provides more details.
      • +
      • attributes: The attributes associated with the particular property. See +napi_property_attributes.
      • +
      • data: The callback data passed into method, getter and setter if this +function is invoked.
      • +
      +

      Functions#

      +

      napi_get_property_names#

      + +
      napi_status napi_get_property_names(napi_env env,
      +                                    napi_value object,
      +                                    napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the properties.
      • +
      • [out] result: A napi_value representing an array of JavaScript values +that represent the property names of the object. The API can be used to +iterate over result using napi_get_array_length +and napi_get_element.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the names of the enumerable properties of object as an array +of strings. The properties of object whose key is a symbol will not be +included.

      +

      napi_get_all_property_names#

      + +
      napi_get_all_property_names(napi_env env,
      +                            napi_value object,
      +                            napi_key_collection_mode key_mode,
      +                            napi_key_filter key_filter,
      +                            napi_key_conversion key_conversion,
      +                            napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the properties.
      • +
      • [in] key_mode: Whether to retrieve prototype properties as well.
      • +
      • [in] key_filter: Which properties to retrieve +(enumerable/readable/writable).
      • +
      • [in] key_conversion: Whether to convert numbered property keys to strings.
      • +
      • [out] result: A napi_value representing an array of JavaScript values +that represent the property names of the object. napi_get_array_length and +napi_get_element can be used to iterate over result.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns an array containing the names of the available properties +of this object.

      +

      napi_set_property#

      + +
      napi_status napi_set_property(napi_env env,
      +                              napi_value object,
      +                              napi_value key,
      +                              napi_value value);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object on which to set the property.
      • +
      • [in] key: The name of the property to set.
      • +
      • [in] value: The property value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API set a property on the Object passed in.

      +

      napi_get_property#

      + +
      napi_status napi_get_property(napi_env env,
      +                              napi_value object,
      +                              napi_value key,
      +                              napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the property.
      • +
      • [in] key: The name of the property to retrieve.
      • +
      • [out] result: The value of the property.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API gets the requested property from the Object passed in.

      +

      napi_has_property#

      + +
      napi_status napi_has_property(napi_env env,
      +                              napi_value object,
      +                              napi_value key,
      +                              bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] key: The name of the property whose existence to check.
      • +
      • [out] result: Whether the property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in has the named property.

      +

      napi_delete_property#

      + +
      napi_status napi_delete_property(napi_env env,
      +                                 napi_value object,
      +                                 napi_value key,
      +                                 bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] key: The name of the property to delete.
      • +
      • [out] result: Whether the property deletion succeeded or not. result can +optionally be ignored by passing NULL.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API attempts to delete the key own property from object.

      +

      napi_has_own_property#

      + +
      napi_status napi_has_own_property(napi_env env,
      +                                  napi_value object,
      +                                  napi_value key,
      +                                  bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] key: The name of the own property whose existence to check.
      • +
      • [out] result: Whether the own property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API checks if the Object passed in has the named own property. key must +be a string or a Symbol, or an error will be thrown. N-API will not perform +any conversion between data types.

      +

      napi_set_named_property#

      + +
      napi_status napi_set_named_property(napi_env env,
      +                                    napi_value object,
      +                                    const char* utf8Name,
      +                                    napi_value value);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object on which to set the property.
      • +
      • [in] utf8Name: The name of the property to set.
      • +
      • [in] value: The property value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is equivalent to calling napi_set_property with a napi_value +created from the string passed in as utf8Name.

      +

      napi_get_named_property#

      + +
      napi_status napi_get_named_property(napi_env env,
      +                                    napi_value object,
      +                                    const char* utf8Name,
      +                                    napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the property.
      • +
      • [in] utf8Name: The name of the property to get.
      • +
      • [out] result: The value of the property.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is equivalent to calling napi_get_property with a napi_value +created from the string passed in as utf8Name.

      +

      napi_has_named_property#

      + +
      napi_status napi_has_named_property(napi_env env,
      +                                    napi_value object,
      +                                    const char* utf8Name,
      +                                    bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] utf8Name: The name of the property whose existence to check.
      • +
      • [out] result: Whether the property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is equivalent to calling napi_has_property with a napi_value +created from the string passed in as utf8Name.

      +

      napi_set_element#

      + +
      napi_status napi_set_element(napi_env env,
      +                             napi_value object,
      +                             uint32_t index,
      +                             napi_value value);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to set the properties.
      • +
      • [in] index: The index of the property to set.
      • +
      • [in] value: The property value.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API sets and element on the Object passed in.

      +

      napi_get_element#

      + +
      napi_status napi_get_element(napi_env env,
      +                             napi_value object,
      +                             uint32_t index,
      +                             napi_value* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the property.
      • +
      • [in] index: The index of the property to get.
      • +
      • [out] result: The value of the property.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API gets the element at the requested index.

      +

      napi_has_element#

      + +
      napi_status napi_has_element(napi_env env,
      +                             napi_value object,
      +                             uint32_t index,
      +                             bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] index: The index of the property whose existence to check.
      • +
      • [out] result: Whether the property exists on the object or not.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns if the Object passed in has an element at the +requested index.

      +

      napi_delete_element#

      + +
      napi_status napi_delete_element(napi_env env,
      +                                napi_value object,
      +                                uint32_t index,
      +                                bool* result);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to query.
      • +
      • [in] index: The index of the property to delete.
      • +
      • [out] result: Whether the element deletion succeeded or not. result can +optionally be ignored by passing NULL.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API attempts to delete the specified index from object.

      +

      napi_define_properties#

      + +
      napi_status napi_define_properties(napi_env env,
      +                                   napi_value object,
      +                                   size_t property_count,
      +                                   const napi_property_descriptor* properties);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object from which to retrieve the properties.
      • +
      • [in] property_count: The number of elements in the properties array.
      • +
      • [in] properties: The array of property descriptors.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method allows the efficient definition of multiple properties on a given +object. The properties are defined using property descriptors (see +napi_property_descriptor). Given an array of such property descriptors, +this API will set the properties on the object one at a time, as defined by +DefineOwnProperty() (described in Section 9.1.6 of the ECMA-262 +specification).

      +

      napi_object_freeze#

      + +
      napi_status napi_object_freeze(napi_env env,
      +                               napi_value object);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to freeze.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method freezes a given object. This prevents new properties from +being added to it, existing properties from being removed, prevents +changing the enumerability, configurability, or writability of existing +properties, and prevents the values of existing properties from being changed. +It also prevents the object's prototype from being changed. This is described +in Section 19.1.2.6 of the +ECMA-262 specification.

      +

      napi_object_seal#

      + +
      napi_status napi_object_seal(napi_env env,
      +                             napi_value object);
      +
        +
      • [in] env: The environment that the N-API call is invoked under.
      • +
      • [in] object: The object to seal.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method seals a given object. This prevents new properties from being +added to it, as well as marking all existing properties as non-configurable. +This is described in Section 19.1.2.20 +of the ECMA-262 specification.

      +

      Working with JavaScript functions#

      +

      N-API provides a set of APIs that allow JavaScript code to +call back into native code. N-API APIs that support calling back +into native code take in a callback functions represented by +the napi_callback type. When the JavaScript VM calls back to +native code, the napi_callback function provided is invoked. The APIs +documented in this section allow the callback function to do the +following:

      +
        +
      • Get information about the context in which the callback was invoked.
      • +
      • Get the arguments passed into the callback.
      • +
      • Return a napi_value back from the callback.
      • +
      +

      Additionally, N-API provides a set of functions which allow calling +JavaScript functions from native code. One can either call a function +like a regular JavaScript function call, or as a constructor +function.

      +

      Any non-NULL data which is passed to this API via the data field of the +napi_property_descriptor items can be associated with object and freed +whenever object is garbage-collected by passing both object and the data to +napi_add_finalizer.

      +

      napi_call_function#

      + +
      NAPI_EXTERN napi_status napi_call_function(napi_env env,
      +                                           napi_value recv,
      +                                           napi_value func,
      +                                           size_t argc,
      +                                           const napi_value* argv,
      +                                           napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] recv: The this object passed to the called function.
      • +
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • +
      • [in] argc: The count of elements in the argv array.
      • +
      • [in] argv: Array of napi_values representing JavaScript values passed in +as arguments to the function.
      • +
      • [out] result: napi_value representing the JavaScript object returned.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method allows a JavaScript function object to be called from a native +add-on. This is the primary mechanism of calling back from the add-on's +native code into JavaScript. For the special case of calling into JavaScript +after an async operation, see napi_make_callback.

      +

      A sample use case might look as follows. Consider the following JavaScript +snippet:

      +
      function AddTwo(num) {
      +  return num + 2;
      +}
      +

      Then, the above function can be invoked from a native add-on using the +following code:

      +
      // Get the function named "AddTwo" on the global object
      +napi_value global, add_two, arg;
      +napi_status status = napi_get_global(env, &global);
      +if (status != napi_ok) return;
      +
      +status = napi_get_named_property(env, global, "AddTwo", &add_two);
      +if (status != napi_ok) return;
      +
      +// const arg = 1337
      +status = napi_create_int32(env, 1337, &arg);
      +if (status != napi_ok) return;
      +
      +napi_value* argv = &arg;
      +size_t argc = 1;
      +
      +// AddTwo(arg);
      +napi_value return_val;
      +status = napi_call_function(env, global, add_two, argc, argv, &return_val);
      +if (status != napi_ok) return;
      +
      +// Convert the result back to a native type
      +int32_t result;
      +status = napi_get_value_int32(env, return_val, &result);
      +if (status != napi_ok) return;
      +

      napi_create_function#

      + +
      napi_status napi_create_function(napi_env env,
      +                                 const char* utf8name,
      +                                 size_t length,
      +                                 napi_callback cb,
      +                                 void* data,
      +                                 napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] utf8Name: The name of the function encoded as UTF8. This is visible +within JavaScript as the new function object's name property.
      • +
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH if +it is null-terminated.
      • +
      • [in] cb: The native function which should be called when this function +object is invoked. napi_callback provides more details.
      • +
      • [in] data: User-provided data context. This will be passed back into the +function when invoked later.
      • +
      • [out] result: napi_value representing the JavaScript function object for +the newly created function.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allows an add-on author to create a function object in native code. +This is the primary mechanism to allow calling into the add-on's native code +from JavaScript.

      +

      The newly created function is not automatically visible from script after this +call. Instead, a property must be explicitly set on any object that is visible +to JavaScript, in order for the function to be accessible from script.

      +

      In order to expose a function as part of the +add-on's module exports, set the newly created function on the exports +object. A sample module might look as follows:

      +
      napi_value SayHello(napi_env env, napi_callback_info info) {
      +  printf("Hello\n");
      +  return NULL;
      +}
      +
      +napi_value Init(napi_env env, napi_value exports) {
      +  napi_status status;
      +
      +  napi_value fn;
      +  status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);
      +  if (status != napi_ok) return NULL;
      +
      +  status = napi_set_named_property(env, exports, "sayHello", fn);
      +  if (status != napi_ok) return NULL;
      +
      +  return exports;
      +}
      +
      +NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
      +

      Given the above code, the add-on can be used from JavaScript as follows:

      +
      const myaddon = require('./addon');
      +myaddon.sayHello();
      +

      The string passed to require() is the name of the target in binding.gyp +responsible for creating the .node file.

      +

      Any non-NULL data which is passed to this API via the data parameter can +be associated with the resulting JavaScript function (which is returned in the +result parameter) and freed whenever the function is garbage-collected by +passing both the JavaScript function and the data to napi_add_finalizer.

      +

      JavaScript Functions are described in Section 19.2 of the ECMAScript +Language Specification.

      +

      napi_get_cb_info#

      + +
      napi_status napi_get_cb_info(napi_env env,
      +                             napi_callback_info cbinfo,
      +                             size_t* argc,
      +                             napi_value* argv,
      +                             napi_value* thisArg,
      +                             void** data)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] cbinfo: The callback info passed into the callback function.
      • +
      • [in-out] argc: Specifies the size of the provided argv array and receives +the actual count of arguments.
      • +
      • [out] argv: Buffer to which the napi_value representing the arguments are +copied. If there are more arguments than the provided count, only the +requested number of arguments are copied. If there are fewer arguments +provided than claimed, the rest of argv is filled with napi_value values +that represent undefined.
      • +
      • [out] this: Receives the JavaScript this argument for the call.
      • +
      • [out] data: Receives the data pointer for the callback.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method is used within a callback function to retrieve details about the +call like the arguments and the this pointer from a given callback info.

      +

      napi_get_new_target#

      + +
      napi_status napi_get_new_target(napi_env env,
      +                                napi_callback_info cbinfo,
      +                                napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] cbinfo: The callback info passed into the callback function.
      • +
      • [out] result: The new.target of the constructor call.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the new.target of the constructor call. If the current +callback is not a constructor call, the result is NULL.

      +

      napi_new_instance#

      + +
      napi_status napi_new_instance(napi_env env,
      +                              napi_value cons,
      +                              size_t argc,
      +                              napi_value* argv,
      +                              napi_value* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] cons: napi_value representing the JavaScript function to be invoked +as a constructor.
      • +
      • [in] argc: The count of elements in the argv array.
      • +
      • [in] argv: Array of JavaScript values as napi_value representing the +arguments to the constructor.
      • +
      • [out] result: napi_value representing the JavaScript object returned, +which in this case is the constructed object.
      • +
      +

      This method is used to instantiate a new JavaScript value using a given +napi_value that represents the constructor for the object. For example, +consider the following snippet:

      +
      function MyObject(param) {
      +  this.param = param;
      +}
      +
      +const arg = 'hello';
      +const value = new MyObject(arg);
      +

      The following can be approximated in N-API using the following snippet:

      +
      // Get the constructor function MyObject
      +napi_value global, constructor, arg, value;
      +napi_status status = napi_get_global(env, &global);
      +if (status != napi_ok) return;
      +
      +status = napi_get_named_property(env, global, "MyObject", &constructor);
      +if (status != napi_ok) return;
      +
      +// const arg = "hello"
      +status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg);
      +if (status != napi_ok) return;
      +
      +napi_value* argv = &arg;
      +size_t argc = 1;
      +
      +// const value = new MyObject(arg)
      +status = napi_new_instance(env, constructor, argc, argv, &value);
      +

      Returns napi_ok if the API succeeded.

      +

      Object wrap#

      +

      N-API offers a way to "wrap" C++ classes and instances so that the class +constructor and methods can be called from JavaScript.

      +
        +
      1. The napi_define_class API defines a JavaScript class with constructor, +static properties and methods, and instance properties and methods that +correspond to the C++ class.
      2. +
      3. When JavaScript code invokes the constructor, the constructor callback +uses napi_wrap to wrap a new C++ instance in a JavaScript object, +then returns the wrapper object.
      4. +
      5. When JavaScript code invokes a method or property accessor on the class, +the corresponding napi_callback C++ function is invoked. For an instance +callback, napi_unwrap obtains the C++ instance that is the target of +the call.
      6. +
      +

      For wrapped objects it may be difficult to distinguish between a function +called on a class prototype and a function called on an instance of a class. +A common pattern used to address this problem is to save a persistent +reference to the class constructor for later instanceof checks.

      +
      napi_value MyClass_constructor = NULL;
      +status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);
      +assert(napi_ok == status);
      +bool is_instance = false;
      +status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);
      +assert(napi_ok == status);
      +if (is_instance) {
      +  // napi_unwrap() ...
      +} else {
      +  // otherwise...
      +}
      +

      The reference must be freed once it is no longer needed.

      +

      There are occasions where napi_instanceof() is insufficient for ensuring that +a JavaScript object is a wrapper for a certain native type. This is the case +especially when wrapped JavaScript objects are passed back into the addon via +static methods rather than as the this value of prototype methods. In such +cases there is a chance that they may be unwrapped incorrectly.

      +
      const myAddon = require('./build/Release/my_addon.node');
      +
      +// `openDatabase()` returns a JavaScript object that wraps a native database
      +// handle.
      +const dbHandle = myAddon.openDatabase();
      +
      +// `query()` returns a JavaScript object that wraps a native query handle.
      +const queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!');
      +
      +// There is an accidental error in the line below. The first parameter to
      +// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not
      +// the query handle (`query`), so the correct condition for the while-loop
      +// should be
      +//
      +// myAddon.queryHasRecords(dbHandle, queryHandle)
      +//
      +while (myAddon.queryHasRecords(queryHandle, dbHandle)) {
      +  // retrieve records
      +}
      +

      In the above example myAddon.queryHasRecords() is a method that accepts two +arguments. The first is a database handle and the second is a query handle. +Internally, it unwraps the first argument and casts the resulting pointer to a +native database handle. It then unwraps the second argument and casts the +resulting pointer to a query handle. If the arguments are passed in the wrong +order, the casts will work, however, there is a good chance that the underlying +database operation will fail, or will even cause an invalid memory access.

      +

      To ensure that the pointer retrieved from the first argument is indeed a pointer +to a database handle and, similarly, that the pointer retrieved from the second +argument is indeed a pointer to a query handle, the implementation of +queryHasRecords() has to perform a type validation. Retaining the JavaScript +class constructor from which the database handle was instantiated and the +constructor from which the query handle was instantiated in napi_refs can +help, because napi_instanceof() can then be used to ensure that the instances +passed into queryHashRecords() are indeed of the correct type.

      +

      Unfortunately, napi_instanceof() does not protect against prototype +manipulation. For example, the prototype of the database handle instance can be +set to the prototype of the constructor for query handle instances. In this +case, the database handle instance can appear as a query handle instance, and it +will pass the napi_instanceof() test for a query handle instance, while still +containing a pointer to a database handle.

      +

      To this end, N-API provides type-tagging capabilities.

      +

      A type tag is a 128-bit integer unique to the addon. N-API provides the +napi_type_tag structure for storing a type tag. When such a value is passed +along with a JavaScript object stored in a napi_value to +napi_type_tag_object(), the JavaScript object will be "marked" with the +type tag. The "mark" is invisible on the JavaScript side. When a JavaScript +object arrives into a native binding, napi_check_object_type_tag() can be used +along with the original type tag to determine whether the JavaScript object was +previously "marked" with the type tag. This creates a type-checking capability +of a higher fidelity than napi_instanceof() can provide, because such type- +tagging survives prototype manipulation and addon unloading/reloading.

      +

      Continuing the above example, the following skeleton addon implementation +illustrates the use of napi_type_tag_object() and +napi_check_object_type_tag().

      +
      // This value is the type tag for a database handle. The command
      +//
      +//   uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/'
      +//
      +// can be used to obtain the two values with which to initialize the structure.
      +static const napi_type_tag DatabaseHandleTypeTag = {
      +  0x1edf75a38336451d, 0xa5ed9ce2e4c00c38
      +};
      +
      +// This value is the type tag for a query handle.
      +static const napi_type_tag QueryHandleTypeTag = {
      +  0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a
      +};
      +
      +static napi_value
      +openDatabase(napi_env env, napi_callback_info info) {
      +  napi_status status;
      +  napi_value result;
      +
      +  // Perform the underlying action which results in a database handle.
      +  DatabaseHandle* dbHandle = open_database();
      +
      +  // Create a new, empty JS object.
      +  status = napi_create_object(env, &result);
      +  if (status != napi_ok) return NULL;
      +
      +  // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.
      +  status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);
      +  if (status != napi_ok) return NULL;
      +
      +  // Store the pointer to the `DatabaseHandle` structure inside the JS object.
      +  status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL);
      +  if (status != napi_ok) return NULL;
      +
      +  return result;
      +}
      +
      +// Later when we receive a JavaScript object purporting to be a database handle
      +// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a
      +// handle.
      +
      +static napi_value
      +query(napi_env env, napi_callback_info info) {
      +  napi_status status;
      +  size_t argc = 2;
      +  napi_value argv[2];
      +  bool is_db_handle;
      +
      +  status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
      +  if (status != napi_ok) return NULL;
      +
      +  // Check that the object passed as the first parameter has the previously
      +  // applied tag.
      +  status = napi_check_object_type_tag(env,
      +                                      argv[0],
      +                                      &DatabaseHandleTypeTag,
      +                                      &is_db_handle);
      +  if (status != napi_ok) return NULL;
      +
      +  // Throw a `TypeError` if it doesn't.
      +  if (!is_db_handle) {
      +    // Throw a TypeError.
      +    return NULL;
      +  }
      +}
      +

      napi_define_class#

      + +
      napi_status napi_define_class(napi_env env,
      +                              const char* utf8name,
      +                              size_t length,
      +                              napi_callback constructor,
      +                              void* data,
      +                              size_t property_count,
      +                              const napi_property_descriptor* properties,
      +                              napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] utf8name: Name of the JavaScript constructor function; this is +not required to be the same as the C++ class name, though it is recommended +for clarity.
      • +
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH +if it is null-terminated.
      • +
      • [in] constructor: Callback function that handles constructing instances +of the class. This should be a static method on the class, not an actual +C++ constructor function. napi_callback provides more details.
      • +
      • [in] data: Optional data to be passed to the constructor callback as +the data property of the callback info.
      • +
      • [in] property_count: Number of items in the properties array argument.
      • +
      • [in] properties: Array of property descriptors describing static and +instance data properties, accessors, and methods on the class +See napi_property_descriptor.
      • +
      • [out] result: A napi_value representing the constructor function for +the class.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Defines a JavaScript class that corresponds to a C++ class, including:

      +
        +
      • A JavaScript constructor function that has the class name and invokes the +provided C++ constructor callback.
      • +
      • Properties on the constructor function corresponding to static data +properties, accessors, and methods of the C++ class (defined by +property descriptors with the napi_static attribute).
      • +
      • Properties on the constructor function's prototype object corresponding to +non-static data properties, accessors, and methods of the C++ class +(defined by property descriptors without the napi_static attribute).
      • +
      +

      The C++ constructor callback should be a static method on the class that calls +the actual class constructor, then wraps the new C++ instance in a JavaScript +object, and returns the wrapper object. See napi_wrap() for details.

      +

      The JavaScript constructor function returned from napi_define_class is +often saved and used later, to construct new instances of the class from native +code, and/or check whether provided values are instances of the class. In that +case, to prevent the function value from being garbage-collected, create a +persistent reference to it using napi_create_reference and ensure the +reference count is kept >= 1.

      +

      Any non-NULL data which is passed to this API via the data parameter or via +the data field of the napi_property_descriptor array items can be associated +with the resulting JavaScript constructor (which is returned in the result +parameter) and freed whenever the class is garbage-collected by passing both +the JavaScript function and the data to napi_add_finalizer.

      +

      napi_wrap#

      + +
      napi_status napi_wrap(napi_env env,
      +                      napi_value js_object,
      +                      void* native_object,
      +                      napi_finalize finalize_cb,
      +                      void* finalize_hint,
      +                      napi_ref* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object that will be the wrapper for the +native object.
      • +
      • [in] native_object: The native instance that will be wrapped in the +JavaScript object.
      • +
      • [in] finalize_cb: Optional native callback that can be used to free the +native instance when the JavaScript object is ready for garbage-collection. +napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional contextual hint that is passed to the +finalize callback.
      • +
      • [out] result: Optional reference to the wrapped object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Wraps a native instance in a JavaScript object. The native instance can be +retrieved later using napi_unwrap().

      +

      When JavaScript code invokes a constructor for a class that was defined using +napi_define_class(), the napi_callback for the constructor is invoked. +After constructing an instance of the native class, the callback must then call +napi_wrap() to wrap the newly constructed instance in the already-created +JavaScript object that is the this argument to the constructor callback. +(That this object was created from the constructor function's prototype, +so it already has definitions of all the instance properties and methods.)

      +

      Typically when wrapping a class instance, a finalize callback should be +provided that simply deletes the native instance that is received as the data +argument to the finalize callback.

      +

      The optional returned reference is initially a weak reference, meaning it +has a reference count of 0. Typically this reference count would be incremented +temporarily during async operations that require the instance to remain valid.

      +

      Caution: The optional returned reference (if obtained) should be deleted via +napi_delete_reference ONLY in response to the finalize callback +invocation. If it is deleted before then, then the finalize callback may never +be invoked. Therefore, when obtaining a reference a finalize callback is also +required in order to enable correct disposal of the reference.

      +

      Calling napi_wrap() a second time on an object will return an error. To +associate another native instance with the object, use napi_remove_wrap() +first.

      +

      napi_unwrap#

      + +
      napi_status napi_unwrap(napi_env env,
      +                        napi_value js_object,
      +                        void** result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The object associated with the native instance.
      • +
      • [out] result: Pointer to the wrapped native instance.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Retrieves a native instance that was previously wrapped in a JavaScript +object using napi_wrap().

      +

      When JavaScript code invokes a method or property accessor on the class, the +corresponding napi_callback is invoked. If the callback is for an instance +method or accessor, then the this argument to the callback is the wrapper +object; the wrapped C++ instance that is the target of the call can be obtained +then by calling napi_unwrap() on the wrapper object.

      +

      napi_remove_wrap#

      + +
      napi_status napi_remove_wrap(napi_env env,
      +                             napi_value js_object,
      +                             void** result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The object associated with the native instance.
      • +
      • [out] result: Pointer to the wrapped native instance.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Retrieves a native instance that was previously wrapped in the JavaScript +object js_object using napi_wrap() and removes the wrapping. If a finalize +callback was associated with the wrapping, it will no longer be called when the +JavaScript object becomes garbage-collected.

      +

      napi_type_tag_object#

      + +
      napi_status napi_type_tag_object(napi_env env,
      +                                 napi_value js_object,
      +                                 const napi_type_tag* type_tag);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object to be marked.
      • +
      • [in] type_tag: The tag with which the object is to be marked.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Associates the value of the type_tag pointer with the JavaScript object. +napi_check_object_type_tag() can then be used to compare the tag that was +attached to the object with one owned by the addon to ensure that the object +has the right type.

      +

      If the object already has an associated type tag, this API will return +napi_invalid_arg.

      +

      napi_check_object_type_tag#

      + +
      napi_status napi_check_object_type_tag(napi_env env,
      +                                       napi_value js_object,
      +                                       const napi_type_tag* type_tag,
      +                                       bool* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object whose type tag to examine.
      • +
      • [in] type_tag: The tag with which to compare any tag found on the object.
      • +
      • [out] result: Whether the type tag given matched the type tag on the +object. false is also returned if no type tag was found on the object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Compares the pointer given as type_tag with any that can be found on +js_object. If no tag is found on js_object or, if a tag is found but it does +not match type_tag, then result is set to false. If a tag is found and it +matches type_tag, then result is set to true.

      +

      napi_add_finalizer#

      + +
      napi_status napi_add_finalizer(napi_env env,
      +                               napi_value js_object,
      +                               void* native_object,
      +                               napi_finalize finalize_cb,
      +                               void* finalize_hint,
      +                               napi_ref* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] js_object: The JavaScript object to which the native data will be +attached.
      • +
      • [in] native_object: The native data that will be attached to the JavaScript +object.
      • +
      • [in] finalize_cb: Native callback that will be used to free the +native data when the JavaScript object is ready for garbage-collection. +napi_finalize provides more details.
      • +
      • [in] finalize_hint: Optional contextual hint that is passed to the +finalize callback.
      • +
      • [out] result: Optional reference to the JavaScript object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      Adds a napi_finalize callback which will be called when the JavaScript object +in js_object is ready for garbage collection. This API is similar to +napi_wrap() except that:

      +
        +
      • the native data cannot be retrieved later using napi_unwrap(),
      • +
      • nor can it be removed later using napi_remove_wrap(), and
      • +
      • the API can be called multiple times with different data items in order to +attach each of them to the JavaScript object, and
      • +
      • the object manipulated by the API can be used with napi_wrap().
      • +
      +

      Caution: The optional returned reference (if obtained) should be deleted via +napi_delete_reference ONLY in response to the finalize callback +invocation. If it is deleted before then, then the finalize callback may never +be invoked. Therefore, when obtaining a reference a finalize callback is also +required in order to enable correct disposal of the reference.

      +

      Simple asynchronous operations#

      +

      Addon modules often need to leverage async helpers from libuv as part of their +implementation. This allows them to schedule work to be executed asynchronously +so that their methods can return in advance of the work being completed. This +allows them to avoid blocking overall execution of the Node.js application.

      +

      N-API provides an ABI-stable interface for these +supporting functions which covers the most common asynchronous use cases.

      +

      N-API defines the napi_async_work structure which is used to manage +asynchronous workers. Instances are created/deleted with +napi_create_async_work and napi_delete_async_work.

      +

      The execute and complete callbacks are functions that will be +invoked when the executor is ready to execute and when it completes its +task respectively.

      +

      The execute function should avoid making any N-API calls +that could result in the execution of JavaScript or interaction with +JavaScript objects. Most often, any code that needs to make N-API +calls should be made in complete callback instead. +Avoid using the napi_env parameter in the execute callback as +it will likely execute JavaScript.

      +

      These functions implement the following interfaces:

      +
      typedef void (*napi_async_execute_callback)(napi_env env,
      +                                            void* data);
      +typedef void (*napi_async_complete_callback)(napi_env env,
      +                                             napi_status status,
      +                                             void* data);
      +

      When these methods are invoked, the data parameter passed will be the +addon-provided void* data that was passed into the +napi_create_async_work call.

      +

      Once created the async worker can be queued +for execution using the napi_queue_async_work function:

      +
      napi_status napi_queue_async_work(napi_env env,
      +                                  napi_async_work work);
      +

      napi_cancel_async_work can be used if the work needs +to be cancelled before the work has started execution.

      +

      After calling napi_cancel_async_work, the complete callback +will be invoked with a status value of napi_cancelled. +The work should not be deleted before the complete +callback invocation, even when it was cancelled.

      +

      napi_create_async_work#

      + +
      napi_status napi_create_async_work(napi_env env,
      +                                   napi_value async_resource,
      +                                   napi_value async_resource_name,
      +                                   napi_async_execute_callback execute,
      +                                   napi_async_complete_callback complete,
      +                                   void* data,
      +                                   napi_async_work* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_resource: An optional object associated with the async work +that will be passed to possible async_hooks init hooks.
      • +
      • [in] async_resource_name: Identifier for the kind of resource that is being +provided for diagnostic information exposed by the async_hooks API.
      • +
      • [in] execute: The native function which should be called to execute the +logic asynchronously. The given function is called from a worker pool thread +and can execute in parallel with the main event loop thread.
      • +
      • [in] complete: The native function which will be called when the +asynchronous logic is completed or is cancelled. The given function is called +from the main event loop thread. napi_async_complete_callback provides +more details.
      • +
      • [in] data: User-provided data context. This will be passed back into the +execute and complete functions.
      • +
      • [out] result: napi_async_work* which is the handle to the newly created +async work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API allocates a work object that is used to execute logic asynchronously. +It should be freed using napi_delete_async_work once the work is no longer +required.

      +

      async_resource_name should be a null-terminated, UTF-8-encoded string.

      +

      The async_resource_name identifier is provided by the user and should be +representative of the type of async work being performed. It is also recommended +to apply namespacing to the identifier, e.g. by including the module name. See +the async_hooks documentation for more information.

      +

      napi_delete_async_work#

      + +
      napi_status napi_delete_async_work(napi_env env,
      +                                   napi_async_work work);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] work: The handle returned by the call to napi_create_async_work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API frees a previously allocated work object.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_queue_async_work#

      + +
      napi_status napi_queue_async_work(napi_env env,
      +                                  napi_async_work work);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] work: The handle returned by the call to napi_create_async_work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API requests that the previously allocated work be scheduled +for execution. Once it returns successfully, this API must not be called again +with the same napi_async_work item or the result will be undefined.

      +

      napi_cancel_async_work#

      + +
      napi_status napi_cancel_async_work(napi_env env,
      +                                   napi_async_work work);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] work: The handle returned by the call to napi_create_async_work.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API cancels queued work if it has not yet +been started. If it has already started executing, it cannot be +cancelled and napi_generic_failure will be returned. If successful, +the complete callback will be invoked with a status value of +napi_cancelled. The work should not be deleted before the complete +callback invocation, even if it has been successfully cancelled.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Custom asynchronous operations#

      +

      The simple asynchronous work APIs above may not be appropriate for every +scenario. When using any other asynchronous mechanism, the following APIs +are necessary to ensure an asynchronous operation is properly tracked by +the runtime.

      +

      napi_async_init#

      + +
      napi_status napi_async_init(napi_env env,
      +                            napi_value async_resource,
      +                            napi_value async_resource_name,
      +                            napi_async_context* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_resource: Object associated with the async work +that will be passed to possible async_hooks init hooks. +In order to retain ABI compatibility with previous versions, +passing NULL for async_resource will not result in an error, however, +this will result incorrect operation of async hooks for the +napi_async_context created. Potential issues include +loss of async context when using the AsyncLocalStorage API.
      • +
      • [in] async_resource_name: Identifier for the kind of resource +that is being provided for diagnostic information exposed by the +async_hooks API.
      • +
      • [out] result: The initialized async context.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      napi_async_destroy#

      + +
      napi_status napi_async_destroy(napi_env env,
      +                               napi_async_context async_context);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_context: The async context to be destroyed.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API can be called even if there is a pending JavaScript exception.

      +

      napi_make_callback#

      + +
      NAPI_EXTERN napi_status napi_make_callback(napi_env env,
      +                                           napi_async_context async_context,
      +                                           napi_value recv,
      +                                           napi_value func,
      +                                           size_t argc,
      +                                           const napi_value* argv,
      +                                           napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] async_context: Context for the async operation that is +invoking the callback. This should normally be a value previously +obtained from napi_async_init. However NULL is also allowed, +which indicates the current async context (if any) is to be used +for the callback.
      • +
      • [in] recv: The this object passed to the called function.
      • +
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • +
      • [in] argc: The count of elements in the argv array.
      • +
      • [in] argv: Array of JavaScript values as napi_value representing the +arguments to the function.
      • +
      • [out] result: napi_value representing the JavaScript object returned.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This method allows a JavaScript function object to be called from a native +add-on. This API is similar to napi_call_function. However, it is used to call +from native code back into JavaScript after returning from an async +operation (when there is no other script on the stack). It is a fairly simple +wrapper around node::MakeCallback.

      +

      Note it is not necessary to use napi_make_callback from within a +napi_async_complete_callback; in that situation the callback's async +context has already been set up, so a direct call to napi_call_function +is sufficient and appropriate. Use of the napi_make_callback function +may be required when implementing custom async behavior that does not use +napi_create_async_work.

      +

      Any process.nextTicks or Promises scheduled on the microtask queue by +JavaScript during the callback are ran before returning back to C/C++.

      +

      napi_open_callback_scope#

      + +
      NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,
      +                                                 napi_value resource_object,
      +                                                 napi_async_context context,
      +                                                 napi_callback_scope* result)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] resource_object: An object associated with the async work +that will be passed to possible async_hooks init hooks.
      • +
      • [in] context: Context for the async operation that is invoking the callback. +This should be a value previously obtained from napi_async_init.
      • +
      • [out] result: The newly created scope.
      • +
      +

      There are cases (for example, resolving promises) where it is +necessary to have the equivalent of the scope associated with a callback +in place when making certain N-API calls. If there is no other script on +the stack the napi_open_callback_scope and +napi_close_callback_scope functions can be used to open/close +the required scope.

      +

      napi_close_callback_scope#

      + +
      NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,
      +                                                  napi_callback_scope scope)
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] scope: The scope to be closed.
      • +
      +

      This API can be called even if there is a pending JavaScript exception.

      +

      Version management#

      +

      napi_get_node_version#

      + +
      typedef struct {
      +  uint32_t major;
      +  uint32_t minor;
      +  uint32_t patch;
      +  const char* release;
      +} napi_node_version;
      +
      +napi_status napi_get_node_version(napi_env env,
      +                                  const napi_node_version** version);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] version: A pointer to version information for Node.js itself.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This function fills the version struct with the major, minor, and patch +version of Node.js that is currently running, and the release field with the +value of process.release.name.

      +

      The returned buffer is statically allocated and does not need to be freed.

      +

      napi_get_version#

      + +
      napi_status napi_get_version(napi_env env,
      +                             uint32_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: The highest version of N-API supported.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API returns the highest N-API version supported by the +Node.js runtime. N-API is planned to be additive such that +newer releases of Node.js may support additional API functions. +In order to allow an addon to use a newer function when running with +versions of Node.js that support it, while providing +fallback behavior when running with Node.js versions that don't +support it:

      +
        +
      • Call napi_get_version() to determine if the API is available.
      • +
      • If available, dynamically load a pointer to the function using uv_dlsym().
      • +
      • Use the dynamically loaded pointer to invoke the function.
      • +
      • If the function is not available, provide an alternate implementation +that does not use the function.
      • +
      +

      Memory management#

      +

      napi_adjust_external_memory#

      + +
      NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,
      +                                                    int64_t change_in_bytes,
      +                                                    int64_t* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] change_in_bytes: The change in externally allocated memory that is kept +alive by JavaScript objects.
      • +
      • [out] result: The adjusted value
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This function gives V8 an indication of the amount of externally allocated +memory that is kept alive by JavaScript objects (i.e. a JavaScript object +that points to its own memory allocated by a native module). Registering +externally allocated memory will trigger global garbage collections more +often than it would otherwise.

      +

      Promises#

      +

      N-API provides facilities for creating Promise objects as described in +Section 25.4 of the ECMA specification. It implements promises as a pair of +objects. When a promise is created by napi_create_promise(), a "deferred" +object is created and returned alongside the Promise. The deferred object is +bound to the created Promise and is the only means to resolve or reject the +Promise using napi_resolve_deferred() or napi_reject_deferred(). The +deferred object that is created by napi_create_promise() is freed by +napi_resolve_deferred() or napi_reject_deferred(). The Promise object may +be returned to JavaScript where it can be used in the usual fashion.

      +

      For example, to create a promise and pass it to an asynchronous worker:

      +
      napi_deferred deferred;
      +napi_value promise;
      +napi_status status;
      +
      +// Create the promise.
      +status = napi_create_promise(env, &deferred, &promise);
      +if (status != napi_ok) return NULL;
      +
      +// Pass the deferred to a function that performs an asynchronous action.
      +do_something_asynchronous(deferred);
      +
      +// Return the promise to JS
      +return promise;
      +

      The above function do_something_asynchronous() would perform its asynchronous +action and then it would resolve or reject the deferred, thereby concluding the +promise and freeing the deferred:

      +
      napi_deferred deferred;
      +napi_value undefined;
      +napi_status status;
      +
      +// Create a value with which to conclude the deferred.
      +status = napi_get_undefined(env, &undefined);
      +if (status != napi_ok) return NULL;
      +
      +// Resolve or reject the promise associated with the deferred depending on
      +// whether the asynchronous action succeeded.
      +if (asynchronous_action_succeeded) {
      +  status = napi_resolve_deferred(env, deferred, undefined);
      +} else {
      +  status = napi_reject_deferred(env, deferred, undefined);
      +}
      +if (status != napi_ok) return NULL;
      +
      +// At this point the deferred has been freed, so we should assign NULL to it.
      +deferred = NULL;
      +

      napi_create_promise#

      + +
      napi_status napi_create_promise(napi_env env,
      +                                napi_deferred* deferred,
      +                                napi_value* promise);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] deferred: A newly created deferred object which can later be passed to +napi_resolve_deferred() or napi_reject_deferred() to resolve resp. reject +the associated promise.
      • +
      • [out] promise: The JavaScript promise associated with the deferred object.
      • +
      +

      Returns napi_ok if the API succeeded.

      +

      This API creates a deferred object and a JavaScript promise.

      +

      napi_resolve_deferred#

      + +
      napi_status napi_resolve_deferred(napi_env env,
      +                                  napi_deferred deferred,
      +                                  napi_value resolution);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] deferred: The deferred object whose associated promise to resolve.
      • +
      • [in] resolution: The value with which to resolve the promise.
      • +
      +

      This API resolves a JavaScript promise by way of the deferred object +with which it is associated. Thus, it can only be used to resolve JavaScript +promises for which the corresponding deferred object is available. This +effectively means that the promise must have been created using +napi_create_promise() and the deferred object returned from that call must +have been retained in order to be passed to this API.

      +

      The deferred object is freed upon successful completion.

      +

      napi_reject_deferred#

      + +
      napi_status napi_reject_deferred(napi_env env,
      +                                 napi_deferred deferred,
      +                                 napi_value rejection);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] deferred: The deferred object whose associated promise to resolve.
      • +
      • [in] rejection: The value with which to reject the promise.
      • +
      +

      This API rejects a JavaScript promise by way of the deferred object +with which it is associated. Thus, it can only be used to reject JavaScript +promises for which the corresponding deferred object is available. This +effectively means that the promise must have been created using +napi_create_promise() and the deferred object returned from that call must +have been retained in order to be passed to this API.

      +

      The deferred object is freed upon successful completion.

      +

      napi_is_promise#

      + +
      napi_status napi_is_promise(napi_env env,
      +                            napi_value value,
      +                            bool* is_promise);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] value: The value to examine
      • +
      • [out] is_promise: Flag indicating whether promise is a native promise +object (that is, a promise object created by the underlying engine).
      • +
      +

      Script execution#

      +

      N-API provides an API for executing a string containing JavaScript using the +underlying JavaScript engine.

      +

      napi_run_script#

      + +
      NAPI_EXTERN napi_status napi_run_script(napi_env env,
      +                                        napi_value script,
      +                                        napi_value* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] script: A JavaScript string containing the script to execute.
      • +
      • [out] result: The value resulting from having executed the script.
      • +
      +

      This function executes a string of JavaScript code and returns its result with +the following caveats:

      +
        +
      • Unlike eval, this function does not allow the script to access the current +lexical scope, and therefore also does not allow to access the +module scope, meaning that pseudo-globals such as require will not be +available.
      • +
      • The script can access the global scope. Function and var declarations +in the script will be added to the global object. Variable declarations +made using let and const will be visible globally, but will not be added +to the global object.
      • +
      • The value of this is global within the script.
      • +
      +

      libuv event loop#

      +

      N-API provides a function for getting the current event loop associated with +a specific napi_env.

      +

      napi_get_uv_event_loop#

      + +
      NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,
      +                                               struct uv_loop_s** loop);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] loop: The current libuv loop instance.
      • +
      +

      Asynchronous thread-safe function calls#

      +

      JavaScript functions can normally only be called from a native addon's main +thread. If an addon creates additional threads, then N-API functions that +require a napi_env, napi_value, or napi_ref must not be called from those +threads.

      +

      When an addon has additional threads and JavaScript functions need to be invoked +based on the processing completed by those threads, those threads must +communicate with the addon's main thread so that the main thread can invoke the +JavaScript function on their behalf. The thread-safe function APIs provide an +easy way to do this.

      +

      These APIs provide the type napi_threadsafe_function as well as APIs to +create, destroy, and call objects of this type. +napi_create_threadsafe_function() creates a persistent reference to a +napi_value that holds a JavaScript function which can be called from multiple +threads. The calls happen asynchronously. This means that values with which the +JavaScript callback is to be called will be placed in a queue, and, for each +value in the queue, a call will eventually be made to the JavaScript function.

      +

      Upon creation of a napi_threadsafe_function a napi_finalize callback can be +provided. This callback will be invoked on the main thread when the thread-safe +function is about to be destroyed. It receives the context and the finalize data +given during construction, and provides an opportunity for cleaning up after the +threads e.g. by calling uv_thread_join(). Aside from the main loop thread, +no threads should be using the thread-safe function after the finalize callback +completes.

      +

      The context given during the call to napi_create_threadsafe_function() can +be retrieved from any thread with a call to +napi_get_threadsafe_function_context().

      +

      Calling a thread-safe function#

      +

      napi_call_threadsafe_function() can be used for initiating a call into +JavaScript. napi_call_threadsafe_function() accepts a parameter which controls +whether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API +behaves non-blockingly, returning napi_queue_full if the queue was full, +preventing data from being successfully added to the queue. If set to +napi_tsfn_blocking, the API blocks until space becomes available in the queue. +napi_call_threadsafe_function() never blocks if the thread-safe function was +created with a maximum queue size of 0.

      +

      The actual call into JavaScript is controlled by the callback given via the +call_js_cb parameter. call_js_cb is invoked on the main thread once for each +value that was placed into the queue by a successful call to +napi_call_threadsafe_function(). If such a callback is not given, a default +callback will be used, and the resulting JavaScript call will have no arguments. +The call_js_cb callback receives the JavaScript function to call as a +napi_value in its parameters, as well as the void* context pointer used when +creating the napi_threadsafe_function, and the next data pointer that was +created by one of the secondary threads. The callback can then use an API such +as napi_call_function() to call into JavaScript.

      +

      The callback may also be invoked with env and call_js_cb both set to NULL +to indicate that calls into JavaScript are no longer possible, while items +remain in the queue that may need to be freed. This normally occurs when the +Node.js process exits while there is a thread-safe function still active.

      +

      It is not necessary to call into JavaScript via napi_make_callback() because +N-API runs call_js_cb in a context appropriate for callbacks.

      +

      Reference counting of thread-safe functions#

      +

      Threads can be added to and removed from a napi_threadsafe_function object +during its existence. Thus, in addition to specifying an initial number of +threads upon creation, napi_acquire_threadsafe_function can be called to +indicate that a new thread will start making use of the thread-safe function. +Similarly, napi_release_threadsafe_function can be called to indicate that an +existing thread will stop making use of the thread-safe function.

      +

      napi_threadsafe_function objects are destroyed when every thread which uses +the object has called napi_release_threadsafe_function() or has received a +return status of napi_closing in response to a call to +napi_call_threadsafe_function. The queue is emptied before the +napi_threadsafe_function is destroyed. napi_release_threadsafe_function() +should be the last API call made in conjunction with a given +napi_threadsafe_function, because after the call completes, there is no +guarantee that the napi_threadsafe_function is still allocated. For the same +reason, do not use a thread-safe function +after receiving a return value of napi_closing in response to a call to +napi_call_threadsafe_function. Data associated with the +napi_threadsafe_function can be freed in its napi_finalize callback which +was passed to napi_create_threadsafe_function(). The parameter +initial_thread_count of napi_create_threadsafe_function marks the initial +number of aquisitions of the thread-safe functions, instead of calling +napi_acquire_threadsafe_function multiple times at creation.

      +

      Once the number of threads making use of a napi_threadsafe_function reaches +zero, no further threads can start making use of it by calling +napi_acquire_threadsafe_function(). In fact, all subsequent API calls +associated with it, except napi_release_threadsafe_function(), will return an +error value of napi_closing.

      +

      The thread-safe function can be "aborted" by giving a value of napi_tsfn_abort +to napi_release_threadsafe_function(). This will cause all subsequent APIs +associated with the thread-safe function except +napi_release_threadsafe_function() to return napi_closing even before its +reference count reaches zero. In particular, napi_call_threadsafe_function() +will return napi_closing, thus informing the threads that it is no longer +possible to make asynchronous calls to the thread-safe function. This can be +used as a criterion for terminating the thread. Upon receiving a return value +of napi_closing from napi_call_threadsafe_function() a thread must not use +the thread-safe function anymore because it is no longer guaranteed to +be allocated.

      +

      Deciding whether to keep the process running#

      +

      Similarly to libuv handles, thread-safe functions can be "referenced" and +"unreferenced". A "referenced" thread-safe function will cause the event loop on +the thread on which it is created to remain alive until the thread-safe function +is destroyed. In contrast, an "unreferenced" thread-safe function will not +prevent the event loop from exiting. The APIs napi_ref_threadsafe_function and +napi_unref_threadsafe_function exist for this purpose.

      +

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as +able to be destroyed nor does napi_ref_threadsafe_function prevent it from +being destroyed.

      +

      napi_create_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_create_threadsafe_function(napi_env env,
      +                                napi_value func,
      +                                napi_value async_resource,
      +                                napi_value async_resource_name,
      +                                size_t max_queue_size,
      +                                size_t initial_thread_count,
      +                                void* thread_finalize_data,
      +                                napi_finalize thread_finalize_cb,
      +                                void* context,
      +                                napi_threadsafe_function_call_js call_js_cb,
      +                                napi_threadsafe_function* result);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] func: An optional JavaScript function to call from another thread. It +must be provided if NULL is passed to call_js_cb.
      • +
      • [in] async_resource: An optional object associated with the async work that +will be passed to possible async_hooks init hooks.
      • +
      • [in] async_resource_name: A JavaScript string to provide an identifier for +the kind of resource that is being provided for diagnostic information exposed +by the async_hooks API.
      • +
      • [in] max_queue_size: Maximum size of the queue. 0 for no limit.
      • +
      • [in] initial_thread_count: The initial number of acquisitions, i.e. the +initial number of threads, including the main thread, which will be making use +of this function.
      • +
      • [in] thread_finalize_data: Optional data to be passed to thread_finalize_cb.
      • +
      • [in] thread_finalize_cb: Optional function to call when the +napi_threadsafe_function is being destroyed.
      • +
      • [in] context: Optional data to attach to the resulting +napi_threadsafe_function.
      • +
      • [in] call_js_cb: Optional callback which calls the JavaScript function in +response to a call on a different thread. This callback will be called on the +main thread. If not given, the JavaScript function will be called with no +parameters and with undefined as its this value. +napi_threadsafe_function_call_js provides more details.
      • +
      • [out] result: The asynchronous thread-safe JavaScript function.
      • +
      +

      napi_get_threadsafe_function_context#

      + +
      NAPI_EXTERN napi_status
      +napi_get_threadsafe_function_context(napi_threadsafe_function func,
      +                                     void** result);
      +
        +
      • [in] func: The thread-safe function for which to retrieve the context.
      • +
      • [out] result: The location where to store the context.
      • +
      +

      This API may be called from any thread which makes use of func.

      +

      napi_call_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_call_threadsafe_function(napi_threadsafe_function func,
      +                              void* data,
      +                              napi_threadsafe_function_call_mode is_blocking);
      +
        +
      • [in] func: The asynchronous thread-safe JavaScript function to invoke.
      • +
      • [in] data: Data to send into JavaScript via the callback call_js_cb +provided during the creation of the thread-safe JavaScript function.
      • +
      • [in] is_blocking: Flag whose value can be either napi_tsfn_blocking to +indicate that the call should block if the queue is full or +napi_tsfn_nonblocking to indicate that the call should return immediately +with a status of napi_queue_full whenever the queue is full.
      • +
      +

      This API will return napi_closing if napi_release_threadsafe_function() was +called with abort set to napi_tsfn_abort from any thread. The value is only +added to the queue if the API returns napi_ok.

      +

      This API may be called from any thread which makes use of func.

      +

      napi_acquire_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_acquire_threadsafe_function(napi_threadsafe_function func);
      +
        +
      • [in] func: The asynchronous thread-safe JavaScript function to start making +use of.
      • +
      +

      A thread should call this API before passing func to any other thread-safe +function APIs to indicate that it will be making use of func. This prevents +func from being destroyed when all other threads have stopped making use of +it.

      +

      This API may be called from any thread which will start making use of func.

      +

      napi_release_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_release_threadsafe_function(napi_threadsafe_function func,
      +                                 napi_threadsafe_function_release_mode mode);
      +
        +
      • [in] func: The asynchronous thread-safe JavaScript function whose reference +count to decrement.
      • +
      • [in] mode: Flag whose value can be either napi_tsfn_release to indicate +that the current thread will make no further calls to the thread-safe +function, or napi_tsfn_abort to indicate that in addition to the current +thread, no other thread should make any further calls to the thread-safe +function. If set to napi_tsfn_abort, further calls to +napi_call_threadsafe_function() will return napi_closing, and no further +values will be placed in the queue.
      • +
      +

      A thread should call this API when it stops making use of func. Passing func +to any thread-safe APIs after having called this API has undefined results, as +func may have been destroyed.

      +

      This API may be called from any thread which will stop making use of func.

      +

      napi_ref_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] func: The thread-safe function to reference.
      • +
      +

      This API is used to indicate that the event loop running on the main thread +should not exit until func has been destroyed. Similar to uv_ref it is +also idempotent.

      +

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as +able to be destroyed nor does napi_ref_threadsafe_function prevent it from +being destroyed. napi_acquire_threadsafe_function and +napi_release_threadsafe_function are available for that purpose.

      +

      This API may only be called from the main thread.

      +

      napi_unref_threadsafe_function#

      + +
      NAPI_EXTERN napi_status
      +napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [in] func: The thread-safe function to unreference.
      • +
      +

      This API is used to indicate that the event loop running on the main thread +may exit before func is destroyed. Similar to uv_unref it is also +idempotent.

      +

      This API may only be called from the main thread.

      +

      Miscellaneous utilities#

      +

      node_api_get_module_file_name#

      + +

      Stability: 1 - Experimental

      +
      NAPI_EXTERN napi_status
      +node_api_get_module_file_name(napi_env env, const char** result);
      +
      +
        +
      • [in] env: The environment that the API is invoked under.
      • +
      • [out] result: A URL containing the absolute path of the +location from which the add-on was loaded. For a file on the local +file system it will start with file://. The string is null-terminated and +owned by env and must thus not be modified or freed.
      • +
      +

      result may be an empty string if the add-on loading process fails to establish +the add-on's file name during loading.

      + +
      +
      +
      + + diff --git a/doc/api/n-api.json b/doc/api/n-api.json new file mode 100644 index 0000000000000000000000000000000000000000..e7e626e223156d54f7f1ab1e8db33e031794ce3f --- /dev/null +++ b/doc/api/n-api.json @@ -0,0 +1,3150 @@ +{ + "type": "module", + "source": "doc/api/n-api.md", + "introduced_in": "v8.0.0", + "stability": 2, + "stabilityText": "Stable", + "miscs": [ + { + "textRaw": "N-API", + "name": "N-API", + "introduced_in": "v8.0.0", + "type": "misc", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      N-API (pronounced N as in the letter, followed by API)\nis an API for building native Addons. It is independent from\nthe underlying JavaScript runtime (for example, V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross versions of Node.js. It is intended to insulate Addons from\nchanges in the underlying JavaScript engine and allow modules\ncompiled for one major version to run on later major versions of Node.js without\nrecompilation. The ABI Stability guide provides a more in-depth explanation.

      \n

      Addons are built/packaged with the same approach/tools outlined in the section\ntitled C++ Addons. The only difference is the set of APIs that are used by\nthe native code. Instead of using the V8 or Native Abstractions for Node.js\nAPIs, the functions available in the N-API are used.

      \n

      APIs exposed by N-API are generally used to create and manipulate\nJavaScript values. Concepts and operations generally map to ideas specified\nin the ECMA-262 Language Specification. The APIs have the following\nproperties:

      \n
        \n
      • All N-API calls return a status code of type napi_status. This\nstatus indicates whether the API call succeeded or failed.
      • \n
      • The API's return value is passed via an out parameter.
      • \n
      • All JavaScript values are abstracted behind an opaque type named\nnapi_value.
      • \n
      • In case of an error status code, additional information can be obtained\nusing napi_get_last_error_info. More information can be found in the error\nhandling section Error handling.
      • \n
      \n

      The N-API is a C API that ensures ABI stability across Node.js versions\nand different compiler levels. A C++ API can be easier to use.\nTo support using C++, the project maintains a\nC++ wrapper module called node-addon-api.\nThis wrapper provides an inlineable C++ API. Binaries built\nwith node-addon-api will depend on the symbols for the N-API C-based\nfunctions exported by Node.js. node-addon-api is a more\nefficient way to write code that calls N-API. Take, for example, the\nfollowing node-addon-api code. The first section shows the\nnode-addon-api code and the second section shows what actually gets\nused in the addon.

      \n
      Object obj = Object::New(env);\nobj[\"foo\"] = String::New(env, \"bar\");\n
      \n
      napi_status status;\nnapi_value object, string;\nstatus = napi_create_object(env, &object);\nif (status != napi_ok) {\n  napi_throw_error(env, ...);\n  return;\n}\n\nstatus = napi_create_string_utf8(env, \"bar\", NAPI_AUTO_LENGTH, &string);\nif (status != napi_ok) {\n  napi_throw_error(env, ...);\n  return;\n}\n\nstatus = napi_set_named_property(env, object, \"foo\", string);\nif (status != napi_ok) {\n  napi_throw_error(env, ...);\n  return;\n}\n
      \n

      The end result is that the addon only uses the exported C APIs. As a result,\nit still gets the benefits of the ABI stability provided by the C API.

      \n

      When using node-addon-api instead of the C APIs, start with the API docs\nfor node-addon-api.

      \n

      The N-API Resource offers an\nexcellent orientation and tips for developers just getting started with N-API\nand node-addon-api.

      ", + "miscs": [ + { + "textRaw": "Implications of ABI stability", + "name": "implications_of_abi_stability", + "desc": "

      Although N-API provides an ABI stability guarantee, other parts of Node.js do\nnot, and any external libraries used from the addon may not. In particular,\nnone of the following APIs provide an ABI stability guarantee across major\nversions:

      \n
        \n
      • \n

        the Node.js C++ APIs available via any of

        \n
        #include <node.h>\n#include <node_buffer.h>\n#include <node_version.h>\n#include <node_object_wrap.h>\n
        \n
      • \n
      • \n

        the libuv APIs which are also included with Node.js and available via

        \n
        #include <uv.h>\n
        \n
      • \n
      • \n

        the V8 API available via

        \n
        #include <v8.h>\n
        \n
      • \n
      \n

      Thus, for an addon to remain ABI-compatible across Node.js major versions, it\nmust use N-API exclusively by restricting itself to using

      \n
      #include <node_api.h>\n
      \n

      and by checking, for all external libraries that it uses, that the external\nlibrary makes ABI stability guarantees similar to N-API.

      ", + "type": "misc", + "displayName": "Implications of ABI stability" + }, + { + "textRaw": "Building", + "name": "building", + "desc": "

      Unlike modules written in JavaScript, developing and deploying Node.js\nnative addons using N-API requires an additional set of tools. Besides the\nbasic tools required to develop for Node.js, the native addon developer\nrequires a toolchain that can compile C and C++ code into a binary. In\naddition, depending upon how the native addon is deployed, the user of\nthe native addon will also need to have a C/C++ toolchain installed.

      \n

      For Linux developers, the necessary C/C++ toolchain packages are readily\navailable. GCC is widely used in the Node.js community to build and\ntest across a variety of platforms. For many developers, the LLVM\ncompiler infrastructure is also a good choice.

      \n

      For Mac developers, Xcode offers all the required compiler tools.\nHowever, it is not necessary to install the entire Xcode IDE. The following\ncommand installs the necessary toolchain:

      \n
      xcode-select --install\n
      \n

      For Windows developers, Visual Studio offers all the required compiler\ntools. However, it is not necessary to install the entire Visual Studio\nIDE. The following command installs the necessary toolchain:

      \n
      npm install --global windows-build-tools\n
      \n

      The sections below describe the additional tools available for developing\nand deploying Node.js native addons.

      ", + "modules": [ + { + "textRaw": "Build tools", + "name": "build_tools", + "desc": "

      Both the tools listed here require that users of the native\naddon have a C/C++ toolchain installed in order to successfully install\nthe native addon.

      ", + "modules": [ + { + "textRaw": "node-gyp", + "name": "node-gyp", + "desc": "

      node-gyp is a build system based on Google's GYP tool and comes\nbundled with npm. GYP, and therefore node-gyp, requires that Python be\ninstalled.

      \n

      Historically, node-gyp has been the tool of choice for building native\naddons. It has widespread adoption and documentation. However, some\ndevelopers have run into limitations in node-gyp.

      ", + "type": "module", + "displayName": "node-gyp" + } + ], + "properties": [ + { + "textRaw": "CMake.js", + "name": "js", + "desc": "

      CMake.js is an alternative build system based on CMake.

      \n

      CMake.js is a good choice for projects that already use CMake or for\ndevelopers affected by limitations in node-gyp.

      " + } + ], + "type": "module", + "displayName": "Build tools" + }, + { + "textRaw": "Uploading precompiled binaries", + "name": "uploading_precompiled_binaries", + "desc": "

      The three tools listed here permit native addon developers and maintainers\nto create and upload binaries to public or private servers. These tools are\ntypically integrated with CI/CD build systems like Travis CI and\nAppVeyor to build and upload binaries for a variety of platforms and\narchitectures. These binaries are then available for download by users who\ndo not need to have a C/C++ toolchain installed.

      ", + "modules": [ + { + "textRaw": "node-pre-gyp", + "name": "node-pre-gyp", + "desc": "

      node-pre-gyp is a tool based on node-gyp that adds the ability to\nupload binaries to a server of the developer's choice. node-pre-gyp has\nparticularly good support for uploading binaries to Amazon S3.

      ", + "type": "module", + "displayName": "node-pre-gyp" + }, + { + "textRaw": "prebuild", + "name": "prebuild", + "desc": "

      prebuild is a tool that supports builds using either node-gyp or\nCMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild\nuploads binaries only to GitHub releases. prebuild is a good choice for\nGitHub projects using CMake.js.

      ", + "type": "module", + "displayName": "prebuild" + }, + { + "textRaw": "prebuildify", + "name": "prebuildify", + "desc": "

      prebuildify is a tool based on node-gyp. The advantage of prebuildify is\nthat the built binaries are bundled with the native module when it's\nuploaded to npm. The binaries are downloaded from npm and are immediately\navailable to the module user when the native module is installed.

      ", + "type": "module", + "displayName": "prebuildify" + } + ], + "type": "module", + "displayName": "Uploading precompiled binaries" + } + ], + "type": "misc", + "displayName": "Building" + }, + { + "textRaw": "Usage", + "name": "usage", + "desc": "

      In order to use the N-API functions, include the file node_api.h which is\nlocated in the src directory in the node development tree:

      \n
      #include <node_api.h>\n
      \n

      This will opt into the default NAPI_VERSION for the given release of Node.js.\nIn order to ensure compatibility with specific versions of N-API, the version\ncan be specified explicitly when including the header:

      \n
      #define NAPI_VERSION 3\n#include <node_api.h>\n
      \n

      This restricts the N-API surface to just the functionality that was available in\nthe specified (and earlier) versions.

      \n

      Some of the N-API surface is experimental and requires explicit opt-in:

      \n
      #define NAPI_EXPERIMENTAL\n#include <node_api.h>\n
      \n

      In this case the entire API surface, including any experimental APIs, will be\navailable to the module code.

      ", + "type": "misc", + "displayName": "Usage" + }, + { + "textRaw": "N-API version matrix", + "name": "n-api_version_matrix", + "desc": "

      N-API versions are additive and versioned independently from Node.js.\nVersion 4 is an extension to version 3 in that it has all of the APIs\nfrom version 3 with some additions. This means that it is not necessary\nto recompile for new versions of Node.js which are\nlisted as supporting a later version.

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      123456
      v6.xv6.14.2*
      v8.xv8.0.0*v8.10.0*v8.11.2v8.16.0
      v9.xv9.0.0*v9.3.0*v9.11.0*
      v10.xv10.0.0v10.0.0v10.0.0v10.16.0v10.17.0v10.20.0
      v11.xv11.0.0v11.0.0v11.0.0v11.8.0
      v12.xv12.0.0v12.0.0v12.0.0v12.0.0v12.11.0v12.17.0
      v13.xv13.0.0v13.0.0v13.0.0v13.0.0v13.0.0
      v14.xv14.0.0v14.0.0v14.0.0v14.0.0v14.0.0v14.0.0
      \n

      * Indicates that the N-API version was released as experimental

      \n

      Each API documented for N-API will have a header named added in:, and APIs\nwhich are stable will have the additional header N-API version:.\nAPIs are directly usable when using a Node.js version which supports\nthe N-API version shown in N-API version: or higher.\nWhen using a Node.js version that does not support the\nN-API version: listed or if there is no N-API version: listed,\nthen the API will only be available if\n#define NAPI_EXPERIMENTAL precedes the inclusion of node_api.h\nor js_native_api.h. If an API appears not to be available on\na version of Node.js which is later than the one shown in added in: then\nthis is most likely the reason for the apparent absence.

      \n

      The N-APIs associated strictly with accessing ECMAScript features from native\ncode can be found separately in js_native_api.h and js_native_api_types.h.\nThe APIs defined in these headers are included in node_api.h and\nnode_api_types.h. The headers are structured in this way in order to allow\nimplementations of N-API outside of Node.js. For those implementations the\nNode.js specific APIs may not be applicable.

      \n

      The Node.js-specific parts of an addon can be separated from the code that\nexposes the actual functionality to the JavaScript environment so that the\nlatter may be used with multiple implementations of N-API. In the example below,\naddon.c and addon.h refer only to js_native_api.h. This ensures that\naddon.c can be reused to compile against either the Node.js implementation of\nN-API or any implementation of N-API outside of Node.js.

      \n

      addon_node.c is a separate file that contains the Node.js specific entry point\nto the addon and which instantiates the addon by calling into addon.c when the\naddon is loaded into a Node.js environment.

      \n
      // addon.h\n#ifndef _ADDON_H_\n#define _ADDON_H_\n#include <js_native_api.h>\nnapi_value create_addon(napi_env env);\n#endif  // _ADDON_H_\n
      \n
      // addon.c\n#include \"addon.h\"\n\n#define NAPI_CALL(env, call)                                      \\\n  do {                                                            \\\n    napi_status status = (call);                                  \\\n    if (status != napi_ok) {                                      \\\n      const napi_extended_error_info* error_info = NULL;          \\\n      napi_get_last_error_info((env), &error_info);               \\\n      bool is_pending;                                            \\\n      napi_is_exception_pending((env), &is_pending);              \\\n      if (!is_pending) {                                          \\\n        const char* message = (error_info->error_message == NULL) \\\n            ? \"empty error message\"                               \\\n            : error_info->error_message;                          \\\n        napi_throw_error((env), NULL, message);                   \\\n        return NULL;                                              \\\n      }                                                           \\\n    }                                                             \\\n  } while(0)\n\nstatic napi_value\nDoSomethingUseful(napi_env env, napi_callback_info info) {\n  // Do something useful.\n  return NULL;\n}\n\nnapi_value create_addon(napi_env env) {\n  napi_value result;\n  NAPI_CALL(env, napi_create_object(env, &result));\n\n  napi_value exported_function;\n  NAPI_CALL(env, napi_create_function(env,\n                                      \"doSomethingUseful\",\n                                      NAPI_AUTO_LENGTH,\n                                      DoSomethingUseful,\n                                      NULL,\n                                      &exported_function));\n\n  NAPI_CALL(env, napi_set_named_property(env,\n                                         result,\n                                         \"doSomethingUseful\",\n                                         exported_function));\n\n  return result;\n}\n
      \n
      // addon_node.c\n#include <node_api.h>\n#include \"addon.h\"\n\nNAPI_MODULE_INIT() {\n  // This function body is expected to return a `napi_value`.\n  // The variables `napi_env env` and `napi_value exports` may be used within\n  // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.\n  return create_addon(env);\n}\n
      ", + "type": "misc", + "displayName": "N-API version matrix" + }, + { + "textRaw": "Environment life cycle APIs", + "name": "environment_life_cycle_apis", + "desc": "

      Section 8.7 of the ECMAScript Language Specification defines the concept\nof an \"Agent\" as a self-contained environment in which JavaScript code runs.\nMultiple such Agents may be started and terminated either concurrently or in\nsequence by the process.

      \n

      A Node.js environment corresponds to an ECMAScript Agent. In the main process,\nan environment is created at startup, and additional environments can be created\non separate threads to serve as worker threads. When Node.js is embedded in\nanother application, the main thread of the application may also construct and\ndestroy a Node.js environment multiple times during the life cycle of the\napplication process such that each Node.js environment created by the\napplication may, in turn, during its life cycle create and destroy additional\nenvironments as worker threads.

      \n

      From the perspective of a native addon this means that the bindings it provides\nmay be called multiple times, from multiple contexts, and even concurrently from\nmultiple threads.

      \n

      Native addons may need to allocate global state which they use during\ntheir entire life cycle such that the state must be unique to each instance of\nthe addon.

      \n

      To this end, N-API provides a way to allocate data such that its life cycle is\ntied to the life cycle of the Agent.

      ", + "modules": [ + { + "textRaw": "napi_set_instance_data", + "name": "napi_set_instance_data", + "meta": { + "added": [ + "v12.8.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_instance_data(napi_env env,\n                                   void* data,\n                                   napi_finalize finalize_cb,\n                                   void* finalize_hint);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] data: The data item to make available to bindings of this instance.
      • \n
      • [in] finalize_cb: The function to call when the environment is being torn\ndown. The function receives data so that it might free it.\nnapi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API associates data with the currently running Agent. data can later\nbe retrieved using napi_get_instance_data(). Any existing data associated with\nthe currently running Agent which was set by means of a previous call to\nnapi_set_instance_data() will be overwritten. If a finalize_cb was provided\nby the previous call, it will not be called.

      ", + "type": "module", + "displayName": "napi_set_instance_data" + }, + { + "textRaw": "napi_get_instance_data", + "name": "napi_get_instance_data", + "meta": { + "added": [ + "v12.8.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_instance_data(napi_env env,\n                                   void** data);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [out] data: The data item that was previously associated with the currently\nrunning Agent by a call to napi_set_instance_data().
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API retrieves data that was previously associated with the currently\nrunning Agent via napi_set_instance_data(). If no data is set, the call will\nsucceed and data will be set to NULL.

      ", + "type": "module", + "displayName": "napi_get_instance_data" + } + ], + "type": "misc", + "displayName": "Environment life cycle APIs" + }, + { + "textRaw": "Basic N-API data types", + "name": "basic_n-api_data_types", + "desc": "

      N-API exposes the following fundamental datatypes as abstractions that are\nconsumed by the various APIs. These APIs should be treated as opaque,\nintrospectable only with other N-API calls.

      ", + "modules": [ + { + "textRaw": "napi_status", + "name": "napi_status", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Integral status code indicating the success or failure of a N-API call.\nCurrently, the following status codes are supported.

      \n
      typedef enum {\n  napi_ok,\n  napi_invalid_arg,\n  napi_object_expected,\n  napi_string_expected,\n  napi_name_expected,\n  napi_function_expected,\n  napi_number_expected,\n  napi_boolean_expected,\n  napi_array_expected,\n  napi_generic_failure,\n  napi_pending_exception,\n  napi_cancelled,\n  napi_escape_called_twice,\n  napi_handle_scope_mismatch,\n  napi_callback_scope_mismatch,\n  napi_queue_full,\n  napi_closing,\n  napi_bigint_expected,\n  napi_date_expected,\n  napi_arraybuffer_expected,\n  napi_detachable_arraybuffer_expected,\n} napi_status;\n
      \n

      If additional information is required upon an API returning a failed status,\nit can be obtained by calling napi_get_last_error_info.

      ", + "type": "module", + "displayName": "napi_status" + }, + { + "textRaw": "napi_extended_error_info", + "name": "napi_extended_error_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      typedef struct {\n  const char* error_message;\n  void* engine_reserved;\n  uint32_t engine_error_code;\n  napi_status error_code;\n} napi_extended_error_info;\n
      \n
        \n
      • error_message: UTF8-encoded string containing a VM-neutral description of\nthe error.
      • \n
      • engine_reserved: Reserved for VM-specific error details. This is currently\nnot implemented for any VM.
      • \n
      • engine_error_code: VM-specific error code. This is currently\nnot implemented for any VM.
      • \n
      • error_code: The N-API status code that originated with the last error.
      • \n
      \n

      See the Error handling section for additional information.

      ", + "type": "module", + "displayName": "napi_extended_error_info" + }, + { + "textRaw": "napi_env", + "name": "napi_env", + "desc": "

      napi_env is used to represent a context that the underlying N-API\nimplementation can use to persist VM-specific state. This structure is passed\nto native functions when they're invoked, and it must be passed back when\nmaking N-API calls. Specifically, the same napi_env that was passed in when\nthe initial native function was called must be passed to any subsequent\nnested N-API calls. Caching the napi_env for the purpose of general reuse,\nand passing the napi_env between instances of the same addon running on\ndifferent Worker threads is not allowed. The napi_env becomes invalid\nwhen an instance of a native addon is unloaded. Notification of this event is\ndelivered through the callbacks given to napi_add_env_cleanup_hook and\nnapi_set_instance_data.

      ", + "type": "module", + "displayName": "napi_env" + }, + { + "textRaw": "napi_value", + "name": "napi_value", + "desc": "

      This is an opaque pointer that is used to represent a JavaScript value.

      ", + "type": "module", + "displayName": "napi_value" + }, + { + "textRaw": "napi_threadsafe_function", + "name": "napi_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      This is an opaque pointer that represents a JavaScript function which can be\ncalled asynchronously from multiple threads via\nnapi_call_threadsafe_function().

      ", + "type": "module", + "displayName": "napi_threadsafe_function" + }, + { + "textRaw": "napi_threadsafe_function_release_mode", + "name": "napi_threadsafe_function_release_mode", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      A value to be given to napi_release_threadsafe_function() to indicate whether\nthe thread-safe function is to be closed immediately (napi_tsfn_abort) or\nmerely released (napi_tsfn_release) and thus available for subsequent use via\nnapi_acquire_threadsafe_function() and napi_call_threadsafe_function().

      \n
      typedef enum {\n  napi_tsfn_release,\n  napi_tsfn_abort\n} napi_threadsafe_function_release_mode;\n
      ", + "type": "module", + "displayName": "napi_threadsafe_function_release_mode" + }, + { + "textRaw": "napi_threadsafe_function_call_mode", + "name": "napi_threadsafe_function_call_mode", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      A value to be given to napi_call_threadsafe_function() to indicate whether\nthe call should block whenever the queue associated with the thread-safe\nfunction is full.

      \n
      typedef enum {\n  napi_tsfn_nonblocking,\n  napi_tsfn_blocking\n} napi_threadsafe_function_call_mode;\n
      ", + "type": "module", + "displayName": "napi_threadsafe_function_call_mode" + }, + { + "textRaw": "N-API memory management types", + "name": "n-api_memory_management_types", + "modules": [ + { + "textRaw": "napi_handle_scope", + "name": "napi_handle_scope", + "desc": "

      This is an abstraction used to control and modify the lifetime of objects\ncreated within a particular scope. In general, N-API values are created within\nthe context of a handle scope. When a native method is called from\nJavaScript, a default handle scope will exist. If the user does not explicitly\ncreate a new handle scope, N-API values will be created in the default handle\nscope. For any invocations of code outside the execution of a native method\n(for instance, during a libuv callback invocation), the module is required to\ncreate a scope before invoking any functions that can result in the creation\nof JavaScript values.

      \n

      Handle scopes are created using napi_open_handle_scope and are destroyed\nusing napi_close_handle_scope. Closing the scope can indicate to the GC\nthat all napi_values created during the lifetime of the handle scope are no\nlonger referenced from the current stack frame.

      \n

      For more details, review the Object lifetime management.

      ", + "type": "module", + "displayName": "napi_handle_scope" + }, + { + "textRaw": "napi_escapable_handle_scope", + "name": "napi_escapable_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Escapable handle scopes are a special type of handle scope to return values\ncreated within a particular handle scope to a parent scope.

      ", + "type": "module", + "displayName": "napi_escapable_handle_scope" + }, + { + "textRaw": "napi_ref", + "name": "napi_ref", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      This is the abstraction to use to reference a napi_value. This allows for\nusers to manage the lifetimes of JavaScript values, including defining their\nminimum lifetimes explicitly.

      \n

      For more details, review the Object lifetime management.

      ", + "type": "module", + "displayName": "napi_ref" + }, + { + "textRaw": "napi_type_tag", + "name": "napi_type_tag", + "meta": { + "added": [ + "v12.19.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "

      A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID\nwith which JavaScript objects can be \"tagged\" in order to ensure that they are\nof a certain type. This is a stronger check than napi_instanceof, because\nthe latter can report a false positive if the object's prototype has been\nmanipulated. Type-tagging is most useful in conjunction with napi_wrap\nbecause it ensures that the pointer retrieved from a wrapped object can be\nsafely cast to the native type corresponding to the type tag that had been\npreviously applied to the JavaScript object.

      \n
      typedef struct {\n  uint64_t lower;\n  uint64_t upper;\n} napi_type_tag;\n
      ", + "type": "module", + "displayName": "napi_type_tag" + }, + { + "textRaw": "napi_async_cleanup_hook_handle", + "name": "napi_async_cleanup_hook_handle", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      An opaque value returned by napi_add_async_cleanup_hook. It must be passed\nto napi_remove_async_cleanup_hook when the chain of asynchronous cleanup\nevents completes.

      ", + "type": "module", + "displayName": "napi_async_cleanup_hook_handle" + } + ], + "type": "module", + "displayName": "N-API memory management types" + }, + { + "textRaw": "N-API callback types", + "name": "n-api_callback_types", + "modules": [ + { + "textRaw": "napi_callback_info", + "name": "napi_callback_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Opaque datatype that is passed to a callback function. It can be used for\ngetting additional information about the context in which the callback was\ninvoked.

      ", + "type": "module", + "displayName": "napi_callback_info" + }, + { + "textRaw": "napi_callback", + "name": "napi_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer type for user-provided native functions which are to be\nexposed to JavaScript via N-API. Callback functions should satisfy the\nfollowing signature:

      \n
      typedef napi_value (*napi_callback)(napi_env, napi_callback_info);\n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside a napi_callback is not necessary.

      ", + "type": "module", + "displayName": "napi_callback" + }, + { + "textRaw": "napi_finalize", + "name": "napi_finalize", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer type for add-on provided functions that allow the user to be\nnotified when externally-owned data is ready to be cleaned up because the\nobject with which it was associated with, has been garbage-collected. The user\nmust provide a function satisfying the following signature which would get\ncalled upon the object's collection. Currently, napi_finalize can be used for\nfinding out when objects that have external data are collected.

      \n
      typedef void (*napi_finalize)(napi_env env,\n                              void* finalize_data,\n                              void* finalize_hint);\n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

      ", + "type": "module", + "displayName": "napi_finalize" + }, + { + "textRaw": "napi_async_execute_callback", + "name": "napi_async_execute_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_async_execute_callback)(napi_env env, void* data);\n
      \n

      Implementations of this function must avoid making N-API calls that execute\nJavaScript or interact with JavaScript objects. N-API calls should be in the\nnapi_async_complete_callback instead. Do not use the napi_env parameter as\nit will likely result in execution of JavaScript.

      ", + "type": "module", + "displayName": "napi_async_execute_callback" + }, + { + "textRaw": "napi_async_complete_callback", + "name": "napi_async_complete_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_async_complete_callback)(napi_env env,\n                                             napi_status status,\n                                             void* data);\n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

      ", + "type": "module", + "displayName": "napi_async_complete_callback" + }, + { + "textRaw": "napi_threadsafe_function_call_js", + "name": "napi_threadsafe_function_call_js", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "

      Function pointer used with asynchronous thread-safe function calls. The callback\nwill be called on the main thread. Its purpose is to use a data item arriving\nvia the queue from one of the secondary threads to construct the parameters\nnecessary for a call into JavaScript, usually via napi_call_function, and then\nmake the call into JavaScript.

      \n

      The data arriving from the secondary thread via the queue is given in the data\nparameter and the JavaScript function to call is given in the js_callback\nparameter.

      \n

      N-API sets up the environment prior to calling this callback, so it is\nsufficient to call the JavaScript function via napi_call_function rather than\nvia napi_make_callback.

      \n

      Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_threadsafe_function_call_js)(napi_env env,\n                                                 napi_value js_callback,\n                                                 void* context,\n                                                 void* data);\n
      \n
        \n
      • [in] env: The environment to use for API calls, or NULL if the thread-safe\nfunction is being torn down and data may need to be freed.
      • \n
      • [in] js_callback: The JavaScript function to call, or NULL if the\nthread-safe function is being torn down and data may need to be freed. It\nmay also be NULL if the thread-safe function was created without\njs_callback.
      • \n
      • [in] context: The optional data with which the thread-safe function was\ncreated.
      • \n
      • [in] data: Data created by the secondary thread. It is the responsibility of\nthe callback to convert this native data to JavaScript values (with N-API\nfunctions) that can be passed as parameters when js_callback is invoked.\nThis pointer is managed entirely by the threads and this callback. Thus this\ncallback should free the data.
      • \n
      \n

      Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

      ", + "type": "module", + "displayName": "napi_threadsafe_function_call_js" + }, + { + "textRaw": "napi_async_cleanup_hook", + "name": "napi_async_cleanup_hook", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      Function pointer used with napi_add_async_cleanup_hook. It will be called\nwhen the environment is being torn down.

      \n

      Callback functions must satisfy the following signature:

      \n
      typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,\n                                        void* data);\n
      \n\n

      The body of the function should initiate the asynchronous cleanup actions at the\nend of which handle must be passed in a call to\nnapi_remove_async_cleanup_hook.

      ", + "type": "module", + "displayName": "napi_async_cleanup_hook" + } + ], + "type": "module", + "displayName": "N-API callback types" + } + ], + "type": "misc", + "displayName": "Basic N-API data types" + }, + { + "textRaw": "Error handling", + "name": "error_handling", + "desc": "

      N-API uses both return values and JavaScript exceptions for error handling.\nThe following sections explain the approach for each case.

      ", + "modules": [ + { + "textRaw": "Return values", + "name": "return_values", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "

      All of the N-API functions share the same error handling pattern. The\nreturn type of all API functions is napi_status.

      \n

      The return value will be napi_ok if the request was successful and\nno uncaught JavaScript exception was thrown. If an error occurred AND\nan exception was thrown, the napi_status value for the error\nwill be returned. If an exception was thrown, and no error occurred,\nnapi_pending_exception will be returned.

      \n

      In cases where a return value other than napi_ok or\nnapi_pending_exception is returned, napi_is_exception_pending\nmust be called to check if an exception is pending.\nSee the section on exceptions for more details.

      \n

      The full set of possible napi_status values is defined\nin napi_api_types.h.

      \n

      The napi_status return value provides a VM-independent representation of\nthe error which occurred. In some cases it is useful to be able to get\nmore detailed information, including a string representing the error as well as\nVM (engine)-specific information.

      \n

      In order to retrieve this information napi_get_last_error_info\nis provided which returns a napi_extended_error_info structure.\nThe format of the napi_extended_error_info structure is as follows:

      \n
      typedef struct napi_extended_error_info {\n  const char* error_message;\n  void* engine_reserved;\n  uint32_t engine_error_code;\n  napi_status error_code;\n};\n
      \n
        \n
      • error_message: Textual representation of the error that occurred.
      • \n
      • engine_reserved: Opaque handle reserved for engine use only.
      • \n
      • engine_error_code: VM specific error code.
      • \n
      • error_code: n-api status code for the last error.
      • \n
      \n

      napi_get_last_error_info returns the information for the last\nN-API call that was made.

      \n

      Do not rely on the content or format of any of the extended information as it\nis not subject to SemVer and may change at any time. It is intended only for\nlogging purposes.

      ", + "modules": [ + { + "textRaw": "napi_get_last_error_info", + "name": "napi_get_last_error_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status\nnapi_get_last_error_info(napi_env env,\n                         const napi_extended_error_info** result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: The napi_extended_error_info structure with more\ninformation about the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API retrieves a napi_extended_error_info structure with information\nabout the last error that occurred.

      \n

      The content of the napi_extended_error_info returned is only valid up until\nan n-api function is called on the same env.

      \n

      Do not rely on the content or format of any of the extended information as it\nis not subject to SemVer and may change at any time. It is intended only for\nlogging purposes.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_get_last_error_info" + } + ], + "type": "module", + "displayName": "Return values" + }, + { + "textRaw": "Exceptions", + "name": "exceptions", + "desc": "

      Any N-API function call may result in a pending JavaScript exception. This is\nthe case for any of the API functions, even those that may not cause the\nexecution of JavaScript.

      \n

      If the napi_status returned by a function is napi_ok then no\nexception is pending and no additional action is required. If the\nnapi_status returned is anything other than napi_ok or\nnapi_pending_exception, in order to try to recover and continue\ninstead of simply returning immediately, napi_is_exception_pending\nmust be called in order to determine if an exception is pending or not.

      \n

      In many cases when an N-API function is called and an exception is\nalready pending, the function will return immediately with a\nnapi_status of napi_pending_exception. However, this is not the case\nfor all functions. N-API allows a subset of the functions to be\ncalled to allow for some minimal cleanup before returning to JavaScript.\nIn that case, napi_status will reflect the status for the function. It\nwill not reflect previous pending exceptions. To avoid confusion, check\nthe error status after every function call.

      \n

      When an exception is pending one of two approaches can be employed.

      \n

      The first approach is to do any appropriate cleanup and then return so that\nexecution will return to JavaScript. As part of the transition back to\nJavaScript, the exception will be thrown at the point in the JavaScript\ncode where the native method was invoked. The behavior of most N-API calls\nis unspecified while an exception is pending, and many will simply return\nnapi_pending_exception, so do as little as possible and then return to\nJavaScript where the exception can be handled.

      \n

      The second approach is to try to handle the exception. There will be cases\nwhere the native code can catch the exception, take the appropriate action,\nand then continue. This is only recommended in specific cases\nwhere it is known that the exception can be safely handled. In these\ncases napi_get_and_clear_last_exception can be used to get and\nclear the exception. On success, result will contain the handle to\nthe last JavaScript Object thrown. If it is determined, after\nretrieving the exception, the exception cannot be handled after all\nit can be re-thrown it with napi_throw where error is the\nJavaScript Error object to be thrown.

      \n

      The following utility functions are also available in case native code\nneeds to throw an exception or determine if a napi_value is an instance\nof a JavaScript Error object: napi_throw_error,\nnapi_throw_type_error, napi_throw_range_error and\nnapi_is_error.

      \n

      The following utility functions are also available in case native\ncode needs to create an Error object: napi_create_error,\nnapi_create_type_error, and napi_create_range_error,\nwhere result is the napi_value that refers to the newly created\nJavaScript Error object.

      \n

      The Node.js project is adding error codes to all of the errors\ngenerated internally. The goal is for applications to use these\nerror codes for all error checking. The associated error messages\nwill remain, but will only be meant to be used for logging and\ndisplay with the expectation that the message can change without\nSemVer applying. In order to support this model with N-API, both\nin internal functionality and for module specific functionality\n(as its good practice), the throw_ and create_ functions\ntake an optional code parameter which is the string for the code\nto be added to the error object. If the optional parameter is NULL\nthen no code will be associated with the error. If a code is provided,\nthe name associated with the error is also updated to be:

      \n
      originalName [code]\n
      \n

      where originalName is the original name associated with the error\nand code is the code that was provided. For example, if the code\nis 'ERR_ERROR_1' and a TypeError is being created the name will be:

      \n
      TypeError [ERR_ERROR_1]\n
      ", + "modules": [ + { + "textRaw": "napi_throw", + "name": "napi_throw", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] error: The JavaScript value to be thrown.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws the JavaScript value provided.

      ", + "type": "module", + "displayName": "napi_throw" + }, + { + "textRaw": "napi_throw_error", + "name": "napi_throw_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw_error(napi_env env,\n                                         const char* code,\n                                         const char* msg);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional error code to be set on the error.
      • \n
      • [in] msg: C string representing the text to be associated with the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws a JavaScript Error with the text provided.

      ", + "type": "module", + "displayName": "napi_throw_error" + }, + { + "textRaw": "napi_throw_type_error", + "name": "napi_throw_type_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,\n                                              const char* code,\n                                              const char* msg);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional error code to be set on the error.
      • \n
      • [in] msg: C string representing the text to be associated with the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws a JavaScript TypeError with the text provided.

      ", + "type": "module", + "displayName": "napi_throw_type_error" + }, + { + "textRaw": "napi_throw_range_error", + "name": "napi_throw_range_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,\n                                               const char* code,\n                                               const char* msg);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional error code to be set on the error.
      • \n
      • [in] msg: C string representing the text to be associated with the error.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API throws a JavaScript RangeError with the text provided.

      ", + "type": "module", + "displayName": "napi_throw_range_error" + }, + { + "textRaw": "napi_is_error", + "name": "napi_is_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_is_error(napi_env env,\n                                      napi_value value,\n                                      bool* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The napi_value to be checked.
      • \n
      • [out] result: Boolean value that is set to true if napi_value represents\nan error, false otherwise.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API queries a napi_value to check if it represents an error object.

      ", + "type": "module", + "displayName": "napi_is_error" + }, + { + "textRaw": "napi_create_error", + "name": "napi_create_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_error(napi_env env,\n                                          napi_value code,\n                                          napi_value msg,\n                                          napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional napi_value with the string for the error code to be\nassociated with the error.
      • \n
      • [in] msg: napi_value that references a JavaScript String to be used as\nthe message for the Error.
      • \n
      • [out] result: napi_value representing the error created.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns a JavaScript Error with the text provided.

      ", + "type": "module", + "displayName": "napi_create_error" + }, + { + "textRaw": "napi_create_type_error", + "name": "napi_create_type_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_type_error(napi_env env,\n                                               napi_value code,\n                                               napi_value msg,\n                                               napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional napi_value with the string for the error code to be\nassociated with the error.
      • \n
      • [in] msg: napi_value that references a JavaScript String to be used as\nthe message for the Error.
      • \n
      • [out] result: napi_value representing the error created.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns a JavaScript TypeError with the text provided.

      ", + "type": "module", + "displayName": "napi_create_type_error" + }, + { + "textRaw": "napi_create_range_error", + "name": "napi_create_range_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_range_error(napi_env env,\n                                                napi_value code,\n                                                napi_value msg,\n                                                napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] code: Optional napi_value with the string for the error code to be\nassociated with the error.
      • \n
      • [in] msg: napi_value that references a JavaScript String to be used as\nthe message for the Error.
      • \n
      • [out] result: napi_value representing the error created.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns a JavaScript RangeError with the text provided.

      ", + "type": "module", + "displayName": "napi_create_range_error" + }, + { + "textRaw": "napi_get_and_clear_last_exception", + "name": "napi_get_and_clear_last_exception", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_and_clear_last_exception(napi_env env,\n                                              napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: The exception if one is pending, NULL otherwise.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_get_and_clear_last_exception" + }, + { + "textRaw": "napi_is_exception_pending", + "name": "napi_is_exception_pending", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_exception_pending(napi_env env, bool* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: Boolean value that is set to true if an exception is pending.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_is_exception_pending" + }, + { + "textRaw": "napi_fatal_exception", + "name": "napi_fatal_exception", + "meta": { + "added": [ + "v9.10.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      napi_status napi_fatal_exception(napi_env env, napi_value err);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] err: The error that is passed to 'uncaughtException'.
      • \n
      \n

      Trigger an 'uncaughtException' in JavaScript. Useful if an async\ncallback throws an exception with no way to recover.

      ", + "type": "module", + "displayName": "napi_fatal_exception" + } + ], + "type": "module", + "displayName": "Exceptions" + }, + { + "textRaw": "Fatal errors", + "name": "fatal_errors", + "desc": "

      In the event of an unrecoverable error in a native module, a fatal error can be\nthrown to immediately terminate the process.

      ", + "modules": [ + { + "textRaw": "napi_fatal_error", + "name": "napi_fatal_error", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_NO_RETURN void napi_fatal_error(const char* location,\n                                                 size_t location_len,\n                                                 const char* message,\n                                                 size_t message_len);\n
      \n
        \n
      • [in] location: Optional location at which the error occurred.
      • \n
      • [in] location_len: The length of the location in bytes, or\nNAPI_AUTO_LENGTH if it is null-terminated.
      • \n
      • [in] message: The message associated with the error.
      • \n
      • [in] message_len: The length of the message in bytes, or NAPI_AUTO_LENGTH\nif it is null-terminated.
      • \n
      \n

      The function call does not return, the process will be terminated.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_fatal_error" + } + ], + "type": "module", + "displayName": "Fatal errors" + } + ], + "type": "misc", + "displayName": "Error handling" + }, + { + "textRaw": "Object lifetime management", + "name": "object_lifetime_management", + "desc": "

      As N-API calls are made, handles to objects in the heap for the underlying\nVM may be returned as napi_values. These handles must hold the\nobjects 'live' until they are no longer required by the native code,\notherwise the objects could be collected before the native code was\nfinished using them.

      \n

      As object handles are returned they are associated with a\n'scope'. The lifespan for the default scope is tied to the lifespan\nof the native method call. The result is that, by default, handles\nremain valid and the objects associated with these handles will be\nheld live for the lifespan of the native method call.

      \n

      In many cases, however, it is necessary that the handles remain valid for\neither a shorter or longer lifespan than that of the native method.\nThe sections which follow describe the N-API functions that can be used\nto change the handle lifespan from the default.

      ", + "modules": [ + { + "textRaw": "Making handle lifespan shorter than that of the native method", + "name": "making_handle_lifespan_shorter_than_that_of_the_native_method", + "desc": "

      It is often necessary to make the lifespan of handles shorter than\nthe lifespan of a native method. For example, consider a native method\nthat has a loop which iterates through the elements in a large array:

      \n
      for (int i = 0; i < 1000000; i++) {\n  napi_value result;\n  napi_status status = napi_get_element(env, object, i, &result);\n  if (status != napi_ok) {\n    break;\n  }\n  // do something with element\n}\n
      \n

      This would result in a large number of handles being created, consuming\nsubstantial resources. In addition, even though the native code could only\nuse the most recent handle, all of the associated objects would also be\nkept alive since they all share the same scope.

      \n

      To handle this case, N-API provides the ability to establish a new 'scope' to\nwhich newly created handles will be associated. Once those handles\nare no longer required, the scope can be 'closed' and any handles associated\nwith the scope are invalidated. The methods available to open/close scopes are\nnapi_open_handle_scope and napi_close_handle_scope.

      \n

      N-API only supports a single nested hierarchy of scopes. There is only one\nactive scope at any time, and all new handles will be associated with that\nscope while it is active. Scopes must be closed in the reverse order from\nwhich they are opened. In addition, all scopes created within a native method\nmust be closed before returning from that method.

      \n

      Taking the earlier example, adding calls to napi_open_handle_scope and\nnapi_close_handle_scope would ensure that at most a single handle\nis valid throughout the execution of the loop:

      \n
      for (int i = 0; i < 1000000; i++) {\n  napi_handle_scope scope;\n  napi_status status = napi_open_handle_scope(env, &scope);\n  if (status != napi_ok) {\n    break;\n  }\n  napi_value result;\n  status = napi_get_element(env, object, i, &result);\n  if (status != napi_ok) {\n    break;\n  }\n  // do something with element\n  status = napi_close_handle_scope(env, scope);\n  if (status != napi_ok) {\n    break;\n  }\n}\n
      \n

      When nesting scopes, there are cases where a handle from an\ninner scope needs to live beyond the lifespan of that scope. N-API supports an\n'escapable scope' in order to support this case. An escapable scope\nallows one handle to be 'promoted' so that it 'escapes' the\ncurrent scope and the lifespan of the handle changes from the current\nscope to that of the outer scope.

      \n

      The methods available to open/close escapable scopes are\nnapi_open_escapable_handle_scope and\nnapi_close_escapable_handle_scope.

      \n

      The request to promote a handle is made through napi_escape_handle which\ncan only be called once.

      ", + "modules": [ + { + "textRaw": "napi_open_handle_scope", + "name": "napi_open_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,\n                                               napi_handle_scope* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing the new scope.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API opens a new scope.

      ", + "type": "module", + "displayName": "napi_open_handle_scope" + }, + { + "textRaw": "napi_close_handle_scope", + "name": "napi_close_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,\n                                                napi_handle_scope scope);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: napi_value representing the scope to be closed.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_close_handle_scope" + }, + { + "textRaw": "napi_open_escapable_handle_scope", + "name": "napi_open_escapable_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\n    napi_open_escapable_handle_scope(napi_env env,\n                                     napi_handle_scope* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing the new scope.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API opens a new scope from which one object can be promoted\nto the outer scope.

      ", + "type": "module", + "displayName": "napi_open_escapable_handle_scope" + }, + { + "textRaw": "napi_close_escapable_handle_scope", + "name": "napi_close_escapable_handle_scope", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\n    napi_close_escapable_handle_scope(napi_env env,\n                                      napi_handle_scope scope);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: napi_value representing the scope to be closed.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_close_escapable_handle_scope" + }, + { + "textRaw": "napi_escape_handle", + "name": "napi_escape_handle", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_escape_handle(napi_env env,\n                               napi_escapable_handle_scope scope,\n                               napi_value escapee,\n                               napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: napi_value representing the current scope.
      • \n
      • [in] escapee: napi_value representing the JavaScript Object to be\nescaped.
      • \n
      • [out] result: napi_value representing the handle to the escaped Object\nin the outer scope.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API promotes the handle to the JavaScript object so that it is valid\nfor the lifetime of the outer scope. It can only be called once per scope.\nIf it is called more than once an error will be returned.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_escape_handle" + } + ], + "type": "module", + "displayName": "Making handle lifespan shorter than that of the native method" + }, + { + "textRaw": "References to objects with a lifespan longer than that of the native method", + "name": "references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method", + "desc": "

      In some cases an addon will need to be able to create and reference objects\nwith a lifespan longer than that of a single native method invocation. For\nexample, to create a constructor and later use that constructor\nin a request to creates instances, it must be possible to reference\nthe constructor object across many different instance creation requests. This\nwould not be possible with a normal handle returned as a napi_value as\ndescribed in the earlier section. The lifespan of a normal handle is\nmanaged by scopes and all scopes must be closed before the end of a native\nmethod.

      \n

      N-API provides methods to create persistent references to an object.\nEach persistent reference has an associated count with a value of 0\nor higher. The count determines if the reference will keep\nthe corresponding object live. References with a count of 0 do not\nprevent the object from being collected and are often called 'weak'\nreferences. Any count greater than 0 will prevent the object\nfrom being collected.

      \n

      References can be created with an initial reference count. The count can\nthen be modified through napi_reference_ref and\nnapi_reference_unref. If an object is collected while the count\nfor a reference is 0, all subsequent calls to\nget the object associated with the reference napi_get_reference_value\nwill return NULL for the returned napi_value. An attempt to call\nnapi_reference_ref for a reference whose object has been collected\nwill result in an error.

      \n

      References must be deleted once they are no longer required by the addon. When\na reference is deleted it will no longer prevent the corresponding object from\nbeing collected. Failure to delete a persistent reference will result in\na 'memory leak' with both the native memory for the persistent reference and\nthe corresponding object on the heap being retained forever.

      \n

      There can be multiple persistent references created which refer to the same\nobject, each of which will either keep the object live or not based on its\nindividual count.

      ", + "modules": [ + { + "textRaw": "napi_create_reference", + "name": "napi_create_reference", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_create_reference(napi_env env,\n                                              napi_value value,\n                                              uint32_t initial_refcount,\n                                              napi_ref* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing the Object to which we want a\nreference.
      • \n
      • [in] initial_refcount: Initial reference count for the new reference.
      • \n
      • [out] result: napi_ref pointing to the new reference.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API create a new reference with the specified reference count\nto the Object passed in.

      ", + "type": "module", + "displayName": "napi_create_reference" + }, + { + "textRaw": "napi_delete_reference", + "name": "napi_delete_reference", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref to be deleted.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API deletes the reference passed in.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_delete_reference" + }, + { + "textRaw": "napi_reference_ref", + "name": "napi_reference_ref", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_reference_ref(napi_env env,\n                                           napi_ref ref,\n                                           uint32_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref for which the reference count will be incremented.
      • \n
      • [out] result: The new reference count.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API increments the reference count for the reference\npassed in and returns the resulting reference count.

      ", + "type": "module", + "displayName": "napi_reference_ref" + }, + { + "textRaw": "napi_reference_unref", + "name": "napi_reference_unref", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_reference_unref(napi_env env,\n                                             napi_ref ref,\n                                             uint32_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref for which the reference count will be decremented.
      • \n
      • [out] result: The new reference count.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API decrements the reference count for the reference\npassed in and returns the resulting reference count.

      ", + "type": "module", + "displayName": "napi_reference_unref" + }, + { + "textRaw": "napi_get_reference_value", + "name": "napi_get_reference_value", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,\n                                                 napi_ref ref,\n                                                 napi_value* result);\n
      \n

      the napi_value passed in or out of these methods is a handle to the\nobject to which the reference is related.

      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] ref: napi_ref for which we requesting the corresponding Object.
      • \n
      • [out] result: The napi_value for the Object referenced by the\nnapi_ref.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      If still valid, this API returns the napi_value representing the\nJavaScript Object associated with the napi_ref. Otherwise, result\nwill be NULL.

      ", + "type": "module", + "displayName": "napi_get_reference_value" + } + ], + "type": "module", + "displayName": "References to objects with a lifespan longer than that of the native method" + }, + { + "textRaw": "Cleanup on exit of the current Node.js instance", + "name": "cleanup_on_exit_of_the_current_node.js_instance", + "desc": "

      While a Node.js process typically releases all its resources when exiting,\nembedders of Node.js, or future Worker support, may require addons to register\nclean-up hooks that will be run once the current Node.js instance exits.

      \n

      N-API provides functions for registering and un-registering such callbacks.\nWhen those callbacks are run, all resources that are being held by the addon\nshould be freed up.

      ", + "modules": [ + { + "textRaw": "napi_add_env_cleanup_hook", + "name": "napi_add_env_cleanup_hook", + "meta": { + "added": [ + "v10.2.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,\n                                                  void (*fun)(void* arg),\n                                                  void* arg);\n
      \n

      Registers fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits.

      \n

      A function can safely be specified multiple times with different\narg values. In that case, it will be called multiple times as well.\nProviding the same fun and arg values multiple times is not allowed\nand will lead the process to abort.

      \n

      The hooks will be called in reverse order, i.e. the most recently added one\nwill be called first.

      \n

      Removing this hook can be done by using napi_remove_env_cleanup_hook.\nTypically, that happens when the resource for which this hook was added\nis being torn down anyway.

      \n

      For asynchronous cleanup, napi_add_async_cleanup_hook is available.

      ", + "type": "module", + "displayName": "napi_add_env_cleanup_hook" + }, + { + "textRaw": "napi_remove_env_cleanup_hook", + "name": "napi_remove_env_cleanup_hook", + "meta": { + "added": [ + "v10.2.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,\n                                                     void (*fun)(void* arg),\n                                                     void* arg);\n
      \n

      Unregisters fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits. Both the argument and the function value\nneed to be exact matches.

      \n

      The function must have originally been registered\nwith napi_add_env_cleanup_hook, otherwise the process will abort.

      ", + "type": "module", + "displayName": "napi_remove_env_cleanup_hook" + }, + { + "textRaw": "napi_add_async_cleanup_hook", + "name": "napi_add_async_cleanup_hook", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34819", + "description": "Changed signature of the `hook` callback." + } + ], + "napiVersion": [ + 8 + ] + }, + "desc": "
      NAPI_EXTERN napi_status napi_add_async_cleanup_hook(\n    napi_env env,\n    napi_async_cleanup_hook hook,\n    void* arg,\n    napi_async_cleanup_hook_handle* remove_handle);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] hook: The function pointer to call at environment teardown.
      • \n
      • [in] arg: The pointer to pass to hook when it gets called.
      • \n
      • [out] remove_handle: Optional handle that refers to the asynchronous cleanup\nhook.
      • \n
      \n

      Registers hook, which is a function of type napi_async_cleanup_hook, as\na function to be run with the remove_handle and arg parameters once the\ncurrent Node.js environment exits.

      \n

      Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.

      \n

      Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.

      \n

      If remove_handle is not NULL, an opaque value will be stored in it\nthat must later be passed to napi_remove_async_cleanup_hook,\nregardless of whether the hook has already been invoked.\nTypically, that happens when the resource for which this hook was added\nis being torn down anyway.

      ", + "type": "module", + "displayName": "napi_add_async_cleanup_hook" + }, + { + "textRaw": "napi_remove_async_cleanup_hook", + "name": "napi_remove_async_cleanup_hook", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34819", + "description": "Removed `env` parameter." + } + ] + }, + "desc": "
      NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(\n    napi_async_cleanup_hook_handle remove_handle);\n
      \n\n

      Unregisters the cleanup hook corresponding to remove_handle. This will prevent\nthe hook from being executed, unless it has already started executing.\nThis must be called on any napi_async_cleanup_hook_handle value obtained\nfrom napi_add_async_cleanup_hook.

      ", + "type": "module", + "displayName": "napi_remove_async_cleanup_hook" + } + ], + "type": "module", + "displayName": "Cleanup on exit of the current Node.js instance" + } + ], + "type": "misc", + "displayName": "Object lifetime management" + }, + { + "textRaw": "Module registration", + "name": "module_registration", + "desc": "

      N-API modules are registered in a manner similar to other modules\nexcept that instead of using the NODE_MODULE macro the following\nis used:

      \n
      NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n
      \n

      The next difference is the signature for the Init method. For a N-API\nmodule it is as follows:

      \n
      napi_value Init(napi_env env, napi_value exports);\n
      \n

      The return value from Init is treated as the exports object for the module.\nThe Init method is passed an empty object via the exports parameter as a\nconvenience. If Init returns NULL, the parameter passed as exports is\nexported by the module. N-API modules cannot modify the module object but can\nspecify anything as the exports property of the module.

      \n

      To add the method hello as a function so that it can be called as a method\nprovided by the addon:

      \n
      napi_value Init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_property_descriptor desc = {\n    \"hello\",\n    NULL,\n    Method,\n    NULL,\n    NULL,\n    NULL,\n    napi_writable | napi_enumerable | napi_configurable,\n    NULL\n  };\n  status = napi_define_properties(env, exports, 1, &desc);\n  if (status != napi_ok) return NULL;\n  return exports;\n}\n
      \n

      To set a function to be returned by the require() for the addon:

      \n
      napi_value Init(napi_env env, napi_value exports) {\n  napi_value method;\n  napi_status status;\n  status = napi_create_function(env, \"exports\", NAPI_AUTO_LENGTH, Method, NULL, &method);\n  if (status != napi_ok) return NULL;\n  return method;\n}\n
      \n

      To define a class so that new instances can be created (often used with\nObject wrap):

      \n
      // NOTE: partial example, not all referenced code is included\nnapi_value Init(napi_env env, napi_value exports) {\n  napi_status status;\n  napi_property_descriptor properties[] = {\n    { \"value\", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL },\n    DECLARE_NAPI_METHOD(\"plusOne\", PlusOne),\n    DECLARE_NAPI_METHOD(\"multiply\", Multiply),\n  };\n\n  napi_value cons;\n  status =\n      napi_define_class(env, \"MyObject\", New, NULL, 3, properties, &cons);\n  if (status != napi_ok) return NULL;\n\n  status = napi_create_reference(env, cons, 1, &constructor);\n  if (status != napi_ok) return NULL;\n\n  status = napi_set_named_property(env, exports, \"MyObject\", cons);\n  if (status != napi_ok) return NULL;\n\n  return exports;\n}\n
      \n

      If the module will be loaded multiple times during the lifetime of the Node.js\nprocess, use the NAPI_MODULE_INIT macro to initialize the module:

      \n
      NAPI_MODULE_INIT() {\n  napi_value answer;\n  napi_status result;\n\n  status = napi_create_int64(env, 42, &answer);\n  if (status != napi_ok) return NULL;\n\n  status = napi_set_named_property(env, exports, \"answer\", answer);\n  if (status != napi_ok) return NULL;\n\n  return exports;\n}\n
      \n

      This macro includes NAPI_MODULE, and declares an Init function with a\nspecial name and with visibility beyond the addon. This will allow Node.js to\ninitialize the module even if it is loaded multiple times.

      \n

      There are a few design considerations when declaring a module that may be loaded\nmultiple times. The documentation of context-aware addons provides more\ndetails.

      \n

      The variables env and exports will be available inside the function body\nfollowing the macro invocation.

      \n

      For more details on setting properties on objects, see the section on\nWorking with JavaScript properties.

      \n

      For more details on building addon modules in general, refer to the existing\nAPI.

      ", + "type": "misc", + "displayName": "Module registration" + }, + { + "textRaw": "Working with JavaScript values", + "name": "working_with_javascript_values", + "desc": "

      N-API exposes a set of APIs to create all types of JavaScript values.\nSome of these types are documented under Section 6\nof the ECMAScript Language Specification.

      \n

      Fundamentally, these APIs are used to do one of the following:

      \n
        \n
      1. Create a new JavaScript object
      2. \n
      3. Convert from a primitive C type to an N-API value
      4. \n
      5. Convert from N-API value to a primitive C type
      6. \n
      7. Get global instances including undefined and null
      8. \n
      \n

      N-API values are represented by the type napi_value.\nAny N-API call that requires a JavaScript value takes in a napi_value.\nIn some cases, the API does check the type of the napi_value up-front.\nHowever, for better performance, it's better for the caller to make sure that\nthe napi_value in question is of the JavaScript type expected by the API.

      ", + "modules": [ + { + "textRaw": "Enum types", + "name": "enum_types", + "modules": [ + { + "textRaw": "napi_key_collection_mode", + "name": "napi_key_collection_mode", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      typedef enum {\n  napi_key_include_prototypes,\n  napi_key_own_only\n} napi_key_collection_mode;\n
      \n

      Describes the Keys/Properties filter enums:

      \n

      napi_key_collection_mode limits the range of collected properties.

      \n

      napi_key_own_only limits the collected properties to the given\nobject only. napi_key_include_prototypes will include all keys\nof the objects's prototype chain as well.

      ", + "type": "module", + "displayName": "napi_key_collection_mode" + }, + { + "textRaw": "napi_key_filter", + "name": "napi_key_filter", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      typedef enum {\n  napi_key_all_properties = 0,\n  napi_key_writable = 1,\n  napi_key_enumerable = 1 << 1,\n  napi_key_configurable = 1 << 2,\n  napi_key_skip_strings = 1 << 3,\n  napi_key_skip_symbols = 1 << 4\n} napi_key_filter;\n
      \n

      Property filter bits. They can be or'ed to build a composite filter.

      ", + "type": "module", + "displayName": "napi_key_filter" + }, + { + "textRaw": "napi_key_conversion", + "name": "napi_key_conversion", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      typedef enum {\n  napi_key_keep_numbers,\n  napi_key_numbers_to_strings\n} napi_key_conversion;\n
      \n

      napi_key_numbers_to_strings will convert integer indices to\nstrings. napi_key_keep_numbers will return numbers for integer\nindices.

      ", + "type": "module", + "displayName": "napi_key_conversion" + }, + { + "textRaw": "napi_valuetype", + "name": "napi_valuetype", + "desc": "
      typedef enum {\n  // ES6 types (corresponds to typeof)\n  napi_undefined,\n  napi_null,\n  napi_boolean,\n  napi_number,\n  napi_string,\n  napi_symbol,\n  napi_object,\n  napi_function,\n  napi_external,\n  napi_bigint,\n} napi_valuetype;\n
      \n

      Describes the type of a napi_value. This generally corresponds to the types\ndescribed in Section 6.1 of the ECMAScript Language Specification.\nIn addition to types in that section, napi_valuetype can also represent\nFunctions and Objects with external data.

      \n

      A JavaScript value of type napi_external appears in JavaScript as a plain\nobject such that no properties can be set on it, and no prototype.

      ", + "type": "module", + "displayName": "napi_valuetype" + }, + { + "textRaw": "napi_typedarray_type", + "name": "napi_typedarray_type", + "desc": "
      typedef enum {\n  napi_int8_array,\n  napi_uint8_array,\n  napi_uint8_clamped_array,\n  napi_int16_array,\n  napi_uint16_array,\n  napi_int32_array,\n  napi_uint32_array,\n  napi_float32_array,\n  napi_float64_array,\n  napi_bigint64_array,\n  napi_biguint64_array,\n} napi_typedarray_type;\n
      \n

      This represents the underlying binary scalar datatype of the TypedArray.\nElements of this enum correspond to\nSection 22.2 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_typedarray_type" + } + ], + "type": "module", + "displayName": "Enum types" + }, + { + "textRaw": "Object creation functions", + "name": "object_creation_functions", + "modules": [ + { + "textRaw": "napi_create_array", + "name": "napi_create_array", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_array(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [out] result: A napi_value representing a JavaScript Array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript Array type.\nJavaScript arrays are described in\nSection 22.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_array" + }, + { + "textRaw": "napi_create_array_with_length", + "name": "napi_create_array_with_length", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_array_with_length(napi_env env,\n                                          size_t length,\n                                          napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: The initial length of the Array.
      • \n
      • [out] result: A napi_value representing a JavaScript Array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript Array type.\nThe Array's length property is set to the passed-in length parameter.\nHowever, the underlying buffer is not guaranteed to be pre-allocated by the VM\nwhen the array is created. That behavior is left to the underlying VM\nimplementation. If the buffer must be a contiguous block of memory that can be\ndirectly read and/or written via C, consider using\nnapi_create_external_arraybuffer.

      \n

      JavaScript arrays are described in\nSection 22.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_array_with_length" + }, + { + "textRaw": "napi_create_arraybuffer", + "name": "napi_create_arraybuffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_arraybuffer(napi_env env,\n                                    size_t byte_length,\n                                    void** data,\n                                    napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: The length in bytes of the array buffer to create.
      • \n
      • [out] data: Pointer to the underlying byte buffer of the ArrayBuffer.
      • \n
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer.\nArrayBuffers are used to represent fixed-length binary data buffers. They are\nnormally used as a backing-buffer for TypedArray objects.\nThe ArrayBuffer allocated will have an underlying byte buffer whose size is\ndetermined by the length parameter that's passed in.\nThe underlying buffer is optionally returned back to the caller in case the\ncaller wants to directly manipulate the buffer. This buffer can only be\nwritten to directly from native code. To write to this buffer from JavaScript,\na typed array or DataView object would need to be created.

      \n

      JavaScript ArrayBuffer objects are described in\nSection 24.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_arraybuffer" + }, + { + "textRaw": "napi_create_buffer", + "name": "napi_create_buffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_buffer(napi_env env,\n                               size_t size,\n                               void** data,\n                               napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] size: Size in bytes of the underlying buffer.
      • \n
      • [out] data: Raw pointer to the underlying buffer.
      • \n
      • [out] result: A napi_value representing a node::Buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a node::Buffer object. While this is still a\nfully-supported data structure, in most cases using a TypedArray will suffice.

      ", + "type": "module", + "displayName": "napi_create_buffer" + }, + { + "textRaw": "napi_create_buffer_copy", + "name": "napi_create_buffer_copy", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_buffer_copy(napi_env env,\n                                    size_t length,\n                                    const void* data,\n                                    void** result_data,\n                                    napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] size: Size in bytes of the input buffer (should be the same as the size\nof the new buffer).
      • \n
      • [in] data: Raw pointer to the underlying buffer to copy from.
      • \n
      • [out] result_data: Pointer to the new Buffer's underlying data buffer.
      • \n
      • [out] result: A napi_value representing a node::Buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a node::Buffer object and initializes it with data copied\nfrom the passed-in buffer. While this is still a fully-supported data\nstructure, in most cases using a TypedArray will suffice.

      ", + "type": "module", + "displayName": "napi_create_buffer_copy" + }, + { + "textRaw": "napi_create_date", + "name": "napi_create_date", + "meta": { + "added": [ + "v11.11.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_date(napi_env env,\n                             double time,\n                             napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] time: ECMAScript time value in milliseconds since 01 January, 1970 UTC.
      • \n
      • [out] result: A napi_value representing a JavaScript Date.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.

      \n

      This API allocates a JavaScript Date object.

      \n

      JavaScript Date objects are described in\nSection 20.3 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_date" + }, + { + "textRaw": "napi_create_external", + "name": "napi_create_external", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_external(napi_env env,\n                                 void* data,\n                                 napi_finalize finalize_cb,\n                                 void* finalize_hint,\n                                 napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] data: Raw pointer to the external data.
      • \n
      • [in] finalize_cb: Optional callback to call when the external value is being\ncollected. napi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      • [out] result: A napi_value representing an external value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a JavaScript value with external data attached to it. This\nis used to pass external data through JavaScript code, so it can be retrieved\nlater by native code using napi_get_value_external.

      \n

      The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the object created by the API can be used with napi_wrap().
      • \n
      \n

      The created value is not an object, and therefore does not support additional\nproperties. It is considered a distinct value type: calling napi_typeof() with\nan external value yields napi_external.

      ", + "type": "module", + "displayName": "napi_create_external" + }, + { + "textRaw": "napi_create_external_arraybuffer", + "name": "napi_create_external_arraybuffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status\nnapi_create_external_arraybuffer(napi_env env,\n                                 void* external_data,\n                                 size_t byte_length,\n                                 napi_finalize finalize_cb,\n                                 void* finalize_hint,\n                                 napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] external_data: Pointer to the underlying byte buffer of the\nArrayBuffer.
      • \n
      • [in] byte_length: The length in bytes of the underlying buffer.
      • \n
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being\ncollected. napi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      • [out] result: A napi_value representing a JavaScript ArrayBuffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an N-API value corresponding to a JavaScript ArrayBuffer.\nThe underlying byte buffer of the ArrayBuffer is externally allocated and\nmanaged. The caller must ensure that the byte buffer remains valid until the\nfinalize callback is called.

      \n

      The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the object created by the API can be used with napi_wrap().
      • \n
      \n

      JavaScript ArrayBuffers are described in\nSection 24.1 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_external_arraybuffer" + }, + { + "textRaw": "napi_create_external_buffer", + "name": "napi_create_external_buffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_external_buffer(napi_env env,\n                                        size_t length,\n                                        void* data,\n                                        napi_finalize finalize_cb,\n                                        void* finalize_hint,\n                                        napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: Size in bytes of the input buffer (should be the same as the\nsize of the new buffer).
      • \n
      • [in] data: Raw pointer to the underlying buffer to expose to JavaScript.
      • \n
      • [in] finalize_cb: Optional callback to call when the ArrayBuffer is being\ncollected. napi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.
      • \n
      • [out] result: A napi_value representing a node::Buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a node::Buffer object and initializes it with data\nbacked by the passed in buffer. While this is still a fully-supported data\nstructure, in most cases using a TypedArray will suffice.

      \n

      The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the object created by the API can be used with napi_wrap().
      • \n
      \n

      For Node.js >=4 Buffers are Uint8Arrays.

      ", + "type": "module", + "displayName": "napi_create_external_buffer" + }, + { + "textRaw": "napi_create_object", + "name": "napi_create_object", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_object(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: A napi_value representing a JavaScript Object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a default JavaScript Object.\nIt is the equivalent of doing new Object() in JavaScript.

      \n

      The JavaScript Object type is described in Section 6.1.7 of the\nECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_object" + }, + { + "textRaw": "napi_create_symbol", + "name": "napi_create_symbol", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_symbol(napi_env env,\n                               napi_value description,\n                               napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] description: Optional napi_value which refers to a JavaScript\nString to be set as the description for the symbol.
      • \n
      • [out] result: A napi_value representing a JavaScript Symbol.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript Symbol object from a UTF8-encoded C string.

      \n

      The JavaScript Symbol type is described in Section 19.4\nof the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_symbol" + }, + { + "textRaw": "napi_create_typedarray", + "name": "napi_create_typedarray", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_typedarray(napi_env env,\n                                   napi_typedarray_type type,\n                                   size_t length,\n                                   napi_value arraybuffer,\n                                   size_t byte_offset,\n                                   napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] type: Scalar datatype of the elements within the TypedArray.
      • \n
      • [in] length: Number of elements in the TypedArray.
      • \n
      • [in] arraybuffer: ArrayBuffer underlying the typed array.
      • \n
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to\nstart projecting the TypedArray.
      • \n
      • [out] result: A napi_value representing a JavaScript TypedArray.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript TypedArray object over an existing\nArrayBuffer. TypedArray objects provide an array-like view over an\nunderlying data buffer where each element has the same underlying binary scalar\ndatatype.

      \n

      It's required that (length * size_of_element) + byte_offset should\nbe <= the size in bytes of the array passed in. If not, a RangeError exception\nis raised.

      \n

      JavaScript TypedArray objects are described in\nSection 22.2 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_typedarray" + }, + { + "textRaw": "napi_create_dataview", + "name": "napi_create_dataview", + "meta": { + "added": [ + "v8.3.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_dataview(napi_env env,\n                                 size_t byte_length,\n                                 napi_value arraybuffer,\n                                 size_t byte_offset,\n                                 napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] length: Number of elements in the DataView.
      • \n
      • [in] arraybuffer: ArrayBuffer underlying the DataView.
      • \n
      • [in] byte_offset: The byte offset within the ArrayBuffer from which to\nstart projecting the DataView.
      • \n
      • [out] result: A napi_value representing a JavaScript DataView.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript DataView object over an existing ArrayBuffer.\nDataView objects provide an array-like view over an underlying data buffer,\nbut one which allows items of different size and type in the ArrayBuffer.

      \n

      It is required that byte_length + byte_offset is less than or equal to the\nsize in bytes of the array passed in. If not, a RangeError exception is\nraised.

      \n

      JavaScript DataView objects are described in\nSection 24.3 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_dataview" + } + ], + "type": "module", + "displayName": "Object creation functions" + }, + { + "textRaw": "Functions to convert from C types to N-API", + "name": "functions_to_convert_from_c_types_to_n-api", + "modules": [ + { + "textRaw": "napi_create_int32", + "name": "napi_create_int32", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C int32_t type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_int32" + }, + { + "textRaw": "napi_create_uint32", + "name": "napi_create_uint32", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C uint32_t type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_uint32" + }, + { + "textRaw": "napi_create_int64", + "name": "napi_create_int64", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C int64_t type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in Section 6.1.6\nof the ECMAScript Language Specification. Note the complete range of int64_t\ncannot be represented with full precision in JavaScript. Integer values\noutside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) -\nNumber.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.

      ", + "type": "module", + "displayName": "napi_create_int64" + }, + { + "textRaw": "napi_create_double", + "name": "napi_create_double", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_double(napi_env env, double value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Double-precision value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to convert from the C double type to the JavaScript\nNumber type.

      \n

      The JavaScript Number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_double" + }, + { + "textRaw": "napi_create_bigint_int64", + "name": "napi_create_bigint_int64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_bigint_int64(napi_env env,\n                                     int64_t value,\n                                     napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript BigInt.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts the C int64_t type to the JavaScript BigInt type.

      ", + "type": "module", + "displayName": "napi_create_bigint_int64" + }, + { + "textRaw": "napi_create_bigint_uint64", + "name": "napi_create_bigint_uint64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_bigint_uint64(napi_env env,\n                                      uint64_t value,\n                                      napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: Unsigned integer value to be represented in JavaScript.
      • \n
      • [out] result: A napi_value representing a JavaScript BigInt.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts the C uint64_t type to the JavaScript BigInt type.

      ", + "type": "module", + "displayName": "napi_create_bigint_uint64" + }, + { + "textRaw": "napi_create_bigint_words", + "name": "napi_create_bigint_words", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_bigint_words(napi_env env,\n                                     int sign_bit,\n                                     size_t word_count,\n                                     const uint64_t* words,\n                                     napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] sign_bit: Determines if the resulting BigInt will be positive or\nnegative.
      • \n
      • [in] word_count: The length of the words array.
      • \n
      • [in] words: An array of uint64_t little-endian 64-bit words.
      • \n
      • [out] result: A napi_value representing a JavaScript BigInt.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts an array of unsigned 64-bit words into a single BigInt\nvalue.

      \n

      The resulting BigInt is calculated as: (–1)sign_bit (words[0]\n× (264)0 + words[1] × (264)1 + …)

      ", + "type": "module", + "displayName": "napi_create_bigint_words" + }, + { + "textRaw": "napi_create_string_latin1", + "name": "napi_create_string_latin1", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_string_latin1(napi_env env,\n                                      const char* str,\n                                      size_t length,\n                                      napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] str: Character buffer representing an ISO-8859-1-encoded string.
      • \n
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.
      • \n
      • [out] result: A napi_value representing a JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript String object from an ISO-8859-1-encoded C\nstring. The native string is copied.

      \n

      The JavaScript String type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_string_latin1" + }, + { + "textRaw": "napi_create_string_utf16", + "name": "napi_create_string_utf16", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_string_utf16(napi_env env,\n                                     const char16_t* str,\n                                     size_t length,\n                                     napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] str: Character buffer representing a UTF16-LE-encoded string.
      • \n
      • [in] length: The length of the string in two-byte code units, or\nNAPI_AUTO_LENGTH if it is null-terminated.
      • \n
      • [out] result: A napi_value representing a JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript String object from a UTF16-LE-encoded C string.\nThe native string is copied.

      \n

      The JavaScript String type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_string_utf16" + }, + { + "textRaw": "napi_create_string_utf8", + "name": "napi_create_string_utf8", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_string_utf8(napi_env env,\n                                    const char* str,\n                                    size_t length,\n                                    napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] str: Character buffer representing a UTF8-encoded string.
      • \n
      • [in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.
      • \n
      • [out] result: A napi_value representing a JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a JavaScript String object from a UTF8-encoded C string.\nThe native string is copied.

      \n

      The JavaScript String type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_create_string_utf8" + } + ], + "type": "module", + "displayName": "Functions to convert from C types to N-API" + }, + { + "textRaw": "Functions to convert from N-API to C types", + "name": "functions_to_convert_from_n-api_to_c_types", + "modules": [ + { + "textRaw": "napi_get_array_length", + "name": "napi_get_array_length", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_array_length(napi_env env,\n                                  napi_value value,\n                                  uint32_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing the JavaScript Array whose length is\nbeing queried.
      • \n
      • [out] result: uint32 representing length of the array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the length of an array.

      \n

      Array length is described in Section 22.1.4.1 of the ECMAScript Language\nSpecification.

      ", + "type": "module", + "displayName": "napi_get_array_length" + }, + { + "textRaw": "napi_get_arraybuffer_info", + "name": "napi_get_arraybuffer_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_arraybuffer_info(napi_env env,\n                                      napi_value arraybuffer,\n                                      void** data,\n                                      size_t* byte_length)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] arraybuffer: napi_value representing the ArrayBuffer being queried.
      • \n
      • [out] data: The underlying data buffer of the ArrayBuffer. If byte_length\nis 0, this may be NULL or any other pointer value.
      • \n
      • [out] byte_length: Length in bytes of the underlying data buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to retrieve the underlying data buffer of an ArrayBuffer and\nits length.

      \n

      WARNING: Use caution while using this API. The lifetime of the underlying data\nbuffer is managed by the ArrayBuffer even after it's returned. A\npossible safe way to use this API is in conjunction with\nnapi_create_reference, which can be used to guarantee control over the\nlifetime of the ArrayBuffer. It's also safe to use the returned data buffer\nwithin the same callback as long as there are no calls to other APIs that might\ntrigger a GC.

      ", + "type": "module", + "displayName": "napi_get_arraybuffer_info" + }, + { + "textRaw": "napi_get_buffer_info", + "name": "napi_get_buffer_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_buffer_info(napi_env env,\n                                 napi_value value,\n                                 void** data,\n                                 size_t* length)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing the node::Buffer being queried.
      • \n
      • [out] data: The underlying data buffer of the node::Buffer.\nIf length is 0, this may be NULL or any other pointer value.
      • \n
      • [out] length: Length in bytes of the underlying data buffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to retrieve the underlying data buffer of a node::Buffer\nand it's length.

      \n

      Warning: Use caution while using this API since the underlying data buffer's\nlifetime is not guaranteed if it's managed by the VM.

      ", + "type": "module", + "displayName": "napi_get_buffer_info" + }, + { + "textRaw": "napi_get_prototype", + "name": "napi_get_prototype", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_prototype(napi_env env,\n                               napi_value object,\n                               napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] object: napi_value representing JavaScript Object whose prototype\nto return. This returns the equivalent of Object.getPrototypeOf (which is\nnot the same as the function's prototype property).
      • \n
      • [out] result: napi_value representing prototype of the given object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      ", + "type": "module", + "displayName": "napi_get_prototype" + }, + { + "textRaw": "napi_get_typedarray_info", + "name": "napi_get_typedarray_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_typedarray_info(napi_env env,\n                                     napi_value typedarray,\n                                     napi_typedarray_type* type,\n                                     size_t* length,\n                                     void** data,\n                                     napi_value* arraybuffer,\n                                     size_t* byte_offset)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] typedarray: napi_value representing the TypedArray whose\nproperties to query.
      • \n
      • [out] type: Scalar datatype of the elements within the TypedArray.
      • \n
      • [out] length: The number of elements in the TypedArray.
      • \n
      • [out] data: The data buffer underlying the TypedArray adjusted by\nthe byte_offset value so that it points to the first element in the\nTypedArray. If the length of the array is 0, this may be NULL or\nany other pointer value.
      • \n
      • [out] arraybuffer: The ArrayBuffer underlying the TypedArray.
      • \n
      • [out] byte_offset: The byte offset within the underlying native array\nat which the first element of the arrays is located. The value for the data\nparameter has already been adjusted so that data points to the first element\nin the array. Therefore, the first byte of the native array would be at\ndata - byte_offset.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns various properties of a typed array.

      \n

      Warning: Use caution while using this API since the underlying data buffer\nis managed by the VM.

      ", + "type": "module", + "displayName": "napi_get_typedarray_info" + }, + { + "textRaw": "napi_get_dataview_info", + "name": "napi_get_dataview_info", + "meta": { + "added": [ + "v8.3.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_dataview_info(napi_env env,\n                                   napi_value dataview,\n                                   size_t* byte_length,\n                                   void** data,\n                                   napi_value* arraybuffer,\n                                   size_t* byte_offset)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] dataview: napi_value representing the DataView whose\nproperties to query.
      • \n
      • [out] byte_length: Number of bytes in the DataView.
      • \n
      • [out] data: The data buffer underlying the DataView.\nIf byte_length is 0, this may be NULL or any other pointer value.
      • \n
      • [out] arraybuffer: ArrayBuffer underlying the DataView.
      • \n
      • [out] byte_offset: The byte offset within the data buffer from which\nto start projecting the DataView.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns various properties of a DataView.

      ", + "type": "module", + "displayName": "napi_get_dataview_info" + }, + { + "textRaw": "napi_get_date_value", + "name": "napi_get_date_value", + "meta": { + "added": [ + "v11.11.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_date_value(napi_env env,\n                                napi_value value,\n                                double* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing a JavaScript Date.
      • \n
      • [out] result: Time value as a double represented as milliseconds since\nmidnight at the beginning of 01 January, 1970 UTC.
      • \n
      \n

      This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.

      \n

      Returns napi_ok if the API succeeded. If a non-date napi_value is passed\nin it returns napi_date_expected.

      \n

      This API returns the C double primitive of time value for the given JavaScript\nDate.

      ", + "type": "module", + "displayName": "napi_get_date_value" + }, + { + "textRaw": "napi_get_value_bool", + "name": "napi_get_value_bool", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Boolean.
      • \n
      • [out] result: C boolean primitive equivalent of the given JavaScript\nBoolean.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-boolean napi_value is\npassed in it returns napi_boolean_expected.

      \n

      This API returns the C boolean primitive equivalent of the given JavaScript\nBoolean.

      ", + "type": "module", + "displayName": "napi_get_value_bool" + }, + { + "textRaw": "napi_get_value_double", + "name": "napi_get_value_double", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_double(napi_env env,\n                                  napi_value value,\n                                  double* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C double primitive equivalent of the given JavaScript\nNumber.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value is passed\nin it returns napi_number_expected.

      \n

      This API returns the C double primitive equivalent of the given JavaScript\nNumber.

      ", + "type": "module", + "displayName": "napi_get_value_double" + }, + { + "textRaw": "napi_get_value_bigint_int64", + "name": "napi_get_value_bigint_int64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bigint_int64(napi_env env,\n                                        napi_value value,\n                                        int64_t* result,\n                                        bool* lossless);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under
      • \n
      • [in] value: napi_value representing JavaScript BigInt.
      • \n
      • [out] result: C int64_t primitive equivalent of the given JavaScript\nBigInt.
      • \n
      • [out] lossless: Indicates whether the BigInt value was converted\nlosslessly.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.

      \n

      This API returns the C int64_t primitive equivalent of the given JavaScript\nBigInt. If needed it will truncate the value, setting lossless to false.

      ", + "type": "module", + "displayName": "napi_get_value_bigint_int64" + }, + { + "textRaw": "napi_get_value_bigint_uint64", + "name": "napi_get_value_bigint_uint64", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bigint_uint64(napi_env env,\n                                        napi_value value,\n                                        uint64_t* result,\n                                        bool* lossless);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript BigInt.
      • \n
      • [out] result: C uint64_t primitive equivalent of the given JavaScript\nBigInt.
      • \n
      • [out] lossless: Indicates whether the BigInt value was converted\nlosslessly.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.

      \n

      This API returns the C uint64_t primitive equivalent of the given JavaScript\nBigInt. If needed it will truncate the value, setting lossless to false.

      ", + "type": "module", + "displayName": "napi_get_value_bigint_uint64" + }, + { + "textRaw": "napi_get_value_bigint_words", + "name": "napi_get_value_bigint_words", + "meta": { + "added": [ + "v10.7.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_bigint_words(napi_env env,\n                                        napi_value value,\n                                        int* sign_bit,\n                                        size_t* word_count,\n                                        uint64_t* words);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript BigInt.
      • \n
      • [out] sign_bit: Integer representing if the JavaScript BigInt is positive\nor negative.
      • \n
      • [in/out] word_count: Must be initialized to the length of the words\narray. Upon return, it will be set to the actual number of words that\nwould be needed to store this BigInt.
      • \n
      • [out] words: Pointer to a pre-allocated 64-bit word array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API converts a single BigInt value into a sign bit, 64-bit little-endian\narray, and the number of elements in the array. sign_bit and words may be\nboth set to NULL, in order to get only word_count.

      ", + "type": "module", + "displayName": "napi_get_value_bigint_words" + }, + { + "textRaw": "napi_get_value_external", + "name": "napi_get_value_external", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_external(napi_env env,\n                                    napi_value value,\n                                    void** result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript external value.
      • \n
      • [out] result: Pointer to the data wrapped by the JavaScript external value.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-external napi_value is\npassed in it returns napi_invalid_arg.

      \n

      This API retrieves the external data pointer that was previously passed to\nnapi_create_external().

      ", + "type": "module", + "displayName": "napi_get_value_external" + }, + { + "textRaw": "napi_get_value_int32", + "name": "napi_get_value_int32", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_int32(napi_env env,\n                                 napi_value value,\n                                 int32_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C int32 primitive equivalent of the given JavaScript\nNumber.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in napi_number_expected.

      \n

      This API returns the C int32 primitive equivalent\nof the given JavaScript Number.

      \n

      If the number exceeds the range of the 32 bit integer, then the result is\ntruncated to the equivalent of the bottom 32 bits. This can result in a large\npositive number becoming a negative number if the value is > 231 - 1.

      \n

      Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.

      ", + "type": "module", + "displayName": "napi_get_value_int32" + }, + { + "textRaw": "napi_get_value_int64", + "name": "napi_get_value_int64", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_int64(napi_env env,\n                                 napi_value value,\n                                 int64_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C int64 primitive equivalent of the given JavaScript\nNumber.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.

      \n

      This API returns the C int64 primitive equivalent of the given JavaScript\nNumber.

      \n

      Number values outside the range of Number.MIN_SAFE_INTEGER\n-(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose\nprecision.

      \n

      Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.

      ", + "type": "module", + "displayName": "napi_get_value_int64" + }, + { + "textRaw": "napi_get_value_string_latin1", + "name": "napi_get_value_string_latin1", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_string_latin1(napi_env env,\n                                         napi_value value,\n                                         char* buf,\n                                         size_t bufsize,\n                                         size_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript string.
      • \n
      • [in] buf: Buffer to write the ISO-8859-1-encoded string into. If NULL is\npassed in, the length of the string (in bytes) is returned.
      • \n
      • [in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string will be truncated.
      • \n
      • [out] result: Number of bytes copied into the buffer, excluding the null\nterminator.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-String napi_value\nis passed in it returns napi_string_expected.

      \n

      This API returns the ISO-8859-1-encoded string corresponding the value passed\nin.

      ", + "type": "module", + "displayName": "napi_get_value_string_latin1" + }, + { + "textRaw": "napi_get_value_string_utf8", + "name": "napi_get_value_string_utf8", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_string_utf8(napi_env env,\n                                       napi_value value,\n                                       char* buf,\n                                       size_t bufsize,\n                                       size_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript string.
      • \n
      • [in] buf: Buffer to write the UTF8-encoded string into. If NULL is passed\nin, the length of the string (in bytes) is returned.
      • \n
      • [in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string will be truncated.
      • \n
      • [out] result: Number of bytes copied into the buffer, excluding the null\nterminator.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-String napi_value\nis passed in it returns napi_string_expected.

      \n

      This API returns the UTF8-encoded string corresponding the value passed in.

      ", + "type": "module", + "displayName": "napi_get_value_string_utf8" + }, + { + "textRaw": "napi_get_value_string_utf16", + "name": "napi_get_value_string_utf16", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_string_utf16(napi_env env,\n                                        napi_value value,\n                                        char16_t* buf,\n                                        size_t bufsize,\n                                        size_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript string.
      • \n
      • [in] buf: Buffer to write the UTF16-LE-encoded string into. If NULL is\npassed in, the length of the string (in 2-byte code units) is returned.
      • \n
      • [in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string will be truncated.
      • \n
      • [out] result: Number of 2-byte code units copied into the buffer, excluding\nthe null terminator.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-String napi_value\nis passed in it returns napi_string_expected.

      \n

      This API returns the UTF16-encoded string corresponding the value passed in.

      ", + "type": "module", + "displayName": "napi_get_value_string_utf16" + }, + { + "textRaw": "napi_get_value_uint32", + "name": "napi_get_value_uint32", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_value_uint32(napi_env env,\n                                  napi_value value,\n                                  uint32_t* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: napi_value representing JavaScript Number.
      • \n
      • [out] result: C primitive equivalent of the given napi_value as a\nuint32_t.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.

      \n

      This API returns the C primitive equivalent of the given napi_value as a\nuint32_t.

      ", + "type": "module", + "displayName": "napi_get_value_uint32" + } + ], + "type": "module", + "displayName": "Functions to convert from N-API to C types" + }, + { + "textRaw": "Functions to get global instances", + "name": "functions_to_get_global_instances", + "modules": [ + { + "textRaw": "napi_get_boolean", + "name": "napi_get_boolean", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The value of the boolean to retrieve.
      • \n
      • [out] result: napi_value representing JavaScript Boolean singleton to\nretrieve.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API is used to return the JavaScript singleton object that is used to\nrepresent the given boolean value.

      ", + "type": "module", + "displayName": "napi_get_boolean" + }, + { + "textRaw": "napi_get_global", + "name": "napi_get_global", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_global(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing JavaScript global object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the global object.

      ", + "type": "module", + "displayName": "napi_get_global" + }, + { + "textRaw": "napi_get_null", + "name": "napi_get_null", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_null(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing JavaScript null object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the null object.

      ", + "type": "module", + "displayName": "napi_get_null" + }, + { + "textRaw": "napi_get_undefined", + "name": "napi_get_undefined", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_undefined(napi_env env, napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: napi_value representing JavaScript Undefined value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the Undefined object.

      ", + "type": "module", + "displayName": "napi_get_undefined" + } + ], + "type": "module", + "displayName": "Functions to get global instances" + } + ], + "type": "misc", + "displayName": "Working with JavaScript values" + }, + { + "textRaw": "Working with JavaScript values and abstract operations", + "name": "working_with_javascript_values_and_abstract_operations", + "desc": "

      N-API exposes a set of APIs to perform some abstract operations on JavaScript\nvalues. Some of these operations are documented under Section 7\nof the ECMAScript Language Specification.

      \n

      These APIs support doing one of the following:

      \n
        \n
      1. Coerce JavaScript values to specific JavaScript types (such as Number or\nString).
      2. \n
      3. Check the type of a JavaScript value.
      4. \n
      5. Check for equality between two JavaScript values.
      6. \n
      ", + "modules": [ + { + "textRaw": "napi_coerce_to_bool", + "name": "napi_coerce_to_bool", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_bool(napi_env env,\n                                napi_value value,\n                                napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript Boolean.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToBoolean() as defined in\nSection 7.1.2 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_bool" + }, + { + "textRaw": "napi_coerce_to_number", + "name": "napi_coerce_to_number", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_number(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript Number.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToNumber() as defined in\nSection 7.1.3 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_number" + }, + { + "textRaw": "napi_coerce_to_object", + "name": "napi_coerce_to_object", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_object(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript Object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToObject() as defined in\nSection 7.1.13 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_object" + }, + { + "textRaw": "napi_coerce_to_string", + "name": "napi_coerce_to_string", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_coerce_to_string(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to coerce.
      • \n
      • [out] result: napi_value representing the coerced JavaScript String.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API implements the abstract operation ToString() as defined in\nSection 7.1.13 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

      ", + "type": "module", + "displayName": "napi_coerce_to_string" + }, + { + "textRaw": "napi_typeof", + "name": "napi_typeof", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value whose type to query.
      • \n
      • [out] result: The type of the JavaScript value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n
        \n
      • napi_invalid_arg if the type of value is not a known ECMAScript type and\nvalue is not an External value.
      • \n
      \n

      This API represents behavior similar to invoking the typeof Operator on\nthe object as defined in Section 12.5.5 of the ECMAScript Language\nSpecification. However, there are some differences:

      \n
        \n
      1. It has support for detecting an External value.
      2. \n
      3. It detects null as a separate type, while ECMAScript typeof would detect\nobject.
      4. \n
      \n

      If value has a type that is invalid, an error is returned.

      ", + "type": "module", + "displayName": "napi_typeof" + }, + { + "textRaw": "napi_instanceof", + "name": "napi_instanceof", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_instanceof(napi_env env,\n                            napi_value object,\n                            napi_value constructor,\n                            bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] object: The JavaScript value to check.
      • \n
      • [in] constructor: The JavaScript function object of the constructor function\nto check against.
      • \n
      • [out] result: Boolean that is set to true if object instanceof constructor\nis true.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API represents invoking the instanceof Operator on the object as\ndefined in Section 12.10.4 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_instanceof" + }, + { + "textRaw": "napi_is_array", + "name": "napi_is_array", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_array(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given object is an array.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API represents invoking the IsArray operation on the object\nas defined in Section 7.2.2 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_is_array" + }, + { + "textRaw": "napi_is_arraybuffer", + "name": "napi_is_arraybuffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given object is an ArrayBuffer.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is an array buffer.

      ", + "type": "module", + "displayName": "napi_is_arraybuffer" + }, + { + "textRaw": "napi_is_buffer", + "name": "napi_is_buffer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a node::Buffer\nobject.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a buffer.

      ", + "type": "module", + "displayName": "napi_is_buffer" + }, + { + "textRaw": "napi_is_date", + "name": "napi_is_date", + "meta": { + "added": [ + "v11.11.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_date(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a JavaScript Date\nobject.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a date.

      ", + "type": "module", + "displayName": "napi_is_date" + }, + { + "textRaw": "napi_is_error", + "name": "napi_is_error", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_error(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents an Error object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is an Error.

      ", + "type": "module", + "displayName": "napi_is_error" + }, + { + "textRaw": "napi_is_typedarray", + "name": "napi_is_typedarray", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a TypedArray.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a typed array.

      ", + "type": "module", + "displayName": "napi_is_typedarray" + }, + { + "textRaw": "napi_is_dataview", + "name": "napi_is_dataview", + "meta": { + "added": [ + "v8.3.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The JavaScript value to check.
      • \n
      • [out] result: Whether the given napi_value represents a DataView.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in is a DataView.

      ", + "type": "module", + "displayName": "napi_is_dataview" + }, + { + "textRaw": "napi_strict_equals", + "name": "napi_strict_equals", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_strict_equals(napi_env env,\n                               napi_value lhs,\n                               napi_value rhs,\n                               bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] lhs: The JavaScript value to check.
      • \n
      • [in] rhs: The JavaScript value to check against.
      • \n
      • [out] result: Whether the two napi_value objects are equal.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API represents the invocation of the Strict Equality algorithm as\ndefined in Section 7.2.14 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_strict_equals" + }, + { + "textRaw": "napi_detach_arraybuffer", + "name": "napi_detach_arraybuffer", + "meta": { + "added": [ + "v12.16.0" + ], + "napiVersion": [ + 7 + ], + "changes": [] + }, + "desc": "
      napi_status napi_detach_arraybuffer(napi_env env,\n                                    napi_value arraybuffer)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] arraybuffer: The JavaScript ArrayBuffer to be detached.
      • \n
      \n

      Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is\npassed in it returns napi_detachable_arraybuffer_expected.

      \n

      Generally, an ArrayBuffer is non-detachable if it has been detached before.\nThe engine may impose additional conditions on whether an ArrayBuffer is\ndetachable. For example, V8 requires that the ArrayBuffer be external,\nthat is, created with napi_create_external_arraybuffer.

      \n

      This API represents the invocation of the ArrayBuffer detach operation as\ndefined in Section 24.1.1.3 of the ECMAScript Language Specification.

      ", + "type": "module", + "displayName": "napi_detach_arraybuffer" + }, + { + "textRaw": "napi_is_detached_arraybuffer", + "name": "napi_is_detached_arraybuffer", + "meta": { + "added": [ + "v12.16.0" + ], + "napiVersion": [ + 7 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_detached_arraybuffer(napi_env env,\n                                         napi_value arraybuffer,\n                                         bool* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] arraybuffer: The JavaScript ArrayBuffer to be checked.
      • \n
      • [out] result: Whether the arraybuffer is detached.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      The ArrayBuffer is considered detached if its internal data is null.

      \n

      This API represents the invocation of the ArrayBuffer IsDetachedBuffer\noperation as defined in Section 24.1.1.2 of the ECMAScript Language\nSpecification.

      ", + "type": "module", + "displayName": "napi_is_detached_arraybuffer" + } + ], + "type": "misc", + "displayName": "Working with JavaScript values and abstract operations" + }, + { + "textRaw": "Working with JavaScript properties", + "name": "working_with_javascript_properties", + "desc": "

      N-API exposes a set of APIs to get and set properties on JavaScript\nobjects. Some of these types are documented under Section 7 of the\nECMAScript Language Specification.

      \n

      Properties in JavaScript are represented as a tuple of a key and a value.\nFundamentally, all property keys in N-API can be represented in one of the\nfollowing forms:

      \n
        \n
      • Named: a simple UTF8-encoded string
      • \n
      • Integer-Indexed: an index value represented by uint32_t
      • \n
      • JavaScript value: these are represented in N-API by napi_value. This can\nbe a napi_value representing a String, Number, or Symbol.
      • \n
      \n

      N-API values are represented by the type napi_value.\nAny N-API call that requires a JavaScript value takes in a napi_value.\nHowever, it's the caller's responsibility to make sure that the\nnapi_value in question is of the JavaScript type expected by the API.

      \n

      The APIs documented in this section provide a simple interface to\nget and set properties on arbitrary JavaScript objects represented by\nnapi_value.

      \n

      For instance, consider the following JavaScript code snippet:

      \n
      const obj = {};\nobj.myProp = 123;\n
      \n

      The equivalent can be done using N-API values with the following snippet:

      \n
      napi_status status = napi_generic_failure;\n\n// const obj = {}\nnapi_value obj, value;\nstatus = napi_create_object(env, &obj);\nif (status != napi_ok) return status;\n\n// Create a napi_value for 123\nstatus = napi_create_int32(env, 123, &value);\nif (status != napi_ok) return status;\n\n// obj.myProp = 123\nstatus = napi_set_named_property(env, obj, \"myProp\", value);\nif (status != napi_ok) return status;\n
      \n

      Indexed properties can be set in a similar manner. Consider the following\nJavaScript snippet:

      \n
      const arr = [];\narr[123] = 'hello';\n
      \n

      The equivalent can be done using N-API values with the following snippet:

      \n
      napi_status status = napi_generic_failure;\n\n// const arr = [];\nnapi_value arr, value;\nstatus = napi_create_array(env, &arr);\nif (status != napi_ok) return status;\n\n// Create a napi_value for 'hello'\nstatus = napi_create_string_utf8(env, \"hello\", NAPI_AUTO_LENGTH, &value);\nif (status != napi_ok) return status;\n\n// arr[123] = 'hello';\nstatus = napi_set_element(env, arr, 123, value);\nif (status != napi_ok) return status;\n
      \n

      Properties can be retrieved using the APIs described in this section.\nConsider the following JavaScript snippet:

      \n
      const arr = [];\nconst value = arr[123];\n
      \n

      The following is the approximate equivalent of the N-API counterpart:

      \n
      napi_status status = napi_generic_failure;\n\n// const arr = []\nnapi_value arr, value;\nstatus = napi_create_array(env, &arr);\nif (status != napi_ok) return status;\n\n// const value = arr[123]\nstatus = napi_get_element(env, arr, 123, &value);\nif (status != napi_ok) return status;\n
      \n

      Finally, multiple properties can also be defined on an object for performance\nreasons. Consider the following JavaScript:

      \n
      const obj = {};\nObject.defineProperties(obj, {\n  'foo': { value: 123, writable: true, configurable: true, enumerable: true },\n  'bar': { value: 456, writable: true, configurable: true, enumerable: true }\n});\n
      \n

      The following is the approximate equivalent of the N-API counterpart:

      \n
      napi_status status = napi_status_generic_failure;\n\n// const obj = {};\nnapi_value obj;\nstatus = napi_create_object(env, &obj);\nif (status != napi_ok) return status;\n\n// Create napi_values for 123 and 456\nnapi_value fooValue, barValue;\nstatus = napi_create_int32(env, 123, &fooValue);\nif (status != napi_ok) return status;\nstatus = napi_create_int32(env, 456, &barValue);\nif (status != napi_ok) return status;\n\n// Set the properties\nnapi_property_descriptor descriptors[] = {\n  { \"foo\", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL },\n  { \"bar\", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL }\n}\nstatus = napi_define_properties(env,\n                                obj,\n                                sizeof(descriptors) / sizeof(descriptors[0]),\n                                descriptors);\nif (status != napi_ok) return status;\n
      ", + "modules": [ + { + "textRaw": "Structures", + "name": "structures", + "modules": [ + { + "textRaw": "napi_property_attributes", + "name": "napi_property_attributes", + "meta": { + "changes": [ + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/35214", + "description": "added `napi_default_method` and `napi_default_property`" + } + ] + }, + "desc": "
      typedef enum {\n  napi_default = 0,\n  napi_writable = 1 << 0,\n  napi_enumerable = 1 << 1,\n  napi_configurable = 1 << 2,\n\n  // Used with napi_define_class to distinguish static properties\n  // from instance properties. Ignored by napi_define_properties.\n  napi_static = 1 << 10,\n\n  // Default for class methods.\n  napi_default_method = napi_writable | napi_configurable,\n\n  // Default for object properties, like in JS obj[prop].\n  napi_default_property = napi_writable |\n                          napi_enumerable |\n                          napi_configurable,\n} napi_property_attributes;\n
      \n

      napi_property_attributes are flags used to control the behavior of properties\nset on a JavaScript object. Other than napi_static they correspond to the\nattributes listed in Section 6.1.7.1\nof the ECMAScript Language Specification.\nThey can be one or more of the following bitflags:

      \n
        \n
      • napi_default: No explicit attributes are set on the property. By default, a\nproperty is read only, not enumerable and not configurable.
      • \n
      • napi_writable: The property is writable.
      • \n
      • napi_enumerable: The property is enumerable.
      • \n
      • napi_configurable: The property is configurable as defined in\nSection 6.1.7.1 of the ECMAScript Language Specification.
      • \n
      • napi_static: The property will be defined as a static property on a class as\nopposed to an instance property, which is the default. This is used only by\nnapi_define_class. It is ignored by napi_define_properties.
      • \n
      • napi_default_method: The property is configureable, writeable but not\nenumerable like a method in a JS class.
      • \n
      • napi_default_property: The property is writable, enumerable and configurable\nlike a property set via JS code obj.key = value.
      • \n
      ", + "type": "module", + "displayName": "napi_property_attributes" + }, + { + "textRaw": "napi_property_descriptor", + "name": "napi_property_descriptor", + "desc": "
      typedef struct {\n  // One of utf8name or name should be NULL.\n  const char* utf8name;\n  napi_value name;\n\n  napi_callback method;\n  napi_callback getter;\n  napi_callback setter;\n  napi_value value;\n\n  napi_property_attributes attributes;\n  void* data;\n} napi_property_descriptor;\n
      \n
        \n
      • utf8name: Optional String describing the key for the property,\nencoded as UTF8. One of utf8name or name must be provided for the\nproperty.
      • \n
      • name: Optional napi_value that points to a JavaScript string or symbol\nto be used as the key for the property. One of utf8name or name must\nbe provided for the property.
      • \n
      • value: The value that's retrieved by a get access of the property if the\nproperty is a data property. If this is passed in, set getter, setter,\nmethod and data to NULL (since these members won't be used).
      • \n
      • getter: A function to call when a get access of the property is performed.\nIf this is passed in, set value and method to NULL (since these members\nwon't be used). The given function is called implicitly by the runtime when\nthe property is accessed from JavaScript code (or if a get on the property is\nperformed using a N-API call). napi_callback provides more details.
      • \n
      • setter: A function to call when a set access of the property is performed.\nIf this is passed in, set value and method to NULL (since these members\nwon't be used). The given function is called implicitly by the runtime when\nthe property is set from JavaScript code (or if a set on the property is\nperformed using a N-API call). napi_callback provides more details.
      • \n
      • method: Set this to make the property descriptor object's value\nproperty to be a JavaScript function represented by method. If this is\npassed in, set value, getter and setter to NULL (since these members\nwon't be used). napi_callback provides more details.
      • \n
      • attributes: The attributes associated with the particular property. See\nnapi_property_attributes.
      • \n
      • data: The callback data passed into method, getter and setter if this\nfunction is invoked.
      • \n
      ", + "type": "module", + "displayName": "napi_property_descriptor" + } + ], + "type": "module", + "displayName": "Structures" + }, + { + "textRaw": "Functions", + "name": "functions", + "modules": [ + { + "textRaw": "napi_get_property_names", + "name": "napi_get_property_names", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_property_names(napi_env env,\n                                    napi_value object,\n                                    napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the properties.
      • \n
      • [out] result: A napi_value representing an array of JavaScript values\nthat represent the property names of the object. The API can be used to\niterate over result using napi_get_array_length\nand napi_get_element.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the names of the enumerable properties of object as an array\nof strings. The properties of object whose key is a symbol will not be\nincluded.

      ", + "type": "module", + "displayName": "napi_get_property_names" + }, + { + "textRaw": "napi_get_all_property_names", + "name": "napi_get_all_property_names", + "meta": { + "added": [ + "v12.17.0" + ], + "napiVersion": [ + 6 + ], + "changes": [] + }, + "desc": "
      napi_get_all_property_names(napi_env env,\n                            napi_value object,\n                            napi_key_collection_mode key_mode,\n                            napi_key_filter key_filter,\n                            napi_key_conversion key_conversion,\n                            napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the properties.
      • \n
      • [in] key_mode: Whether to retrieve prototype properties as well.
      • \n
      • [in] key_filter: Which properties to retrieve\n(enumerable/readable/writable).
      • \n
      • [in] key_conversion: Whether to convert numbered property keys to strings.
      • \n
      • [out] result: A napi_value representing an array of JavaScript values\nthat represent the property names of the object. napi_get_array_length and\nnapi_get_element can be used to iterate over result.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns an array containing the names of the available properties\nof this object.

      ", + "type": "module", + "displayName": "napi_get_all_property_names" + }, + { + "textRaw": "napi_set_property", + "name": "napi_set_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              napi_value value);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object on which to set the property.
      • \n
      • [in] key: The name of the property to set.
      • \n
      • [in] value: The property value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API set a property on the Object passed in.

      ", + "type": "module", + "displayName": "napi_set_property" + }, + { + "textRaw": "napi_get_property", + "name": "napi_get_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the property.
      • \n
      • [in] key: The name of the property to retrieve.
      • \n
      • [out] result: The value of the property.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API gets the requested property from the Object passed in.

      ", + "type": "module", + "displayName": "napi_get_property" + }, + { + "textRaw": "napi_has_property", + "name": "napi_has_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] key: The name of the property whose existence to check.
      • \n
      • [out] result: Whether the property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in has the named property.

      ", + "type": "module", + "displayName": "napi_has_property" + }, + { + "textRaw": "napi_delete_property", + "name": "napi_delete_property", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_delete_property(napi_env env,\n                                 napi_value object,\n                                 napi_value key,\n                                 bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] key: The name of the property to delete.
      • \n
      • [out] result: Whether the property deletion succeeded or not. result can\noptionally be ignored by passing NULL.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API attempts to delete the key own property from object.

      ", + "type": "module", + "displayName": "napi_delete_property" + }, + { + "textRaw": "napi_has_own_property", + "name": "napi_has_own_property", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_own_property(napi_env env,\n                                  napi_value object,\n                                  napi_value key,\n                                  bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] key: The name of the own property whose existence to check.
      • \n
      • [out] result: Whether the own property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API checks if the Object passed in has the named own property. key must\nbe a string or a Symbol, or an error will be thrown. N-API will not perform\nany conversion between data types.

      ", + "type": "module", + "displayName": "napi_has_own_property" + }, + { + "textRaw": "napi_set_named_property", + "name": "napi_set_named_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    napi_value value);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object on which to set the property.
      • \n
      • [in] utf8Name: The name of the property to set.
      • \n
      • [in] value: The property value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is equivalent to calling napi_set_property with a napi_value\ncreated from the string passed in as utf8Name.

      ", + "type": "module", + "displayName": "napi_set_named_property" + }, + { + "textRaw": "napi_get_named_property", + "name": "napi_get_named_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the property.
      • \n
      • [in] utf8Name: The name of the property to get.
      • \n
      • [out] result: The value of the property.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is equivalent to calling napi_get_property with a napi_value\ncreated from the string passed in as utf8Name.

      ", + "type": "module", + "displayName": "napi_get_named_property" + }, + { + "textRaw": "napi_has_named_property", + "name": "napi_has_named_property", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] utf8Name: The name of the property whose existence to check.
      • \n
      • [out] result: Whether the property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is equivalent to calling napi_has_property with a napi_value\ncreated from the string passed in as utf8Name.

      ", + "type": "module", + "displayName": "napi_has_named_property" + }, + { + "textRaw": "napi_set_element", + "name": "napi_set_element", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_set_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             napi_value value);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to set the properties.
      • \n
      • [in] index: The index of the property to set.
      • \n
      • [in] value: The property value.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API sets and element on the Object passed in.

      ", + "type": "module", + "displayName": "napi_set_element" + }, + { + "textRaw": "napi_get_element", + "name": "napi_get_element", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the property.
      • \n
      • [in] index: The index of the property to get.
      • \n
      • [out] result: The value of the property.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API gets the element at the requested index.

      ", + "type": "module", + "displayName": "napi_get_element" + }, + { + "textRaw": "napi_has_element", + "name": "napi_has_element", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_has_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] index: The index of the property whose existence to check.
      • \n
      • [out] result: Whether the property exists on the object or not.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns if the Object passed in has an element at the\nrequested index.

      ", + "type": "module", + "displayName": "napi_has_element" + }, + { + "textRaw": "napi_delete_element", + "name": "napi_delete_element", + "meta": { + "added": [ + "v8.2.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_delete_element(napi_env env,\n                                napi_value object,\n                                uint32_t index,\n                                bool* result);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to query.
      • \n
      • [in] index: The index of the property to delete.
      • \n
      • [out] result: Whether the element deletion succeeded or not. result can\noptionally be ignored by passing NULL.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API attempts to delete the specified index from object.

      ", + "type": "module", + "displayName": "napi_delete_element" + }, + { + "textRaw": "napi_define_properties", + "name": "napi_define_properties", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_define_properties(napi_env env,\n                                   napi_value object,\n                                   size_t property_count,\n                                   const napi_property_descriptor* properties);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object from which to retrieve the properties.
      • \n
      • [in] property_count: The number of elements in the properties array.
      • \n
      • [in] properties: The array of property descriptors.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method allows the efficient definition of multiple properties on a given\nobject. The properties are defined using property descriptors (see\nnapi_property_descriptor). Given an array of such property descriptors,\nthis API will set the properties on the object one at a time, as defined by\nDefineOwnProperty() (described in Section 9.1.6 of the ECMA-262\nspecification).

      ", + "type": "module", + "displayName": "napi_define_properties" + }, + { + "textRaw": "napi_object_freeze", + "name": "napi_object_freeze", + "meta": { + "added": [ + "v12.20.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_object_freeze(napi_env env,\n                               napi_value object);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to freeze.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method freezes a given object. This prevents new properties from\nbeing added to it, existing properties from being removed, prevents\nchanging the enumerability, configurability, or writability of existing\nproperties, and prevents the values of existing properties from being changed.\nIt also prevents the object's prototype from being changed. This is described\nin Section 19.1.2.6 of the\nECMA-262 specification.

      ", + "type": "module", + "displayName": "napi_object_freeze" + }, + { + "textRaw": "napi_object_seal", + "name": "napi_object_seal", + "meta": { + "added": [ + "v12.20.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_object_seal(napi_env env,\n                             napi_value object);\n
      \n
        \n
      • [in] env: The environment that the N-API call is invoked under.
      • \n
      • [in] object: The object to seal.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method seals a given object. This prevents new properties from being\nadded to it, as well as marking all existing properties as non-configurable.\nThis is described in Section 19.1.2.20\nof the ECMA-262 specification.

      ", + "type": "module", + "displayName": "napi_object_seal" + } + ], + "type": "module", + "displayName": "Functions" + } + ], + "type": "misc", + "displayName": "Working with JavaScript properties" + }, + { + "textRaw": "Working with JavaScript functions", + "name": "working_with_javascript_functions", + "desc": "

      N-API provides a set of APIs that allow JavaScript code to\ncall back into native code. N-API APIs that support calling back\ninto native code take in a callback functions represented by\nthe napi_callback type. When the JavaScript VM calls back to\nnative code, the napi_callback function provided is invoked. The APIs\ndocumented in this section allow the callback function to do the\nfollowing:

      \n
        \n
      • Get information about the context in which the callback was invoked.
      • \n
      • Get the arguments passed into the callback.
      • \n
      • Return a napi_value back from the callback.
      • \n
      \n

      Additionally, N-API provides a set of functions which allow calling\nJavaScript functions from native code. One can either call a function\nlike a regular JavaScript function call, or as a constructor\nfunction.

      \n

      Any non-NULL data which is passed to this API via the data field of the\nnapi_property_descriptor items can be associated with object and freed\nwhenever object is garbage-collected by passing both object and the data to\nnapi_add_finalizer.

      ", + "modules": [ + { + "textRaw": "napi_call_function", + "name": "napi_call_function", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_call_function(napi_env env,\n                                           napi_value recv,\n                                           napi_value func,\n                                           size_t argc,\n                                           const napi_value* argv,\n                                           napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] recv: The this object passed to the called function.
      • \n
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • \n
      • [in] argc: The count of elements in the argv array.
      • \n
      • [in] argv: Array of napi_values representing JavaScript values passed in\nas arguments to the function.
      • \n
      • [out] result: napi_value representing the JavaScript object returned.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method allows a JavaScript function object to be called from a native\nadd-on. This is the primary mechanism of calling back from the add-on's\nnative code into JavaScript. For the special case of calling into JavaScript\nafter an async operation, see napi_make_callback.

      \n

      A sample use case might look as follows. Consider the following JavaScript\nsnippet:

      \n
      function AddTwo(num) {\n  return num + 2;\n}\n
      \n

      Then, the above function can be invoked from a native add-on using the\nfollowing code:

      \n
      // Get the function named \"AddTwo\" on the global object\nnapi_value global, add_two, arg;\nnapi_status status = napi_get_global(env, &global);\nif (status != napi_ok) return;\n\nstatus = napi_get_named_property(env, global, \"AddTwo\", &add_two);\nif (status != napi_ok) return;\n\n// const arg = 1337\nstatus = napi_create_int32(env, 1337, &arg);\nif (status != napi_ok) return;\n\nnapi_value* argv = &arg;\nsize_t argc = 1;\n\n// AddTwo(arg);\nnapi_value return_val;\nstatus = napi_call_function(env, global, add_two, argc, argv, &return_val);\nif (status != napi_ok) return;\n\n// Convert the result back to a native type\nint32_t result;\nstatus = napi_get_value_int32(env, return_val, &result);\nif (status != napi_ok) return;\n
      ", + "type": "module", + "displayName": "napi_call_function" + }, + { + "textRaw": "napi_create_function", + "name": "napi_create_function", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_function(napi_env env,\n                                 const char* utf8name,\n                                 size_t length,\n                                 napi_callback cb,\n                                 void* data,\n                                 napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] utf8Name: The name of the function encoded as UTF8. This is visible\nwithin JavaScript as the new function object's name property.
      • \n
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH if\nit is null-terminated.
      • \n
      • [in] cb: The native function which should be called when this function\nobject is invoked. napi_callback provides more details.
      • \n
      • [in] data: User-provided data context. This will be passed back into the\nfunction when invoked later.
      • \n
      • [out] result: napi_value representing the JavaScript function object for\nthe newly created function.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allows an add-on author to create a function object in native code.\nThis is the primary mechanism to allow calling into the add-on's native code\nfrom JavaScript.

      \n

      The newly created function is not automatically visible from script after this\ncall. Instead, a property must be explicitly set on any object that is visible\nto JavaScript, in order for the function to be accessible from script.

      \n

      In order to expose a function as part of the\nadd-on's module exports, set the newly created function on the exports\nobject. A sample module might look as follows:

      \n
      napi_value SayHello(napi_env env, napi_callback_info info) {\n  printf(\"Hello\\n\");\n  return NULL;\n}\n\nnapi_value Init(napi_env env, napi_value exports) {\n  napi_status status;\n\n  napi_value fn;\n  status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);\n  if (status != napi_ok) return NULL;\n\n  status = napi_set_named_property(env, exports, \"sayHello\", fn);\n  if (status != napi_ok) return NULL;\n\n  return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n
      \n

      Given the above code, the add-on can be used from JavaScript as follows:

      \n
      const myaddon = require('./addon');\nmyaddon.sayHello();\n
      \n

      The string passed to require() is the name of the target in binding.gyp\nresponsible for creating the .node file.

      \n

      Any non-NULL data which is passed to this API via the data parameter can\nbe associated with the resulting JavaScript function (which is returned in the\nresult parameter) and freed whenever the function is garbage-collected by\npassing both the JavaScript function and the data to napi_add_finalizer.

      \n

      JavaScript Functions are described in Section 19.2 of the ECMAScript\nLanguage Specification.

      ", + "type": "module", + "displayName": "napi_create_function" + }, + { + "textRaw": "napi_get_cb_info", + "name": "napi_get_cb_info", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_cb_info(napi_env env,\n                             napi_callback_info cbinfo,\n                             size_t* argc,\n                             napi_value* argv,\n                             napi_value* thisArg,\n                             void** data)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] cbinfo: The callback info passed into the callback function.
      • \n
      • [in-out] argc: Specifies the size of the provided argv array and receives\nthe actual count of arguments.
      • \n
      • [out] argv: Buffer to which the napi_value representing the arguments are\ncopied. If there are more arguments than the provided count, only the\nrequested number of arguments are copied. If there are fewer arguments\nprovided than claimed, the rest of argv is filled with napi_value values\nthat represent undefined.
      • \n
      • [out] this: Receives the JavaScript this argument for the call.
      • \n
      • [out] data: Receives the data pointer for the callback.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method is used within a callback function to retrieve details about the\ncall like the arguments and the this pointer from a given callback info.

      ", + "type": "module", + "displayName": "napi_get_cb_info" + }, + { + "textRaw": "napi_get_new_target", + "name": "napi_get_new_target", + "meta": { + "added": [ + "v8.6.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_new_target(napi_env env,\n                                napi_callback_info cbinfo,\n                                napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] cbinfo: The callback info passed into the callback function.
      • \n
      • [out] result: The new.target of the constructor call.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the new.target of the constructor call. If the current\ncallback is not a constructor call, the result is NULL.

      ", + "type": "module", + "displayName": "napi_get_new_target" + }, + { + "textRaw": "napi_new_instance", + "name": "napi_new_instance", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_new_instance(napi_env env,\n                              napi_value cons,\n                              size_t argc,\n                              napi_value* argv,\n                              napi_value* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] cons: napi_value representing the JavaScript function to be invoked\nas a constructor.
      • \n
      • [in] argc: The count of elements in the argv array.
      • \n
      • [in] argv: Array of JavaScript values as napi_value representing the\narguments to the constructor.
      • \n
      • [out] result: napi_value representing the JavaScript object returned,\nwhich in this case is the constructed object.
      • \n
      \n

      This method is used to instantiate a new JavaScript value using a given\nnapi_value that represents the constructor for the object. For example,\nconsider the following snippet:

      \n
      function MyObject(param) {\n  this.param = param;\n}\n\nconst arg = 'hello';\nconst value = new MyObject(arg);\n
      \n

      The following can be approximated in N-API using the following snippet:

      \n
      // Get the constructor function MyObject\nnapi_value global, constructor, arg, value;\nnapi_status status = napi_get_global(env, &global);\nif (status != napi_ok) return;\n\nstatus = napi_get_named_property(env, global, \"MyObject\", &constructor);\nif (status != napi_ok) return;\n\n// const arg = \"hello\"\nstatus = napi_create_string_utf8(env, \"hello\", NAPI_AUTO_LENGTH, &arg);\nif (status != napi_ok) return;\n\nnapi_value* argv = &arg;\nsize_t argc = 1;\n\n// const value = new MyObject(arg)\nstatus = napi_new_instance(env, constructor, argc, argv, &value);\n
      \n

      Returns napi_ok if the API succeeded.

      ", + "type": "module", + "displayName": "napi_new_instance" + } + ], + "type": "misc", + "displayName": "Working with JavaScript functions" + }, + { + "textRaw": "Object wrap", + "name": "object_wrap", + "desc": "

      N-API offers a way to \"wrap\" C++ classes and instances so that the class\nconstructor and methods can be called from JavaScript.

      \n
        \n
      1. The napi_define_class API defines a JavaScript class with constructor,\nstatic properties and methods, and instance properties and methods that\ncorrespond to the C++ class.
      2. \n
      3. When JavaScript code invokes the constructor, the constructor callback\nuses napi_wrap to wrap a new C++ instance in a JavaScript object,\nthen returns the wrapper object.
      4. \n
      5. When JavaScript code invokes a method or property accessor on the class,\nthe corresponding napi_callback C++ function is invoked. For an instance\ncallback, napi_unwrap obtains the C++ instance that is the target of\nthe call.
      6. \n
      \n

      For wrapped objects it may be difficult to distinguish between a function\ncalled on a class prototype and a function called on an instance of a class.\nA common pattern used to address this problem is to save a persistent\nreference to the class constructor for later instanceof checks.

      \n
      napi_value MyClass_constructor = NULL;\nstatus = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);\nassert(napi_ok == status);\nbool is_instance = false;\nstatus = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);\nassert(napi_ok == status);\nif (is_instance) {\n  // napi_unwrap() ...\n} else {\n  // otherwise...\n}\n
      \n

      The reference must be freed once it is no longer needed.

      \n

      There are occasions where napi_instanceof() is insufficient for ensuring that\na JavaScript object is a wrapper for a certain native type. This is the case\nespecially when wrapped JavaScript objects are passed back into the addon via\nstatic methods rather than as the this value of prototype methods. In such\ncases there is a chance that they may be unwrapped incorrectly.

      \n
      const myAddon = require('./build/Release/my_addon.node');\n\n// `openDatabase()` returns a JavaScript object that wraps a native database\n// handle.\nconst dbHandle = myAddon.openDatabase();\n\n// `query()` returns a JavaScript object that wraps a native query handle.\nconst queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!');\n\n// There is an accidental error in the line below. The first parameter to\n// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not\n// the query handle (`query`), so the correct condition for the while-loop\n// should be\n//\n// myAddon.queryHasRecords(dbHandle, queryHandle)\n//\nwhile (myAddon.queryHasRecords(queryHandle, dbHandle)) {\n  // retrieve records\n}\n
      \n

      In the above example myAddon.queryHasRecords() is a method that accepts two\narguments. The first is a database handle and the second is a query handle.\nInternally, it unwraps the first argument and casts the resulting pointer to a\nnative database handle. It then unwraps the second argument and casts the\nresulting pointer to a query handle. If the arguments are passed in the wrong\norder, the casts will work, however, there is a good chance that the underlying\ndatabase operation will fail, or will even cause an invalid memory access.

      \n

      To ensure that the pointer retrieved from the first argument is indeed a pointer\nto a database handle and, similarly, that the pointer retrieved from the second\nargument is indeed a pointer to a query handle, the implementation of\nqueryHasRecords() has to perform a type validation. Retaining the JavaScript\nclass constructor from which the database handle was instantiated and the\nconstructor from which the query handle was instantiated in napi_refs can\nhelp, because napi_instanceof() can then be used to ensure that the instances\npassed into queryHashRecords() are indeed of the correct type.

      \n

      Unfortunately, napi_instanceof() does not protect against prototype\nmanipulation. For example, the prototype of the database handle instance can be\nset to the prototype of the constructor for query handle instances. In this\ncase, the database handle instance can appear as a query handle instance, and it\nwill pass the napi_instanceof() test for a query handle instance, while still\ncontaining a pointer to a database handle.

      \n

      To this end, N-API provides type-tagging capabilities.

      \n

      A type tag is a 128-bit integer unique to the addon. N-API provides the\nnapi_type_tag structure for storing a type tag. When such a value is passed\nalong with a JavaScript object stored in a napi_value to\nnapi_type_tag_object(), the JavaScript object will be \"marked\" with the\ntype tag. The \"mark\" is invisible on the JavaScript side. When a JavaScript\nobject arrives into a native binding, napi_check_object_type_tag() can be used\nalong with the original type tag to determine whether the JavaScript object was\npreviously \"marked\" with the type tag. This creates a type-checking capability\nof a higher fidelity than napi_instanceof() can provide, because such type-\ntagging survives prototype manipulation and addon unloading/reloading.

      \n

      Continuing the above example, the following skeleton addon implementation\nillustrates the use of napi_type_tag_object() and\nnapi_check_object_type_tag().

      \n
      // This value is the type tag for a database handle. The command\n//\n//   uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\\1, 0x\\2/'\n//\n// can be used to obtain the two values with which to initialize the structure.\nstatic const napi_type_tag DatabaseHandleTypeTag = {\n  0x1edf75a38336451d, 0xa5ed9ce2e4c00c38\n};\n\n// This value is the type tag for a query handle.\nstatic const napi_type_tag QueryHandleTypeTag = {\n  0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a\n};\n\nstatic napi_value\nopenDatabase(napi_env env, napi_callback_info info) {\n  napi_status status;\n  napi_value result;\n\n  // Perform the underlying action which results in a database handle.\n  DatabaseHandle* dbHandle = open_database();\n\n  // Create a new, empty JS object.\n  status = napi_create_object(env, &result);\n  if (status != napi_ok) return NULL;\n\n  // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.\n  status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);\n  if (status != napi_ok) return NULL;\n\n  // Store the pointer to the `DatabaseHandle` structure inside the JS object.\n  status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL);\n  if (status != napi_ok) return NULL;\n\n  return result;\n}\n\n// Later when we receive a JavaScript object purporting to be a database handle\n// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a\n// handle.\n\nstatic napi_value\nquery(napi_env env, napi_callback_info info) {\n  napi_status status;\n  size_t argc = 2;\n  napi_value argv[2];\n  bool is_db_handle;\n\n  status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);\n  if (status != napi_ok) return NULL;\n\n  // Check that the object passed as the first parameter has the previously\n  // applied tag.\n  status = napi_check_object_type_tag(env,\n                                      argv[0],\n                                      &DatabaseHandleTypeTag,\n                                      &is_db_handle);\n  if (status != napi_ok) return NULL;\n\n  // Throw a `TypeError` if it doesn't.\n  if (!is_db_handle) {\n    // Throw a TypeError.\n    return NULL;\n  }\n}\n
      ", + "modules": [ + { + "textRaw": "napi_define_class", + "name": "napi_define_class", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_define_class(napi_env env,\n                              const char* utf8name,\n                              size_t length,\n                              napi_callback constructor,\n                              void* data,\n                              size_t property_count,\n                              const napi_property_descriptor* properties,\n                              napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] utf8name: Name of the JavaScript constructor function; this is\nnot required to be the same as the C++ class name, though it is recommended\nfor clarity.
      • \n
      • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH\nif it is null-terminated.
      • \n
      • [in] constructor: Callback function that handles constructing instances\nof the class. This should be a static method on the class, not an actual\nC++ constructor function. napi_callback provides more details.
      • \n
      • [in] data: Optional data to be passed to the constructor callback as\nthe data property of the callback info.
      • \n
      • [in] property_count: Number of items in the properties array argument.
      • \n
      • [in] properties: Array of property descriptors describing static and\ninstance data properties, accessors, and methods on the class\nSee napi_property_descriptor.
      • \n
      • [out] result: A napi_value representing the constructor function for\nthe class.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Defines a JavaScript class that corresponds to a C++ class, including:

      \n
        \n
      • A JavaScript constructor function that has the class name and invokes the\nprovided C++ constructor callback.
      • \n
      • Properties on the constructor function corresponding to static data\nproperties, accessors, and methods of the C++ class (defined by\nproperty descriptors with the napi_static attribute).
      • \n
      • Properties on the constructor function's prototype object corresponding to\nnon-static data properties, accessors, and methods of the C++ class\n(defined by property descriptors without the napi_static attribute).
      • \n
      \n

      The C++ constructor callback should be a static method on the class that calls\nthe actual class constructor, then wraps the new C++ instance in a JavaScript\nobject, and returns the wrapper object. See napi_wrap() for details.

      \n

      The JavaScript constructor function returned from napi_define_class is\noften saved and used later, to construct new instances of the class from native\ncode, and/or check whether provided values are instances of the class. In that\ncase, to prevent the function value from being garbage-collected, create a\npersistent reference to it using napi_create_reference and ensure the\nreference count is kept >= 1.

      \n

      Any non-NULL data which is passed to this API via the data parameter or via\nthe data field of the napi_property_descriptor array items can be associated\nwith the resulting JavaScript constructor (which is returned in the result\nparameter) and freed whenever the class is garbage-collected by passing both\nthe JavaScript function and the data to napi_add_finalizer.

      ", + "type": "module", + "displayName": "napi_define_class" + }, + { + "textRaw": "napi_wrap", + "name": "napi_wrap", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_wrap(napi_env env,\n                      napi_value js_object,\n                      void* native_object,\n                      napi_finalize finalize_cb,\n                      void* finalize_hint,\n                      napi_ref* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object that will be the wrapper for the\nnative object.
      • \n
      • [in] native_object: The native instance that will be wrapped in the\nJavaScript object.
      • \n
      • [in] finalize_cb: Optional native callback that can be used to free the\nnative instance when the JavaScript object is ready for garbage-collection.\nnapi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.
      • \n
      • [out] result: Optional reference to the wrapped object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Wraps a native instance in a JavaScript object. The native instance can be\nretrieved later using napi_unwrap().

      \n

      When JavaScript code invokes a constructor for a class that was defined using\nnapi_define_class(), the napi_callback for the constructor is invoked.\nAfter constructing an instance of the native class, the callback must then call\nnapi_wrap() to wrap the newly constructed instance in the already-created\nJavaScript object that is the this argument to the constructor callback.\n(That this object was created from the constructor function's prototype,\nso it already has definitions of all the instance properties and methods.)

      \n

      Typically when wrapping a class instance, a finalize callback should be\nprovided that simply deletes the native instance that is received as the data\nargument to the finalize callback.

      \n

      The optional returned reference is initially a weak reference, meaning it\nhas a reference count of 0. Typically this reference count would be incremented\ntemporarily during async operations that require the instance to remain valid.

      \n

      Caution: The optional returned reference (if obtained) should be deleted via\nnapi_delete_reference ONLY in response to the finalize callback\ninvocation. If it is deleted before then, then the finalize callback may never\nbe invoked. Therefore, when obtaining a reference a finalize callback is also\nrequired in order to enable correct disposal of the reference.

      \n

      Calling napi_wrap() a second time on an object will return an error. To\nassociate another native instance with the object, use napi_remove_wrap()\nfirst.

      ", + "type": "module", + "displayName": "napi_wrap" + }, + { + "textRaw": "napi_unwrap", + "name": "napi_unwrap", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_unwrap(napi_env env,\n                        napi_value js_object,\n                        void** result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The object associated with the native instance.
      • \n
      • [out] result: Pointer to the wrapped native instance.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Retrieves a native instance that was previously wrapped in a JavaScript\nobject using napi_wrap().

      \n

      When JavaScript code invokes a method or property accessor on the class, the\ncorresponding napi_callback is invoked. If the callback is for an instance\nmethod or accessor, then the this argument to the callback is the wrapper\nobject; the wrapped C++ instance that is the target of the call can be obtained\nthen by calling napi_unwrap() on the wrapper object.

      ", + "type": "module", + "displayName": "napi_unwrap" + }, + { + "textRaw": "napi_remove_wrap", + "name": "napi_remove_wrap", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_remove_wrap(napi_env env,\n                             napi_value js_object,\n                             void** result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The object associated with the native instance.
      • \n
      • [out] result: Pointer to the wrapped native instance.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Retrieves a native instance that was previously wrapped in the JavaScript\nobject js_object using napi_wrap() and removes the wrapping. If a finalize\ncallback was associated with the wrapping, it will no longer be called when the\nJavaScript object becomes garbage-collected.

      ", + "type": "module", + "displayName": "napi_remove_wrap" + }, + { + "textRaw": "napi_type_tag_object", + "name": "napi_type_tag_object", + "meta": { + "added": [ + "v12.19.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_type_tag_object(napi_env env,\n                                 napi_value js_object,\n                                 const napi_type_tag* type_tag);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object to be marked.
      • \n
      • [in] type_tag: The tag with which the object is to be marked.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Associates the value of the type_tag pointer with the JavaScript object.\nnapi_check_object_type_tag() can then be used to compare the tag that was\nattached to the object with one owned by the addon to ensure that the object\nhas the right type.

      \n

      If the object already has an associated type tag, this API will return\nnapi_invalid_arg.

      ", + "type": "module", + "displayName": "napi_type_tag_object" + }, + { + "textRaw": "napi_check_object_type_tag", + "name": "napi_check_object_type_tag", + "meta": { + "added": [ + "v12.19.0" + ], + "napiVersion": [ + 8 + ], + "changes": [] + }, + "desc": "
      napi_status napi_check_object_type_tag(napi_env env,\n                                       napi_value js_object,\n                                       const napi_type_tag* type_tag,\n                                       bool* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object whose type tag to examine.
      • \n
      • [in] type_tag: The tag with which to compare any tag found on the object.
      • \n
      • [out] result: Whether the type tag given matched the type tag on the\nobject. false is also returned if no type tag was found on the object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Compares the pointer given as type_tag with any that can be found on\njs_object. If no tag is found on js_object or, if a tag is found but it does\nnot match type_tag, then result is set to false. If a tag is found and it\nmatches type_tag, then result is set to true.

      ", + "type": "module", + "displayName": "napi_check_object_type_tag" + }, + { + "textRaw": "napi_add_finalizer", + "name": "napi_add_finalizer", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 5 + ], + "changes": [] + }, + "desc": "
      napi_status napi_add_finalizer(napi_env env,\n                               napi_value js_object,\n                               void* native_object,\n                               napi_finalize finalize_cb,\n                               void* finalize_hint,\n                               napi_ref* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] js_object: The JavaScript object to which the native data will be\nattached.
      • \n
      • [in] native_object: The native data that will be attached to the JavaScript\nobject.
      • \n
      • [in] finalize_cb: Native callback that will be used to free the\nnative data when the JavaScript object is ready for garbage-collection.\nnapi_finalize provides more details.
      • \n
      • [in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.
      • \n
      • [out] result: Optional reference to the JavaScript object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      Adds a napi_finalize callback which will be called when the JavaScript object\nin js_object is ready for garbage collection. This API is similar to\nnapi_wrap() except that:

      \n
        \n
      • the native data cannot be retrieved later using napi_unwrap(),
      • \n
      • nor can it be removed later using napi_remove_wrap(), and
      • \n
      • the API can be called multiple times with different data items in order to\nattach each of them to the JavaScript object, and
      • \n
      • the object manipulated by the API can be used with napi_wrap().
      • \n
      \n

      Caution: The optional returned reference (if obtained) should be deleted via\nnapi_delete_reference ONLY in response to the finalize callback\ninvocation. If it is deleted before then, then the finalize callback may never\nbe invoked. Therefore, when obtaining a reference a finalize callback is also\nrequired in order to enable correct disposal of the reference.

      ", + "type": "module", + "displayName": "napi_add_finalizer" + } + ], + "type": "misc", + "displayName": "Object wrap" + }, + { + "textRaw": "Simple asynchronous operations", + "name": "simple_asynchronous_operations", + "desc": "

      Addon modules often need to leverage async helpers from libuv as part of their\nimplementation. This allows them to schedule work to be executed asynchronously\nso that their methods can return in advance of the work being completed. This\nallows them to avoid blocking overall execution of the Node.js application.

      \n

      N-API provides an ABI-stable interface for these\nsupporting functions which covers the most common asynchronous use cases.

      \n

      N-API defines the napi_async_work structure which is used to manage\nasynchronous workers. Instances are created/deleted with\nnapi_create_async_work and napi_delete_async_work.

      \n

      The execute and complete callbacks are functions that will be\ninvoked when the executor is ready to execute and when it completes its\ntask respectively.

      \n

      The execute function should avoid making any N-API calls\nthat could result in the execution of JavaScript or interaction with\nJavaScript objects. Most often, any code that needs to make N-API\ncalls should be made in complete callback instead.\nAvoid using the napi_env parameter in the execute callback as\nit will likely execute JavaScript.

      \n

      These functions implement the following interfaces:

      \n
      typedef void (*napi_async_execute_callback)(napi_env env,\n                                            void* data);\ntypedef void (*napi_async_complete_callback)(napi_env env,\n                                             napi_status status,\n                                             void* data);\n
      \n

      When these methods are invoked, the data parameter passed will be the\naddon-provided void* data that was passed into the\nnapi_create_async_work call.

      \n

      Once created the async worker can be queued\nfor execution using the napi_queue_async_work function:

      \n
      napi_status napi_queue_async_work(napi_env env,\n                                  napi_async_work work);\n
      \n

      napi_cancel_async_work can be used if the work needs\nto be cancelled before the work has started execution.

      \n

      After calling napi_cancel_async_work, the complete callback\nwill be invoked with a status value of napi_cancelled.\nThe work should not be deleted before the complete\ncallback invocation, even when it was cancelled.

      ", + "modules": [ + { + "textRaw": "napi_create_async_work", + "name": "napi_create_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [ + { + "version": "v8.6.0", + "pr-url": "https://github.com/nodejs/node/pull/14697", + "description": "Added `async_resource` and `async_resource_name` parameters." + } + ] + }, + "desc": "
      napi_status napi_create_async_work(napi_env env,\n                                   napi_value async_resource,\n                                   napi_value async_resource_name,\n                                   napi_async_execute_callback execute,\n                                   napi_async_complete_callback complete,\n                                   void* data,\n                                   napi_async_work* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_resource: An optional object associated with the async work\nthat will be passed to possible async_hooks init hooks.
      • \n
      • [in] async_resource_name: Identifier for the kind of resource that is being\nprovided for diagnostic information exposed by the async_hooks API.
      • \n
      • [in] execute: The native function which should be called to execute the\nlogic asynchronously. The given function is called from a worker pool thread\nand can execute in parallel with the main event loop thread.
      • \n
      • [in] complete: The native function which will be called when the\nasynchronous logic is completed or is cancelled. The given function is called\nfrom the main event loop thread. napi_async_complete_callback provides\nmore details.
      • \n
      • [in] data: User-provided data context. This will be passed back into the\nexecute and complete functions.
      • \n
      • [out] result: napi_async_work* which is the handle to the newly created\nasync work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API allocates a work object that is used to execute logic asynchronously.\nIt should be freed using napi_delete_async_work once the work is no longer\nrequired.

      \n

      async_resource_name should be a null-terminated, UTF-8-encoded string.

      \n

      The async_resource_name identifier is provided by the user and should be\nrepresentative of the type of async work being performed. It is also recommended\nto apply namespacing to the identifier, e.g. by including the module name. See\nthe async_hooks documentation for more information.

      ", + "type": "module", + "displayName": "napi_create_async_work" + }, + { + "textRaw": "napi_delete_async_work", + "name": "napi_delete_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_delete_async_work(napi_env env,\n                                   napi_async_work work);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] work: The handle returned by the call to napi_create_async_work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API frees a previously allocated work object.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_delete_async_work" + }, + { + "textRaw": "napi_queue_async_work", + "name": "napi_queue_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_queue_async_work(napi_env env,\n                                  napi_async_work work);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] work: The handle returned by the call to napi_create_async_work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API requests that the previously allocated work be scheduled\nfor execution. Once it returns successfully, this API must not be called again\nwith the same napi_async_work item or the result will be undefined.

      ", + "type": "module", + "displayName": "napi_queue_async_work" + }, + { + "textRaw": "napi_cancel_async_work", + "name": "napi_cancel_async_work", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_cancel_async_work(napi_env env,\n                                   napi_async_work work);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] work: The handle returned by the call to napi_create_async_work.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API cancels queued work if it has not yet\nbeen started. If it has already started executing, it cannot be\ncancelled and napi_generic_failure will be returned. If successful,\nthe complete callback will be invoked with a status value of\nnapi_cancelled. The work should not be deleted before the complete\ncallback invocation, even if it has been successfully cancelled.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_cancel_async_work" + } + ], + "type": "misc", + "displayName": "Simple asynchronous operations" + }, + { + "textRaw": "Custom asynchronous operations", + "name": "custom_asynchronous_operations", + "desc": "

      The simple asynchronous work APIs above may not be appropriate for every\nscenario. When using any other asynchronous mechanism, the following APIs\nare necessary to ensure an asynchronous operation is properly tracked by\nthe runtime.

      ", + "modules": [ + { + "textRaw": "napi_async_init", + "name": "napi_async_init", + "meta": { + "added": [ + "v8.6.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_async_init(napi_env env,\n                            napi_value async_resource,\n                            napi_value async_resource_name,\n                            napi_async_context* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_resource: Object associated with the async work\nthat will be passed to possible async_hooks init hooks.\nIn order to retain ABI compatibility with previous versions,\npassing NULL for async_resource will not result in an error, however,\nthis will result incorrect operation of async hooks for the\nnapi_async_context created. Potential issues include\nloss of async context when using the AsyncLocalStorage API.
      • \n
      • [in] async_resource_name: Identifier for the kind of resource\nthat is being provided for diagnostic information exposed by the\nasync_hooks API.
      • \n
      • [out] result: The initialized async context.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      ", + "type": "module", + "displayName": "napi_async_init" + }, + { + "textRaw": "napi_async_destroy", + "name": "napi_async_destroy", + "meta": { + "added": [ + "v8.6.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_async_destroy(napi_env env,\n                               napi_async_context async_context);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_context: The async context to be destroyed.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_async_destroy" + }, + { + "textRaw": "napi_make_callback", + "name": "napi_make_callback", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [ + { + "version": "v8.6.0", + "description": "Added `async_context` parameter." + } + ] + }, + "desc": "
      NAPI_EXTERN napi_status napi_make_callback(napi_env env,\n                                           napi_async_context async_context,\n                                           napi_value recv,\n                                           napi_value func,\n                                           size_t argc,\n                                           const napi_value* argv,\n                                           napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] async_context: Context for the async operation that is\ninvoking the callback. This should normally be a value previously\nobtained from napi_async_init. However NULL is also allowed,\nwhich indicates the current async context (if any) is to be used\nfor the callback.
      • \n
      • [in] recv: The this object passed to the called function.
      • \n
      • [in] func: napi_value representing the JavaScript function to be invoked.
      • \n
      • [in] argc: The count of elements in the argv array.
      • \n
      • [in] argv: Array of JavaScript values as napi_value representing the\narguments to the function.
      • \n
      • [out] result: napi_value representing the JavaScript object returned.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This method allows a JavaScript function object to be called from a native\nadd-on. This API is similar to napi_call_function. However, it is used to call\nfrom native code back into JavaScript after returning from an async\noperation (when there is no other script on the stack). It is a fairly simple\nwrapper around node::MakeCallback.

      \n

      Note it is not necessary to use napi_make_callback from within a\nnapi_async_complete_callback; in that situation the callback's async\ncontext has already been set up, so a direct call to napi_call_function\nis sufficient and appropriate. Use of the napi_make_callback function\nmay be required when implementing custom async behavior that does not use\nnapi_create_async_work.

      \n

      Any process.nextTicks or Promises scheduled on the microtask queue by\nJavaScript during the callback are ran before returning back to C/C++.

      ", + "type": "module", + "displayName": "napi_make_callback" + }, + { + "textRaw": "napi_open_callback_scope", + "name": "napi_open_callback_scope", + "meta": { + "added": [ + "v9.6.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,\n                                                 napi_value resource_object,\n                                                 napi_async_context context,\n                                                 napi_callback_scope* result)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] resource_object: An object associated with the async work\nthat will be passed to possible async_hooks init hooks.
      • \n
      • [in] context: Context for the async operation that is invoking the callback.\nThis should be a value previously obtained from napi_async_init.
      • \n
      • [out] result: The newly created scope.
      • \n
      \n

      There are cases (for example, resolving promises) where it is\nnecessary to have the equivalent of the scope associated with a callback\nin place when making certain N-API calls. If there is no other script on\nthe stack the napi_open_callback_scope and\nnapi_close_callback_scope functions can be used to open/close\nthe required scope.

      ", + "type": "module", + "displayName": "napi_open_callback_scope" + }, + { + "textRaw": "napi_close_callback_scope", + "name": "napi_close_callback_scope", + "meta": { + "added": [ + "v9.6.0" + ], + "napiVersion": [ + 3 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,\n                                                  napi_callback_scope scope)\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] scope: The scope to be closed.
      • \n
      \n

      This API can be called even if there is a pending JavaScript exception.

      ", + "type": "module", + "displayName": "napi_close_callback_scope" + } + ], + "type": "misc", + "displayName": "Custom asynchronous operations" + }, + { + "textRaw": "Version management", + "name": "version_management", + "modules": [ + { + "textRaw": "napi_get_node_version", + "name": "napi_get_node_version", + "meta": { + "added": [ + "v8.4.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      typedef struct {\n  uint32_t major;\n  uint32_t minor;\n  uint32_t patch;\n  const char* release;\n} napi_node_version;\n\nnapi_status napi_get_node_version(napi_env env,\n                                  const napi_node_version** version);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] version: A pointer to version information for Node.js itself.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This function fills the version struct with the major, minor, and patch\nversion of Node.js that is currently running, and the release field with the\nvalue of process.release.name.

      \n

      The returned buffer is statically allocated and does not need to be freed.

      ", + "type": "module", + "displayName": "napi_get_node_version" + }, + { + "textRaw": "napi_get_version", + "name": "napi_get_version", + "meta": { + "added": [ + "v8.0.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_get_version(napi_env env,\n                             uint32_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: The highest version of N-API supported.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API returns the highest N-API version supported by the\nNode.js runtime. N-API is planned to be additive such that\nnewer releases of Node.js may support additional API functions.\nIn order to allow an addon to use a newer function when running with\nversions of Node.js that support it, while providing\nfallback behavior when running with Node.js versions that don't\nsupport it:

      \n
        \n
      • Call napi_get_version() to determine if the API is available.
      • \n
      • If available, dynamically load a pointer to the function using uv_dlsym().
      • \n
      • Use the dynamically loaded pointer to invoke the function.
      • \n
      • If the function is not available, provide an alternate implementation\nthat does not use the function.
      • \n
      ", + "type": "module", + "displayName": "napi_get_version" + } + ], + "type": "misc", + "displayName": "Version management" + }, + { + "textRaw": "Memory management", + "name": "memory_management", + "modules": [ + { + "textRaw": "napi_adjust_external_memory", + "name": "napi_adjust_external_memory", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,\n                                                    int64_t change_in_bytes,\n                                                    int64_t* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] change_in_bytes: The change in externally allocated memory that is kept\nalive by JavaScript objects.
      • \n
      • [out] result: The adjusted value
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This function gives V8 an indication of the amount of externally allocated\nmemory that is kept alive by JavaScript objects (i.e. a JavaScript object\nthat points to its own memory allocated by a native module). Registering\nexternally allocated memory will trigger global garbage collections more\noften than it would otherwise.

      ", + "type": "module", + "displayName": "napi_adjust_external_memory" + } + ], + "type": "misc", + "displayName": "Memory management" + }, + { + "textRaw": "Promises", + "name": "promises", + "desc": "

      N-API provides facilities for creating Promise objects as described in\nSection 25.4 of the ECMA specification. It implements promises as a pair of\nobjects. When a promise is created by napi_create_promise(), a \"deferred\"\nobject is created and returned alongside the Promise. The deferred object is\nbound to the created Promise and is the only means to resolve or reject the\nPromise using napi_resolve_deferred() or napi_reject_deferred(). The\ndeferred object that is created by napi_create_promise() is freed by\nnapi_resolve_deferred() or napi_reject_deferred(). The Promise object may\nbe returned to JavaScript where it can be used in the usual fashion.

      \n

      For example, to create a promise and pass it to an asynchronous worker:

      \n
      napi_deferred deferred;\nnapi_value promise;\nnapi_status status;\n\n// Create the promise.\nstatus = napi_create_promise(env, &deferred, &promise);\nif (status != napi_ok) return NULL;\n\n// Pass the deferred to a function that performs an asynchronous action.\ndo_something_asynchronous(deferred);\n\n// Return the promise to JS\nreturn promise;\n
      \n

      The above function do_something_asynchronous() would perform its asynchronous\naction and then it would resolve or reject the deferred, thereby concluding the\npromise and freeing the deferred:

      \n
      napi_deferred deferred;\nnapi_value undefined;\nnapi_status status;\n\n// Create a value with which to conclude the deferred.\nstatus = napi_get_undefined(env, &undefined);\nif (status != napi_ok) return NULL;\n\n// Resolve or reject the promise associated with the deferred depending on\n// whether the asynchronous action succeeded.\nif (asynchronous_action_succeeded) {\n  status = napi_resolve_deferred(env, deferred, undefined);\n} else {\n  status = napi_reject_deferred(env, deferred, undefined);\n}\nif (status != napi_ok) return NULL;\n\n// At this point the deferred has been freed, so we should assign NULL to it.\ndeferred = NULL;\n
      ", + "modules": [ + { + "textRaw": "napi_create_promise", + "name": "napi_create_promise", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_create_promise(napi_env env,\n                                napi_deferred* deferred,\n                                napi_value* promise);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] deferred: A newly created deferred object which can later be passed to\nnapi_resolve_deferred() or napi_reject_deferred() to resolve resp. reject\nthe associated promise.
      • \n
      • [out] promise: The JavaScript promise associated with the deferred object.
      • \n
      \n

      Returns napi_ok if the API succeeded.

      \n

      This API creates a deferred object and a JavaScript promise.

      ", + "type": "module", + "displayName": "napi_create_promise" + }, + { + "textRaw": "napi_resolve_deferred", + "name": "napi_resolve_deferred", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_resolve_deferred(napi_env env,\n                                  napi_deferred deferred,\n                                  napi_value resolution);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] deferred: The deferred object whose associated promise to resolve.
      • \n
      • [in] resolution: The value with which to resolve the promise.
      • \n
      \n

      This API resolves a JavaScript promise by way of the deferred object\nwith which it is associated. Thus, it can only be used to resolve JavaScript\npromises for which the corresponding deferred object is available. This\neffectively means that the promise must have been created using\nnapi_create_promise() and the deferred object returned from that call must\nhave been retained in order to be passed to this API.

      \n

      The deferred object is freed upon successful completion.

      ", + "type": "module", + "displayName": "napi_resolve_deferred" + }, + { + "textRaw": "napi_reject_deferred", + "name": "napi_reject_deferred", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_reject_deferred(napi_env env,\n                                 napi_deferred deferred,\n                                 napi_value rejection);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] deferred: The deferred object whose associated promise to resolve.
      • \n
      • [in] rejection: The value with which to reject the promise.
      • \n
      \n

      This API rejects a JavaScript promise by way of the deferred object\nwith which it is associated. Thus, it can only be used to reject JavaScript\npromises for which the corresponding deferred object is available. This\neffectively means that the promise must have been created using\nnapi_create_promise() and the deferred object returned from that call must\nhave been retained in order to be passed to this API.

      \n

      The deferred object is freed upon successful completion.

      ", + "type": "module", + "displayName": "napi_reject_deferred" + }, + { + "textRaw": "napi_is_promise", + "name": "napi_is_promise", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      napi_status napi_is_promise(napi_env env,\n                            napi_value value,\n                            bool* is_promise);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] value: The value to examine
      • \n
      • [out] is_promise: Flag indicating whether promise is a native promise\nobject (that is, a promise object created by the underlying engine).
      • \n
      ", + "type": "module", + "displayName": "napi_is_promise" + } + ], + "type": "misc", + "displayName": "Promises" + }, + { + "textRaw": "Script execution", + "name": "script_execution", + "desc": "

      N-API provides an API for executing a string containing JavaScript using the\nunderlying JavaScript engine.

      ", + "modules": [ + { + "textRaw": "napi_run_script", + "name": "napi_run_script", + "meta": { + "added": [ + "v8.5.0" + ], + "napiVersion": [ + 1 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_run_script(napi_env env,\n                                        napi_value script,\n                                        napi_value* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] script: A JavaScript string containing the script to execute.
      • \n
      • [out] result: The value resulting from having executed the script.
      • \n
      \n

      This function executes a string of JavaScript code and returns its result with\nthe following caveats:

      \n
        \n
      • Unlike eval, this function does not allow the script to access the current\nlexical scope, and therefore also does not allow to access the\nmodule scope, meaning that pseudo-globals such as require will not be\navailable.
      • \n
      • The script can access the global scope. Function and var declarations\nin the script will be added to the global object. Variable declarations\nmade using let and const will be visible globally, but will not be added\nto the global object.
      • \n
      • The value of this is global within the script.
      • \n
      ", + "type": "module", + "displayName": "napi_run_script" + } + ], + "type": "misc", + "displayName": "Script execution" + }, + { + "textRaw": "libuv event loop", + "name": "libuv_event_loop", + "desc": "

      N-API provides a function for getting the current event loop associated with\na specific napi_env.

      ", + "modules": [ + { + "textRaw": "napi_get_uv_event_loop", + "name": "napi_get_uv_event_loop", + "meta": { + "added": [ + "v8.10.0", + "v9.3.0" + ], + "napiVersion": [ + 2 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,\n                                               struct uv_loop_s** loop);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] loop: The current libuv loop instance.
      • \n
      ", + "type": "module", + "displayName": "napi_get_uv_event_loop" + } + ], + "type": "misc", + "displayName": "libuv event loop" + }, + { + "textRaw": "Asynchronous thread-safe function calls", + "name": "asynchronous_thread-safe_function_calls", + "desc": "

      JavaScript functions can normally only be called from a native addon's main\nthread. If an addon creates additional threads, then N-API functions that\nrequire a napi_env, napi_value, or napi_ref must not be called from those\nthreads.

      \n

      When an addon has additional threads and JavaScript functions need to be invoked\nbased on the processing completed by those threads, those threads must\ncommunicate with the addon's main thread so that the main thread can invoke the\nJavaScript function on their behalf. The thread-safe function APIs provide an\neasy way to do this.

      \n

      These APIs provide the type napi_threadsafe_function as well as APIs to\ncreate, destroy, and call objects of this type.\nnapi_create_threadsafe_function() creates a persistent reference to a\nnapi_value that holds a JavaScript function which can be called from multiple\nthreads. The calls happen asynchronously. This means that values with which the\nJavaScript callback is to be called will be placed in a queue, and, for each\nvalue in the queue, a call will eventually be made to the JavaScript function.

      \n

      Upon creation of a napi_threadsafe_function a napi_finalize callback can be\nprovided. This callback will be invoked on the main thread when the thread-safe\nfunction is about to be destroyed. It receives the context and the finalize data\ngiven during construction, and provides an opportunity for cleaning up after the\nthreads e.g. by calling uv_thread_join(). Aside from the main loop thread,\nno threads should be using the thread-safe function after the finalize callback\ncompletes.

      \n

      The context given during the call to napi_create_threadsafe_function() can\nbe retrieved from any thread with a call to\nnapi_get_threadsafe_function_context().

      ", + "modules": [ + { + "textRaw": "Calling a thread-safe function", + "name": "calling_a_thread-safe_function", + "desc": "

      napi_call_threadsafe_function() can be used for initiating a call into\nJavaScript. napi_call_threadsafe_function() accepts a parameter which controls\nwhether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API\nbehaves non-blockingly, returning napi_queue_full if the queue was full,\npreventing data from being successfully added to the queue. If set to\nnapi_tsfn_blocking, the API blocks until space becomes available in the queue.\nnapi_call_threadsafe_function() never blocks if the thread-safe function was\ncreated with a maximum queue size of 0.

      \n

      The actual call into JavaScript is controlled by the callback given via the\ncall_js_cb parameter. call_js_cb is invoked on the main thread once for each\nvalue that was placed into the queue by a successful call to\nnapi_call_threadsafe_function(). If such a callback is not given, a default\ncallback will be used, and the resulting JavaScript call will have no arguments.\nThe call_js_cb callback receives the JavaScript function to call as a\nnapi_value in its parameters, as well as the void* context pointer used when\ncreating the napi_threadsafe_function, and the next data pointer that was\ncreated by one of the secondary threads. The callback can then use an API such\nas napi_call_function() to call into JavaScript.

      \n

      The callback may also be invoked with env and call_js_cb both set to NULL\nto indicate that calls into JavaScript are no longer possible, while items\nremain in the queue that may need to be freed. This normally occurs when the\nNode.js process exits while there is a thread-safe function still active.

      \n

      It is not necessary to call into JavaScript via napi_make_callback() because\nN-API runs call_js_cb in a context appropriate for callbacks.

      ", + "type": "module", + "displayName": "Calling a thread-safe function" + }, + { + "textRaw": "Reference counting of thread-safe functions", + "name": "reference_counting_of_thread-safe_functions", + "desc": "

      Threads can be added to and removed from a napi_threadsafe_function object\nduring its existence. Thus, in addition to specifying an initial number of\nthreads upon creation, napi_acquire_threadsafe_function can be called to\nindicate that a new thread will start making use of the thread-safe function.\nSimilarly, napi_release_threadsafe_function can be called to indicate that an\nexisting thread will stop making use of the thread-safe function.

      \n

      napi_threadsafe_function objects are destroyed when every thread which uses\nthe object has called napi_release_threadsafe_function() or has received a\nreturn status of napi_closing in response to a call to\nnapi_call_threadsafe_function. The queue is emptied before the\nnapi_threadsafe_function is destroyed. napi_release_threadsafe_function()\nshould be the last API call made in conjunction with a given\nnapi_threadsafe_function, because after the call completes, there is no\nguarantee that the napi_threadsafe_function is still allocated. For the same\nreason, do not use a thread-safe function\nafter receiving a return value of napi_closing in response to a call to\nnapi_call_threadsafe_function. Data associated with the\nnapi_threadsafe_function can be freed in its napi_finalize callback which\nwas passed to napi_create_threadsafe_function(). The parameter\ninitial_thread_count of napi_create_threadsafe_function marks the initial\nnumber of aquisitions of the thread-safe functions, instead of calling\nnapi_acquire_threadsafe_function multiple times at creation.

      \n

      Once the number of threads making use of a napi_threadsafe_function reaches\nzero, no further threads can start making use of it by calling\nnapi_acquire_threadsafe_function(). In fact, all subsequent API calls\nassociated with it, except napi_release_threadsafe_function(), will return an\nerror value of napi_closing.

      \n

      The thread-safe function can be \"aborted\" by giving a value of napi_tsfn_abort\nto napi_release_threadsafe_function(). This will cause all subsequent APIs\nassociated with the thread-safe function except\nnapi_release_threadsafe_function() to return napi_closing even before its\nreference count reaches zero. In particular, napi_call_threadsafe_function()\nwill return napi_closing, thus informing the threads that it is no longer\npossible to make asynchronous calls to the thread-safe function. This can be\nused as a criterion for terminating the thread. Upon receiving a return value\nof napi_closing from napi_call_threadsafe_function() a thread must not use\nthe thread-safe function anymore because it is no longer guaranteed to\nbe allocated.

      ", + "type": "module", + "displayName": "Reference counting of thread-safe functions" + }, + { + "textRaw": "Deciding whether to keep the process running", + "name": "deciding_whether_to_keep_the_process_running", + "desc": "

      Similarly to libuv handles, thread-safe functions can be \"referenced\" and\n\"unreferenced\". A \"referenced\" thread-safe function will cause the event loop on\nthe thread on which it is created to remain alive until the thread-safe function\nis destroyed. In contrast, an \"unreferenced\" thread-safe function will not\nprevent the event loop from exiting. The APIs napi_ref_threadsafe_function and\nnapi_unref_threadsafe_function exist for this purpose.

      \n

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as\nable to be destroyed nor does napi_ref_threadsafe_function prevent it from\nbeing destroyed.

      ", + "type": "module", + "displayName": "Deciding whether to keep the process running" + }, + { + "textRaw": "napi_create_threadsafe_function", + "name": "napi_create_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [ + { + "version": "v12.6.0", + "pr-url": "https://github.com/nodejs/node/pull/27791", + "description": "Made `func` parameter optional with custom `call_js_cb`." + } + ] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_create_threadsafe_function(napi_env env,\n                                napi_value func,\n                                napi_value async_resource,\n                                napi_value async_resource_name,\n                                size_t max_queue_size,\n                                size_t initial_thread_count,\n                                void* thread_finalize_data,\n                                napi_finalize thread_finalize_cb,\n                                void* context,\n                                napi_threadsafe_function_call_js call_js_cb,\n                                napi_threadsafe_function* result);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] func: An optional JavaScript function to call from another thread. It\nmust be provided if NULL is passed to call_js_cb.
      • \n
      • [in] async_resource: An optional object associated with the async work that\nwill be passed to possible async_hooks init hooks.
      • \n
      • [in] async_resource_name: A JavaScript string to provide an identifier for\nthe kind of resource that is being provided for diagnostic information exposed\nby the async_hooks API.
      • \n
      • [in] max_queue_size: Maximum size of the queue. 0 for no limit.
      • \n
      • [in] initial_thread_count: The initial number of acquisitions, i.e. the\ninitial number of threads, including the main thread, which will be making use\nof this function.
      • \n
      • [in] thread_finalize_data: Optional data to be passed to thread_finalize_cb.
      • \n
      • [in] thread_finalize_cb: Optional function to call when the\nnapi_threadsafe_function is being destroyed.
      • \n
      • [in] context: Optional data to attach to the resulting\nnapi_threadsafe_function.
      • \n
      • [in] call_js_cb: Optional callback which calls the JavaScript function in\nresponse to a call on a different thread. This callback will be called on the\nmain thread. If not given, the JavaScript function will be called with no\nparameters and with undefined as its this value.\nnapi_threadsafe_function_call_js provides more details.
      • \n
      • [out] result: The asynchronous thread-safe JavaScript function.
      • \n
      ", + "type": "module", + "displayName": "napi_create_threadsafe_function" + }, + { + "textRaw": "napi_get_threadsafe_function_context", + "name": "napi_get_threadsafe_function_context", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_get_threadsafe_function_context(napi_threadsafe_function func,\n                                     void** result);\n
      \n
        \n
      • [in] func: The thread-safe function for which to retrieve the context.
      • \n
      • [out] result: The location where to store the context.
      • \n
      \n

      This API may be called from any thread which makes use of func.

      ", + "type": "module", + "displayName": "napi_get_threadsafe_function_context" + }, + { + "textRaw": "napi_call_threadsafe_function", + "name": "napi_call_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_call_threadsafe_function(napi_threadsafe_function func,\n                              void* data,\n                              napi_threadsafe_function_call_mode is_blocking);\n
      \n
        \n
      • [in] func: The asynchronous thread-safe JavaScript function to invoke.
      • \n
      • [in] data: Data to send into JavaScript via the callback call_js_cb\nprovided during the creation of the thread-safe JavaScript function.
      • \n
      • [in] is_blocking: Flag whose value can be either napi_tsfn_blocking to\nindicate that the call should block if the queue is full or\nnapi_tsfn_nonblocking to indicate that the call should return immediately\nwith a status of napi_queue_full whenever the queue is full.
      • \n
      \n

      This API will return napi_closing if napi_release_threadsafe_function() was\ncalled with abort set to napi_tsfn_abort from any thread. The value is only\nadded to the queue if the API returns napi_ok.

      \n

      This API may be called from any thread which makes use of func.

      ", + "type": "module", + "displayName": "napi_call_threadsafe_function" + }, + { + "textRaw": "napi_acquire_threadsafe_function", + "name": "napi_acquire_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_acquire_threadsafe_function(napi_threadsafe_function func);\n
      \n
        \n
      • [in] func: The asynchronous thread-safe JavaScript function to start making\nuse of.
      • \n
      \n

      A thread should call this API before passing func to any other thread-safe\nfunction APIs to indicate that it will be making use of func. This prevents\nfunc from being destroyed when all other threads have stopped making use of\nit.

      \n

      This API may be called from any thread which will start making use of func.

      ", + "type": "module", + "displayName": "napi_acquire_threadsafe_function" + }, + { + "textRaw": "napi_release_threadsafe_function", + "name": "napi_release_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_release_threadsafe_function(napi_threadsafe_function func,\n                                 napi_threadsafe_function_release_mode mode);\n
      \n
        \n
      • [in] func: The asynchronous thread-safe JavaScript function whose reference\ncount to decrement.
      • \n
      • [in] mode: Flag whose value can be either napi_tsfn_release to indicate\nthat the current thread will make no further calls to the thread-safe\nfunction, or napi_tsfn_abort to indicate that in addition to the current\nthread, no other thread should make any further calls to the thread-safe\nfunction. If set to napi_tsfn_abort, further calls to\nnapi_call_threadsafe_function() will return napi_closing, and no further\nvalues will be placed in the queue.
      • \n
      \n

      A thread should call this API when it stops making use of func. Passing func\nto any thread-safe APIs after having called this API has undefined results, as\nfunc may have been destroyed.

      \n

      This API may be called from any thread which will stop making use of func.

      ", + "type": "module", + "displayName": "napi_release_threadsafe_function" + }, + { + "textRaw": "napi_ref_threadsafe_function", + "name": "napi_ref_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] func: The thread-safe function to reference.
      • \n
      \n

      This API is used to indicate that the event loop running on the main thread\nshould not exit until func has been destroyed. Similar to uv_ref it is\nalso idempotent.

      \n

      Neither does napi_unref_threadsafe_function mark the thread-safe functions as\nable to be destroyed nor does napi_ref_threadsafe_function prevent it from\nbeing destroyed. napi_acquire_threadsafe_function and\nnapi_release_threadsafe_function are available for that purpose.

      \n

      This API may only be called from the main thread.

      ", + "type": "module", + "displayName": "napi_ref_threadsafe_function" + }, + { + "textRaw": "napi_unref_threadsafe_function", + "name": "napi_unref_threadsafe_function", + "meta": { + "added": [ + "v10.6.0" + ], + "napiVersion": [ + 4 + ], + "changes": [] + }, + "desc": "
      NAPI_EXTERN napi_status\nnapi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [in] func: The thread-safe function to unreference.
      • \n
      \n

      This API is used to indicate that the event loop running on the main thread\nmay exit before func is destroyed. Similar to uv_unref it is also\nidempotent.

      \n

      This API may only be called from the main thread.

      ", + "type": "module", + "displayName": "napi_unref_threadsafe_function" + } + ], + "type": "misc", + "displayName": "Asynchronous thread-safe function calls" + }, + { + "textRaw": "Miscellaneous utilities", + "name": "miscellaneous_utilities", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "
      NAPI_EXTERN napi_status\nnode_api_get_module_file_name(napi_env env, const char** result);\n\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: A URL containing the absolute path of the\nlocation from which the add-on was loaded. For a file on the local\nfile system it will start with file://. The string is null-terminated and\nowned by env and must thus not be modified or freed.
      • \n
      \n

      result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.

      ", + "type": "misc", + "displayName": "Miscellaneous utilities" + }, + { + "textRaw": "node_api_get_module_file_name", + "name": "node_api_get_module_file_name", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "
      NAPI_EXTERN napi_status\nnode_api_get_module_file_name(napi_env env, const char** result);\n\n
      \n
        \n
      • [in] env: The environment that the API is invoked under.
      • \n
      • [out] result: A URL containing the absolute path of the\nlocation from which the add-on was loaded. For a file on the local\nfile system it will start with file://. The string is null-terminated and\nowned by env and must thus not be modified or freed.
      • \n
      \n

      result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.

      ", + "type": "misc", + "displayName": "node_api_get_module_file_name" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 1f3c90de3d461a9297bbaa6c8bd2501d5ad541d1..a55bffd3fab47838bda1222469239224e0eadaed 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -608,6 +608,7 @@ For more details, review the [Object lifetime management][]. #### napi_type_tag A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID @@ -1620,10 +1621,9 @@ changes: - version: v12.19.0 pr-url: https://github.com/nodejs/node/pull/34819 description: Changed signature of the `hook` callback. +napiVersion: 8 --> -> Stability: 1 - Experimental - ```c NAPI_EXTERN napi_status napi_add_async_cleanup_hook( napi_env env, @@ -1661,8 +1661,6 @@ changes: description: Removed `env` parameter. --> -> Stability: 1 - Experimental - ```c NAPI_EXTERN napi_status napi_remove_async_cleanup_hook( napi_async_cleanup_hook_handle remove_handle); @@ -4095,10 +4093,9 @@ specification). #### napi_object_freeze -> Stability: 1 - Experimental - ```c napi_status napi_object_freeze(napi_env env, napi_value object); @@ -4120,10 +4117,9 @@ ECMA-262 specification. #### napi_object_seal -> Stability: 1 - Experimental - ```c napi_status napi_object_seal(napi_env env, napi_value object); @@ -4776,10 +4772,9 @@ JavaScript object becomes garbage-collected. ### napi_type_tag_object -> Stability: 1 - Experimental - ```c napi_status napi_type_tag_object(napi_env env, napi_value js_object, @@ -4803,10 +4798,9 @@ If the object already has an associated type tag, this API will return ### napi_check_object_type_tag -> Stability: 1 - Experimental - ```c napi_status napi_check_object_type_tag(napi_env env, napi_value js_object, @@ -5791,6 +5785,31 @@ idempotent. This API may only be called from the main thread. +## Miscellaneous utilities + +## node_api_get_module_file_name + + + +> Stability: 1 - Experimental + +```c +NAPI_EXTERN napi_status +node_api_get_module_file_name(napi_env env, const char** result); + +``` + +* `[in] env`: The environment that the API is invoked under. +* `[out] result`: A URL containing the absolute path of the + location from which the add-on was loaded. For a file on the local + file system it will start with `file://`. The string is null-terminated and + owned by `env` and must thus not be modified or freed. + +`result` may be an empty string if the add-on loading process fails to establish +the add-on's file name during loading. + [ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/ [AppVeyor]: https://www.appveyor.com [C++ Addons]: addons.html diff --git a/doc/api/net.html b/doc/api/net.html new file mode 100644 index 0000000000000000000000000000000000000000..72255febf5a41adfedfca8b4bdcb0b9850c9a63b --- /dev/null +++ b/doc/api/net.html @@ -0,0 +1,1295 @@ + + + + + + + Net | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Net#

      + + +

      Stability: 2 - Stable

      +

      Source Code: lib/net.js

      +

      The net module provides an asynchronous network API for creating stream-based +TCP or IPC servers (net.createServer()) and clients +(net.createConnection()).

      +

      It can be accessed using:

      +
      const net = require('net');
      +

      IPC support#

      +

      The net module supports IPC with named pipes on Windows, and Unix domain +sockets on other operating systems.

      +

      Identifying paths for IPC connections#

      +

      net.connect(), net.createConnection(), server.listen() and +socket.connect() take a path parameter to identify IPC endpoints.

      +

      On Unix, the local domain is also known as the Unix domain. The path is a +filesystem pathname. It gets truncated to an OS-dependent length of +sizeof(sockaddr_un.sun_path) - 1. Typical values are 107 bytes on Linux and +103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket, +it will unlink the Unix domain socket as well. For example, +net.createServer() may create a Unix domain socket and +server.close() will unlink it. But if a user creates the Unix domain +socket outside of these abstractions, the user will need to remove it. The same +applies when a Node.js API creates a Unix domain socket but the program then +crashes. In short, a Unix domain socket will be visible in the filesystem and +will persist until unlinked.

      +

      On Windows, the local domain is implemented using a named pipe. The path must +refer to an entry in \\?\pipe\ or \\.\pipe\. Any characters are permitted, +but the latter may do some processing of pipe names, such as resolving .. +sequences. Despite how it might look, the pipe namespace is flat. Pipes will +not persist. They are removed when the last reference to them is closed. +Unlike Unix domain sockets, Windows will close and remove the pipe when the +owning process exits.

      +

      JavaScript string escaping requires paths to be specified with extra backslash +escaping such as:

      +
      net.createServer().listen(
      +  path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
      +

      Class: net.Server#

      + + +

      This class is used to create a TCP or IPC server.

      +

      new net.Server([options][, connectionListener])#

      + +

      net.Server is an EventEmitter with the following events:

      +

      Event: 'close'#

      + +

      Emitted when the server closes. If connections exist, this +event is not emitted until all connections are ended.

      +

      Event: 'connection'#

      + + +

      Emitted when a new connection is made. socket is an instance of +net.Socket.

      +

      Event: 'error'#

      + + +

      Emitted when an error occurs. Unlike net.Socket, the 'close' +event will not be emitted directly following this event unless +server.close() is manually called. See the example in discussion of +server.listen().

      +

      Event: 'listening'#

      + +

      Emitted when the server has been bound after calling server.listen().

      +

      server.address()#

      + + +

      Returns the bound address, the address family name, and port of the server +as reported by the operating system if listening on an IP socket +(useful to find which port was assigned when getting an OS-assigned address): +{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      +

      For a server listening on a pipe or Unix domain socket, the name is returned +as a string.

      +
      const server = net.createServer((socket) => {
      +  socket.end('goodbye\n');
      +}).on('error', (err) => {
      +  // Handle errors here.
      +  throw err;
      +});
      +
      +// Grab an arbitrary unused port.
      +server.listen(() => {
      +  console.log('opened server on', server.address());
      +});
      +

      server.address() returns null before the 'listening' event has been +emitted or after calling server.close().

      +

      server.close([callback])#

      + + +

      Stops the server from accepting new connections and keeps existing +connections. This function is asynchronous, the server is finally closed +when all connections are ended and the server emits a 'close' event. +The optional callback will be called once the 'close' event occurs. Unlike +that event, it will be called with an Error as its only argument if the server +was not open when it was closed.

      +

      server.connections#

      + +

      Stability: 0 - Deprecated: Use server.getConnections() instead.

      + +

      The number of concurrent connections on the server.

      +

      This becomes null when sending a socket to a child with +child_process.fork(). To poll forks and get current number of active +connections, use asynchronous server.getConnections() instead.

      +

      server.getConnections(callback)#

      + + +

      Asynchronously get the number of concurrent connections on the server. Works +when sockets were sent to forks.

      +

      Callback should take two arguments err and count.

      +

      server.listen()#

      +

      Start a server listening for connections. A net.Server can be a TCP or +an IPC server depending on what it listens to.

      +

      Possible signatures:

      + +

      This function is asynchronous. When the server starts listening, the +'listening' event will be emitted. The last parameter callback +will be added as a listener for the 'listening' event.

      +

      All listen() methods can take a backlog parameter to specify the maximum +length of the queue of pending connections. The actual length will be determined +by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn +on Linux. The default value of this parameter is 511 (not 512).

      +

      All net.Socket are set to SO_REUSEADDR (see socket(7) for +details).

      +

      The server.listen() method can be called again if and only if there was an +error during the first server.listen() call or server.close() has been +called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      +

      One of the most common errors raised when listening is EADDRINUSE. +This happens when another server is already listening on the requested +port/path/handle. One way to handle this would be to retry +after a certain amount of time:

      +
      server.on('error', (e) => {
      +  if (e.code === 'EADDRINUSE') {
      +    console.log('Address in use, retrying...');
      +    setTimeout(() => {
      +      server.close();
      +      server.listen(PORT, HOST);
      +    }, 1000);
      +  }
      +});
      +

      server.listen(handle[, backlog][, callback])#

      + + +

      Start a server listening for connections on a given handle that has +already been bound to a port, a Unix domain socket, or a Windows named pipe.

      +

      The handle object can be either a server, a socket (anything with an +underlying _handle member), or an object with an fd member that is a +valid file descriptor.

      +

      Listening on a file descriptor is not supported on Windows.

      +

      server.listen(options[, callback])#

      + + +

      If port is specified, it behaves the same as + +server.listen([port[, host[, backlog]]][, callback]). +Otherwise, if path is specified, it behaves the same as +server.listen(path[, backlog][, callback]). +If none of them is specified, an error will be thrown.

      +

      If exclusive is false (default), then cluster workers will use the same +underlying handle, allowing connection handling duties to be shared. When +exclusive is true, the handle is not shared, and attempted port sharing +results in an error. An example which listens on an exclusive port is +shown below.

      +
      server.listen({
      +  host: 'localhost',
      +  port: 80,
      +  exclusive: true
      +});
      +

      Starting an IPC server as root may cause the server path to be inaccessible for +unprivileged users. Using readableAll and writableAll will make the server +accessible for all users.

      +

      server.listen(path[, backlog][, callback])#

      + + +

      Start an IPC server listening for connections on the given path.

      +

      server.listen([port[, host[, backlog]]][, callback])#

      + + +

      Start a TCP server listening for connections on the given port and host.

      +

      If port is omitted or is 0, the operating system will assign an arbitrary +unused port, which can be retrieved by using server.address().port +after the 'listening' event has been emitted.

      +

      If host is omitted, the server will accept connections on the +unspecified IPv6 address (::) when IPv6 is available, or the +unspecified IPv4 address (0.0.0.0) otherwise.

      +

      In most operating systems, listening to the unspecified IPv6 address (::) +may cause the net.Server to also listen on the unspecified IPv4 address +(0.0.0.0).

      +

      server.listening#

      + +
        +
      • <boolean> Indicates whether or not the server is listening for connections.
      • +
      +

      server.maxConnections#

      + + +

      Set this property to reject connections when the server's connection count gets +high.

      +

      It is not recommended to use this option once a socket has been sent to a child +with child_process.fork().

      +

      server.ref()#

      + + +

      Opposite of unref(), calling ref() on a previously unrefed server will +not let the program exit if it's the only server left (the default behavior). +If the server is refed calling ref() again will have no effect.

      +

      server.unref()#

      + + +

      Calling unref() on a server will allow the program to exit if this is the only +active server in the event system. If the server is already unrefed calling +unref() again will have no effect.

      +

      Class: net.Socket#

      + + +

      This class is an abstraction of a TCP socket or a streaming IPC endpoint +(uses named pipes on Windows, and Unix domain sockets otherwise). It is also +an EventEmitter.

      +

      A net.Socket can be created by the user and used directly to interact with +a server. For example, it is returned by net.createConnection(), +so the user can use it to talk to the server.

      +

      It can also be created by Node.js and passed to the user when a connection +is received. For example, it is passed to the listeners of a +'connection' event emitted on a net.Server, so the user can use +it to interact with the client.

      +

      new net.Socket([options])#

      + +
        +
      • options <Object> Available options are: +
          +
        • fd <number> If specified, wrap around an existing socket with +the given file descriptor, otherwise a new socket will be created.
        • +
        • allowHalfOpen <boolean> Indicates whether half-opened TCP connections +are allowed. See net.createServer() and the 'end' event +for details. Default: false.
        • +
        • readable <boolean> Allow reads on the socket when an fd is passed, +otherwise ignored. Default: false.
        • +
        • writable <boolean> Allow writes on the socket when an fd is passed, +otherwise ignored. Default: false.
        • +
        +
      • +
      • Returns: <net.Socket>
      • +
      +

      Creates a new socket object.

      +

      The newly created socket can be either a TCP socket or a streaming IPC +endpoint, depending on what it connect() to.

      +

      Event: 'close'#

      + +
        +
      • hadError <boolean> true if the socket had a transmission error.
      • +
      +

      Emitted once the socket is fully closed. The argument hadError is a boolean +which says if the socket was closed due to a transmission error.

      +

      Event: 'connect'#

      + +

      Emitted when a socket connection is successfully established. +See net.createConnection().

      +

      Event: 'data'#

      + + +

      Emitted when data is received. The argument data will be a Buffer or +String. Encoding of data is set by socket.setEncoding().

      +

      The data will be lost if there is no listener when a Socket +emits a 'data' event.

      +

      Event: 'drain'#

      + +

      Emitted when the write buffer becomes empty. Can be used to throttle uploads.

      +

      See also: the return values of socket.write().

      +

      Event: 'end'#

      + +

      Emitted when the other end of the socket sends a FIN packet, thus ending the +readable side of the socket.

      +

      By default (allowHalfOpen is false) the socket will send a FIN packet +back and destroy its file descriptor once it has written out its pending +write queue. However, if allowHalfOpen is set to true, the socket will +not automatically end() its writable side, allowing the +user to write arbitrary amounts of data. The user must call +end() explicitly to close the connection (i.e. sending a +FIN packet back).

      +

      Event: 'error'#

      + + +

      Emitted when an error occurs. The 'close' event will be called directly +following this event.

      +

      Event: 'lookup'#

      + +

      Emitted after resolving the host name but before connecting. +Not applicable to Unix sockets.

      + +

      Event: 'ready'#

      + +

      Emitted when a socket is ready to be used.

      +

      Triggered immediately after 'connect'.

      +

      Event: 'timeout'#

      + +

      Emitted if the socket times out from inactivity. This is only to notify that +the socket has been idle. The user must manually close the connection.

      +

      See also: socket.setTimeout().

      +

      socket.address()#

      + + +

      Returns the bound address, the address family name and port of the +socket as reported by the operating system: +{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

      +

      socket.bufferSize#

      + + +

      This property shows the number of characters buffered for writing. The buffer +may contain strings whose length after encoding is not yet known. So this number +is only an approximation of the number of bytes in the buffer.

      +

      net.Socket has the property that socket.write() always works. This is to +help users get up and running quickly. The computer cannot always keep up +with the amount of data that is written to a socket. The network connection +simply might be too slow. Node.js will internally queue up the data written to a +socket and send it out over the wire when it is possible.

      +

      The consequence of this internal buffering is that memory may grow. +Users who experience large or growing bufferSize should attempt to +"throttle" the data flows in their program with +socket.pause() and socket.resume().

      +

      socket.bytesRead#

      + + +

      The amount of received bytes.

      +

      socket.bytesWritten#

      + + +

      The amount of bytes sent.

      +

      socket.connect()#

      +

      Initiate a connection on a given socket.

      +

      Possible signatures:

      + +

      This function is asynchronous. When the connection is established, the +'connect' event will be emitted. If there is a problem connecting, +instead of a 'connect' event, an 'error' event will be emitted with +the error passed to the 'error' listener. +The last parameter connectListener, if supplied, will be added as a listener +for the 'connect' event once.

      +

      This function should only be used for reconnecting a socket after +'close' has been emitted or otherwise it may lead to undefined +behavior.

      +

      socket.connect(options[, connectListener])#

      + + +

      Initiate a connection on a given socket. Normally this method is not needed, +the socket should be created and opened with net.createConnection(). Use +this only when implementing a custom Socket.

      +

      For TCP connections, available options are:

      +
        +
      • port <number> Required. Port the socket should connect to.
      • +
      • host <string> Host the socket should connect to. Default: 'localhost'.
      • +
      • localAddress <string> Local address the socket should connect from.
      • +
      • localPort <number> Local port the socket should connect from.
      • +
      • family <number>: Version of IP stack. Must be 4, 6, or 0. The value +0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.
      • +
      • hints <number> Optional dns.lookup() hints.
      • +
      • lookup <Function> Custom lookup function. Default: dns.lookup().
      • +
      +

      For IPC connections, available options are:

      + +

      For both types, available options include:

      +
        +
      • onread <Object> If specified, incoming data is stored in a single buffer +and passed to the supplied callback when data arrives on the socket. +This will cause the streaming functionality to not provide any data. +The socket will emit events like 'error', 'end', and 'close' +as usual. Methods like pause() and resume() will also behave as +expected. +
          +
        • buffer <Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to +use for storing incoming data or a function that returns such.
        • +
        • callback <Function> This function is called for every chunk of incoming +data. Two arguments are passed to it: the number of bytes written to +buffer and a reference to buffer. Return false from this function to +implicitly pause() the socket. This function will be executed in the +global context.
        • +
        +
      • +
      +

      Following is an example of a client using the onread option:

      +
      const net = require('net');
      +net.connect({
      +  port: 80,
      +  onread: {
      +    // Reuses a 4KiB Buffer for every read from the socket.
      +    buffer: Buffer.alloc(4 * 1024),
      +    callback: function(nread, buf) {
      +      // Received data is available in `buf` from 0 to `nread`.
      +      console.log(buf.toString('utf8', 0, nread));
      +    }
      +  }
      +});
      +

      socket.connect(path[, connectListener])#

      + +

      Initiate an IPC connection on the given socket.

      +

      Alias to +socket.connect(options[, connectListener]) +called with { path: path } as options.

      +

      socket.connect(port[, host][, connectListener])#

      + + +

      Initiate a TCP connection on the given socket.

      +

      Alias to +socket.connect(options[, connectListener]) +called with {port: port, host: host} as options.

      +

      socket.connecting#

      + + +

      If true, +socket.connect(options[, connectListener]) was +called and has not yet finished. It will stay true until the socket becomes +connected, then it is set to false and the 'connect' event is emitted. Note +that the +socket.connect(options[, connectListener]) +callback is a listener for the 'connect' event.

      +

      socket.destroy([error])#

      + + +

      Ensures that no more I/O activity happens on this socket. +Destroys the stream and closes the connection.

      +

      See writable.destroy() for further details.

      +

      socket.destroyed#

      +
        +
      • <boolean> Indicates if the connection is destroyed or not. Once a +connection is destroyed no further data can be transferred using it.
      • +
      +

      See writable.destroyed for further details.

      +

      socket.end([data[, encoding]][, callback])#

      + + +

      Half-closes the socket. i.e., it sends a FIN packet. It is possible the +server will still send some data.

      +

      See writable.end() for further details.

      +

      socket.localAddress#

      + + +

      The string representation of the local IP address the remote client is +connecting on. For example, in a server listening on '0.0.0.0', if a client +connects on '192.168.1.1', the value of socket.localAddress would be +'192.168.1.1'.

      +

      socket.localPort#

      + + +

      The numeric representation of the local port. For example, 80 or 21.

      +

      socket.pause()#

      + +

      Pauses the reading of data. That is, 'data' events will not be emitted. +Useful to throttle back an upload.

      +

      socket.pending#

      + + +

      This is true if the socket is not connected yet, either because .connect() +has not yet been called or because it is still in the process of connecting +(see socket.connecting).

      +

      socket.ref()#

      + + +

      Opposite of unref(), calling ref() on a previously unrefed socket will +not let the program exit if it's the only socket left (the default behavior). +If the socket is refed calling ref again will have no effect.

      +

      socket.remoteAddress#

      + + +

      The string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if +the socket is destroyed (for example, if the client disconnected).

      +

      socket.remoteFamily#

      + + +

      The string representation of the remote IP family. 'IPv4' or 'IPv6'.

      +

      socket.remotePort#

      + + +

      The numeric representation of the remote port. For example, 80 or 21.

      +

      socket.resume()#

      + +

      Resumes reading after a call to socket.pause().

      +

      socket.setEncoding([encoding])#

      + + +

      Set the encoding for the socket as a Readable Stream. See +readable.setEncoding() for more information.

      +

      socket.setKeepAlive([enable][, initialDelay])#

      + + +

      Enable/disable keep-alive functionality, and optionally set the initial +delay before the first keepalive probe is sent on an idle socket.

      +

      Set initialDelay (in milliseconds) to set the delay between the last +data packet received and the first keepalive probe. Setting 0 for +initialDelay will leave the value unchanged from the default +(or previous) setting.

      +

      socket.setNoDelay([noDelay])#

      + + +

      Enable/disable the use of Nagle's algorithm.

      +

      When a TCP connection is created, it will have Nagle's algorithm enabled.

      +

      Nagle's algorithm delays data before it is sent via the network. It attempts +to optimize throughput at the expense of latency.

      +

      Passing true for noDelay or not passing an argument will disable Nagle's +algorithm for the socket. Passing false for noDelay will enable Nagle's +algorithm.

      +

      socket.setTimeout(timeout[, callback])#

      + + +

      Sets the socket to timeout after timeout milliseconds of inactivity on +the socket. By default net.Socket do not have a timeout.

      +

      When an idle timeout is triggered the socket will receive a 'timeout' +event but the connection will not be severed. The user must manually call +socket.end() or socket.destroy() to end the connection.

      +
      socket.setTimeout(3000);
      +socket.on('timeout', () => {
      +  console.log('socket timeout');
      +  socket.end();
      +});
      +

      If timeout is 0, then the existing idle timeout is disabled.

      +

      The optional callback parameter will be added as a one-time listener for the +'timeout' event.

      +

      socket.unref()#

      + + +

      Calling unref() on a socket will allow the program to exit if this is the only +active socket in the event system. If the socket is already unrefed calling +unref() again will have no effect.

      +

      socket.write(data[, encoding][, callback])#

      + + +

      Sends data on the socket. The second parameter specifies the encoding in the +case of a string. It defaults to UTF8 encoding.

      +

      Returns true if the entire data was flushed successfully to the kernel +buffer. Returns false if all or part of the data was queued in user memory. +'drain' will be emitted when the buffer is again free.

      +

      The optional callback parameter will be executed when the data is finally +written out, which may not be immediately.

      +

      See Writable stream write() method for more +information.

      +

      net.connect()#

      +

      Aliases to +net.createConnection().

      +

      Possible signatures:

      + +

      net.connect(options[, connectListener])#

      + + +

      Alias to +net.createConnection(options[, connectListener]).

      +

      net.connect(path[, connectListener])#

      + + +

      Alias to +net.createConnection(path[, connectListener]).

      +

      net.connect(port[, host][, connectListener])#

      + + +

      Alias to +net.createConnection(port[, host][, connectListener]).

      +

      net.createConnection()#

      +

      A factory function, which creates a new net.Socket, +immediately initiates connection with socket.connect(), +then returns the net.Socket that starts the connection.

      +

      When the connection is established, a 'connect' event will be emitted +on the returned socket. The last parameter connectListener, if supplied, +will be added as a listener for the 'connect' event once.

      +

      Possible signatures:

      + +

      The net.connect() function is an alias to this function.

      +

      net.createConnection(options[, connectListener])#

      + + +

      For available options, see +new net.Socket([options]) +and socket.connect(options[, connectListener]).

      +

      Additional options:

      + +

      Following is an example of a client of the echo server described +in the net.createServer() section:

      +
      const net = require('net');
      +const client = net.createConnection({ port: 8124 }, () => {
      +  // 'connect' listener.
      +  console.log('connected to server!');
      +  client.write('world!\r\n');
      +});
      +client.on('data', (data) => {
      +  console.log(data.toString());
      +  client.end();
      +});
      +client.on('end', () => {
      +  console.log('disconnected from server');
      +});
      +

      To connect on the socket /tmp/echo.sock:

      +
      const client = net.createConnection({ path: '/tmp/echo.sock' });
      +

      net.createConnection(path[, connectListener])#

      + + +

      Initiates an IPC connection.

      +

      This function creates a new net.Socket with all options set to default, +immediately initiates connection with +socket.connect(path[, connectListener]), +then returns the net.Socket that starts the connection.

      +

      net.createConnection(port[, host][, connectListener])#

      + + +

      Initiates a TCP connection.

      +

      This function creates a new net.Socket with all options set to default, +immediately initiates connection with +socket.connect(port[, host][, connectListener]), +then returns the net.Socket that starts the connection.

      +

      net.createServer([options][, connectionListener])#

      + +
        +
      • options <Object> +
          +
        • allowHalfOpen <boolean> Indicates whether half-opened TCP +connections are allowed. Default: false.
        • +
        • pauseOnConnect <boolean> Indicates whether the socket should be +paused on incoming connections. Default: false.
        • +
        +
      • +
      • connectionListener <Function> Automatically set as a listener for the +'connection' event.
      • +
      • Returns: <net.Server>
      • +
      +

      Creates a new TCP or IPC server.

      +

      If allowHalfOpen is set to true, when the other end of the socket +sends a FIN packet, the server will only send a FIN packet back when +socket.end() is explicitly called, until then the connection is +half-closed (non-readable but still writable). See 'end' event +and RFC 1122 (section 4.2.2.13) for more information.

      +

      If pauseOnConnect is set to true, then the socket associated with each +incoming connection will be paused, and no data will be read from its handle. +This allows connections to be passed between processes without any data being +read by the original process. To begin reading data from a paused socket, call +socket.resume().

      +

      The server can be a TCP server or an IPC server, depending on what it +listen() to.

      +

      Here is an example of an TCP echo server which listens for connections +on port 8124:

      +
      const net = require('net');
      +const server = net.createServer((c) => {
      +  // 'connection' listener.
      +  console.log('client connected');
      +  c.on('end', () => {
      +    console.log('client disconnected');
      +  });
      +  c.write('hello\r\n');
      +  c.pipe(c);
      +});
      +server.on('error', (err) => {
      +  throw err;
      +});
      +server.listen(8124, () => {
      +  console.log('server bound');
      +});
      +

      Test this by using telnet:

      +
      $ telnet localhost 8124
      +

      To listen on the socket /tmp/echo.sock:

      +
      server.listen('/tmp/echo.sock', () => {
      +  console.log('server bound');
      +});
      +

      Use nc to connect to a Unix domain socket server:

      +
      $ nc -U /tmp/echo.sock
      +

      net.isIP(input)#

      + + +

      Tests if input is an IP address. Returns 0 for invalid strings, +returns 4 for IP version 4 addresses, and returns 6 for IP version 6 +addresses.

      +

      net.isIPv4(input)#

      + + +

      Returns true if input is a version 4 IP address, otherwise returns false.

      +

      net.isIPv6(input)#

      + + +

      Returns true if input is a version 6 IP address, otherwise returns false.

      + +
      +
      +
      + + diff --git a/doc/api/net.json b/doc/api/net.json new file mode 100644 index 0000000000000000000000000000000000000000..6a857b6bd4605a5d39a90c4ab25595bbeb185015 --- /dev/null +++ b/doc/api/net.json @@ -0,0 +1,1723 @@ +{ + "type": "module", + "source": "doc/api/net.md", + "modules": [ + { + "textRaw": "Net", + "name": "net", + "introduced_in": "v0.10.0", + "desc": "\n
      \n

      Stability: 2 - Stable

      \n
      \n

      Source Code: lib/net.js

      \n

      The net module provides an asynchronous network API for creating stream-based\nTCP or IPC servers (net.createServer()) and clients\n(net.createConnection()).

      \n

      It can be accessed using:

      \n
      const net = require('net');\n
      ", + "modules": [ + { + "textRaw": "IPC support", + "name": "ipc_support", + "desc": "

      The net module supports IPC with named pipes on Windows, and Unix domain\nsockets on other operating systems.

      ", + "modules": [ + { + "textRaw": "Identifying paths for IPC connections", + "name": "identifying_paths_for_ipc_connections", + "desc": "

      net.connect(), net.createConnection(), server.listen() and\nsocket.connect() take a path parameter to identify IPC endpoints.

      \n

      On Unix, the local domain is also known as the Unix domain. The path is a\nfilesystem pathname. It gets truncated to an OS-dependent length of\nsizeof(sockaddr_un.sun_path) - 1. Typical values are 107 bytes on Linux and\n103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,\nit will unlink the Unix domain socket as well. For example,\nnet.createServer() may create a Unix domain socket and\nserver.close() will unlink it. But if a user creates the Unix domain\nsocket outside of these abstractions, the user will need to remove it. The same\napplies when a Node.js API creates a Unix domain socket but the program then\ncrashes. In short, a Unix domain socket will be visible in the filesystem and\nwill persist until unlinked.

      \n

      On Windows, the local domain is implemented using a named pipe. The path must\nrefer to an entry in \\\\?\\pipe\\ or \\\\.\\pipe\\. Any characters are permitted,\nbut the latter may do some processing of pipe names, such as resolving ..\nsequences. Despite how it might look, the pipe namespace is flat. Pipes will\nnot persist. They are removed when the last reference to them is closed.\nUnlike Unix domain sockets, Windows will close and remove the pipe when the\nowning process exits.

      \n

      JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:

      \n
      net.createServer().listen(\n  path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n
      ", + "type": "module", + "displayName": "Identifying paths for IPC connections" + } + ], + "type": "module", + "displayName": "IPC support" + } + ], + "classes": [ + { + "textRaw": "Class: `net.Server`", + "type": "class", + "name": "net.Server", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "desc": "\n

      This class is used to create a TCP or IPC server.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.

      " + }, + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{net.Socket} The connection object", + "type": "net.Socket", + "desc": "The connection object" + } + ], + "desc": "

      Emitted when a new connection is made. socket is an instance of\nnet.Socket.

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      Emitted when an error occurs. Unlike net.Socket, the 'close'\nevent will not be emitted directly following this event unless\nserver.close() is manually called. See the example in discussion of\nserver.listen().

      " + }, + { + "textRaw": "Event: `'listening'`", + "type": "event", + "name": "listening", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the server has been bound after calling server.listen().

      " + } + ], + "methods": [ + { + "textRaw": "`server.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object|string|null}", + "name": "return", + "type": "Object|string|null" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name, and port of the server\nas reported by the operating system if listening on an IP socket\n(useful to find which port was assigned when getting an OS-assigned address):\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      \n

      For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.

      \n
      const server = net.createServer((socket) => {\n  socket.end('goodbye\\n');\n}).on('error', (err) => {\n  // Handle errors here.\n  throw err;\n});\n\n// Grab an arbitrary unused port.\nserver.listen(() => {\n  console.log('opened server on', server.address());\n});\n
      \n

      server.address() returns null before the 'listening' event has been\nemitted or after calling server.close().

      " + }, + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function} Called when the server is closed.", + "name": "callback", + "type": "Function", + "desc": "Called when the server is closed." + } + ] + } + ], + "desc": "

      Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally closed\nwhen all connections are ended and the server emits a 'close' event.\nThe optional callback will be called once the 'close' event occurs. Unlike\nthat event, it will be called with an Error as its only argument if the server\nwas not open when it was closed.

      " + }, + { + "textRaw": "`server.getConnections(callback)`", + "type": "method", + "name": "getConnections", + "meta": { + "added": [ + "v0.9.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.

      \n

      Callback should take two arguments err and count.

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.

      \n

      Possible signatures:

      \n\n

      This function is asynchronous. When the server starts listening, the\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.

      \n

      All listen() methods can take a backlog parameter to specify the maximum\nlength of the queue of pending connections. The actual length will be determined\nby the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn\non Linux. The default value of this parameter is 511 (not 512).

      \n

      All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).

      \n

      The server.listen() method can be called again if and only if there was an\nerror during the first server.listen() call or server.close() has been\ncalled. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

      \n

      One of the most common errors raised when listening is EADDRINUSE.\nThis happens when another server is already listening on the requested\nport/path/handle. One way to handle this would be to retry\nafter a certain amount of time:

      \n
      server.on('error', (e) => {\n  if (e.code === 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(() => {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});\n
      ", + "methods": [ + { + "textRaw": "`server.listen(handle[, backlog][, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`handle` {Object}", + "name": "handle", + "type": "Object" + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Start a server listening for connections on a given handle that has\nalready been bound to a port, a Unix domain socket, or a Windows named pipe.

      \n

      The handle object can be either a server, a socket (anything with an\nunderlying _handle member), or an object with an fd member that is a\nvalid file descriptor.

      \n

      Listening on a file descriptor is not supported on Windows.

      " + }, + { + "textRaw": "`server.listen(options[, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [ + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/23798", + "description": "The `ipv6Only` option is supported." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`options` {Object} Required. Supports the following properties:", + "name": "options", + "type": "Object", + "desc": "Required. Supports the following properties:", + "options": [ + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`host` {string}", + "name": "host", + "type": "string" + }, + { + "textRaw": "`path` {string} Will be ignored if `port` is specified. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Will be ignored if `port` is specified. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions." + }, + { + "textRaw": "`exclusive` {boolean} **Default:** `false`", + "name": "exclusive", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`readableAll` {boolean} For IPC servers makes the pipe readable for all users. **Default:** `false`.", + "name": "readableAll", + "type": "boolean", + "default": "`false`", + "desc": "For IPC servers makes the pipe readable for all users." + }, + { + "textRaw": "`writableAll` {boolean} For IPC servers makes the pipe writable for all users. **Default:** `false`.", + "name": "writableAll", + "type": "boolean", + "default": "`false`", + "desc": "For IPC servers makes the pipe writable for all users." + }, + { + "textRaw": "`ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound. **Default:** `false`.", + "name": "ipv6Only", + "type": "boolean", + "default": "`false`", + "desc": "For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound." + } + ] + }, + { + "textRaw": "`callback` {Function} functions.", + "name": "callback", + "type": "Function", + "desc": "functions." + } + ] + } + ], + "desc": "

      If port is specified, it behaves the same as\n\nserver.listen([port[, host[, backlog]]][, callback]).\nOtherwise, if path is specified, it behaves the same as\nserver.listen(path[, backlog][, callback]).\nIf none of them is specified, an error will be thrown.

      \n

      If exclusive is false (default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive is true, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.

      \n
      server.listen({\n  host: 'localhost',\n  port: 80,\n  exclusive: true\n});\n
      \n

      Starting an IPC server as root may cause the server path to be inaccessible for\nunprivileged users. Using readableAll and writableAll will make the server\naccessible for all users.

      " + }, + { + "textRaw": "`server.listen(path[, backlog][, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`path` {string} Path the server should listen to. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Path the server should listen to. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions." + }, + { + "textRaw": "`callback` {Function}.", + "name": "callback", + "type": "Function", + "desc": "." + } + ] + } + ], + "desc": "

      Start an IPC server listening for connections on the given path.

      " + }, + { + "textRaw": "`server.listen([port[, host[, backlog]]][, callback])`", + "type": "method", + "name": "listen", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`host` {string}", + "name": "host", + "type": "string" + }, + { + "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", + "name": "backlog", + "type": "number", + "desc": "Common parameter of [`server.listen()`][] functions." + }, + { + "textRaw": "`callback` {Function}.", + "name": "callback", + "type": "Function", + "desc": "." + } + ] + } + ], + "desc": "

      Start a TCP server listening for connections on the given port and host.

      \n

      If port is omitted or is 0, the operating system will assign an arbitrary\nunused port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.

      \n

      If host is omitted, the server will accept connections on the\nunspecified IPv6 address (::) when IPv6 is available, or the\nunspecified IPv4 address (0.0.0.0) otherwise.

      \n

      In most operating systems, listening to the unspecified IPv6 address (::)\nmay cause the net.Server to also listen on the unspecified IPv4 address\n(0.0.0.0).

      " + } + ] + }, + { + "textRaw": "`server.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [] + } + ], + "desc": "

      Opposite of unref(), calling ref() on a previously unrefed server will\nnot let the program exit if it's the only server left (the default behavior).\nIf the server is refed calling ref() again will have no effect.

      " + }, + { + "textRaw": "`server.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [] + } + ], + "desc": "

      Calling unref() on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefed calling\nunref() again will have no effect.

      " + } + ], + "properties": [ + { + "textRaw": "`connections` {integer|null}", + "type": "integer|null", + "name": "connections", + "meta": { + "added": [ + "v0.2.0" + ], + "deprecated": [ + "v0.9.7" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", + "desc": "

      The number of concurrent connections on the server.

      \n

      This becomes null when sending a socket to a child with\nchild_process.fork(). To poll forks and get current number of active\nconnections, use asynchronous server.getConnections() instead.

      " + }, + { + "textRaw": "`listening` {boolean} Indicates whether or not the server is listening for connections.", + "type": "boolean", + "name": "listening", + "meta": { + "added": [ + "v5.7.0" + ], + "changes": [] + }, + "desc": "Indicates whether or not the server is listening for connections." + }, + { + "textRaw": "`maxConnections` {integer}", + "type": "integer", + "name": "maxConnections", + "meta": { + "added": [ + "v0.2.0" + ], + "changes": [] + }, + "desc": "

      Set this property to reject connections when the server's connection count gets\nhigh.

      \n

      It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().

      " + } + ], + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`options` {Object} See [`net.createServer([options][, connectionListener])`][`net.createServer()`].", + "name": "options", + "type": "Object", + "desc": "See [`net.createServer([options][, connectionListener])`][`net.createServer()`]." + }, + { + "textRaw": "`connectionListener` {Function} Automatically set as a listener for the [`'connection'`][] event.", + "name": "connectionListener", + "type": "Function", + "desc": "Automatically set as a listener for the [`'connection'`][] event." + } + ], + "desc": "

      net.Server is an EventEmitter with the following events:

      " + } + ] + }, + { + "textRaw": "Class: `net.Socket`", + "type": "class", + "name": "net.Socket", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "desc": "\n

      This class is an abstraction of a TCP socket or a streaming IPC endpoint\n(uses named pipes on Windows, and Unix domain sockets otherwise). It is also\nan EventEmitter.

      \n

      A net.Socket can be created by the user and used directly to interact with\na server. For example, it is returned by net.createConnection(),\nso the user can use it to talk to the server.

      \n

      It can also be created by Node.js and passed to the user when a connection\nis received. For example, it is passed to the listeners of a\n'connection' event emitted on a net.Server, so the user can use\nit to interact with the client.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`hadError` {boolean} `true` if the socket had a transmission error.", + "name": "hadError", + "type": "boolean", + "desc": "`true` if the socket had a transmission error." + } + ], + "desc": "

      Emitted once the socket is fully closed. The argument hadError is a boolean\nwhich says if the socket was closed due to a transmission error.

      " + }, + { + "textRaw": "Event: `'connect'`", + "type": "event", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when a socket connection is successfully established.\nSee net.createConnection().

      " + }, + { + "textRaw": "Event: `'data'`", + "type": "event", + "name": "data", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Buffer|string}", + "type": "Buffer|string" + } + ], + "desc": "

      Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().

      \n

      The data will be lost if there is no listener when a Socket\nemits a 'data' event.

      " + }, + { + "textRaw": "Event: `'drain'`", + "type": "event", + "name": "drain", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the write buffer becomes empty. Can be used to throttle uploads.

      \n

      See also: the return values of socket.write().

      " + }, + { + "textRaw": "Event: `'end'`", + "type": "event", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when the other end of the socket sends a FIN packet, thus ending the\nreadable side of the socket.

      \n

      By default (allowHalfOpen is false) the socket will send a FIN packet\nback and destroy its file descriptor once it has written out its pending\nwrite queue. However, if allowHalfOpen is set to true, the socket will\nnot automatically end() its writable side, allowing the\nuser to write arbitrary amounts of data. The user must call\nend() explicitly to close the connection (i.e. sending a\nFIN packet back).

      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.

      " + }, + { + "textRaw": "Event: `'lookup'`", + "type": "event", + "name": "lookup", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [ + { + "version": "v5.10.0", + "pr-url": "https://github.com/nodejs/node/pull/5598", + "description": "The `host` parameter is supported now." + } + ] + }, + "params": [], + "desc": "

      Emitted after resolving the host name but before connecting.\nNot applicable to Unix sockets.

      \n" + }, + { + "textRaw": "Event: `'ready'`", + "type": "event", + "name": "ready", + "meta": { + "added": [ + "v9.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted when a socket is ready to be used.

      \n

      Triggered immediately after 'connect'.

      " + }, + { + "textRaw": "Event: `'timeout'`", + "type": "event", + "name": "timeout", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "params": [], + "desc": "

      Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.

      \n

      See also: socket.setTimeout().

      " + } + ], + "methods": [ + { + "textRaw": "`socket.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name and port of the\nsocket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

      " + }, + { + "textRaw": "`socket.connect()`", + "type": "method", + "name": "connect", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Initiate a connection on a given socket.

      \n

      Possible signatures:

      \n\n

      This function is asynchronous. When the connection is established, the\n'connect' event will be emitted. If there is a problem connecting,\ninstead of a 'connect' event, an 'error' event will be emitted with\nthe error passed to the 'error' listener.\nThe last parameter connectListener, if supplied, will be added as a listener\nfor the 'connect' event once.

      \n

      This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.

      ", + "methods": [ + { + "textRaw": "`socket.connect(options[, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [ + { + "version": "v12.10.0", + "pr-url": "https://github.com/nodejs/node/pull/25436", + "description": "Added `onread` option." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6021", + "description": "The `hints` option defaults to `0` in all cases now. Previously, in the absence of the `family` option it would default to `dns.ADDRCONFIG | dns.V4MAPPED`." + }, + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/6000", + "description": "The `hints` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object" + }, + { + "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." + } + ] + } + ], + "desc": "

      Initiate a connection on a given socket. Normally this method is not needed,\nthe socket should be created and opened with net.createConnection(). Use\nthis only when implementing a custom Socket.

      \n

      For TCP connections, available options are:

      \n
        \n
      • port <number> Required. Port the socket should connect to.
      • \n
      • host <string> Host the socket should connect to. Default: 'localhost'.
      • \n
      • localAddress <string> Local address the socket should connect from.
      • \n
      • localPort <number> Local port the socket should connect from.
      • \n
      • family <number>: Version of IP stack. Must be 4, 6, or 0. The value\n0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.
      • \n
      • hints <number> Optional dns.lookup() hints.
      • \n
      • lookup <Function> Custom lookup function. Default: dns.lookup().
      • \n
      \n

      For IPC connections, available options are:

      \n\n

      For both types, available options include:

      \n
        \n
      • onread <Object> If specified, incoming data is stored in a single buffer\nand passed to the supplied callback when data arrives on the socket.\nThis will cause the streaming functionality to not provide any data.\nThe socket will emit events like 'error', 'end', and 'close'\nas usual. Methods like pause() and resume() will also behave as\nexpected.\n
          \n
        • buffer <Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to\nuse for storing incoming data or a function that returns such.
        • \n
        • callback <Function> This function is called for every chunk of incoming\ndata. Two arguments are passed to it: the number of bytes written to\nbuffer and a reference to buffer. Return false from this function to\nimplicitly pause() the socket. This function will be executed in the\nglobal context.
        • \n
        \n
      • \n
      \n

      Following is an example of a client using the onread option:

      \n
      const net = require('net');\nnet.connect({\n  port: 80,\n  onread: {\n    // Reuses a 4KiB Buffer for every read from the socket.\n    buffer: Buffer.alloc(4 * 1024),\n    callback: function(nread, buf) {\n      // Received data is available in `buf` from 0 to `nread`.\n      console.log(buf.toString('utf8', 0, nread));\n    }\n  }\n});\n
      " + }, + { + "textRaw": "`socket.connect(path[, connectListener])`", + "type": "method", + "name": "connect", + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`path` {string} Path the client should connect to. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Path the client should connect to. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." + } + ] + } + ], + "desc": "

      Initiate an IPC connection on the given socket.

      \n

      Alias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.

      " + }, + { + "textRaw": "`socket.connect(port[, host][, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`port` {number} Port the client should connect to.", + "name": "port", + "type": "number", + "desc": "Port the client should connect to." + }, + { + "textRaw": "`host` {string} Host the client should connect to.", + "name": "host", + "type": "string", + "desc": "Host the client should connect to." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." + } + ] + } + ], + "desc": "

      Initiate a TCP connection on the given socket.

      \n

      Alias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.

      " + } + ] + }, + { + "textRaw": "`socket.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`error` {Object}", + "name": "error", + "type": "Object" + } + ] + } + ], + "desc": "

      Ensures that no more I/O activity happens on this socket.\nDestroys the stream and closes the connection.

      \n

      See writable.destroy() for further details.

      " + }, + { + "textRaw": "`socket.end([data[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "Only used when data is `string`." + }, + { + "textRaw": "`callback` {Function} Optional callback for when the socket is finished.", + "name": "callback", + "type": "Function", + "desc": "Optional callback for when the socket is finished." + } + ] + } + ], + "desc": "

      Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.

      \n

      See writable.end() for further details.

      " + }, + { + "textRaw": "`socket.pause()`", + "type": "method", + "name": "pause", + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.

      " + }, + { + "textRaw": "`socket.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Opposite of unref(), calling ref() on a previously unrefed socket will\nnot let the program exit if it's the only socket left (the default behavior).\nIf the socket is refed calling ref again will have no effect.

      " + }, + { + "textRaw": "`socket.resume()`", + "type": "method", + "name": "resume", + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Resumes reading after a call to socket.pause().

      " + }, + { + "textRaw": "`socket.setEncoding([encoding])`", + "type": "method", + "name": "setEncoding", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`encoding` {string}", + "name": "encoding", + "type": "string" + } + ] + } + ], + "desc": "

      Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.

      " + }, + { + "textRaw": "`socket.setKeepAlive([enable][, initialDelay])`", + "type": "method", + "name": "setKeepAlive", + "meta": { + "added": [ + "v0.1.92" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`enable` {boolean} **Default:** `false`", + "name": "enable", + "type": "boolean", + "default": "`false`" + }, + { + "textRaw": "`initialDelay` {number} **Default:** `0`", + "name": "initialDelay", + "type": "number", + "default": "`0`" + } + ] + } + ], + "desc": "

      Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.

      \n

      Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting.

      " + }, + { + "textRaw": "`socket.setNoDelay([noDelay])`", + "type": "method", + "name": "setNoDelay", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`noDelay` {boolean} **Default:** `true`", + "name": "noDelay", + "type": "boolean", + "default": "`true`" + } + ] + } + ], + "desc": "

      Enable/disable the use of Nagle's algorithm.

      \n

      When a TCP connection is created, it will have Nagle's algorithm enabled.

      \n

      Nagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.

      \n

      Passing true for noDelay or not passing an argument will disable Nagle's\nalgorithm for the socket. Passing false for noDelay will enable Nagle's\nalgorithm.

      " + }, + { + "textRaw": "`socket.setTimeout(timeout[, callback])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [ + { + "textRaw": "`timeout` {number}", + "name": "timeout", + "type": "number" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.

      \n

      When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually call\nsocket.end() or socket.destroy() to end the connection.

      \n
      socket.setTimeout(3000);\nsocket.on('timeout', () => {\n  console.log('socket timeout');\n  socket.end();\n});\n
      \n

      If timeout is 0, then the existing idle timeout is disabled.

      \n

      The optional callback parameter will be added as a one-time listener for the\n'timeout' event.

      " + }, + { + "textRaw": "`socket.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The socket itself.", + "name": "return", + "type": "net.Socket", + "desc": "The socket itself." + }, + "params": [] + } + ], + "desc": "

      Calling unref() on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefed calling\nunref() again will have no effect.

      " + }, + { + "textRaw": "`socket.write(data[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`data` {string|Buffer|Uint8Array}", + "name": "data", + "type": "string|Buffer|Uint8Array" + }, + { + "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `utf8`.", + "name": "encoding", + "type": "string", + "default": "`utf8`", + "desc": "Only used when data is `string`." + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.

      \n

      Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.

      \n

      The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.

      \n

      See Writable stream write() method for more\ninformation.

      " + } + ], + "properties": [ + { + "textRaw": "`bufferSize` {integer}", + "type": "integer", + "name": "bufferSize", + "meta": { + "added": [ + "v0.3.8" + ], + "changes": [] + }, + "desc": "

      This property shows the number of characters buffered for writing. The buffer\nmay contain strings whose length after encoding is not yet known. So this number\nis only an approximation of the number of bytes in the buffer.

      \n

      net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket. The network connection\nsimply might be too slow. Node.js will internally queue up the data written to a\nsocket and send it out over the wire when it is possible.

      \n

      The consequence of this internal buffering is that memory may grow.\nUsers who experience large or growing bufferSize should attempt to\n\"throttle\" the data flows in their program with\nsocket.pause() and socket.resume().

      " + }, + { + "textRaw": "`bytesRead` {integer}", + "type": "integer", + "name": "bytesRead", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "desc": "

      The amount of received bytes.

      " + }, + { + "textRaw": "`bytesWritten` {integer}", + "type": "integer", + "name": "bytesWritten", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "desc": "

      The amount of bytes sent.

      " + }, + { + "textRaw": "`connecting` {boolean}", + "type": "boolean", + "name": "connecting", + "meta": { + "added": [ + "v6.1.0" + ], + "changes": [] + }, + "desc": "

      If true,\nsocket.connect(options[, connectListener]) was\ncalled and has not yet finished. It will stay true until the socket becomes\nconnected, then it is set to false and the 'connect' event is emitted. Note\nthat the\nsocket.connect(options[, connectListener])\ncallback is a listener for the 'connect' event.

      " + }, + { + "textRaw": "`destroyed` {boolean} Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.", + "type": "boolean", + "name": "destroyed", + "desc": "

      See writable.destroyed for further details.

      ", + "shortDesc": "Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it." + }, + { + "textRaw": "`localAddress` {string}", + "type": "string", + "name": "localAddress", + "meta": { + "added": [ + "v0.9.6" + ], + "changes": [] + }, + "desc": "

      The string representation of the local IP address the remote client is\nconnecting on. For example, in a server listening on '0.0.0.0', if a client\nconnects on '192.168.1.1', the value of socket.localAddress would be\n'192.168.1.1'.

      " + }, + { + "textRaw": "`localPort` {integer}", + "type": "integer", + "name": "localPort", + "meta": { + "added": [ + "v0.9.6" + ], + "changes": [] + }, + "desc": "

      The numeric representation of the local port. For example, 80 or 21.

      " + }, + { + "textRaw": "`pending` {boolean}", + "type": "boolean", + "name": "pending", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "desc": "

      This is true if the socket is not connected yet, either because .connect()\nhas not yet been called or because it is still in the process of connecting\n(see socket.connecting).

      " + }, + { + "textRaw": "`remoteAddress` {string}", + "type": "string", + "name": "remoteAddress", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "desc": "

      The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).

      " + }, + { + "textRaw": "`remoteFamily` {string}", + "type": "string", + "name": "remoteFamily", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "desc": "

      The string representation of the remote IP family. 'IPv4' or 'IPv6'.

      " + }, + { + "textRaw": "`remotePort` {integer}", + "type": "integer", + "name": "remotePort", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "desc": "

      The numeric representation of the remote port. For example, 80 or 21.

      " + } + ], + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`options` {Object} Available options are:", + "name": "options", + "type": "Object", + "desc": "Available options are:", + "options": [ + { + "textRaw": "`fd` {number} If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.", + "name": "fd", + "type": "number", + "desc": "If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created." + }, + { + "textRaw": "`allowHalfOpen` {boolean} Indicates whether half-opened TCP connections are allowed. See [`net.createServer()`][] and the [`'end'`][] event for details. **Default:** `false`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether half-opened TCP connections are allowed. See [`net.createServer()`][] and the [`'end'`][] event for details." + }, + { + "textRaw": "`readable` {boolean} Allow reads on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", + "name": "readable", + "type": "boolean", + "default": "`false`", + "desc": "Allow reads on the socket when an `fd` is passed, otherwise ignored." + }, + { + "textRaw": "`writable` {boolean} Allow writes on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", + "name": "writable", + "type": "boolean", + "default": "`false`", + "desc": "Allow writes on the socket when an `fd` is passed, otherwise ignored." + } + ] + } + ], + "desc": "

      Creates a new socket object.

      \n

      The newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`net.connect()`", + "type": "method", + "name": "connect", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Aliases to\nnet.createConnection().

      \n

      Possible signatures:

      \n", + "methods": [ + { + "textRaw": "`net.connect(options[, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object" + }, + { + "textRaw": "`connectListener` {Function}", + "name": "connectListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias to\nnet.createConnection(options[, connectListener]).

      " + }, + { + "textRaw": "`net.connect(path[, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + }, + { + "textRaw": "`connectListener` {Function}", + "name": "connectListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias to\nnet.createConnection(path[, connectListener]).

      " + }, + { + "textRaw": "`net.connect(port[, host][, connectListener])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket}", + "name": "return", + "type": "net.Socket" + }, + "params": [ + { + "textRaw": "`port` {number}", + "name": "port", + "type": "number" + }, + { + "textRaw": "`host` {string}", + "name": "host", + "type": "string" + }, + { + "textRaw": "`connectListener` {Function}", + "name": "connectListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Alias to\nnet.createConnection(port[, host][, connectListener]).

      " + } + ] + }, + { + "textRaw": "`net.createConnection()`", + "type": "method", + "name": "createConnection", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.

      \n

      When the connection is established, a 'connect' event will be emitted\non the returned socket. The last parameter connectListener, if supplied,\nwill be added as a listener for the 'connect' event once.

      \n

      Possible signatures:

      \n\n

      The net.connect() function is an alias to this function.

      ", + "methods": [ + { + "textRaw": "`net.createConnection(options[, connectListener])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.", + "name": "return", + "type": "net.Socket", + "desc": "The newly created socket used to start the connection." + }, + "params": [ + { + "textRaw": "`options` {Object} Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] method.", + "name": "options", + "type": "Object", + "desc": "Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] method." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions. If supplied, will be added as a listener for the [`'connect'`][] event on the returned socket once.", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of the [`net.createConnection()`][] functions. If supplied, will be added as a listener for the [`'connect'`][] event on the returned socket once." + } + ] + } + ], + "desc": "

      For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).

      \n

      Additional options:

      \n\n

      Following is an example of a client of the echo server described\nin the net.createServer() section:

      \n
      const net = require('net');\nconst client = net.createConnection({ port: 8124 }, () => {\n  // 'connect' listener.\n  console.log('connected to server!');\n  client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', () => {\n  console.log('disconnected from server');\n});\n
      \n

      To connect on the socket /tmp/echo.sock:

      \n
      const client = net.createConnection({ path: '/tmp/echo.sock' });\n
      " + }, + { + "textRaw": "`net.createConnection(path[, connectListener])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.", + "name": "return", + "type": "net.Socket", + "desc": "The newly created socket used to start the connection." + }, + "params": [ + { + "textRaw": "`path` {string} Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. See [Identifying paths for IPC connections][].", + "name": "path", + "type": "string", + "desc": "Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. See [Identifying paths for IPC connections][]." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`].", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]." + } + ] + } + ], + "desc": "

      Initiates an IPC connection.

      \n

      This function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(path[, connectListener]),\nthen returns the net.Socket that starts the connection.

      " + }, + { + "textRaw": "`net.createConnection(port[, host][, connectListener])`", + "type": "method", + "name": "createConnection", + "meta": { + "added": [ + "v0.1.90" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.", + "name": "return", + "type": "net.Socket", + "desc": "The newly created socket used to start the connection." + }, + "params": [ + { + "textRaw": "`port` {number} Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].", + "name": "port", + "type": "number", + "desc": "Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." + }, + { + "textRaw": "`host` {string} Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." + }, + { + "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].", + "name": "connectListener", + "type": "Function", + "desc": "Common parameter of the [`net.createConnection()`][] functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." + } + ] + } + ], + "desc": "

      Initiates a TCP connection.

      \n

      This function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(port[, host][, connectListener]),\nthen returns the net.Socket that starts the connection.

      " + } + ] + }, + { + "textRaw": "`net.createServer([options][, connectionListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {net.Server}", + "name": "return", + "type": "net.Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`allowHalfOpen` {boolean} Indicates whether half-opened TCP connections are allowed. **Default:** `false`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether half-opened TCP connections are allowed." + }, + { + "textRaw": "`pauseOnConnect` {boolean} Indicates whether the socket should be paused on incoming connections. **Default:** `false`.", + "name": "pauseOnConnect", + "type": "boolean", + "default": "`false`", + "desc": "Indicates whether the socket should be paused on incoming connections." + } + ] + }, + { + "textRaw": "`connectionListener` {Function} Automatically set as a listener for the [`'connection'`][] event.", + "name": "connectionListener", + "type": "Function", + "desc": "Automatically set as a listener for the [`'connection'`][] event." + } + ] + } + ], + "desc": "

      Creates a new TCP or IPC server.

      \n

      If allowHalfOpen is set to true, when the other end of the socket\nsends a FIN packet, the server will only send a FIN packet back when\nsocket.end() is explicitly called, until then the connection is\nhalf-closed (non-readable but still writable). See 'end' event\nand RFC 1122 (section 4.2.2.13) for more information.

      \n

      If pauseOnConnect is set to true, then the socket associated with each\nincoming connection will be paused, and no data will be read from its handle.\nThis allows connections to be passed between processes without any data being\nread by the original process. To begin reading data from a paused socket, call\nsocket.resume().

      \n

      The server can be a TCP server or an IPC server, depending on what it\nlisten() to.

      \n

      Here is an example of an TCP echo server which listens for connections\non port 8124:

      \n
      const net = require('net');\nconst server = net.createServer((c) => {\n  // 'connection' listener.\n  console.log('client connected');\n  c.on('end', () => {\n    console.log('client disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.on('error', (err) => {\n  throw err;\n});\nserver.listen(8124, () => {\n  console.log('server bound');\n});\n
      \n

      Test this by using telnet:

      \n
      $ telnet localhost 8124\n
      \n

      To listen on the socket /tmp/echo.sock:

      \n
      server.listen('/tmp/echo.sock', () => {\n  console.log('server bound');\n});\n
      \n

      Use nc to connect to a Unix domain socket server:

      \n
      $ nc -U /tmp/echo.sock\n
      " + }, + { + "textRaw": "`net.isIP(input)`", + "type": "method", + "name": "isIP", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`input` {string}", + "name": "input", + "type": "string" + } + ] + } + ], + "desc": "

      Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6\naddresses.

      " + }, + { + "textRaw": "`net.isIPv4(input)`", + "type": "method", + "name": "isIPv4", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`input` {string}", + "name": "input", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if input is a version 4 IP address, otherwise returns false.

      " + }, + { + "textRaw": "`net.isIPv6(input)`", + "type": "method", + "name": "isIPv6", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`input` {string}", + "name": "input", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if input is a version 6 IP address, otherwise returns false.

      " + } + ], + "type": "module", + "displayName": "Net" + } + ] +} \ No newline at end of file diff --git a/doc/api/os.html b/doc/api/os.html new file mode 100644 index 0000000000000000000000000000000000000000..e3ad9211ebfa5d1ed545250536c431e5ff795262 --- /dev/null +++ b/doc/api/os.html @@ -0,0 +1,1390 @@ + + + + + + + OS | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      OS#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/os.js

      +

      The os module provides operating system-related utility methods and +properties. It can be accessed using:

      +
      const os = require('os');
      +

      os.EOL#

      + + +

      The operating system-specific end-of-line marker.

      +
        +
      • \n on POSIX
      • +
      • \r\n on Windows
      • +
      +

      os.arch()#

      + + +

      Returns the operating system CPU architecture for which the Node.js binary was +compiled. Possible values are 'arm', 'arm64', 'ia32', 'mips', +'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

      +

      The return value is equivalent to process.arch.

      +

      os.constants#

      + + +

      Contains commonly used operating system-specific constants for error codes, +process signals, and so on. The specific constants defined are described in +OS constants.

      +

      os.cpus()#

      + + +

      Returns an array of objects containing information about each logical CPU core.

      +

      The properties included on each object include:

      +
        +
      • model <string>
      • +
      • speed <number> (in MHz)
      • +
      • times <Object> +
          +
        • user <number> The number of milliseconds the CPU has spent in user mode.
        • +
        • nice <number> The number of milliseconds the CPU has spent in nice mode.
        • +
        • sys <number> The number of milliseconds the CPU has spent in sys mode.
        • +
        • idle <number> The number of milliseconds the CPU has spent in idle mode.
        • +
        • irq <number> The number of milliseconds the CPU has spent in irq mode.
        • +
        +
      • +
      + +
      [
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 252020,
      +      nice: 0,
      +      sys: 30340,
      +      idle: 1070356870,
      +      irq: 0
      +    }
      +  },
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 306960,
      +      nice: 0,
      +      sys: 26980,
      +      idle: 1071569080,
      +      irq: 0
      +    }
      +  },
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 248450,
      +      nice: 0,
      +      sys: 21750,
      +      idle: 1070919370,
      +      irq: 0
      +    }
      +  },
      +  {
      +    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
      +    speed: 2926,
      +    times: {
      +      user: 256880,
      +      nice: 0,
      +      sys: 19430,
      +      idle: 1070905480,
      +      irq: 20
      +    }
      +  }
      +]
      +

      nice values are POSIX-only. On Windows, the nice values of all processors +are always 0.

      +

      os.endianness()#

      + + +

      Returns a string identifying the endianness of the CPU for which the Node.js +binary was compiled.

      +

      Possible values are 'BE' for big endian and 'LE' for little endian.

      +

      os.freemem()#

      + + +

      Returns the amount of free system memory in bytes as an integer.

      +

      os.getPriority([pid])#

      + +
        +
      • pid <integer> The process ID to retrieve scheduling priority for. +Default 0.
      • +
      • Returns: <integer>
      • +
      +

      Returns the scheduling priority for the process specified by pid. If pid is +not provided or is 0, the priority of the current process is returned.

      +

      os.homedir()#

      + + +

      Returns the string path of the current user's home directory.

      +

      On POSIX, it uses the $HOME environment variable if defined. Otherwise it +uses the effective UID to look up the user's home directory.

      +

      On Windows, it uses the USERPROFILE environment variable if defined. +Otherwise it uses the path to the profile directory of the current user.

      +

      os.hostname()#

      + + +

      Returns the host name of the operating system as a string.

      +

      os.loadavg()#

      + + +

      Returns an array containing the 1, 5, and 15 minute load averages.

      +

      The load average is a measure of system activity calculated by the operating +system and expressed as a fractional number.

      +

      The load average is a Unix-specific concept. On Windows, the return value is +always [0, 0, 0].

      +

      os.networkInterfaces()#

      + + +

      Returns an object containing network interfaces that have been assigned a +network address.

      +

      Each key on the returned object identifies a network interface. The associated +value is an array of objects that each describe an assigned network address.

      +

      The properties available on the assigned network address object include:

      +
        +
      • address <string> The assigned IPv4 or IPv6 address
      • +
      • netmask <string> The IPv4 or IPv6 network mask
      • +
      • family <string> Either IPv4 or IPv6
      • +
      • mac <string> The MAC address of the network interface
      • +
      • internal <boolean> true if the network interface is a loopback or +similar interface that is not remotely accessible; otherwise false
      • +
      • scopeid <number> The numeric IPv6 scope ID (only specified when family +is IPv6)
      • +
      • cidr <string> The assigned IPv4 or IPv6 address with the routing prefix +in CIDR notation. If the netmask is invalid, this property is set +to null.
      • +
      + +
      {
      +  lo: [
      +    {
      +      address: '127.0.0.1',
      +      netmask: '255.0.0.0',
      +      family: 'IPv4',
      +      mac: '00:00:00:00:00:00',
      +      internal: true,
      +      cidr: '127.0.0.1/8'
      +    },
      +    {
      +      address: '::1',
      +      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      +      family: 'IPv6',
      +      mac: '00:00:00:00:00:00',
      +      scopeid: 0,
      +      internal: true,
      +      cidr: '::1/128'
      +    }
      +  ],
      +  eth0: [
      +    {
      +      address: '192.168.1.108',
      +      netmask: '255.255.255.0',
      +      family: 'IPv4',
      +      mac: '01:02:03:0a:0b:0c',
      +      internal: false,
      +      cidr: '192.168.1.108/24'
      +    },
      +    {
      +      address: 'fe80::a00:27ff:fe4e:66a1',
      +      netmask: 'ffff:ffff:ffff:ffff::',
      +      family: 'IPv6',
      +      mac: '01:02:03:0a:0b:0c',
      +      scopeid: 1,
      +      internal: false,
      +      cidr: 'fe80::a00:27ff:fe4e:66a1/64'
      +    }
      +  ]
      +}
      +

      os.platform()#

      + + +

      Returns a string identifying the operating system platform. The value is set +at compile time. Possible values are 'aix', 'darwin', 'freebsd', +'linux', 'openbsd', 'sunos', and 'win32'.

      +

      The return value is equivalent to process.platform.

      +

      The value 'android' may also be returned if Node.js is built on the Android +operating system. Android support is experimental.

      +

      os.release()#

      + + +

      Returns the operating system as a string.

      +

      On POSIX systems, the operating system release is determined by calling +uname(3). On Windows, GetVersionExW() is used. See +https://en.wikipedia.org/wiki/Uname#Examples for more information.

      +

      os.setPriority([pid, ]priority)#

      + +
        +
      • pid <integer> The process ID to set scheduling priority for. +Default 0.
      • +
      • priority <integer> The scheduling priority to assign to the process.
      • +
      +

      Attempts to set the scheduling priority for the process specified by pid. If +pid is not provided or is 0, the process ID of the current process is used.

      +

      The priority input must be an integer between -20 (high priority) and 19 +(low priority). Due to differences between Unix priority levels and Windows +priority classes, priority is mapped to one of six priority constants in +os.constants.priority. When retrieving a process priority level, this range +mapping may cause the return value to be slightly different on Windows. To avoid +confusion, set priority to one of the priority constants.

      +

      On Windows, setting priority to PRIORITY_HIGHEST requires elevated user +privileges. Otherwise the set priority will be silently reduced to +PRIORITY_HIGH.

      +

      os.tmpdir()#

      + + +

      Returns the operating system's default directory for temporary files as a +string.

      +

      os.totalmem()#

      + + +

      Returns the total amount of system memory in bytes as an integer.

      +

      os.type()#

      + + +

      Returns the operating system name as returned by uname(3). For example, it +returns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows.

      +

      See https://en.wikipedia.org/wiki/Uname#Examples for additional information +about the output of running uname(3) on various operating systems.

      +

      os.uptime()#

      + + +

      Returns the system uptime in number of seconds.

      +

      os.userInfo([options])#

      + +
        +
      • options <Object> +
          +
        • encoding <string> Character encoding used to interpret resulting strings. +If encoding is set to 'buffer', the username, shell, and homedir +values will be Buffer instances. Default: 'utf8'.
        • +
        +
      • +
      • Returns: <Object>
      • +
      +

      Returns information about the currently effective user. On POSIX platforms, +this is typically a subset of the password file. The returned object includes +the username, uid, gid, shell, and homedir. On Windows, the uid and +gid fields are -1, and shell is null.

      +

      The value of homedir returned by os.userInfo() is provided by the operating +system. This differs from the result of os.homedir(), which queries +environment variables for the home directory before falling back to the +operating system response.

      +

      Throws a SystemError if a user has no username or homedir.

      +

      os.version()#

      + + +

      Returns a string identifying the kernel version.

      +

      On POSIX systems, the operating system release is determined by calling +uname(3). On Windows, RtlGetVersion() is used, and if it is not +available, GetVersionExW() will be used. See +https://en.wikipedia.org/wiki/Uname#Examples for more information.

      +

      OS constants#

      +

      The following constants are exported by os.constants.

      +

      Not all constants will be available on every operating system.

      +

      Signal constants#

      + +

      The following signal constants are exported by os.constants.signals.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      SIGHUPSent to indicate when a controlling terminal is closed or a parent + process exits.
      SIGINTSent to indicate when a user wishes to interrupt a process + ((Ctrl+C)).
      SIGQUITSent to indicate when a user wishes to terminate a process and perform a + core dump.
      SIGILLSent to a process to notify that it has attempted to perform an illegal, + malformed, unknown, or privileged instruction.
      SIGTRAPSent to a process when an exception has occurred.
      SIGABRTSent to a process to request that it abort.
      SIGIOTSynonym for SIGABRT
      SIGBUSSent to a process to notify that it has caused a bus error.
      SIGFPESent to a process to notify that it has performed an illegal arithmetic + operation.
      SIGKILLSent to a process to terminate it immediately.
      SIGUSR1 SIGUSR2Sent to a process to identify user-defined conditions.
      SIGSEGVSent to a process to notify of a segmentation fault.
      SIGPIPESent to a process when it has attempted to write to a disconnected + pipe.
      SIGALRMSent to a process when a system timer elapses.
      SIGTERMSent to a process to request termination.
      SIGCHLDSent to a process when a child process terminates.
      SIGSTKFLTSent to a process to indicate a stack fault on a coprocessor.
      SIGCONTSent to instruct the operating system to continue a paused process.
      SIGSTOPSent to instruct the operating system to halt a process.
      SIGTSTPSent to a process to request it to stop.
      SIGBREAKSent to indicate when a user wishes to interrupt a process.
      SIGTTINSent to a process when it reads from the TTY while in the + background.
      SIGTTOUSent to a process when it writes to the TTY while in the + background.
      SIGURGSent to a process when a socket has urgent data to read.
      SIGXCPUSent to a process when it has exceeded its limit on CPU usage.
      SIGXFSZSent to a process when it grows a file larger than the maximum + allowed.
      SIGVTALRMSent to a process when a virtual timer has elapsed.
      SIGPROFSent to a process when a system timer has elapsed.
      SIGWINCHSent to a process when the controlling terminal has changed its + size.
      SIGIOSent to a process when I/O is available.
      SIGPOLLSynonym for SIGIO
      SIGLOSTSent to a process when a file lock has been lost.
      SIGPWRSent to a process to notify of a power failure.
      SIGINFOSynonym for SIGPWR
      SIGSYSSent to a process to notify of a bad argument.
      SIGUNUSEDSynonym for SIGSYS
      +

      Error constants#

      +

      The following error constants are exported by os.constants.errno.

      +

      POSIX error constants#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      E2BIGIndicates that the list of arguments is longer than expected.
      EACCESIndicates that the operation did not have sufficient permissions.
      EADDRINUSEIndicates that the network address is already in use.
      EADDRNOTAVAILIndicates that the network address is currently unavailable for + use.
      EAFNOSUPPORTIndicates that the network address family is not supported.
      EAGAINIndicates that there is no data available and to try the + operation again later.
      EALREADYIndicates that the socket already has a pending connection in + progress.
      EBADFIndicates that a file descriptor is not valid.
      EBADMSGIndicates an invalid data message.
      EBUSYIndicates that a device or resource is busy.
      ECANCELEDIndicates that an operation was canceled.
      ECHILDIndicates that there are no child processes.
      ECONNABORTEDIndicates that the network connection has been aborted.
      ECONNREFUSEDIndicates that the network connection has been refused.
      ECONNRESETIndicates that the network connection has been reset.
      EDEADLKIndicates that a resource deadlock has been avoided.
      EDESTADDRREQIndicates that a destination address is required.
      EDOMIndicates that an argument is out of the domain of the function.
      EDQUOTIndicates that the disk quota has been exceeded.
      EEXISTIndicates that the file already exists.
      EFAULTIndicates an invalid pointer address.
      EFBIGIndicates that the file is too large.
      EHOSTUNREACHIndicates that the host is unreachable.
      EIDRMIndicates that the identifier has been removed.
      EILSEQIndicates an illegal byte sequence.
      EINPROGRESSIndicates that an operation is already in progress.
      EINTRIndicates that a function call was interrupted.
      EINVALIndicates that an invalid argument was provided.
      EIOIndicates an otherwise unspecified I/O error.
      EISCONNIndicates that the socket is connected.
      EISDIRIndicates that the path is a directory.
      ELOOPIndicates too many levels of symbolic links in a path.
      EMFILEIndicates that there are too many open files.
      EMLINKIndicates that there are too many hard links to a file.
      EMSGSIZEIndicates that the provided message is too long.
      EMULTIHOPIndicates that a multihop was attempted.
      ENAMETOOLONGIndicates that the filename is too long.
      ENETDOWNIndicates that the network is down.
      ENETRESETIndicates that the connection has been aborted by the network.
      ENETUNREACHIndicates that the network is unreachable.
      ENFILEIndicates too many open files in the system.
      ENOBUFSIndicates that no buffer space is available.
      ENODATAIndicates that no message is available on the stream head read + queue.
      ENODEVIndicates that there is no such device.
      ENOENTIndicates that there is no such file or directory.
      ENOEXECIndicates an exec format error.
      ENOLCKIndicates that there are no locks available.
      ENOLINKIndications that a link has been severed.
      ENOMEMIndicates that there is not enough space.
      ENOMSGIndicates that there is no message of the desired type.
      ENOPROTOOPTIndicates that a given protocol is not available.
      ENOSPCIndicates that there is no space available on the device.
      ENOSRIndicates that there are no stream resources available.
      ENOSTRIndicates that a given resource is not a stream.
      ENOSYSIndicates that a function has not been implemented.
      ENOTCONNIndicates that the socket is not connected.
      ENOTDIRIndicates that the path is not a directory.
      ENOTEMPTYIndicates that the directory is not empty.
      ENOTSOCKIndicates that the given item is not a socket.
      ENOTSUPIndicates that a given operation is not supported.
      ENOTTYIndicates an inappropriate I/O control operation.
      ENXIOIndicates no such device or address.
      EOPNOTSUPPIndicates that an operation is not supported on the socket. Although + ENOTSUP and EOPNOTSUPP have the same value + on Linux, according to POSIX.1 these error values should be distinct.)
      EOVERFLOWIndicates that a value is too large to be stored in a given data + type.
      EPERMIndicates that the operation is not permitted.
      EPIPEIndicates a broken pipe.
      EPROTOIndicates a protocol error.
      EPROTONOSUPPORTIndicates that a protocol is not supported.
      EPROTOTYPEIndicates the wrong type of protocol for a socket.
      ERANGEIndicates that the results are too large.
      EROFSIndicates that the file system is read only.
      ESPIPEIndicates an invalid seek operation.
      ESRCHIndicates that there is no such process.
      ESTALEIndicates that the file handle is stale.
      ETIMEIndicates an expired timer.
      ETIMEDOUTIndicates that the connection timed out.
      ETXTBSYIndicates that a text file is busy.
      EWOULDBLOCKIndicates that the operation would block.
      EXDEVIndicates an improper link. +
      +

      Windows-specific error constants#

      +

      The following error codes are specific to the Windows operating system.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      WSAEINTRIndicates an interrupted function call.
      WSAEBADFIndicates an invalid file handle.
      WSAEACCESIndicates insufficient permissions to complete the operation.
      WSAEFAULTIndicates an invalid pointer address.
      WSAEINVALIndicates that an invalid argument was passed.
      WSAEMFILEIndicates that there are too many open files.
      WSAEWOULDBLOCKIndicates that a resource is temporarily unavailable.
      WSAEINPROGRESSIndicates that an operation is currently in progress.
      WSAEALREADYIndicates that an operation is already in progress.
      WSAENOTSOCKIndicates that the resource is not a socket.
      WSAEDESTADDRREQIndicates that a destination address is required.
      WSAEMSGSIZEIndicates that the message size is too long.
      WSAEPROTOTYPEIndicates the wrong protocol type for the socket.
      WSAENOPROTOOPTIndicates a bad protocol option.
      WSAEPROTONOSUPPORTIndicates that the protocol is not supported.
      WSAESOCKTNOSUPPORTIndicates that the socket type is not supported.
      WSAEOPNOTSUPPIndicates that the operation is not supported.
      WSAEPFNOSUPPORTIndicates that the protocol family is not supported.
      WSAEAFNOSUPPORTIndicates that the address family is not supported.
      WSAEADDRINUSEIndicates that the network address is already in use.
      WSAEADDRNOTAVAILIndicates that the network address is not available.
      WSAENETDOWNIndicates that the network is down.
      WSAENETUNREACHIndicates that the network is unreachable.
      WSAENETRESETIndicates that the network connection has been reset.
      WSAECONNABORTEDIndicates that the connection has been aborted.
      WSAECONNRESETIndicates that the connection has been reset by the peer.
      WSAENOBUFSIndicates that there is no buffer space available.
      WSAEISCONNIndicates that the socket is already connected.
      WSAENOTCONNIndicates that the socket is not connected.
      WSAESHUTDOWNIndicates that data cannot be sent after the socket has been + shutdown.
      WSAETOOMANYREFSIndicates that there are too many references.
      WSAETIMEDOUTIndicates that the connection has timed out.
      WSAECONNREFUSEDIndicates that the connection has been refused.
      WSAELOOPIndicates that a name cannot be translated.
      WSAENAMETOOLONGIndicates that a name was too long.
      WSAEHOSTDOWNIndicates that a network host is down.
      WSAEHOSTUNREACHIndicates that there is no route to a network host.
      WSAENOTEMPTYIndicates that the directory is not empty.
      WSAEPROCLIMIndicates that there are too many processes.
      WSAEUSERSIndicates that the user quota has been exceeded.
      WSAEDQUOTIndicates that the disk quota has been exceeded.
      WSAESTALEIndicates a stale file handle reference.
      WSAEREMOTEIndicates that the item is remote.
      WSASYSNOTREADYIndicates that the network subsystem is not ready.
      WSAVERNOTSUPPORTEDIndicates that the winsock.dll version is out of + range.
      WSANOTINITIALISEDIndicates that successful WSAStartup has not yet been performed.
      WSAEDISCONIndicates that a graceful shutdown is in progress.
      WSAENOMOREIndicates that there are no more results.
      WSAECANCELLEDIndicates that an operation has been canceled.
      WSAEINVALIDPROCTABLEIndicates that the procedure call table is invalid.
      WSAEINVALIDPROVIDERIndicates an invalid service provider.
      WSAEPROVIDERFAILEDINITIndicates that the service provider failed to initialized.
      WSASYSCALLFAILUREIndicates a system call failure.
      WSASERVICE_NOT_FOUNDIndicates that a service was not found.
      WSATYPE_NOT_FOUNDIndicates that a class type was not found.
      WSA_E_NO_MOREIndicates that there are no more results.
      WSA_E_CANCELLEDIndicates that the call was canceled.
      WSAEREFUSEDIndicates that a database query was refused.
      +

      dlopen constants#

      +

      If available on the operating system, the following constants +are exported in os.constants.dlopen. See dlopen(3) for detailed +information.

      + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      RTLD_LAZYPerform lazy binding. Node.js sets this flag by default.
      RTLD_NOWResolve all undefined symbols in the library before dlopen(3) + returns.
      RTLD_GLOBALSymbols defined by the library will be made available for symbol + resolution of subsequently loaded libraries.
      RTLD_LOCALThe converse of RTLD_GLOBAL. This is the default behavior + if neither flag is specified.
      RTLD_DEEPBINDMake a self-contained library use its own symbols in preference to + symbols from previously loaded libraries.
      +

      Priority constants#

      + +

      The following process scheduling constants are exported by +os.constants.priority.

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      ConstantDescription
      PRIORITY_LOWThe lowest process scheduling priority. This corresponds to + IDLE_PRIORITY_CLASS on Windows, and a nice value of + 19 on all other platforms.
      PRIORITY_BELOW_NORMALThe process scheduling priority above PRIORITY_LOW and + below PRIORITY_NORMAL. This corresponds to + BELOW_NORMAL_PRIORITY_CLASS on Windows, and a nice value of + 10 on all other platforms.
      PRIORITY_NORMALThe default process scheduling priority. This corresponds to + NORMAL_PRIORITY_CLASS on Windows, and a nice value of + 0 on all other platforms.
      PRIORITY_ABOVE_NORMALThe process scheduling priority above PRIORITY_NORMAL and + below PRIORITY_HIGH. This corresponds to + ABOVE_NORMAL_PRIORITY_CLASS on Windows, and a nice value of + -7 on all other platforms.
      PRIORITY_HIGHThe process scheduling priority above PRIORITY_ABOVE_NORMAL + and below PRIORITY_HIGHEST. This corresponds to + HIGH_PRIORITY_CLASS on Windows, and a nice value of + -14 on all other platforms.
      PRIORITY_HIGHESTThe highest process scheduling priority. This corresponds to + REALTIME_PRIORITY_CLASS on Windows, and a nice value of + -20 on all other platforms.
      +

      libuv constants#

      + + + + + + + + + +
      ConstantDescription
      UV_UDP_REUSEADDR
      + +
      +
      +
      + + diff --git a/doc/api/os.json b/doc/api/os.json new file mode 100644 index 0000000000000000000000000000000000000000..a01b4b97be60a9f927bc9abea7d72597a1977da9 --- /dev/null +++ b/doc/api/os.json @@ -0,0 +1,559 @@ +{ + "type": "module", + "source": "doc/api/os.md", + "modules": [ + { + "textRaw": "OS", + "name": "os", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/os.js

      \n

      The os module provides operating system-related utility methods and\nproperties. It can be accessed using:

      \n
      const os = require('os');\n
      ", + "properties": [ + { + "textRaw": "`EOL` {string}", + "type": "string", + "name": "EOL", + "meta": { + "added": [ + "v0.7.8" + ], + "changes": [] + }, + "desc": "

      The operating system-specific end-of-line marker.

      \n
        \n
      • \\n on POSIX
      • \n
      • \\r\\n on Windows
      • \n
      " + }, + { + "textRaw": "`constants` {Object}", + "type": "Object", + "name": "constants", + "meta": { + "added": [ + "v6.3.0" + ], + "changes": [] + }, + "desc": "

      Contains commonly used operating system-specific constants for error codes,\nprocess signals, and so on. The specific constants defined are described in\nOS constants.

      " + } + ], + "methods": [ + { + "textRaw": "`os.arch()`", + "type": "method", + "name": "arch", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system CPU architecture for which the Node.js binary was\ncompiled. Possible values are 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

      \n

      The return value is equivalent to process.arch.

      " + }, + { + "textRaw": "`os.cpus()`", + "type": "method", + "name": "cpus", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object[]}", + "name": "return", + "type": "Object[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array of objects containing information about each logical CPU core.

      \n

      The properties included on each object include:

      \n
        \n
      • model <string>
      • \n
      • speed <number> (in MHz)
      • \n
      • times <Object>\n
          \n
        • user <number> The number of milliseconds the CPU has spent in user mode.
        • \n
        • nice <number> The number of milliseconds the CPU has spent in nice mode.
        • \n
        • sys <number> The number of milliseconds the CPU has spent in sys mode.
        • \n
        • idle <number> The number of milliseconds the CPU has spent in idle mode.
        • \n
        • irq <number> The number of milliseconds the CPU has spent in irq mode.
        • \n
        \n
      • \n
      \n\n
      [\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 252020,\n      nice: 0,\n      sys: 30340,\n      idle: 1070356870,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 306960,\n      nice: 0,\n      sys: 26980,\n      idle: 1071569080,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 248450,\n      nice: 0,\n      sys: 21750,\n      idle: 1070919370,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 256880,\n      nice: 0,\n      sys: 19430,\n      idle: 1070905480,\n      irq: 20\n    }\n  }\n]\n
      \n

      nice values are POSIX-only. On Windows, the nice values of all processors\nare always 0.

      " + }, + { + "textRaw": "`os.endianness()`", + "type": "method", + "name": "endianness", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a string identifying the endianness of the CPU for which the Node.js\nbinary was compiled.

      \n

      Possible values are 'BE' for big endian and 'LE' for little endian.

      " + }, + { + "textRaw": "`os.freemem()`", + "type": "method", + "name": "freemem", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the amount of free system memory in bytes as an integer.

      " + }, + { + "textRaw": "`os.getPriority([pid])`", + "type": "method", + "name": "getPriority", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [ + { + "textRaw": "`pid` {integer} The process ID to retrieve scheduling priority for. **Default** `0`.", + "name": "pid", + "type": "integer", + "desc": "The process ID to retrieve scheduling priority for. **Default** `0`." + } + ] + } + ], + "desc": "

      Returns the scheduling priority for the process specified by pid. If pid is\nnot provided or is 0, the priority of the current process is returned.

      " + }, + { + "textRaw": "`os.homedir()`", + "type": "method", + "name": "homedir", + "meta": { + "added": [ + "v2.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the string path of the current user's home directory.

      \n

      On POSIX, it uses the $HOME environment variable if defined. Otherwise it\nuses the effective UID to look up the user's home directory.

      \n

      On Windows, it uses the USERPROFILE environment variable if defined.\nOtherwise it uses the path to the profile directory of the current user.

      " + }, + { + "textRaw": "`os.hostname()`", + "type": "method", + "name": "hostname", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the host name of the operating system as a string.

      " + }, + { + "textRaw": "`os.loadavg()`", + "type": "method", + "name": "loadavg", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number[]}", + "name": "return", + "type": "number[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array containing the 1, 5, and 15 minute load averages.

      \n

      The load average is a measure of system activity calculated by the operating\nsystem and expressed as a fractional number.

      \n

      The load average is a Unix-specific concept. On Windows, the return value is\nalways [0, 0, 0].

      " + }, + { + "textRaw": "`os.networkInterfaces()`", + "type": "method", + "name": "networkInterfaces", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object containing network interfaces that have been assigned a\nnetwork address.

      \n

      Each key on the returned object identifies a network interface. The associated\nvalue is an array of objects that each describe an assigned network address.

      \n

      The properties available on the assigned network address object include:

      \n
        \n
      • address <string> The assigned IPv4 or IPv6 address
      • \n
      • netmask <string> The IPv4 or IPv6 network mask
      • \n
      • family <string> Either IPv4 or IPv6
      • \n
      • mac <string> The MAC address of the network interface
      • \n
      • internal <boolean> true if the network interface is a loopback or\nsimilar interface that is not remotely accessible; otherwise false
      • \n
      • scopeid <number> The numeric IPv6 scope ID (only specified when family\nis IPv6)
      • \n
      • cidr <string> The assigned IPv4 or IPv6 address with the routing prefix\nin CIDR notation. If the netmask is invalid, this property is set\nto null.
      • \n
      \n\n
      {\n  lo: [\n    {\n      address: '127.0.0.1',\n      netmask: '255.0.0.0',\n      family: 'IPv4',\n      mac: '00:00:00:00:00:00',\n      internal: true,\n      cidr: '127.0.0.1/8'\n    },\n    {\n      address: '::1',\n      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',\n      family: 'IPv6',\n      mac: '00:00:00:00:00:00',\n      scopeid: 0,\n      internal: true,\n      cidr: '::1/128'\n    }\n  ],\n  eth0: [\n    {\n      address: '192.168.1.108',\n      netmask: '255.255.255.0',\n      family: 'IPv4',\n      mac: '01:02:03:0a:0b:0c',\n      internal: false,\n      cidr: '192.168.1.108/24'\n    },\n    {\n      address: 'fe80::a00:27ff:fe4e:66a1',\n      netmask: 'ffff:ffff:ffff:ffff::',\n      family: 'IPv6',\n      mac: '01:02:03:0a:0b:0c',\n      scopeid: 1,\n      internal: false,\n      cidr: 'fe80::a00:27ff:fe4e:66a1/64'\n    }\n  ]\n}\n
      " + }, + { + "textRaw": "`os.platform()`", + "type": "method", + "name": "platform", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a string identifying the operating system platform. The value is set\nat compile time. Possible values are 'aix', 'darwin', 'freebsd',\n'linux', 'openbsd', 'sunos', and 'win32'.

      \n

      The return value is equivalent to process.platform.

      \n

      The value 'android' may also be returned if Node.js is built on the Android\noperating system. Android support is experimental.

      " + }, + { + "textRaw": "`os.release()`", + "type": "method", + "name": "release", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system as a string.

      \n

      On POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, GetVersionExW() is used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.

      " + }, + { + "textRaw": "`os.setPriority([pid, ]priority)`", + "type": "method", + "name": "setPriority", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`pid` {integer} The process ID to set scheduling priority for. **Default** `0`.", + "name": "pid", + "type": "integer", + "desc": "The process ID to set scheduling priority for. **Default** `0`." + }, + { + "textRaw": "`priority` {integer} The scheduling priority to assign to the process.", + "name": "priority", + "type": "integer", + "desc": "The scheduling priority to assign to the process." + } + ] + } + ], + "desc": "

      Attempts to set the scheduling priority for the process specified by pid. If\npid is not provided or is 0, the process ID of the current process is used.

      \n

      The priority input must be an integer between -20 (high priority) and 19\n(low priority). Due to differences between Unix priority levels and Windows\npriority classes, priority is mapped to one of six priority constants in\nos.constants.priority. When retrieving a process priority level, this range\nmapping may cause the return value to be slightly different on Windows. To avoid\nconfusion, set priority to one of the priority constants.

      \n

      On Windows, setting priority to PRIORITY_HIGHEST requires elevated user\nprivileges. Otherwise the set priority will be silently reduced to\nPRIORITY_HIGH.

      " + }, + { + "textRaw": "`os.tmpdir()`", + "type": "method", + "name": "tmpdir", + "meta": { + "added": [ + "v0.9.9" + ], + "changes": [ + { + "version": "v2.0.0", + "pr-url": "https://github.com/nodejs/node/pull/747", + "description": "This function is now cross-platform consistent and no longer returns a path with a trailing slash on any platform" + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system's default directory for temporary files as a\nstring.

      " + }, + { + "textRaw": "`os.totalmem()`", + "type": "method", + "name": "totalmem", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the total amount of system memory in bytes as an integer.

      " + }, + { + "textRaw": "`os.type()`", + "type": "method", + "name": "type", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the operating system name as returned by uname(3). For example, it\nreturns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows.

      \n

      See https://en.wikipedia.org/wiki/Uname#Examples for additional information\nabout the output of running uname(3) on various operating systems.

      " + }, + { + "textRaw": "`os.uptime()`", + "type": "method", + "name": "uptime", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/20129", + "description": "The result of this function no longer contains a fraction component on Windows." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns the system uptime in number of seconds.

      " + }, + { + "textRaw": "`os.userInfo([options])`", + "type": "method", + "name": "userInfo", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`encoding` {string} Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances." + } + ] + } + ] + } + ], + "desc": "

      Returns information about the currently effective user. On POSIX platforms,\nthis is typically a subset of the password file. The returned object includes\nthe username, uid, gid, shell, and homedir. On Windows, the uid and\ngid fields are -1, and shell is null.

      \n

      The value of homedir returned by os.userInfo() is provided by the operating\nsystem. This differs from the result of os.homedir(), which queries\nenvironment variables for the home directory before falling back to the\noperating system response.

      \n

      Throws a SystemError if a user has no username or homedir.

      " + }, + { + "textRaw": "`os.version()`", + "type": "method", + "name": "version", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a string identifying the kernel version.

      \n

      On POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, RtlGetVersion() is used, and if it is not\navailable, GetVersionExW() will be used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.

      " + } + ], + "modules": [ + { + "textRaw": "OS constants", + "name": "os_constants", + "desc": "

      The following constants are exported by os.constants.

      \n

      Not all constants will be available on every operating system.

      ", + "modules": [ + { + "textRaw": "Signal constants", + "name": "signal_constants", + "meta": { + "changes": [ + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/6093", + "description": "Added support for `SIGINFO`." + } + ] + }, + "desc": "

      The following signal constants are exported by os.constants.signals.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      SIGHUPSent to indicate when a controlling terminal is closed or a parent\n process exits.
      SIGINTSent to indicate when a user wishes to interrupt a process\n ((Ctrl+C)).
      SIGQUITSent to indicate when a user wishes to terminate a process and perform a\n core dump.
      SIGILLSent to a process to notify that it has attempted to perform an illegal,\n malformed, unknown, or privileged instruction.
      SIGTRAPSent to a process when an exception has occurred.
      SIGABRTSent to a process to request that it abort.
      SIGIOTSynonym for SIGABRT
      SIGBUSSent to a process to notify that it has caused a bus error.
      SIGFPESent to a process to notify that it has performed an illegal arithmetic\n operation.
      SIGKILLSent to a process to terminate it immediately.
      SIGUSR1 SIGUSR2Sent to a process to identify user-defined conditions.
      SIGSEGVSent to a process to notify of a segmentation fault.
      SIGPIPESent to a process when it has attempted to write to a disconnected\n pipe.
      SIGALRMSent to a process when a system timer elapses.
      SIGTERMSent to a process to request termination.
      SIGCHLDSent to a process when a child process terminates.
      SIGSTKFLTSent to a process to indicate a stack fault on a coprocessor.
      SIGCONTSent to instruct the operating system to continue a paused process.
      SIGSTOPSent to instruct the operating system to halt a process.
      SIGTSTPSent to a process to request it to stop.
      SIGBREAKSent to indicate when a user wishes to interrupt a process.
      SIGTTINSent to a process when it reads from the TTY while in the\n background.
      SIGTTOUSent to a process when it writes to the TTY while in the\n background.
      SIGURGSent to a process when a socket has urgent data to read.
      SIGXCPUSent to a process when it has exceeded its limit on CPU usage.
      SIGXFSZSent to a process when it grows a file larger than the maximum\n allowed.
      SIGVTALRMSent to a process when a virtual timer has elapsed.
      SIGPROFSent to a process when a system timer has elapsed.
      SIGWINCHSent to a process when the controlling terminal has changed its\n size.
      SIGIOSent to a process when I/O is available.
      SIGPOLLSynonym for SIGIO
      SIGLOSTSent to a process when a file lock has been lost.
      SIGPWRSent to a process to notify of a power failure.
      SIGINFOSynonym for SIGPWR
      SIGSYSSent to a process to notify of a bad argument.
      SIGUNUSEDSynonym for SIGSYS
      ", + "type": "module", + "displayName": "Signal constants" + }, + { + "textRaw": "Error constants", + "name": "error_constants", + "desc": "

      The following error constants are exported by os.constants.errno.

      ", + "modules": [ + { + "textRaw": "POSIX error constants", + "name": "posix_error_constants", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      E2BIGIndicates that the list of arguments is longer than expected.
      EACCESIndicates that the operation did not have sufficient permissions.
      EADDRINUSEIndicates that the network address is already in use.
      EADDRNOTAVAILIndicates that the network address is currently unavailable for\n use.
      EAFNOSUPPORTIndicates that the network address family is not supported.
      EAGAINIndicates that there is no data available and to try the\n operation again later.
      EALREADYIndicates that the socket already has a pending connection in\n progress.
      EBADFIndicates that a file descriptor is not valid.
      EBADMSGIndicates an invalid data message.
      EBUSYIndicates that a device or resource is busy.
      ECANCELEDIndicates that an operation was canceled.
      ECHILDIndicates that there are no child processes.
      ECONNABORTEDIndicates that the network connection has been aborted.
      ECONNREFUSEDIndicates that the network connection has been refused.
      ECONNRESETIndicates that the network connection has been reset.
      EDEADLKIndicates that a resource deadlock has been avoided.
      EDESTADDRREQIndicates that a destination address is required.
      EDOMIndicates that an argument is out of the domain of the function.
      EDQUOTIndicates that the disk quota has been exceeded.
      EEXISTIndicates that the file already exists.
      EFAULTIndicates an invalid pointer address.
      EFBIGIndicates that the file is too large.
      EHOSTUNREACHIndicates that the host is unreachable.
      EIDRMIndicates that the identifier has been removed.
      EILSEQIndicates an illegal byte sequence.
      EINPROGRESSIndicates that an operation is already in progress.
      EINTRIndicates that a function call was interrupted.
      EINVALIndicates that an invalid argument was provided.
      EIOIndicates an otherwise unspecified I/O error.
      EISCONNIndicates that the socket is connected.
      EISDIRIndicates that the path is a directory.
      ELOOPIndicates too many levels of symbolic links in a path.
      EMFILEIndicates that there are too many open files.
      EMLINKIndicates that there are too many hard links to a file.
      EMSGSIZEIndicates that the provided message is too long.
      EMULTIHOPIndicates that a multihop was attempted.
      ENAMETOOLONGIndicates that the filename is too long.
      ENETDOWNIndicates that the network is down.
      ENETRESETIndicates that the connection has been aborted by the network.
      ENETUNREACHIndicates that the network is unreachable.
      ENFILEIndicates too many open files in the system.
      ENOBUFSIndicates that no buffer space is available.
      ENODATAIndicates that no message is available on the stream head read\n queue.
      ENODEVIndicates that there is no such device.
      ENOENTIndicates that there is no such file or directory.
      ENOEXECIndicates an exec format error.
      ENOLCKIndicates that there are no locks available.
      ENOLINKIndications that a link has been severed.
      ENOMEMIndicates that there is not enough space.
      ENOMSGIndicates that there is no message of the desired type.
      ENOPROTOOPTIndicates that a given protocol is not available.
      ENOSPCIndicates that there is no space available on the device.
      ENOSRIndicates that there are no stream resources available.
      ENOSTRIndicates that a given resource is not a stream.
      ENOSYSIndicates that a function has not been implemented.
      ENOTCONNIndicates that the socket is not connected.
      ENOTDIRIndicates that the path is not a directory.
      ENOTEMPTYIndicates that the directory is not empty.
      ENOTSOCKIndicates that the given item is not a socket.
      ENOTSUPIndicates that a given operation is not supported.
      ENOTTYIndicates an inappropriate I/O control operation.
      ENXIOIndicates no such device or address.
      EOPNOTSUPPIndicates that an operation is not supported on the socket. Although\n ENOTSUP and EOPNOTSUPP have the same value\n on Linux, according to POSIX.1 these error values should be distinct.)
      EOVERFLOWIndicates that a value is too large to be stored in a given data\n type.
      EPERMIndicates that the operation is not permitted.
      EPIPEIndicates a broken pipe.
      EPROTOIndicates a protocol error.
      EPROTONOSUPPORTIndicates that a protocol is not supported.
      EPROTOTYPEIndicates the wrong type of protocol for a socket.
      ERANGEIndicates that the results are too large.
      EROFSIndicates that the file system is read only.
      ESPIPEIndicates an invalid seek operation.
      ESRCHIndicates that there is no such process.
      ESTALEIndicates that the file handle is stale.
      ETIMEIndicates an expired timer.
      ETIMEDOUTIndicates that the connection timed out.
      ETXTBSYIndicates that a text file is busy.
      EWOULDBLOCKIndicates that the operation would block.
      EXDEVIndicates an improper link.\n
      ", + "type": "module", + "displayName": "POSIX error constants" + }, + { + "textRaw": "Windows-specific error constants", + "name": "windows-specific_error_constants", + "desc": "

      The following error codes are specific to the Windows operating system.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      WSAEINTRIndicates an interrupted function call.
      WSAEBADFIndicates an invalid file handle.
      WSAEACCESIndicates insufficient permissions to complete the operation.
      WSAEFAULTIndicates an invalid pointer address.
      WSAEINVALIndicates that an invalid argument was passed.
      WSAEMFILEIndicates that there are too many open files.
      WSAEWOULDBLOCKIndicates that a resource is temporarily unavailable.
      WSAEINPROGRESSIndicates that an operation is currently in progress.
      WSAEALREADYIndicates that an operation is already in progress.
      WSAENOTSOCKIndicates that the resource is not a socket.
      WSAEDESTADDRREQIndicates that a destination address is required.
      WSAEMSGSIZEIndicates that the message size is too long.
      WSAEPROTOTYPEIndicates the wrong protocol type for the socket.
      WSAENOPROTOOPTIndicates a bad protocol option.
      WSAEPROTONOSUPPORTIndicates that the protocol is not supported.
      WSAESOCKTNOSUPPORTIndicates that the socket type is not supported.
      WSAEOPNOTSUPPIndicates that the operation is not supported.
      WSAEPFNOSUPPORTIndicates that the protocol family is not supported.
      WSAEAFNOSUPPORTIndicates that the address family is not supported.
      WSAEADDRINUSEIndicates that the network address is already in use.
      WSAEADDRNOTAVAILIndicates that the network address is not available.
      WSAENETDOWNIndicates that the network is down.
      WSAENETUNREACHIndicates that the network is unreachable.
      WSAENETRESETIndicates that the network connection has been reset.
      WSAECONNABORTEDIndicates that the connection has been aborted.
      WSAECONNRESETIndicates that the connection has been reset by the peer.
      WSAENOBUFSIndicates that there is no buffer space available.
      WSAEISCONNIndicates that the socket is already connected.
      WSAENOTCONNIndicates that the socket is not connected.
      WSAESHUTDOWNIndicates that data cannot be sent after the socket has been\n shutdown.
      WSAETOOMANYREFSIndicates that there are too many references.
      WSAETIMEDOUTIndicates that the connection has timed out.
      WSAECONNREFUSEDIndicates that the connection has been refused.
      WSAELOOPIndicates that a name cannot be translated.
      WSAENAMETOOLONGIndicates that a name was too long.
      WSAEHOSTDOWNIndicates that a network host is down.
      WSAEHOSTUNREACHIndicates that there is no route to a network host.
      WSAENOTEMPTYIndicates that the directory is not empty.
      WSAEPROCLIMIndicates that there are too many processes.
      WSAEUSERSIndicates that the user quota has been exceeded.
      WSAEDQUOTIndicates that the disk quota has been exceeded.
      WSAESTALEIndicates a stale file handle reference.
      WSAEREMOTEIndicates that the item is remote.
      WSASYSNOTREADYIndicates that the network subsystem is not ready.
      WSAVERNOTSUPPORTEDIndicates that the winsock.dll version is out of\n range.
      WSANOTINITIALISEDIndicates that successful WSAStartup has not yet been performed.
      WSAEDISCONIndicates that a graceful shutdown is in progress.
      WSAENOMOREIndicates that there are no more results.
      WSAECANCELLEDIndicates that an operation has been canceled.
      WSAEINVALIDPROCTABLEIndicates that the procedure call table is invalid.
      WSAEINVALIDPROVIDERIndicates an invalid service provider.
      WSAEPROVIDERFAILEDINITIndicates that the service provider failed to initialized.
      WSASYSCALLFAILUREIndicates a system call failure.
      WSASERVICE_NOT_FOUNDIndicates that a service was not found.
      WSATYPE_NOT_FOUNDIndicates that a class type was not found.
      WSA_E_NO_MOREIndicates that there are no more results.
      WSA_E_CANCELLEDIndicates that the call was canceled.
      WSAEREFUSEDIndicates that a database query was refused.
      ", + "type": "module", + "displayName": "Windows-specific error constants" + } + ], + "type": "module", + "displayName": "Error constants" + }, + { + "textRaw": "dlopen constants", + "name": "dlopen_constants", + "desc": "

      If available on the operating system, the following constants\nare exported in os.constants.dlopen. See dlopen(3) for detailed\ninformation.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      RTLD_LAZYPerform lazy binding. Node.js sets this flag by default.
      RTLD_NOWResolve all undefined symbols in the library before dlopen(3)\n returns.
      RTLD_GLOBALSymbols defined by the library will be made available for symbol\n resolution of subsequently loaded libraries.
      RTLD_LOCALThe converse of RTLD_GLOBAL. This is the default behavior\n if neither flag is specified.
      RTLD_DEEPBINDMake a self-contained library use its own symbols in preference to\n symbols from previously loaded libraries.
      ", + "type": "module", + "displayName": "dlopen constants" + }, + { + "textRaw": "Priority constants", + "name": "priority_constants", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      The following process scheduling constants are exported by\nos.constants.priority.

      \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      ConstantDescription
      PRIORITY_LOWThe lowest process scheduling priority. This corresponds to\n IDLE_PRIORITY_CLASS on Windows, and a nice value of\n 19 on all other platforms.
      PRIORITY_BELOW_NORMALThe process scheduling priority above PRIORITY_LOW and\n below PRIORITY_NORMAL. This corresponds to\n BELOW_NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n 10 on all other platforms.
      PRIORITY_NORMALThe default process scheduling priority. This corresponds to\n NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n 0 on all other platforms.
      PRIORITY_ABOVE_NORMALThe process scheduling priority above PRIORITY_NORMAL and\n below PRIORITY_HIGH. This corresponds to\n ABOVE_NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n -7 on all other platforms.
      PRIORITY_HIGHThe process scheduling priority above PRIORITY_ABOVE_NORMAL\n and below PRIORITY_HIGHEST. This corresponds to\n HIGH_PRIORITY_CLASS on Windows, and a nice value of\n -14 on all other platforms.
      PRIORITY_HIGHESTThe highest process scheduling priority. This corresponds to\n REALTIME_PRIORITY_CLASS on Windows, and a nice value of\n -20 on all other platforms.
      ", + "type": "module", + "displayName": "Priority constants" + }, + { + "textRaw": "libuv constants", + "name": "libuv_constants", + "desc": "\n \n \n \n \n \n \n \n \n
      ConstantDescription
      UV_UDP_REUSEADDR
      ", + "type": "module", + "displayName": "libuv constants" + } + ], + "type": "module", + "displayName": "OS constants" + } + ], + "type": "module", + "displayName": "OS" + } + ] +} \ No newline at end of file diff --git a/doc/api/packages.html b/doc/api/packages.html new file mode 100644 index 0000000000000000000000000000000000000000..c44228be6ee74d00525bda5314f0abd68a37754b --- /dev/null +++ b/doc/api/packages.html @@ -0,0 +1,949 @@ + + + + + + + Modules: Packages | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Modules: Packages#

      + + +

      Introduction#

      +

      A package is a folder tree described by a package.json file. The package +consists of the folder containing the package.json file and all subfolders +until the next folder containing another package.json file, or a folder +named node_modules.

      +

      This page provides guidance for package authors writing package.json files +along with a reference for the package.json fields defined by Node.js.

      +

      Determining module system#

      +

      Node.js will treat the following as ES modules when passed to node as the +initial input, or when referenced by import statements within ES module code:

      +
        +
      • +

        Files ending in .mjs.

        +
      • +
      • +

        Files ending in .js when the nearest parent package.json file contains a +top-level "type" field with a value of "module".

        +
      • +
      • +

        Strings passed in as an argument to --eval, or piped to node via STDIN, +with the flag --input-type=module.

        +
      • +
      +

      Node.js will treat as CommonJS all other forms of input, such as .js files +where the nearest parent package.json file contains no top-level "type" +field, or string input without the flag --input-type. This behavior is to +preserve backward compatibility. However, now that Node.js supports both +CommonJS and ES modules, it is best to be explicit whenever possible. Node.js +will treat the following as CommonJS when passed to node as the initial input, +or when referenced by import statements within ES module code:

      +
        +
      • +

        Files ending in .cjs.

        +
      • +
      • +

        Files ending in .js when the nearest parent package.json file contains a +top-level field "type" with a value of "commonjs".

        +
      • +
      • +

        Strings passed in as an argument to --eval or --print, or piped to node +via STDIN, with the flag --input-type=commonjs.

        +
      • +
      +

      Package authors should include the "type" field, even in packages where +all sources are CommonJS. Being explicit about the type of the package will +future-proof the package in case the default type of Node.js ever changes, and +it will also make things easier for build tools and loaders to determine how the +files in the package should be interpreted.

      +

      package.json and file extensions#

      +

      Within a package, the package.json "type" field defines how +Node.js should interpret .js files. If a package.json file does not have a +"type" field, .js files are treated as CommonJS.

      +

      A package.json "type" value of "module" tells Node.js to interpret .js +files within that package as using ES module syntax.

      +

      The "type" field applies not only to initial entry points (node my-app.js) +but also to files referenced by import statements and import() expressions.

      +
      // my-app.js, treated as an ES module because there is a package.json
      +// file in the same folder with "type": "module".
      +
      +import './startup/init.js';
      +// Loaded as ES module since ./startup contains no package.json file,
      +// and therefore inherits the "type" value from one level up.
      +
      +import 'commonjs-package';
      +// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
      +// lacks a "type" field or contains "type": "commonjs".
      +
      +import './node_modules/commonjs-package/index.js';
      +// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
      +// lacks a "type" field or contains "type": "commonjs".
      +

      Files ending with .mjs are always loaded as ES modules regardless of +the nearest parent package.json.

      +

      Files ending with .cjs are always loaded as CommonJS regardless of the +nearest parent package.json.

      +
      import './legacy-file.cjs';
      +// Loaded as CommonJS since .cjs is always loaded as CommonJS.
      +
      +import 'commonjs-package/src/index.mjs';
      +// Loaded as ES module since .mjs is always loaded as ES module.
      +

      The .mjs and .cjs extensions can be used to mix types within the same +package:

      +
        +
      • +

        Within a "type": "module" package, Node.js can be instructed to +interpret a particular file as CommonJS by naming it with a .cjs +extension (since both .js and .mjs files are treated as ES modules within +a "module" package).

        +
      • +
      • +

        Within a "type": "commonjs" package, Node.js can be instructed to +interpret a particular file as an ES module by naming it with an .mjs +extension (since both .js and .cjs files are treated as CommonJS within a +"commonjs" package).

        +
      • +
      +

      --input-type flag#

      +

      Strings passed in as an argument to --eval (or -e), or piped to node via +STDIN, are treated as ES modules when the --input-type=module flag +is set.

      +
      node --input-type=module --eval "import { sep } from 'path'; console.log(sep);"
      +
      +echo "import { sep } from 'path'; console.log(sep);" | node --input-type=module
      +

      For completeness there is also --input-type=commonjs, for explicitly running +string input as CommonJS. This is the default behavior if --input-type is +unspecified.

      +

      Package entry points#

      +

      In a package’s package.json file, two fields can define entry points for a +package: "main" and "exports". The "main" field is supported +in all versions of Node.js, but its capabilities are limited: it only defines +the main entry point of the package.

      +

      The "exports" field provides an alternative to "main" where the +package main entry point can be defined while also encapsulating the package, +preventing any other entry points besides those defined in "exports". +This encapsulation allows module authors to define a public interface for +their package.

      +

      If both "exports" and "main" are defined, the "exports" field +takes precedence over "main". "exports" are not specific to ES +modules or CommonJS; "main" is overridden by "exports" if it +exists. As such "main" cannot be used as a fallback for CommonJS but it +can be used as a fallback for legacy versions of Node.js that do not support the +"exports" field.

      +

      Conditional exports can be used within "exports" to define different +package entry points per environment, including whether the package is +referenced via require or via import. For more information about supporting +both CommonJS and ES Modules in a single package please consult +the dual CommonJS/ES module packages section.

      +

      Warning: Introducing the "exports" field prevents consumers of a +package from using any entry points that are not defined, including the +package.json (e.g. require('your-package/package.json'). This will +likely be a breaking change.

      +

      To make the introduction of "exports" non-breaking, ensure that every +previously supported entry point is exported. It is best to explicitly specify +entry points so that the package’s public API is well-defined. For example, +a project that previous exported main, lib, +feature, and the package.json could use the following package.exports:

      +
      {
      +  "name": "my-mod",
      +  "exports": {
      +    ".": "./lib/index.js",
      +    "./lib": "./lib/index.js",
      +    "./lib/index": "./lib/index.js",
      +    "./lib/index.js": "./lib/index.js",
      +    "./feature": "./feature/index.js",
      +    "./feature/index.js": "./feature/index.js",
      +    "./package.json": "./package.json"
      +  }
      +}
      +

      Alternatively a project could choose to export entire folders:

      +
      {
      +  "name": "my-mod",
      +  "exports": {
      +    ".": "./lib/index.js",
      +    "./lib": "./lib/index.js",
      +    "./lib/*": "./lib/*.js",
      +    "./feature": "./feature/index.js",
      +    "./feature/*": "./feature/*.js",
      +    "./package.json": "./package.json"
      +  }
      +}
      +

      As a last resort, package encapsulation can be disabled entirely by creating an +export for the root of the package "./*": "./*". This exposes every file +in the package at the cost of disabling the encapsulation and potential tooling +benefits this provides. As the ES Module loader in Node.js enforces the use of +the full specifier path, exporting the root rather than being explicit +about entry is less expressive than either of the prior examples. Not only +is encapsulation lost but module consumers are unable to +import feature from 'my-mod/feature' as they need to provide the full +path import feature from 'my-mod/feature/index.js.

      +

      Main entry point export#

      +

      To set the main entry point for a package, it is advisable to define both +"exports" and "main" in the package’s package.json file:

      +
      {
      +  "main": "./main.js",
      +  "exports": "./main.js"
      +}
      +

      When the "exports" field is defined, all subpaths of the package are +encapsulated and no longer available to importers. For example, +require('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED +error.

      +

      This encapsulation of exports provides more reliable guarantees +about package interfaces for tools and when handling semver upgrades for a +package. It is not a strong encapsulation since a direct require of any +absolute subpath of the package such as +require('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.

      +

      Subpath exports#

      +

      Stability: 1 - Experimental

      +

      When using the "exports" field, custom subpaths can be defined along +with the main entry point by treating the main entry point as the +"." subpath:

      +
      {
      +  "main": "./main.js",
      +  "exports": {
      +    ".": "./main.js",
      +    "./submodule": "./src/submodule.js"
      +  }
      +}
      +

      Now only the defined subpath in "exports" can be imported by a consumer:

      +
      import submodule from 'es-module-package/submodule';
      +// Loads ./node_modules/es-module-package/src/submodule.js
      +

      While other subpaths will error:

      +
      import submodule from 'es-module-package/private-module.js';
      +// Throws ERR_PACKAGE_PATH_NOT_EXPORTED
      +

      Subpath imports#

      +

      Stability: 1 - Experimental

      +

      In addition to the "exports" field, it is possible to define internal +package import maps that only apply to import specifiers from within the package +itself.

      +

      Entries in the imports field must always start with # to ensure they are +disambiguated from package specifiers.

      +

      For example, the imports field can be used to gain the benefits of conditional +exports for internal modules:

      +
      // package.json
      +{
      +  "imports": {
      +    "#dep": {
      +      "node": "dep-node-native",
      +      "default": "./dep-polyfill.js"
      +    }
      +  },
      +  "dependencies": {
      +    "dep-node-native": "^1.0.0"
      +  }
      +}
      +

      where import '#dep' does not get the resolution of the external package +dep-node-native (including its exports in turn), and instead gets the local +file ./dep-polyfill.js relative to the package in other environments.

      +

      Unlike the "exports" field, the "imports" field permits mapping to external +packages.

      +

      The resolution rules for the imports field are otherwise +analogous to the exports field.

      +

      Subpath patterns#

      +

      Stability: 1 - Experimental

      +

      For packages with a small number of exports or imports, we recommend +explicitly listing each exports subpath entry. But for packages that have +large numbers of subpaths, this might cause package.json bloat and +maintenance issues.

      +

      For these use cases, subpath export patterns can be used instead:

      +
      // ./node_modules/es-module-package/package.json
      +{
      +  "exports": {
      +    "./features/*": "./src/features/*.js"
      +  },
      +  "imports": {
      +    "#internal/*": "./src/internal/*.js"
      +  }
      +}
      +

      The left hand matching pattern must always end in *. All instances of * on +the right hand side will then be replaced with this value, including if it +contains any / separators.

      +
      import featureX from 'es-module-package/features/x';
      +// Loads ./node_modules/es-module-package/src/features/x.js
      +
      +import featureY from 'es-module-package/features/y/y';
      +// Loads ./node_modules/es-module-package/src/features/y/y.js
      +
      +import internalZ from '#internal/z';
      +// Loads ./node_modules/es-module-package/src/internal/z.js
      +

      This is a direct static replacement without any special handling for file +extensions. In the previous example, pkg/features/x.json would be resolved to +./src/features/x.json.js in the mapping.

      +

      The property of exports being statically enumerable is maintained with exports +patterns since the individual exports for a package can be determined by +treating the right hand side target pattern as a ** glob against the list of +files within the package. Because node_modules paths are forbidden in exports +targets, this expansion is dependent on only the files of the package itself.

      +

      Exports sugar#

      +

      Stability: 1 - Experimental

      +

      If the "." export is the only export, the "exports" field provides sugar +for this case being the direct "exports" field value.

      +

      If the "." export has a fallback array or string value, then the +"exports" field can be set to this value directly.

      +
      {
      +  "exports": {
      +    ".": "./main.js"
      +  }
      +}
      +

      can be written:

      +
      {
      +  "exports": "./main.js"
      +}
      +

      Conditional exports#

      +

      Stability: 1 - Experimental

      +

      Conditional exports provide a way to map to different paths depending on +certain conditions. They are supported for both CommonJS and ES module imports.

      +

      For example, a package that wants to provide different ES module exports for +require() and import can be written:

      +
      // package.json
      +{
      +  "main": "./main-require.cjs",
      +  "exports": {
      +    "import": "./main-module.js",
      +    "require": "./main-require.cjs"
      +  },
      +  "type": "module"
      +}
      +

      Node.js supports the following conditions out of the box:

      +
        +
      • "import" - matches when the package is loaded via import or +import(), or via any top-level import or resolve operation by the +ECMAScript module loader. Applies regardless of the module format of the +target file. Always mutually exclusive with "require".
      • +
      • "require" - matches when the package is loaded via require(). The +referenced file should be loadable with require() although the condition +matches regardless of the module format of the target file. Expected +formats include CommonJS, JSON, and native addons but not ES modules as +require() doesn't support them. Always mutually exclusive with +"import".
      • +
      • "node" - matches for any Node.js environment. Can be a CommonJS or ES +module file. This condition should always come after "import" or +"require".
      • +
      • "default" - the generic fallback that always matches. Can be a CommonJS +or ES module file. This condition should always come last.
      • +
      +

      Within the "exports" object, key order is significant. During condition +matching, earlier entries have higher priority and take precedence over later +entries. The general rule is that conditions should be from most specific to +least specific in object order.

      +

      Other conditions such as "browser", "electron", "deno", "react-native", +etc., are unknown to Node.js, and thus ignored. Runtimes or tools other than +Node.js can use them at their discretion. Further restrictions, definitions, or +guidance on condition names might occur in the future.

      +

      Using the "import" and "require" conditions can lead to some hazards, +which are further explained in the dual CommonJS/ES module packages section.

      +

      Conditional exports can also be extended to exports subpaths, for example:

      +
      {
      +  "main": "./main.js",
      +  "exports": {
      +    ".": "./main.js",
      +    "./feature": {
      +      "node": "./feature-node.js",
      +      "default": "./feature.js"
      +    }
      +  }
      +}
      +

      Defines a package where require('pkg/feature') and import 'pkg/feature' +could provide different implementations between Node.js and other JS +environments.

      +

      When using environment branches, always include a "default" condition where +possible. Providing a "default" condition ensures that any unknown JS +environments are able to use this universal implementation, which helps avoid +these JS environments from having to pretend to be existing environments in +order to support packages with conditional exports. For this reason, using +"node" and "default" condition branches is usually preferable to using +"node" and "browser" condition branches.

      +

      Nested conditions#

      +

      Stability: 1 - Experimental

      +

      In addition to direct mappings, Node.js also supports nested condition objects.

      +

      For example, to define a package that only has dual mode entry points for +use in Node.js but not the browser:

      +
      {
      +  "main": "./main.js",
      +  "exports": {
      +    "node": {
      +      "import": "./feature-node.mjs",
      +      "require": "./feature-node.cjs"
      +    },
      +    "default": "./feature.mjs",
      +  }
      +}
      +

      Conditions continue to be matched in order as with flat conditions. If +a nested conditional does not have any mapping it will continue checking +the remaining conditions of the parent condition. In this way nested +conditions behave analogously to nested JavaScript if statements.

      +

      Resolving user conditions#

      +

      When running Node.js, custom user conditions can be added with the +--conditions flag:

      +
      node --conditions=development main.js
      +

      which would then resolve the "development" condition in package imports and +exports, while resolving the existing "node", "default", "import", and +"require" conditions as appropriate.

      +

      Any number of custom conditions can be set with repeat flags.

      +

      Self-referencing a package using its name#

      +

      Within a package, the values defined in the package’s +package.json "exports" field can be referenced via the package’s name. +For example, assuming the package.json is:

      +
      // package.json
      +{
      +  "name": "a-package",
      +  "exports": {
      +    ".": "./main.mjs",
      +    "./foo": "./foo.js"
      +  }
      +}
      +

      Then any module in that package can reference an export in the package itself:

      +
      // ./a-module.mjs
      +import { something } from 'a-package'; // Imports "something" from ./main.mjs.
      +

      Self-referencing is available only if package.json has "exports", and +will allow importing only what that "exports" (in the package.json) +allows. So the code below, given the previous package, will generate a runtime +error:

      +
      // ./another-module.mjs
      +
      +// Imports "another" from ./m.mjs. Fails because
      +// the "package.json" "exports" field
      +// does not provide an export named "./m.mjs".
      +import { another } from 'a-package/m.mjs';
      +

      Self-referencing is also available when using require, both in an ES module, +and in a CommonJS one. For example, this code will also work:

      +
      // ./a-module.js
      +const { something } = require('a-package/foo'); // Loads from ./foo.js.
      +

      Dual CommonJS/ES module packages#

      +

      Prior to the introduction of support for ES modules in Node.js, it was a common +pattern for package authors to include both CommonJS and ES module JavaScript +sources in their package, with package.json "main" specifying the +CommonJS entry point and package.json "module" specifying the ES module +entry point. +This enabled Node.js to run the CommonJS entry point while build tools such as +bundlers used the ES module entry point, since Node.js ignored (and still +ignores) the top-level "module" field.

      +

      Node.js can now run ES module entry points, and a package can contain both +CommonJS and ES module entry points (either via separate specifiers such as +'pkg' and 'pkg/es-module', or both at the same specifier via Conditional +exports). Unlike in the scenario where "module" is only used by bundlers, +or ES module files are transpiled into CommonJS on the fly before evaluation by +Node.js, the files referenced by the ES module entry point are evaluated as ES +modules.

      +

      Dual package hazard#

      +

      When an application is using a package that provides both CommonJS and ES module +sources, there is a risk of certain bugs if both versions of the package get +loaded. This potential comes from the fact that the pkgInstance created by +const pkgInstance = require('pkg') is not the same as the pkgInstance +created by import pkgInstance from 'pkg' (or an alternative main path like +'pkg/module'). This is the “dual package hazard,†where two versions of the +same package can be loaded within the same runtime environment. While it is +unlikely that an application or package would intentionally load both versions +directly, it is common for an application to load one version while a dependency +of the application loads the other version. This hazard can happen because +Node.js supports intermixing CommonJS and ES modules, and can lead to unexpected +behavior.

      +

      If the package main export is a constructor, an instanceof comparison of +instances created by the two versions returns false, and if the export is an +object, properties added to one (like pkgInstance.foo = 3) are not present on +the other. This differs from how import and require statements work in +all-CommonJS or all-ES module environments, respectively, and therefore is +surprising to users. It also differs from the behavior users are familiar with +when using transpilation via tools like Babel or esm.

      +

      Writing dual packages while avoiding or minimizing hazards#

      +

      First, the hazard described in the previous section occurs when a package +contains both CommonJS and ES module sources and both sources are provided for +use in Node.js, either via separate main entry points or exported paths. A +package might instead be written where any version of Node.js receives only +CommonJS sources, and any separate ES module sources the package might contain +are intended only for other environments such as browsers. Such a package +would be usable by any version of Node.js, since import can refer to CommonJS +files; but it would not provide any of the advantages of using ES module syntax.

      +

      A package might also switch from CommonJS to ES module syntax in a breaking +change version bump. This has the disadvantage that the +newest version of the package would only be usable in ES module-supporting +versions of Node.js.

      +

      Every pattern has tradeoffs, but there are two broad approaches that satisfy the +following conditions:

      +
        +
      1. The package is usable via both require and import.
      2. +
      3. The package is usable in both current Node.js and older versions of Node.js +that lack support for ES modules.
      4. +
      5. The package main entry point, e.g. 'pkg' can be used by both require to +resolve to a CommonJS file and by import to resolve to an ES module file. +(And likewise for exported paths, e.g. 'pkg/feature'.)
      6. +
      7. The package provides named exports, e.g. import { name } from 'pkg' rather +than import pkg from 'pkg'; pkg.name.
      8. +
      9. The package is potentially usable in other ES module environments such as +browsers.
      10. +
      11. The hazards described in the previous section are avoided or minimized.
      12. +
      +

      Approach #1: Use an ES module wrapper#

      +

      Write the package in CommonJS or transpile ES module sources into CommonJS, and +create an ES module wrapper file that defines the named exports. Using +Conditional exports, the ES module wrapper is used for import and the +CommonJS entry point for require.

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    "import": "./wrapper.mjs",
      +    "require": "./index.cjs"
      +  }
      +}
      +

      The preceding example uses explicit extensions .mjs and .cjs. +If your files use the .js extension, "type": "module" will cause such files +to be treated as ES modules, just as "type": "commonjs" would cause them +to be treated as CommonJS. +See Enabling.

      +
      // ./node_modules/pkg/index.cjs
      +exports.name = 'value';
      +
      // ./node_modules/pkg/wrapper.mjs
      +import cjsModule from './index.cjs';
      +export const name = cjsModule.name;
      +

      In this example, the name from import { name } from 'pkg' is the same +singleton as the name from const { name } = require('pkg'). Therefore === +returns true when comparing the two names and the divergent specifier hazard +is avoided.

      +

      If the module is not simply a list of named exports, but rather contains a +unique function or object export like module.exports = function () { ... }, +or if support in the wrapper for the import pkg from 'pkg' pattern is desired, +then the wrapper would instead be written to export the default optionally +along with any named exports as well:

      +
      import cjsModule from './index.cjs';
      +export const name = cjsModule.name;
      +export default cjsModule;
      +

      This approach is appropriate for any of the following use cases:

      +
        +
      • The package is currently written in CommonJS and the author would prefer not +to refactor it into ES module syntax, but wishes to provide named exports for +ES module consumers.
      • +
      • The package has other packages that depend on it, and the end user might +install both this package and those other packages. For example a utilities +package is used directly in an application, and a utilities-plus package +adds a few more functions to utilities. Because the wrapper exports +underlying CommonJS files, it doesn’t matter if utilities-plus is written in +CommonJS or ES module syntax; it will work either way.
      • +
      • The package stores internal state, and the package author would prefer not to +refactor the package to isolate its state management. See the next section.
      • +
      +

      A variant of this approach not requiring conditional exports for consumers could +be to add an export, e.g. "./module", to point to an all-ES module-syntax +version of the package. This could be used via import 'pkg/module' by users +who are certain that the CommonJS version will not be loaded anywhere in the +application, such as by dependencies; or if the CommonJS version can be loaded +but doesn’t affect the ES module version (for example, because the package is +stateless):

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    ".": "./index.cjs",
      +    "./module": "./wrapper.mjs"
      +  }
      +}
      +

      Approach #2: Isolate state#

      +

      A package.json file can define the separate CommonJS and ES module entry +points directly:

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    "import": "./index.mjs",
      +    "require": "./index.cjs"
      +  }
      +}
      +

      This can be done if both the CommonJS and ES module versions of the package are +equivalent, for example because one is the transpiled output of the other; and +the package’s management of state is carefully isolated (or the package is +stateless).

      +

      The reason that state is an issue is because both the CommonJS and ES module +versions of the package might get used within an application; for example, the +user’s application code could import the ES module version while a dependency +requires the CommonJS version. If that were to occur, two copies of the +package would be loaded in memory and therefore two separate states would be +present. This would likely cause hard-to-troubleshoot bugs.

      +

      Aside from writing a stateless package (if JavaScript’s Math were a package, +for example, it would be stateless as all of its methods are static), there are +some ways to isolate state so that it’s shared between the potentially loaded +CommonJS and ES module instances of the package:

      +
        +
      1. +

        If possible, contain all state within an instantiated object. JavaScript’s +Date, for example, needs to be instantiated to contain state; if it were a +package, it would be used like this:

        +
        import Date from 'date';
        +const someDate = new Date();
        +// someDate contains state; Date does not
        +

        The new keyword isn’t required; a package’s function can return a new +object, or modify a passed-in object, to keep the state external to the +package.

        +
      2. +
      3. +

        Isolate the state in one or more CommonJS files that are shared between the +CommonJS and ES module versions of the package. For example, if the CommonJS +and ES module entry points are index.cjs and index.mjs, respectively:

        +
        // ./node_modules/pkg/index.cjs
        +const state = require('./state.cjs');
        +module.exports.state = state;
        +
        // ./node_modules/pkg/index.mjs
        +import state from './state.cjs';
        +export {
        +  state
        +};
        +

        Even if pkg is used via both require and import in an application (for +example, via import in application code and via require by a dependency) +each reference of pkg will contain the same state; and modifying that +state from either module system will apply to both.

        +
      4. +
      +

      Any plugins that attach to the package’s singleton would need to separately +attach to both the CommonJS and ES module singletons.

      +

      This approach is appropriate for any of the following use cases:

      +
        +
      • The package is currently written in ES module syntax and the package author +wants that version to be used wherever such syntax is supported.
      • +
      • The package is stateless or its state can be isolated without too much +difficulty.
      • +
      • The package is unlikely to have other public packages that depend on it, or if +it does, the package is stateless or has state that need not be shared between +dependencies or with the overall application.
      • +
      +

      Even with isolated state, there is still the cost of possible extra code +execution between the CommonJS and ES module versions of a package.

      +

      As with the previous approach, a variant of this approach not requiring +conditional exports for consumers could be to add an export, e.g. +"./module", to point to an all-ES module-syntax version of the package:

      +
      // ./node_modules/pkg/package.json
      +{
      +  "type": "module",
      +  "main": "./index.cjs",
      +  "exports": {
      +    ".": "./index.cjs",
      +    "./module": "./index.mjs"
      +  }
      +}
      +

      Node.js package.json field definitions#

      +

      This section describes the fields used by the Node.js runtime. Other tools (such +as npm) use +additional fields which are ignored by Node.js and not documented here.

      +

      The following fields in package.json files are used in Node.js:

      +
        +
      • "name" - Relevant when using named imports within a package. Also used +by package managers as the name of the package.
      • +
      • "type" - The package type determining whether to load .js files as +CommonJS or ES modules.
      • +
      • "exports" - Package exports and conditional exports. When present, +limits which submodules can be loaded from within the package.
      • +
      • "main" - The default module when loading the package, if exports is not +specified, and in versions of Node.js prior to the introduction of exports.
      • +
      • "imports" - Package imports, for use by modules within the package +itself.
      • +
      +

      "name"#

      + + +
      {
      +  "name": "package-name"
      +}
      +

      The "name" field defines your package’s name. Publishing to the +npm registry requires a name that satisfies +certain requirements.

      +

      The "name" field can be used in addition to the "exports" field to +self-reference a package using its name.

      +

      "type"#

      + + +

      The "type" field defines the module format that Node.js uses for all +.js files that have that package.json file as their nearest parent.

      +

      Files ending with .js are loaded as ES modules when the nearest parent +package.json file contains a top-level field "type" with a value of +"module".

      +

      The nearest parent package.json is defined as the first package.json found +when searching in the current folder, that folder’s parent, and so on up +until a node_modules folder or the volume root is reached.

      +
      // package.json
      +{
      +  "type": "module"
      +}
      +
      # In same folder as preceding package.json
      +node my-app.js # Runs as ES module
      +

      If the nearest parent package.json lacks a "type" field, or contains +"type": "commonjs", .js files are treated as CommonJS. If the volume +root is reached and no package.json is found, .js files are treated as +CommonJS.

      +

      import statements of .js files are treated as ES modules if the nearest +parent package.json contains "type": "module".

      +
      // my-app.js, part of the same example as above
      +import './startup.js'; // Loaded as ES module because of package.json
      +

      Regardless of the value of the "type" field, .mjs files are always treated +as ES modules and .cjs files are always treated as CommonJS.

      +

      "exports"#

      + + +
      {
      +  "exports": "./index.js"
      +}
      +

      The "exports" field allows defining the entry points of a package when +imported by name loaded either via a node_modules lookup or a +self-reference to its own name. It is supported in Node.js 12+ as an +alternative to the "main" that can support defining subpath exports +and conditional exports while encapsulating internal unexported modules.

      +

      Conditional Exports can also be used within "exports" to define different +package entry points per environment, including whether the package is +referenced via require or via import.

      +

      All paths defined in the "exports" must be relative file URLs starting with +./.

      +

      "main"#

      + + +
      {
      +  "main": "./main.js"
      +}
      +

      The "main" field defines the script that is used when the package directory +is loaded via require(). Its value +is interpreted as a path.

      +
      require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.
      +

      When a package has an "exports" field, this will take precedence over the +"main" field when importing the package by name.

      +

      "imports"#

      + +

      Stability: 1 - Experimental

      + +
      // package.json
      +{
      +  "imports": {
      +    "#dep": {
      +      "node": "dep-node-native",
      +      "default": "./dep-polyfill.js"
      +    }
      +  },
      +  "dependencies": {
      +    "dep-node-native": "^1.0.0"
      +  }
      +}
      +

      Entries in the imports field must be strings starting with #.

      +

      Import maps permit mapping to external packages.

      +

      This field defines subpath imports for the current package.

      + +
      +
      +
      + + diff --git a/doc/api/packages.json b/doc/api/packages.json new file mode 100644 index 0000000000000000000000000000000000000000..0056e8765732d1d25a795a62a1e678293a659852 --- /dev/null +++ b/doc/api/packages.json @@ -0,0 +1,363 @@ +{ + "type": "module", + "source": "doc/api/packages.md", + "meta": { + "changes": [ + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/34718", + "description": "Add support for `\"exports\"` patterns." + }, + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34117", + "description": "Add package `\"imports\"` field." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31001", + "description": "Unflag conditional exports." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31002", + "description": "Unflag self-referencing a package using its name." + }, + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28568", + "description": "Introduce `\"exports\"` `package.json` field as a more powerful alternative to the classic `\"main\"` field." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26745", + "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." + } + ] + }, + "miscs": [ + { + "textRaw": "Modules: Packages", + "name": "Modules: Packages", + "type": "misc", + "meta": { + "changes": [ + { + "version": "v12.20.0", + "pr-url": "https://github.com/nodejs/node/pull/34718", + "description": "Add support for `\"exports\"` patterns." + }, + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/34117", + "description": "Add package `\"imports\"` field." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31001", + "description": "Unflag conditional exports." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31002", + "description": "Unflag self-referencing a package using its name." + }, + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28568", + "description": "Introduce `\"exports\"` `package.json` field as a more powerful alternative to the classic `\"main\"` field." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26745", + "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." + } + ] + }, + "miscs": [ + { + "textRaw": "Introduction", + "name": "introduction", + "desc": "

      A package is a folder tree described by a package.json file. The package\nconsists of the folder containing the package.json file and all subfolders\nuntil the next folder containing another package.json file, or a folder\nnamed node_modules.

      \n

      This page provides guidance for package authors writing package.json files\nalong with a reference for the package.json fields defined by Node.js.

      ", + "type": "misc", + "displayName": "Introduction" + }, + { + "textRaw": "Determining module system", + "name": "determining_module_system", + "desc": "

      Node.js will treat the following as ES modules when passed to node as the\ninitial input, or when referenced by import statements within ES module code:

      \n
        \n
      • \n

        Files ending in .mjs.

        \n
      • \n
      • \n

        Files ending in .js when the nearest parent package.json file contains a\ntop-level \"type\" field with a value of \"module\".

        \n
      • \n
      • \n

        Strings passed in as an argument to --eval, or piped to node via STDIN,\nwith the flag --input-type=module.

        \n
      • \n
      \n

      Node.js will treat as CommonJS all other forms of input, such as .js files\nwhere the nearest parent package.json file contains no top-level \"type\"\nfield, or string input without the flag --input-type. This behavior is to\npreserve backward compatibility. However, now that Node.js supports both\nCommonJS and ES modules, it is best to be explicit whenever possible. Node.js\nwill treat the following as CommonJS when passed to node as the initial input,\nor when referenced by import statements within ES module code:

      \n
        \n
      • \n

        Files ending in .cjs.

        \n
      • \n
      • \n

        Files ending in .js when the nearest parent package.json file contains a\ntop-level field \"type\" with a value of \"commonjs\".

        \n
      • \n
      • \n

        Strings passed in as an argument to --eval or --print, or piped to node\nvia STDIN, with the flag --input-type=commonjs.

        \n
      • \n
      \n

      Package authors should include the \"type\" field, even in packages where\nall sources are CommonJS. Being explicit about the type of the package will\nfuture-proof the package in case the default type of Node.js ever changes, and\nit will also make things easier for build tools and loaders to determine how the\nfiles in the package should be interpreted.

      ", + "modules": [ + { + "textRaw": "`package.json` and file extensions", + "name": "`package.json`_and_file_extensions", + "desc": "

      Within a package, the package.json \"type\" field defines how\nNode.js should interpret .js files. If a package.json file does not have a\n\"type\" field, .js files are treated as CommonJS.

      \n

      A package.json \"type\" value of \"module\" tells Node.js to interpret .js\nfiles within that package as using ES module syntax.

      \n

      The \"type\" field applies not only to initial entry points (node my-app.js)\nbut also to files referenced by import statements and import() expressions.

      \n
      // my-app.js, treated as an ES module because there is a package.json\n// file in the same folder with \"type\": \"module\".\n\nimport './startup/init.js';\n// Loaded as ES module since ./startup contains no package.json file,\n// and therefore inherits the \"type\" value from one level up.\n\nimport 'commonjs-package';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nimport './node_modules/commonjs-package/index.js';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n
      \n

      Files ending with .mjs are always loaded as ES modules regardless of\nthe nearest parent package.json.

      \n

      Files ending with .cjs are always loaded as CommonJS regardless of the\nnearest parent package.json.

      \n
      import './legacy-file.cjs';\n// Loaded as CommonJS since .cjs is always loaded as CommonJS.\n\nimport 'commonjs-package/src/index.mjs';\n// Loaded as ES module since .mjs is always loaded as ES module.\n
      \n

      The .mjs and .cjs extensions can be used to mix types within the same\npackage:

      \n
        \n
      • \n

        Within a \"type\": \"module\" package, Node.js can be instructed to\ninterpret a particular file as CommonJS by naming it with a .cjs\nextension (since both .js and .mjs files are treated as ES modules within\na \"module\" package).

        \n
      • \n
      • \n

        Within a \"type\": \"commonjs\" package, Node.js can be instructed to\ninterpret a particular file as an ES module by naming it with an .mjs\nextension (since both .js and .cjs files are treated as CommonJS within a\n\"commonjs\" package).

        \n
      • \n
      ", + "type": "module", + "displayName": "`package.json` and file extensions" + }, + { + "textRaw": "`--input-type` flag", + "name": "`--input-type`_flag", + "desc": "

      Strings passed in as an argument to --eval (or -e), or piped to node via\nSTDIN, are treated as ES modules when the --input-type=module flag\nis set.

      \n
      node --input-type=module --eval \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | node --input-type=module\n
      \n

      For completeness there is also --input-type=commonjs, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type is\nunspecified.

      ", + "type": "module", + "displayName": "`--input-type` flag" + } + ], + "type": "misc", + "displayName": "Determining module system" + }, + { + "textRaw": "Package entry points", + "name": "package_entry_points", + "desc": "

      In a package’s package.json file, two fields can define entry points for a\npackage: \"main\" and \"exports\". The \"main\" field is supported\nin all versions of Node.js, but its capabilities are limited: it only defines\nthe main entry point of the package.

      \n

      The \"exports\" field provides an alternative to \"main\" where the\npackage main entry point can be defined while also encapsulating the package,\npreventing any other entry points besides those defined in \"exports\".\nThis encapsulation allows module authors to define a public interface for\ntheir package.

      \n

      If both \"exports\" and \"main\" are defined, the \"exports\" field\ntakes precedence over \"main\". \"exports\" are not specific to ES\nmodules or CommonJS; \"main\" is overridden by \"exports\" if it\nexists. As such \"main\" cannot be used as a fallback for CommonJS but it\ncan be used as a fallback for legacy versions of Node.js that do not support the\n\"exports\" field.

      \n

      Conditional exports can be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import. For more information about supporting\nboth CommonJS and ES Modules in a single package please consult\nthe dual CommonJS/ES module packages section.

      \n

      Warning: Introducing the \"exports\" field prevents consumers of a\npackage from using any entry points that are not defined, including the\npackage.json (e.g. require('your-package/package.json'). This will\nlikely be a breaking change.

      \n

      To make the introduction of \"exports\" non-breaking, ensure that every\npreviously supported entry point is exported. It is best to explicitly specify\nentry points so that the package’s public API is well-defined. For example,\na project that previous exported main, lib,\nfeature, and the package.json could use the following package.exports:

      \n
      {\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/index\": \"./lib/index.js\",\n    \"./lib/index.js\": \"./lib/index.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/index.js\": \"./feature/index.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
      \n

      Alternatively a project could choose to export entire folders:

      \n
      {\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/*\": \"./lib/*.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/*\": \"./feature/*.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
      \n

      As a last resort, package encapsulation can be disabled entirely by creating an\nexport for the root of the package \"./*\": \"./*\". This exposes every file\nin the package at the cost of disabling the encapsulation and potential tooling\nbenefits this provides. As the ES Module loader in Node.js enforces the use of\nthe full specifier path, exporting the root rather than being explicit\nabout entry is less expressive than either of the prior examples. Not only\nis encapsulation lost but module consumers are unable to\nimport feature from 'my-mod/feature' as they need to provide the full\npath import feature from 'my-mod/feature/index.js.

      ", + "modules": [ + { + "textRaw": "Main entry point export", + "name": "main_entry_point_export", + "desc": "

      To set the main entry point for a package, it is advisable to define both\n\"exports\" and \"main\" in the package’s package.json file:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": \"./main.js\"\n}\n
      \n

      When the \"exports\" field is defined, all subpaths of the package are\nencapsulated and no longer available to importers. For example,\nrequire('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED\nerror.

      \n

      This encapsulation of exports provides more reliable guarantees\nabout package interfaces for tools and when handling semver upgrades for a\npackage. It is not a strong encapsulation since a direct require of any\nabsolute subpath of the package such as\nrequire('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.

      ", + "type": "module", + "displayName": "Main entry point export" + }, + { + "textRaw": "Subpath exports", + "name": "subpath_exports", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      When using the \"exports\" field, custom subpaths can be defined along\nwith the main entry point by treating the main entry point as the\n\".\" subpath:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./submodule\": \"./src/submodule.js\"\n  }\n}\n
      \n

      Now only the defined subpath in \"exports\" can be imported by a consumer:

      \n
      import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
      \n

      While other subpaths will error:

      \n
      import submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n
      ", + "type": "module", + "displayName": "Subpath exports" + }, + { + "textRaw": "Subpath imports", + "name": "subpath_imports", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      In addition to the \"exports\" field, it is possible to define internal\npackage import maps that only apply to import specifiers from within the package\nitself.

      \n

      Entries in the imports field must always start with # to ensure they are\ndisambiguated from package specifiers.

      \n

      For example, the imports field can be used to gain the benefits of conditional\nexports for internal modules:

      \n
      // package.json\n{\n  \"imports\": {\n    \"#dep\": {\n      \"node\": \"dep-node-native\",\n      \"default\": \"./dep-polyfill.js\"\n    }\n  },\n  \"dependencies\": {\n    \"dep-node-native\": \"^1.0.0\"\n  }\n}\n
      \n

      where import '#dep' does not get the resolution of the external package\ndep-node-native (including its exports in turn), and instead gets the local\nfile ./dep-polyfill.js relative to the package in other environments.

      \n

      Unlike the \"exports\" field, the \"imports\" field permits mapping to external\npackages.

      \n

      The resolution rules for the imports field are otherwise\nanalogous to the exports field.

      ", + "type": "module", + "displayName": "Subpath imports" + }, + { + "textRaw": "Subpath patterns", + "name": "subpath_patterns", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      For packages with a small number of exports or imports, we recommend\nexplicitly listing each exports subpath entry. But for packages that have\nlarge numbers of subpaths, this might cause package.json bloat and\nmaintenance issues.

      \n

      For these use cases, subpath export patterns can be used instead:

      \n
      // ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./features/*\": \"./src/features/*.js\"\n  },\n  \"imports\": {\n    \"#internal/*\": \"./src/internal/*.js\"\n  }\n}\n
      \n

      The left hand matching pattern must always end in *. All instances of * on\nthe right hand side will then be replaced with this value, including if it\ncontains any / separators.

      \n
      import featureX from 'es-module-package/features/x';\n// Loads ./node_modules/es-module-package/src/features/x.js\n\nimport featureY from 'es-module-package/features/y/y';\n// Loads ./node_modules/es-module-package/src/features/y/y.js\n\nimport internalZ from '#internal/z';\n// Loads ./node_modules/es-module-package/src/internal/z.js\n
      \n

      This is a direct static replacement without any special handling for file\nextensions. In the previous example, pkg/features/x.json would be resolved to\n./src/features/x.json.js in the mapping.

      \n

      The property of exports being statically enumerable is maintained with exports\npatterns since the individual exports for a package can be determined by\ntreating the right hand side target pattern as a ** glob against the list of\nfiles within the package. Because node_modules paths are forbidden in exports\ntargets, this expansion is dependent on only the files of the package itself.

      ", + "type": "module", + "displayName": "Subpath patterns" + }, + { + "textRaw": "Exports sugar", + "name": "exports_sugar", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      If the \".\" export is the only export, the \"exports\" field provides sugar\nfor this case being the direct \"exports\" field value.

      \n

      If the \".\" export has a fallback array or string value, then the\n\"exports\" field can be set to this value directly.

      \n
      {\n  \"exports\": {\n    \".\": \"./main.js\"\n  }\n}\n
      \n

      can be written:

      \n
      {\n  \"exports\": \"./main.js\"\n}\n
      ", + "type": "module", + "displayName": "Exports sugar" + }, + { + "textRaw": "Conditional exports", + "name": "conditional_exports", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Conditional exports provide a way to map to different paths depending on\ncertain conditions. They are supported for both CommonJS and ES module imports.

      \n

      For example, a package that wants to provide different ES module exports for\nrequire() and import can be written:

      \n
      // package.json\n{\n  \"main\": \"./main-require.cjs\",\n  \"exports\": {\n    \"import\": \"./main-module.js\",\n    \"require\": \"./main-require.cjs\"\n  },\n  \"type\": \"module\"\n}\n
      \n

      Node.js supports the following conditions out of the box:

      \n
        \n
      • \"import\" - matches when the package is loaded via import or\nimport(), or via any top-level import or resolve operation by the\nECMAScript module loader. Applies regardless of the module format of the\ntarget file. Always mutually exclusive with \"require\".
      • \n
      • \"require\" - matches when the package is loaded via require(). The\nreferenced file should be loadable with require() although the condition\nmatches regardless of the module format of the target file. Expected\nformats include CommonJS, JSON, and native addons but not ES modules as\nrequire() doesn't support them. Always mutually exclusive with\n\"import\".
      • \n
      • \"node\" - matches for any Node.js environment. Can be a CommonJS or ES\nmodule file. This condition should always come after \"import\" or\n\"require\".
      • \n
      • \"default\" - the generic fallback that always matches. Can be a CommonJS\nor ES module file. This condition should always come last.
      • \n
      \n

      Within the \"exports\" object, key order is significant. During condition\nmatching, earlier entries have higher priority and take precedence over later\nentries. The general rule is that conditions should be from most specific to\nleast specific in object order.

      \n

      Other conditions such as \"browser\", \"electron\", \"deno\", \"react-native\",\netc., are unknown to Node.js, and thus ignored. Runtimes or tools other than\nNode.js can use them at their discretion. Further restrictions, definitions, or\nguidance on condition names might occur in the future.

      \n

      Using the \"import\" and \"require\" conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.

      \n

      Conditional exports can also be extended to exports subpaths, for example:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./feature\": {\n      \"node\": \"./feature-node.js\",\n      \"default\": \"./feature.js\"\n    }\n  }\n}\n
      \n

      Defines a package where require('pkg/feature') and import 'pkg/feature'\ncould provide different implementations between Node.js and other JS\nenvironments.

      \n

      When using environment branches, always include a \"default\" condition where\npossible. Providing a \"default\" condition ensures that any unknown JS\nenvironments are able to use this universal implementation, which helps avoid\nthese JS environments from having to pretend to be existing environments in\norder to support packages with conditional exports. For this reason, using\n\"node\" and \"default\" condition branches is usually preferable to using\n\"node\" and \"browser\" condition branches.

      ", + "type": "module", + "displayName": "Conditional exports" + }, + { + "textRaw": "Nested conditions", + "name": "nested_conditions", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      In addition to direct mappings, Node.js also supports nested condition objects.

      \n

      For example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:

      \n
      {\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \"node\": {\n      \"import\": \"./feature-node.mjs\",\n      \"require\": \"./feature-node.cjs\"\n    },\n    \"default\": \"./feature.mjs\",\n  }\n}\n
      \n

      Conditions continue to be matched in order as with flat conditions. If\na nested conditional does not have any mapping it will continue checking\nthe remaining conditions of the parent condition. In this way nested\nconditions behave analogously to nested JavaScript if statements.

      ", + "type": "module", + "displayName": "Nested conditions" + }, + { + "textRaw": "Resolving user conditions", + "name": "resolving_user_conditions", + "desc": "

      When running Node.js, custom user conditions can be added with the\n--conditions flag:

      \n
      node --conditions=development main.js\n
      \n

      which would then resolve the \"development\" condition in package imports and\nexports, while resolving the existing \"node\", \"default\", \"import\", and\n\"require\" conditions as appropriate.

      \n

      Any number of custom conditions can be set with repeat flags.

      ", + "type": "module", + "displayName": "Resolving user conditions" + }, + { + "textRaw": "Self-referencing a package using its name", + "name": "self-referencing_a_package_using_its_name", + "desc": "

      Within a package, the values defined in the package’s\npackage.json \"exports\" field can be referenced via the package’s name.\nFor example, assuming the package.json is:

      \n
      // package.json\n{\n  \"name\": \"a-package\",\n  \"exports\": {\n    \".\": \"./main.mjs\",\n    \"./foo\": \"./foo.js\"\n  }\n}\n
      \n

      Then any module in that package can reference an export in the package itself:

      \n
      // ./a-module.mjs\nimport { something } from 'a-package'; // Imports \"something\" from ./main.mjs.\n
      \n

      Self-referencing is available only if package.json has \"exports\", and\nwill allow importing only what that \"exports\" (in the package.json)\nallows. So the code below, given the previous package, will generate a runtime\nerror:

      \n
      // ./another-module.mjs\n\n// Imports \"another\" from ./m.mjs. Fails because\n// the \"package.json\" \"exports\" field\n// does not provide an export named \"./m.mjs\".\nimport { another } from 'a-package/m.mjs';\n
      \n

      Self-referencing is also available when using require, both in an ES module,\nand in a CommonJS one. For example, this code will also work:

      \n
      // ./a-module.js\nconst { something } = require('a-package/foo'); // Loads from ./foo.js.\n
      ", + "type": "module", + "displayName": "Self-referencing a package using its name" + } + ], + "type": "misc", + "displayName": "Package entry points" + }, + { + "textRaw": "Dual CommonJS/ES module packages", + "name": "dual_commonjs/es_module_packages", + "desc": "

      Prior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with package.json \"main\" specifying the\nCommonJS entry point and package.json \"module\" specifying the ES module\nentry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) the top-level \"module\" field.

      \n

      Node.js can now run ES module entry points, and a package can contain both\nCommonJS and ES module entry points (either via separate specifiers such as\n'pkg' and 'pkg/es-module', or both at the same specifier via Conditional\nexports). Unlike in the scenario where \"module\" is only used by bundlers,\nor ES module files are transpiled into CommonJS on the fly before evaluation by\nNode.js, the files referenced by the ES module entry point are evaluated as ES\nmodules.

      ", + "modules": [ + { + "textRaw": "Dual package hazard", + "name": "dual_package_hazard", + "desc": "

      When an application is using a package that provides both CommonJS and ES module\nsources, there is a risk of certain bugs if both versions of the package get\nloaded. This potential comes from the fact that the pkgInstance created by\nconst pkgInstance = require('pkg') is not the same as the pkgInstance\ncreated by import pkgInstance from 'pkg' (or an alternative main path like\n'pkg/module'). This is the “dual package hazard,†where two versions of the\nsame package can be loaded within the same runtime environment. While it is\nunlikely that an application or package would intentionally load both versions\ndirectly, it is common for an application to load one version while a dependency\nof the application loads the other version. This hazard can happen because\nNode.js supports intermixing CommonJS and ES modules, and can lead to unexpected\nbehavior.

      \n

      If the package main export is a constructor, an instanceof comparison of\ninstances created by the two versions returns false, and if the export is an\nobject, properties added to one (like pkgInstance.foo = 3) are not present on\nthe other. This differs from how import and require statements work in\nall-CommonJS or all-ES module environments, respectively, and therefore is\nsurprising to users. It also differs from the behavior users are familiar with\nwhen using transpilation via tools like Babel or esm.

      ", + "type": "module", + "displayName": "Dual package hazard" + }, + { + "textRaw": "Writing dual packages while avoiding or minimizing hazards", + "name": "writing_dual_packages_while_avoiding_or_minimizing_hazards", + "desc": "

      First, the hazard described in the previous section occurs when a package\ncontains both CommonJS and ES module sources and both sources are provided for\nuse in Node.js, either via separate main entry points or exported paths. A\npackage might instead be written where any version of Node.js receives only\nCommonJS sources, and any separate ES module sources the package might contain\nare intended only for other environments such as browsers. Such a package\nwould be usable by any version of Node.js, since import can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.

      \n

      A package might also switch from CommonJS to ES module syntax in a breaking\nchange version bump. This has the disadvantage that the\nnewest version of the package would only be usable in ES module-supporting\nversions of Node.js.

      \n

      Every pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:

      \n
        \n
      1. The package is usable via both require and import.
      2. \n
      3. The package is usable in both current Node.js and older versions of Node.js\nthat lack support for ES modules.
      4. \n
      5. The package main entry point, e.g. 'pkg' can be used by both require to\nresolve to a CommonJS file and by import to resolve to an ES module file.\n(And likewise for exported paths, e.g. 'pkg/feature'.)
      6. \n
      7. The package provides named exports, e.g. import { name } from 'pkg' rather\nthan import pkg from 'pkg'; pkg.name.
      8. \n
      9. The package is potentially usable in other ES module environments such as\nbrowsers.
      10. \n
      11. The hazards described in the previous section are avoided or minimized.
      12. \n
      ", + "modules": [ + { + "textRaw": "Approach #1: Use an ES module wrapper", + "name": "approach_#1:_use_an_es_module_wrapper", + "desc": "

      Write the package in CommonJS or transpile ES module sources into CommonJS, and\ncreate an ES module wrapper file that defines the named exports. Using\nConditional exports, the ES module wrapper is used for import and the\nCommonJS entry point for require.

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./wrapper.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
      \n

      The preceding example uses explicit extensions .mjs and .cjs.\nIf your files use the .js extension, \"type\": \"module\" will cause such files\nto be treated as ES modules, just as \"type\": \"commonjs\" would cause them\nto be treated as CommonJS.\nSee Enabling.

      \n
      // ./node_modules/pkg/index.cjs\nexports.name = 'value';\n
      \n
      // ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n
      \n

      In this example, the name from import { name } from 'pkg' is the same\nsingleton as the name from const { name } = require('pkg'). Therefore ===\nreturns true when comparing the two names and the divergent specifier hazard\nis avoided.

      \n

      If the module is not simply a list of named exports, but rather contains a\nunique function or object export like module.exports = function () { ... },\nor if support in the wrapper for the import pkg from 'pkg' pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:

      \n
      import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n
      \n

      This approach is appropriate for any of the following use cases:

      \n
        \n
      • The package is currently written in CommonJS and the author would prefer not\nto refactor it into ES module syntax, but wishes to provide named exports for\nES module consumers.
      • \n
      • The package has other packages that depend on it, and the end user might\ninstall both this package and those other packages. For example a utilities\npackage is used directly in an application, and a utilities-plus package\nadds a few more functions to utilities. Because the wrapper exports\nunderlying CommonJS files, it doesn’t matter if utilities-plus is written in\nCommonJS or ES module syntax; it will work either way.
      • \n
      • The package stores internal state, and the package author would prefer not to\nrefactor the package to isolate its state management. See the next section.
      • \n
      \n

      A variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. \"./module\", to point to an all-ES module-syntax\nversion of the package. This could be used via import 'pkg/module' by users\nwho are certain that the CommonJS version will not be loaded anywhere in the\napplication, such as by dependencies; or if the CommonJS version can be loaded\nbut doesn’t affect the ES module version (for example, because the package is\nstateless):

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./wrapper.mjs\"\n  }\n}\n
      ", + "type": "module", + "displayName": "Approach #1: Use an ES module wrapper" + }, + { + "textRaw": "Approach #2: Isolate state", + "name": "approach_#2:_isolate_state", + "desc": "

      A package.json file can define the separate CommonJS and ES module entry\npoints directly:

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./index.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
      \n

      This can be done if both the CommonJS and ES module versions of the package are\nequivalent, for example because one is the transpiled output of the other; and\nthe package’s management of state is carefully isolated (or the package is\nstateless).

      \n

      The reason that state is an issue is because both the CommonJS and ES module\nversions of the package might get used within an application; for example, the\nuser’s application code could import the ES module version while a dependency\nrequires the CommonJS version. If that were to occur, two copies of the\npackage would be loaded in memory and therefore two separate states would be\npresent. This would likely cause hard-to-troubleshoot bugs.

      \n

      Aside from writing a stateless package (if JavaScript’s Math were a package,\nfor example, it would be stateless as all of its methods are static), there are\nsome ways to isolate state so that it’s shared between the potentially loaded\nCommonJS and ES module instances of the package:

      \n
        \n
      1. \n

        If possible, contain all state within an instantiated object. JavaScript’s\nDate, for example, needs to be instantiated to contain state; if it were a\npackage, it would be used like this:

        \n
        import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n
        \n

        The new keyword isn’t required; a package’s function can return a new\nobject, or modify a passed-in object, to keep the state external to the\npackage.

        \n
      2. \n
      3. \n

        Isolate the state in one or more CommonJS files that are shared between the\nCommonJS and ES module versions of the package. For example, if the CommonJS\nand ES module entry points are index.cjs and index.mjs, respectively:

        \n
        // ./node_modules/pkg/index.cjs\nconst state = require('./state.cjs');\nmodule.exports.state = state;\n
        \n
        // ./node_modules/pkg/index.mjs\nimport state from './state.cjs';\nexport {\n  state\n};\n
        \n

        Even if pkg is used via both require and import in an application (for\nexample, via import in application code and via require by a dependency)\neach reference of pkg will contain the same state; and modifying that\nstate from either module system will apply to both.

        \n
      4. \n
      \n

      Any plugins that attach to the package’s singleton would need to separately\nattach to both the CommonJS and ES module singletons.

      \n

      This approach is appropriate for any of the following use cases:

      \n
        \n
      • The package is currently written in ES module syntax and the package author\nwants that version to be used wherever such syntax is supported.
      • \n
      • The package is stateless or its state can be isolated without too much\ndifficulty.
      • \n
      • The package is unlikely to have other public packages that depend on it, or if\nit does, the package is stateless or has state that need not be shared between\ndependencies or with the overall application.
      • \n
      \n

      Even with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.

      \n

      As with the previous approach, a variant of this approach not requiring\nconditional exports for consumers could be to add an export, e.g.\n\"./module\", to point to an all-ES module-syntax version of the package:

      \n
      // ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./index.mjs\"\n  }\n}\n
      ", + "type": "module", + "displayName": "Approach #2: Isolate state" + } + ], + "type": "module", + "displayName": "Writing dual packages while avoiding or minimizing hazards" + } + ], + "type": "misc", + "displayName": "Dual CommonJS/ES module packages" + }, + { + "textRaw": "Node.js `package.json` field definitions", + "name": "node.js_`package.json`_field_definitions", + "desc": "

      This section describes the fields used by the Node.js runtime. Other tools (such\nas npm) use\nadditional fields which are ignored by Node.js and not documented here.

      \n

      The following fields in package.json files are used in Node.js:

      \n
        \n
      • \"name\" - Relevant when using named imports within a package. Also used\nby package managers as the name of the package.
      • \n
      • \"type\" - The package type determining whether to load .js files as\nCommonJS or ES modules.
      • \n
      • \"exports\" - Package exports and conditional exports. When present,\nlimits which submodules can be loaded from within the package.
      • \n
      • \"main\" - The default module when loading the package, if exports is not\nspecified, and in versions of Node.js prior to the introduction of exports.
      • \n
      • \"imports\" - Package imports, for use by modules within the package\nitself.
      • \n
      ", + "modules": [ + { + "textRaw": "`\"name\"`", + "name": "`\"name\"`", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [ + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31002", + "description": "Remove the `--experimental-resolve-self` option." + } + ] + }, + "desc": "\n
      {\n  \"name\": \"package-name\"\n}\n
      \n

      The \"name\" field defines your package’s name. Publishing to the\nnpm registry requires a name that satisfies\ncertain requirements.

      \n

      The \"name\" field can be used in addition to the \"exports\" field to\nself-reference a package using its name.

      ", + "type": "module", + "displayName": "`\"name\"`" + }, + { + "textRaw": "`\"type\"`", + "name": "`\"type\"`", + "meta": { + "added": [ + "v12.0.0" + ], + "changes": [ + { + "version": [ + "v12.17.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29866", + "description": "Unflag `--experimental-modules`." + } + ] + }, + "desc": "\n

      The \"type\" field defines the module format that Node.js uses for all\n.js files that have that package.json file as their nearest parent.

      \n

      Files ending with .js are loaded as ES modules when the nearest parent\npackage.json file contains a top-level field \"type\" with a value of\n\"module\".

      \n

      The nearest parent package.json is defined as the first package.json found\nwhen searching in the current folder, that folder’s parent, and so on up\nuntil a node_modules folder or the volume root is reached.

      \n
      // package.json\n{\n  \"type\": \"module\"\n}\n
      \n
      # In same folder as preceding package.json\nnode my-app.js # Runs as ES module\n
      \n

      If the nearest parent package.json lacks a \"type\" field, or contains\n\"type\": \"commonjs\", .js files are treated as CommonJS. If the volume\nroot is reached and no package.json is found, .js files are treated as\nCommonJS.

      \n

      import statements of .js files are treated as ES modules if the nearest\nparent package.json contains \"type\": \"module\".

      \n
      // my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
      \n

      Regardless of the value of the \"type\" field, .mjs files are always treated\nas ES modules and .cjs files are always treated as CommonJS.

      ", + "type": "module", + "displayName": "`\"type\"`" + }, + { + "textRaw": "`\"exports\"`", + "name": "`\"exports\"`", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [ + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/29978", + "description": "Implement conditional exports." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31001", + "description": "Remove the `--experimental-conditional-exports` option." + }, + { + "version": [ + "v12.16.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/31008", + "description": "Implement logical conditional exports ordering." + }, + { + "version": [ + "v12.20.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/34718", + "description": "Add support for `\"exports\"` patterns." + } + ] + }, + "desc": "\n
      {\n  \"exports\": \"./index.js\"\n}\n
      \n

      The \"exports\" field allows defining the entry points of a package when\nimported by name loaded either via a node_modules lookup or a\nself-reference to its own name. It is supported in Node.js 12+ as an\nalternative to the \"main\" that can support defining subpath exports\nand conditional exports while encapsulating internal unexported modules.

      \n

      Conditional Exports can also be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import.

      \n

      All paths defined in the \"exports\" must be relative file URLs starting with\n./.

      ", + "type": "module", + "displayName": "`\"exports\"`" + }, + { + "textRaw": "`\"main\"`", + "name": "`\"main\"`", + "meta": { + "added": [ + "v0.4.0" + ], + "changes": [] + }, + "desc": "\n
      {\n  \"main\": \"./main.js\"\n}\n
      \n

      The \"main\" field defines the script that is used when the package directory\nis loaded via require(). Its value\nis interpreted as a path.

      \n
      require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.\n
      \n

      When a package has an \"exports\" field, this will take precedence over the\n\"main\" field when importing the package by name.

      ", + "type": "module", + "displayName": "`\"main\"`" + }, + { + "textRaw": "`\"imports\"`", + "name": "`\"imports\"`", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "\n
      // package.json\n{\n  \"imports\": {\n    \"#dep\": {\n      \"node\": \"dep-node-native\",\n      \"default\": \"./dep-polyfill.js\"\n    }\n  },\n  \"dependencies\": {\n    \"dep-node-native\": \"^1.0.0\"\n  }\n}\n
      \n

      Entries in the imports field must be strings starting with #.

      \n

      Import maps permit mapping to external packages.

      \n

      This field defines subpath imports for the current package.

      ", + "type": "module", + "displayName": "`\"imports\"`" + } + ], + "type": "misc", + "displayName": "Node.js `package.json` field definitions" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/path.html b/doc/api/path.html new file mode 100644 index 0000000000000000000000000000000000000000..27b53d417a9ac93e7a44b20d058d3c0418c36256 --- /dev/null +++ b/doc/api/path.html @@ -0,0 +1,605 @@ + + + + + + + Path | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Path#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/path.js

      +

      The path module provides utilities for working with file and directory paths. +It can be accessed using:

      +
      const path = require('path');
      +

      Windows vs. POSIX#

      +

      The default operation of the path module varies based on the operating system +on which a Node.js application is running. Specifically, when running on a +Windows operating system, the path module will assume that Windows-style +paths are being used.

      +

      So using path.basename() might yield different results on POSIX and Windows:

      +

      On POSIX:

      +
      path.basename('C:\\temp\\myfile.html');
      +// Returns: 'C:\\temp\\myfile.html'
      +

      On Windows:

      +
      path.basename('C:\\temp\\myfile.html');
      +// Returns: 'myfile.html'
      +

      To achieve consistent results when working with Windows file paths on any +operating system, use path.win32:

      +

      On POSIX and Windows:

      +
      path.win32.basename('C:\\temp\\myfile.html');
      +// Returns: 'myfile.html'
      +

      To achieve consistent results when working with POSIX file paths on any +operating system, use path.posix:

      +

      On POSIX and Windows:

      +
      path.posix.basename('/tmp/myfile.html');
      +// Returns: 'myfile.html'
      +

      On Windows Node.js follows the concept of per-drive working directory. +This behavior can be observed when using a drive path without a backslash. For +example, path.resolve('C:\\') can potentially return a different result than +path.resolve('C:'). For more information, see +this MSDN page.

      +

      path.basename(path[, ext])#

      + + +

      The path.basename() method returns the last portion of a path, similar to +the Unix basename command. Trailing directory separators are ignored, see +path.sep.

      +
      path.basename('/foo/bar/baz/asdf/quux.html');
      +// Returns: 'quux.html'
      +
      +path.basename('/foo/bar/baz/asdf/quux.html', '.html');
      +// Returns: 'quux'
      +

      Although Windows usually treats file names, including file extensions, in a +case-insensitive manner, this function does not. For example, C:\\foo.html and +C:\\foo.HTML refer to the same file, but basename treats the extension as a +case-sensitive string:

      +
      path.win32.basename('C:\\foo.html', '.html');
      +// Returns: 'foo'
      +
      +path.win32.basename('C:\\foo.HTML', '.html');
      +// Returns: 'foo.HTML'
      +

      A TypeError is thrown if path is not a string or if ext is given +and is not a string.

      +

      path.delimiter#

      + + +

      Provides the platform-specific path delimiter:

      +
        +
      • ; for Windows
      • +
      • : for POSIX
      • +
      +

      For example, on POSIX:

      +
      console.log(process.env.PATH);
      +// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
      +
      +process.env.PATH.split(path.delimiter);
      +// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
      +

      On Windows:

      +
      console.log(process.env.PATH);
      +// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
      +
      +process.env.PATH.split(path.delimiter);
      +// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
      +

      path.dirname(path)#

      + + +

      The path.dirname() method returns the directory name of a path, similar to +the Unix dirname command. Trailing directory separators are ignored, see +path.sep.

      +
      path.dirname('/foo/bar/baz/asdf/quux');
      +// Returns: '/foo/bar/baz/asdf'
      +

      A TypeError is thrown if path is not a string.

      +

      path.extname(path)#

      + + +

      The path.extname() method returns the extension of the path, from the last +occurrence of the . (period) character to end of string in the last portion of +the path. If there is no . in the last portion of the path, or if +there are no . characters other than the first character of +the basename of path (see path.basename()) , an empty string is returned.

      +
      path.extname('index.html');
      +// Returns: '.html'
      +
      +path.extname('index.coffee.md');
      +// Returns: '.md'
      +
      +path.extname('index.');
      +// Returns: '.'
      +
      +path.extname('index');
      +// Returns: ''
      +
      +path.extname('.index');
      +// Returns: ''
      +
      +path.extname('.index.md');
      +// Returns: '.md'
      +

      A TypeError is thrown if path is not a string.

      +

      path.format(pathObject)#

      + + +

      The path.format() method returns a path string from an object. This is the +opposite of path.parse().

      +

      When providing properties to the pathObject remember that there are +combinations where one property has priority over another:

      +
        +
      • pathObject.root is ignored if pathObject.dir is provided
      • +
      • pathObject.ext and pathObject.name are ignored if pathObject.base exists
      • +
      +

      For example, on POSIX:

      +
      // If `dir`, `root` and `base` are provided,
      +// `${dir}${path.sep}${base}`
      +// will be returned. `root` is ignored.
      +path.format({
      +  root: '/ignored',
      +  dir: '/home/user/dir',
      +  base: 'file.txt'
      +});
      +// Returns: '/home/user/dir/file.txt'
      +
      +// `root` will be used if `dir` is not specified.
      +// If only `root` is provided or `dir` is equal to `root` then the
      +// platform separator will not be included. `ext` will be ignored.
      +path.format({
      +  root: '/',
      +  base: 'file.txt',
      +  ext: 'ignored'
      +});
      +// Returns: '/file.txt'
      +
      +// `name` + `ext` will be used if `base` is not specified.
      +path.format({
      +  root: '/',
      +  name: 'file',
      +  ext: '.txt'
      +});
      +// Returns: '/file.txt'
      +

      On Windows:

      +
      path.format({
      +  dir: 'C:\\path\\dir',
      +  base: 'file.txt'
      +});
      +// Returns: 'C:\\path\\dir\\file.txt'
      +

      path.isAbsolute(path)#

      + + +

      The path.isAbsolute() method determines if path is an absolute path.

      +

      If the given path is a zero-length string, false will be returned.

      +

      For example, on POSIX:

      +
      path.isAbsolute('/foo/bar'); // true
      +path.isAbsolute('/baz/..');  // true
      +path.isAbsolute('qux/');     // false
      +path.isAbsolute('.');        // false
      +

      On Windows:

      +
      path.isAbsolute('//server');    // true
      +path.isAbsolute('\\\\server');  // true
      +path.isAbsolute('C:/foo/..');   // true
      +path.isAbsolute('C:\\foo\\..'); // true
      +path.isAbsolute('bar\\baz');    // false
      +path.isAbsolute('bar/baz');     // false
      +path.isAbsolute('.');           // false
      +

      A TypeError is thrown if path is not a string.

      +

      path.join([...paths])#

      + + +

      The path.join() method joins all given path segments together using the +platform-specific separator as a delimiter, then normalizes the resulting path.

      +

      Zero-length path segments are ignored. If the joined path string is a +zero-length string then '.' will be returned, representing the current +working directory.

      +
      path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
      +// Returns: '/foo/bar/baz/asdf'
      +
      +path.join('foo', {}, 'bar');
      +// Throws 'TypeError: Path must be a string. Received {}'
      +

      A TypeError is thrown if any of the path segments is not a string.

      +

      path.normalize(path)#

      + + +

      The path.normalize() method normalizes the given path, resolving '..' and +'.' segments.

      +

      When multiple, sequential path segment separation characters are found (e.g. +/ on POSIX and either \ or / on Windows), they are replaced by a single +instance of the platform-specific path segment separator (/ on POSIX and +\ on Windows). Trailing separators are preserved.

      +

      If the path is a zero-length string, '.' is returned, representing the +current working directory.

      +

      For example, on POSIX:

      +
      path.normalize('/foo/bar//baz/asdf/quux/..');
      +// Returns: '/foo/bar/baz/asdf'
      +

      On Windows:

      +
      path.normalize('C:\\temp\\\\foo\\bar\\..\\');
      +// Returns: 'C:\\temp\\foo\\'
      +

      Since Windows recognizes multiple path separators, both separators will be +replaced by instances of the Windows preferred separator (\):

      +
      path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
      +// Returns: 'C:\\temp\\foo\\bar'
      +

      A TypeError is thrown if path is not a string.

      +

      path.parse(path)#

      + + +

      The path.parse() method returns an object whose properties represent +significant elements of the path. Trailing directory separators are ignored, +see path.sep.

      +

      The returned object will have the following properties:

      + +

      For example, on POSIX:

      +
      path.parse('/home/user/dir/file.txt');
      +// Returns:
      +// { root: '/',
      +//   dir: '/home/user/dir',
      +//   base: 'file.txt',
      +//   ext: '.txt',
      +//   name: 'file' }
      +
      ┌─────────────────────┬────────────â”
      +│          dir        │    base    │
      +├──────┬              ├──────┬─────┤
      +│ root │              │ name │ ext │
      +"  /    home/user/dir / file  .txt "
      +└──────┴──────────────┴──────┴─────┘
      +(All spaces in the "" line should be ignored. They are purely for formatting.)
      +

      On Windows:

      +
      path.parse('C:\\path\\dir\\file.txt');
      +// Returns:
      +// { root: 'C:\\',
      +//   dir: 'C:\\path\\dir',
      +//   base: 'file.txt',
      +//   ext: '.txt',
      +//   name: 'file' }
      +
      ┌─────────────────────┬────────────â”
      +│          dir        │    base    │
      +├──────┬              ├──────┬─────┤
      +│ root │              │ name │ ext │
      +" C:\      path\dir   \ file  .txt "
      +└──────┴──────────────┴──────┴─────┘
      +(All spaces in the "" line should be ignored. They are purely for formatting.)
      +

      A TypeError is thrown if path is not a string.

      +

      path.posix#

      + + +

      The path.posix property provides access to POSIX specific implementations +of the path methods.

      +

      path.relative(from, to)#

      + + +

      The path.relative() method returns the relative path from from to to based +on the current working directory. If from and to each resolve to the same +path (after calling path.resolve() on each), a zero-length string is returned.

      +

      If a zero-length string is passed as from or to, the current working +directory will be used instead of the zero-length strings.

      +

      For example, on POSIX:

      +
      path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
      +// Returns: '../../impl/bbb'
      +

      On Windows:

      +
      path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
      +// Returns: '..\\..\\impl\\bbb'
      +

      A TypeError is thrown if either from or to is not a string.

      +

      path.resolve([...paths])#

      + + +

      The path.resolve() method resolves a sequence of paths or path segments into +an absolute path.

      +

      The given sequence of paths is processed from right to left, with each +subsequent path prepended until an absolute path is constructed. +For instance, given the sequence of path segments: /foo, /bar, baz, +calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz +because 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.

      +

      If, after processing all given path segments, an absolute path has not yet +been generated, the current working directory is used.

      +

      The resulting path is normalized and trailing slashes are removed unless the +path is resolved to the root directory.

      +

      Zero-length path segments are ignored.

      +

      If no path segments are passed, path.resolve() will return the absolute path +of the current working directory.

      +
      path.resolve('/foo/bar', './baz');
      +// Returns: '/foo/bar/baz'
      +
      +path.resolve('/foo/bar', '/tmp/file/');
      +// Returns: '/tmp/file'
      +
      +path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
      +// If the current working directory is /home/myself/node,
      +// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
      +

      A TypeError is thrown if any of the arguments is not a string.

      +

      path.sep#

      + + +

      Provides the platform-specific path segment separator:

      +
        +
      • \ on Windows
      • +
      • / on POSIX
      • +
      +

      For example, on POSIX:

      +
      'foo/bar/baz'.split(path.sep);
      +// Returns: ['foo', 'bar', 'baz']
      +

      On Windows:

      +
      'foo\\bar\\baz'.split(path.sep);
      +// Returns: ['foo', 'bar', 'baz']
      +

      On Windows, both the forward slash (/) and backward slash (\) are accepted +as path segment separators; however, the path methods only add backward +slashes (\).

      +

      path.toNamespacedPath(path)#

      + + +

      On Windows systems only, returns an equivalent namespace-prefixed path for +the given path. If path is not a string, path will be returned without +modifications.

      +

      This method is meaningful only on Windows systems. On POSIX systems, the +method is non-operational and always returns path without modifications.

      +

      path.win32#

      + + +

      The path.win32 property provides access to Windows-specific implementations +of the path methods.

      + +
      +
      +
      + + diff --git a/doc/api/path.json b/doc/api/path.json new file mode 100644 index 0000000000000000000000000000000000000000..af74f7d6d2215d6eec2125ba913032cbfe474a8d --- /dev/null +++ b/doc/api/path.json @@ -0,0 +1,449 @@ +{ + "type": "module", + "source": "doc/api/path.md", + "modules": [ + { + "textRaw": "Path", + "name": "path", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/path.js

      \n

      The path module provides utilities for working with file and directory paths.\nIt can be accessed using:

      \n
      const path = require('path');\n
      ", + "modules": [ + { + "textRaw": "Windows vs. POSIX", + "name": "windows_vs._posix", + "desc": "

      The default operation of the path module varies based on the operating system\non which a Node.js application is running. Specifically, when running on a\nWindows operating system, the path module will assume that Windows-style\npaths are being used.

      \n

      So using path.basename() might yield different results on POSIX and Windows:

      \n

      On POSIX:

      \n
      path.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'C:\\\\temp\\\\myfile.html'\n
      \n

      On Windows:

      \n
      path.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
      \n

      To achieve consistent results when working with Windows file paths on any\noperating system, use path.win32:

      \n

      On POSIX and Windows:

      \n
      path.win32.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
      \n

      To achieve consistent results when working with POSIX file paths on any\noperating system, use path.posix:

      \n

      On POSIX and Windows:

      \n
      path.posix.basename('/tmp/myfile.html');\n// Returns: 'myfile.html'\n
      \n

      On Windows Node.js follows the concept of per-drive working directory.\nThis behavior can be observed when using a drive path without a backslash. For\nexample, path.resolve('C:\\\\') can potentially return a different result than\npath.resolve('C:'). For more information, see\nthis MSDN page.

      ", + "type": "module", + "displayName": "Windows vs. POSIX" + } + ], + "methods": [ + { + "textRaw": "`path.basename(path[, ext])`", + "type": "method", + "name": "basename", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Passing a non-string as the `path` argument will throw now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + }, + { + "textRaw": "`ext` {string} An optional file extension", + "name": "ext", + "type": "string", + "desc": "An optional file extension" + } + ] + } + ], + "desc": "

      The path.basename() method returns the last portion of a path, similar to\nthe Unix basename command. Trailing directory separators are ignored, see\npath.sep.

      \n
      path.basename('/foo/bar/baz/asdf/quux.html');\n// Returns: 'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html');\n// Returns: 'quux'\n
      \n

      Although Windows usually treats file names, including file extensions, in a\ncase-insensitive manner, this function does not. For example, C:\\\\foo.html and\nC:\\\\foo.HTML refer to the same file, but basename treats the extension as a\ncase-sensitive string:

      \n
      path.win32.basename('C:\\\\foo.html', '.html');\n// Returns: 'foo'\n\npath.win32.basename('C:\\\\foo.HTML', '.html');\n// Returns: 'foo.HTML'\n
      \n

      A TypeError is thrown if path is not a string or if ext is given\nand is not a string.

      " + }, + { + "textRaw": "`path.dirname(path)`", + "type": "method", + "name": "dirname", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Passing a non-string as the `path` argument will throw now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.dirname() method returns the directory name of a path, similar to\nthe Unix dirname command. Trailing directory separators are ignored, see\npath.sep.

      \n
      path.dirname('/foo/bar/baz/asdf/quux');\n// Returns: '/foo/bar/baz/asdf'\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.extname(path)`", + "type": "method", + "name": "extname", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5348", + "description": "Passing a non-string as the `path` argument will throw now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.extname() method returns the extension of the path, from the last\noccurrence of the . (period) character to end of string in the last portion of\nthe path. If there is no . in the last portion of the path, or if\nthere are no . characters other than the first character of\nthe basename of path (see path.basename()) , an empty string is returned.

      \n
      path.extname('index.html');\n// Returns: '.html'\n\npath.extname('index.coffee.md');\n// Returns: '.md'\n\npath.extname('index.');\n// Returns: '.'\n\npath.extname('index');\n// Returns: ''\n\npath.extname('.index');\n// Returns: ''\n\npath.extname('.index.md');\n// Returns: '.md'\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.format(pathObject)`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`pathObject` {Object}", + "name": "pathObject", + "type": "Object", + "options": [ + { + "textRaw": "`dir` {string}", + "name": "dir", + "type": "string" + }, + { + "textRaw": "`root` {string}", + "name": "root", + "type": "string" + }, + { + "textRaw": "`base` {string}", + "name": "base", + "type": "string" + }, + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`ext` {string}", + "name": "ext", + "type": "string" + } + ] + } + ] + } + ], + "desc": "

      The path.format() method returns a path string from an object. This is the\nopposite of path.parse().

      \n

      When providing properties to the pathObject remember that there are\ncombinations where one property has priority over another:

      \n
        \n
      • pathObject.root is ignored if pathObject.dir is provided
      • \n
      • pathObject.ext and pathObject.name are ignored if pathObject.base exists
      • \n
      \n

      For example, on POSIX:

      \n
      // If `dir`, `root` and `base` are provided,\n// `${dir}${path.sep}${base}`\n// will be returned. `root` is ignored.\npath.format({\n  root: '/ignored',\n  dir: '/home/user/dir',\n  base: 'file.txt'\n});\n// Returns: '/home/user/dir/file.txt'\n\n// `root` will be used if `dir` is not specified.\n// If only `root` is provided or `dir` is equal to `root` then the\n// platform separator will not be included. `ext` will be ignored.\npath.format({\n  root: '/',\n  base: 'file.txt',\n  ext: 'ignored'\n});\n// Returns: '/file.txt'\n\n// `name` + `ext` will be used if `base` is not specified.\npath.format({\n  root: '/',\n  name: 'file',\n  ext: '.txt'\n});\n// Returns: '/file.txt'\n
      \n

      On Windows:

      \n
      path.format({\n  dir: 'C:\\\\path\\\\dir',\n  base: 'file.txt'\n});\n// Returns: 'C:\\\\path\\\\dir\\\\file.txt'\n
      " + }, + { + "textRaw": "`path.isAbsolute(path)`", + "type": "method", + "name": "isAbsolute", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.isAbsolute() method determines if path is an absolute path.

      \n

      If the given path is a zero-length string, false will be returned.

      \n

      For example, on POSIX:

      \n
      path.isAbsolute('/foo/bar'); // true\npath.isAbsolute('/baz/..');  // true\npath.isAbsolute('qux/');     // false\npath.isAbsolute('.');        // false\n
      \n

      On Windows:

      \n
      path.isAbsolute('//server');    // true\npath.isAbsolute('\\\\\\\\server');  // true\npath.isAbsolute('C:/foo/..');   // true\npath.isAbsolute('C:\\\\foo\\\\..'); // true\npath.isAbsolute('bar\\\\baz');    // false\npath.isAbsolute('bar/baz');     // false\npath.isAbsolute('.');           // false\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.join([...paths])`", + "type": "method", + "name": "join", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`...paths` {string} A sequence of path segments", + "name": "...paths", + "type": "string", + "desc": "A sequence of path segments" + } + ] + } + ], + "desc": "

      The path.join() method joins all given path segments together using the\nplatform-specific separator as a delimiter, then normalizes the resulting path.

      \n

      Zero-length path segments are ignored. If the joined path string is a\nzero-length string then '.' will be returned, representing the current\nworking directory.

      \n
      path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');\n// Returns: '/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar');\n// Throws 'TypeError: Path must be a string. Received {}'\n
      \n

      A TypeError is thrown if any of the path segments is not a string.

      " + }, + { + "textRaw": "`path.normalize(path)`", + "type": "method", + "name": "normalize", + "meta": { + "added": [ + "v0.1.23" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.normalize() method normalizes the given path, resolving '..' and\n'.' segments.

      \n

      When multiple, sequential path segment separation characters are found (e.g.\n/ on POSIX and either \\ or / on Windows), they are replaced by a single\ninstance of the platform-specific path segment separator (/ on POSIX and\n\\ on Windows). Trailing separators are preserved.

      \n

      If the path is a zero-length string, '.' is returned, representing the\ncurrent working directory.

      \n

      For example, on POSIX:

      \n
      path.normalize('/foo/bar//baz/asdf/quux/..');\n// Returns: '/foo/bar/baz/asdf'\n
      \n

      On Windows:

      \n
      path.normalize('C:\\\\temp\\\\\\\\foo\\\\bar\\\\..\\\\');\n// Returns: 'C:\\\\temp\\\\foo\\\\'\n
      \n

      Since Windows recognizes multiple path separators, both separators will be\nreplaced by instances of the Windows preferred separator (\\):

      \n
      path.win32.normalize('C:////temp\\\\\\\\/\\\\/\\\\/foo/bar');\n// Returns: 'C:\\\\temp\\\\foo\\\\bar'\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.parse(path)`", + "type": "method", + "name": "parse", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      The path.parse() method returns an object whose properties represent\nsignificant elements of the path. Trailing directory separators are ignored,\nsee path.sep.

      \n

      The returned object will have the following properties:

      \n\n

      For example, on POSIX:

      \n
      path.parse('/home/user/dir/file.txt');\n// Returns:\n// { root: '/',\n//   dir: '/home/user/dir',\n//   base: 'file.txt',\n//   ext: '.txt',\n//   name: 'file' }\n
      \n
      ┌─────────────────────┬────────────â”\n│          dir        │    base    │\n├──────┬              ├──────┬─────┤\n│ root │              │ name │ ext │\n\"  /    home/user/dir / file  .txt \"\n└──────┴──────────────┴──────┴─────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
      \n

      On Windows:

      \n
      path.parse('C:\\\\path\\\\dir\\\\file.txt');\n// Returns:\n// { root: 'C:\\\\',\n//   dir: 'C:\\\\path\\\\dir',\n//   base: 'file.txt',\n//   ext: '.txt',\n//   name: 'file' }\n
      \n
      ┌─────────────────────┬────────────â”\n│          dir        │    base    │\n├──────┬              ├──────┬─────┤\n│ root │              │ name │ ext │\n\" C:\\      path\\dir   \\ file  .txt \"\n└──────┴──────────────┴──────┴─────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
      \n

      A TypeError is thrown if path is not a string.

      " + }, + { + "textRaw": "`path.relative(from, to)`", + "type": "method", + "name": "relative", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [ + { + "version": "v6.8.0", + "pr-url": "https://github.com/nodejs/node/pull/8523", + "description": "On Windows, the leading slashes for UNC paths are now included in the return value." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`from` {string}", + "name": "from", + "type": "string" + }, + { + "textRaw": "`to` {string}", + "name": "to", + "type": "string" + } + ] + } + ], + "desc": "

      The path.relative() method returns the relative path from from to to based\non the current working directory. If from and to each resolve to the same\npath (after calling path.resolve() on each), a zero-length string is returned.

      \n

      If a zero-length string is passed as from or to, the current working\ndirectory will be used instead of the zero-length strings.

      \n

      For example, on POSIX:

      \n
      path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');\n// Returns: '../../impl/bbb'\n
      \n

      On Windows:

      \n
      path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb');\n// Returns: '..\\\\..\\\\impl\\\\bbb'\n
      \n

      A TypeError is thrown if either from or to is not a string.

      " + }, + { + "textRaw": "`path.resolve([...paths])`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`...paths` {string} A sequence of paths or path segments", + "name": "...paths", + "type": "string", + "desc": "A sequence of paths or path segments" + } + ] + } + ], + "desc": "

      The path.resolve() method resolves a sequence of paths or path segments into\nan absolute path.

      \n

      The given sequence of paths is processed from right to left, with each\nsubsequent path prepended until an absolute path is constructed.\nFor instance, given the sequence of path segments: /foo, /bar, baz,\ncalling path.resolve('/foo', '/bar', 'baz') would return /bar/baz\nbecause 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.

      \n

      If, after processing all given path segments, an absolute path has not yet\nbeen generated, the current working directory is used.

      \n

      The resulting path is normalized and trailing slashes are removed unless the\npath is resolved to the root directory.

      \n

      Zero-length path segments are ignored.

      \n

      If no path segments are passed, path.resolve() will return the absolute path\nof the current working directory.

      \n
      path.resolve('/foo/bar', './baz');\n// Returns: '/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/');\n// Returns: '/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');\n// If the current working directory is /home/myself/node,\n// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'\n
      \n

      A TypeError is thrown if any of the arguments is not a string.

      " + }, + { + "textRaw": "`path.toNamespacedPath(path)`", + "type": "method", + "name": "toNamespacedPath", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`path` {string}", + "name": "path", + "type": "string" + } + ] + } + ], + "desc": "

      On Windows systems only, returns an equivalent namespace-prefixed path for\nthe given path. If path is not a string, path will be returned without\nmodifications.

      \n

      This method is meaningful only on Windows systems. On POSIX systems, the\nmethod is non-operational and always returns path without modifications.

      " + } + ], + "properties": [ + { + "textRaw": "`delimiter` {string}", + "type": "string", + "name": "delimiter", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "desc": "

      Provides the platform-specific path delimiter:

      \n
        \n
      • ; for Windows
      • \n
      • : for POSIX
      • \n
      \n

      For example, on POSIX:

      \n
      console.log(process.env.PATH);\n// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter);\n// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']\n
      \n

      On Windows:

      \n
      console.log(process.env.PATH);\n// Prints: 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\node\\'\n\nprocess.env.PATH.split(path.delimiter);\n// Returns ['C:\\\\Windows\\\\system32', 'C:\\\\Windows', 'C:\\\\Program Files\\\\node\\\\']\n
      " + }, + { + "textRaw": "`posix` {Object}", + "type": "Object", + "name": "posix", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      The path.posix property provides access to POSIX specific implementations\nof the path methods.

      " + }, + { + "textRaw": "`sep` {string}", + "type": "string", + "name": "sep", + "meta": { + "added": [ + "v0.7.9" + ], + "changes": [] + }, + "desc": "

      Provides the platform-specific path segment separator:

      \n
        \n
      • \\ on Windows
      • \n
      • / on POSIX
      • \n
      \n

      For example, on POSIX:

      \n
      'foo/bar/baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n
      \n

      On Windows:

      \n
      'foo\\\\bar\\\\baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n
      \n

      On Windows, both the forward slash (/) and backward slash (\\) are accepted\nas path segment separators; however, the path methods only add backward\nslashes (\\).

      " + }, + { + "textRaw": "`win32` {Object}", + "type": "Object", + "name": "win32", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [] + }, + "desc": "

      The path.win32 property provides access to Windows-specific implementations\nof the path methods.

      " + } + ], + "type": "module", + "displayName": "Path" + } + ] +} \ No newline at end of file diff --git a/doc/api/perf_hooks.html b/doc/api/perf_hooks.html new file mode 100644 index 0000000000000000000000000000000000000000..0d7dcbe648a13fe01670a85afe8f7e48f0e94a52 --- /dev/null +++ b/doc/api/perf_hooks.html @@ -0,0 +1,928 @@ + + + + + + + Performance measurement APIs | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Performance measurement APIs#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/perf_hooks.js

      +

      This module provides an implementation of a subset of the W3C +Web Performance APIs as well as additional APIs for +Node.js-specific performance measurements.

      +

      Node.js supports the following Web Performance APIs:

      + +
      const { PerformanceObserver, performance } = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((items) => {
      +  console.log(items.getEntries()[0].duration);
      +  performance.clearMarks();
      +});
      +obs.observe({ entryTypes: ['measure'] });
      +performance.measure('Start to Now');
      +
      +performance.mark('A');
      +doSomeLongRunningProcess(() => {
      +  performance.measure('A to Now', 'A');
      +
      +  performance.mark('B');
      +  performance.measure('A to B', 'A', 'B');
      +});
      +

      perf_hooks.performance#

      + +

      An object that can be used to collect performance metrics from the current +Node.js instance. It is similar to window.performance in browsers.

      +

      performance.clearMarks([name])#

      + + +

      If name is not provided, removes all PerformanceMark objects from the +Performance Timeline. If name is provided, removes only the named mark.

      +

      performance.eventLoopUtilization([utilization1[, utilization2]])#

      + +
        +
      • utilization1 <Object> The result of a previous call to + eventLoopUtilization().
      • +
      • utilization2 <Object> The result of a previous call to + eventLoopUtilization() prior to utilization1.
      • +
      • Returns <Object> + +
      • +
      +

      The eventLoopUtilization() method returns an object that contains the +cumulative duration of time the event loop has been both idle and active as a +high resolution milliseconds timer. The utilization value is the calculated +Event Loop Utilization (ELU).

      +

      If bootstrapping has not yet finished on the main thread the properties have +the value of 0. The ELU is immediately available on Worker threads since +bootstrap happens within the event loop.

      +

      Both utilization1 and utilization2 are optional parameters.

      +

      If utilization1 is passed, then the delta between the current call's active +and idle times, as well as the corresponding utilization value are +calculated and returned (similar to process.hrtime()).

      +

      If utilization1 and utilization2 are both passed, then the delta is +calculated between the two arguments. This is a convenience option because, +unlike process.hrtime(), calculating the ELU is more complex than a +single subtraction.

      +

      ELU is similar to CPU utilization, except that it only measures event loop +statistics and not CPU usage. It represents the percentage of time the event +loop has spent outside the event loop's event provider (e.g. epoll_wait). +No other CPU idle time is taken into consideration. The following is an example +of how a mostly idle process will have a high ELU.

      +
      'use strict';
      +const { eventLoopUtilization } = require('perf_hooks').performance;
      +const { spawnSync } = require('child_process');
      +
      +setImmediate(() => {
      +  const elu = eventLoopUtilization();
      +  spawnSync('sleep', ['5']);
      +  console.log(eventLoopUtilization(elu).utilization);
      +});
      +

      Although the CPU is mostly idle while running this script, the value of +utilization is 1. This is because the call to +child_process.spawnSync() blocks the event loop from proceeding.

      +

      Passing in a user-defined object instead of the result of a previous call to +eventLoopUtilization() will lead to undefined behavior. The return values +are not guaranteed to reflect any correct state of the event loop.

      +

      performance.mark([name])#

      + + +

      Creates a new PerformanceMark entry in the Performance Timeline. A +PerformanceMark is a subclass of PerformanceEntry whose +performanceEntry.entryType is always 'mark', and whose +performanceEntry.duration is always 0. Performance marks are used +to mark specific significant moments in the Performance Timeline.

      +

      performance.measure(name[, startMark[, endMark]])#

      + + +

      Creates a new PerformanceMeasure entry in the Performance Timeline. A +PerformanceMeasure is a subclass of PerformanceEntry whose +performanceEntry.entryType is always 'measure', and whose +performanceEntry.duration measures the number of milliseconds elapsed since +startMark and endMark.

      +

      The startMark argument may identify any existing PerformanceMark in the +Performance Timeline, or may identify any of the timestamp properties +provided by the PerformanceNodeTiming class. If the named startMark does +not exist, then startMark is set to timeOrigin by default.

      +

      The optional endMark argument must identify any existing PerformanceMark +in the Performance Timeline or any of the timestamp properties provided by the +PerformanceNodeTiming class. endMark will be performance.now() +if no parameter is passed, otherwise if the named endMark does not exist, an +error will be thrown.

      +

      performance.nodeTiming#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      An instance of the PerformanceNodeTiming class that provides performance +metrics for specific Node.js operational milestones.

      +

      performance.now()#

      + + +

      Returns the current high resolution millisecond timestamp, where 0 represents +the start of the current node process.

      +

      performance.timeOrigin#

      + + +

      The timeOrigin specifies the high resolution millisecond timestamp at +which the current node process began, measured in Unix time.

      +

      performance.timerify(fn)#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      Wraps a function within a new function that measures the running time of the +wrapped function. A PerformanceObserver must be subscribed to the 'function' +event type in order for the timing details to be accessed.

      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +function someFunction() {
      +  console.log('hello world');
      +}
      +
      +const wrapped = performance.timerify(someFunction);
      +
      +const obs = new PerformanceObserver((list) => {
      +  console.log(list.getEntries()[0].duration);
      +  obs.disconnect();
      +});
      +obs.observe({ entryTypes: ['function'] });
      +
      +// A performance timeline entry will be created
      +wrapped();
      +

      performance.eventLoopUtilization([util1][,util2])#

      + +
        +
      • util1 <Object> The result of a previous call to eventLoopUtilization()
      • +
      • util2 <Object> The result of a previous call to eventLoopUtilization() +prior to util1
      • +
      • Returns <Object> + +
      • +
      +

      The eventLoopUtilization() method returns an object that contains the +cumulative duration of time the event loop has been both idle and active as a +high resolution milliseconds timer. The utilization value is the calculated +Event Loop Utilization (ELU). If bootstrapping has not yet finished, the +properties have the value of 0.

      +

      util1 and util2 are optional parameters.

      +

      If util1 is passed then the delta between the current call's active and +idle times are calculated and returned (similar to process.hrtime()). +Likewise the adjusted utilization value is calculated.

      +

      If util1 and util2 are both passed then the calculation adjustments are +done between the two arguments. This is a convenience option because unlike +process.hrtime() additional work is done to calculate the ELU.

      +

      ELU is similar to CPU utilization except that it is calculated using high +precision wall-clock time. It represents the percentage of time the event loop +has spent outside the event loop's event provider (e.g. epoll_wait). No other +CPU idle time is taken into consideration. The following is an example of how +a mostly idle process will have a high ELU.

      + +
      'use strict';
      +const { eventLoopUtilization } = require('perf_hooks').performance;
      +const { spawnSync } = require('child_process');
      +
      +setImmediate(() => {
      +  const elu = eventLoopUtilization();
      +  spawnSync('sleep', ['5']);
      +  console.log(eventLoopUtilization(elu).utilization);
      +});
      +

      Although the CPU is mostly idle while running this script, the value of +utilization is 1. This is because the call to child_process.spawnSync() +blocks the event loop from proceeding.

      +

      Passing in a user-defined object instead of the result of a previous call to +eventLoopUtilization() will lead to undefined behavior. The return values +are not guaranteed to reflect any correct state of the event loop.

      +

      Class: PerformanceEntry#

      + +

      performanceEntry.duration#

      + + +

      The total number of milliseconds elapsed for this entry. This value will not +be meaningful for all Performance Entry types.

      +

      performanceEntry.name#

      + + +

      The name of the performance entry.

      +

      performanceEntry.startTime#

      + + +

      The high resolution millisecond timestamp marking the starting time of the +Performance Entry.

      +

      performanceEntry.entryType#

      + + +

      The type of the performance entry. It may be one of:

      +
        +
      • 'node' (Node.js only)
      • +
      • 'mark' (available on the Web)
      • +
      • 'measure' (available on the Web)
      • +
      • 'gc' (Node.js only)
      • +
      • 'function' (Node.js only)
      • +
      • 'http2' (Node.js only)
      • +
      • 'http' (Node.js only)
      • +
      +

      performanceEntry.kind#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      When performanceEntry.entryType is equal to 'gc', the performance.kind +property identifies the type of garbage collection operation that occurred. +The value may be one of:

      +
        +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
      • +
      +

      performanceEntry.flags#

      + + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      When performanceEntry.entryType is equal to 'gc', the performance.flags +property contains additional information about garbage collection operation. +The value may be one of:

      +
        +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
      • +
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
      • +
      +

      Class: PerformanceNodeTiming extends PerformanceEntry#

      + +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      Provides timing details for Node.js itself. The constructor of this class +is not exposed to users.

      +

      performanceNodeTiming.bootstrapComplete#

      + + +

      The high resolution millisecond timestamp at which the Node.js process +completed bootstrapping. If bootstrapping has not yet finished, the property +has the value of -1.

      +

      performanceNodeTiming.environment#

      + + +

      The high resolution millisecond timestamp at which the Node.js environment was +initialized.

      +

      performanceNodeTiming.loopExit#

      + + +

      The high resolution millisecond timestamp at which the Node.js event loop +exited. If the event loop has not yet exited, the property has the value of -1. +It can only have a value of not -1 in a handler of the 'exit' event.

      +

      performanceNodeTiming.loopStart#

      + + +

      The high resolution millisecond timestamp at which the Node.js event loop +started. If the event loop has not yet started (e.g., in the first tick of the +main script), the property has the value of -1.

      +

      performanceNodeTiming.nodeStart#

      + + +

      The high resolution millisecond timestamp at which the Node.js process was +initialized.

      +

      performanceNodeTiming.v8Start#

      + + +

      The high resolution millisecond timestamp at which the V8 platform was +initialized.

      +

      performanceNodeTiming.idleTime#

      + + +

      The high resolution millisecond timestamp of the amount of time the event loop +has been idle within the event loop's event provider (e.g. epoll_wait). This +does not take CPU usage into consideration. If the event loop has not yet +started (e.g., in the first tick of the main script), the property has the +value of 0.

      +

      Class: perf_hooks.PerformanceObserver#

      +

      new PerformanceObserver(callback)#

      + + +

      PerformanceObserver objects provide notifications when new +PerformanceEntry instances have been added to the Performance Timeline.

      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  console.log(list.getEntries());
      +  observer.disconnect();
      +});
      +obs.observe({ entryTypes: ['mark'], buffered: true });
      +
      +performance.mark('test');
      +

      Because PerformanceObserver instances introduce their own additional +performance overhead, instances should not be left subscribed to notifications +indefinitely. Users should disconnect observers as soon as they are no +longer needed.

      +

      The callback is invoked when a PerformanceObserver is +notified about new PerformanceEntry instances. The callback receives a +PerformanceObserverEntryList instance and a reference to the +PerformanceObserver.

      +

      performanceObserver.disconnect()#

      + +

      Disconnects the PerformanceObserver instance from all notifications.

      +

      performanceObserver.observe(options)#

      + +
        +
      • options <Object> +
          +
        • entryTypes <string[]> An array of strings identifying the types of +PerformanceEntry instances the observer is interested in. If not +provided an error will be thrown.
        • +
        • buffered <boolean> If true, the notification callback will be +called using setImmediate() and multiple PerformanceEntry instance +notifications will be buffered internally. If false, notifications will +be immediate and synchronous. Default: false.
        • +
        +
      • +
      +

      Subscribes the PerformanceObserver instance to notifications of new +PerformanceEntry instances identified by options.entryTypes.

      +

      When options.buffered is false, the callback will be invoked once for +every PerformanceEntry instance:

      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  // Called three times synchronously. `list` contains one item.
      +});
      +obs.observe({ entryTypes: ['mark'] });
      +
      +for (let n = 0; n < 3; n++)
      +  performance.mark(`test${n}`);
      +
      const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  // Called once. `list` contains three items.
      +});
      +obs.observe({ entryTypes: ['mark'], buffered: true });
      +
      +for (let n = 0; n < 3; n++)
      +  performance.mark(`test${n}`);
      +

      Class: PerformanceObserverEntryList#

      + +

      The PerformanceObserverEntryList class is used to provide access to the +PerformanceEntry instances passed to a PerformanceObserver. +The constructor of this class is not exposed to users.

      +

      performanceObserverEntryList.getEntries()#

      + + +

      Returns a list of PerformanceEntry objects in chronological order +with respect to performanceEntry.startTime.

      +

      performanceObserverEntryList.getEntriesByName(name[, type])#

      + + +

      Returns a list of PerformanceEntry objects in chronological order +with respect to performanceEntry.startTime whose performanceEntry.name is +equal to name, and optionally, whose performanceEntry.entryType is equal to +type.

      +

      performanceObserverEntryList.getEntriesByType(type)#

      + + +

      Returns a list of PerformanceEntry objects in chronological order +with respect to performanceEntry.startTime whose performanceEntry.entryType +is equal to type.

      +

      perf_hooks.monitorEventLoopDelay([options])#

      + +
        +
      • options <Object> +
          +
        • resolution <number> The sampling rate in milliseconds. Must be greater +than zero. Default: 10.
        • +
        +
      • +
      • Returns: <Histogram>
      • +
      +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      Creates a Histogram object that samples and reports the event loop delay +over time. The delays will be reported in nanoseconds.

      +

      Using a timer to detect approximate event loop delay works because the +execution of timers is tied specifically to the lifecycle of the libuv +event loop. That is, a delay in the loop will cause a delay in the execution +of the timer, and those delays are specifically what this API is intended to +detect.

      +
      const { monitorEventLoopDelay } = require('perf_hooks');
      +const h = monitorEventLoopDelay({ resolution: 20 });
      +h.enable();
      +// Do something.
      +h.disable();
      +console.log(h.min);
      +console.log(h.max);
      +console.log(h.mean);
      +console.log(h.stddev);
      +console.log(h.percentiles);
      +console.log(h.percentile(50));
      +console.log(h.percentile(99));
      +

      Class: Histogram#

      + +

      Tracks the event loop delay at a given sampling rate. The constructor of +this class not exposed to users.

      +

      This property is an extension by Node.js. It is not available in Web browsers.

      +

      histogram.disable()#

      + + +

      Disables the event loop delay sample timer. Returns true if the timer was +stopped, false if it was already stopped.

      +

      histogram.enable()#

      + + +

      Enables the event loop delay sample timer. Returns true if the timer was +started, false if it was already started.

      +

      histogram.exceeds#

      + + +

      The number of times the event loop delay exceeded the maximum 1 hour event +loop delay threshold.

      +

      histogram.max#

      + + +

      The maximum recorded event loop delay.

      +

      histogram.mean#

      + + +

      The mean of the recorded event loop delays.

      +

      histogram.min#

      + + +

      The minimum recorded event loop delay.

      +

      histogram.percentile(percentile)#

      + +
        +
      • percentile <number> A percentile value between 1 and 100.
      • +
      • Returns: <number>
      • +
      +

      Returns the value at the given percentile.

      +

      histogram.percentiles#

      + + +

      Returns a Map object detailing the accumulated percentile distribution.

      +

      histogram.reset()#

      + +

      Resets the collected histogram data.

      +

      histogram.stddev#

      + + +

      The standard deviation of the recorded event loop delays.

      +

      Examples#

      +

      Measuring the duration of async operations#

      +

      The following example uses the Async Hooks and Performance APIs to measure +the actual duration of a Timeout operation (including the amount of time it took +to execute the callback).

      +
      'use strict';
      +const async_hooks = require('async_hooks');
      +const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +
      +const set = new Set();
      +const hook = async_hooks.createHook({
      +  init(id, type) {
      +    if (type === 'Timeout') {
      +      performance.mark(`Timeout-${id}-Init`);
      +      set.add(id);
      +    }
      +  },
      +  destroy(id) {
      +    if (set.has(id)) {
      +      set.delete(id);
      +      performance.mark(`Timeout-${id}-Destroy`);
      +      performance.measure(`Timeout-${id}`,
      +                          `Timeout-${id}-Init`,
      +                          `Timeout-${id}-Destroy`);
      +    }
      +  }
      +});
      +hook.enable();
      +
      +const obs = new PerformanceObserver((list, observer) => {
      +  console.log(list.getEntries()[0]);
      +  performance.clearMarks();
      +  observer.disconnect();
      +});
      +obs.observe({ entryTypes: ['measure'], buffered: true });
      +
      +setTimeout(() => {}, 1000);
      +

      Measuring how long it takes to load dependencies#

      +

      The following example measures the duration of require() operations to load +dependencies:

      + +
      'use strict';
      +const {
      +  performance,
      +  PerformanceObserver
      +} = require('perf_hooks');
      +const mod = require('module');
      +
      +// Monkey patch the require function
      +mod.Module.prototype.require =
      +  performance.timerify(mod.Module.prototype.require);
      +require = performance.timerify(require);
      +
      +// Activate the observer
      +const obs = new PerformanceObserver((list) => {
      +  const entries = list.getEntries();
      +  entries.forEach((entry) => {
      +    console.log(`require('${entry[0]}')`, entry.duration);
      +  });
      +  obs.disconnect();
      +});
      +obs.observe({ entryTypes: ['function'], buffered: true });
      +
      +require('some-module');
      + +
      +
      +
      + + diff --git a/doc/api/perf_hooks.json b/doc/api/perf_hooks.json new file mode 100644 index 0000000000000000000000000000000000000000..6d8ff70ac1889a1d4f88364eccd41c18111a3341 --- /dev/null +++ b/doc/api/perf_hooks.json @@ -0,0 +1,897 @@ +{ + "type": "module", + "source": "doc/api/perf_hooks.md", + "modules": [ + { + "textRaw": "Performance measurement APIs", + "name": "performance_measurement_apis", + "introduced_in": "v8.5.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/perf_hooks.js

      \n

      This module provides an implementation of a subset of the W3C\nWeb Performance APIs as well as additional APIs for\nNode.js-specific performance measurements.

      \n

      Node.js supports the following Web Performance APIs:

      \n\n
      const { PerformanceObserver, performance } = require('perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n  console.log(items.getEntries()[0].duration);\n  performance.clearMarks();\n});\nobs.observe({ entryTypes: ['measure'] });\nperformance.measure('Start to Now');\n\nperformance.mark('A');\ndoSomeLongRunningProcess(() => {\n  performance.measure('A to Now', 'A');\n\n  performance.mark('B');\n  performance.measure('A to B', 'A', 'B');\n});\n
      ", + "properties": [ + { + "textRaw": "`perf_hooks.performance`", + "name": "performance", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      An object that can be used to collect performance metrics from the current\nNode.js instance. It is similar to window.performance in browsers.

      ", + "methods": [ + { + "textRaw": "`performance.clearMarks([name])`", + "type": "method", + "name": "clearMarks", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      If name is not provided, removes all PerformanceMark objects from the\nPerformance Timeline. If name is provided, removes only the named mark.

      " + }, + { + "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", + "type": "method", + "name": "eventLoopUtilization", + "meta": { + "added": [ + "v14.10.0", + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`idle` {number}", + "name": "idle", + "type": "number" + }, + { + "textRaw": "`active` {number}", + "name": "active", + "type": "number" + }, + { + "textRaw": "`utilization` {number}", + "name": "utilization", + "type": "number" + } + ] + }, + "params": [ + { + "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", + "name": "utilization1", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()`." + }, + { + "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", + "name": "utilization2", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." + } + ] + } + ], + "desc": "

      The eventLoopUtilization() method returns an object that contains the\ncumulative duration of time the event loop has been both idle and active as a\nhigh resolution milliseconds timer. The utilization value is the calculated\nEvent Loop Utilization (ELU).

      \n

      If bootstrapping has not yet finished on the main thread the properties have\nthe value of 0. The ELU is immediately available on Worker threads since\nbootstrap happens within the event loop.

      \n

      Both utilization1 and utilization2 are optional parameters.

      \n

      If utilization1 is passed, then the delta between the current call's active\nand idle times, as well as the corresponding utilization value are\ncalculated and returned (similar to process.hrtime()).

      \n

      If utilization1 and utilization2 are both passed, then the delta is\ncalculated between the two arguments. This is a convenience option because,\nunlike process.hrtime(), calculating the ELU is more complex than a\nsingle subtraction.

      \n

      ELU is similar to CPU utilization, except that it only measures event loop\nstatistics and not CPU usage. It represents the percentage of time the event\nloop has spent outside the event loop's event provider (e.g. epoll_wait).\nNo other CPU idle time is taken into consideration. The following is an example\nof how a mostly idle process will have a high ELU.

      \n
      'use strict';\nconst { eventLoopUtilization } = require('perf_hooks').performance;\nconst { spawnSync } = require('child_process');\n\nsetImmediate(() => {\n  const elu = eventLoopUtilization();\n  spawnSync('sleep', ['5']);\n  console.log(eventLoopUtilization(elu).utilization);\n});\n
      \n

      Although the CPU is mostly idle while running this script, the value of\nutilization is 1. This is because the call to\nchild_process.spawnSync() blocks the event loop from proceeding.

      \n

      Passing in a user-defined object instead of the result of a previous call to\neventLoopUtilization() will lead to undefined behavior. The return values\nare not guaranteed to reflect any correct state of the event loop.

      " + }, + { + "textRaw": "`performance.mark([name])`", + "type": "method", + "name": "mark", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Creates a new PerformanceMark entry in the Performance Timeline. A\nPerformanceMark is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'mark', and whose\nperformanceEntry.duration is always 0. Performance marks are used\nto mark specific significant moments in the Performance Timeline.

      " + }, + { + "textRaw": "`performance.measure(name[, startMark[, endMark]])`", + "type": "method", + "name": "measure", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [ + { + "version": "v12.16.3", + "pr-url": "https://github.com/nodejs/node/pull/32651", + "description": "Make `startMark` and `endMark` parameters optional." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`startMark` {string} Optional.", + "name": "startMark", + "type": "string", + "desc": "Optional." + }, + { + "textRaw": "`endMark` {string} Optional.", + "name": "endMark", + "type": "string", + "desc": "Optional." + } + ] + } + ], + "desc": "

      Creates a new PerformanceMeasure entry in the Performance Timeline. A\nPerformanceMeasure is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'measure', and whose\nperformanceEntry.duration measures the number of milliseconds elapsed since\nstartMark and endMark.

      \n

      The startMark argument may identify any existing PerformanceMark in the\nPerformance Timeline, or may identify any of the timestamp properties\nprovided by the PerformanceNodeTiming class. If the named startMark does\nnot exist, then startMark is set to timeOrigin by default.

      \n

      The optional endMark argument must identify any existing PerformanceMark\nin the Performance Timeline or any of the timestamp properties provided by the\nPerformanceNodeTiming class. endMark will be performance.now()\nif no parameter is passed, otherwise if the named endMark does not exist, an\nerror will be thrown.

      " + }, + { + "textRaw": "`performance.now()`", + "type": "method", + "name": "now", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [] + } + ], + "desc": "

      Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node process.

      " + }, + { + "textRaw": "`performance.timerify(fn)`", + "type": "method", + "name": "timerify", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function}", + "name": "fn", + "type": "Function" + } + ] + } + ], + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      Wraps a function within a new function that measures the running time of the\nwrapped function. A PerformanceObserver must be subscribed to the 'function'\nevent type in order for the timing details to be accessed.

      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nfunction someFunction() {\n  console.log('hello world');\n}\n\nconst wrapped = performance.timerify(someFunction);\n\nconst obs = new PerformanceObserver((list) => {\n  console.log(list.getEntries()[0].duration);\n  obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n
      " + }, + { + "textRaw": "`performance.eventLoopUtilization([util1][,util2])`", + "type": "method", + "name": "eventLoopUtilization", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`idle` {number}", + "name": "idle", + "type": "number" + }, + { + "textRaw": "`active` {number}", + "name": "active", + "type": "number" + }, + { + "textRaw": "`utilization` {number}", + "name": "utilization", + "type": "number" + } + ] + }, + "params": [ + { + "textRaw": "`util1` {Object} The result of a previous call to `eventLoopUtilization()`", + "name": "util1", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()`" + }, + { + "textRaw": "`util2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `util1`", + "name": "util2", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()` prior to `util1`" + } + ] + } + ], + "desc": "

      The eventLoopUtilization() method returns an object that contains the\ncumulative duration of time the event loop has been both idle and active as a\nhigh resolution milliseconds timer. The utilization value is the calculated\nEvent Loop Utilization (ELU). If bootstrapping has not yet finished, the\nproperties have the value of 0.

      \n

      util1 and util2 are optional parameters.

      \n

      If util1 is passed then the delta between the current call's active and\nidle times are calculated and returned (similar to process.hrtime()).\nLikewise the adjusted utilization value is calculated.

      \n

      If util1 and util2 are both passed then the calculation adjustments are\ndone between the two arguments. This is a convenience option because unlike\nprocess.hrtime() additional work is done to calculate the ELU.

      \n

      ELU is similar to CPU utilization except that it is calculated using high\nprecision wall-clock time. It represents the percentage of time the event loop\nhas spent outside the event loop's event provider (e.g. epoll_wait). No other\nCPU idle time is taken into consideration. The following is an example of how\na mostly idle process will have a high ELU.

      \n\n
      'use strict';\nconst { eventLoopUtilization } = require('perf_hooks').performance;\nconst { spawnSync } = require('child_process');\n\nsetImmediate(() => {\n  const elu = eventLoopUtilization();\n  spawnSync('sleep', ['5']);\n  console.log(eventLoopUtilization(elu).utilization);\n});\n
      \n

      Although the CPU is mostly idle while running this script, the value of\nutilization is 1. This is because the call to child_process.spawnSync()\nblocks the event loop from proceeding.

      \n

      Passing in a user-defined object instead of the result of a previous call to\neventLoopUtilization() will lead to undefined behavior. The return values\nare not guaranteed to reflect any correct state of the event loop.

      " + } + ], + "properties": [ + { + "textRaw": "`nodeTiming` {PerformanceNodeTiming}", + "type": "PerformanceNodeTiming", + "name": "nodeTiming", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      An instance of the PerformanceNodeTiming class that provides performance\nmetrics for specific Node.js operational milestones.

      " + }, + { + "textRaw": "`timeOrigin` {number}", + "type": "number", + "name": "timeOrigin", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The timeOrigin specifies the high resolution millisecond timestamp at\nwhich the current node process began, measured in Unix time.

      " + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: `PerformanceEntry`", + "type": "class", + "name": "PerformanceEntry", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "properties": [ + { + "textRaw": "`duration` {number}", + "type": "number", + "name": "duration", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.

      " + }, + { + "textRaw": "`name` {string}", + "type": "string", + "name": "name", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The name of the performance entry.

      " + }, + { + "textRaw": "`startTime` {number}", + "type": "number", + "name": "startTime", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp marking the starting time of the\nPerformance Entry.

      " + }, + { + "textRaw": "`entryType` {string}", + "type": "string", + "name": "entryType", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The type of the performance entry. It may be one of:

      \n
        \n
      • 'node' (Node.js only)
      • \n
      • 'mark' (available on the Web)
      • \n
      • 'measure' (available on the Web)
      • \n
      • 'gc' (Node.js only)
      • \n
      • 'function' (Node.js only)
      • \n
      • 'http2' (Node.js only)
      • \n
      • 'http' (Node.js only)
      • \n
      " + }, + { + "textRaw": "`kind` {number}", + "type": "number", + "name": "kind", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      When performanceEntry.entryType is equal to 'gc', the performance.kind\nproperty identifies the type of garbage collection operation that occurred.\nThe value may be one of:

      \n
        \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
      • \n
      " + }, + { + "textRaw": "`flags` {number}", + "type": "number", + "name": "flags", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      When performanceEntry.entryType is equal to 'gc', the performance.flags\nproperty contains additional information about garbage collection operation.\nThe value may be one of:

      \n
        \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
      • \n
      • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
      • \n
      " + } + ] + }, + { + "textRaw": "Class: `PerformanceNodeTiming extends PerformanceEntry`", + "type": "class", + "name": "PerformanceNodeTiming", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      Provides timing details for Node.js itself. The constructor of this class\nis not exposed to users.

      ", + "properties": [ + { + "textRaw": "`bootstrapComplete` {number}", + "type": "number", + "name": "bootstrapComplete", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js process\ncompleted bootstrapping. If bootstrapping has not yet finished, the property\nhas the value of -1.

      " + }, + { + "textRaw": "`environment` {number}", + "type": "number", + "name": "environment", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js environment was\ninitialized.

      " + }, + { + "textRaw": "`loopExit` {number}", + "type": "number", + "name": "loopExit", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js event loop\nexited. If the event loop has not yet exited, the property has the value of -1.\nIt can only have a value of not -1 in a handler of the 'exit' event.

      " + }, + { + "textRaw": "`loopStart` {number}", + "type": "number", + "name": "loopStart", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js event loop\nstarted. If the event loop has not yet started (e.g., in the first tick of the\nmain script), the property has the value of -1.

      " + }, + { + "textRaw": "`nodeStart` {number}", + "type": "number", + "name": "nodeStart", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the Node.js process was\ninitialized.

      " + }, + { + "textRaw": "`v8Start` {number}", + "type": "number", + "name": "v8Start", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp at which the V8 platform was\ninitialized.

      " + }, + { + "textRaw": "`idleTime` {number}", + "type": "number", + "name": "idleTime", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "desc": "

      The high resolution millisecond timestamp of the amount of time the event loop\nhas been idle within the event loop's event provider (e.g. epoll_wait). This\ndoes not take CPU usage into consideration. If the event loop has not yet\nstarted (e.g., in the first tick of the main script), the property has the\nvalue of 0.

      " + } + ] + }, + { + "textRaw": "Class: `perf_hooks.PerformanceObserver`", + "type": "class", + "name": "perf_hooks.PerformanceObserver", + "methods": [ + { + "textRaw": "`performanceObserver.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disconnects the PerformanceObserver instance from all notifications.

      " + }, + { + "textRaw": "`performanceObserver.observe(options)`", + "type": "method", + "name": "observe", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`entryTypes` {string[]} An array of strings identifying the types of `PerformanceEntry` instances the observer is interested in. If not provided an error will be thrown.", + "name": "entryTypes", + "type": "string[]", + "desc": "An array of strings identifying the types of `PerformanceEntry` instances the observer is interested in. If not provided an error will be thrown." + }, + { + "textRaw": "`buffered` {boolean} If true, the notification callback will be called using `setImmediate()` and multiple `PerformanceEntry` instance notifications will be buffered internally. If `false`, notifications will be immediate and synchronous. **Default:** `false`.", + "name": "buffered", + "type": "boolean", + "default": "`false`", + "desc": "If true, the notification callback will be called using `setImmediate()` and multiple `PerformanceEntry` instance notifications will be buffered internally. If `false`, notifications will be immediate and synchronous." + } + ] + } + ] + } + ], + "desc": "

      Subscribes the PerformanceObserver instance to notifications of new\nPerformanceEntry instances identified by options.entryTypes.

      \n

      When options.buffered is false, the callback will be invoked once for\nevery PerformanceEntry instance:

      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  // Called three times synchronously. `list` contains one item.\n});\nobs.observe({ entryTypes: ['mark'] });\n\nfor (let n = 0; n < 3; n++)\n  performance.mark(`test${n}`);\n
      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  // Called once. `list` contains three items.\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nfor (let n = 0; n < 3; n++)\n  performance.mark(`test${n}`);\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function", + "options": [ + { + "textRaw": "`list` {PerformanceObserverEntryList}", + "name": "list", + "type": "PerformanceObserverEntryList" + }, + { + "textRaw": "`observer` {PerformanceObserver}", + "name": "observer", + "type": "PerformanceObserver" + } + ] + } + ], + "desc": "

      PerformanceObserver objects provide notifications when new\nPerformanceEntry instances have been added to the Performance Timeline.

      \n
      const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  console.log(list.getEntries());\n  observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nperformance.mark('test');\n
      \n

      Because PerformanceObserver instances introduce their own additional\nperformance overhead, instances should not be left subscribed to notifications\nindefinitely. Users should disconnect observers as soon as they are no\nlonger needed.

      \n

      The callback is invoked when a PerformanceObserver is\nnotified about new PerformanceEntry instances. The callback receives a\nPerformanceObserverEntryList instance and a reference to the\nPerformanceObserver.

      " + } + ] + }, + { + "textRaw": "Class: `PerformanceObserverEntryList`", + "type": "class", + "name": "PerformanceObserverEntryList", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "desc": "

      The PerformanceObserverEntryList class is used to provide access to the\nPerformanceEntry instances passed to a PerformanceObserver.\nThe constructor of this class is not exposed to users.

      ", + "methods": [ + { + "textRaw": "`performanceObserverEntryList.getEntries()`", + "type": "method", + "name": "getEntries", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {PerformanceEntry[]}", + "name": "return", + "type": "PerformanceEntry[]" + }, + "params": [] + } + ], + "desc": "

      Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime.

      " + }, + { + "textRaw": "`performanceObserverEntryList.getEntriesByName(name[, type])`", + "type": "method", + "name": "getEntriesByName", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {PerformanceEntry[]}", + "name": "return", + "type": "PerformanceEntry[]" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + } + ] + } + ], + "desc": "

      Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.name is\nequal to name, and optionally, whose performanceEntry.entryType is equal to\ntype.

      " + }, + { + "textRaw": "`performanceObserverEntryList.getEntriesByType(type)`", + "type": "method", + "name": "getEntriesByType", + "meta": { + "added": [ + "v8.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {PerformanceEntry[]}", + "name": "return", + "type": "PerformanceEntry[]" + }, + "params": [ + { + "textRaw": "`type` {string}", + "name": "type", + "type": "string" + } + ] + } + ], + "desc": "

      Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.entryType\nis equal to type.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`perf_hooks.monitorEventLoopDelay([options])`", + "type": "method", + "name": "monitorEventLoopDelay", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Histogram}", + "name": "return", + "type": "Histogram" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`resolution` {number} The sampling rate in milliseconds. Must be greater than zero. **Default:** `10`.", + "name": "resolution", + "type": "number", + "default": "`10`", + "desc": "The sampling rate in milliseconds. Must be greater than zero." + } + ] + } + ] + } + ], + "desc": "

      This property is an extension by Node.js. It is not available in Web browsers.

      \n

      Creates a Histogram object that samples and reports the event loop delay\nover time. The delays will be reported in nanoseconds.

      \n

      Using a timer to detect approximate event loop delay works because the\nexecution of timers is tied specifically to the lifecycle of the libuv\nevent loop. That is, a delay in the loop will cause a delay in the execution\nof the timer, and those delays are specifically what this API is intended to\ndetect.

      \n
      const { monitorEventLoopDelay } = require('perf_hooks');\nconst h = monitorEventLoopDelay({ resolution: 20 });\nh.enable();\n// Do something.\nh.disable();\nconsole.log(h.min);\nconsole.log(h.max);\nconsole.log(h.mean);\nconsole.log(h.stddev);\nconsole.log(h.percentiles);\nconsole.log(h.percentile(50));\nconsole.log(h.percentile(99));\n
      ", + "classes": [ + { + "textRaw": "Class: `Histogram`", + "type": "class", + "name": "Histogram", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      Tracks the event loop delay at a given sampling rate. The constructor of\nthis class not exposed to users.

      \n

      This property is an extension by Node.js. It is not available in Web browsers.

      ", + "methods": [ + { + "textRaw": "`histogram.disable()`", + "type": "method", + "name": "disable", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Disables the event loop delay sample timer. Returns true if the timer was\nstopped, false if it was already stopped.

      " + }, + { + "textRaw": "`histogram.enable()`", + "type": "method", + "name": "enable", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Enables the event loop delay sample timer. Returns true if the timer was\nstarted, false if it was already started.

      " + }, + { + "textRaw": "`histogram.percentile(percentile)`", + "type": "method", + "name": "percentile", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`percentile` {number} A percentile value between 1 and 100.", + "name": "percentile", + "type": "number", + "desc": "A percentile value between 1 and 100." + } + ] + } + ], + "desc": "

      Returns the value at the given percentile.

      " + }, + { + "textRaw": "`histogram.reset()`", + "type": "method", + "name": "reset", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Resets the collected histogram data.

      " + } + ], + "properties": [ + { + "textRaw": "`exceeds` {number}", + "type": "number", + "name": "exceeds", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.

      " + }, + { + "textRaw": "`max` {number}", + "type": "number", + "name": "max", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The maximum recorded event loop delay.

      " + }, + { + "textRaw": "`mean` {number}", + "type": "number", + "name": "mean", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The mean of the recorded event loop delays.

      " + }, + { + "textRaw": "`min` {number}", + "type": "number", + "name": "min", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The minimum recorded event loop delay.

      " + }, + { + "textRaw": "`percentiles` {Map}", + "type": "Map", + "name": "percentiles", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      Returns a Map object detailing the accumulated percentile distribution.

      " + }, + { + "textRaw": "`stddev` {number}", + "type": "number", + "name": "stddev", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "desc": "

      The standard deviation of the recorded event loop delays.

      \n

      Examples

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Measuring the duration of async operations", + "name": "measuring_the_duration_of_async_operations", + "desc": "

      The following example uses the Async Hooks and Performance APIs to measure\nthe actual duration of a Timeout operation (including the amount of time it took\nto execute the callback).

      \n
      'use strict';\nconst async_hooks = require('async_hooks');\nconst {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst set = new Set();\nconst hook = async_hooks.createHook({\n  init(id, type) {\n    if (type === 'Timeout') {\n      performance.mark(`Timeout-${id}-Init`);\n      set.add(id);\n    }\n  },\n  destroy(id) {\n    if (set.has(id)) {\n      set.delete(id);\n      performance.mark(`Timeout-${id}-Destroy`);\n      performance.measure(`Timeout-${id}`,\n                          `Timeout-${id}-Init`,\n                          `Timeout-${id}-Destroy`);\n    }\n  }\n});\nhook.enable();\n\nconst obs = new PerformanceObserver((list, observer) => {\n  console.log(list.getEntries()[0]);\n  performance.clearMarks();\n  observer.disconnect();\n});\nobs.observe({ entryTypes: ['measure'], buffered: true });\n\nsetTimeout(() => {}, 1000);\n
      ", + "type": "module", + "displayName": "Measuring the duration of async operations" + }, + { + "textRaw": "Measuring how long it takes to load dependencies", + "name": "measuring_how_long_it_takes_to_load_dependencies", + "desc": "

      The following example measures the duration of require() operations to load\ndependencies:

      \n\n
      'use strict';\nconst {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\nconst mod = require('module');\n\n// Monkey patch the require function\nmod.Module.prototype.require =\n  performance.timerify(mod.Module.prototype.require);\nrequire = performance.timerify(require);\n\n// Activate the observer\nconst obs = new PerformanceObserver((list) => {\n  const entries = list.getEntries();\n  entries.forEach((entry) => {\n    console.log(`require('${entry[0]}')`, entry.duration);\n  });\n  obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'], buffered: true });\n\nrequire('some-module');\n
      ", + "type": "module", + "displayName": "Measuring how long it takes to load dependencies" + } + ] + } + ], + "type": "module", + "displayName": "Performance measurement APIs" + } + ] +} \ No newline at end of file diff --git a/doc/api/perf_hooks.md b/doc/api/perf_hooks.md index eb919f109051bbec219a2dba3598706307b655e6..b9ecc848700b0d4be1ce7612a1b9fa05ac112b7b 100644 --- a/doc/api/perf_hooks.md +++ b/doc/api/perf_hooks.md @@ -53,6 +53,68 @@ added: v8.5.0 If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. If `name` is provided, removes only the named mark. +### `performance.eventLoopUtilization([utilization1[, utilization2]])` + + +* `utilization1` {Object} The result of a previous call to + `eventLoopUtilization()`. +* `utilization2` {Object} The result of a previous call to + `eventLoopUtilization()` prior to `utilization1`. +* Returns {Object} + * `idle` {number} + * `active` {number} + * `utilization` {number} + +The `eventLoopUtilization()` method returns an object that contains the +cumulative duration of time the event loop has been both idle and active as a +high resolution milliseconds timer. The `utilization` value is the calculated +Event Loop Utilization (ELU). + +If bootstrapping has not yet finished on the main thread the properties have +the value of `0`. The ELU is immediately available on [Worker threads][] since +bootstrap happens within the event loop. + +Both `utilization1` and `utilization2` are optional parameters. + +If `utilization1` is passed, then the delta between the current call's `active` +and `idle` times, as well as the corresponding `utilization` value are +calculated and returned (similar to [`process.hrtime()`][]). + +If `utilization1` and `utilization2` are both passed, then the delta is +calculated between the two arguments. This is a convenience option because, +unlike [`process.hrtime()`][], calculating the ELU is more complex than a +single subtraction. + +ELU is similar to CPU utilization, except that it only measures event loop +statistics and not CPU usage. It represents the percentage of time the event +loop has spent outside the event loop's event provider (e.g. `epoll_wait`). +No other CPU idle time is taken into consideration. The following is an example +of how a mostly idle process will have a high ELU. + +```js +'use strict'; +const { eventLoopUtilization } = require('perf_hooks').performance; +const { spawnSync } = require('child_process'); + +setImmediate(() => { + const elu = eventLoopUtilization(); + spawnSync('sleep', ['5']); + console.log(eventLoopUtilization(elu).utilization); +}); +``` + +Although the CPU is mostly idle while running this script, the value of +`utilization` is `1`. This is because the call to +[`child_process.spawnSync()`][] blocks the event loop from proceeding. + +Passing in a user-defined object instead of the result of a previous call to +`eventLoopUtilization()` will lead to undefined behavior. The return values +are not guaranteed to reflect any correct state of the event loop. + ### `performance.mark([name])` + + + + + diff --git a/doc/api/policy.json b/doc/api/policy.json new file mode 100644 index 0000000000000000000000000000000000000000..6cf2bdfa0fd4e2d0e4c84adb99bf2d8311ad6507 --- /dev/null +++ b/doc/api/policy.json @@ -0,0 +1,55 @@ +{ + "type": "module", + "source": "doc/api/policy.md", + "introduced_in": "v11.8.0", + "stability": 1, + "stabilityText": "Experimental", + "miscs": [ + { + "textRaw": "Policies", + "name": "policy", + "introduced_in": "v11.8.0", + "type": "misc", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Node.js contains experimental support for creating policies on loading code.

      \n

      Policies are a security feature intended to allow guarantees\nabout what code Node.js is able to load. The use of policies assumes\nsafe practices for the policy files such as ensuring that policy\nfiles cannot be overwritten by the Node.js application by using\nfile permissions.

      \n

      A best practice would be to ensure that the policy manifest is read only for\nthe running Node.js application, and that the file cannot be changed\nby the running Node.js application in any way. A typical setup would be to\ncreate the policy file as a different user id than the one running Node.js\nand granting read permissions to the user id running Node.js.

      ", + "miscs": [ + { + "textRaw": "Enabling", + "name": "Enabling", + "type": "misc", + "desc": "

      The --experimental-policy flag can be used to enable features for policies\nwhen loading modules.

      \n

      Once this has been set, all modules must conform to a policy manifest file\npassed to the flag:

      \n
      node --experimental-policy=policy.json app.js\n
      \n

      The policy manifest will be used to enforce constraints on code loaded by\nNode.js.

      \n

      To mitigate tampering with policy files on disk, an integrity for\nthe policy file itself may be provided via --policy-integrity.\nThis allows running node and asserting the policy file contents\neven if the file is changed on disk.

      \n
      node --experimental-policy=policy.json --policy-integrity=\"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\" app.js\n
      " + }, + { + "textRaw": "Features", + "name": "features", + "modules": [ + { + "textRaw": "Error behavior", + "name": "error_behavior", + "desc": "

      When a policy check fails, Node.js by default will throw an error.\nIt is possible to change the error behavior to one of a few possibilities\nby defining an \"onerror\" field in a policy manifest. The following values are\navailable to change the behavior:

      \n
        \n
      • \"exit\": will exit the process immediately.\nNo cleanup code will be allowed to run.
      • \n
      • \"log\": will log the error at the site of the failure.
      • \n
      • \"throw\": will throw a JS error at the site of the failure. This is the\ndefault.
      • \n
      \n
      {\n  \"onerror\": \"log\",\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
      ", + "type": "module", + "displayName": "Error behavior" + }, + { + "textRaw": "Integrity checks", + "name": "integrity_checks", + "desc": "

      Policy files must use integrity checks with Subresource Integrity strings\ncompatible with the browser\nintegrity attribute\nassociated with absolute URLs.

      \n

      When using require() all resources involved in loading are checked for\nintegrity if a policy manifest has been specified. If a resource does not match\nthe integrity listed in the manifest, an error will be thrown.

      \n

      An example policy file that would allow loading a file checked.js:

      \n
      {\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
      \n

      Each resource listed in the policy manifest can be of one the following\nformats to determine its location:

      \n
        \n
      1. A relative url string to a resource from the manifest such as ./resource.js, ../resource.js, or /resource.js.
      2. \n
      3. A complete url string to a resource such as file:///resource.js.
      4. \n
      \n

      When loading resources the entire URL must match including search parameters\nand hash fragment. ./a.js?b will not be used when attempting to load\n./a.js and vice versa.

      \n

      To generate integrity strings, a script such as\nprintf \"sha384-$(cat checked.js | openssl dgst -sha384 -binary | base64)\"\ncan be used.

      \n

      Integrity can be specified as the boolean value true to accept any\nbody for the resource which can be useful for local development. It is not\nrecommended in production since it would allow unexpected alteration of\nresources to be considered valid.

      ", + "type": "module", + "displayName": "Integrity checks" + }, + { + "textRaw": "Dependency redirection", + "name": "dependency_redirection", + "desc": "

      An application may need to ship patched versions of modules or to prevent\nmodules from allowing all modules access to all other modules. Redirection\ncan be used by intercepting attempts to load the modules wishing to be\nreplaced.

      \n
      {\n  \"builtins\": [],\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"dependencies\": {\n        \"fs\": true,\n        \"os\": \"./app/node_modules/alt-os\"\n      }\n    }\n  }\n}\n
      \n

      The dependencies are keyed by the requested string specifier and have values\nof either true or a string pointing to a module that will be resolved.

      \n

      The specifier string does not perform any searching and must match exactly\nwhat is provided to the require(). Therefore, multiple specifiers may be\nneeded in the policy if require() uses multiple different strings to point\nto the same module (such as excluding the extension).

      \n

      If the value of the redirection is true the default searching algorithms will\nbe used to find the module.

      \n

      If the value of the redirection is a string, it will be resolved relative to\nthe manifest and then immediately be used without searching.

      \n

      Any specifier string that is require()ed and not listed in the dependencies\nwill result in an error according to the policy.

      \n

      Redirection will not prevent access to APIs through means such as direct access\nto require.cache and/or through module.constructor which allow access to\nloading modules. Policy redirection only affect specifiers to require().\nOther means such as to prevent undesired access to APIs through variables are\nnecessary to lock down that path of loading modules.

      \n

      A boolean value of true for the dependencies map can be specified to allow a\nmodule to load any specifier without redirection. This can be useful for local\ndevelopment and may have some valid usage in production, but should be used\nonly with care after auditing a module to ensure its behavior is valid.

      \n

      Example: Patched dependency

      \n

      Redirected dependencies can provide attenuated or modified functionality as fits\nthe application. For example, log data about timing of function durations by\nwrapping the original:

      \n
      const original = require('fn');\nmodule.exports = function fn(...args) {\n  console.time();\n  try {\n    return new.target ?\n      Reflect.construct(original, args) :\n      Reflect.apply(original, this, args);\n  } finally {\n    console.timeEnd();\n  }\n};\n
      ", + "type": "module", + "displayName": "Dependency redirection" + } + ], + "type": "misc", + "displayName": "Features" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/process.html b/doc/api/process.html new file mode 100644 index 0000000000000000000000000000000000000000..ab466d7084a333d5df5f1a120cfd4b14d15d3832 --- /dev/null +++ b/doc/api/process.html @@ -0,0 +1,2395 @@ + + + + + + + Process | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Process#

      + + +

      Source Code: lib/process.js

      +

      The process object is a global that provides information about, and control +over, the current Node.js process. As a global, it is always available to +Node.js applications without using require(). It can also be explicitly +accessed using require():

      +
      const process = require('process');
      +

      Process events#

      +

      The process object is an instance of EventEmitter.

      +

      Event: 'beforeExit'#

      + +

      The 'beforeExit' event is emitted when Node.js empties its event loop and has +no additional work to schedule. Normally, the Node.js process will exit when +there is no work scheduled, but a listener registered on the 'beforeExit' +event can make asynchronous calls, and thereby cause the Node.js process to +continue.

      +

      The listener callback function is invoked with the value of +process.exitCode passed as the only argument.

      +

      The 'beforeExit' event is not emitted for conditions causing explicit +termination, such as calling process.exit() or uncaught exceptions.

      +

      The 'beforeExit' should not be used as an alternative to the 'exit' event +unless the intention is to schedule additional work.

      +
      process.on('beforeExit', (code) => {
      +  console.log('Process beforeExit event with code: ', code);
      +});
      +
      +process.on('exit', (code) => {
      +  console.log('Process exit event with code: ', code);
      +});
      +
      +console.log('This message is displayed first.');
      +
      +// Prints:
      +// This message is displayed first.
      +// Process beforeExit event with code: 0
      +// Process exit event with code: 0
      +

      Event: 'disconnect'#

      + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the 'disconnect' event will be emitted when +the IPC channel is closed.

      +

      Event: 'exit'#

      + + +

      The 'exit' event is emitted when the Node.js process is about to exit as a +result of either:

      +
        +
      • The process.exit() method being called explicitly;
      • +
      • The Node.js event loop no longer having any additional work to perform.
      • +
      +

      There is no way to prevent the exiting of the event loop at this point, and once +all 'exit' listeners have finished running the Node.js process will terminate.

      +

      The listener callback function is invoked with the exit code specified either +by the process.exitCode property, or the exitCode argument passed to the +process.exit() method.

      +
      process.on('exit', (code) => {
      +  console.log(`About to exit with code: ${code}`);
      +});
      +

      Listener functions must only perform synchronous operations. The Node.js +process will exit immediately after calling the 'exit' event listeners +causing any additional work still queued in the event loop to be abandoned. +In the following example, for instance, the timeout will never occur:

      +
      process.on('exit', (code) => {
      +  setTimeout(() => {
      +    console.log('This will not run');
      +  }, 0);
      +});
      +

      Event: 'message'#

      + + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the 'message' event is emitted whenever a +message sent by a parent process using childprocess.send() is received by +the child process.

      +

      The message goes through serialization and parsing. The resulting message might +not be the same as what is originally sent.

      +

      If the serialization option was set to advanced used when spawning the +process, the message argument can contain data that JSON is not able +to represent. +See Advanced serialization for child_process for more details.

      +

      Event: 'multipleResolves'#

      + +
        +
      • type <string> The resolution type. One of 'resolve' or 'reject'.
      • +
      • promise <Promise> The promise that resolved or rejected more than once.
      • +
      • value <any> The value with which the promise was either resolved or +rejected after the original resolve.
      • +
      +

      The 'multipleResolves' event is emitted whenever a Promise has been either:

      +
        +
      • Resolved more than once.
      • +
      • Rejected more than once.
      • +
      • Rejected after resolve.
      • +
      • Resolved after reject.
      • +
      +

      This is useful for tracking potential errors in an application while using the +Promise constructor, as multiple resolutions are silently swallowed. However, +the occurrence of this event does not necessarily indicate an error. For +example, Promise.race() can trigger a 'multipleResolves' event.

      +
      process.on('multipleResolves', (type, promise, reason) => {
      +  console.error(type, promise, reason);
      +  setImmediate(() => process.exit(1));
      +});
      +
      +async function main() {
      +  try {
      +    return await new Promise((resolve, reject) => {
      +      resolve('First call');
      +      resolve('Swallowed resolve');
      +      reject(new Error('Swallowed reject'));
      +    });
      +  } catch {
      +    throw new Error('Failed');
      +  }
      +}
      +
      +main().then(console.log);
      +// resolve: Promise { 'First call' } 'Swallowed resolve'
      +// reject: Promise { 'First call' } Error: Swallowed reject
      +//     at Promise (*)
      +//     at new Promise (<anonymous>)
      +//     at main (*)
      +// First call
      +

      Event: 'rejectionHandled'#

      + +
        +
      • promise <Promise> The late handled promise.
      • +
      +

      The 'rejectionHandled' event is emitted whenever a Promise has been rejected +and an error handler was attached to it (using promise.catch(), for +example) later than one turn of the Node.js event loop.

      +

      The Promise object would have previously been emitted in an +'unhandledRejection' event, but during the course of processing gained a +rejection handler.

      +

      There is no notion of a top level for a Promise chain at which rejections can +always be handled. Being inherently asynchronous in nature, a Promise +rejection can be handled at a future point in time, possibly much later than +the event loop turn it takes for the 'unhandledRejection' event to be emitted.

      +

      Another way of stating this is that, unlike in synchronous code where there is +an ever-growing list of unhandled exceptions, with Promises there can be a +growing-and-shrinking list of unhandled rejections.

      +

      In synchronous code, the 'uncaughtException' event is emitted when the list of +unhandled exceptions grows.

      +

      In asynchronous code, the 'unhandledRejection' event is emitted when the list +of unhandled rejections grows, and the 'rejectionHandled' event is emitted +when the list of unhandled rejections shrinks.

      +
      const unhandledRejections = new Map();
      +process.on('unhandledRejection', (reason, promise) => {
      +  unhandledRejections.set(promise, reason);
      +});
      +process.on('rejectionHandled', (promise) => {
      +  unhandledRejections.delete(promise);
      +});
      +

      In this example, the unhandledRejections Map will grow and shrink over time, +reflecting rejections that start unhandled and then become handled. It is +possible to record such errors in an error log, either periodically (which is +likely best for long-running application) or upon process exit (which is likely +most convenient for scripts).

      +

      Event: 'uncaughtException'#

      + +
        +
      • err <Error> The uncaught exception.
      • +
      • origin <string> Indicates if the exception originates from an unhandled +rejection or from an synchronous error. Can either be 'uncaughtException' or +'unhandledRejection'. The latter is only used in conjunction with the +--unhandled-rejections flag set to strict and an unhandled rejection.
      • +
      +

      The 'uncaughtException' event is emitted when an uncaught JavaScript +exception bubbles all the way back to the event loop. By default, Node.js +handles such exceptions by printing the stack trace to stderr and exiting +with code 1, overriding any previously set process.exitCode. +Adding a handler for the 'uncaughtException' event overrides this default +behavior. Alternatively, change the process.exitCode in the +'uncaughtException' handler which will result in the process exiting with the +provided exit code. Otherwise, in the presence of such handler the process will +exit with 0.

      +
      process.on('uncaughtException', (err, origin) => {
      +  fs.writeSync(
      +    process.stderr.fd,
      +    `Caught exception: ${err}\n` +
      +    `Exception origin: ${origin}`
      +  );
      +});
      +
      +setTimeout(() => {
      +  console.log('This will still run.');
      +}, 500);
      +
      +// Intentionally cause an exception, but don't catch it.
      +nonexistentFunc();
      +console.log('This will not run.');
      +

      It is possible to monitor 'uncaughtException' events without overriding the +default behavior to exit the process by installing a +'uncaughtExceptionMonitor' listener.

      +

      Warning: Using 'uncaughtException' correctly#

      +

      'uncaughtException' is a crude mechanism for exception handling +intended to be used only as a last resort. The event should not be used as +an equivalent to On Error Resume Next. Unhandled exceptions inherently mean +that an application is in an undefined state. Attempting to resume application +code without properly recovering from the exception can cause additional +unforeseen and unpredictable issues.

      +

      Exceptions thrown from within the event handler will not be caught. Instead the +process will exit with a non-zero exit code and the stack trace will be printed. +This is to avoid infinite recursion.

      +

      Attempting to resume normally after an uncaught exception can be similar to +pulling out the power cord when upgrading a computer. Nine out of ten +times, nothing happens. But the tenth time, the system becomes corrupted.

      +

      The correct use of 'uncaughtException' is to perform synchronous cleanup +of allocated resources (e.g. file descriptors, handles, etc) before shutting +down the process. It is not safe to resume normal operation after +'uncaughtException'.

      +

      To restart a crashed application in a more reliable way, whether +'uncaughtException' is emitted or not, an external monitor should be employed +in a separate process to detect application failures and recover or restart as +needed.

      +

      Event: 'uncaughtExceptionMonitor'#

      + +
        +
      • err <Error> The uncaught exception.
      • +
      • origin <string> Indicates if the exception originates from an unhandled +rejection or from synchronous errors. Can either be 'uncaughtException' or +'unhandledRejection'.
      • +
      +

      The 'uncaughtExceptionMonitor' event is emitted before an +'uncaughtException' event is emitted or a hook installed via +process.setUncaughtExceptionCaptureCallback() is called.

      +

      Installing an 'uncaughtExceptionMonitor' listener does not change the behavior +once an 'uncaughtException' event is emitted. The process will +still crash if no 'uncaughtException' listener is installed.

      +
      process.on('uncaughtExceptionMonitor', (err, origin) => {
      +  MyMonitoringTool.logSync(err, origin);
      +});
      +
      +// Intentionally cause an exception, but don't catch it.
      +nonexistentFunc();
      +// Still crashes Node.js
      +

      Event: 'unhandledRejection'#

      + +
        +
      • reason <Error> | <any> The object with which the promise was rejected +(typically an Error object).
      • +
      • promise <Promise> The rejected promise.
      • +
      +

      The 'unhandledRejection' event is emitted whenever a Promise is rejected and +no error handler is attached to the promise within a turn of the event loop. +When programming with Promises, exceptions are encapsulated as "rejected +promises". Rejections can be caught and handled using promise.catch() and +are propagated through a Promise chain. The 'unhandledRejection' event is +useful for detecting and keeping track of promises that were rejected whose +rejections have not yet been handled.

      +
      process.on('unhandledRejection', (reason, promise) => {
      +  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
      +  // Application specific logging, throwing an error, or other logic here
      +});
      +
      +somePromise.then((res) => {
      +  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
      +}); // No `.catch()` or `.then()`
      +

      The following will also trigger the 'unhandledRejection' event to be +emitted:

      +
      function SomeResource() {
      +  // Initially set the loaded status to a rejected promise
      +  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
      +}
      +
      +const resource = new SomeResource();
      +// no .catch or .then on resource.loaded for at least a turn
      +

      In this example case, it is possible to track the rejection as a developer error +as would typically be the case for other 'unhandledRejection' events. To +address such failures, a non-operational +.catch(() => { }) handler may be attached to +resource.loaded, which would prevent the 'unhandledRejection' event from +being emitted.

      +

      Event: 'warning'#

      + +
        +
      • warning <Error> Key properties of the warning are: +
          +
        • name <string> The name of the warning. Default: 'Warning'.
        • +
        • message <string> A system-provided description of the warning.
        • +
        • stack <string> A stack trace to the location in the code where the warning +was issued.
        • +
        +
      • +
      +

      The 'warning' event is emitted whenever Node.js emits a process warning.

      +

      A process warning is similar to an error in that it describes exceptional +conditions that are being brought to the user's attention. However, warnings +are not part of the normal Node.js and JavaScript error handling flow. +Node.js can emit warnings whenever it detects bad coding practices that could +lead to sub-optimal application performance, bugs, or security vulnerabilities.

      +
      process.on('warning', (warning) => {
      +  console.warn(warning.name);    // Print the warning name
      +  console.warn(warning.message); // Print the warning message
      +  console.warn(warning.stack);   // Print the stack trace
      +});
      +

      By default, Node.js will print process warnings to stderr. The --no-warnings +command-line option can be used to suppress the default console output but the +'warning' event will still be emitted by the process object.

      +

      The following example illustrates the warning that is printed to stderr when +too many listeners have been added to an event:

      +
      $ node
      +> events.defaultMaxListeners = 1;
      +> process.on('foo', () => {});
      +> process.on('foo', () => {});
      +> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak
      +detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit
      +

      In contrast, the following example turns off the default warning output and +adds a custom handler to the 'warning' event:

      +
      $ node --no-warnings
      +> const p = process.on('warning', (warning) => console.warn('Do not do that!'));
      +> events.defaultMaxListeners = 1;
      +> process.on('foo', () => {});
      +> process.on('foo', () => {});
      +> Do not do that!
      +

      The --trace-warnings command-line option can be used to have the default +console output for warnings include the full stack trace of the warning.

      +

      Launching Node.js using the --throw-deprecation command line flag will +cause custom deprecation warnings to be thrown as exceptions.

      +

      Using the --trace-deprecation command line flag will cause the custom +deprecation to be printed to stderr along with the stack trace.

      +

      Using the --no-deprecation command line flag will suppress all reporting +of the custom deprecation.

      +

      The *-deprecation command line flags only affect warnings that use the name +'DeprecationWarning'.

      +

      Emitting custom warnings#

      +

      See the process.emitWarning() method for issuing +custom or application-specific warnings.

      +

      Signal events#

      + + +

      Signal events will be emitted when the Node.js process receives a signal. Please +refer to signal(7) for a listing of standard POSIX signal names such as +'SIGINT', 'SIGHUP', etc.

      +

      Signals are not available on Worker threads.

      +

      The signal handler will receive the signal's name ('SIGINT', +'SIGTERM', etc.) as the first argument.

      +

      The name of each event will be the uppercase common name for the signal (e.g. +'SIGINT' for SIGINT signals).

      +
      // Begin reading from stdin so the process does not exit.
      +process.stdin.resume();
      +
      +process.on('SIGINT', () => {
      +  console.log('Received SIGINT. Press Control-D to exit.');
      +});
      +
      +// Using a single function to handle multiple signals
      +function handle(signal) {
      +  console.log(`Received ${signal}`);
      +}
      +
      +process.on('SIGINT', handle);
      +process.on('SIGTERM', handle);
      +
        +
      • 'SIGUSR1' is reserved by Node.js to start the debugger. It's possible to +install a listener but doing so might interfere with the debugger.
      • +
      • 'SIGTERM' and 'SIGINT' have default handlers on non-Windows platforms that +reset the terminal mode before exiting with code 128 + signal number. If one +of these signals has a listener installed, its default behavior will be +removed (Node.js will no longer exit).
      • +
      • 'SIGPIPE' is ignored by default. It can have a listener installed.
      • +
      • 'SIGHUP' is generated on Windows when the console window is closed, and on +other platforms under various similar conditions. See signal(7). It can have a +listener installed, however Node.js will be unconditionally terminated by +Windows about 10 seconds later. On non-Windows platforms, the default +behavior of SIGHUP is to terminate Node.js, but once a listener has been +installed its default behavior will be removed.
      • +
      • 'SIGTERM' is not supported on Windows, it can be listened on.
      • +
      • 'SIGINT' from the terminal is supported on all platforms, and can usually be +generated with Ctrl+C (though this may be configurable). +It is not generated when terminal raw mode is enabled and +Ctrl+C is used.
      • +
      • 'SIGBREAK' is delivered on Windows when Ctrl+Break is +pressed. On non-Windows platforms, it can be listened on, but there is no way +to send or generate it.
      • +
      • 'SIGWINCH' is delivered when the console has been resized. On Windows, this +will only happen on write to the console when the cursor is being moved, or +when a readable tty is used in raw mode.
      • +
      • 'SIGKILL' cannot have a listener installed, it will unconditionally +terminate Node.js on all platforms.
      • +
      • 'SIGSTOP' cannot have a listener installed.
      • +
      • 'SIGBUS', 'SIGFPE', 'SIGSEGV' and 'SIGILL', when not raised + artificially using kill(2), inherently leave the process in a state from + which it is not safe to attempt to call JS listeners. Doing so might lead to + the process hanging in an endless loop, since listeners attached using + process.on() are called asynchronously and therefore unable to correct the +underlying problem.
      • +
      • 0 can be sent to test for the existence of a process, it has no effect if +the process exists, but will throw an error if the process does not exist.
      • +
      +

      Windows does not support signals so has no equivalent to termination by signal, +but Node.js offers some emulation with process.kill(), and +subprocess.kill():

      +
        +
      • Sending SIGINT, SIGTERM, and SIGKILL will cause the unconditional +termination of the target process, and afterwards, subprocess will report that +the process was terminated by signal.
      • +
      • Sending signal 0 can be used as a platform independent way to test for the +existence of a process.
      • +
      +

      process.abort()#

      + +

      The process.abort() method causes the Node.js process to exit immediately and +generate a core file.

      +

      This feature is not available in Worker threads.

      +

      process.allowedNodeEnvironmentFlags#

      + + +

      The process.allowedNodeEnvironmentFlags property is a special, +read-only Set of flags allowable within the NODE_OPTIONS +environment variable.

      +

      process.allowedNodeEnvironmentFlags extends Set, but overrides +Set.prototype.has to recognize several different possible flag +representations. process.allowedNodeEnvironmentFlags.has() will +return true in the following cases:

      +
        +
      • Flags may omit leading single (-) or double (--) dashes; e.g., +inspect-brk for --inspect-brk, or r for -r.
      • +
      • Flags passed through to V8 (as listed in --v8-options) may replace +one or more non-leading dashes for an underscore, or vice-versa; +e.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof, +etc.
      • +
      • Flags may contain one or more equals (=) characters; all +characters after and including the first equals will be ignored; +e.g., --stack-trace-limit=100.
      • +
      • Flags must be allowable within NODE_OPTIONS.
      • +
      +

      When iterating over process.allowedNodeEnvironmentFlags, flags will +appear only once; each will begin with one or more dashes. Flags +passed through to V8 will contain underscores instead of non-leading +dashes:

      +
      process.allowedNodeEnvironmentFlags.forEach((flag) => {
      +  // -r
      +  // --inspect-brk
      +  // --abort_on_uncaught_exception
      +  // ...
      +});
      +

      The methods add(), clear(), and delete() of +process.allowedNodeEnvironmentFlags do nothing, and will fail +silently.

      +

      If Node.js was compiled without NODE_OPTIONS support (shown in +process.config), process.allowedNodeEnvironmentFlags will +contain what would have been allowable.

      +

      process.arch#

      + + +

      The operating system CPU architecture for which the Node.js binary was compiled. +Possible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc', +'ppc64', 's390', 's390x', 'x32', and 'x64'.

      +
      console.log(`This processor architecture is ${process.arch}`);
      +

      process.argv#

      + + +

      The process.argv property returns an array containing the command line +arguments passed when the Node.js process was launched. The first element will +be process.execPath. See process.argv0 if access to the original value +of argv[0] is needed. The second element will be the path to the JavaScript +file being executed. The remaining elements will be any additional command line +arguments.

      +

      For example, assuming the following script for process-args.js:

      +
      // print process.argv
      +process.argv.forEach((val, index) => {
      +  console.log(`${index}: ${val}`);
      +});
      +

      Launching the Node.js process as:

      +
      $ node process-args.js one two=three four
      +

      Would generate the output:

      +
      0: /usr/local/bin/node
      +1: /Users/mjr/work/node/process-args.js
      +2: one
      +3: two=three
      +4: four
      +

      process.argv0#

      + + +

      The process.argv0 property stores a read-only copy of the original value of +argv[0] passed when Node.js starts.

      +
      $ bash -c 'exec -a customArgv0 ./node'
      +> process.argv[0]
      +'/Volumes/code/external/node/out/Release/node'
      +> process.argv0
      +'customArgv0'
      +

      process.channel#

      + + +

      If the Node.js process was spawned with an IPC channel (see the +Child Process documentation), the process.channel +property is a reference to the IPC channel. If no IPC channel exists, this +property is undefined.

      +

      process.chdir(directory)#

      + + +

      The process.chdir() method changes the current working directory of the +Node.js process or throws an exception if doing so fails (for instance, if +the specified directory does not exist).

      +
      console.log(`Starting directory: ${process.cwd()}`);
      +try {
      +  process.chdir('/tmp');
      +  console.log(`New directory: ${process.cwd()}`);
      +} catch (err) {
      +  console.error(`chdir: ${err}`);
      +}
      +

      This feature is not available in Worker threads.

      +

      process.config#

      + + +

      The process.config property returns an Object containing the JavaScript +representation of the configure options used to compile the current Node.js +executable. This is the same as the config.gypi file that was produced when +running the ./configure script.

      +

      An example of the possible output looks like:

      + +
      {
      +  target_defaults:
      +   { cflags: [],
      +     default_configuration: 'Release',
      +     defines: [],
      +     include_dirs: [],
      +     libraries: [] },
      +  variables:
      +   {
      +     host_arch: 'x64',
      +     napi_build_version: 5,
      +     node_install_npm: 'true',
      +     node_prefix: '',
      +     node_shared_cares: 'false',
      +     node_shared_http_parser: 'false',
      +     node_shared_libuv: 'false',
      +     node_shared_zlib: 'false',
      +     node_use_dtrace: 'false',
      +     node_use_openssl: 'true',
      +     node_shared_openssl: 'false',
      +     strict_aliasing: 'true',
      +     target_arch: 'x64',
      +     v8_use_snapshot: 1
      +   }
      +}
      +

      The process.config property is not read-only and there are existing +modules in the ecosystem that are known to extend, modify, or entirely replace +the value of process.config.

      +

      process.connected#

      + + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the process.connected property will return +true so long as the IPC channel is connected and will return false after +process.disconnect() is called.

      +

      Once process.connected is false, it is no longer possible to send messages +over the IPC channel using process.send().

      +

      process.cpuUsage([previousValue])#

      + + +

      The process.cpuUsage() method returns the user and system CPU time usage of +the current process, in an object with properties user and system, whose +values are microsecond values (millionth of a second). These values measure time +spent in user and system code respectively, and may end up being greater than +actual elapsed time if multiple CPU cores are performing work for this process.

      +

      The result of a previous call to process.cpuUsage() can be passed as the +argument to the function, to get a diff reading.

      +
      const startUsage = process.cpuUsage();
      +// { user: 38579, system: 6986 }
      +
      +// spin the CPU for 500 milliseconds
      +const now = Date.now();
      +while (Date.now() - now < 500);
      +
      +console.log(process.cpuUsage(startUsage));
      +// { user: 514883, system: 11226 }
      +

      process.cwd()#

      + + +

      The process.cwd() method returns the current working directory of the Node.js +process.

      +
      console.log(`Current directory: ${process.cwd()}`);
      +

      process.debugPort#

      + + +

      The port used by the Node.js debugger when enabled.

      +
      process.debugPort = 5858;
      +

      process.disconnect()#

      + +

      If the Node.js process is spawned with an IPC channel (see the Child Process +and Cluster documentation), the process.disconnect() method will close the +IPC channel to the parent process, allowing the child process to exit gracefully +once there are no other connections keeping it alive.

      +

      The effect of calling process.disconnect() is the same as calling +ChildProcess.disconnect() from the parent process.

      +

      If the Node.js process was not spawned with an IPC channel, +process.disconnect() will be undefined.

      +

      process.dlopen(module, filename[, flags])#

      + + +

      The process.dlopen() method allows to dynamically load shared +objects. It is primarily used by require() to load +C++ Addons, and should not be used directly, except in special +cases. In other words, require() should be preferred over +process.dlopen(), unless there are specific reasons.

      +

      The flags argument is an integer that allows to specify dlopen +behavior. See the os.constants.dlopen documentation for details.

      +

      If there are specific reasons to use process.dlopen() (for instance, +to specify dlopen flags), it's often useful to use require.resolve() +to look up the module's path.

      +

      An important drawback when calling process.dlopen() is that the module +instance must be passed. Functions exported by the C++ Addon will be accessible +via module.exports.

      +

      The example below shows how to load a C++ Addon, named as binding, +that exports a foo function. All the symbols will be loaded before +the call returns, by passing the RTLD_NOW constant. In this example +the constant is assumed to be available.

      +
      const os = require('os');
      +process.dlopen(module, require.resolve('binding'),
      +               os.constants.dlopen.RTLD_NOW);
      +module.exports.foo();
      +

      process.emitWarning(warning[, options])#

      + +
        +
      • warning <string> | <Error> The warning to emit.
      • +
      • options <Object> +
          +
        • type <string> When warning is a String, type is the name to use +for the type of warning being emitted. Default: 'Warning'.
        • +
        • code <string> A unique identifier for the warning instance being emitted.
        • +
        • ctor <Function> When warning is a String, ctor is an optional +function used to limit the generated stack trace. Default: +process.emitWarning.
        • +
        • detail <string> Additional text to include with the error.
        • +
        +
      • +
      +

      The process.emitWarning() method can be used to emit custom or application +specific process warnings. These can be listened for by adding a handler to the +'warning' event.

      +
      // Emit a warning with a code and additional detail.
      +process.emitWarning('Something happened!', {
      +  code: 'MY_WARNING',
      +  detail: 'This is some additional information'
      +});
      +// Emits:
      +// (node:56338) [MY_WARNING] Warning: Something happened!
      +// This is some additional information
      +

      In this example, an Error object is generated internally by +process.emitWarning() and passed through to the +'warning' handler.

      +
      process.on('warning', (warning) => {
      +  console.warn(warning.name);    // 'Warning'
      +  console.warn(warning.message); // 'Something happened!'
      +  console.warn(warning.code);    // 'MY_WARNING'
      +  console.warn(warning.stack);   // Stack trace
      +  console.warn(warning.detail);  // 'This is some additional information'
      +});
      +

      If warning is passed as an Error object, the options argument is ignored.

      +

      process.emitWarning(warning[, type[, code]][, ctor])#

      + +
        +
      • warning <string> | <Error> The warning to emit.
      • +
      • type <string> When warning is a String, type is the name to use +for the type of warning being emitted. Default: 'Warning'.
      • +
      • code <string> A unique identifier for the warning instance being emitted.
      • +
      • ctor <Function> When warning is a String, ctor is an optional +function used to limit the generated stack trace. Default: +process.emitWarning.
      • +
      +

      The process.emitWarning() method can be used to emit custom or application +specific process warnings. These can be listened for by adding a handler to the +'warning' event.

      +
      // Emit a warning using a string.
      +process.emitWarning('Something happened!');
      +// Emits: (node: 56338) Warning: Something happened!
      +
      // Emit a warning using a string and a type.
      +process.emitWarning('Something Happened!', 'CustomWarning');
      +// Emits: (node:56338) CustomWarning: Something Happened!
      +
      process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
      +// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
      +

      In each of the previous examples, an Error object is generated internally by +process.emitWarning() and passed through to the 'warning' +handler.

      +
      process.on('warning', (warning) => {
      +  console.warn(warning.name);
      +  console.warn(warning.message);
      +  console.warn(warning.code);
      +  console.warn(warning.stack);
      +});
      +

      If warning is passed as an Error object, it will be passed through to the +'warning' event handler unmodified (and the optional type, +code and ctor arguments will be ignored):

      +
      // Emit a warning using an Error object.
      +const myWarning = new Error('Something happened!');
      +// Use the Error name property to specify the type name
      +myWarning.name = 'CustomWarning';
      +myWarning.code = 'WARN001';
      +
      +process.emitWarning(myWarning);
      +// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
      +

      A TypeError is thrown if warning is anything other than a string or Error +object.

      +

      While process warnings use Error objects, the process warning +mechanism is not a replacement for normal error handling mechanisms.

      +

      The following additional handling is implemented if the warning type is +'DeprecationWarning':

      +
        +
      • If the --throw-deprecation command-line flag is used, the deprecation +warning is thrown as an exception rather than being emitted as an event.
      • +
      • If the --no-deprecation command-line flag is used, the deprecation +warning is suppressed.
      • +
      • If the --trace-deprecation command-line flag is used, the deprecation +warning is printed to stderr along with the full stack trace.
      • +
      +

      Avoiding duplicate warnings#

      +

      As a best practice, warnings should be emitted only once per process. To do +so, it is recommended to place the emitWarning() behind a simple boolean +flag as illustrated in the example below:

      +
      function emitMyWarning() {
      +  if (!emitMyWarning.warned) {
      +    emitMyWarning.warned = true;
      +    process.emitWarning('Only warn once!');
      +  }
      +}
      +emitMyWarning();
      +// Emits: (node: 56339) Warning: Only warn once!
      +emitMyWarning();
      +// Emits nothing
      +

      process.env#

      + + +

      The process.env property returns an object containing the user environment. +See environ(7).

      +

      An example of this object looks like:

      + +
      {
      +  TERM: 'xterm-256color',
      +  SHELL: '/usr/local/bin/bash',
      +  USER: 'maciej',
      +  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
      +  PWD: '/Users/maciej',
      +  EDITOR: 'vim',
      +  SHLVL: '1',
      +  HOME: '/Users/maciej',
      +  LOGNAME: 'maciej',
      +  _: '/usr/local/bin/node'
      +}
      +

      It is possible to modify this object, but such modifications will not be +reflected outside the Node.js process, or (unless explicitly requested) +to other Worker threads. +In other words, the following example would not work:

      +
      $ node -e 'process.env.foo = "bar"' && echo $foo
      +

      While the following will:

      +
      process.env.foo = 'bar';
      +console.log(process.env.foo);
      +

      Assigning a property on process.env will implicitly convert the value +to a string. This behavior is deprecated. Future versions of Node.js may +throw an error when the value is not a string, number, or boolean.

      +
      process.env.test = null;
      +console.log(process.env.test);
      +// => 'null'
      +process.env.test = undefined;
      +console.log(process.env.test);
      +// => 'undefined'
      +

      Use delete to delete a property from process.env.

      +
      process.env.TEST = 1;
      +delete process.env.TEST;
      +console.log(process.env.TEST);
      +// => undefined
      +

      On Windows operating systems, environment variables are case-insensitive.

      +
      process.env.TEST = 1;
      +console.log(process.env.test);
      +// => 1
      +

      Unless explicitly specified when creating a Worker instance, +each Worker thread has its own copy of process.env, based on its +parent thread’s process.env, or whatever was specified as the env option +to the Worker constructor. Changes to process.env will not be visible +across Worker threads, and only the main thread can make changes that +are visible to the operating system or to native add-ons.

      +

      process.execArgv#

      + + +

      The process.execArgv property returns the set of Node.js-specific command-line +options passed when the Node.js process was launched. These options do not +appear in the array returned by the process.argv property, and do not +include the Node.js executable, the name of the script, or any options following +the script name. These options are useful in order to spawn child processes with +the same execution environment as the parent.

      +
      $ node --harmony script.js --version
      +

      Results in process.execArgv:

      + +
      ['--harmony']
      +

      And process.argv:

      + +
      ['/usr/local/bin/node', 'script.js', '--version']
      +

      process.execPath#

      + + +

      The process.execPath property returns the absolute pathname of the executable +that started the Node.js process. Symbolic links, if any, are resolved.

      + +
      '/usr/local/bin/node'
      +

      process.exit([code])#

      + +
        +
      • code <integer> The exit code. Default: 0.
      • +
      +

      The process.exit() method instructs Node.js to terminate the process +synchronously with an exit status of code. If code is omitted, exit uses +either the 'success' code 0 or the value of process.exitCode if it has been +set. Node.js will not terminate until all the 'exit' event listeners are +called.

      +

      To exit with a 'failure' code:

      +
      process.exit(1);
      +

      The shell that executed Node.js should see the exit code as 1.

      +

      Calling process.exit() will force the process to exit as quickly as possible +even if there are still asynchronous operations pending that have not yet +completed fully, including I/O operations to process.stdout and +process.stderr.

      +

      In most situations, it is not actually necessary to call process.exit() +explicitly. The Node.js process will exit on its own if there is no additional +work pending in the event loop. The process.exitCode property can be set to +tell the process which exit code to use when the process exits gracefully.

      +

      For instance, the following example illustrates a misuse of the +process.exit() method that could lead to data printed to stdout being +truncated and lost:

      +
      // This is an example of what *not* to do:
      +if (someConditionNotMet()) {
      +  printUsageToStdout();
      +  process.exit(1);
      +}
      +

      The reason this is problematic is because writes to process.stdout in Node.js +are sometimes asynchronous and may occur over multiple ticks of the Node.js +event loop. Calling process.exit(), however, forces the process to exit +before those additional writes to stdout can be performed.

      +

      Rather than calling process.exit() directly, the code should set the +process.exitCode and allow the process to exit naturally by avoiding +scheduling any additional work for the event loop:

      +
      // How to properly set the exit code while letting
      +// the process exit gracefully.
      +if (someConditionNotMet()) {
      +  printUsageToStdout();
      +  process.exitCode = 1;
      +}
      +

      If it is necessary to terminate the Node.js process due to an error condition, +throwing an uncaught error and allowing the process to terminate accordingly +is safer than calling process.exit().

      +

      In Worker threads, this function stops the current thread rather +than the current process.

      +

      process.exitCode#

      + + +

      A number which will be the process exit code, when the process either +exits gracefully, or is exited via process.exit() without specifying +a code.

      +

      Specifying a code to process.exit(code) will override any +previous setting of process.exitCode.

      +

      process.getegid()#

      + +

      The process.getegid() method returns the numerical effective group identity +of the Node.js process. (See getegid(2).)

      +
      if (process.getegid) {
      +  console.log(`Current gid: ${process.getegid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.geteuid()#

      + + +

      The process.geteuid() method returns the numerical effective user identity of +the process. (See geteuid(2).)

      +
      if (process.geteuid) {
      +  console.log(`Current uid: ${process.geteuid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.getgid()#

      + + +

      The process.getgid() method returns the numerical group identity of the +process. (See getgid(2).)

      +
      if (process.getgid) {
      +  console.log(`Current gid: ${process.getgid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.getgroups()#

      + + +

      The process.getgroups() method returns an array with the supplementary group +IDs. POSIX leaves it unspecified if the effective group ID is included but +Node.js ensures it always is.

      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.getuid()#

      + + +

      The process.getuid() method returns the numeric user identity of the process. +(See getuid(2).)

      +
      if (process.getuid) {
      +  console.log(`Current uid: ${process.getuid()}`);
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android).

      +

      process.hasUncaughtExceptionCaptureCallback()#

      + + +

      Indicates whether a callback has been set using +process.setUncaughtExceptionCaptureCallback().

      +

      process.hrtime([time])#

      + + +

      This is the legacy version of process.hrtime.bigint() +before bigint was introduced in JavaScript.

      +

      The process.hrtime() method returns the current high-resolution real time +in a [seconds, nanoseconds] tuple Array, where nanoseconds is the +remaining part of the real time that can't be represented in second precision.

      +

      time is an optional parameter that must be the result of a previous +process.hrtime() call to diff with the current time. If the parameter +passed in is not a tuple Array, a TypeError will be thrown. Passing in a +user-defined array instead of the result of a previous call to +process.hrtime() will lead to undefined behavior.

      +

      These times are relative to an arbitrary time in the +past, and not related to the time of day and therefore not subject to clock +drift. The primary use is for measuring performance between intervals:

      +
      const NS_PER_SEC = 1e9;
      +const time = process.hrtime();
      +// [ 1800216, 25 ]
      +
      +setTimeout(() => {
      +  const diff = process.hrtime(time);
      +  // [ 1, 552 ]
      +
      +  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
      +  // Benchmark took 1000000552 nanoseconds
      +}, 1000);
      +

      process.hrtime.bigint()#

      + + +

      The bigint version of the process.hrtime() method returning the +current high-resolution real time in nanoseconds as a bigint.

      +

      Unlike process.hrtime(), it does not support an additional time +argument since the difference can just be computed directly +by subtraction of the two bigints.

      +
      const start = process.hrtime.bigint();
      +// 191051479007711n
      +
      +setTimeout(() => {
      +  const end = process.hrtime.bigint();
      +  // 191052633396993n
      +
      +  console.log(`Benchmark took ${end - start} nanoseconds`);
      +  // Benchmark took 1154389282 nanoseconds
      +}, 1000);
      +

      process.initgroups(user, extraGroup)#

      + + +

      The process.initgroups() method reads the /etc/group file and initializes +the group access list, using all groups of which the user is a member. This is +a privileged operation that requires that the Node.js process either have root +access or the CAP_SETGID capability.

      +

      Use care when dropping privileges:

      +
      console.log(process.getgroups());         // [ 0 ]
      +process.initgroups('nodeuser', 1000);     // switch user
      +console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
      +process.setgid(1000);                     // drop root gid
      +console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.kill(pid[, signal])#

      + +
        +
      • pid <number> A process ID
      • +
      • signal <string> | <number> The signal to send, either as a string or number. +Default: 'SIGTERM'.
      • +
      +

      The process.kill() method sends the signal to the process identified by +pid.

      +

      Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events +and kill(2) for more information.

      +

      This method will throw an error if the target pid does not exist. As a special +case, a signal of 0 can be used to test for the existence of a process. +Windows platforms will throw an error if the pid is used to kill a process +group.

      +

      Even though the name of this function is process.kill(), it is really just a +signal sender, like the kill system call. The signal sent may do something +other than kill the target process.

      +
      process.on('SIGHUP', () => {
      +  console.log('Got SIGHUP signal.');
      +});
      +
      +setTimeout(() => {
      +  console.log('Exiting.');
      +  process.exit(0);
      +}, 100);
      +
      +process.kill(process.pid, 'SIGHUP');
      +

      When SIGUSR1 is received by a Node.js process, Node.js will start the +debugger. See Signal Events.

      +

      process.mainModule#

      + + +

      The process.mainModule property provides an alternative way of retrieving +require.main. The difference is that if the main module changes at +runtime, require.main may still refer to the original main module in +modules that were required before the change occurred. Generally, it's +safe to assume that the two refer to the same module.

      +

      As with require.main, process.mainModule will be undefined if there +is no entry script.

      +

      process.memoryUsage()#

      + + +

      The process.memoryUsage() method returns an object describing the memory usage +of the Node.js process measured in bytes.

      +

      For example, the code:

      +
      console.log(process.memoryUsage());
      +

      Will generate:

      + +
      {
      +  rss: 4935680,
      +  heapTotal: 1826816,
      +  heapUsed: 650472,
      +  external: 49879,
      +  arrayBuffers: 9386
      +}
      +
        +
      • heapTotal and heapUsed refer to V8's memory usage.
      • +
      • external refers to the memory usage of C++ objects bound to JavaScript +objects managed by V8.
      • +
      • rss, Resident Set Size, is the amount of space occupied in the main +memory device (that is a subset of the total allocated memory) for the +process, including all C++ and JavaScript objects and code.
      • +
      • arrayBuffers refers to memory allocated for ArrayBuffers and +SharedArrayBuffers, including all Node.js Buffers. +This is also included in the external value. When Node.js is used as an +embedded library, this value may be 0 because allocations for ArrayBuffers +may not be tracked in that case.
      • +
      +

      When using Worker threads, rss will be a value that is valid for the +entire process, while the other fields will only refer to the current thread.

      +

      process.nextTick(callback[, ...args])#

      + +
        +
      • callback <Function>
      • +
      • ...args <any> Additional arguments to pass when invoking the callback
      • +
      +

      process.nextTick() adds callback to the "next tick queue". This queue is +fully drained after the current operation on the JavaScript stack runs to +completion and before the event loop is allowed to continue. It's possible to +create an infinite loop if one were to recursively call process.nextTick(). +See the Event Loop guide for more background.

      +
      console.log('start');
      +process.nextTick(() => {
      +  console.log('nextTick callback');
      +});
      +console.log('scheduled');
      +// Output:
      +// start
      +// scheduled
      +// nextTick callback
      +

      This is important when developing APIs in order to give users the opportunity +to assign event handlers after an object has been constructed but before any +I/O has occurred:

      +
      function MyThing(options) {
      +  this.setupOptions(options);
      +
      +  process.nextTick(() => {
      +    this.startDoingStuff();
      +  });
      +}
      +
      +const thing = new MyThing();
      +thing.getReadyForStuff();
      +
      +// thing.startDoingStuff() gets called now, not before.
      +

      It is very important for APIs to be either 100% synchronous or 100% +asynchronous. Consider this example:

      +
      // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
      +function maybeSync(arg, cb) {
      +  if (arg) {
      +    cb();
      +    return;
      +  }
      +
      +  fs.stat('file', cb);
      +}
      +

      This API is hazardous because in the following case:

      +
      const maybeTrue = Math.random() > 0.5;
      +
      +maybeSync(maybeTrue, () => {
      +  foo();
      +});
      +
      +bar();
      +

      It is not clear whether foo() or bar() will be called first.

      +

      The following approach is much better:

      +
      function definitelyAsync(arg, cb) {
      +  if (arg) {
      +    process.nextTick(cb);
      +    return;
      +  }
      +
      +  fs.stat('file', cb);
      +}
      +

      process.noDeprecation#

      + + +

      The process.noDeprecation property indicates whether the --no-deprecation +flag is set on the current Node.js process. See the documentation for +the 'warning' event and the +emitWarning() method for more information about this +flag's behavior.

      +

      process.pid#

      + + +

      The process.pid property returns the PID of the process.

      +
      console.log(`This process is pid ${process.pid}`);
      +

      process.platform#

      + + +

      The process.platform property returns a string identifying the operating +system platform on which the Node.js process is running.

      +

      Currently possible values are:

      +
        +
      • 'aix'
      • +
      • 'darwin'
      • +
      • 'freebsd'
      • +
      • 'linux'
      • +
      • 'openbsd'
      • +
      • 'sunos'
      • +
      • 'win32'
      • +
      +
      console.log(`This platform is ${process.platform}`);
      +

      The value 'android' may also be returned if the Node.js is built on the +Android operating system. However, Android support in Node.js +is experimental.

      +

      process.ppid#

      + + +

      The process.ppid property returns the PID of the parent of the +current process.

      +
      console.log(`The parent process is pid ${process.ppid}`);
      +

      process.release#

      + + +

      The process.release property returns an Object containing metadata related +to the current release, including URLs for the source tarball and headers-only +tarball.

      +

      process.release contains the following properties:

      +
        +
      • name <string> A value that will always be 'node' for Node.js. For +legacy io.js releases, this will be 'io.js'.
      • +
      • sourceUrl <string> an absolute URL pointing to a .tar.gz file containing +the source code of the current release.
      • +
      • headersUrl<string> an absolute URL pointing to a .tar.gz file containing +only the source header files for the current release. This file is +significantly smaller than the full source file and can be used for compiling +Node.js native add-ons.
      • +
      • libUrl <string> an absolute URL pointing to a node.lib file matching the +architecture and version of the current release. This file is used for +compiling Node.js native add-ons. This property is only present on Windows +builds of Node.js and will be missing on all other platforms.
      • +
      • lts <string> a string label identifying the LTS label for this release. +This property only exists for LTS releases and is undefined for all other +release types, including Current releases. +Valid values include the LTS Release Codenames (including those +that are no longer supported). A non-exhaustive example of +these codenames includes: +
          +
        • 'Dubnium' for the 10.x LTS line beginning with 10.13.0.
        • +
        • 'Erbium' for the 12.x LTS line beginning with 12.13.0. +For other LTS Release Codenames, see Node.js Changelog Archive
        • +
        +
      • +
      + +
      {
      +  name: 'node',
      +  lts: 'Erbium',
      +  sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz',
      +  headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz',
      +  libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib'
      +}
      +

      In custom builds from non-release versions of the source tree, only the +name property may be present. The additional properties should not be +relied upon to exist.

      +

      process.report#

      + + +

      process.report is an object whose methods are used to generate diagnostic +reports for the current process. Additional documentation is available in the +report documentation.

      +

      process.report.compact#

      + + +

      Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption.

      +
      console.log(`Reports are compact? ${process.report.compact}`);
      +

      process.report.directory#

      + + +

      Directory where the report is written. The default value is the empty string, +indicating that reports are written to the current working directory of the +Node.js process.

      +
      console.log(`Report directory is ${process.report.directory}`);
      +

      process.report.filename#

      + + +

      Filename where the report is written. If set to the empty string, the output +filename will be comprised of a timestamp, PID, and sequence number. The default +value is the empty string.

      +
      console.log(`Report filename is ${process.report.filename}`);
      +

      process.report.getReport([err])#

      + +
        +
      • err <Error> A custom error used for reporting the JavaScript stack.
      • +
      • Returns: <Object>
      • +
      +

      Returns a JavaScript Object representation of a diagnostic report for the +running process. The report's JavaScript stack trace is taken from err, if +present.

      +
      const data = process.report.getReport();
      +console.log(data.header.nodeJsVersion);
      +
      +// Similar to process.report.writeReport()
      +const fs = require('fs');
      +fs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8');
      +

      Additional documentation is available in the report documentation.

      +

      process.report.reportOnFatalError#

      + +

      Stability: 1 - Experimental

      + +

      If true, a diagnostic report is generated on fatal errors, such as out of +memory errors or failed C++ assertions.

      +
      console.log(`Report on fatal error: ${process.report.reportOnFatalError}`);
      +

      process.report.reportOnSignal#

      + + +

      If true, a diagnostic report is generated when the process receives the +signal specified by process.report.signal.

      +
      console.log(`Report on signal: ${process.report.reportOnSignal}`);
      +

      process.report.reportOnUncaughtException#

      + + +

      If true, a diagnostic report is generated on uncaught exception.

      +
      console.log(`Report on exception: ${process.report.reportOnUncaughtException}`);
      +

      process.report.signal#

      + + +

      The signal used to trigger the creation of a diagnostic report. Defaults to +'SIGUSR2'.

      +
      console.log(`Report signal: ${process.report.signal}`);
      +

      process.report.writeReport([filename][, err])#

      + +
        +
      • +

        filename <string> Name of the file where the report is written. This +should be a relative path, that will be appended to the directory specified in +process.report.directory, or the current working directory of the Node.js +process, if unspecified.

        +
      • +
      • +

        err <Error> A custom error used for reporting the JavaScript stack.

        +
      • +
      • +

        Returns: <string> Returns the filename of the generated report.

        +
      • +
      +

      Writes a diagnostic report to a file. If filename is not provided, the default +filename includes the date, time, PID, and a sequence number. The report's +JavaScript stack trace is taken from err, if present.

      +
      process.report.writeReport();
      +

      Additional documentation is available in the report documentation.

      +

      process.resourceUsage()#

      + +
        +
      • Returns: <Object> the resource usage for the current process. All of these +values come from the uv_getrusage call which returns +a uv_rusage_t struct. +
          +
        • userCPUTime <integer> maps to ru_utime computed in microseconds. +It is the same value as process.cpuUsage().user.
        • +
        • systemCPUTime <integer> maps to ru_stime computed in microseconds. +It is the same value as process.cpuUsage().system.
        • +
        • maxRSS <integer> maps to ru_maxrss which is the maximum resident set +size used in kilobytes.
        • +
        • sharedMemorySize <integer> maps to ru_ixrss but is not supported by +any platform.
        • +
        • unsharedDataSize <integer> maps to ru_idrss but is not supported by +any platform.
        • +
        • unsharedStackSize <integer> maps to ru_isrss but is not supported by +any platform.
        • +
        • minorPageFault <integer> maps to ru_minflt which is the number of +minor page faults for the process, see +this article for more details.
        • +
        • majorPageFault <integer> maps to ru_majflt which is the number of +major page faults for the process, see +this article for more details. This field is not +supported on Windows.
        • +
        • swappedOut <integer> maps to ru_nswap but is not supported by any +platform.
        • +
        • fsRead <integer> maps to ru_inblock which is the number of times the +file system had to perform input.
        • +
        • fsWrite <integer> maps to ru_oublock which is the number of times the +file system had to perform output.
        • +
        • ipcSent <integer> maps to ru_msgsnd but is not supported by any +platform.
        • +
        • ipcReceived <integer> maps to ru_msgrcv but is not supported by any +platform.
        • +
        • signalsCount <integer> maps to ru_nsignals but is not supported by any +platform.
        • +
        • voluntaryContextSwitches <integer> maps to ru_nvcsw which is the +number of times a CPU context switch resulted due to a process voluntarily +giving up the processor before its time slice was completed (usually to +await availability of a resource). This field is not supported on Windows.
        • +
        • involuntaryContextSwitches <integer> maps to ru_nivcsw which is the +number of times a CPU context switch resulted due to a higher priority +process becoming runnable or because the current process exceeded its +time slice. This field is not supported on Windows.
        • +
        +
      • +
      +
      console.log(process.resourceUsage());
      +/*
      +  Will output:
      +  {
      +    userCPUTime: 82872,
      +    systemCPUTime: 4143,
      +    maxRSS: 33164,
      +    sharedMemorySize: 0,
      +    unsharedDataSize: 0,
      +    unsharedStackSize: 0,
      +    minorPageFault: 2469,
      +    majorPageFault: 0,
      +    swappedOut: 0,
      +    fsRead: 0,
      +    fsWrite: 8,
      +    ipcSent: 0,
      +    ipcReceived: 0,
      +    signalsCount: 0,
      +    voluntaryContextSwitches: 79,
      +    involuntaryContextSwitches: 1
      +  }
      +*/
      +

      process.send(message[, sendHandle[, options]][, callback])#

      + +
        +
      • message <Object>
      • +
      • sendHandle <net.Server> | <net.Socket>
      • +
      • options <Object> used to parameterize the sending of certain types of +handles.options supports the following properties: +
          +
        • keepOpen <boolean> A value that can be used when passing instances of +net.Socket. When true, the socket is kept open in the sending process. +Default: false.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <boolean>
      • +
      +

      If Node.js is spawned with an IPC channel, the process.send() method can be +used to send messages to the parent process. Messages will be received as a +'message' event on the parent's ChildProcess object.

      +

      If Node.js was not spawned with an IPC channel, process.send will be +undefined.

      +

      The message goes through serialization and parsing. The resulting message might +not be the same as what is originally sent.

      +

      process.setegid(id)#

      + + +

      The process.setegid() method sets the effective group identity of the process. +(See setegid(2).) The id can be passed as either a numeric ID or a group +name string. If a group name is specified, this method blocks while resolving +the associated a numeric ID.

      +
      if (process.getegid && process.setegid) {
      +  console.log(`Current gid: ${process.getegid()}`);
      +  try {
      +    process.setegid(501);
      +    console.log(`New gid: ${process.getegid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set gid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.seteuid(id)#

      + + +

      The process.seteuid() method sets the effective user identity of the process. +(See seteuid(2).) The id can be passed as either a numeric ID or a username +string. If a username is specified, the method blocks while resolving the +associated numeric ID.

      +
      if (process.geteuid && process.seteuid) {
      +  console.log(`Current uid: ${process.geteuid()}`);
      +  try {
      +    process.seteuid(501);
      +    console.log(`New uid: ${process.geteuid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set uid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setgid(id)#

      + + +

      The process.setgid() method sets the group identity of the process. (See +setgid(2).) The id can be passed as either a numeric ID or a group name +string. If a group name is specified, this method blocks while resolving the +associated numeric ID.

      +
      if (process.getgid && process.setgid) {
      +  console.log(`Current gid: ${process.getgid()}`);
      +  try {
      +    process.setgid(501);
      +    console.log(`New gid: ${process.getgid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set gid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setgroups(groups)#

      + + +

      The process.setgroups() method sets the supplementary group IDs for the +Node.js process. This is a privileged operation that requires the Node.js +process to have root or the CAP_SETGID capability.

      +

      The groups array can contain numeric group IDs, group names or both.

      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setuid(id)#

      + + +

      The process.setuid(id) method sets the user identity of the process. (See +setuid(2).) The id can be passed as either a numeric ID or a username string. +If a username is specified, the method blocks while resolving the associated +numeric ID.

      +
      if (process.getuid && process.setuid) {
      +  console.log(`Current uid: ${process.getuid()}`);
      +  try {
      +    process.setuid(501);
      +    console.log(`New uid: ${process.getuid()}`);
      +  } catch (err) {
      +    console.log(`Failed to set uid: ${err}`);
      +  }
      +}
      +

      This function is only available on POSIX platforms (i.e. not Windows or +Android). +This feature is not available in Worker threads.

      +

      process.setUncaughtExceptionCaptureCallback(fn)#

      + + +

      The process.setUncaughtExceptionCaptureCallback() function sets a function +that will be invoked when an uncaught exception occurs, which will receive the +exception value itself as its first argument.

      +

      If such a function is set, the 'uncaughtException' event will +not be emitted. If --abort-on-uncaught-exception was passed from the +command line or set through v8.setFlagsFromString(), the process will +not abort.

      +

      To unset the capture function, +process.setUncaughtExceptionCaptureCallback(null) may be used. Calling this +method with a non-null argument while another capture function is set will +throw an error.

      +

      Using this function is mutually exclusive with using the deprecated +domain built-in module.

      +

      process.stderr#

      + +

      The process.stderr property returns a stream connected to +stderr (fd 2). It is a net.Socket (which is a Duplex +stream) unless fd 2 refers to a file, in which case it is +a Writable stream.

      +

      process.stderr differs from other Node.js streams in important ways. See +note on process I/O for more information.

      +

      process.stderr.fd#

      + +

      This property refers to the value of underlying file descriptor of +process.stderr. The value is fixed at 2. In Worker threads, +this field does not exist.

      +

      process.stdin#

      + +

      The process.stdin property returns a stream connected to +stdin (fd 0). It is a net.Socket (which is a Duplex +stream) unless fd 0 refers to a file, in which case it is +a Readable stream.

      +

      For details of how to read from stdin see readable.read().

      +

      As a Duplex stream, process.stdin can also be used in "old" mode that +is compatible with scripts written for Node.js prior to v0.10. +For more information see Stream compatibility.

      +

      In "old" streams mode the stdin stream is paused by default, so one +must call process.stdin.resume() to read from it. Note also that calling +process.stdin.resume() itself would switch stream to "old" mode.

      +

      process.stdin.fd#

      + +

      This property refers to the value of underlying file descriptor of +process.stdin. The value is fixed at 0. In Worker threads, +this field does not exist.

      +

      process.stdout#

      + +

      The process.stdout property returns a stream connected to +stdout (fd 1). It is a net.Socket (which is a Duplex +stream) unless fd 1 refers to a file, in which case it is +a Writable stream.

      +

      For example, to copy process.stdin to process.stdout:

      +
      process.stdin.pipe(process.stdout);
      +

      process.stdout differs from other Node.js streams in important ways. See +note on process I/O for more information.

      +

      process.stdout.fd#

      + +

      This property refers to the value of underlying file descriptor of +process.stdout. The value is fixed at 1. In Worker threads, +this field does not exist.

      +

      A note on process I/O#

      +

      process.stdout and process.stderr differ from other Node.js streams in +important ways:

      +
        +
      1. They are used internally by console.log() and console.error(), +respectively.
      2. +
      3. Writes may be synchronous depending on what the stream is connected to +and whether the system is Windows or POSIX: +
          +
        • Files: synchronous on Windows and POSIX
        • +
        • TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
        • +
        • Pipes (and sockets): synchronous on Windows, asynchronous on POSIX
        • +
        +
      4. +
      +

      These behaviors are partly for historical reasons, as changing them would +create backward incompatibility, but they are also expected by some users.

      +

      Synchronous writes avoid problems such as output written with console.log() or +console.error() being unexpectedly interleaved, or not written at all if +process.exit() is called before an asynchronous write completes. See +process.exit() for more information.

      +

      Warning: Synchronous writes block the event loop until the write has +completed. This can be near instantaneous in the case of output to a file, but +under high system load, pipes that are not being read at the receiving end, or +with slow terminals or file systems, its possible for the event loop to be +blocked often enough and long enough to have severe negative performance +impacts. This may not be a problem when writing to an interactive terminal +session, but consider this particularly careful when doing production logging to +the process output streams.

      +

      To check if a stream is connected to a TTY context, check the isTTY +property.

      +

      For instance:

      +
      $ node -p "Boolean(process.stdin.isTTY)"
      +true
      +$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
      +false
      +$ node -p "Boolean(process.stdout.isTTY)"
      +true
      +$ node -p "Boolean(process.stdout.isTTY)" | cat
      +false
      +

      See the TTY documentation for more information.

      +

      process.throwDeprecation#

      + + +

      The initial value of process.throwDeprecation indicates whether the +--throw-deprecation flag is set on the current Node.js process. +process.throwDeprecation is mutable, so whether or not deprecation +warnings result in errors may be altered at runtime. See the +documentation for the 'warning' event and the +emitWarning() method for more information.

      +
      $ node --throw-deprecation -p "process.throwDeprecation"
      +true
      +$ node -p "process.throwDeprecation"
      +undefined
      +$ node
      +> process.emitWarning('test', 'DeprecationWarning');
      +undefined
      +> (node:26598) DeprecationWarning: test
      +> process.throwDeprecation = true;
      +true
      +> process.emitWarning('test', 'DeprecationWarning');
      +Thrown:
      +[DeprecationWarning: test] { name: 'DeprecationWarning' }
      +

      process.title#

      + + +

      The process.title property returns the current process title (i.e. returns +the current value of ps). Assigning a new value to process.title modifies +the current value of ps.

      +

      When a new value is assigned, different platforms will impose different maximum +length restrictions on the title. Usually such restrictions are quite limited. +For instance, on Linux and macOS, process.title is limited to the size of the +binary name plus the length of the command line arguments because setting the +process.title overwrites the argv memory of the process. Node.js v0.8 +allowed for longer process title strings by also overwriting the environ +memory but that was potentially insecure and confusing in some (rather obscure) +cases.

      +

      Assigning a value to process.title might not result in an accurate label +within process manager applications such as macOS Activity Monitor or Windows +Services Manager.

      +

      process.traceDeprecation#

      + + +

      The process.traceDeprecation property indicates whether the +--trace-deprecation flag is set on the current Node.js process. See the +documentation for the 'warning' event and the +emitWarning() method for more information about this +flag's behavior.

      +

      process.umask()#

      + +

      Stability: 0 - Deprecated. Calling process.umask() with no argument causes +the process-wide umask to be written twice. This introduces a race condition +between threads, and is a potential security vulnerability. There is no safe, +cross-platform alternative API.

      +

      process.umask() returns the Node.js process's file mode creation mask. Child +processes inherit the mask from the parent process.

      +

      process.umask(mask)#

      + + +

      process.umask(mask) sets the Node.js process's file mode creation mask. Child +processes inherit the mask from the parent process. Returns the previous mask.

      +
      const newmask = 0o022;
      +const oldmask = process.umask(newmask);
      +console.log(
      +  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
      +);
      +

      In Worker threads, process.umask(mask) will throw an exception.

      +

      process.uptime()#

      + + +

      The process.uptime() method returns the number of seconds the current Node.js +process has been running.

      +

      The return value includes fractions of a second. Use Math.floor() to get whole +seconds.

      +

      process.version#

      + + +

      The process.version property contains the Node.js version string.

      +
      console.log(`Version: ${process.version}`);
      +// Version: v14.8.0
      +

      To get the version string without the prepended v, use +process.versions.node.

      +

      process.versions#

      + + +

      The process.versions property returns an object listing the version strings of +Node.js and its dependencies. process.versions.modules indicates the current +ABI version, which is increased whenever a C++ API changes. Node.js will refuse +to load modules that were compiled against a different module ABI version.

      +
      console.log(process.versions);
      +

      Will generate an object similar to:

      +
      { node: '11.13.0',
      +  v8: '7.0.276.38-node.18',
      +  uv: '1.27.0',
      +  zlib: '1.2.11',
      +  brotli: '1.0.7',
      +  ares: '1.15.0',
      +  modules: '67',
      +  nghttp2: '1.34.0',
      +  napi: '4',
      +  llhttp: '1.1.1',
      +  http_parser: '2.8.0',
      +  openssl: '1.1.1b',
      +  cldr: '34.0',
      +  icu: '63.1',
      +  tz: '2018e',
      +  unicode: '11.0' }
      +

      Exit codes#

      +

      Node.js will normally exit with a 0 status code when no more async +operations are pending. The following status codes are used in other +cases:

      +
        +
      • 1 Uncaught Fatal Exception: There was an uncaught exception, +and it was not handled by a domain or an 'uncaughtException' event +handler.
      • +
      • 2: Unused (reserved by Bash for builtin misuse)
      • +
      • 3 Internal JavaScript Parse Error: The JavaScript source code +internal in the Node.js bootstrapping process caused a parse error. This +is extremely rare, and generally can only happen during development +of Node.js itself.
      • +
      • 4 Internal JavaScript Evaluation Failure: The JavaScript +source code internal in the Node.js bootstrapping process failed to +return a function value when evaluated. This is extremely rare, and +generally can only happen during development of Node.js itself.
      • +
      • 5 Fatal Error: There was a fatal unrecoverable error in V8. +Typically a message will be printed to stderr with the prefix FATAL ERROR.
      • +
      • 6 Non-function Internal Exception Handler: There was an +uncaught exception, but the internal fatal exception handler +function was somehow set to a non-function, and could not be called.
      • +
      • 7 Internal Exception Handler Run-Time Failure: There was an +uncaught exception, and the internal fatal exception handler +function itself threw an error while attempting to handle it. This +can happen, for example, if an 'uncaughtException' or +domain.on('error') handler throws an error.
      • +
      • 8: Unused. In previous versions of Node.js, exit code 8 sometimes +indicated an uncaught exception.
      • +
      • 9 Invalid Argument: Either an unknown option was specified, +or an option requiring a value was provided without a value.
      • +
      • 10 Internal JavaScript Run-Time Failure: The JavaScript +source code internal in the Node.js bootstrapping process threw an error +when the bootstrapping function was called. This is extremely rare, +and generally can only happen during development of Node.js itself.
      • +
      • 12 Invalid Debug Argument: The --inspect and/or --inspect-brk +options were set, but the port number chosen was invalid or unavailable.
      • +
      • >128 Signal Exits: If Node.js receives a fatal signal such as +SIGKILL or SIGHUP, then its exit code will be 128 plus the +value of the signal code. This is a standard POSIX practice, since +exit codes are defined to be 7-bit integers, and signal exits set +the high-order bit, and then contain the value of the signal code. +For example, signal SIGABRT has value 6, so the expected exit +code will be 128 + 6, or 134.
      • +
      + +
      +
      +
      + + diff --git a/doc/api/process.json b/doc/api/process.json new file mode 100644 index 0000000000000000000000000000000000000000..4e170c856d1bf41e45139f15d8dffa748c9c26b4 --- /dev/null +++ b/doc/api/process.json @@ -0,0 +1,1908 @@ +{ + "type": "module", + "source": "doc/api/process.md", + "globals": [ + { + "textRaw": "Process", + "name": "Process", + "introduced_in": "v0.10.0", + "type": "global", + "desc": "

      Source Code: lib/process.js

      \n

      The process object is a global that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require(). It can also be explicitly\naccessed using require():

      \n
      const process = require('process');\n
      ", + "modules": [ + { + "textRaw": "Process events", + "name": "process_events", + "desc": "

      The process object is an instance of EventEmitter.

      ", + "events": [ + { + "textRaw": "Event: `'beforeExit'`", + "type": "event", + "name": "beforeExit", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'beforeExit' event is emitted when Node.js empties its event loop and has\nno additional work to schedule. Normally, the Node.js process will exit when\nthere is no work scheduled, but a listener registered on the 'beforeExit'\nevent can make asynchronous calls, and thereby cause the Node.js process to\ncontinue.

      \n

      The listener callback function is invoked with the value of\nprocess.exitCode passed as the only argument.

      \n

      The 'beforeExit' event is not emitted for conditions causing explicit\ntermination, such as calling process.exit() or uncaught exceptions.

      \n

      The 'beforeExit' should not be used as an alternative to the 'exit' event\nunless the intention is to schedule additional work.

      \n
      process.on('beforeExit', (code) => {\n  console.log('Process beforeExit event with code: ', code);\n});\n\nprocess.on('exit', (code) => {\n  console.log('Process exit event with code: ', code);\n});\n\nconsole.log('This message is displayed first.');\n\n// Prints:\n// This message is displayed first.\n// Process beforeExit event with code: 0\n// Process exit event with code: 0\n
      " + }, + { + "textRaw": "Event: `'disconnect'`", + "type": "event", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'disconnect' event will be emitted when\nthe IPC channel is closed.

      " + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.1.7" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`code` {integer}", + "name": "code", + "type": "integer" + } + ], + "desc": "

      The 'exit' event is emitted when the Node.js process is about to exit as a\nresult of either:

      \n
        \n
      • The process.exit() method being called explicitly;
      • \n
      • The Node.js event loop no longer having any additional work to perform.
      • \n
      \n

      There is no way to prevent the exiting of the event loop at this point, and once\nall 'exit' listeners have finished running the Node.js process will terminate.

      \n

      The listener callback function is invoked with the exit code specified either\nby the process.exitCode property, or the exitCode argument passed to the\nprocess.exit() method.

      \n
      process.on('exit', (code) => {\n  console.log(`About to exit with code: ${code}`);\n});\n
      \n

      Listener functions must only perform synchronous operations. The Node.js\nprocess will exit immediately after calling the 'exit' event listeners\ncausing any additional work still queued in the event loop to be abandoned.\nIn the following example, for instance, the timeout will never occur:

      \n
      process.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
      " + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v0.5.10" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`message` { Object | boolean | number | string | null } a parsed JSON object or a serializable primitive value.", + "name": "message", + "type": " Object | boolean | number | string | null ", + "desc": "a parsed JSON object or a serializable primitive value." + }, + { + "textRaw": "`sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] object, or undefined.", + "name": "sendHandle", + "type": "net.Server|net.Socket", + "desc": "a [`net.Server`][] or [`net.Socket`][] object, or undefined." + } + ], + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'message' event is emitted whenever a\nmessage sent by a parent process using childprocess.send() is received by\nthe child process.

      \n

      The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.

      \n

      If the serialization option was set to advanced used when spawning the\nprocess, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for child_process for more details.

      " + }, + { + "textRaw": "Event: `'multipleResolves'`", + "type": "event", + "name": "multipleResolves", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`type` {string} The resolution type. One of `'resolve'` or `'reject'`.", + "name": "type", + "type": "string", + "desc": "The resolution type. One of `'resolve'` or `'reject'`." + }, + { + "textRaw": "`promise` {Promise} The promise that resolved or rejected more than once.", + "name": "promise", + "type": "Promise", + "desc": "The promise that resolved or rejected more than once." + }, + { + "textRaw": "`value` {any} The value with which the promise was either resolved or rejected after the original resolve.", + "name": "value", + "type": "any", + "desc": "The value with which the promise was either resolved or rejected after the original resolve." + } + ], + "desc": "

      The 'multipleResolves' event is emitted whenever a Promise has been either:

      \n
        \n
      • Resolved more than once.
      • \n
      • Rejected more than once.
      • \n
      • Rejected after resolve.
      • \n
      • Resolved after reject.
      • \n
      \n

      This is useful for tracking potential errors in an application while using the\nPromise constructor, as multiple resolutions are silently swallowed. However,\nthe occurrence of this event does not necessarily indicate an error. For\nexample, Promise.race() can trigger a 'multipleResolves' event.

      \n
      process.on('multipleResolves', (type, promise, reason) => {\n  console.error(type, promise, reason);\n  setImmediate(() => process.exit(1));\n});\n\nasync function main() {\n  try {\n    return await new Promise((resolve, reject) => {\n      resolve('First call');\n      resolve('Swallowed resolve');\n      reject(new Error('Swallowed reject'));\n    });\n  } catch {\n    throw new Error('Failed');\n  }\n}\n\nmain().then(console.log);\n// resolve: Promise { 'First call' } 'Swallowed resolve'\n// reject: Promise { 'First call' } Error: Swallowed reject\n//     at Promise (*)\n//     at new Promise (<anonymous>)\n//     at main (*)\n// First call\n
      " + }, + { + "textRaw": "Event: `'rejectionHandled'`", + "type": "event", + "name": "rejectionHandled", + "meta": { + "added": [ + "v1.4.1" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`promise` {Promise} The late handled promise.", + "name": "promise", + "type": "Promise", + "desc": "The late handled promise." + } + ], + "desc": "

      The 'rejectionHandled' event is emitted whenever a Promise has been rejected\nand an error handler was attached to it (using promise.catch(), for\nexample) later than one turn of the Node.js event loop.

      \n

      The Promise object would have previously been emitted in an\n'unhandledRejection' event, but during the course of processing gained a\nrejection handler.

      \n

      There is no notion of a top level for a Promise chain at which rejections can\nalways be handled. Being inherently asynchronous in nature, a Promise\nrejection can be handled at a future point in time, possibly much later than\nthe event loop turn it takes for the 'unhandledRejection' event to be emitted.

      \n

      Another way of stating this is that, unlike in synchronous code where there is\nan ever-growing list of unhandled exceptions, with Promises there can be a\ngrowing-and-shrinking list of unhandled rejections.

      \n

      In synchronous code, the 'uncaughtException' event is emitted when the list of\nunhandled exceptions grows.

      \n

      In asynchronous code, the 'unhandledRejection' event is emitted when the list\nof unhandled rejections grows, and the 'rejectionHandled' event is emitted\nwhen the list of unhandled rejections shrinks.

      \n
      const unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, promise) => {\n  unhandledRejections.set(promise, reason);\n});\nprocess.on('rejectionHandled', (promise) => {\n  unhandledRejections.delete(promise);\n});\n
      \n

      In this example, the unhandledRejections Map will grow and shrink over time,\nreflecting rejections that start unhandled and then become handled. It is\npossible to record such errors in an error log, either periodically (which is\nlikely best for long-running application) or upon process exit (which is likely\nmost convenient for scripts).

      " + }, + { + "textRaw": "Event: `'uncaughtException'`", + "type": "event", + "name": "uncaughtException", + "meta": { + "added": [ + "v0.1.18" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26599", + "description": "Added the `origin` argument." + } + ] + }, + "params": [ + { + "textRaw": "`err` {Error} The uncaught exception.", + "name": "err", + "type": "Error", + "desc": "The uncaught exception." + }, + { + "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` and an unhandled rejection.", + "name": "origin", + "type": "string", + "desc": "Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` and an unhandled rejection." + } + ], + "desc": "

      The 'uncaughtException' event is emitted when an uncaught JavaScript\nexception bubbles all the way back to the event loop. By default, Node.js\nhandles such exceptions by printing the stack trace to stderr and exiting\nwith code 1, overriding any previously set process.exitCode.\nAdding a handler for the 'uncaughtException' event overrides this default\nbehavior. Alternatively, change the process.exitCode in the\n'uncaughtException' handler which will result in the process exiting with the\nprovided exit code. Otherwise, in the presence of such handler the process will\nexit with 0.

      \n
      process.on('uncaughtException', (err, origin) => {\n  fs.writeSync(\n    process.stderr.fd,\n    `Caught exception: ${err}\\n` +\n    `Exception origin: ${origin}`\n  );\n});\n\nsetTimeout(() => {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
      \n

      It is possible to monitor 'uncaughtException' events without overriding the\ndefault behavior to exit the process by installing a\n'uncaughtExceptionMonitor' listener.

      ", + "modules": [ + { + "textRaw": "Warning: Using `'uncaughtException'` correctly", + "name": "warning:_using_`'uncaughtexception'`_correctly", + "desc": "

      'uncaughtException' is a crude mechanism for exception handling\nintended to be used only as a last resort. The event should not be used as\nan equivalent to On Error Resume Next. Unhandled exceptions inherently mean\nthat an application is in an undefined state. Attempting to resume application\ncode without properly recovering from the exception can cause additional\nunforeseen and unpredictable issues.

      \n

      Exceptions thrown from within the event handler will not be caught. Instead the\nprocess will exit with a non-zero exit code and the stack trace will be printed.\nThis is to avoid infinite recursion.

      \n

      Attempting to resume normally after an uncaught exception can be similar to\npulling out the power cord when upgrading a computer. Nine out of ten\ntimes, nothing happens. But the tenth time, the system becomes corrupted.

      \n

      The correct use of 'uncaughtException' is to perform synchronous cleanup\nof allocated resources (e.g. file descriptors, handles, etc) before shutting\ndown the process. It is not safe to resume normal operation after\n'uncaughtException'.

      \n

      To restart a crashed application in a more reliable way, whether\n'uncaughtException' is emitted or not, an external monitor should be employed\nin a separate process to detect application failures and recover or restart as\nneeded.

      ", + "type": "module", + "displayName": "Warning: Using `'uncaughtException'` correctly" + } + ] + }, + { + "textRaw": "Event: `'uncaughtExceptionMonitor'`", + "type": "event", + "name": "uncaughtExceptionMonitor", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`err` {Error} The uncaught exception.", + "name": "err", + "type": "Error", + "desc": "The uncaught exception." + }, + { + "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`.", + "name": "origin", + "type": "string", + "desc": "Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`." + } + ], + "desc": "

      The 'uncaughtExceptionMonitor' event is emitted before an\n'uncaughtException' event is emitted or a hook installed via\nprocess.setUncaughtExceptionCaptureCallback() is called.

      \n

      Installing an 'uncaughtExceptionMonitor' listener does not change the behavior\nonce an 'uncaughtException' event is emitted. The process will\nstill crash if no 'uncaughtException' listener is installed.

      \n
      process.on('uncaughtExceptionMonitor', (err, origin) => {\n  MyMonitoringTool.logSync(err, origin);\n});\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\n// Still crashes Node.js\n
      " + }, + { + "textRaw": "Event: `'unhandledRejection'`", + "type": "event", + "name": "unhandledRejection", + "meta": { + "added": [ + "v1.4.1" + ], + "changes": [ + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/8217", + "description": "Not handling `Promise` rejections is deprecated." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8223", + "description": "Unhandled `Promise` rejections will now emit a process warning." + } + ] + }, + "params": [ + { + "textRaw": "`reason` {Error|any} The object with which the promise was rejected (typically an [`Error`][] object).", + "name": "reason", + "type": "Error|any", + "desc": "The object with which the promise was rejected (typically an [`Error`][] object)." + }, + { + "textRaw": "`promise` {Promise} The rejected promise.", + "name": "promise", + "type": "Promise", + "desc": "The rejected promise." + } + ], + "desc": "

      The 'unhandledRejection' event is emitted whenever a Promise is rejected and\nno error handler is attached to the promise within a turn of the event loop.\nWhen programming with Promises, exceptions are encapsulated as \"rejected\npromises\". Rejections can be caught and handled using promise.catch() and\nare propagated through a Promise chain. The 'unhandledRejection' event is\nuseful for detecting and keeping track of promises that were rejected whose\nrejections have not yet been handled.

      \n
      process.on('unhandledRejection', (reason, promise) => {\n  console.log('Unhandled Rejection at:', promise, 'reason:', reason);\n  // Application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)\n}); // No `.catch()` or `.then()`\n
      \n

      The following will also trigger the 'unhandledRejection' event to be\nemitted:

      \n
      function SomeResource() {\n  // Initially set the loaded status to a rejected promise\n  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));\n}\n\nconst resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn\n
      \n

      In this example case, it is possible to track the rejection as a developer error\nas would typically be the case for other 'unhandledRejection' events. To\naddress such failures, a non-operational\n.catch(() => { }) handler may be attached to\nresource.loaded, which would prevent the 'unhandledRejection' event from\nbeing emitted.

      " + }, + { + "textRaw": "Event: `'warning'`", + "type": "event", + "name": "warning", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`warning` {Error} Key properties of the warning are:", + "name": "warning", + "type": "Error", + "desc": "Key properties of the warning are:", + "options": [ + { + "textRaw": "`name` {string} The name of the warning. **Default:** `'Warning'`.", + "name": "name", + "type": "string", + "default": "`'Warning'`", + "desc": "The name of the warning." + }, + { + "textRaw": "`message` {string} A system-provided description of the warning.", + "name": "message", + "type": "string", + "desc": "A system-provided description of the warning." + }, + { + "textRaw": "`stack` {string} A stack trace to the location in the code where the warning was issued.", + "name": "stack", + "type": "string", + "desc": "A stack trace to the location in the code where the warning was issued." + } + ] + } + ], + "desc": "

      The 'warning' event is emitted whenever Node.js emits a process warning.

      \n

      A process warning is similar to an error in that it describes exceptional\nconditions that are being brought to the user's attention. However, warnings\nare not part of the normal Node.js and JavaScript error handling flow.\nNode.js can emit warnings whenever it detects bad coding practices that could\nlead to sub-optimal application performance, bugs, or security vulnerabilities.

      \n
      process.on('warning', (warning) => {\n  console.warn(warning.name);    // Print the warning name\n  console.warn(warning.message); // Print the warning message\n  console.warn(warning.stack);   // Print the stack trace\n});\n
      \n

      By default, Node.js will print process warnings to stderr. The --no-warnings\ncommand-line option can be used to suppress the default console output but the\n'warning' event will still be emitted by the process object.

      \n

      The following example illustrates the warning that is printed to stderr when\ntoo many listeners have been added to an event:

      \n
      $ node\n> events.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak\ndetected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit\n
      \n

      In contrast, the following example turns off the default warning output and\nadds a custom handler to the 'warning' event:

      \n
      $ node --no-warnings\n> const p = process.on('warning', (warning) => console.warn('Do not do that!'));\n> events.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> Do not do that!\n
      \n

      The --trace-warnings command-line option can be used to have the default\nconsole output for warnings include the full stack trace of the warning.

      \n

      Launching Node.js using the --throw-deprecation command line flag will\ncause custom deprecation warnings to be thrown as exceptions.

      \n

      Using the --trace-deprecation command line flag will cause the custom\ndeprecation to be printed to stderr along with the stack trace.

      \n

      Using the --no-deprecation command line flag will suppress all reporting\nof the custom deprecation.

      \n

      The *-deprecation command line flags only affect warnings that use the name\n'DeprecationWarning'.

      ", + "modules": [ + { + "textRaw": "Emitting custom warnings", + "name": "emitting_custom_warnings", + "desc": "

      See the process.emitWarning() method for issuing\ncustom or application-specific warnings.

      ", + "type": "module", + "displayName": "Emitting custom warnings" + } + ] + }, + { + "textRaw": "Signal events", + "name": "SIGINT, SIGHUP, etc.", + "type": "event", + "params": [], + "desc": "

      Signal events will be emitted when the Node.js process receives a signal. Please\nrefer to signal(7) for a listing of standard POSIX signal names such as\n'SIGINT', 'SIGHUP', etc.

      \n

      Signals are not available on Worker threads.

      \n

      The signal handler will receive the signal's name ('SIGINT',\n'SIGTERM', etc.) as the first argument.

      \n

      The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT' for SIGINT signals).

      \n
      // Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Received SIGINT. Press Control-D to exit.');\n});\n\n// Using a single function to handle multiple signals\nfunction handle(signal) {\n  console.log(`Received ${signal}`);\n}\n\nprocess.on('SIGINT', handle);\nprocess.on('SIGTERM', handle);\n
      \n
        \n
      • 'SIGUSR1' is reserved by Node.js to start the debugger. It's possible to\ninstall a listener but doing so might interfere with the debugger.
      • \n
      • 'SIGTERM' and 'SIGINT' have default handlers on non-Windows platforms that\nreset the terminal mode before exiting with code 128 + signal number. If one\nof these signals has a listener installed, its default behavior will be\nremoved (Node.js will no longer exit).
      • \n
      • 'SIGPIPE' is ignored by default. It can have a listener installed.
      • \n
      • 'SIGHUP' is generated on Windows when the console window is closed, and on\nother platforms under various similar conditions. See signal(7). It can have a\nlistener installed, however Node.js will be unconditionally terminated by\nWindows about 10 seconds later. On non-Windows platforms, the default\nbehavior of SIGHUP is to terminate Node.js, but once a listener has been\ninstalled its default behavior will be removed.
      • \n
      • 'SIGTERM' is not supported on Windows, it can be listened on.
      • \n
      • 'SIGINT' from the terminal is supported on all platforms, and can usually be\ngenerated with Ctrl+C (though this may be configurable).\nIt is not generated when terminal raw mode is enabled and\nCtrl+C is used.
      • \n
      • 'SIGBREAK' is delivered on Windows when Ctrl+Break is\npressed. On non-Windows platforms, it can be listened on, but there is no way\nto send or generate it.
      • \n
      • 'SIGWINCH' is delivered when the console has been resized. On Windows, this\nwill only happen on write to the console when the cursor is being moved, or\nwhen a readable tty is used in raw mode.
      • \n
      • 'SIGKILL' cannot have a listener installed, it will unconditionally\nterminate Node.js on all platforms.
      • \n
      • 'SIGSTOP' cannot have a listener installed.
      • \n
      • 'SIGBUS', 'SIGFPE', 'SIGSEGV' and 'SIGILL', when not raised\n artificially using kill(2), inherently leave the process in a state from\n which it is not safe to attempt to call JS listeners. Doing so might lead to\n the process hanging in an endless loop, since listeners attached using\n process.on() are called asynchronously and therefore unable to correct the\nunderlying problem.
      • \n
      • 0 can be sent to test for the existence of a process, it has no effect if\nthe process exists, but will throw an error if the process does not exist.
      • \n
      \n

      Windows does not support signals so has no equivalent to termination by signal,\nbut Node.js offers some emulation with process.kill(), and\nsubprocess.kill():

      \n
        \n
      • Sending SIGINT, SIGTERM, and SIGKILL will cause the unconditional\ntermination of the target process, and afterwards, subprocess will report that\nthe process was terminated by signal.
      • \n
      • Sending signal 0 can be used as a platform independent way to test for the\nexistence of a process.
      • \n
      " + } + ], + "type": "module", + "displayName": "Process events" + }, + { + "textRaw": "Exit codes", + "name": "exit_codes", + "desc": "

      Node.js will normally exit with a 0 status code when no more async\noperations are pending. The following status codes are used in other\ncases:

      \n
        \n
      • 1 Uncaught Fatal Exception: There was an uncaught exception,\nand it was not handled by a domain or an 'uncaughtException' event\nhandler.
      • \n
      • 2: Unused (reserved by Bash for builtin misuse)
      • \n
      • 3 Internal JavaScript Parse Error: The JavaScript source code\ninternal in the Node.js bootstrapping process caused a parse error. This\nis extremely rare, and generally can only happen during development\nof Node.js itself.
      • \n
      • 4 Internal JavaScript Evaluation Failure: The JavaScript\nsource code internal in the Node.js bootstrapping process failed to\nreturn a function value when evaluated. This is extremely rare, and\ngenerally can only happen during development of Node.js itself.
      • \n
      • 5 Fatal Error: There was a fatal unrecoverable error in V8.\nTypically a message will be printed to stderr with the prefix FATAL ERROR.
      • \n
      • 6 Non-function Internal Exception Handler: There was an\nuncaught exception, but the internal fatal exception handler\nfunction was somehow set to a non-function, and could not be called.
      • \n
      • 7 Internal Exception Handler Run-Time Failure: There was an\nuncaught exception, and the internal fatal exception handler\nfunction itself threw an error while attempting to handle it. This\ncan happen, for example, if an 'uncaughtException' or\ndomain.on('error') handler throws an error.
      • \n
      • 8: Unused. In previous versions of Node.js, exit code 8 sometimes\nindicated an uncaught exception.
      • \n
      • 9 Invalid Argument: Either an unknown option was specified,\nor an option requiring a value was provided without a value.
      • \n
      • 10 Internal JavaScript Run-Time Failure: The JavaScript\nsource code internal in the Node.js bootstrapping process threw an error\nwhen the bootstrapping function was called. This is extremely rare,\nand generally can only happen during development of Node.js itself.
      • \n
      • 12 Invalid Debug Argument: The --inspect and/or --inspect-brk\noptions were set, but the port number chosen was invalid or unavailable.
      • \n
      • >128 Signal Exits: If Node.js receives a fatal signal such as\nSIGKILL or SIGHUP, then its exit code will be 128 plus the\nvalue of the signal code. This is a standard POSIX practice, since\nexit codes are defined to be 7-bit integers, and signal exits set\nthe high-order bit, and then contain the value of the signal code.\nFor example, signal SIGABRT has value 6, so the expected exit\ncode will be 128 + 6, or 134.
      • \n
      ", + "type": "module", + "displayName": "Exit codes" + } + ], + "methods": [ + { + "textRaw": "`process.abort()`", + "type": "method", + "name": "abort", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The process.abort() method causes the Node.js process to exit immediately and\ngenerate a core file.

      \n

      This feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.chdir(directory)`", + "type": "method", + "name": "chdir", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`directory` {string}", + "name": "directory", + "type": "string" + } + ] + } + ], + "desc": "

      The process.chdir() method changes the current working directory of the\nNode.js process or throws an exception if doing so fails (for instance, if\nthe specified directory does not exist).

      \n
      console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n} catch (err) {\n  console.error(`chdir: ${err}`);\n}\n
      \n

      This feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.cpuUsage([previousValue])`", + "type": "method", + "name": "cpuUsage", + "meta": { + "added": [ + "v6.1.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`user` {integer}", + "name": "user", + "type": "integer" + }, + { + "textRaw": "`system` {integer}", + "name": "system", + "type": "integer" + } + ] + }, + "params": [ + { + "textRaw": "`previousValue` {Object} A previous return value from calling `process.cpuUsage()`", + "name": "previousValue", + "type": "Object", + "desc": "A previous return value from calling `process.cpuUsage()`" + } + ] + } + ], + "desc": "

      The process.cpuUsage() method returns the user and system CPU time usage of\nthe current process, in an object with properties user and system, whose\nvalues are microsecond values (millionth of a second). These values measure time\nspent in user and system code respectively, and may end up being greater than\nactual elapsed time if multiple CPU cores are performing work for this process.

      \n

      The result of a previous call to process.cpuUsage() can be passed as the\nargument to the function, to get a diff reading.

      \n
      const startUsage = process.cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
      " + }, + { + "textRaw": "`process.cwd()`", + "type": "method", + "name": "cwd", + "meta": { + "added": [ + "v0.1.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      The process.cwd() method returns the current working directory of the Node.js\nprocess.

      \n
      console.log(`Current directory: ${process.cwd()}`);\n
      " + }, + { + "textRaw": "`process.disconnect()`", + "type": "method", + "name": "disconnect", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.disconnect() method will close the\nIPC channel to the parent process, allowing the child process to exit gracefully\nonce there are no other connections keeping it alive.

      \n

      The effect of calling process.disconnect() is the same as calling\nChildProcess.disconnect() from the parent process.

      \n

      If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect() will be undefined.

      " + }, + { + "textRaw": "`process.dlopen(module, filename[, flags])`", + "type": "method", + "name": "dlopen", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12794", + "description": "Added support for the `flags` argument." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`module` {Object}", + "name": "module", + "type": "Object" + }, + { + "textRaw": "`filename` {string}", + "name": "filename", + "type": "string" + }, + { + "textRaw": "`flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY`", + "name": "flags", + "type": "os.constants.dlopen", + "default": "`os.constants.dlopen.RTLD_LAZY`" + } + ] + } + ], + "desc": "

      The process.dlopen() method allows to dynamically load shared\nobjects. It is primarily used by require() to load\nC++ Addons, and should not be used directly, except in special\ncases. In other words, require() should be preferred over\nprocess.dlopen(), unless there are specific reasons.

      \n

      The flags argument is an integer that allows to specify dlopen\nbehavior. See the os.constants.dlopen documentation for details.

      \n

      If there are specific reasons to use process.dlopen() (for instance,\nto specify dlopen flags), it's often useful to use require.resolve()\nto look up the module's path.

      \n

      An important drawback when calling process.dlopen() is that the module\ninstance must be passed. Functions exported by the C++ Addon will be accessible\nvia module.exports.

      \n

      The example below shows how to load a C++ Addon, named as binding,\nthat exports a foo function. All the symbols will be loaded before\nthe call returns, by passing the RTLD_NOW constant. In this example\nthe constant is assumed to be available.

      \n
      const os = require('os');\nprocess.dlopen(module, require.resolve('binding'),\n               os.constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
      " + }, + { + "textRaw": "`process.emitWarning(warning[, options])`", + "type": "method", + "name": "emitWarning", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`warning` {string|Error} The warning to emit.", + "name": "warning", + "type": "string|Error", + "desc": "The warning to emit." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", + "name": "type", + "type": "string", + "default": "`'Warning'`", + "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." + }, + { + "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", + "name": "code", + "type": "string", + "desc": "A unique identifier for the warning instance being emitted." + }, + { + "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", + "name": "ctor", + "type": "Function", + "default": "`process.emitWarning`", + "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." + }, + { + "textRaw": "`detail` {string} Additional text to include with the error.", + "name": "detail", + "type": "string", + "desc": "Additional text to include with the error." + } + ] + } + ] + } + ], + "desc": "

      The process.emitWarning() method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\n'warning' event.

      \n
      // Emit a warning with a code and additional detail.\nprocess.emitWarning('Something happened!', {\n  code: 'MY_WARNING',\n  detail: 'This is some additional information'\n});\n// Emits:\n// (node:56338) [MY_WARNING] Warning: Something happened!\n// This is some additional information\n
      \n

      In this example, an Error object is generated internally by\nprocess.emitWarning() and passed through to the\n'warning' handler.

      \n
      process.on('warning', (warning) => {\n  console.warn(warning.name);    // 'Warning'\n  console.warn(warning.message); // 'Something happened!'\n  console.warn(warning.code);    // 'MY_WARNING'\n  console.warn(warning.stack);   // Stack trace\n  console.warn(warning.detail);  // 'This is some additional information'\n});\n
      \n

      If warning is passed as an Error object, the options argument is ignored.

      " + }, + { + "textRaw": "`process.emitWarning(warning[, type[, code]][, ctor])`", + "type": "method", + "name": "emitWarning", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`warning` {string|Error} The warning to emit.", + "name": "warning", + "type": "string|Error", + "desc": "The warning to emit." + }, + { + "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", + "name": "type", + "type": "string", + "default": "`'Warning'`", + "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." + }, + { + "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", + "name": "code", + "type": "string", + "desc": "A unique identifier for the warning instance being emitted." + }, + { + "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", + "name": "ctor", + "type": "Function", + "default": "`process.emitWarning`", + "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." + } + ] + } + ], + "desc": "

      The process.emitWarning() method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\n'warning' event.

      \n
      // Emit a warning using a string.\nprocess.emitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
      \n
      // Emit a warning using a string and a type.\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
      \n
      process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
      \n

      In each of the previous examples, an Error object is generated internally by\nprocess.emitWarning() and passed through to the 'warning'\nhandler.

      \n
      process.on('warning', (warning) => {\n  console.warn(warning.name);\n  console.warn(warning.message);\n  console.warn(warning.code);\n  console.warn(warning.stack);\n});\n
      \n

      If warning is passed as an Error object, it will be passed through to the\n'warning' event handler unmodified (and the optional type,\ncode and ctor arguments will be ignored):

      \n
      // Emit a warning using an Error object.\nconst myWarning = new Error('Something happened!');\n// Use the Error name property to specify the type name\nmyWarning.name = 'CustomWarning';\nmyWarning.code = 'WARN001';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
      \n

      A TypeError is thrown if warning is anything other than a string or Error\nobject.

      \n

      While process warnings use Error objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.

      \n

      The following additional handling is implemented if the warning type is\n'DeprecationWarning':

      \n
        \n
      • If the --throw-deprecation command-line flag is used, the deprecation\nwarning is thrown as an exception rather than being emitted as an event.
      • \n
      • If the --no-deprecation command-line flag is used, the deprecation\nwarning is suppressed.
      • \n
      • If the --trace-deprecation command-line flag is used, the deprecation\nwarning is printed to stderr along with the full stack trace.
      • \n
      ", + "modules": [ + { + "textRaw": "Avoiding duplicate warnings", + "name": "avoiding_duplicate_warnings", + "desc": "

      As a best practice, warnings should be emitted only once per process. To do\nso, it is recommended to place the emitWarning() behind a simple boolean\nflag as illustrated in the example below:

      \n
      function emitMyWarning() {\n  if (!emitMyWarning.warned) {\n    emitMyWarning.warned = true;\n    process.emitWarning('Only warn once!');\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
      ", + "type": "module", + "displayName": "Avoiding duplicate warnings" + } + ] + }, + { + "textRaw": "`process.exit([code])`", + "type": "method", + "name": "exit", + "meta": { + "added": [ + "v0.1.13" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {integer} The exit code. **Default:** `0`.", + "name": "code", + "type": "integer", + "default": "`0`", + "desc": "The exit code." + } + ] + } + ], + "desc": "

      The process.exit() method instructs Node.js to terminate the process\nsynchronously with an exit status of code. If code is omitted, exit uses\neither the 'success' code 0 or the value of process.exitCode if it has been\nset. Node.js will not terminate until all the 'exit' event listeners are\ncalled.

      \n

      To exit with a 'failure' code:

      \n
      process.exit(1);\n
      \n

      The shell that executed Node.js should see the exit code as 1.

      \n

      Calling process.exit() will force the process to exit as quickly as possible\neven if there are still asynchronous operations pending that have not yet\ncompleted fully, including I/O operations to process.stdout and\nprocess.stderr.

      \n

      In most situations, it is not actually necessary to call process.exit()\nexplicitly. The Node.js process will exit on its own if there is no additional\nwork pending in the event loop. The process.exitCode property can be set to\ntell the process which exit code to use when the process exits gracefully.

      \n

      For instance, the following example illustrates a misuse of the\nprocess.exit() method that could lead to data printed to stdout being\ntruncated and lost:

      \n
      // This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exit(1);\n}\n
      \n

      The reason this is problematic is because writes to process.stdout in Node.js\nare sometimes asynchronous and may occur over multiple ticks of the Node.js\nevent loop. Calling process.exit(), however, forces the process to exit\nbefore those additional writes to stdout can be performed.

      \n

      Rather than calling process.exit() directly, the code should set the\nprocess.exitCode and allow the process to exit naturally by avoiding\nscheduling any additional work for the event loop:

      \n
      // How to properly set the exit code while letting\n// the process exit gracefully.\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exitCode = 1;\n}\n
      \n

      If it is necessary to terminate the Node.js process due to an error condition,\nthrowing an uncaught error and allowing the process to terminate accordingly\nis safer than calling process.exit().

      \n

      In Worker threads, this function stops the current thread rather\nthan the current process.

      " + }, + { + "textRaw": "`process.getegid()`", + "type": "method", + "name": "getegid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The process.getegid() method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)

      \n
      if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.geteuid()`", + "type": "method", + "name": "geteuid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      The process.geteuid() method returns the numerical effective user identity of\nthe process. (See geteuid(2).)

      \n
      if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.getgid()`", + "type": "method", + "name": "getgid", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      The process.getgid() method returns the numerical group identity of the\nprocess. (See getgid(2).)

      \n
      if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.getgroups()`", + "type": "method", + "name": "getgroups", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer[]}", + "name": "return", + "type": "integer[]" + }, + "params": [] + } + ], + "desc": "

      The process.getgroups() method returns an array with the supplementary group\nIDs. POSIX leaves it unspecified if the effective group ID is included but\nNode.js ensures it always is.

      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.getuid()`", + "type": "method", + "name": "getuid", + "meta": { + "added": [ + "v0.1.28" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      The process.getuid() method returns the numeric user identity of the process.\n(See getuid(2).)

      \n
      if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

      " + }, + { + "textRaw": "`process.hasUncaughtExceptionCaptureCallback()`", + "type": "method", + "name": "hasUncaughtExceptionCaptureCallback", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      Indicates whether a callback has been set using\nprocess.setUncaughtExceptionCaptureCallback().

      " + }, + { + "textRaw": "`process.hrtime([time])`", + "type": "method", + "name": "hrtime", + "meta": { + "added": [ + "v0.7.6" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer[]}", + "name": "return", + "type": "integer[]" + }, + "params": [ + { + "textRaw": "`time` {integer[]} The result of a previous call to `process.hrtime()`", + "name": "time", + "type": "integer[]", + "desc": "The result of a previous call to `process.hrtime()`" + } + ] + } + ], + "desc": "

      This is the legacy version of process.hrtime.bigint()\nbefore bigint was introduced in JavaScript.

      \n

      The process.hrtime() method returns the current high-resolution real time\nin a [seconds, nanoseconds] tuple Array, where nanoseconds is the\nremaining part of the real time that can't be represented in second precision.

      \n

      time is an optional parameter that must be the result of a previous\nprocess.hrtime() call to diff with the current time. If the parameter\npassed in is not a tuple Array, a TypeError will be thrown. Passing in a\nuser-defined array instead of the result of a previous call to\nprocess.hrtime() will lead to undefined behavior.

      \n

      These times are relative to an arbitrary time in the\npast, and not related to the time of day and therefore not subject to clock\ndrift. The primary use is for measuring performance between intervals:

      \n
      const NS_PER_SEC = 1e9;\nconst time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);\n  // Benchmark took 1000000552 nanoseconds\n}, 1000);\n
      " + }, + { + "textRaw": "`process.hrtime.bigint()`", + "type": "method", + "name": "bigint", + "meta": { + "added": [ + "v10.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {bigint}", + "name": "return", + "type": "bigint" + }, + "params": [] + } + ], + "desc": "

      The bigint version of the process.hrtime() method returning the\ncurrent high-resolution real time in nanoseconds as a bigint.

      \n

      Unlike process.hrtime(), it does not support an additional time\nargument since the difference can just be computed directly\nby subtraction of the two bigints.

      \n
      const start = process.hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n  const end = process.hrtime.bigint();\n  // 191052633396993n\n\n  console.log(`Benchmark took ${end - start} nanoseconds`);\n  // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
      " + }, + { + "textRaw": "`process.initgroups(user, extraGroup)`", + "type": "method", + "name": "initgroups", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`user` {string|number} The user name or numeric identifier.", + "name": "user", + "type": "string|number", + "desc": "The user name or numeric identifier." + }, + { + "textRaw": "`extraGroup` {string|number} A group name or numeric identifier.", + "name": "extraGroup", + "type": "string|number", + "desc": "A group name or numeric identifier." + } + ] + } + ], + "desc": "

      The process.initgroups() method reads the /etc/group file and initializes\nthe group access list, using all groups of which the user is a member. This is\na privileged operation that requires that the Node.js process either have root\naccess or the CAP_SETGID capability.

      \n

      Use care when dropping privileges:

      \n
      console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('nodeuser', 1000);     // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.kill(pid[, signal])`", + "type": "method", + "name": "kill", + "meta": { + "added": [ + "v0.0.6" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`pid` {number} A process ID", + "name": "pid", + "type": "number", + "desc": "A process ID" + }, + { + "textRaw": "`signal` {string|number} The signal to send, either as a string or number. **Default:** `'SIGTERM'`.", + "name": "signal", + "type": "string|number", + "default": "`'SIGTERM'`", + "desc": "The signal to send, either as a string or number." + } + ] + } + ], + "desc": "

      The process.kill() method sends the signal to the process identified by\npid.

      \n

      Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events\nand kill(2) for more information.

      \n

      This method will throw an error if the target pid does not exist. As a special\ncase, a signal of 0 can be used to test for the existence of a process.\nWindows platforms will throw an error if the pid is used to kill a process\ngroup.

      \n

      Even though the name of this function is process.kill(), it is really just a\nsignal sender, like the kill system call. The signal sent may do something\nother than kill the target process.

      \n
      process.on('SIGHUP', () => {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');\n
      \n

      When SIGUSR1 is received by a Node.js process, Node.js will start the\ndebugger. See Signal Events.

      " + }, + { + "textRaw": "`process.memoryUsage()`", + "type": "method", + "name": "memoryUsage", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/31550", + "description": "Added `arrayBuffers` to the returned object." + }, + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/9587", + "description": "Added `external` to the returned object." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`rss` {integer}", + "name": "rss", + "type": "integer" + }, + { + "textRaw": "`heapTotal` {integer}", + "name": "heapTotal", + "type": "integer" + }, + { + "textRaw": "`heapUsed` {integer}", + "name": "heapUsed", + "type": "integer" + }, + { + "textRaw": "`external` {integer}", + "name": "external", + "type": "integer" + }, + { + "textRaw": "`arrayBuffers` {integer}", + "name": "arrayBuffers", + "type": "integer" + } + ] + }, + "params": [] + } + ], + "desc": "

      The process.memoryUsage() method returns an object describing the memory usage\nof the Node.js process measured in bytes.

      \n

      For example, the code:

      \n
      console.log(process.memoryUsage());\n
      \n

      Will generate:

      \n\n
      {\n  rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472,\n  external: 49879,\n  arrayBuffers: 9386\n}\n
      \n
        \n
      • heapTotal and heapUsed refer to V8's memory usage.
      • \n
      • external refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8.
      • \n
      • rss, Resident Set Size, is the amount of space occupied in the main\nmemory device (that is a subset of the total allocated memory) for the\nprocess, including all C++ and JavaScript objects and code.
      • \n
      • arrayBuffers refers to memory allocated for ArrayBuffers and\nSharedArrayBuffers, including all Node.js Buffers.\nThis is also included in the external value. When Node.js is used as an\nembedded library, this value may be 0 because allocations for ArrayBuffers\nmay not be tracked in that case.
      • \n
      \n

      When using Worker threads, rss will be a value that is valid for the\nentire process, while the other fields will only refer to the current thread.

      " + }, + { + "textRaw": "`process.nextTick(callback[, ...args])`", + "type": "method", + "name": "nextTick", + "meta": { + "added": [ + "v0.1.26" + ], + "changes": [ + { + "version": "v1.8.1", + "pr-url": "https://github.com/nodejs/node/pull/1077", + "description": "Additional arguments after `callback` are now supported." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + }, + { + "textRaw": "`...args` {any} Additional arguments to pass when invoking the `callback`", + "name": "...args", + "type": "any", + "desc": "Additional arguments to pass when invoking the `callback`" + } + ] + } + ], + "desc": "

      process.nextTick() adds callback to the \"next tick queue\". This queue is\nfully drained after the current operation on the JavaScript stack runs to\ncompletion and before the event loop is allowed to continue. It's possible to\ncreate an infinite loop if one were to recursively call process.nextTick().\nSee the Event Loop guide for more background.

      \n
      console.log('start');\nprocess.nextTick(() => {\n  console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
      \n

      This is important when developing APIs in order to give users the opportunity\nto assign event handlers after an object has been constructed but before any\nI/O has occurred:

      \n
      function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
      \n

      It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:

      \n
      // WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
      \n

      This API is hazardous because in the following case:

      \n
      const maybeTrue = Math.random() > 0.5;\n\nmaybeSync(maybeTrue, () => {\n  foo();\n});\n\nbar();\n
      \n

      It is not clear whether foo() or bar() will be called first.

      \n

      The following approach is much better:

      \n
      function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
      " + }, + { + "textRaw": "`process.resourceUsage()`", + "type": "method", + "name": "resourceUsage", + "meta": { + "added": [ + "v12.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t].", + "name": "return", + "type": "Object", + "desc": "the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t].", + "options": [ + { + "textRaw": "`userCPUTime` {integer} maps to `ru_utime` computed in microseconds. It is the same value as [`process.cpuUsage().user`][process.cpuUsage].", + "name": "userCPUTime", + "type": "integer", + "desc": "maps to `ru_utime` computed in microseconds. It is the same value as [`process.cpuUsage().user`][process.cpuUsage]." + }, + { + "textRaw": "`systemCPUTime` {integer} maps to `ru_stime` computed in microseconds. It is the same value as [`process.cpuUsage().system`][process.cpuUsage].", + "name": "systemCPUTime", + "type": "integer", + "desc": "maps to `ru_stime` computed in microseconds. It is the same value as [`process.cpuUsage().system`][process.cpuUsage]." + }, + { + "textRaw": "`maxRSS` {integer} maps to `ru_maxrss` which is the maximum resident set size used in kilobytes.", + "name": "maxRSS", + "type": "integer", + "desc": "maps to `ru_maxrss` which is the maximum resident set size used in kilobytes." + }, + { + "textRaw": "`sharedMemorySize` {integer} maps to `ru_ixrss` but is not supported by any platform.", + "name": "sharedMemorySize", + "type": "integer", + "desc": "maps to `ru_ixrss` but is not supported by any platform." + }, + { + "textRaw": "`unsharedDataSize` {integer} maps to `ru_idrss` but is not supported by any platform.", + "name": "unsharedDataSize", + "type": "integer", + "desc": "maps to `ru_idrss` but is not supported by any platform." + }, + { + "textRaw": "`unsharedStackSize` {integer} maps to `ru_isrss` but is not supported by any platform.", + "name": "unsharedStackSize", + "type": "integer", + "desc": "maps to `ru_isrss` but is not supported by any platform." + }, + { + "textRaw": "`minorPageFault` {integer} maps to `ru_minflt` which is the number of minor page faults for the process, see [this article for more details][wikipedia_minor_fault].", + "name": "minorPageFault", + "type": "integer", + "desc": "maps to `ru_minflt` which is the number of minor page faults for the process, see [this article for more details][wikipedia_minor_fault]." + }, + { + "textRaw": "`majorPageFault` {integer} maps to `ru_majflt` which is the number of major page faults for the process, see [this article for more details][wikipedia_major_fault]. This field is not supported on Windows.", + "name": "majorPageFault", + "type": "integer", + "desc": "maps to `ru_majflt` which is the number of major page faults for the process, see [this article for more details][wikipedia_major_fault]. This field is not supported on Windows." + }, + { + "textRaw": "`swappedOut` {integer} maps to `ru_nswap` but is not supported by any platform.", + "name": "swappedOut", + "type": "integer", + "desc": "maps to `ru_nswap` but is not supported by any platform." + }, + { + "textRaw": "`fsRead` {integer} maps to `ru_inblock` which is the number of times the file system had to perform input.", + "name": "fsRead", + "type": "integer", + "desc": "maps to `ru_inblock` which is the number of times the file system had to perform input." + }, + { + "textRaw": "`fsWrite` {integer} maps to `ru_oublock` which is the number of times the file system had to perform output.", + "name": "fsWrite", + "type": "integer", + "desc": "maps to `ru_oublock` which is the number of times the file system had to perform output." + }, + { + "textRaw": "`ipcSent` {integer} maps to `ru_msgsnd` but is not supported by any platform.", + "name": "ipcSent", + "type": "integer", + "desc": "maps to `ru_msgsnd` but is not supported by any platform." + }, + { + "textRaw": "`ipcReceived` {integer} maps to `ru_msgrcv` but is not supported by any platform.", + "name": "ipcReceived", + "type": "integer", + "desc": "maps to `ru_msgrcv` but is not supported by any platform." + }, + { + "textRaw": "`signalsCount` {integer} maps to `ru_nsignals` but is not supported by any platform.", + "name": "signalsCount", + "type": "integer", + "desc": "maps to `ru_nsignals` but is not supported by any platform." + }, + { + "textRaw": "`voluntaryContextSwitches` {integer} maps to `ru_nvcsw` which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows.", + "name": "voluntaryContextSwitches", + "type": "integer", + "desc": "maps to `ru_nvcsw` which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows." + }, + { + "textRaw": "`involuntaryContextSwitches` {integer} maps to `ru_nivcsw` which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows.", + "name": "involuntaryContextSwitches", + "type": "integer", + "desc": "maps to `ru_nivcsw` which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows." + } + ] + }, + "params": [] + } + ], + "desc": "
      console.log(process.resourceUsage());\n/*\n  Will output:\n  {\n    userCPUTime: 82872,\n    systemCPUTime: 4143,\n    maxRSS: 33164,\n    sharedMemorySize: 0,\n    unsharedDataSize: 0,\n    unsharedStackSize: 0,\n    minorPageFault: 2469,\n    majorPageFault: 0,\n    swappedOut: 0,\n    fsRead: 0,\n    fsWrite: 8,\n    ipcSent: 0,\n    ipcReceived: 0,\n    signalsCount: 0,\n    voluntaryContextSwitches: 79,\n    involuntaryContextSwitches: 1\n  }\n*/\n
      " + }, + { + "textRaw": "`process.send(message[, sendHandle[, options]][, callback])`", + "type": "method", + "name": "send", + "meta": { + "added": [ + "v0.5.9" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`message` {Object}", + "name": "message", + "type": "Object" + }, + { + "textRaw": "`sendHandle` {net.Server|net.Socket}", + "name": "sendHandle", + "type": "net.Server|net.Socket" + }, + { + "textRaw": "`options` {Object} used to parameterize the sending of certain types of handles.`options` supports the following properties:", + "name": "options", + "type": "Object", + "desc": "used to parameterize the sending of certain types of handles.`options` supports the following properties:", + "options": [ + { + "textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.", + "name": "keepOpen", + "type": "boolean", + "default": "`false`", + "desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      If Node.js is spawned with an IPC channel, the process.send() method can be\nused to send messages to the parent process. Messages will be received as a\n'message' event on the parent's ChildProcess object.

      \n

      If Node.js was not spawned with an IPC channel, process.send will be\nundefined.

      \n

      The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.

      " + }, + { + "textRaw": "`process.setegid(id)`", + "type": "method", + "name": "setegid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {string|number} A group name or ID", + "name": "id", + "type": "string|number", + "desc": "A group name or ID" + } + ] + } + ], + "desc": "

      The process.setegid() method sets the effective group identity of the process.\n(See setegid(2).) The id can be passed as either a numeric ID or a group\nname string. If a group name is specified, this method blocks while resolving\nthe associated a numeric ID.

      \n
      if (process.getegid && process.setegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n  try {\n    process.setegid(501);\n    console.log(`New gid: ${process.getegid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.seteuid(id)`", + "type": "method", + "name": "seteuid", + "meta": { + "added": [ + "v2.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {string|number} A user name or ID", + "name": "id", + "type": "string|number", + "desc": "A user name or ID" + } + ] + } + ], + "desc": "

      The process.seteuid() method sets the effective user identity of the process.\n(See seteuid(2).) The id can be passed as either a numeric ID or a username\nstring. If a username is specified, the method blocks while resolving the\nassociated numeric ID.

      \n
      if (process.geteuid && process.seteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n  try {\n    process.seteuid(501);\n    console.log(`New uid: ${process.geteuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setgid(id)`", + "type": "method", + "name": "setgid", + "meta": { + "added": [ + "v0.1.31" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {string|number} The group name or ID", + "name": "id", + "type": "string|number", + "desc": "The group name or ID" + } + ] + } + ], + "desc": "

      The process.setgid() method sets the group identity of the process. (See\nsetgid(2).) The id can be passed as either a numeric ID or a group name\nstring. If a group name is specified, this method blocks while resolving the\nassociated numeric ID.

      \n
      if (process.getgid && process.setgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n  try {\n    process.setgid(501);\n    console.log(`New gid: ${process.getgid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setgroups(groups)`", + "type": "method", + "name": "setgroups", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`groups` {integer[]}", + "name": "groups", + "type": "integer[]" + } + ] + } + ], + "desc": "

      The process.setgroups() method sets the supplementary group IDs for the\nNode.js process. This is a privileged operation that requires the Node.js\nprocess to have root or the CAP_SETGID capability.

      \n

      The groups array can contain numeric group IDs, group names or both.

      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setuid(id)`", + "type": "method", + "name": "setuid", + "meta": { + "added": [ + "v0.1.28" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {integer | string}", + "name": "id", + "type": "integer | string" + } + ] + } + ], + "desc": "

      The process.setuid(id) method sets the user identity of the process. (See\nsetuid(2).) The id can be passed as either a numeric ID or a username string.\nIf a username is specified, the method blocks while resolving the associated\nnumeric ID.

      \n
      if (process.getuid && process.setuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n  try {\n    process.setuid(501);\n    console.log(`New uid: ${process.getuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
      \n

      This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

      " + }, + { + "textRaw": "`process.setUncaughtExceptionCaptureCallback(fn)`", + "type": "method", + "name": "setUncaughtExceptionCaptureCallback", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function|null}", + "name": "fn", + "type": "Function|null" + } + ] + } + ], + "desc": "

      The process.setUncaughtExceptionCaptureCallback() function sets a function\nthat will be invoked when an uncaught exception occurs, which will receive the\nexception value itself as its first argument.

      \n

      If such a function is set, the 'uncaughtException' event will\nnot be emitted. If --abort-on-uncaught-exception was passed from the\ncommand line or set through v8.setFlagsFromString(), the process will\nnot abort.

      \n

      To unset the capture function,\nprocess.setUncaughtExceptionCaptureCallback(null) may be used. Calling this\nmethod with a non-null argument while another capture function is set will\nthrow an error.

      \n

      Using this function is mutually exclusive with using the deprecated\ndomain built-in module.

      " + }, + { + "textRaw": "`process.umask()`", + "type": "method", + "name": "umask", + "meta": { + "added": [ + "v0.1.19" + ], + "changes": [ + { + "version": [ + "v12.19.0", + "v14.0.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/32499", + "description": "Calling `process.umask()` with no arguments is deprecated." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated. Calling `process.umask()` with no argument causes\nthe process-wide umask to be written twice. This introduces a race condition\nbetween threads, and is a potential security vulnerability. There is no safe,\ncross-platform alternative API.", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      process.umask() returns the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process.

      " + }, + { + "textRaw": "`process.umask(mask)`", + "type": "method", + "name": "umask", + "meta": { + "added": [ + "v0.1.19" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`mask` {string|integer}", + "name": "mask", + "type": "string|integer" + } + ] + } + ], + "desc": "

      process.umask(mask) sets the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process. Returns the previous mask.

      \n
      const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
      \n

      In Worker threads, process.umask(mask) will throw an exception.

      " + }, + { + "textRaw": "`process.uptime()`", + "type": "method", + "name": "uptime", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [] + } + ], + "desc": "

      The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.

      \n

      The return value includes fractions of a second. Use Math.floor() to get whole\nseconds.

      " + } + ], + "properties": [ + { + "textRaw": "`allowedNodeEnvironmentFlags` {Set}", + "type": "Set", + "name": "allowedNodeEnvironmentFlags", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "desc": "

      The process.allowedNodeEnvironmentFlags property is a special,\nread-only Set of flags allowable within the NODE_OPTIONS\nenvironment variable.

      \n

      process.allowedNodeEnvironmentFlags extends Set, but overrides\nSet.prototype.has to recognize several different possible flag\nrepresentations. process.allowedNodeEnvironmentFlags.has() will\nreturn true in the following cases:

      \n
        \n
      • Flags may omit leading single (-) or double (--) dashes; e.g.,\ninspect-brk for --inspect-brk, or r for -r.
      • \n
      • Flags passed through to V8 (as listed in --v8-options) may replace\none or more non-leading dashes for an underscore, or vice-versa;\ne.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof,\netc.
      • \n
      • Flags may contain one or more equals (=) characters; all\ncharacters after and including the first equals will be ignored;\ne.g., --stack-trace-limit=100.
      • \n
      • Flags must be allowable within NODE_OPTIONS.
      • \n
      \n

      When iterating over process.allowedNodeEnvironmentFlags, flags will\nappear only once; each will begin with one or more dashes. Flags\npassed through to V8 will contain underscores instead of non-leading\ndashes:

      \n
      process.allowedNodeEnvironmentFlags.forEach((flag) => {\n  // -r\n  // --inspect-brk\n  // --abort_on_uncaught_exception\n  // ...\n});\n
      \n

      The methods add(), clear(), and delete() of\nprocess.allowedNodeEnvironmentFlags do nothing, and will fail\nsilently.

      \n

      If Node.js was compiled without NODE_OPTIONS support (shown in\nprocess.config), process.allowedNodeEnvironmentFlags will\ncontain what would have been allowable.

      " + }, + { + "textRaw": "`arch` {string}", + "type": "string", + "name": "arch", + "meta": { + "added": [ + "v0.5.0" + ], + "changes": [] + }, + "desc": "

      The operating system CPU architecture for which the Node.js binary was compiled.\nPossible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc',\n'ppc64', 's390', 's390x', 'x32', and 'x64'.

      \n
      console.log(`This processor architecture is ${process.arch}`);\n
      " + }, + { + "textRaw": "`argv` {string[]}", + "type": "string[]", + "name": "argv", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [] + }, + "desc": "

      The process.argv property returns an array containing the command line\narguments passed when the Node.js process was launched. The first element will\nbe process.execPath. See process.argv0 if access to the original value\nof argv[0] is needed. The second element will be the path to the JavaScript\nfile being executed. The remaining elements will be any additional command line\narguments.

      \n

      For example, assuming the following script for process-args.js:

      \n
      // print process.argv\nprocess.argv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n
      \n

      Launching the Node.js process as:

      \n
      $ node process-args.js one two=three four\n
      \n

      Would generate the output:

      \n
      0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-args.js\n2: one\n3: two=three\n4: four\n
      " + }, + { + "textRaw": "`argv0` {string}", + "type": "string", + "name": "argv0", + "meta": { + "added": [ + "v6.4.0" + ], + "changes": [] + }, + "desc": "

      The process.argv0 property stores a read-only copy of the original value of\nargv[0] passed when Node.js starts.

      \n
      $ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
      " + }, + { + "textRaw": "`channel` {Object}", + "type": "Object", + "name": "channel", + "meta": { + "added": [ + "v7.1.0" + ], + "changes": [] + }, + "desc": "

      If the Node.js process was spawned with an IPC channel (see the\nChild Process documentation), the process.channel\nproperty is a reference to the IPC channel. If no IPC channel exists, this\nproperty is undefined.

      " + }, + { + "textRaw": "`config` {Object}", + "type": "Object", + "name": "config", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      The process.config property returns an Object containing the JavaScript\nrepresentation of the configure options used to compile the current Node.js\nexecutable. This is the same as the config.gypi file that was produced when\nrunning the ./configure script.

      \n

      An example of the possible output looks like:

      \n\n
      {\n  target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   {\n     host_arch: 'x64',\n     napi_build_version: 5,\n     node_install_npm: 'true',\n     node_prefix: '',\n     node_shared_cares: 'false',\n     node_shared_http_parser: 'false',\n     node_shared_libuv: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 1\n   }\n}\n
      \n

      The process.config property is not read-only and there are existing\nmodules in the ecosystem that are known to extend, modify, or entirely replace\nthe value of process.config.

      " + }, + { + "textRaw": "`connected` {boolean}", + "type": "boolean", + "name": "connected", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "desc": "

      If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.connected property will return\ntrue so long as the IPC channel is connected and will return false after\nprocess.disconnect() is called.

      \n

      Once process.connected is false, it is no longer possible to send messages\nover the IPC channel using process.send().

      " + }, + { + "textRaw": "`debugPort` {number}", + "type": "number", + "name": "debugPort", + "meta": { + "added": [ + "v0.7.2" + ], + "changes": [] + }, + "desc": "

      The port used by the Node.js debugger when enabled.

      \n
      process.debugPort = 5858;\n
      " + }, + { + "textRaw": "`env` {Object}", + "type": "Object", + "name": "env", + "meta": { + "added": [ + "v0.1.27" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26544", + "description": "Worker threads will now use a copy of the parent thread’s `process.env` by default, configurable through the `env` option of the `Worker` constructor." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18990", + "description": "Implicit conversion of variable value to string is deprecated." + } + ] + }, + "desc": "

      The process.env property returns an object containing the user environment.\nSee environ(7).

      \n

      An example of this object looks like:

      \n\n
      {\n  TERM: 'xterm-256color',\n  SHELL: '/usr/local/bin/bash',\n  USER: 'maciej',\n  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n  PWD: '/Users/maciej',\n  EDITOR: 'vim',\n  SHLVL: '1',\n  HOME: '/Users/maciej',\n  LOGNAME: 'maciej',\n  _: '/usr/local/bin/node'\n}\n
      \n

      It is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process, or (unless explicitly requested)\nto other Worker threads.\nIn other words, the following example would not work:

      \n
      $ node -e 'process.env.foo = \"bar\"' && echo $foo\n
      \n

      While the following will:

      \n
      process.env.foo = 'bar';\nconsole.log(process.env.foo);\n
      \n

      Assigning a property on process.env will implicitly convert the value\nto a string. This behavior is deprecated. Future versions of Node.js may\nthrow an error when the value is not a string, number, or boolean.

      \n
      process.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
      \n

      Use delete to delete a property from process.env.

      \n
      process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
      \n

      On Windows operating systems, environment variables are case-insensitive.

      \n
      process.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
      \n

      Unless explicitly specified when creating a Worker instance,\neach Worker thread has its own copy of process.env, based on its\nparent thread’s process.env, or whatever was specified as the env option\nto the Worker constructor. Changes to process.env will not be visible\nacross Worker threads, and only the main thread can make changes that\nare visible to the operating system or to native add-ons.

      " + }, + { + "textRaw": "`execArgv` {string[]}", + "type": "string[]", + "name": "execArgv", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      The process.execArgv property returns the set of Node.js-specific command-line\noptions passed when the Node.js process was launched. These options do not\nappear in the array returned by the process.argv property, and do not\ninclude the Node.js executable, the name of the script, or any options following\nthe script name. These options are useful in order to spawn child processes with\nthe same execution environment as the parent.

      \n
      $ node --harmony script.js --version\n
      \n

      Results in process.execArgv:

      \n\n
      ['--harmony']\n
      \n

      And process.argv:

      \n\n
      ['/usr/local/bin/node', 'script.js', '--version']\n
      " + }, + { + "textRaw": "`execPath` {string}", + "type": "string", + "name": "execPath", + "meta": { + "added": [ + "v0.1.100" + ], + "changes": [] + }, + "desc": "

      The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process. Symbolic links, if any, are resolved.

      \n\n
      '/usr/local/bin/node'\n
      " + }, + { + "textRaw": "`exitCode` {integer}", + "type": "integer", + "name": "exitCode", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "desc": "

      A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit() without specifying\na code.

      \n

      Specifying a code to process.exit(code) will override any\nprevious setting of process.exitCode.

      " + }, + { + "textRaw": "`mainModule` {Object}", + "type": "Object", + "name": "mainModule", + "meta": { + "added": [ + "v0.1.17" + ], + "changes": [] + }, + "desc": "

      The process.mainModule property provides an alternative way of retrieving\nrequire.main. The difference is that if the main module changes at\nruntime, require.main may still refer to the original main module in\nmodules that were required before the change occurred. Generally, it's\nsafe to assume that the two refer to the same module.

      \n

      As with require.main, process.mainModule will be undefined if there\nis no entry script.

      " + }, + { + "textRaw": "`noDeprecation` {boolean}", + "type": "boolean", + "name": "noDeprecation", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      The process.noDeprecation property indicates whether the --no-deprecation\nflag is set on the current Node.js process. See the documentation for\nthe 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

      " + }, + { + "textRaw": "`pid` {integer}", + "type": "integer", + "name": "pid", + "meta": { + "added": [ + "v0.1.15" + ], + "changes": [] + }, + "desc": "

      The process.pid property returns the PID of the process.

      \n
      console.log(`This process is pid ${process.pid}`);\n
      " + }, + { + "textRaw": "`platform` {string}", + "type": "string", + "name": "platform", + "meta": { + "added": [ + "v0.1.16" + ], + "changes": [] + }, + "desc": "

      The process.platform property returns a string identifying the operating\nsystem platform on which the Node.js process is running.

      \n

      Currently possible values are:

      \n
        \n
      • 'aix'
      • \n
      • 'darwin'
      • \n
      • 'freebsd'
      • \n
      • 'linux'
      • \n
      • 'openbsd'
      • \n
      • 'sunos'
      • \n
      • 'win32'
      • \n
      \n
      console.log(`This platform is ${process.platform}`);\n
      \n

      The value 'android' may also be returned if the Node.js is built on the\nAndroid operating system. However, Android support in Node.js\nis experimental.

      " + }, + { + "textRaw": "`ppid` {integer}", + "type": "integer", + "name": "ppid", + "meta": { + "added": [ + "v9.2.0", + "v8.10.0", + "v6.13.0" + ], + "changes": [] + }, + "desc": "

      The process.ppid property returns the PID of the parent of the\ncurrent process.

      \n
      console.log(`The parent process is pid ${process.ppid}`);\n
      " + }, + { + "textRaw": "`release` {Object}", + "type": "Object", + "name": "release", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [ + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3212", + "description": "The `lts` property is now supported." + } + ] + }, + "desc": "

      The process.release property returns an Object containing metadata related\nto the current release, including URLs for the source tarball and headers-only\ntarball.

      \n

      process.release contains the following properties:

      \n
        \n
      • name <string> A value that will always be 'node' for Node.js. For\nlegacy io.js releases, this will be 'io.js'.
      • \n
      • sourceUrl <string> an absolute URL pointing to a .tar.gz file containing\nthe source code of the current release.
      • \n
      • headersUrl<string> an absolute URL pointing to a .tar.gz file containing\nonly the source header files for the current release. This file is\nsignificantly smaller than the full source file and can be used for compiling\nNode.js native add-ons.
      • \n
      • libUrl <string> an absolute URL pointing to a node.lib file matching the\narchitecture and version of the current release. This file is used for\ncompiling Node.js native add-ons. This property is only present on Windows\nbuilds of Node.js and will be missing on all other platforms.
      • \n
      • lts <string> a string label identifying the LTS label for this release.\nThis property only exists for LTS releases and is undefined for all other\nrelease types, including Current releases.\nValid values include the LTS Release Codenames (including those\nthat are no longer supported). A non-exhaustive example of\nthese codenames includes:\n
          \n
        • 'Dubnium' for the 10.x LTS line beginning with 10.13.0.
        • \n
        • 'Erbium' for the 12.x LTS line beginning with 12.13.0.\nFor other LTS Release Codenames, see Node.js Changelog Archive
        • \n
        \n
      • \n
      \n\n
      {\n  name: 'node',\n  lts: 'Erbium',\n  sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib'\n}\n
      \n

      In custom builds from non-release versions of the source tree, only the\nname property may be present. The additional properties should not be\nrelied upon to exist.

      " + }, + { + "textRaw": "`report` {Object}", + "type": "Object", + "name": "report", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      process.report is an object whose methods are used to generate diagnostic\nreports for the current process. Additional documentation is available in the\nreport documentation.

      ", + "properties": [ + { + "textRaw": "`compact` {boolean}", + "type": "boolean", + "name": "compact", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      Write reports in a compact format, single-line JSON, more easily consumable\nby log processing systems than the default multi-line format designed for\nhuman consumption.

      \n
      console.log(`Reports are compact? ${process.report.compact}`);\n
      " + }, + { + "textRaw": "`directory` {string}", + "type": "string", + "name": "directory", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      Directory where the report is written. The default value is the empty string,\nindicating that reports are written to the current working directory of the\nNode.js process.

      \n
      console.log(`Report directory is ${process.report.directory}`);\n
      " + }, + { + "textRaw": "`filename` {string}", + "type": "string", + "name": "filename", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      Filename where the report is written. If set to the empty string, the output\nfilename will be comprised of a timestamp, PID, and sequence number. The default\nvalue is the empty string.

      \n
      console.log(`Report filename is ${process.report.filename}`);\n
      " + }, + { + "textRaw": "`reportOnFatalError` {boolean}", + "type": "boolean", + "name": "reportOnFatalError", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      If true, a diagnostic report is generated on fatal errors, such as out of\nmemory errors or failed C++ assertions.

      \n
      console.log(`Report on fatal error: ${process.report.reportOnFatalError}`);\n
      " + }, + { + "textRaw": "`reportOnSignal` {boolean}", + "type": "boolean", + "name": "reportOnSignal", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      If true, a diagnostic report is generated when the process receives the\nsignal specified by process.report.signal.

      \n
      console.log(`Report on signal: ${process.report.reportOnSignal}`);\n
      " + }, + { + "textRaw": "`reportOnUncaughtException` {boolean}", + "type": "boolean", + "name": "reportOnUncaughtException", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      If true, a diagnostic report is generated on uncaught exception.

      \n
      console.log(`Report on exception: ${process.report.reportOnUncaughtException}`);\n
      " + }, + { + "textRaw": "`signal` {string}", + "type": "string", + "name": "signal", + "meta": { + "added": [ + "v11.12.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "desc": "

      The signal used to trigger the creation of a diagnostic report. Defaults to\n'SIGUSR2'.

      \n
      console.log(`Report signal: ${process.report.signal}`);\n
      " + } + ], + "methods": [ + { + "textRaw": "`process.report.getReport([err])`", + "type": "method", + "name": "getReport", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [ + { + "textRaw": "`err` {Error} A custom error used for reporting the JavaScript stack.", + "name": "err", + "type": "Error", + "desc": "A custom error used for reporting the JavaScript stack." + } + ] + } + ], + "desc": "

      Returns a JavaScript Object representation of a diagnostic report for the\nrunning process. The report's JavaScript stack trace is taken from err, if\npresent.

      \n
      const data = process.report.getReport();\nconsole.log(data.header.nodeJsVersion);\n\n// Similar to process.report.writeReport()\nconst fs = require('fs');\nfs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8');\n
      \n

      Additional documentation is available in the report documentation.

      " + }, + { + "textRaw": "`process.report.writeReport([filename][, err])`", + "type": "method", + "name": "writeReport", + "meta": { + "added": [ + "v11.8.0" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32242", + "description": "This API is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} Returns the filename of the generated report.", + "name": "return", + "type": "string", + "desc": "Returns the filename of the generated report." + }, + "params": [ + { + "textRaw": "`filename` {string} Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js process, if unspecified.", + "name": "filename", + "type": "string", + "desc": "Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js process, if unspecified." + }, + { + "textRaw": "`err` {Error} A custom error used for reporting the JavaScript stack.", + "name": "err", + "type": "Error", + "desc": "A custom error used for reporting the JavaScript stack." + } + ] + } + ], + "desc": "

      Writes a diagnostic report to a file. If filename is not provided, the default\nfilename includes the date, time, PID, and a sequence number. The report's\nJavaScript stack trace is taken from err, if present.

      \n
      process.report.writeReport();\n
      \n

      Additional documentation is available in the report documentation.

      " + } + ] + }, + { + "textRaw": "`stderr` {Stream}", + "type": "Stream", + "name": "stderr", + "desc": "

      The process.stderr property returns a stream connected to\nstderr (fd 2). It is a net.Socket (which is a Duplex\nstream) unless fd 2 refers to a file, in which case it is\na Writable stream.

      \n

      process.stderr differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

      ", + "properties": [ + { + "textRaw": "`fd` {number}", + "type": "number", + "name": "fd", + "desc": "

      This property refers to the value of underlying file descriptor of\nprocess.stderr. The value is fixed at 2. In Worker threads,\nthis field does not exist.

      " + } + ] + }, + { + "textRaw": "`stdin` {Stream}", + "type": "Stream", + "name": "stdin", + "desc": "

      The process.stdin property returns a stream connected to\nstdin (fd 0). It is a net.Socket (which is a Duplex\nstream) unless fd 0 refers to a file, in which case it is\na Readable stream.

      \n

      For details of how to read from stdin see readable.read().

      \n

      As a Duplex stream, process.stdin can also be used in \"old\" mode that\nis compatible with scripts written for Node.js prior to v0.10.\nFor more information see Stream compatibility.

      \n

      In \"old\" streams mode the stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it. Note also that calling\nprocess.stdin.resume() itself would switch stream to \"old\" mode.

      ", + "properties": [ + { + "textRaw": "`fd` {number}", + "type": "number", + "name": "fd", + "desc": "

      This property refers to the value of underlying file descriptor of\nprocess.stdin. The value is fixed at 0. In Worker threads,\nthis field does not exist.

      " + } + ] + }, + { + "textRaw": "`stdout` {Stream}", + "type": "Stream", + "name": "stdout", + "desc": "

      The process.stdout property returns a stream connected to\nstdout (fd 1). It is a net.Socket (which is a Duplex\nstream) unless fd 1 refers to a file, in which case it is\na Writable stream.

      \n

      For example, to copy process.stdin to process.stdout:

      \n
      process.stdin.pipe(process.stdout);\n
      \n

      process.stdout differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

      ", + "properties": [ + { + "textRaw": "`fd` {number}", + "type": "number", + "name": "fd", + "desc": "

      This property refers to the value of underlying file descriptor of\nprocess.stdout. The value is fixed at 1. In Worker threads,\nthis field does not exist.

      " + } + ], + "modules": [ + { + "textRaw": "A note on process I/O", + "name": "a_note_on_process_i/o", + "desc": "

      process.stdout and process.stderr differ from other Node.js streams in\nimportant ways:

      \n
        \n
      1. They are used internally by console.log() and console.error(),\nrespectively.
      2. \n
      3. Writes may be synchronous depending on what the stream is connected to\nand whether the system is Windows or POSIX:\n
          \n
        • Files: synchronous on Windows and POSIX
        • \n
        • TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
        • \n
        • Pipes (and sockets): synchronous on Windows, asynchronous on POSIX
        • \n
        \n
      4. \n
      \n

      These behaviors are partly for historical reasons, as changing them would\ncreate backward incompatibility, but they are also expected by some users.

      \n

      Synchronous writes avoid problems such as output written with console.log() or\nconsole.error() being unexpectedly interleaved, or not written at all if\nprocess.exit() is called before an asynchronous write completes. See\nprocess.exit() for more information.

      \n

      Warning: Synchronous writes block the event loop until the write has\ncompleted. This can be near instantaneous in the case of output to a file, but\nunder high system load, pipes that are not being read at the receiving end, or\nwith slow terminals or file systems, its possible for the event loop to be\nblocked often enough and long enough to have severe negative performance\nimpacts. This may not be a problem when writing to an interactive terminal\nsession, but consider this particularly careful when doing production logging to\nthe process output streams.

      \n

      To check if a stream is connected to a TTY context, check the isTTY\nproperty.

      \n

      For instance:

      \n
      $ node -p \"Boolean(process.stdin.isTTY)\"\ntrue\n$ echo \"foo\" | node -p \"Boolean(process.stdin.isTTY)\"\nfalse\n$ node -p \"Boolean(process.stdout.isTTY)\"\ntrue\n$ node -p \"Boolean(process.stdout.isTTY)\" | cat\nfalse\n
      \n

      See the TTY documentation for more information.

      ", + "type": "module", + "displayName": "A note on process I/O" + } + ] + }, + { + "textRaw": "`throwDeprecation` {boolean}", + "type": "boolean", + "name": "throwDeprecation", + "meta": { + "added": [ + "v0.9.12" + ], + "changes": [] + }, + "desc": "

      The initial value of process.throwDeprecation indicates whether the\n--throw-deprecation flag is set on the current Node.js process.\nprocess.throwDeprecation is mutable, so whether or not deprecation\nwarnings result in errors may be altered at runtime. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information.

      \n
      $ node --throw-deprecation -p \"process.throwDeprecation\"\ntrue\n$ node -p \"process.throwDeprecation\"\nundefined\n$ node\n> process.emitWarning('test', 'DeprecationWarning');\nundefined\n> (node:26598) DeprecationWarning: test\n> process.throwDeprecation = true;\ntrue\n> process.emitWarning('test', 'DeprecationWarning');\nThrown:\n[DeprecationWarning: test] { name: 'DeprecationWarning' }\n
      " + }, + { + "textRaw": "`title` {string}", + "type": "string", + "name": "title", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "desc": "

      The process.title property returns the current process title (i.e. returns\nthe current value of ps). Assigning a new value to process.title modifies\nthe current value of ps.

      \n

      When a new value is assigned, different platforms will impose different maximum\nlength restrictions on the title. Usually such restrictions are quite limited.\nFor instance, on Linux and macOS, process.title is limited to the size of the\nbinary name plus the length of the command line arguments because setting the\nprocess.title overwrites the argv memory of the process. Node.js v0.8\nallowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure and confusing in some (rather obscure)\ncases.

      \n

      Assigning a value to process.title might not result in an accurate label\nwithin process manager applications such as macOS Activity Monitor or Windows\nServices Manager.

      " + }, + { + "textRaw": "`traceDeprecation` {boolean}", + "type": "boolean", + "name": "traceDeprecation", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [] + }, + "desc": "

      The process.traceDeprecation property indicates whether the\n--trace-deprecation flag is set on the current Node.js process. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

      " + }, + { + "textRaw": "`version` {string}", + "type": "string", + "name": "version", + "meta": { + "added": [ + "v0.1.3" + ], + "changes": [] + }, + "desc": "

      The process.version property contains the Node.js version string.

      \n
      console.log(`Version: ${process.version}`);\n// Version: v14.8.0\n
      \n

      To get the version string without the prepended v, use\nprocess.versions.node.

      " + }, + { + "textRaw": "`versions` {Object}", + "type": "Object", + "name": "versions", + "meta": { + "added": [ + "v0.2.0" + ], + "changes": [ + { + "version": "v4.2.0", + "pr-url": "https://github.com/nodejs/node/pull/3102", + "description": "The `icu` property is now supported." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15785", + "description": "The `v8` property now includes a Node.js specific suffix." + } + ] + }, + "desc": "

      The process.versions property returns an object listing the version strings of\nNode.js and its dependencies. process.versions.modules indicates the current\nABI version, which is increased whenever a C++ API changes. Node.js will refuse\nto load modules that were compiled against a different module ABI version.

      \n
      console.log(process.versions);\n
      \n

      Will generate an object similar to:

      \n
      { node: '11.13.0',\n  v8: '7.0.276.38-node.18',\n  uv: '1.27.0',\n  zlib: '1.2.11',\n  brotli: '1.0.7',\n  ares: '1.15.0',\n  modules: '67',\n  nghttp2: '1.34.0',\n  napi: '4',\n  llhttp: '1.1.1',\n  http_parser: '2.8.0',\n  openssl: '1.1.1b',\n  cldr: '34.0',\n  icu: '63.1',\n  tz: '2018e',\n  unicode: '11.0' }\n
      " + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/punycode.html b/doc/api/punycode.html new file mode 100644 index 0000000000000000000000000000000000000000..26d0f95d85f6fc0627da5832e61940d08ecc7652 --- /dev/null +++ b/doc/api/punycode.html @@ -0,0 +1,266 @@ + + + + + + + Punycode | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Punycode#

      + + +

      Stability: 0 - Deprecated

      +

      Source Code: lib/punycode.js

      +

      The version of the punycode module bundled in Node.js is being deprecated. +In a future major version of Node.js this module will be removed. Users +currently depending on the punycode module should switch to using the +userland-provided Punycode.js module instead.

      +

      The punycode module is a bundled version of the Punycode.js module. It +can be accessed using:

      +
      const punycode = require('punycode');
      +

      Punycode is a character encoding scheme defined by RFC 3492 that is +primarily intended for use in Internationalized Domain Names. Because host +names in URLs are limited to ASCII characters only, Domain Names that contain +non-ASCII characters must be converted into ASCII using the Punycode scheme. +For instance, the Japanese character that translates into the English word, +'example' is '例'. The Internationalized Domain Name, '例.com' (equivalent +to 'example.com') is represented by Punycode as the ASCII string +'xn--fsq.com'.

      +

      The punycode module provides a simple implementation of the Punycode standard.

      +

      The punycode module is a third-party dependency used by Node.js and +made available to developers as a convenience. Fixes or other modifications to +the module must be directed to the Punycode.js project.

      +

      punycode.decode(string)#

      + + +

      The punycode.decode() method converts a Punycode string of ASCII-only +characters to the equivalent string of Unicode codepoints.

      +
      punycode.decode('maana-pta'); // 'mañana'
      +punycode.decode('--dqo34k'); // '☃-⌘'
      +

      punycode.encode(string)#

      + + +

      The punycode.encode() method converts a string of Unicode codepoints to a +Punycode string of ASCII-only characters.

      +
      punycode.encode('mañana'); // 'maana-pta'
      +punycode.encode('☃-⌘'); // '--dqo34k'
      +

      punycode.toASCII(domain)#

      + + +

      The punycode.toASCII() method converts a Unicode string representing an +Internationalized Domain Name to Punycode. Only the non-ASCII parts of the +domain name will be converted. Calling punycode.toASCII() on a string that +already only contains ASCII characters will have no effect.

      +
      // encode domain names
      +punycode.toASCII('mañana.com');  // 'xn--maana-pta.com'
      +punycode.toASCII('☃-⌘.com');   // 'xn----dqo34k.com'
      +punycode.toASCII('example.com'); // 'example.com'
      +

      punycode.toUnicode(domain)#

      + + +

      The punycode.toUnicode() method converts a string representing a domain name +containing Punycode encoded characters into Unicode. Only the Punycode +encoded parts of the domain name are be converted.

      +
      // decode domain names
      +punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
      +punycode.toUnicode('xn----dqo34k.com');  // '☃-⌘.com'
      +punycode.toUnicode('example.com');       // 'example.com'
      +

      punycode.ucs2#

      + +

      punycode.ucs2.decode(string)#

      + + +

      The punycode.ucs2.decode() method returns an array containing the numeric +codepoint values of each Unicode symbol in the string.

      +
      punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]
      +// surrogate pair for U+1D306 tetragram for centre:
      +punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
      +

      punycode.ucs2.encode(codePoints)#

      + + +

      The punycode.ucs2.encode() method returns a string based on an array of +numeric code point values.

      +
      punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'
      +punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
      +

      punycode.version#

      + + +

      Returns a string identifying the current Punycode.js version number.

      + +
      +
      +
      + + diff --git a/doc/api/punycode.json b/doc/api/punycode.json new file mode 100644 index 0000000000000000000000000000000000000000..b5e611d8f838a93c4531823a8bbe5ba8b77a60cc --- /dev/null +++ b/doc/api/punycode.json @@ -0,0 +1,188 @@ +{ + "type": "module", + "source": "doc/api/punycode.md", + "modules": [ + { + "textRaw": "Punycode", + "name": "punycode", + "meta": { + "deprecated": [ + "v7.0.0" + ], + "changes": [] + }, + "introduced_in": "v0.10.0", + "stability": 0, + "stabilityText": "Deprecated", + "desc": "

      Source Code: lib/punycode.js

      \n

      The version of the punycode module bundled in Node.js is being deprecated.\nIn a future major version of Node.js this module will be removed. Users\ncurrently depending on the punycode module should switch to using the\nuserland-provided Punycode.js module instead.

      \n

      The punycode module is a bundled version of the Punycode.js module. It\ncan be accessed using:

      \n
      const punycode = require('punycode');\n
      \n

      Punycode is a character encoding scheme defined by RFC 3492 that is\nprimarily intended for use in Internationalized Domain Names. Because host\nnames in URLs are limited to ASCII characters only, Domain Names that contain\nnon-ASCII characters must be converted into ASCII using the Punycode scheme.\nFor instance, the Japanese character that translates into the English word,\n'example' is '例'. The Internationalized Domain Name, '例.com' (equivalent\nto 'example.com') is represented by Punycode as the ASCII string\n'xn--fsq.com'.

      \n

      The punycode module provides a simple implementation of the Punycode standard.

      \n

      The punycode module is a third-party dependency used by Node.js and\nmade available to developers as a convenience. Fixes or other modifications to\nthe module must be directed to the Punycode.js project.

      ", + "methods": [ + { + "textRaw": "`punycode.decode(string)`", + "type": "method", + "name": "decode", + "meta": { + "added": [ + "v0.5.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.decode() method converts a Punycode string of ASCII-only\ncharacters to the equivalent string of Unicode codepoints.

      \n
      punycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n
      " + }, + { + "textRaw": "`punycode.encode(string)`", + "type": "method", + "name": "encode", + "meta": { + "added": [ + "v0.5.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.encode() method converts a string of Unicode codepoints to a\nPunycode string of ASCII-only characters.

      \n
      punycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n
      " + }, + { + "textRaw": "`punycode.toASCII(domain)`", + "type": "method", + "name": "toASCII", + "meta": { + "added": [ + "v0.6.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.toASCII() method converts a Unicode string representing an\nInternationalized Domain Name to Punycode. Only the non-ASCII parts of the\ndomain name will be converted. Calling punycode.toASCII() on a string that\nalready only contains ASCII characters will have no effect.

      \n
      // encode domain names\npunycode.toASCII('mañana.com');  // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com');   // 'xn----dqo34k.com'\npunycode.toASCII('example.com'); // 'example.com'\n
      " + }, + { + "textRaw": "`punycode.toUnicode(domain)`", + "type": "method", + "name": "toUnicode", + "meta": { + "added": [ + "v0.6.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.toUnicode() method converts a string representing a domain name\ncontaining Punycode encoded characters into Unicode. Only the Punycode\nencoded parts of the domain name are be converted.

      \n
      // decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com');  // '☃-⌘.com'\npunycode.toUnicode('example.com');       // 'example.com'\n
      " + } + ], + "properties": [ + { + "textRaw": "`punycode.ucs2`", + "name": "ucs2", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "methods": [ + { + "textRaw": "`punycode.ucs2.decode(string)`", + "type": "method", + "name": "decode", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The punycode.ucs2.decode() method returns an array containing the numeric\ncodepoint values of each Unicode symbol in the string.

      \n
      punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]\n
      " + }, + { + "textRaw": "`punycode.ucs2.encode(codePoints)`", + "type": "method", + "name": "encode", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`codePoints` {integer[]}", + "name": "codePoints", + "type": "integer[]" + } + ] + } + ], + "desc": "

      The punycode.ucs2.encode() method returns a string based on an array of\nnumeric code point values.

      \n
      punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'\n
      " + } + ] + }, + { + "textRaw": "`version` {string}", + "type": "string", + "name": "version", + "meta": { + "added": [ + "v0.6.1" + ], + "changes": [] + }, + "desc": "

      Returns a string identifying the current Punycode.js version number.

      " + } + ], + "type": "module", + "displayName": "Punycode" + } + ] +} \ No newline at end of file diff --git a/doc/api/querystring.html b/doc/api/querystring.html new file mode 100644 index 0000000000000000000000000000000000000000..de55d5ac30933c6b6720344413a8555fb8bf5ede --- /dev/null +++ b/doc/api/querystring.html @@ -0,0 +1,283 @@ + + + + + + + Query string | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Query string#

      + +

      Stability: 2 - Stable

      + +

      Source Code: lib/querystring.js

      +

      The querystring module provides utilities for parsing and formatting URL +query strings. It can be accessed using:

      +
      const querystring = require('querystring');
      +

      querystring.decode()#

      + +

      The querystring.decode() function is an alias for querystring.parse().

      +

      querystring.encode()#

      + +

      The querystring.encode() function is an alias for querystring.stringify().

      +

      querystring.escape(str)#

      + + +

      The querystring.escape() method performs URL percent-encoding on the given +str in a manner that is optimized for the specific requirements of URL +query strings.

      +

      The querystring.escape() method is used by querystring.stringify() and is +generally not expected to be used directly. It is exported primarily to allow +application code to provide a replacement percent-encoding implementation if +necessary by assigning querystring.escape to an alternative function.

      +

      querystring.parse(str[, sep[, eq[, options]]])#

      + +
        +
      • str <string> The URL query string to parse
      • +
      • sep <string> The substring used to delimit key and value pairs in the +query string. Default: '&'.
      • +
      • eq <string>. The substring used to delimit keys and values in the +query string. Default: '='.
      • +
      • options <Object> +
          +
        • decodeURIComponent <Function> The function to use when decoding +percent-encoded characters in the query string. Default: +querystring.unescape().
        • +
        • maxKeys <number> Specifies the maximum number of keys to parse. +Specify 0 to remove key counting limitations. Default: 1000.
        • +
        +
      • +
      +

      The querystring.parse() method parses a URL query string (str) into a +collection of key and value pairs.

      +

      For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:

      + +
      {
      +  foo: 'bar',
      +  abc: ['xyz', '123']
      +}
      +

      The object returned by the querystring.parse() method does not +prototypically inherit from the JavaScript Object. This means that typical +Object methods such as obj.toString(), obj.hasOwnProperty(), and others +are not defined and will not work.

      +

      By default, percent-encoded characters within the query string will be assumed +to use UTF-8 encoding. If an alternative character encoding is used, then an +alternative decodeURIComponent option will need to be specified:

      +
      // Assuming gbkDecodeURIComponent function already exists...
      +
      +querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
      +                  { decodeURIComponent: gbkDecodeURIComponent });
      +

      querystring.stringify(obj[, sep[, eq[, options]]])#

      + +
        +
      • obj <Object> The object to serialize into a URL query string
      • +
      • sep <string> The substring used to delimit key and value pairs in the +query string. Default: '&'.
      • +
      • eq <string>. The substring used to delimit keys and values in the +query string. Default: '='.
      • +
      • options +
          +
        • encodeURIComponent <Function> The function to use when converting +URL-unsafe characters to percent-encoding in the query string. Default: +querystring.escape().
        • +
        +
      • +
      +

      The querystring.stringify() method produces a URL query string from a +given obj by iterating through the object's "own properties".

      +

      It serializes the following types of values passed in obj: +<string> | <number> | <boolean> | <string[]> | <number[]> | <boolean[]> +Any other input values will be coerced to empty strings.

      +
      querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
      +// Returns 'foo=bar&baz=qux&baz=quux&corge='
      +
      +querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
      +// Returns 'foo:bar;baz:qux'
      +

      By default, characters requiring percent-encoding within the query string will +be encoded as UTF-8. If an alternative encoding is required, then an alternative +encodeURIComponent option will need to be specified:

      +
      // Assuming gbkEncodeURIComponent function already exists,
      +
      +querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
      +                      { encodeURIComponent: gbkEncodeURIComponent });
      +

      querystring.unescape(str)#

      + + +

      The querystring.unescape() method performs decoding of URL percent-encoded +characters on the given str.

      +

      The querystring.unescape() method is used by querystring.parse() and is +generally not expected to be used directly. It is exported primarily to allow +application code to provide a replacement decoding implementation if +necessary by assigning querystring.unescape to an alternative function.

      +

      By default, the querystring.unescape() method will attempt to use the +JavaScript built-in decodeURIComponent() method to decode. If that fails, +a safer equivalent that does not throw on malformed URLs will be used.

      + +
      +
      +
      + + diff --git a/doc/api/querystring.json b/doc/api/querystring.json new file mode 100644 index 0000000000000000000000000000000000000000..ad255d3fce5d331b8a37d464d9b8f58c695f922a --- /dev/null +++ b/doc/api/querystring.json @@ -0,0 +1,224 @@ +{ + "type": "module", + "source": "doc/api/querystring.md", + "modules": [ + { + "textRaw": "Query string", + "name": "querystring", + "introduced_in": "v0.1.25", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/querystring.js

      \n

      The querystring module provides utilities for parsing and formatting URL\nquery strings. It can be accessed using:

      \n
      const querystring = require('querystring');\n
      ", + "methods": [ + { + "textRaw": "`querystring.decode()`", + "type": "method", + "name": "decode", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The querystring.decode() function is an alias for querystring.parse().

      " + }, + { + "textRaw": "`querystring.encode()`", + "type": "method", + "name": "encode", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The querystring.encode() function is an alias for querystring.stringify().

      " + }, + { + "textRaw": "`querystring.escape(str)`", + "type": "method", + "name": "escape", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`str` {string}", + "name": "str", + "type": "string" + } + ] + } + ], + "desc": "

      The querystring.escape() method performs URL percent-encoding on the given\nstr in a manner that is optimized for the specific requirements of URL\nquery strings.

      \n

      The querystring.escape() method is used by querystring.stringify() and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement percent-encoding implementation if\nnecessary by assigning querystring.escape to an alternative function.

      " + }, + { + "textRaw": "`querystring.parse(str[, sep[, eq[, options]]])`", + "type": "method", + "name": "parse", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/10967", + "description": "Multiple empty entries are now parsed correctly (e.g. `&=&=`)." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6055", + "description": "The returned object no longer inherits from `Object.prototype`." + }, + { + "version": "v6.0.0, v4.2.4", + "pr-url": "https://github.com/nodejs/node/pull/3807", + "description": "The `eq` parameter may now have a length of more than `1`." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`str` {string} The URL query string to parse", + "name": "str", + "type": "string", + "desc": "The URL query string to parse" + }, + { + "textRaw": "`sep` {string} The substring used to delimit key and value pairs in the query string. **Default:** `'&'`.", + "name": "sep", + "type": "string", + "default": "`'&'`", + "desc": "The substring used to delimit key and value pairs in the query string." + }, + { + "textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. **Default:** `'='`.", + "name": "eq", + "type": "string", + "default": "`'='`", + "desc": ". The substring used to delimit keys and values in the query string." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`decodeURIComponent` {Function} The function to use when decoding percent-encoded characters in the query string. **Default:** `querystring.unescape()`.", + "name": "decodeURIComponent", + "type": "Function", + "default": "`querystring.unescape()`", + "desc": "The function to use when decoding percent-encoded characters in the query string." + }, + { + "textRaw": "`maxKeys` {number} Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. **Default:** `1000`.", + "name": "maxKeys", + "type": "number", + "default": "`1000`", + "desc": "Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations." + } + ] + } + ] + } + ], + "desc": "

      The querystring.parse() method parses a URL query string (str) into a\ncollection of key and value pairs.

      \n

      For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:

      \n\n
      {\n  foo: 'bar',\n  abc: ['xyz', '123']\n}\n
      \n

      The object returned by the querystring.parse() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.

      \n

      By default, percent-encoded characters within the query string will be assumed\nto use UTF-8 encoding. If an alternative character encoding is used, then an\nalternative decodeURIComponent option will need to be specified:

      \n
      // Assuming gbkDecodeURIComponent function already exists...\n\nquerystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,\n                  { decodeURIComponent: gbkDecodeURIComponent });\n
      " + }, + { + "textRaw": "`querystring.stringify(obj[, sep[, eq[, options]]])`", + "type": "method", + "name": "stringify", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`obj` {Object} The object to serialize into a URL query string", + "name": "obj", + "type": "Object", + "desc": "The object to serialize into a URL query string" + }, + { + "textRaw": "`sep` {string} The substring used to delimit key and value pairs in the query string. **Default:** `'&'`.", + "name": "sep", + "type": "string", + "default": "`'&'`", + "desc": "The substring used to delimit key and value pairs in the query string." + }, + { + "textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. **Default:** `'='`.", + "name": "eq", + "type": "string", + "default": "`'='`", + "desc": ". The substring used to delimit keys and values in the query string." + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`encodeURIComponent` {Function} The function to use when converting URL-unsafe characters to percent-encoding in the query string. **Default:** `querystring.escape()`.", + "name": "encodeURIComponent", + "type": "Function", + "default": "`querystring.escape()`", + "desc": "The function to use when converting URL-unsafe characters to percent-encoding in the query string." + } + ] + } + ] + } + ], + "desc": "

      The querystring.stringify() method produces a URL query string from a\ngiven obj by iterating through the object's \"own properties\".

      \n

      It serializes the following types of values passed in obj:\n<string> | <number> | <boolean> | <string[]> | <number[]> | <boolean[]>\nAny other input values will be coerced to empty strings.

      \n
      querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });\n// Returns 'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');\n// Returns 'foo:bar;baz:qux'\n
      \n

      By default, characters requiring percent-encoding within the query string will\nbe encoded as UTF-8. If an alternative encoding is required, then an alternative\nencodeURIComponent option will need to be specified:

      \n
      // Assuming gbkEncodeURIComponent function already exists,\n\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n                      { encodeURIComponent: gbkEncodeURIComponent });\n
      " + }, + { + "textRaw": "`querystring.unescape(str)`", + "type": "method", + "name": "unescape", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`str` {string}", + "name": "str", + "type": "string" + } + ] + } + ], + "desc": "

      The querystring.unescape() method performs decoding of URL percent-encoded\ncharacters on the given str.

      \n

      The querystring.unescape() method is used by querystring.parse() and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement decoding implementation if\nnecessary by assigning querystring.unescape to an alternative function.

      \n

      By default, the querystring.unescape() method will attempt to use the\nJavaScript built-in decodeURIComponent() method to decode. If that fails,\na safer equivalent that does not throw on malformed URLs will be used.

      " + } + ], + "type": "module", + "displayName": "querystring" + } + ] +} \ No newline at end of file diff --git a/doc/api/readline.html b/doc/api/readline.html new file mode 100644 index 0000000000000000000000000000000000000000..47fff56505794a037199e3062ea3585bc167fdca --- /dev/null +++ b/doc/api/readline.html @@ -0,0 +1,911 @@ + + + + + + + Readline | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Readline#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/readline.js

      +

      The readline module provides an interface for reading data from a Readable +stream (such as process.stdin) one line at a time. It can be accessed +using:

      +
      const readline = require('readline');
      +

      The following simple example illustrates the basic use of the readline module.

      +
      const readline = require('readline');
      +
      +const rl = readline.createInterface({
      +  input: process.stdin,
      +  output: process.stdout
      +});
      +
      +rl.question('What do you think of Node.js? ', (answer) => {
      +  // TODO: Log the answer in a database
      +  console.log(`Thank you for your valuable feedback: ${answer}`);
      +
      +  rl.close();
      +});
      +

      Once this code is invoked, the Node.js application will not terminate until the +readline.Interface is closed because the interface waits for data to be +received on the input stream.

      +

      Class: Interface#

      + + +

      Instances of the readline.Interface class are constructed using the +readline.createInterface() method. Every instance is associated with a +single input Readable stream and a single output Writable stream. +The output stream is used to print prompts for user input that arrives on, +and is read from, the input stream.

      +

      Event: 'close'#

      + +

      The 'close' event is emitted when one of the following occur:

      +
        +
      • The rl.close() method is called and the readline.Interface instance has +relinquished control over the input and output streams;
      • +
      • The input stream receives its 'end' event;
      • +
      • The input stream receives <ctrl>-D to signal end-of-transmission (EOT);
      • +
      • The input stream receives <ctrl>-C to signal SIGINT and there is no +'SIGINT' event listener registered on the readline.Interface instance.
      • +
      +

      The listener function is called without passing any arguments.

      +

      The readline.Interface instance is finished once the 'close' event is +emitted.

      +

      Event: 'line'#

      + +

      The 'line' event is emitted whenever the input stream receives an +end-of-line input (\n, \r, or \r\n). This usually occurs when the user +presses the <Enter>, or <Return> keys.

      +

      The listener function is called with a string containing the single line of +received input.

      +
      rl.on('line', (input) => {
      +  console.log(`Received: ${input}`);
      +});
      +

      Event: 'pause'#

      + +

      The 'pause' event is emitted when one of the following occur:

      +
        +
      • The input stream is paused.
      • +
      • The input stream is not paused and receives the 'SIGCONT' event. (See +events 'SIGTSTP' and 'SIGCONT'.)
      • +
      +

      The listener function is called without passing any arguments.

      +
      rl.on('pause', () => {
      +  console.log('Readline paused.');
      +});
      +

      Event: 'resume'#

      + +

      The 'resume' event is emitted whenever the input stream is resumed.

      +

      The listener function is called without passing any arguments.

      +
      rl.on('resume', () => {
      +  console.log('Readline resumed.');
      +});
      +

      Event: 'SIGCONT'#

      + +

      The 'SIGCONT' event is emitted when a Node.js process previously moved into +the background using <ctrl>-Z (i.e. SIGTSTP) is then brought back to the +foreground using fg(1p).

      +

      If the input stream was paused before the SIGTSTP request, this event will +not be emitted.

      +

      The listener function is invoked without passing any arguments.

      +
      rl.on('SIGCONT', () => {
      +  // `prompt` will automatically resume the stream
      +  rl.prompt();
      +});
      +

      The 'SIGCONT' event is not supported on Windows.

      +

      Event: 'SIGINT'#

      + +

      The 'SIGINT' event is emitted whenever the input stream receives a +<ctrl>-C input, known typically as SIGINT. If there are no 'SIGINT' event +listeners registered when the input stream receives a SIGINT, the 'pause' +event will be emitted.

      +

      The listener function is invoked without passing any arguments.

      +
      rl.on('SIGINT', () => {
      +  rl.question('Are you sure you want to exit? ', (answer) => {
      +    if (answer.match(/^y(es)?$/i)) rl.pause();
      +  });
      +});
      +

      Event: 'SIGTSTP'#

      + +

      The 'SIGTSTP' event is emitted when the input stream receives a <ctrl>-Z +input, typically known as SIGTSTP. If there are no 'SIGTSTP' event listeners +registered when the input stream receives a SIGTSTP, the Node.js process +will be sent to the background.

      +

      When the program is resumed using fg(1p), the 'pause' and 'SIGCONT' events +will be emitted. These can be used to resume the input stream.

      +

      The 'pause' and 'SIGCONT' events will not be emitted if the input was +paused before the process was sent to the background.

      +

      The listener function is invoked without passing any arguments.

      +
      rl.on('SIGTSTP', () => {
      +  // This will override SIGTSTP and prevent the program from going to the
      +  // background.
      +  console.log('Caught SIGTSTP.');
      +});
      +

      The 'SIGTSTP' event is not supported on Windows.

      +

      rl.close()#

      + +

      The rl.close() method closes the readline.Interface instance and +relinquishes control over the input and output streams. When called, +the 'close' event will be emitted.

      +

      Calling rl.close() does not immediately stop other events (including 'line') +from being emitted by the readline.Interface instance.

      +

      rl.pause()#

      + +

      The rl.pause() method pauses the input stream, allowing it to be resumed +later if necessary.

      +

      Calling rl.pause() does not immediately pause other events (including +'line') from being emitted by the readline.Interface instance.

      +

      rl.prompt([preserveCursor])#

      + +
        +
      • preserveCursor <boolean> If true, prevents the cursor placement from +being reset to 0.
      • +
      +

      The rl.prompt() method writes the readline.Interface instances configured +prompt to a new line in output in order to provide a user with a new +location at which to provide input.

      +

      When called, rl.prompt() will resume the input stream if it has been +paused.

      +

      If the readline.Interface was created with output set to null or +undefined the prompt is not written.

      +

      rl.question(query, callback)#

      + +
        +
      • query <string> A statement or query to write to output, prepended to the +prompt.
      • +
      • callback <Function> A callback function that is invoked with the user's +input in response to the query.
      • +
      +

      The rl.question() method displays the query by writing it to the output, +waits for user input to be provided on input, then invokes the callback +function passing the provided input as the first argument.

      +

      When called, rl.question() will resume the input stream if it has been +paused.

      +

      If the readline.Interface was created with output set to null or +undefined the query is not written.

      +

      Example usage:

      +
      rl.question('What is your favorite food? ', (answer) => {
      +  console.log(`Oh, so your favorite food is ${answer}`);
      +});
      +

      The callback function passed to rl.question() does not follow the typical +pattern of accepting an Error object or null as the first argument. +The callback is called with the provided answer as the only argument.

      +

      rl.resume()#

      + +

      The rl.resume() method resumes the input stream if it has been paused.

      +

      rl.setPrompt(prompt)#

      + + +

      The rl.setPrompt() method sets the prompt that will be written to output +whenever rl.prompt() is called.

      +

      rl.write(data[, key])#

      + + +

      The rl.write() method will write either data or a key sequence identified +by key to the output. The key argument is supported only if output is +a TTY text terminal. See TTY keybindings for a list of key +combinations.

      +

      If key is specified, data is ignored.

      +

      When called, rl.write() will resume the input stream if it has been +paused.

      +

      If the readline.Interface was created with output set to null or +undefined the data and key are not written.

      +
      rl.write('Delete this!');
      +// Simulate Ctrl+u to delete the line written previously
      +rl.write(null, { ctrl: true, name: 'u' });
      +

      The rl.write() method will write the data to the readline Interface's +input as if it were provided by the user.

      +

      rl[Symbol.asyncIterator]()#

      + + +

      Create an AsyncIterator object that iterates through each line in the input +stream as a string. This method allows asynchronous iteration of +readline.Interface objects through for await...of loops.

      +

      Errors in the input stream are not forwarded.

      +

      If the loop is terminated with break, throw, or return, +rl.close() will be called. In other words, iterating over a +readline.Interface will always consume the input stream fully.

      +

      Performance is not on par with the traditional 'line' event API. Use 'line' +instead for performance-sensitive applications.

      +
      async function processLineByLine() {
      +  const rl = readline.createInterface({
      +    // ...
      +  });
      +
      +  for await (const line of rl) {
      +    // Each line in the readline input will be successively available here as
      +    // `line`.
      +  }
      +}
      +

      rl.line#

      + + +

      The current input data being processed by node.

      +

      This can be used when collecting input from a TTY stream to retrieve the +current value that has been processed thus far, prior to the line event +being emitted. Once the line event has been emitted, this property will +be an empty string.

      +

      Be aware that modifying the value during the instance runtime may have +unintended consequences if rl.cursor is not also controlled.

      +

      If not using a TTY stream for input, use the 'line' event.

      +

      One possible use case would be as follows:

      +
      const values = ['lorem ipsum', 'dolor sit amet'];
      +const rl = readline.createInterface(process.stdin);
      +const showResults = debounce(() => {
      +  console.log(
      +    '\n',
      +    values.filter((val) => val.startsWith(rl.line)).join(' ')
      +  );
      +}, 300);
      +process.stdin.on('keypress', (c, k) => {
      +  showResults();
      +});
      +

      rl.cursor#

      + + +

      The cursor position relative to rl.line.

      +

      This will track where the current cursor lands in the input string, when +reading input from a TTY stream. The position of cursor determines the +portion of the input string that will be modified as input is processed, +as well as the column where the terminal caret will be rendered.

      +

      rl.getCursorPos()#

      + +
        +
      • Returns: <Object> +
          +
        • rows <number> the row of the prompt the cursor currently lands on
        • +
        • cols <number> the screen column the cursor currently lands on
        • +
        +
      • +
      +

      Returns the real position of the cursor in relation to the input +prompt + string. Long input (wrapping) strings, as well as multiple +line prompts are included in the calculations.

      +

      readline.clearLine(stream, dir[, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • dir <number> +
          +
        • -1: to the left from cursor
        • +
        • 1: to the right from cursor
        • +
        • 0: the entire line
        • +
        +
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.clearLine() method clears current line of given TTY stream +in a specified direction identified by dir.

      +

      readline.clearScreenDown(stream[, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.clearScreenDown() method clears the given TTY stream from +the current position of the cursor down.

      +

      readline.createInterface(options)#

      + +
        +
      • options <Object> +
          +
        • input <stream.Readable> The Readable stream to listen to. This option +is required.
        • +
        • output <stream.Writable> The Writable stream to write readline data +to.
        • +
        • completer <Function> An optional function used for Tab autocompletion.
        • +
        • terminal <boolean> true if the input and output streams should be +treated like a TTY, and have ANSI/VT100 escape codes written to it. +Default: checking isTTY on the output stream upon instantiation.
        • +
        • historySize <number> Maximum number of history lines retained. To disable +the history set this value to 0. This option makes sense only if +terminal is set to true by the user or by an internal output check, +otherwise the history caching mechanism is not initialized at all. +Default: 30.
        • +
        • prompt <string> The prompt string to use. Default: '> '.
        • +
        • crlfDelay <number> If the delay between \r and \n exceeds +crlfDelay milliseconds, both \r and \n will be treated as separate +end-of-line input. crlfDelay will be coerced to a number no less than +100. It can be set to Infinity, in which case \r followed by \n +will always be considered a single newline (which may be reasonable for +reading files with \r\n line delimiter). Default: 100.
        • +
        • removeHistoryDuplicates <boolean> If true, when a new input line added +to the history list duplicates an older one, this removes the older line +from the list. Default: false.
        • +
        • escapeCodeTimeout <number> The duration readline will wait for a +character (when reading an ambiguous key sequence in milliseconds one that +can both form a complete key sequence using the input read so far and can +take additional input to complete a longer key sequence). +Default: 500.
        • +
        +
      • +
      +

      The readline.createInterface() method creates a new readline.Interface +instance.

      +
      const readline = require('readline');
      +const rl = readline.createInterface({
      +  input: process.stdin,
      +  output: process.stdout
      +});
      +

      Once the readline.Interface instance is created, the most common case is to +listen for the 'line' event:

      +
      rl.on('line', (line) => {
      +  console.log(`Received: ${line}`);
      +});
      +

      If terminal is true for this instance then the output stream will get +the best compatibility if it defines an output.columns property and emits +a 'resize' event on the output if or when the columns ever change +(process.stdout does this automatically when it is a TTY).

      +

      Use of the completer function#

      +

      The completer function takes the current line entered by the user +as an argument, and returns an Array with 2 entries:

      +
        +
      • An Array with matching entries for the completion.
      • +
      • The substring that was used for the matching.
      • +
      +

      For instance: [[substr1, substr2, ...], originalsubstring].

      +
      function completer(line) {
      +  const completions = '.help .error .exit .quit .q'.split(' ');
      +  const hits = completions.filter((c) => c.startsWith(line));
      +  // Show all completions if none found
      +  return [hits.length ? hits : completions, line];
      +}
      +

      The completer function can be called asynchronously if it accepts two +arguments:

      +
      function completer(linePartial, callback) {
      +  callback(null, [['123'], linePartial]);
      +}
      +

      readline.cursorTo(stream, x[, y][, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • x <number>
      • +
      • y <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.cursorTo() method moves cursor to the specified position in a +given TTY stream.

      +

      readline.emitKeypressEvents(stream[, interface])#

      + + +

      The readline.emitKeypressEvents() method causes the given Readable +stream to begin emitting 'keypress' events corresponding to received input.

      +

      Optionally, interface specifies a readline.Interface instance for which +autocompletion is disabled when copy-pasted input is detected.

      +

      If the stream is a TTY, then it must be in raw mode.

      +

      This is automatically called by any readline instance on its input if the +input is a terminal. Closing the readline instance does not stop +the input from emitting 'keypress' events.

      +
      readline.emitKeypressEvents(process.stdin);
      +if (process.stdin.isTTY)
      +  process.stdin.setRawMode(true);
      +

      readline.moveCursor(stream, dx, dy[, callback])#

      + +
        +
      • stream <stream.Writable>
      • +
      • dx <number>
      • +
      • dy <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if stream wishes for the calling code to wait for +the 'drain' event to be emitted before continuing to write additional data; +otherwise true.
      • +
      +

      The readline.moveCursor() method moves the cursor relative to its current +position in a given TTY stream.

      +

      Example: Tiny CLI#

      +

      The following example illustrates the use of readline.Interface class to +implement a small command-line interface:

      +
      const readline = require('readline');
      +const rl = readline.createInterface({
      +  input: process.stdin,
      +  output: process.stdout,
      +  prompt: 'OHAI> '
      +});
      +
      +rl.prompt();
      +
      +rl.on('line', (line) => {
      +  switch (line.trim()) {
      +    case 'hello':
      +      console.log('world!');
      +      break;
      +    default:
      +      console.log(`Say what? I might have heard '${line.trim()}'`);
      +      break;
      +  }
      +  rl.prompt();
      +}).on('close', () => {
      +  console.log('Have a great day!');
      +  process.exit(0);
      +});
      +

      Example: Read file stream line-by-Line#

      +

      A common use case for readline is to consume an input file one line at a +time. The easiest way to do so is leveraging the fs.ReadStream API as +well as a for await...of loop:

      +
      const fs = require('fs');
      +const readline = require('readline');
      +
      +async function processLineByLine() {
      +  const fileStream = fs.createReadStream('input.txt');
      +
      +  const rl = readline.createInterface({
      +    input: fileStream,
      +    crlfDelay: Infinity
      +  });
      +  // Note: we use the crlfDelay option to recognize all instances of CR LF
      +  // ('\r\n') in input.txt as a single line break.
      +
      +  for await (const line of rl) {
      +    // Each line in input.txt will be successively available here as `line`.
      +    console.log(`Line from file: ${line}`);
      +  }
      +}
      +
      +processLineByLine();
      +

      Alternatively, one could use the 'line' event:

      +
      const fs = require('fs');
      +const readline = require('readline');
      +
      +const rl = readline.createInterface({
      +  input: fs.createReadStream('sample.txt'),
      +  crlfDelay: Infinity
      +});
      +
      +rl.on('line', (line) => {
      +  console.log(`Line from file: ${line}`);
      +});
      +

      Currently, for await...of loop can be a bit slower. If async / await +flow and speed are both essential, a mixed approach can be applied:

      +
      const { once } = require('events');
      +const { createReadStream } = require('fs');
      +const { createInterface } = require('readline');
      +
      +(async function processLineByLine() {
      +  try {
      +    const rl = createInterface({
      +      input: createReadStream('big-file.txt'),
      +      crlfDelay: Infinity
      +    });
      +
      +    rl.on('line', (line) => {
      +      // Process the line.
      +    });
      +
      +    await once(rl, 'close');
      +
      +    console.log('File processed.');
      +  } catch (err) {
      +    console.error(err);
      +  }
      +})();
      +

      TTY keybindings#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      KeybindingsDescriptionNotes
      ctrl + shift + backspaceDelete line leftDoesn't work on Linux, Mac and Windows
      ctrl + shift + deleteDelete line rightDoesn't work on Mac
      ctrl + cEmit SIGINT or close the readline instance
      ctrl + hDelete left
      ctrl + dDelete right or close the readline instance in case the current line is empty / EOFDoesn't work on Windows
      ctrl + uDelete from the current position to the line start
      ctrl + kDelete from the current position to the end of line
      ctrl + aGo to start of line
      ctrl + eGo to to end of line
      ctrl + bBack one character
      ctrl + fForward one character
      ctrl + lClear screen
      ctrl + nNext history item
      ctrl + pPrevious history item
      ctrl + zMoves running process into background. Type + fg and press enter + to return.Doesn't work on Windows
      ctrl + w or ctrl + + backspaceDelete backward to a word boundaryctrl + backspace Doesn't + work on Linux, Mac and Windows
      ctrl + deleteDelete forward to a word boundaryDoesn't work on Mac
      ctrl + left or + meta + bWord leftctrl + left Doesn't work + on Mac
      ctrl + right or + meta + fWord rightctrl + right Doesn't work + on Mac
      meta + d or meta + + deleteDelete word rightmeta + delete Doesn't work + on windows
      meta + backspaceDelete word leftDoesn't work on Mac
      + +
      +
      +
      + + diff --git a/doc/api/readline.json b/doc/api/readline.json new file mode 100644 index 0000000000000000000000000000000000000000..edd7985fe929dcb73a6cec14815da88b729a0f5a --- /dev/null +++ b/doc/api/readline.json @@ -0,0 +1,757 @@ +{ + "type": "module", + "source": "doc/api/readline.md", + "modules": [ + { + "textRaw": "Readline", + "name": "readline", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/readline.js

      \n

      The readline module provides an interface for reading data from a Readable\nstream (such as process.stdin) one line at a time. It can be accessed\nusing:

      \n
      const readline = require('readline');\n
      \n

      The following simple example illustrates the basic use of the readline module.

      \n
      const readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question('What do you think of Node.js? ', (answer) => {\n  // TODO: Log the answer in a database\n  console.log(`Thank you for your valuable feedback: ${answer}`);\n\n  rl.close();\n});\n
      \n

      Once this code is invoked, the Node.js application will not terminate until the\nreadline.Interface is closed because the interface waits for data to be\nreceived on the input stream.

      ", + "classes": [ + { + "textRaw": "Class: `Interface`", + "type": "class", + "name": "Interface", + "meta": { + "added": [ + "v0.1.104" + ], + "changes": [] + }, + "desc": "\n

      Instances of the readline.Interface class are constructed using the\nreadline.createInterface() method. Every instance is associated with a\nsingle input Readable stream and a single output Writable stream.\nThe output stream is used to print prompts for user input that arrives on,\nand is read from, the input stream.

      ", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'close' event is emitted when one of the following occur:

      \n
        \n
      • The rl.close() method is called and the readline.Interface instance has\nrelinquished control over the input and output streams;
      • \n
      • The input stream receives its 'end' event;
      • \n
      • The input stream receives <ctrl>-D to signal end-of-transmission (EOT);
      • \n
      • The input stream receives <ctrl>-C to signal SIGINT and there is no\n'SIGINT' event listener registered on the readline.Interface instance.
      • \n
      \n

      The listener function is called without passing any arguments.

      \n

      The readline.Interface instance is finished once the 'close' event is\nemitted.

      " + }, + { + "textRaw": "Event: `'line'`", + "type": "event", + "name": "line", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'line' event is emitted whenever the input stream receives an\nend-of-line input (\\n, \\r, or \\r\\n). This usually occurs when the user\npresses the <Enter>, or <Return> keys.

      \n

      The listener function is called with a string containing the single line of\nreceived input.

      \n
      rl.on('line', (input) => {\n  console.log(`Received: ${input}`);\n});\n
      " + }, + { + "textRaw": "Event: `'pause'`", + "type": "event", + "name": "pause", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'pause' event is emitted when one of the following occur:

      \n
        \n
      • The input stream is paused.
      • \n
      • The input stream is not paused and receives the 'SIGCONT' event. (See\nevents 'SIGTSTP' and 'SIGCONT'.)
      • \n
      \n

      The listener function is called without passing any arguments.

      \n
      rl.on('pause', () => {\n  console.log('Readline paused.');\n});\n
      " + }, + { + "textRaw": "Event: `'resume'`", + "type": "event", + "name": "resume", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resume' event is emitted whenever the input stream is resumed.

      \n

      The listener function is called without passing any arguments.

      \n
      rl.on('resume', () => {\n  console.log('Readline resumed.');\n});\n
      " + }, + { + "textRaw": "Event: `'SIGCONT'`", + "type": "event", + "name": "SIGCONT", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'SIGCONT' event is emitted when a Node.js process previously moved into\nthe background using <ctrl>-Z (i.e. SIGTSTP) is then brought back to the\nforeground using fg(1p).

      \n

      If the input stream was paused before the SIGTSTP request, this event will\nnot be emitted.

      \n

      The listener function is invoked without passing any arguments.

      \n
      rl.on('SIGCONT', () => {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});\n
      \n

      The 'SIGCONT' event is not supported on Windows.

      " + }, + { + "textRaw": "Event: `'SIGINT'`", + "type": "event", + "name": "SIGINT", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'SIGINT' event is emitted whenever the input stream receives a\n<ctrl>-C input, known typically as SIGINT. If there are no 'SIGINT' event\nlisteners registered when the input stream receives a SIGINT, the 'pause'\nevent will be emitted.

      \n

      The listener function is invoked without passing any arguments.

      \n
      rl.on('SIGINT', () => {\n  rl.question('Are you sure you want to exit? ', (answer) => {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});\n
      " + }, + { + "textRaw": "Event: `'SIGTSTP'`", + "type": "event", + "name": "SIGTSTP", + "meta": { + "added": [ + "v0.7.5" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'SIGTSTP' event is emitted when the input stream receives a <ctrl>-Z\ninput, typically known as SIGTSTP. If there are no 'SIGTSTP' event listeners\nregistered when the input stream receives a SIGTSTP, the Node.js process\nwill be sent to the background.

      \n

      When the program is resumed using fg(1p), the 'pause' and 'SIGCONT' events\nwill be emitted. These can be used to resume the input stream.

      \n

      The 'pause' and 'SIGCONT' events will not be emitted if the input was\npaused before the process was sent to the background.

      \n

      The listener function is invoked without passing any arguments.

      \n
      rl.on('SIGTSTP', () => {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});\n
      \n

      The 'SIGTSTP' event is not supported on Windows.

      " + } + ], + "methods": [ + { + "textRaw": "`rl.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The rl.close() method closes the readline.Interface instance and\nrelinquishes control over the input and output streams. When called,\nthe 'close' event will be emitted.

      \n

      Calling rl.close() does not immediately stop other events (including 'line')\nfrom being emitted by the readline.Interface instance.

      " + }, + { + "textRaw": "`rl.pause()`", + "type": "method", + "name": "pause", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The rl.pause() method pauses the input stream, allowing it to be resumed\nlater if necessary.

      \n

      Calling rl.pause() does not immediately pause other events (including\n'line') from being emitted by the readline.Interface instance.

      " + }, + { + "textRaw": "`rl.prompt([preserveCursor])`", + "type": "method", + "name": "prompt", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`preserveCursor` {boolean} If `true`, prevents the cursor placement from being reset to `0`.", + "name": "preserveCursor", + "type": "boolean", + "desc": "If `true`, prevents the cursor placement from being reset to `0`." + } + ] + } + ], + "desc": "

      The rl.prompt() method writes the readline.Interface instances configured\nprompt to a new line in output in order to provide a user with a new\nlocation at which to provide input.

      \n

      When called, rl.prompt() will resume the input stream if it has been\npaused.

      \n

      If the readline.Interface was created with output set to null or\nundefined the prompt is not written.

      " + }, + { + "textRaw": "`rl.question(query, callback)`", + "type": "method", + "name": "question", + "meta": { + "added": [ + "v0.3.3" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`query` {string} A statement or query to write to `output`, prepended to the prompt.", + "name": "query", + "type": "string", + "desc": "A statement or query to write to `output`, prepended to the prompt." + }, + { + "textRaw": "`callback` {Function} A callback function that is invoked with the user's input in response to the `query`.", + "name": "callback", + "type": "Function", + "desc": "A callback function that is invoked with the user's input in response to the `query`." + } + ] + } + ], + "desc": "

      The rl.question() method displays the query by writing it to the output,\nwaits for user input to be provided on input, then invokes the callback\nfunction passing the provided input as the first argument.

      \n

      When called, rl.question() will resume the input stream if it has been\npaused.

      \n

      If the readline.Interface was created with output set to null or\nundefined the query is not written.

      \n

      Example usage:

      \n
      rl.question('What is your favorite food? ', (answer) => {\n  console.log(`Oh, so your favorite food is ${answer}`);\n});\n
      \n

      The callback function passed to rl.question() does not follow the typical\npattern of accepting an Error object or null as the first argument.\nThe callback is called with the provided answer as the only argument.

      " + }, + { + "textRaw": "`rl.resume()`", + "type": "method", + "name": "resume", + "meta": { + "added": [ + "v0.3.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The rl.resume() method resumes the input stream if it has been paused.

      " + }, + { + "textRaw": "`rl.setPrompt(prompt)`", + "type": "method", + "name": "setPrompt", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`prompt` {string}", + "name": "prompt", + "type": "string" + } + ] + } + ], + "desc": "

      The rl.setPrompt() method sets the prompt that will be written to output\nwhenever rl.prompt() is called.

      " + }, + { + "textRaw": "`rl.write(data[, key])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`data` {string}", + "name": "data", + "type": "string" + }, + { + "textRaw": "`key` {Object}", + "name": "key", + "type": "Object", + "options": [ + { + "textRaw": "`ctrl` {boolean} `true` to indicate the `` key.", + "name": "ctrl", + "type": "boolean", + "desc": "`true` to indicate the `` key." + }, + { + "textRaw": "`meta` {boolean} `true` to indicate the `` key.", + "name": "meta", + "type": "boolean", + "desc": "`true` to indicate the `` key." + }, + { + "textRaw": "`shift` {boolean} `true` to indicate the `` key.", + "name": "shift", + "type": "boolean", + "desc": "`true` to indicate the `` key." + }, + { + "textRaw": "`name` {string} The name of the a key.", + "name": "name", + "type": "string", + "desc": "The name of the a key." + } + ] + } + ] + } + ], + "desc": "

      The rl.write() method will write either data or a key sequence identified\nby key to the output. The key argument is supported only if output is\na TTY text terminal. See TTY keybindings for a list of key\ncombinations.

      \n

      If key is specified, data is ignored.

      \n

      When called, rl.write() will resume the input stream if it has been\npaused.

      \n

      If the readline.Interface was created with output set to null or\nundefined the data and key are not written.

      \n
      rl.write('Delete this!');\n// Simulate Ctrl+u to delete the line written previously\nrl.write(null, { ctrl: true, name: 'u' });\n
      \n

      The rl.write() method will write the data to the readline Interface's\ninput as if it were provided by the user.

      " + }, + { + "textRaw": "`rl[Symbol.asyncIterator]()`", + "type": "method", + "name": "[Symbol.asyncIterator]", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26989", + "description": "Symbol.asyncIterator support is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator}", + "name": "return", + "type": "AsyncIterator" + }, + "params": [] + } + ], + "desc": "

      Create an AsyncIterator object that iterates through each line in the input\nstream as a string. This method allows asynchronous iteration of\nreadline.Interface objects through for await...of loops.

      \n

      Errors in the input stream are not forwarded.

      \n

      If the loop is terminated with break, throw, or return,\nrl.close() will be called. In other words, iterating over a\nreadline.Interface will always consume the input stream fully.

      \n

      Performance is not on par with the traditional 'line' event API. Use 'line'\ninstead for performance-sensitive applications.

      \n
      async function processLineByLine() {\n  const rl = readline.createInterface({\n    // ...\n  });\n\n  for await (const line of rl) {\n    // Each line in the readline input will be successively available here as\n    // `line`.\n  }\n}\n
      " + }, + { + "textRaw": "`rl.getCursorPos()`", + "type": "method", + "name": "getCursorPos", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`rows` {number} the row of the prompt the cursor currently lands on", + "name": "rows", + "type": "number", + "desc": "the row of the prompt the cursor currently lands on" + }, + { + "textRaw": "`cols` {number} the screen column the cursor currently lands on", + "name": "cols", + "type": "number", + "desc": "the screen column the cursor currently lands on" + } + ] + }, + "params": [] + } + ], + "desc": "

      Returns the real position of the cursor in relation to the input\nprompt + string. Long input (wrapping) strings, as well as multiple\nline prompts are included in the calculations.

      " + } + ], + "properties": [ + { + "textRaw": "`line` {string|undefined}", + "type": "string|undefined", + "name": "line", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "desc": "

      The current input data being processed by node.

      \n

      This can be used when collecting input from a TTY stream to retrieve the\ncurrent value that has been processed thus far, prior to the line event\nbeing emitted. Once the line event has been emitted, this property will\nbe an empty string.

      \n

      Be aware that modifying the value during the instance runtime may have\nunintended consequences if rl.cursor is not also controlled.

      \n

      If not using a TTY stream for input, use the 'line' event.

      \n

      One possible use case would be as follows:

      \n
      const values = ['lorem ipsum', 'dolor sit amet'];\nconst rl = readline.createInterface(process.stdin);\nconst showResults = debounce(() => {\n  console.log(\n    '\\n',\n    values.filter((val) => val.startsWith(rl.line)).join(' ')\n  );\n}, 300);\nprocess.stdin.on('keypress', (c, k) => {\n  showResults();\n});\n
      " + }, + { + "textRaw": "`cursor` {number|undefined}", + "type": "number|undefined", + "name": "cursor", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [] + }, + "desc": "

      The cursor position relative to rl.line.

      \n

      This will track where the current cursor lands in the input string, when\nreading input from a TTY stream. The position of cursor determines the\nportion of the input string that will be modified as input is processed,\nas well as the column where the terminal caret will be rendered.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`readline.clearLine(stream, dir[, callback])`", + "type": "method", + "name": "clearLine", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28674", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`dir` {number}", + "name": "dir", + "type": "number", + "options": [ + { + "textRaw": "`-1`: to the left from cursor", + "name": "-1", + "desc": "to the left from cursor" + }, + { + "textRaw": "`1`: to the right from cursor", + "name": "1", + "desc": "to the right from cursor" + }, + { + "textRaw": "`0`: the entire line", + "name": "0", + "desc": "the entire line" + } + ] + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.clearLine() method clears current line of given TTY stream\nin a specified direction identified by dir.

      " + }, + { + "textRaw": "`readline.clearScreenDown(stream[, callback])`", + "type": "method", + "name": "clearScreenDown", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28641", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.clearScreenDown() method clears the given TTY stream from\nthe current position of the cursor down.

      " + }, + { + "textRaw": "`readline.createInterface(options)`", + "type": "method", + "name": "createInterface", + "meta": { + "added": [ + "v0.1.98" + ], + "changes": [ + { + "version": "v8.3.0, 6.11.4", + "pr-url": "https://github.com/nodejs/node/pull/13497", + "description": "Remove max limit of `crlfDelay` option." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8109", + "description": "The `crlfDelay` option is supported now." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/7125", + "description": "The `prompt` option is supported now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6352", + "description": "The `historySize` option can be `0` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`input` {stream.Readable} The [Readable][] stream to listen to. This option is *required*.", + "name": "input", + "type": "stream.Readable", + "desc": "The [Readable][] stream to listen to. This option is *required*." + }, + { + "textRaw": "`output` {stream.Writable} The [Writable][] stream to write readline data to.", + "name": "output", + "type": "stream.Writable", + "desc": "The [Writable][] stream to write readline data to." + }, + { + "textRaw": "`completer` {Function} An optional function used for Tab autocompletion.", + "name": "completer", + "type": "Function", + "desc": "An optional function used for Tab autocompletion." + }, + { + "textRaw": "`terminal` {boolean} `true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. **Default:** checking `isTTY` on the `output` stream upon instantiation.", + "name": "terminal", + "type": "boolean", + "default": "checking `isTTY` on the `output` stream upon instantiation", + "desc": "`true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it." + }, + { + "textRaw": "`historySize` {number} Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all. **Default:** `30`.", + "name": "historySize", + "type": "number", + "default": "`30`", + "desc": "Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all." + }, + { + "textRaw": "`prompt` {string} The prompt string to use. **Default:** `'> '`.", + "name": "prompt", + "type": "string", + "default": "`'> '`", + "desc": "The prompt string to use." + }, + { + "textRaw": "`crlfDelay` {number} If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter). **Default:** `100`.", + "name": "crlfDelay", + "type": "number", + "default": "`100`", + "desc": "If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter)." + }, + { + "textRaw": "`removeHistoryDuplicates` {boolean} If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list. **Default:** `false`.", + "name": "removeHistoryDuplicates", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list." + }, + { + "textRaw": "`escapeCodeTimeout` {number} The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence). **Default:** `500`.", + "name": "escapeCodeTimeout", + "type": "number", + "default": "`500`", + "desc": "The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence)." + } + ] + } + ] + } + ], + "desc": "

      The readline.createInterface() method creates a new readline.Interface\ninstance.

      \n
      const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n
      \n

      Once the readline.Interface instance is created, the most common case is to\nlisten for the 'line' event:

      \n
      rl.on('line', (line) => {\n  console.log(`Received: ${line}`);\n});\n
      \n

      If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property and emits\na 'resize' event on the output if or when the columns ever change\n(process.stdout does this automatically when it is a TTY).

      ", + "modules": [ + { + "textRaw": "Use of the `completer` function", + "name": "use_of_the_`completer`_function", + "desc": "

      The completer function takes the current line entered by the user\nas an argument, and returns an Array with 2 entries:

      \n
        \n
      • An Array with matching entries for the completion.
      • \n
      • The substring that was used for the matching.
      • \n
      \n

      For instance: [[substr1, substr2, ...], originalsubstring].

      \n
      function completer(line) {\n  const completions = '.help .error .exit .quit .q'.split(' ');\n  const hits = completions.filter((c) => c.startsWith(line));\n  // Show all completions if none found\n  return [hits.length ? hits : completions, line];\n}\n
      \n

      The completer function can be called asynchronously if it accepts two\narguments:

      \n
      function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}\n
      ", + "type": "module", + "displayName": "Use of the `completer` function" + } + ] + }, + { + "textRaw": "`readline.cursorTo(stream, x[, y][, callback])`", + "type": "method", + "name": "cursorTo", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28674", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`x` {number}", + "name": "x", + "type": "number" + }, + { + "textRaw": "`y` {number}", + "name": "y", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.cursorTo() method moves cursor to the specified position in a\ngiven TTY stream.

      " + }, + { + "textRaw": "`readline.emitKeypressEvents(stream[, interface])`", + "type": "method", + "name": "emitKeypressEvents", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`stream` {stream.Readable}", + "name": "stream", + "type": "stream.Readable" + }, + { + "textRaw": "`interface` {readline.Interface}", + "name": "interface", + "type": "readline.Interface" + } + ] + } + ], + "desc": "

      The readline.emitKeypressEvents() method causes the given Readable\nstream to begin emitting 'keypress' events corresponding to received input.

      \n

      Optionally, interface specifies a readline.Interface instance for which\nautocompletion is disabled when copy-pasted input is detected.

      \n

      If the stream is a TTY, then it must be in raw mode.

      \n

      This is automatically called by any readline instance on its input if the\ninput is a terminal. Closing the readline instance does not stop\nthe input from emitting 'keypress' events.

      \n
      readline.emitKeypressEvents(process.stdin);\nif (process.stdin.isTTY)\n  process.stdin.setRawMode(true);\n
      " + }, + { + "textRaw": "`readline.moveCursor(stream, dx, dy[, callback])`", + "type": "method", + "name": "moveCursor", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28674", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`stream` {stream.Writable}", + "name": "stream", + "type": "stream.Writable" + }, + { + "textRaw": "`dx` {number}", + "name": "dx", + "type": "number" + }, + { + "textRaw": "`dy` {number}", + "name": "dy", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      The readline.moveCursor() method moves the cursor relative to its current\nposition in a given TTY stream.

      \n

      Example: Tiny CLI

      \n

      The following example illustrates the use of readline.Interface class to\nimplement a small command-line interface:

      \n
      const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout,\n  prompt: 'OHAI> '\n});\n\nrl.prompt();\n\nrl.on('line', (line) => {\n  switch (line.trim()) {\n    case 'hello':\n      console.log('world!');\n      break;\n    default:\n      console.log(`Say what? I might have heard '${line.trim()}'`);\n      break;\n  }\n  rl.prompt();\n}).on('close', () => {\n  console.log('Have a great day!');\n  process.exit(0);\n});\n
      \n

      Example: Read file stream line-by-Line

      \n

      A common use case for readline is to consume an input file one line at a\ntime. The easiest way to do so is leveraging the fs.ReadStream API as\nwell as a for await...of loop:

      \n
      const fs = require('fs');\nconst readline = require('readline');\n\nasync function processLineByLine() {\n  const fileStream = fs.createReadStream('input.txt');\n\n  const rl = readline.createInterface({\n    input: fileStream,\n    crlfDelay: Infinity\n  });\n  // Note: we use the crlfDelay option to recognize all instances of CR LF\n  // ('\\r\\n') in input.txt as a single line break.\n\n  for await (const line of rl) {\n    // Each line in input.txt will be successively available here as `line`.\n    console.log(`Line from file: ${line}`);\n  }\n}\n\nprocessLineByLine();\n
      \n

      Alternatively, one could use the 'line' event:

      \n
      const fs = require('fs');\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: fs.createReadStream('sample.txt'),\n  crlfDelay: Infinity\n});\n\nrl.on('line', (line) => {\n  console.log(`Line from file: ${line}`);\n});\n
      \n

      Currently, for await...of loop can be a bit slower. If async / await\nflow and speed are both essential, a mixed approach can be applied:

      \n
      const { once } = require('events');\nconst { createReadStream } = require('fs');\nconst { createInterface } = require('readline');\n\n(async function processLineByLine() {\n  try {\n    const rl = createInterface({\n      input: createReadStream('big-file.txt'),\n      crlfDelay: Infinity\n    });\n\n    rl.on('line', (line) => {\n      // Process the line.\n    });\n\n    await once(rl, 'close');\n\n    console.log('File processed.');\n  } catch (err) {\n    console.error(err);\n  }\n})();\n
      " + } + ], + "modules": [ + { + "textRaw": "TTY keybindings", + "name": "tty_keybindings", + "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
      KeybindingsDescriptionNotes
      ctrl + shift + backspaceDelete line leftDoesn't work on Linux, Mac and Windows
      ctrl + shift + deleteDelete line rightDoesn't work on Mac
      ctrl + cEmit SIGINT or close the readline instance
      ctrl + hDelete left
      ctrl + dDelete right or close the readline instance in case the current line is empty / EOFDoesn't work on Windows
      ctrl + uDelete from the current position to the line start
      ctrl + kDelete from the current position to the end of line
      ctrl + aGo to start of line
      ctrl + eGo to to end of line
      ctrl + bBack one character
      ctrl + fForward one character
      ctrl + lClear screen
      ctrl + nNext history item
      ctrl + pPrevious history item
      ctrl + zMoves running process into background. Type\n fg and press enter\n to return.Doesn't work on Windows
      ctrl + w or ctrl\n + backspaceDelete backward to a word boundaryctrl + backspace Doesn't\n work on Linux, Mac and Windows
      ctrl + deleteDelete forward to a word boundaryDoesn't work on Mac
      ctrl + left or\n meta + bWord leftctrl + left Doesn't work\n on Mac
      ctrl + right or\n meta + fWord rightctrl + right Doesn't work\n on Mac
      meta + d or meta\n + deleteDelete word rightmeta + delete Doesn't work\n on windows
      meta + backspaceDelete word leftDoesn't work on Mac
      ", + "type": "module", + "displayName": "TTY keybindings" + } + ], + "type": "module", + "displayName": "Readline" + } + ] +} \ No newline at end of file diff --git a/doc/api/repl.html b/doc/api/repl.html new file mode 100644 index 0000000000000000000000000000000000000000..d9b87316c71cc7208d164447a59c84144ef7033f --- /dev/null +++ b/doc/api/repl.html @@ -0,0 +1,776 @@ + + + + + + + REPL | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      REPL#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/repl.js

      +

      The repl module provides a Read-Eval-Print-Loop (REPL) implementation that +is available both as a standalone program or includible in other applications. +It can be accessed using:

      +
      const repl = require('repl');
      +

      Design and features#

      +

      The repl module exports the repl.REPLServer class. While running, +instances of repl.REPLServer will accept individual lines of user input, +evaluate those according to a user-defined evaluation function, then output the +result. Input and output may be from stdin and stdout, respectively, or may +be connected to any Node.js stream.

      +

      Instances of repl.REPLServer support automatic completion of inputs, +completion preview, simplistic Emacs-style line editing, multi-line inputs, +ZSH-like reverse-i-search, ZSH-like substring-based history search, +ANSI-styled output, saving and restoring current REPL session state, error +recovery, and customizable evaluation functions. Terminals that do not support +ANSI styles and Emacs-style line editing automatically fall back to a limited +feature set.

      +

      Commands and special keys#

      +

      The following special commands are supported by all REPL instances:

      +
        +
      • .break: When in the process of inputting a multi-line expression, entering +the .break command (or pressing the <ctrl>-C key combination) will abort +further input or processing of that expression.
      • +
      • .clear: Resets the REPL context to an empty object and clears any +multi-line expression being input.
      • +
      • .exit: Close the I/O stream, causing the REPL to exit.
      • +
      • .help: Show this list of special commands.
      • +
      • .save: Save the current REPL session to a file: +> .save ./file/to/save.js
      • +
      • .load: Load a file into the current REPL session. +> .load ./file/to/load.js
      • +
      • .editor: Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel).
      • +
      +
      > .editor
      +// Entering editor mode (^D to finish, ^C to cancel)
      +function welcome(name) {
      +  return `Hello ${name}!`;
      +}
      +
      +welcome('Node.js User');
      +
      +// ^D
      +'Hello Node.js User!'
      +>
      +

      The following key combinations in the REPL have these special effects:

      +
        +
      • <ctrl>-C: When pressed once, has the same effect as the .break command. +When pressed twice on a blank line, has the same effect as the .exit +command.
      • +
      • <ctrl>-D: Has the same effect as the .exit command.
      • +
      • <tab>: When pressed on a blank line, displays global and local (scope) +variables. When pressed while entering other input, displays relevant +autocompletion options.
      • +
      +

      For key bindings related to the reverse-i-search, see reverse-i-search. +For all other key bindings, see TTY keybindings.

      +

      Default evaluation#

      +

      By default, all instances of repl.REPLServer use an evaluation function +that evaluates JavaScript expressions and provides access to Node.js built-in +modules. This default behavior can be overridden by passing in an alternative +evaluation function when the repl.REPLServer instance is created.

      +

      JavaScript expressions#

      +

      The default evaluator supports direct evaluation of JavaScript expressions:

      +
      > 1 + 1
      +2
      +> const m = 2
      +undefined
      +> m + 1
      +3
      +

      Unless otherwise scoped within blocks or functions, variables declared +either implicitly or using the const, let, or var keywords +are declared at the global scope.

      +

      Global and local scope#

      +

      The default evaluator provides access to any variables that exist in the global +scope. It is possible to expose a variable to the REPL explicitly by assigning +it to the context object associated with each REPLServer:

      +
      const repl = require('repl');
      +const msg = 'message';
      +
      +repl.start('> ').context.m = msg;
      +

      Properties in the context object appear as local within the REPL:

      +
      $ node repl_test.js
      +> m
      +'message'
      +

      Context properties are not read-only by default. To specify read-only globals, +context properties must be defined using Object.defineProperty():

      +
      const repl = require('repl');
      +const msg = 'message';
      +
      +const r = repl.start('> ');
      +Object.defineProperty(r.context, 'm', {
      +  configurable: false,
      +  enumerable: true,
      +  value: msg
      +});
      +

      Accessing core Node.js modules#

      +

      The default evaluator will automatically load Node.js core modules into the +REPL environment when used. For instance, unless otherwise declared as a +global or scoped variable, the input fs will be evaluated on-demand as +global.fs = require('fs').

      +
      > fs.createReadStream('./some/file');
      +

      Global uncaught exceptions#

      + +

      The REPL uses the domain module to catch all uncaught exceptions for that +REPL session.

      +

      This use of the domain module in the REPL has these side effects:

      + +

      As standalone program:

      +
      process.on('uncaughtException', () => console.log('Uncaught'));
      +
      +throw new Error('foobar');
      +// Uncaught
      +

      When used in another application:

      +
      process.on('uncaughtException', () => console.log('Uncaught'));
      +// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`
      +// cannot be used in the REPL
      +
      +throw new Error('foobar');
      +// Thrown:
      +// Error: foobar
      +

      Assignment of the _ (underscore) variable#

      + +

      The default evaluator will, by default, assign the result of the most recently +evaluated expression to the special variable _ (underscore). +Explicitly setting _ to a value will disable this behavior.

      +
      > [ 'a', 'b', 'c' ]
      +[ 'a', 'b', 'c' ]
      +> _.length
      +3
      +> _ += 1
      +Expression assignment to _ now disabled.
      +4
      +> 1 + 1
      +2
      +> _
      +4
      +

      Similarly, _error will refer to the last seen error, if there was any. +Explicitly setting _error to a value will disable this behavior.

      +
      > throw new Error('foo');
      +Error: foo
      +> _error.message
      +'foo'
      +

      await keyword#

      +

      With the --experimental-repl-await command line option specified, +experimental support for the await keyword is enabled.

      +
      > await Promise.resolve(123)
      +123
      +> await Promise.reject(new Error('REPL await'))
      +Error: REPL await
      +    at repl:1:45
      +> const timeout = util.promisify(setTimeout);
      +undefined
      +> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
      +1002
      +undefined
      +

      Reverse-i-search#

      + +

      The REPL supports bi-directional reverse-i-search similar to ZSH. It is +triggered with <ctrl> + R to search backward and <ctrl> + S to search +forward.

      +

      Duplicated history entires will be skipped.

      +

      Entries are accepted as soon as any button is pressed that doesn't correspond +with the reverse search. Cancelling is possible by pressing escape or +<ctrl> + C.

      +

      Changing the direction immediately searches for the next entry in the expected +direction from the current position on.

      +

      Custom evaluation functions#

      +

      When a new repl.REPLServer is created, a custom evaluation function may be +provided. This can be used, for instance, to implement fully customized REPL +applications.

      +

      The following illustrates a hypothetical example of a REPL that performs +translation of text from one language to another:

      +
      const repl = require('repl');
      +const { Translator } = require('translator');
      +
      +const myTranslator = new Translator('en', 'fr');
      +
      +function myEval(cmd, context, filename, callback) {
      +  callback(null, myTranslator.translate(cmd));
      +}
      +
      +repl.start({ prompt: '> ', eval: myEval });
      +

      Recoverable errors#

      +

      As a user is typing input into the REPL prompt, pressing the <enter> key will +send the current line of input to the eval function. In order to support +multi-line input, the eval function can return an instance of repl.Recoverable +to the provided callback function:

      +
      function myEval(cmd, context, filename, callback) {
      +  let result;
      +  try {
      +    result = vm.runInThisContext(cmd);
      +  } catch (e) {
      +    if (isRecoverableError(e)) {
      +      return callback(new repl.Recoverable(e));
      +    }
      +  }
      +  callback(null, result);
      +}
      +
      +function isRecoverableError(error) {
      +  if (error.name === 'SyntaxError') {
      +    return /^(Unexpected end of input|Unexpected token)/.test(error.message);
      +  }
      +  return false;
      +}
      +

      Customizing REPL output#

      +

      By default, repl.REPLServer instances format output using the +util.inspect() method before writing the output to the provided Writable +stream (process.stdout by default). The showProxy inspection option is set +to true by default and the colors option is set to true depending on the +REPL's useColors option.

      +

      The useColors boolean option can be specified at construction to instruct the +default writer to use ANSI style codes to colorize the output from the +util.inspect() method.

      +

      If the REPL is run as standalone program, it is also possible to change the +REPL's inspection defaults from inside the REPL by using the +inspect.replDefaults property which mirrors the defaultOptions from +util.inspect().

      +
      > util.inspect.replDefaults.compact = false;
      +false
      +> [1]
      +[
      +  1
      +]
      +>
      +

      To fully customize the output of a repl.REPLServer instance pass in a new +function for the writer option on construction. The following example, for +instance, simply converts any input text to upper case:

      +
      const repl = require('repl');
      +
      +const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });
      +
      +function myEval(cmd, context, filename, callback) {
      +  callback(null, cmd);
      +}
      +
      +function myWriter(output) {
      +  return output.toUpperCase();
      +}
      +

      Class: REPLServer#

      + + +

      Instances of repl.REPLServer are created using the repl.start() method +or directly using the JavaScript new keyword.

      +
      const repl = require('repl');
      +
      +const options = { useColors: true };
      +
      +const firstInstance = repl.start(options);
      +const secondInstance = new repl.REPLServer(options);
      +

      Event: 'exit'#

      + +

      The 'exit' event is emitted when the REPL is exited either by receiving the +.exit command as input, the user pressing <ctrl>-C twice to signal SIGINT, +or by pressing <ctrl>-D to signal 'end' on the input stream. The listener +callback is invoked without any arguments.

      +
      replServer.on('exit', () => {
      +  console.log('Received "exit" event from repl!');
      +  process.exit();
      +});
      +

      Event: 'reset'#

      + +

      The 'reset' event is emitted when the REPL's context is reset. This occurs +whenever the .clear command is received as input unless the REPL is using +the default evaluator and the repl.REPLServer instance was created with the +useGlobal option set to true. The listener callback will be called with a +reference to the context object as the only argument.

      +

      This can be used primarily to re-initialize REPL context to some pre-defined +state:

      +
      const repl = require('repl');
      +
      +function initializeContext(context) {
      +  context.m = 'test';
      +}
      +
      +const r = repl.start({ prompt: '> ' });
      +initializeContext(r.context);
      +
      +r.on('reset', initializeContext);
      +

      When this code is executed, the global 'm' variable can be modified but then +reset to its initial value using the .clear command:

      +
      $ ./node example.js
      +> m
      +'test'
      +> m = 1
      +1
      +> m
      +1
      +> .clear
      +Clearing context...
      +> m
      +'test'
      +>
      +

      replServer.defineCommand(keyword, cmd)#

      + +
        +
      • keyword <string> The command keyword (without a leading . character).
      • +
      • cmd <Object> | <Function> The function to invoke when the command is processed.
      • +
      +

      The replServer.defineCommand() method is used to add new .-prefixed commands +to the REPL instance. Such commands are invoked by typing a . followed by the +keyword. The cmd is either a Function or an Object with the following +properties:

      +
        +
      • help <string> Help text to be displayed when .help is entered (Optional).
      • +
      • action <Function> The function to execute, optionally accepting a single +string argument.
      • +
      +

      The following example shows two new commands added to the REPL instance:

      +
      const repl = require('repl');
      +
      +const replServer = repl.start({ prompt: '> ' });
      +replServer.defineCommand('sayhello', {
      +  help: 'Say hello',
      +  action(name) {
      +    this.clearBufferedCommand();
      +    console.log(`Hello, ${name}!`);
      +    this.displayPrompt();
      +  }
      +});
      +replServer.defineCommand('saybye', function saybye() {
      +  console.log('Goodbye!');
      +  this.close();
      +});
      +

      The new commands can then be used from within the REPL instance:

      +
      > .sayhello Node.js User
      +Hello, Node.js User!
      +> .saybye
      +Goodbye!
      +

      replServer.displayPrompt([preserveCursor])#

      + + +

      The replServer.displayPrompt() method readies the REPL instance for input +from the user, printing the configured prompt to a new line in the output +and resuming the input to accept new input.

      +

      When multi-line input is being entered, an ellipsis is printed rather than the +'prompt'.

      +

      When preserveCursor is true, the cursor placement will not be reset to 0.

      +

      The replServer.displayPrompt method is primarily intended to be called from +within the action function for commands registered using the +replServer.defineCommand() method.

      +

      replServer.clearBufferedCommand()#

      + +

      The replServer.clearBufferedCommand() method clears any command that has been +buffered but not yet executed. This method is primarily intended to be +called from within the action function for commands registered using the +replServer.defineCommand() method.

      +

      replServer.parseREPLKeyword(keyword[, rest])#

      + +

      Stability: 0 - Deprecated.

      +
        +
      • keyword <string> the potential keyword to parse and execute
      • +
      • rest <any> any parameters to the keyword command
      • +
      • Returns: <boolean>
      • +
      +

      An internal method used to parse and execute REPLServer keywords. +Returns true if keyword is a valid keyword, otherwise false.

      +

      replServer.setupHistory(historyPath, callback)#

      + + +

      Initializes a history log file for the REPL instance. When executing the +Node.js binary and using the command line REPL, a history file is initialized +by default. However, this is not the case when creating a REPL +programmatically. Use this method to initialize a history log file when working +with REPL instances programmatically.

      +

      repl.start([options])#

      + +
        +
      • options <Object> | <string> +
          +
        • prompt <string> The input prompt to display. Default: '> ' +(with a trailing space).
        • +
        • input <stream.Readable> The Readable stream from which REPL input will +be read. Default: process.stdin.
        • +
        • output <stream.Writable> The Writable stream to which REPL output will +be written. Default: process.stdout.
        • +
        • terminal <boolean> If true, specifies that the output should be +treated as a TTY terminal. +Default: checking the value of the isTTY property on the output +stream upon instantiation.
        • +
        • eval <Function> The function to be used when evaluating each given line +of input. Default: an async wrapper for the JavaScript eval() +function. An eval function can error with repl.Recoverable to indicate +the input was incomplete and prompt for additional lines.
        • +
        • useColors <boolean> If true, specifies that the default writer +function should include ANSI color styling to REPL output. If a custom +writer function is provided then this has no effect. Default: checking +color support on the output stream if the REPL instance's terminal value +is true.
        • +
        • useGlobal <boolean> If true, specifies that the default evaluation +function will use the JavaScript global as the context as opposed to +creating a new separate context for the REPL instance. The node CLI REPL +sets this value to true. Default: false.
        • +
        • ignoreUndefined <boolean> If true, specifies that the default writer +will not output the return value of a command if it evaluates to +undefined. Default: false.
        • +
        • writer <Function> The function to invoke to format the output of each + command before writing to output. Default: util.inspect().
        • +
        • completer <Function> An optional function used for custom Tab auto + completion. See readline.InterfaceCompleter for an example.
        • +
        • replMode <symbol> A flag that specifies whether the default evaluator +executes all JavaScript commands in strict mode or default (sloppy) mode. +Acceptable values are: +
            +
          • repl.REPL_MODE_SLOPPY to evaluate expressions in sloppy mode.
          • +
          • repl.REPL_MODE_STRICT to evaluate expressions in strict mode. This is +equivalent to prefacing every repl statement with 'use strict'.
          • +
          +
        • +
        • breakEvalOnSigint <boolean> Stop evaluating the current piece of code when +SIGINT is received, such as when Ctrl+C is pressed. This cannot be used +together with a custom eval function. Default: false.
        • +
        • preview <boolean> Defines if the repl prints autocomplete and output +previews or not. Default: true with the default eval function and +false in case a custom eval function is used. If terminal is falsy, then +there are no previews and the value of preview has no effect.
        • +
        +
      • +
      • Returns: <repl.REPLServer>
      • +
      +

      The repl.start() method creates and starts a repl.REPLServer instance.

      +

      If options is a string, then it specifies the input prompt:

      +
      const repl = require('repl');
      +
      +// a Unix style prompt
      +repl.start('$ ');
      +

      The Node.js REPL#

      +

      Node.js itself uses the repl module to provide its own interactive interface +for executing JavaScript. This can be used by executing the Node.js binary +without passing any arguments (or by passing the -i argument):

      +
      $ node
      +> const a = [1, 2, 3];
      +undefined
      +> a
      +[ 1, 2, 3 ]
      +> a.forEach((v) => {
      +...   console.log(v);
      +...   });
      +1
      +2
      +3
      +

      Environment variable options#

      +

      Various behaviors of the Node.js REPL can be customized using the following +environment variables:

      +
        +
      • NODE_REPL_HISTORY: When a valid path is given, persistent REPL history +will be saved to the specified file rather than .node_repl_history in the +user's home directory. Setting this value to '' (an empty string) will +disable persistent REPL history. Whitespace will be trimmed from the value. +On Windows platforms environment variables with empty values are invalid so +set this variable to one or more spaces to disable persistent REPL history.
      • +
      • NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be +persisted if history is available. Must be a positive number. +Default: 1000.
      • +
      • NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default: +'sloppy', which will allow non-strict mode code to be run.
      • +
      +

      Persistent history#

      +

      By default, the Node.js REPL will persist history between node REPL sessions +by saving inputs to a .node_repl_history file located in the user's home +directory. This can be disabled by setting the environment variable +NODE_REPL_HISTORY=''.

      +

      Using the Node.js REPL with advanced line-editors#

      +

      For advanced line-editors, start Node.js with the environment variable +NODE_NO_READLINE=1. This will start the main and debugger REPL in canonical +terminal settings, which will allow use with rlwrap.

      +

      For example, the following can be added to a .bashrc file:

      +
      alias node="env NODE_NO_READLINE=1 rlwrap node"
      +

      Starting multiple REPL instances against a single running instance#

      +

      It is possible to create and run multiple REPL instances against a single +running instance of Node.js that share a single global object but have +separate I/O interfaces.

      +

      The following example, for instance, provides separate REPLs on stdin, a Unix +socket, and a TCP socket:

      +
      const net = require('net');
      +const repl = require('repl');
      +let connections = 0;
      +
      +repl.start({
      +  prompt: 'Node.js via stdin> ',
      +  input: process.stdin,
      +  output: process.stdout
      +});
      +
      +net.createServer((socket) => {
      +  connections += 1;
      +  repl.start({
      +    prompt: 'Node.js via Unix socket> ',
      +    input: socket,
      +    output: socket
      +  }).on('exit', () => {
      +    socket.end();
      +  });
      +}).listen('/tmp/node-repl-sock');
      +
      +net.createServer((socket) => {
      +  connections += 1;
      +  repl.start({
      +    prompt: 'Node.js via TCP socket> ',
      +    input: socket,
      +    output: socket
      +  }).on('exit', () => {
      +    socket.end();
      +  });
      +}).listen(5001);
      +

      Running this application from the command line will start a REPL on stdin. +Other REPL clients may connect through the Unix socket or TCP socket. telnet, +for instance, is useful for connecting to TCP sockets, while socat can be used +to connect to both Unix and TCP sockets.

      +

      By starting a REPL from a Unix socket-based server instead of stdin, it is +possible to connect to a long-running Node.js process without restarting it.

      +

      For an example of running a "full-featured" (terminal) REPL over +a net.Server and net.Socket instance, see: +https://gist.github.com/TooTallNate/2209310.

      +

      For an example of running a REPL instance over curl(1), see: +https://gist.github.com/TooTallNate/2053342.

      + +
      +
      +
      + + diff --git a/doc/api/repl.json b/doc/api/repl.json new file mode 100644 index 0000000000000000000000000000000000000000..9eff9448adbea947ea5c43fa356aac990b6209e3 --- /dev/null +++ b/doc/api/repl.json @@ -0,0 +1,531 @@ +{ + "type": "module", + "source": "doc/api/repl.md", + "modules": [ + { + "textRaw": "REPL", + "name": "repl", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/repl.js

      \n

      The repl module provides a Read-Eval-Print-Loop (REPL) implementation that\nis available both as a standalone program or includible in other applications.\nIt can be accessed using:

      \n
      const repl = require('repl');\n
      ", + "modules": [ + { + "textRaw": "Design and features", + "name": "design_and_features", + "desc": "

      The repl module exports the repl.REPLServer class. While running,\ninstances of repl.REPLServer will accept individual lines of user input,\nevaluate those according to a user-defined evaluation function, then output the\nresult. Input and output may be from stdin and stdout, respectively, or may\nbe connected to any Node.js stream.

      \n

      Instances of repl.REPLServer support automatic completion of inputs,\ncompletion preview, simplistic Emacs-style line editing, multi-line inputs,\nZSH-like reverse-i-search, ZSH-like substring-based history search,\nANSI-styled output, saving and restoring current REPL session state, error\nrecovery, and customizable evaluation functions. Terminals that do not support\nANSI styles and Emacs-style line editing automatically fall back to a limited\nfeature set.

      ", + "modules": [ + { + "textRaw": "Commands and special keys", + "name": "commands_and_special_keys", + "desc": "

      The following special commands are supported by all REPL instances:

      \n
        \n
      • .break: When in the process of inputting a multi-line expression, entering\nthe .break command (or pressing the <ctrl>-C key combination) will abort\nfurther input or processing of that expression.
      • \n
      • .clear: Resets the REPL context to an empty object and clears any\nmulti-line expression being input.
      • \n
      • .exit: Close the I/O stream, causing the REPL to exit.
      • \n
      • .help: Show this list of special commands.
      • \n
      • .save: Save the current REPL session to a file:\n> .save ./file/to/save.js
      • \n
      • .load: Load a file into the current REPL session.\n> .load ./file/to/load.js
      • \n
      • .editor: Enter editor mode (<ctrl>-D to finish, <ctrl>-C to cancel).
      • \n
      \n
      > .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n  return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>\n
      \n

      The following key combinations in the REPL have these special effects:

      \n
        \n
      • <ctrl>-C: When pressed once, has the same effect as the .break command.\nWhen pressed twice on a blank line, has the same effect as the .exit\ncommand.
      • \n
      • <ctrl>-D: Has the same effect as the .exit command.
      • \n
      • <tab>: When pressed on a blank line, displays global and local (scope)\nvariables. When pressed while entering other input, displays relevant\nautocompletion options.
      • \n
      \n

      For key bindings related to the reverse-i-search, see reverse-i-search.\nFor all other key bindings, see TTY keybindings.

      ", + "type": "module", + "displayName": "Commands and special keys" + }, + { + "textRaw": "Default evaluation", + "name": "default_evaluation", + "desc": "

      By default, all instances of repl.REPLServer use an evaluation function\nthat evaluates JavaScript expressions and provides access to Node.js built-in\nmodules. This default behavior can be overridden by passing in an alternative\nevaluation function when the repl.REPLServer instance is created.

      ", + "modules": [ + { + "textRaw": "JavaScript expressions", + "name": "javascript_expressions", + "desc": "

      The default evaluator supports direct evaluation of JavaScript expressions:

      \n
      > 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n
      \n

      Unless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const, let, or var keywords\nare declared at the global scope.

      ", + "type": "module", + "displayName": "JavaScript expressions" + }, + { + "textRaw": "Global and local scope", + "name": "global_and_local_scope", + "desc": "

      The default evaluator provides access to any variables that exist in the global\nscope. It is possible to expose a variable to the REPL explicitly by assigning\nit to the context object associated with each REPLServer:

      \n
      const repl = require('repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n
      \n

      Properties in the context object appear as local within the REPL:

      \n
      $ node repl_test.js\n> m\n'message'\n
      \n

      Context properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using Object.defineProperty():

      \n
      const repl = require('repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n  configurable: false,\n  enumerable: true,\n  value: msg\n});\n
      ", + "type": "module", + "displayName": "Global and local scope" + }, + { + "textRaw": "Accessing core Node.js modules", + "name": "accessing_core_node.js_modules", + "desc": "

      The default evaluator will automatically load Node.js core modules into the\nREPL environment when used. For instance, unless otherwise declared as a\nglobal or scoped variable, the input fs will be evaluated on-demand as\nglobal.fs = require('fs').

      \n
      > fs.createReadStream('./some/file');\n
      ", + "type": "module", + "displayName": "Accessing core Node.js modules" + }, + { + "textRaw": "Global uncaught exceptions", + "name": "global_uncaught_exceptions", + "meta": { + "changes": [ + { + "version": "v12.3.0", + "pr-url": "https://github.com/nodejs/node/pull/27151", + "description": "The `'uncaughtException'` event is from now on triggered if the repl is used as standalone program." + } + ] + }, + "desc": "

      The REPL uses the domain module to catch all uncaught exceptions for that\nREPL session.

      \n

      This use of the domain module in the REPL has these side effects:

      \n\n

      As standalone program:

      \n
      process.on('uncaughtException', () => console.log('Uncaught'));\n\nthrow new Error('foobar');\n// Uncaught\n
      \n

      When used in another application:

      \n
      process.on('uncaughtException', () => console.log('Uncaught'));\n// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n// cannot be used in the REPL\n\nthrow new Error('foobar');\n// Thrown:\n// Error: foobar\n
      ", + "type": "module", + "displayName": "Global uncaught exceptions" + }, + { + "textRaw": "Assignment of the `_` (underscore) variable", + "name": "assignment_of_the_`_`_(underscore)_variable", + "meta": { + "changes": [ + { + "version": "v9.8.0", + "pr-url": "https://github.com/nodejs/node/pull/18919", + "description": "Added `_error` support." + } + ] + }, + "desc": "

      The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable _ (underscore).\nExplicitly setting _ to a value will disable this behavior.

      \n
      > [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4\n
      \n

      Similarly, _error will refer to the last seen error, if there was any.\nExplicitly setting _error to a value will disable this behavior.

      \n
      > throw new Error('foo');\nError: foo\n> _error.message\n'foo'\n
      ", + "type": "module", + "displayName": "Assignment of the `_` (underscore) variable" + }, + { + "textRaw": "`await` keyword", + "name": "`await`_keyword", + "desc": "

      With the --experimental-repl-await command line option specified,\nexperimental support for the await keyword is enabled.

      \n
      > await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nError: REPL await\n    at repl:1:45\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined\n
      ", + "type": "module", + "displayName": "`await` keyword" + } + ], + "type": "module", + "displayName": "Default evaluation" + }, + { + "textRaw": "Reverse-i-search", + "name": "reverse-i-search", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "desc": "

      The REPL supports bi-directional reverse-i-search similar to ZSH. It is\ntriggered with <ctrl> + R to search backward and <ctrl> + S to search\nforward.

      \n

      Duplicated history entires will be skipped.

      \n

      Entries are accepted as soon as any button is pressed that doesn't correspond\nwith the reverse search. Cancelling is possible by pressing escape or\n<ctrl> + C.

      \n

      Changing the direction immediately searches for the next entry in the expected\ndirection from the current position on.

      ", + "type": "module", + "displayName": "Reverse-i-search" + }, + { + "textRaw": "Custom evaluation functions", + "name": "custom_evaluation_functions", + "desc": "

      When a new repl.REPLServer is created, a custom evaluation function may be\nprovided. This can be used, for instance, to implement fully customized REPL\napplications.

      \n

      The following illustrates a hypothetical example of a REPL that performs\ntranslation of text from one language to another:

      \n
      const repl = require('repl');\nconst { Translator } = require('translator');\n\nconst myTranslator = new Translator('en', 'fr');\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, myTranslator.translate(cmd));\n}\n\nrepl.start({ prompt: '> ', eval: myEval });\n
      ", + "modules": [ + { + "textRaw": "Recoverable errors", + "name": "recoverable_errors", + "desc": "

      As a user is typing input into the REPL prompt, pressing the <enter> key will\nsend the current line of input to the eval function. In order to support\nmulti-line input, the eval function can return an instance of repl.Recoverable\nto the provided callback function:

      \n
      function myEval(cmd, context, filename, callback) {\n  let result;\n  try {\n    result = vm.runInThisContext(cmd);\n  } catch (e) {\n    if (isRecoverableError(e)) {\n      return callback(new repl.Recoverable(e));\n    }\n  }\n  callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n  if (error.name === 'SyntaxError') {\n    return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n  }\n  return false;\n}\n
      ", + "type": "module", + "displayName": "Recoverable errors" + } + ], + "type": "module", + "displayName": "Custom evaluation functions" + }, + { + "textRaw": "Customizing REPL output", + "name": "customizing_repl_output", + "desc": "

      By default, repl.REPLServer instances format output using the\nutil.inspect() method before writing the output to the provided Writable\nstream (process.stdout by default). The showProxy inspection option is set\nto true by default and the colors option is set to true depending on the\nREPL's useColors option.

      \n

      The useColors boolean option can be specified at construction to instruct the\ndefault writer to use ANSI style codes to colorize the output from the\nutil.inspect() method.

      \n

      If the REPL is run as standalone program, it is also possible to change the\nREPL's inspection defaults from inside the REPL by using the\ninspect.replDefaults property which mirrors the defaultOptions from\nutil.inspect().

      \n
      > util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n  1\n]\n>\n
      \n

      To fully customize the output of a repl.REPLServer instance pass in a new\nfunction for the writer option on construction. The following example, for\ninstance, simply converts any input text to upper case:

      \n
      const repl = require('repl');\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, cmd);\n}\n\nfunction myWriter(output) {\n  return output.toUpperCase();\n}\n
      ", + "type": "module", + "displayName": "Customizing REPL output" + } + ], + "type": "module", + "displayName": "Design and features" + }, + { + "textRaw": "The Node.js REPL", + "name": "the_node.js_repl", + "desc": "

      Node.js itself uses the repl module to provide its own interactive interface\nfor executing JavaScript. This can be used by executing the Node.js binary\nwithout passing any arguments (or by passing the -i argument):

      \n
      $ node\n> const a = [1, 2, 3];\nundefined\n> a\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n...   console.log(v);\n...   });\n1\n2\n3\n
      ", + "modules": [ + { + "textRaw": "Environment variable options", + "name": "environment_variable_options", + "desc": "

      Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:

      \n
        \n
      • NODE_REPL_HISTORY: When a valid path is given, persistent REPL history\nwill be saved to the specified file rather than .node_repl_history in the\nuser's home directory. Setting this value to '' (an empty string) will\ndisable persistent REPL history. Whitespace will be trimmed from the value.\nOn Windows platforms environment variables with empty values are invalid so\nset this variable to one or more spaces to disable persistent REPL history.
      • \n
      • NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be\npersisted if history is available. Must be a positive number.\nDefault: 1000.
      • \n
      • NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default:\n'sloppy', which will allow non-strict mode code to be run.
      • \n
      ", + "type": "module", + "displayName": "Environment variable options" + }, + { + "textRaw": "Persistent history", + "name": "persistent_history", + "desc": "

      By default, the Node.js REPL will persist history between node REPL sessions\nby saving inputs to a .node_repl_history file located in the user's home\ndirectory. This can be disabled by setting the environment variable\nNODE_REPL_HISTORY=''.

      ", + "type": "module", + "displayName": "Persistent history" + }, + { + "textRaw": "Using the Node.js REPL with advanced line-editors", + "name": "using_the_node.js_repl_with_advanced_line-editors", + "desc": "

      For advanced line-editors, start Node.js with the environment variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings, which will allow use with rlwrap.

      \n

      For example, the following can be added to a .bashrc file:

      \n
      alias node=\"env NODE_NO_READLINE=1 rlwrap node\"\n
      ", + "type": "module", + "displayName": "Using the Node.js REPL with advanced line-editors" + }, + { + "textRaw": "Starting multiple REPL instances against a single running instance", + "name": "starting_multiple_repl_instances_against_a_single_running_instance", + "desc": "

      It is possible to create and run multiple REPL instances against a single\nrunning instance of Node.js that share a single global object but have\nseparate I/O interfaces.

      \n

      The following example, for instance, provides separate REPLs on stdin, a Unix\nsocket, and a TCP socket:

      \n
      const net = require('net');\nconst repl = require('repl');\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    input: socket,\n    output: socket\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen('/tmp/node-repl-sock');\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    input: socket,\n    output: socket\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);\n
      \n

      Running this application from the command line will start a REPL on stdin.\nOther REPL clients may connect through the Unix socket or TCP socket. telnet,\nfor instance, is useful for connecting to TCP sockets, while socat can be used\nto connect to both Unix and TCP sockets.

      \n

      By starting a REPL from a Unix socket-based server instead of stdin, it is\npossible to connect to a long-running Node.js process without restarting it.

      \n

      For an example of running a \"full-featured\" (terminal) REPL over\na net.Server and net.Socket instance, see:\nhttps://gist.github.com/TooTallNate/2209310.

      \n

      For an example of running a REPL instance over curl(1), see:\nhttps://gist.github.com/TooTallNate/2053342.

      ", + "type": "module", + "displayName": "Starting multiple REPL instances against a single running instance" + } + ], + "type": "module", + "displayName": "The Node.js REPL" + } + ], + "classes": [ + { + "textRaw": "Class: `REPLServer`", + "type": "class", + "name": "REPLServer", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [] + }, + "desc": "\n

      Instances of repl.REPLServer are created using the repl.start() method\nor directly using the JavaScript new keyword.

      \n
      const repl = require('repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n
      ", + "events": [ + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'exit' event is emitted when the REPL is exited either by receiving the\n.exit command as input, the user pressing <ctrl>-C twice to signal SIGINT,\nor by pressing <ctrl>-D to signal 'end' on the input stream. The listener\ncallback is invoked without any arguments.

      \n
      replServer.on('exit', () => {\n  console.log('Received \"exit\" event from repl!');\n  process.exit();\n});\n
      " + }, + { + "textRaw": "Event: `'reset'`", + "type": "event", + "name": "reset", + "meta": { + "added": [ + "v0.11.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'reset' event is emitted when the REPL's context is reset. This occurs\nwhenever the .clear command is received as input unless the REPL is using\nthe default evaluator and the repl.REPLServer instance was created with the\nuseGlobal option set to true. The listener callback will be called with a\nreference to the context object as the only argument.

      \n

      This can be used primarily to re-initialize REPL context to some pre-defined\nstate:

      \n
      const repl = require('repl');\n\nfunction initializeContext(context) {\n  context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n
      \n

      When this code is executed, the global 'm' variable can be modified but then\nreset to its initial value using the .clear command:

      \n
      $ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n
      " + } + ], + "methods": [ + { + "textRaw": "`replServer.defineCommand(keyword, cmd)`", + "type": "method", + "name": "defineCommand", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`keyword` {string} The command keyword (*without* a leading `.` character).", + "name": "keyword", + "type": "string", + "desc": "The command keyword (*without* a leading `.` character)." + }, + { + "textRaw": "`cmd` {Object|Function} The function to invoke when the command is processed.", + "name": "cmd", + "type": "Object|Function", + "desc": "The function to invoke when the command is processed." + } + ] + } + ], + "desc": "

      The replServer.defineCommand() method is used to add new .-prefixed commands\nto the REPL instance. Such commands are invoked by typing a . followed by the\nkeyword. The cmd is either a Function or an Object with the following\nproperties:

      \n
        \n
      • help <string> Help text to be displayed when .help is entered (Optional).
      • \n
      • action <Function> The function to execute, optionally accepting a single\nstring argument.
      • \n
      \n

      The following example shows two new commands added to the REPL instance:

      \n
      const repl = require('repl');\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action(name) {\n    this.clearBufferedCommand();\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  }\n});\nreplServer.defineCommand('saybye', function saybye() {\n  console.log('Goodbye!');\n  this.close();\n});\n
      \n

      The new commands can then be used from within the REPL instance:

      \n
      > .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n
      " + }, + { + "textRaw": "`replServer.displayPrompt([preserveCursor])`", + "type": "method", + "name": "displayPrompt", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`preserveCursor` {boolean}", + "name": "preserveCursor", + "type": "boolean" + } + ] + } + ], + "desc": "

      The replServer.displayPrompt() method readies the REPL instance for input\nfrom the user, printing the configured prompt to a new line in the output\nand resuming the input to accept new input.

      \n

      When multi-line input is being entered, an ellipsis is printed rather than the\n'prompt'.

      \n

      When preserveCursor is true, the cursor placement will not be reset to 0.

      \n

      The replServer.displayPrompt method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand() method.

      " + }, + { + "textRaw": "`replServer.clearBufferedCommand()`", + "type": "method", + "name": "clearBufferedCommand", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The replServer.clearBufferedCommand() method clears any command that has been\nbuffered but not yet executed. This method is primarily intended to be\ncalled from within the action function for commands registered using the\nreplServer.defineCommand() method.

      " + }, + { + "textRaw": "`replServer.parseREPLKeyword(keyword[, rest])`", + "type": "method", + "name": "parseREPLKeyword", + "meta": { + "added": [ + "v0.8.9" + ], + "deprecated": [ + "v9.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`keyword` {string} the potential keyword to parse and execute", + "name": "keyword", + "type": "string", + "desc": "the potential keyword to parse and execute" + }, + { + "textRaw": "`rest` {any} any parameters to the keyword command", + "name": "rest", + "type": "any", + "desc": "any parameters to the keyword command" + } + ] + } + ], + "desc": "

      An internal method used to parse and execute REPLServer keywords.\nReturns true if keyword is a valid keyword, otherwise false.

      " + }, + { + "textRaw": "`replServer.setupHistory(historyPath, callback)`", + "type": "method", + "name": "setupHistory", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`historyPath` {string} the path to the history file", + "name": "historyPath", + "type": "string", + "desc": "the path to the history file" + }, + { + "textRaw": "`callback` {Function} called when history writes are ready or upon error", + "name": "callback", + "type": "Function", + "desc": "called when history writes are ready or upon error", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + }, + { + "textRaw": "`repl` {repl.REPLServer}", + "name": "repl", + "type": "repl.REPLServer" + } + ] + } + ] + } + ], + "desc": "

      Initializes a history log file for the REPL instance. When executing the\nNode.js binary and using the command line REPL, a history file is initialized\nby default. However, this is not the case when creating a REPL\nprogrammatically. Use this method to initialize a history log file when working\nwith REPL instances programmatically.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`repl.start([options])`", + "type": "method", + "name": "start", + "meta": { + "added": [ + "v0.1.91" + ], + "changes": [ + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/30811", + "description": "The `preview` option is now available." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26518", + "description": "The `terminal` option now follows the default description in all cases and `useColors` checks `hasColors()` if available." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19187", + "description": "The `REPL_MAGIC_MODE` `replMode` was removed." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakEvalOnSigint` option is supported now." + }, + { + "version": "v5.8.0", + "pr-url": "https://github.com/nodejs/node/pull/5388", + "description": "The `options` parameter is optional now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {repl.REPLServer}", + "name": "return", + "type": "repl.REPLServer" + }, + "params": [ + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`prompt` {string} The input prompt to display. **Default:** `'> '` (with a trailing space).", + "name": "prompt", + "type": "string", + "default": "`'> '` (with a trailing space)", + "desc": "The input prompt to display." + }, + { + "textRaw": "`input` {stream.Readable} The `Readable` stream from which REPL input will be read. **Default:** `process.stdin`.", + "name": "input", + "type": "stream.Readable", + "default": "`process.stdin`", + "desc": "The `Readable` stream from which REPL input will be read." + }, + { + "textRaw": "`output` {stream.Writable} The `Writable` stream to which REPL output will be written. **Default:** `process.stdout`.", + "name": "output", + "type": "stream.Writable", + "default": "`process.stdout`", + "desc": "The `Writable` stream to which REPL output will be written." + }, + { + "textRaw": "`terminal` {boolean} If `true`, specifies that the `output` should be treated as a TTY terminal. **Default:** checking the value of the `isTTY` property on the `output` stream upon instantiation.", + "name": "terminal", + "type": "boolean", + "default": "checking the value of the `isTTY` property on the `output` stream upon instantiation", + "desc": "If `true`, specifies that the `output` should be treated as a TTY terminal." + }, + { + "textRaw": "`eval` {Function} The function to be used when evaluating each given line of input. **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines.", + "name": "eval", + "type": "Function", + "default": "an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines", + "desc": "The function to be used when evaluating each given line of input." + }, + { + "textRaw": "`useColors` {boolean} If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect. **Default:** checking color support on the `output` stream if the REPL instance's `terminal` value is `true`.", + "name": "useColors", + "type": "boolean", + "default": "checking color support on the `output` stream if the REPL instance's `terminal` value is `true`", + "desc": "If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect." + }, + { + "textRaw": "`useGlobal` {boolean} If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`. **Default:** `false`.", + "name": "useGlobal", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`." + }, + { + "textRaw": "`ignoreUndefined` {boolean} If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. **Default:** `false`.", + "name": "ignoreUndefined", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`." + }, + { + "textRaw": "`writer` {Function} The function to invoke to format the output of each command before writing to `output`. **Default:** [`util.inspect()`][].", + "name": "writer", + "type": "Function", + "default": "[`util.inspect()`][]", + "desc": "The function to invoke to format the output of each command before writing to `output`." + }, + { + "textRaw": "`completer` {Function} An optional function used for custom Tab auto completion. See [`readline.InterfaceCompleter`][] for an example.", + "name": "completer", + "type": "Function", + "desc": "An optional function used for custom Tab auto completion. See [`readline.InterfaceCompleter`][] for an example." + }, + { + "textRaw": "`replMode` {symbol} A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:", + "name": "replMode", + "type": "symbol", + "desc": "A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:", + "options": [ + { + "textRaw": "`repl.REPL_MODE_SLOPPY` to evaluate expressions in sloppy mode.", + "name": "repl.REPL_MODE_SLOPPY", + "desc": "to evaluate expressions in sloppy mode." + }, + { + "textRaw": "`repl.REPL_MODE_STRICT` to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`.", + "name": "repl.REPL_MODE_STRICT", + "desc": "to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`." + } + ] + }, + { + "textRaw": "`breakEvalOnSigint` {boolean} Stop evaluating the current piece of code when `SIGINT` is received, such as when `Ctrl+C` is pressed. This cannot be used together with a custom `eval` function. **Default:** `false`.", + "name": "breakEvalOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "Stop evaluating the current piece of code when `SIGINT` is received, such as when `Ctrl+C` is pressed. This cannot be used together with a custom `eval` function." + }, + { + "textRaw": "`preview` {boolean} Defines if the repl prints autocomplete and output previews or not. **Default:** `true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect.", + "name": "preview", + "type": "boolean", + "default": "`true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect", + "desc": "Defines if the repl prints autocomplete and output previews or not." + } + ] + } + ] + } + ], + "desc": "

      The repl.start() method creates and starts a repl.REPLServer instance.

      \n

      If options is a string, then it specifies the input prompt:

      \n
      const repl = require('repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n
      " + } + ], + "type": "module", + "displayName": "REPL" + } + ] +} \ No newline at end of file diff --git a/doc/api/report.html b/doc/api/report.html new file mode 100644 index 0000000000000000000000000000000000000000..164150bfb08a155dc3b9c9f512bca1a27a2ae0c7 --- /dev/null +++ b/doc/api/report.html @@ -0,0 +1,684 @@ + + + + + + + Diagnostic report | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Diagnostic report#

      + + +

      Stability: 2 - Stable

      + +

      Delivers a JSON-formatted diagnostic summary, written to a file.

      +

      The report is intended for development, test and production use, to capture +and preserve information for problem determination. It includes JavaScript +and native stack traces, heap statistics, platform information, resource +usage etc. With the report option enabled, diagnostic reports can be triggered +on unhandled exceptions, fatal errors and user signals, in addition to +triggering programmatically through API calls.

      +

      A complete example report that was generated on an uncaught exception +is provided below for reference.

      +
      {
      +  "header": {
      +    "reportVersion": 1,
      +    "event": "exception",
      +    "trigger": "Exception",
      +    "filename": "report.20181221.005011.8974.0.001.json",
      +    "dumpEventTime": "2018-12-21T00:50:11Z",
      +    "dumpEventTimeStamp": "1545371411331",
      +    "processId": 8974,
      +    "cwd": "/home/nodeuser/project/node",
      +    "commandLine": [
      +      "/home/nodeuser/project/node/out/Release/node",
      +      "--report-uncaught-exception",
      +      "/home/nodeuser/project/node/test/report/test-exception.js",
      +      "child"
      +    ],
      +    "nodejsVersion": "v12.0.0-pre",
      +    "glibcVersionRuntime": "2.17",
      +    "glibcVersionCompiler": "2.17",
      +    "wordSize": "64 bit",
      +    "arch": "x64",
      +    "platform": "linux",
      +    "componentVersions": {
      +      "node": "12.0.0-pre",
      +      "v8": "7.1.302.28-node.5",
      +      "uv": "1.24.1",
      +      "zlib": "1.2.11",
      +      "ares": "1.15.0",
      +      "modules": "68",
      +      "nghttp2": "1.34.0",
      +      "napi": "3",
      +      "llhttp": "1.0.1",
      +      "http_parser": "2.8.0",
      +      "openssl": "1.1.0j"
      +    },
      +    "release": {
      +      "name": "node"
      +    },
      +    "osName": "Linux",
      +    "osRelease": "3.10.0-862.el7.x86_64",
      +    "osVersion": "#1 SMP Wed Mar 21 18:14:51 EDT 2018",
      +    "osMachine": "x86_64",
      +    "cpus": [
      +      {
      +        "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
      +        "speed": 2700,
      +        "user": 88902660,
      +        "nice": 0,
      +        "sys": 50902570,
      +        "idle": 241732220,
      +        "irq": 0
      +      },
      +      {
      +        "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
      +        "speed": 2700,
      +        "user": 88902660,
      +        "nice": 0,
      +        "sys": 50902570,
      +        "idle": 241732220,
      +        "irq": 0
      +      }
      +    ],
      +    "networkInterfaces": [
      +      {
      +        "name": "en0",
      +        "internal": false,
      +        "mac": "13:10:de:ad:be:ef",
      +        "address": "10.0.0.37",
      +        "netmask": "255.255.255.0",
      +        "family": "IPv4"
      +      }
      +    ],
      +    "host": "test_machine"
      +  },
      +  "javascriptStack": {
      +    "message": "Error: *** test-exception.js: throwing uncaught Error",
      +    "stack": [
      +      "at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)",
      +      "at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)",
      +      "at Module._compile (internal/modules/cjs/loader.js:718:30)",
      +      "at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)",
      +      "at Module.load (internal/modules/cjs/loader.js:617:32)",
      +      "at tryModuleLoad (internal/modules/cjs/loader.js:560:12)",
      +      "at Function.Module._load (internal/modules/cjs/loader.js:552:3)",
      +      "at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)",
      +      "at executeUserCode (internal/bootstrap/node.js:332:15)"
      +    ]
      +  },
      +  "nativeStack": [
      +    {
      +      "pc": "0x000055b57f07a9ef",
      +      "symbol": "report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57f07cf03",
      +      "symbol": "report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57f1bccfd",
      +      "symbol": " [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57f1be048",
      +      "symbol": "v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]"
      +    },
      +    {
      +      "pc": "0x000055b57feeda0e",
      +      "symbol": " [./node]"
      +    }
      +  ],
      +  "javascriptHeap": {
      +    "totalMemory": 6127616,
      +    "totalCommittedMemory": 4357352,
      +    "usedMemory": 3221136,
      +    "availableMemory": 1521370240,
      +    "memoryLimit": 1526909922,
      +    "heapSpaces": {
      +      "read_only_space": {
      +        "memorySize": 524288,
      +        "committedMemory": 39208,
      +        "capacity": 515584,
      +        "used": 30504,
      +        "available": 485080
      +      },
      +      "new_space": {
      +        "memorySize": 2097152,
      +        "committedMemory": 2019312,
      +        "capacity": 1031168,
      +        "used": 985496,
      +        "available": 45672
      +      },
      +      "old_space": {
      +        "memorySize": 2273280,
      +        "committedMemory": 1769008,
      +        "capacity": 1974640,
      +        "used": 1725488,
      +        "available": 249152
      +      },
      +      "code_space": {
      +        "memorySize": 696320,
      +        "committedMemory": 184896,
      +        "capacity": 152128,
      +        "used": 152128,
      +        "available": 0
      +      },
      +      "map_space": {
      +        "memorySize": 536576,
      +        "committedMemory": 344928,
      +        "capacity": 327520,
      +        "used": 327520,
      +        "available": 0
      +      },
      +      "large_object_space": {
      +        "memorySize": 0,
      +        "committedMemory": 0,
      +        "capacity": 1520590336,
      +        "used": 0,
      +        "available": 1520590336
      +      },
      +      "new_large_object_space": {
      +        "memorySize": 0,
      +        "committedMemory": 0,
      +        "capacity": 0,
      +        "used": 0,
      +        "available": 0
      +      }
      +    }
      +  },
      +  "resourceUsage": {
      +    "userCpuSeconds": 0.069595,
      +    "kernelCpuSeconds": 0.019163,
      +    "cpuConsumptionPercent": 0.000000,
      +    "maxRss": 18079744,
      +    "pageFaults": {
      +      "IORequired": 0,
      +      "IONotRequired": 4610
      +    },
      +    "fsActivity": {
      +      "reads": 0,
      +      "writes": 0
      +    }
      +  },
      +  "uvthreadResourceUsage": {
      +    "userCpuSeconds": 0.068457,
      +    "kernelCpuSeconds": 0.019127,
      +    "cpuConsumptionPercent": 0.000000,
      +    "fsActivity": {
      +      "reads": 0,
      +      "writes": 0
      +    }
      +  },
      +  "libuv": [
      +    {
      +      "type": "async",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x0000000102910900",
      +      "details": ""
      +    },
      +    {
      +      "type": "timer",
      +      "is_active": false,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfeab0",
      +      "repeat": 0,
      +      "firesInMsFromNow": 94403548320796,
      +      "expired": true
      +    },
      +    {
      +      "type": "check",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfeb48"
      +    },
      +    {
      +      "type": "idle",
      +      "is_active": false,
      +      "is_referenced": true,
      +      "address": "0x00007fff5fbfebc0"
      +    },
      +    {
      +      "type": "prepare",
      +      "is_active": false,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfec38"
      +    },
      +    {
      +      "type": "check",
      +      "is_active": false,
      +      "is_referenced": false,
      +      "address": "0x00007fff5fbfecb0"
      +    },
      +    {
      +      "type": "async",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x000000010188f2e0"
      +    },
      +    {
      +      "type": "tty",
      +      "is_active": false,
      +      "is_referenced": true,
      +      "address": "0x000055b581db0e18",
      +      "width": 204,
      +      "height": 55,
      +      "fd": 17,
      +      "writeQueueSize": 0,
      +      "readable": true,
      +      "writable": true
      +    },
      +    {
      +      "type": "signal",
      +      "is_active": true,
      +      "is_referenced": false,
      +      "address": "0x000055b581d80010",
      +      "signum": 28,
      +      "signal": "SIGWINCH"
      +    },
      +    {
      +      "type": "tty",
      +      "is_active": true,
      +      "is_referenced": true,
      +      "address": "0x000055b581df59f8",
      +      "width": 204,
      +      "height": 55,
      +      "fd": 19,
      +      "writeQueueSize": 0,
      +      "readable": true,
      +      "writable": true
      +    },
      +    {
      +      "type": "loop",
      +      "is_active": true,
      +      "address": "0x000055fc7b2cb180"
      +    }
      +  ],
      +  "workers": [],
      +  "environmentVariables": {
      +    "REMOTEHOST": "REMOVED",
      +    "MANPATH": "/opt/rh/devtoolset-3/root/usr/share/man:",
      +    "XDG_SESSION_ID": "66126",
      +    "HOSTNAME": "test_machine",
      +    "HOST": "test_machine",
      +    "TERM": "xterm-256color",
      +    "SHELL": "/bin/csh",
      +    "SSH_CLIENT": "REMOVED",
      +    "PERL5LIB": "/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl",
      +    "OLDPWD": "/home/nodeuser/project/node/src",
      +    "JAVACONFDIRS": "/opt/rh/devtoolset-3/root/etc/java:/etc/java",
      +    "SSH_TTY": "/dev/pts/0",
      +    "PCP_DIR": "/opt/rh/devtoolset-3/root",
      +    "GROUP": "normaluser",
      +    "USER": "nodeuser",
      +    "LD_LIBRARY_PATH": "/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib",
      +    "HOSTTYPE": "x86_64-linux",
      +    "XDG_CONFIG_DIRS": "/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg",
      +    "MAIL": "/var/spool/mail/nodeuser",
      +    "PATH": "/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin",
      +    "PWD": "/home/nodeuser/project/node",
      +    "LANG": "en_US.UTF-8",
      +    "PS1": "\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] >  ",
      +    "SHLVL": "2",
      +    "HOME": "/home/nodeuser",
      +    "OSTYPE": "linux",
      +    "VENDOR": "unknown",
      +    "PYTHONPATH": "/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages",
      +    "MACHTYPE": "x86_64",
      +    "LOGNAME": "nodeuser",
      +    "XDG_DATA_DIRS": "/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share",
      +    "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
      +    "INFOPATH": "/opt/rh/devtoolset-3/root/usr/share/info",
      +    "XDG_RUNTIME_DIR": "/run/user/50141",
      +    "_": "./node"
      +  },
      +  "userLimits": {
      +    "core_file_size_blocks": {
      +      "soft": "",
      +      "hard": "unlimited"
      +    },
      +    "data_seg_size_kbytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "file_size_blocks": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "max_locked_memory_bytes": {
      +      "soft": "unlimited",
      +      "hard": 65536
      +    },
      +    "max_memory_size_kbytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "open_files": {
      +      "soft": "unlimited",
      +      "hard": 4096
      +    },
      +    "stack_size_bytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "cpu_time_seconds": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    },
      +    "max_user_processes": {
      +      "soft": "unlimited",
      +      "hard": 4127290
      +    },
      +    "virtual_memory_kbytes": {
      +      "soft": "unlimited",
      +      "hard": "unlimited"
      +    }
      +  },
      +  "sharedObjects": [
      +    "/lib64/libdl.so.2",
      +    "/lib64/librt.so.1",
      +    "/lib64/libstdc++.so.6",
      +    "/lib64/libm.so.6",
      +    "/lib64/libgcc_s.so.1",
      +    "/lib64/libpthread.so.0",
      +    "/lib64/libc.so.6",
      +    "/lib64/ld-linux-x86-64.so.2"
      +  ]
      +}
      +

      Usage#

      +
      node --report-uncaught-exception --report-on-signal \
      +--report-on-fatalerror app.js
      +
        +
      • +

        --report-uncaught-exception Enables report to be generated on +un-caught exceptions. Useful when inspecting JavaScript stack in conjunction +with native stack and other runtime environment data.

        +
      • +
      • +

        --report-on-signal Enables report to be generated upon receiving +the specified (or predefined) signal to the running Node.js process. (See below +on how to modify the signal that triggers the report.) Default signal is SIGUSR2. +Useful when a report needs to be triggered from another program. +Application monitors may leverage this feature to collect report at regular +intervals and plot rich set of internal runtime data to their views.

        +
      • +
      +

      Signal based report generation is not supported in Windows.

      +

      Under normal circumstances, there is no need to modify the report triggering +signal. However, if SIGUSR2 is already used for other purposes, then this +flag helps to change the signal for report generation and preserve the original +meaning of SIGUSR2 for the said purposes.

      +
        +
      • +

        --report-on-fatalerror Enables the report to be triggered on +fatal errors (internal errors within the Node.js runtime, such as out of memory) +that leads to termination of the application. Useful to inspect various +diagnostic data elements such as heap, stack, event loop state, resource +consumption etc. to reason about the fatal error.

        +
      • +
      • +

        --report-compact Write reports in a compact format, single-line JSON, more +easily consumable by log processing systems than the default multi-line format +designed for human consumption.

        +
      • +
      • +

        --report-directory Location at which the report will be +generated.

        +
      • +
      • +

        --report-filename Name of the file to which the report will be +written.

        +
      • +
      • +

        --report-signal Sets or resets the signal for report generation +(not supported on Windows). Default signal is SIGUSR2.

        +
      • +
      +

      A report can also be triggered via an API call from a JavaScript application:

      +
      process.report.writeReport();
      +

      This function takes an optional additional argument filename, which is +the name of a file into which the report is written.

      +
      process.report.writeReport('./foo.json');
      +

      This function takes an optional additional argument err which is an Error +object that will be used as the context for the JavaScript stack printed in the +report. When using report to handle errors in a callback or an exception +handler, this allows the report to include the location of the original error as +well as where it was handled.

      +
      try {
      +  process.chdir('/non-existent-path');
      +} catch (err) {
      +  process.report.writeReport(err);
      +}
      +// Any other code
      +

      If both filename and error object are passed to writeReport() the +error object must be the second parameter.

      +
      try {
      +  process.chdir('/non-existent-path');
      +} catch (err) {
      +  process.report.writeReport(filename, err);
      +}
      +// Any other code
      +

      The content of the diagnostic report can be returned as a JavaScript Object +via an API call from a JavaScript application:

      +
      const report = process.report.getReport();
      +console.log(typeof report === 'object'); // true
      +
      +// Similar to process.report.writeReport() output
      +console.log(JSON.stringify(report, null, 2));
      +

      This function takes an optional additional argument err, which is an Error +object that will be used as the context for the JavaScript stack printed in the +report.

      +
      const report = process.report.getReport(new Error('custom error'));
      +console.log(typeof report === 'object'); // true
      +

      The API versions are useful when inspecting the runtime state from within +the application, in expectation of self-adjusting the resource consumption, +load balancing, monitoring etc.

      +

      The content of the report consists of a header section containing the event +type, date, time, PID and Node.js version, sections containing JavaScript and +native stack traces, a section containing V8 heap information, a section +containing libuv handle information and an OS platform information section +showing CPU and memory usage and system limits. An example report can be +triggered using the Node.js REPL:

      +
      $ node
      +> process.report.writeReport();
      +Writing Node.js report to file: report.20181126.091102.8480.0.001.json
      +Node.js report completed
      +>
      +

      When a report is written, start and end messages are issued to stderr +and the filename of the report is returned to the caller. The default filename +includes the date, time, PID and a sequence number. The sequence number helps +in associating the report dump with the runtime state if generated multiple +times for the same Node.js process.

      +

      Configuration#

      +

      Additional runtime configuration of report generation is available via +the following properties of process.report:

      +

      reportOnFatalError triggers diagnostic reporting on fatal errors when true. +Defaults to false.

      +

      reportOnSignal triggers diagnostic reporting on signal when true. This is +not supported on Windows. Defaults to false.

      +

      reportOnUncaughtException triggers diagnostic reporting on uncaught exception +when true. Defaults to false.

      +

      signal specifies the POSIX signal identifier that will be used +to intercept external triggers for report generation. Defaults to +'SIGUSR2'.

      +

      filename specifies the name of the output file in the file system. +Special meaning is attached to stdout and stderr. Usage of these +will result in report being written to the associated standard streams. +In cases where standard streams are used, the value in directory is ignored. +URLs are not supported. Defaults to a composite filename that contains +timestamp, PID and sequence number.

      +

      directory specifies the filesystem directory where the report will be written. +URLs are not supported. Defaults to the current working directory of the +Node.js process.

      +
      // Trigger report only on uncaught exceptions.
      +process.report.reportOnFatalError = false;
      +process.report.reportOnSignal = false;
      +process.report.reportOnUncaughtException = true;
      +
      +// Trigger report for both internal errors as well as external signal.
      +process.report.reportOnFatalError = true;
      +process.report.reportOnSignal = true;
      +process.report.reportOnUncaughtException = false;
      +
      +// Change the default signal to 'SIGQUIT' and enable it.
      +process.report.reportOnFatalError = false;
      +process.report.reportOnUncaughtException = false;
      +process.report.reportOnSignal = true;
      +process.report.signal = 'SIGQUIT';
      +

      Configuration on module initialization is also available via +environment variables:

      +
      NODE_OPTIONS="--report-uncaught-exception \
      +  --report-on-fatalerror --report-on-signal \
      +  --report-signal=SIGUSR2  --report-filename=./report.json \
      +  --report-directory=/home/nodeuser"
      +

      Specific API documentation can be found under +process API documentation section.

      +

      Interaction with workers#

      + +

      Worker threads can create reports in the same way that the main thread +does.

      +

      Reports will include information on any Workers that are children of the current +thread as part of the workers section, with each Worker generating a report +in the standard report format.

      +

      The thread which is generating the report will wait for the reports from Worker +threads to finish. However, the latency for this will usually be low, as both +running JavaScript and the event loop are interrupted to generate the report.

      + +
      +
      +
      + + diff --git a/doc/api/report.json b/doc/api/report.json new file mode 100644 index 0000000000000000000000000000000000000000..51a3497657bd972550c01605574280d85cc35275 --- /dev/null +++ b/doc/api/report.json @@ -0,0 +1,50 @@ +{ + "type": "module", + "source": "doc/api/report.md", + "introduced_in": "v11.8.0", + "stability": 2, + "stabilityText": "Stable", + "miscs": [ + { + "textRaw": "Diagnostic report", + "name": "report", + "introduced_in": "v11.8.0", + "type": "misc", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Delivers a JSON-formatted diagnostic summary, written to a file.

      \n

      The report is intended for development, test and production use, to capture\nand preserve information for problem determination. It includes JavaScript\nand native stack traces, heap statistics, platform information, resource\nusage etc. With the report option enabled, diagnostic reports can be triggered\non unhandled exceptions, fatal errors and user signals, in addition to\ntriggering programmatically through API calls.

      \n

      A complete example report that was generated on an uncaught exception\nis provided below for reference.

      \n
      {\n  \"header\": {\n    \"reportVersion\": 1,\n    \"event\": \"exception\",\n    \"trigger\": \"Exception\",\n    \"filename\": \"report.20181221.005011.8974.0.001.json\",\n    \"dumpEventTime\": \"2018-12-21T00:50:11Z\",\n    \"dumpEventTimeStamp\": \"1545371411331\",\n    \"processId\": 8974,\n    \"cwd\": \"/home/nodeuser/project/node\",\n    \"commandLine\": [\n      \"/home/nodeuser/project/node/out/Release/node\",\n      \"--report-uncaught-exception\",\n      \"/home/nodeuser/project/node/test/report/test-exception.js\",\n      \"child\"\n    ],\n    \"nodejsVersion\": \"v12.0.0-pre\",\n    \"glibcVersionRuntime\": \"2.17\",\n    \"glibcVersionCompiler\": \"2.17\",\n    \"wordSize\": \"64 bit\",\n    \"arch\": \"x64\",\n    \"platform\": \"linux\",\n    \"componentVersions\": {\n      \"node\": \"12.0.0-pre\",\n      \"v8\": \"7.1.302.28-node.5\",\n      \"uv\": \"1.24.1\",\n      \"zlib\": \"1.2.11\",\n      \"ares\": \"1.15.0\",\n      \"modules\": \"68\",\n      \"nghttp2\": \"1.34.0\",\n      \"napi\": \"3\",\n      \"llhttp\": \"1.0.1\",\n      \"http_parser\": \"2.8.0\",\n      \"openssl\": \"1.1.0j\"\n    },\n    \"release\": {\n      \"name\": \"node\"\n    },\n    \"osName\": \"Linux\",\n    \"osRelease\": \"3.10.0-862.el7.x86_64\",\n    \"osVersion\": \"#1 SMP Wed Mar 21 18:14:51 EDT 2018\",\n    \"osMachine\": \"x86_64\",\n    \"cpus\": [\n      {\n        \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n        \"speed\": 2700,\n        \"user\": 88902660,\n        \"nice\": 0,\n        \"sys\": 50902570,\n        \"idle\": 241732220,\n        \"irq\": 0\n      },\n      {\n        \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n        \"speed\": 2700,\n        \"user\": 88902660,\n        \"nice\": 0,\n        \"sys\": 50902570,\n        \"idle\": 241732220,\n        \"irq\": 0\n      }\n    ],\n    \"networkInterfaces\": [\n      {\n        \"name\": \"en0\",\n        \"internal\": false,\n        \"mac\": \"13:10:de:ad:be:ef\",\n        \"address\": \"10.0.0.37\",\n        \"netmask\": \"255.255.255.0\",\n        \"family\": \"IPv4\"\n      }\n    ],\n    \"host\": \"test_machine\"\n  },\n  \"javascriptStack\": {\n    \"message\": \"Error: *** test-exception.js: throwing uncaught Error\",\n    \"stack\": [\n      \"at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)\",\n      \"at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)\",\n      \"at Module._compile (internal/modules/cjs/loader.js:718:30)\",\n      \"at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)\",\n      \"at Module.load (internal/modules/cjs/loader.js:617:32)\",\n      \"at tryModuleLoad (internal/modules/cjs/loader.js:560:12)\",\n      \"at Function.Module._load (internal/modules/cjs/loader.js:552:3)\",\n      \"at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)\",\n      \"at executeUserCode (internal/bootstrap/node.js:332:15)\"\n    ]\n  },\n  \"nativeStack\": [\n    {\n      \"pc\": \"0x000055b57f07a9ef\",\n      \"symbol\": \"report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57f07cf03\",\n      \"symbol\": \"report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57f1bccfd\",\n      \"symbol\": \" [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57f1be048\",\n      \"symbol\": \"v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]\"\n    },\n    {\n      \"pc\": \"0x000055b57feeda0e\",\n      \"symbol\": \" [./node]\"\n    }\n  ],\n  \"javascriptHeap\": {\n    \"totalMemory\": 6127616,\n    \"totalCommittedMemory\": 4357352,\n    \"usedMemory\": 3221136,\n    \"availableMemory\": 1521370240,\n    \"memoryLimit\": 1526909922,\n    \"heapSpaces\": {\n      \"read_only_space\": {\n        \"memorySize\": 524288,\n        \"committedMemory\": 39208,\n        \"capacity\": 515584,\n        \"used\": 30504,\n        \"available\": 485080\n      },\n      \"new_space\": {\n        \"memorySize\": 2097152,\n        \"committedMemory\": 2019312,\n        \"capacity\": 1031168,\n        \"used\": 985496,\n        \"available\": 45672\n      },\n      \"old_space\": {\n        \"memorySize\": 2273280,\n        \"committedMemory\": 1769008,\n        \"capacity\": 1974640,\n        \"used\": 1725488,\n        \"available\": 249152\n      },\n      \"code_space\": {\n        \"memorySize\": 696320,\n        \"committedMemory\": 184896,\n        \"capacity\": 152128,\n        \"used\": 152128,\n        \"available\": 0\n      },\n      \"map_space\": {\n        \"memorySize\": 536576,\n        \"committedMemory\": 344928,\n        \"capacity\": 327520,\n        \"used\": 327520,\n        \"available\": 0\n      },\n      \"large_object_space\": {\n        \"memorySize\": 0,\n        \"committedMemory\": 0,\n        \"capacity\": 1520590336,\n        \"used\": 0,\n        \"available\": 1520590336\n      },\n      \"new_large_object_space\": {\n        \"memorySize\": 0,\n        \"committedMemory\": 0,\n        \"capacity\": 0,\n        \"used\": 0,\n        \"available\": 0\n      }\n    }\n  },\n  \"resourceUsage\": {\n    \"userCpuSeconds\": 0.069595,\n    \"kernelCpuSeconds\": 0.019163,\n    \"cpuConsumptionPercent\": 0.000000,\n    \"maxRss\": 18079744,\n    \"pageFaults\": {\n      \"IORequired\": 0,\n      \"IONotRequired\": 4610\n    },\n    \"fsActivity\": {\n      \"reads\": 0,\n      \"writes\": 0\n    }\n  },\n  \"uvthreadResourceUsage\": {\n    \"userCpuSeconds\": 0.068457,\n    \"kernelCpuSeconds\": 0.019127,\n    \"cpuConsumptionPercent\": 0.000000,\n    \"fsActivity\": {\n      \"reads\": 0,\n      \"writes\": 0\n    }\n  },\n  \"libuv\": [\n    {\n      \"type\": \"async\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x0000000102910900\",\n      \"details\": \"\"\n    },\n    {\n      \"type\": \"timer\",\n      \"is_active\": false,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfeab0\",\n      \"repeat\": 0,\n      \"firesInMsFromNow\": 94403548320796,\n      \"expired\": true\n    },\n    {\n      \"type\": \"check\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfeb48\"\n    },\n    {\n      \"type\": \"idle\",\n      \"is_active\": false,\n      \"is_referenced\": true,\n      \"address\": \"0x00007fff5fbfebc0\"\n    },\n    {\n      \"type\": \"prepare\",\n      \"is_active\": false,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfec38\"\n    },\n    {\n      \"type\": \"check\",\n      \"is_active\": false,\n      \"is_referenced\": false,\n      \"address\": \"0x00007fff5fbfecb0\"\n    },\n    {\n      \"type\": \"async\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x000000010188f2e0\"\n    },\n    {\n      \"type\": \"tty\",\n      \"is_active\": false,\n      \"is_referenced\": true,\n      \"address\": \"0x000055b581db0e18\",\n      \"width\": 204,\n      \"height\": 55,\n      \"fd\": 17,\n      \"writeQueueSize\": 0,\n      \"readable\": true,\n      \"writable\": true\n    },\n    {\n      \"type\": \"signal\",\n      \"is_active\": true,\n      \"is_referenced\": false,\n      \"address\": \"0x000055b581d80010\",\n      \"signum\": 28,\n      \"signal\": \"SIGWINCH\"\n    },\n    {\n      \"type\": \"tty\",\n      \"is_active\": true,\n      \"is_referenced\": true,\n      \"address\": \"0x000055b581df59f8\",\n      \"width\": 204,\n      \"height\": 55,\n      \"fd\": 19,\n      \"writeQueueSize\": 0,\n      \"readable\": true,\n      \"writable\": true\n    },\n    {\n      \"type\": \"loop\",\n      \"is_active\": true,\n      \"address\": \"0x000055fc7b2cb180\"\n    }\n  ],\n  \"workers\": [],\n  \"environmentVariables\": {\n    \"REMOTEHOST\": \"REMOVED\",\n    \"MANPATH\": \"/opt/rh/devtoolset-3/root/usr/share/man:\",\n    \"XDG_SESSION_ID\": \"66126\",\n    \"HOSTNAME\": \"test_machine\",\n    \"HOST\": \"test_machine\",\n    \"TERM\": \"xterm-256color\",\n    \"SHELL\": \"/bin/csh\",\n    \"SSH_CLIENT\": \"REMOVED\",\n    \"PERL5LIB\": \"/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl\",\n    \"OLDPWD\": \"/home/nodeuser/project/node/src\",\n    \"JAVACONFDIRS\": \"/opt/rh/devtoolset-3/root/etc/java:/etc/java\",\n    \"SSH_TTY\": \"/dev/pts/0\",\n    \"PCP_DIR\": \"/opt/rh/devtoolset-3/root\",\n    \"GROUP\": \"normaluser\",\n    \"USER\": \"nodeuser\",\n    \"LD_LIBRARY_PATH\": \"/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib\",\n    \"HOSTTYPE\": \"x86_64-linux\",\n    \"XDG_CONFIG_DIRS\": \"/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg\",\n    \"MAIL\": \"/var/spool/mail/nodeuser\",\n    \"PATH\": \"/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin\",\n    \"PWD\": \"/home/nodeuser/project/node\",\n    \"LANG\": \"en_US.UTF-8\",\n    \"PS1\": \"\\\\u@\\\\h : \\\\[\\\\e[31m\\\\]\\\\w\\\\[\\\\e[m\\\\] >  \",\n    \"SHLVL\": \"2\",\n    \"HOME\": \"/home/nodeuser\",\n    \"OSTYPE\": \"linux\",\n    \"VENDOR\": \"unknown\",\n    \"PYTHONPATH\": \"/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages\",\n    \"MACHTYPE\": \"x86_64\",\n    \"LOGNAME\": \"nodeuser\",\n    \"XDG_DATA_DIRS\": \"/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share\",\n    \"LESSOPEN\": \"||/usr/bin/lesspipe.sh %s\",\n    \"INFOPATH\": \"/opt/rh/devtoolset-3/root/usr/share/info\",\n    \"XDG_RUNTIME_DIR\": \"/run/user/50141\",\n    \"_\": \"./node\"\n  },\n  \"userLimits\": {\n    \"core_file_size_blocks\": {\n      \"soft\": \"\",\n      \"hard\": \"unlimited\"\n    },\n    \"data_seg_size_kbytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"file_size_blocks\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"max_locked_memory_bytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": 65536\n    },\n    \"max_memory_size_kbytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"open_files\": {\n      \"soft\": \"unlimited\",\n      \"hard\": 4096\n    },\n    \"stack_size_bytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"cpu_time_seconds\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    },\n    \"max_user_processes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": 4127290\n    },\n    \"virtual_memory_kbytes\": {\n      \"soft\": \"unlimited\",\n      \"hard\": \"unlimited\"\n    }\n  },\n  \"sharedObjects\": [\n    \"/lib64/libdl.so.2\",\n    \"/lib64/librt.so.1\",\n    \"/lib64/libstdc++.so.6\",\n    \"/lib64/libm.so.6\",\n    \"/lib64/libgcc_s.so.1\",\n    \"/lib64/libpthread.so.0\",\n    \"/lib64/libc.so.6\",\n    \"/lib64/ld-linux-x86-64.so.2\"\n  ]\n}\n
      ", + "miscs": [ + { + "textRaw": "Usage", + "name": "usage", + "desc": "
      node --report-uncaught-exception --report-on-signal \\\n--report-on-fatalerror app.js\n
      \n
        \n
      • \n

        --report-uncaught-exception Enables report to be generated on\nun-caught exceptions. Useful when inspecting JavaScript stack in conjunction\nwith native stack and other runtime environment data.

        \n
      • \n
      • \n

        --report-on-signal Enables report to be generated upon receiving\nthe specified (or predefined) signal to the running Node.js process. (See below\non how to modify the signal that triggers the report.) Default signal is SIGUSR2.\nUseful when a report needs to be triggered from another program.\nApplication monitors may leverage this feature to collect report at regular\nintervals and plot rich set of internal runtime data to their views.

        \n
      • \n
      \n

      Signal based report generation is not supported in Windows.

      \n

      Under normal circumstances, there is no need to modify the report triggering\nsignal. However, if SIGUSR2 is already used for other purposes, then this\nflag helps to change the signal for report generation and preserve the original\nmeaning of SIGUSR2 for the said purposes.

      \n
        \n
      • \n

        --report-on-fatalerror Enables the report to be triggered on\nfatal errors (internal errors within the Node.js runtime, such as out of memory)\nthat leads to termination of the application. Useful to inspect various\ndiagnostic data elements such as heap, stack, event loop state, resource\nconsumption etc. to reason about the fatal error.

        \n
      • \n
      • \n

        --report-compact Write reports in a compact format, single-line JSON, more\neasily consumable by log processing systems than the default multi-line format\ndesigned for human consumption.

        \n
      • \n
      • \n

        --report-directory Location at which the report will be\ngenerated.

        \n
      • \n
      • \n

        --report-filename Name of the file to which the report will be\nwritten.

        \n
      • \n
      • \n

        --report-signal Sets or resets the signal for report generation\n(not supported on Windows). Default signal is SIGUSR2.

        \n
      • \n
      \n

      A report can also be triggered via an API call from a JavaScript application:

      \n
      process.report.writeReport();\n
      \n

      This function takes an optional additional argument filename, which is\nthe name of a file into which the report is written.

      \n
      process.report.writeReport('./foo.json');\n
      \n

      This function takes an optional additional argument err which is an Error\nobject that will be used as the context for the JavaScript stack printed in the\nreport. When using report to handle errors in a callback or an exception\nhandler, this allows the report to include the location of the original error as\nwell as where it was handled.

      \n
      try {\n  process.chdir('/non-existent-path');\n} catch (err) {\n  process.report.writeReport(err);\n}\n// Any other code\n
      \n

      If both filename and error object are passed to writeReport() the\nerror object must be the second parameter.

      \n
      try {\n  process.chdir('/non-existent-path');\n} catch (err) {\n  process.report.writeReport(filename, err);\n}\n// Any other code\n
      \n

      The content of the diagnostic report can be returned as a JavaScript Object\nvia an API call from a JavaScript application:

      \n
      const report = process.report.getReport();\nconsole.log(typeof report === 'object'); // true\n\n// Similar to process.report.writeReport() output\nconsole.log(JSON.stringify(report, null, 2));\n
      \n

      This function takes an optional additional argument err, which is an Error\nobject that will be used as the context for the JavaScript stack printed in the\nreport.

      \n
      const report = process.report.getReport(new Error('custom error'));\nconsole.log(typeof report === 'object'); // true\n
      \n

      The API versions are useful when inspecting the runtime state from within\nthe application, in expectation of self-adjusting the resource consumption,\nload balancing, monitoring etc.

      \n

      The content of the report consists of a header section containing the event\ntype, date, time, PID and Node.js version, sections containing JavaScript and\nnative stack traces, a section containing V8 heap information, a section\ncontaining libuv handle information and an OS platform information section\nshowing CPU and memory usage and system limits. An example report can be\ntriggered using the Node.js REPL:

      \n
      $ node\n> process.report.writeReport();\nWriting Node.js report to file: report.20181126.091102.8480.0.001.json\nNode.js report completed\n>\n
      \n

      When a report is written, start and end messages are issued to stderr\nand the filename of the report is returned to the caller. The default filename\nincludes the date, time, PID and a sequence number. The sequence number helps\nin associating the report dump with the runtime state if generated multiple\ntimes for the same Node.js process.

      ", + "type": "misc", + "displayName": "Usage" + }, + { + "textRaw": "Configuration", + "name": "configuration", + "desc": "

      Additional runtime configuration of report generation is available via\nthe following properties of process.report:

      \n

      reportOnFatalError triggers diagnostic reporting on fatal errors when true.\nDefaults to false.

      \n

      reportOnSignal triggers diagnostic reporting on signal when true. This is\nnot supported on Windows. Defaults to false.

      \n

      reportOnUncaughtException triggers diagnostic reporting on uncaught exception\nwhen true. Defaults to false.

      \n

      signal specifies the POSIX signal identifier that will be used\nto intercept external triggers for report generation. Defaults to\n'SIGUSR2'.

      \n

      filename specifies the name of the output file in the file system.\nSpecial meaning is attached to stdout and stderr. Usage of these\nwill result in report being written to the associated standard streams.\nIn cases where standard streams are used, the value in directory is ignored.\nURLs are not supported. Defaults to a composite filename that contains\ntimestamp, PID and sequence number.

      \n

      directory specifies the filesystem directory where the report will be written.\nURLs are not supported. Defaults to the current working directory of the\nNode.js process.

      \n
      // Trigger report only on uncaught exceptions.\nprocess.report.reportOnFatalError = false;\nprocess.report.reportOnSignal = false;\nprocess.report.reportOnUncaughtException = true;\n\n// Trigger report for both internal errors as well as external signal.\nprocess.report.reportOnFatalError = true;\nprocess.report.reportOnSignal = true;\nprocess.report.reportOnUncaughtException = false;\n\n// Change the default signal to 'SIGQUIT' and enable it.\nprocess.report.reportOnFatalError = false;\nprocess.report.reportOnUncaughtException = false;\nprocess.report.reportOnSignal = true;\nprocess.report.signal = 'SIGQUIT';\n
      \n

      Configuration on module initialization is also available via\nenvironment variables:

      \n
      NODE_OPTIONS=\"--report-uncaught-exception \\\n  --report-on-fatalerror --report-on-signal \\\n  --report-signal=SIGUSR2  --report-filename=./report.json \\\n  --report-directory=/home/nodeuser\"\n
      \n

      Specific API documentation can be found under\nprocess API documentation section.

      ", + "type": "misc", + "displayName": "Configuration" + }, + { + "textRaw": "Interaction with workers", + "name": "interaction_with_workers", + "meta": { + "changes": [ + { + "version": "v12.16.2", + "pr-url": "https://github.com/nodejs/node/pull/31386", + "description": "Workers are now included in the report." + } + ] + }, + "desc": "

      Worker threads can create reports in the same way that the main thread\ndoes.

      \n

      Reports will include information on any Workers that are children of the current\nthread as part of the workers section, with each Worker generating a report\nin the standard report format.

      \n

      The thread which is generating the report will wait for the reports from Worker\nthreads to finish. However, the latency for this will usually be low, as both\nrunning JavaScript and the event loop are interrupted to generate the report.

      ", + "type": "misc", + "displayName": "Interaction with workers" + } + ] + } + ] +} \ No newline at end of file diff --git a/doc/api/stream.html b/doc/api/stream.html new file mode 100644 index 0000000000000000000000000000000000000000..fb8d33a0ed8ee12769c51537f1c2858edecf3638 --- /dev/null +++ b/doc/api/stream.html @@ -0,0 +1,2729 @@ + + + + + + + Stream | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Stream[src]#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/stream.js

      +

      A stream is an abstract interface for working with streaming data in Node.js. +The stream module provides an API for implementing the stream interface.

      +

      There are many stream objects provided by Node.js. For instance, a +request to an HTTP server and process.stdout +are both stream instances.

      +

      Streams can be readable, writable, or both. All streams are instances of +EventEmitter.

      +

      To access the stream module:

      +
      const stream = require('stream');
      +

      The stream module is useful for creating new types of stream instances. It is +usually not necessary to use the stream module to consume streams.

      +

      Organization of this document#

      +

      This document contains two primary sections and a third section for notes. The +first section explains how to use existing streams within an application. The +second section explains how to create new types of streams.

      +

      Types of streams#

      +

      There are four fundamental stream types within Node.js:

      + +

      Additionally, this module includes the utility functions +stream.pipeline(), stream.finished() and +stream.Readable.from().

      +

      Object mode#

      +

      All streams created by Node.js APIs operate exclusively on strings and Buffer +(or Uint8Array) objects. It is possible, however, for stream implementations +to work with other types of JavaScript values (with the exception of null, +which serves a special purpose within streams). Such streams are considered to +operate in "object mode".

      +

      Stream instances are switched into object mode using the objectMode option +when the stream is created. Attempting to switch an existing stream into +object mode is not safe.

      +

      Buffering#

      + +

      Both Writable and Readable streams will store data in an internal +buffer that can be retrieved using writable.writableBuffer or +readable.readableBuffer, respectively.

      +

      The amount of data potentially buffered depends on the highWaterMark option +passed into the stream's constructor. For normal streams, the highWaterMark +option specifies a total number of bytes. For streams operating +in object mode, the highWaterMark specifies a total number of objects.

      +

      Data is buffered in Readable streams when the implementation calls +stream.push(chunk). If the consumer of the Stream does not +call stream.read(), the data will sit in the internal +queue until it is consumed.

      +

      Once the total size of the internal read buffer reaches the threshold specified +by highWaterMark, the stream will temporarily stop reading data from the +underlying resource until the data currently buffered can be consumed (that is, +the stream will stop calling the internal readable._read() method that is +used to fill the read buffer).

      +

      Data is buffered in Writable streams when the +writable.write(chunk) method is called repeatedly. While the +total size of the internal write buffer is below the threshold set by +highWaterMark, calls to writable.write() will return true. Once +the size of the internal buffer reaches or exceeds the highWaterMark, false +will be returned.

      +

      A key goal of the stream API, particularly the stream.pipe() method, +is to limit the buffering of data to acceptable levels such that sources and +destinations of differing speeds will not overwhelm the available memory.

      +

      The highWaterMark option is a threshold, not a limit: it dictates the amount +of data that a stream buffers before it stops asking for more data. It does not +enforce a strict memory limitation in general. Specific stream implementations +may choose to enforce stricter limits but doing so is optional.

      +

      Because Duplex and Transform streams are both Readable and +Writable, each maintains two separate internal buffers used for reading and +writing, allowing each side to operate independently of the other while +maintaining an appropriate and efficient flow of data. For example, +net.Socket instances are Duplex streams whose Readable side allows +consumption of data received from the socket and whose Writable side allows +writing data to the socket. Because data may be written to the socket at a +faster or slower rate than data is received, each side should +operate (and buffer) independently of the other.

      +

      API for stream consumers#

      + +

      Almost all Node.js applications, no matter how simple, use streams in some +manner. The following is an example of using streams in a Node.js application +that implements an HTTP server:

      +
      const http = require('http');
      +
      +const server = http.createServer((req, res) => {
      +  // `req` is an http.IncomingMessage, which is a readable stream.
      +  // `res` is an http.ServerResponse, which is a writable stream.
      +
      +  let body = '';
      +  // Get the data as utf8 strings.
      +  // If an encoding is not set, Buffer objects will be received.
      +  req.setEncoding('utf8');
      +
      +  // Readable streams emit 'data' events once a listener is added.
      +  req.on('data', (chunk) => {
      +    body += chunk;
      +  });
      +
      +  // The 'end' event indicates that the entire body has been received.
      +  req.on('end', () => {
      +    try {
      +      const data = JSON.parse(body);
      +      // Write back something interesting to the user:
      +      res.write(typeof data);
      +      res.end();
      +    } catch (er) {
      +      // uh oh! bad json!
      +      res.statusCode = 400;
      +      return res.end(`error: ${er.message}`);
      +    }
      +  });
      +});
      +
      +server.listen(1337);
      +
      +// $ curl localhost:1337 -d "{}"
      +// object
      +// $ curl localhost:1337 -d "\"foo\""
      +// string
      +// $ curl localhost:1337 -d "not json"
      +// error: Unexpected token o in JSON at position 1
      +

      Writable streams (such as res in the example) expose methods such as +write() and end() that are used to write data onto the stream.

      +

      Readable streams use the EventEmitter API for notifying application +code when data is available to be read off the stream. That available data can +be read from the stream in multiple ways.

      +

      Both Writable and Readable streams use the EventEmitter API in +various ways to communicate the current state of the stream.

      +

      Duplex and Transform streams are both Writable and +Readable.

      +

      Applications that are either writing data to or consuming data from a stream +are not required to implement the stream interfaces directly and will generally +have no reason to call require('stream').

      +

      Developers wishing to implement new types of streams should refer to the +section API for stream implementers.

      +

      Writable streams#

      +

      Writable streams are an abstraction for a destination to which data is +written.

      +

      Examples of Writable streams include:

      + +

      Some of these examples are actually Duplex streams that implement the +Writable interface.

      +

      All Writable streams implement the interface defined by the +stream.Writable class.

      +

      While specific instances of Writable streams may differ in various ways, +all Writable streams follow the same fundamental usage pattern as illustrated +in the example below:

      +
      const myStream = getWritableStreamSomehow();
      +myStream.write('some data');
      +myStream.write('some more data');
      +myStream.end('done writing data');
      +

      Class: stream.Writable#

      + + +
      Event: 'close'#
      + +

      The 'close' event is emitted when the stream and any of its underlying +resources (a file descriptor, for example) have been closed. The event indicates +that no more events will be emitted, and no further computation will occur.

      +

      A Writable stream will always emit the 'close' event if it is +created with the emitClose option.

      +
      Event: 'drain'#
      + +

      If a call to stream.write(chunk) returns false, the +'drain' event will be emitted when it is appropriate to resume writing data +to the stream.

      +
      // Write the data to the supplied writable stream one million times.
      +// Be attentive to back-pressure.
      +function writeOneMillionTimes(writer, data, encoding, callback) {
      +  let i = 1000000;
      +  write();
      +  function write() {
      +    let ok = true;
      +    do {
      +      i--;
      +      if (i === 0) {
      +        // Last time!
      +        writer.write(data, encoding, callback);
      +      } else {
      +        // See if we should continue, or wait.
      +        // Don't pass the callback, because we're not done yet.
      +        ok = writer.write(data, encoding);
      +      }
      +    } while (i > 0 && ok);
      +    if (i > 0) {
      +      // Had to stop early!
      +      // Write some more once it drains.
      +      writer.once('drain', write);
      +    }
      +  }
      +}
      +
      Event: 'error'#
      + + +

      The 'error' event is emitted if an error occurred while writing or piping +data. The listener callback is passed a single Error argument when called.

      +

      The stream is not closed when the 'error' event is emitted unless the +autoDestroy option was set to true when creating the +stream.

      +
      Event: 'finish'#
      + +

      The 'finish' event is emitted after the stream.end() method +has been called, and all data has been flushed to the underlying system.

      +
      const writer = getWritableStreamSomehow();
      +for (let i = 0; i < 100; i++) {
      +  writer.write(`hello, #${i}!\n`);
      +}
      +writer.on('finish', () => {
      +  console.log('All writes are now complete.');
      +});
      +writer.end('This is the end\n');
      +
      Event: 'pipe'#
      + + +

      The 'pipe' event is emitted when the stream.pipe() method is called on +a readable stream, adding this writable to its set of destinations.

      +
      const writer = getWritableStreamSomehow();
      +const reader = getReadableStreamSomehow();
      +writer.on('pipe', (src) => {
      +  console.log('Something is piping into the writer.');
      +  assert.equal(src, reader);
      +});
      +reader.pipe(writer);
      +
      Event: 'unpipe'#
      + + +

      The 'unpipe' event is emitted when the stream.unpipe() method is called +on a Readable stream, removing this Writable from its set of +destinations.

      +

      This is also emitted in case this Writable stream emits an error when a +Readable stream pipes into it.

      +
      const writer = getWritableStreamSomehow();
      +const reader = getReadableStreamSomehow();
      +writer.on('unpipe', (src) => {
      +  console.log('Something has stopped piping into the writer.');
      +  assert.equal(src, reader);
      +});
      +reader.pipe(writer);
      +reader.unpipe(writer);
      +
      writable.cork()#
      + +

      The writable.cork() method forces all written data to be buffered in memory. +The buffered data will be flushed when either the stream.uncork() or +stream.end() methods are called.

      +

      The primary intent of writable.cork() is to accommodate a situation in which +several small chunks are written to the stream in rapid succession. Instead of +immediately forwarding them to the underlying destination, writable.cork() +buffers all the chunks until writable.uncork() is called, which will pass them +all to writable._writev(), if present. This prevents a head-of-line blocking +situation where data is being buffered while waiting for the first small chunk +to be processed. However, use of writable.cork() without implementing +writable._writev() may have an adverse effect on throughput.

      +

      See also: writable.uncork(), writable._writev().

      +
      writable.destroy([error])#
      + +
        +
      • error <Error> Optional, an error to emit with 'error' event.
      • +
      • Returns: <this>
      • +
      +

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' +event (unless emitClose is set to false). After this call, the writable +stream has ended and subsequent calls to write() or end() will result in +an ERR_STREAM_DESTROYED error. +This is a destructive and immediate way to destroy a stream. Previous calls to +write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. +Use end() instead of destroy if data should flush before close, or wait for +the 'drain' event before destroying the stream. +Implementors should not override this method, +but instead implement writable._destroy().

      +
      writable.destroyed#
      + + +

      Is true after writable.destroy() has been called.

      +
      writable.end([chunk[, encoding]][, callback])#
      + +
        +
      • chunk <string> | <Buffer> | <Uint8Array> | <any> Optional data to write. For streams +not operating in object mode, chunk must be a string, Buffer or +Uint8Array. For object mode streams, chunk may be any JavaScript value +other than null.
      • +
      • encoding <string> The encoding if chunk is a string
      • +
      • callback <Function> Optional callback for when the stream is finished
      • +
      • Returns: <this>
      • +
      +

      Calling the writable.end() method signals that no more data will be written +to the Writable. The optional chunk and encoding arguments allow one +final additional chunk of data to be written immediately before closing the +stream. If provided, the optional callback function is attached as a listener +for the 'finish' event.

      +

      Calling the stream.write() method after calling +stream.end() will raise an error.

      +
      // Write 'hello, ' and then end with 'world!'.
      +const fs = require('fs');
      +const file = fs.createWriteStream('example.txt');
      +file.write('hello, ');
      +file.end('world!');
      +// Writing more now is not allowed!
      +
      writable.setDefaultEncoding(encoding)#
      + + +

      The writable.setDefaultEncoding() method sets the default encoding for a +Writable stream.

      +
      writable.uncork()#
      + +

      The writable.uncork() method flushes all data buffered since +stream.cork() was called.

      +

      When using writable.cork() and writable.uncork() to manage the buffering +of writes to a stream, it is recommended that calls to writable.uncork() be +deferred using process.nextTick(). Doing so allows batching of all +writable.write() calls that occur within a given Node.js event loop phase.

      +
      stream.cork();
      +stream.write('some ');
      +stream.write('data ');
      +process.nextTick(() => stream.uncork());
      +

      If the writable.cork() method is called multiple times on a stream, the +same number of calls to writable.uncork() must be called to flush the buffered +data.

      +
      stream.cork();
      +stream.write('some ');
      +stream.cork();
      +stream.write('data ');
      +process.nextTick(() => {
      +  stream.uncork();
      +  // The data will not be flushed until uncork() is called a second time.
      +  stream.uncork();
      +});
      +

      See also: writable.cork().

      +
      writable.writable#
      + + +

      Is true if it is safe to call writable.write().

      +
      writable.writableEnded#
      + + +

      Is true after writable.end() has been called. This property +does not indicate whether the data has been flushed, for this use +writable.writableFinished instead.

      +
      writable.writableCorked#
      + + +

      Number of times writable.uncork() needs to be +called in order to fully uncork the stream.

      +
      writable.writableFinished#
      + + +

      Is set to true immediately before the 'finish' event is emitted.

      +
      writable.writableHighWaterMark#
      + + +

      Return the value of highWaterMark passed when constructing this +Writable.

      +
      writable.writableLength#
      + + +

      This property contains the number of bytes (or objects) in the queue +ready to be written. The value provides introspection data regarding +the status of the highWaterMark.

      +
      writable.writableObjectMode#
      + + +

      Getter for the property objectMode of a given Writable stream.

      +
      writable.write(chunk[, encoding][, callback])#
      + +
        +
      • chunk <string> | <Buffer> | <Uint8Array> | <any> Optional data to write. For streams +not operating in object mode, chunk must be a string, Buffer or +Uint8Array. For object mode streams, chunk may be any JavaScript value +other than null.
      • +
      • encoding <string> The encoding, if chunk is a string. Default: 'utf8'
      • +
      • callback <Function> Callback for when this chunk of data is flushed
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to +wait for the 'drain' event to be emitted before continuing to write +additional data; otherwise true.
      • +
      +

      The writable.write() method writes some data to the stream, and calls the +supplied callback once the data has been fully handled. If an error +occurs, the callback may or may not be called with the error as its +first argument. To reliably detect write errors, add a listener for the +'error' event.

      +

      The return value is true if the internal buffer is less than the +highWaterMark configured when the stream was created after admitting chunk. +If false is returned, further attempts to write data to the stream should +stop until the 'drain' event is emitted.

      +

      While a stream is not draining, calls to write() will buffer chunk, and +return false. Once all currently buffered chunks are drained (accepted for +delivery by the operating system), the 'drain' event will be emitted. +It is recommended that once write() returns false, no more chunks be written +until the 'drain' event is emitted. While calling write() on a stream that +is not draining is allowed, Node.js will buffer all written chunks until +maximum memory usage occurs, at which point it will abort unconditionally. +Even before it aborts, high memory usage will cause poor garbage collector +performance and high RSS (which is not typically released back to the system, +even after the memory is no longer required). Since TCP sockets may never +drain if the remote peer does not read the data, writing a socket that is +not draining may lead to a remotely exploitable vulnerability.

      +

      Writing data while the stream is not draining is particularly +problematic for a Transform, because the Transform streams are paused +by default until they are piped or a 'data' or 'readable' event handler +is added.

      +

      If the data to be written can be generated or fetched on demand, it is +recommended to encapsulate the logic into a Readable and use +stream.pipe(). However, if calling write() is preferred, it is +possible to respect backpressure and avoid memory issues using the +'drain' event:

      +
      function write(data, cb) {
      +  if (!stream.write(data)) {
      +    stream.once('drain', cb);
      +  } else {
      +    process.nextTick(cb);
      +  }
      +}
      +
      +// Wait for cb to be called before doing any other write.
      +write('hello', () => {
      +  console.log('Write completed, do more writes now.');
      +});
      +

      A Writable stream in object mode will always ignore the encoding argument.

      +

      Readable streams#

      +

      Readable streams are an abstraction for a source from which data is +consumed.

      +

      Examples of Readable streams include:

      + +

      All Readable streams implement the interface defined by the +stream.Readable class.

      +

      Two reading modes#

      +

      Readable streams effectively operate in one of two modes: flowing and +paused. These modes are separate from object mode. +A Readable stream can be in object mode or not, regardless of whether +it is in flowing mode or paused mode.

      +
        +
      • +

        In flowing mode, data is read from the underlying system automatically +and provided to an application as quickly as possible using events via the +EventEmitter interface.

        +
      • +
      • +

        In paused mode, the stream.read() method must be called +explicitly to read chunks of data from the stream.

        +
      • +
      +

      All Readable streams begin in paused mode but can be switched to flowing +mode in one of the following ways:

      + +

      The Readable can switch back to paused mode using one of the following:

      +
        +
      • If there are no pipe destinations, by calling the +stream.pause() method.
      • +
      • If there are pipe destinations, by removing all pipe destinations. +Multiple pipe destinations may be removed by calling the +stream.unpipe() method.
      • +
      +

      The important concept to remember is that a Readable will not generate data +until a mechanism for either consuming or ignoring that data is provided. If +the consuming mechanism is disabled or taken away, the Readable will attempt +to stop generating the data.

      +

      For backward compatibility reasons, removing 'data' event handlers will +not automatically pause the stream. Also, if there are piped destinations, +then calling stream.pause() will not guarantee that the +stream will remain paused once those destinations drain and ask for more data.

      +

      If a Readable is switched into flowing mode and there are no consumers +available to handle the data, that data will be lost. This can occur, for +instance, when the readable.resume() method is called without a listener +attached to the 'data' event, or when a 'data' event handler is removed +from the stream.

      +

      Adding a 'readable' event handler automatically makes the stream +stop flowing, and the data has to be consumed via +readable.read(). If the 'readable' event handler is +removed, then the stream will start flowing again if there is a +'data' event handler.

      +

      Three states#

      +

      The "two modes" of operation for a Readable stream are a simplified +abstraction for the more complicated internal state management that is happening +within the Readable stream implementation.

      +

      Specifically, at any given point in time, every Readable is in one of three +possible states:

      +
        +
      • readable.readableFlowing === null
      • +
      • readable.readableFlowing === false
      • +
      • readable.readableFlowing === true
      • +
      +

      When readable.readableFlowing is null, no mechanism for consuming the +stream's data is provided. Therefore, the stream will not generate data. +While in this state, attaching a listener for the 'data' event, calling the +readable.pipe() method, or calling the readable.resume() method will switch +readable.readableFlowing to true, causing the Readable to begin actively +emitting events as data is generated.

      +

      Calling readable.pause(), readable.unpipe(), or receiving backpressure +will cause the readable.readableFlowing to be set as false, +temporarily halting the flowing of events but not halting the generation of +data. While in this state, attaching a listener for the 'data' event +will not switch readable.readableFlowing to true.

      +
      const { PassThrough, Writable } = require('stream');
      +const pass = new PassThrough();
      +const writable = new Writable();
      +
      +pass.pipe(writable);
      +pass.unpipe(writable);
      +// readableFlowing is now false.
      +
      +pass.on('data', (chunk) => { console.log(chunk.toString()); });
      +pass.write('ok');  // Will not emit 'data'.
      +pass.resume();     // Must be called to make stream emit 'data'.
      +

      While readable.readableFlowing is false, data may be accumulating +within the stream's internal buffer.

      +

      Choose one API style#

      +

      The Readable stream API evolved across multiple Node.js versions and provides +multiple methods of consuming stream data. In general, developers should choose +one of the methods of consuming data and should never use multiple methods +to consume data from a single stream. Specifically, using a combination +of on('data'), on('readable'), pipe(), or async iterators could +lead to unintuitive behavior.

      +

      Use of the readable.pipe() method is recommended for most users as it has been +implemented to provide the easiest way of consuming stream data. Developers that +require more fine-grained control over the transfer and generation of data can +use the EventEmitter and readable.on('readable')/readable.read() +or the readable.pause()/readable.resume() APIs.

      +

      Class: stream.Readable#

      + + +
      Event: 'close'#
      + +

      The 'close' event is emitted when the stream and any of its underlying +resources (a file descriptor, for example) have been closed. The event indicates +that no more events will be emitted, and no further computation will occur.

      +

      A Readable stream will always emit the 'close' event if it is +created with the emitClose option.

      +
      Event: 'data'#
      + +
        +
      • chunk <Buffer> | <string> | <any> The chunk of data. For streams that are not +operating in object mode, the chunk will be either a string or Buffer. +For streams that are in object mode, the chunk can be any JavaScript value +other than null.
      • +
      +

      The 'data' event is emitted whenever the stream is relinquishing ownership of +a chunk of data to a consumer. This may occur whenever the stream is switched +in flowing mode by calling readable.pipe(), readable.resume(), or by +attaching a listener callback to the 'data' event. The 'data' event will +also be emitted whenever the readable.read() method is called and a chunk of +data is available to be returned.

      +

      Attaching a 'data' event listener to a stream that has not been explicitly +paused will switch the stream into flowing mode. Data will then be passed as +soon as it is available.

      +

      The listener callback will be passed the chunk of data as a string if a default +encoding has been specified for the stream using the +readable.setEncoding() method; otherwise the data will be passed as a +Buffer.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('data', (chunk) => {
      +  console.log(`Received ${chunk.length} bytes of data.`);
      +});
      +
      Event: 'end'#
      + +

      The 'end' event is emitted when there is no more data to be consumed from +the stream.

      +

      The 'end' event will not be emitted unless the data is completely +consumed. This can be accomplished by switching the stream into flowing mode, +or by calling stream.read() repeatedly until all data has been +consumed.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('data', (chunk) => {
      +  console.log(`Received ${chunk.length} bytes of data.`);
      +});
      +readable.on('end', () => {
      +  console.log('There will be no more data.');
      +});
      +
      Event: 'error'#
      + + +

      The 'error' event may be emitted by a Readable implementation at any time. +Typically, this may occur if the underlying stream is unable to generate data +due to an underlying internal failure, or when a stream implementation attempts +to push an invalid chunk of data.

      +

      The listener callback will be passed a single Error object.

      +
      Event: 'pause'#
      + +

      The 'pause' event is emitted when stream.pause() is called +and readableFlowing is not false.

      +
      Event: 'readable'#
      + +

      The 'readable' event is emitted when there is data available to be read from +the stream. In some cases, attaching a listener for the 'readable' event will +cause some amount of data to be read into an internal buffer.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('readable', function() {
      +  // There is some data to read now.
      +  let data;
      +
      +  while (data = this.read()) {
      +    console.log(data);
      +  }
      +});
      +

      The 'readable' event will also be emitted once the end of the stream data +has been reached but before the 'end' event is emitted.

      +

      Effectively, the 'readable' event indicates that the stream has new +information: either new data is available or the end of the stream has been +reached. In the former case, stream.read() will return the +available data. In the latter case, stream.read() will return +null. For instance, in the following example, foo.txt is an empty file:

      +
      const fs = require('fs');
      +const rr = fs.createReadStream('foo.txt');
      +rr.on('readable', () => {
      +  console.log(`readable: ${rr.read()}`);
      +});
      +rr.on('end', () => {
      +  console.log('end');
      +});
      +

      The output of running this script is:

      +
      $ node test.js
      +readable: null
      +end
      +

      In general, the readable.pipe() and 'data' event mechanisms are easier to +understand than the 'readable' event. However, handling 'readable' might +result in increased throughput.

      +

      If both 'readable' and 'data' are used at the same time, 'readable' +takes precedence in controlling the flow, i.e. 'data' will be emitted +only when stream.read() is called. The +readableFlowing property would become false. +If there are 'data' listeners when 'readable' is removed, the stream +will start flowing, i.e. 'data' events will be emitted without calling +.resume().

      +
      Event: 'resume'#
      + +

      The 'resume' event is emitted when stream.resume() is +called and readableFlowing is not true.

      +
      readable.destroy([error])#
      + +
        +
      • error <Error> Error which will be passed as payload in 'error' event
      • +
      • Returns: <this>
      • +
      +

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close' +event (unless emitClose is set to false). After this call, the readable +stream will release any internal resources and subsequent calls to push() +will be ignored. +Implementors should not override this method, but instead implement +readable._destroy().

      +
      readable.destroyed#
      + + +

      Is true after readable.destroy() has been called.

      +
      readable.isPaused()#
      + + +

      The readable.isPaused() method returns the current operating state of the +Readable. This is used primarily by the mechanism that underlies the +readable.pipe() method. In most typical cases, there will be no reason to +use this method directly.

      +
      const readable = new stream.Readable();
      +
      +readable.isPaused(); // === false
      +readable.pause();
      +readable.isPaused(); // === true
      +readable.resume();
      +readable.isPaused(); // === false
      +
      readable.pause()#
      + + +

      The readable.pause() method will cause a stream in flowing mode to stop +emitting 'data' events, switching out of flowing mode. Any data that +becomes available will remain in the internal buffer.

      +
      const readable = getReadableStreamSomehow();
      +readable.on('data', (chunk) => {
      +  console.log(`Received ${chunk.length} bytes of data.`);
      +  readable.pause();
      +  console.log('There will be no additional data for 1 second.');
      +  setTimeout(() => {
      +    console.log('Now data will start flowing again.');
      +    readable.resume();
      +  }, 1000);
      +});
      +

      The readable.pause() method has no effect if there is a 'readable' +event listener.

      +
      readable.pipe(destination[, options])#
      + + +

      The readable.pipe() method attaches a Writable stream to the readable, +causing it to switch automatically into flowing mode and push all of its data +to the attached Writable. The flow of data will be automatically managed +so that the destination Writable stream is not overwhelmed by a faster +Readable stream.

      +

      The following example pipes all of the data from the readable into a file +named file.txt:

      +
      const fs = require('fs');
      +const readable = getReadableStreamSomehow();
      +const writable = fs.createWriteStream('file.txt');
      +// All the data from readable goes into 'file.txt'.
      +readable.pipe(writable);
      +

      It is possible to attach multiple Writable streams to a single Readable +stream.

      +

      The readable.pipe() method returns a reference to the destination stream +making it possible to set up chains of piped streams:

      +
      const fs = require('fs');
      +const r = fs.createReadStream('file.txt');
      +const z = zlib.createGzip();
      +const w = fs.createWriteStream('file.txt.gz');
      +r.pipe(z).pipe(w);
      +

      By default, stream.end() is called on the destination Writable +stream when the source Readable stream emits 'end', so that the +destination is no longer writable. To disable this default behavior, the end +option can be passed as false, causing the destination stream to remain open:

      +
      reader.pipe(writer, { end: false });
      +reader.on('end', () => {
      +  writer.end('Goodbye\n');
      +});
      +

      One important caveat is that if the Readable stream emits an error during +processing, the Writable destination is not closed automatically. If an +error occurs, it will be necessary to manually close each stream in order +to prevent memory leaks.

      +

      The process.stderr and process.stdout Writable streams are never +closed until the Node.js process exits, regardless of the specified options.

      +
      readable.read([size])#
      + + +

      The readable.read() method pulls some data out of the internal buffer and +returns it. If no data available to be read, null is returned. By default, +the data will be returned as a Buffer object unless an encoding has been +specified using the readable.setEncoding() method or the stream is operating +in object mode.

      +

      The optional size argument specifies a specific number of bytes to read. If +size bytes are not available to be read, null will be returned unless +the stream has ended, in which case all of the data remaining in the internal +buffer will be returned.

      +

      If the size argument is not specified, all of the data contained in the +internal buffer will be returned.

      +

      The size argument must be less than or equal to 1 GB.

      +

      The readable.read() method should only be called on Readable streams +operating in paused mode. In flowing mode, readable.read() is called +automatically until the internal buffer is fully drained.

      +
      const readable = getReadableStreamSomehow();
      +
      +// 'readable' may be triggered multiple times as data is buffered in
      +readable.on('readable', () => {
      +  let chunk;
      +  console.log('Stream is readable (new data received in buffer)');
      +  // Use a loop to make sure we read all currently available data
      +  while (null !== (chunk = readable.read())) {
      +    console.log(`Read ${chunk.length} bytes of data...`);
      +  }
      +});
      +
      +// 'end' will be triggered once when there is no more data available
      +readable.on('end', () => {
      +  console.log('Reached end of stream.');
      +});
      +

      Each call to readable.read() returns a chunk of data, or null. The chunks +are not concatenated. A while loop is necessary to consume all data +currently in the buffer. When reading a large file .read() may return null, +having consumed all buffered content so far, but there is still more data to +come not yet buffered. In this case a new 'readable' event will be emitted +when there is more data in the buffer. Finally the 'end' event will be +emitted when there is no more data to come.

      +

      Therefore to read a file's whole contents from a readable, it is necessary +to collect chunks across multiple 'readable' events:

      +
      const chunks = [];
      +
      +readable.on('readable', () => {
      +  let chunk;
      +  while (null !== (chunk = readable.read())) {
      +    chunks.push(chunk);
      +  }
      +});
      +
      +readable.on('end', () => {
      +  const content = chunks.join('');
      +});
      +

      A Readable stream in object mode will always return a single item from +a call to readable.read(size), regardless of the value of the +size argument.

      +

      If the readable.read() method returns a chunk of data, a 'data' event will +also be emitted.

      +

      Calling stream.read([size]) after the 'end' event has +been emitted will return null. No runtime error will be raised.

      +
      readable.readable#
      + + +

      Is true if it is safe to call readable.read().

      +
      readable.readableEncoding#
      + + +

      Getter for the property encoding of a given Readable stream. The encoding +property can be set using the readable.setEncoding() method.

      +
      readable.readableEnded#
      + + +

      Becomes true when 'end' event is emitted.

      +
      readable.readableFlowing#
      + + +

      This property reflects the current state of a Readable stream as described +in the Three states section.

      +
      readable.readableHighWaterMark#
      + + +

      Returns the value of highWaterMark passed when constructing this +Readable.

      +
      readable.readableLength#
      + + +

      This property contains the number of bytes (or objects) in the queue +ready to be read. The value provides introspection data regarding +the status of the highWaterMark.

      +
      readable.readableObjectMode#
      + + +

      Getter for the property objectMode of a given Readable stream.

      +
      readable.resume()#
      + + +

      The readable.resume() method causes an explicitly paused Readable stream to +resume emitting 'data' events, switching the stream into flowing mode.

      +

      The readable.resume() method can be used to fully consume the data from a +stream without actually processing any of that data:

      +
      getReadableStreamSomehow()
      +  .resume()
      +  .on('end', () => {
      +    console.log('Reached the end, but did not read anything.');
      +  });
      +

      The readable.resume() method has no effect if there is a 'readable' +event listener.

      +
      readable.setEncoding(encoding)#
      + + +

      The readable.setEncoding() method sets the character encoding for +data read from the Readable stream.

      +

      By default, no encoding is assigned and stream data will be returned as +Buffer objects. Setting an encoding causes the stream data +to be returned as strings of the specified encoding rather than as Buffer +objects. For instance, calling readable.setEncoding('utf8') will cause the +output data to be interpreted as UTF-8 data, and passed as strings. Calling +readable.setEncoding('hex') will cause the data to be encoded in hexadecimal +string format.

      +

      The Readable stream will properly handle multi-byte characters delivered +through the stream that would otherwise become improperly decoded if simply +pulled from the stream as Buffer objects.

      +
      const readable = getReadableStreamSomehow();
      +readable.setEncoding('utf8');
      +readable.on('data', (chunk) => {
      +  assert.equal(typeof chunk, 'string');
      +  console.log('Got %d characters of string data:', chunk.length);
      +});
      +
      readable.unpipe([destination])#
      + + +

      The readable.unpipe() method detaches a Writable stream previously attached +using the stream.pipe() method.

      +

      If the destination is not specified, then all pipes are detached.

      +

      If the destination is specified, but no pipe is set up for it, then +the method does nothing.

      +
      const fs = require('fs');
      +const readable = getReadableStreamSomehow();
      +const writable = fs.createWriteStream('file.txt');
      +// All the data from readable goes into 'file.txt',
      +// but only for the first second.
      +readable.pipe(writable);
      +setTimeout(() => {
      +  console.log('Stop writing to file.txt.');
      +  readable.unpipe(writable);
      +  console.log('Manually close the file stream.');
      +  writable.end();
      +}, 1000);
      +
      readable.unshift(chunk[, encoding])#
      + +
        +
      • chunk <Buffer> | <Uint8Array> | <string> | <null> | <any> Chunk of data to unshift onto the +read queue. For streams not operating in object mode, chunk must be a +string, Buffer, Uint8Array or null. For object mode streams, chunk +may be any JavaScript value.
      • +
      • encoding <string> Encoding of string chunks. Must be a valid +Buffer encoding, such as 'utf8' or 'ascii'.
      • +
      +

      Passing chunk as null signals the end of the stream (EOF) and behaves the +same as readable.push(null), after which no more data can be written. The EOF +signal is put at the end of the buffer and any buffered data will still be +flushed.

      +

      The readable.unshift() method pushes a chunk of data back into the internal +buffer. This is useful in certain situations where a stream is being consumed by +code that needs to "un-consume" some amount of data that it has optimistically +pulled out of the source, so that the data can be passed on to some other party.

      +

      The stream.unshift(chunk) method cannot be called after the 'end' event +has been emitted or a runtime error will be thrown.

      +

      Developers using stream.unshift() often should consider switching to +use of a Transform stream instead. See the API for stream implementers +section for more information.

      +
      // Pull off a header delimited by \n\n.
      +// Use unshift() if we get too much.
      +// Call the callback with (error, header, stream).
      +const { StringDecoder } = require('string_decoder');
      +function parseHeader(stream, callback) {
      +  stream.on('error', callback);
      +  stream.on('readable', onReadable);
      +  const decoder = new StringDecoder('utf8');
      +  let header = '';
      +  function onReadable() {
      +    let chunk;
      +    while (null !== (chunk = stream.read())) {
      +      const str = decoder.write(chunk);
      +      if (str.match(/\n\n/)) {
      +        // Found the header boundary.
      +        const split = str.split(/\n\n/);
      +        header += split.shift();
      +        const remaining = split.join('\n\n');
      +        const buf = Buffer.from(remaining, 'utf8');
      +        stream.removeListener('error', callback);
      +        // Remove the 'readable' listener before unshifting.
      +        stream.removeListener('readable', onReadable);
      +        if (buf.length)
      +          stream.unshift(buf);
      +        // Now the body of the message can be read from the stream.
      +        callback(null, header, stream);
      +      } else {
      +        // Still reading the header.
      +        header += str;
      +      }
      +    }
      +  }
      +}
      +

      Unlike stream.push(chunk), stream.unshift(chunk) will not +end the reading process by resetting the internal reading state of the stream. +This can cause unexpected results if readable.unshift() is called during a +read (i.e. from within a stream._read() implementation on a +custom stream). Following the call to readable.unshift() with an immediate +stream.push('') will reset the reading state appropriately, +however it is best to simply avoid calling readable.unshift() while in the +process of performing a read.

      +
      readable.wrap(stream)#
      + + +

      Prior to Node.js 0.10, streams did not implement the entire stream module API +as it is currently defined. (See Compatibility for more information.)

      +

      When using an older Node.js library that emits 'data' events and has a +stream.pause() method that is advisory only, the +readable.wrap() method can be used to create a Readable stream that uses +the old stream as its data source.

      +

      It will rarely be necessary to use readable.wrap() but the method has been +provided as a convenience for interacting with older Node.js applications and +libraries.

      +
      const { OldReader } = require('./old-api-module.js');
      +const { Readable } = require('stream');
      +const oreader = new OldReader();
      +const myReader = new Readable().wrap(oreader);
      +
      +myReader.on('readable', () => {
      +  myReader.read(); // etc.
      +});
      +
      readable[Symbol.asyncIterator]()#
      + + +
      const fs = require('fs');
      +
      +async function print(readable) {
      +  readable.setEncoding('utf8');
      +  let data = '';
      +  for await (const chunk of readable) {
      +    data += chunk;
      +  }
      +  console.log(data);
      +}
      +
      +print(fs.createReadStream('file')).catch(console.error);
      +

      If the loop terminates with a break or a throw, the stream will be +destroyed. In other terms, iterating over a stream will consume the stream +fully. The stream will be read in chunks of size equal to the highWaterMark +option. In the code example above, data will be in a single chunk if the file +has less then 64KB of data because no highWaterMark option is provided to +fs.createReadStream().

      +

      Duplex and transform streams#

      +

      Class: stream.Duplex#

      + + +

      Duplex streams are streams that implement both the Readable and +Writable interfaces.

      +

      Examples of Duplex streams include:

      + +

      Class: stream.Transform#

      + + +

      Transform streams are Duplex streams where the output is in some way +related to the input. Like all Duplex streams, Transform streams +implement both the Readable and Writable interfaces.

      +

      Examples of Transform streams include:

      + +
      transform.destroy([error])#
      + + +

      Destroy the stream, and optionally emit an 'error' event. After this call, the +transform stream would release any internal resources. +Implementors should not override this method, but instead implement +readable._destroy(). +The default implementation of _destroy() for Transform also emit 'close' +unless emitClose is set in false.

      +

      stream.finished(stream[, options], callback)#

      + +
        +
      • stream <Stream> A readable and/or writable stream.
      • +
      • options <Object> +
          +
        • error <boolean> If set to false, then a call to emit('error', err) is +not treated as finished. Default: true.
        • +
        • readable <boolean> When set to false, the callback will be called when +the stream ends even though the stream might still be readable. +Default: true.
        • +
        • writable <boolean> When set to false, the callback will be called when +the stream ends even though the stream might still be writable. +Default: true.
        • +
        +
      • +
      • callback <Function> A callback function that takes an optional error +argument.
      • +
      • Returns: <Function> A cleanup function which removes all registered +listeners.
      • +
      +

      A function to get notified when a stream is no longer readable, writable +or has experienced an error or a premature close event.

      +
      const { finished } = require('stream');
      +
      +const rs = fs.createReadStream('archive.tar');
      +
      +finished(rs, (err) => {
      +  if (err) {
      +    console.error('Stream failed.', err);
      +  } else {
      +    console.log('Stream is done reading.');
      +  }
      +});
      +
      +rs.resume(); // Drain the stream.
      +

      Especially useful in error handling scenarios where a stream is destroyed +prematurely (like an aborted HTTP request), and will not emit 'end' +or 'finish'.

      +

      The finished API is promisify-able as well;

      +
      const finished = util.promisify(stream.finished);
      +
      +const rs = fs.createReadStream('archive.tar');
      +
      +async function run() {
      +  await finished(rs);
      +  console.log('Stream is done reading.');
      +}
      +
      +run().catch(console.error);
      +rs.resume(); // Drain the stream.
      +

      stream.finished() leaves dangling event listeners (in particular +'error', 'end', 'finish' and 'close') after callback has been +invoked. The reason for this is so that unexpected 'error' events (due to +incorrect stream implementations) do not cause unexpected crashes. +If this is unwanted behavior then the returned cleanup function needs to be +invoked in the callback:

      +
      const cleanup = finished(rs, (err) => {
      +  cleanup();
      +  // ...
      +});
      +

      stream.pipeline(...streams, callback)#

      + +
        +
      • ...streams <Stream> Two or more streams to pipe between.
      • +
      • callback <Function> Called when the pipeline is fully done. + +
      • +
      +

      A module method to pipe between streams forwarding errors and properly cleaning +up and provide a callback when the pipeline is complete.

      +
      const { pipeline } = require('stream');
      +const fs = require('fs');
      +const zlib = require('zlib');
      +
      +// Use the pipeline API to easily pipe a series of streams
      +// together and get notified when the pipeline is fully done.
      +
      +// A pipeline to gzip a potentially huge tar file efficiently:
      +
      +pipeline(
      +  fs.createReadStream('archive.tar'),
      +  zlib.createGzip(),
      +  fs.createWriteStream('archive.tar.gz'),
      +  (err) => {
      +    if (err) {
      +      console.error('Pipeline failed.', err);
      +    } else {
      +      console.log('Pipeline succeeded.');
      +    }
      +  }
      +);
      +

      The pipeline API is promisify-able as well:

      +
      const pipeline = util.promisify(stream.pipeline);
      +
      +async function run() {
      +  await pipeline(
      +    fs.createReadStream('archive.tar'),
      +    zlib.createGzip(),
      +    fs.createWriteStream('archive.tar.gz')
      +  );
      +  console.log('Pipeline succeeded.');
      +}
      +
      +run().catch(console.error);
      +

      stream.pipeline() will call stream.destroy(err) on all streams except:

      +
        +
      • Readable streams which have emitted 'end' or 'close'.
      • +
      • Writable streams which have emitted 'finish' or 'close'.
      • +
      +

      stream.pipeline() leaves dangling event listeners on the streams +after the callback has been invoked. In the case of reuse of streams after +failure, this can cause event listener leaks and swallowed errors.

      +

      stream.Readable.from(iterable, [options])#

      + +
        +
      • iterable <Iterable> Object implementing the Symbol.asyncIterator or +Symbol.iterator iterable protocol. Emits an 'error' event if a null +value is passed.
      • +
      • options <Object> Options provided to new stream.Readable([options]). +By default, Readable.from() will set options.objectMode to true, unless +this is explicitly opted out by setting options.objectMode to false.
      • +
      • Returns: <stream.Readable>
      • +
      +

      A utility method for creating readable streams out of iterators.

      +
      const { Readable } = require('stream');
      +
      +async function * generate() {
      +  yield 'hello';
      +  yield 'streams';
      +}
      +
      +const readable = Readable.from(generate());
      +
      +readable.on('data', (chunk) => {
      +  console.log(chunk);
      +});
      +

      Calling Readable.from(string) or Readable.from(buffer) will not have +the strings or buffers be iterated to match the other streams semantics +for performance reasons.

      +

      API for stream implementers#

      + +

      The stream module API has been designed to make it possible to easily +implement streams using JavaScript's prototypal inheritance model.

      +

      First, a stream developer would declare a new JavaScript class that extends one +of the four basic stream classes (stream.Writable, stream.Readable, +stream.Duplex, or stream.Transform), making sure they call the appropriate +parent class constructor:

      + +
      const { Writable } = require('stream');
      +
      +class MyWritable extends Writable {
      +  constructor({ highWaterMark, ...options }) {
      +    super({
      +      highWaterMark,
      +      autoDestroy: true,
      +      emitClose: true
      +    });
      +    // ...
      +  }
      +}
      +

      When extending streams, keep in mind what options the user +can and should provide before forwarding these to the base constructor. For +example, if the implementation makes assumptions in regard to the +autoDestroy and emitClose options, do not allow the +user to override these. Be explicit about what +options are forwarded instead of implicitly forwarding all options.

      +

      The new stream class must then implement one or more specific methods, depending +on the type of stream being created, as detailed in the chart below:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      Use-caseClassMethod(s) to implement
      Reading onlyReadable_read()
      Writing onlyWritable_write(), _writev(), _final()
      Reading and writingDuplex_read(), _write(), _writev(), _final()
      Operate on written data, then read the resultTransform_transform(), _flush(), _final()
      +

      The implementation code for a stream should never call the "public" methods +of a stream that are intended for use by consumers (as described in the +API for stream consumers section). Doing so may lead to adverse side effects +in application code consuming the stream.

      +

      Avoid overriding public methods such as write(), end(), cork(), +uncork(), read() and destroy(), or emitting internal events such +as 'error', 'data', 'end', 'finish' and 'close' through .emit(). +Doing so can break current and future stream invariants leading to behavior +and/or compatibility issues with other streams, stream utilities, and user +expectations.

      +

      Simplified construction#

      + +

      For many simple cases, it is possible to construct a stream without relying on +inheritance. This can be accomplished by directly creating instances of the +stream.Writable, stream.Readable, stream.Duplex or stream.Transform +objects and passing appropriate methods as constructor options.

      +
      const { Writable } = require('stream');
      +
      +const myWritable = new Writable({
      +  write(chunk, encoding, callback) {
      +    // ...
      +  }
      +});
      +

      Implementing a writable stream#

      +

      The stream.Writable class is extended to implement a Writable stream.

      +

      Custom Writable streams must call the new stream.Writable([options]) +constructor and implement the writable._write() and/or writable._writev() +method.

      +

      new stream.Writable([options])#

      + +
        +
      • options <Object> +
          +
        • highWaterMark <number> Buffer level when +stream.write() starts returning false. Default: +16384 (16KB), or 16 for objectMode streams.
        • +
        • decodeStrings <boolean> Whether to encode strings passed to +stream.write() to Buffers (with the encoding +specified in the stream.write() call) before passing +them to stream._write(). Other types of data are not +converted (i.e. Buffers are not decoded into strings). Setting to +false will prevent strings from being converted. Default: true.
        • +
        • defaultEncoding <string> The default encoding that is used when no +encoding is specified as an argument to stream.write(). +Default: 'utf8'.
        • +
        • objectMode <boolean> Whether or not the +stream.write(anyObj) is a valid operation. When set, +it becomes possible to write JavaScript values other than string, +Buffer or Uint8Array if supported by the stream implementation. +Default: false.
        • +
        • emitClose <boolean> Whether or not the stream should emit 'close' +after it has been destroyed. Default: true.
        • +
        • write <Function> Implementation for the +stream._write() method.
        • +
        • writev <Function> Implementation for the +stream._writev() method.
        • +
        • destroy <Function> Implementation for the +stream._destroy() method.
        • +
        • final <Function> Implementation for the +stream._final() method.
        • +
        • autoDestroy <boolean> Whether this stream should automatically call +.destroy() on itself after ending. Default: false.
        • +
        +
      • +
      + +
      const { Writable } = require('stream');
      +
      +class MyWritable extends Writable {
      +  constructor(options) {
      +    // Calls the stream.Writable() constructor.
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Writable } = require('stream');
      +const util = require('util');
      +
      +function MyWritable(options) {
      +  if (!(this instanceof MyWritable))
      +    return new MyWritable(options);
      +  Writable.call(this, options);
      +}
      +util.inherits(MyWritable, Writable);
      +

      Or, using the simplified constructor approach:

      +
      const { Writable } = require('stream');
      +
      +const myWritable = new Writable({
      +  write(chunk, encoding, callback) {
      +    // ...
      +  },
      +  writev(chunks, callback) {
      +    // ...
      +  }
      +});
      +

      writable._write(chunk, encoding, callback)#

      + +
        +
      • chunk <Buffer> | <string> | <any> The Buffer to be written, converted from the +string passed to stream.write(). If the stream's +decodeStrings option is false or the stream is operating in object mode, +the chunk will not be converted & will be whatever was passed to +stream.write().
      • +
      • encoding <string> If the chunk is a string, then encoding is the +character encoding of that string. If chunk is a Buffer, or if the +stream is operating in object mode, encoding may be ignored.
      • +
      • callback <Function> Call this function (optionally with an error +argument) when processing is complete for the supplied chunk.
      • +
      +

      All Writable stream implementations must provide a +writable._write() and/or +writable._writev() method to send data to the underlying +resource.

      +

      Transform streams provide their own implementation of the +writable._write().

      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Writable class +methods only.

      +

      The callback method must be called to signal either that the write completed +successfully or failed with an error. The first argument passed to the +callback must be the Error object if the call failed or null if the +write succeeded.

      +

      All calls to writable.write() that occur between the time writable._write() +is called and the callback is called will cause the written data to be +buffered. When the callback is invoked, the stream might emit a 'drain' +event. If a stream implementation is capable of processing multiple chunks of +data at once, the writable._writev() method should be implemented.

      +

      If the decodeStrings property is explicitly set to false in the constructor +options, then chunk will remain the same object that is passed to .write(), +and may be a string rather than a Buffer. This is to support implementations +that have an optimized handling for certain string data encodings. In that case, +the encoding argument will indicate the character encoding of the string. +Otherwise, the encoding argument can be safely ignored.

      +

      The writable._write() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      writable._writev(chunks, callback)#

      +
        +
      • chunks <Object[]> The chunks to be written. Each chunk has following +format: { chunk: ..., encoding: ... }.
      • +
      • callback <Function> A callback function (optionally with an error +argument) to be invoked when processing is complete for the supplied chunks.
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Writable class +methods only.

      +

      The writable._writev() method may be implemented in addition or alternatively +to writable._write() in stream implementations that are capable of processing +multiple chunks of data at once. If implemented and if there is buffered data +from previous writes, _writev() will be called instead of _write().

      +

      The writable._writev() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      writable._destroy(err, callback)#

      + +
        +
      • err <Error> A possible error.
      • +
      • callback <Function> A callback function that takes an optional error +argument.
      • +
      +

      The _destroy() method is called by writable.destroy(). +It can be overridden by child classes but it must not be called directly.

      +

      writable._final(callback)#

      + +
        +
      • callback <Function> Call this function (optionally with an error +argument) when finished writing any remaining data.
      • +
      +

      The _final() method must not be called directly. It may be implemented +by child classes, and if so, will be called by the internal Writable +class methods only.

      +

      This optional function will be called before the stream closes, delaying the +'finish' event until callback is called. This is useful to close resources +or write buffered data before a stream ends.

      +

      Errors while writing#

      +

      Errors occurring during the processing of the writable._write(), +writable._writev() and writable._final() methods must be propagated +by invoking the callback and passing the error as the first argument. +Throwing an Error from within these methods or manually emitting an 'error' +event results in undefined behavior.

      +

      If a Readable stream pipes into a Writable stream when Writable emits an +error, the Readable stream will be unpiped.

      +
      const { Writable } = require('stream');
      +
      +const myWritable = new Writable({
      +  write(chunk, encoding, callback) {
      +    if (chunk.toString().indexOf('a') >= 0) {
      +      callback(new Error('chunk is invalid'));
      +    } else {
      +      callback();
      +    }
      +  }
      +});
      +

      An example writable stream#

      +

      The following illustrates a rather simplistic (and somewhat pointless) custom +Writable stream implementation. While this specific Writable stream instance +is not of any real particular usefulness, the example illustrates each of the +required elements of a custom Writable stream instance:

      +
      const { Writable } = require('stream');
      +
      +class MyWritable extends Writable {
      +  _write(chunk, encoding, callback) {
      +    if (chunk.toString().indexOf('a') >= 0) {
      +      callback(new Error('chunk is invalid'));
      +    } else {
      +      callback();
      +    }
      +  }
      +}
      +

      Decoding buffers in a writable stream#

      +

      Decoding buffers is a common task, for instance, when using transformers whose +input is a string. This is not a trivial process when using multi-byte +characters encoding, such as UTF-8. The following example shows how to decode +multi-byte strings using StringDecoder and Writable.

      +
      const { Writable } = require('stream');
      +const { StringDecoder } = require('string_decoder');
      +
      +class StringWritable extends Writable {
      +  constructor(options) {
      +    super(options);
      +    this._decoder = new StringDecoder(options && options.defaultEncoding);
      +    this.data = '';
      +  }
      +  _write(chunk, encoding, callback) {
      +    if (encoding === 'buffer') {
      +      chunk = this._decoder.write(chunk);
      +    }
      +    this.data += chunk;
      +    callback();
      +  }
      +  _final(callback) {
      +    this.data += this._decoder.end();
      +    callback();
      +  }
      +}
      +
      +const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
      +const w = new StringWritable();
      +
      +w.write('currency: ');
      +w.write(euro[0]);
      +w.end(euro[1]);
      +
      +console.log(w.data); // currency: €
      +

      Implementing a readable stream#

      +

      The stream.Readable class is extended to implement a Readable stream.

      +

      Custom Readable streams must call the new stream.Readable([options]) +constructor and implement the readable._read() method.

      +

      new stream.Readable([options])#

      + +
        +
      • options <Object> +
          +
        • highWaterMark <number> The maximum number of bytes to store +in the internal buffer before ceasing to read from the underlying resource. +Default: 16384 (16KB), or 16 for objectMode streams.
        • +
        • encoding <string> If specified, then buffers will be decoded to +strings using the specified encoding. Default: null.
        • +
        • objectMode <boolean> Whether this stream should behave +as a stream of objects. Meaning that stream.read(n) returns +a single value instead of a Buffer of size n. Default: false.
        • +
        • emitClose <boolean> Whether or not the stream should emit 'close' +after it has been destroyed. Default: true.
        • +
        • read <Function> Implementation for the stream._read() +method.
        • +
        • destroy <Function> Implementation for the +stream._destroy() method.
        • +
        • autoDestroy <boolean> Whether this stream should automatically call +.destroy() on itself after ending. Default: false.
        • +
        +
      • +
      + +
      const { Readable } = require('stream');
      +
      +class MyReadable extends Readable {
      +  constructor(options) {
      +    // Calls the stream.Readable(options) constructor.
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Readable } = require('stream');
      +const util = require('util');
      +
      +function MyReadable(options) {
      +  if (!(this instanceof MyReadable))
      +    return new MyReadable(options);
      +  Readable.call(this, options);
      +}
      +util.inherits(MyReadable, Readable);
      +

      Or, using the simplified constructor approach:

      +
      const { Readable } = require('stream');
      +
      +const myReadable = new Readable({
      +  read(size) {
      +    // ...
      +  }
      +});
      +

      readable._read(size)#

      + +
        +
      • size <number> Number of bytes to read asynchronously
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Readable class +methods only.

      +

      All Readable stream implementations must provide an implementation of the +readable._read() method to fetch data from the underlying resource.

      +

      When readable._read() is called, if data is available from the resource, +the implementation should begin pushing that data into the read queue using the +this.push(dataChunk) method. _read() should continue reading +from the resource and pushing data until readable.push() returns false. Only +when _read() is called again after it has stopped should it resume pushing +additional data onto the queue.

      +

      Once the readable._read() method has been called, it will not be called +again until more data is pushed through the readable.push() +method. Empty data such as empty buffers and strings will not cause +readable._read() to be called.

      +

      The size argument is advisory. For implementations where a "read" is a +single operation that returns data can use the size argument to determine how +much data to fetch. Other implementations may ignore this argument and simply +provide data whenever it becomes available. There is no need to "wait" until +size bytes are available before calling stream.push(chunk).

      +

      The readable._read() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      readable._destroy(err, callback)#

      + +
        +
      • err <Error> A possible error.
      • +
      • callback <Function> A callback function that takes an optional error +argument.
      • +
      +

      The _destroy() method is called by readable.destroy(). +It can be overridden by child classes but it must not be called directly.

      +

      readable.push(chunk[, encoding])#

      + +
        +
      • chunk <Buffer> | <Uint8Array> | <string> | <null> | <any> Chunk of data to push into the +read queue. For streams not operating in object mode, chunk must be a +string, Buffer or Uint8Array. For object mode streams, chunk may be +any JavaScript value.
      • +
      • encoding <string> Encoding of string chunks. Must be a valid +Buffer encoding, such as 'utf8' or 'ascii'.
      • +
      • Returns: <boolean> true if additional chunks of data may continue to be +pushed; false otherwise.
      • +
      +

      When chunk is a Buffer, Uint8Array or string, the chunk of data will +be added to the internal queue for users of the stream to consume. +Passing chunk as null signals the end of the stream (EOF), after which no +more data can be written.

      +

      When the Readable is operating in paused mode, the data added with +readable.push() can be read out by calling the +readable.read() method when the 'readable' event is +emitted.

      +

      When the Readable is operating in flowing mode, the data added with +readable.push() will be delivered by emitting a 'data' event.

      +

      The readable.push() method is designed to be as flexible as possible. For +example, when wrapping a lower-level source that provides some form of +pause/resume mechanism, and a data callback, the low-level source can be wrapped +by the custom Readable instance:

      +
      // `_source` is an object with readStop() and readStart() methods,
      +// and an `ondata` member that gets called when it has data, and
      +// an `onend` member that gets called when the data is over.
      +
      +class SourceWrapper extends Readable {
      +  constructor(options) {
      +    super(options);
      +
      +    this._source = getLowLevelSourceObject();
      +
      +    // Every time there's data, push it into the internal buffer.
      +    this._source.ondata = (chunk) => {
      +      // If push() returns false, then stop reading from source.
      +      if (!this.push(chunk))
      +        this._source.readStop();
      +    };
      +
      +    // When the source ends, push the EOF-signaling `null` chunk.
      +    this._source.onend = () => {
      +      this.push(null);
      +    };
      +  }
      +  // _read() will be called when the stream wants to pull more data in.
      +  // The advisory size argument is ignored in this case.
      +  _read(size) {
      +    this._source.readStart();
      +  }
      +}
      +

      The readable.push() method is used to push the content +into the internal buffer. It can be driven by the readable._read() method.

      +

      For streams not operating in object mode, if the chunk parameter of +readable.push() is undefined, it will be treated as empty string or +buffer. See readable.push('') for more information.

      +

      Errors while reading#

      +

      Errors occurring during processing of the readable._read() must be +propagated through the readable.destroy(err) method. +Throwing an Error from within readable._read() or manually emitting an +'error' event results in undefined behavior.

      +
      const { Readable } = require('stream');
      +
      +const myReadable = new Readable({
      +  read(size) {
      +    const err = checkSomeErrorCondition();
      +    if (err) {
      +      this.destroy(err);
      +    } else {
      +      // Do some work.
      +    }
      +  }
      +});
      +

      An example counting stream#

      + +

      The following is a basic example of a Readable stream that emits the numerals +from 1 to 1,000,000 in ascending order, and then ends.

      +
      const { Readable } = require('stream');
      +
      +class Counter extends Readable {
      +  constructor(opt) {
      +    super(opt);
      +    this._max = 1000000;
      +    this._index = 1;
      +  }
      +
      +  _read() {
      +    const i = this._index++;
      +    if (i > this._max)
      +      this.push(null);
      +    else {
      +      const str = String(i);
      +      const buf = Buffer.from(str, 'ascii');
      +      this.push(buf);
      +    }
      +  }
      +}
      +

      Implementing a duplex stream#

      +

      A Duplex stream is one that implements both Readable and +Writable, such as a TCP socket connection.

      +

      Because JavaScript does not have support for multiple inheritance, the +stream.Duplex class is extended to implement a Duplex stream (as opposed +to extending the stream.Readable and stream.Writable classes).

      +

      The stream.Duplex class prototypically inherits from stream.Readable and +parasitically from stream.Writable, but instanceof will work properly for +both base classes due to overriding Symbol.hasInstance on +stream.Writable.

      +

      Custom Duplex streams must call the new stream.Duplex([options]) +constructor and implement both the readable._read() and +writable._write() methods.

      +

      new stream.Duplex(options)#

      + +
        +
      • options <Object> Passed to both Writable and Readable +constructors. Also has the following fields: +
          +
        • allowHalfOpen <boolean> If set to false, then the stream will +automatically end the writable side when the readable side ends. +Default: true.
        • +
        • readable <boolean> Sets whether the Duplex should be readable. +Default: true.
        • +
        • writable <boolean> Sets whether the Duplex should be writable. +Default: true.
        • +
        • readableObjectMode <boolean> Sets objectMode for readable side of the +stream. Has no effect if objectMode is true. Default: false.
        • +
        • writableObjectMode <boolean> Sets objectMode for writable side of the +stream. Has no effect if objectMode is true. Default: false.
        • +
        • readableHighWaterMark <number> Sets highWaterMark for the readable side +of the stream. Has no effect if highWaterMark is provided.
        • +
        • writableHighWaterMark <number> Sets highWaterMark for the writable side +of the stream. Has no effect if highWaterMark is provided.
        • +
        +
      • +
      + +
      const { Duplex } = require('stream');
      +
      +class MyDuplex extends Duplex {
      +  constructor(options) {
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Duplex } = require('stream');
      +const util = require('util');
      +
      +function MyDuplex(options) {
      +  if (!(this instanceof MyDuplex))
      +    return new MyDuplex(options);
      +  Duplex.call(this, options);
      +}
      +util.inherits(MyDuplex, Duplex);
      +

      Or, using the simplified constructor approach:

      +
      const { Duplex } = require('stream');
      +
      +const myDuplex = new Duplex({
      +  read(size) {
      +    // ...
      +  },
      +  write(chunk, encoding, callback) {
      +    // ...
      +  }
      +});
      +

      An example duplex stream#

      +

      The following illustrates a simple example of a Duplex stream that wraps a +hypothetical lower-level source object to which data can be written, and +from which data can be read, albeit using an API that is not compatible with +Node.js streams. +The following illustrates a simple example of a Duplex stream that buffers +incoming written data via the Writable interface that is read back out +via the Readable interface.

      +
      const { Duplex } = require('stream');
      +const kSource = Symbol('source');
      +
      +class MyDuplex extends Duplex {
      +  constructor(source, options) {
      +    super(options);
      +    this[kSource] = source;
      +  }
      +
      +  _write(chunk, encoding, callback) {
      +    // The underlying source only deals with strings.
      +    if (Buffer.isBuffer(chunk))
      +      chunk = chunk.toString();
      +    this[kSource].writeSomeData(chunk);
      +    callback();
      +  }
      +
      +  _read(size) {
      +    this[kSource].fetchSomeData(size, (data, encoding) => {
      +      this.push(Buffer.from(data, encoding));
      +    });
      +  }
      +}
      +

      The most important aspect of a Duplex stream is that the Readable and +Writable sides operate independently of one another despite co-existing within +a single object instance.

      +

      Object mode duplex streams#

      +

      For Duplex streams, objectMode can be set exclusively for either the +Readable or Writable side using the readableObjectMode and +writableObjectMode options respectively.

      +

      In the following example, for instance, a new Transform stream (which is a +type of Duplex stream) is created that has an object mode Writable side +that accepts JavaScript numbers that are converted to hexadecimal strings on +the Readable side.

      +
      const { Transform } = require('stream');
      +
      +// All Transform streams are also Duplex Streams.
      +const myTransform = new Transform({
      +  writableObjectMode: true,
      +
      +  transform(chunk, encoding, callback) {
      +    // Coerce the chunk to a number if necessary.
      +    chunk |= 0;
      +
      +    // Transform the chunk into something else.
      +    const data = chunk.toString(16);
      +
      +    // Push the data onto the readable queue.
      +    callback(null, '0'.repeat(data.length % 2) + data);
      +  }
      +});
      +
      +myTransform.setEncoding('ascii');
      +myTransform.on('data', (chunk) => console.log(chunk));
      +
      +myTransform.write(1);
      +// Prints: 01
      +myTransform.write(10);
      +// Prints: 0a
      +myTransform.write(100);
      +// Prints: 64
      +

      Implementing a transform stream#

      +

      A Transform stream is a Duplex stream where the output is computed +in some way from the input. Examples include zlib streams or crypto +streams that compress, encrypt, or decrypt data.

      +

      There is no requirement that the output be the same size as the input, the same +number of chunks, or arrive at the same time. For example, a Hash stream will +only ever have a single chunk of output which is provided when the input is +ended. A zlib stream will produce output that is either much smaller or much +larger than its input.

      +

      The stream.Transform class is extended to implement a Transform stream.

      +

      The stream.Transform class prototypically inherits from stream.Duplex and +implements its own versions of the writable._write() and +readable._read() methods. Custom Transform implementations must +implement the transform._transform() method and may +also implement the transform._flush() method.

      +

      Care must be taken when using Transform streams in that data written to the +stream can cause the Writable side of the stream to become paused if the +output on the Readable side is not consumed.

      +

      new stream.Transform([options])#

      + + +
      const { Transform } = require('stream');
      +
      +class MyTransform extends Transform {
      +  constructor(options) {
      +    super(options);
      +    // ...
      +  }
      +}
      +

      Or, when using pre-ES6 style constructors:

      +
      const { Transform } = require('stream');
      +const util = require('util');
      +
      +function MyTransform(options) {
      +  if (!(this instanceof MyTransform))
      +    return new MyTransform(options);
      +  Transform.call(this, options);
      +}
      +util.inherits(MyTransform, Transform);
      +

      Or, using the simplified constructor approach:

      +
      const { Transform } = require('stream');
      +
      +const myTransform = new Transform({
      +  transform(chunk, encoding, callback) {
      +    // ...
      +  }
      +});
      +

      Events: 'finish' and 'end'#

      +

      The 'finish' and 'end' events are from the stream.Writable +and stream.Readable classes, respectively. The 'finish' event is emitted +after stream.end() is called and all chunks have been processed +by stream._transform(). The 'end' event is emitted +after all data has been output, which occurs after the callback in +transform._flush() has been called.

      +

      transform._flush(callback)#

      +
        +
      • callback <Function> A callback function (optionally with an error +argument and data) to be called when remaining data has been flushed.
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Readable class +methods only.

      +

      In some cases, a transform operation may need to emit an additional bit of +data at the end of the stream. For example, a zlib compression stream will +store an amount of internal state used to optimally compress the output. When +the stream ends, however, that additional data needs to be flushed so that the +compressed data will be complete.

      +

      Custom Transform implementations may implement the transform._flush() +method. This will be called when there is no more written data to be consumed, +but before the 'end' event is emitted signaling the end of the +Readable stream.

      +

      Within the transform._flush() implementation, the transform.push() method +may be called zero or more times, as appropriate. The callback function must +be called when the flush operation is complete.

      +

      The transform._flush() method is prefixed with an underscore because it is +internal to the class that defines it, and should never be called directly by +user programs.

      +

      transform._transform(chunk, encoding, callback)#

      +
        +
      • chunk <Buffer> | <string> | <any> The Buffer to be transformed, converted from +the string passed to stream.write(). If the stream's +decodeStrings option is false or the stream is operating in object mode, +the chunk will not be converted & will be whatever was passed to +stream.write().
      • +
      • encoding <string> If the chunk is a string, then this is the +encoding type. If chunk is a buffer, then this is the special +value 'buffer'. Ignore it in that case.
      • +
      • callback <Function> A callback function (optionally with an error +argument and data) to be called after the supplied chunk has been +processed.
      • +
      +

      This function MUST NOT be called by application code directly. It should be +implemented by child classes, and called by the internal Readable class +methods only.

      +

      All Transform stream implementations must provide a _transform() +method to accept input and produce output. The transform._transform() +implementation handles the bytes being written, computes an output, then passes +that output off to the readable portion using the transform.push() method.

      +

      The transform.push() method may be called zero or more times to generate +output from a single input chunk, depending on how much is to be output +as a result of the chunk.

      +

      It is possible that no output is generated from any given chunk of input data.

      +

      The callback function must be called only when the current chunk is completely +consumed. The first argument passed to the callback must be an Error object +if an error occurred while processing the input or null otherwise. If a second +argument is passed to the callback, it will be forwarded on to the +transform.push() method. In other words, the following are equivalent:

      +
      transform.prototype._transform = function(data, encoding, callback) {
      +  this.push(data);
      +  callback();
      +};
      +
      +transform.prototype._transform = function(data, encoding, callback) {
      +  callback(null, data);
      +};
      +

      The transform._transform() method is prefixed with an underscore because it +is internal to the class that defines it, and should never be called directly by +user programs.

      +

      transform._transform() is never called in parallel; streams implement a +queue mechanism, and to receive the next chunk, callback must be +called, either synchronously or asynchronously.

      +

      Class: stream.PassThrough#

      +

      The stream.PassThrough class is a trivial implementation of a Transform +stream that simply passes the input bytes across to the output. Its purpose is +primarily for examples and testing, but there are some use cases where +stream.PassThrough is useful as a building block for novel sorts of streams.

      +

      Additional notes#

      + +

      Streams compatibility with async generators and async iterators#

      +

      With the support of async generators and iterators in JavaScript, async +generators are effectively a first-class language-level stream construct at +this point.

      +

      Some common interop cases of using Node.js streams with async generators +and async iterators are provided below.

      +

      Consuming readable streams with async iterators#

      +
      (async function() {
      +  for await (const chunk of readable) {
      +    console.log(chunk);
      +  }
      +})();
      +

      Async iterators register a permanent error handler on the stream to prevent any +unhandled post-destroy errors.

      +

      Creating readable streams with async generators#

      +

      We can construct a Node.js readable stream from an asynchronous generator +using the Readable.from() utility method:

      +
      const { Readable } = require('stream');
      +
      +async function * generate() {
      +  yield 'a';
      +  yield 'b';
      +  yield 'c';
      +}
      +
      +const readable = Readable.from(generate());
      +
      +readable.on('data', (chunk) => {
      +  console.log(chunk);
      +});
      +

      Piping to writable streams from async iterators#

      +

      In the scenario of writing to a writable stream from an async iterator, ensure +the correct handling of backpressure and errors.

      +
      const { once } = require('events');
      +const finished = util.promisify(stream.finished);
      +
      +const writable = fs.createWriteStream('./file');
      +
      +function drain(writable) {
      +  if (writable.destroyed) {
      +    return Promise.reject(new Error('premature close'));
      +  }
      +  return Promise.race([
      +    once(writable, 'drain'),
      +    once(writable, 'close')
      +      .then(() => Promise.reject(new Error('premature close')))
      +  ]);
      +}
      +
      +async function pump(iterable, writable) {
      +  for await (const chunk of iterable) {
      +    // Handle backpressure on write().
      +    if (!writable.write(chunk)) {
      +      await drain(writable);
      +    }
      +  }
      +  writable.end();
      +}
      +
      +(async function() {
      +  // Ensure completion without errors.
      +  await Promise.all([
      +    pump(iterable, writable),
      +    finished(writable)
      +  ]);
      +})();
      +

      In the above, errors on write() would be caught and thrown by the +once() listener for the 'drain' event, since once() will also handle the +'error' event. To ensure completion of the write stream without errors, +it is safer to use the finished() method as above, instead of using the +once() listener for the 'finish' event. Under certain cases, an 'error' +event could be emitted by the writable stream after 'finish' and as once() +will release the 'error' handler on handling the 'finish' event, it could +result in an unhandled error.

      +

      Alternatively, the readable stream could be wrapped with Readable.from() and +then piped via .pipe():

      +
      const finished = util.promisify(stream.finished);
      +
      +const writable = fs.createWriteStream('./file');
      +
      +(async function() {
      +  const readable = Readable.from(iterable);
      +  readable.pipe(writable);
      +  // Ensure completion without errors.
      +  await finished(writable);
      +})();
      +

      Or, using stream.pipeline() to pipe streams:

      +
      const pipeline = util.promisify(stream.pipeline);
      +
      +const writable = fs.createWriteStream('./file');
      +
      +(async function() {
      +  const readable = Readable.from(iterable);
      +  await pipeline(readable, writable);
      +})();
      + +

      Compatibility with older Node.js versions#

      + +

      Prior to Node.js 0.10, the Readable stream interface was simpler, but also +less powerful and less useful.

      +
        +
      • Rather than waiting for calls to the stream.read() method, +'data' events would begin emitting immediately. Applications that +would need to perform some amount of work to decide how to handle data +were required to store read data into buffers so the data would not be lost.
      • +
      • The stream.pause() method was advisory, rather than +guaranteed. This meant that it was still necessary to be prepared to receive +'data' events even when the stream was in a paused state.
      • +
      +

      In Node.js 0.10, the Readable class was added. For backward +compatibility with older Node.js programs, Readable streams switch into +"flowing mode" when a 'data' event handler is added, or when the +stream.resume() method is called. The effect is that, even +when not using the new stream.read() method and +'readable' event, it is no longer necessary to worry about losing +'data' chunks.

      +

      While most applications will continue to function normally, this introduces an +edge case in the following conditions:

      +
        +
      • No 'data' event listener is added.
      • +
      • The stream.resume() method is never called.
      • +
      • The stream is not piped to any writable destination.
      • +
      +

      For example, consider the following code:

      +
      // WARNING!  BROKEN!
      +net.createServer((socket) => {
      +
      +  // We add an 'end' listener, but never consume the data.
      +  socket.on('end', () => {
      +    // It will never get here.
      +    socket.end('The message was received but was not processed.\n');
      +  });
      +
      +}).listen(1337);
      +

      Prior to Node.js 0.10, the incoming message data would be simply discarded. +However, in Node.js 0.10 and beyond, the socket remains paused forever.

      +

      The workaround in this situation is to call the +stream.resume() method to begin the flow of data:

      +
      // Workaround.
      +net.createServer((socket) => {
      +  socket.on('end', () => {
      +    socket.end('The message was received but was not processed.\n');
      +  });
      +
      +  // Start the flow of data, discarding it.
      +  socket.resume();
      +}).listen(1337);
      +

      In addition to new Readable streams switching into flowing mode, +pre-0.10 style streams can be wrapped in a Readable class using the +readable.wrap() method.

      +

      readable.read(0)#

      +

      There are some cases where it is necessary to trigger a refresh of the +underlying readable stream mechanisms, without actually consuming any +data. In such cases, it is possible to call readable.read(0), which will +always return null.

      +

      If the internal read buffer is below the highWaterMark, and the +stream is not currently reading, then calling stream.read(0) will trigger +a low-level stream._read() call.

      +

      While most applications will almost never need to do this, there are +situations within Node.js where this is done, particularly in the +Readable stream class internals.

      +

      readable.push('')#

      +

      Use of readable.push('') is not recommended.

      +

      Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in +object mode has an interesting side effect. Because it is a call to +readable.push(), the call will end the reading process. +However, because the argument is an empty string, no data is added to the +readable buffer so there is nothing for a user to consume.

      +

      highWaterMark discrepancy after calling readable.setEncoding()#

      +

      The use of readable.setEncoding() will change the behavior of how the +highWaterMark operates in non-object mode.

      +

      Typically, the size of the current buffer is measured against the +highWaterMark in bytes. However, after setEncoding() is called, the +comparison function will begin to measure the buffer's size in characters.

      +

      This is not a problem in common cases with latin1 or ascii. But it is +advised to be mindful about this behavior when working with strings that could +contain multi-byte characters.

      + +
      +
      +
      + + diff --git a/doc/api/stream.json b/doc/api/stream.json new file mode 100644 index 0000000000000000000000000000000000000000..1e37bc606931acd450bcff0a7dbd5e79c3c05f3e --- /dev/null +++ b/doc/api/stream.json @@ -0,0 +1,2193 @@ +{ + "type": "module", + "source": "doc/api/stream.md", + "modules": [ + { + "textRaw": "Stream", + "name": "stream", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/stream.js

      \n

      A stream is an abstract interface for working with streaming data in Node.js.\nThe stream module provides an API for implementing the stream interface.

      \n

      There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout\nare both stream instances.

      \n

      Streams can be readable, writable, or both. All streams are instances of\nEventEmitter.

      \n

      To access the stream module:

      \n
      const stream = require('stream');\n
      \n

      The stream module is useful for creating new types of stream instances. It is\nusually not necessary to use the stream module to consume streams.

      ", + "modules": [ + { + "textRaw": "Organization of this document", + "name": "organization_of_this_document", + "desc": "

      This document contains two primary sections and a third section for notes. The\nfirst section explains how to use existing streams within an application. The\nsecond section explains how to create new types of streams.

      ", + "type": "module", + "displayName": "Organization of this document" + }, + { + "textRaw": "Types of streams", + "name": "types_of_streams", + "desc": "

      There are four fundamental stream types within Node.js:

      \n\n

      Additionally, this module includes the utility functions\nstream.pipeline(), stream.finished() and\nstream.Readable.from().

      ", + "modules": [ + { + "textRaw": "Object mode", + "name": "object_mode", + "desc": "

      All streams created by Node.js APIs operate exclusively on strings and Buffer\n(or Uint8Array) objects. It is possible, however, for stream implementations\nto work with other types of JavaScript values (with the exception of null,\nwhich serves a special purpose within streams). Such streams are considered to\noperate in \"object mode\".

      \n

      Stream instances are switched into object mode using the objectMode option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.

      ", + "type": "module", + "displayName": "Object mode" + } + ], + "miscs": [ + { + "textRaw": "Buffering", + "name": "Buffering", + "type": "misc", + "desc": "

      Both Writable and Readable streams will store data in an internal\nbuffer that can be retrieved using writable.writableBuffer or\nreadable.readableBuffer, respectively.

      \n

      The amount of data potentially buffered depends on the highWaterMark option\npassed into the stream's constructor. For normal streams, the highWaterMark\noption specifies a total number of bytes. For streams operating\nin object mode, the highWaterMark specifies a total number of objects.

      \n

      Data is buffered in Readable streams when the implementation calls\nstream.push(chunk). If the consumer of the Stream does not\ncall stream.read(), the data will sit in the internal\nqueue until it is consumed.

      \n

      Once the total size of the internal read buffer reaches the threshold specified\nby highWaterMark, the stream will temporarily stop reading data from the\nunderlying resource until the data currently buffered can be consumed (that is,\nthe stream will stop calling the internal readable._read() method that is\nused to fill the read buffer).

      \n

      Data is buffered in Writable streams when the\nwritable.write(chunk) method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\nhighWaterMark, calls to writable.write() will return true. Once\nthe size of the internal buffer reaches or exceeds the highWaterMark, false\nwill be returned.

      \n

      A key goal of the stream API, particularly the stream.pipe() method,\nis to limit the buffering of data to acceptable levels such that sources and\ndestinations of differing speeds will not overwhelm the available memory.

      \n

      The highWaterMark option is a threshold, not a limit: it dictates the amount\nof data that a stream buffers before it stops asking for more data. It does not\nenforce a strict memory limitation in general. Specific stream implementations\nmay choose to enforce stricter limits but doing so is optional.

      \n

      Because Duplex and Transform streams are both Readable and\nWritable, each maintains two separate internal buffers used for reading and\nwriting, allowing each side to operate independently of the other while\nmaintaining an appropriate and efficient flow of data. For example,\nnet.Socket instances are Duplex streams whose Readable side allows\nconsumption of data received from the socket and whose Writable side allows\nwriting data to the socket. Because data may be written to the socket at a\nfaster or slower rate than data is received, each side should\noperate (and buffer) independently of the other.

      " + } + ], + "type": "module", + "displayName": "Types of streams" + } + ], + "methods": [ + { + "textRaw": "`stream.finished(stream[, options], callback)`", + "type": "method", + "name": "finished", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", + "name": "return", + "type": "Function", + "desc": "A cleanup function which removes all registered listeners." + }, + "params": [ + { + "textRaw": "`stream` {Stream} A readable and/or writable stream.", + "name": "stream", + "type": "Stream", + "desc": "A readable and/or writable stream." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`.", + "name": "error", + "type": "boolean", + "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`." + }, + { + "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`.", + "name": "readable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`." + }, + { + "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`.", + "name": "writable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`." + } + ] + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

      \n
      const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n  if (err) {\n    console.error('Stream failed.', err);\n  } else {\n    console.log('Stream is done reading.');\n  }\n});\n\nrs.resume(); // Drain the stream.\n
      \n

      Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

      \n

      The finished API is promisify-able as well;

      \n
      const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n  await finished(rs);\n  console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n
      \n

      stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:

      \n
      const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n
      " + }, + { + "textRaw": "`stream.pipeline(...streams, callback)`", + "type": "method", + "name": "pipeline", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...streams` {Stream} Two or more streams to pipe between.", + "name": "...streams", + "type": "Stream", + "desc": "Two or more streams to pipe between." + }, + { + "textRaw": "`callback` {Function} Called when the pipeline is fully done.", + "name": "callback", + "type": "Function", + "desc": "Called when the pipeline is fully done.", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      A module method to pipe between streams forwarding errors and properly cleaning\nup and provide a callback when the pipeline is complete.

      \n
      const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n  fs.createReadStream('archive.tar'),\n  zlib.createGzip(),\n  fs.createWriteStream('archive.tar.gz'),\n  (err) => {\n    if (err) {\n      console.error('Pipeline failed.', err);\n    } else {\n      console.log('Pipeline succeeded.');\n    }\n  }\n);\n
      \n

      The pipeline API is promisify-able as well:

      \n
      const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
      \n

      stream.pipeline() will call stream.destroy(err) on all streams except:

      \n
        \n
      • Readable streams which have emitted 'end' or 'close'.
      • \n
      • Writable streams which have emitted 'finish' or 'close'.
      • \n
      \n

      stream.pipeline() leaves dangling event listeners on the streams\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.

      " + }, + { + "textRaw": "`stream.Readable.from(iterable, [options])`", + "type": "method", + "name": "from", + "meta": { + "added": [ + "v12.3.0", + "v10.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Readable}", + "name": "return", + "type": "stream.Readable" + }, + "params": [ + { + "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", + "name": "iterable", + "type": "Iterable", + "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." + }, + { + "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", + "name": "options", + "type": "Object", + "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`." + } + ] + } + ], + "desc": "

      A utility method for creating readable streams out of iterators.

      \n
      const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'hello';\n  yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
      \n

      Calling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.

      " + }, + { + "textRaw": "`readable.read(0)`", + "type": "method", + "name": "read", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.

      \n

      If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.

      \n

      While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.

      " + }, + { + "textRaw": "`readable.push('')`", + "type": "method", + "name": "push", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Use of readable.push('') is not recommended.

      \n

      Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.

      " + } + ], + "miscs": [ + { + "textRaw": "API for stream consumers", + "name": "API for stream consumers", + "type": "misc", + "desc": "

      Almost all Node.js applications, no matter how simple, use streams in some\nmanner. The following is an example of using streams in a Node.js application\nthat implements an HTTP server:

      \n
      const http = require('http');\n\nconst server = http.createServer((req, res) => {\n  // `req` is an http.IncomingMessage, which is a readable stream.\n  // `res` is an http.ServerResponse, which is a writable stream.\n\n  let body = '';\n  // Get the data as utf8 strings.\n  // If an encoding is not set, Buffer objects will be received.\n  req.setEncoding('utf8');\n\n  // Readable streams emit 'data' events once a listener is added.\n  req.on('data', (chunk) => {\n    body += chunk;\n  });\n\n  // The 'end' event indicates that the entire body has been received.\n  req.on('end', () => {\n    try {\n      const data = JSON.parse(body);\n      // Write back something interesting to the user:\n      res.write(typeof data);\n      res.end();\n    } catch (er) {\n      // uh oh! bad json!\n      res.statusCode = 400;\n      return res.end(`error: ${er.message}`);\n    }\n  });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d \"{}\"\n// object\n// $ curl localhost:1337 -d \"\\\"foo\\\"\"\n// string\n// $ curl localhost:1337 -d \"not json\"\n// error: Unexpected token o in JSON at position 1\n
      \n

      Writable streams (such as res in the example) expose methods such as\nwrite() and end() that are used to write data onto the stream.

      \n

      Readable streams use the EventEmitter API for notifying application\ncode when data is available to be read off the stream. That available data can\nbe read from the stream in multiple ways.

      \n

      Both Writable and Readable streams use the EventEmitter API in\nvarious ways to communicate the current state of the stream.

      \n

      Duplex and Transform streams are both Writable and\nReadable.

      \n

      Applications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call require('stream').

      \n

      Developers wishing to implement new types of streams should refer to the\nsection API for stream implementers.

      ", + "miscs": [ + { + "textRaw": "Writable streams", + "name": "writable_streams", + "desc": "

      Writable streams are an abstraction for a destination to which data is\nwritten.

      \n

      Examples of Writable streams include:

      \n\n

      Some of these examples are actually Duplex streams that implement the\nWritable interface.

      \n

      All Writable streams implement the interface defined by the\nstream.Writable class.

      \n

      While specific instances of Writable streams may differ in various ways,\nall Writable streams follow the same fundamental usage pattern as illustrated\nin the example below:

      \n
      const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n
      ", + "classes": [ + { + "textRaw": "Class: `stream.Writable`", + "type": "class", + "name": "stream.Writable", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18438", + "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." + } + ] + }, + "params": [], + "desc": "

      The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.

      \n

      A Writable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

      " + }, + { + "textRaw": "Event: `'drain'`", + "type": "event", + "name": "drain", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      If a call to stream.write(chunk) returns false, the\n'drain' event will be emitted when it is appropriate to resume writing data\nto the stream.

      \n
      // Write the data to the supplied writable stream one million times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  let i = 1000000;\n  write();\n  function write() {\n    let ok = true;\n    do {\n      i--;\n      if (i === 0) {\n        // Last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // See if we should continue, or wait.\n        // Don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // Had to stop early!\n      // Write some more once it drains.\n      writer.once('drain', write);\n    }\n  }\n}\n
      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      The 'error' event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single Error argument when called.

      \n

      The stream is not closed when the 'error' event is emitted unless the\nautoDestroy option was set to true when creating the\nstream.

      " + }, + { + "textRaw": "Event: `'finish'`", + "type": "event", + "name": "finish", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'finish' event is emitted after the stream.end() method\nhas been called, and all data has been flushed to the underlying system.

      \n
      const writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n  writer.write(`hello, #${i}!\\n`);\n}\nwriter.on('finish', () => {\n  console.log('All writes are now complete.');\n});\nwriter.end('This is the end\\n');\n
      " + }, + { + "textRaw": "Event: `'pipe'`", + "type": "event", + "name": "pipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`src` {stream.Readable} source stream that is piping to this writable", + "name": "src", + "type": "stream.Readable", + "desc": "source stream that is piping to this writable" + } + ], + "desc": "

      The 'pipe' event is emitted when the stream.pipe() method is called on\na readable stream, adding this writable to its set of destinations.

      \n
      const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n  console.log('Something is piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\n
      " + }, + { + "textRaw": "Event: `'unpipe'`", + "type": "event", + "name": "unpipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`src` {stream.Readable} The source stream that [unpiped][`stream.unpipe()`] this writable", + "name": "src", + "type": "stream.Readable", + "desc": "The source stream that [unpiped][`stream.unpipe()`] this writable" + } + ], + "desc": "

      The 'unpipe' event is emitted when the stream.unpipe() method is called\non a Readable stream, removing this Writable from its set of\ndestinations.

      \n

      This is also emitted in case this Writable stream emits an error when a\nReadable stream pipes into it.

      \n
      const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n  console.log('Something has stopped piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n
      " + } + ], + "methods": [ + { + "textRaw": "`writable.cork()`", + "type": "method", + "name": "cork", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The writable.cork() method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the stream.uncork() or\nstream.end() methods are called.

      \n

      The primary intent of writable.cork() is to accommodate a situation in which\nseveral small chunks are written to the stream in rapid succession. Instead of\nimmediately forwarding them to the underlying destination, writable.cork()\nbuffers all the chunks until writable.uncork() is called, which will pass them\nall to writable._writev(), if present. This prevents a head-of-line blocking\nsituation where data is being buffered while waiting for the first small chunk\nto be processed. However, use of writable.cork() without implementing\nwritable._writev() may have an adverse effect on throughput.

      \n

      See also: writable.uncork(), writable._writev().

      " + }, + { + "textRaw": "`writable.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error} Optional, an error to emit with `'error'` event.", + "name": "error", + "type": "Error", + "desc": "Optional, an error to emit with `'error'` event." + } + ] + } + ], + "desc": "

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the writable\nstream has ended and subsequent calls to write() or end() will result in\nan ERR_STREAM_DESTROYED error.\nThis is a destructive and immediate way to destroy a stream. Previous calls to\nwrite() may not have drained, and may trigger an ERR_STREAM_DESTROYED error.\nUse end() instead of destroy if data should flush before close, or wait for\nthe 'drain' event before destroying the stream.\nImplementors should not override this method,\nbut instead implement writable._destroy().

      " + }, + { + "textRaw": "`writable.end([chunk[, encoding]][, callback])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18780", + "description": "This method now returns a reference to `writable`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", + "name": "chunk", + "type": "string|Buffer|Uint8Array|any", + "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." + }, + { + "textRaw": "`encoding` {string} The encoding if `chunk` is a string", + "name": "encoding", + "type": "string", + "desc": "The encoding if `chunk` is a string" + }, + { + "textRaw": "`callback` {Function} Optional callback for when the stream is finished", + "name": "callback", + "type": "Function", + "desc": "Optional callback for when the stream is finished" + } + ] + } + ], + "desc": "

      Calling the writable.end() method signals that no more data will be written\nto the Writable. The optional chunk and encoding arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream. If provided, the optional callback function is attached as a listener\nfor the 'finish' event.

      \n

      Calling the stream.write() method after calling\nstream.end() will raise an error.

      \n
      // Write 'hello, ' and then end with 'world!'.\nconst fs = require('fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!\n
      " + }, + { + "textRaw": "`writable.setDefaultEncoding(encoding)`", + "type": "method", + "name": "setDefaultEncoding", + "meta": { + "added": [ + "v0.11.15" + ], + "changes": [ + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/5040", + "description": "This method now returns a reference to `writable`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`encoding` {string} The new default encoding", + "name": "encoding", + "type": "string", + "desc": "The new default encoding" + } + ] + } + ], + "desc": "

      The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.

      " + }, + { + "textRaw": "`writable.uncork()`", + "type": "method", + "name": "uncork", + "meta": { + "added": [ + "v0.11.2" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The writable.uncork() method flushes all data buffered since\nstream.cork() was called.

      \n

      When using writable.cork() and writable.uncork() to manage the buffering\nof writes to a stream, it is recommended that calls to writable.uncork() be\ndeferred using process.nextTick(). Doing so allows batching of all\nwritable.write() calls that occur within a given Node.js event loop phase.

      \n
      stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n
      \n

      If the writable.cork() method is called multiple times on a stream, the\nsame number of calls to writable.uncork() must be called to flush the buffered\ndata.

      \n
      stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n  stream.uncork();\n  // The data will not be flushed until uncork() is called a second time.\n  stream.uncork();\n});\n
      \n

      See also: writable.cork().

      " + }, + { + "textRaw": "`writable.write(chunk[, encoding][, callback])`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/6170", + "description": "Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", + "name": "chunk", + "type": "string|Buffer|Uint8Array|any", + "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." + }, + { + "textRaw": "`encoding` {string} The encoding, if `chunk` is a string. **Default:** `'utf8'`", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The encoding, if `chunk` is a string." + }, + { + "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed", + "name": "callback", + "type": "Function", + "desc": "Callback for when this chunk of data is flushed" + } + ] + } + ], + "desc": "

      The writable.write() method writes some data to the stream, and calls the\nsupplied callback once the data has been fully handled. If an error\noccurs, the callback may or may not be called with the error as its\nfirst argument. To reliably detect write errors, add a listener for the\n'error' event.

      \n

      The return value is true if the internal buffer is less than the\nhighWaterMark configured when the stream was created after admitting chunk.\nIf false is returned, further attempts to write data to the stream should\nstop until the 'drain' event is emitted.

      \n

      While a stream is not draining, calls to write() will buffer chunk, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the 'drain' event will be emitted.\nIt is recommended that once write() returns false, no more chunks be written\nuntil the 'drain' event is emitted. While calling write() on a stream that\nis not draining is allowed, Node.js will buffer all written chunks until\nmaximum memory usage occurs, at which point it will abort unconditionally.\nEven before it aborts, high memory usage will cause poor garbage collector\nperformance and high RSS (which is not typically released back to the system,\neven after the memory is no longer required). Since TCP sockets may never\ndrain if the remote peer does not read the data, writing a socket that is\nnot draining may lead to a remotely exploitable vulnerability.

      \n

      Writing data while the stream is not draining is particularly\nproblematic for a Transform, because the Transform streams are paused\nby default until they are piped or a 'data' or 'readable' event handler\nis added.

      \n

      If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a Readable and use\nstream.pipe(). However, if calling write() is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n'drain' event:

      \n
      function write(data, cb) {\n  if (!stream.write(data)) {\n    stream.once('drain', cb);\n  } else {\n    process.nextTick(cb);\n  }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n  console.log('Write completed, do more writes now.');\n});\n
      \n

      A Writable stream in object mode will always ignore the encoding argument.

      " + } + ], + "properties": [ + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Is true after writable.destroy() has been called.

      " + }, + { + "textRaw": "`writable` {boolean}", + "type": "boolean", + "name": "writable", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "desc": "

      Is true if it is safe to call writable.write().

      " + }, + { + "textRaw": "`writableEnded` {boolean}", + "type": "boolean", + "name": "writableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Is true after writable.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.

      " + }, + { + "textRaw": "`writableCorked` {integer}", + "type": "integer", + "name": "writableCorked", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

      Number of times writable.uncork() needs to be\ncalled in order to fully uncork the stream.

      " + }, + { + "textRaw": "`writableFinished` {boolean}", + "type": "boolean", + "name": "writableFinished", + "meta": { + "added": [ + "v12.6.0" + ], + "changes": [] + }, + "desc": "

      Is set to true immediately before the 'finish' event is emitted.

      " + }, + { + "textRaw": "`writableHighWaterMark` {number}", + "type": "number", + "name": "writableHighWaterMark", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "desc": "

      Return the value of highWaterMark passed when constructing this\nWritable.

      " + }, + { + "textRaw": "`writableLength` {number}", + "type": "number", + "name": "writableLength", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      This property contains the number of bytes (or objects) in the queue\nready to be written. The value provides introspection data regarding\nthe status of the highWaterMark.

      " + }, + { + "textRaw": "`writableObjectMode` {boolean}", + "type": "boolean", + "name": "writableObjectMode", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "desc": "

      Getter for the property objectMode of a given Writable stream.

      " + } + ] + } + ], + "type": "misc", + "displayName": "Writable streams" + }, + { + "textRaw": "Readable streams", + "name": "readable_streams", + "desc": "

      Readable streams are an abstraction for a source from which data is\nconsumed.

      \n

      Examples of Readable streams include:

      \n\n

      All Readable streams implement the interface defined by the\nstream.Readable class.

      ", + "modules": [ + { + "textRaw": "Two reading modes", + "name": "two_reading_modes", + "desc": "

      Readable streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from object mode.\nA Readable stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.

      \n
        \n
      • \n

        In flowing mode, data is read from the underlying system automatically\nand provided to an application as quickly as possible using events via the\nEventEmitter interface.

        \n
      • \n
      • \n

        In paused mode, the stream.read() method must be called\nexplicitly to read chunks of data from the stream.

        \n
      • \n
      \n

      All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:

      \n\n

      The Readable can switch back to paused mode using one of the following:

      \n
        \n
      • If there are no pipe destinations, by calling the\nstream.pause() method.
      • \n
      • If there are pipe destinations, by removing all pipe destinations.\nMultiple pipe destinations may be removed by calling the\nstream.unpipe() method.
      • \n
      \n

      The important concept to remember is that a Readable will not generate data\nuntil a mechanism for either consuming or ignoring that data is provided. If\nthe consuming mechanism is disabled or taken away, the Readable will attempt\nto stop generating the data.

      \n

      For backward compatibility reasons, removing 'data' event handlers will\nnot automatically pause the stream. Also, if there are piped destinations,\nthen calling stream.pause() will not guarantee that the\nstream will remain paused once those destinations drain and ask for more data.

      \n

      If a Readable is switched into flowing mode and there are no consumers\navailable to handle the data, that data will be lost. This can occur, for\ninstance, when the readable.resume() method is called without a listener\nattached to the 'data' event, or when a 'data' event handler is removed\nfrom the stream.

      \n

      Adding a 'readable' event handler automatically makes the stream\nstop flowing, and the data has to be consumed via\nreadable.read(). If the 'readable' event handler is\nremoved, then the stream will start flowing again if there is a\n'data' event handler.

      ", + "type": "module", + "displayName": "Two reading modes" + }, + { + "textRaw": "Three states", + "name": "three_states", + "desc": "

      The \"two modes\" of operation for a Readable stream are a simplified\nabstraction for the more complicated internal state management that is happening\nwithin the Readable stream implementation.

      \n

      Specifically, at any given point in time, every Readable is in one of three\npossible states:

      \n
        \n
      • readable.readableFlowing === null
      • \n
      • readable.readableFlowing === false
      • \n
      • readable.readableFlowing === true
      • \n
      \n

      When readable.readableFlowing is null, no mechanism for consuming the\nstream's data is provided. Therefore, the stream will not generate data.\nWhile in this state, attaching a listener for the 'data' event, calling the\nreadable.pipe() method, or calling the readable.resume() method will switch\nreadable.readableFlowing to true, causing the Readable to begin actively\nemitting events as data is generated.

      \n

      Calling readable.pause(), readable.unpipe(), or receiving backpressure\nwill cause the readable.readableFlowing to be set as false,\ntemporarily halting the flowing of events but not halting the generation of\ndata. While in this state, attaching a listener for the 'data' event\nwill not switch readable.readableFlowing to true.

      \n
      const { PassThrough, Writable } = require('stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// readableFlowing is now false.\n\npass.on('data', (chunk) => { console.log(chunk.toString()); });\npass.write('ok');  // Will not emit 'data'.\npass.resume();     // Must be called to make stream emit 'data'.\n
      \n

      While readable.readableFlowing is false, data may be accumulating\nwithin the stream's internal buffer.

      ", + "type": "module", + "displayName": "Three states" + }, + { + "textRaw": "Choose one API style", + "name": "choose_one_api_style", + "desc": "

      The Readable stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\none of the methods of consuming data and should never use multiple methods\nto consume data from a single stream. Specifically, using a combination\nof on('data'), on('readable'), pipe(), or async iterators could\nlead to unintuitive behavior.

      \n

      Use of the readable.pipe() method is recommended for most users as it has been\nimplemented to provide the easiest way of consuming stream data. Developers that\nrequire more fine-grained control over the transfer and generation of data can\nuse the EventEmitter and readable.on('readable')/readable.read()\nor the readable.pause()/readable.resume() APIs.

      ", + "type": "module", + "displayName": "Choose one API style" + } + ], + "classes": [ + { + "textRaw": "Class: `stream.Readable`", + "type": "class", + "name": "stream.Readable", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18438", + "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." + } + ] + }, + "params": [], + "desc": "

      The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.

      \n

      A Readable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

      " + }, + { + "textRaw": "Event: `'data'`", + "type": "event", + "name": "data", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`chunk` {Buffer|string|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`.", + "name": "chunk", + "type": "Buffer|string|any", + "desc": "The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`." + } + ], + "desc": "

      The 'data' event is emitted whenever the stream is relinquishing ownership of\na chunk of data to a consumer. This may occur whenever the stream is switched\nin flowing mode by calling readable.pipe(), readable.resume(), or by\nattaching a listener callback to the 'data' event. The 'data' event will\nalso be emitted whenever the readable.read() method is called and a chunk of\ndata is available to be returned.

      \n

      Attaching a 'data' event listener to a stream that has not been explicitly\npaused will switch the stream into flowing mode. Data will then be passed as\nsoon as it is available.

      \n

      The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\nreadable.setEncoding() method; otherwise the data will be passed as a\nBuffer.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\n
      " + }, + { + "textRaw": "Event: `'end'`", + "type": "event", + "name": "end", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'end' event is emitted when there is no more data to be consumed from\nthe stream.

      \n

      The 'end' event will not be emitted unless the data is completely\nconsumed. This can be accomplished by switching the stream into flowing mode,\nor by calling stream.read() repeatedly until all data has been\nconsumed.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n  console.log('There will be no more data.');\n});\n
      " + }, + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "{Error}", + "type": "Error" + } + ], + "desc": "

      The 'error' event may be emitted by a Readable implementation at any time.\nTypically, this may occur if the underlying stream is unable to generate data\ndue to an underlying internal failure, or when a stream implementation attempts\nto push an invalid chunk of data.

      \n

      The listener callback will be passed a single Error object.

      " + }, + { + "textRaw": "Event: `'pause'`", + "type": "event", + "name": "pause", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'pause' event is emitted when stream.pause() is called\nand readableFlowing is not false.

      " + }, + { + "textRaw": "Event: `'readable'`", + "type": "event", + "name": "readable", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17979", + "description": "The `'readable'` is always emitted in the next tick after `.push()` is called." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18994", + "description": "Using `'readable'` requires calling `.read()`." + } + ] + }, + "params": [], + "desc": "

      The 'readable' event is emitted when there is data available to be read from\nthe stream. In some cases, attaching a listener for the 'readable' event will\ncause some amount of data to be read into an internal buffer.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // There is some data to read now.\n  let data;\n\n  while (data = this.read()) {\n    console.log(data);\n  }\n});\n
      \n

      The 'readable' event will also be emitted once the end of the stream data\nhas been reached but before the 'end' event is emitted.

      \n

      Effectively, the 'readable' event indicates that the stream has new\ninformation: either new data is available or the end of the stream has been\nreached. In the former case, stream.read() will return the\navailable data. In the latter case, stream.read() will return\nnull. For instance, in the following example, foo.txt is an empty file:

      \n
      const fs = require('fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n  console.log(`readable: ${rr.read()}`);\n});\nrr.on('end', () => {\n  console.log('end');\n});\n
      \n

      The output of running this script is:

      \n
      $ node test.js\nreadable: null\nend\n
      \n

      In general, the readable.pipe() and 'data' event mechanisms are easier to\nunderstand than the 'readable' event. However, handling 'readable' might\nresult in increased throughput.

      \n

      If both 'readable' and 'data' are used at the same time, 'readable'\ntakes precedence in controlling the flow, i.e. 'data' will be emitted\nonly when stream.read() is called. The\nreadableFlowing property would become false.\nIf there are 'data' listeners when 'readable' is removed, the stream\nwill start flowing, i.e. 'data' events will be emitted without calling\n.resume().

      " + }, + { + "textRaw": "Event: `'resume'`", + "type": "event", + "name": "resume", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resume' event is emitted when stream.resume() is\ncalled and readableFlowing is not true.

      " + } + ], + "methods": [ + { + "textRaw": "`readable.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error} Error which will be passed as payload in `'error'` event", + "name": "error", + "type": "Error", + "desc": "Error which will be passed as payload in `'error'` event" + } + ] + } + ], + "desc": "

      Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the readable\nstream will release any internal resources and subsequent calls to push()\nwill be ignored.\nImplementors should not override this method, but instead implement\nreadable._destroy().

      " + }, + { + "textRaw": "`readable.isPaused()`", + "type": "method", + "name": "isPaused", + "meta": { + "added": [ + "v0.11.14" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      The readable.isPaused() method returns the current operating state of the\nReadable. This is used primarily by the mechanism that underlies the\nreadable.pipe() method. In most typical cases, there will be no reason to\nuse this method directly.

      \n
      const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n
      " + }, + { + "textRaw": "`readable.pause()`", + "type": "method", + "name": "pause", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [] + } + ], + "desc": "

      The readable.pause() method will cause a stream in flowing mode to stop\nemitting 'data' events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.

      \n
      const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n  readable.pause();\n  console.log('There will be no additional data for 1 second.');\n  setTimeout(() => {\n    console.log('Now data will start flowing again.');\n    readable.resume();\n  }, 1000);\n});\n
      \n

      The readable.pause() method has no effect if there is a 'readable'\nevent listener.

      " + }, + { + "textRaw": "`readable.pipe(destination[, options])`", + "type": "method", + "name": "pipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream", + "name": "return", + "type": "stream.Writable", + "desc": "The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream" + }, + "params": [ + { + "textRaw": "`destination` {stream.Writable} The destination for writing data", + "name": "destination", + "type": "stream.Writable", + "desc": "The destination for writing data" + }, + { + "textRaw": "`options` {Object} Pipe options", + "name": "options", + "type": "Object", + "desc": "Pipe options", + "options": [ + { + "textRaw": "`end` {boolean} End the writer when the reader ends. **Default:** `true`.", + "name": "end", + "type": "boolean", + "default": "`true`", + "desc": "End the writer when the reader ends." + } + ] + } + ] + } + ], + "desc": "

      The readable.pipe() method attaches a Writable stream to the readable,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached Writable. The flow of data will be automatically managed\nso that the destination Writable stream is not overwhelmed by a faster\nReadable stream.

      \n

      The following example pipes all of the data from the readable into a file\nnamed file.txt:

      \n
      const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);\n
      \n

      It is possible to attach multiple Writable streams to a single Readable\nstream.

      \n

      The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:

      \n
      const fs = require('fs');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n
      \n

      By default, stream.end() is called on the destination Writable\nstream when the source Readable stream emits 'end', so that the\ndestination is no longer writable. To disable this default behavior, the end\noption can be passed as false, causing the destination stream to remain open:

      \n
      reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});\n
      \n

      One important caveat is that if the Readable stream emits an error during\nprocessing, the Writable destination is not closed automatically. If an\nerror occurs, it will be necessary to manually close each stream in order\nto prevent memory leaks.

      \n

      The process.stderr and process.stdout Writable streams are never\nclosed until the Node.js process exits, regardless of the specified options.

      " + }, + { + "textRaw": "`readable.read([size])`", + "type": "method", + "name": "read", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|Buffer|null|any}", + "name": "return", + "type": "string|Buffer|null|any" + }, + "params": [ + { + "textRaw": "`size` {number} Optional argument to specify how much data to read.", + "name": "size", + "type": "number", + "desc": "Optional argument to specify how much data to read." + } + ] + } + ], + "desc": "

      The readable.read() method pulls some data out of the internal buffer and\nreturns it. If no data available to be read, null is returned. By default,\nthe data will be returned as a Buffer object unless an encoding has been\nspecified using the readable.setEncoding() method or the stream is operating\nin object mode.

      \n

      The optional size argument specifies a specific number of bytes to read. If\nsize bytes are not available to be read, null will be returned unless\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned.

      \n

      If the size argument is not specified, all of the data contained in the\ninternal buffer will be returned.

      \n

      The size argument must be less than or equal to 1 GB.

      \n

      The readable.read() method should only be called on Readable streams\noperating in paused mode. In flowing mode, readable.read() is called\nautomatically until the internal buffer is fully drained.

      \n
      const readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n  let chunk;\n  console.log('Stream is readable (new data received in buffer)');\n  // Use a loop to make sure we read all currently available data\n  while (null !== (chunk = readable.read())) {\n    console.log(`Read ${chunk.length} bytes of data...`);\n  }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n  console.log('Reached end of stream.');\n});\n
      \n

      Each call to readable.read() returns a chunk of data, or null. The chunks\nare not concatenated. A while loop is necessary to consume all data\ncurrently in the buffer. When reading a large file .read() may return null,\nhaving consumed all buffered content so far, but there is still more data to\ncome not yet buffered. In this case a new 'readable' event will be emitted\nwhen there is more data in the buffer. Finally the 'end' event will be\nemitted when there is no more data to come.

      \n

      Therefore to read a file's whole contents from a readable, it is necessary\nto collect chunks across multiple 'readable' events:

      \n
      const chunks = [];\n\nreadable.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = readable.read())) {\n    chunks.push(chunk);\n  }\n});\n\nreadable.on('end', () => {\n  const content = chunks.join('');\n});\n
      \n

      A Readable stream in object mode will always return a single item from\na call to readable.read(size), regardless of the value of the\nsize argument.

      \n

      If the readable.read() method returns a chunk of data, a 'data' event will\nalso be emitted.

      \n

      Calling stream.read([size]) after the 'end' event has\nbeen emitted will return null. No runtime error will be raised.

      " + }, + { + "textRaw": "`readable.resume()`", + "type": "method", + "name": "resume", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18994", + "description": "The `resume()` has no effect if there is a `'readable'` event listening." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [] + } + ], + "desc": "

      The readable.resume() method causes an explicitly paused Readable stream to\nresume emitting 'data' events, switching the stream into flowing mode.

      \n

      The readable.resume() method can be used to fully consume the data from a\nstream without actually processing any of that data:

      \n
      getReadableStreamSomehow()\n  .resume()\n  .on('end', () => {\n    console.log('Reached the end, but did not read anything.');\n  });\n
      \n

      The readable.resume() method has no effect if there is a 'readable'\nevent listener.

      " + }, + { + "textRaw": "`readable.setEncoding(encoding)`", + "type": "method", + "name": "setEncoding", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`encoding` {string} The encoding to use.", + "name": "encoding", + "type": "string", + "desc": "The encoding to use." + } + ] + } + ], + "desc": "

      The readable.setEncoding() method sets the character encoding for\ndata read from the Readable stream.

      \n

      By default, no encoding is assigned and stream data will be returned as\nBuffer objects. Setting an encoding causes the stream data\nto be returned as strings of the specified encoding rather than as Buffer\nobjects. For instance, calling readable.setEncoding('utf8') will cause the\noutput data to be interpreted as UTF-8 data, and passed as strings. Calling\nreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal\nstring format.

      \n

      The Readable stream will properly handle multi-byte characters delivered\nthrough the stream that would otherwise become improperly decoded if simply\npulled from the stream as Buffer objects.

      \n
      const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n  assert.equal(typeof chunk, 'string');\n  console.log('Got %d characters of string data:', chunk.length);\n});\n
      " + }, + { + "textRaw": "`readable.unpipe([destination])`", + "type": "method", + "name": "unpipe", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe", + "name": "destination", + "type": "stream.Writable", + "desc": "Optional specific stream to unpipe" + } + ] + } + ], + "desc": "

      The readable.unpipe() method detaches a Writable stream previously attached\nusing the stream.pipe() method.

      \n

      If the destination is not specified, then all pipes are detached.

      \n

      If the destination is specified, but no pipe is set up for it, then\nthe method does nothing.

      \n
      const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second.\nreadable.pipe(writable);\nsetTimeout(() => {\n  console.log('Stop writing to file.txt.');\n  readable.unpipe(writable);\n  console.log('Manually close the file stream.');\n  writable.end();\n}, 1000);\n
      " + }, + { + "textRaw": "`readable.unshift(chunk[, encoding])`", + "type": "method", + "name": "unshift", + "meta": { + "added": [ + "v0.9.11" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value.", + "name": "chunk", + "type": "Buffer|Uint8Array|string|null|any", + "desc": "Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value." + }, + { + "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", + "name": "encoding", + "type": "string", + "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`." + } + ] + } + ], + "desc": "

      Passing chunk as null signals the end of the stream (EOF) and behaves the\nsame as readable.push(null), after which no more data can be written. The EOF\nsignal is put at the end of the buffer and any buffered data will still be\nflushed.

      \n

      The readable.unshift() method pushes a chunk of data back into the internal\nbuffer. This is useful in certain situations where a stream is being consumed by\ncode that needs to \"un-consume\" some amount of data that it has optimistically\npulled out of the source, so that the data can be passed on to some other party.

      \n

      The stream.unshift(chunk) method cannot be called after the 'end' event\nhas been emitted or a runtime error will be thrown.

      \n

      Developers using stream.unshift() often should consider switching to\nuse of a Transform stream instead. See the API for stream implementers\nsection for more information.

      \n
      // Pull off a header delimited by \\n\\n.\n// Use unshift() if we get too much.\n// Call the callback with (error, header, stream).\nconst { StringDecoder } = require('string_decoder');\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  const decoder = new StringDecoder('utf8');\n  let header = '';\n  function onReadable() {\n    let chunk;\n    while (null !== (chunk = stream.read())) {\n      const str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // Found the header boundary.\n        const split = str.split(/\\n\\n/);\n        header += split.shift();\n        const remaining = split.join('\\n\\n');\n        const buf = Buffer.from(remaining, 'utf8');\n        stream.removeListener('error', callback);\n        // Remove the 'readable' listener before unshifting.\n        stream.removeListener('readable', onReadable);\n        if (buf.length)\n          stream.unshift(buf);\n        // Now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // Still reading the header.\n        header += str;\n      }\n    }\n  }\n}\n
      \n

      Unlike stream.push(chunk), stream.unshift(chunk) will not\nend the reading process by resetting the internal reading state of the stream.\nThis can cause unexpected results if readable.unshift() is called during a\nread (i.e. from within a stream._read() implementation on a\ncustom stream). Following the call to readable.unshift() with an immediate\nstream.push('') will reset the reading state appropriately,\nhowever it is best to simply avoid calling readable.unshift() while in the\nprocess of performing a read.

      " + }, + { + "textRaw": "`readable.wrap(stream)`", + "type": "method", + "name": "wrap", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`stream` {Stream} An \"old style\" readable stream", + "name": "stream", + "type": "Stream", + "desc": "An \"old style\" readable stream" + } + ] + } + ], + "desc": "

      Prior to Node.js 0.10, streams did not implement the entire stream module API\nas it is currently defined. (See Compatibility for more information.)

      \n

      When using an older Node.js library that emits 'data' events and has a\nstream.pause() method that is advisory only, the\nreadable.wrap() method can be used to create a Readable stream that uses\nthe old stream as its data source.

      \n

      It will rarely be necessary to use readable.wrap() but the method has been\nprovided as a convenience for interacting with older Node.js applications and\nlibraries.

      \n
      const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n  myReader.read(); // etc.\n});\n
      " + }, + { + "textRaw": "`readable[Symbol.asyncIterator]()`", + "type": "method", + "name": "[Symbol.asyncIterator]", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26989", + "description": "Symbol.asyncIterator support is no longer experimental." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {AsyncIterator} to fully consume the stream.", + "name": "return", + "type": "AsyncIterator", + "desc": "to fully consume the stream." + }, + "params": [] + } + ], + "desc": "
      const fs = require('fs');\n\nasync function print(readable) {\n  readable.setEncoding('utf8');\n  let data = '';\n  for await (const chunk of readable) {\n    data += chunk;\n  }\n  console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.error);\n
      \n

      If the loop terminates with a break or a throw, the stream will be\ndestroyed. In other terms, iterating over a stream will consume the stream\nfully. The stream will be read in chunks of size equal to the highWaterMark\noption. In the code example above, data will be in a single chunk if the file\nhas less then 64KB of data because no highWaterMark option is provided to\nfs.createReadStream().

      " + } + ], + "properties": [ + { + "textRaw": "`destroyed` {boolean}", + "type": "boolean", + "name": "destroyed", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      Is true after readable.destroy() has been called.

      " + }, + { + "textRaw": "`readable` {boolean}", + "type": "boolean", + "name": "readable", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "desc": "

      Is true if it is safe to call readable.read().

      " + }, + { + "textRaw": "`readableEncoding` {null|string}", + "type": "null|string", + "name": "readableEncoding", + "meta": { + "added": [ + "v12.7.0" + ], + "changes": [] + }, + "desc": "

      Getter for the property encoding of a given Readable stream. The encoding\nproperty can be set using the readable.setEncoding() method.

      " + }, + { + "textRaw": "`readableEnded` {boolean}", + "type": "boolean", + "name": "readableEnded", + "meta": { + "added": [ + "v12.9.0" + ], + "changes": [] + }, + "desc": "

      Becomes true when 'end' event is emitted.

      " + }, + { + "textRaw": "`readableFlowing` {boolean}", + "type": "boolean", + "name": "readableFlowing", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      This property reflects the current state of a Readable stream as described\nin the Three states section.

      " + }, + { + "textRaw": "`readableHighWaterMark` {number}", + "type": "number", + "name": "readableHighWaterMark", + "meta": { + "added": [ + "v9.3.0" + ], + "changes": [] + }, + "desc": "

      Returns the value of highWaterMark passed when constructing this\nReadable.

      " + }, + { + "textRaw": "`readableLength` {number}", + "type": "number", + "name": "readableLength", + "meta": { + "added": [ + "v9.4.0" + ], + "changes": [] + }, + "desc": "

      This property contains the number of bytes (or objects) in the queue\nready to be read. The value provides introspection data regarding\nthe status of the highWaterMark.

      " + }, + { + "textRaw": "`readableObjectMode` {boolean}", + "type": "boolean", + "name": "readableObjectMode", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "desc": "

      Getter for the property objectMode of a given Readable stream.

      " + } + ] + } + ], + "type": "misc", + "displayName": "Readable streams" + }, + { + "textRaw": "Duplex and transform streams", + "name": "duplex_and_transform_streams", + "classes": [ + { + "textRaw": "Class: `stream.Duplex`", + "type": "class", + "name": "stream.Duplex", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [ + { + "version": "v6.8.0", + "pr-url": "https://github.com/nodejs/node/pull/8834", + "description": "Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`." + } + ] + }, + "desc": "

      Duplex streams are streams that implement both the Readable and\nWritable interfaces.

      \n

      Examples of Duplex streams include:

      \n" + }, + { + "textRaw": "Class: `stream.Transform`", + "type": "class", + "name": "stream.Transform", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "desc": "

      Transform streams are Duplex streams where the output is in some way\nrelated to the input. Like all Duplex streams, Transform streams\nimplement both the Readable and Writable interfaces.

      \n

      Examples of Transform streams include:

      \n", + "methods": [ + { + "textRaw": "`transform.destroy([error])`", + "type": "method", + "name": "destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this}", + "name": "return", + "type": "this" + }, + "params": [ + { + "textRaw": "`error` {Error}", + "name": "error", + "type": "Error" + } + ] + } + ], + "desc": "

      Destroy the stream, and optionally emit an 'error' event. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\nreadable._destroy().\nThe default implementation of _destroy() for Transform also emit 'close'\nunless emitClose is set in false.

      " + } + ] + } + ], + "type": "misc", + "displayName": "Duplex and transform streams" + } + ], + "methods": [ + { + "textRaw": "`stream.finished(stream[, options], callback)`", + "type": "method", + "name": "finished", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", + "name": "return", + "type": "Function", + "desc": "A cleanup function which removes all registered listeners." + }, + "params": [ + { + "textRaw": "`stream` {Stream} A readable and/or writable stream.", + "name": "stream", + "type": "Stream", + "desc": "A readable and/or writable stream." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`.", + "name": "error", + "type": "boolean", + "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`." + }, + { + "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`.", + "name": "readable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`." + }, + { + "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`.", + "name": "writable", + "type": "boolean", + "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`." + } + ] + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

      \n
      const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n  if (err) {\n    console.error('Stream failed.', err);\n  } else {\n    console.log('Stream is done reading.');\n  }\n});\n\nrs.resume(); // Drain the stream.\n
      \n

      Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

      \n

      The finished API is promisify-able as well;

      \n
      const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n  await finished(rs);\n  console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n
      \n

      stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:

      \n
      const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n
      " + }, + { + "textRaw": "`stream.pipeline(...streams, callback)`", + "type": "method", + "name": "pipeline", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`...streams` {Stream} Two or more streams to pipe between.", + "name": "...streams", + "type": "Stream", + "desc": "Two or more streams to pipe between." + }, + { + "textRaw": "`callback` {Function} Called when the pipeline is fully done.", + "name": "callback", + "type": "Function", + "desc": "Called when the pipeline is fully done.", + "options": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ] + } + ] + } + ], + "desc": "

      A module method to pipe between streams forwarding errors and properly cleaning\nup and provide a callback when the pipeline is complete.

      \n
      const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n  fs.createReadStream('archive.tar'),\n  zlib.createGzip(),\n  fs.createWriteStream('archive.tar.gz'),\n  (err) => {\n    if (err) {\n      console.error('Pipeline failed.', err);\n    } else {\n      console.log('Pipeline succeeded.');\n    }\n  }\n);\n
      \n

      The pipeline API is promisify-able as well:

      \n
      const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
      \n

      stream.pipeline() will call stream.destroy(err) on all streams except:

      \n
        \n
      • Readable streams which have emitted 'end' or 'close'.
      • \n
      • Writable streams which have emitted 'finish' or 'close'.
      • \n
      \n

      stream.pipeline() leaves dangling event listeners on the streams\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.

      " + }, + { + "textRaw": "`stream.Readable.from(iterable, [options])`", + "type": "method", + "name": "from", + "meta": { + "added": [ + "v12.3.0", + "v10.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Readable}", + "name": "return", + "type": "stream.Readable" + }, + "params": [ + { + "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", + "name": "iterable", + "type": "Iterable", + "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." + }, + { + "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", + "name": "options", + "type": "Object", + "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`." + } + ] + } + ], + "desc": "

      A utility method for creating readable streams out of iterators.

      \n
      const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'hello';\n  yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
      \n

      Calling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.

      " + } + ] + }, + { + "textRaw": "API for stream implementers", + "name": "API for stream implementers", + "type": "misc", + "desc": "

      The stream module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.

      \n

      First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (stream.Writable, stream.Readable,\nstream.Duplex, or stream.Transform), making sure they call the appropriate\nparent class constructor:

      \n\n
      const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor({ highWaterMark, ...options }) {\n    super({\n      highWaterMark,\n      autoDestroy: true,\n      emitClose: true\n    });\n    // ...\n  }\n}\n
      \n

      When extending streams, keep in mind what options the user\ncan and should provide before forwarding these to the base constructor. For\nexample, if the implementation makes assumptions in regard to the\nautoDestroy and emitClose options, do not allow the\nuser to override these. Be explicit about what\noptions are forwarded instead of implicitly forwarding all options.

      \n

      The new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      Use-caseClassMethod(s) to implement
      Reading onlyReadable_read()
      Writing onlyWritable_write(), _writev(), _final()
      Reading and writingDuplex_read(), _write(), _writev(), _final()
      Operate on written data, then read the resultTransform_transform(), _flush(), _final()
      \n

      The implementation code for a stream should never call the \"public\" methods\nof a stream that are intended for use by consumers (as described in the\nAPI for stream consumers section). Doing so may lead to adverse side effects\nin application code consuming the stream.

      \n

      Avoid overriding public methods such as write(), end(), cork(),\nuncork(), read() and destroy(), or emitting internal events such\nas 'error', 'data', 'end', 'finish' and 'close' through .emit().\nDoing so can break current and future stream invariants leading to behavior\nand/or compatibility issues with other streams, stream utilities, and user\nexpectations.

      ", + "miscs": [ + { + "textRaw": "Simplified construction", + "name": "simplified_construction", + "meta": { + "added": [ + "v1.2.0" + ], + "changes": [] + }, + "desc": "

      For many simple cases, it is possible to construct a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\nstream.Writable, stream.Readable, stream.Duplex or stream.Transform\nobjects and passing appropriate methods as constructor options.

      \n
      const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
      ", + "type": "misc", + "displayName": "Simplified construction" + }, + { + "textRaw": "Implementing a writable stream", + "name": "implementing_a_writable_stream", + "desc": "

      The stream.Writable class is extended to implement a Writable stream.

      \n

      Custom Writable streams must call the new stream.Writable([options])\nconstructor and implement the writable._write() and/or writable._writev()\nmethod.

      ", + "ctors": [ + { + "textRaw": "`new stream.Writable([options])`", + "type": "ctor", + "name": "stream.Writable", + "meta": { + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18438", + "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." + }, + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/22795", + "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`highWaterMark` {number} Buffer level when [`stream.write()`][stream-write] starts returning `false`. **Default:** `16384` (16KB), or `16` for `objectMode` streams.", + "name": "highWaterMark", + "type": "number", + "default": "`16384` (16KB), or `16` for `objectMode` streams", + "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`." + }, + { + "textRaw": "`decodeStrings` {boolean} Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted. **Default:** `true`.", + "name": "decodeStrings", + "type": "boolean", + "default": "`true`", + "desc": "Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted." + }, + { + "textRaw": "`defaultEncoding` {string} The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]. **Default:** `'utf8'`.", + "name": "defaultEncoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]." + }, + { + "textRaw": "`objectMode` {boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation. **Default:** `false`.", + "name": "objectMode", + "type": "boolean", + "default": "`false`", + "desc": "Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation." + }, + { + "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", + "name": "emitClose", + "type": "boolean", + "default": "`true`", + "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." + }, + { + "textRaw": "`write` {Function} Implementation for the [`stream._write()`][stream-_write] method.", + "name": "write", + "type": "Function", + "desc": "Implementation for the [`stream._write()`][stream-_write] method." + }, + { + "textRaw": "`writev` {Function} Implementation for the [`stream._writev()`][stream-_writev] method.", + "name": "writev", + "type": "Function", + "desc": "Implementation for the [`stream._writev()`][stream-_writev] method." + }, + { + "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][writable-_destroy] method.", + "name": "destroy", + "type": "Function", + "desc": "Implementation for the [`stream._destroy()`][writable-_destroy] method." + }, + { + "textRaw": "`final` {Function} Implementation for the [`stream._final()`][stream-_final] method.", + "name": "final", + "type": "Function", + "desc": "Implementation for the [`stream._final()`][stream-_final] method." + }, + { + "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `false`.", + "name": "autoDestroy", + "type": "boolean", + "default": "`false`", + "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." + } + ] + } + ] + } + ], + "desc": "\n
      const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Writable } = require('stream');\nconst util = require('util');\n\nfunction MyWritable(options) {\n  if (!(this instanceof MyWritable))\n    return new MyWritable(options);\n  Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  }\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`writable._write(chunk, encoding, callback)`", + "type": "method", + "name": "_write", + "meta": { + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29639", + "description": "_write() is optional when providing _writev()." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", + "name": "chunk", + "type": "Buffer|string|any", + "desc": "The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." + }, + { + "textRaw": "`encoding` {string} If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored.", + "name": "encoding", + "type": "string", + "desc": "If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored." + }, + { + "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk.", + "name": "callback", + "type": "Function", + "desc": "Call this function (optionally with an error argument) when processing is complete for the supplied chunk." + } + ] + } + ], + "desc": "

      All Writable stream implementations must provide a\nwritable._write() and/or\nwritable._writev() method to send data to the underlying\nresource.

      \n

      Transform streams provide their own implementation of the\nwritable._write().

      \n

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.

      \n

      The callback method must be called to signal either that the write completed\nsuccessfully or failed with an error. The first argument passed to the\ncallback must be the Error object if the call failed or null if the\nwrite succeeded.

      \n

      All calls to writable.write() that occur between the time writable._write()\nis called and the callback is called will cause the written data to be\nbuffered. When the callback is invoked, the stream might emit a 'drain'\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the writable._writev() method should be implemented.

      \n

      If the decodeStrings property is explicitly set to false in the constructor\noptions, then chunk will remain the same object that is passed to .write(),\nand may be a string rather than a Buffer. This is to support implementations\nthat have an optimized handling for certain string data encodings. In that case,\nthe encoding argument will indicate the character encoding of the string.\nOtherwise, the encoding argument can be safely ignored.

      \n

      The writable._write() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`writable._writev(chunks, callback)`", + "type": "method", + "name": "_writev", + "signatures": [ + { + "params": [ + { + "textRaw": "`chunks` {Object[]} The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`.", + "name": "chunks", + "type": "Object[]", + "desc": "The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`." + }, + { + "textRaw": "`callback` {Function} A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks.", + "name": "callback", + "type": "Function", + "desc": "A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks." + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.

      \n

      The writable._writev() method may be implemented in addition or alternatively\nto writable._write() in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented and if there is buffered data\nfrom previous writes, _writev() will be called instead of _write().

      \n

      The writable._writev() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`writable._destroy(err, callback)`", + "type": "method", + "name": "_destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`err` {Error} A possible error.", + "name": "err", + "type": "Error", + "desc": "A possible error." + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      The _destroy() method is called by writable.destroy().\nIt can be overridden by child classes but it must not be called directly.

      " + }, + { + "textRaw": "`writable._final(callback)`", + "type": "method", + "name": "_final", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when finished writing any remaining data.", + "name": "callback", + "type": "Function", + "desc": "Call this function (optionally with an error argument) when finished writing any remaining data." + } + ] + } + ], + "desc": "

      The _final() method must not be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.

      \n

      This optional function will be called before the stream closes, delaying the\n'finish' event until callback is called. This is useful to close resources\nor write buffered data before a stream ends.

      " + } + ], + "modules": [ + { + "textRaw": "Errors while writing", + "name": "errors_while_writing", + "desc": "

      Errors occurring during the processing of the writable._write(),\nwritable._writev() and writable._final() methods must be propagated\nby invoking the callback and passing the error as the first argument.\nThrowing an Error from within these methods or manually emitting an 'error'\nevent results in undefined behavior.

      \n

      If a Readable stream pipes into a Writable stream when Writable emits an\nerror, the Readable stream will be unpiped.

      \n
      const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    if (chunk.toString().indexOf('a') >= 0) {\n      callback(new Error('chunk is invalid'));\n    } else {\n      callback();\n    }\n  }\n});\n
      ", + "type": "module", + "displayName": "Errors while writing" + }, + { + "textRaw": "An example writable stream", + "name": "an_example_writable_stream", + "desc": "

      The following illustrates a rather simplistic (and somewhat pointless) custom\nWritable stream implementation. While this specific Writable stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom Writable stream instance:

      \n
      const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  _write(chunk, encoding, callback) {\n    if (chunk.toString().indexOf('a') >= 0) {\n      callback(new Error('chunk is invalid'));\n    } else {\n      callback();\n    }\n  }\n}\n
      ", + "type": "module", + "displayName": "An example writable stream" + }, + { + "textRaw": "Decoding buffers in a writable stream", + "name": "decoding_buffers_in_a_writable_stream", + "desc": "

      Decoding buffers is a common task, for instance, when using transformers whose\ninput is a string. This is not a trivial process when using multi-byte\ncharacters encoding, such as UTF-8. The following example shows how to decode\nmulti-byte strings using StringDecoder and Writable.

      \n
      const { Writable } = require('stream');\nconst { StringDecoder } = require('string_decoder');\n\nclass StringWritable extends Writable {\n  constructor(options) {\n    super(options);\n    this._decoder = new StringDecoder(options && options.defaultEncoding);\n    this.data = '';\n  }\n  _write(chunk, encoding, callback) {\n    if (encoding === 'buffer') {\n      chunk = this._decoder.write(chunk);\n    }\n    this.data += chunk;\n    callback();\n  }\n  _final(callback) {\n    this.data += this._decoder.end();\n    callback();\n  }\n}\n\nconst euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);\nconst w = new StringWritable();\n\nw.write('currency: ');\nw.write(euro[0]);\nw.end(euro[1]);\n\nconsole.log(w.data); // currency: €\n
      ", + "type": "module", + "displayName": "Decoding buffers in a writable stream" + } + ], + "type": "misc", + "displayName": "Implementing a writable stream" + }, + { + "textRaw": "Implementing a readable stream", + "name": "implementing_a_readable_stream", + "desc": "

      The stream.Readable class is extended to implement a Readable stream.

      \n

      Custom Readable streams must call the new stream.Readable([options])\nconstructor and implement the readable._read() method.

      ", + "ctors": [ + { + "textRaw": "`new stream.Readable([options])`", + "type": "ctor", + "name": "stream.Readable", + "meta": { + "changes": [ + { + "version": "v11.2.0", + "pr-url": "https://github.com/nodejs/node/pull/22795", + "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource. **Default:** `16384` (16KB), or `16` for `objectMode` streams.", + "name": "highWaterMark", + "type": "number", + "default": "`16384` (16KB), or `16` for `objectMode` streams", + "desc": "The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource." + }, + { + "textRaw": "`encoding` {string} If specified, then buffers will be decoded to strings using the specified encoding. **Default:** `null`.", + "name": "encoding", + "type": "string", + "default": "`null`", + "desc": "If specified, then buffers will be decoded to strings using the specified encoding." + }, + { + "textRaw": "`objectMode` {boolean} Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`. **Default:** `false`.", + "name": "objectMode", + "type": "boolean", + "default": "`false`", + "desc": "Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`." + }, + { + "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", + "name": "emitClose", + "type": "boolean", + "default": "`true`", + "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." + }, + { + "textRaw": "`read` {Function} Implementation for the [`stream._read()`][stream-_read] method.", + "name": "read", + "type": "Function", + "desc": "Implementation for the [`stream._read()`][stream-_read] method." + }, + { + "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][readable-_destroy] method.", + "name": "destroy", + "type": "Function", + "desc": "Implementation for the [`stream._destroy()`][readable-_destroy] method." + }, + { + "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `false`.", + "name": "autoDestroy", + "type": "boolean", + "default": "`false`", + "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." + } + ] + } + ] + } + ], + "desc": "\n
      const { Readable } = require('stream');\n\nclass MyReadable extends Readable {\n  constructor(options) {\n    // Calls the stream.Readable(options) constructor.\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Readable } = require('stream');\nconst util = require('util');\n\nfunction MyReadable(options) {\n  if (!(this instanceof MyReadable))\n    return new MyReadable(options);\n  Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  }\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`readable._read(size)`", + "type": "method", + "name": "_read", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`size` {number} Number of bytes to read asynchronously", + "name": "size", + "type": "number", + "desc": "Number of bytes to read asynchronously" + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

      \n

      All Readable stream implementations must provide an implementation of the\nreadable._read() method to fetch data from the underlying resource.

      \n

      When readable._read() is called, if data is available from the resource,\nthe implementation should begin pushing that data into the read queue using the\nthis.push(dataChunk) method. _read() should continue reading\nfrom the resource and pushing data until readable.push() returns false. Only\nwhen _read() is called again after it has stopped should it resume pushing\nadditional data onto the queue.

      \n

      Once the readable._read() method has been called, it will not be called\nagain until more data is pushed through the readable.push()\nmethod. Empty data such as empty buffers and strings will not cause\nreadable._read() to be called.

      \n

      The size argument is advisory. For implementations where a \"read\" is a\nsingle operation that returns data can use the size argument to determine how\nmuch data to fetch. Other implementations may ignore this argument and simply\nprovide data whenever it becomes available. There is no need to \"wait\" until\nsize bytes are available before calling stream.push(chunk).

      \n

      The readable._read() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`readable._destroy(err, callback)`", + "type": "method", + "name": "_destroy", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`err` {Error} A possible error.", + "name": "err", + "type": "Error", + "desc": "A possible error." + }, + { + "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", + "name": "callback", + "type": "Function", + "desc": "A callback function that takes an optional error argument." + } + ] + } + ], + "desc": "

      The _destroy() method is called by readable.destroy().\nIt can be overridden by child classes but it must not be called directly.

      " + }, + { + "textRaw": "`readable.push(chunk[, encoding])`", + "type": "method", + "name": "push", + "meta": { + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11608", + "description": "The `chunk` argument can now be a `Uint8Array` instance." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if additional chunks of data may continue to be pushed; `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if additional chunks of data may continue to be pushed; `false` otherwise." + }, + "params": [ + { + "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value.", + "name": "chunk", + "type": "Buffer|Uint8Array|string|null|any", + "desc": "Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value." + }, + { + "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", + "name": "encoding", + "type": "string", + "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`." + } + ] + } + ], + "desc": "

      When chunk is a Buffer, Uint8Array or string, the chunk of data will\nbe added to the internal queue for users of the stream to consume.\nPassing chunk as null signals the end of the stream (EOF), after which no\nmore data can be written.

      \n

      When the Readable is operating in paused mode, the data added with\nreadable.push() can be read out by calling the\nreadable.read() method when the 'readable' event is\nemitted.

      \n

      When the Readable is operating in flowing mode, the data added with\nreadable.push() will be delivered by emitting a 'data' event.

      \n

      The readable.push() method is designed to be as flexible as possible. For\nexample, when wrapping a lower-level source that provides some form of\npause/resume mechanism, and a data callback, the low-level source can be wrapped\nby the custom Readable instance:

      \n
      // `_source` is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nclass SourceWrapper extends Readable {\n  constructor(options) {\n    super(options);\n\n    this._source = getLowLevelSourceObject();\n\n    // Every time there's data, push it into the internal buffer.\n    this._source.ondata = (chunk) => {\n      // If push() returns false, then stop reading from source.\n      if (!this.push(chunk))\n        this._source.readStop();\n    };\n\n    // When the source ends, push the EOF-signaling `null` chunk.\n    this._source.onend = () => {\n      this.push(null);\n    };\n  }\n  // _read() will be called when the stream wants to pull more data in.\n  // The advisory size argument is ignored in this case.\n  _read(size) {\n    this._source.readStart();\n  }\n}\n
      \n

      The readable.push() method is used to push the content\ninto the internal buffer. It can be driven by the readable._read() method.

      \n

      For streams not operating in object mode, if the chunk parameter of\nreadable.push() is undefined, it will be treated as empty string or\nbuffer. See readable.push('') for more information.

      " + } + ], + "modules": [ + { + "textRaw": "Errors while reading", + "name": "errors_while_reading", + "desc": "

      Errors occurring during processing of the readable._read() must be\npropagated through the readable.destroy(err) method.\nThrowing an Error from within readable._read() or manually emitting an\n'error' event results in undefined behavior.

      \n
      const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    const err = checkSomeErrorCondition();\n    if (err) {\n      this.destroy(err);\n    } else {\n      // Do some work.\n    }\n  }\n});\n
      ", + "type": "module", + "displayName": "Errors while reading" + } + ], + "examples": [ + { + "textRaw": "An example counting stream", + "name": "An example counting stream", + "type": "example", + "desc": "

      The following is a basic example of a Readable stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.

      \n
      const { Readable } = require('stream');\n\nclass Counter extends Readable {\n  constructor(opt) {\n    super(opt);\n    this._max = 1000000;\n    this._index = 1;\n  }\n\n  _read() {\n    const i = this._index++;\n    if (i > this._max)\n      this.push(null);\n    else {\n      const str = String(i);\n      const buf = Buffer.from(str, 'ascii');\n      this.push(buf);\n    }\n  }\n}\n
      " + } + ], + "type": "misc", + "displayName": "Implementing a readable stream" + }, + { + "textRaw": "Implementing a duplex stream", + "name": "implementing_a_duplex_stream", + "desc": "

      A Duplex stream is one that implements both Readable and\nWritable, such as a TCP socket connection.

      \n

      Because JavaScript does not have support for multiple inheritance, the\nstream.Duplex class is extended to implement a Duplex stream (as opposed\nto extending the stream.Readable and stream.Writable classes).

      \n

      The stream.Duplex class prototypically inherits from stream.Readable and\nparasitically from stream.Writable, but instanceof will work properly for\nboth base classes due to overriding Symbol.hasInstance on\nstream.Writable.

      \n

      Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.

      ", + "ctors": [ + { + "textRaw": "`new stream.Duplex(options)`", + "type": "ctor", + "name": "stream.Duplex", + "meta": { + "changes": [ + { + "version": "v8.4.0", + "pr-url": "https://github.com/nodejs/node/pull/14636", + "description": "The `readableHighWaterMark` and `writableHighWaterMark` options are supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "name": "options", + "type": "Object", + "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "options": [ + { + "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the stream will automatically end the writable side when the readable side ends. **Default:** `true`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`true`", + "desc": "If set to `false`, then the stream will automatically end the writable side when the readable side ends." + }, + { + "textRaw": "`readable` {boolean} Sets whether the `Duplex` should be readable. **Default:** `true`.", + "name": "readable", + "type": "boolean", + "default": "`true`", + "desc": "Sets whether the `Duplex` should be readable." + }, + { + "textRaw": "`writable` {boolean} Sets whether the `Duplex` should be writable. **Default:** `true`.", + "name": "writable", + "type": "boolean", + "default": "`true`", + "desc": "Sets whether the `Duplex` should be writable." + }, + { + "textRaw": "`readableObjectMode` {boolean} Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", + "name": "readableObjectMode", + "type": "boolean", + "default": "`false`", + "desc": "Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." + }, + { + "textRaw": "`writableObjectMode` {boolean} Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", + "name": "writableObjectMode", + "type": "boolean", + "default": "`false`", + "desc": "Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`." + }, + { + "textRaw": "`readableHighWaterMark` {number} Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided.", + "name": "readableHighWaterMark", + "type": "number", + "desc": "Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided." + }, + { + "textRaw": "`writableHighWaterMark` {number} Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided.", + "name": "writableHighWaterMark", + "type": "number", + "desc": "Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided." + } + ] + } + ] + } + ], + "desc": "\n
      const { Duplex } = require('stream');\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Duplex } = require('stream');\nconst util = require('util');\n\nfunction MyDuplex(options) {\n  if (!(this instanceof MyDuplex))\n    return new MyDuplex(options);\n  Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Duplex } = require('stream');\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
      " + } + ], + "modules": [ + { + "textRaw": "An example duplex stream", + "name": "an_example_duplex_stream", + "desc": "

      The following illustrates a simple example of a Duplex stream that wraps a\nhypothetical lower-level source object to which data can be written, and\nfrom which data can be read, albeit using an API that is not compatible with\nNode.js streams.\nThe following illustrates a simple example of a Duplex stream that buffers\nincoming written data via the Writable interface that is read back out\nvia the Readable interface.

      \n
      const { Duplex } = require('stream');\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n  constructor(source, options) {\n    super(options);\n    this[kSource] = source;\n  }\n\n  _write(chunk, encoding, callback) {\n    // The underlying source only deals with strings.\n    if (Buffer.isBuffer(chunk))\n      chunk = chunk.toString();\n    this[kSource].writeSomeData(chunk);\n    callback();\n  }\n\n  _read(size) {\n    this[kSource].fetchSomeData(size, (data, encoding) => {\n      this.push(Buffer.from(data, encoding));\n    });\n  }\n}\n
      \n

      The most important aspect of a Duplex stream is that the Readable and\nWritable sides operate independently of one another despite co-existing within\na single object instance.

      ", + "type": "module", + "displayName": "An example duplex stream" + }, + { + "textRaw": "Object mode duplex streams", + "name": "object_mode_duplex_streams", + "desc": "

      For Duplex streams, objectMode can be set exclusively for either the\nReadable or Writable side using the readableObjectMode and\nwritableObjectMode options respectively.

      \n

      In the following example, for instance, a new Transform stream (which is a\ntype of Duplex stream) is created that has an object mode Writable side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe Readable side.

      \n
      const { Transform } = require('stream');\n\n// All Transform streams are also Duplex Streams.\nconst myTransform = new Transform({\n  writableObjectMode: true,\n\n  transform(chunk, encoding, callback) {\n    // Coerce the chunk to a number if necessary.\n    chunk |= 0;\n\n    // Transform the chunk into something else.\n    const data = chunk.toString(16);\n\n    // Push the data onto the readable queue.\n    callback(null, '0'.repeat(data.length % 2) + data);\n  }\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n
      ", + "type": "module", + "displayName": "Object mode duplex streams" + } + ], + "type": "misc", + "displayName": "Implementing a duplex stream" + }, + { + "textRaw": "Implementing a transform stream", + "name": "implementing_a_transform_stream", + "desc": "

      A Transform stream is a Duplex stream where the output is computed\nin some way from the input. Examples include zlib streams or crypto\nstreams that compress, encrypt, or decrypt data.

      \n

      There is no requirement that the output be the same size as the input, the same\nnumber of chunks, or arrive at the same time. For example, a Hash stream will\nonly ever have a single chunk of output which is provided when the input is\nended. A zlib stream will produce output that is either much smaller or much\nlarger than its input.

      \n

      The stream.Transform class is extended to implement a Transform stream.

      \n

      The stream.Transform class prototypically inherits from stream.Duplex and\nimplements its own versions of the writable._write() and\nreadable._read() methods. Custom Transform implementations must\nimplement the transform._transform() method and may\nalso implement the transform._flush() method.

      \n

      Care must be taken when using Transform streams in that data written to the\nstream can cause the Writable side of the stream to become paused if the\noutput on the Readable side is not consumed.

      ", + "ctors": [ + { + "textRaw": "`new stream.Transform([options])`", + "type": "ctor", + "name": "stream.Transform", + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "name": "options", + "type": "Object", + "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", + "options": [ + { + "textRaw": "`transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method.", + "name": "transform", + "type": "Function", + "desc": "Implementation for the [`stream._transform()`][stream-_transform] method." + }, + { + "textRaw": "`flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] method.", + "name": "flush", + "type": "Function", + "desc": "Implementation for the [`stream._flush()`][stream-_flush] method." + } + ] + } + ] + } + ], + "desc": "\n
      const { Transform } = require('stream');\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
      \n

      Or, when using pre-ES6 style constructors:

      \n
      const { Transform } = require('stream');\nconst util = require('util');\n\nfunction MyTransform(options) {\n  if (!(this instanceof MyTransform))\n    return new MyTransform(options);\n  Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n
      \n

      Or, using the simplified constructor approach:

      \n
      const { Transform } = require('stream');\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  }\n});\n
      " + } + ], + "modules": [ + { + "textRaw": "Events: `'finish'` and `'end'`", + "name": "events:_`'finish'`_and_`'end'`", + "desc": "

      The 'finish' and 'end' events are from the stream.Writable\nand stream.Readable classes, respectively. The 'finish' event is emitted\nafter stream.end() is called and all chunks have been processed\nby stream._transform(). The 'end' event is emitted\nafter all data has been output, which occurs after the callback in\ntransform._flush() has been called.

      ", + "type": "module", + "displayName": "Events: `'finish'` and `'end'`" + } + ], + "methods": [ + { + "textRaw": "`transform._flush(callback)`", + "type": "method", + "name": "_flush", + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.", + "name": "callback", + "type": "Function", + "desc": "A callback function (optionally with an error argument and data) to be called when remaining data has been flushed." + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

      \n

      In some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a zlib compression stream will\nstore an amount of internal state used to optimally compress the output. When\nthe stream ends, however, that additional data needs to be flushed so that the\ncompressed data will be complete.

      \n

      Custom Transform implementations may implement the transform._flush()\nmethod. This will be called when there is no more written data to be consumed,\nbut before the 'end' event is emitted signaling the end of the\nReadable stream.

      \n

      Within the transform._flush() implementation, the transform.push() method\nmay be called zero or more times, as appropriate. The callback function must\nbe called when the flush operation is complete.

      \n

      The transform._flush() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

      " + }, + { + "textRaw": "`transform._transform(chunk, encoding, callback)`", + "type": "method", + "name": "_transform", + "signatures": [ + { + "params": [ + { + "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", + "name": "chunk", + "type": "Buffer|string|any", + "desc": "The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." + }, + { + "textRaw": "`encoding` {string} If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case.", + "name": "encoding", + "type": "string", + "desc": "If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case." + }, + { + "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed.", + "name": "callback", + "type": "Function", + "desc": "A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed." + } + ] + } + ], + "desc": "

      This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

      \n

      All Transform stream implementations must provide a _transform()\nmethod to accept input and produce output. The transform._transform()\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the transform.push() method.

      \n

      The transform.push() method may be called zero or more times to generate\noutput from a single input chunk, depending on how much is to be output\nas a result of the chunk.

      \n

      It is possible that no output is generated from any given chunk of input data.

      \n

      The callback function must be called only when the current chunk is completely\nconsumed. The first argument passed to the callback must be an Error object\nif an error occurred while processing the input or null otherwise. If a second\nargument is passed to the callback, it will be forwarded on to the\ntransform.push() method. In other words, the following are equivalent:

      \n
      transform.prototype._transform = function(data, encoding, callback) {\n  this.push(data);\n  callback();\n};\n\ntransform.prototype._transform = function(data, encoding, callback) {\n  callback(null, data);\n};\n
      \n

      The transform._transform() method is prefixed with an underscore because it\nis internal to the class that defines it, and should never be called directly by\nuser programs.

      \n

      transform._transform() is never called in parallel; streams implement a\nqueue mechanism, and to receive the next chunk, callback must be\ncalled, either synchronously or asynchronously.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `stream.PassThrough`", + "type": "class", + "name": "stream.PassThrough", + "desc": "

      The stream.PassThrough class is a trivial implementation of a Transform\nstream that simply passes the input bytes across to the output. Its purpose is\nprimarily for examples and testing, but there are some use cases where\nstream.PassThrough is useful as a building block for novel sorts of streams.

      " + } + ], + "type": "misc", + "displayName": "Implementing a transform stream" + } + ] + }, + { + "textRaw": "Additional notes", + "name": "Additional notes", + "type": "misc", + "miscs": [ + { + "textRaw": "Streams compatibility with async generators and async iterators", + "name": "streams_compatibility_with_async_generators_and_async_iterators", + "desc": "

      With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.

      \n

      Some common interop cases of using Node.js streams with async generators\nand async iterators are provided below.

      ", + "modules": [ + { + "textRaw": "Consuming readable streams with async iterators", + "name": "consuming_readable_streams_with_async_iterators", + "desc": "
      (async function() {\n  for await (const chunk of readable) {\n    console.log(chunk);\n  }\n})();\n
      \n

      Async iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.

      ", + "type": "module", + "displayName": "Consuming readable streams with async iterators" + }, + { + "textRaw": "Creating readable streams with async generators", + "name": "creating_readable_streams_with_async_generators", + "desc": "

      We can construct a Node.js readable stream from an asynchronous generator\nusing the Readable.from() utility method:

      \n
      const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'a';\n  yield 'b';\n  yield 'c';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
      ", + "type": "module", + "displayName": "Creating readable streams with async generators" + } + ], + "miscs": [ + { + "textRaw": "Piping to writable streams from async iterators", + "name": "Piping to writable streams from async iterators", + "type": "misc", + "desc": "

      In the scenario of writing to a writable stream from an async iterator, ensure\nthe correct handling of backpressure and errors.

      \n
      const { once } = require('events');\nconst finished = util.promisify(stream.finished);\n\nconst writable = fs.createWriteStream('./file');\n\nfunction drain(writable) {\n  if (writable.destroyed) {\n    return Promise.reject(new Error('premature close'));\n  }\n  return Promise.race([\n    once(writable, 'drain'),\n    once(writable, 'close')\n      .then(() => Promise.reject(new Error('premature close')))\n  ]);\n}\n\nasync function pump(iterable, writable) {\n  for await (const chunk of iterable) {\n    // Handle backpressure on write().\n    if (!writable.write(chunk)) {\n      await drain(writable);\n    }\n  }\n  writable.end();\n}\n\n(async function() {\n  // Ensure completion without errors.\n  await Promise.all([\n    pump(iterable, writable),\n    finished(writable)\n  ]);\n})();\n
      \n

      In the above, errors on write() would be caught and thrown by the\nonce() listener for the 'drain' event, since once() will also handle the\n'error' event. To ensure completion of the write stream without errors,\nit is safer to use the finished() method as above, instead of using the\nonce() listener for the 'finish' event. Under certain cases, an 'error'\nevent could be emitted by the writable stream after 'finish' and as once()\nwill release the 'error' handler on handling the 'finish' event, it could\nresult in an unhandled error.

      \n

      Alternatively, the readable stream could be wrapped with Readable.from() and\nthen piped via .pipe():

      \n
      const finished = util.promisify(stream.finished);\n\nconst writable = fs.createWriteStream('./file');\n\n(async function() {\n  const readable = Readable.from(iterable);\n  readable.pipe(writable);\n  // Ensure completion without errors.\n  await finished(writable);\n})();\n
      \n

      Or, using stream.pipeline() to pipe streams:

      \n
      const pipeline = util.promisify(stream.pipeline);\n\nconst writable = fs.createWriteStream('./file');\n\n(async function() {\n  const readable = Readable.from(iterable);\n  await pipeline(readable, writable);\n})();\n
      " + } + ], + "type": "misc", + "displayName": "Streams compatibility with async generators and async iterators" + }, + { + "textRaw": "Compatibility with older Node.js versions", + "name": "Compatibility with older Node.js versions", + "type": "misc", + "desc": "

      Prior to Node.js 0.10, the Readable stream interface was simpler, but also\nless powerful and less useful.

      \n
        \n
      • Rather than waiting for calls to the stream.read() method,\n'data' events would begin emitting immediately. Applications that\nwould need to perform some amount of work to decide how to handle data\nwere required to store read data into buffers so the data would not be lost.
      • \n
      • The stream.pause() method was advisory, rather than\nguaranteed. This meant that it was still necessary to be prepared to receive\n'data' events even when the stream was in a paused state.
      • \n
      \n

      In Node.js 0.10, the Readable class was added. For backward\ncompatibility with older Node.js programs, Readable streams switch into\n\"flowing mode\" when a 'data' event handler is added, or when the\nstream.resume() method is called. The effect is that, even\nwhen not using the new stream.read() method and\n'readable' event, it is no longer necessary to worry about losing\n'data' chunks.

      \n

      While most applications will continue to function normally, this introduces an\nedge case in the following conditions:

      \n
        \n
      • No 'data' event listener is added.
      • \n
      • The stream.resume() method is never called.
      • \n
      • The stream is not piped to any writable destination.
      • \n
      \n

      For example, consider the following code:

      \n
      // WARNING!  BROKEN!\nnet.createServer((socket) => {\n\n  // We add an 'end' listener, but never consume the data.\n  socket.on('end', () => {\n    // It will never get here.\n    socket.end('The message was received but was not processed.\\n');\n  });\n\n}).listen(1337);\n
      \n

      Prior to Node.js 0.10, the incoming message data would be simply discarded.\nHowever, in Node.js 0.10 and beyond, the socket remains paused forever.

      \n

      The workaround in this situation is to call the\nstream.resume() method to begin the flow of data:

      \n
      // Workaround.\nnet.createServer((socket) => {\n  socket.on('end', () => {\n    socket.end('The message was received but was not processed.\\n');\n  });\n\n  // Start the flow of data, discarding it.\n  socket.resume();\n}).listen(1337);\n
      \n

      In addition to new Readable streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap() method.

      " + }, + { + "textRaw": "`highWaterMark` discrepancy after calling `readable.setEncoding()`", + "name": "`highwatermark`_discrepancy_after_calling_`readable.setencoding()`", + "desc": "

      The use of readable.setEncoding() will change the behavior of how the\nhighWaterMark operates in non-object mode.

      \n

      Typically, the size of the current buffer is measured against the\nhighWaterMark in bytes. However, after setEncoding() is called, the\ncomparison function will begin to measure the buffer's size in characters.

      \n

      This is not a problem in common cases with latin1 or ascii. But it is\nadvised to be mindful about this behavior when working with strings that could\ncontain multi-byte characters.

      ", + "type": "misc", + "displayName": "`highWaterMark` discrepancy after calling `readable.setEncoding()`" + } + ], + "methods": [ + { + "textRaw": "`readable.read(0)`", + "type": "method", + "name": "read", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.

      \n

      If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.

      \n

      While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.

      " + }, + { + "textRaw": "`readable.push('')`", + "type": "method", + "name": "push", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Use of readable.push('') is not recommended.

      \n

      Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.

      " + } + ] + } + ], + "type": "module", + "displayName": "Stream" + } + ] +} \ No newline at end of file diff --git a/doc/api/string_decoder.html b/doc/api/string_decoder.html new file mode 100644 index 0000000000000000000000000000000000000000..34825b56dfe0cae361557ad1d4b849ebb9dcde9b --- /dev/null +++ b/doc/api/string_decoder.html @@ -0,0 +1,224 @@ + + + + + + + String decoder | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      String decoder#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/string_decoder.js

      +

      The string_decoder module provides an API for decoding Buffer objects into +strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 +characters. It can be accessed using:

      +
      const { StringDecoder } = require('string_decoder');
      +

      The following example shows the basic use of the StringDecoder class.

      +
      const { StringDecoder } = require('string_decoder');
      +const decoder = new StringDecoder('utf8');
      +
      +const cent = Buffer.from([0xC2, 0xA2]);
      +console.log(decoder.write(cent));
      +
      +const euro = Buffer.from([0xE2, 0x82, 0xAC]);
      +console.log(decoder.write(euro));
      +

      When a Buffer instance is written to the StringDecoder instance, an +internal buffer is used to ensure that the decoded string does not contain +any incomplete multibyte characters. These are held in the buffer until the +next call to stringDecoder.write() or until stringDecoder.end() is called.

      +

      In the following example, the three UTF-8 encoded bytes of the European Euro +symbol (€) are written over three separate operations:

      +
      const { StringDecoder } = require('string_decoder');
      +const decoder = new StringDecoder('utf8');
      +
      +decoder.write(Buffer.from([0xE2]));
      +decoder.write(Buffer.from([0x82]));
      +console.log(decoder.end(Buffer.from([0xAC])));
      +

      Class: StringDecoder#

      +

      new StringDecoder([encoding])#

      + +
        +
      • encoding <string> The character encoding the StringDecoder will use. +Default: 'utf8'.
      • +
      +

      Creates a new StringDecoder instance.

      +

      stringDecoder.end([buffer])#

      + + +

      Returns any remaining input stored in the internal buffer as a string. Bytes +representing incomplete UTF-8 and UTF-16 characters will be replaced with +substitution characters appropriate for the character encoding.

      +

      If the buffer argument is provided, one final call to stringDecoder.write() +is performed before returning the remaining input.

      +

      stringDecoder.write(buffer)#

      + + +

      Returns a decoded string, ensuring that any incomplete multibyte characters at +the end of the Buffer, or TypedArray, or DataView are omitted from the +returned string and stored in an internal buffer for the next call to +stringDecoder.write() or stringDecoder.end().

      + +
      +
      +
      + + diff --git a/doc/api/string_decoder.json b/doc/api/string_decoder.json new file mode 100644 index 0000000000000000000000000000000000000000..425b48ca1eb73b8b21ff420598d18a1b629b3664 --- /dev/null +++ b/doc/api/string_decoder.json @@ -0,0 +1,103 @@ +{ + "type": "module", + "source": "doc/api/string_decoder.md", + "modules": [ + { + "textRaw": "String decoder", + "name": "string_decoder", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/string_decoder.js

      \n

      The string_decoder module provides an API for decoding Buffer objects into\nstrings in a manner that preserves encoded multi-byte UTF-8 and UTF-16\ncharacters. It can be accessed using:

      \n
      const { StringDecoder } = require('string_decoder');\n
      \n

      The following example shows the basic use of the StringDecoder class.

      \n
      const { StringDecoder } = require('string_decoder');\nconst decoder = new StringDecoder('utf8');\n\nconst cent = Buffer.from([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nconst euro = Buffer.from([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));\n
      \n

      When a Buffer instance is written to the StringDecoder instance, an\ninternal buffer is used to ensure that the decoded string does not contain\nany incomplete multibyte characters. These are held in the buffer until the\nnext call to stringDecoder.write() or until stringDecoder.end() is called.

      \n

      In the following example, the three UTF-8 encoded bytes of the European Euro\nsymbol (€) are written over three separate operations:

      \n
      const { StringDecoder } = require('string_decoder');\nconst decoder = new StringDecoder('utf8');\n\ndecoder.write(Buffer.from([0xE2]));\ndecoder.write(Buffer.from([0x82]));\nconsole.log(decoder.end(Buffer.from([0xAC])));\n
      ", + "classes": [ + { + "textRaw": "Class: `StringDecoder`", + "type": "class", + "name": "StringDecoder", + "methods": [ + { + "textRaw": "`stringDecoder.end([buffer])`", + "type": "method", + "name": "end", + "meta": { + "added": [ + "v0.9.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode." + } + ] + } + ], + "desc": "

      Returns any remaining input stored in the internal buffer as a string. Bytes\nrepresenting incomplete UTF-8 and UTF-16 characters will be replaced with\nsubstitution characters appropriate for the character encoding.

      \n

      If the buffer argument is provided, one final call to stringDecoder.write()\nis performed before returning the remaining input.

      " + }, + { + "textRaw": "`stringDecoder.write(buffer)`", + "type": "method", + "name": "write", + "meta": { + "added": [ + "v0.1.99" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/9618", + "description": "Each invalid character is now replaced by a single replacement character instead of one for each individual byte." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode." + } + ] + } + ], + "desc": "

      Returns a decoded string, ensuring that any incomplete multibyte characters at\nthe end of the Buffer, or TypedArray, or DataView are omitted from the\nreturned string and stored in an internal buffer for the next call to\nstringDecoder.write() or stringDecoder.end().

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`encoding` {string} The character [encoding][] the `StringDecoder` will use. **Default:** `'utf8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf8'`", + "desc": "The character [encoding][] the `StringDecoder` will use." + } + ], + "desc": "

      Creates a new StringDecoder instance.

      " + } + ] + } + ], + "type": "module", + "displayName": "String decoder" + } + ] +} \ No newline at end of file diff --git a/doc/api/synopsis.html b/doc/api/synopsis.html new file mode 100644 index 0000000000000000000000000000000000000000..a16f33a46f4fd6c431fd249909a99a2575b78dde --- /dev/null +++ b/doc/api/synopsis.html @@ -0,0 +1,196 @@ + + + + + + + Usage and example | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Usage and example#

      +

      Usage#

      + + +

      node [options] [V8 options] [script.js | -e "script" | - ] [arguments]

      +

      Please see the Command Line Options document for more information.

      +

      Example#

      +

      An example of a web server written with Node.js which responds with +'Hello, World!':

      +

      Commands in this document start with $ or > to replicate how they would +appear in a user's terminal. Do not include the $ and > characters. They are +there to show the start of each command.

      +

      Lines that don’t start with $ or > character show the output of the previous +command.

      +

      First, make sure to have downloaded and installed Node.js. See this guide +for further install information.

      +

      Now, create an empty project folder called projects, then navigate into it.

      +

      Linux and Mac:

      +
      $ mkdir ~/projects
      +$ cd ~/projects
      +

      Windows CMD:

      +
      > mkdir %USERPROFILE%\projects
      +> cd %USERPROFILE%\projects
      +

      Windows PowerShell:

      +
      > mkdir $env:USERPROFILE\projects
      +> cd $env:USERPROFILE\projects
      +

      Next, create a new source file in the projects +folder and call it hello-world.js.

      +

      Open hello-world.js in any preferred text editor and +paste in the following content:

      +
      const http = require('http');
      +
      +const hostname = '127.0.0.1';
      +const port = 3000;
      +
      +const server = http.createServer((req, res) => {
      +  res.statusCode = 200;
      +  res.setHeader('Content-Type', 'text/plain');
      +  res.end('Hello, World!\n');
      +});
      +
      +server.listen(port, hostname, () => {
      +  console.log(`Server running at http://${hostname}:${port}/`);
      +});
      +

      Save the file, go back to the terminal window, and enter the following command:

      +
      $ node hello-world.js
      +

      Output like this should appear in the terminal:

      +
      Server running at http://127.0.0.1:3000/
      +

      Now, open any preferred web browser and visit http://127.0.0.1:3000.

      +

      If the browser displays the string Hello, World!, that indicates +the server is working.

      + +
      +
      +
      + + diff --git a/doc/api/synopsis.json b/doc/api/synopsis.json new file mode 100644 index 0000000000000000000000000000000000000000..ce0d7b631595e3b3fde035b66fe9fbeb3191fb65 --- /dev/null +++ b/doc/api/synopsis.json @@ -0,0 +1,22 @@ +{ + "type": "module", + "source": "doc/api/synopsis.md", + "modules": [ + { + "textRaw": "Usage and example", + "name": "usage_and_example", + "introduced_in": "v0.10.0", + "miscs": [ + { + "textRaw": "Usage", + "name": "Usage", + "introduced_in": "v0.10.0", + "type": "misc", + "desc": "

      node [options] [V8 options] [script.js | -e \"script\" | - ] [arguments]

      \n

      Please see the Command Line Options document for more information.

      \n

      Example

      \n

      An example of a web server written with Node.js which responds with\n'Hello, World!':

      \n

      Commands in this document start with $ or > to replicate how they would\nappear in a user's terminal. Do not include the $ and > characters. They are\nthere to show the start of each command.

      \n

      Lines that don’t start with $ or > character show the output of the previous\ncommand.

      \n

      First, make sure to have downloaded and installed Node.js. See this guide\nfor further install information.

      \n

      Now, create an empty project folder called projects, then navigate into it.

      \n

      Linux and Mac:

      \n
      $ mkdir ~/projects\n$ cd ~/projects\n
      \n

      Windows CMD:

      \n
      > mkdir %USERPROFILE%\\projects\n> cd %USERPROFILE%\\projects\n
      \n

      Windows PowerShell:

      \n
      > mkdir $env:USERPROFILE\\projects\n> cd $env:USERPROFILE\\projects\n
      \n

      Next, create a new source file in the projects\nfolder and call it hello-world.js.

      \n

      Open hello-world.js in any preferred text editor and\npaste in the following content:

      \n
      const http = require('http');\n\nconst hostname = '127.0.0.1';\nconst port = 3000;\n\nconst server = http.createServer((req, res) => {\n  res.statusCode = 200;\n  res.setHeader('Content-Type', 'text/plain');\n  res.end('Hello, World!\\n');\n});\n\nserver.listen(port, hostname, () => {\n  console.log(`Server running at http://${hostname}:${port}/`);\n});\n
      \n

      Save the file, go back to the terminal window, and enter the following command:

      \n
      $ node hello-world.js\n
      \n

      Output like this should appear in the terminal:

      \n
      Server running at http://127.0.0.1:3000/\n
      \n

      Now, open any preferred web browser and visit http://127.0.0.1:3000.

      \n

      If the browser displays the string Hello, World!, that indicates\nthe server is working.

      " + } + ], + "type": "module", + "displayName": "Usage and example" + } + ] +} \ No newline at end of file diff --git a/doc/api/timers.html b/doc/api/timers.html new file mode 100644 index 0000000000000000000000000000000000000000..82edc4f2dfbc9e6fa3fbe7788e7f2b57ec83d2d9 --- /dev/null +++ b/doc/api/timers.html @@ -0,0 +1,404 @@ + + + + + + + Timers | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Timers#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/timers.js

      +

      The timer module exposes a global API for scheduling functions to +be called at some future period of time. Because the timer functions are +globals, there is no need to call require('timers') to use the API.

      +

      The timer functions within Node.js implement a similar API as the timers API +provided by Web Browsers but use a different internal implementation that is +built around the Node.js Event Loop.

      +

      Class: Immediate#

      +

      This object is created internally and is returned from setImmediate(). It +can be passed to clearImmediate() in order to cancel the scheduled +actions.

      +

      By default, when an immediate is scheduled, the Node.js event loop will continue +running as long as the immediate is active. The Immediate object returned by +setImmediate() exports both immediate.ref() and immediate.unref() +functions that can be used to control this default behavior.

      +

      immediate.hasRef()#

      + + +

      If true, the Immediate object will keep the Node.js event loop active.

      +

      immediate.ref()#

      + + +

      When called, requests that the Node.js event loop not exit so long as the +Immediate is active. Calling immediate.ref() multiple times will have no +effect.

      +

      By default, all Immediate objects are "ref'ed", making it normally unnecessary +to call immediate.ref() unless immediate.unref() had been called previously.

      +

      immediate.unref()#

      + + +

      When called, the active Immediate object will not require the Node.js event +loop to remain active. If there is no other activity keeping the event loop +running, the process may exit before the Immediate object's callback is +invoked. Calling immediate.unref() multiple times will have no effect.

      +

      Class: Timeout#

      +

      This object is created internally and is returned from setTimeout() and +setInterval(). It can be passed to either clearTimeout() or +clearInterval() in order to cancel the scheduled actions.

      +

      By default, when a timer is scheduled using either setTimeout() or +setInterval(), the Node.js event loop will continue running as long as the +timer is active. Each of the Timeout objects returned by these functions +export both timeout.ref() and timeout.unref() functions that can be used to +control this default behavior.

      +

      timeout.hasRef()#

      + + +

      If true, the Timeout object will keep the Node.js event loop active.

      +

      timeout.ref()#

      + +
        +
      • Returns: <Timeout> a reference to timeout
      • +
      +

      When called, requests that the Node.js event loop not exit so long as the +Timeout is active. Calling timeout.ref() multiple times will have no effect.

      +

      By default, all Timeout objects are "ref'ed", making it normally unnecessary +to call timeout.ref() unless timeout.unref() had been called previously.

      +

      timeout.refresh()#

      + +
        +
      • Returns: <Timeout> a reference to timeout
      • +
      +

      Sets the timer's start time to the current time, and reschedules the timer to +call its callback at the previously specified duration adjusted to the current +time. This is useful for refreshing a timer without allocating a new +JavaScript object.

      +

      Using this on a timer that has already called its callback will reactivate the +timer.

      +

      timeout.unref()#

      + +
        +
      • Returns: <Timeout> a reference to timeout
      • +
      +

      When called, the active Timeout object will not require the Node.js event loop +to remain active. If there is no other activity keeping the event loop running, +the process may exit before the Timeout object's callback is invoked. Calling +timeout.unref() multiple times will have no effect.

      +

      Calling timeout.unref() creates an internal timer that will wake the Node.js +event loop. Creating too many of these can adversely impact performance +of the Node.js application.

      +

      timeout[Symbol.toPrimitive]()#

      + +
        +
      • Returns: <integer> a number that can be used to reference this timeout
      • +
      +

      Coerce a Timeout to a primitive. The primitive can be used to +clear the Timeout. The primitive can only be used in the +same thread where the timeout was created. Therefore, to use it +across worker_threads it must first be passed to the correct +thread. This allows enhanced compatibility with browser +setTimeout() and setInterval() implementations.

      +

      Scheduling timers#

      +

      A timer in Node.js is an internal construct that calls a given function after +a certain period of time. When a timer's function is called varies depending on +which method was used to create the timer and what other work the Node.js +event loop is doing.

      +

      setImmediate(callback[, ...args])#

      + + +

      Schedules the "immediate" execution of the callback after I/O events' +callbacks.

      +

      When multiple calls to setImmediate() are made, the callback functions are +queued for execution in the order in which they are created. The entire callback +queue is processed every event loop iteration. If an immediate timer is queued +from inside an executing callback, that timer will not be triggered until the +next event loop iteration.

      +

      If callback is not a function, a TypeError will be thrown.

      +

      This method has a custom variant for promises that is available using +util.promisify():

      +
      const util = require('util');
      +const setImmediatePromise = util.promisify(setImmediate);
      +
      +setImmediatePromise('foobar').then((value) => {
      +  // value === 'foobar' (passing values is optional)
      +  // This is executed after all I/O callbacks.
      +});
      +
      +// Or with async function
      +async function timerExample() {
      +  console.log('Before I/O callbacks');
      +  await setImmediatePromise();
      +  console.log('After I/O callbacks');
      +}
      +timerExample();
      +

      setInterval(callback, delay[, ...args])#

      + +
        +
      • callback <Function> The function to call when the timer elapses.
      • +
      • delay <number> The number of milliseconds to wait before calling the +callback.
      • +
      • ...args <any> Optional arguments to pass when the callback is called.
      • +
      • Returns: <Timeout> for use with clearInterval()
      • +
      +

      Schedules repeated execution of callback every delay milliseconds.

      +

      When delay is larger than 2147483647 or less than 1, the delay will be +set to 1. Non-integer delays are truncated to an integer.

      +

      If callback is not a function, a TypeError will be thrown.

      +

      setTimeout(callback, delay[, ...args])#

      + +
        +
      • callback <Function> The function to call when the timer elapses.
      • +
      • delay <number> The number of milliseconds to wait before calling the +callback.
      • +
      • ...args <any> Optional arguments to pass when the callback is called.
      • +
      • Returns: <Timeout> for use with clearTimeout()
      • +
      +

      Schedules execution of a one-time callback after delay milliseconds.

      +

      The callback will likely not be invoked in precisely delay milliseconds. +Node.js makes no guarantees about the exact timing of when callbacks will fire, +nor of their ordering. The callback will be called as close as possible to the +time specified.

      +

      When delay is larger than 2147483647 or less than 1, the delay +will be set to 1. Non-integer delays are truncated to an integer.

      +

      If callback is not a function, a TypeError will be thrown.

      +

      This method has a custom variant for promises that is available using +util.promisify():

      +
      const util = require('util');
      +const setTimeoutPromise = util.promisify(setTimeout);
      +
      +setTimeoutPromise(40, 'foobar').then((value) => {
      +  // value === 'foobar' (passing values is optional)
      +  // This is executed after about 40 milliseconds.
      +});
      +

      Cancelling timers#

      +

      The setImmediate(), setInterval(), and setTimeout() methods +each return objects that represent the scheduled timers. These can be used to +cancel the timer and prevent it from triggering.

      +

      It is not possible to cancel timers that were created using the promisified +variants of setImmediate(), setTimeout().

      +

      clearImmediate(immediate)#

      + + +

      Cancels an Immediate object created by setImmediate().

      +

      clearInterval(timeout)#

      + + +

      Cancels a Timeout object created by setInterval().

      +

      clearTimeout(timeout)#

      + + +

      Cancels a Timeout object created by setTimeout().

      + +
      +
      +
      + + diff --git a/doc/api/timers.json b/doc/api/timers.json new file mode 100644 index 0000000000000000000000000000000000000000..49f50baef6a760543423956a3525c154caa20dcc --- /dev/null +++ b/doc/api/timers.json @@ -0,0 +1,428 @@ +{ + "type": "module", + "source": "doc/api/timers.md", + "modules": [ + { + "textRaw": "Timers", + "name": "timers", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/timers.js

      \n

      The timer module exposes a global API for scheduling functions to\nbe called at some future period of time. Because the timer functions are\nglobals, there is no need to call require('timers') to use the API.

      \n

      The timer functions within Node.js implement a similar API as the timers API\nprovided by Web Browsers but use a different internal implementation that is\nbuilt around the Node.js Event Loop.

      ", + "classes": [ + { + "textRaw": "Class: `Immediate`", + "type": "class", + "name": "Immediate", + "desc": "

      This object is created internally and is returned from setImmediate(). It\ncan be passed to clearImmediate() in order to cancel the scheduled\nactions.

      \n

      By default, when an immediate is scheduled, the Node.js event loop will continue\nrunning as long as the immediate is active. The Immediate object returned by\nsetImmediate() exports both immediate.ref() and immediate.unref()\nfunctions that can be used to control this default behavior.

      ", + "methods": [ + { + "textRaw": "`immediate.hasRef()`", + "type": "method", + "name": "hasRef", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      If true, the Immediate object will keep the Node.js event loop active.

      " + }, + { + "textRaw": "`immediate.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v9.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Immediate} a reference to `immediate`", + "name": "return", + "type": "Immediate", + "desc": "a reference to `immediate`" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nImmediate is active. Calling immediate.ref() multiple times will have no\neffect.

      \n

      By default, all Immediate objects are \"ref'ed\", making it normally unnecessary\nto call immediate.ref() unless immediate.unref() had been called previously.

      " + }, + { + "textRaw": "`immediate.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v9.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Immediate} a reference to `immediate`", + "name": "return", + "type": "Immediate", + "desc": "a reference to `immediate`" + }, + "params": [] + } + ], + "desc": "

      When called, the active Immediate object will not require the Node.js event\nloop to remain active. If there is no other activity keeping the event loop\nrunning, the process may exit before the Immediate object's callback is\ninvoked. Calling immediate.unref() multiple times will have no effect.

      " + } + ] + }, + { + "textRaw": "Class: `Timeout`", + "type": "class", + "name": "Timeout", + "desc": "

      This object is created internally and is returned from setTimeout() and\nsetInterval(). It can be passed to either clearTimeout() or\nclearInterval() in order to cancel the scheduled actions.

      \n

      By default, when a timer is scheduled using either setTimeout() or\nsetInterval(), the Node.js event loop will continue running as long as the\ntimer is active. Each of the Timeout objects returned by these functions\nexport both timeout.ref() and timeout.unref() functions that can be used to\ncontrol this default behavior.

      ", + "methods": [ + { + "textRaw": "`timeout.hasRef()`", + "type": "method", + "name": "hasRef", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [] + } + ], + "desc": "

      If true, the Timeout object will keep the Node.js event loop active.

      " + }, + { + "textRaw": "`timeout.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} a reference to `timeout`", + "name": "return", + "type": "Timeout", + "desc": "a reference to `timeout`" + }, + "params": [] + } + ], + "desc": "

      When called, requests that the Node.js event loop not exit so long as the\nTimeout is active. Calling timeout.ref() multiple times will have no effect.

      \n

      By default, all Timeout objects are \"ref'ed\", making it normally unnecessary\nto call timeout.ref() unless timeout.unref() had been called previously.

      " + }, + { + "textRaw": "`timeout.refresh()`", + "type": "method", + "name": "refresh", + "meta": { + "added": [ + "v10.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} a reference to `timeout`", + "name": "return", + "type": "Timeout", + "desc": "a reference to `timeout`" + }, + "params": [] + } + ], + "desc": "

      Sets the timer's start time to the current time, and reschedules the timer to\ncall its callback at the previously specified duration adjusted to the current\ntime. This is useful for refreshing a timer without allocating a new\nJavaScript object.

      \n

      Using this on a timer that has already called its callback will reactivate the\ntimer.

      " + }, + { + "textRaw": "`timeout.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} a reference to `timeout`", + "name": "return", + "type": "Timeout", + "desc": "a reference to `timeout`" + }, + "params": [] + } + ], + "desc": "

      When called, the active Timeout object will not require the Node.js event loop\nto remain active. If there is no other activity keeping the event loop running,\nthe process may exit before the Timeout object's callback is invoked. Calling\ntimeout.unref() multiple times will have no effect.

      \n

      Calling timeout.unref() creates an internal timer that will wake the Node.js\nevent loop. Creating too many of these can adversely impact performance\nof the Node.js application.

      " + }, + { + "textRaw": "`timeout[Symbol.toPrimitive]()`", + "type": "method", + "name": "[Symbol.toPrimitive]", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer} a number that can be used to reference this `timeout`", + "name": "return", + "type": "integer", + "desc": "a number that can be used to reference this `timeout`" + }, + "params": [] + } + ], + "desc": "

      Coerce a Timeout to a primitive. The primitive can be used to\nclear the Timeout. The primitive can only be used in the\nsame thread where the timeout was created. Therefore, to use it\nacross worker_threads it must first be passed to the correct\nthread. This allows enhanced compatibility with browser\nsetTimeout() and setInterval() implementations.

      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Scheduling timers", + "name": "scheduling_timers", + "desc": "

      A timer in Node.js is an internal construct that calls a given function after\na certain period of time. When a timer's function is called varies depending on\nwhich method was used to create the timer and what other work the Node.js\nevent loop is doing.

      ", + "methods": [ + { + "textRaw": "`setImmediate(callback[, ...args])`", + "type": "method", + "name": "setImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Immediate} for use with [`clearImmediate()`][]", + "name": "return", + "type": "Immediate", + "desc": "for use with [`clearImmediate()`][]" + }, + "params": [ + { + "textRaw": "`callback` {Function} The function to call at the end of this turn of the Node.js [Event Loop][]", + "name": "callback", + "type": "Function", + "desc": "The function to call at the end of this turn of the Node.js [Event Loop][]" + }, + { + "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass when the `callback` is called." + } + ] + } + ], + "desc": "

      Schedules the \"immediate\" execution of the callback after I/O events'\ncallbacks.

      \n

      When multiple calls to setImmediate() are made, the callback functions are\nqueued for execution in the order in which they are created. The entire callback\nqueue is processed every event loop iteration. If an immediate timer is queued\nfrom inside an executing callback, that timer will not be triggered until the\nnext event loop iteration.

      \n

      If callback is not a function, a TypeError will be thrown.

      \n

      This method has a custom variant for promises that is available using\nutil.promisify():

      \n
      const util = require('util');\nconst setImmediatePromise = util.promisify(setImmediate);\n\nsetImmediatePromise('foobar').then((value) => {\n  // value === 'foobar' (passing values is optional)\n  // This is executed after all I/O callbacks.\n});\n\n// Or with async function\nasync function timerExample() {\n  console.log('Before I/O callbacks');\n  await setImmediatePromise();\n  console.log('After I/O callbacks');\n}\ntimerExample();\n
      " + }, + { + "textRaw": "`setInterval(callback, delay[, ...args])`", + "type": "method", + "name": "setInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} for use with [`clearInterval()`][]", + "name": "return", + "type": "Timeout", + "desc": "for use with [`clearInterval()`][]" + }, + "params": [ + { + "textRaw": "`callback` {Function} The function to call when the timer elapses.", + "name": "callback", + "type": "Function", + "desc": "The function to call when the timer elapses." + }, + { + "textRaw": "`delay` {number} The number of milliseconds to wait before calling the `callback`.", + "name": "delay", + "type": "number", + "desc": "The number of milliseconds to wait before calling the `callback`." + }, + { + "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass when the `callback` is called." + } + ] + } + ], + "desc": "

      Schedules repeated execution of callback every delay milliseconds.

      \n

      When delay is larger than 2147483647 or less than 1, the delay will be\nset to 1. Non-integer delays are truncated to an integer.

      \n

      If callback is not a function, a TypeError will be thrown.

      " + }, + { + "textRaw": "`setTimeout(callback, delay[, ...args])`", + "type": "method", + "name": "setTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Timeout} for use with [`clearTimeout()`][]", + "name": "return", + "type": "Timeout", + "desc": "for use with [`clearTimeout()`][]" + }, + "params": [ + { + "textRaw": "`callback` {Function} The function to call when the timer elapses.", + "name": "callback", + "type": "Function", + "desc": "The function to call when the timer elapses." + }, + { + "textRaw": "`delay` {number} The number of milliseconds to wait before calling the `callback`.", + "name": "delay", + "type": "number", + "desc": "The number of milliseconds to wait before calling the `callback`." + }, + { + "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", + "name": "...args", + "type": "any", + "desc": "Optional arguments to pass when the `callback` is called." + } + ] + } + ], + "desc": "

      Schedules execution of a one-time callback after delay milliseconds.

      \n

      The callback will likely not be invoked in precisely delay milliseconds.\nNode.js makes no guarantees about the exact timing of when callbacks will fire,\nnor of their ordering. The callback will be called as close as possible to the\ntime specified.

      \n

      When delay is larger than 2147483647 or less than 1, the delay\nwill be set to 1. Non-integer delays are truncated to an integer.

      \n

      If callback is not a function, a TypeError will be thrown.

      \n

      This method has a custom variant for promises that is available using\nutil.promisify():

      \n
      const util = require('util');\nconst setTimeoutPromise = util.promisify(setTimeout);\n\nsetTimeoutPromise(40, 'foobar').then((value) => {\n  // value === 'foobar' (passing values is optional)\n  // This is executed after about 40 milliseconds.\n});\n
      " + } + ], + "type": "module", + "displayName": "Scheduling timers" + }, + { + "textRaw": "Cancelling timers", + "name": "cancelling_timers", + "desc": "

      The setImmediate(), setInterval(), and setTimeout() methods\neach return objects that represent the scheduled timers. These can be used to\ncancel the timer and prevent it from triggering.

      \n

      It is not possible to cancel timers that were created using the promisified\nvariants of setImmediate(), setTimeout().

      ", + "methods": [ + { + "textRaw": "`clearImmediate(immediate)`", + "type": "method", + "name": "clearImmediate", + "meta": { + "added": [ + "v0.9.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`immediate` {Immediate} An `Immediate` object as returned by [`setImmediate()`][].", + "name": "immediate", + "type": "Immediate", + "desc": "An `Immediate` object as returned by [`setImmediate()`][]." + } + ] + } + ], + "desc": "

      Cancels an Immediate object created by setImmediate().

      " + }, + { + "textRaw": "`clearInterval(timeout)`", + "type": "method", + "name": "clearInterval", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`timeout` {Timeout} A `Timeout` object as returned by [`setInterval()`][].", + "name": "timeout", + "type": "Timeout", + "desc": "A `Timeout` object as returned by [`setInterval()`][]." + } + ] + } + ], + "desc": "

      Cancels a Timeout object created by setInterval().

      " + }, + { + "textRaw": "`clearTimeout(timeout)`", + "type": "method", + "name": "clearTimeout", + "meta": { + "added": [ + "v0.0.1" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`timeout` {Timeout} A `Timeout` object as returned by [`setTimeout()`][].", + "name": "timeout", + "type": "Timeout", + "desc": "A `Timeout` object as returned by [`setTimeout()`][]." + } + ] + } + ], + "desc": "

      Cancels a Timeout object created by setTimeout().

      " + } + ], + "type": "module", + "displayName": "Cancelling timers" + } + ], + "type": "module", + "displayName": "Timers" + } + ] +} \ No newline at end of file diff --git a/doc/api/tls.html b/doc/api/tls.html new file mode 100644 index 0000000000000000000000000000000000000000..3352477e5127da7bc940413997cffbb113075a9a --- /dev/null +++ b/doc/api/tls.html @@ -0,0 +1,1960 @@ + + + + + + + TLS (SSL) | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      TLS (SSL)#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/tls.js

      +

      The tls module provides an implementation of the Transport Layer Security +(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. +The module can be accessed using:

      +
      const tls = require('tls');
      +

      TLS/SSL concepts#

      +

      The TLS/SSL is a public/private key infrastructure (PKI). For most common +cases, each client and server must have a private key.

      +

      Private keys can be generated in multiple ways. The example below illustrates +use of the OpenSSL command-line interface to generate a 2048-bit RSA private +key:

      +
      openssl genrsa -out ryans-key.pem 2048
      +

      With TLS/SSL, all servers (and some clients) must have a certificate. +Certificates are public keys that correspond to a private key, and that are +digitally signed either by a Certificate Authority or by the owner of the +private key (such certificates are referred to as "self-signed"). The first +step to obtaining a certificate is to create a Certificate Signing Request +(CSR) file.

      +

      The OpenSSL command-line interface can be used to generate a CSR for a private +key:

      +
      openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
      +

      Once the CSR file is generated, it can either be sent to a Certificate +Authority for signing or used to generate a self-signed certificate.

      +

      Creating a self-signed certificate using the OpenSSL command-line interface +is illustrated in the example below:

      +
      openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
      +

      Once the certificate is generated, it can be used to generate a .pfx or +.p12 file:

      +
      openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \
      +      -certfile ca-cert.pem -out ryans.pfx
      +

      Where:

      +
        +
      • in: is the signed certificate
      • +
      • inkey: is the associated private key
      • +
      • certfile: is a concatenation of all Certificate Authority (CA) certs into +a single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
      • +
      +

      Perfect forward secrecy#

      + +

      The term forward secrecy or perfect forward secrecy describes a feature +of key-agreement (i.e., key-exchange) methods. That is, the server and client +keys are used to negotiate new temporary keys that are used specifically and +only for the current communication session. Practically, this means that even +if the server's private key is compromised, communication can only be decrypted +by eavesdroppers if the attacker manages to obtain the key-pair specifically +generated for the session.

      +

      Perfect forward secrecy is achieved by randomly generating a key pair for +key-agreement on every TLS/SSL handshake (in contrast to using the same key for +all sessions). Methods implementing this technique are called "ephemeral".

      +

      Currently two methods are commonly used to achieve perfect forward secrecy (note +the character "E" appended to the traditional abbreviations):

      +
        +
      • DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.
      • +
      • ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman +key-agreement protocol.
      • +
      +

      Ephemeral methods may have some performance drawbacks, because key generation +is expensive.

      +

      To use perfect forward secrecy using DHE with the tls module, it is required +to generate Diffie-Hellman parameters and specify them with the dhparam +option to tls.createSecureContext(). The following illustrates the use of +the OpenSSL command-line interface to generate such parameters:

      +
      openssl dhparam -outform PEM -out dhparam.pem 2048
      +

      If using perfect forward secrecy using ECDHE, Diffie-Hellman parameters are +not required and a default ECDHE curve will be used. The ecdhCurve property +can be used when creating a TLS Server to specify the list of names of supported +curves to use, see tls.createServer() for more info.

      +

      Perfect forward secrecy was optional up to TLSv1.2, but it is not optional for +TLSv1.3, because all TLSv1.3 cipher suites use ECDHE.

      +

      ALPN and SNI#

      + +

      ALPN (Application-Layer Protocol Negotiation Extension) and +SNI (Server Name Indication) are TLS handshake extensions:

      +
        +
      • ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)
      • +
      • SNI: Allows the use of one TLS server for multiple hostnames with different +SSL certificates.
      • +
      +

      Pre-shared keys#

      + +

      TLS-PSK support is available as an alternative to normal certificate-based +authentication. It uses a pre-shared key instead of certificates to +authenticate a TLS connection, providing mutual authentication. +TLS-PSK and public key infrastructure are not mutually exclusive. Clients and +servers can accommodate both, choosing either of them during the normal cipher +negotiation step.

      +

      TLS-PSK is only a good choice where means exist to securely share a +key with every connecting machine, so it does not replace PKI +(Public Key Infrastructure) for the majority of TLS uses. +The TLS-PSK implementation in OpenSSL has seen many security flaws in +recent years, mostly because it is used only by a minority of applications. +Please consider all alternative solutions before switching to PSK ciphers. +Upon generating PSK it is of critical importance to use sufficient entropy as +discussed in RFC 4086. Deriving a shared secret from a password or other +low-entropy sources is not secure.

      +

      PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly +specifying a cipher suite with the ciphers option. The list of available +ciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3 +ciphers are eligible for PSK but currently only those that use SHA256 digest are +supported they can be retrieved via openssl ciphers -v -s -tls1_3 -psk.

      +

      According to the RFC 4279, PSK identities up to 128 bytes in length and +PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0 +maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.

      +

      The current implementation doesn't support asynchronous PSK callbacks due to the +limitations of the underlying OpenSSL API.

      +

      Client-initiated renegotiation attack mitigation#

      + +

      The TLS protocol allows clients to renegotiate certain aspects of the TLS +session. Unfortunately, session renegotiation requires a disproportionate amount +of server-side resources, making it a potential vector for denial-of-service +attacks.

      +

      To mitigate the risk, renegotiation is limited to three times every ten minutes. +An 'error' event is emitted on the tls.TLSSocket instance when this +threshold is exceeded. The limits are configurable:

      +
        +
      • tls.CLIENT_RENEG_LIMIT <number> Specifies the number of renegotiation +requests. Default: 3.
      • +
      • tls.CLIENT_RENEG_WINDOW <number> Specifies the time renegotiation window +in seconds. Default: 600 (10 minutes).
      • +
      +

      The default renegotiation limits should not be modified without a full +understanding of the implications and risks.

      +

      TLSv1.3 does not support renegotiation.

      +

      Session resumption#

      +

      Establishing a TLS session can be relatively slow. The process can be sped +up by saving and later reusing the session state. There are several mechanisms +to do so, discussed here from oldest to newest (and preferred).

      +

      Session identifiers#

      +

      Servers generate a unique ID for new connections and +send it to the client. Clients and servers save the session state. When +reconnecting, clients send the ID of their saved session state and if the server +also has the state for that ID, it can agree to use it. Otherwise, the server +will create a new session. See RFC 2246 for more information, page 23 and +30.

      +

      Resumption using session identifiers is supported by most web browsers when +making HTTPS requests.

      +

      For Node.js, clients wait for the 'session' event to get the session data, +and provide the data to the session option of a subsequent tls.connect() +to reuse the session. Servers must +implement handlers for the 'newSession' and 'resumeSession' events +to save and restore the session data using the session ID as the lookup key to +reuse sessions. To reuse sessions across load balancers or cluster workers, +servers must use a shared session cache (such as Redis) in their session +handlers.

      +

      Session tickets#

      +

      The servers encrypt the entire session state and send it +to the client as a "ticket". When reconnecting, the state is sent to the server +in the initial connection. This mechanism avoids the need for server-side +session cache. If the server doesn't use the ticket, for any reason (failure +to decrypt it, it's too old, etc.), it will create a new session and send a new +ticket. See RFC 5077 for more information.

      +

      Resumption using session tickets is becoming commonly supported by many web +browsers when making HTTPS requests.

      +

      For Node.js, clients use the same APIs for resumption with session identifiers +as for resumption with session tickets. For debugging, if +tls.TLSSocket.getTLSTicket() returns a value, the session data contains a +ticket, otherwise it contains client-side session state.

      +

      With TLSv1.3, be aware that multiple tickets may be sent by the server, +resulting in multiple 'session' events, see 'session' for more +information.

      +

      Single process servers need no specific implementation to use session tickets. +To use session tickets across server restarts or load balancers, servers must +all have the same ticket keys. There are three 16-byte keys internally, but the +tls API exposes them as a single 48-byte buffer for convenience.

      +

      Its possible to get the ticket keys by calling server.getTicketKeys() on +one server instance and then distribute them, but it is more reasonable to +securely generate 48 bytes of secure random data and set them with the +ticketKeys option of tls.createServer(). The keys should be regularly +regenerated and server's keys can be reset with +server.setTicketKeys().

      +

      Session ticket keys are cryptographic keys, and they must be stored +securely. With TLS 1.2 and below, if they are compromised all sessions that +used tickets encrypted with them can be decrypted. They should not be stored +on disk, and they should be regenerated regularly.

      +

      If clients advertise support for tickets, the server will send them. The +server can disable tickets by supplying +require('constants').SSL_OP_NO_TICKET in secureOptions.

      +

      Both session identifiers and session tickets timeout, causing the server to +create new sessions. The timeout can be configured with the sessionTimeout +option of tls.createServer().

      +

      For all the mechanisms, when resumption fails, servers will create new sessions. +Since failing to resume the session does not cause TLS/HTTPS connection +failures, it is easy to not notice unnecessarily poor TLS performance. The +OpenSSL CLI can be used to verify that servers are resuming sessions. Use the +-reconnect option to openssl s_client, for example:

      +
      $ openssl s_client -connect localhost:443 -reconnect
      +

      Read through the debug output. The first connection should say "New", for +example:

      +
      New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
      +

      Subsequent connections should say "Reused", for example:

      +
      Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
      +

      Modifying the default TLS cipher suite#

      +

      Node.js is built with a default suite of enabled and disabled TLS ciphers. This +default cipher list can be configured when building Node.js to allow +distributions to provide their own default list.

      +

      The following command can be used to show the default cipher suite:

      +
      node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
      +TLS_AES_256_GCM_SHA384
      +TLS_CHACHA20_POLY1305_SHA256
      +TLS_AES_128_GCM_SHA256
      +ECDHE-RSA-AES128-GCM-SHA256
      +ECDHE-ECDSA-AES128-GCM-SHA256
      +ECDHE-RSA-AES256-GCM-SHA384
      +ECDHE-ECDSA-AES256-GCM-SHA384
      +DHE-RSA-AES128-GCM-SHA256
      +ECDHE-RSA-AES128-SHA256
      +DHE-RSA-AES128-SHA256
      +ECDHE-RSA-AES256-SHA384
      +DHE-RSA-AES256-SHA384
      +ECDHE-RSA-AES256-SHA256
      +DHE-RSA-AES256-SHA256
      +HIGH
      +!aNULL
      +!eNULL
      +!EXPORT
      +!DES
      +!RC4
      +!MD5
      +!PSK
      +!SRP
      +!CAMELLIA
      +

      This default can be replaced entirely using the --tls-cipher-list command +line switch (directly, or via the NODE_OPTIONS environment variable). For +instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS +cipher suite:

      +
      node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js
      +
      +export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
      +node server.js
      +

      The default can also be replaced on a per client or server basis using the +ciphers option from tls.createSecureContext(), which is also available +in tls.createServer(), tls.connect(), and when creating new +tls.TLSSockets.

      +

      The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones +that start with 'TLS_', and specifications for TLSv1.2 and below cipher +suites. The TLSv1.2 ciphers support a legacy specification format, consult +the OpenSSL cipher list format documentation for details, but those +specifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only +be enabled by including their full name in the cipher list. They cannot, for +example, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or +'!EECDH' specification.

      +

      Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3 +protocol is significantly more secure than TLSv1.2, and will always be chosen +over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3 +cipher suites are enabled.

      +

      The default cipher suite included within Node.js has been carefully +selected to reflect current security best practices and risk mitigation. +Changing the default cipher suite can have a significant impact on the security +of an application. The --tls-cipher-list switch and ciphers option should by +used only if absolutely necessary.

      +

      The default cipher suite prefers GCM ciphers for Chrome's 'modern +cryptography' setting and also prefers ECDHE and DHE ciphers for perfect +forward secrecy, while offering some backward compatibility.

      +

      128 bit AES is preferred over 192 and 256 bit AES in light of specific +attacks affecting larger AES key sizes.

      +

      Old clients that rely on insecure and deprecated RC4 or DES-based ciphers +(like Internet Explorer 6) cannot complete the handshaking process with +the default configuration. If these clients must be supported, the +TLS recommendations may offer a compatible cipher suite. For more details +on the format, see the OpenSSL cipher list format documentation.

      +

      There are only 5 TLSv1.3 cipher suites:

      +
        +
      • 'TLS_AES_256_GCM_SHA384'
      • +
      • 'TLS_CHACHA20_POLY1305_SHA256'
      • +
      • 'TLS_AES_128_GCM_SHA256'
      • +
      • 'TLS_AES_128_CCM_SHA256'
      • +
      • 'TLS_AES_128_CCM_8_SHA256'
      • +
      +

      The first 3 are enabled by default. The last 2 CCM-based suites are supported +by TLSv1.3 because they may be more performant on constrained systems, but they +are not enabled by default since they offer less security.

      +

      Class: tls.CryptoStream#

      + +

      Stability: 0 - Deprecated: Use tls.TLSSocket instead.

      +

      The tls.CryptoStream class represents a stream of encrypted data. This class +is deprecated and should no longer be used.

      +

      cryptoStream.bytesWritten#

      + +

      The cryptoStream.bytesWritten property returns the total number of bytes +written to the underlying socket including the bytes required for the +implementation of the TLS protocol.

      +

      Class: tls.SecurePair#

      + +

      Stability: 0 - Deprecated: Use tls.TLSSocket instead.

      +

      Returned by tls.createSecurePair().

      +

      Event: 'secure'#

      + +

      The 'secure' event is emitted by the SecurePair object once a secure +connection has been established.

      +

      As with checking for the server +'secureConnection' +event, pair.cleartext.authorized should be inspected to confirm whether the +certificate used is properly authorized.

      +

      Class: tls.Server#

      + + +

      Accepts encrypted connections using TLS or SSL.

      +

      Event: 'connection'#

      + + +

      This event is emitted when a new TCP stream is established, before the TLS +handshake begins. socket is typically an object of type net.Socket. +Usually users will not want to access this event.

      +

      This event can also be explicitly emitted by users to inject connections +into the TLS server. In that case, any Duplex stream can be passed.

      +

      Event: 'keylog'#

      + +
        +
      • line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.
      • +
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance on which it was +generated.
      • +
      +

      The keylog event is emitted when key material is generated or received by +a connection to this server (typically before handshake has completed, but not +necessarily). This keying material can be stored for debugging, as it allows +captured TLS traffic to be decrypted. It may be emitted multiple times for +each socket.

      +

      A typical use case is to append received lines to a common text file, which +is later used by software (such as Wireshark) to decrypt the traffic:

      +
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
      +// ...
      +server.on('keylog', (line, tlsSocket) => {
      +  if (tlsSocket.remoteAddress !== '...')
      +    return; // Only log keys for a particular IP
      +  logFile.write(line);
      +});
      +

      Event: 'newSession'#

      + +

      The 'newSession' event is emitted upon creation of a new TLS session. This may +be used to store sessions in external storage. The data should be provided to +the 'resumeSession' callback.

      +

      The listener callback is passed three arguments when called:

      +
        +
      • sessionId <Buffer> The TLS session identifier
      • +
      • sessionData <Buffer> The TLS session data
      • +
      • callback <Function> A callback function taking no arguments that must be +invoked in order for data to be sent or received over the secure connection.
      • +
      +

      Listening for this event will have an effect only on connections established +after the addition of the event listener.

      +

      Event: 'OCSPRequest'#

      + +

      The 'OCSPRequest' event is emitted when the client sends a certificate status +request. The listener callback is passed three arguments when called:

      +
        +
      • certificate <Buffer> The server certificate
      • +
      • issuer <Buffer> The issuer's certificate
      • +
      • callback <Function> A callback function that must be invoked to provide +the results of the OCSP request.
      • +
      +

      The server's current certificate can be parsed to obtain the OCSP URL +and certificate ID; after obtaining an OCSP response, callback(null, resp) is +then invoked, where resp is a Buffer instance containing the OCSP response. +Both certificate and issuer are Buffer DER-representations of the +primary and issuer's certificates. These can be used to obtain the OCSP +certificate ID and OCSP endpoint URL.

      +

      Alternatively, callback(null, null) may be called, indicating that there was +no OCSP response.

      +

      Calling callback(err) will result in a socket.destroy(err) call.

      +

      The typical flow of an OCSP Request is as follows:

      +
        +
      1. Client connects to the server and sends an 'OCSPRequest' (via the status +info extension in ClientHello).
      2. +
      3. Server receives the request and emits the 'OCSPRequest' event, calling the +listener if registered.
      4. +
      5. Server extracts the OCSP URL from either the certificate or issuer and +performs an OCSP request to the CA.
      6. +
      7. Server receives 'OCSPResponse' from the CA and sends it back to the client +via the callback argument
      8. +
      9. Client validates the response and either destroys the socket or performs a +handshake.
      10. +
      +

      The issuer can be null if the certificate is either self-signed or the +issuer is not in the root certificates list. (An issuer may be provided +via the ca option when establishing the TLS connection.)

      +

      Listening for this event will have an effect only on connections established +after the addition of the event listener.

      +

      An npm module like asn1.js may be used to parse the certificates.

      +

      Event: 'resumeSession'#

      + +

      The 'resumeSession' event is emitted when the client requests to resume a +previous TLS session. The listener callback is passed two arguments when +called:

      +
        +
      • sessionId <Buffer> The TLS session identifier
      • +
      • callback <Function> A callback function to be called when the prior session +has been recovered: callback([err[, sessionData]]) + +
      • +
      +

      The event listener should perform a lookup in external storage for the +sessionData saved by the 'newSession' event handler using the given +sessionId. If found, call callback(null, sessionData) to resume the session. +If not found, the session cannot be resumed. callback() must be called +without sessionData so that the handshake can continue and a new session can +be created. It is possible to call callback(err) to terminate the incoming +connection and destroy the socket.

      +

      Listening for this event will have an effect only on connections established +after the addition of the event listener.

      +

      The following illustrates resuming a TLS session:

      +
      const tlsSessionStore = {};
      +server.on('newSession', (id, data, cb) => {
      +  tlsSessionStore[id.toString('hex')] = data;
      +  cb();
      +});
      +server.on('resumeSession', (id, cb) => {
      +  cb(null, tlsSessionStore[id.toString('hex')] || null);
      +});
      +

      Event: 'secureConnection'#

      + +

      The 'secureConnection' event is emitted after the handshaking process for a +new connection has successfully completed. The listener callback is passed a +single argument when called:

      + +

      The tlsSocket.authorized property is a boolean indicating whether the +client has been verified by one of the supplied Certificate Authorities for the +server. If tlsSocket.authorized is false, then socket.authorizationError +is set to describe how authorization failed. Depending on the settings +of the TLS server, unauthorized connections may still be accepted.

      +

      The tlsSocket.alpnProtocol property is a string that contains the selected +ALPN protocol. When ALPN has no selected protocol, tlsSocket.alpnProtocol +equals false.

      +

      The tlsSocket.servername property is a string containing the server name +requested via SNI.

      +

      Event: 'tlsClientError'#

      + +

      The 'tlsClientError' event is emitted when an error occurs before a secure +connection is established. The listener callback is passed two arguments when +called:

      +
        +
      • exception <Error> The Error object describing the error
      • +
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance from which the +error originated.
      • +
      +

      server.addContext(hostname, context)#

      + +
        +
      • hostname <string> A SNI host name or wildcard (e.g. '*')
      • +
      • context <Object> An object containing any of the possible properties +from the tls.createSecureContext() options arguments (e.g. key, +cert, ca, etc).
      • +
      +

      The server.addContext() method adds a secure context that will be used if +the client request's SNI name matches the supplied hostname (or wildcard).

      +

      server.address()#

      + + +

      Returns the bound address, the address family name, and port of the +server as reported by the operating system. See net.Server.address() for +more information.

      +

      server.close([callback])#

      + +
        +
      • callback <Function> A listener callback that will be registered to listen +for the server instance's 'close' event.
      • +
      • Returns: <tls.Server>
      • +
      +

      The server.close() method stops the server from accepting new connections.

      +

      This function operates asynchronously. The 'close' event will be emitted +when the server has no more open connections.

      +

      server.connections#

      + +

      Stability: 0 - Deprecated: Use server.getConnections() instead.

      + +

      Returns the current number of concurrent connections on the server.

      +

      server.getTicketKeys()#

      + +
        +
      • Returns: <Buffer> A 48-byte buffer containing the session ticket keys.
      • +
      +

      Returns the session ticket keys.

      +

      See Session Resumption for more information.

      +

      server.listen()#

      +

      Starts the server listening for encrypted connections. +This method is identical to server.listen() from net.Server.

      +

      server.setSecureContext(options)#

      + + +

      The server.setSecureContext() method replaces the secure context of an +existing server. Existing connections to the server are not interrupted.

      +

      server.setTicketKeys(keys)#

      + +
        +
      • keys <Buffer> A 48-byte buffer containing the session ticket keys.
      • +
      +

      Sets the session ticket keys.

      +

      Changes to the ticket keys are effective only for future server connections. +Existing or currently pending server connections will use the previous keys.

      +

      See Session Resumption for more information.

      +

      Class: tls.TLSSocket#

      + + +

      Performs transparent encryption of written data and all required TLS +negotiation.

      +

      Instances of tls.TLSSocket implement the duplex Stream interface.

      +

      Methods that return TLS connection metadata (e.g. +tls.TLSSocket.getPeerCertificate() will only return data while the +connection is open.

      +

      new tls.TLSSocket(socket[, options])#

      + +
        +
      • socket <net.Socket> | <stream.Duplex> +On the server side, any Duplex stream. On the client side, any +instance of net.Socket (for generic Duplex stream support +on the client side, tls.connect() must be used).
      • +
      • options <Object> +
          +
        • enableTrace: See tls.createServer()
        • +
        • isServer: The SSL/TLS protocol is asymmetrical, TLSSockets must know if +they are to behave as a server or a client. If true the TLS socket will be +instantiated as a server. Default: false.
        • +
        • server <net.Server> A net.Server instance.
        • +
        • requestCert: Whether to authenticate the remote peer by requesting a +certificate. Clients always request a server certificate. Servers +(isServer is true) may set requestCert to true to request a client +certificate.
        • +
        • rejectUnauthorized: See tls.createServer()
        • +
        • ALPNProtocols: See tls.createServer()
        • +
        • SNICallback: See tls.createServer()
        • +
        • session <Buffer> A Buffer instance containing a TLS session.
        • +
        • requestOCSP <boolean> If true, specifies that the OCSP status request +extension will be added to the client hello and an 'OCSPResponse' event +will be emitted on the socket before establishing a secure communication
        • +
        • secureContext: TLS context object created with +tls.createSecureContext(). If a secureContext is not provided, one +will be created by passing the entire options object to +tls.createSecureContext().
        • +
        • ...: tls.createSecureContext() options that are used if the +secureContext option is missing. Otherwise, they are ignored.
        • +
        +
      • +
      +

      Construct a new tls.TLSSocket object from an existing TCP socket.

      +

      Event: 'keylog'#

      + +
        +
      • line <Buffer> Line of ASCII text, in NSS SSLKEYLOGFILE format.
      • +
      +

      The keylog event is emitted on a tls.TLSSocket when key material +is generated or received by the socket. This keying material can be stored +for debugging, as it allows captured TLS traffic to be decrypted. It may +be emitted multiple times, before or after the handshake completes.

      +

      A typical use case is to append received lines to a common text file, which +is later used by software (such as Wireshark) to decrypt the traffic:

      +
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
      +// ...
      +tlsSocket.on('keylog', (line) => logFile.write(line));
      +

      Event: 'OCSPResponse'#

      + +

      The 'OCSPResponse' event is emitted if the requestOCSP option was set +when the tls.TLSSocket was created and an OCSP response has been received. +The listener callback is passed a single argument when called:

      +
        +
      • response <Buffer> The server's OCSP response
      • +
      +

      Typically, the response is a digitally signed object from the server's CA that +contains information about server's certificate revocation status.

      +

      Event: 'secureConnect'#

      + +

      The 'secureConnect' event is emitted after the handshaking process for a new +connection has successfully completed. The listener callback will be called +regardless of whether or not the server's certificate has been authorized. It +is the client's responsibility to check the tlsSocket.authorized property to +determine if the server certificate was signed by one of the specified CAs. If +tlsSocket.authorized === false, then the error can be found by examining the +tlsSocket.authorizationError property. If ALPN was used, the +tlsSocket.alpnProtocol property can be checked to determine the negotiated +protocol.

      +

      Event: 'session'#

      + + +

      The 'session' event is emitted on a client tls.TLSSocket when a new session +or TLS ticket is available. This may or may not be before the handshake is +complete, depending on the TLS protocol version that was negotiated. The event +is not emitted on the server, or if a new session was not created, for example, +when the connection was resumed. For some TLS protocol versions the event may be +emitted multiple times, in which case all the sessions can be used for +resumption.

      +

      On the client, the session can be provided to the session option of +tls.connect() to resume the connection.

      +

      See Session Resumption for more information.

      +

      For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once +the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed +by the protocol, multiple tickets are sent, and the tickets aren't sent until +after the handshake completes. So it is necessary to wait for the +'session' event to get a resumable session. Applications +should use the 'session' event instead of getSession() to ensure +they will work for all TLS versions. Applications that only expect to +get or use one session should listen for this event only once:

      +
      tlsSocket.once('session', (session) => {
      +  // The session can be used immediately or later.
      +  tls.connect({
      +    session: session,
      +    // Other connect options...
      +  });
      +});
      +

      tlsSocket.address()#

      + + +

      Returns the bound address, the address family name, and port of the +underlying socket as reported by the operating system: +{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      +

      tlsSocket.authorizationError#

      + +

      Returns the reason why the peer's certificate was not been verified. This +property is set only when tlsSocket.authorized === false.

      +

      tlsSocket.authorized#

      + + +

      Returns true if the peer certificate was signed by one of the CAs specified +when creating the tls.TLSSocket instance, otherwise false.

      +

      tlsSocket.disableRenegotiation()#

      + +

      Disables TLS renegotiation for this TLSSocket instance. Once called, attempts +to renegotiate will trigger an 'error' event on the TLSSocket.

      +

      tlsSocket.enableTrace()#

      + +

      When enabled, TLS packet trace information is written to stderr. This can be +used to debug TLS connection problems.

      +

      Note: The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's +SSL_trace() function, the format is undocumented, can change without notice, +and should not be relied on.

      +

      tlsSocket.encrypted#

      + +

      Always returns true. This may be used to distinguish TLS sockets from regular +net.Socket instances.

      +

      tlsSocket.getCertificate()#

      + + +

      Returns an object representing the local certificate. The returned object has +some properties corresponding to the fields of the certificate.

      +

      See tls.TLSSocket.getPeerCertificate() for an example of the certificate +structure.

      +

      If there is no local certificate, an empty object will be returned. If the +socket has been destroyed, null will be returned.

      +

      tlsSocket.getCipher()#

      + +
        +
      • Returns: <Object> +
          +
        • name <string> OpenSSL name for the cipher suite.
        • +
        • standardName <string> IETF name for the cipher suite.
        • +
        • version <string> The minimum TLS protocol version supported by this cipher +suite.
        • +
        +
      • +
      +

      Returns an object containing information on the negotiated cipher suite.

      +

      For example:

      +
      {
      +    "name": "AES128-SHA256",
      +    "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256",
      +    "version": "TLSv1.2"
      +}
      +

      See +SSL_CIPHER_get_name +for more information.

      +

      tlsSocket.getEphemeralKeyInfo()#

      + + +

      Returns an object representing the type, name, and size of parameter of +an ephemeral key exchange in perfect forward secrecy on a client +connection. It returns an empty object when the key exchange is not +ephemeral. As this is only supported on a client socket; null is returned +if called on a server socket. The supported types are 'DH' and 'ECDH'. The +name property is available only when type is 'ECDH'.

      +

      For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

      +

      tlsSocket.getFinished()#

      + +
        +
      • Returns: <Buffer> | <undefined> The latest Finished message that has been +sent to the socket as part of a SSL/TLS handshake, or undefined if +no Finished message has been sent yet.
      • +
      +

      As the Finished messages are message digests of the complete handshake +(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can +be used for external authentication procedures when the authentication +provided by SSL/TLS is not desired or is not enough.

      +

      Corresponds to the SSL_get_finished routine in OpenSSL and may be used +to implement the tls-unique channel binding from RFC 5929.

      +

      tlsSocket.getPeerCertificate([detailed])#

      + +
        +
      • detailed <boolean> Include the full certificate chain if true, otherwise +include just the peer's certificate.
      • +
      • Returns: <Object> A certificate object.
      • +
      +

      Returns an object representing the peer's certificate. If the peer does not +provide a certificate, an empty object will be returned. If the socket has been +destroyed, null will be returned.

      +

      If the full certificate chain was requested, each certificate will include an +issuerCertificate property containing an object representing its issuer's +certificate.

      +

      Certificate object#

      + +

      A certificate object has properties corresponding to the fields of the +certificate.

      +
        +
      • raw <Buffer> The DER encoded X.509 certificate data.
      • +
      • subject <Object> The certificate subject, described in terms of + Country (C:), StateOrProvince (ST), Locality (L), Organization (O), +OrganizationalUnit (OU), and CommonName (CN). The CommonName is typically +a DNS name with TLS certificates. Example: +{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.
      • +
      • issuer <Object> The certificate issuer, described in the same terms as the + subject.
      • +
      • valid_from <string> The date-time the certificate is valid from.
      • +
      • valid_to <string> The date-time the certificate is valid to.
      • +
      • serialNumber <string> The certificate serial number, as a hex string. + Example: 'B9B0D332A1AA5635'.
      • +
      • fingerprint <string> The SHA-1 digest of the DER encoded certificate. It is +returned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
      • +
      • fingerprint256 <string> The SHA-256 digest of the DER encoded certificate. + It is returned as a : separated hexadecimal string. Example: +'2A:7A:C2:DD:...'.
      • +
      • ext_key_usage <Array> (Optional) The extended key usage, a set of OIDs.
      • +
      • subjectaltname <string> (Optional) A string containing concatenated names +for the subject, an alternative to the subject names.
      • +
      • infoAccess <Array> (Optional) An array describing the AuthorityInfoAccess, + used with OCSP.
      • +
      • issuerCertificate <Object> (Optional) The issuer certificate object. For + self-signed certificates, this may be a circular reference.
      • +
      +

      The certificate may contain information about the public key, depending on +the key type.

      +

      For RSA keys, the following properties may be defined:

      +
        +
      • bits <number> The RSA bit size. Example: 1024.
      • +
      • exponent <string> The RSA exponent, as a string in hexadecimal number +notation. Example: '0x010001'.
      • +
      • modulus <string> The RSA modulus, as a hexadecimal string. Example: + 'B56CE45CB7...'.
      • +
      • pubkey <Buffer> The public key.
      • +
      +

      For EC keys, the following properties may be defined:

      +
        +
      • pubkey <Buffer> The public key.
      • +
      • bits <number> The key size in bits. Example: 256.
      • +
      • asn1Curve <string> (Optional) The ASN.1 name of the OID of the elliptic +curve. Well-known curves are identified by an OID. While it is unusual, it is +possible that the curve is identified by its mathematical properties, in which +case it will not have an OID. Example: 'prime256v1'.
      • +
      • nistCurve <string> (Optional) The NIST name for the elliptic curve, if it +has one (not all well-known curves have been assigned names by NIST). Example: +'P-256'.
      • +
      +

      Example certificate:

      + +
      { subject:
      +   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
      +     CN: '*.nodejs.org' },
      +  issuer:
      +   { C: 'GB',
      +     ST: 'Greater Manchester',
      +     L: 'Salford',
      +     O: 'COMODO CA Limited',
      +     CN: 'COMODO RSA Domain Validation Secure Server CA' },
      +  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',
      +  infoAccess:
      +   { 'CA Issuers - URI':
      +      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],
      +     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },
      +  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',
      +  exponent: '0x10001',
      +  pubkey: <Buffer ... >,
      +  valid_from: 'Aug 14 00:00:00 2017 GMT',
      +  valid_to: 'Nov 20 23:59:59 2019 GMT',
      +  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',
      +  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',
      +  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],
      +  serialNumber: '66593D57F20CBC573E433381B5FEC280',
      +  raw: <Buffer ... > }
      +

      tlsSocket.getPeerFinished()#

      + +
        +
      • Returns: <Buffer> | <undefined> The latest Finished message that is expected +or has actually been received from the socket as part of a SSL/TLS handshake, +or undefined if there is no Finished message so far.
      • +
      +

      As the Finished messages are message digests of the complete handshake +(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can +be used for external authentication procedures when the authentication +provided by SSL/TLS is not desired or is not enough.

      +

      Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used +to implement the tls-unique channel binding from RFC 5929.

      +

      tlsSocket.getProtocol()#

      + + +

      Returns a string containing the negotiated SSL/TLS protocol version of the +current connection. The value 'unknown' will be returned for connected +sockets that have not completed the handshaking process. The value null will +be returned for server sockets or disconnected client sockets.

      +

      Protocol versions are:

      +
        +
      • 'SSLv3'
      • +
      • 'TLSv1'
      • +
      • 'TLSv1.1'
      • +
      • 'TLSv1.2'
      • +
      • 'TLSv1.3'
      • +
      +

      See the OpenSSL SSL_get_version documentation for more information.

      +

      tlsSocket.getSession()#

      + + +

      Returns the TLS session data or undefined if no session was +negotiated. On the client, the data can be provided to the session option of +tls.connect() to resume the connection. On the server, it may be useful +for debugging.

      +

      See Session Resumption for more information.

      +

      Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications +must use the 'session' event (it also works for TLSv1.2 and below).

      +

      tlsSocket.getSharedSigalgs()#

      + +
        +
      • Returns: <Array> List of signature algorithms shared between the server and +the client in the order of decreasing preference.
      • +
      +

      See +SSL_get_shared_sigalgs +for more information.

      +

      tlsSocket.exportKeyingMaterial(length, label[, context])#

      + +
        +
      • +

        length <number> number of bytes to retrieve from keying material

        +
      • +
      • +

        label <string> an application specific label, typically this will be a +value from the +IANA Exporter Label Registry.

        +
      • +
      • +

        context <Buffer> Optionally provide a context.

        +
      • +
      • +

        Returns: <Buffer> requested bytes of the keying material

        +
      • +
      +

      Keying material is used for validations to prevent different kind of attacks in +network protocols, for example in the specifications of IEEE 802.1X.

      +

      Example

      +
      const keyingMaterial = tlsSocket.exportKeyingMaterial(
      +  128,
      +  'client finished');
      +
      +/**
      + Example return value of keyingMaterial:
      + <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
      +    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
      +    74 ef 2c ... 78 more bytes>
      +*/
      +

      See the OpenSSL SSL_export_keying_material documentation for more +information.

      +

      tlsSocket.getTLSTicket()#

      + + +

      For a client, returns the TLS session ticket if one is available, or +undefined. For a server, always returns undefined.

      +

      It may be useful for debugging.

      +

      See Session Resumption for more information.

      +

      tlsSocket.isSessionReused()#

      + +
        +
      • Returns: <boolean> true if the session was reused, false otherwise.
      • +
      +

      See Session Resumption for more information.

      +

      tlsSocket.localAddress#

      + + +

      Returns the string representation of the local IP address.

      +

      tlsSocket.localPort#

      + + +

      Returns the numeric representation of the local port.

      +

      tlsSocket.remoteAddress#

      + + +

      Returns the string representation of the remote IP address. For example, +'74.125.127.100' or '2001:4860:a005::68'.

      +

      tlsSocket.remoteFamily#

      + + +

      Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

      +

      tlsSocket.remotePort#

      + + +

      Returns the numeric representation of the remote port. For example, 443.

      +

      tlsSocket.renegotiate(options, callback)#

      + +
        +
      • +

        options <Object>

        +
          +
        • rejectUnauthorized <boolean> If not false, the server certificate is +verified against the list of supplied CAs. An 'error' event is emitted if +verification fails; err.code contains the OpenSSL error code. Default: +true.
        • +
        • requestCert
        • +
        +
      • +
      • +

        callback <Function> If renegotiate() returned true, callback is +attached once to the 'secure' event. If renegotiate() returned false, +callback will be called in the next tick with an error, unless the +tlsSocket has been destroyed, in which case callback will not be called +at all.

        +
      • +
      • +

        Returns: <boolean> true if renegotiation was initiated, false otherwise.

        +
      • +
      +

      The tlsSocket.renegotiate() method initiates a TLS renegotiation process. +Upon completion, the callback function will be passed a single argument +that is either an Error (if the request failed) or null.

      +

      This method can be used to request a peer's certificate after the secure +connection has been established.

      +

      When running as the server, the socket will be destroyed with an error after +handshakeTimeout timeout.

      +

      For TLSv1.3, renegotiation cannot be initiated, it is not supported by the +protocol.

      +

      tlsSocket.setMaxSendFragment(size)#

      + +
        +
      • size <number> The maximum TLS fragment size. The maximum value is 16384. +Default: 16384.
      • +
      • Returns: <boolean>
      • +
      +

      The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size. +Returns true if setting the limit succeeded; false otherwise.

      +

      Smaller fragment sizes decrease the buffering latency on the client: larger +fragments are buffered by the TLS layer until the entire fragment is received +and its integrity is verified; large fragments can span multiple roundtrips +and their processing can be delayed due to packet loss or reordering. However, +smaller fragments add extra TLS framing bytes and CPU overhead, which may +decrease overall server throughput.

      +

      tls.checkServerIdentity(hostname, cert)#

      + + +

      Verifies the certificate cert is issued to hostname.

      +

      Returns <Error> object, populating it with reason, host, and cert on +failure. On success, returns <undefined>.

      +

      This function can be overwritten by providing alternative function as part of +the options.checkServerIdentity option passed to tls.connect(). The +overwriting function can call tls.checkServerIdentity() of course, to augment +the checks done with additional verification.

      +

      This function is only called if the certificate passed all other checks, such as +being issued by trusted CA (options.ca).

      +

      tls.connect(options[, callback])#

      + +
        +
      • options <Object> +
          +
        • enableTrace: See tls.createServer()
        • +
        • host <string> Host the client should connect to. Default: +'localhost'.
        • +
        • port <number> Port the client should connect to.
        • +
        • path <string> Creates Unix socket connection to path. If this option is +specified, host and port are ignored.
        • +
        • socket <stream.Duplex> Establish secure connection on a given socket +rather than creating a new socket. Typically, this is an instance of +net.Socket, but any Duplex stream is allowed. +If this option is specified, path, host and port are ignored, +except for certificate validation. Usually, a socket is already connected +when passed to tls.connect(), but it can be connected later. +Connection/disconnection/destruction of socket is the user's +responsibility; calling tls.connect() will not cause net.connect() to be +called.
        • +
        • allowHalfOpen <boolean> If the socket option is missing, indicates +whether or not to allow the internally created socket to be half-open, +otherwise the option is ignored. See the allowHalfOpen option of +net.Socket for details. Default: false.
        • +
        • rejectUnauthorized <boolean> If not false, the server certificate is +verified against the list of supplied CAs. An 'error' event is emitted if +verification fails; err.code contains the OpenSSL error code. Default: +true.
        • +
        • pskCallback <Function> +
            +
          • hint: <string> optional message sent from the server to help client +decide which identity to use during negotiation. +Always null if TLS 1.3 is used.
          • +
          • Returns: <Object> in the form + { psk: <Buffer|TypedArray|DataView>, identity: <string> } +or null to stop the negotiation process. psk must be +compatible with the selected cipher's digest. +identity must use UTF-8 encoding. +When negotiating TLS-PSK (pre-shared keys), this function is called +with optional identity hint provided by the server or null +in case of TLS 1.3 where hint was removed. +It will be necessary to provide a custom tls.checkServerIdentity() +for the connection as the default one will try to check host name/IP +of the server against the certificate but that's not applicable for PSK +because there won't be a certificate present. +More information can be found in the RFC 4279.
          • +
          +
        • +
        • ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> +An array of strings, Buffers or TypedArrays or DataViews, or a +single Buffer or TypedArray or DataView containing the supported ALPN +protocols. Buffers should have the format [len][name][len][name]... +e.g. '\x08http/1.1\x08http/1.0', where the len byte is the length of the +next protocol name. Passing an array is usually much simpler, e.g. +['http/1.1', 'http/1.0']. Protocols earlier in the list have higher +preference than those later.
        • +
        • servername: <string> Server name for the SNI (Server Name Indication) TLS +extension. It is the name of the host being connected to, and must be a host +name, and not an IP address. It can be used by a multi-homed server to +choose the correct certificate to present to the client, see the +SNICallback option to tls.createServer().
        • +
        • checkServerIdentity(servername, cert) <Function> A callback function +to be used (instead of the builtin tls.checkServerIdentity() function) +when checking the server's host name (or the provided servername when +explicitly set) against the certificate. This should return an <Error> if +verification fails. The method should return undefined if the servername +and cert are verified.
        • +
        • session <Buffer> A Buffer instance, containing TLS session.
        • +
        • minDHSize <number> Minimum size of the DH parameter in bits to accept a +TLS connection. When a server offers a DH parameter with a size less +than minDHSize, the TLS connection is destroyed and an error is thrown. +Default: 1024.
        • +
        • secureContext: TLS context object created with +tls.createSecureContext(). If a secureContext is not provided, one +will be created by passing the entire options object to +tls.createSecureContext().
        • +
        • ...: tls.createSecureContext() options that are used if the +secureContext option is missing, otherwise they are ignored.
        • +
        • ...: Any socket.connect() option not already listed.
        • +
        +
      • +
      • callback <Function>
      • +
      • Returns: <tls.TLSSocket>
      • +
      +

      The callback function, if specified, will be added as a listener for the +'secureConnect' event.

      +

      tls.connect() returns a tls.TLSSocket object.

      +

      Unlike the https API, tls.connect() does not enable the +SNI (Server Name Indication) extension by default, which may cause some +servers to return an incorrect certificate or reject the connection +altogether. To enable SNI, set the servername option in addition +to host.

      +

      The following illustrates a client for the echo server example from +tls.createServer():

      +
      // Assumes an echo server that is listening on port 8000.
      +const tls = require('tls');
      +const fs = require('fs');
      +
      +const options = {
      +  // Necessary only if the server requires client certificate authentication.
      +  key: fs.readFileSync('client-key.pem'),
      +  cert: fs.readFileSync('client-cert.pem'),
      +
      +  // Necessary only if the server uses a self-signed certificate.
      +  ca: [ fs.readFileSync('server-cert.pem') ],
      +
      +  // Necessary only if the server's cert isn't for "localhost".
      +  checkServerIdentity: () => { return null; },
      +};
      +
      +const socket = tls.connect(8000, options, () => {
      +  console.log('client connected',
      +              socket.authorized ? 'authorized' : 'unauthorized');
      +  process.stdin.pipe(socket);
      +  process.stdin.resume();
      +});
      +socket.setEncoding('utf8');
      +socket.on('data', (data) => {
      +  console.log(data);
      +});
      +socket.on('end', () => {
      +  console.log('server ends connection');
      +});
      +

      tls.connect(path[, options][, callback])#

      + + +

      Same as tls.connect() except that path can be provided +as an argument instead of an option.

      +

      A path option, if specified, will take precedence over the path argument.

      +

      tls.connect(port[, host][, options][, callback])#

      + + +

      Same as tls.connect() except that port and host can be provided +as arguments instead of options.

      +

      A port or host option, if specified, will take precedence over any port or host +argument.

      +

      tls.createSecureContext([options])#

      + +
        +
      • options <Object> +
          +
        • ca <string> | <string[]> | <Buffer> | <Buffer[]> Optionally override the trusted CA +certificates. Default is to trust the well-known CAs curated by Mozilla. +Mozilla's CAs are completely replaced when CAs are explicitly specified +using this option. The value can be a string or Buffer, or an Array of +strings and/or Buffers. Any string or Buffer can contain multiple PEM +CAs concatenated together. The peer's certificate must be chainable to a CA +trusted by the server for the connection to be authenticated. When using +certificates that are not chainable to a well-known CA, the certificate's CA +must be explicitly specified as a trusted or the connection will fail to +authenticate. +If the peer uses a certificate that doesn't match or chain to one of the +default CAs, use the ca option to provide a CA certificate that the peer's +certificate can match or chain to. +For self-signed certificates, the certificate is its own CA, and must be +provided. +For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", +"X509 CERTIFICATE", and "CERTIFICATE". +See also tls.rootCertificates.
        • +
        • cert <string> | <string[]> | <Buffer> | <Buffer[]> Cert chains in PEM format. One cert +chain should be provided per private key. Each cert chain should consist of +the PEM formatted certificate for a provided private key, followed by the +PEM formatted intermediate certificates (if any), in order, and not +including the root CA (the root CA must be pre-known to the peer, see ca). +When providing multiple cert chains, they do not have to be in the same +order as their private keys in key. If the intermediate certificates are +not provided, the peer will not be able to validate the certificate, and the +handshake will fail.
        • +
        • sigalgs <string> Colon-separated list of supported signature algorithms. +The list can contain digest algorithms (SHA256, MD5 etc.), public key +algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g +'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). +See OpenSSL man pages +for more info.
        • +
        • ciphers <string> Cipher suite specification, replacing the default. For +more information, see modifying the default cipher suite. Permitted +ciphers can be obtained via tls.getCiphers(). Cipher names must be +uppercased in order for OpenSSL to accept them.
        • +
        • clientCertEngine <string> Name of an OpenSSL engine which can provide the +client certificate.
        • +
        • crl <string> | <string[]> | <Buffer> | <Buffer[]> PEM formatted CRLs (Certificate +Revocation Lists).
        • +
        • dhparam <string> | <Buffer> Diffie-Hellman parameters, required for +perfect forward secrecy. Use openssl dhparam to create the parameters. +The key length must be greater than or equal to 1024 bits or else an error +will be thrown. Although 1024 bits is permissible, use 2048 bits or larger +for stronger security. If omitted or invalid, the parameters are silently +discarded and DHE ciphers will not be available.
        • +
        • ecdhCurve <string> A string describing a named curve or a colon separated +list of curve NIDs or names, for example P-521:P-384:P-256, to use for +ECDH key agreement. Set to auto to select the +curve automatically. Use crypto.getCurves() to obtain a list of +available curve names. On recent releases, openssl ecparam -list_curves +will also display the name and description of each available elliptic curve. +Default: tls.DEFAULT_ECDH_CURVE.
        • +
        • honorCipherOrder <boolean> Attempt to use the server's cipher suite +preferences instead of the client's. When true, causes +SSL_OP_CIPHER_SERVER_PREFERENCE to be set in secureOptions, see +OpenSSL Options for more information.
        • +
        • key <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> Private keys in PEM format. +PEM allows the option of private keys being encrypted. Encrypted keys will +be decrypted with options.passphrase. Multiple keys using different +algorithms can be provided either as an array of unencrypted key strings or +buffers, or an array of objects in the form +{pem: <string|buffer>[, passphrase: <string>]}. The object form can only +occur in an array. object.passphrase is optional. Encrypted keys will be +decrypted with object.passphrase if provided, or options.passphrase if +it is not.
        • +
        • privateKeyEngine <string> Name of an OpenSSL engine to get private key +from. Should be used together with privateKeyIdentifier.
        • +
        • privateKeyIdentifier <string> Identifier of a private key managed by +an OpenSSL engine. Should be used together with privateKeyEngine. +Should not be set together with key, because both options define a +private key in different ways.
        • +
        • maxVersion <string> Optionally set the maximum TLS version to allow. One +of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified +along with the secureProtocol option, use one or the other. +Default: tls.DEFAULT_MAX_VERSION.
        • +
        • minVersion <string> Optionally set the minimum TLS version to allow. One +of 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Cannot be specified +along with the secureProtocol option, use one or the other. It is not +recommended to use less than TLSv1.2, but it may be required for +interoperability. +Default: tls.DEFAULT_MIN_VERSION.
        • +
        • passphrase <string> Shared passphrase used for a single private key and/or +a PFX.
        • +
        • pfx <string> | <string[]> | <Buffer> | <Buffer[]> | <Object[]> PFX or PKCS12 encoded +private key and certificate chain. pfx is an alternative to providing +key and cert individually. PFX is usually encrypted, if it is, +passphrase will be used to decrypt it. Multiple PFX can be provided either +as an array of unencrypted PFX buffers, or an array of objects in the form +{buf: <string|buffer>[, passphrase: <string>]}. The object form can only +occur in an array. object.passphrase is optional. Encrypted PFX will be +decrypted with object.passphrase if provided, or options.passphrase if +it is not.
        • +
        • secureOptions <number> Optionally affect the OpenSSL protocol behavior, +which is not usually necessary. This should be used carefully if at all! +Value is a numeric bitmask of the SSL_OP_* options from +OpenSSL Options.
        • +
        • secureProtocol <string> Legacy mechanism to select the TLS protocol +version to use, it does not support independent control of the minimum and +maximum version, and does not support limiting the protocol to TLSv1.3. Use +minVersion and maxVersion instead. The possible values are listed as +SSL_METHODS, use the function names as strings. For example, use +'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow any +TLS protocol version up to TLSv1.3. It is not recommended to use TLS +versions less than 1.2, but it may be required for interoperability. +Default: none, see minVersion.
        • +
        • sessionIdContext <string> Opaque identifier used by servers to ensure +session state is not shared between applications. Unused by clients.
        • +
        • ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudo-random +data. See Session Resumption for more information.
        • +
        • sessionTimeout <number> The number of seconds after which a TLS session +created by the server will no longer be resumable. See +Session Resumption for more information. Default: 300.
        • +
        +
      • +
      +

      tls.createServer() sets the default value of the honorCipherOrder option +to true, other APIs that create secure contexts leave it unset.

      +

      tls.createServer() uses a 128 bit truncated SHA1 hash value generated +from process.argv as the default value of the sessionIdContext option, other +APIs that create secure contexts have no default value.

      +

      The tls.createSecureContext() method creates a SecureContext object. It is +usable as an argument to several tls APIs, such as tls.createServer() +and server.addContext(), but has no public methods.

      +

      A key is required for ciphers that use certificates. Either key or +pfx can be used to provide it.

      +

      If the ca option is not given, then Node.js will default to using +Mozilla's publicly trusted list of CAs.

      +

      tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])#

      + +

      Stability: 0 - Deprecated: Use tls.TLSSocket instead.

      +
        +
      • context <Object> A secure context object as returned by +tls.createSecureContext()
      • +
      • isServer <boolean> true to specify that this TLS connection should be +opened as a server.
      • +
      • requestCert <boolean> true to specify whether a server should request a +certificate from a connecting client. Only applies when isServer is true.
      • +
      • rejectUnauthorized <boolean> If not false a server automatically reject +clients with invalid certificates. Only applies when isServer is true.
      • +
      • options + +
      • +
      +

      Creates a new secure pair object with two streams, one of which reads and writes +the encrypted data and the other of which reads and writes the cleartext data. +Generally, the encrypted stream is piped to/from an incoming encrypted data +stream and the cleartext one is used as a replacement for the initial encrypted +stream.

      +

      tls.createSecurePair() returns a tls.SecurePair object with cleartext and +encrypted stream properties.

      +

      Using cleartext has the same API as tls.TLSSocket.

      +

      The tls.createSecurePair() method is now deprecated in favor of +tls.TLSSocket(). For example, the code:

      +
      pair = tls.createSecurePair(/* ... */);
      +pair.encrypted.pipe(socket);
      +socket.pipe(pair.encrypted);
      +

      can be replaced by:

      +
      secureSocket = tls.TLSSocket(socket, options);
      +

      where secureSocket has the same API as pair.cleartext.

      +

      tls.createServer([options][, secureConnectionListener])#

      + +
        +
      • options <Object> +
          +
        • ALPNProtocols: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> +An array of strings, Buffers or TypedArrays or DataViews, or a single +Buffer or TypedArray or DataView containing the supported ALPN +protocols. Buffers should have the format [len][name][len][name]... +e.g. 0x05hello0x05world, where the first byte is the length of the next +protocol name. Passing an array is usually much simpler, e.g. +['hello', 'world']. (Protocols should be ordered by their priority.)
        • +
        • clientCertEngine <string> Name of an OpenSSL engine which can provide the +client certificate.
        • +
        • enableTrace <boolean> If true, tls.TLSSocket.enableTrace() will be +called on new connections. Tracing can be enabled after the secure +connection is established, but this option must be used to trace the secure +connection setup. Default: false.
        • +
        • handshakeTimeout <number> Abort the connection if the SSL/TLS handshake +does not finish in the specified number of milliseconds. +A 'tlsClientError' is emitted on the tls.Server object whenever +a handshake times out. Default: 120000 (120 seconds).
        • +
        • rejectUnauthorized <boolean> If not false the server will reject any +connection which is not authorized with the list of supplied CAs. This +option only has an effect if requestCert is true. Default: true.
        • +
        • requestCert <boolean> If true the server will request a certificate from +clients that connect and attempt to verify that certificate. Default: +false.
        • +
        • sessionTimeout <number> The number of seconds after which a TLS session +created by the server will no longer be resumable. See +Session Resumption for more information. Default: 300.
        • +
        • SNICallback(servername, callback) <Function> A function that will be +called if the client supports SNI TLS extension. Two arguments will be +passed when called: servername and callback. callback is an +error-first callback that takes two optional arguments: error and ctx. +ctx, if provided, is a SecureContext instance. +tls.createSecureContext() can be used to get a proper SecureContext. +If callback is called with a falsy ctx argument, the default secure +context of the server will be used. If SNICallback wasn't provided the +default callback with high-level API will be used (see below).
        • +
        • ticketKeys: <Buffer> 48-bytes of cryptographically strong pseudo-random +data. See Session Resumption for more information.
        • +
        • pskCallback <Function> +
            +
          • socket: <tls.TLSSocket> the server tls.TLSSocket instance for +this connection.
          • +
          • identity: <string> identity parameter sent from the client.
          • +
          • Returns: <Buffer> | <TypedArray> | <DataView> pre-shared key that must either be + a buffer or null to stop the negotiation process. Returned PSK must be +compatible with the selected cipher's digest. +When negotiating TLS-PSK (pre-shared keys), this function is called +with the identity provided by the client. +If the return value is null the negotiation process will stop and an +"unknown_psk_identity" alert message will be sent to the other party. +If the server wishes to hide the fact that the PSK identity was not known, +the callback must provide some random data as psk to make the connection +fail with "decrypt_error" before negotiation is finished. +PSK ciphers are disabled by default, and using TLS-PSK thus +requires explicitly specifying a cipher suite with the ciphers option. +More information can be found in the RFC 4279.
          • +
          +
        • +
        • pskIdentityHint <string> optional hint to send to a client to help +with selecting the identity during TLS-PSK negotiation. Will be ignored +in TLS 1.3. Upon failing to set pskIdentityHint 'tlsClientError' will be +emitted with 'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED' code.
        • +
        • ...: Any tls.createSecureContext() option can be provided. For +servers, the identity options (pfx, key/cert or pskCallback) +are usually required.
        • +
        • ...: Any net.createServer() option can be provided.
        • +
        +
      • +
      • secureConnectionListener <Function>
      • +
      • Returns: <tls.Server>
      • +
      +

      Creates a new tls.Server. The secureConnectionListener, if provided, is +automatically set as a listener for the 'secureConnection' event.

      +

      The ticketKeys options is automatically shared between cluster module +workers.

      +

      The following illustrates a simple echo server:

      +
      const tls = require('tls');
      +const fs = require('fs');
      +
      +const options = {
      +  key: fs.readFileSync('server-key.pem'),
      +  cert: fs.readFileSync('server-cert.pem'),
      +
      +  // This is necessary only if using client certificate authentication.
      +  requestCert: true,
      +
      +  // This is necessary only if the client uses a self-signed certificate.
      +  ca: [ fs.readFileSync('client-cert.pem') ]
      +};
      +
      +const server = tls.createServer(options, (socket) => {
      +  console.log('server connected',
      +              socket.authorized ? 'authorized' : 'unauthorized');
      +  socket.write('welcome!\n');
      +  socket.setEncoding('utf8');
      +  socket.pipe(socket);
      +});
      +server.listen(8000, () => {
      +  console.log('server bound');
      +});
      +

      The server can be tested by connecting to it using the example client from +tls.connect().

      +

      tls.getCiphers()#

      + + +

      Returns an array with the names of the supported TLS ciphers. The names are +lower-case for historical reasons, but must be uppercased to be used in +the ciphers option of tls.createSecureContext().

      +

      Cipher names that start with 'tls_' are for TLSv1.3, all the others are for +TLSv1.2 and below.

      +
      console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
      +

      tls.rootCertificates#

      + + +

      An immutable array of strings representing the root certificates (in PEM format) +from the bundled Mozilla CA store as supplied by current Node.js version.

      +

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store +that is fixed at release time. It is identical on all supported platforms.

      +

      tls.DEFAULT_ECDH_CURVE#

      + +

      The default curve name to use for ECDH key agreement in a tls server. The +default value is 'auto'. See tls.createSecureContext() for further +information.

      +

      tls.DEFAULT_MAX_VERSION#

      + +
        +
      • <string> The default value of the maxVersion option of +tls.createSecureContext(). It can be assigned any of the supported TLS +protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. +Default: 'TLSv1.3', unless changed using CLI options. Using +--tls-max-v1.2 sets the default to 'TLSv1.2'. Using --tls-max-v1.3 sets +the default to 'TLSv1.3'. If multiple of the options are provided, the +highest maximum is used.
      • +
      +

      tls.DEFAULT_MIN_VERSION#

      + +
        +
      • <string> The default value of the minVersion option of +tls.createSecureContext(). It can be assigned any of the supported TLS +protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. +Default: 'TLSv1.2', unless changed using CLI options. Using +--tls-min-v1.0 sets the default to 'TLSv1'. Using --tls-min-v1.1 sets +the default to 'TLSv1.1'. Using --tls-min-v1.3 sets the default to +'TLSv1.3'. If multiple of the options are provided, the lowest minimum is +used.
      • +
      + +
      +
      +
      + + diff --git a/doc/api/tls.json b/doc/api/tls.json new file mode 100644 index 0000000000000000000000000000000000000000..9b5812466bf2f8d0a02499a4da8ececbd4154cfa --- /dev/null +++ b/doc/api/tls.json @@ -0,0 +1,2070 @@ +{ + "type": "module", + "source": "doc/api/tls.md", + "modules": [ + { + "textRaw": "TLS (SSL)", + "name": "tls_(ssl)", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/tls.js

      \n

      The tls module provides an implementation of the Transport Layer Security\n(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.\nThe module can be accessed using:

      \n
      const tls = require('tls');\n
      ", + "modules": [ + { + "textRaw": "TLS/SSL concepts", + "name": "tls/ssl_concepts", + "desc": "

      The TLS/SSL is a public/private key infrastructure (PKI). For most common\ncases, each client and server must have a private key.

      \n

      Private keys can be generated in multiple ways. The example below illustrates\nuse of the OpenSSL command-line interface to generate a 2048-bit RSA private\nkey:

      \n
      openssl genrsa -out ryans-key.pem 2048\n
      \n

      With TLS/SSL, all servers (and some clients) must have a certificate.\nCertificates are public keys that correspond to a private key, and that are\ndigitally signed either by a Certificate Authority or by the owner of the\nprivate key (such certificates are referred to as \"self-signed\"). The first\nstep to obtaining a certificate is to create a Certificate Signing Request\n(CSR) file.

      \n

      The OpenSSL command-line interface can be used to generate a CSR for a private\nkey:

      \n
      openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem\n
      \n

      Once the CSR file is generated, it can either be sent to a Certificate\nAuthority for signing or used to generate a self-signed certificate.

      \n

      Creating a self-signed certificate using the OpenSSL command-line interface\nis illustrated in the example below:

      \n
      openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem\n
      \n

      Once the certificate is generated, it can be used to generate a .pfx or\n.p12 file:

      \n
      openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \\\n      -certfile ca-cert.pem -out ryans.pfx\n
      \n

      Where:

      \n
        \n
      • in: is the signed certificate
      • \n
      • inkey: is the associated private key
      • \n
      • certfile: is a concatenation of all Certificate Authority (CA) certs into\na single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
      • \n
      ", + "miscs": [ + { + "textRaw": "Perfect forward secrecy", + "name": "Perfect forward secrecy", + "type": "misc", + "desc": "

      The term forward secrecy or perfect forward secrecy describes a feature\nof key-agreement (i.e., key-exchange) methods. That is, the server and client\nkeys are used to negotiate new temporary keys that are used specifically and\nonly for the current communication session. Practically, this means that even\nif the server's private key is compromised, communication can only be decrypted\nby eavesdroppers if the attacker manages to obtain the key-pair specifically\ngenerated for the session.

      \n

      Perfect forward secrecy is achieved by randomly generating a key pair for\nkey-agreement on every TLS/SSL handshake (in contrast to using the same key for\nall sessions). Methods implementing this technique are called \"ephemeral\".

      \n

      Currently two methods are commonly used to achieve perfect forward secrecy (note\nthe character \"E\" appended to the traditional abbreviations):

      \n
        \n
      • DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.
      • \n
      • ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman\nkey-agreement protocol.
      • \n
      \n

      Ephemeral methods may have some performance drawbacks, because key generation\nis expensive.

      \n

      To use perfect forward secrecy using DHE with the tls module, it is required\nto generate Diffie-Hellman parameters and specify them with the dhparam\noption to tls.createSecureContext(). The following illustrates the use of\nthe OpenSSL command-line interface to generate such parameters:

      \n
      openssl dhparam -outform PEM -out dhparam.pem 2048\n
      \n

      If using perfect forward secrecy using ECDHE, Diffie-Hellman parameters are\nnot required and a default ECDHE curve will be used. The ecdhCurve property\ncan be used when creating a TLS Server to specify the list of names of supported\ncurves to use, see tls.createServer() for more info.

      \n

      Perfect forward secrecy was optional up to TLSv1.2, but it is not optional for\nTLSv1.3, because all TLSv1.3 cipher suites use ECDHE.

      " + }, + { + "textRaw": "ALPN and SNI", + "name": "ALPN and SNI", + "type": "misc", + "desc": "

      ALPN (Application-Layer Protocol Negotiation Extension) and\nSNI (Server Name Indication) are TLS handshake extensions:

      \n
        \n
      • ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)
      • \n
      • SNI: Allows the use of one TLS server for multiple hostnames with different\nSSL certificates.
      • \n
      " + }, + { + "textRaw": "Pre-shared keys", + "name": "Pre-shared keys", + "type": "misc", + "desc": "

      TLS-PSK support is available as an alternative to normal certificate-based\nauthentication. It uses a pre-shared key instead of certificates to\nauthenticate a TLS connection, providing mutual authentication.\nTLS-PSK and public key infrastructure are not mutually exclusive. Clients and\nservers can accommodate both, choosing either of them during the normal cipher\nnegotiation step.

      \n

      TLS-PSK is only a good choice where means exist to securely share a\nkey with every connecting machine, so it does not replace PKI\n(Public Key Infrastructure) for the majority of TLS uses.\nThe TLS-PSK implementation in OpenSSL has seen many security flaws in\nrecent years, mostly because it is used only by a minority of applications.\nPlease consider all alternative solutions before switching to PSK ciphers.\nUpon generating PSK it is of critical importance to use sufficient entropy as\ndiscussed in RFC 4086. Deriving a shared secret from a password or other\nlow-entropy sources is not secure.

      \n

      PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly\nspecifying a cipher suite with the ciphers option. The list of available\nciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3\nciphers are eligible for PSK but currently only those that use SHA256 digest are\nsupported they can be retrieved via openssl ciphers -v -s -tls1_3 -psk.

      \n

      According to the RFC 4279, PSK identities up to 128 bytes in length and\nPSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0\nmaximum identity size is 128 bytes, and maximum PSK length is 256 bytes.

      \n

      The current implementation doesn't support asynchronous PSK callbacks due to the\nlimitations of the underlying OpenSSL API.

      " + }, + { + "textRaw": "Client-initiated renegotiation attack mitigation", + "name": "Client-initiated renegotiation attack mitigation", + "type": "misc", + "desc": "

      The TLS protocol allows clients to renegotiate certain aspects of the TLS\nsession. Unfortunately, session renegotiation requires a disproportionate amount\nof server-side resources, making it a potential vector for denial-of-service\nattacks.

      \n

      To mitigate the risk, renegotiation is limited to three times every ten minutes.\nAn 'error' event is emitted on the tls.TLSSocket instance when this\nthreshold is exceeded. The limits are configurable:

      \n
        \n
      • tls.CLIENT_RENEG_LIMIT <number> Specifies the number of renegotiation\nrequests. Default: 3.
      • \n
      • tls.CLIENT_RENEG_WINDOW <number> Specifies the time renegotiation window\nin seconds. Default: 600 (10 minutes).
      • \n
      \n

      The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.

      \n

      TLSv1.3 does not support renegotiation.

      " + } + ], + "modules": [ + { + "textRaw": "Session resumption", + "name": "session_resumption", + "desc": "

      Establishing a TLS session can be relatively slow. The process can be sped\nup by saving and later reusing the session state. There are several mechanisms\nto do so, discussed here from oldest to newest (and preferred).

      ", + "modules": [ + { + "textRaw": "Session identifiers", + "name": "session_identifiers", + "desc": "

      Servers generate a unique ID for new connections and\nsend it to the client. Clients and servers save the session state. When\nreconnecting, clients send the ID of their saved session state and if the server\nalso has the state for that ID, it can agree to use it. Otherwise, the server\nwill create a new session. See RFC 2246 for more information, page 23 and\n30.

      \n

      Resumption using session identifiers is supported by most web browsers when\nmaking HTTPS requests.

      \n

      For Node.js, clients wait for the 'session' event to get the session data,\nand provide the data to the session option of a subsequent tls.connect()\nto reuse the session. Servers must\nimplement handlers for the 'newSession' and 'resumeSession' events\nto save and restore the session data using the session ID as the lookup key to\nreuse sessions. To reuse sessions across load balancers or cluster workers,\nservers must use a shared session cache (such as Redis) in their session\nhandlers.

      ", + "type": "module", + "displayName": "Session identifiers" + }, + { + "textRaw": "Session tickets", + "name": "session_tickets", + "desc": "

      The servers encrypt the entire session state and send it\nto the client as a \"ticket\". When reconnecting, the state is sent to the server\nin the initial connection. This mechanism avoids the need for server-side\nsession cache. If the server doesn't use the ticket, for any reason (failure\nto decrypt it, it's too old, etc.), it will create a new session and send a new\nticket. See RFC 5077 for more information.

      \n

      Resumption using session tickets is becoming commonly supported by many web\nbrowsers when making HTTPS requests.

      \n

      For Node.js, clients use the same APIs for resumption with session identifiers\nas for resumption with session tickets. For debugging, if\ntls.TLSSocket.getTLSTicket() returns a value, the session data contains a\nticket, otherwise it contains client-side session state.

      \n

      With TLSv1.3, be aware that multiple tickets may be sent by the server,\nresulting in multiple 'session' events, see 'session' for more\ninformation.

      \n

      Single process servers need no specific implementation to use session tickets.\nTo use session tickets across server restarts or load balancers, servers must\nall have the same ticket keys. There are three 16-byte keys internally, but the\ntls API exposes them as a single 48-byte buffer for convenience.

      \n

      Its possible to get the ticket keys by calling server.getTicketKeys() on\none server instance and then distribute them, but it is more reasonable to\nsecurely generate 48 bytes of secure random data and set them with the\nticketKeys option of tls.createServer(). The keys should be regularly\nregenerated and server's keys can be reset with\nserver.setTicketKeys().

      \n

      Session ticket keys are cryptographic keys, and they must be stored\nsecurely. With TLS 1.2 and below, if they are compromised all sessions that\nused tickets encrypted with them can be decrypted. They should not be stored\non disk, and they should be regenerated regularly.

      \n

      If clients advertise support for tickets, the server will send them. The\nserver can disable tickets by supplying\nrequire('constants').SSL_OP_NO_TICKET in secureOptions.

      \n

      Both session identifiers and session tickets timeout, causing the server to\ncreate new sessions. The timeout can be configured with the sessionTimeout\noption of tls.createServer().

      \n

      For all the mechanisms, when resumption fails, servers will create new sessions.\nSince failing to resume the session does not cause TLS/HTTPS connection\nfailures, it is easy to not notice unnecessarily poor TLS performance. The\nOpenSSL CLI can be used to verify that servers are resuming sessions. Use the\n-reconnect option to openssl s_client, for example:

      \n
      $ openssl s_client -connect localhost:443 -reconnect\n
      \n

      Read through the debug output. The first connection should say \"New\", for\nexample:

      \n
      New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256\n
      \n

      Subsequent connections should say \"Reused\", for example:

      \n
      Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256\n
      ", + "type": "module", + "displayName": "Session tickets" + } + ], + "type": "module", + "displayName": "Session resumption" + } + ], + "type": "module", + "displayName": "TLS/SSL concepts" + }, + { + "textRaw": "Modifying the default TLS cipher suite", + "name": "modifying_the_default_tls_cipher_suite", + "desc": "

      Node.js is built with a default suite of enabled and disabled TLS ciphers. This\ndefault cipher list can be configured when building Node.js to allow\ndistributions to provide their own default list.

      \n

      The following command can be used to show the default cipher suite:

      \n
      node -p crypto.constants.defaultCoreCipherList | tr ':' '\\n'\nTLS_AES_256_GCM_SHA384\nTLS_CHACHA20_POLY1305_SHA256\nTLS_AES_128_GCM_SHA256\nECDHE-RSA-AES128-GCM-SHA256\nECDHE-ECDSA-AES128-GCM-SHA256\nECDHE-RSA-AES256-GCM-SHA384\nECDHE-ECDSA-AES256-GCM-SHA384\nDHE-RSA-AES128-GCM-SHA256\nECDHE-RSA-AES128-SHA256\nDHE-RSA-AES128-SHA256\nECDHE-RSA-AES256-SHA384\nDHE-RSA-AES256-SHA384\nECDHE-RSA-AES256-SHA256\nDHE-RSA-AES256-SHA256\nHIGH\n!aNULL\n!eNULL\n!EXPORT\n!DES\n!RC4\n!MD5\n!PSK\n!SRP\n!CAMELLIA\n
      \n

      This default can be replaced entirely using the --tls-cipher-list command\nline switch (directly, or via the NODE_OPTIONS environment variable). For\ninstance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS\ncipher suite:

      \n
      node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js\n\nexport NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'\nnode server.js\n
      \n

      The default can also be replaced on a per client or server basis using the\nciphers option from tls.createSecureContext(), which is also available\nin tls.createServer(), tls.connect(), and when creating new\ntls.TLSSockets.

      \n

      The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones\nthat start with 'TLS_', and specifications for TLSv1.2 and below cipher\nsuites. The TLSv1.2 ciphers support a legacy specification format, consult\nthe OpenSSL cipher list format documentation for details, but those\nspecifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only\nbe enabled by including their full name in the cipher list. They cannot, for\nexample, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or\n'!EECDH' specification.

      \n

      Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3\nprotocol is significantly more secure than TLSv1.2, and will always be chosen\nover TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3\ncipher suites are enabled.

      \n

      The default cipher suite included within Node.js has been carefully\nselected to reflect current security best practices and risk mitigation.\nChanging the default cipher suite can have a significant impact on the security\nof an application. The --tls-cipher-list switch and ciphers option should by\nused only if absolutely necessary.

      \n

      The default cipher suite prefers GCM ciphers for Chrome's 'modern\ncryptography' setting and also prefers ECDHE and DHE ciphers for perfect\nforward secrecy, while offering some backward compatibility.

      \n

      128 bit AES is preferred over 192 and 256 bit AES in light of specific\nattacks affecting larger AES key sizes.

      \n

      Old clients that rely on insecure and deprecated RC4 or DES-based ciphers\n(like Internet Explorer 6) cannot complete the handshaking process with\nthe default configuration. If these clients must be supported, the\nTLS recommendations may offer a compatible cipher suite. For more details\non the format, see the OpenSSL cipher list format documentation.

      \n

      There are only 5 TLSv1.3 cipher suites:

      \n
        \n
      • 'TLS_AES_256_GCM_SHA384'
      • \n
      • 'TLS_CHACHA20_POLY1305_SHA256'
      • \n
      • 'TLS_AES_128_GCM_SHA256'
      • \n
      • 'TLS_AES_128_CCM_SHA256'
      • \n
      • 'TLS_AES_128_CCM_8_SHA256'
      • \n
      \n

      The first 3 are enabled by default. The last 2 CCM-based suites are supported\nby TLSv1.3 because they may be more performant on constrained systems, but they\nare not enabled by default since they offer less security.

      ", + "type": "module", + "displayName": "Modifying the default TLS cipher suite" + } + ], + "classes": [ + { + "textRaw": "Class: `tls.CryptoStream`", + "type": "class", + "name": "tls.CryptoStream", + "meta": { + "added": [ + "v0.3.4" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", + "desc": "

      The tls.CryptoStream class represents a stream of encrypted data. This class\nis deprecated and should no longer be used.

      ", + "properties": [ + { + "textRaw": "`cryptoStream.bytesWritten`", + "name": "bytesWritten", + "meta": { + "added": [ + "v0.3.4" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "desc": "

      The cryptoStream.bytesWritten property returns the total number of bytes\nwritten to the underlying socket including the bytes required for the\nimplementation of the TLS protocol.

      " + } + ] + }, + { + "textRaw": "Class: `tls.SecurePair`", + "type": "class", + "name": "tls.SecurePair", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", + "desc": "

      Returned by tls.createSecurePair().

      ", + "events": [ + { + "textRaw": "Event: `'secure'`", + "type": "event", + "name": "secure", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'secure' event is emitted by the SecurePair object once a secure\nconnection has been established.

      \n

      As with checking for the server\n'secureConnection'\nevent, pair.cleartext.authorized should be inspected to confirm whether the\ncertificate used is properly authorized.

      " + } + ] + }, + { + "textRaw": "Class: `tls.Server`", + "type": "class", + "name": "tls.Server", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "desc": "\n

      Accepts encrypted connections using TLS or SSL.

      ", + "events": [ + { + "textRaw": "Event: `'connection'`", + "type": "event", + "name": "connection", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`socket` {stream.Duplex}", + "name": "socket", + "type": "stream.Duplex" + } + ], + "desc": "

      This event is emitted when a new TCP stream is established, before the TLS\nhandshake begins. socket is typically an object of type net.Socket.\nUsually users will not want to access this event.

      \n

      This event can also be explicitly emitted by users to inject connections\ninto the TLS server. In that case, any Duplex stream can be passed.

      " + }, + { + "textRaw": "Event: `'keylog'`", + "type": "event", + "name": "keylog", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`line` {Buffer} Line of ASCII text, in NSS `SSLKEYLOGFILE` format.", + "name": "line", + "type": "Buffer", + "desc": "Line of ASCII text, in NSS `SSLKEYLOGFILE` format." + }, + { + "textRaw": "`tlsSocket` {tls.TLSSocket} The `tls.TLSSocket` instance on which it was generated.", + "name": "tlsSocket", + "type": "tls.TLSSocket", + "desc": "The `tls.TLSSocket` instance on which it was generated." + } + ], + "desc": "

      The keylog event is emitted when key material is generated or received by\na connection to this server (typically before handshake has completed, but not\nnecessarily). This keying material can be stored for debugging, as it allows\ncaptured TLS traffic to be decrypted. It may be emitted multiple times for\neach socket.

      \n

      A typical use case is to append received lines to a common text file, which\nis later used by software (such as Wireshark) to decrypt the traffic:

      \n
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });\n// ...\nserver.on('keylog', (line, tlsSocket) => {\n  if (tlsSocket.remoteAddress !== '...')\n    return; // Only log keys for a particular IP\n  logFile.write(line);\n});\n
      " + }, + { + "textRaw": "Event: `'newSession'`", + "type": "event", + "name": "newSession", + "meta": { + "added": [ + "v0.9.2" + ], + "changes": [ + { + "version": "v0.11.12", + "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7118", + "description": "The `callback` argument is now supported." + } + ] + }, + "params": [], + "desc": "

      The 'newSession' event is emitted upon creation of a new TLS session. This may\nbe used to store sessions in external storage. The data should be provided to\nthe 'resumeSession' callback.

      \n

      The listener callback is passed three arguments when called:

      \n
        \n
      • sessionId <Buffer> The TLS session identifier
      • \n
      • sessionData <Buffer> The TLS session data
      • \n
      • callback <Function> A callback function taking no arguments that must be\ninvoked in order for data to be sent or received over the secure connection.
      • \n
      \n

      Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

      " + }, + { + "textRaw": "Event: `'OCSPRequest'`", + "type": "event", + "name": "OCSPRequest", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'OCSPRequest' event is emitted when the client sends a certificate status\nrequest. The listener callback is passed three arguments when called:

      \n
        \n
      • certificate <Buffer> The server certificate
      • \n
      • issuer <Buffer> The issuer's certificate
      • \n
      • callback <Function> A callback function that must be invoked to provide\nthe results of the OCSP request.
      • \n
      \n

      The server's current certificate can be parsed to obtain the OCSP URL\nand certificate ID; after obtaining an OCSP response, callback(null, resp) is\nthen invoked, where resp is a Buffer instance containing the OCSP response.\nBoth certificate and issuer are Buffer DER-representations of the\nprimary and issuer's certificates. These can be used to obtain the OCSP\ncertificate ID and OCSP endpoint URL.

      \n

      Alternatively, callback(null, null) may be called, indicating that there was\nno OCSP response.

      \n

      Calling callback(err) will result in a socket.destroy(err) call.

      \n

      The typical flow of an OCSP Request is as follows:

      \n
        \n
      1. Client connects to the server and sends an 'OCSPRequest' (via the status\ninfo extension in ClientHello).
      2. \n
      3. Server receives the request and emits the 'OCSPRequest' event, calling the\nlistener if registered.
      4. \n
      5. Server extracts the OCSP URL from either the certificate or issuer and\nperforms an OCSP request to the CA.
      6. \n
      7. Server receives 'OCSPResponse' from the CA and sends it back to the client\nvia the callback argument
      8. \n
      9. Client validates the response and either destroys the socket or performs a\nhandshake.
      10. \n
      \n

      The issuer can be null if the certificate is either self-signed or the\nissuer is not in the root certificates list. (An issuer may be provided\nvia the ca option when establishing the TLS connection.)

      \n

      Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

      \n

      An npm module like asn1.js may be used to parse the certificates.

      " + }, + { + "textRaw": "Event: `'resumeSession'`", + "type": "event", + "name": "resumeSession", + "meta": { + "added": [ + "v0.9.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resumeSession' event is emitted when the client requests to resume a\nprevious TLS session. The listener callback is passed two arguments when\ncalled:

      \n
        \n
      • sessionId <Buffer> The TLS session identifier
      • \n
      • callback <Function> A callback function to be called when the prior session\nhas been recovered: callback([err[, sessionData]])\n\n
      • \n
      \n

      The event listener should perform a lookup in external storage for the\nsessionData saved by the 'newSession' event handler using the given\nsessionId. If found, call callback(null, sessionData) to resume the session.\nIf not found, the session cannot be resumed. callback() must be called\nwithout sessionData so that the handshake can continue and a new session can\nbe created. It is possible to call callback(err) to terminate the incoming\nconnection and destroy the socket.

      \n

      Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

      \n

      The following illustrates resuming a TLS session:

      \n
      const tlsSessionStore = {};\nserver.on('newSession', (id, data, cb) => {\n  tlsSessionStore[id.toString('hex')] = data;\n  cb();\n});\nserver.on('resumeSession', (id, cb) => {\n  cb(null, tlsSessionStore[id.toString('hex')] || null);\n});\n
      " + }, + { + "textRaw": "Event: `'secureConnection'`", + "type": "event", + "name": "secureConnection", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'secureConnection' event is emitted after the handshaking process for a\nnew connection has successfully completed. The listener callback is passed a\nsingle argument when called:

      \n\n

      The tlsSocket.authorized property is a boolean indicating whether the\nclient has been verified by one of the supplied Certificate Authorities for the\nserver. If tlsSocket.authorized is false, then socket.authorizationError\nis set to describe how authorization failed. Depending on the settings\nof the TLS server, unauthorized connections may still be accepted.

      \n

      The tlsSocket.alpnProtocol property is a string that contains the selected\nALPN protocol. When ALPN has no selected protocol, tlsSocket.alpnProtocol\nequals false.

      \n

      The tlsSocket.servername property is a string containing the server name\nrequested via SNI.

      " + }, + { + "textRaw": "Event: `'tlsClientError'`", + "type": "event", + "name": "tlsClientError", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'tlsClientError' event is emitted when an error occurs before a secure\nconnection is established. The listener callback is passed two arguments when\ncalled:

      \n
        \n
      • exception <Error> The Error object describing the error
      • \n
      • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance from which the\nerror originated.
      • \n
      " + } + ], + "methods": [ + { + "textRaw": "`server.addContext(hostname, context)`", + "type": "method", + "name": "addContext", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`hostname` {string} A SNI host name or wildcard (e.g. `'*'`)", + "name": "hostname", + "type": "string", + "desc": "A SNI host name or wildcard (e.g. `'*'`)" + }, + { + "textRaw": "`context` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc).", + "name": "context", + "type": "Object", + "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." + } + ] + } + ], + "desc": "

      The server.addContext() method adds a secure context that will be used if\nthe client request's SNI name matches the supplied hostname (or wildcard).

      " + }, + { + "textRaw": "`server.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name, and port of the\nserver as reported by the operating system. See net.Server.address() for\nmore information.

      " + }, + { + "textRaw": "`server.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.Server}", + "name": "return", + "type": "tls.Server" + }, + "params": [ + { + "textRaw": "`callback` {Function} A listener callback that will be registered to listen for the server instance's `'close'` event.", + "name": "callback", + "type": "Function", + "desc": "A listener callback that will be registered to listen for the server instance's `'close'` event." + } + ] + } + ], + "desc": "

      The server.close() method stops the server from accepting new connections.

      \n

      This function operates asynchronously. The 'close' event will be emitted\nwhen the server has no more open connections.

      " + }, + { + "textRaw": "`server.getTicketKeys()`", + "type": "method", + "name": "getTicketKeys", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} A 48-byte buffer containing the session ticket keys.", + "name": "return", + "type": "Buffer", + "desc": "A 48-byte buffer containing the session ticket keys." + }, + "params": [] + } + ], + "desc": "

      Returns the session ticket keys.

      \n

      See Session Resumption for more information.

      " + }, + { + "textRaw": "`server.listen()`", + "type": "method", + "name": "listen", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Starts the server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.

      " + }, + { + "textRaw": "`server.setSecureContext(options)`", + "type": "method", + "name": "setSecureContext", + "meta": { + "added": [ + "v11.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc).", + "name": "options", + "type": "Object", + "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." + } + ] + } + ], + "desc": "

      The server.setSecureContext() method replaces the secure context of an\nexisting server. Existing connections to the server are not interrupted.

      " + }, + { + "textRaw": "`server.setTicketKeys(keys)`", + "type": "method", + "name": "setTicketKeys", + "meta": { + "added": [ + "v3.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`keys` {Buffer} A 48-byte buffer containing the session ticket keys.", + "name": "keys", + "type": "Buffer", + "desc": "A 48-byte buffer containing the session ticket keys." + } + ] + } + ], + "desc": "

      Sets the session ticket keys.

      \n

      Changes to the ticket keys are effective only for future server connections.\nExisting or currently pending server connections will use the previous keys.

      \n

      See Session Resumption for more information.

      " + } + ], + "properties": [ + { + "textRaw": "`connections` {number}", + "type": "number", + "name": "connections", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.9.7" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", + "desc": "

      Returns the current number of concurrent connections on the server.

      " + } + ] + }, + { + "textRaw": "Class: `tls.TLSSocket`", + "type": "class", + "name": "tls.TLSSocket", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "\n

      Performs transparent encryption of written data and all required TLS\nnegotiation.

      \n

      Instances of tls.TLSSocket implement the duplex Stream interface.

      \n

      Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate() will only return data while the\nconnection is open.

      ", + "events": [ + { + "textRaw": "Event: `'keylog'`", + "type": "event", + "name": "keylog", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`line` {Buffer} Line of ASCII text, in NSS `SSLKEYLOGFILE` format.", + "name": "line", + "type": "Buffer", + "desc": "Line of ASCII text, in NSS `SSLKEYLOGFILE` format." + } + ], + "desc": "

      The keylog event is emitted on a tls.TLSSocket when key material\nis generated or received by the socket. This keying material can be stored\nfor debugging, as it allows captured TLS traffic to be decrypted. It may\nbe emitted multiple times, before or after the handshake completes.

      \n

      A typical use case is to append received lines to a common text file, which\nis later used by software (such as Wireshark) to decrypt the traffic:

      \n
      const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });\n// ...\ntlsSocket.on('keylog', (line) => logFile.write(line));\n
      " + }, + { + "textRaw": "Event: `'OCSPResponse'`", + "type": "event", + "name": "OCSPResponse", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'OCSPResponse' event is emitted if the requestOCSP option was set\nwhen the tls.TLSSocket was created and an OCSP response has been received.\nThe listener callback is passed a single argument when called:

      \n
        \n
      • response <Buffer> The server's OCSP response
      • \n
      \n

      Typically, the response is a digitally signed object from the server's CA that\ncontains information about server's certificate revocation status.

      " + }, + { + "textRaw": "Event: `'secureConnect'`", + "type": "event", + "name": "secureConnect", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'secureConnect' event is emitted after the handshaking process for a new\nconnection has successfully completed. The listener callback will be called\nregardless of whether or not the server's certificate has been authorized. It\nis the client's responsibility to check the tlsSocket.authorized property to\ndetermine if the server certificate was signed by one of the specified CAs. If\ntlsSocket.authorized === false, then the error can be found by examining the\ntlsSocket.authorizationError property. If ALPN was used, the\ntlsSocket.alpnProtocol property can be checked to determine the negotiated\nprotocol.

      " + }, + { + "textRaw": "Event: `'session'`", + "type": "event", + "name": "session", + "meta": { + "added": [ + "v11.10.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`session` {Buffer}", + "name": "session", + "type": "Buffer" + } + ], + "desc": "

      The 'session' event is emitted on a client tls.TLSSocket when a new session\nor TLS ticket is available. This may or may not be before the handshake is\ncomplete, depending on the TLS protocol version that was negotiated. The event\nis not emitted on the server, or if a new session was not created, for example,\nwhen the connection was resumed. For some TLS protocol versions the event may be\nemitted multiple times, in which case all the sessions can be used for\nresumption.

      \n

      On the client, the session can be provided to the session option of\ntls.connect() to resume the connection.

      \n

      See Session Resumption for more information.

      \n

      For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once\nthe handshake is complete. For TLSv1.3, only ticket-based resumption is allowed\nby the protocol, multiple tickets are sent, and the tickets aren't sent until\nafter the handshake completes. So it is necessary to wait for the\n'session' event to get a resumable session. Applications\nshould use the 'session' event instead of getSession() to ensure\nthey will work for all TLS versions. Applications that only expect to\nget or use one session should listen for this event only once:

      \n
      tlsSocket.once('session', (session) => {\n  // The session can be used immediately or later.\n  tls.connect({\n    session: session,\n    // Other connect options...\n  });\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`tlsSocket.address()`", + "type": "method", + "name": "address", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns the bound address, the address family name, and port of the\nunderlying socket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

      " + }, + { + "textRaw": "`tlsSocket.disableRenegotiation()`", + "type": "method", + "name": "disableRenegotiation", + "meta": { + "added": [ + "v8.4.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disables TLS renegotiation for this TLSSocket instance. Once called, attempts\nto renegotiate will trigger an 'error' event on the TLSSocket.

      " + }, + { + "textRaw": "`tlsSocket.enableTrace()`", + "type": "method", + "name": "enableTrace", + "meta": { + "added": [ + "v12.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      When enabled, TLS packet trace information is written to stderr. This can be\nused to debug TLS connection problems.

      \n

      Note: The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's\nSSL_trace() function, the format is undocumented, can change without notice,\nand should not be relied on.

      " + }, + { + "textRaw": "`tlsSocket.getCertificate()`", + "type": "method", + "name": "getCertificate", + "meta": { + "added": [ + "v11.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object representing the local certificate. The returned object has\nsome properties corresponding to the fields of the certificate.

      \n

      See tls.TLSSocket.getPeerCertificate() for an example of the certificate\nstructure.

      \n

      If there is no local certificate, an empty object will be returned. If the\nsocket has been destroyed, null will be returned.

      " + }, + { + "textRaw": "`tlsSocket.getCipher()`", + "type": "method", + "name": "getCipher", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [ + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26625", + "description": "Return the minimum cipher version, instead of a fixed string (`'TLSv1/SSLv3'`)." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30637", + "description": "Return the IETF cipher name as `standardName`." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`name` {string} OpenSSL name for the cipher suite.", + "name": "name", + "type": "string", + "desc": "OpenSSL name for the cipher suite." + }, + { + "textRaw": "`standardName` {string} IETF name for the cipher suite.", + "name": "standardName", + "type": "string", + "desc": "IETF name for the cipher suite." + }, + { + "textRaw": "`version` {string} The minimum TLS protocol version supported by this cipher suite.", + "name": "version", + "type": "string", + "desc": "The minimum TLS protocol version supported by this cipher suite." + } + ] + }, + "params": [] + } + ], + "desc": "

      Returns an object containing information on the negotiated cipher suite.

      \n

      For example:

      \n
      {\n    \"name\": \"AES128-SHA256\",\n    \"standardName\": \"TLS_RSA_WITH_AES_128_CBC_SHA256\",\n    \"version\": \"TLSv1.2\"\n}\n
      \n

      See\nSSL_CIPHER_get_name\nfor more information.

      " + }, + { + "textRaw": "`tlsSocket.getEphemeralKeyInfo()`", + "type": "method", + "name": "getEphemeralKeyInfo", + "meta": { + "added": [ + "v5.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object representing the type, name, and size of parameter of\nan ephemeral key exchange in perfect forward secrecy on a client\nconnection. It returns an empty object when the key exchange is not\nephemeral. As this is only supported on a client socket; null is returned\nif called on a server socket. The supported types are 'DH' and 'ECDH'. The\nname property is available only when type is 'ECDH'.

      \n

      For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

      " + }, + { + "textRaw": "`tlsSocket.getFinished()`", + "type": "method", + "name": "getFinished", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|undefined} The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet.", + "name": "return", + "type": "Buffer|undefined", + "desc": "The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet." + }, + "params": [] + } + ], + "desc": "

      As the Finished messages are message digests of the complete handshake\n(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can\nbe used for external authentication procedures when the authentication\nprovided by SSL/TLS is not desired or is not enough.

      \n

      Corresponds to the SSL_get_finished routine in OpenSSL and may be used\nto implement the tls-unique channel binding from RFC 5929.

      " + }, + { + "textRaw": "`tlsSocket.getPeerCertificate([detailed])`", + "type": "method", + "name": "getPeerCertificate", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} A certificate object.", + "name": "return", + "type": "Object", + "desc": "A certificate object." + }, + "params": [ + { + "textRaw": "`detailed` {boolean} Include the full certificate chain if `true`, otherwise include just the peer's certificate.", + "name": "detailed", + "type": "boolean", + "desc": "Include the full certificate chain if `true`, otherwise include just the peer's certificate." + } + ] + } + ], + "desc": "

      Returns an object representing the peer's certificate. If the peer does not\nprovide a certificate, an empty object will be returned. If the socket has been\ndestroyed, null will be returned.

      \n

      If the full certificate chain was requested, each certificate will include an\nissuerCertificate property containing an object representing its issuer's\ncertificate.

      ", + "modules": [ + { + "textRaw": "Certificate object", + "name": "certificate_object", + "meta": { + "changes": [ + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24358", + "description": "Support Elliptic Curve public key info." + } + ] + }, + "desc": "

      A certificate object has properties corresponding to the fields of the\ncertificate.

      \n
        \n
      • raw <Buffer> The DER encoded X.509 certificate data.
      • \n
      • subject <Object> The certificate subject, described in terms of\n Country (C:), StateOrProvince (ST), Locality (L), Organization (O),\nOrganizationalUnit (OU), and CommonName (CN). The CommonName is typically\na DNS name with TLS certificates. Example:\n{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.
      • \n
      • issuer <Object> The certificate issuer, described in the same terms as the\n subject.
      • \n
      • valid_from <string> The date-time the certificate is valid from.
      • \n
      • valid_to <string> The date-time the certificate is valid to.
      • \n
      • serialNumber <string> The certificate serial number, as a hex string.\n Example: 'B9B0D332A1AA5635'.
      • \n
      • fingerprint <string> The SHA-1 digest of the DER encoded certificate. It is\nreturned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
      • \n
      • fingerprint256 <string> The SHA-256 digest of the DER encoded certificate.\n It is returned as a : separated hexadecimal string. Example:\n'2A:7A:C2:DD:...'.
      • \n
      • ext_key_usage <Array> (Optional) The extended key usage, a set of OIDs.
      • \n
      • subjectaltname <string> (Optional) A string containing concatenated names\nfor the subject, an alternative to the subject names.
      • \n
      • infoAccess <Array> (Optional) An array describing the AuthorityInfoAccess,\n used with OCSP.
      • \n
      • issuerCertificate <Object> (Optional) The issuer certificate object. For\n self-signed certificates, this may be a circular reference.
      • \n
      \n

      The certificate may contain information about the public key, depending on\nthe key type.

      \n

      For RSA keys, the following properties may be defined:

      \n
        \n
      • bits <number> The RSA bit size. Example: 1024.
      • \n
      • exponent <string> The RSA exponent, as a string in hexadecimal number\nnotation. Example: '0x010001'.
      • \n
      • modulus <string> The RSA modulus, as a hexadecimal string. Example:\n 'B56CE45CB7...'.
      • \n
      • pubkey <Buffer> The public key.
      • \n
      \n

      For EC keys, the following properties may be defined:

      \n
        \n
      • pubkey <Buffer> The public key.
      • \n
      • bits <number> The key size in bits. Example: 256.
      • \n
      • asn1Curve <string> (Optional) The ASN.1 name of the OID of the elliptic\ncurve. Well-known curves are identified by an OID. While it is unusual, it is\npossible that the curve is identified by its mathematical properties, in which\ncase it will not have an OID. Example: 'prime256v1'.
      • \n
      • nistCurve <string> (Optional) The NIST name for the elliptic curve, if it\nhas one (not all well-known curves have been assigned names by NIST). Example:\n'P-256'.
      • \n
      \n

      Example certificate:

      \n\n
      { subject:\n   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],\n     CN: '*.nodejs.org' },\n  issuer:\n   { C: 'GB',\n     ST: 'Greater Manchester',\n     L: 'Salford',\n     O: 'COMODO CA Limited',\n     CN: 'COMODO RSA Domain Validation Secure Server CA' },\n  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',\n  infoAccess:\n   { 'CA Issuers - URI':\n      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],\n     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },\n  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',\n  exponent: '0x10001',\n  pubkey: <Buffer ... >,\n  valid_from: 'Aug 14 00:00:00 2017 GMT',\n  valid_to: 'Nov 20 23:59:59 2019 GMT',\n  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',\n  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',\n  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],\n  serialNumber: '66593D57F20CBC573E433381B5FEC280',\n  raw: <Buffer ... > }\n
      ", + "type": "module", + "displayName": "Certificate object" + } + ] + }, + { + "textRaw": "`tlsSocket.getPeerFinished()`", + "type": "method", + "name": "getPeerFinished", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer|undefined} The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so far.", + "name": "return", + "type": "Buffer|undefined", + "desc": "The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so far." + }, + "params": [] + } + ], + "desc": "

      As the Finished messages are message digests of the complete handshake\n(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can\nbe used for external authentication procedures when the authentication\nprovided by SSL/TLS is not desired or is not enough.

      \n

      Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used\nto implement the tls-unique channel binding from RFC 5929.

      " + }, + { + "textRaw": "`tlsSocket.getProtocol()`", + "type": "method", + "name": "getProtocol", + "meta": { + "added": [ + "v5.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string|null}", + "name": "return", + "type": "string|null" + }, + "params": [] + } + ], + "desc": "

      Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. The value 'unknown' will be returned for connected\nsockets that have not completed the handshaking process. The value null will\nbe returned for server sockets or disconnected client sockets.

      \n

      Protocol versions are:

      \n
        \n
      • 'SSLv3'
      • \n
      • 'TLSv1'
      • \n
      • 'TLSv1.1'
      • \n
      • 'TLSv1.2'
      • \n
      • 'TLSv1.3'
      • \n
      \n

      See the OpenSSL SSL_get_version documentation for more information.

      " + }, + { + "textRaw": "`tlsSocket.getSession()`", + "type": "method", + "name": "getSession", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "{Buffer}", + "type": "Buffer" + } + ] + } + ], + "desc": "

      Returns the TLS session data or undefined if no session was\nnegotiated. On the client, the data can be provided to the session option of\ntls.connect() to resume the connection. On the server, it may be useful\nfor debugging.

      \n

      See Session Resumption for more information.

      \n

      Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications\nmust use the 'session' event (it also works for TLSv1.2 and below).

      " + }, + { + "textRaw": "`tlsSocket.getSharedSigalgs()`", + "type": "method", + "name": "getSharedSigalgs", + "meta": { + "added": [ + "v12.11.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Array} List of signature algorithms shared between the server and the client in the order of decreasing preference.", + "name": "return", + "type": "Array", + "desc": "List of signature algorithms shared between the server and the client in the order of decreasing preference." + }, + "params": [] + } + ], + "desc": "

      See\nSSL_get_shared_sigalgs\nfor more information.

      " + }, + { + "textRaw": "`tlsSocket.exportKeyingMaterial(length, label[, context])`", + "type": "method", + "name": "exportKeyingMaterial", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer} requested bytes of the keying material", + "name": "return", + "type": "Buffer", + "desc": "requested bytes of the keying material" + }, + "params": [ + { + "textRaw": "`length` {number} number of bytes to retrieve from keying material", + "name": "length", + "type": "number", + "desc": "number of bytes to retrieve from keying material" + }, + { + "textRaw": "`label` {string} an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).", + "name": "label", + "type": "string", + "desc": "an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels)." + }, + { + "textRaw": "`context` {Buffer} Optionally provide a context.", + "name": "context", + "type": "Buffer", + "desc": "Optionally provide a context." + } + ] + } + ], + "desc": "

      Keying material is used for validations to prevent different kind of attacks in\nnetwork protocols, for example in the specifications of IEEE 802.1X.

      \n

      Example

      \n
      const keyingMaterial = tlsSocket.exportKeyingMaterial(\n  128,\n  'client finished');\n\n/**\n Example return value of keyingMaterial:\n <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9\n    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91\n    74 ef 2c ... 78 more bytes>\n*/\n
      \n

      See the OpenSSL SSL_export_keying_material documentation for more\ninformation.

      " + }, + { + "textRaw": "`tlsSocket.getTLSTicket()`", + "type": "method", + "name": "getTLSTicket", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "{Buffer}", + "type": "Buffer" + } + ] + } + ], + "desc": "

      For a client, returns the TLS session ticket if one is available, or\nundefined. For a server, always returns undefined.

      \n

      It may be useful for debugging.

      \n

      See Session Resumption for more information.

      " + }, + { + "textRaw": "`tlsSocket.isSessionReused()`", + "type": "method", + "name": "isSessionReused", + "meta": { + "added": [ + "v0.5.6" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if the session was reused, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if the session was reused, `false` otherwise." + }, + "params": [] + } + ], + "desc": "

      See Session Resumption for more information.

      " + }, + { + "textRaw": "`tlsSocket.renegotiate(options, callback)`", + "type": "method", + "name": "renegotiate", + "meta": { + "added": [ + "v0.11.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `true` if renegotiation was initiated, `false` otherwise.", + "name": "return", + "type": "boolean", + "desc": "`true` if renegotiation was initiated, `false` otherwise." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "default": "`true`", + "desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code." + }, + { + "textRaw": "`requestCert`", + "name": "requestCert" + } + ] + }, + { + "textRaw": "`callback` {Function} If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.", + "name": "callback", + "type": "Function", + "desc": "If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all." + } + ] + } + ], + "desc": "

      The tlsSocket.renegotiate() method initiates a TLS renegotiation process.\nUpon completion, the callback function will be passed a single argument\nthat is either an Error (if the request failed) or null.

      \n

      This method can be used to request a peer's certificate after the secure\nconnection has been established.

      \n

      When running as the server, the socket will be destroyed with an error after\nhandshakeTimeout timeout.

      \n

      For TLSv1.3, renegotiation cannot be initiated, it is not supported by the\nprotocol.

      " + }, + { + "textRaw": "`tlsSocket.setMaxSendFragment(size)`", + "type": "method", + "name": "setMaxSendFragment", + "meta": { + "added": [ + "v0.11.11" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`size` {number} The maximum TLS fragment size. The maximum value is `16384`. **Default:** `16384`.", + "name": "size", + "type": "number", + "default": "`16384`", + "desc": "The maximum TLS fragment size. The maximum value is `16384`." + } + ] + } + ], + "desc": "

      The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size.\nReturns true if setting the limit succeeded; false otherwise.

      \n

      Smaller fragment sizes decrease the buffering latency on the client: larger\nfragments are buffered by the TLS layer until the entire fragment is received\nand its integrity is verified; large fragments can span multiple roundtrips\nand their processing can be delayed due to packet loss or reordering. However,\nsmaller fragments add extra TLS framing bytes and CPU overhead, which may\ndecrease overall server throughput.

      " + } + ], + "properties": [ + { + "textRaw": "`tlsSocket.authorizationError`", + "name": "authorizationError", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the reason why the peer's certificate was not been verified. This\nproperty is set only when tlsSocket.authorized === false.

      " + }, + { + "textRaw": "`authorized` Returns: {boolean}", + "type": "boolean", + "name": "return", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns true if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket instance, otherwise false.

      " + }, + { + "textRaw": "`tlsSocket.encrypted`", + "name": "encrypted", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Always returns true. This may be used to distinguish TLS sockets from regular\nnet.Socket instances.

      " + }, + { + "textRaw": "`localAddress` {string}", + "type": "string", + "name": "localAddress", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the string representation of the local IP address.

      " + }, + { + "textRaw": "`localPort` {number}", + "type": "number", + "name": "localPort", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the numeric representation of the local port.

      " + }, + { + "textRaw": "`remoteAddress` {string}", + "type": "string", + "name": "remoteAddress", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.

      " + }, + { + "textRaw": "`remoteFamily` {string}", + "type": "string", + "name": "remoteFamily", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

      " + }, + { + "textRaw": "`remotePort` {number}", + "type": "number", + "name": "remotePort", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "desc": "

      Returns the numeric representation of the remote port. For example, 443.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`socket` {net.Socket|stream.Duplex} On the server side, any `Duplex` stream. On the client side, any instance of [`net.Socket`][] (for generic `Duplex` stream support on the client side, [`tls.connect()`][] must be used).", + "name": "socket", + "type": "net.Socket|stream.Duplex", + "desc": "On the server side, any `Duplex` stream. On the client side, any instance of [`net.Socket`][] (for generic `Duplex` stream support on the client side, [`tls.connect()`][] must be used)." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`enableTrace`: See [`tls.createServer()`][]", + "name": "enableTrace", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`isServer`: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If `true` the TLS socket will be instantiated as a server. **Default:** `false`.", + "name": "isServer", + "default": "`false`", + "desc": "The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If `true` the TLS socket will be instantiated as a server." + }, + { + "textRaw": "`server` {net.Server} A [`net.Server`][] instance.", + "name": "server", + "type": "net.Server", + "desc": "A [`net.Server`][] instance." + }, + { + "textRaw": "`requestCert`: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may set `requestCert` to true to request a client certificate.", + "name": "requestCert", + "desc": "Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may set `requestCert` to true to request a client certificate." + }, + { + "textRaw": "`rejectUnauthorized`: See [`tls.createServer()`][]", + "name": "rejectUnauthorized", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`ALPNProtocols`: See [`tls.createServer()`][]", + "name": "ALPNProtocols", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`SNICallback`: See [`tls.createServer()`][]", + "name": "SNICallback", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`session` {Buffer} A `Buffer` instance containing a TLS session.", + "name": "session", + "type": "Buffer", + "desc": "A `Buffer` instance containing a TLS session." + }, + { + "textRaw": "`requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication", + "name": "requestOCSP", + "type": "boolean", + "desc": "If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication" + }, + { + "textRaw": "`secureContext`: TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`.", + "name": "secureContext", + "desc": "TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`." + }, + { + "textRaw": "...: [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing. Otherwise, they are ignored.", + "name": "...", + "desc": "[`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing. Otherwise, they are ignored." + } + ] + } + ], + "desc": "

      Construct a new tls.TLSSocket object from an existing TCP socket.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`tls.checkServerIdentity(hostname, cert)`", + "type": "method", + "name": "checkServerIdentity", + "meta": { + "added": [ + "v0.8.4" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Error|undefined}", + "name": "return", + "type": "Error|undefined" + }, + "params": [ + { + "textRaw": "`hostname` {string} The host name or IP address to verify the certificate against.", + "name": "hostname", + "type": "string", + "desc": "The host name or IP address to verify the certificate against." + }, + { + "textRaw": "`cert` {Object} A [certificate object][] representing the peer's certificate.", + "name": "cert", + "type": "Object", + "desc": "A [certificate object][] representing the peer's certificate." + } + ] + } + ], + "desc": "

      Verifies the certificate cert is issued to hostname.

      \n

      Returns <Error> object, populating it with reason, host, and cert on\nfailure. On success, returns <undefined>.

      \n

      This function can be overwritten by providing alternative function as part of\nthe options.checkServerIdentity option passed to tls.connect(). The\noverwriting function can call tls.checkServerIdentity() of course, to augment\nthe checks done with additional verification.

      \n

      This function is only called if the certificate passed all other checks, such as\nbeing issued by trusted CA (options.ca).

      " + }, + { + "textRaw": "`tls.connect(options[, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [ + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/23188", + "description": "The `pskCallback` option is now supported." + }, + { + "version": "v12.9.0", + "pr-url": "https://github.com/nodejs/node/pull/27836", + "description": "Support the `allowHalfOpen` option." + }, + { + "version": "v12.4.0", + "pr-url": "https://github.com/nodejs/node/pull/27816", + "description": "The `hints` option is now supported." + }, + { + "version": "v12.2.0", + "pr-url": "https://github.com/nodejs/node/pull/27497", + "description": "The `enableTrace` option is now supported." + }, + { + "version": "v11.8.0", + "pr-url": "https://github.com/nodejs/node/pull/25517", + "description": "The `timeout` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12839", + "description": "The `lookup` option is supported now." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11984", + "description": "The `ALPNProtocols` option can be a `TypedArray` or `DataView` now." + }, + { + "version": "v5.3.0, v4.7.0", + "pr-url": "https://github.com/nodejs/node/pull/4246", + "description": "The `secureContext` option is supported now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2564", + "description": "ALPN options are supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.TLSSocket}", + "name": "return", + "type": "tls.TLSSocket" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`enableTrace`: See [`tls.createServer()`][]", + "name": "enableTrace", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`host` {string} Host the client should connect to. **Default:** `'localhost'`.", + "name": "host", + "type": "string", + "default": "`'localhost'`", + "desc": "Host the client should connect to." + }, + { + "textRaw": "`port` {number} Port the client should connect to.", + "name": "port", + "type": "number", + "desc": "Port the client should connect to." + }, + { + "textRaw": "`path` {string} Creates Unix socket connection to path. If this option is specified, `host` and `port` are ignored.", + "name": "path", + "type": "string", + "desc": "Creates Unix socket connection to path. If this option is specified, `host` and `port` are ignored." + }, + { + "textRaw": "`socket` {stream.Duplex} Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Connection/disconnection/destruction of `socket` is the user's responsibility; calling `tls.connect()` will not cause `net.connect()` to be called.", + "name": "socket", + "type": "stream.Duplex", + "desc": "Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Connection/disconnection/destruction of `socket` is the user's responsibility; calling `tls.connect()` will not cause `net.connect()` to be called." + }, + { + "textRaw": "`allowHalfOpen` {boolean} If the `socket` option is missing, indicates whether or not to allow the internally created socket to be half-open, otherwise the option is ignored. See the `allowHalfOpen` option of [`net.Socket`][] for details. **Default:** `false`.", + "name": "allowHalfOpen", + "type": "boolean", + "default": "`false`", + "desc": "If the `socket` option is missing, indicates whether or not to allow the internally created socket to be half-open, otherwise the option is ignored. See the `allowHalfOpen` option of [`net.Socket`][] for details." + }, + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "default": "`true`", + "desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code." + }, + { + "textRaw": "`pskCallback` {Function}", + "name": "pskCallback", + "type": "Function", + "options": [ + { + "textRaw": "hint: {string} optional message sent from the server to help client decide which identity to use during negotiation. Always `null` if TLS 1.3 is used.", + "name": "hint", + "type": "string", + "desc": "optional message sent from the server to help client decide which identity to use during negotiation. Always `null` if TLS 1.3 is used." + }, + { + "textRaw": "Returns: {Object} in the form `{ psk: , identity: }` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding. When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity `hint` provided by the server or `null` in case of TLS 1.3 where `hint` was removed. It will be necessary to provide a custom `tls.checkServerIdentity()` for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][].", + "name": "return", + "type": "Object", + "desc": "in the form `{ psk: , identity: }` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding. When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity `hint` provided by the server or `null` in case of TLS 1.3 where `hint` was removed. It will be necessary to provide a custom `tls.checkServerIdentity()` for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][]." + } + ] + }, + { + "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `'\\x08http/1.1\\x08http/1.0'`, where the `len` byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher preference than those later.", + "name": "ALPNProtocols", + "type": "string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView", + "desc": "An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `'\\x08http/1.1\\x08http/1.0'`, where the `len` byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher preference than those later." + }, + { + "textRaw": "`servername`: {string} Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the `SNICallback` option to [`tls.createServer()`][].", + "name": "servername", + "type": "string", + "desc": "Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the `SNICallback` option to [`tls.createServer()`][]." + }, + { + "textRaw": "`checkServerIdentity(servername, cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's host name (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified.", + "name": "checkServerIdentity(servername,", + "desc": "cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's host name (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified." + }, + { + "textRaw": "`session` {Buffer} A `Buffer` instance, containing TLS session.", + "name": "session", + "type": "Buffer", + "desc": "A `Buffer` instance, containing TLS session." + }, + { + "textRaw": "`minDHSize` {number} Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. **Default:** `1024`.", + "name": "minDHSize", + "type": "number", + "default": "`1024`", + "desc": "Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown." + }, + { + "textRaw": "`secureContext`: TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`.", + "name": "secureContext", + "desc": "TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`." + }, + { + "textRaw": "...: [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored.", + "name": "...", + "desc": "[`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored." + }, + { + "textRaw": "...: Any [`socket.connect()`][] option not already listed.", + "name": "...", + "desc": "Any [`socket.connect()`][] option not already listed." + } + ] + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

      The callback function, if specified, will be added as a listener for the\n'secureConnect' event.

      \n

      tls.connect() returns a tls.TLSSocket object.

      \n

      Unlike the https API, tls.connect() does not enable the\nSNI (Server Name Indication) extension by default, which may cause some\nservers to return an incorrect certificate or reject the connection\naltogether. To enable SNI, set the servername option in addition\nto host.

      \n

      The following illustrates a client for the echo server example from\ntls.createServer():

      \n
      // Assumes an echo server that is listening on port 8000.\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // Necessary only if the server requires client certificate authentication.\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // Necessary only if the server uses a self-signed certificate.\n  ca: [ fs.readFileSync('server-cert.pem') ],\n\n  // Necessary only if the server's cert isn't for \"localhost\".\n  checkServerIdentity: () => { return null; },\n};\n\nconst socket = tls.connect(8000, options, () => {\n  console.log('client connected',\n              socket.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(socket);\n  process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', (data) => {\n  console.log(data);\n});\nsocket.on('end', () => {\n  console.log('server ends connection');\n});\n
      " + }, + { + "textRaw": "`tls.connect(path[, options][, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.TLSSocket}", + "name": "return", + "type": "tls.TLSSocket" + }, + "params": [ + { + "textRaw": "`path` {string} Default value for `options.path`.", + "name": "path", + "type": "string", + "desc": "Default value for `options.path`." + }, + { + "textRaw": "`options` {Object} See [`tls.connect()`][].", + "name": "options", + "type": "Object", + "desc": "See [`tls.connect()`][]." + }, + { + "textRaw": "`callback` {Function} See [`tls.connect()`][].", + "name": "callback", + "type": "Function", + "desc": "See [`tls.connect()`][]." + } + ] + } + ], + "desc": "

      Same as tls.connect() except that path can be provided\nas an argument instead of an option.

      \n

      A path option, if specified, will take precedence over the path argument.

      " + }, + { + "textRaw": "`tls.connect(port[, host][, options][, callback])`", + "type": "method", + "name": "connect", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.TLSSocket}", + "name": "return", + "type": "tls.TLSSocket" + }, + "params": [ + { + "textRaw": "`port` {number} Default value for `options.port`.", + "name": "port", + "type": "number", + "desc": "Default value for `options.port`." + }, + { + "textRaw": "`host` {string} Default value for `options.host`.", + "name": "host", + "type": "string", + "desc": "Default value for `options.host`." + }, + { + "textRaw": "`options` {Object} See [`tls.connect()`][].", + "name": "options", + "type": "Object", + "desc": "See [`tls.connect()`][]." + }, + { + "textRaw": "`callback` {Function} See [`tls.connect()`][].", + "name": "callback", + "type": "Function", + "desc": "See [`tls.connect()`][]." + } + ] + } + ], + "desc": "

      Same as tls.connect() except that port and host can be provided\nas arguments instead of options.

      \n

      A port or host option, if specified, will take precedence over any port or host\nargument.

      " + }, + { + "textRaw": "`tls.createSecureContext([options])`", + "type": "method", + "name": "createSecureContext", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v12.12.0", + "pr-url": "https://github.com/nodejs/node/pull/28973", + "description": "Added `privateKeyIdentifier` and `privateKeyEngine` options to get private key from an OpenSSL engine." + }, + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29598", + "description": "Added `sigalgs` option to override supported signature algorithms." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/26209", + "description": "TLSv1.3 support added." + }, + { + "version": "v11.5.0", + "pr-url": "https://github.com/nodejs/node/pull/24733", + "description": "The `ca:` option now supports `BEGIN TRUSTED CERTIFICATE`." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24405", + "description": "The `minVersion` and `maxVersion` can be used to restrict the allowed TLS protocol versions." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19794", + "description": "The `ecdhCurve` cannot be set to `false` anymore due to a change in OpenSSL." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/15206", + "description": "The `ecdhCurve` option can now be multiple `':'` separated curve names or `'auto'`." + }, + { + "version": "v7.3.0", + "pr-url": "https://github.com/nodejs/node/pull/10294", + "description": "If the `key` option is an array, individual entries do not need a `passphrase` property anymore. `Array` entries can also just be `string`s or `Buffer`s now." + }, + { + "version": "v5.2.0", + "pr-url": "https://github.com/nodejs/node/pull/4099", + "description": "The `ca` option can now be a single string containing multiple CA certificates." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of strings and/or `Buffer`s. Any string or `Buffer` can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are \"TRUSTED CERTIFICATE\", \"X509 CERTIFICATE\", and \"CERTIFICATE\". See also [`tls.rootCertificates`][].", + "name": "ca", + "type": "string|string[]|Buffer|Buffer[]", + "desc": "Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of strings and/or `Buffer`s. Any string or `Buffer` can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are \"TRUSTED CERTIFICATE\", \"X509 CERTIFICATE\", and \"CERTIFICATE\". See also [`tls.rootCertificates`][]." + }, + { + "textRaw": "`cert` {string|string[]|Buffer|Buffer[]} Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.", + "name": "cert", + "type": "string|string[]|Buffer|Buffer[]", + "desc": "Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail." + }, + { + "textRaw": "`sigalgs` {string} Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) for more info.", + "name": "sigalgs", + "type": "string", + "desc": "Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) for more info." + }, + { + "textRaw": "`ciphers` {string} Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted ciphers can be obtained via [`tls.getCiphers()`][]. Cipher names must be uppercased in order for OpenSSL to accept them.", + "name": "ciphers", + "type": "string", + "desc": "Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted ciphers can be obtained via [`tls.getCiphers()`][]. Cipher names must be uppercased in order for OpenSSL to accept them." + }, + { + "textRaw": "`clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate.", + "name": "clientCertEngine", + "type": "string", + "desc": "Name of an OpenSSL engine which can provide the client certificate." + }, + { + "textRaw": "`crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate Revocation Lists).", + "name": "crl", + "type": "string|string[]|Buffer|Buffer[]", + "desc": "PEM formatted CRLs (Certificate Revocation Lists)." + }, + { + "textRaw": "`dhparam` {string|Buffer} Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.", + "name": "dhparam", + "type": "string|Buffer", + "desc": "Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available." + }, + { + "textRaw": "`ecdhCurve` {string} A string describing a named curve or a colon separated list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for ECDH key agreement. Set to `auto` to select the curve automatically. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. **Default:** [`tls.DEFAULT_ECDH_CURVE`][].", + "name": "ecdhCurve", + "type": "string", + "default": "[`tls.DEFAULT_ECDH_CURVE`][]", + "desc": "A string describing a named curve or a colon separated list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for ECDH key agreement. Set to `auto` to select the curve automatically. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve." + }, + { + "textRaw": "`honorCipherOrder` {boolean} Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information.", + "name": "honorCipherOrder", + "type": "boolean", + "desc": "Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information." + }, + { + "textRaw": "`key` {string|string[]|Buffer|Buffer[]|Object[]} Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.", + "name": "key", + "type": "string|string[]|Buffer|Buffer[]|Object[]", + "desc": "Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." + }, + { + "textRaw": "`privateKeyEngine` {string} Name of an OpenSSL engine to get private key from. Should be used together with `privateKeyIdentifier`.", + "name": "privateKeyEngine", + "type": "string", + "desc": "Name of an OpenSSL engine to get private key from. Should be used together with `privateKeyIdentifier`." + }, + { + "textRaw": "`privateKeyIdentifier` {string} Identifier of a private key managed by an OpenSSL engine. Should be used together with `privateKeyEngine`. Should not be set together with `key`, because both options define a private key in different ways.", + "name": "privateKeyIdentifier", + "type": "string", + "desc": "Identifier of a private key managed by an OpenSSL engine. Should be used together with `privateKeyEngine`. Should not be set together with `key`, because both options define a private key in different ways." + }, + { + "textRaw": "`maxVersion` {string} Optionally set the maximum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other. **Default:** [`tls.DEFAULT_MAX_VERSION`][].", + "name": "maxVersion", + "type": "string", + "default": "[`tls.DEFAULT_MAX_VERSION`][]", + "desc": "Optionally set the maximum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other." + }, + { + "textRaw": "`minVersion` {string} Optionally set the minimum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability. **Default:** [`tls.DEFAULT_MIN_VERSION`][].", + "name": "minVersion", + "type": "string", + "default": "[`tls.DEFAULT_MIN_VERSION`][]", + "desc": "Optionally set the minimum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability." + }, + { + "textRaw": "`passphrase` {string} Shared passphrase used for a single private key and/or a PFX.", + "name": "passphrase", + "type": "string", + "desc": "Shared passphrase used for a single private key and/or a PFX." + }, + { + "textRaw": "`pfx` {string|string[]|Buffer|Buffer[]|Object[]} PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.", + "name": "pfx", + "type": "string|string[]|Buffer|Buffer[]|Object[]", + "desc": "PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." + }, + { + "textRaw": "`secureOptions` {number} Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][].", + "name": "secureOptions", + "type": "number", + "desc": "Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][]." + }, + { + "textRaw": "`secureProtocol` {string} Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. **Default:** none, see `minVersion`.", + "name": "secureProtocol", + "type": "string", + "default": "none, see `minVersion`", + "desc": "Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability." + }, + { + "textRaw": "`sessionIdContext` {string} Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.", + "name": "sessionIdContext", + "type": "string", + "desc": "Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients." + }, + { + "textRaw": "`ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information.", + "name": "ticketKeys", + "type": "Buffer", + "desc": "48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information." + }, + { + "textRaw": "`sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`.", + "name": "sessionTimeout", + "type": "number", + "default": "`300`", + "desc": "The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information." + } + ] + } + ] + } + ], + "desc": "

      tls.createServer() sets the default value of the honorCipherOrder option\nto true, other APIs that create secure contexts leave it unset.

      \n

      tls.createServer() uses a 128 bit truncated SHA1 hash value generated\nfrom process.argv as the default value of the sessionIdContext option, other\nAPIs that create secure contexts have no default value.

      \n

      The tls.createSecureContext() method creates a SecureContext object. It is\nusable as an argument to several tls APIs, such as tls.createServer()\nand server.addContext(), but has no public methods.

      \n

      A key is required for ciphers that use certificates. Either key or\npfx can be used to provide it.

      \n

      If the ca option is not given, then Node.js will default to using\nMozilla's publicly trusted list of CAs.

      " + }, + { + "textRaw": "`tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])`", + "type": "method", + "name": "createSecurePair", + "meta": { + "added": [ + "v0.3.2" + ], + "deprecated": [ + "v0.11.3" + ], + "changes": [ + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2564", + "description": "ALPN options are supported now." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`context` {Object} A secure context object as returned by `tls.createSecureContext()`", + "name": "context", + "type": "Object", + "desc": "A secure context object as returned by `tls.createSecureContext()`" + }, + { + "textRaw": "`isServer` {boolean} `true` to specify that this TLS connection should be opened as a server.", + "name": "isServer", + "type": "boolean", + "desc": "`true` to specify that this TLS connection should be opened as a server." + }, + { + "textRaw": "`requestCert` {boolean} `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.", + "name": "requestCert", + "type": "boolean", + "desc": "`true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`." + }, + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "desc": "If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`." + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`enableTrace`: See [`tls.createServer()`][]", + "name": "enableTrace", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`secureContext`: A TLS context object from [`tls.createSecureContext()`][]", + "name": "secureContext", + "desc": "A TLS context object from [`tls.createSecureContext()`][]" + }, + { + "textRaw": "`isServer`: If `true` the TLS socket will be instantiated in server-mode. **Default:** `false`.", + "name": "isServer", + "default": "`false`", + "desc": "If `true` the TLS socket will be instantiated in server-mode." + }, + { + "textRaw": "`server` {net.Server} A [`net.Server`][] instance", + "name": "server", + "type": "net.Server", + "desc": "A [`net.Server`][] instance" + }, + { + "textRaw": "`requestCert`: See [`tls.createServer()`][]", + "name": "requestCert", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`rejectUnauthorized`: See [`tls.createServer()`][]", + "name": "rejectUnauthorized", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`ALPNProtocols`: See [`tls.createServer()`][]", + "name": "ALPNProtocols", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`SNICallback`: See [`tls.createServer()`][]", + "name": "SNICallback", + "desc": "See [`tls.createServer()`][]" + }, + { + "textRaw": "`session` {Buffer} A `Buffer` instance containing a TLS session.", + "name": "session", + "type": "Buffer", + "desc": "A `Buffer` instance containing a TLS session." + }, + { + "textRaw": "`requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication.", + "name": "requestOCSP", + "type": "boolean", + "desc": "If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication." + } + ] + } + ] + } + ], + "desc": "

      Creates a new secure pair object with two streams, one of which reads and writes\nthe encrypted data and the other of which reads and writes the cleartext data.\nGenerally, the encrypted stream is piped to/from an incoming encrypted data\nstream and the cleartext one is used as a replacement for the initial encrypted\nstream.

      \n

      tls.createSecurePair() returns a tls.SecurePair object with cleartext and\nencrypted stream properties.

      \n

      Using cleartext has the same API as tls.TLSSocket.

      \n

      The tls.createSecurePair() method is now deprecated in favor of\ntls.TLSSocket(). For example, the code:

      \n
      pair = tls.createSecurePair(/* ... */);\npair.encrypted.pipe(socket);\nsocket.pipe(pair.encrypted);\n
      \n

      can be replaced by:

      \n
      secureSocket = tls.TLSSocket(socket, options);\n
      \n

      where secureSocket has the same API as pair.cleartext.

      " + }, + { + "textRaw": "`tls.createServer([options][, secureConnectionListener])`", + "type": "method", + "name": "createServer", + "meta": { + "added": [ + "v0.3.2" + ], + "changes": [ + { + "version": "v12.3.0", + "pr-url": "https://github.com/nodejs/node/pull/27665", + "description": "The `options` parameter now supports `net.createServer()` options." + }, + { + "version": "v9.3.0", + "pr-url": "https://github.com/nodejs/node/pull/14903", + "description": "The `options` parameter can now include `clientCertEngine`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/11984", + "description": "The `ALPNProtocols` option can be a `TypedArray` or `DataView` now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2564", + "description": "ALPN options are supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {tls.Server}", + "name": "return", + "type": "tls.Server" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)", + "name": "ALPNProtocols", + "type": "string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView", + "desc": "An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)" + }, + { + "textRaw": "`clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate.", + "name": "clientCertEngine", + "type": "string", + "desc": "Name of an OpenSSL engine which can provide the client certificate." + }, + { + "textRaw": "`enableTrace` {boolean} If `true`, [`tls.TLSSocket.enableTrace()`][] will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. **Default:** `false`.", + "name": "enableTrace", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, [`tls.TLSSocket.enableTrace()`][] will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup." + }, + { + "textRaw": "`handshakeTimeout` {number} Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out. **Default:** `120000` (120 seconds).", + "name": "handshakeTimeout", + "type": "number", + "default": "`120000` (120 seconds)", + "desc": "Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out." + }, + { + "textRaw": "`rejectUnauthorized` {boolean} If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. **Default:** `true`.", + "name": "rejectUnauthorized", + "type": "boolean", + "default": "`true`", + "desc": "If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`." + }, + { + "textRaw": "`requestCert` {boolean} If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. **Default:** `false`.", + "name": "requestCert", + "type": "boolean", + "default": "`false`", + "desc": "If `true` the server will request a certificate from clients that connect and attempt to verify that certificate." + }, + { + "textRaw": "`sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`.", + "name": "sessionTimeout", + "type": "number", + "default": "`300`", + "desc": "The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information." + }, + { + "textRaw": "`SNICallback(servername, callback)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `callback`. `callback` is an error-first callback that takes two optional arguments: `error` and `ctx`. `ctx`, if provided, is a `SecureContext` instance. [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. If `callback` is called with a falsy `ctx` argument, the default secure context of the server will be used. If `SNICallback` wasn't provided the default callback with high-level API will be used (see below).", + "name": "SNICallback(servername,", + "desc": "callback)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `callback`. `callback` is an error-first callback that takes two optional arguments: `error` and `ctx`. `ctx`, if provided, is a `SecureContext` instance. [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. If `callback` is called with a falsy `ctx` argument, the default secure context of the server will be used. If `SNICallback` wasn't provided the default callback with high-level API will be used (see below)." + }, + { + "textRaw": "`ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information.", + "name": "ticketKeys", + "type": "Buffer", + "desc": "48-bytes of cryptographically strong pseudo-random data. See [Session Resumption][] for more information." + }, + { + "textRaw": "`pskCallback` {Function}", + "name": "pskCallback", + "type": "Function", + "options": [ + { + "textRaw": "socket: {tls.TLSSocket} the server [`tls.TLSSocket`][] instance for this connection.", + "name": "socket", + "type": "tls.TLSSocket", + "desc": "the server [`tls.TLSSocket`][] instance for this connection." + }, + { + "textRaw": "identity: {string} identity parameter sent from the client.", + "name": "identity", + "type": "string", + "desc": "identity parameter sent from the client." + }, + { + "textRaw": "Returns: {Buffer|TypedArray|DataView} pre-shared key that must either be a buffer or `null` to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest. When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an \"unknown_psk_identity\" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection fail with \"decrypt_error\" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][].", + "name": "return", + "type": "Buffer|TypedArray|DataView", + "desc": "pre-shared key that must either be a buffer or `null` to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest. When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an \"unknown_psk_identity\" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection fail with \"decrypt_error\" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][]." + } + ] + }, + { + "textRaw": "`pskIdentityHint` {string} optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code.", + "name": "pskIdentityHint", + "type": "string", + "desc": "optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code." + }, + { + "textRaw": "...: Any [`tls.createSecureContext()`][] option can be provided. For servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) are usually required.", + "name": "...", + "desc": "Any [`tls.createSecureContext()`][] option can be provided. For servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) are usually required." + }, + { + "textRaw": "...: Any [`net.createServer()`][] option can be provided.", + "name": "...", + "desc": "Any [`net.createServer()`][] option can be provided." + } + ] + }, + { + "textRaw": "`secureConnectionListener` {Function}", + "name": "secureConnectionListener", + "type": "Function" + } + ] + } + ], + "desc": "

      Creates a new tls.Server. The secureConnectionListener, if provided, is\nautomatically set as a listener for the 'secureConnection' event.

      \n

      The ticketKeys options is automatically shared between cluster module\nworkers.

      \n

      The following illustrates a simple echo server:

      \n
      const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses a self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nconst server = tls.createServer(options, (socket) => {\n  console.log('server connected',\n              socket.authorized ? 'authorized' : 'unauthorized');\n  socket.write('welcome!\\n');\n  socket.setEncoding('utf8');\n  socket.pipe(socket);\n});\nserver.listen(8000, () => {\n  console.log('server bound');\n});\n
      \n

      The server can be tested by connecting to it using the example client from\ntls.connect().

      " + }, + { + "textRaw": "`tls.getCiphers()`", + "type": "method", + "name": "getCiphers", + "meta": { + "added": [ + "v0.10.2" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [] + } + ], + "desc": "

      Returns an array with the names of the supported TLS ciphers. The names are\nlower-case for historical reasons, but must be uppercased to be used in\nthe ciphers option of tls.createSecureContext().

      \n

      Cipher names that start with 'tls_' are for TLSv1.3, all the others are for\nTLSv1.2 and below.

      \n
      console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]\n
      " + } + ], + "properties": [ + { + "textRaw": "`rootCertificates` {string[]}", + "type": "string[]", + "name": "rootCertificates", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "desc": "

      An immutable array of strings representing the root certificates (in PEM format)\nfrom the bundled Mozilla CA store as supplied by current Node.js version.

      \n

      The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store\nthat is fixed at release time. It is identical on all supported platforms.

      " + }, + { + "textRaw": "`tls.DEFAULT_ECDH_CURVE`", + "name": "DEFAULT_ECDH_CURVE", + "meta": { + "added": [ + "v0.11.13" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16853", + "description": "Default value changed to `'auto'`." + } + ] + }, + "desc": "

      The default curve name to use for ECDH key agreement in a tls server. The\ndefault value is 'auto'. See tls.createSecureContext() for further\ninformation.

      " + }, + { + "textRaw": "`DEFAULT_MAX_VERSION` {string} The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.", + "type": "string", + "name": "DEFAULT_MAX_VERSION", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "default": "`'TLSv1.3'`, unless changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used", + "desc": "The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`." + }, + { + "textRaw": "`DEFAULT_MIN_VERSION` {string} The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless changed using CLI options. Using `--tls-min-v1.0` sets the default to `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is used.", + "type": "string", + "name": "DEFAULT_MIN_VERSION", + "meta": { + "added": [ + "v11.4.0" + ], + "changes": [] + }, + "default": "`'TLSv1.2'`, unless changed using CLI options. Using `--tls-min-v1.0` sets the default to `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is used", + "shortDesc": "The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`." + } + ], + "type": "module", + "displayName": "TLS (SSL)" + } + ] +} \ No newline at end of file diff --git a/doc/api/tracing.html b/doc/api/tracing.html new file mode 100644 index 0000000000000000000000000000000000000000..0b450257fd9c3b960711a48b161fdee793ae8d30 --- /dev/null +++ b/doc/api/tracing.html @@ -0,0 +1,320 @@ + + + + + + + Trace events | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      Trace events#

      + +

      Stability: 1 - Experimental

      +

      Source Code: lib/trace_events.js

      +

      The trace_events module provides a mechanism to centralize tracing information +generated by V8, Node.js core, and userspace code.

      +

      Tracing can be enabled with the --trace-event-categories command-line flag +or by using the trace_events module. The --trace-event-categories flag +accepts a list of comma-separated category names.

      +

      The available categories are:

      +
        +
      • node: An empty placeholder.
      • +
      • node.async_hooks: Enables capture of detailed async_hooks trace data. +The async_hooks events have a unique asyncId and a special triggerId +triggerAsyncId property.
      • +
      • node.bootstrap: Enables capture of Node.js bootstrap milestones.
      • +
      • node.console: Enables capture of console.time() and console.count() +output.
      • +
      • node.dns.native: Enables capture of trace data for DNS queries.
      • +
      • node.environment: Enables capture of Node.js Environment milestones.
      • +
      • node.fs.sync: Enables capture of trace data for file system sync methods.
      • +
      • node.perf: Enables capture of Performance API measurements. +
          +
        • node.perf.usertiming: Enables capture of only Performance API User Timing +measures and marks.
        • +
        • node.perf.timerify: Enables capture of only Performance API timerify +measurements.
        • +
        +
      • +
      • node.promises.rejections: Enables capture of trace data tracking the number +of unhandled Promise rejections and handled-after-rejections.
      • +
      • node.vm.script: Enables capture of trace data for the vm module's +runInNewContext(), runInContext(), and runInThisContext() methods.
      • +
      • v8: The V8 events are GC, compiling, and execution related.
      • +
      +

      By default the node, node.async_hooks, and v8 categories are enabled.

      +
      node --trace-event-categories v8,node,node.async_hooks server.js
      +

      Prior versions of Node.js required the use of the --trace-events-enabled +flag to enable trace events. This requirement has been removed. However, the +--trace-events-enabled flag may still be used and will enable the +node, node.async_hooks, and v8 trace event categories by default.

      +
      node --trace-events-enabled
      +
      +# is equivalent to
      +
      +node --trace-event-categories v8,node,node.async_hooks
      +

      Alternatively, trace events may be enabled using the trace_events module:

      +
      const trace_events = require('trace_events');
      +const tracing = trace_events.createTracing({ categories: ['node.perf'] });
      +tracing.enable();  // Enable trace event capture for the 'node.perf' category
      +
      +// do work
      +
      +tracing.disable();  // Disable trace event capture for the 'node.perf' category
      +

      Running Node.js with tracing enabled will produce log files that can be opened +in the chrome://tracing +tab of Chrome.

      +

      The logging file is by default called node_trace.${rotation}.log, where +${rotation} is an incrementing log-rotation id. The filepath pattern can +be specified with --trace-event-file-pattern that accepts a template +string that supports ${rotation} and ${pid}:

      +
      node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
      +

      The tracing system uses the same time source +as the one used by process.hrtime(). +However the trace-event timestamps are expressed in microseconds, +unlike process.hrtime() which returns nanoseconds.

      +

      The features from this module are not available in Worker threads.

      +

      The trace_events module#

      + +

      Tracing object#

      + +

      The Tracing object is used to enable or disable tracing for sets of +categories. Instances are created using the trace_events.createTracing() +method.

      +

      When created, the Tracing object is disabled. Calling the +tracing.enable() method adds the categories to the set of enabled trace event +categories. Calling tracing.disable() will remove the categories from the +set of enabled trace event categories.

      +

      tracing.categories#

      + + +

      A comma-separated list of the trace event categories covered by this +Tracing object.

      +

      tracing.disable()#

      + +

      Disables this Tracing object.

      +

      Only trace event categories not covered by other enabled Tracing objects +and not specified by the --trace-event-categories flag will be disabled.

      +
      const trace_events = require('trace_events');
      +const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
      +const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
      +t1.enable();
      +t2.enable();
      +
      +// Prints 'node,node.perf,v8'
      +console.log(trace_events.getEnabledCategories());
      +
      +t2.disable(); // Will only disable emission of the 'node.perf' category
      +
      +// Prints 'node,v8'
      +console.log(trace_events.getEnabledCategories());
      +

      tracing.enable()#

      + +

      Enables this Tracing object for the set of categories covered by the +Tracing object.

      +

      tracing.enabled#

      + +
        +
      • <boolean> true only if the Tracing object has been enabled.
      • +
      +

      trace_events.createTracing(options)#

      + +
        +
      • options <Object> +
          +
        • categories <string[]> An array of trace category names. Values included +in the array are coerced to a string when possible. An error will be +thrown if the value cannot be coerced.
        • +
        +
      • +
      • Returns: <Tracing>.
      • +
      +

      Creates and returns a Tracing object for the given set of categories.

      +
      const trace_events = require('trace_events');
      +const categories = ['node.perf', 'node.async_hooks'];
      +const tracing = trace_events.createTracing({ categories });
      +tracing.enable();
      +// do stuff
      +tracing.disable();
      +

      trace_events.getEnabledCategories()#

      + + +

      Returns a comma-separated list of all currently-enabled trace event +categories. The current set of enabled trace event categories is determined +by the union of all currently-enabled Tracing objects and any categories +enabled using the --trace-event-categories flag.

      +

      Given the file test.js below, the command +node --trace-event-categories node.perf test.js will print +'node.async_hooks,node.perf' to the console.

      +
      const trace_events = require('trace_events');
      +const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
      +const t2 = trace_events.createTracing({ categories: ['node.perf'] });
      +const t3 = trace_events.createTracing({ categories: ['v8'] });
      +
      +t1.enable();
      +t2.enable();
      +
      +console.log(trace_events.getEnabledCategories());
      + +
      +
      +
      + + diff --git a/doc/api/tracing.json b/doc/api/tracing.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1c74c79873b7dd83811890710d4fe21692cfcc --- /dev/null +++ b/doc/api/tracing.json @@ -0,0 +1,168 @@ +{ + "type": "module", + "source": "doc/api/tracing.md", + "modules": [ + { + "textRaw": "Trace events", + "name": "trace_events", + "introduced_in": "v7.7.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

      Source Code: lib/trace_events.js

      \n

      The trace_events module provides a mechanism to centralize tracing information\ngenerated by V8, Node.js core, and userspace code.

      \n

      Tracing can be enabled with the --trace-event-categories command-line flag\nor by using the trace_events module. The --trace-event-categories flag\naccepts a list of comma-separated category names.

      \n

      The available categories are:

      \n
        \n
      • node: An empty placeholder.
      • \n
      • node.async_hooks: Enables capture of detailed async_hooks trace data.\nThe async_hooks events have a unique asyncId and a special triggerId\ntriggerAsyncId property.
      • \n
      • node.bootstrap: Enables capture of Node.js bootstrap milestones.
      • \n
      • node.console: Enables capture of console.time() and console.count()\noutput.
      • \n
      • node.dns.native: Enables capture of trace data for DNS queries.
      • \n
      • node.environment: Enables capture of Node.js Environment milestones.
      • \n
      • node.fs.sync: Enables capture of trace data for file system sync methods.
      • \n
      • node.perf: Enables capture of Performance API measurements.\n
          \n
        • node.perf.usertiming: Enables capture of only Performance API User Timing\nmeasures and marks.
        • \n
        • node.perf.timerify: Enables capture of only Performance API timerify\nmeasurements.
        • \n
        \n
      • \n
      • node.promises.rejections: Enables capture of trace data tracking the number\nof unhandled Promise rejections and handled-after-rejections.
      • \n
      • node.vm.script: Enables capture of trace data for the vm module's\nrunInNewContext(), runInContext(), and runInThisContext() methods.
      • \n
      • v8: The V8 events are GC, compiling, and execution related.
      • \n
      \n

      By default the node, node.async_hooks, and v8 categories are enabled.

      \n
      node --trace-event-categories v8,node,node.async_hooks server.js\n
      \n

      Prior versions of Node.js required the use of the --trace-events-enabled\nflag to enable trace events. This requirement has been removed. However, the\n--trace-events-enabled flag may still be used and will enable the\nnode, node.async_hooks, and v8 trace event categories by default.

      \n
      node --trace-events-enabled\n\n# is equivalent to\n\nnode --trace-event-categories v8,node,node.async_hooks\n
      \n

      Alternatively, trace events may be enabled using the trace_events module:

      \n
      const trace_events = require('trace_events');\nconst tracing = trace_events.createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category\n
      \n

      Running Node.js with tracing enabled will produce log files that can be opened\nin the chrome://tracing\ntab of Chrome.

      \n

      The logging file is by default called node_trace.${rotation}.log, where\n${rotation} is an incrementing log-rotation id. The filepath pattern can\nbe specified with --trace-event-file-pattern that accepts a template\nstring that supports ${rotation} and ${pid}:

      \n
      node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js\n
      \n

      The tracing system uses the same time source\nas the one used by process.hrtime().\nHowever the trace-event timestamps are expressed in microseconds,\nunlike process.hrtime() which returns nanoseconds.

      \n

      The features from this module are not available in Worker threads.

      ", + "modules": [ + { + "textRaw": "The `trace_events` module", + "name": "the_`trace_events`_module", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "modules": [ + { + "textRaw": "`Tracing` object", + "name": "`tracing`_object", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      The Tracing object is used to enable or disable tracing for sets of\ncategories. Instances are created using the trace_events.createTracing()\nmethod.

      \n

      When created, the Tracing object is disabled. Calling the\ntracing.enable() method adds the categories to the set of enabled trace event\ncategories. Calling tracing.disable() will remove the categories from the\nset of enabled trace event categories.

      ", + "properties": [ + { + "textRaw": "`categories` {string}", + "type": "string", + "name": "categories", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      A comma-separated list of the trace event categories covered by this\nTracing object.

      " + }, + { + "textRaw": "`enabled` {boolean} `true` only if the `Tracing` object has been enabled.", + "type": "boolean", + "name": "enabled", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "`true` only if the `Tracing` object has been enabled." + } + ], + "methods": [ + { + "textRaw": "`tracing.disable()`", + "type": "method", + "name": "disable", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Disables this Tracing object.

      \n

      Only trace event categories not covered by other enabled Tracing objects\nand not specified by the --trace-event-categories flag will be disabled.

      \n
      const trace_events = require('trace_events');\nconst t1 = trace_events.createTracing({ categories: ['node', 'v8'] });\nconst t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(trace_events.getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(trace_events.getEnabledCategories());\n
      " + }, + { + "textRaw": "`tracing.enable()`", + "type": "method", + "name": "enable", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Enables this Tracing object for the set of categories covered by the\nTracing object.

      " + } + ], + "type": "module", + "displayName": "`Tracing` object" + } + ], + "methods": [ + { + "textRaw": "`trace_events.createTracing(options)`", + "type": "method", + "name": "createTracing", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Tracing}.", + "name": "return", + "type": "Tracing", + "desc": "." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`categories` {string[]} An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced.", + "name": "categories", + "type": "string[]", + "desc": "An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced." + } + ] + } + ] + } + ], + "desc": "

      Creates and returns a Tracing object for the given set of categories.

      \n
      const trace_events = require('trace_events');\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = trace_events.createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();\n
      " + }, + { + "textRaw": "`trace_events.getEnabledCategories()`", + "type": "method", + "name": "getEnabledCategories", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns a comma-separated list of all currently-enabled trace event\ncategories. The current set of enabled trace event categories is determined\nby the union of all currently-enabled Tracing objects and any categories\nenabled using the --trace-event-categories flag.

      \n

      Given the file test.js below, the command\nnode --trace-event-categories node.perf test.js will print\n'node.async_hooks,node.perf' to the console.

      \n
      const trace_events = require('trace_events');\nconst t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });\nconst t2 = trace_events.createTracing({ categories: ['node.perf'] });\nconst t3 = trace_events.createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(trace_events.getEnabledCategories());\n
      " + } + ], + "type": "module", + "displayName": "The `trace_events` module" + } + ], + "type": "module", + "displayName": "Trace events" + } + ] +} \ No newline at end of file diff --git a/doc/api/tty.html b/doc/api/tty.html new file mode 100644 index 0000000000000000000000000000000000000000..0538ea0ecf1615b5b0de14d1286f395a645816cf --- /dev/null +++ b/doc/api/tty.html @@ -0,0 +1,433 @@ + + + + + + + TTY | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      TTY#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/tty.js

      +

      The tty module provides the tty.ReadStream and tty.WriteStream classes. +In most cases, it will not be necessary or possible to use this module directly. +However, it can be accessed using:

      +
      const tty = require('tty');
      +

      When Node.js detects that it is being run with a text terminal ("TTY") +attached, process.stdin will, by default, be initialized as an instance of +tty.ReadStream and both process.stdout and process.stderr will, by +default be instances of tty.WriteStream. The preferred method of determining +whether Node.js is being run within a TTY context is to check that the value of +the process.stdout.isTTY property is true:

      +
      $ node -p -e "Boolean(process.stdout.isTTY)"
      +true
      +$ node -p -e "Boolean(process.stdout.isTTY)" | cat
      +false
      +

      In most cases, there should be little to no reason for an application to +manually create instances of the tty.ReadStream and tty.WriteStream +classes.

      +

      Class: tty.ReadStream#

      + + +

      Represents the readable side of a TTY. In normal circumstances +process.stdin will be the only tty.ReadStream instance in a Node.js +process and there should be no reason to create additional instances.

      +

      readStream.isRaw#

      + +

      A boolean that is true if the TTY is currently configured to operate as a +raw device. Defaults to false.

      +

      readStream.isTTY#

      + +

      A boolean that is always true for tty.ReadStream instances.

      +

      readStream.setRawMode(mode)#

      + +
        +
      • mode <boolean> If true, configures the tty.ReadStream to operate as a +raw device. If false, configures the tty.ReadStream to operate in its +default mode. The readStream.isRaw property will be set to the resulting +mode.
      • +
      • Returns: <this> The read stream instance.
      • +
      +

      Allows configuration of tty.ReadStream so that it operates as a raw device.

      +

      When in raw mode, input is always available character-by-character, not +including modifiers. Additionally, all special processing of characters by the +terminal is disabled, including echoing input characters. +CTRL+C will no longer cause a SIGINT when in this mode.

      +

      Class: tty.WriteStream#

      + + +

      Represents the writable side of a TTY. In normal circumstances, +process.stdout and process.stderr will be the only +tty.WriteStream instances created for a Node.js process and there +should be no reason to create additional instances.

      +

      Event: 'resize'#

      + +

      The 'resize' event is emitted whenever either of the writeStream.columns +or writeStream.rows properties have changed. No arguments are passed to the +listener callback when called.

      +
      process.stdout.on('resize', () => {
      +  console.log('screen size has changed!');
      +  console.log(`${process.stdout.columns}x${process.stdout.rows}`);
      +});
      +

      writeStream.clearLine(dir[, callback])#

      + +
        +
      • dir <number> +
          +
        • -1: to the left from cursor
        • +
        • 1: to the right from cursor
        • +
        • 0: the entire line
        • +
        +
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.clearLine() clears the current line of this WriteStream in a +direction identified by dir.

      +

      writeStream.clearScreenDown([callback])#

      + +
        +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.clearScreenDown() clears this WriteStream from the current +cursor down.

      +

      writeStream.columns#

      + +

      A number specifying the number of columns the TTY currently has. This property +is updated whenever the 'resize' event is emitted.

      +

      writeStream.cursorTo(x[, y][, callback])#

      + +
        +
      • x <number>
      • +
      • y <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.cursorTo() moves this WriteStream's cursor to the specified +position.

      +

      writeStream.getColorDepth([env])#

      + +
        +
      • env <Object> An object containing the environment variables to check. This +enables simulating the usage of a specific terminal. Default: +process.env.
      • +
      • Returns: <number>
      • +
      +

      Returns:

      +
        +
      • 1 for 2,
      • +
      • 4 for 16,
      • +
      • 8 for 256,
      • +
      • 24 for 16,777,216 +colors supported.
      • +
      +

      Use this to determine what colors the terminal supports. Due to the nature of +colors in terminals it is possible to either have false positives or false +negatives. It depends on process information and the environment variables that +may lie about what terminal is used. +It is possible to pass in an env object to simulate the usage of a specific +terminal. This can be useful to check how specific environment settings behave.

      +

      To enforce a specific color support, use one of the below environment settings.

      +
        +
      • 2 colors: FORCE_COLOR = 0 (Disables colors)
      • +
      • 16 colors: FORCE_COLOR = 1
      • +
      • 256 colors: FORCE_COLOR = 2
      • +
      • 16,777,216 colors: FORCE_COLOR = 3
      • +
      +

      Disabling color support is also possible by using the NO_COLOR and +NODE_DISABLE_COLORS environment variables.

      +

      writeStream.getWindowSize()#

      + + +

      writeStream.getWindowSize() returns the size of the TTY +corresponding to this WriteStream. The array is of the type +[numColumns, numRows] where numColumns and numRows represent the number +of columns and rows in the corresponding TTY.

      +

      writeStream.hasColors([count][, env])#

      + +
        +
      • count <integer> The number of colors that are requested (minimum 2). +Default: 16.
      • +
      • env <Object> An object containing the environment variables to check. This +enables simulating the usage of a specific terminal. Default: +process.env.
      • +
      • Returns: <boolean>
      • +
      +

      Returns true if the writeStream supports at least as many colors as provided +in count. Minimum support is 2 (black and white).

      +

      This has the same false positives and negatives as described in +writeStream.getColorDepth().

      +
      process.stdout.hasColors();
      +// Returns true or false depending on if `stdout` supports at least 16 colors.
      +process.stdout.hasColors(256);
      +// Returns true or false depending on if `stdout` supports at least 256 colors.
      +process.stdout.hasColors({ TMUX: '1' });
      +// Returns true.
      +process.stdout.hasColors(2 ** 24, { TMUX: '1' });
      +// Returns false (the environment setting pretends to support 2 ** 8 colors).
      +

      writeStream.isTTY#

      + +

      A boolean that is always true.

      +

      writeStream.moveCursor(dx, dy[, callback])#

      + +
        +
      • dx <number>
      • +
      • dy <number>
      • +
      • callback <Function> Invoked once the operation completes.
      • +
      • Returns: <boolean> false if the stream wishes for the calling code to wait +for the 'drain' event to be emitted before continuing to write additional +data; otherwise true.
      • +
      +

      writeStream.moveCursor() moves this WriteStream's cursor relative to its +current position.

      +

      writeStream.rows#

      + +

      A number specifying the number of rows the TTY currently has. This property +is updated whenever the 'resize' event is emitted.

      +

      tty.isatty(fd)#

      + + +

      The tty.isatty() method returns true if the given fd is associated with +a TTY and false if it is not, including whenever fd is not a non-negative +integer.

      + +
      +
      +
      + + diff --git a/doc/api/tty.json b/doc/api/tty.json new file mode 100644 index 0000000000000000000000000000000000000000..0618e8d77bf578a128fd8339d84f2238b159ed59 --- /dev/null +++ b/doc/api/tty.json @@ -0,0 +1,456 @@ +{ + "type": "module", + "source": "doc/api/tty.md", + "modules": [ + { + "textRaw": "TTY", + "name": "tty", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/tty.js

      \n

      The tty module provides the tty.ReadStream and tty.WriteStream classes.\nIn most cases, it will not be necessary or possible to use this module directly.\nHowever, it can be accessed using:

      \n
      const tty = require('tty');\n
      \n

      When Node.js detects that it is being run with a text terminal (\"TTY\")\nattached, process.stdin will, by default, be initialized as an instance of\ntty.ReadStream and both process.stdout and process.stderr will, by\ndefault be instances of tty.WriteStream. The preferred method of determining\nwhether Node.js is being run within a TTY context is to check that the value of\nthe process.stdout.isTTY property is true:

      \n
      $ node -p -e \"Boolean(process.stdout.isTTY)\"\ntrue\n$ node -p -e \"Boolean(process.stdout.isTTY)\" | cat\nfalse\n
      \n

      In most cases, there should be little to no reason for an application to\nmanually create instances of the tty.ReadStream and tty.WriteStream\nclasses.

      ", + "classes": [ + { + "textRaw": "Class: `tty.ReadStream`", + "type": "class", + "name": "tty.ReadStream", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "\n

      Represents the readable side of a TTY. In normal circumstances\nprocess.stdin will be the only tty.ReadStream instance in a Node.js\nprocess and there should be no reason to create additional instances.

      ", + "properties": [ + { + "textRaw": "`readStream.isRaw`", + "name": "isRaw", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      A boolean that is true if the TTY is currently configured to operate as a\nraw device. Defaults to false.

      " + }, + { + "textRaw": "`readStream.isTTY`", + "name": "isTTY", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      A boolean that is always true for tty.ReadStream instances.

      " + } + ], + "methods": [ + { + "textRaw": "`readStream.setRawMode(mode)`", + "type": "method", + "name": "setRawMode", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {this} The read stream instance.", + "name": "return", + "type": "this", + "desc": "The read stream instance." + }, + "params": [ + { + "textRaw": "`mode` {boolean} If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` property will be set to the resulting mode.", + "name": "mode", + "type": "boolean", + "desc": "If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` property will be set to the resulting mode." + } + ] + } + ], + "desc": "

      Allows configuration of tty.ReadStream so that it operates as a raw device.

      \n

      When in raw mode, input is always available character-by-character, not\nincluding modifiers. Additionally, all special processing of characters by the\nterminal is disabled, including echoing input characters.\nCTRL+C will no longer cause a SIGINT when in this mode.

      " + } + ] + }, + { + "textRaw": "Class: `tty.WriteStream`", + "type": "class", + "name": "tty.WriteStream", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "\n

      Represents the writable side of a TTY. In normal circumstances,\nprocess.stdout and process.stderr will be the only\ntty.WriteStream instances created for a Node.js process and there\nshould be no reason to create additional instances.

      ", + "events": [ + { + "textRaw": "Event: `'resize'`", + "type": "event", + "name": "resize", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "params": [], + "desc": "

      The 'resize' event is emitted whenever either of the writeStream.columns\nor writeStream.rows properties have changed. No arguments are passed to the\nlistener callback when called.

      \n
      process.stdout.on('resize', () => {\n  console.log('screen size has changed!');\n  console.log(`${process.stdout.columns}x${process.stdout.rows}`);\n});\n
      " + } + ], + "methods": [ + { + "textRaw": "`writeStream.clearLine(dir[, callback])`", + "type": "method", + "name": "clearLine", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`dir` {number}", + "name": "dir", + "type": "number", + "options": [ + { + "textRaw": "`-1`: to the left from cursor", + "name": "-1", + "desc": "to the left from cursor" + }, + { + "textRaw": "`1`: to the right from cursor", + "name": "1", + "desc": "to the right from cursor" + }, + { + "textRaw": "`0`: the entire line", + "name": "0", + "desc": "the entire line" + } + ] + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.clearLine() clears the current line of this WriteStream in a\ndirection identified by dir.

      " + }, + { + "textRaw": "`writeStream.clearScreenDown([callback])`", + "type": "method", + "name": "clearScreenDown", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.clearScreenDown() clears this WriteStream from the current\ncursor down.

      " + }, + { + "textRaw": "`writeStream.cursorTo(x[, y][, callback])`", + "type": "method", + "name": "cursorTo", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`x` {number}", + "name": "x", + "type": "number" + }, + { + "textRaw": "`y` {number}", + "name": "y", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.cursorTo() moves this WriteStream's cursor to the specified\nposition.

      " + }, + { + "textRaw": "`writeStream.getColorDepth([env])`", + "type": "method", + "name": "getColorDepth", + "meta": { + "added": [ + "v9.9.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [ + { + "textRaw": "`env` {Object} An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "An object containing the environment variables to check. This enables simulating the usage of a specific terminal." + } + ] + } + ], + "desc": "

      Returns:

      \n
        \n
      • 1 for 2,
      • \n
      • 4 for 16,
      • \n
      • 8 for 256,
      • \n
      • 24 for 16,777,216\ncolors supported.
      • \n
      \n

      Use this to determine what colors the terminal supports. Due to the nature of\ncolors in terminals it is possible to either have false positives or false\nnegatives. It depends on process information and the environment variables that\nmay lie about what terminal is used.\nIt is possible to pass in an env object to simulate the usage of a specific\nterminal. This can be useful to check how specific environment settings behave.

      \n

      To enforce a specific color support, use one of the below environment settings.

      \n
        \n
      • 2 colors: FORCE_COLOR = 0 (Disables colors)
      • \n
      • 16 colors: FORCE_COLOR = 1
      • \n
      • 256 colors: FORCE_COLOR = 2
      • \n
      • 16,777,216 colors: FORCE_COLOR = 3
      • \n
      \n

      Disabling color support is also possible by using the NO_COLOR and\nNODE_DISABLE_COLORS environment variables.

      " + }, + { + "textRaw": "`writeStream.getWindowSize()`", + "type": "method", + "name": "getWindowSize", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {number[]}", + "name": "return", + "type": "number[]" + }, + "params": [] + } + ], + "desc": "

      writeStream.getWindowSize() returns the size of the TTY\ncorresponding to this WriteStream. The array is of the type\n[numColumns, numRows] where numColumns and numRows represent the number\nof columns and rows in the corresponding TTY.

      " + }, + { + "textRaw": "`writeStream.hasColors([count][, env])`", + "type": "method", + "name": "hasColors", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`count` {integer} The number of colors that are requested (minimum 2). **Default:** 16.", + "name": "count", + "type": "integer", + "default": "16", + "desc": "The number of colors that are requested (minimum 2)." + }, + { + "textRaw": "`env` {Object} An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "An object containing the environment variables to check. This enables simulating the usage of a specific terminal." + } + ] + } + ], + "desc": "

      Returns true if the writeStream supports at least as many colors as provided\nin count. Minimum support is 2 (black and white).

      \n

      This has the same false positives and negatives as described in\nwriteStream.getColorDepth().

      \n
      process.stdout.hasColors();\n// Returns true or false depending on if `stdout` supports at least 16 colors.\nprocess.stdout.hasColors(256);\n// Returns true or false depending on if `stdout` supports at least 256 colors.\nprocess.stdout.hasColors({ TMUX: '1' });\n// Returns true.\nprocess.stdout.hasColors(2 ** 24, { TMUX: '1' });\n// Returns false (the environment setting pretends to support 2 ** 8 colors).\n
      " + }, + { + "textRaw": "`writeStream.moveCursor(dx, dy[, callback])`", + "type": "method", + "name": "moveCursor", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [ + { + "version": "v12.7.0", + "pr-url": "https://github.com/nodejs/node/pull/28721", + "description": "The stream's write() callback and return value are exposed." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", + "name": "return", + "type": "boolean", + "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." + }, + "params": [ + { + "textRaw": "`dx` {number}", + "name": "dx", + "type": "number" + }, + { + "textRaw": "`dy` {number}", + "name": "dy", + "type": "number" + }, + { + "textRaw": "`callback` {Function} Invoked once the operation completes.", + "name": "callback", + "type": "Function", + "desc": "Invoked once the operation completes." + } + ] + } + ], + "desc": "

      writeStream.moveCursor() moves this WriteStream's cursor relative to its\ncurrent position.

      " + } + ], + "properties": [ + { + "textRaw": "`writeStream.columns`", + "name": "columns", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      A number specifying the number of columns the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

      " + }, + { + "textRaw": "`writeStream.isTTY`", + "name": "isTTY", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

      A boolean that is always true.

      " + }, + { + "textRaw": "`writeStream.rows`", + "name": "rows", + "meta": { + "added": [ + "v0.7.7" + ], + "changes": [] + }, + "desc": "

      A number specifying the number of rows the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`tty.isatty(fd)`", + "type": "method", + "name": "isatty", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`fd` {number} A numeric file descriptor", + "name": "fd", + "type": "number", + "desc": "A numeric file descriptor" + } + ] + } + ], + "desc": "

      The tty.isatty() method returns true if the given fd is associated with\na TTY and false if it is not, including whenever fd is not a non-negative\ninteger.

      " + } + ], + "type": "module", + "displayName": "TTY" + } + ] +} \ No newline at end of file diff --git a/doc/api/url.html b/doc/api/url.html new file mode 100644 index 0000000000000000000000000000000000000000..71721b2d6384af838667a2f3cf10ebd676c9266b --- /dev/null +++ b/doc/api/url.html @@ -0,0 +1,1335 @@ + + + + + + + URL | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      URL#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/url.js

      +

      The url module provides utilities for URL resolution and parsing. It can be +accessed using:

      +
      const url = require('url');
      +

      URL strings and URL objects#

      +

      A URL string is a structured string containing multiple meaningful components. +When parsed, a URL object is returned containing properties for each of these +components.

      +

      The url module provides two APIs for working with URLs: a legacy API that is +Node.js specific, and a newer API that implements the same +WHATWG URL Standard used by web browsers.

      +

      A comparison between the WHATWG and Legacy APIs is provided below. Above the URL +'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', properties +of an object returned by the legacy url.parse() are shown. Below it are +properties of a WHATWG URL object.

      +

      WHATWG URL's origin property includes protocol and host, but not +username or password.

      +
      ┌────────────────────────────────────────────────────────────────────────────────────────────────â”
      +│                                              href                                              │
      +├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
      +│ protocol │  │        auth         │          host          │           path            │ hash  │
      +│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
      +│          │  │                     │    hostname     │ port │ pathname │     search     │       │
      +│          │  │                     │                 │      │          ├─┬──────────────┤       │
      +│          │  │                     │                 │      │          │ │    query     │       │
      +"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
      +│          │  │          │          │    hostname     │ port │          │                │       │
      +│          │  │          │          ├─────────────────┴──────┤          │                │       │
      +│ protocol │  │ username │ password │          host          │          │                │       │
      +├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
      +│   origin    │                     │         origin         │ pathname │     search     │ hash  │
      +├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
      +│                                              href                                              │
      +└────────────────────────────────────────────────────────────────────────────────────────────────┘
      +(All spaces in the "" line should be ignored. They are purely for formatting.)
      +

      Parsing the URL string using the WHATWG API:

      +
      const myURL =
      +  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
      +

      Parsing the URL string using the Legacy API:

      +
      const url = require('url');
      +const myURL =
      +  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
      +

      The WHATWG URL API#

      +

      Class: URL#

      + +

      Browser-compatible URL class, implemented by following the WHATWG URL +Standard. Examples of parsed URLs may be found in the Standard itself. +The URL class is also available on the global object.

      +

      In accordance with browser conventions, all properties of URL objects +are implemented as getters and setters on the class prototype, rather than as +data properties on the object itself. Thus, unlike legacy urlObjects, +using the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still +return true.

      +

      new URL(input[, base])#

      +
        +
      • input <string> The absolute or relative input URL to parse. If input +is relative, then base is required. If input is absolute, the base +is ignored.
      • +
      • base <string> | <URL> The base URL to resolve against if the input is not +absolute.
      • +
      +

      Creates a new URL object by parsing the input relative to the base. If +base is passed as a string, it will be parsed equivalent to new URL(base).

      +
      const myURL = new URL('/foo', 'https://example.org/');
      +// https://example.org/foo
      +

      The URL constructor is accessible as a property on the global object. +It can also be imported from the built-in url module:

      +
      console.log(URL === require('url').URL); // Prints 'true'.
      +

      A TypeError will be thrown if the input or base are not valid URLs. Note +that an effort will be made to coerce the given values into strings. For +instance:

      +
      const myURL = new URL({ toString: () => 'https://example.org/' });
      +// https://example.org/
      +

      Unicode characters appearing within the host name of input will be +automatically converted to ASCII using the Punycode algorithm.

      +
      const myURL = new URL('https://測試');
      +// https://xn--g6w251d/
      +

      This feature is only available if the node executable was compiled with +ICU enabled. If not, the domain names are passed through unchanged.

      +

      In cases where it is not known in advance if input is an absolute URL +and a base is provided, it is advised to validate that the origin of +the URL object is what is expected.

      +
      let myURL = new URL('http://Example.com/', 'https://example.org/');
      +// http://example.com/
      +
      +myURL = new URL('https://Example.com/', 'https://example.org/');
      +// https://example.com/
      +
      +myURL = new URL('foo://Example.com/', 'https://example.org/');
      +// foo://Example.com/
      +
      +myURL = new URL('http:Example.com/', 'https://example.org/');
      +// http://example.com/
      +
      +myURL = new URL('https:Example.com/', 'https://example.org/');
      +// https://example.org/Example.com/
      +
      +myURL = new URL('foo:Example.com/', 'https://example.org/');
      +// foo:Example.com/
      +

      url.hash#

      + +

      Gets and sets the fragment portion of the URL.

      +
      const myURL = new URL('https://example.org/foo#bar');
      +console.log(myURL.hash);
      +// Prints #bar
      +
      +myURL.hash = 'baz';
      +console.log(myURL.href);
      +// Prints https://example.org/foo#baz
      +

      Invalid URL characters included in the value assigned to the hash property +are percent-encoded. The selection of which characters to +percent-encode may vary somewhat from what the url.parse() and +url.format() methods would produce.

      +

      url.host#

      + +

      Gets and sets the host portion of the URL.

      +
      const myURL = new URL('https://example.org:81/foo');
      +console.log(myURL.host);
      +// Prints example.org:81
      +
      +myURL.host = 'example.com:82';
      +console.log(myURL.href);
      +// Prints https://example.com:82/foo
      +

      Invalid host values assigned to the host property are ignored.

      +

      url.hostname#

      + +

      Gets and sets the host name portion of the URL. The key difference between +url.host and url.hostname is that url.hostname does not include the +port.

      +
      const myURL = new URL('https://example.org:81/foo');
      +console.log(myURL.hostname);
      +// Prints example.org
      +
      +myURL.hostname = 'example.com:82';
      +console.log(myURL.href);
      +// Prints https://example.com:81/foo
      +

      Invalid host name values assigned to the hostname property are ignored.

      +

      url.href#

      + +

      Gets and sets the serialized URL.

      +
      const myURL = new URL('https://example.org/foo');
      +console.log(myURL.href);
      +// Prints https://example.org/foo
      +
      +myURL.href = 'https://example.com/bar';
      +console.log(myURL.href);
      +// Prints https://example.com/bar
      +

      Getting the value of the href property is equivalent to calling +url.toString().

      +

      Setting the value of this property to a new value is equivalent to creating a +new URL object using new URL(value). Each of the URL +object's properties will be modified.

      +

      If the value assigned to the href property is not a valid URL, a TypeError +will be thrown.

      +

      url.origin#

      + +

      Gets the read-only serialization of the URL's origin.

      +
      const myURL = new URL('https://example.org/foo/bar?baz');
      +console.log(myURL.origin);
      +// Prints https://example.org
      +
      const idnURL = new URL('https://測試');
      +console.log(idnURL.origin);
      +// Prints https://xn--g6w251d
      +
      +console.log(idnURL.hostname);
      +// Prints xn--g6w251d
      +

      url.password#

      + +

      Gets and sets the password portion of the URL.

      +
      const myURL = new URL('https://abc:xyz@example.com');
      +console.log(myURL.password);
      +// Prints xyz
      +
      +myURL.password = '123';
      +console.log(myURL.href);
      +// Prints https://abc:123@example.com
      +

      Invalid URL characters included in the value assigned to the password property +are percent-encoded. The selection of which characters to +percent-encode may vary somewhat from what the url.parse() and +url.format() methods would produce.

      +

      url.pathname#

      + +

      Gets and sets the path portion of the URL.

      +
      const myURL = new URL('https://example.org/abc/xyz?123');
      +console.log(myURL.pathname);
      +// Prints /abc/xyz
      +
      +myURL.pathname = '/abcdef';
      +console.log(myURL.href);
      +// Prints https://example.org/abcdef?123
      +

      Invalid URL characters included in the value assigned to the pathname +property are percent-encoded. The selection of which characters +to percent-encode may vary somewhat from what the url.parse() and +url.format() methods would produce.

      +

      url.port#

      + +

      Gets and sets the port portion of the URL.

      +

      The port value may be a number or a string containing a number in the range +0 to 65535 (inclusive). Setting the value to the default port of the +URL objects given protocol will result in the port value becoming +the empty string ('').

      +

      The port value can be an empty string in which case the port depends on +the protocol/scheme:

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      protocolport
      "ftp"21
      "file"
      "gopher"70
      "http"80
      "https"443
      "ws"80
      "wss"443
      +

      Upon assigning a value to the port, the value will first be converted to a +string using .toString().

      +

      If that string is invalid but it begins with a number, the leading number is +assigned to port. +If the number lies outside the range denoted above, it is ignored.

      +
      const myURL = new URL('https://example.org:8888');
      +console.log(myURL.port);
      +// Prints 8888
      +
      +// Default ports are automatically transformed to the empty string
      +// (HTTPS protocol's default port is 443)
      +myURL.port = '443';
      +console.log(myURL.port);
      +// Prints the empty string
      +console.log(myURL.href);
      +// Prints https://example.org/
      +
      +myURL.port = 1234;
      +console.log(myURL.port);
      +// Prints 1234
      +console.log(myURL.href);
      +// Prints https://example.org:1234/
      +
      +// Completely invalid port strings are ignored
      +myURL.port = 'abcd';
      +console.log(myURL.port);
      +// Prints 1234
      +
      +// Leading numbers are treated as a port number
      +myURL.port = '5678abcd';
      +console.log(myURL.port);
      +// Prints 5678
      +
      +// Non-integers are truncated
      +myURL.port = 1234.5678;
      +console.log(myURL.port);
      +// Prints 1234
      +
      +// Out-of-range numbers which are not represented in scientific notation
      +// will be ignored.
      +myURL.port = 1e10; // 10000000000, will be range-checked as described below
      +console.log(myURL.port);
      +// Prints 1234
      +

      Numbers which contain a decimal point, +such as floating-point numbers or numbers in scientific notation, +are not an exception to this rule. +Leading numbers up to the decimal point will be set as the URL's port, +assuming they are valid:

      +
      myURL.port = 4.567e21;
      +console.log(myURL.port);
      +// Prints 4 (because it is the leading number in the string '4.567e21')
      +

      url.protocol#

      + +

      Gets and sets the protocol portion of the URL.

      +
      const myURL = new URL('https://example.org');
      +console.log(myURL.protocol);
      +// Prints https:
      +
      +myURL.protocol = 'ftp';
      +console.log(myURL.href);
      +// Prints ftp://example.org/
      +

      Invalid URL protocol values assigned to the protocol property are ignored.

      +
      Special schemes#
      +

      The WHATWG URL Standard considers a handful of URL protocol schemes to be +special in terms of how they are parsed and serialized. When a URL is +parsed using one of these special protocols, the url.protocol property +may be changed to another special protocol but cannot be changed to a +non-special protocol, and vice versa.

      +

      For instance, changing from http to https works:

      +
      const u = new URL('http://example.org');
      +u.protocol = 'https';
      +console.log(u.href);
      +// https://example.org
      +

      However, changing from http to a hypothetical fish protocol does not +because the new protocol is not special.

      +
      const u = new URL('http://example.org');
      +u.protocol = 'fish';
      +console.log(u.href);
      +// http://example.org
      +

      Likewise, changing from a non-special protocol to a special protocol is also +not permitted:

      +
      const u = new URL('fish://example.org');
      +u.protocol = 'http';
      +console.log(u.href);
      +// fish://example.org
      +

      According to the WHATWG URL Standard, special protocol schemes are ftp, +file, gopher, http, https, ws, and wss.

      +

      url.search#

      + +

      Gets and sets the serialized query portion of the URL.

      +
      const myURL = new URL('https://example.org/abc?123');
      +console.log(myURL.search);
      +// Prints ?123
      +
      +myURL.search = 'abc=xyz';
      +console.log(myURL.href);
      +// Prints https://example.org/abc?abc=xyz
      +

      Any invalid URL characters appearing in the value assigned the search +property will be percent-encoded. The selection of which +characters to percent-encode may vary somewhat from what the url.parse() +and url.format() methods would produce.

      +

      url.searchParams#

      + +

      Gets the URLSearchParams object representing the query parameters of the +URL. This property is read-only but the URLSearchParams object it provides +can be used to mutate the URL instance; to replace the entirety of query +parameters of the URL, use the url.search setter. See +URLSearchParams documentation for details.

      +

      Use care when using .searchParams to modify the URL because, +per the WHATWG specification, the URLSearchParams object uses +different rules to determine which characters to percent-encode. For +instance, the URL object will not percent encode the ASCII tilde (~) +character, while URLSearchParams will always encode it:

      +
      const myUrl = new URL('https://example.org/abc?foo=~bar');
      +
      +console.log(myUrl.search);  // prints ?foo=~bar
      +
      +// Modify the URL via searchParams...
      +myUrl.searchParams.sort();
      +
      +console.log(myUrl.search);  // prints ?foo=%7Ebar
      +

      url.username#

      + +

      Gets and sets the username portion of the URL.

      +
      const myURL = new URL('https://abc:xyz@example.com');
      +console.log(myURL.username);
      +// Prints abc
      +
      +myURL.username = '123';
      +console.log(myURL.href);
      +// Prints https://123:xyz@example.com/
      +

      Any invalid URL characters appearing in the value assigned the username +property will be percent-encoded. The selection of which +characters to percent-encode may vary somewhat from what the url.parse() +and url.format() methods would produce.

      +

      url.toString()#

      + +

      The toString() method on the URL object returns the serialized URL. The +value returned is equivalent to that of url.href and url.toJSON().

      +

      Because of the need for standard compliance, this method does not allow users +to customize the serialization process of the URL. For more flexibility, +require('url').format() method might be of interest.

      +

      url.toJSON()#

      + +

      The toJSON() method on the URL object returns the serialized URL. The +value returned is equivalent to that of url.href and +url.toString().

      +

      This method is automatically called when an URL object is serialized +with JSON.stringify().

      +
      const myURLs = [
      +  new URL('https://www.example.com'),
      +  new URL('https://test.example.org')
      +];
      +console.log(JSON.stringify(myURLs));
      +// Prints ["https://www.example.com/","https://test.example.org/"]
      +

      Class: URLSearchParams#

      + +

      The URLSearchParams API provides read and write access to the query of a +URL. The URLSearchParams class can also be used standalone with one of the +four following constructors. +The URLSearchParams class is also available on the global object.

      +

      The WHATWG URLSearchParams interface and the querystring module have +similar purpose, but the purpose of the querystring module is more +general, as it allows the customization of delimiter characters (& and =). +On the other hand, this API is designed purely for URL query strings.

      +
      const myURL = new URL('https://example.org/?abc=123');
      +console.log(myURL.searchParams.get('abc'));
      +// Prints 123
      +
      +myURL.searchParams.append('abc', 'xyz');
      +console.log(myURL.href);
      +// Prints https://example.org/?abc=123&abc=xyz
      +
      +myURL.searchParams.delete('abc');
      +myURL.searchParams.set('a', 'b');
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b
      +
      +const newSearchParams = new URLSearchParams(myURL.searchParams);
      +// The above is equivalent to
      +// const newSearchParams = new URLSearchParams(myURL.search);
      +
      +newSearchParams.append('a', 'c');
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b
      +console.log(newSearchParams.toString());
      +// Prints a=b&a=c
      +
      +// newSearchParams.toString() is implicitly called
      +myURL.search = newSearchParams;
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b&a=c
      +newSearchParams.delete('a');
      +console.log(myURL.href);
      +// Prints https://example.org/?a=b&a=c
      +

      new URLSearchParams()#

      +

      Instantiate a new empty URLSearchParams object.

      +

      new URLSearchParams(string)#

      + +

      Parse the string as a query string, and use it to instantiate a new +URLSearchParams object. A leading '?', if present, is ignored.

      +
      let params;
      +
      +params = new URLSearchParams('user=abc&query=xyz');
      +console.log(params.get('user'));
      +// Prints 'abc'
      +console.log(params.toString());
      +// Prints 'user=abc&query=xyz'
      +
      +params = new URLSearchParams('?user=abc&query=xyz');
      +console.log(params.toString());
      +// Prints 'user=abc&query=xyz'
      +

      new URLSearchParams(obj)#

      + +
        +
      • obj <Object> An object representing a collection of key-value pairs
      • +
      +

      Instantiate a new URLSearchParams object with a query hash map. The key and +value of each property of obj are always coerced to strings.

      +

      Unlike querystring module, duplicate keys in the form of array values are +not allowed. Arrays are stringified using array.toString(), which simply +joins all array elements with commas.

      +
      const params = new URLSearchParams({
      +  user: 'abc',
      +  query: ['first', 'second']
      +});
      +console.log(params.getAll('query'));
      +// Prints [ 'first,second' ]
      +console.log(params.toString());
      +// Prints 'user=abc&query=first%2Csecond'
      +

      new URLSearchParams(iterable)#

      + +
        +
      • iterable <Iterable> An iterable object whose elements are key-value pairs
      • +
      +

      Instantiate a new URLSearchParams object with an iterable map in a way that +is similar to Map's constructor. iterable can be an Array or any +iterable object. That means iterable can be another URLSearchParams, in +which case the constructor will simply create a clone of the provided +URLSearchParams. Elements of iterable are key-value pairs, and can +themselves be any iterable object.

      +

      Duplicate keys are allowed.

      +
      let params;
      +
      +// Using an array
      +params = new URLSearchParams([
      +  ['user', 'abc'],
      +  ['query', 'first'],
      +  ['query', 'second']
      +]);
      +console.log(params.toString());
      +// Prints 'user=abc&query=first&query=second'
      +
      +// Using a Map object
      +const map = new Map();
      +map.set('user', 'abc');
      +map.set('query', 'xyz');
      +params = new URLSearchParams(map);
      +console.log(params.toString());
      +// Prints 'user=abc&query=xyz'
      +
      +// Using a generator function
      +function* getQueryPairs() {
      +  yield ['user', 'abc'];
      +  yield ['query', 'first'];
      +  yield ['query', 'second'];
      +}
      +params = new URLSearchParams(getQueryPairs());
      +console.log(params.toString());
      +// Prints 'user=abc&query=first&query=second'
      +
      +// Each key-value pair must have exactly two elements
      +new URLSearchParams([
      +  ['user', 'abc', 'error']
      +]);
      +// Throws TypeError [ERR_INVALID_TUPLE]:
      +//        Each query pair must be an iterable [name, value] tuple
      +

      urlSearchParams.append(name, value)#

      + +

      Append a new name-value pair to the query string.

      +

      urlSearchParams.delete(name)#

      + +

      Remove all name-value pairs whose name is name.

      +

      urlSearchParams.entries()#

      + +

      Returns an ES6 Iterator over each of the name-value pairs in the query. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the name, the second item of the Array is the value.

      +

      Alias for urlSearchParams[@@iterator]().

      +

      urlSearchParams.forEach(fn[, thisArg])#

      +
        +
      • fn <Function> Invoked for each name-value pair in the query
      • +
      • thisArg <Object> To be used as this value for when fn is called
      • +
      +

      Iterates over each name-value pair in the query and invokes the given function.

      +
      const myURL = new URL('https://example.org/?a=b&c=d');
      +myURL.searchParams.forEach((value, name, searchParams) => {
      +  console.log(name, value, myURL.searchParams === searchParams);
      +});
      +// Prints:
      +//   a b true
      +//   c d true
      +

      urlSearchParams.get(name)#

      +
        +
      • name <string>
      • +
      • Returns: <string> or null if there is no name-value pair with the given +name.
      • +
      +

      Returns the value of the first name-value pair whose name is name. If there +are no such pairs, null is returned.

      +

      urlSearchParams.getAll(name)#

      + +

      Returns the values of all name-value pairs whose name is name. If there are +no such pairs, an empty array is returned.

      +

      urlSearchParams.has(name)#

      + +

      Returns true if there is at least one name-value pair whose name is name.

      +

      urlSearchParams.keys()#

      + +

      Returns an ES6 Iterator over the names of each name-value pair.

      +
      const params = new URLSearchParams('foo=bar&foo=baz');
      +for (const name of params.keys()) {
      +  console.log(name);
      +}
      +// Prints:
      +//   foo
      +//   foo
      +

      urlSearchParams.set(name, value)#

      + +

      Sets the value in the URLSearchParams object associated with name to +value. If there are any pre-existing name-value pairs whose names are name, +set the first such pair's value to value and remove all others. If not, +append the name-value pair to the query string.

      +
      const params = new URLSearchParams();
      +params.append('foo', 'bar');
      +params.append('foo', 'baz');
      +params.append('abc', 'def');
      +console.log(params.toString());
      +// Prints foo=bar&foo=baz&abc=def
      +
      +params.set('foo', 'def');
      +params.set('xyz', 'opq');
      +console.log(params.toString());
      +// Prints foo=def&abc=def&xyz=opq
      +

      urlSearchParams.sort()#

      + +

      Sort all existing name-value pairs in-place by their names. Sorting is done +with a stable sorting algorithm, so relative order between name-value pairs +with the same name is preserved.

      +

      This method can be used, in particular, to increase cache hits.

      +
      const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
      +params.sort();
      +console.log(params.toString());
      +// Prints query%5B%5D=abc&query%5B%5D=123&type=search
      +

      urlSearchParams.toString()#

      + +

      Returns the search parameters serialized as a string, with characters +percent-encoded where necessary.

      +

      urlSearchParams.values()#

      + +

      Returns an ES6 Iterator over the values of each name-value pair.

      +

      urlSearchParams[Symbol.iterator]()#

      + +

      Returns an ES6 Iterator over each of the name-value pairs in the query string. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the name, the second item of the Array is the value.

      +

      Alias for urlSearchParams.entries().

      +
      const params = new URLSearchParams('foo=bar&xyz=baz');
      +for (const [name, value] of params) {
      +  console.log(name, value);
      +}
      +// Prints:
      +//   foo bar
      +//   xyz baz
      +

      url.domainToASCII(domain)#

      + + +

      Returns the Punycode ASCII serialization of the domain. If domain is an +invalid domain, the empty string is returned.

      +

      It performs the inverse operation to url.domainToUnicode().

      +
      const url = require('url');
      +console.log(url.domainToASCII('español.com'));
      +// Prints xn--espaol-zwa.com
      +console.log(url.domainToASCII('中文.com'));
      +// Prints xn--fiq228c.com
      +console.log(url.domainToASCII('xn--iñvalid.com'));
      +// Prints an empty string
      +

      url.domainToUnicode(domain)#

      + + +

      Returns the Unicode serialization of the domain. If domain is an invalid +domain, the empty string is returned.

      +

      It performs the inverse operation to url.domainToASCII().

      +
      const url = require('url');
      +console.log(url.domainToUnicode('xn--espaol-zwa.com'));
      +// Prints español.com
      +console.log(url.domainToUnicode('xn--fiq228c.com'));
      +// Prints 中文.com
      +console.log(url.domainToUnicode('xn--iñvalid.com'));
      +// Prints an empty string
      +

      url.fileURLToPath(url)#

      + +
        +
      • url <URL> | <string> The file URL string or URL object to convert to a path.
      • +
      • Returns: <string> The fully-resolved platform-specific Node.js file path.
      • +
      +

      This function ensures the correct decodings of percent-encoded characters as +well as ensuring a cross-platform valid absolute path string.

      +
      new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/
      +fileURLToPath('file:///C:/path/');       // Correct:   C:\path\ (Windows)
      +
      +new URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt
      +fileURLToPath('file://nas/foo.txt');     // Correct:   \\nas\foo.txt (Windows)
      +
      +new URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
      +fileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)
      +
      +new URL('file:///hello world').pathname; // Incorrect: /hello%20world
      +fileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)
      +

      url.format(URL[, options])#

      + +
        +
      • URL <URL> A WHATWG URL object
      • +
      • options <Object> +
          +
        • auth <boolean> true if the serialized URL string should include the +username and password, false otherwise. Default: true.
        • +
        • fragment <boolean> true if the serialized URL string should include the +fragment, false otherwise. Default: true.
        • +
        • search <boolean> true if the serialized URL string should include the +search query, false otherwise. Default: true.
        • +
        • unicode <boolean> true if Unicode characters appearing in the host +component of the URL string should be encoded directly as opposed to being +Punycode encoded. Default: false.
        • +
        +
      • +
      • Returns: <string>
      • +
      +

      Returns a customizable serialization of a URL String representation of a +WHATWG URL object.

      +

      The URL object has both a toString() method and href property that return +string serializations of the URL. These are not, however, customizable in +any way. The url.format(URL[, options]) method allows for basic customization +of the output.

      +
      const myURL = new URL('https://a:b@測試?abc#foo');
      +
      +console.log(myURL.href);
      +// Prints https://a:b@xn--g6w251d/?abc#foo
      +
      +console.log(myURL.toString());
      +// Prints https://a:b@xn--g6w251d/?abc#foo
      +
      +console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
      +// Prints 'https://測試/?abc'
      +

      url.pathToFileURL(path)#

      + +
        +
      • path <string> The path to convert to a File URL.
      • +
      • Returns: <URL> The file URL object.
      • +
      +

      This function ensures that path is resolved absolutely, and that the URL +control characters are correctly encoded when converting into a File URL.

      +
      new URL(__filename);                // Incorrect: throws (POSIX)
      +new URL(__filename);                // Incorrect: C:\... (Windows)
      +pathToFileURL(__filename);          // Correct:   file:///... (POSIX)
      +pathToFileURL(__filename);          // Correct:   file:///C:/... (Windows)
      +
      +new URL('/foo#1', 'file:');         // Incorrect: file:///foo#1
      +pathToFileURL('/foo#1');            // Correct:   file:///foo%231 (POSIX)
      +
      +new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
      +pathToFileURL('/some/path%.c');    // Correct:   file:///some/path%25.c (POSIX)
      +

      Legacy URL API#

      + +

      Legacy urlObject#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +

      The legacy urlObject (require('url').Url) is created and returned by the +url.parse() function.

      +

      urlObject.auth#

      +

      The auth property is the username and password portion of the URL, also +referred to as userinfo. This string subset follows the protocol and +double slashes (if present) and precedes the host component, delimited by @. +The string is either the username, or it is the username and password separated +by :.

      +

      For example: 'user:pass'.

      +

      urlObject.hash#

      +

      The hash property is the fragment identifier portion of the URL including the +leading # character.

      +

      For example: '#hash'.

      +

      urlObject.host#

      +

      The host property is the full lower-cased host portion of the URL, including +the port if specified.

      +

      For example: 'sub.example.com:8080'.

      +

      urlObject.hostname#

      +

      The hostname property is the lower-cased host name portion of the host +component without the port included.

      +

      For example: 'sub.example.com'.

      +

      urlObject.href#

      +

      The href property is the full URL string that was parsed with both the +protocol and host components converted to lower-case.

      +

      For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.

      +

      urlObject.path#

      +

      The path property is a concatenation of the pathname and search +components.

      +

      For example: '/p/a/t/h?query=string'.

      +

      No decoding of the path is performed.

      +

      urlObject.pathname#

      +

      The pathname property consists of the entire path section of the URL. This +is everything following the host (including the port) and before the start +of the query or hash components, delimited by either the ASCII question +mark (?) or hash (#) characters.

      +

      For example: '/p/a/t/h'.

      +

      No decoding of the path string is performed.

      +

      urlObject.port#

      +

      The port property is the numeric port portion of the host component.

      +

      For example: '8080'.

      +

      urlObject.protocol#

      +

      The protocol property identifies the URL's lower-cased protocol scheme.

      +

      For example: 'http:'.

      +

      urlObject.query#

      +

      The query property is either the query string without the leading ASCII +question mark (?), or an object returned by the querystring module's +parse() method. Whether the query property is a string or object is +determined by the parseQueryString argument passed to url.parse().

      +

      For example: 'query=string' or {'query': 'string'}.

      +

      If returned as a string, no decoding of the query string is performed. If +returned as an object, both keys and values are decoded.

      +

      urlObject.search#

      +

      The search property consists of the entire "query string" portion of the +URL, including the leading ASCII question mark (?) character.

      +

      For example: '?query=string'.

      +

      No decoding of the query string is performed.

      +

      urlObject.slashes#

      +

      The slashes property is a boolean with a value of true if two ASCII +forward-slash characters (/) are required following the colon in the +protocol.

      +

      url.format(urlObject)#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +
        +
      • urlObject <Object> | <string> A URL object (as returned by url.parse() or +constructed otherwise). If a string, it is converted to an object by passing +it to url.parse().
      • +
      +

      The url.format() method returns a formatted URL string derived from +urlObject.

      +
      url.format({
      +  protocol: 'https',
      +  hostname: 'example.com',
      +  pathname: '/some/path',
      +  query: {
      +    page: 1,
      +    format: 'json'
      +  }
      +});
      +
      +// => 'https://example.com/some/path?page=1&format=json'
      +

      If urlObject is not an object or a string, url.format() will throw a +TypeError.

      +

      The formatting process operates as follows:

      +
        +
      • A new empty string result is created.
      • +
      • If urlObject.protocol is a string, it is appended as-is to result.
      • +
      • Otherwise, if urlObject.protocol is not undefined and is not a string, an +Error is thrown.
      • +
      • For all string values of urlObject.protocol that do not end with an ASCII +colon (:) character, the literal string : will be appended to result.
      • +
      • If either of the following conditions is true, then the literal string // +will be appended to result: +
          +
        • urlObject.slashes property is true;
        • +
        • urlObject.protocol begins with http, https, ftp, gopher, or +file;
        • +
        +
      • +
      • If the value of the urlObject.auth property is truthy, and either +urlObject.host or urlObject.hostname are not undefined, the value of +urlObject.auth will be coerced into a string and appended to result +followed by the literal string @.
      • +
      • If the urlObject.host property is undefined then: +
          +
        • If the urlObject.hostname is a string, it is appended to result.
        • +
        • Otherwise, if urlObject.hostname is not undefined and is not a string, +an Error is thrown.
        • +
        • If the urlObject.port property value is truthy, and urlObject.hostname +is not undefined: +
            +
          • The literal string : is appended to result, and
          • +
          • The value of urlObject.port is coerced to a string and appended to +result.
          • +
          +
        • +
        +
      • +
      • Otherwise, if the urlObject.host property value is truthy, the value of +urlObject.host is coerced to a string and appended to result.
      • +
      • If the urlObject.pathname property is a string that is not an empty string: +
          +
        • If the urlObject.pathname does not start with an ASCII forward slash +(/), then the literal string '/' is appended to result.
        • +
        • The value of urlObject.pathname is appended to result.
        • +
        +
      • +
      • Otherwise, if urlObject.pathname is not undefined and is not a string, an +Error is thrown.
      • +
      • If the urlObject.search property is undefined and if the urlObject.query +property is an Object, the literal string ? is appended to result +followed by the output of calling the querystring module's stringify() +method passing the value of urlObject.query.
      • +
      • Otherwise, if urlObject.search is a string: +
          +
        • If the value of urlObject.search does not start with the ASCII question +mark (?) character, the literal string ? is appended to result.
        • +
        • The value of urlObject.search is appended to result.
        • +
        +
      • +
      • Otherwise, if urlObject.search is not undefined and is not a string, an +Error is thrown.
      • +
      • If the urlObject.hash property is a string: +
          +
        • If the value of urlObject.hash does not start with the ASCII hash (#) +character, the literal string # is appended to result.
        • +
        • The value of urlObject.hash is appended to result.
        • +
        +
      • +
      • Otherwise, if the urlObject.hash property is not undefined and is not a +string, an Error is thrown.
      • +
      • result is returned.
      • +
      +

      url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +
        +
      • urlString <string> The URL string to parse.
      • +
      • parseQueryString <boolean> If true, the query property will always +be set to an object returned by the querystring module's parse() +method. If false, the query property on the returned URL object will be an +unparsed, undecoded string. Default: false.
      • +
      • slashesDenoteHost <boolean> If true, the first token after the literal +string // and preceding the next / will be interpreted as the host. +For instance, given //foo/bar, the result would be +{host: 'foo', pathname: '/bar'} rather than {pathname: '//foo/bar'}. +Default: false.
      • +
      +

      The url.parse() method takes a URL string, parses it, and returns a URL +object.

      +

      A TypeError is thrown if urlString is not a string.

      +

      A URIError is thrown if the auth property is present but cannot be decoded.

      +

      Use of the legacy url.parse() method is discouraged. Users should +use the WHATWG URL API. Because the url.parse() method uses a +lenient, non-standard algorithm for parsing URL strings, security +issues can be introduced. Specifically, issues with host name spoofing and +incorrect handling of usernames and passwords have been identified.

      +

      url.resolve(from, to)#

      + +

      Stability: 0 - Deprecated: Use the WHATWG URL API instead.

      +
        +
      • from <string> The Base URL being resolved against.
      • +
      • to <string> The HREF URL being resolved.
      • +
      +

      The url.resolve() method resolves a target URL relative to a base URL in a +manner similar to that of a Web browser resolving an anchor tag HREF.

      +
      const url = require('url');
      +url.resolve('/one/two/three', 'four');         // '/one/two/four'
      +url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
      +url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
      +

      +

      Percent-encoding in URLs#

      +

      URLs are permitted to only contain a certain range of characters. Any character +falling outside of that range must be encoded. How such characters are encoded, +and which characters to encode depends entirely on where the character is +located within the structure of the URL.

      +

      Legacy API#

      +

      Within the Legacy API, spaces (' ') and the following characters will be +automatically escaped in the properties of URL objects:

      +
      < > " ` \r \n \t { } | \ ^ '
      +

      For example, the ASCII space character (' ') is encoded as %20. The ASCII +forward slash (/) character is encoded as %3C.

      +

      WHATWG API#

      +

      The WHATWG URL Standard uses a more selective and fine grained approach to +selecting encoded characters than that used by the Legacy API.

      +

      The WHATWG algorithm defines four "percent-encode sets" that describe ranges +of characters that must be percent-encoded:

      +
        +
      • +

        The C0 control percent-encode set includes code points in range U+0000 to +U+001F (inclusive) and all code points greater than U+007E.

        +
      • +
      • +

        The fragment percent-encode set includes the C0 control percent-encode set +and code points U+0020, U+0022, U+003C, U+003E, and U+0060.

        +
      • +
      • +

        The path percent-encode set includes the C0 control percent-encode set +and code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060, +U+007B, and U+007D.

        +
      • +
      • +

        The userinfo encode set includes the path percent-encode set and code +points U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D, +U+005E, and U+007C.

        +
      • +
      +

      The userinfo percent-encode set is used exclusively for username and +passwords encoded within the URL. The path percent-encode set is used for the +path of most URLs. The fragment percent-encode set is used for URL fragments. +The C0 control percent-encode set is used for host and path under certain +specific conditions, in addition to all other cases.

      +

      When non-ASCII characters appear within a host name, the host name is encoded +using the Punycode algorithm. Note, however, that a host name may contain +both Punycode encoded and percent-encoded characters:

      +
      const myURL = new URL('https://%CF%80.example.com/foo');
      +console.log(myURL.href);
      +// Prints https://xn--1xa.example.com/foo
      +console.log(myURL.origin);
      +// Prints https://xn--1xa.example.com
      + +
      +
      +
      + + diff --git a/doc/api/url.json b/doc/api/url.json new file mode 100644 index 0000000000000000000000000000000000000000..f7df7e6bf0454b757344c090bc5605c9d79312ac --- /dev/null +++ b/doc/api/url.json @@ -0,0 +1,947 @@ +{ + "type": "module", + "source": "doc/api/url.md", + "modules": [ + { + "textRaw": "URL", + "name": "url", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/url.js

      \n

      The url module provides utilities for URL resolution and parsing. It can be\naccessed using:

      \n
      const url = require('url');\n
      ", + "modules": [ + { + "textRaw": "URL strings and URL objects", + "name": "url_strings_and_url_objects", + "desc": "

      A URL string is a structured string containing multiple meaningful components.\nWhen parsed, a URL object is returned containing properties for each of these\ncomponents.

      \n

      The url module provides two APIs for working with URLs: a legacy API that is\nNode.js specific, and a newer API that implements the same\nWHATWG URL Standard used by web browsers.

      \n

      A comparison between the WHATWG and Legacy APIs is provided below. Above the URL\n'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', properties\nof an object returned by the legacy url.parse() are shown. Below it are\nproperties of a WHATWG URL object.

      \n

      WHATWG URL's origin property includes protocol and host, but not\nusername or password.

      \n
      ┌────────────────────────────────────────────────────────────────────────────────────────────────â”\n│                                              href                                              │\n├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤\n│ protocol │  │        auth         │          host          │           path            │ hash  │\n│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │\n│          │  │                     │    hostname     │ port │ pathname │     search     │       │\n│          │  │                     │                 │      │          ├─┬──────────────┤       │\n│          │  │                     │                 │      │          │ │    query     │       │\n\"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash \"\n│          │  │          │          │    hostname     │ port │          │                │       │\n│          │  │          │          ├─────────────────┴──────┤          │                │       │\n│ protocol │  │ username │ password │          host          │          │                │       │\n├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │\n│   origin    │                     │         origin         │ pathname │     search     │ hash  │\n├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤\n│                                              href                                              │\n└────────────────────────────────────────────────────────────────────────────────────────────────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
      \n

      Parsing the URL string using the WHATWG API:

      \n
      const myURL =\n  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
      \n

      Parsing the URL string using the Legacy API:

      \n
      const url = require('url');\nconst myURL =\n  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
      ", + "type": "module", + "displayName": "URL strings and URL objects" + }, + { + "textRaw": "The WHATWG URL API", + "name": "the_whatwg_url_api", + "classes": [ + { + "textRaw": "Class: `URL`", + "type": "class", + "name": "URL", + "meta": { + "added": [ + "v7.0.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18281", + "description": "The class is now available on the global object." + } + ] + }, + "desc": "

      Browser-compatible URL class, implemented by following the WHATWG URL\nStandard. Examples of parsed URLs may be found in the Standard itself.\nThe URL class is also available on the global object.

      \n

      In accordance with browser conventions, all properties of URL objects\nare implemented as getters and setters on the class prototype, rather than as\ndata properties on the object itself. Thus, unlike legacy urlObjects,\nusing the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still\nreturn true.

      ", + "properties": [ + { + "textRaw": "`hash` {string}", + "type": "string", + "name": "hash", + "desc": "

      Gets and sets the fragment portion of the URL.

      \n
      const myURL = new URL('https://example.org/foo#bar');\nconsole.log(myURL.hash);\n// Prints #bar\n\nmyURL.hash = 'baz';\nconsole.log(myURL.href);\n// Prints https://example.org/foo#baz\n
      \n

      Invalid URL characters included in the value assigned to the hash property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

      " + }, + { + "textRaw": "`host` {string}", + "type": "string", + "name": "host", + "desc": "

      Gets and sets the host portion of the URL.

      \n
      const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.host);\n// Prints example.org:81\n\nmyURL.host = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:82/foo\n
      \n

      Invalid host values assigned to the host property are ignored.

      " + }, + { + "textRaw": "`hostname` {string}", + "type": "string", + "name": "hostname", + "desc": "

      Gets and sets the host name portion of the URL. The key difference between\nurl.host and url.hostname is that url.hostname does not include the\nport.

      \n
      const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.hostname);\n// Prints example.org\n\nmyURL.hostname = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:81/foo\n
      \n

      Invalid host name values assigned to the hostname property are ignored.

      " + }, + { + "textRaw": "`href` {string}", + "type": "string", + "name": "href", + "desc": "

      Gets and sets the serialized URL.

      \n
      const myURL = new URL('https://example.org/foo');\nconsole.log(myURL.href);\n// Prints https://example.org/foo\n\nmyURL.href = 'https://example.com/bar';\nconsole.log(myURL.href);\n// Prints https://example.com/bar\n
      \n

      Getting the value of the href property is equivalent to calling\nurl.toString().

      \n

      Setting the value of this property to a new value is equivalent to creating a\nnew URL object using new URL(value). Each of the URL\nobject's properties will be modified.

      \n

      If the value assigned to the href property is not a valid URL, a TypeError\nwill be thrown.

      " + }, + { + "textRaw": "`origin` {string}", + "type": "string", + "name": "origin", + "desc": "

      Gets the read-only serialization of the URL's origin.

      \n
      const myURL = new URL('https://example.org/foo/bar?baz');\nconsole.log(myURL.origin);\n// Prints https://example.org\n
      \n
      const idnURL = new URL('https://測試');\nconsole.log(idnURL.origin);\n// Prints https://xn--g6w251d\n\nconsole.log(idnURL.hostname);\n// Prints xn--g6w251d\n
      " + }, + { + "textRaw": "`password` {string}", + "type": "string", + "name": "password", + "desc": "

      Gets and sets the password portion of the URL.

      \n
      const myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.password);\n// Prints xyz\n\nmyURL.password = '123';\nconsole.log(myURL.href);\n// Prints https://abc:123@example.com\n
      \n

      Invalid URL characters included in the value assigned to the password property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

      " + }, + { + "textRaw": "`pathname` {string}", + "type": "string", + "name": "pathname", + "desc": "

      Gets and sets the path portion of the URL.

      \n
      const myURL = new URL('https://example.org/abc/xyz?123');\nconsole.log(myURL.pathname);\n// Prints /abc/xyz\n\nmyURL.pathname = '/abcdef';\nconsole.log(myURL.href);\n// Prints https://example.org/abcdef?123\n
      \n

      Invalid URL characters included in the value assigned to the pathname\nproperty are percent-encoded. The selection of which characters\nto percent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

      " + }, + { + "textRaw": "`port` {string}", + "type": "string", + "name": "port", + "desc": "

      Gets and sets the port portion of the URL.

      \n

      The port value may be a number or a string containing a number in the range\n0 to 65535 (inclusive). Setting the value to the default port of the\nURL objects given protocol will result in the port value becoming\nthe empty string ('').

      \n

      The port value can be an empty string in which case the port depends on\nthe protocol/scheme:

      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      protocolport
      \"ftp\"21
      \"file\"
      \"gopher\"70
      \"http\"80
      \"https\"443
      \"ws\"80
      \"wss\"443
      \n

      Upon assigning a value to the port, the value will first be converted to a\nstring using .toString().

      \n

      If that string is invalid but it begins with a number, the leading number is\nassigned to port.\nIf the number lies outside the range denoted above, it is ignored.

      \n
      const myURL = new URL('https://example.org:8888');\nconsole.log(myURL.port);\n// Prints 8888\n\n// Default ports are automatically transformed to the empty string\n// (HTTPS protocol's default port is 443)\nmyURL.port = '443';\nconsole.log(myURL.port);\n// Prints the empty string\nconsole.log(myURL.href);\n// Prints https://example.org/\n\nmyURL.port = 1234;\nconsole.log(myURL.port);\n// Prints 1234\nconsole.log(myURL.href);\n// Prints https://example.org:1234/\n\n// Completely invalid port strings are ignored\nmyURL.port = 'abcd';\nconsole.log(myURL.port);\n// Prints 1234\n\n// Leading numbers are treated as a port number\nmyURL.port = '5678abcd';\nconsole.log(myURL.port);\n// Prints 5678\n\n// Non-integers are truncated\nmyURL.port = 1234.5678;\nconsole.log(myURL.port);\n// Prints 1234\n\n// Out-of-range numbers which are not represented in scientific notation\n// will be ignored.\nmyURL.port = 1e10; // 10000000000, will be range-checked as described below\nconsole.log(myURL.port);\n// Prints 1234\n
      \n

      Numbers which contain a decimal point,\nsuch as floating-point numbers or numbers in scientific notation,\nare not an exception to this rule.\nLeading numbers up to the decimal point will be set as the URL's port,\nassuming they are valid:

      \n
      myURL.port = 4.567e21;\nconsole.log(myURL.port);\n// Prints 4 (because it is the leading number in the string '4.567e21')\n
      " + }, + { + "textRaw": "`protocol` {string}", + "type": "string", + "name": "protocol", + "desc": "

      Gets and sets the protocol portion of the URL.

      \n
      const myURL = new URL('https://example.org');\nconsole.log(myURL.protocol);\n// Prints https:\n\nmyURL.protocol = 'ftp';\nconsole.log(myURL.href);\n// Prints ftp://example.org/\n
      \n

      Invalid URL protocol values assigned to the protocol property are ignored.

      ", + "modules": [ + { + "textRaw": "Special schemes", + "name": "special_schemes", + "desc": "

      The WHATWG URL Standard considers a handful of URL protocol schemes to be\nspecial in terms of how they are parsed and serialized. When a URL is\nparsed using one of these special protocols, the url.protocol property\nmay be changed to another special protocol but cannot be changed to a\nnon-special protocol, and vice versa.

      \n

      For instance, changing from http to https works:

      \n
      const u = new URL('http://example.org');\nu.protocol = 'https';\nconsole.log(u.href);\n// https://example.org\n
      \n

      However, changing from http to a hypothetical fish protocol does not\nbecause the new protocol is not special.

      \n
      const u = new URL('http://example.org');\nu.protocol = 'fish';\nconsole.log(u.href);\n// http://example.org\n
      \n

      Likewise, changing from a non-special protocol to a special protocol is also\nnot permitted:

      \n
      const u = new URL('fish://example.org');\nu.protocol = 'http';\nconsole.log(u.href);\n// fish://example.org\n
      \n

      According to the WHATWG URL Standard, special protocol schemes are ftp,\nfile, gopher, http, https, ws, and wss.

      ", + "type": "module", + "displayName": "Special schemes" + } + ] + }, + { + "textRaw": "`search` {string}", + "type": "string", + "name": "search", + "desc": "

      Gets and sets the serialized query portion of the URL.

      \n
      const myURL = new URL('https://example.org/abc?123');\nconsole.log(myURL.search);\n// Prints ?123\n\nmyURL.search = 'abc=xyz';\nconsole.log(myURL.href);\n// Prints https://example.org/abc?abc=xyz\n
      \n

      Any invalid URL characters appearing in the value assigned the search\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

      " + }, + { + "textRaw": "`searchParams` {URLSearchParams}", + "type": "URLSearchParams", + "name": "searchParams", + "desc": "

      Gets the URLSearchParams object representing the query parameters of the\nURL. This property is read-only but the URLSearchParams object it provides\ncan be used to mutate the URL instance; to replace the entirety of query\nparameters of the URL, use the url.search setter. See\nURLSearchParams documentation for details.

      \n

      Use care when using .searchParams to modify the URL because,\nper the WHATWG specification, the URLSearchParams object uses\ndifferent rules to determine which characters to percent-encode. For\ninstance, the URL object will not percent encode the ASCII tilde (~)\ncharacter, while URLSearchParams will always encode it:

      \n
      const myUrl = new URL('https://example.org/abc?foo=~bar');\n\nconsole.log(myUrl.search);  // prints ?foo=~bar\n\n// Modify the URL via searchParams...\nmyUrl.searchParams.sort();\n\nconsole.log(myUrl.search);  // prints ?foo=%7Ebar\n
      " + }, + { + "textRaw": "`username` {string}", + "type": "string", + "name": "username", + "desc": "

      Gets and sets the username portion of the URL.

      \n
      const myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.username);\n// Prints abc\n\nmyURL.username = '123';\nconsole.log(myURL.href);\n// Prints https://123:xyz@example.com/\n
      \n

      Any invalid URL characters appearing in the value assigned the username\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

      " + } + ], + "methods": [ + { + "textRaw": "`url.toString()`", + "type": "method", + "name": "toString", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      The toString() method on the URL object returns the serialized URL. The\nvalue returned is equivalent to that of url.href and url.toJSON().

      \n

      Because of the need for standard compliance, this method does not allow users\nto customize the serialization process of the URL. For more flexibility,\nrequire('url').format() method might be of interest.

      " + }, + { + "textRaw": "`url.toJSON()`", + "type": "method", + "name": "toJSON", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      The toJSON() method on the URL object returns the serialized URL. The\nvalue returned is equivalent to that of url.href and\nurl.toString().

      \n

      This method is automatically called when an URL object is serialized\nwith JSON.stringify().

      \n
      const myURLs = [\n  new URL('https://www.example.com'),\n  new URL('https://test.example.org')\n];\nconsole.log(JSON.stringify(myURLs));\n// Prints [\"https://www.example.com/\",\"https://test.example.org/\"]\n
      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`input` {string} The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored.", + "name": "input", + "type": "string", + "desc": "The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored." + }, + { + "textRaw": "`base` {string|URL} The base URL to resolve against if the `input` is not absolute.", + "name": "base", + "type": "string|URL", + "desc": "The base URL to resolve against if the `input` is not absolute." + } + ], + "desc": "

      Creates a new URL object by parsing the input relative to the base. If\nbase is passed as a string, it will be parsed equivalent to new URL(base).

      \n
      const myURL = new URL('/foo', 'https://example.org/');\n// https://example.org/foo\n
      \n

      The URL constructor is accessible as a property on the global object.\nIt can also be imported from the built-in url module:

      \n
      console.log(URL === require('url').URL); // Prints 'true'.\n
      \n

      A TypeError will be thrown if the input or base are not valid URLs. Note\nthat an effort will be made to coerce the given values into strings. For\ninstance:

      \n
      const myURL = new URL({ toString: () => 'https://example.org/' });\n// https://example.org/\n
      \n

      Unicode characters appearing within the host name of input will be\nautomatically converted to ASCII using the Punycode algorithm.

      \n
      const myURL = new URL('https://測試');\n// https://xn--g6w251d/\n
      \n

      This feature is only available if the node executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.

      \n

      In cases where it is not known in advance if input is an absolute URL\nand a base is provided, it is advised to validate that the origin of\nthe URL object is what is expected.

      \n
      let myURL = new URL('http://Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https://Example.com/', 'https://example.org/');\n// https://example.com/\n\nmyURL = new URL('foo://Example.com/', 'https://example.org/');\n// foo://Example.com/\n\nmyURL = new URL('http:Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https:Example.com/', 'https://example.org/');\n// https://example.org/Example.com/\n\nmyURL = new URL('foo:Example.com/', 'https://example.org/');\n// foo:Example.com/\n
      " + } + ] + }, + { + "textRaw": "Class: `URLSearchParams`", + "type": "class", + "name": "URLSearchParams", + "meta": { + "added": [ + "v7.5.0", + "v6.13.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/18281", + "description": "The class is now available on the global object." + } + ] + }, + "desc": "

      The URLSearchParams API provides read and write access to the query of a\nURL. The URLSearchParams class can also be used standalone with one of the\nfour following constructors.\nThe URLSearchParams class is also available on the global object.

      \n

      The WHATWG URLSearchParams interface and the querystring module have\nsimilar purpose, but the purpose of the querystring module is more\ngeneral, as it allows the customization of delimiter characters (& and =).\nOn the other hand, this API is designed purely for URL query strings.

      \n
      const myURL = new URL('https://example.org/?abc=123');\nconsole.log(myURL.searchParams.get('abc'));\n// Prints 123\n\nmyURL.searchParams.append('abc', 'xyz');\nconsole.log(myURL.href);\n// Prints https://example.org/?abc=123&abc=xyz\n\nmyURL.searchParams.delete('abc');\nmyURL.searchParams.set('a', 'b');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\n\nconst newSearchParams = new URLSearchParams(myURL.searchParams);\n// The above is equivalent to\n// const newSearchParams = new URLSearchParams(myURL.search);\n\nnewSearchParams.append('a', 'c');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\nconsole.log(newSearchParams.toString());\n// Prints a=b&a=c\n\n// newSearchParams.toString() is implicitly called\nmyURL.search = newSearchParams;\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\nnewSearchParams.delete('a');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\n
      ", + "methods": [ + { + "textRaw": "`urlSearchParams.append(name, value)`", + "type": "method", + "name": "append", + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {string}", + "name": "value", + "type": "string" + } + ] + } + ], + "desc": "

      Append a new name-value pair to the query string.

      " + }, + { + "textRaw": "`urlSearchParams.delete(name)`", + "type": "method", + "name": "delete", + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Remove all name-value pairs whose name is name.

      " + }, + { + "textRaw": "`urlSearchParams.entries()`", + "type": "method", + "name": "entries", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over each of the name-value pairs in the query.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name, the second item of the Array is the value.

      \n

      Alias for urlSearchParams[@@iterator]().

      " + }, + { + "textRaw": "`urlSearchParams.forEach(fn[, thisArg])`", + "type": "method", + "name": "forEach", + "signatures": [ + { + "params": [ + { + "textRaw": "`fn` {Function} Invoked for each name-value pair in the query", + "name": "fn", + "type": "Function", + "desc": "Invoked for each name-value pair in the query" + }, + { + "textRaw": "`thisArg` {Object} To be used as `this` value for when `fn` is called", + "name": "thisArg", + "type": "Object", + "desc": "To be used as `this` value for when `fn` is called" + } + ] + } + ], + "desc": "

      Iterates over each name-value pair in the query and invokes the given function.

      \n
      const myURL = new URL('https://example.org/?a=b&c=d');\nmyURL.searchParams.forEach((value, name, searchParams) => {\n  console.log(name, value, myURL.searchParams === searchParams);\n});\n// Prints:\n//   a b true\n//   c d true\n
      " + }, + { + "textRaw": "`urlSearchParams.get(name)`", + "type": "method", + "name": "get", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} or `null` if there is no name-value pair with the given `name`.", + "name": "return", + "type": "string", + "desc": "or `null` if there is no name-value pair with the given `name`." + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the value of the first name-value pair whose name is name. If there\nare no such pairs, null is returned.

      " + }, + { + "textRaw": "`urlSearchParams.getAll(name)`", + "type": "method", + "name": "getAll", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string[]}", + "name": "return", + "type": "string[]" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the values of all name-value pairs whose name is name. If there are\nno such pairs, an empty array is returned.

      " + }, + { + "textRaw": "`urlSearchParams.has(name)`", + "type": "method", + "name": "has", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + } + ] + } + ], + "desc": "

      Returns true if there is at least one name-value pair whose name is name.

      " + }, + { + "textRaw": "`urlSearchParams.keys()`", + "type": "method", + "name": "keys", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over the names of each name-value pair.

      \n
      const params = new URLSearchParams('foo=bar&foo=baz');\nfor (const name of params.keys()) {\n  console.log(name);\n}\n// Prints:\n//   foo\n//   foo\n
      " + }, + { + "textRaw": "`urlSearchParams.set(name, value)`", + "type": "method", + "name": "set", + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string}", + "name": "name", + "type": "string" + }, + { + "textRaw": "`value` {string}", + "name": "value", + "type": "string" + } + ] + } + ], + "desc": "

      Sets the value in the URLSearchParams object associated with name to\nvalue. If there are any pre-existing name-value pairs whose names are name,\nset the first such pair's value to value and remove all others. If not,\nappend the name-value pair to the query string.

      \n
      const params = new URLSearchParams();\nparams.append('foo', 'bar');\nparams.append('foo', 'baz');\nparams.append('abc', 'def');\nconsole.log(params.toString());\n// Prints foo=bar&foo=baz&abc=def\n\nparams.set('foo', 'def');\nparams.set('xyz', 'opq');\nconsole.log(params.toString());\n// Prints foo=def&abc=def&xyz=opq\n
      " + }, + { + "textRaw": "`urlSearchParams.sort()`", + "type": "method", + "name": "sort", + "meta": { + "added": [ + "v7.7.0", + "v6.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Sort all existing name-value pairs in-place by their names. Sorting is done\nwith a stable sorting algorithm, so relative order between name-value pairs\nwith the same name is preserved.

      \n

      This method can be used, in particular, to increase cache hits.

      \n
      const params = new URLSearchParams('query[]=abc&type=search&query[]=123');\nparams.sort();\nconsole.log(params.toString());\n// Prints query%5B%5D=abc&query%5B%5D=123&type=search\n
      " + }, + { + "textRaw": "`urlSearchParams.toString()`", + "type": "method", + "name": "toString", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [] + } + ], + "desc": "

      Returns the search parameters serialized as a string, with characters\npercent-encoded where necessary.

      " + }, + { + "textRaw": "`urlSearchParams.values()`", + "type": "method", + "name": "values", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over the values of each name-value pair.

      " + }, + { + "textRaw": "`urlSearchParams[Symbol.iterator]()`", + "type": "method", + "name": "[Symbol.iterator]", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Iterator}", + "name": "return", + "type": "Iterator" + }, + "params": [] + } + ], + "desc": "

      Returns an ES6 Iterator over each of the name-value pairs in the query string.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name, the second item of the Array is the value.

      \n

      Alias for urlSearchParams.entries().

      \n
      const params = new URLSearchParams('foo=bar&xyz=baz');\nfor (const [name, value] of params) {\n  console.log(name, value);\n}\n// Prints:\n//   foo bar\n//   xyz baz\n
      " + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Instantiate a new empty URLSearchParams object.

      " + }, + { + "params": [ + { + "textRaw": "`string` {string} A query string", + "name": "string", + "type": "string", + "desc": "A query string" + } + ], + "desc": "

      Parse the string as a query string, and use it to instantiate a new\nURLSearchParams object. A leading '?', if present, is ignored.

      \n
      let params;\n\nparams = new URLSearchParams('user=abc&query=xyz');\nconsole.log(params.get('user'));\n// Prints 'abc'\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\nparams = new URLSearchParams('?user=abc&query=xyz');\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n
      " + }, + { + "params": [ + { + "textRaw": "`obj` {Object} An object representing a collection of key-value pairs", + "name": "obj", + "type": "Object", + "desc": "An object representing a collection of key-value pairs" + } + ], + "desc": "

      Instantiate a new URLSearchParams object with a query hash map. The key and\nvalue of each property of obj are always coerced to strings.

      \n

      Unlike querystring module, duplicate keys in the form of array values are\nnot allowed. Arrays are stringified using array.toString(), which simply\njoins all array elements with commas.

      \n
      const params = new URLSearchParams({\n  user: 'abc',\n  query: ['first', 'second']\n});\nconsole.log(params.getAll('query'));\n// Prints [ 'first,second' ]\nconsole.log(params.toString());\n// Prints 'user=abc&query=first%2Csecond'\n
      " + }, + { + "params": [ + { + "textRaw": "`iterable` {Iterable} An iterable object whose elements are key-value pairs", + "name": "iterable", + "type": "Iterable", + "desc": "An iterable object whose elements are key-value pairs" + } + ], + "desc": "

      Instantiate a new URLSearchParams object with an iterable map in a way that\nis similar to Map's constructor. iterable can be an Array or any\niterable object. That means iterable can be another URLSearchParams, in\nwhich case the constructor will simply create a clone of the provided\nURLSearchParams. Elements of iterable are key-value pairs, and can\nthemselves be any iterable object.

      \n

      Duplicate keys are allowed.

      \n
      let params;\n\n// Using an array\nparams = new URLSearchParams([\n  ['user', 'abc'],\n  ['query', 'first'],\n  ['query', 'second']\n]);\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Using a Map object\nconst map = new Map();\nmap.set('user', 'abc');\nmap.set('query', 'xyz');\nparams = new URLSearchParams(map);\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\n// Using a generator function\nfunction* getQueryPairs() {\n  yield ['user', 'abc'];\n  yield ['query', 'first'];\n  yield ['query', 'second'];\n}\nparams = new URLSearchParams(getQueryPairs());\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Each key-value pair must have exactly two elements\nnew URLSearchParams([\n  ['user', 'abc', 'error']\n]);\n// Throws TypeError [ERR_INVALID_TUPLE]:\n//        Each query pair must be an iterable [name, value] tuple\n
      " + } + ] + } + ], + "methods": [ + { + "textRaw": "`url.domainToASCII(domain)`", + "type": "method", + "name": "domainToASCII", + "meta": { + "added": [ + "v7.4.0", + "v6.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the Punycode ASCII serialization of the domain. If domain is an\ninvalid domain, the empty string is returned.

      \n

      It performs the inverse operation to url.domainToUnicode().

      \n
      const url = require('url');\nconsole.log(url.domainToASCII('español.com'));\n// Prints xn--espaol-zwa.com\nconsole.log(url.domainToASCII('中文.com'));\n// Prints xn--fiq228c.com\nconsole.log(url.domainToASCII('xn--iñvalid.com'));\n// Prints an empty string\n
      " + }, + { + "textRaw": "`url.domainToUnicode(domain)`", + "type": "method", + "name": "domainToUnicode", + "meta": { + "added": [ + "v7.4.0", + "v6.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`domain` {string}", + "name": "domain", + "type": "string" + } + ] + } + ], + "desc": "

      Returns the Unicode serialization of the domain. If domain is an invalid\ndomain, the empty string is returned.

      \n

      It performs the inverse operation to url.domainToASCII().

      \n
      const url = require('url');\nconsole.log(url.domainToUnicode('xn--espaol-zwa.com'));\n// Prints español.com\nconsole.log(url.domainToUnicode('xn--fiq228c.com'));\n// Prints 中文.com\nconsole.log(url.domainToUnicode('xn--iñvalid.com'));\n// Prints an empty string\n
      " + }, + { + "textRaw": "`url.fileURLToPath(url)`", + "type": "method", + "name": "fileURLToPath", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The fully-resolved platform-specific Node.js file path.", + "name": "return", + "type": "string", + "desc": "The fully-resolved platform-specific Node.js file path." + }, + "params": [ + { + "textRaw": "`url` {URL | string} The file URL string or URL object to convert to a path.", + "name": "url", + "type": "URL | string", + "desc": "The file URL string or URL object to convert to a path." + } + ] + } + ], + "desc": "

      This function ensures the correct decodings of percent-encoded characters as\nwell as ensuring a cross-platform valid absolute path string.

      \n
      new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/\nfileURLToPath('file:///C:/path/');       // Correct:   C:\\path\\ (Windows)\n\nnew URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt\nfileURLToPath('file://nas/foo.txt');     // Correct:   \\\\nas\\foo.txt (Windows)\n\nnew URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt\nfileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)\n\nnew URL('file:///hello world').pathname; // Incorrect: /hello%20world\nfileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)\n
      " + }, + { + "textRaw": "`url.format(URL[, options])`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v7.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`URL` {URL} A [WHATWG URL][] object", + "name": "URL", + "type": "URL", + "desc": "A [WHATWG URL][] object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`auth` {boolean} `true` if the serialized URL string should include the username and password, `false` otherwise. **Default:** `true`.", + "name": "auth", + "type": "boolean", + "default": "`true`", + "desc": "`true` if the serialized URL string should include the username and password, `false` otherwise." + }, + { + "textRaw": "`fragment` {boolean} `true` if the serialized URL string should include the fragment, `false` otherwise. **Default:** `true`.", + "name": "fragment", + "type": "boolean", + "default": "`true`", + "desc": "`true` if the serialized URL string should include the fragment, `false` otherwise." + }, + { + "textRaw": "`search` {boolean} `true` if the serialized URL string should include the search query, `false` otherwise. **Default:** `true`.", + "name": "search", + "type": "boolean", + "default": "`true`", + "desc": "`true` if the serialized URL string should include the search query, `false` otherwise." + }, + { + "textRaw": "`unicode` {boolean} `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded. **Default:** `false`.", + "name": "unicode", + "type": "boolean", + "default": "`false`", + "desc": "`true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded." + } + ] + } + ] + } + ], + "desc": "

      Returns a customizable serialization of a URL String representation of a\nWHATWG URL object.

      \n

      The URL object has both a toString() method and href property that return\nstring serializations of the URL. These are not, however, customizable in\nany way. The url.format(URL[, options]) method allows for basic customization\nof the output.

      \n
      const myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(myURL.href);\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(myURL.toString());\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));\n// Prints 'https://測試/?abc'\n
      " + }, + { + "textRaw": "`url.pathToFileURL(path)`", + "type": "method", + "name": "pathToFileURL", + "meta": { + "added": [ + "v10.12.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {URL} The file URL object.", + "name": "return", + "type": "URL", + "desc": "The file URL object." + }, + "params": [ + { + "textRaw": "`path` {string} The path to convert to a File URL.", + "name": "path", + "type": "string", + "desc": "The path to convert to a File URL." + } + ] + } + ], + "desc": "

      This function ensures that path is resolved absolutely, and that the URL\ncontrol characters are correctly encoded when converting into a File URL.

      \n
      new URL(__filename);                // Incorrect: throws (POSIX)\nnew URL(__filename);                // Incorrect: C:\\... (Windows)\npathToFileURL(__filename);          // Correct:   file:///... (POSIX)\npathToFileURL(__filename);          // Correct:   file:///C:/... (Windows)\n\nnew URL('/foo#1', 'file:');         // Incorrect: file:///foo#1\npathToFileURL('/foo#1');            // Correct:   file:///foo%231 (POSIX)\n\nnew URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c\npathToFileURL('/some/path%.c');    // Correct:   file:///some/path%25.c (POSIX)\n
      " + } + ], + "type": "module", + "displayName": "The WHATWG URL API" + }, + { + "textRaw": "Legacy URL API", + "name": "legacy_url_api", + "meta": { + "deprecated": [ + "v11.0.0" + ], + "changes": [] + }, + "modules": [ + { + "textRaw": "Legacy `urlObject`", + "name": "legacy_`urlobject`", + "meta": { + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "desc": "

      The legacy urlObject (require('url').Url) is created and returned by the\nurl.parse() function.

      ", + "properties": [ + { + "textRaw": "`urlObject.auth`", + "name": "auth", + "desc": "

      The auth property is the username and password portion of the URL, also\nreferred to as userinfo. This string subset follows the protocol and\ndouble slashes (if present) and precedes the host component, delimited by @.\nThe string is either the username, or it is the username and password separated\nby :.

      \n

      For example: 'user:pass'.

      " + }, + { + "textRaw": "`urlObject.hash`", + "name": "hash", + "desc": "

      The hash property is the fragment identifier portion of the URL including the\nleading # character.

      \n

      For example: '#hash'.

      " + }, + { + "textRaw": "`urlObject.host`", + "name": "host", + "desc": "

      The host property is the full lower-cased host portion of the URL, including\nthe port if specified.

      \n

      For example: 'sub.example.com:8080'.

      " + }, + { + "textRaw": "`urlObject.hostname`", + "name": "hostname", + "desc": "

      The hostname property is the lower-cased host name portion of the host\ncomponent without the port included.

      \n

      For example: 'sub.example.com'.

      " + }, + { + "textRaw": "`urlObject.href`", + "name": "href", + "desc": "

      The href property is the full URL string that was parsed with both the\nprotocol and host components converted to lower-case.

      \n

      For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.

      " + }, + { + "textRaw": "`urlObject.path`", + "name": "path", + "desc": "

      The path property is a concatenation of the pathname and search\ncomponents.

      \n

      For example: '/p/a/t/h?query=string'.

      \n

      No decoding of the path is performed.

      " + }, + { + "textRaw": "`urlObject.pathname`", + "name": "pathname", + "desc": "

      The pathname property consists of the entire path section of the URL. This\nis everything following the host (including the port) and before the start\nof the query or hash components, delimited by either the ASCII question\nmark (?) or hash (#) characters.

      \n

      For example: '/p/a/t/h'.

      \n

      No decoding of the path string is performed.

      " + }, + { + "textRaw": "`urlObject.port`", + "name": "port", + "desc": "

      The port property is the numeric port portion of the host component.

      \n

      For example: '8080'.

      " + }, + { + "textRaw": "`urlObject.protocol`", + "name": "protocol", + "desc": "

      The protocol property identifies the URL's lower-cased protocol scheme.

      \n

      For example: 'http:'.

      " + }, + { + "textRaw": "`urlObject.query`", + "name": "query", + "desc": "

      The query property is either the query string without the leading ASCII\nquestion mark (?), or an object returned by the querystring module's\nparse() method. Whether the query property is a string or object is\ndetermined by the parseQueryString argument passed to url.parse().

      \n

      For example: 'query=string' or {'query': 'string'}.

      \n

      If returned as a string, no decoding of the query string is performed. If\nreturned as an object, both keys and values are decoded.

      " + }, + { + "textRaw": "`urlObject.search`", + "name": "search", + "desc": "

      The search property consists of the entire \"query string\" portion of the\nURL, including the leading ASCII question mark (?) character.

      \n

      For example: '?query=string'.

      \n

      No decoding of the query string is performed.

      " + }, + { + "textRaw": "`urlObject.slashes`", + "name": "slashes", + "desc": "

      The slashes property is a boolean with a value of true if two ASCII\nforward-slash characters (/) are required following the colon in the\nprotocol.

      " + } + ], + "type": "module", + "displayName": "Legacy `urlObject`" + } + ], + "methods": [ + { + "textRaw": "`url.format(urlObject)`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + }, + { + "version": "v7.0.0", + "pr-url": "https://github.com/nodejs/node/pull/7234", + "description": "URLs with a `file:` scheme will now always use the correct number of slashes regardless of `slashes` option. A falsy `slashes` option with no protocol is now also respected at all times." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`urlObject` {Object|string} A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`.", + "name": "urlObject", + "type": "Object|string", + "desc": "A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`." + } + ] + } + ], + "desc": "

      The url.format() method returns a formatted URL string derived from\nurlObject.

      \n
      url.format({\n  protocol: 'https',\n  hostname: 'example.com',\n  pathname: '/some/path',\n  query: {\n    page: 1,\n    format: 'json'\n  }\n});\n\n// => 'https://example.com/some/path?page=1&format=json'\n
      \n

      If urlObject is not an object or a string, url.format() will throw a\nTypeError.

      \n

      The formatting process operates as follows:

      \n
        \n
      • A new empty string result is created.
      • \n
      • If urlObject.protocol is a string, it is appended as-is to result.
      • \n
      • Otherwise, if urlObject.protocol is not undefined and is not a string, an\nError is thrown.
      • \n
      • For all string values of urlObject.protocol that do not end with an ASCII\ncolon (:) character, the literal string : will be appended to result.
      • \n
      • If either of the following conditions is true, then the literal string //\nwill be appended to result:\n
          \n
        • urlObject.slashes property is true;
        • \n
        • urlObject.protocol begins with http, https, ftp, gopher, or\nfile;
        • \n
        \n
      • \n
      • If the value of the urlObject.auth property is truthy, and either\nurlObject.host or urlObject.hostname are not undefined, the value of\nurlObject.auth will be coerced into a string and appended to result\nfollowed by the literal string @.
      • \n
      • If the urlObject.host property is undefined then:\n
          \n
        • If the urlObject.hostname is a string, it is appended to result.
        • \n
        • Otherwise, if urlObject.hostname is not undefined and is not a string,\nan Error is thrown.
        • \n
        • If the urlObject.port property value is truthy, and urlObject.hostname\nis not undefined:\n
            \n
          • The literal string : is appended to result, and
          • \n
          • The value of urlObject.port is coerced to a string and appended to\nresult.
          • \n
          \n
        • \n
        \n
      • \n
      • Otherwise, if the urlObject.host property value is truthy, the value of\nurlObject.host is coerced to a string and appended to result.
      • \n
      • If the urlObject.pathname property is a string that is not an empty string:\n
          \n
        • If the urlObject.pathname does not start with an ASCII forward slash\n(/), then the literal string '/' is appended to result.
        • \n
        • The value of urlObject.pathname is appended to result.
        • \n
        \n
      • \n
      • Otherwise, if urlObject.pathname is not undefined and is not a string, an\nError is thrown.
      • \n
      • If the urlObject.search property is undefined and if the urlObject.query\nproperty is an Object, the literal string ? is appended to result\nfollowed by the output of calling the querystring module's stringify()\nmethod passing the value of urlObject.query.
      • \n
      • Otherwise, if urlObject.search is a string:\n
          \n
        • If the value of urlObject.search does not start with the ASCII question\nmark (?) character, the literal string ? is appended to result.
        • \n
        • The value of urlObject.search is appended to result.
        • \n
        \n
      • \n
      • Otherwise, if urlObject.search is not undefined and is not a string, an\nError is thrown.
      • \n
      • If the urlObject.hash property is a string:\n
          \n
        • If the value of urlObject.hash does not start with the ASCII hash (#)\ncharacter, the literal string # is appended to result.
        • \n
        • The value of urlObject.hash is appended to result.
        • \n
        \n
      • \n
      • Otherwise, if the urlObject.hash property is not undefined and is not a\nstring, an Error is thrown.
      • \n
      • result is returned.
      • \n
      " + }, + { + "textRaw": "`url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`", + "type": "method", + "name": "parse", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v11.14.0", + "pr-url": "https://github.com/nodejs/node/pull/26941", + "description": "The `pathname` property on the returned URL object is now `/` when there is no path and the protocol scheme is `ws:` or `wss:`." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + }, + { + "version": "v9.0.0", + "pr-url": "https://github.com/nodejs/node/pull/13606", + "description": "The `search` property on the returned URL object is now `null` when no query string is present." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`urlString` {string} The URL string to parse.", + "name": "urlString", + "type": "string", + "desc": "The URL string to parse." + }, + { + "textRaw": "`parseQueryString` {boolean} If `true`, the `query` property will always be set to an object returned by the [`querystring`][] module's `parse()` method. If `false`, the `query` property on the returned URL object will be an unparsed, undecoded string. **Default:** `false`.", + "name": "parseQueryString", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the `query` property will always be set to an object returned by the [`querystring`][] module's `parse()` method. If `false`, the `query` property on the returned URL object will be an unparsed, undecoded string." + }, + { + "textRaw": "`slashesDenoteHost` {boolean} If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. **Default:** `false`.", + "name": "slashesDenoteHost", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`." + } + ] + } + ], + "desc": "

      The url.parse() method takes a URL string, parses it, and returns a URL\nobject.

      \n

      A TypeError is thrown if urlString is not a string.

      \n

      A URIError is thrown if the auth property is present but cannot be decoded.

      \n

      Use of the legacy url.parse() method is discouraged. Users should\nuse the WHATWG URL API. Because the url.parse() method uses a\nlenient, non-standard algorithm for parsing URL strings, security\nissues can be introduced. Specifically, issues with host name spoofing and\nincorrect handling of usernames and passwords have been identified.

      " + }, + { + "textRaw": "`url.resolve(from, to)`", + "type": "method", + "name": "resolve", + "meta": { + "added": [ + "v0.1.25" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22715", + "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8215", + "description": "The `auth` fields are now kept intact when `from` and `to` refer to the same host." + }, + { + "version": "v6.5.0, v4.6.2", + "pr-url": "https://github.com/nodejs/node/pull/8214", + "description": "The `port` field is copied correctly now." + }, + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/1480", + "description": "The `auth` fields is cleared now the `to` parameter contains a hostname." + } + ] + }, + "stability": 0, + "stabilityText": "Deprecated: Use the WHATWG URL API instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`from` {string} The Base URL being resolved against.", + "name": "from", + "type": "string", + "desc": "The Base URL being resolved against." + }, + { + "textRaw": "`to` {string} The HREF URL being resolved.", + "name": "to", + "type": "string", + "desc": "The HREF URL being resolved." + } + ] + } + ], + "desc": "

      The url.resolve() method resolves a target URL relative to a base URL in a\nmanner similar to that of a Web browser resolving an anchor tag HREF.

      \n
      const url = require('url');\nurl.resolve('/one/two/three', 'four');         // '/one/two/four'\nurl.resolve('http://example.com/', '/one');    // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two'); // 'http://example.com/two'\n
      \n

      " + } + ], + "type": "module", + "displayName": "Legacy URL API" + }, + { + "textRaw": "Percent-encoding in URLs", + "name": "percent-encoding_in_urls", + "desc": "

      URLs are permitted to only contain a certain range of characters. Any character\nfalling outside of that range must be encoded. How such characters are encoded,\nand which characters to encode depends entirely on where the character is\nlocated within the structure of the URL.

      ", + "modules": [ + { + "textRaw": "Legacy API", + "name": "legacy_api", + "desc": "

      Within the Legacy API, spaces (' ') and the following characters will be\nautomatically escaped in the properties of URL objects:

      \n
      < > \" ` \\r \\n \\t { } | \\ ^ '\n
      \n

      For example, the ASCII space character (' ') is encoded as %20. The ASCII\nforward slash (/) character is encoded as %3C.

      ", + "type": "module", + "displayName": "Legacy API" + }, + { + "textRaw": "WHATWG API", + "name": "whatwg_api", + "desc": "

      The WHATWG URL Standard uses a more selective and fine grained approach to\nselecting encoded characters than that used by the Legacy API.

      \n

      The WHATWG algorithm defines four \"percent-encode sets\" that describe ranges\nof characters that must be percent-encoded:

      \n
        \n
      • \n

        The C0 control percent-encode set includes code points in range U+0000 to\nU+001F (inclusive) and all code points greater than U+007E.

        \n
      • \n
      • \n

        The fragment percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+003C, U+003E, and U+0060.

        \n
      • \n
      • \n

        The path percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060,\nU+007B, and U+007D.

        \n
      • \n
      • \n

        The userinfo encode set includes the path percent-encode set and code\npoints U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D,\nU+005E, and U+007C.

        \n
      • \n
      \n

      The userinfo percent-encode set is used exclusively for username and\npasswords encoded within the URL. The path percent-encode set is used for the\npath of most URLs. The fragment percent-encode set is used for URL fragments.\nThe C0 control percent-encode set is used for host and path under certain\nspecific conditions, in addition to all other cases.

      \n

      When non-ASCII characters appear within a host name, the host name is encoded\nusing the Punycode algorithm. Note, however, that a host name may contain\nboth Punycode encoded and percent-encoded characters:

      \n
      const myURL = new URL('https://%CF%80.example.com/foo');\nconsole.log(myURL.href);\n// Prints https://xn--1xa.example.com/foo\nconsole.log(myURL.origin);\n// Prints https://xn--1xa.example.com\n
      ", + "type": "module", + "displayName": "WHATWG API" + } + ], + "type": "module", + "displayName": "Percent-encoding in URLs" + } + ], + "type": "module", + "displayName": "URL" + } + ] +} \ No newline at end of file diff --git a/doc/api/util.html b/doc/api/util.html new file mode 100644 index 0000000000000000000000000000000000000000..1720ee3a512654db17e369e971d2abc85bebbe4f --- /dev/null +++ b/doc/api/util.html @@ -0,0 +1,2316 @@ + + + + + + + Util | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + +
      +

      Table of Contents

      + +
      + +
      +

      Util#

      + +

      Stability: 2 - Stable

      +

      Source Code: lib/util.js

      +

      The util module supports the needs of Node.js internal APIs. Many of the +utilities are useful for application and module developers as well. To access +it:

      +
      const util = require('util');
      +

      util.callbackify(original)#

      + + +

      Takes an async function (or a function that returns a Promise) and returns a +function following the error-first callback style, i.e. taking +an (err, value) => ... callback as the last argument. In the callback, the +first argument will be the rejection reason (or null if the Promise +resolved), and the second argument will be the resolved value.

      +
      const util = require('util');
      +
      +async function fn() {
      +  return 'hello world';
      +}
      +const callbackFunction = util.callbackify(fn);
      +
      +callbackFunction((err, ret) => {
      +  if (err) throw err;
      +  console.log(ret);
      +});
      +

      Will print:

      +
      hello world
      +

      The callback is executed asynchronously, and will have a limited stack trace. +If the callback throws, the process will emit an 'uncaughtException' +event, and if not handled will exit.

      +

      Since null has a special meaning as the first argument to a callback, if a +wrapped function rejects a Promise with a falsy value as a reason, the value +is wrapped in an Error with the original value stored in a field named +reason.

      +
      function fn() {
      +  return Promise.reject(null);
      +}
      +const callbackFunction = util.callbackify(fn);
      +
      +callbackFunction((err, ret) => {
      +  // When the Promise was rejected with `null` it is wrapped with an Error and
      +  // the original value is stored in `reason`.
      +  err && err.hasOwnProperty('reason') && err.reason === null;  // true
      +});
      +

      util.debuglog(section[, callback])#

      + +
        +
      • section <string> A string identifying the portion of the application for +which the debuglog function is being created.
      • +
      • callback <Function> A callback invoked the first time the logging function +is called with a function argument that is a more optimized logging function.
      • +
      • Returns: <Function> The logging function
      • +
      +

      The util.debuglog() method is used to create a function that conditionally +writes debug messages to stderr based on the existence of the NODE_DEBUG +environment variable. If the section name appears within the value of that +environment variable, then the returned function operates similar to +console.error(). If not, then the returned function is a no-op.

      +
      const util = require('util');
      +const debuglog = util.debuglog('foo');
      +
      +debuglog('hello from foo [%d]', 123);
      +

      If this program is run with NODE_DEBUG=foo in the environment, then +it will output something like:

      +
      FOO 3245: hello from foo [123]
      +

      where 3245 is the process id. If it is not run with that +environment variable set, then it will not print anything.

      +

      The section supports wildcard also:

      +
      const util = require('util');
      +const debuglog = util.debuglog('foo-bar');
      +
      +debuglog('hi there, it\'s foo-bar [%d]', 2333);
      +

      if it is run with NODE_DEBUG=foo* in the environment, then it will output +something like:

      +
      FOO-BAR 3257: hi there, it's foo-bar [2333]
      +

      Multiple comma-separated section names may be specified in the NODE_DEBUG +environment variable: NODE_DEBUG=fs,net,tls.

      +

      The optional callback argument can be used to replace the logging function +with a different function that doesn't have any initialization or +unnecessary wrapping.

      +
      const util = require('util');
      +let debuglog = util.debuglog('internals', (debug) => {
      +  // Replace with a logging function that optimizes out
      +  // testing if the section is enabled
      +  debuglog = debug;
      +});
      +

      util.deprecate(fn, msg[, code])#

      + +
        +
      • fn <Function> The function that is being deprecated.
      • +
      • msg <string> A warning message to display when the deprecated function is +invoked.
      • +
      • code <string> A deprecation code. See the list of deprecated APIs for a +list of codes.
      • +
      • Returns: <Function> The deprecated function wrapped to emit a warning.
      • +
      +

      The util.deprecate() method wraps fn (which may be a function or class) in +such a way that it is marked as deprecated.

      +
      const util = require('util');
      +
      +exports.obsoleteFunction = util.deprecate(() => {
      +  // Do something here.
      +}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
      +

      When called, util.deprecate() will return a function that will emit a +DeprecationWarning using the 'warning' event. The warning will +be emitted and printed to stderr the first time the returned function is +called. After the warning is emitted, the wrapped function is called without +emitting a warning.

      +

      If the same optional code is supplied in multiple calls to util.deprecate(), +the warning will be emitted only once for that code.

      +
      const util = require('util');
      +
      +const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
      +const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
      +fn1(); // Emits a deprecation warning with code DEP0001
      +fn2(); // Does not emit a deprecation warning because it has the same code
      +

      If either the --no-deprecation or --no-warnings command line flags are +used, or if the process.noDeprecation property is set to true prior to +the first deprecation warning, the util.deprecate() method does nothing.

      +

      If the --trace-deprecation or --trace-warnings command line flags are set, +or the process.traceDeprecation property is set to true, a warning and a +stack trace are printed to stderr the first time the deprecated function is +called.

      +

      If the --throw-deprecation command line flag is set, or the +process.throwDeprecation property is set to true, then an exception will be +thrown when the deprecated function is called.

      +

      The --throw-deprecation command line flag and process.throwDeprecation +property take precedence over --trace-deprecation and +process.traceDeprecation.

      +

      util.format(format[, ...args])#

      + +
        +
      • format <string> A printf-like format string.
      • +
      +

      The util.format() method returns a formatted string using the first argument +as a printf-like format string which can contain zero or more format +specifiers. Each specifier is replaced with the converted value from the +corresponding argument. Supported specifiers are:

      +
        +
      • %s: String will be used to convert all values except BigInt, Object +and -0. BigInt values will be represented with an n and Objects that +have no user defined toString function are inspected using util.inspect() +with options { depth: 0, colors: false, compact: 3 }.
      • +
      • %d: Number will be used to convert all values except BigInt and +Symbol.
      • +
      • %i: parseInt(value, 10) is used for all values except BigInt and +Symbol.
      • +
      • %f: parseFloat(value) is used for all values expect Symbol.
      • +
      • %j: JSON. Replaced with the string '[Circular]' if the argument contains +circular references.
      • +
      • %o: Object. A string representation of an object with generic JavaScript +object formatting. Similar to util.inspect() with options +{ showHidden: true, showProxy: true }. This will show the full object +including non-enumerable properties and proxies.
      • +
      • %O: Object. A string representation of an object with generic JavaScript +object formatting. Similar to util.inspect() without options. This will show +the full object not including non-enumerable properties and proxies.
      • +
      • %c: CSS. This specifier is ignored and will skip any CSS passed in.
      • +
      • %%: single percent sign ('%'). This does not consume an argument.
      • +
      • Returns: <string> The formatted string
      • +
      +

      If a specifier does not have a corresponding argument, it is not replaced:

      +
      util.format('%s:%s', 'foo');
      +// Returns: 'foo:%s'
      +

      Values that are not part of the format string are formatted using +util.inspect() if their type is not string.

      +

      If there are more arguments passed to the util.format() method than the +number of specifiers, the extra arguments are concatenated to the returned +string, separated by spaces:

      +
      util.format('%s:%s', 'foo', 'bar', 'baz');
      +// Returns: 'foo:bar baz'
      +

      If the first argument does not contain a valid format specifier, util.format() +returns a string that is the concatenation of all arguments separated by spaces:

      +
      util.format(1, 2, 3);
      +// Returns: '1 2 3'
      +

      If only one argument is passed to util.format(), it is returned as it is +without any formatting:

      +
      util.format('%% %s');
      +// Returns: '%% %s'
      +

      util.format() is a synchronous method that is intended as a debugging tool. +Some input values can have a significant performance overhead that can block the +event loop. Use this function with care and never in a hot code path.

      +

      util.formatWithOptions(inspectOptions, format[, ...args])#

      + + +

      This function is identical to util.format(), except in that it takes +an inspectOptions argument which specifies options that are passed along to +util.inspect().

      +
      util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
      +// Returns 'See object { foo: 42 }', where `42` is colored as a number
      +// when printed to a terminal.
      +

      util.getSystemErrorName(err)#

      + + +

      Returns the string name for a numeric error code that comes from a Node.js API. +The mapping between error codes and error names is platform-dependent. +See Common System Errors for the names of common errors.

      +
      fs.access('file/that/does/not/exist', (err) => {
      +  const name = util.getSystemErrorName(err.errno);
      +  console.error(name);  // ENOENT
      +});
      +

      util.inherits(constructor, superConstructor)#

      + + +

      Usage of util.inherits() is discouraged. Please use the ES6 class and +extends keywords to get language level inheritance support. Also note +that the two styles are semantically incompatible.

      +

      Inherit the prototype methods from one constructor into another. The +prototype of constructor will be set to a new object created from +superConstructor.

      +

      This mainly adds some input validation on top of +Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). +As an additional convenience, superConstructor will be accessible +through the constructor.super_ property.

      +
      const util = require('util');
      +const EventEmitter = require('events');
      +
      +function MyStream() {
      +  EventEmitter.call(this);
      +}
      +
      +util.inherits(MyStream, EventEmitter);
      +
      +MyStream.prototype.write = function(data) {
      +  this.emit('data', data);
      +};
      +
      +const stream = new MyStream();
      +
      +console.log(stream instanceof EventEmitter); // true
      +console.log(MyStream.super_ === EventEmitter); // true
      +
      +stream.on('data', (data) => {
      +  console.log(`Received data: "${data}"`);
      +});
      +stream.write('It works!'); // Received data: "It works!"
      +

      ES6 example using class and extends:

      +
      const EventEmitter = require('events');
      +
      +class MyStream extends EventEmitter {
      +  write(data) {
      +    this.emit('data', data);
      +  }
      +}
      +
      +const stream = new MyStream();
      +
      +stream.on('data', (data) => {
      +  console.log(`Received data: "${data}"`);
      +});
      +stream.write('With ES6');
      +

      util.inspect(object[, options])#

      +

      util.inspect(object[, showHidden[, depth[, colors]]])#

      + +
        +
      • object <any> Any JavaScript primitive or Object.
      • +
      • options <Object> +
          +
        • showHidden <boolean> If true, object's non-enumerable symbols and +properties are included in the formatted result. WeakMap and +WeakSet entries are also included as well as user defined prototype +properties (excluding method properties). Default: false.
        • +
        • depth <number> Specifies the number of times to recurse while formatting +object. This is useful for inspecting large objects. To recurse up to +the maximum call stack size pass Infinity or null. +Default: 2.
        • +
        • colors <boolean> If true, the output is styled with ANSI color +codes. Colors are customizable. See Customizing util.inspect colors. +Default: false.
        • +
        • customInspect <boolean> If false, +[util.inspect.custom](depth, opts) functions are not invoked. +Default: true.
        • +
        • showProxy <boolean> If true, Proxy inspection includes +the target and handler objects. Default: false.
        • +
        • maxArrayLength <integer> Specifies the maximum number of Array, +TypedArray, WeakMap and WeakSet elements to include when +formatting. Set to null or Infinity to show all elements. Set to 0 or +negative to show no elements. Default: 100.
        • +
        • maxStringLength <integer> Specifies the maximum number of characters to +include when formatting. Set to null or Infinity to show all elements. +Set to 0 or negative to show no characters. Default: Infinity.
        • +
        • breakLength <integer> The length at which input values are split across +multiple lines. Set to Infinity to format the input as a single line +(in combination with compact set to true or any number >= 1). +Default: 80.
        • +
        • compact <boolean> | <integer> Setting this to false causes each object key +to be displayed on a new line. It will also add new lines to text that is +longer than breakLength. If set to a number, the most n inner elements +are united on a single line as long as all properties fit into +breakLength. Short array elements are also grouped together. No +text will be reduced below 16 characters, no matter the breakLength size. +For more information, see the example below. Default: 3.
        • +
        • sorted <boolean> | <Function> If set to true or a function, all properties +of an object, and Set and Map entries are sorted in the resulting +string. If set to true the default sort is used. If set to a function, +it is used as a compare function.
        • +
        • getters <boolean> | <string> If set to true, getters are inspected. If set +to 'get', only getters without a corresponding setter are inspected. If +set to 'set', only getters with a corresponding setter are inspected. +This might cause side effects depending on the getter function. +Default: false.
        • +
        +
      • +
      • Returns: <string> The representation of object.
      • +
      +

      The util.inspect() method returns a string representation of object that is +intended for debugging. The output of util.inspect may change at any time +and should not be depended upon programmatically. Additional options may be +passed that alter the result. +util.inspect() will use the constructor's name and/or @@toStringTag to make +an identifiable tag for an inspected value.

      +
      class Foo {
      +  get [Symbol.toStringTag]() {
      +    return 'bar';
      +  }
      +}
      +
      +class Bar {}
      +
      +const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
      +
      +util.inspect(new Foo()); // 'Foo [bar] {}'
      +util.inspect(new Bar()); // 'Bar {}'
      +util.inspect(baz);       // '[foo] {}'
      +

      Circular references are marked as '[Circular]':

      +
      const { inspect } = require('util');
      +
      +const obj = {};
      +obj.a = [obj];
      +obj.b = {};
      +obj.b.inner = obj.b;
      +obj.b.obj = obj;
      +
      +console.log(inspect(obj));
      +// {
      +//   a: [ [Circular] ],
      +//   b: { inner: [Circular], obj: [Circular] }
      +// }
      +

      The following example inspects all properties of the util object:

      +
      const util = require('util');
      +
      +console.log(util.inspect(util, { showHidden: true, depth: null }));
      +

      The following example highlights the effect of the compact option:

      +
      const util = require('util');
      +
      +const o = {
      +  a: [1, 2, [[
      +    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      +      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
      +    'test',
      +    'foo']], 4],
      +  b: new Map([['za', 1], ['zb', 'test']])
      +};
      +console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
      +
      +// { a:
      +//   [ 1,
      +//     2,
      +//     [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line
      +//           'test',
      +//           'foo' ] ],
      +//     4 ],
      +//   b: Map { 'za' => 1, 'zb' => 'test' } }
      +
      +// Setting `compact` to false changes the output to be more reader friendly.
      +console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
      +
      +// {
      +//   a: [
      +//     1,
      +//     2,
      +//     [
      +//       [
      +//         'Lorem ipsum dolor sit amet, consectetur ' +
      +//           'adipiscing elit, sed do eiusmod tempor ' +
      +//           'incididunt ut labore et dolore magna ' +
      +//           'aliqua.,
      +//         'test',
      +//         'foo'
      +//       ]
      +//     ],
      +//     4
      +//   ],
      +//   b: Map {
      +//     'za' => 1,
      +//     'zb' => 'test'
      +//   }
      +// }
      +
      +// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
      +// single line.
      +// Reducing the `breakLength` will split the "Lorem ipsum" text in smaller
      +// chunks.
      +

      The showHidden option allows WeakMap and WeakSet entries to be +inspected. If there are more entries than maxArrayLength, there is no +guarantee which entries are displayed. That means retrieving the same +WeakSet entries twice may result in different output. Furthermore, entries +with no remaining strong references may be garbage collected at any time.

      +
      const { inspect } = require('util');
      +
      +const obj = { a: 1 };
      +const obj2 = { b: 2 };
      +const weakSet = new WeakSet([obj, obj2]);
      +
      +console.log(inspect(weakSet, { showHidden: true }));
      +// WeakSet { { a: 1 }, { b: 2 } }
      +

      The sorted option ensures that an object's property insertion order does not +impact the result of util.inspect().

      +
      const { inspect } = require('util');
      +const assert = require('assert');
      +
      +const o1 = {
      +  b: [2, 3, 1],
      +  a: '`a` comes before `b`',
      +  c: new Set([2, 3, 1])
      +};
      +console.log(inspect(o1, { sorted: true }));
      +// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }
      +console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
      +// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
      +
      +const o2 = {
      +  c: new Set([2, 1, 3]),
      +  a: '`a` comes before `b`',
      +  b: [2, 3, 1]
      +};
      +assert.strict.equal(
      +  inspect(o1, { sorted: true }),
      +  inspect(o2, { sorted: true })
      +);
      +

      util.inspect() is a synchronous method intended for debugging. Its maximum +output length is approximately 128 MB. Inputs that result in longer output will +be truncated.

      +

      Customizing util.inspect colors#

      + +

      Color output (if enabled) of util.inspect is customizable globally +via the util.inspect.styles and util.inspect.colors properties.

      +

      util.inspect.styles is a map associating a style name to a color from +util.inspect.colors.

      +

      The default styles and associated colors are:

      +
        +
      • bigint: yellow
      • +
      • boolean: yellow
      • +
      • date: magenta
      • +
      • module: underline
      • +
      • name: (no styling)
      • +
      • null: bold
      • +
      • number: yellow
      • +
      • regexp: red
      • +
      • special: cyan (e.g., Proxies)
      • +
      • string: green
      • +
      • symbol: green
      • +
      • undefined: grey
      • +
      +

      Color styling uses ANSI control codes that may not be supported on all +terminals. To verify color support use tty.hasColors().

      +

      Predefined control codes are listed below (grouped as "Modifiers", "Foreground +colors", and "Background colors").

      +

      Modifiers#

      +

      Modifier support varies throughout different terminals. They will mostly be +ignored, if not supported.

      +
        +
      • reset - Resets all (color) modifiers to their defaults
      • +
      • bold - Make text bold
      • +
      • italic - Make text italic
      • +
      • underline - Make text underlined
      • +
      • strikethrough - Puts a horizontal line through the center of the text +(Alias: strikeThrough, crossedout, crossedOut)
      • +
      • hidden - Prints the text, but makes it invisible (Alias: conceal)
      • +
      • dim - Decreased color intensity (Alias: +faint)
      • +
      • overlined - Make text overlined
      • +
      • blink - Hides and shows the text in an interval
      • +
      • inverse - Swap foreground and +background colors (Alias: swapcolors, swapColors)
      • +
      • doubleunderline - Make text +double underlined (Alias: doubleUnderline)
      • +
      • framed - Draw a frame around the text
      • +
      +

      Foreground colors#

      +
        +
      • black
      • +
      • red
      • +
      • green
      • +
      • yellow
      • +
      • blue
      • +
      • magenta
      • +
      • cyan
      • +
      • white
      • +
      • gray (alias: grey, blackBright)
      • +
      • redBright
      • +
      • greenBright
      • +
      • yellowBright
      • +
      • blueBright
      • +
      • magentaBright
      • +
      • cyanBright
      • +
      • whiteBright
      • +
      +

      Background colors#

      +
        +
      • bgBlack
      • +
      • bgRed
      • +
      • bgGreen
      • +
      • bgYellow
      • +
      • bgBlue
      • +
      • bgMagenta
      • +
      • bgCyan
      • +
      • bgWhite
      • +
      • bgGray (alias: bgGrey, bgBlackBright)
      • +
      • bgRedBright
      • +
      • bgGreenBright
      • +
      • bgYellowBright
      • +
      • bgBlueBright
      • +
      • bgMagentaBright
      • +
      • bgCyanBright
      • +
      • bgWhiteBright
      • +
      +

      Custom inspection functions on objects#

      + +

      Objects may also define their own +[util.inspect.custom](depth, opts) function, +which util.inspect() will invoke and use the result of when inspecting +the object:

      +
      const util = require('util');
      +
      +class Box {
      +  constructor(value) {
      +    this.value = value;
      +  }
      +
      +  [util.inspect.custom](depth, options) {
      +    if (depth < 0) {
      +      return options.stylize('[Box]', 'special');
      +    }
      +
      +    const newOptions = Object.assign({}, options, {
      +      depth: options.depth === null ? null : options.depth - 1
      +    });
      +
      +    // Five space padding because that's the size of "Box< ".
      +    const padding = ' '.repeat(5);
      +    const inner = util.inspect(this.value, newOptions)
      +                      .replace(/\n/g, `\n${padding}`);
      +    return `${options.stylize('Box', 'special')}< ${inner} >`;
      +  }
      +}
      +
      +const box = new Box(true);
      +
      +util.inspect(box);
      +// Returns: "Box< true >"
      +

      Custom [util.inspect.custom](depth, opts) functions typically return a string +but may return a value of any type that will be formatted accordingly by +util.inspect().

      +
      const util = require('util');
      +
      +const obj = { foo: 'this will not show up in the inspect() output' };
      +obj[util.inspect.custom] = (depth) => {
      +  return { bar: 'baz' };
      +};
      +
      +util.inspect(obj);
      +// Returns: "{ bar: 'baz' }"
      +

      util.inspect.custom#

      + +
        +
      • <symbol> that can be used to declare custom inspect functions.
      • +
      +

      In addition to being accessible through util.inspect.custom, this +symbol is registered globally and can be +accessed in any environment as Symbol.for('nodejs.util.inspect.custom').

      +
      const inspect = Symbol.for('nodejs.util.inspect.custom');
      +
      +class Password {
      +  constructor(value) {
      +    this.value = value;
      +  }
      +
      +  toString() {
      +    return 'xxxxxxxx';
      +  }
      +
      +  [inspect]() {
      +    return `Password <${this.toString()}>`;
      +  }
      +}
      +
      +const password = new Password('r0sebud');
      +console.log(password);
      +// Prints Password <xxxxxxxx>
      +

      See Custom inspection functions on Objects for more details.

      +

      util.inspect.defaultOptions#

      + +

      The defaultOptions value allows customization of the default options used by +util.inspect. This is useful for functions like console.log or +util.format which implicitly call into util.inspect. It shall be set to an +object containing one or more valid util.inspect() options. Setting +option properties directly is also supported.

      +
      const util = require('util');
      +const arr = Array(101).fill(0);
      +
      +console.log(arr); // Logs the truncated array
      +util.inspect.defaultOptions.maxArrayLength = null;
      +console.log(arr); // logs the full array
      +

      util.isDeepStrictEqual(val1, val2)#

      + + +

      Returns true if there is deep strict equality between val1 and val2. +Otherwise, returns false.

      +

      See assert.deepStrictEqual() for more information about deep strict +equality.

      +

      util.promisify(original)#

      + + +

      Takes a function following the common error-first callback style, i.e. taking +an (err, value) => ... callback as the last argument, and returns a version +that returns promises.

      +
      const util = require('util');
      +const fs = require('fs');
      +
      +const stat = util.promisify(fs.stat);
      +stat('.').then((stats) => {
      +  // Do something with `stats`
      +}).catch((error) => {
      +  // Handle the error.
      +});
      +

      Or, equivalently using async functions:

      +
      const util = require('util');
      +const fs = require('fs');
      +
      +const stat = util.promisify(fs.stat);
      +
      +async function callStat() {
      +  const stats = await stat('.');
      +  console.log(`This directory is owned by ${stats.uid}`);
      +}
      +

      If there is an original[util.promisify.custom] property present, promisify +will return its value, see Custom promisified functions.

      +

      promisify() assumes that original is a function taking a callback as its +final argument in all cases. If original is not a function, promisify() +will throw an error. If original is a function but its last argument is not +an error-first callback, it will still be passed an error-first +callback as its last argument.

      +

      Using promisify() on class methods or other methods that use this may not +work as expected unless handled specially:

      +
      const util = require('util');
      +
      +class Foo {
      +  constructor() {
      +    this.a = 42;
      +  }
      +
      +  bar(callback) {
      +    callback(null, this.a);
      +  }
      +}
      +
      +const foo = new Foo();
      +
      +const naiveBar = util.promisify(foo.bar);
      +// TypeError: Cannot read property 'a' of undefined
      +// naiveBar().then(a => console.log(a));
      +
      +naiveBar.call(foo).then((a) => console.log(a)); // '42'
      +
      +const bindBar = naiveBar.bind(foo);
      +bindBar().then((a) => console.log(a)); // '42'
      +

      Custom promisified functions#

      +

      Using the util.promisify.custom symbol one can override the return value of +util.promisify():

      +
      const util = require('util');
      +
      +function doSomething(foo, callback) {
      +  // ...
      +}
      +
      +doSomething[util.promisify.custom] = (foo) => {
      +  return getPromiseSomehow();
      +};
      +
      +const promisified = util.promisify(doSomething);
      +console.log(promisified === doSomething[util.promisify.custom]);
      +// prints 'true'
      +

      This can be useful for cases where the original function does not follow the +standard format of taking an error-first callback as the last argument.

      +

      For example, with a function that takes in +(foo, onSuccessCallback, onErrorCallback):

      +
      doSomething[util.promisify.custom] = (foo) => {
      +  return new Promise((resolve, reject) => {
      +    doSomething(foo, resolve, reject);
      +  });
      +};
      +

      If promisify.custom is defined but is not a function, promisify() will +throw an error.

      +

      util.promisify.custom#

      + + +

      In addition to being accessible through util.promisify.custom, this +symbol is registered globally and can be +accessed in any environment as Symbol.for('nodejs.util.promisify.custom').

      +

      For example, with a function that takes in +(foo, onSuccessCallback, onErrorCallback):

      +
      const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');
      +
      +doSomething[kCustomPromisifiedSymbol] = (foo) => {
      +  return new Promise((resolve, reject) => {
      +    doSomething(foo, resolve, reject);
      +  });
      +};
      +

      Class: util.TextDecoder#

      + +

      An implementation of the WHATWG Encoding Standard TextDecoder API.

      +
      const decoder = new TextDecoder('shift_jis');
      +let string = '';
      +let buffer;
      +while (buffer = getNextChunkSomehow()) {
      +  string += decoder.decode(buffer, { stream: true });
      +}
      +string += decoder.decode(); // end-of-stream
      +

      WHATWG supported encodings#

      +

      Per the WHATWG Encoding Standard, the encodings supported by the +TextDecoder API are outlined in the tables below. For each encoding, +one or more aliases may be used.

      +

      Different Node.js build configurations support different sets of encodings. +While a very basic set of encodings is supported even on Node.js builds without +ICU enabled, support for some encodings is provided only when Node.js is built +with ICU and using the full ICU data (see Internationalization).

      +

      Encodings Supported Without ICU#

      + + + + + + + + + + + + + + + + + +
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      +

      Encodings Supported by Default (With ICU)#

      + + + + + + + + + + + + + + + + + + + + + +
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      'utf-16be'
      +

      Encodings requiring full ICU data#

      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      EncodingAliases
      'ibm866''866', 'cp866', 'csibm866'
      'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
      'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
      'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
      'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
      'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
      'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
      'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
      'iso-8859-8-i''csiso88598i', 'logical'
      'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
      'iso-8859-13''iso8859-13', 'iso885913'
      'iso-8859-14''iso8859-14', 'iso885914'
      'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
      'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
      'koi8-u''koi8-ru'
      'macintosh''csmacintosh', 'mac', 'x-mac-roman'
      'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
      'windows-1250''cp1250', 'x-cp1250'
      'windows-1251''cp1251', 'x-cp1251'
      'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
      'windows-1253''cp1253', 'x-cp1253'
      'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
      'windows-1255''cp1255', 'x-cp1255'
      'windows-1256''cp1256', 'x-cp1256'
      'windows-1257''cp1257', 'x-cp1257'
      'windows-1258''cp1258', 'x-cp1258'
      'x-mac-cyrillic''x-mac-ukrainian'
      'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
      'gb18030'
      'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
      'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
      'iso-2022-jp''csiso2022jp'
      'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
      'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
      +

      The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard +is not supported.

      +

      new TextDecoder([encoding[, options]])#

      + +
        +
      • encoding <string> Identifies the encoding that this TextDecoder instance +supports. Default: 'utf-8'.
      • +
      • options <Object> +
          +
        • fatal <boolean> true if decoding failures are fatal. This option is only +supported when ICU is enabled (see Internationalization). Default: +false.
        • +
        • ignoreBOM <boolean> When true, the TextDecoder will include the byte +order mark in the decoded result. When false, the byte order mark will +be removed from the output. This option is only used when encoding is +'utf-8', 'utf-16be' or 'utf-16le'. Default: false.
        • +
        +
      • +
      +

      Creates an new TextDecoder instance. The encoding may specify one of the +supported encodings or an alias.

      +

      The TextDecoder class is also available on the global object.

      +

      textDecoder.decode([input[, options]])#

      + +

      Decodes the input and returns a string. If options.stream is true, any +incomplete byte sequences occurring at the end of the input are buffered +internally and emitted after the next call to textDecoder.decode().

      +

      If textDecoder.fatal is true, decoding errors that occur will result in a +TypeError being thrown.

      +

      textDecoder.encoding#

      + +

      The encoding supported by the TextDecoder instance.

      +

      textDecoder.fatal#

      + +

      The value will be true if decoding errors result in a TypeError being +thrown.

      +

      textDecoder.ignoreBOM#

      + +

      The value will be true if the decoding result will include the byte order +mark.

      +

      Class: util.TextEncoder#

      + +

      An implementation of the WHATWG Encoding Standard TextEncoder API. All +instances of TextEncoder only support UTF-8 encoding.

      +
      const encoder = new TextEncoder();
      +const uint8array = encoder.encode('this is some data');
      +

      The TextEncoder class is also available on the global object.

      +

      textEncoder.encode([input])#

      + +

      UTF-8 encodes the input string and returns a Uint8Array containing the +encoded bytes.

      +

      textEncoder.encodeInto(src, dest)#

      + +

      UTF-8 encodes the src string to the dest Uint8Array and returns an object +containing the read Unicode code units and written UTF-8 bytes.

      +
      const encoder = new TextEncoder();
      +const src = 'this is some data';
      +const dest = new Uint8Array(10);
      +const { read, written } = encoder.encodeInto(src, dest);
      +

      textEncoder.encoding#

      + +

      The encoding supported by the TextEncoder instance. Always set to 'utf-8'.

      +

      util.types#

      + +

      util.types provides type checks for different kinds of built-in objects. +Unlike instanceof or Object.prototype.toString.call(value), these checks do +not inspect properties of the object that are accessible from JavaScript (like +their prototype), and usually have the overhead of calling into C++.

      +

      The result generally does not make any guarantees about what kinds of +properties or behavior a value exposes in JavaScript. They are primarily +useful for addon developers who prefer to do type checking in JavaScript.

      +

      util.types.isAnyArrayBuffer(value)#

      + + +

      Returns true if the value is a built-in ArrayBuffer or +SharedArrayBuffer instance.

      +

      See also util.types.isArrayBuffer() and +util.types.isSharedArrayBuffer().

      +
      util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true
      +util.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true
      +

      util.types.isArrayBufferView(value)#

      + + +

      Returns true if the value is an instance of one of the ArrayBuffer +views, such as typed array objects or DataView. Equivalent to +ArrayBuffer.isView().

      +
      util.types.isArrayBufferView(new Int8Array());  // true
      +util.types.isArrayBufferView(Buffer.from('hello world')); // true
      +util.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true
      +util.types.isArrayBufferView(new ArrayBuffer());  // false
      +

      util.types.isArgumentsObject(value)#

      + + +

      Returns true if the value is an arguments object.

      + +
      function foo() {
      +  util.types.isArgumentsObject(arguments);  // Returns true
      +}
      +

      util.types.isArrayBuffer(value)#

      + + +

      Returns true if the value is a built-in ArrayBuffer instance. +This does not include SharedArrayBuffer instances. Usually, it is +desirable to test for both; See util.types.isAnyArrayBuffer() for that.

      +
      util.types.isArrayBuffer(new ArrayBuffer());  // Returns true
      +util.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false
      +

      util.types.isAsyncFunction(value)#

      + + +

      Returns true if the value is an async function. +This only reports back what the JavaScript engine is seeing; +in particular, the return value may not match the original source code if +a transpilation tool was used.

      +
      util.types.isAsyncFunction(function foo() {});  // Returns false
      +util.types.isAsyncFunction(async function foo() {});  // Returns true
      +

      util.types.isBigInt64Array(value)#

      + + +

      Returns true if the value is a BigInt64Array instance.

      +
      util.types.isBigInt64Array(new BigInt64Array());   // Returns true
      +util.types.isBigInt64Array(new BigUint64Array());  // Returns false
      +

      util.types.isBigUint64Array(value)#

      + + +

      Returns true if the value is a BigUint64Array instance.

      +
      util.types.isBigUint64Array(new BigInt64Array());   // Returns false
      +util.types.isBigUint64Array(new BigUint64Array());  // Returns true
      +

      util.types.isBooleanObject(value)#

      + + +

      Returns true if the value is a boolean object, e.g. created +by new Boolean().

      +
      util.types.isBooleanObject(false);  // Returns false
      +util.types.isBooleanObject(true);   // Returns false
      +util.types.isBooleanObject(new Boolean(false)); // Returns true
      +util.types.isBooleanObject(new Boolean(true));  // Returns true
      +util.types.isBooleanObject(Boolean(false)); // Returns false
      +util.types.isBooleanObject(Boolean(true));  // Returns false
      +

      util.types.isBoxedPrimitive(value)#

      + + +

      Returns true if the value is any boxed primitive object, e.g. created +by new Boolean(), new String() or Object(Symbol()).

      +

      For example:

      +
      util.types.isBoxedPrimitive(false); // Returns false
      +util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
      +util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
      +util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
      +util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
      +

      util.types.isDataView(value)#

      + + +

      Returns true if the value is a built-in DataView instance.

      +
      const ab = new ArrayBuffer(20);
      +util.types.isDataView(new DataView(ab));  // Returns true
      +util.types.isDataView(new Float64Array());  // Returns false
      +

      See also ArrayBuffer.isView().

      +

      util.types.isDate(value)#

      + + +

      Returns true if the value is a built-in Date instance.

      +
      util.types.isDate(new Date());  // Returns true
      +

      util.types.isExternal(value)#

      + + +

      Returns true if the value is a native External value.

      +

      A native External value is a special type of object that contains a +raw C++ pointer (void*) for access from native code, and has no other +properties. Such objects are created either by Node.js internals or native +addons. In JavaScript, they are frozen objects with a +null prototype.

      +
      #include <js_native_api.h>
      +#include <stdlib.h>
      +napi_value result;
      +static napi_value MyNapi(napi_env env, napi_callback_info info) {
      +  int* raw = (int*) malloc(1024);
      +  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
      +  if (status != napi_ok) {
      +    napi_throw_error(env, NULL, "napi_create_external failed");
      +    return NULL;
      +  }
      +  return result;
      +}
      +...
      +DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
      +...
      +
      const native = require('napi_addon.node');
      +const data = native.myNapi();
      +util.types.isExternal(data); // returns true
      +util.types.isExternal(0); // returns false
      +util.types.isExternal(new String('foo')); // returns false
      +

      For further information on napi_create_external, refer to +napi_create_external().

      +

      util.types.isFloat32Array(value)#

      + + +

      Returns true if the value is a built-in Float32Array instance.

      +
      util.types.isFloat32Array(new ArrayBuffer());  // Returns false
      +util.types.isFloat32Array(new Float32Array());  // Returns true
      +util.types.isFloat32Array(new Float64Array());  // Returns false
      +

      util.types.isFloat64Array(value)#

      + + +

      Returns true if the value is a built-in Float64Array instance.

      +
      util.types.isFloat64Array(new ArrayBuffer());  // Returns false
      +util.types.isFloat64Array(new Uint8Array());  // Returns false
      +util.types.isFloat64Array(new Float64Array());  // Returns true
      +

      util.types.isGeneratorFunction(value)#

      + + +

      Returns true if the value is a generator function. +This only reports back what the JavaScript engine is seeing; +in particular, the return value may not match the original source code if +a transpilation tool was used.

      +
      util.types.isGeneratorFunction(function foo() {});  // Returns false
      +util.types.isGeneratorFunction(function* foo() {});  // Returns true
      +

      util.types.isGeneratorObject(value)#

      + + +

      Returns true if the value is a generator object as returned from a +built-in generator function. +This only reports back what the JavaScript engine is seeing; +in particular, the return value may not match the original source code if +a transpilation tool was used.

      +
      function* foo() {}
      +const generator = foo();
      +util.types.isGeneratorObject(generator);  // Returns true
      +

      util.types.isInt8Array(value)#

      + + +

      Returns true if the value is a built-in Int8Array instance.

      +
      util.types.isInt8Array(new ArrayBuffer());  // Returns false
      +util.types.isInt8Array(new Int8Array());  // Returns true
      +util.types.isInt8Array(new Float64Array());  // Returns false
      +

      util.types.isInt16Array(value)#

      + + +

      Returns true if the value is a built-in Int16Array instance.

      +
      util.types.isInt16Array(new ArrayBuffer());  // Returns false
      +util.types.isInt16Array(new Int16Array());  // Returns true
      +util.types.isInt16Array(new Float64Array());  // Returns false
      +

      util.types.isInt32Array(value)#

      + + +

      Returns true if the value is a built-in Int32Array instance.

      +
      util.types.isInt32Array(new ArrayBuffer());  // Returns false
      +util.types.isInt32Array(new Int32Array());  // Returns true
      +util.types.isInt32Array(new Float64Array());  // Returns false
      +

      util.types.isMap(value)#

      + + +

      Returns true if the value is a built-in Map instance.

      +
      util.types.isMap(new Map());  // Returns true
      +

      util.types.isMapIterator(value)#

      + + +

      Returns true if the value is an iterator returned for a built-in +Map instance.

      +
      const map = new Map();
      +util.types.isMapIterator(map.keys());  // Returns true
      +util.types.isMapIterator(map.values());  // Returns true
      +util.types.isMapIterator(map.entries());  // Returns true
      +util.types.isMapIterator(map[Symbol.iterator]());  // Returns true
      +

      util.types.isModuleNamespaceObject(value)#

      + + +

      Returns true if the value is an instance of a Module Namespace Object.

      + +
      import * as ns from './a.js';
      +
      +util.types.isModuleNamespaceObject(ns);  // Returns true
      +

      util.types.isNativeError(value)#

      + + +

      Returns true if the value is an instance of a built-in Error type.

      +
      util.types.isNativeError(new Error());  // Returns true
      +util.types.isNativeError(new TypeError());  // Returns true
      +util.types.isNativeError(new RangeError());  // Returns true
      +

      util.types.isNumberObject(value)#

      + + +

      Returns true if the value is a number object, e.g. created +by new Number().

      +
      util.types.isNumberObject(0);  // Returns false
      +util.types.isNumberObject(new Number(0));   // Returns true
      +

      util.types.isPromise(value)#

      + + +

      Returns true if the value is a built-in Promise.

      +
      util.types.isPromise(Promise.resolve(42));  // Returns true
      +

      util.types.isProxy(value)#

      + + +

      Returns true if the value is a Proxy instance.

      +
      const target = {};
      +const proxy = new Proxy(target, {});
      +util.types.isProxy(target);  // Returns false
      +util.types.isProxy(proxy);  // Returns true
      +

      util.types.isRegExp(value)#

      + + +

      Returns true if the value is a regular expression object.

      +
      util.types.isRegExp(/abc/);  // Returns true
      +util.types.isRegExp(new RegExp('abc'));  // Returns true
      +

      util.types.isSet(value)#

      + + +

      Returns true if the value is a built-in Set instance.

      +
      util.types.isSet(new Set());  // Returns true
      +

      util.types.isSetIterator(value)#

      + + +

      Returns true if the value is an iterator returned for a built-in +Set instance.

      +
      const set = new Set();
      +util.types.isSetIterator(set.keys());  // Returns true
      +util.types.isSetIterator(set.values());  // Returns true
      +util.types.isSetIterator(set.entries());  // Returns true
      +util.types.isSetIterator(set[Symbol.iterator]());  // Returns true
      +

      util.types.isSharedArrayBuffer(value)#

      + + +

      Returns true if the value is a built-in SharedArrayBuffer instance. +This does not include ArrayBuffer instances. Usually, it is +desirable to test for both; See util.types.isAnyArrayBuffer() for that.

      +
      util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false
      +util.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true
      +

      util.types.isStringObject(value)#

      + + +

      Returns true if the value is a string object, e.g. created +by new String().

      +
      util.types.isStringObject('foo');  // Returns false
      +util.types.isStringObject(new String('foo'));   // Returns true
      +

      util.types.isSymbolObject(value)#

      + + +

      Returns true if the value is a symbol object, created +by calling Object() on a Symbol primitive.

      +
      const symbol = Symbol('foo');
      +util.types.isSymbolObject(symbol);  // Returns false
      +util.types.isSymbolObject(Object(symbol));   // Returns true
      +

      util.types.isTypedArray(value)#

      + + +

      Returns true if the value is a built-in TypedArray instance.

      +
      util.types.isTypedArray(new ArrayBuffer());  // Returns false
      +util.types.isTypedArray(new Uint8Array());  // Returns true
      +util.types.isTypedArray(new Float64Array());  // Returns true
      +

      See also ArrayBuffer.isView().

      +

      util.types.isUint8Array(value)#

      + + +

      Returns true if the value is a built-in Uint8Array instance.

      +
      util.types.isUint8Array(new ArrayBuffer());  // Returns false
      +util.types.isUint8Array(new Uint8Array());  // Returns true
      +util.types.isUint8Array(new Float64Array());  // Returns false
      +

      util.types.isUint8ClampedArray(value)#

      + + +

      Returns true if the value is a built-in Uint8ClampedArray instance.

      +
      util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false
      +util.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true
      +util.types.isUint8ClampedArray(new Float64Array());  // Returns false
      +

      util.types.isUint16Array(value)#

      + + +

      Returns true if the value is a built-in Uint16Array instance.

      +
      util.types.isUint16Array(new ArrayBuffer());  // Returns false
      +util.types.isUint16Array(new Uint16Array());  // Returns true
      +util.types.isUint16Array(new Float64Array());  // Returns false
      +

      util.types.isUint32Array(value)#

      + + +

      Returns true if the value is a built-in Uint32Array instance.

      +
      util.types.isUint32Array(new ArrayBuffer());  // Returns false
      +util.types.isUint32Array(new Uint32Array());  // Returns true
      +util.types.isUint32Array(new Float64Array());  // Returns false
      +

      util.types.isWeakMap(value)#

      + + +

      Returns true if the value is a built-in WeakMap instance.

      +
      util.types.isWeakMap(new WeakMap());  // Returns true
      +

      util.types.isWeakSet(value)#

      + + +

      Returns true if the value is a built-in WeakSet instance.

      +
      util.types.isWeakSet(new WeakSet());  // Returns true
      +

      util.types.isWebAssemblyCompiledModule(value)#

      + + +

      Returns true if the value is a built-in WebAssembly.Module instance.

      +
      const module = new WebAssembly.Module(wasmBuffer);
      +util.types.isWebAssemblyCompiledModule(module);  // Returns true
      +

      Deprecated APIs#

      +

      The following APIs are deprecated and should no longer be used. Existing +applications and modules should be updated to find alternative approaches.

      +

      util._extend(target, source)#

      + +

      Stability: 0 - Deprecated: Use Object.assign() instead.

      + +

      The util._extend() method was never intended to be used outside of internal +Node.js modules. The community found and used it anyway.

      +

      It is deprecated and should not be used in new code. JavaScript comes with very +similar built-in functionality through Object.assign().

      +

      util.isArray(object)#

      + +

      Stability: 0 - Deprecated: Use Array.isArray() instead.

      + +

      Alias for Array.isArray().

      +

      Returns true if the given object is an Array. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isArray([]);
      +// Returns: true
      +util.isArray(new Array());
      +// Returns: true
      +util.isArray({});
      +// Returns: false
      +

      util.isBoolean(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'boolean' instead.

      + +

      Returns true if the given object is a Boolean. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isBoolean(1);
      +// Returns: false
      +util.isBoolean(0);
      +// Returns: false
      +util.isBoolean(false);
      +// Returns: true
      +

      util.isBuffer(object)#

      + +

      Stability: 0 - Deprecated: Use Buffer.isBuffer() instead.

      + +

      Returns true if the given object is a Buffer. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isBuffer({ length: 0 });
      +// Returns: false
      +util.isBuffer([]);
      +// Returns: false
      +util.isBuffer(Buffer.from('hello world'));
      +// Returns: true
      +

      util.isDate(object)#

      + +

      Stability: 0 - Deprecated: Use util.types.isDate() instead.

      + +

      Returns true if the given object is a Date. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isDate(new Date());
      +// Returns: true
      +util.isDate(Date());
      +// false (without 'new' returns a String)
      +util.isDate({});
      +// Returns: false
      +

      util.isError(object)#

      + +

      Stability: 0 - Deprecated: Use util.types.isNativeError() instead.

      + +

      Returns true if the given object is an Error. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +util.isError(new Error());
      +// Returns: true
      +util.isError(new TypeError());
      +// Returns: true
      +util.isError({ name: 'Error', message: 'an error occurred' });
      +// Returns: false
      +

      This method relies on Object.prototype.toString() behavior. It is +possible to obtain an incorrect result when the object argument manipulates +@@toStringTag.

      +
      const util = require('util');
      +const obj = { name: 'Error', message: 'an error occurred' };
      +
      +util.isError(obj);
      +// Returns: false
      +obj[Symbol.toStringTag] = 'Error';
      +util.isError(obj);
      +// Returns: true
      +

      util.isFunction(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'function' instead.

      + +

      Returns true if the given object is a Function. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +function Foo() {}
      +const Bar = () => {};
      +
      +util.isFunction({});
      +// Returns: false
      +util.isFunction(Foo);
      +// Returns: true
      +util.isFunction(Bar);
      +// Returns: true
      +

      util.isNull(object)#

      + +

      Stability: 0 - Deprecated: Use value === null instead.

      + +

      Returns true if the given object is strictly null. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +util.isNull(0);
      +// Returns: false
      +util.isNull(undefined);
      +// Returns: false
      +util.isNull(null);
      +// Returns: true
      +

      util.isNullOrUndefined(object)#

      + +

      Stability: 0 - Deprecated: Use +value === undefined || value === null instead.

      + +

      Returns true if the given object is null or undefined. Otherwise, +returns false.

      +
      const util = require('util');
      +
      +util.isNullOrUndefined(0);
      +// Returns: false
      +util.isNullOrUndefined(undefined);
      +// Returns: true
      +util.isNullOrUndefined(null);
      +// Returns: true
      +

      util.isNumber(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'number' instead.

      + +

      Returns true if the given object is a Number. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isNumber(false);
      +// Returns: false
      +util.isNumber(Infinity);
      +// Returns: true
      +util.isNumber(0);
      +// Returns: true
      +util.isNumber(NaN);
      +// Returns: true
      +

      util.isObject(object)#

      + +

      Stability: 0 - Deprecated: +Use value !== null && typeof value === 'object' instead.

      + +

      Returns true if the given object is strictly an Object and not a +Function (even though functions are objects in JavaScript). +Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isObject(5);
      +// Returns: false
      +util.isObject(null);
      +// Returns: false
      +util.isObject({});
      +// Returns: true
      +util.isObject(() => {});
      +// Returns: false
      +

      util.isPrimitive(object)#

      + +

      Stability: 0 - Deprecated: Use +(typeof value !== 'object' && typeof value !== 'function') || value === null +instead.

      + +

      Returns true if the given object is a primitive type. Otherwise, returns +false.

      +
      const util = require('util');
      +
      +util.isPrimitive(5);
      +// Returns: true
      +util.isPrimitive('foo');
      +// Returns: true
      +util.isPrimitive(false);
      +// Returns: true
      +util.isPrimitive(null);
      +// Returns: true
      +util.isPrimitive(undefined);
      +// Returns: true
      +util.isPrimitive({});
      +// Returns: false
      +util.isPrimitive(() => {});
      +// Returns: false
      +util.isPrimitive(/^$/);
      +// Returns: false
      +util.isPrimitive(new Date());
      +// Returns: false
      +

      util.isRegExp(object)#

      + +

      Stability: 0 - Deprecated

      + +

      Returns true if the given object is a RegExp. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isRegExp(/some regexp/);
      +// Returns: true
      +util.isRegExp(new RegExp('another regexp'));
      +// Returns: true
      +util.isRegExp({});
      +// Returns: false
      +

      util.isString(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'string' instead.

      + +

      Returns true if the given object is a string. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isString('');
      +// Returns: true
      +util.isString('foo');
      +// Returns: true
      +util.isString(String('foo'));
      +// Returns: true
      +util.isString(5);
      +// Returns: false
      +

      util.isSymbol(object)#

      + +

      Stability: 0 - Deprecated: Use typeof value === 'symbol' instead.

      + +

      Returns true if the given object is a Symbol. Otherwise, returns false.

      +
      const util = require('util');
      +
      +util.isSymbol(5);
      +// Returns: false
      +util.isSymbol('foo');
      +// Returns: false
      +util.isSymbol(Symbol('foo'));
      +// Returns: true
      +

      util.isUndefined(object)#

      + +

      Stability: 0 - Deprecated: Use value === undefined instead.

      + +

      Returns true if the given object is undefined. Otherwise, returns false.

      +
      const util = require('util');
      +
      +const foo = undefined;
      +util.isUndefined(5);
      +// Returns: false
      +util.isUndefined(foo);
      +// Returns: true
      +util.isUndefined(null);
      +// Returns: false
      +

      util.log(string)#

      + +

      Stability: 0 - Deprecated: Use a third party module instead.

      + +

      The util.log() method prints the given string to stdout with an included +timestamp.

      +
      const util = require('util');
      +
      +util.log('Timestamped message.');
      + +
      +
      +
      + + diff --git a/doc/api/util.json b/doc/api/util.json new file mode 100644 index 0000000000000000000000000000000000000000..5230fd8c3a5a4d4ff88a61a30847a0cf0686b1f6 --- /dev/null +++ b/doc/api/util.json @@ -0,0 +1,2808 @@ +{ + "type": "module", + "source": "doc/api/util.md", + "modules": [ + { + "textRaw": "Util", + "name": "util", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

      Source Code: lib/util.js

      \n

      The util module supports the needs of Node.js internal APIs. Many of the\nutilities are useful for application and module developers as well. To access\nit:

      \n
      const util = require('util');\n
      ", + "methods": [ + { + "textRaw": "`util.callbackify(original)`", + "type": "method", + "name": "callbackify", + "meta": { + "added": [ + "v8.2.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} a callback style function", + "name": "return", + "type": "Function", + "desc": "a callback style function" + }, + "params": [ + { + "textRaw": "`original` {Function} An `async` function", + "name": "original", + "type": "Function", + "desc": "An `async` function" + } + ] + } + ], + "desc": "

      Takes an async function (or a function that returns a Promise) and returns a\nfunction following the error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument. In the callback, the\nfirst argument will be the rejection reason (or null if the Promise\nresolved), and the second argument will be the resolved value.

      \n
      const util = require('util');\n\nasync function fn() {\n  return 'hello world';\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n  if (err) throw err;\n  console.log(ret);\n});\n
      \n

      Will print:

      \n
      hello world\n
      \n

      The callback is executed asynchronously, and will have a limited stack trace.\nIf the callback throws, the process will emit an 'uncaughtException'\nevent, and if not handled will exit.

      \n

      Since null has a special meaning as the first argument to a callback, if a\nwrapped function rejects a Promise with a falsy value as a reason, the value\nis wrapped in an Error with the original value stored in a field named\nreason.

      \n
      function fn() {\n  return Promise.reject(null);\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n  // When the Promise was rejected with `null` it is wrapped with an Error and\n  // the original value is stored in `reason`.\n  err && err.hasOwnProperty('reason') && err.reason === null;  // true\n});\n
      " + }, + { + "textRaw": "`util.debuglog(section[, callback])`", + "type": "method", + "name": "debuglog", + "meta": { + "added": [ + "v0.11.3" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The logging function", + "name": "return", + "type": "Function", + "desc": "The logging function" + }, + "params": [ + { + "textRaw": "`section` {string} A string identifying the portion of the application for which the `debuglog` function is being created.", + "name": "section", + "type": "string", + "desc": "A string identifying the portion of the application for which the `debuglog` function is being created." + }, + { + "textRaw": "`callback` {Function} A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.", + "name": "callback", + "type": "Function", + "desc": "A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function." + } + ] + } + ], + "desc": "

      The util.debuglog() method is used to create a function that conditionally\nwrites debug messages to stderr based on the existence of the NODE_DEBUG\nenvironment variable. If the section name appears within the value of that\nenvironment variable, then the returned function operates similar to\nconsole.error(). If not, then the returned function is a no-op.

      \n
      const util = require('util');\nconst debuglog = util.debuglog('foo');\n\ndebuglog('hello from foo [%d]', 123);\n
      \n

      If this program is run with NODE_DEBUG=foo in the environment, then\nit will output something like:

      \n
      FOO 3245: hello from foo [123]\n
      \n

      where 3245 is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.

      \n

      The section supports wildcard also:

      \n
      const util = require('util');\nconst debuglog = util.debuglog('foo-bar');\n\ndebuglog('hi there, it\\'s foo-bar [%d]', 2333);\n
      \n

      if it is run with NODE_DEBUG=foo* in the environment, then it will output\nsomething like:

      \n
      FOO-BAR 3257: hi there, it's foo-bar [2333]\n
      \n

      Multiple comma-separated section names may be specified in the NODE_DEBUG\nenvironment variable: NODE_DEBUG=fs,net,tls.

      \n

      The optional callback argument can be used to replace the logging function\nwith a different function that doesn't have any initialization or\nunnecessary wrapping.

      \n
      const util = require('util');\nlet debuglog = util.debuglog('internals', (debug) => {\n  // Replace with a logging function that optimizes out\n  // testing if the section is enabled\n  debuglog = debug;\n});\n
      " + }, + { + "textRaw": "`util.deprecate(fn, msg[, code])`", + "type": "method", + "name": "deprecate", + "meta": { + "added": [ + "v0.8.0" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/16393", + "description": "Deprecation warnings are only emitted once for each code." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function} The deprecated function wrapped to emit a warning.", + "name": "return", + "type": "Function", + "desc": "The deprecated function wrapped to emit a warning." + }, + "params": [ + { + "textRaw": "`fn` {Function} The function that is being deprecated.", + "name": "fn", + "type": "Function", + "desc": "The function that is being deprecated." + }, + { + "textRaw": "`msg` {string} A warning message to display when the deprecated function is invoked.", + "name": "msg", + "type": "string", + "desc": "A warning message to display when the deprecated function is invoked." + }, + { + "textRaw": "`code` {string} A deprecation code. See the [list of deprecated APIs][] for a list of codes.", + "name": "code", + "type": "string", + "desc": "A deprecation code. See the [list of deprecated APIs][] for a list of codes." + } + ] + } + ], + "desc": "

      The util.deprecate() method wraps fn (which may be a function or class) in\nsuch a way that it is marked as deprecated.

      \n
      const util = require('util');\n\nexports.obsoleteFunction = util.deprecate(() => {\n  // Do something here.\n}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');\n
      \n

      When called, util.deprecate() will return a function that will emit a\nDeprecationWarning using the 'warning' event. The warning will\nbe emitted and printed to stderr the first time the returned function is\ncalled. After the warning is emitted, the wrapped function is called without\nemitting a warning.

      \n

      If the same optional code is supplied in multiple calls to util.deprecate(),\nthe warning will be emitted only once for that code.

      \n
      const util = require('util');\n\nconst fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');\nconst fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');\nfn1(); // Emits a deprecation warning with code DEP0001\nfn2(); // Does not emit a deprecation warning because it has the same code\n
      \n

      If either the --no-deprecation or --no-warnings command line flags are\nused, or if the process.noDeprecation property is set to true prior to\nthe first deprecation warning, the util.deprecate() method does nothing.

      \n

      If the --trace-deprecation or --trace-warnings command line flags are set,\nor the process.traceDeprecation property is set to true, a warning and a\nstack trace are printed to stderr the first time the deprecated function is\ncalled.

      \n

      If the --throw-deprecation command line flag is set, or the\nprocess.throwDeprecation property is set to true, then an exception will be\nthrown when the deprecated function is called.

      \n

      The --throw-deprecation command line flag and process.throwDeprecation\nproperty take precedence over --trace-deprecation and\nprocess.traceDeprecation.

      " + }, + { + "textRaw": "`util.format(format[, ...args])`", + "type": "method", + "name": "format", + "meta": { + "added": [ + "v0.5.3" + ], + "changes": [ + { + "version": "v12.11.0", + "pr-url": "https://github.com/nodejs/node/pull/29606", + "description": "The `%c` specifier is ignored now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/23708", + "description": "The `%d`, `%f` and `%i` specifiers now support Symbols properly." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23162", + "description": "The `format` argument is now only taken as such if it actually contains format specifiers." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/23162", + "description": "If the `format` argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24806", + "description": "The `%o` specifier's `depth` has default depth of 4 again." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/17907", + "description": "The `%o` specifier's `depth` option will now fall back to the default depth." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22097", + "description": "The `%d` and `%i` specifiers now support BigInt." + }, + { + "version": "v8.4.0", + "pr-url": "https://github.com/nodejs/node/pull/14558", + "description": "The `%o` and `%O` specifiers are supported now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`format` {string} A `printf`-like format string.", + "name": "format", + "type": "string", + "desc": "A `printf`-like format string." + } + ] + } + ], + "desc": "

      The util.format() method returns a formatted string using the first argument\nas a printf-like format string which can contain zero or more format\nspecifiers. Each specifier is replaced with the converted value from the\ncorresponding argument. Supported specifiers are:

      \n
        \n
      • %s: String will be used to convert all values except BigInt, Object\nand -0. BigInt values will be represented with an n and Objects that\nhave no user defined toString function are inspected using util.inspect()\nwith options { depth: 0, colors: false, compact: 3 }.
      • \n
      • %d: Number will be used to convert all values except BigInt and\nSymbol.
      • \n
      • %i: parseInt(value, 10) is used for all values except BigInt and\nSymbol.
      • \n
      • %f: parseFloat(value) is used for all values expect Symbol.
      • \n
      • %j: JSON. Replaced with the string '[Circular]' if the argument contains\ncircular references.
      • \n
      • %o: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() with options\n{ showHidden: true, showProxy: true }. This will show the full object\nincluding non-enumerable properties and proxies.
      • \n
      • %O: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() without options. This will show\nthe full object not including non-enumerable properties and proxies.
      • \n
      • %c: CSS. This specifier is ignored and will skip any CSS passed in.
      • \n
      • %%: single percent sign ('%'). This does not consume an argument.
      • \n
      • Returns: <string> The formatted string
      • \n
      \n

      If a specifier does not have a corresponding argument, it is not replaced:

      \n
      util.format('%s:%s', 'foo');\n// Returns: 'foo:%s'\n
      \n

      Values that are not part of the format string are formatted using\nutil.inspect() if their type is not string.

      \n

      If there are more arguments passed to the util.format() method than the\nnumber of specifiers, the extra arguments are concatenated to the returned\nstring, separated by spaces:

      \n
      util.format('%s:%s', 'foo', 'bar', 'baz');\n// Returns: 'foo:bar baz'\n
      \n

      If the first argument does not contain a valid format specifier, util.format()\nreturns a string that is the concatenation of all arguments separated by spaces:

      \n
      util.format(1, 2, 3);\n// Returns: '1 2 3'\n
      \n

      If only one argument is passed to util.format(), it is returned as it is\nwithout any formatting:

      \n
      util.format('%% %s');\n// Returns: '%% %s'\n
      \n

      util.format() is a synchronous method that is intended as a debugging tool.\nSome input values can have a significant performance overhead that can block the\nevent loop. Use this function with care and never in a hot code path.

      " + }, + { + "textRaw": "`util.formatWithOptions(inspectOptions, format[, ...args])`", + "type": "method", + "name": "formatWithOptions", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`inspectOptions` {Object}", + "name": "inspectOptions", + "type": "Object" + }, + { + "textRaw": "`format` {string}", + "name": "format", + "type": "string" + } + ] + } + ], + "desc": "

      This function is identical to util.format(), except in that it takes\nan inspectOptions argument which specifies options that are passed along to\nutil.inspect().

      \n
      util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });\n// Returns 'See object { foo: 42 }', where `42` is colored as a number\n// when printed to a terminal.\n
      " + }, + { + "textRaw": "`util.getSystemErrorName(err)`", + "type": "method", + "name": "getSystemErrorName", + "meta": { + "added": [ + "v9.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`err` {number}", + "name": "err", + "type": "number" + } + ] + } + ], + "desc": "

      Returns the string name for a numeric error code that comes from a Node.js API.\nThe mapping between error codes and error names is platform-dependent.\nSee Common System Errors for the names of common errors.

      \n
      fs.access('file/that/does/not/exist', (err) => {\n  const name = util.getSystemErrorName(err.errno);\n  console.error(name);  // ENOENT\n});\n
      " + }, + { + "textRaw": "`util.inherits(constructor, superConstructor)`", + "type": "method", + "name": "inherits", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/3455", + "description": "The `constructor` parameter can refer to an ES6 class now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`constructor` {Function}", + "name": "constructor", + "type": "Function" + }, + { + "textRaw": "`superConstructor` {Function}", + "name": "superConstructor", + "type": "Function" + } + ] + } + ], + "desc": "

      Usage of util.inherits() is discouraged. Please use the ES6 class and\nextends keywords to get language level inheritance support. Also note\nthat the two styles are semantically incompatible.

      \n

      Inherit the prototype methods from one constructor into another. The\nprototype of constructor will be set to a new object created from\nsuperConstructor.

      \n

      This mainly adds some input validation on top of\nObject.setPrototypeOf(constructor.prototype, superConstructor.prototype).\nAs an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.

      \n
      const util = require('util');\nconst EventEmitter = require('events');\n\nfunction MyStream() {\n  EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, EventEmitter);\n\nMyStream.prototype.write = function(data) {\n  this.emit('data', data);\n};\n\nconst stream = new MyStream();\n\nconsole.log(stream instanceof EventEmitter); // true\nconsole.log(MyStream.super_ === EventEmitter); // true\n\nstream.on('data', (data) => {\n  console.log(`Received data: \"${data}\"`);\n});\nstream.write('It works!'); // Received data: \"It works!\"\n
      \n

      ES6 example using class and extends:

      \n
      const EventEmitter = require('events');\n\nclass MyStream extends EventEmitter {\n  write(data) {\n    this.emit('data', data);\n  }\n}\n\nconst stream = new MyStream();\n\nstream.on('data', (data) => {\n  console.log(`Received data: \"${data}\"`);\n});\nstream.write('With ES6');\n
      " + }, + { + "textRaw": "`util.inspect(object[, options])`", + "type": "method", + "name": "inspect", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": [ + "v14.6.0", + "v12.19.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/33690", + "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32392", + "description": "The `maxStringLength` option is supported now." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30768", + "description": "User defined prototype properties are inspected in case `showHidden` is `true`." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27109", + "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." + }, + { + "version": "v11.11.0", + "pr-url": "https://github.com/nodejs/node/pull/26269", + "description": "The `compact` option accepts numbers for a new output mode." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24971", + "description": "Internal properties no longer appear in the context argument of a custom inspection function." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25006", + "description": "ArrayBuffers now also show their binary contents." + }, + { + "version": "v11.5.0", + "pr-url": "https://github.com/nodejs/node/pull/24852", + "description": "The `getters` option is supported now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24326", + "description": "The `depth` default changed back to `2`." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22846", + "description": "The `depth` default changed to `20`." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22788", + "description": "The `sorted` option is supported now." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22756", + "description": "The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected." + }, + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/20725", + "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19259", + "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17576", + "description": "The `compact` option is supported now." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8174", + "description": "Custom inspection functions can now return `this`." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/7499", + "description": "The `breakLength` option is supported now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6334", + "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6465", + "description": "The `showProxy` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The representation of `object`.", + "name": "return", + "type": "string", + "desc": "The representation of `object`." + }, + "params": [ + { + "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", + "name": "object", + "type": "any", + "desc": "Any JavaScript primitive or `Object`." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", + "name": "showHidden", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties)." + }, + { + "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", + "name": "depth", + "type": "number", + "default": "`2`", + "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`." + }, + { + "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]. **Default:** `false`.", + "name": "colors", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]." + }, + { + "textRaw": "`customInspect` {boolean} If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked. **Default:** `true`.", + "name": "customInspect", + "type": "boolean", + "default": "`true`", + "desc": "If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked." + }, + { + "textRaw": "`showProxy` {boolean} If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects. **Default:** `false`.", + "name": "showProxy", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects." + }, + { + "textRaw": "`maxArrayLength` {integer} Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements. **Default:** `100`.", + "name": "maxArrayLength", + "type": "integer", + "default": "`100`", + "desc": "Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements." + }, + { + "textRaw": "`maxStringLength` {integer} Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters. **Default:** `Infinity`.", + "name": "maxStringLength", + "type": "integer", + "default": "`Infinity`", + "desc": "Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters." + }, + { + "textRaw": "`breakLength` {integer} The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`). **Default:** `80`.", + "name": "breakLength", + "type": "integer", + "default": "`80`", + "desc": "The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`)." + }, + { + "textRaw": "`compact` {boolean|integer} Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below. **Default:** `3`.", + "name": "compact", + "type": "boolean|integer", + "default": "`3`", + "desc": "Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below." + }, + { + "textRaw": "`sorted` {boolean|Function} If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][].", + "name": "sorted", + "type": "boolean|Function", + "desc": "If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][]." + }, + { + "textRaw": "`getters` {boolean|string} If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. **Default:** `false`.", + "name": "getters", + "type": "boolean|string", + "default": "`false`", + "desc": "If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function." + } + ] + } + ] + } + ], + "desc": "

      The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or @@toStringTag to make\nan identifiable tag for an inspected value.

      \n
      class Foo {\n  get [Symbol.toStringTag]() {\n    return 'bar';\n  }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz);       // '[foo] {}'\n
      \n

      Circular references are marked as '[Circular]':

      \n
      const { inspect } = require('util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// {\n//   a: [ [Circular] ],\n//   b: { inner: [Circular], obj: [Circular] }\n// }\n
      \n

      The following example inspects all properties of the util object:

      \n
      const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
      \n

      The following example highlights the effect of the compact option:

      \n
      const util = require('util');\n\nconst o = {\n  a: [1, 2, [[\n    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +\n      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',\n    'test',\n    'foo']], 4],\n  b: new Map([['za', 1], ['zb', 'test']])\n};\nconsole.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n//   [ 1,\n//     2,\n//     [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line\n//           'test',\n//           'foo' ] ],\n//     4 ],\n//   b: Map { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false changes the output to be more reader friendly.\nconsole.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n//   a: [\n//     1,\n//     2,\n//     [\n//       [\n//         'Lorem ipsum dolor sit amet, consectetur ' +\n//           'adipiscing elit, sed do eiusmod tempor ' +\n//           'incididunt ut labore et dolore magna ' +\n//           'aliqua.,\n//         'test',\n//         'foo'\n//       ]\n//     ],\n//     4\n//   ],\n//   b: Map {\n//     'za' => 1,\n//     'zb' => 'test'\n//   }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n// Reducing the `breakLength` will split the \"Lorem ipsum\" text in smaller\n// chunks.\n
      \n

      The showHidden option allows WeakMap and WeakSet entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\nWeakSet entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.

      \n
      const { inspect } = require('util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n
      \n

      The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().

      \n
      const { inspect } = require('util');\nconst assert = require('assert');\n\nconst o1 = {\n  b: [2, 3, 1],\n  a: '`a` comes before `b`',\n  c: new Set([2, 3, 1])\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n  c: new Set([2, 1, 3]),\n  a: '`a` comes before `b`',\n  b: [2, 3, 1]\n};\nassert.strict.equal(\n  inspect(o1, { sorted: true }),\n  inspect(o2, { sorted: true })\n);\n
      \n

      util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MB. Inputs that result in longer output will\nbe truncated.

      " + }, + { + "textRaw": "`util.inspect(object[, showHidden[, depth[, colors]]])`", + "type": "method", + "name": "inspect", + "meta": { + "added": [ + "v0.3.0" + ], + "changes": [ + { + "version": [ + "v14.6.0", + "v12.19.0" + ], + "pr-url": "https://github.com/nodejs/node/pull/33690", + "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." + }, + { + "version": "v12.17.0", + "pr-url": "https://github.com/nodejs/node/pull/32392", + "description": "The `maxStringLength` option is supported now." + }, + { + "version": "v12.16.0", + "pr-url": "https://github.com/nodejs/node/pull/30768", + "description": "User defined prototype properties are inspected in case `showHidden` is `true`." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/27109", + "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." + }, + { + "version": "v11.11.0", + "pr-url": "https://github.com/nodejs/node/pull/26269", + "description": "The `compact` option accepts numbers for a new output mode." + }, + { + "version": "v12.0.0", + "pr-url": "https://github.com/nodejs/node/pull/24971", + "description": "Internal properties no longer appear in the context argument of a custom inspection function." + }, + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/25006", + "description": "ArrayBuffers now also show their binary contents." + }, + { + "version": "v11.5.0", + "pr-url": "https://github.com/nodejs/node/pull/24852", + "description": "The `getters` option is supported now." + }, + { + "version": "v11.4.0", + "pr-url": "https://github.com/nodejs/node/pull/24326", + "description": "The `depth` default changed back to `2`." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22846", + "description": "The `depth` default changed to `20`." + }, + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/22788", + "description": "The `sorted` option is supported now." + }, + { + "version": "v11.0.0", + "pr-url": "https://github.com/nodejs/node/pull/22756", + "description": "The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected." + }, + { + "version": "v10.6.0", + "pr-url": "https://github.com/nodejs/node/pull/20725", + "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19259", + "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." + }, + { + "version": "v9.9.0", + "pr-url": "https://github.com/nodejs/node/pull/17576", + "description": "The `compact` option is supported now." + }, + { + "version": "v6.6.0", + "pr-url": "https://github.com/nodejs/node/pull/8174", + "description": "Custom inspection functions can now return `this`." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/7499", + "description": "The `breakLength` option is supported now." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6334", + "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." + }, + { + "version": "v6.1.0", + "pr-url": "https://github.com/nodejs/node/pull/6465", + "description": "The `showProxy` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The representation of `object`.", + "name": "return", + "type": "string", + "desc": "The representation of `object`." + }, + "params": [ + { + "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", + "name": "object", + "type": "any", + "desc": "Any JavaScript primitive or `Object`." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", + "name": "showHidden", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties)." + }, + { + "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", + "name": "depth", + "type": "number", + "default": "`2`", + "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`." + }, + { + "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]. **Default:** `false`.", + "name": "colors", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]." + }, + { + "textRaw": "`customInspect` {boolean} If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked. **Default:** `true`.", + "name": "customInspect", + "type": "boolean", + "default": "`true`", + "desc": "If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked." + }, + { + "textRaw": "`showProxy` {boolean} If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects. **Default:** `false`.", + "name": "showProxy", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects." + }, + { + "textRaw": "`maxArrayLength` {integer} Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements. **Default:** `100`.", + "name": "maxArrayLength", + "type": "integer", + "default": "`100`", + "desc": "Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements." + }, + { + "textRaw": "`maxStringLength` {integer} Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters. **Default:** `Infinity`.", + "name": "maxStringLength", + "type": "integer", + "default": "`Infinity`", + "desc": "Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters." + }, + { + "textRaw": "`breakLength` {integer} The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`). **Default:** `80`.", + "name": "breakLength", + "type": "integer", + "default": "`80`", + "desc": "The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`)." + }, + { + "textRaw": "`compact` {boolean|integer} Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below. **Default:** `3`.", + "name": "compact", + "type": "boolean|integer", + "default": "`3`", + "desc": "Setting this to `false` causes each object key to be displayed on a new line. It will also add new lines to text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the `breakLength` size. For more information, see the example below." + }, + { + "textRaw": "`sorted` {boolean|Function} If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][].", + "name": "sorted", + "type": "boolean|Function", + "desc": "If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][]." + }, + { + "textRaw": "`getters` {boolean|string} If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. **Default:** `false`.", + "name": "getters", + "type": "boolean|string", + "default": "`false`", + "desc": "If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function." + } + ] + } + ] + } + ], + "desc": "

      The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or @@toStringTag to make\nan identifiable tag for an inspected value.

      \n
      class Foo {\n  get [Symbol.toStringTag]() {\n    return 'bar';\n  }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz);       // '[foo] {}'\n
      \n

      Circular references are marked as '[Circular]':

      \n
      const { inspect } = require('util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// {\n//   a: [ [Circular] ],\n//   b: { inner: [Circular], obj: [Circular] }\n// }\n
      \n

      The following example inspects all properties of the util object:

      \n
      const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
      \n

      The following example highlights the effect of the compact option:

      \n
      const util = require('util');\n\nconst o = {\n  a: [1, 2, [[\n    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +\n      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',\n    'test',\n    'foo']], 4],\n  b: new Map([['za', 1], ['zb', 'test']])\n};\nconsole.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n//   [ 1,\n//     2,\n//     [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line\n//           'test',\n//           'foo' ] ],\n//     4 ],\n//   b: Map { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false changes the output to be more reader friendly.\nconsole.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n//   a: [\n//     1,\n//     2,\n//     [\n//       [\n//         'Lorem ipsum dolor sit amet, consectetur ' +\n//           'adipiscing elit, sed do eiusmod tempor ' +\n//           'incididunt ut labore et dolore magna ' +\n//           'aliqua.,\n//         'test',\n//         'foo'\n//       ]\n//     ],\n//     4\n//   ],\n//   b: Map {\n//     'za' => 1,\n//     'zb' => 'test'\n//   }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n// Reducing the `breakLength` will split the \"Lorem ipsum\" text in smaller\n// chunks.\n
      \n

      The showHidden option allows WeakMap and WeakSet entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\nWeakSet entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.

      \n
      const { inspect } = require('util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n
      \n

      The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().

      \n
      const { inspect } = require('util');\nconst assert = require('assert');\n\nconst o1 = {\n  b: [2, 3, 1],\n  a: '`a` comes before `b`',\n  c: new Set([2, 3, 1])\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n  c: new Set([2, 1, 3]),\n  a: '`a` comes before `b`',\n  b: [2, 3, 1]\n};\nassert.strict.equal(\n  inspect(o1, { sorted: true }),\n  inspect(o2, { sorted: true })\n);\n
      \n

      util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MB. Inputs that result in longer output will\nbe truncated.

      ", + "miscs": [ + { + "textRaw": "Customizing `util.inspect` colors", + "name": "Customizing `util.inspect` colors", + "type": "misc", + "desc": "

      Color output (if enabled) of util.inspect is customizable globally\nvia the util.inspect.styles and util.inspect.colors properties.

      \n

      util.inspect.styles is a map associating a style name to a color from\nutil.inspect.colors.

      \n

      The default styles and associated colors are:

      \n
        \n
      • bigint: yellow
      • \n
      • boolean: yellow
      • \n
      • date: magenta
      • \n
      • module: underline
      • \n
      • name: (no styling)
      • \n
      • null: bold
      • \n
      • number: yellow
      • \n
      • regexp: red
      • \n
      • special: cyan (e.g., Proxies)
      • \n
      • string: green
      • \n
      • symbol: green
      • \n
      • undefined: grey
      • \n
      \n

      Color styling uses ANSI control codes that may not be supported on all\nterminals. To verify color support use tty.hasColors().

      \n

      Predefined control codes are listed below (grouped as \"Modifiers\", \"Foreground\ncolors\", and \"Background colors\").

      ", + "miscs": [ + { + "textRaw": "Modifiers", + "name": "modifiers", + "desc": "

      Modifier support varies throughout different terminals. They will mostly be\nignored, if not supported.

      \n
        \n
      • reset - Resets all (color) modifiers to their defaults
      • \n
      • bold - Make text bold
      • \n
      • italic - Make text italic
      • \n
      • underline - Make text underlined
      • \n
      • strikethrough - Puts a horizontal line through the center of the text\n(Alias: strikeThrough, crossedout, crossedOut)
      • \n
      • hidden - Prints the text, but makes it invisible (Alias: conceal)
      • \n
      • dim - Decreased color intensity (Alias:\nfaint)
      • \n
      • overlined - Make text overlined
      • \n
      • blink - Hides and shows the text in an interval
      • \n
      • inverse - Swap foreground and\nbackground colors (Alias: swapcolors, swapColors)
      • \n
      • doubleunderline - Make text\ndouble underlined (Alias: doubleUnderline)
      • \n
      • framed - Draw a frame around the text
      • \n
      ", + "type": "misc", + "displayName": "Modifiers" + }, + { + "textRaw": "Foreground colors", + "name": "foreground_colors", + "desc": "
        \n
      • black
      • \n
      • red
      • \n
      • green
      • \n
      • yellow
      • \n
      • blue
      • \n
      • magenta
      • \n
      • cyan
      • \n
      • white
      • \n
      • gray (alias: grey, blackBright)
      • \n
      • redBright
      • \n
      • greenBright
      • \n
      • yellowBright
      • \n
      • blueBright
      • \n
      • magentaBright
      • \n
      • cyanBright
      • \n
      • whiteBright
      • \n
      ", + "type": "misc", + "displayName": "Foreground colors" + }, + { + "textRaw": "Background colors", + "name": "background_colors", + "desc": "
        \n
      • bgBlack
      • \n
      • bgRed
      • \n
      • bgGreen
      • \n
      • bgYellow
      • \n
      • bgBlue
      • \n
      • bgMagenta
      • \n
      • bgCyan
      • \n
      • bgWhite
      • \n
      • bgGray (alias: bgGrey, bgBlackBright)
      • \n
      • bgRedBright
      • \n
      • bgGreenBright
      • \n
      • bgYellowBright
      • \n
      • bgBlueBright
      • \n
      • bgMagentaBright
      • \n
      • bgCyanBright
      • \n
      • bgWhiteBright
      • \n
      ", + "type": "misc", + "displayName": "Background colors" + } + ] + }, + { + "textRaw": "Custom inspection functions on objects", + "name": "Custom inspection functions on objects", + "type": "misc", + "desc": "

      Objects may also define their own\n[util.inspect.custom](depth, opts) function,\nwhich util.inspect() will invoke and use the result of when inspecting\nthe object:

      \n
      const util = require('util');\n\nclass Box {\n  constructor(value) {\n    this.value = value;\n  }\n\n  [util.inspect.custom](depth, options) {\n    if (depth < 0) {\n      return options.stylize('[Box]', 'special');\n    }\n\n    const newOptions = Object.assign({}, options, {\n      depth: options.depth === null ? null : options.depth - 1\n    });\n\n    // Five space padding because that's the size of \"Box< \".\n    const padding = ' '.repeat(5);\n    const inner = util.inspect(this.value, newOptions)\n                      .replace(/\\n/g, `\\n${padding}`);\n    return `${options.stylize('Box', 'special')}< ${inner} >`;\n  }\n}\n\nconst box = new Box(true);\n\nutil.inspect(box);\n// Returns: \"Box< true >\"\n
      \n

      Custom [util.inspect.custom](depth, opts) functions typically return a string\nbut may return a value of any type that will be formatted accordingly by\nutil.inspect().

      \n
      const util = require('util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj[util.inspect.custom] = (depth) => {\n  return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: \"{ bar: 'baz' }\"\n
      " + } + ], + "properties": [ + { + "textRaw": "`custom` {symbol} that can be used to declare custom inspect functions.", + "type": "symbol", + "name": "custom", + "meta": { + "added": [ + "v6.6.0" + ], + "changes": [ + { + "version": "v10.12.0", + "pr-url": "https://github.com/nodejs/node/pull/20857", + "description": "This is now defined as a shared symbol." + } + ] + }, + "desc": "

      In addition to being accessible through util.inspect.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.inspect.custom').

      \n
      const inspect = Symbol.for('nodejs.util.inspect.custom');\n\nclass Password {\n  constructor(value) {\n    this.value = value;\n  }\n\n  toString() {\n    return 'xxxxxxxx';\n  }\n\n  [inspect]() {\n    return `Password <${this.toString()}>`;\n  }\n}\n\nconst password = new Password('r0sebud');\nconsole.log(password);\n// Prints Password <xxxxxxxx>\n
      \n

      See Custom inspection functions on Objects for more details.

      ", + "shortDesc": "that can be used to declare custom inspect functions." + }, + { + "textRaw": "`util.inspect.defaultOptions`", + "name": "defaultOptions", + "meta": { + "added": [ + "v6.4.0" + ], + "changes": [] + }, + "desc": "

      The defaultOptions value allows customization of the default options used by\nutil.inspect. This is useful for functions like console.log or\nutil.format which implicitly call into util.inspect. It shall be set to an\nobject containing one or more valid util.inspect() options. Setting\noption properties directly is also supported.

      \n
      const util = require('util');\nconst arr = Array(101).fill(0);\n\nconsole.log(arr); // Logs the truncated array\nutil.inspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n
      " + } + ] + }, + { + "textRaw": "`util.isDeepStrictEqual(val1, val2)`", + "type": "method", + "name": "isDeepStrictEqual", + "meta": { + "added": [ + "v9.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`val1` {any}", + "name": "val1", + "type": "any" + }, + { + "textRaw": "`val2` {any}", + "name": "val2", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if there is deep strict equality between val1 and val2.\nOtherwise, returns false.

      \n

      See assert.deepStrictEqual() for more information about deep strict\nequality.

      " + }, + { + "textRaw": "`util.promisify(original)`", + "type": "method", + "name": "promisify", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function}", + "name": "return", + "type": "Function" + }, + "params": [ + { + "textRaw": "`original` {Function}", + "name": "original", + "type": "Function" + } + ] + } + ], + "desc": "

      Takes a function following the common error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument, and returns a version\nthat returns promises.

      \n
      const util = require('util');\nconst fs = require('fs');\n\nconst stat = util.promisify(fs.stat);\nstat('.').then((stats) => {\n  // Do something with `stats`\n}).catch((error) => {\n  // Handle the error.\n});\n
      \n

      Or, equivalently using async functions:

      \n
      const util = require('util');\nconst fs = require('fs');\n\nconst stat = util.promisify(fs.stat);\n\nasync function callStat() {\n  const stats = await stat('.');\n  console.log(`This directory is owned by ${stats.uid}`);\n}\n
      \n

      If there is an original[util.promisify.custom] property present, promisify\nwill return its value, see Custom promisified functions.

      \n

      promisify() assumes that original is a function taking a callback as its\nfinal argument in all cases. If original is not a function, promisify()\nwill throw an error. If original is a function but its last argument is not\nan error-first callback, it will still be passed an error-first\ncallback as its last argument.

      \n

      Using promisify() on class methods or other methods that use this may not\nwork as expected unless handled specially:

      \n
      const util = require('util');\n\nclass Foo {\n  constructor() {\n    this.a = 42;\n  }\n\n  bar(callback) {\n    callback(null, this.a);\n  }\n}\n\nconst foo = new Foo();\n\nconst naiveBar = util.promisify(foo.bar);\n// TypeError: Cannot read property 'a' of undefined\n// naiveBar().then(a => console.log(a));\n\nnaiveBar.call(foo).then((a) => console.log(a)); // '42'\n\nconst bindBar = naiveBar.bind(foo);\nbindBar().then((a) => console.log(a)); // '42'\n
      ", + "modules": [ + { + "textRaw": "Custom promisified functions", + "name": "custom_promisified_functions", + "desc": "

      Using the util.promisify.custom symbol one can override the return value of\nutil.promisify():

      \n
      const util = require('util');\n\nfunction doSomething(foo, callback) {\n  // ...\n}\n\ndoSomething[util.promisify.custom] = (foo) => {\n  return getPromiseSomehow();\n};\n\nconst promisified = util.promisify(doSomething);\nconsole.log(promisified === doSomething[util.promisify.custom]);\n// prints 'true'\n
      \n

      This can be useful for cases where the original function does not follow the\nstandard format of taking an error-first callback as the last argument.

      \n

      For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):

      \n
      doSomething[util.promisify.custom] = (foo) => {\n  return new Promise((resolve, reject) => {\n    doSomething(foo, resolve, reject);\n  });\n};\n
      \n

      If promisify.custom is defined but is not a function, promisify() will\nthrow an error.

      ", + "type": "module", + "displayName": "Custom promisified functions" + } + ], + "properties": [ + { + "textRaw": "`custom` {symbol} that can be used to declare custom promisified variants of functions, see [Custom promisified functions][].", + "type": "symbol", + "name": "custom", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [ + { + "version": "v12.16.2", + "pr-url": "https://github.com/nodejs/node/pull/31672", + "description": "This is now defined as a shared symbol." + } + ] + }, + "desc": "

      In addition to being accessible through util.promisify.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.promisify.custom').

      \n

      For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):

      \n
      const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');\n\ndoSomething[kCustomPromisifiedSymbol] = (foo) => {\n  return new Promise((resolve, reject) => {\n    doSomething(foo, resolve, reject);\n  });\n};\n
      ", + "shortDesc": "that can be used to declare custom promisified variants of functions, see [Custom promisified functions][]." + } + ] + } + ], + "classes": [ + { + "textRaw": "Class: `util.TextDecoder`", + "type": "class", + "name": "util.TextDecoder", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [] + }, + "desc": "

      An implementation of the WHATWG Encoding Standard TextDecoder API.

      \n
      const decoder = new TextDecoder('shift_jis');\nlet string = '';\nlet buffer;\nwhile (buffer = getNextChunkSomehow()) {\n  string += decoder.decode(buffer, { stream: true });\n}\nstring += decoder.decode(); // end-of-stream\n
      ", + "modules": [ + { + "textRaw": "WHATWG supported encodings", + "name": "whatwg_supported_encodings", + "desc": "

      Per the WHATWG Encoding Standard, the encodings supported by the\nTextDecoder API are outlined in the tables below. For each encoding,\none or more aliases may be used.

      \n

      Different Node.js build configurations support different sets of encodings.\nWhile a very basic set of encodings is supported even on Node.js builds without\nICU enabled, support for some encodings is provided only when Node.js is built\nwith ICU and using the full ICU data (see Internationalization).

      ", + "modules": [ + { + "textRaw": "Encodings Supported Without ICU", + "name": "encodings_supported_without_icu", + "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      ", + "type": "module", + "displayName": "Encodings Supported Without ICU" + }, + { + "textRaw": "Encodings Supported by Default (With ICU)", + "name": "encodings_supported_by_default_(with_icu)", + "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      EncodingAliases
      'utf-8''unicode-1-1-utf-8', 'utf8'
      'utf-16le''utf-16'
      'utf-16be'
      ", + "type": "module", + "displayName": "Encodings Supported by Default (With ICU)" + }, + { + "textRaw": "Encodings requiring full ICU data", + "name": "encodings_requiring_full_icu_data", + "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      EncodingAliases
      'ibm866''866', 'cp866', 'csibm866'
      'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
      'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
      'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
      'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
      'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
      'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
      'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
      'iso-8859-8-i''csiso88598i', 'logical'
      'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
      'iso-8859-13''iso8859-13', 'iso885913'
      'iso-8859-14''iso8859-14', 'iso885914'
      'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
      'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
      'koi8-u''koi8-ru'
      'macintosh''csmacintosh', 'mac', 'x-mac-roman'
      'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
      'windows-1250''cp1250', 'x-cp1250'
      'windows-1251''cp1251', 'x-cp1251'
      'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
      'windows-1253''cp1253', 'x-cp1253'
      'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
      'windows-1255''cp1255', 'x-cp1255'
      'windows-1256''cp1256', 'x-cp1256'
      'windows-1257''cp1257', 'x-cp1257'
      'windows-1258''cp1258', 'x-cp1258'
      'x-mac-cyrillic''x-mac-ukrainian'
      'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
      'gb18030'
      'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
      'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
      'iso-2022-jp''csiso2022jp'
      'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
      'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
      \n

      The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard\nis not supported.

      ", + "type": "module", + "displayName": "Encodings requiring full ICU data" + } + ], + "type": "module", + "displayName": "WHATWG supported encodings" + } + ], + "methods": [ + { + "textRaw": "`textDecoder.decode([input[, options]])`", + "type": "method", + "name": "decode", + "signatures": [ + { + "return": { + "textRaw": "Returns: {string}", + "name": "return", + "type": "string" + }, + "params": [ + { + "textRaw": "`input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data.", + "name": "input", + "type": "ArrayBuffer|DataView|TypedArray", + "desc": "An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`stream` {boolean} `true` if additional chunks of data are expected. **Default:** `false`.", + "name": "stream", + "type": "boolean", + "default": "`false`", + "desc": "`true` if additional chunks of data are expected." + } + ] + } + ] + } + ], + "desc": "

      Decodes the input and returns a string. If options.stream is true, any\nincomplete byte sequences occurring at the end of the input are buffered\ninternally and emitted after the next call to textDecoder.decode().

      \n

      If textDecoder.fatal is true, decoding errors that occur will result in a\nTypeError being thrown.

      " + } + ], + "properties": [ + { + "textRaw": "`encoding` {string}", + "type": "string", + "name": "encoding", + "desc": "

      The encoding supported by the TextDecoder instance.

      " + }, + { + "textRaw": "`fatal` {boolean}", + "type": "boolean", + "name": "fatal", + "desc": "

      The value will be true if decoding errors result in a TypeError being\nthrown.

      " + }, + { + "textRaw": "`ignoreBOM` {boolean}", + "type": "boolean", + "name": "ignoreBOM", + "desc": "

      The value will be true if the decoding result will include the byte order\nmark.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`encoding` {string} Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`.", + "name": "encoding", + "type": "string", + "default": "`'utf-8'`", + "desc": "Identifies the `encoding` that this `TextDecoder` instance supports." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`fatal` {boolean} `true` if decoding failures are fatal. This option is only supported when ICU is enabled (see [Internationalization][]). **Default:** `false`.", + "name": "fatal", + "type": "boolean", + "default": "`false`", + "desc": "`true` if decoding failures are fatal. This option is only supported when ICU is enabled (see [Internationalization][])." + }, + { + "textRaw": "`ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`.", + "name": "ignoreBOM", + "type": "boolean", + "default": "`false`", + "desc": "When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`." + } + ] + } + ], + "desc": "

      Creates an new TextDecoder instance. The encoding may specify one of the\nsupported encodings or an alias.

      \n

      The TextDecoder class is also available on the global object.

      " + } + ] + }, + { + "textRaw": "Class: `util.TextEncoder`", + "type": "class", + "name": "util.TextEncoder", + "meta": { + "added": [ + "v8.3.0" + ], + "changes": [ + { + "version": "v11.0.0", + "pr-url": "v11.0.0", + "description": "The class is now available on the global object." + } + ] + }, + "desc": "

      An implementation of the WHATWG Encoding Standard TextEncoder API. All\ninstances of TextEncoder only support UTF-8 encoding.

      \n
      const encoder = new TextEncoder();\nconst uint8array = encoder.encode('this is some data');\n
      \n

      The TextEncoder class is also available on the global object.

      ", + "methods": [ + { + "textRaw": "`textEncoder.encode([input])`", + "type": "method", + "name": "encode", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Uint8Array}", + "name": "return", + "type": "Uint8Array" + }, + "params": [ + { + "textRaw": "`input` {string} The text to encode. **Default:** an empty string.", + "name": "input", + "type": "string", + "default": "an empty string", + "desc": "The text to encode." + } + ] + } + ], + "desc": "

      UTF-8 encodes the input string and returns a Uint8Array containing the\nencoded bytes.

      " + }, + { + "textRaw": "`textEncoder.encodeInto(src, dest)`", + "type": "method", + "name": "encodeInto", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`read` {number} The read Unicode code units of src.", + "name": "read", + "type": "number", + "desc": "The read Unicode code units of src." + }, + { + "textRaw": "`written` {number} The written UTF-8 bytes of dest.", + "name": "written", + "type": "number", + "desc": "The written UTF-8 bytes of dest." + } + ] + }, + "params": [ + { + "textRaw": "`src` {string} The text to encode.", + "name": "src", + "type": "string", + "desc": "The text to encode." + }, + { + "textRaw": "`dest` {Uint8Array} The array to hold the encode result.", + "name": "dest", + "type": "Uint8Array", + "desc": "The array to hold the encode result." + } + ] + } + ], + "desc": "

      UTF-8 encodes the src string to the dest Uint8Array and returns an object\ncontaining the read Unicode code units and written UTF-8 bytes.

      \n
      const encoder = new TextEncoder();\nconst src = 'this is some data';\nconst dest = new Uint8Array(10);\nconst { read, written } = encoder.encodeInto(src, dest);\n
      " + } + ], + "properties": [ + { + "textRaw": "`encoding` {string}", + "type": "string", + "name": "encoding", + "desc": "

      The encoding supported by the TextEncoder instance. Always set to 'utf-8'.

      " + } + ] + } + ], + "properties": [ + { + "textRaw": "`util.types`", + "name": "types", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

      util.types provides type checks for different kinds of built-in objects.\nUnlike instanceof or Object.prototype.toString.call(value), these checks do\nnot inspect properties of the object that are accessible from JavaScript (like\ntheir prototype), and usually have the overhead of calling into C++.

      \n

      The result generally does not make any guarantees about what kinds of\nproperties or behavior a value exposes in JavaScript. They are primarily\nuseful for addon developers who prefer to do type checking in JavaScript.

      ", + "methods": [ + { + "textRaw": "`util.types.isAnyArrayBuffer(value)`", + "type": "method", + "name": "isAnyArrayBuffer", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in ArrayBuffer or\nSharedArrayBuffer instance.

      \n

      See also util.types.isArrayBuffer() and\nutil.types.isSharedArrayBuffer().

      \n
      util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true\nutil.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isArrayBufferView(value)`", + "type": "method", + "name": "isArrayBufferView", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an instance of one of the ArrayBuffer\nviews, such as typed array objects or DataView. Equivalent to\nArrayBuffer.isView().

      \n
      util.types.isArrayBufferView(new Int8Array());  // true\nutil.types.isArrayBufferView(Buffer.from('hello world')); // true\nutil.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true\nutil.types.isArrayBufferView(new ArrayBuffer());  // false\n
      " + }, + { + "textRaw": "`util.types.isArgumentsObject(value)`", + "type": "method", + "name": "isArgumentsObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an arguments object.

      \n\n
      function foo() {\n  util.types.isArgumentsObject(arguments);  // Returns true\n}\n
      " + }, + { + "textRaw": "`util.types.isArrayBuffer(value)`", + "type": "method", + "name": "isArrayBuffer", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in ArrayBuffer instance.\nThis does not include SharedArrayBuffer instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.

      \n
      util.types.isArrayBuffer(new ArrayBuffer());  // Returns true\nutil.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isAsyncFunction(value)`", + "type": "method", + "name": "isAsyncFunction", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an async function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

      \n
      util.types.isAsyncFunction(function foo() {});  // Returns false\nutil.types.isAsyncFunction(async function foo() {});  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isBigInt64Array(value)`", + "type": "method", + "name": "isBigInt64Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a BigInt64Array instance.

      \n
      util.types.isBigInt64Array(new BigInt64Array());   // Returns true\nutil.types.isBigInt64Array(new BigUint64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isBigUint64Array(value)`", + "type": "method", + "name": "isBigUint64Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a BigUint64Array instance.

      \n
      util.types.isBigUint64Array(new BigInt64Array());   // Returns false\nutil.types.isBigUint64Array(new BigUint64Array());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isBooleanObject(value)`", + "type": "method", + "name": "isBooleanObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a boolean object, e.g. created\nby new Boolean().

      \n
      util.types.isBooleanObject(false);  // Returns false\nutil.types.isBooleanObject(true);   // Returns false\nutil.types.isBooleanObject(new Boolean(false)); // Returns true\nutil.types.isBooleanObject(new Boolean(true));  // Returns true\nutil.types.isBooleanObject(Boolean(false)); // Returns false\nutil.types.isBooleanObject(Boolean(true));  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isBoxedPrimitive(value)`", + "type": "method", + "name": "isBoxedPrimitive", + "meta": { + "added": [ + "v10.11.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is any boxed primitive object, e.g. created\nby new Boolean(), new String() or Object(Symbol()).

      \n

      For example:

      \n
      util.types.isBoxedPrimitive(false); // Returns false\nutil.types.isBoxedPrimitive(new Boolean(false)); // Returns true\nutil.types.isBoxedPrimitive(Symbol('foo')); // Returns false\nutil.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true\nutil.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true\n
      " + }, + { + "textRaw": "`util.types.isDataView(value)`", + "type": "method", + "name": "isDataView", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in DataView instance.

      \n
      const ab = new ArrayBuffer(20);\nutil.types.isDataView(new DataView(ab));  // Returns true\nutil.types.isDataView(new Float64Array());  // Returns false\n
      \n

      See also ArrayBuffer.isView().

      " + }, + { + "textRaw": "`util.types.isDate(value)`", + "type": "method", + "name": "isDate", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Date instance.

      \n
      util.types.isDate(new Date());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isExternal(value)`", + "type": "method", + "name": "isExternal", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a native External value.

      \n

      A native External value is a special type of object that contains a\nraw C++ pointer (void*) for access from native code, and has no other\nproperties. Such objects are created either by Node.js internals or native\naddons. In JavaScript, they are frozen objects with a\nnull prototype.

      \n
      #include <js_native_api.h>\n#include <stdlib.h>\nnapi_value result;\nstatic napi_value MyNapi(napi_env env, napi_callback_info info) {\n  int* raw = (int*) malloc(1024);\n  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);\n  if (status != napi_ok) {\n    napi_throw_error(env, NULL, \"napi_create_external failed\");\n    return NULL;\n  }\n  return result;\n}\n...\nDECLARE_NAPI_PROPERTY(\"myNapi\", MyNapi)\n...\n
      \n
      const native = require('napi_addon.node');\nconst data = native.myNapi();\nutil.types.isExternal(data); // returns true\nutil.types.isExternal(0); // returns false\nutil.types.isExternal(new String('foo')); // returns false\n
      \n

      For further information on napi_create_external, refer to\nnapi_create_external().

      " + }, + { + "textRaw": "`util.types.isFloat32Array(value)`", + "type": "method", + "name": "isFloat32Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Float32Array instance.

      \n
      util.types.isFloat32Array(new ArrayBuffer());  // Returns false\nutil.types.isFloat32Array(new Float32Array());  // Returns true\nutil.types.isFloat32Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isFloat64Array(value)`", + "type": "method", + "name": "isFloat64Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Float64Array instance.

      \n
      util.types.isFloat64Array(new ArrayBuffer());  // Returns false\nutil.types.isFloat64Array(new Uint8Array());  // Returns false\nutil.types.isFloat64Array(new Float64Array());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isGeneratorFunction(value)`", + "type": "method", + "name": "isGeneratorFunction", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

      \n
      util.types.isGeneratorFunction(function foo() {});  // Returns false\nutil.types.isGeneratorFunction(function* foo() {});  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isGeneratorObject(value)`", + "type": "method", + "name": "isGeneratorObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a generator object as returned from a\nbuilt-in generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

      \n
      function* foo() {}\nconst generator = foo();\nutil.types.isGeneratorObject(generator);  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isInt8Array(value)`", + "type": "method", + "name": "isInt8Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Int8Array instance.

      \n
      util.types.isInt8Array(new ArrayBuffer());  // Returns false\nutil.types.isInt8Array(new Int8Array());  // Returns true\nutil.types.isInt8Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isInt16Array(value)`", + "type": "method", + "name": "isInt16Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Int16Array instance.

      \n
      util.types.isInt16Array(new ArrayBuffer());  // Returns false\nutil.types.isInt16Array(new Int16Array());  // Returns true\nutil.types.isInt16Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isInt32Array(value)`", + "type": "method", + "name": "isInt32Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Int32Array instance.

      \n
      util.types.isInt32Array(new ArrayBuffer());  // Returns false\nutil.types.isInt32Array(new Int32Array());  // Returns true\nutil.types.isInt32Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isMap(value)`", + "type": "method", + "name": "isMap", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Map instance.

      \n
      util.types.isMap(new Map());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isMapIterator(value)`", + "type": "method", + "name": "isMapIterator", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an iterator returned for a built-in\nMap instance.

      \n
      const map = new Map();\nutil.types.isMapIterator(map.keys());  // Returns true\nutil.types.isMapIterator(map.values());  // Returns true\nutil.types.isMapIterator(map.entries());  // Returns true\nutil.types.isMapIterator(map[Symbol.iterator]());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isModuleNamespaceObject(value)`", + "type": "method", + "name": "isModuleNamespaceObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an instance of a Module Namespace Object.

      \n\n
      import * as ns from './a.js';\n\nutil.types.isModuleNamespaceObject(ns);  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isNativeError(value)`", + "type": "method", + "name": "isNativeError", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an instance of a built-in Error type.

      \n
      util.types.isNativeError(new Error());  // Returns true\nutil.types.isNativeError(new TypeError());  // Returns true\nutil.types.isNativeError(new RangeError());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isNumberObject(value)`", + "type": "method", + "name": "isNumberObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a number object, e.g. created\nby new Number().

      \n
      util.types.isNumberObject(0);  // Returns false\nutil.types.isNumberObject(new Number(0));   // Returns true\n
      " + }, + { + "textRaw": "`util.types.isPromise(value)`", + "type": "method", + "name": "isPromise", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Promise.

      \n
      util.types.isPromise(Promise.resolve(42));  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isProxy(value)`", + "type": "method", + "name": "isProxy", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a Proxy instance.

      \n
      const target = {};\nconst proxy = new Proxy(target, {});\nutil.types.isProxy(target);  // Returns false\nutil.types.isProxy(proxy);  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isRegExp(value)`", + "type": "method", + "name": "isRegExp", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a regular expression object.

      \n
      util.types.isRegExp(/abc/);  // Returns true\nutil.types.isRegExp(new RegExp('abc'));  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSet(value)`", + "type": "method", + "name": "isSet", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Set instance.

      \n
      util.types.isSet(new Set());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSetIterator(value)`", + "type": "method", + "name": "isSetIterator", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is an iterator returned for a built-in\nSet instance.

      \n
      const set = new Set();\nutil.types.isSetIterator(set.keys());  // Returns true\nutil.types.isSetIterator(set.values());  // Returns true\nutil.types.isSetIterator(set.entries());  // Returns true\nutil.types.isSetIterator(set[Symbol.iterator]());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSharedArrayBuffer(value)`", + "type": "method", + "name": "isSharedArrayBuffer", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in SharedArrayBuffer instance.\nThis does not include ArrayBuffer instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.

      \n
      util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false\nutil.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isStringObject(value)`", + "type": "method", + "name": "isStringObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a string object, e.g. created\nby new String().

      \n
      util.types.isStringObject('foo');  // Returns false\nutil.types.isStringObject(new String('foo'));   // Returns true\n
      " + }, + { + "textRaw": "`util.types.isSymbolObject(value)`", + "type": "method", + "name": "isSymbolObject", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a symbol object, created\nby calling Object() on a Symbol primitive.

      \n
      const symbol = Symbol('foo');\nutil.types.isSymbolObject(symbol);  // Returns false\nutil.types.isSymbolObject(Object(symbol));   // Returns true\n
      " + }, + { + "textRaw": "`util.types.isTypedArray(value)`", + "type": "method", + "name": "isTypedArray", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in TypedArray instance.

      \n
      util.types.isTypedArray(new ArrayBuffer());  // Returns false\nutil.types.isTypedArray(new Uint8Array());  // Returns true\nutil.types.isTypedArray(new Float64Array());  // Returns true\n
      \n

      See also ArrayBuffer.isView().

      " + }, + { + "textRaw": "`util.types.isUint8Array(value)`", + "type": "method", + "name": "isUint8Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint8Array instance.

      \n
      util.types.isUint8Array(new ArrayBuffer());  // Returns false\nutil.types.isUint8Array(new Uint8Array());  // Returns true\nutil.types.isUint8Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isUint8ClampedArray(value)`", + "type": "method", + "name": "isUint8ClampedArray", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint8ClampedArray instance.

      \n
      util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false\nutil.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true\nutil.types.isUint8ClampedArray(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isUint16Array(value)`", + "type": "method", + "name": "isUint16Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint16Array instance.

      \n
      util.types.isUint16Array(new ArrayBuffer());  // Returns false\nutil.types.isUint16Array(new Uint16Array());  // Returns true\nutil.types.isUint16Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isUint32Array(value)`", + "type": "method", + "name": "isUint32Array", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in Uint32Array instance.

      \n
      util.types.isUint32Array(new ArrayBuffer());  // Returns false\nutil.types.isUint32Array(new Uint32Array());  // Returns true\nutil.types.isUint32Array(new Float64Array());  // Returns false\n
      " + }, + { + "textRaw": "`util.types.isWeakMap(value)`", + "type": "method", + "name": "isWeakMap", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in WeakMap instance.

      \n
      util.types.isWeakMap(new WeakMap());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isWeakSet(value)`", + "type": "method", + "name": "isWeakSet", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in WeakSet instance.

      \n
      util.types.isWeakSet(new WeakSet());  // Returns true\n
      " + }, + { + "textRaw": "`util.types.isWebAssemblyCompiledModule(value)`", + "type": "method", + "name": "isWebAssemblyCompiledModule", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the value is a built-in WebAssembly.Module instance.

      \n
      const module = new WebAssembly.Module(wasmBuffer);\nutil.types.isWebAssemblyCompiledModule(module);  // Returns true\n
      " + } + ] + } + ], + "modules": [ + { + "textRaw": "Deprecated APIs", + "name": "deprecated_apis", + "desc": "

      The following APIs are deprecated and should no longer be used. Existing\napplications and modules should be updated to find alternative approaches.

      ", + "methods": [ + { + "textRaw": "`util._extend(target, source)`", + "type": "method", + "name": "_extend", + "meta": { + "added": [ + "v0.7.5" + ], + "deprecated": [ + "v6.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Object.assign()`][] instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`target` {Object}", + "name": "target", + "type": "Object" + }, + { + "textRaw": "`source` {Object}", + "name": "source", + "type": "Object" + } + ] + } + ], + "desc": "

      The util._extend() method was never intended to be used outside of internal\nNode.js modules. The community found and used it anyway.

      \n

      It is deprecated and should not be used in new code. JavaScript comes with very\nsimilar built-in functionality through Object.assign().

      " + }, + { + "textRaw": "`util.isArray(object)`", + "type": "method", + "name": "isArray", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Array.isArray()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Alias for Array.isArray().

      \n

      Returns true if the given object is an Array. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isArray([]);\n// Returns: true\nutil.isArray(new Array());\n// Returns: true\nutil.isArray({});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isBoolean(object)`", + "type": "method", + "name": "isBoolean", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'boolean'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Boolean. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isBoolean(1);\n// Returns: false\nutil.isBoolean(0);\n// Returns: false\nutil.isBoolean(false);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isBuffer(object)`", + "type": "method", + "name": "isBuffer", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`Buffer.isBuffer()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Buffer. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isBuffer({ length: 0 });\n// Returns: false\nutil.isBuffer([]);\n// Returns: false\nutil.isBuffer(Buffer.from('hello world'));\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isDate(object)`", + "type": "method", + "name": "isDate", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`util.types.isDate()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Date. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isDate(new Date());\n// Returns: true\nutil.isDate(Date());\n// false (without 'new' returns a String)\nutil.isDate({});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isError(object)`", + "type": "method", + "name": "isError", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`util.types.isNativeError()`][] instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is an Error. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nutil.isError(new Error());\n// Returns: true\nutil.isError(new TypeError());\n// Returns: true\nutil.isError({ name: 'Error', message: 'an error occurred' });\n// Returns: false\n
      \n

      This method relies on Object.prototype.toString() behavior. It is\npossible to obtain an incorrect result when the object argument manipulates\n@@toStringTag.

      \n
      const util = require('util');\nconst obj = { name: 'Error', message: 'an error occurred' };\n\nutil.isError(obj);\n// Returns: false\nobj[Symbol.toStringTag] = 'Error';\nutil.isError(obj);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isFunction(object)`", + "type": "method", + "name": "isFunction", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'function'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Function. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nfunction Foo() {}\nconst Bar = () => {};\n\nutil.isFunction({});\n// Returns: false\nutil.isFunction(Foo);\n// Returns: true\nutil.isFunction(Bar);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isNull(object)`", + "type": "method", + "name": "isNull", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `value === null` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is strictly null. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nutil.isNull(0);\n// Returns: false\nutil.isNull(undefined);\n// Returns: false\nutil.isNull(null);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isNullOrUndefined(object)`", + "type": "method", + "name": "isNullOrUndefined", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use\n`value === undefined || value === null` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is null or undefined. Otherwise,\nreturns false.

      \n
      const util = require('util');\n\nutil.isNullOrUndefined(0);\n// Returns: false\nutil.isNullOrUndefined(undefined);\n// Returns: true\nutil.isNullOrUndefined(null);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isNumber(object)`", + "type": "method", + "name": "isNumber", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'number'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Number. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isNumber(false);\n// Returns: false\nutil.isNumber(Infinity);\n// Returns: true\nutil.isNumber(0);\n// Returns: true\nutil.isNumber(NaN);\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isObject(object)`", + "type": "method", + "name": "isObject", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated:\nUse `value !== null && typeof value === 'object'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is strictly an Object and not a\nFunction (even though functions are objects in JavaScript).\nOtherwise, returns false.

      \n
      const util = require('util');\n\nutil.isObject(5);\n// Returns: false\nutil.isObject(null);\n// Returns: false\nutil.isObject({});\n// Returns: true\nutil.isObject(() => {});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isPrimitive(object)`", + "type": "method", + "name": "isPrimitive", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use\n`(typeof value !== 'object' && typeof value !== 'function') || value === null`\ninstead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a primitive type. Otherwise, returns\nfalse.

      \n
      const util = require('util');\n\nutil.isPrimitive(5);\n// Returns: true\nutil.isPrimitive('foo');\n// Returns: true\nutil.isPrimitive(false);\n// Returns: true\nutil.isPrimitive(null);\n// Returns: true\nutil.isPrimitive(undefined);\n// Returns: true\nutil.isPrimitive({});\n// Returns: false\nutil.isPrimitive(() => {});\n// Returns: false\nutil.isPrimitive(/^$/);\n// Returns: false\nutil.isPrimitive(new Date());\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isRegExp(object)`", + "type": "method", + "name": "isRegExp", + "meta": { + "added": [ + "v0.6.0" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a RegExp. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isRegExp(/some regexp/);\n// Returns: true\nutil.isRegExp(new RegExp('another regexp'));\n// Returns: true\nutil.isRegExp({});\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isString(object)`", + "type": "method", + "name": "isString", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'string'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a string. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isString('');\n// Returns: true\nutil.isString('foo');\n// Returns: true\nutil.isString(String('foo'));\n// Returns: true\nutil.isString(5);\n// Returns: false\n
      " + }, + { + "textRaw": "`util.isSymbol(object)`", + "type": "method", + "name": "isSymbol", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `typeof value === 'symbol'` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is a Symbol. Otherwise, returns false.

      \n
      const util = require('util');\n\nutil.isSymbol(5);\n// Returns: false\nutil.isSymbol('foo');\n// Returns: false\nutil.isSymbol(Symbol('foo'));\n// Returns: true\n
      " + }, + { + "textRaw": "`util.isUndefined(object)`", + "type": "method", + "name": "isUndefined", + "meta": { + "added": [ + "v0.11.5" + ], + "deprecated": [ + "v4.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use `value === undefined` instead.", + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {any}", + "name": "object", + "type": "any" + } + ] + } + ], + "desc": "

      Returns true if the given object is undefined. Otherwise, returns false.

      \n
      const util = require('util');\n\nconst foo = undefined;\nutil.isUndefined(5);\n// Returns: false\nutil.isUndefined(foo);\n// Returns: true\nutil.isUndefined(null);\n// Returns: false\n
      " + }, + { + "textRaw": "`util.log(string)`", + "type": "method", + "name": "log", + "meta": { + "added": [ + "v0.3.0" + ], + "deprecated": [ + "v6.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use a third party module instead.", + "signatures": [ + { + "params": [ + { + "textRaw": "`string` {string}", + "name": "string", + "type": "string" + } + ] + } + ], + "desc": "

      The util.log() method prints the given string to stdout with an included\ntimestamp.

      \n
      const util = require('util');\n\nutil.log('Timestamped message.');\n
      " + } + ], + "type": "module", + "displayName": "Deprecated APIs" + } + ], + "type": "module", + "displayName": "Util" + } + ] +} \ No newline at end of file diff --git a/doc/api/v8.html b/doc/api/v8.html new file mode 100644 index 0000000000000000000000000000000000000000..a8e8a22d6225cc1c45ea585ebf3a12b2e15fa307 --- /dev/null +++ b/doc/api/v8.html @@ -0,0 +1,638 @@ + + + + + + + V8 | Node.js v12.22.7 Documentation + + + + + + +
      + + +
      +
      +

      Node.js v12.22.7 Documentation

      + +
      +
      + + + +
      +

      V8#

      + +

      Source Code: lib/v8.js

      +

      The v8 module exposes APIs that are specific to the version of V8 +built into the Node.js binary. It can be accessed using:

      +
      const v8 = require('v8');
      +

      The APIs and implementation are subject to change at any time.

      +

      v8.cachedDataVersionTag()#

      + + +

      Returns an integer representing a "version tag" derived from the V8 version, +command line flags and detected CPU features. This is useful for determining +whether a vm.Script cachedData buffer is compatible with this instance +of V8.

      +

      v8.getHeapSpaceStatistics()#

      + + +

      Returns statistics about the V8 heap spaces, i.e. the segments which make up +the V8 heap. Neither the ordering of heap spaces, nor the availability of a +heap space can be guaranteed as the statistics are provided via the V8 +GetHeapSpaceStatistics function and may change from one V8 version to the +next.

      +

      The value returned is an array of objects containing the following properties:

      + +
      [
      +  {
      +    "space_name": "new_space",
      +    "space_size": 2063872,
      +    "space_used_size": 951112,
      +    "space_available_size": 80824,
      +    "physical_space_size": 2063872
      +  },
      +  {
      +    "space_name": "old_space",
      +    "space_size": 3090560,
      +    "space_used_size": 2493792,
      +    "space_available_size": 0,
      +    "physical_space_size": 3090560
      +  },
      +  {
      +    "space_name": "code_space",
      +    "space_size": 1260160,
      +    "space_used_size": 644256,
      +    "space_available_size": 960,
      +    "physical_space_size": 1260160
      +  },
      +  {
      +    "space_name": "map_space",
      +    "space_size": 1094160,
      +    "space_used_size": 201608,
      +    "space_available_size": 0,
      +    "physical_space_size": 1094160
      +  },
      +  {
      +    "space_name": "large_object_space",
      +    "space_size": 0,
      +    "space_used_size": 0,
      +    "space_available_size": 1490980608,
      +    "physical_space_size": 0
      +  }
      +]
      +

      v8.getHeapSnapshot()#

      + + +

      Generates a snapshot of the current V8 heap and returns a Readable +Stream that may be used to read the JSON serialized representation. +This JSON stream format is intended to be used with tools such as +Chrome DevTools. The JSON schema is undocumented and specific to the +V8 engine, and may change from one version of V8 to the next.

      +
      const stream = v8.getHeapSnapshot();
      +stream.pipe(process.stdout);
      +

      v8.getHeapStatistics()#

      + + +

      Returns an object with the following properties:

      + +

      does_zap_garbage is a 0/1 boolean, which signifies whether the +--zap_code_space option is enabled or not. This makes V8 overwrite heap +garbage with a bit pattern. The RSS footprint (resident memory set) gets bigger +because it continuously touches all heap pages and that makes them less likely +to get swapped out by the operating system.

      +

      number_of_native_contexts The value of native_context is the number of the +top-level contexts currently active. Increase of this number over time indicates +a memory leak.

      +

      number_of_detached_contexts The value of detached_context is the number +of contexts that were detached and not yet garbage collected. This number +being non-zero indicates a potential memory leak.

      + +
      {
      +  total_heap_size: 7326976,
      +  total_heap_size_executable: 4194304,
      +  total_physical_size: 7326976,
      +  total_available_size: 1152656,
      +  used_heap_size: 3476208,
      +  heap_size_limit: 1535115264,
      +  malloced_memory: 16384,
      +  peak_malloced_memory: 1127496,
      +  does_zap_garbage: 0,
      +  number_of_native_contexts: 1,
      +  number_of_detached_contexts: 0
      +}
      +

      v8.getHeapCodeStatistics()#

      + + +

      Returns an object with the following properties:

      + + +
      {
      +  code_and_metadata_size: 212208,
      +  bytecode_and_metadata_size: 161368,
      +  external_script_source_size: 1410794
      +}
      +

      v8.setFlagsFromString(flags)#

      + + +

      The v8.setFlagsFromString() method can be used to programmatically set +V8 command line flags. This method should be used with care. Changing settings +after the VM has started may result in unpredictable behavior, including +crashes and data loss; or it may simply do nothing.

      +

      The V8 options available for a version of Node.js may be determined by running +node --v8-options.

      +

      Usage:

      +
      // Print GC events to stdout for one minute.
      +const v8 = require('v8');
      +v8.setFlagsFromString('--trace_gc');
      +setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
      +

      v8.takeCoverage()#

      + +

      The v8.takeCoverage() method allows the user to write the coverage started by +NODE_V8_COVERAGE to disk on demand. This method can be invoked multiple +times during the lifetime of the process, each time the execution counter will +be reset and a new coverage report will be written to the directory specified +by NODE_V8_COVERAGE.

      +

      When the process is about to exit, one last coverage will still be written to +disk, unless v8.stopCoverage() is invoked before the process exits.

      +

      v8.stopCoverage()#

      + +

      The v8.stopCoverage() method allows the user to stop the coverage collection +started by NODE_V8_COVERAGE, so that V8 can release the execution count +records and optimize code. This can be used in conjunction with +v8.takeCoverage() if the user wants to collect the coverage on demand.

      +

      v8.writeHeapSnapshot([filename])#

      + +
        +
      • filename <string> The file path where the V8 heap snapshot is to be +saved. If not specified, a file name with the pattern +'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot' will be +generated, where {pid} will be the PID of the Node.js process, +{thread_id} will be 0 when writeHeapSnapshot() is called from +the main Node.js thread or the id of a worker thread.
      • +
      • Returns: <string> The filename where the snapshot was saved.
      • +
      +

      Generates a snapshot of the current V8 heap and writes it to a JSON +file. This file is intended to be used with tools such as Chrome +DevTools. The JSON schema is undocumented and specific to the V8 +engine, and may change from one version of V8 to the next.

      +

      A heap snapshot is specific to a single V8 isolate. When using +worker threads, a heap snapshot generated from the main thread will +not contain any information about the workers, and vice versa.

      +
      const { writeHeapSnapshot } = require('v8');
      +const {
      +  Worker,
      +  isMainThread,
      +  parentPort
      +} = require('worker_threads');
      +
      +if (isMainThread) {
      +  const worker = new Worker(__filename);
      +
      +  worker.once('message', (filename) => {
      +    console.log(`worker heapdump: ${filename}`);
      +    // Now get a heapdump for the main thread.
      +    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
      +  });
      +
      +  // Tell the worker to create a heapdump.
      +  worker.postMessage('heapdump');
      +} else {
      +  parentPort.once('message', (message) => {
      +    if (message === 'heapdump') {
      +      // Generate a heapdump for the worker
      +      // and return the filename to the parent.
      +      parentPort.postMessage(writeHeapSnapshot());
      +    }
      +  });
      +}
      +

      Serialization API#

      +

      The serialization API provides means of serializing JavaScript values in a way +that is compatible with the HTML structured clone algorithm.

      +

      The format is backward-compatible (i.e. safe to store to disk). +Equal JavaScript values may result in different serialized output.

      +

      v8.serialize(value)#

      + + +

      Uses a DefaultSerializer to serialize value into a buffer.

      +

      v8.deserialize(buffer)#

      + + +

      Uses a DefaultDeserializer with default options to read a JS value +from a buffer.

      +

      Class: v8.Serializer#

      + +

      new Serializer()#

      +

      Creates a new Serializer object.

      +

      serializer.writeHeader()#

      +

      Writes out a header, which includes the serialization format version.

      +

      serializer.writeValue(value)#

      + +

      Serializes a JavaScript value and adds the serialized representation to the +internal buffer.

      +

      This throws an error if value cannot be serialized.

      +

      serializer.releaseBuffer()#

      + +

      Returns the stored internal buffer. This serializer should not be used once +the buffer is released. Calling this method results in undefined behavior +if a previous write has failed.

      +

      serializer.transferArrayBuffer(id, arrayBuffer)#

      + +

      Marks an ArrayBuffer as having its contents transferred out of band. +Pass the corresponding ArrayBuffer in the deserializing context to +deserializer.transferArrayBuffer().

      +

      serializer.writeUint32(value)#

      + +

      Write a raw 32-bit unsigned integer. +For use inside of a custom serializer._writeHostObject().

      +

      serializer.writeUint64(hi, lo)#

      + +

      Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. +For use inside of a custom serializer._writeHostObject().

      +

      serializer.writeDouble(value)#

      + +

      Write a JS number value. +For use inside of a custom serializer._writeHostObject().

      +

      serializer.writeRawBytes(buffer)#

      + +

      Write raw bytes into the serializer’s internal buffer. The deserializer +will require a way to compute the length of the buffer. +For use inside of a custom serializer._writeHostObject().

      +

      serializer._writeHostObject(object)#

      + +

      This method is called to write some kind of host object, i.e. an object created +by native C++ bindings. If it is not possible to serialize object, a suitable +exception should be thrown.

      +

      This method is not present on the Serializer class itself but can be provided +by subclasses.

      +

      serializer._getDataCloneError(message)#

      + +

      This method is called to generate error objects that will be thrown when an +object can not be cloned.

      +

      This method defaults to the Error constructor and can be overridden on +subclasses.

      +

      serializer._getSharedArrayBufferId(sharedArrayBuffer)#

      + +

      This method is called when the serializer is going to serialize a +SharedArrayBuffer object. It must return an unsigned 32-bit integer ID for +the object, using the same ID if this SharedArrayBuffer has already been +serialized. When deserializing, this ID will be passed to +deserializer.transferArrayBuffer().

      +

      If the object cannot be serialized, an exception should be thrown.

      +

      This method is not present on the Serializer class itself but can be provided +by subclasses.

      +

      serializer._setTreatArrayBufferViewsAsHostObjects(flag)#

      + +

      Indicate whether to treat TypedArray and DataView objects as +host objects, i.e. pass them to serializer._writeHostObject().

      +

      Class: v8.Deserializer#

      + +

      new Deserializer(buffer)#

      + +

      Creates a new Deserializer object.

      +

      deserializer.readHeader()#

      +

      Reads and validates a header (including the format version). +May, for example, reject an invalid or unsupported wire format. In that case, +an Error is thrown.

      +

      deserializer.readValue()#

      +

      Deserializes a JavaScript value from the buffer and returns it.

      +

      deserializer.transferArrayBuffer(id, arrayBuffer)#

      + +

      Marks an ArrayBuffer as having its contents transferred out of band. +Pass the corresponding ArrayBuffer in the serializing context to +serializer.transferArrayBuffer() (or return the id from +serializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).

      +

      deserializer.getWireFormatVersion()#

      + +

      Reads the underlying wire format version. Likely mostly to be useful to +legacy code reading old wire format versions. May not be called before +.readHeader().

      +

      deserializer.readUint32()#

      + +

      Read a raw 32-bit unsigned integer and return it. +For use inside of a custom deserializer._readHostObject().

      +

      deserializer.readUint64()#

      + +

      Read a raw 64-bit unsigned integer and return it as an array [hi, lo] +with two 32-bit unsigned integer entries. +For use inside of a custom deserializer._readHostObject().

      +

      deserializer.readDouble()#

      + +

      Read a JS number value. +For use inside of a custom deserializer._readHostObject().

      +

      deserializer.readRawBytes(length)#

      + +

      Read raw bytes from the deserializer’s internal buffer. The length parameter +must correspond to the length of the buffer that was passed to +serializer.writeRawBytes(). +For use inside of a custom deserializer._readHostObject().

      +

      deserializer._readHostObject()#

      +

      This method is called to read some kind of host object, i.e. an object that is +created by native C++ bindings. If it is not possible to deserialize the data, +a suitable exception should be thrown.

      +

      This method is not present on the Deserializer class itself but can be +provided by subclasses.

      +

      Class: v8.DefaultSerializer#

      + +

      A subclass of Serializer that serializes TypedArray +(in particular Buffer) and DataView objects as host objects, and only +stores the part of their underlying ArrayBuffers that they are referring to.

      +

      Class: v8.DefaultDeserializer#

      + +

      A subclass of Deserializer corresponding to the format written by +DefaultSerializer.

      + +
      +
      +
      + + diff --git a/doc/api/v8.json b/doc/api/v8.json new file mode 100644 index 0000000000000000000000000000000000000000..98798881d7c3eb217046ad6e5a34c790436dba61 --- /dev/null +++ b/doc/api/v8.json @@ -0,0 +1,718 @@ +{ + "type": "module", + "source": "doc/api/v8.md", + "modules": [ + { + "textRaw": "V8", + "name": "v8", + "introduced_in": "v4.0.0", + "desc": "

      Source Code: lib/v8.js

      \n

      The v8 module exposes APIs that are specific to the version of V8\nbuilt into the Node.js binary. It can be accessed using:

      \n
      const v8 = require('v8');\n
      \n

      The APIs and implementation are subject to change at any time.

      ", + "methods": [ + { + "textRaw": "`v8.cachedDataVersionTag()`", + "type": "method", + "name": "cachedDataVersionTag", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Returns an integer representing a \"version tag\" derived from the V8 version,\ncommand line flags and detected CPU features. This is useful for determining\nwhether a vm.Script cachedData buffer is compatible with this instance\nof V8.

      " + }, + { + "textRaw": "`v8.getHeapSpaceStatistics()`", + "type": "method", + "name": "getHeapSpaceStatistics", + "meta": { + "added": [ + "v6.0.0" + ], + "changes": [ + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10186", + "description": "Support values exceeding the 32-bit unsigned integer range." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object[]}", + "name": "return", + "type": "Object[]" + }, + "params": [] + } + ], + "desc": "

      Returns statistics about the V8 heap spaces, i.e. the segments which make up\nthe V8 heap. Neither the ordering of heap spaces, nor the availability of a\nheap space can be guaranteed as the statistics are provided via the V8\nGetHeapSpaceStatistics function and may change from one V8 version to the\nnext.

      \n

      The value returned is an array of objects containing the following properties:

      \n\n
      [\n  {\n    \"space_name\": \"new_space\",\n    \"space_size\": 2063872,\n    \"space_used_size\": 951112,\n    \"space_available_size\": 80824,\n    \"physical_space_size\": 2063872\n  },\n  {\n    \"space_name\": \"old_space\",\n    \"space_size\": 3090560,\n    \"space_used_size\": 2493792,\n    \"space_available_size\": 0,\n    \"physical_space_size\": 3090560\n  },\n  {\n    \"space_name\": \"code_space\",\n    \"space_size\": 1260160,\n    \"space_used_size\": 644256,\n    \"space_available_size\": 960,\n    \"physical_space_size\": 1260160\n  },\n  {\n    \"space_name\": \"map_space\",\n    \"space_size\": 1094160,\n    \"space_used_size\": 201608,\n    \"space_available_size\": 0,\n    \"physical_space_size\": 1094160\n  },\n  {\n    \"space_name\": \"large_object_space\",\n    \"space_size\": 0,\n    \"space_used_size\": 0,\n    \"space_available_size\": 1490980608,\n    \"physical_space_size\": 0\n  }\n]\n
      " + }, + { + "textRaw": "`v8.getHeapSnapshot()`", + "type": "method", + "name": "getHeapSnapshot", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {stream.Readable} A Readable Stream containing the V8 heap snapshot", + "name": "return", + "type": "stream.Readable", + "desc": "A Readable Stream containing the V8 heap snapshot" + }, + "params": [] + } + ], + "desc": "

      Generates a snapshot of the current V8 heap and returns a Readable\nStream that may be used to read the JSON serialized representation.\nThis JSON stream format is intended to be used with tools such as\nChrome DevTools. The JSON schema is undocumented and specific to the\nV8 engine, and may change from one version of V8 to the next.

      \n
      const stream = v8.getHeapSnapshot();\nstream.pipe(process.stdout);\n
      " + }, + { + "textRaw": "`v8.getHeapStatistics()`", + "type": "method", + "name": "getHeapStatistics", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [ + { + "version": "v7.2.0", + "pr-url": "https://github.com/nodejs/node/pull/8610", + "description": "Added `malloced_memory`, `peak_malloced_memory`, and `does_zap_garbage`." + }, + { + "version": "v7.5.0", + "pr-url": "https://github.com/nodejs/node/pull/10186", + "description": "Support values exceeding the 32-bit unsigned integer range." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object with the following properties:

      \n\n

      does_zap_garbage is a 0/1 boolean, which signifies whether the\n--zap_code_space option is enabled or not. This makes V8 overwrite heap\ngarbage with a bit pattern. The RSS footprint (resident memory set) gets bigger\nbecause it continuously touches all heap pages and that makes them less likely\nto get swapped out by the operating system.

      \n

      number_of_native_contexts The value of native_context is the number of the\ntop-level contexts currently active. Increase of this number over time indicates\na memory leak.

      \n

      number_of_detached_contexts The value of detached_context is the number\nof contexts that were detached and not yet garbage collected. This number\nbeing non-zero indicates a potential memory leak.

      \n\n
      {\n  total_heap_size: 7326976,\n  total_heap_size_executable: 4194304,\n  total_physical_size: 7326976,\n  total_available_size: 1152656,\n  used_heap_size: 3476208,\n  heap_size_limit: 1535115264,\n  malloced_memory: 16384,\n  peak_malloced_memory: 1127496,\n  does_zap_garbage: 0,\n  number_of_native_contexts: 1,\n  number_of_detached_contexts: 0\n}\n
      " + }, + { + "textRaw": "`v8.getHeapCodeStatistics()`", + "type": "method", + "name": "getHeapCodeStatistics", + "meta": { + "added": [ + "v12.8.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object}", + "name": "return", + "type": "Object" + }, + "params": [] + } + ], + "desc": "

      Returns an object with the following properties:

      \n\n\n
      {\n  code_and_metadata_size: 212208,\n  bytecode_and_metadata_size: 161368,\n  external_script_source_size: 1410794\n}\n
      " + }, + { + "textRaw": "`v8.setFlagsFromString(flags)`", + "type": "method", + "name": "setFlagsFromString", + "meta": { + "added": [ + "v1.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`flags` {string}", + "name": "flags", + "type": "string" + } + ] + } + ], + "desc": "

      The v8.setFlagsFromString() method can be used to programmatically set\nV8 command line flags. This method should be used with care. Changing settings\nafter the VM has started may result in unpredictable behavior, including\ncrashes and data loss; or it may simply do nothing.

      \n

      The V8 options available for a version of Node.js may be determined by running\nnode --v8-options.

      \n

      Usage:

      \n
      // Print GC events to stdout for one minute.\nconst v8 = require('v8');\nv8.setFlagsFromString('--trace_gc');\nsetTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);\n
      " + }, + { + "textRaw": "`v8.takeCoverage()`", + "type": "method", + "name": "takeCoverage", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The v8.takeCoverage() method allows the user to write the coverage started by\nNODE_V8_COVERAGE to disk on demand. This method can be invoked multiple\ntimes during the lifetime of the process, each time the execution counter will\nbe reset and a new coverage report will be written to the directory specified\nby NODE_V8_COVERAGE.

      \n

      When the process is about to exit, one last coverage will still be written to\ndisk, unless v8.stopCoverage() is invoked before the process exits.

      " + }, + { + "textRaw": "`v8.stopCoverage()`", + "type": "method", + "name": "stopCoverage", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

      The v8.stopCoverage() method allows the user to stop the coverage collection\nstarted by NODE_V8_COVERAGE, so that V8 can release the execution count\nrecords and optimize code. This can be used in conjunction with\nv8.takeCoverage() if the user wants to collect the coverage on demand.

      " + }, + { + "textRaw": "`v8.writeHeapSnapshot([filename])`", + "type": "method", + "name": "writeHeapSnapshot", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {string} The filename where the snapshot was saved.", + "name": "return", + "type": "string", + "desc": "The filename where the snapshot was saved." + }, + "params": [ + { + "textRaw": "`filename` {string} The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread.", + "name": "filename", + "type": "string", + "desc": "The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread." + } + ] + } + ], + "desc": "

      Generates a snapshot of the current V8 heap and writes it to a JSON\nfile. This file is intended to be used with tools such as Chrome\nDevTools. The JSON schema is undocumented and specific to the V8\nengine, and may change from one version of V8 to the next.

      \n

      A heap snapshot is specific to a single V8 isolate. When using\nworker threads, a heap snapshot generated from the main thread will\nnot contain any information about the workers, and vice versa.

      \n
      const { writeHeapSnapshot } = require('v8');\nconst {\n  Worker,\n  isMainThread,\n  parentPort\n} = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n\n  worker.once('message', (filename) => {\n    console.log(`worker heapdump: ${filename}`);\n    // Now get a heapdump for the main thread.\n    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);\n  });\n\n  // Tell the worker to create a heapdump.\n  worker.postMessage('heapdump');\n} else {\n  parentPort.once('message', (message) => {\n    if (message === 'heapdump') {\n      // Generate a heapdump for the worker\n      // and return the filename to the parent.\n      parentPort.postMessage(writeHeapSnapshot());\n    }\n  });\n}\n
      " + } + ], + "modules": [ + { + "textRaw": "Serialization API", + "name": "serialization_api", + "desc": "

      The serialization API provides means of serializing JavaScript values in a way\nthat is compatible with the HTML structured clone algorithm.

      \n

      The format is backward-compatible (i.e. safe to store to disk).\nEqual JavaScript values may result in different serialized output.

      ", + "methods": [ + { + "textRaw": "`v8.serialize(value)`", + "type": "method", + "name": "serialize", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Uses a DefaultSerializer to serialize value into a buffer.

      " + }, + { + "textRaw": "`v8.deserialize(buffer)`", + "type": "method", + "name": "deserialize", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serialize()`][].", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A buffer returned by [`serialize()`][]." + } + ] + } + ], + "desc": "

      Uses a DefaultDeserializer with default options to read a JS value\nfrom a buffer.

      " + } + ], + "classes": [ + { + "textRaw": "Class: `v8.Serializer`", + "type": "class", + "name": "v8.Serializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "methods": [ + { + "textRaw": "`serializer.writeHeader()`", + "type": "method", + "name": "writeHeader", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Writes out a header, which includes the serialization format version.

      " + }, + { + "textRaw": "`serializer.writeValue(value)`", + "type": "method", + "name": "writeValue", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + } + ] + } + ], + "desc": "

      Serializes a JavaScript value and adds the serialized representation to the\ninternal buffer.

      \n

      This throws an error if value cannot be serialized.

      " + }, + { + "textRaw": "`serializer.releaseBuffer()`", + "type": "method", + "name": "releaseBuffer", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [] + } + ], + "desc": "

      Returns the stored internal buffer. This serializer should not be used once\nthe buffer is released. Calling this method results in undefined behavior\nif a previous write has failed.

      " + }, + { + "textRaw": "`serializer.transferArrayBuffer(id, arrayBuffer)`", + "type": "method", + "name": "transferArrayBuffer", + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {integer} A 32-bit unsigned integer.", + "name": "id", + "type": "integer", + "desc": "A 32-bit unsigned integer." + }, + { + "textRaw": "`arrayBuffer` {ArrayBuffer} An `ArrayBuffer` instance.", + "name": "arrayBuffer", + "type": "ArrayBuffer", + "desc": "An `ArrayBuffer` instance." + } + ] + } + ], + "desc": "

      Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the deserializing context to\ndeserializer.transferArrayBuffer().

      " + }, + { + "textRaw": "`serializer.writeUint32(value)`", + "type": "method", + "name": "writeUint32", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {integer}", + "name": "value", + "type": "integer" + } + ] + } + ], + "desc": "

      Write a raw 32-bit unsigned integer.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer.writeUint64(hi, lo)`", + "type": "method", + "name": "writeUint64", + "signatures": [ + { + "params": [ + { + "textRaw": "`hi` {integer}", + "name": "hi", + "type": "integer" + }, + { + "textRaw": "`lo` {integer}", + "name": "lo", + "type": "integer" + } + ] + } + ], + "desc": "

      Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer.writeDouble(value)`", + "type": "method", + "name": "writeDouble", + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {number}", + "name": "value", + "type": "number" + } + ] + } + ], + "desc": "

      Write a JS number value.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer.writeRawBytes(buffer)`", + "type": "method", + "name": "writeRawBytes", + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView" + } + ] + } + ], + "desc": "

      Write raw bytes into the serializer’s internal buffer. The deserializer\nwill require a way to compute the length of the buffer.\nFor use inside of a custom serializer._writeHostObject().

      " + }, + { + "textRaw": "`serializer._writeHostObject(object)`", + "type": "method", + "name": "_writeHostObject", + "signatures": [ + { + "params": [ + { + "textRaw": "`object` {Object}", + "name": "object", + "type": "Object" + } + ] + } + ], + "desc": "

      This method is called to write some kind of host object, i.e. an object created\nby native C++ bindings. If it is not possible to serialize object, a suitable\nexception should be thrown.

      \n

      This method is not present on the Serializer class itself but can be provided\nby subclasses.

      " + }, + { + "textRaw": "`serializer._getDataCloneError(message)`", + "type": "method", + "name": "_getDataCloneError", + "signatures": [ + { + "params": [ + { + "textRaw": "`message` {string}", + "name": "message", + "type": "string" + } + ] + } + ], + "desc": "

      This method is called to generate error objects that will be thrown when an\nobject can not be cloned.

      \n

      This method defaults to the Error constructor and can be overridden on\nsubclasses.

      " + }, + { + "textRaw": "`serializer._getSharedArrayBufferId(sharedArrayBuffer)`", + "type": "method", + "name": "_getSharedArrayBufferId", + "signatures": [ + { + "params": [ + { + "textRaw": "`sharedArrayBuffer` {SharedArrayBuffer}", + "name": "sharedArrayBuffer", + "type": "SharedArrayBuffer" + } + ] + } + ], + "desc": "

      This method is called when the serializer is going to serialize a\nSharedArrayBuffer object. It must return an unsigned 32-bit integer ID for\nthe object, using the same ID if this SharedArrayBuffer has already been\nserialized. When deserializing, this ID will be passed to\ndeserializer.transferArrayBuffer().

      \n

      If the object cannot be serialized, an exception should be thrown.

      \n

      This method is not present on the Serializer class itself but can be provided\nby subclasses.

      " + }, + { + "textRaw": "`serializer._setTreatArrayBufferViewsAsHostObjects(flag)`", + "type": "method", + "name": "_setTreatArrayBufferViewsAsHostObjects", + "signatures": [ + { + "params": [ + { + "textRaw": "`flag` {boolean} **Default:** `false`", + "name": "flag", + "type": "boolean", + "default": "`false`" + } + ] + } + ], + "desc": "

      Indicate whether to treat TypedArray and DataView objects as\nhost objects, i.e. pass them to serializer._writeHostObject().

      " + } + ], + "signatures": [ + { + "params": [], + "desc": "

      Creates a new Serializer object.

      " + } + ] + }, + { + "textRaw": "Class: `v8.Deserializer`", + "type": "class", + "name": "v8.Deserializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "methods": [ + { + "textRaw": "`deserializer.readHeader()`", + "type": "method", + "name": "readHeader", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Reads and validates a header (including the format version).\nMay, for example, reject an invalid or unsupported wire format. In that case,\nan Error is thrown.

      " + }, + { + "textRaw": "`deserializer.readValue()`", + "type": "method", + "name": "readValue", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      Deserializes a JavaScript value from the buffer and returns it.

      " + }, + { + "textRaw": "`deserializer.transferArrayBuffer(id, arrayBuffer)`", + "type": "method", + "name": "transferArrayBuffer", + "signatures": [ + { + "params": [ + { + "textRaw": "`id` {integer} A 32-bit unsigned integer.", + "name": "id", + "type": "integer", + "desc": "A 32-bit unsigned integer." + }, + { + "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An `ArrayBuffer` instance.", + "name": "arrayBuffer", + "type": "ArrayBuffer|SharedArrayBuffer", + "desc": "An `ArrayBuffer` instance." + } + ] + } + ], + "desc": "

      Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the serializing context to\nserializer.transferArrayBuffer() (or return the id from\nserializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).

      " + }, + { + "textRaw": "`deserializer.getWireFormatVersion()`", + "type": "method", + "name": "getWireFormatVersion", + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Reads the underlying wire format version. Likely mostly to be useful to\nlegacy code reading old wire format versions. May not be called before\n.readHeader().

      " + }, + { + "textRaw": "`deserializer.readUint32()`", + "type": "method", + "name": "readUint32", + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer}", + "name": "return", + "type": "integer" + }, + "params": [] + } + ], + "desc": "

      Read a raw 32-bit unsigned integer and return it.\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer.readUint64()`", + "type": "method", + "name": "readUint64", + "signatures": [ + { + "return": { + "textRaw": "Returns: {integer[]}", + "name": "return", + "type": "integer[]" + }, + "params": [] + } + ], + "desc": "

      Read a raw 64-bit unsigned integer and return it as an array [hi, lo]\nwith two 32-bit unsigned integer entries.\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer.readDouble()`", + "type": "method", + "name": "readDouble", + "signatures": [ + { + "return": { + "textRaw": "Returns: {number}", + "name": "return", + "type": "number" + }, + "params": [] + } + ], + "desc": "

      Read a JS number value.\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer.readRawBytes(length)`", + "type": "method", + "name": "readRawBytes", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [ + { + "textRaw": "`length` {integer}", + "name": "length", + "type": "integer" + } + ] + } + ], + "desc": "

      Read raw bytes from the deserializer’s internal buffer. The length parameter\nmust correspond to the length of the buffer that was passed to\nserializer.writeRawBytes().\nFor use inside of a custom deserializer._readHostObject().

      " + }, + { + "textRaw": "`deserializer._readHostObject()`", + "type": "method", + "name": "_readHostObject", + "signatures": [ + { + "params": [] + } + ], + "desc": "

      This method is called to read some kind of host object, i.e. an object that is\ncreated by native C++ bindings. If it is not possible to deserialize the data,\na suitable exception should be thrown.

      \n

      This method is not present on the Deserializer class itself but can be\nprovided by subclasses.

      " + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serializer.releaseBuffer()`][].", + "name": "buffer", + "type": "Buffer|TypedArray|DataView", + "desc": "A buffer returned by [`serializer.releaseBuffer()`][]." + } + ], + "desc": "

      Creates a new Deserializer object.

      " + } + ] + }, + { + "textRaw": "Class: `v8.DefaultSerializer`", + "type": "class", + "name": "v8.DefaultSerializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      A subclass of Serializer that serializes TypedArray\n(in particular Buffer) and DataView objects as host objects, and only\nstores the part of their underlying ArrayBuffers that they are referring to.

      " + }, + { + "textRaw": "Class: `v8.DefaultDeserializer`", + "type": "class", + "name": "v8.DefaultDeserializer", + "meta": { + "added": [ + "v8.0.0" + ], + "changes": [] + }, + "desc": "

      A subclass of Deserializer corresponding to the format written by\nDefaultSerializer.

      " + } + ], + "type": "module", + "displayName": "Serialization API" + } + ], + "type": "module", + "displayName": "V8" + } + ] +} \ No newline at end of file diff --git a/doc/api/v8.md b/doc/api/v8.md index 921c4378199496c73e00c1104fe5d98500f39105..7f337aaf1568e37870322589adae9abb7b0c8913 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -214,6 +214,32 @@ v8.setFlagsFromString('--trace_gc'); setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); ``` +## `v8.takeCoverage()` + + + +The `v8.takeCoverage()` method allows the user to write the coverage started by +[`NODE_V8_COVERAGE`][] to disk on demand. This method can be invoked multiple +times during the lifetime of the process, each time the execution counter will +be reset and a new coverage report will be written to the directory specified +by [`NODE_V8_COVERAGE`][]. + +When the process is about to exit, one last coverage will still be written to +disk, unless [`v8.stopCoverage()`][] is invoked before the process exits. + +## `v8.stopCoverage()` + + + +The `v8.stopCoverage()` method allows the user to stop the coverage collection +started by [`NODE_V8_COVERAGE`][], so that V8 can release the execution count +records and optimize code. This can be used in conjunction with +`v8.takeCoverage()` if the user wants to collect the coverage on demand. + ## `v8.writeHeapSnapshot([filename])` +
      import foo from 'foo';
      +//              ^^^^^ the module specifier
      + +
    • +

      referencingModule <vm.Module> The Module object link() is called on.

      +
    • +
    • +

      Returns: <vm.Module> | <Promise>

      +
    • +
    + +
  • +

    Returns: <Promise>

    +
  • +
+

Link module dependencies. This method must be called before evaluation, and +can only be called once per module.

+

The function is expected to return a Module object or a Promise that +eventually resolves to a Module object. The returned Module must satisfy the +following two invariants:

+
    +
  • It must belong to the same context as the parent Module.
  • +
  • Its status must not be 'errored'.
  • +
+

If the returned Module's status is 'unlinked', this method will be +recursively called on the returned Module with the same provided linker +function.

+

link() returns a Promise that will either get resolved when all linking +instances resolve to a valid Module, or rejected if the linker function either +throws an exception or returns an invalid Module.

+

The linker function roughly corresponds to the implementation-defined +HostResolveImportedModule abstract operation in the ECMAScript +specification, with a few key differences:

+ +

The actual HostResolveImportedModule implementation used during module +linking is one that returns the modules linked during linking. Since at +that point all modules would have been fully linked already, the +HostResolveImportedModule implementation is fully synchronous per +specification.

+

Corresponds to the Link() concrete method field of Cyclic Module +Records in the ECMAScript specification.

+

module.namespace#

+ +

The namespace object of the module. This is only available after linking +(module.link()) has completed.

+

Corresponds to the GetModuleNamespace abstract operation in the ECMAScript +specification.

+

module.status#

+ +

The current status of the module. Will be one of:

+
    +
  • +

    'unlinked': module.link() has not yet been called.

    +
  • +
  • +

    'linking': module.link() has been called, but not all Promises returned +by the linker function have been resolved yet.

    +
  • +
  • +

    'linked': The module has been linked successfully, and all of its +dependencies are linked, but module.evaluate() has not yet been called.

    +
  • +
  • +

    'evaluating': The module is being evaluated through a module.evaluate() on +itself or a parent module.

    +
  • +
  • +

    'evaluated': The module has been successfully evaluated.

    +
  • +
  • +

    'errored': The module has been evaluated, but an exception was thrown.

    +
  • +
+

Other than 'errored', this status string corresponds to the specification's +Cyclic Module Record's [[Status]] field. 'errored' corresponds to +'evaluated' in the specification, but with [[EvaluationError]] set to a +value that is not undefined.

+

module.identifier#

+ +

The identifier of the current module, as set in the constructor.

+

Class: vm.SourceTextModule#

+ +

Stability: 1 - Experimental

+

This feature is only available with the --experimental-vm-modules command +flag enabled.

+ +

The vm.SourceTextModule class provides the Source Text Module Record as +defined in the ECMAScript specification.

+

new vm.SourceTextModule(code[, options])#

+
    +
  • code <string> JavaScript Module code to parse
  • +
  • options +
      +
    • identifier <string> String used in stack traces. +Default: 'vm:module(i)' where i is a context-specific ascending +index.
    • +
    • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. The code must be the same as the module from which this +cachedData was created.
    • +
    • context <Object> The contextified object as returned by the +vm.createContext() method, to compile and evaluate this Module in.
    • +
    • lineOffset <integer> Specifies the line number offset that is displayed +in stack traces produced by this Module. Default: 0.
    • +
    • columnOffset <integer> Specifies the column number offset that is +displayed in stack traces produced by this Module. Default: 0.
    • +
    • initializeImportMeta <Function> Called during evaluation of this Module +to initialize the import.meta. + +
    • +
    • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +
        +
      • specifier <string> specifier passed to import()
      • +
      • module <vm.Module>
      • +
      • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
      • +
      +
    • +
    +
  • +
+

Creates a new SourceTextModule instance.

+

Properties assigned to the import.meta object that are objects may +allow the module to access information outside the specified context. Use +vm.runInContext() to create objects in a specific context.

+
const vm = require('vm');
+
+const contextifiedObject = vm.createContext({ secret: 42 });
+
+(async () => {
+  const module = new vm.SourceTextModule(
+    'Object.getPrototypeOf(import.meta.prop).secret = secret;',
+    {
+      initializeImportMeta(meta) {
+        // Note: this object is created in the top context. As such,
+        // Object.getPrototypeOf(import.meta.prop) points to the
+        // Object.prototype in the top context rather than that in
+        // the contextified object.
+        meta.prop = {};
+      }
+    });
+  // Since module has no dependencies, the linker function will never be called.
+  await module.link(() => {});
+  await module.evaluate();
+
+  // Now, Object.prototype.secret will be equal to 42.
+  //
+  // To fix this problem, replace
+  //     meta.prop = {};
+  // above with
+  //     meta.prop = vm.runInContext('{}', contextifiedObject);
+})();
+

sourceTextModule.createCachedData()#

+ + +

Creates a code cache that can be used with the SourceTextModule constructor's +cachedData option. Returns a Buffer. This method may be called any number +of times before the module has been evaluated.

+
// Create an initial module
+const module = new vm.SourceTextModule('const a = 1;');
+
+// Create cached data from this module
+const cachedData = module.createCachedData();
+
+// Create a new module using the cached data. The code must be the same.
+const module2 = new vm.SourceTextModule('const a = 1;', { cachedData });
+

Class: vm.SyntheticModule#

+ +

Stability: 1 - Experimental

+

This feature is only available with the --experimental-vm-modules command +flag enabled.

+ +

The vm.SyntheticModule class provides the Synthetic Module Record as +defined in the WebIDL specification. The purpose of synthetic modules is to +provide a generic interface for exposing non-JavaScript sources to ECMAScript +module graphs.

+
const vm = require('vm');
+
+const source = '{ "a": 1 }';
+const module = new vm.SyntheticModule(['default'], function() {
+  const obj = JSON.parse(source);
+  this.setExport('default', obj);
+});
+
+// Use `module` in linking...
+

new vm.SyntheticModule(exportNames, evaluateCallback[, options])#

+ +
    +
  • exportNames <string[]> Array of names that will be exported from the module.
  • +
  • evaluateCallback <Function> Called when the module is evaluated.
  • +
  • options +
      +
    • identifier <string> String used in stack traces. +Default: 'vm:module(i)' where i is a context-specific ascending +index.
    • +
    • context <Object> The contextified object as returned by the +vm.createContext() method, to compile and evaluate this Module in.
    • +
    +
  • +
+

Creates a new SyntheticModule instance.

+

Objects assigned to the exports of this instance may allow importers of +the module to access information outside the specified context. Use +vm.runInContext() to create objects in a specific context.

+

syntheticModule.setExport(name, value)#

+ +
    +
  • name <string> Name of the export to set.
  • +
  • value <any> The value to set the export to.
  • +
+

This method is used after the module is linked to set the values of exports. If +it is called before the module is linked, an ERR_VM_MODULE_STATUS error +will be thrown.

+
const vm = require('vm');
+
+(async () => {
+  const m = new vm.SyntheticModule(['x'], () => {
+    m.setExport('x', 1);
+  });
+
+  await m.link(() => {});
+  await m.evaluate();
+
+  assert.strictEqual(m.namespace.x, 1);
+})();
+

vm.compileFunction(code[, params[, options]])#

+ +
    +
  • code <string> The body of the function to compile.
  • +
  • params <string[]> An array of strings containing all parameters for the +function.
  • +
  • options <Object> +
      +
    • filename <string> Specifies the filename used in stack traces produced +by this script. Default: ''.
    • +
    • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source.
    • +
    • produceCachedData <boolean> Specifies whether to produce new cache data. +Default: false.
    • +
    • parsingContext <Object> The contextified object in which the said +function should be compiled in.
    • +
    • contextExtensions <Object[]> An array containing a collection of context +extensions (objects wrapping the current scope) to be applied while +compiling. Default: [].
    • +
    +
  • +
  • Returns: <Function>
  • +
+

Compiles the given code into the provided context (if no context is +supplied, the current context is used), and returns it wrapped inside a +function with the given params.

+

vm.createContext([contextObject[, options]])#

+ +
    +
  • contextObject <Object>
  • +
  • options <Object> +
      +
    • name <string> Human-readable name of the newly created context. +Default: 'VM Context i', where i is an ascending numerical index of +the created context.
    • +
    • origin <string> Origin corresponding to the newly created +context for display purposes. The origin should be formatted like a URL, +but with only the scheme, host, and port (if necessary), like the value of +the url.origin property of a URL object. Most notably, this +string should omit the trailing slash, as that denotes a path. +Default: ''.
    • +
    • codeGeneration <Object> +
        +
      • strings <boolean> If set to false any calls to eval or function +constructors (Function, GeneratorFunction, etc) will throw an +EvalError. Default: true.
      • +
      • wasm <boolean> If set to false any attempt to compile a WebAssembly +module will throw a WebAssembly.CompileError. Default: true.
      • +
      +
    • +
    +
  • +
  • Returns: <Object> contextified object.
  • +
+

If given a contextObject, the vm.createContext() method will prepare +that object so that it can be used in calls to +vm.runInContext() or script.runInContext(). Inside such scripts, +the contextObject will be the global object, retaining all of its existing +properties but also having the built-in objects and functions any standard +global object has. Outside of scripts run by the vm module, global variables +will remain unchanged.

+
const vm = require('vm');
+
+global.globalVar = 3;
+
+const context = { globalVar: 1 };
+vm.createContext(context);
+
+vm.runInContext('globalVar *= 2;', context);
+
+console.log(context);
+// Prints: { globalVar: 2 }
+
+console.log(global.globalVar);
+// Prints: 3
+

If contextObject is omitted (or passed explicitly as undefined), a new, +empty contextified object will be returned.

+

The vm.createContext() method is primarily useful for creating a single +context that can be used to run multiple scripts. For instance, if emulating a +web browser, the method can be used to create a single context representing a +window's global object, then run all <script> tags together within that +context.

+

The provided name and origin of the context are made visible through the +Inspector API.

+

vm.isContext(object)#

+ + +

Returns true if the given oject object has been contextified using +vm.createContext().

+

vm.runInContext(code, contextifiedObject[, options])#

+ +
    +
  • code <string> The JavaScript code to compile and run.
  • +
  • contextifiedObject <Object> The contextified object that will be used +as the global when the code is compiled and run.
  • +
  • options <Object> | <string> +
      +
    • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
    • +
    • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
    • +
    • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
    • +
    • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
    • +
    • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
    • +
    • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
    • +
    • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
        +
      • specifier <string> specifier passed to import()
      • +
      • module <vm.Module>
      • +
      • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
      • +
      +
    • +
    +
  • +
  • Returns: <any> the result of the very last statement executed in the script.
  • +
+

The vm.runInContext() method compiles code, runs it within the context of +the contextifiedObject, then returns the result. Running code does not have +access to the local scope. The contextifiedObject object must have been +previously contextified using the vm.createContext() method.

+

If options is a string, then it specifies the filename.

+

The following example compiles and executes different scripts using a single +contextified object:

+
const vm = require('vm');
+
+const contextObject = { globalVar: 1 };
+vm.createContext(contextObject);
+
+for (let i = 0; i < 10; ++i) {
+  vm.runInContext('globalVar *= 2;', contextObject);
+}
+console.log(contextObject);
+// Prints: { globalVar: 1024 }
+

vm.runInNewContext(code[, contextObject[, options]])#

+ +
    +
  • code <string> The JavaScript code to compile and run.
  • +
  • contextObject <Object> An object that will be contextified. If +undefined, a new object will be created.
  • +
  • options <Object> | <string> +
      +
    • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
    • +
    • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
    • +
    • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
    • +
    • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
    • +
    • contextName <string> Human-readable name of the newly created context. +Default: 'VM Context i', where i is an ascending numerical index of +the created context.
    • +
    • contextOrigin <string> Origin corresponding to the newly +created context for display purposes. The origin should be formatted like a +URL, but with only the scheme, host, and port (if necessary), like the +value of the url.origin property of a URL object. Most notably, +this string should omit the trailing slash, as that denotes a path. +Default: ''.
    • +
    • contextCodeGeneration <Object> +
        +
      • strings <boolean> If set to false any calls to eval or function +constructors (Function, GeneratorFunction, etc) will throw an +EvalError. Default: true.
      • +
      • wasm <boolean> If set to false any attempt to compile a WebAssembly +module will throw a WebAssembly.CompileError. Default: true.
      • +
      +
    • +
    • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
    • +
    • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
    • +
    • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
        +
      • specifier <string> specifier passed to import()
      • +
      • module <vm.Module>
      • +
      • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
      • +
      +
    • +
    +
  • +
  • Returns: <any> the result of the very last statement executed in the script.
  • +
+

The vm.runInNewContext() first contextifies the given contextObject (or +creates a new contextObject if passed as undefined), compiles the code, +runs it within the created context, then returns the result. Running code +does not have access to the local scope.

+

If options is a string, then it specifies the filename.

+

The following example compiles and executes code that increments a global +variable and sets a new one. These globals are contained in the contextObject.

+
const vm = require('vm');
+
+const contextObject = {
+  animal: 'cat',
+  count: 2
+};
+
+vm.runInNewContext('count += 1; name = "kitty"', contextObject);
+console.log(contextObject);
+// Prints: { animal: 'cat', count: 3, name: 'kitty' }
+

vm.runInThisContext(code[, options])#

+ +
    +
  • code <string> The JavaScript code to compile and run.
  • +
  • options <Object> | <string> +
      +
    • filename <string> Specifies the filename used in stack traces produced +by this script. Default: 'evalmachine.<anonymous>'.
    • +
    • lineOffset <number> Specifies the line number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • columnOffset <number> Specifies the column number offset that is displayed +in stack traces produced by this script. Default: 0.
    • +
    • displayErrors <boolean> When true, if an Error occurs +while compiling the code, the line of code causing the error is attached +to the stack trace. Default: true.
    • +
    • timeout <integer> Specifies the number of milliseconds to execute code +before terminating execution. If execution is terminated, an Error +will be thrown. This value must be a strictly positive integer.
    • +
    • breakOnSigint <boolean> If true, the execution will be terminated when +SIGINT (Ctrl+C) is received. Existing handlers for the +event that have been attached via process.on('SIGINT') will be disabled +during script execution, but will continue to work after that. If execution +is terminated, an Error will be thrown. Default: false.
    • +
    • cachedData <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or +TypedArray, or DataView with V8's code cache data for the supplied +source. When supplied, the cachedDataRejected value will be set to +either true or false depending on acceptance of the data by V8.
    • +
    • produceCachedData <boolean> When true and no cachedData is present, V8 +will attempt to produce code cache data for code. Upon success, a +Buffer with V8's code cache data will be produced and stored in the +cachedData property of the returned vm.Script instance. +The cachedDataProduced value will be set to either true or false +depending on whether code cache data is produced successfully. +This option is deprecated in favor of script.createCachedData(). +Default: false.
    • +
    • importModuleDynamically <Function> Called during evaluation of this module +when import() is called. If this option is not specified, calls to +import() will reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING. +This option is part of the experimental modules API, and should not be +considered stable. +
        +
      • specifier <string> specifier passed to import()
      • +
      • module <vm.Module>
      • +
      • Returns: <Module Namespace Object> | <vm.Module> Returning a vm.Module is +recommended in order to take advantage of error tracking, and to avoid +issues with namespaces that contain then function exports.
      • +
      +
    • +
    +
  • +
  • Returns: <any> the result of the very last statement executed in the script.
  • +
+

vm.runInThisContext() compiles code, runs it within the context of the +current global and returns the result. Running code does not have access to +local scope, but does have access to the current global object.

+

If options is a string, then it specifies the filename.

+

The following example illustrates using both vm.runInThisContext() and +the JavaScript eval() function to run the same code:

+ +
const vm = require('vm');
+let localVar = 'initial value';
+
+const vmResult = vm.runInThisContext('localVar = "vm";');
+console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);
+// Prints: vmResult: 'vm', localVar: 'initial value'
+
+const evalResult = eval('localVar = "eval";');
+console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);
+// Prints: evalResult: 'eval', localVar: 'eval'
+

Because vm.runInThisContext() does not have access to the local scope, +localVar is unchanged. In contrast, eval() does have access to the +local scope, so the value localVar is changed. In this way +vm.runInThisContext() is much like an indirect eval() call, e.g. +(0,eval)('code').

+

Example: Running an HTTP server within a VM#

+

When using either script.runInThisContext() or +vm.runInThisContext(), the code is executed within the current V8 global +context. The code passed to this VM context will have its own isolated scope.

+

In order to run a simple web server using the http module the code passed to +the context must either call require('http') on its own, or have a reference +to the http module passed to it. For instance:

+
'use strict';
+const vm = require('vm');
+
+const code = `
+((require) => {
+  const http = require('http');
+
+  http.createServer((request, response) => {
+    response.writeHead(200, { 'Content-Type': 'text/plain' });
+    response.end('Hello World\\n');
+  }).listen(8124);
+
+  console.log('Server running at http://127.0.0.1:8124/');
+})`;
+
+vm.runInThisContext(code)(require);
+

The require() in the above case shares the state with the context it is +passed from. This may introduce risks when untrusted code is executed, e.g. +altering objects in the context in unwanted ways.

+

What does it mean to "contextify" an object?#

+

All JavaScript executed within Node.js runs within the scope of a "context". +According to the V8 Embedder's Guide:

+
+

In V8, a context is an execution environment that allows separate, unrelated, +JavaScript applications to run in a single instance of V8. You must explicitly +specify the context in which you want any JavaScript code to be run.

+
+

When the method vm.createContext() is called, the contextObject argument +(or a newly-created object if contextObject is undefined) is associated +internally with a new instance of a V8 Context. This V8 Context provides the +code run using the vm module's methods with an isolated global environment +within which it can operate. The process of creating the V8 Context and +associating it with the contextObject is what this document refers to as +"contextifying" the object.

+

Timeout limitations when using process.nextTick(), promises, and queueMicrotask()#

+

Because of the internal mechanics of how the process.nextTick() queue and +the microtask queue that underlies Promises are implemented within V8 and +Node.js, it is possible for code running within a context to "escape" the +timeout set using vm.runInContext(), vm.runInNewContext(), and +vm.runInThisContext().

+

For example, the following code executed by vm.runInNewContext() with a +timeout of 5 milliseconds schedules an infinite loop to run after a promise +resolves. The scheduled loop is never interrupted by the timeout:

+
const vm = require('vm');
+
+function loop() {
+  while (1) console.log(Date.now());
+}
+
+vm.runInNewContext(
+  'Promise.resolve().then(loop);',
+  { loop, console },
+  { timeout: 5 }
+);
+

This issue also occurs when the loop() call is scheduled using +the process.nextTick() and queueMicrotask() functions.

+

This issue occurs because all contexts share the same microtask and nextTick +queues.

+ + + + + + diff --git a/doc/api/vm.json b/doc/api/vm.json new file mode 100644 index 0000000000000000000000000000000000000000..496119cf48249ff5d57d6388cbdde2b66f59f676 --- /dev/null +++ b/doc/api/vm.json @@ -0,0 +1,1334 @@ +{ + "type": "module", + "source": "doc/api/vm.md", + "modules": [ + { + "textRaw": "VM (executing JavaScript)", + "name": "vm", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

Source Code: lib/vm.js

\n

The vm module enables compiling and running code within V8 Virtual\nMachine contexts. The vm module is not a security mechanism. Do\nnot use it to run untrusted code.

\n

JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.

\n

A common use case is to run the code in a different V8 Context. This means\ninvoked code has a different global object than the invoking code.

\n

One can provide the context by contextifying an\nobject. The invoked code treats any property in the context like a\nglobal variable. Any changes to global variables caused by the invoked\ncode are reflected in the context object.

\n
const vm = require('vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\nvm.createContext(context); // Contextify the object.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the context.\n// Initially, x has the value 2 because that is the value of context.x.\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
", + "classes": [ + { + "textRaw": "Class: `vm.Script`", + "type": "class", + "name": "vm.Script", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [] + }, + "desc": "

Instances of the vm.Script class contain precompiled scripts that can be\nexecuted in specific contexts.

", + "methods": [ + { + "textRaw": "`script.createCachedData()`", + "type": "method", + "name": "createCachedData", + "meta": { + "added": [ + "v10.6.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [] + } + ], + "desc": "

Creates a code cache that can be used with the Script constructor's\ncachedData option. Returns a Buffer. This method may be called at any\ntime and any number of times.

\n
const script = new vm.Script(`\nfunction add(a, b) {\n  return a + b;\n}\n\nconst x = add(1, 2);\n`);\n\nconst cacheWithoutX = script.createCachedData();\n\nscript.runInThisContext();\n\nconst cacheWithX = script.createCachedData();\n
" + }, + { + "textRaw": "`script.runInContext(contextifiedObject[, options])`", + "type": "method", + "name": "runInContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`contextifiedObject` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", + "name": "contextifiedObject", + "type": "Object", + "desc": "A [contextified][] object as returned by the `vm.createContext()` method." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + } + ] + } + ] + } + ], + "desc": "

Runs the compiled code contained by the vm.Script object within the given\ncontextifiedObject and returns the result. Running code does not have access\nto local scope.

\n

The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the context object.

\n
const vm = require('vm');\n\nconst context = {\n  animal: 'cat',\n  count: 2\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nvm.createContext(context);\nfor (let i = 0; i < 10; ++i) {\n  script.runInContext(context);\n}\n\nconsole.log(context);\n// Prints: { animal: 'cat', count: 12, name: 'kitty' }\n
\n

Using the timeout or breakOnSigint options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.

" + }, + { + "textRaw": "`script.runInNewContext([contextObject[, options]])`", + "type": "method", + "name": "runInNewContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19016", + "description": "The `contextCodeGeneration` option is supported now." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", + "name": "contextObject", + "type": "Object", + "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", + "name": "contextName", + "type": "string", + "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", + "desc": "Human-readable name of the newly created context." + }, + { + "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", + "name": "contextOrigin", + "type": "string", + "default": "`''`", + "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." + }, + { + "textRaw": "`contextCodeGeneration` {Object}", + "name": "contextCodeGeneration", + "type": "Object", + "options": [ + { + "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", + "name": "strings", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." + }, + { + "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", + "name": "wasm", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." + } + ] + } + ] + } + ] + } + ], + "desc": "

First contextifies the given contextObject, runs the compiled code contained\nby the vm.Script object within the created context, and returns the result.\nRunning code does not have access to local scope.

\n

The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual context.

\n
const vm = require('vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst contexts = [{}, {}, {}];\ncontexts.forEach((context) => {\n  script.runInNewContext(context);\n});\n\nconsole.log(contexts);\n// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
" + }, + { + "textRaw": "`script.runInThisContext([options])`", + "type": "method", + "name": "runInThisContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + } + ] + } + ] + } + ], + "desc": "

Runs the compiled code contained by the vm.Script within the context of the\ncurrent global object. Running code does not have access to local scope, but\ndoes have access to the current global object.

\n

The following example compiles code that increments a global variable then\nexecutes that code multiple times:

\n
const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ], + "desc": "

If options is a string, then it specifies the filename.

\n

Creating a new vm.Script object compiles code but does not run it. The\ncompiled vm.Script can be run later multiple times. The code is not bound to\nany global object; rather, it is bound before each run, just for that run.

" + } + ] + }, + { + "textRaw": "Class: `vm.Module`", + "type": "class", + "name": "vm.Module", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n

The vm.Module class provides a low-level interface for using\nECMAScript modules in VM contexts. It is the counterpart of the vm.Script\nclass that closely mirrors Module Records as defined in the ECMAScript\nspecification.

\n

Unlike vm.Script however, every vm.Module object is bound to a context from\nits creation. Operations on vm.Module objects are intrinsically asynchronous,\nin contrast with the synchronous nature of vm.Script objects. The use of\n'async' functions can help with manipulating vm.Module objects.

\n

Using a vm.Module object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.

\n

This implementation lies at a lower level than the ECMAScript Module\nloader. There is also no way to interact with the Loader yet, though\nsupport is planned.

\n
const vm = require('vm');\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\n(async () => {\n  // Step 1\n  //\n  // Create a Module by constructing a new `vm.SourceTextModule` object. This\n  // parses the provided source text, throwing a `SyntaxError` if anything goes\n  // wrong. By default, a Module is created in the top context. But here, we\n  // specify `contextifiedObject` as the context this Module belongs to.\n  //\n  // Here, we attempt to obtain the default export from the module \"foo\", and\n  // put it into local binding \"secret\".\n\n  const bar = new vm.SourceTextModule(`\n    import s from 'foo';\n    s;\n  `, { context: contextifiedObject });\n\n  // Step 2\n  //\n  // \"Link\" the imported dependencies of this Module to it.\n  //\n  // The provided linking callback (the \"linker\") accepts two arguments: the\n  // parent module (`bar` in this case) and the string that is the specifier of\n  // the imported module. The callback is expected to return a Module that\n  // corresponds to the provided specifier, with certain requirements documented\n  // in `module.link()`.\n  //\n  // If linking has not started for the returned Module, the same linker\n  // callback will be called on the returned Module.\n  //\n  // Even top-level Modules without dependencies must be explicitly linked. The\n  // callback provided would never be called, however.\n  //\n  // The link() method returns a Promise that will be resolved when all the\n  // Promises returned by the linker resolve.\n  //\n  // Note: This is a contrived example in that the linker function creates a new\n  // \"foo\" module every time it is called. In a full-fledged module system, a\n  // cache would probably be used to avoid duplicated modules.\n\n  async function linker(specifier, referencingModule) {\n    if (specifier === 'foo') {\n      return new vm.SourceTextModule(`\n        // The \"secret\" variable refers to the global variable we added to\n        // \"contextifiedObject\" when creating the context.\n        export default secret;\n      `, { context: referencingModule.context });\n\n      // Using `contextifiedObject` instead of `referencingModule.context`\n      // here would work as well.\n    }\n    throw new Error(`Unable to resolve dependency: ${specifier}`);\n  }\n  await bar.link(linker);\n\n  // Step 3\n  //\n  // Evaluate the Module. The evaluate() method returns a Promise with a single\n  // property \"result\" that contains the result of the very last statement\n  // executed in the Module. In the case of `bar`, it is `s;`, which refers to\n  // the default export of the `foo` module, the `secret` we set in the\n  // beginning to 42.\n\n  const { result } = await bar.evaluate();\n\n  console.log(result);\n  // Prints 42.\n})();\n
", + "properties": [ + { + "textRaw": "`dependencySpecifiers` {string[]}", + "type": "string[]", + "name": "dependencySpecifiers", + "desc": "

The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.

\n

Corresponds to the [[RequestedModules]] field of Cyclic Module Records in\nthe ECMAScript specification.

" + }, + { + "textRaw": "`error` {any}", + "type": "any", + "name": "error", + "desc": "

If the module.status is 'errored', this property contains the exception\nthrown by the module during evaluation. If the status is anything else,\naccessing this property will result in a thrown exception.

\n

The value undefined cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with throw undefined;.

\n

Corresponds to the [[EvaluationError]] field of Cyclic Module Records\nin the ECMAScript specification.

" + }, + { + "textRaw": "`namespace` {Object}", + "type": "Object", + "name": "namespace", + "desc": "

The namespace object of the module. This is only available after linking\n(module.link()) has completed.

\n

Corresponds to the GetModuleNamespace abstract operation in the ECMAScript\nspecification.

" + }, + { + "textRaw": "`status` {string}", + "type": "string", + "name": "status", + "desc": "

The current status of the module. Will be one of:

\n
    \n
  • \n

    'unlinked': module.link() has not yet been called.

    \n
  • \n
  • \n

    'linking': module.link() has been called, but not all Promises returned\nby the linker function have been resolved yet.

    \n
  • \n
  • \n

    'linked': The module has been linked successfully, and all of its\ndependencies are linked, but module.evaluate() has not yet been called.

    \n
  • \n
  • \n

    'evaluating': The module is being evaluated through a module.evaluate() on\nitself or a parent module.

    \n
  • \n
  • \n

    'evaluated': The module has been successfully evaluated.

    \n
  • \n
  • \n

    'errored': The module has been evaluated, but an exception was thrown.

    \n
  • \n
\n

Other than 'errored', this status string corresponds to the specification's\nCyclic Module Record's [[Status]] field. 'errored' corresponds to\n'evaluated' in the specification, but with [[EvaluationError]] set to a\nvalue that is not undefined.

" + }, + { + "textRaw": "`identifier` {string}", + "type": "string", + "name": "identifier", + "desc": "

The identifier of the current module, as set in the constructor.

" + } + ], + "methods": [ + { + "textRaw": "`module.evaluate([options])`", + "type": "method", + "name": "evaluate", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is interrupted, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is interrupted, an [`Error`][] will be thrown." + } + ] + } + ] + } + ], + "desc": "

Evaluate the module.

\n

This must be called after the module has been linked; otherwise it will\nthrow an error. It could be called also when the module has already been\nevaluated, in which case it will do one of the following two things:

\n
    \n
  • return undefined if the initial evaluation ended in success (module.status\nis 'evaluated')
  • \n
  • rethrow the same exception the initial evaluation threw if the initial\nevaluation ended in an error (module.status is 'errored')
  • \n
\n

This method cannot be called while the module is being evaluated\n(module.status is 'evaluating') to prevent infinite recursion.

\n

Corresponds to the Evaluate() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.

" + }, + { + "textRaw": "`module.link(linker)`", + "type": "method", + "name": "link", + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [ + { + "textRaw": "`linker` {Function}", + "name": "linker", + "type": "Function", + "options": [ + { + "textRaw": "`specifier` {string} The specifier of the requested module:```js import foo from 'foo'; // ^^^^^ the module specifier ```", + "name": "specifier", + "type": "string", + "desc": "The specifier of the requested module:```js import foo from 'foo'; // ^^^^^ the module specifier ```" + }, + { + "textRaw": "`referencingModule` {vm.Module} The `Module` object `link()` is called on.", + "name": "referencingModule", + "type": "vm.Module", + "desc": "The `Module` object `link()` is called on." + }, + { + "textRaw": "Returns: {vm.Module|Promise}", + "name": "return", + "type": "vm.Module|Promise" + } + ] + } + ] + } + ], + "desc": "

Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.

\n

The function is expected to return a Module object or a Promise that\neventually resolves to a Module object. The returned Module must satisfy the\nfollowing two invariants:

\n
    \n
  • It must belong to the same context as the parent Module.
  • \n
  • Its status must not be 'errored'.
  • \n
\n

If the returned Module's status is 'unlinked', this method will be\nrecursively called on the returned Module with the same provided linker\nfunction.

\n

link() returns a Promise that will either get resolved when all linking\ninstances resolve to a valid Module, or rejected if the linker function either\nthrows an exception or returns an invalid Module.

\n

The linker function roughly corresponds to the implementation-defined\nHostResolveImportedModule abstract operation in the ECMAScript\nspecification, with a few key differences:

\n\n

The actual HostResolveImportedModule implementation used during module\nlinking is one that returns the modules linked during linking. Since at\nthat point all modules would have been fully linked already, the\nHostResolveImportedModule implementation is fully synchronous per\nspecification.

\n

Corresponds to the Link() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.

" + } + ] + }, + { + "textRaw": "Class: `vm.SourceTextModule`", + "type": "class", + "name": "vm.SourceTextModule", + "meta": { + "added": [ + "v9.6.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n\n

The vm.SourceTextModule class provides the Source Text Module Record as\ndefined in the ECMAScript specification.

", + "methods": [ + { + "textRaw": "`sourceTextModule.createCachedData()`", + "type": "method", + "name": "createCachedData", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Buffer}", + "name": "return", + "type": "Buffer" + }, + "params": [] + } + ], + "desc": "

Creates a code cache that can be used with the SourceTextModule constructor's\ncachedData option. Returns a Buffer. This method may be called any number\nof times before the module has been evaluated.

\n
// Create an initial module\nconst module = new vm.SourceTextModule('const a = 1;');\n\n// Create cached data from this module\nconst cachedData = module.createCachedData();\n\n// Create a new module using the cached data. The code must be the same.\nconst module2 = new vm.SourceTextModule('const a = 1;', { cachedData });\n
" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`code` {string} JavaScript Module code to parse", + "name": "code", + "type": "string", + "desc": "JavaScript Module code to parse" + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", + "name": "identifier", + "type": "string", + "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", + "desc": "String used in stack traces." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created." + }, + { + "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", + "name": "context", + "type": "Object", + "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." + }, + { + "textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", + "name": "lineOffset", + "type": "integer", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`." + }, + { + "textRaw": "`columnOffset` {integer} Specifies the column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", + "name": "columnOffset", + "type": "integer", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this `Module`." + }, + { + "textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.", + "name": "initializeImportMeta", + "type": "Function", + "desc": "Called during evaluation of this `Module` to initialize the `import.meta`.", + "options": [ + { + "textRaw": "`meta` {import.meta}", + "name": "meta", + "type": "import.meta" + }, + { + "textRaw": "`module` {vm.SourceTextModule}", + "name": "module", + "type": "vm.SourceTextModule" + } + ] + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ], + "desc": "

Creates a new SourceTextModule instance.

\n

Properties assigned to the import.meta object that are objects may\nallow the module to access information outside the specified context. Use\nvm.runInContext() to create objects in a specific context.

\n
const vm = require('vm');\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\n(async () => {\n  const module = new vm.SourceTextModule(\n    'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n    {\n      initializeImportMeta(meta) {\n        // Note: this object is created in the top context. As such,\n        // Object.getPrototypeOf(import.meta.prop) points to the\n        // Object.prototype in the top context rather than that in\n        // the contextified object.\n        meta.prop = {};\n      }\n    });\n  // Since module has no dependencies, the linker function will never be called.\n  await module.link(() => {});\n  await module.evaluate();\n\n  // Now, Object.prototype.secret will be equal to 42.\n  //\n  // To fix this problem, replace\n  //     meta.prop = {};\n  // above with\n  //     meta.prop = vm.runInContext('{}', contextifiedObject);\n})();\n
" + } + ] + }, + { + "textRaw": "Class: `vm.SyntheticModule`", + "type": "class", + "name": "vm.SyntheticModule", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "stability": 1, + "stabilityText": "Experimental", + "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n\n

The vm.SyntheticModule class provides the Synthetic Module Record as\ndefined in the WebIDL specification. The purpose of synthetic modules is to\nprovide a generic interface for exposing non-JavaScript sources to ECMAScript\nmodule graphs.

\n
const vm = require('vm');\n\nconst source = '{ \"a\": 1 }';\nconst module = new vm.SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `module` in linking...\n
", + "methods": [ + { + "textRaw": "`syntheticModule.setExport(name, value)`", + "type": "method", + "name": "setExport", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`name` {string} Name of the export to set.", + "name": "name", + "type": "string", + "desc": "Name of the export to set." + }, + { + "textRaw": "`value` {any} The value to set the export to.", + "name": "value", + "type": "any", + "desc": "The value to set the export to." + } + ] + } + ], + "desc": "

This method is used after the module is linked to set the values of exports. If\nit is called before the module is linked, an ERR_VM_MODULE_STATUS error\nwill be thrown.

\n
const vm = require('vm');\n\n(async () => {\n  const m = new vm.SyntheticModule(['x'], () => {\n    m.setExport('x', 1);\n  });\n\n  await m.link(() => {});\n  await m.evaluate();\n\n  assert.strictEqual(m.namespace.x, 1);\n})();\n
" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`exportNames` {string[]} Array of names that will be exported from the module.", + "name": "exportNames", + "type": "string[]", + "desc": "Array of names that will be exported from the module." + }, + { + "textRaw": "`evaluateCallback` {Function} Called when the module is evaluated.", + "name": "evaluateCallback", + "type": "Function", + "desc": "Called when the module is evaluated." + }, + { + "textRaw": "`options`", + "name": "options", + "options": [ + { + "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", + "name": "identifier", + "type": "string", + "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", + "desc": "String used in stack traces." + }, + { + "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", + "name": "context", + "type": "Object", + "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." + } + ] + } + ], + "desc": "

Creates a new SyntheticModule instance.

\n

Objects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified context. Use\nvm.runInContext() to create objects in a specific context.

" + } + ] + } + ], + "methods": [ + { + "textRaw": "`vm.compileFunction(code[, params[, options]])`", + "type": "method", + "name": "compileFunction", + "meta": { + "added": [ + "v10.10.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Function}", + "name": "return", + "type": "Function" + }, + "params": [ + { + "textRaw": "`code` {string} The body of the function to compile.", + "name": "code", + "type": "string", + "desc": "The body of the function to compile." + }, + { + "textRaw": "`params` {string[]} An array of strings containing all parameters for the function.", + "name": "params", + "type": "string[]", + "desc": "An array of strings containing all parameters for the function." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `''`.", + "name": "filename", + "type": "string", + "default": "`''`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." + }, + { + "textRaw": "`produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "Specifies whether to produce new cache data." + }, + { + "textRaw": "`parsingContext` {Object} The [contextified][] object in which the said function should be compiled in.", + "name": "parsingContext", + "type": "Object", + "desc": "The [contextified][] object in which the said function should be compiled in." + }, + { + "textRaw": "`contextExtensions` {Object[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`.", + "name": "contextExtensions", + "type": "Object[]", + "default": "`[]`", + "desc": "An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling." + } + ] + } + ] + } + ], + "desc": "

Compiles the given code into the provided context (if no context is\nsupplied, the current context is used), and returns it wrapped inside a\nfunction with the given params.

" + }, + { + "textRaw": "`vm.createContext([contextObject[, options]])`", + "type": "method", + "name": "createContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19398", + "description": "The first argument can no longer be a function." + }, + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19016", + "description": "The `codeGeneration` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object} contextified object.", + "name": "return", + "type": "Object", + "desc": "contextified object." + }, + "params": [ + { + "textRaw": "`contextObject` {Object}", + "name": "contextObject", + "type": "Object" + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`name` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", + "name": "name", + "type": "string", + "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", + "desc": "Human-readable name of the newly created context." + }, + { + "textRaw": "`origin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", + "name": "origin", + "type": "string", + "default": "`''`", + "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." + }, + { + "textRaw": "`codeGeneration` {Object}", + "name": "codeGeneration", + "type": "Object", + "options": [ + { + "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", + "name": "strings", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." + }, + { + "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", + "name": "wasm", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." + } + ] + } + ] + } + ] + } + ], + "desc": "

If given a contextObject, the vm.createContext() method will prepare\nthat object so that it can be used in calls to\nvm.runInContext() or script.runInContext(). Inside such scripts,\nthe contextObject will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.

\n
const vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\nvm.createContext(context);\n\nvm.runInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n
\n

If contextObject is omitted (or passed explicitly as undefined), a new,\nempty contextified object will be returned.

\n

The vm.createContext() method is primarily useful for creating a single\ncontext that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single context representing a\nwindow's global object, then run all <script> tags together within that\ncontext.

\n

The provided name and origin of the context are made visible through the\nInspector API.

" + }, + { + "textRaw": "`vm.isContext(object)`", + "type": "method", + "name": "isContext", + "meta": { + "added": [ + "v0.11.7" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {boolean}", + "name": "return", + "type": "boolean" + }, + "params": [ + { + "textRaw": "`object` {Object}", + "name": "object", + "type": "Object" + } + ] + } + ], + "desc": "

Returns true if the given oject object has been contextified using\nvm.createContext().

" + }, + { + "textRaw": "`vm.runInContext(code, contextifiedObject[, options])`", + "type": "method", + "name": "runInContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile and run.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile and run." + }, + { + "textRaw": "`contextifiedObject` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.", + "name": "contextifiedObject", + "type": "Object", + "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ] + } + ], + "desc": "

The vm.runInContext() method compiles code, runs it within the context of\nthe contextifiedObject, then returns the result. Running code does not have\naccess to the local scope. The contextifiedObject object must have been\npreviously contextified using the vm.createContext() method.

\n

If options is a string, then it specifies the filename.

\n

The following example compiles and executes different scripts using a single\ncontextified object:

\n
const vm = require('vm');\n\nconst contextObject = { globalVar: 1 };\nvm.createContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  vm.runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n
" + }, + { + "textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`", + "type": "method", + "name": "runInNewContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v10.0.0", + "pr-url": "https://github.com/nodejs/node/pull/19016", + "description": "The `contextCodeGeneration` option is supported now." + }, + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile and run.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile and run." + }, + { + "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", + "name": "contextObject", + "type": "Object", + "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", + "name": "contextName", + "type": "string", + "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", + "desc": "Human-readable name of the newly created context." + }, + { + "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", + "name": "contextOrigin", + "type": "string", + "default": "`''`", + "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." + }, + { + "textRaw": "`contextCodeGeneration` {Object}", + "name": "contextCodeGeneration", + "type": "Object", + "options": [ + { + "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", + "name": "strings", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." + }, + { + "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", + "name": "wasm", + "type": "boolean", + "default": "`true`", + "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." + } + ] + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ] + } + ], + "desc": "

The vm.runInNewContext() first contextifies the given contextObject (or\ncreates a new contextObject if passed as undefined), compiles the code,\nruns it within the created context, then returns the result. Running code\ndoes not have access to the local scope.

\n

If options is a string, then it specifies the filename.

\n

The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the contextObject.

\n
const vm = require('vm');\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n
" + }, + { + "textRaw": "`vm.runInThisContext(code[, options])`", + "type": "method", + "name": "runInThisContext", + "meta": { + "added": [ + "v0.3.1" + ], + "changes": [ + { + "version": "v6.3.0", + "pr-url": "https://github.com/nodejs/node/pull/6635", + "description": "The `breakOnSigint` option is supported now." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {any} the result of the very last statement executed in the script.", + "name": "return", + "type": "any", + "desc": "the result of the very last statement executed in the script." + }, + "params": [ + { + "textRaw": "`code` {string} The JavaScript code to compile and run.", + "name": "code", + "type": "string", + "desc": "The JavaScript code to compile and run." + }, + { + "textRaw": "`options` {Object|string}", + "name": "options", + "type": "Object|string", + "options": [ + { + "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", + "name": "filename", + "type": "string", + "default": "`'evalmachine.'`", + "desc": "Specifies the filename used in stack traces produced by this script." + }, + { + "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "lineOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", + "name": "columnOffset", + "type": "number", + "default": "`0`", + "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." + }, + { + "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", + "name": "displayErrors", + "type": "boolean", + "default": "`true`", + "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." + }, + { + "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", + "name": "timeout", + "type": "integer", + "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." + }, + { + "textRaw": "`breakOnSigint` {boolean} If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. **Default:** `false`.", + "name": "breakOnSigint", + "type": "boolean", + "default": "`false`", + "desc": "If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." + }, + { + "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", + "name": "cachedData", + "type": "Buffer|TypedArray|DataView", + "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." + }, + { + "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", + "name": "produceCachedData", + "type": "boolean", + "default": "`false`", + "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." + }, + { + "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "name": "importModuleDynamically", + "type": "Function", + "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", + "options": [ + { + "textRaw": "`specifier` {string} specifier passed to `import()`", + "name": "specifier", + "type": "string", + "desc": "specifier passed to `import()`" + }, + { + "textRaw": "`module` {vm.Module}", + "name": "module", + "type": "vm.Module" + }, + { + "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", + "name": "return", + "type": "Module Namespace Object|vm.Module", + "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." + } + ] + } + ] + } + ] + } + ], + "desc": "

vm.runInThisContext() compiles code, runs it within the context of the\ncurrent global and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global object.

\n

If options is a string, then it specifies the filename.

\n

The following example illustrates using both vm.runInThisContext() and\nthe JavaScript eval() function to run the same code:

\n\n
const vm = require('vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = \"vm\";');\nconsole.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);\n// Prints: vmResult: 'vm', localVar: 'initial value'\n\nconst evalResult = eval('localVar = \"eval\";');\nconsole.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);\n// Prints: evalResult: 'eval', localVar: 'eval'\n
\n

Because vm.runInThisContext() does not have access to the local scope,\nlocalVar is unchanged. In contrast, eval() does have access to the\nlocal scope, so the value localVar is changed. In this way\nvm.runInThisContext() is much like an indirect eval() call, e.g.\n(0,eval)('code').

\n

Example: Running an HTTP server within a VM

\n

When using either script.runInThisContext() or\nvm.runInThisContext(), the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.

\n

In order to run a simple web server using the http module the code passed to\nthe context must either call require('http') on its own, or have a reference\nto the http module passed to it. For instance:

\n
'use strict';\nconst vm = require('vm');\n\nconst code = `\n((require) => {\n  const http = require('http');\n\n  http.createServer((request, response) => {\n    response.writeHead(200, { 'Content-Type': 'text/plain' });\n    response.end('Hello World\\\\n');\n  }).listen(8124);\n\n  console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n
\n

The require() in the above case shares the state with the context it is\npassed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.

" + } + ], + "modules": [ + { + "textRaw": "What does it mean to \"contextify\" an object?", + "name": "what_does_it_mean_to_\"contextify\"_an_object?", + "desc": "

All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the V8 Embedder's Guide:

\n
\n

In V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.

\n
\n

When the method vm.createContext() is called, the contextObject argument\n(or a newly-created object if contextObject is undefined) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode run using the vm module's methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the contextObject is what this document refers to as\n\"contextifying\" the object.

", + "type": "module", + "displayName": "What does it mean to \"contextify\" an object?" + }, + { + "textRaw": "Timeout limitations when using `process.nextTick()`, promises, and `queueMicrotask()`", + "name": "timeout_limitations_when_using_`process.nexttick()`,_promises,_and_`queuemicrotask()`", + "desc": "

Because of the internal mechanics of how the process.nextTick() queue and\nthe microtask queue that underlies Promises are implemented within V8 and\nNode.js, it is possible for code running within a context to \"escape\" the\ntimeout set using vm.runInContext(), vm.runInNewContext(), and\nvm.runInThisContext().

\n

For example, the following code executed by vm.runInNewContext() with a\ntimeout of 5 milliseconds schedules an infinite loop to run after a promise\nresolves. The scheduled loop is never interrupted by the timeout:

\n
const vm = require('vm');\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n  'Promise.resolve().then(loop);',\n  { loop, console },\n  { timeout: 5 }\n);\n
\n

This issue also occurs when the loop() call is scheduled using\nthe process.nextTick() and queueMicrotask() functions.

\n

This issue occurs because all contexts share the same microtask and nextTick\nqueues.

", + "type": "module", + "displayName": "Timeout limitations when using `process.nextTick()`, promises, and `queueMicrotask()`" + } + ], + "type": "module", + "displayName": "vm" + } + ] +} \ No newline at end of file diff --git a/doc/api/wasi.html b/doc/api/wasi.html new file mode 100644 index 0000000000000000000000000000000000000000..579619a5d9a665b9df8598c5c2d375d1ddffcbf8 --- /dev/null +++ b/doc/api/wasi.html @@ -0,0 +1,273 @@ + + + + + + + WebAssembly System Interface (WASI) | Node.js v12.22.7 Documentation + + + + + + +
+ + +
+
+

Node.js v12.22.7 Documentation

+ +
+
+ + + +
+

WebAssembly System Interface (WASI)#

+ +

Stability: 1 - Experimental

+

Source Code: lib/wasi.js

+

The WASI API provides an implementation of the WebAssembly System Interface +specification. WASI gives sandboxed WebAssembly applications access to the +underlying operating system via a collection of POSIX-like functions.

+
'use strict';
+const fs = require('fs');
+const { WASI } = require('wasi');
+const wasi = new WASI({
+  args: process.argv,
+  env: process.env,
+  preopens: {
+    '/sandbox': '/some/real/path/that/wasm/can/access'
+  }
+});
+const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
+
+(async () => {
+  const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
+  const instance = await WebAssembly.instantiate(wasm, importObject);
+
+  wasi.start(instance);
+})();
+

To run the above example, create a new WebAssembly text format file named +demo.wat:

+
(module
+    ;; Import the required fd_write WASI function which will write the given io vectors to stdout
+    ;; The function signature for fd_write is:
+    ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
+    (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
+
+    (memory 1)
+    (export "memory" (memory 0))
+
+    ;; Write 'hello world\n' to memory at an offset of 8 bytes
+    ;; Note the trailing newline which is required for the text to appear
+    (data (i32.const 8) "hello world\n")
+
+    (func $main (export "_start")
+        ;; Creating a new io vector within linear memory
+        (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
+        (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\n' string
+
+        (call $fd_write
+            (i32.const 1) ;; file_descriptor - 1 for stdout
+            (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
+            (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
+            (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
+        )
+        drop ;; Discard the number of bytes written from the top of the stack
+    )
+)
+

Use wabt to compile .wat to .wasm

+
$ wat2wasm demo.wat
+

The --experimental-wasi-unstable-preview1 and --experimental-wasm-bigint +CLI arguments are needed for this example to run.

+

Class: WASI#

+ +

The WASI class provides the WASI system call API and additional convenience +methods for working with WASI-based applications. Each WASI instance +represents a distinct sandbox environment. For security purposes, each WASI +instance must have its command line arguments, environment variables, and +sandbox directory structure configured explicitly.

+

new WASI([options])#

+ +
    +
  • options <Object> +
      +
    • args <Array> An array of strings that the WebAssembly application will +see as command line arguments. The first argument is the virtual path to the +WASI command itself. Default: [].
    • +
    • env <Object> An object similar to process.env that the WebAssembly +application will see as its environment. Default: {}.
    • +
    • preopens <Object> This object represents the WebAssembly application's +sandbox directory structure. The string keys of preopens are treated as +directories within the sandbox. The corresponding values in preopens are +the real paths to those directories on the host machine.
    • +
    • returnOnExit <boolean> By default, WASI applications terminate the Node.js +process via the __wasi_proc_exit() function. Setting this option to true +causes wasi.start() to return the exit code rather than terminate the +process. Default: false.
    • +
    • stdin <integer> The file descriptor used as standard input in the +WebAssembly application. Default: 0.
    • +
    • stdout <integer> The file descriptor used as standard output in the +WebAssembly application. Default: 1.
    • +
    • stderr <integer> The file descriptor used as standard error in the +WebAssembly application. Default: 2.
    • +
    +
  • +
+

wasi.start(instance)#

+ + +

Attempt to begin execution of instance as a WASI command by invoking its +_start() export. If instance does not contain a _start() export, or if +instance contains an _initialize() export, then an exception is thrown.

+

start() requires that instance exports a WebAssembly.Memory named +memory. If instance does not have a memory export an exception is thrown.

+

If start() is called more than once, an exception is thrown.

+

wasi.initialize(instance)#

+ + +

Attempt to initialize instance as a WASI reactor by invoking its +_initialize() export, if it is present. If instance contains a _start() +export, then an exception is thrown.

+

initialize() requires that instance exports a WebAssembly.Memory named +memory. If instance does not have a memory export an exception is thrown.

+

If initialize() is called more than once, an exception is thrown.

+

wasi.wasiImport#

+ + +

wasiImport is an object that implements the WASI system call API. This object +should be passed as the wasi_snapshot_preview1 import during the instantiation +of a WebAssembly.Instance.

+ +
+
+
+ + diff --git a/doc/api/wasi.json b/doc/api/wasi.json new file mode 100644 index 0000000000000000000000000000000000000000..cd95529988f54333142a4ee7be21c161e463cea4 --- /dev/null +++ b/doc/api/wasi.json @@ -0,0 +1,153 @@ +{ + "type": "module", + "source": "doc/api/wasi.md", + "modules": [ + { + "textRaw": "WebAssembly System Interface (WASI)", + "name": "webassembly_system_interface_(wasi)", + "introduced_in": "v12.16.0", + "stability": 1, + "stabilityText": "Experimental", + "desc": "

Source Code: lib/wasi.js

\n

The WASI API provides an implementation of the WebAssembly System Interface\nspecification. WASI gives sandboxed WebAssembly applications access to the\nunderlying operating system via a collection of POSIX-like functions.

\n
'use strict';\nconst fs = require('fs');\nconst { WASI } = require('wasi');\nconst wasi = new WASI({\n  args: process.argv,\n  env: process.env,\n  preopens: {\n    '/sandbox': '/some/real/path/that/wasm/can/access'\n  }\n});\nconst importObject = { wasi_snapshot_preview1: wasi.wasiImport };\n\n(async () => {\n  const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));\n  const instance = await WebAssembly.instantiate(wasm, importObject);\n\n  wasi.start(instance);\n})();\n
\n

To run the above example, create a new WebAssembly text format file named\ndemo.wat:

\n
(module\n    ;; Import the required fd_write WASI function which will write the given io vectors to stdout\n    ;; The function signature for fd_write is:\n    ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written\n    (import \"wasi_snapshot_preview1\" \"fd_write\" (func $fd_write (param i32 i32 i32 i32) (result i32)))\n\n    (memory 1)\n    (export \"memory\" (memory 0))\n\n    ;; Write 'hello world\\n' to memory at an offset of 8 bytes\n    ;; Note the trailing newline which is required for the text to appear\n    (data (i32.const 8) \"hello world\\n\")\n\n    (func $main (export \"_start\")\n        ;; Creating a new io vector within linear memory\n        (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\\n' string\n        (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\\n' string\n\n        (call $fd_write\n            (i32.const 1) ;; file_descriptor - 1 for stdout\n            (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0\n            (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.\n            (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written\n        )\n        drop ;; Discard the number of bytes written from the top of the stack\n    )\n)\n
\n

Use wabt to compile .wat to .wasm

\n
$ wat2wasm demo.wat\n
\n

The --experimental-wasi-unstable-preview1 and --experimental-wasm-bigint\nCLI arguments are needed for this example to run.

", + "classes": [ + { + "textRaw": "Class: `WASI`", + "type": "class", + "name": "WASI", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

The WASI class provides the WASI system call API and additional convenience\nmethods for working with WASI-based applications. Each WASI instance\nrepresents a distinct sandbox environment. For security purposes, each WASI\ninstance must have its command line arguments, environment variables, and\nsandbox directory structure configured explicitly.

", + "methods": [ + { + "textRaw": "`wasi.start(instance)`", + "type": "method", + "name": "start", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`instance` {WebAssembly.Instance}", + "name": "instance", + "type": "WebAssembly.Instance" + } + ] + } + ], + "desc": "

Attempt to begin execution of instance as a WASI command by invoking its\n_start() export. If instance does not contain a _start() export, or if\ninstance contains an _initialize() export, then an exception is thrown.

\n

start() requires that instance exports a WebAssembly.Memory named\nmemory. If instance does not have a memory export an exception is thrown.

\n

If start() is called more than once, an exception is thrown.

" + }, + { + "textRaw": "`wasi.initialize(instance)`", + "type": "method", + "name": "initialize", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`instance` {WebAssembly.Instance}", + "name": "instance", + "type": "WebAssembly.Instance" + } + ] + } + ], + "desc": "

Attempt to initialize instance as a WASI reactor by invoking its\n_initialize() export, if it is present. If instance contains a _start()\nexport, then an exception is thrown.

\n

initialize() requires that instance exports a WebAssembly.Memory named\nmemory. If instance does not have a memory export an exception is thrown.

\n

If initialize() is called more than once, an exception is thrown.

" + } + ], + "properties": [ + { + "textRaw": "`wasiImport` {Object}", + "type": "Object", + "name": "wasiImport", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "desc": "

wasiImport is an object that implements the WASI system call API. This object\nshould be passed as the wasi_snapshot_preview1 import during the instantiation\nof a WebAssembly.Instance.

" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`args` {Array} An array of strings that the WebAssembly application will see as command line arguments. The first argument is the virtual path to the WASI command itself. **Default:** `[]`.", + "name": "args", + "type": "Array", + "default": "`[]`", + "desc": "An array of strings that the WebAssembly application will see as command line arguments. The first argument is the virtual path to the WASI command itself." + }, + { + "textRaw": "`env` {Object} An object similar to `process.env` that the WebAssembly application will see as its environment. **Default:** `{}`.", + "name": "env", + "type": "Object", + "default": "`{}`", + "desc": "An object similar to `process.env` that the WebAssembly application will see as its environment." + }, + { + "textRaw": "`preopens` {Object} This object represents the WebAssembly application's sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine.", + "name": "preopens", + "type": "Object", + "desc": "This object represents the WebAssembly application's sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine." + }, + { + "textRaw": "`returnOnExit` {boolean} By default, WASI applications terminate the Node.js process via the `__wasi_proc_exit()` function. Setting this option to `true` causes `wasi.start()` to return the exit code rather than terminate the process. **Default:** `false`.", + "name": "returnOnExit", + "type": "boolean", + "default": "`false`", + "desc": "By default, WASI applications terminate the Node.js process via the `__wasi_proc_exit()` function. Setting this option to `true` causes `wasi.start()` to return the exit code rather than terminate the process." + }, + { + "textRaw": "`stdin` {integer} The file descriptor used as standard input in the WebAssembly application. **Default:** `0`.", + "name": "stdin", + "type": "integer", + "default": "`0`", + "desc": "The file descriptor used as standard input in the WebAssembly application." + }, + { + "textRaw": "`stdout` {integer} The file descriptor used as standard output in the WebAssembly application. **Default:** `1`.", + "name": "stdout", + "type": "integer", + "default": "`1`", + "desc": "The file descriptor used as standard output in the WebAssembly application." + }, + { + "textRaw": "`stderr` {integer} The file descriptor used as standard error in the WebAssembly application. **Default:** `2`.", + "name": "stderr", + "type": "integer", + "default": "`2`", + "desc": "The file descriptor used as standard error in the WebAssembly application." + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "WebAssembly System Interface (WASI)" + } + ] +} \ No newline at end of file diff --git a/doc/api/worker_threads.html b/doc/api/worker_threads.html new file mode 100644 index 0000000000000000000000000000000000000000..7b08c69c4b4781e5ac8e32d9c617c705fa57deca --- /dev/null +++ b/doc/api/worker_threads.html @@ -0,0 +1,1009 @@ + + + + + + + Worker threads | Node.js v12.22.7 Documentation + + + + + + +
+ + +
+
+

Node.js v12.22.7 Documentation

+ +
+
+ + + +
+

Worker threads#

+ +

Stability: 2 - Stable

+

Source Code: lib/worker_threads.js

+

The worker_threads module enables the use of threads that execute JavaScript +in parallel. To access it:

+
const worker = require('worker_threads');
+

Workers (threads) are useful for performing CPU-intensive JavaScript operations. +They will not help much with I/O-intensive work. Node.js’s built-in asynchronous +I/O operations are more efficient than Workers can be.

+

Unlike child_process or cluster, worker_threads can share memory. They do +so by transferring ArrayBuffer instances or sharing SharedArrayBuffer +instances.

+
const {
+  Worker, isMainThread, parentPort, workerData
+} = require('worker_threads');
+
+if (isMainThread) {
+  module.exports = function parseJSAsync(script) {
+    return new Promise((resolve, reject) => {
+      const worker = new Worker(__filename, {
+        workerData: script
+      });
+      worker.on('message', resolve);
+      worker.on('error', reject);
+      worker.on('exit', (code) => {
+        if (code !== 0)
+          reject(new Error(`Worker stopped with exit code ${code}`));
+      });
+    });
+  };
+} else {
+  const { parse } = require('some-js-parsing-library');
+  const script = workerData;
+  parentPort.postMessage(parse(script));
+}
+

The above example spawns a Worker thread for each parse() call. In actual +practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the +overhead of creating Workers would likely exceed their benefit.

+

When implementing a worker pool, use the AsyncResource API to inform +diagnostic tools (e.g. in order to provide asynchronous stack traces) about the +correlation between tasks and their outcomes. See +"Using AsyncResource for a Worker thread pool" +in the async_hooks documentation for an example implementation.

+

Worker threads inherit non-process-specific options by default. Refer to +Worker constructor options to know how to customize worker thread options, +specifically argv and execArgv options.

+

worker.isMainThread#

+ + +

Is true if this code is not running inside of a Worker thread.

+
const { Worker, isMainThread } = require('worker_threads');
+
+if (isMainThread) {
+  // This re-loads the current file inside a Worker instance.
+  new Worker(__filename);
+} else {
+  console.log('Inside Worker!');
+  console.log(isMainThread);  // Prints 'false'.
+}
+

worker.markAsUntransferable(object)#

+ +

Mark an object as not transferable. If object occurs in the transfer list of +a port.postMessage() call, it will be ignored.

+

In particular, this makes sense for objects that can be cloned, rather than +transferred, and which are used by other objects on the sending side. +For example, Node.js marks the ArrayBuffers it uses for its +Buffer pool with this.

+

This operation cannot be undone.

+
const { MessageChannel, markAsUntransferable } = require('worker_threads');
+
+const pooledBuffer = new ArrayBuffer(8);
+const typedArray1 = new Uint8Array(pooledBuffer);
+const typedArray2 = new Float64Array(pooledBuffer);
+
+markAsUntransferable(pooledBuffer);
+
+const { port1 } = new MessageChannel();
+port1.postMessage(typedArray1, [ typedArray1.buffer ]);
+
+// The following line prints the contents of typedArray1 -- it still owns
+// its memory and has been cloned, not transferred. Without
+// `markAsUntransferable()`, this would print an empty Uint8Array.
+// typedArray2 is intact as well.
+console.log(typedArray1);
+console.log(typedArray2);
+

There is no equivalent to this API in browsers.

+

worker.moveMessagePortToContext(port, contextifiedSandbox)#

+ + +

Transfer a MessagePort to a different vm Context. The original port +object will be rendered unusable, and the returned MessagePort instance will +take its place.

+

The returned MessagePort will be an object in the target context, and will +inherit from its global Object class. Objects passed to the +port.onmessage() listener will also be created in the target context +and inherit from its global Object class.

+

However, the created MessagePort will no longer inherit from +EventEmitter, and only port.onmessage() can be used to receive +events using it.

+

worker.parentPort#

+ + +

If this thread was spawned as a Worker, this will be a MessagePort +allowing communication with the parent thread. Messages sent using +parentPort.postMessage() will be available in the parent thread +using worker.on('message'), and messages sent from the parent thread +using worker.postMessage() will be available in this thread using +parentPort.on('message').

+
const { Worker, isMainThread, parentPort } = require('worker_threads');
+
+if (isMainThread) {
+  const worker = new Worker(__filename);
+  worker.once('message', (message) => {
+    console.log(message);  // Prints 'Hello, world!'.
+  });
+  worker.postMessage('Hello, world!');
+} else {
+  // When a message from the parent thread is received, send it back:
+  parentPort.once('message', (message) => {
+    parentPort.postMessage(message);
+  });
+}
+

worker.receiveMessageOnPort(port)#

+ + +

Receive a single message from a given MessagePort. If no message is available, +undefined is returned, otherwise an object with a single message property +that contains the message payload, corresponding to the oldest message in the +MessagePort’s queue.

+
const { MessageChannel, receiveMessageOnPort } = require('worker_threads');
+const { port1, port2 } = new MessageChannel();
+port1.postMessage({ hello: 'world' });
+
+console.log(receiveMessageOnPort(port2));
+// Prints: { message: { hello: 'world' } }
+console.log(receiveMessageOnPort(port2));
+// Prints: undefined
+

When this function is used, no 'message' event will be emitted and the +onmessage listener will not be invoked.

+

worker.resourceLimits#

+ + +

Provides the set of JS engine resource constraints inside this Worker thread. +If the resourceLimits option was passed to the Worker constructor, +this matches its values.

+

If this is used in the main thread, its value is an empty object.

+

worker.SHARE_ENV#

+ + +

A special value that can be passed as the env option of the Worker +constructor, to indicate that the current thread and the Worker thread should +share read and write access to the same set of environment variables.

+
const { Worker, SHARE_ENV } = require('worker_threads');
+new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
+  .on('exit', () => {
+    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.
+  });
+

worker.threadId#

+ + +

An integer identifier for the current thread. On the corresponding worker object +(if there is any), it is available as worker.threadId. +This value is unique for each Worker instance inside a single process.

+

worker.workerData#

+ +

An arbitrary JavaScript value that contains a clone of the data passed +to this thread’s Worker constructor.

+

The data is cloned as if using postMessage(), +according to the HTML structured clone algorithm.

+
const { Worker, isMainThread, workerData } = require('worker_threads');
+
+if (isMainThread) {
+  const worker = new Worker(__filename, { workerData: 'Hello, world!' });
+} else {
+  console.log(workerData);  // Prints 'Hello, world!'.
+}
+

Class: MessageChannel#

+ +

Instances of the worker.MessageChannel class represent an asynchronous, +two-way communications channel. +The MessageChannel has no methods of its own. new MessageChannel() +yields an object with port1 and port2 properties, which refer to linked +MessagePort instances.

+
const { MessageChannel } = require('worker_threads');
+
+const { port1, port2 } = new MessageChannel();
+port1.on('message', (message) => console.log('received', message));
+port2.postMessage({ foo: 'bar' });
+// Prints: received { foo: 'bar' } from the `port1.on('message')` listener
+

Class: MessagePort#

+ + +

Instances of the worker.MessagePort class represent one end of an +asynchronous, two-way communications channel. It can be used to transfer +structured data, memory regions and other MessagePorts between different +Workers.

+

With the exception of MessagePorts being EventEmitters rather +than EventTargets, this implementation matches browser MessagePorts.

+

Event: 'close'#

+ +

The 'close' event is emitted once either side of the channel has been +disconnected.

+
const { MessageChannel } = require('worker_threads');
+const { port1, port2 } = new MessageChannel();
+
+// Prints:
+//   foobar
+//   closed!
+port2.on('message', (message) => console.log(message));
+port2.on('close', () => console.log('closed!'));
+
+port1.postMessage('foobar');
+port1.close();
+

Event: 'message'#

+ +
    +
  • value <any> The transmitted value
  • +
+

The 'message' event is emitted for any incoming message, containing the cloned +input of port.postMessage().

+

Listeners on this event will receive a clone of the value parameter as passed +to postMessage() and no further arguments.

+

Event: 'messageerror'#

+ + +

The 'messageerror' event is emitted when deserializing a message failed.

+

port.close()#

+ +

Disables further sending of messages on either side of the connection. +This method can be called when no further communication will happen over this +MessagePort.

+

The 'close' event will be emitted on both MessagePort instances that +are part of the channel.

+

port.postMessage(value[, transferList])#

+ + +

Sends a JavaScript value to the receiving side of this channel. +value will be transferred in a way which is compatible with +the HTML structured clone algorithm.

+

In particular, the significant differences to JSON are:

+
    +
  • value may contain circular references.
  • +
  • value may contain instances of builtin JS types such as RegExps, +BigInts, Maps, Sets, etc.
  • +
  • value may contain typed arrays, both using ArrayBuffers +and SharedArrayBuffers.
  • +
  • value may contain WebAssembly.Module instances.
  • +
  • value may not contain native (C++-backed) objects other than MessagePorts, +FileHandles, and KeyObjects.
  • +
+
const { MessageChannel } = require('worker_threads');
+const { port1, port2 } = new MessageChannel();
+
+port1.on('message', (message) => console.log(message));
+
+const circularData = {};
+circularData.foo = circularData;
+// Prints: { foo: [Circular] }
+port2.postMessage(circularData);
+

transferList may be a list of ArrayBuffer, MessagePort and +FileHandle objects. +After transferring, they will not be usable on the sending side of the channel +anymore (even if they are not contained in value). Unlike with +child processes, transferring handles such as network sockets is currently +not supported.

+

If value contains SharedArrayBuffer instances, those will be accessible +from either thread. They cannot be listed in transferList.

+

value may still contain ArrayBuffer instances that are not in +transferList; in that case, the underlying memory is copied rather than moved.

+
const { MessageChannel } = require('worker_threads');
+const { port1, port2 } = new MessageChannel();
+
+port1.on('message', (message) => console.log(message));
+
+const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
+// This posts a copy of `uint8Array`:
+port2.postMessage(uint8Array);
+// This does not copy data, but renders `uint8Array` unusable:
+port2.postMessage(uint8Array, [ uint8Array.buffer ]);
+
+// The memory for the `sharedUint8Array` will be accessible from both the
+// original and the copy received by `.on('message')`:
+const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
+port2.postMessage(sharedUint8Array);
+
+// This transfers a freshly created message port to the receiver.
+// This can be used, for example, to create communication channels between
+// multiple `Worker` threads that are children of the same parent thread.
+const otherChannel = new MessageChannel();
+port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
+

Because the object cloning uses the structured clone algorithm, +non-enumerable properties, property accessors, and object prototypes are +not preserved. In particular, Buffer objects will be read as +plain Uint8Arrays on the receiving side.

+

The message object will be cloned immediately, and can be modified after +posting without having side effects.

+

For more information on the serialization and deserialization mechanisms +behind this API, see the serialization API of the v8 module.

+

Considerations when transferring TypedArrays and Buffers#

+

All TypedArray and Buffer instances are views over an underlying +ArrayBuffer. That is, it is the ArrayBuffer that actually stores +the raw data while the TypedArray and Buffer objects provide a +way of viewing and manipulating the data. It is possible and common +for multiple views to be created over the same ArrayBuffer instance. +Great care must be taken when using a transfer list to transfer an +ArrayBuffer as doing so will cause all TypedArray and Buffer +instances that share that same ArrayBuffer to become unusable.

+
const ab = new ArrayBuffer(10);
+
+const u1 = new Uint8Array(ab);
+const u2 = new Uint16Array(ab);
+
+console.log(u2.length);  // prints 5
+
+port.postMessage(u1, [u1.buffer]);
+
+console.log(u2.length);  // prints 0
+

For Buffer instances, specifically, whether the underlying +ArrayBuffer can be transferred or cloned depends entirely on how +instances were created, which often cannot be reliably determined.

+

An ArrayBuffer can be marked with markAsUntransferable() to indicate +that it should always be cloned and never transferred.

+

Depending on how a Buffer instance was created, it may or may +not own its underlying ArrayBuffer. An ArrayBuffer must not +be transferred unless it is known that the Buffer instance +owns it. In particular, for Buffers created from the internal +Buffer pool (using, for instance Buffer.from() or Buffer.alloc()), +transferring them is not possible and they will always be cloned, +which sends a copy of the entire Buffer pool. +This behavior may come with unintended higher memory +usage and possible security concerns.

+

See Buffer.allocUnsafe() for more details on Buffer pooling.

+

The ArrayBuffers for Buffer instances created using +Buffer.alloc() or Buffer.allocUnsafeSlow() can always be +transferred but doing so will render all other existing views of +those ArrayBuffers unusable.

+

port.ref()#

+ +

Opposite of unref(). Calling ref() on a previously unref()ed port will +not let the program exit if it's the only active handle left (the default +behavior). If the port is ref()ed, calling ref() again will have no effect.

+

If listeners are attached or removed using .on('message'), the port will +be ref()ed and unref()ed automatically depending on whether +listeners for the event exist.

+

port.start()#

+ +

Starts receiving messages on this MessagePort. When using this port +as an event emitter, this will be called automatically once 'message' +listeners are attached.

+

This method exists for parity with the Web MessagePort API. In Node.js, +it is only useful for ignoring messages when no event listener is present. +Node.js also diverges in its handling of .onmessage. Setting it will +automatically call .start(), but unsetting it will let messages queue up +until a new handler is set or the port is discarded.

+

port.unref()#

+ +

Calling unref() on a port will allow the thread to exit if this is the only +active handle in the event system. If the port is already unref()ed calling +unref() again will have no effect.

+

If listeners are attached or removed using .on('message'), the port will +be ref()ed and unref()ed automatically depending on whether +listeners for the event exist.

+

Class: Worker#

+ + +

The Worker class represents an independent JavaScript execution thread. +Most Node.js APIs are available inside of it.

+

Notable differences inside a Worker environment are:

+ +

Creating Worker instances inside of other Workers is possible.

+

Like Web Workers and the cluster module, two-way communication can be +achieved through inter-thread message passing. Internally, a Worker has a +built-in pair of MessagePorts that are already associated with each other +when the Worker is created. While the MessagePort object on the parent side +is not directly exposed, its functionalities are exposed through +worker.postMessage() and the worker.on('message') event +on the Worker object for the parent thread.

+

To create custom messaging channels (which is encouraged over using the default +global channel because it facilitates separation of concerns), users can create +a MessageChannel object on either thread and pass one of the +MessagePorts on that MessageChannel to the other thread through a +pre-existing channel, such as the global one.

+

See port.postMessage() for more information on how messages are passed, +and what kind of JavaScript values can be successfully transported through +the thread barrier.

+
const assert = require('assert');
+const {
+  Worker, MessageChannel, MessagePort, isMainThread, parentPort
+} = require('worker_threads');
+if (isMainThread) {
+  const worker = new Worker(__filename);
+  const subChannel = new MessageChannel();
+  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
+  subChannel.port2.on('message', (value) => {
+    console.log('received:', value);
+  });
+} else {
+  parentPort.once('message', (value) => {
+    assert(value.hereIsYourPort instanceof MessagePort);
+    value.hereIsYourPort.postMessage('the worker is sending this');
+    value.hereIsYourPort.close();
+  });
+}
+

new Worker(filename[, options])#

+ +
    +
  • filename <string> | <URL> The path to the Worker’s main script or module. Must +be either an absolute path or a relative path (i.e. relative to the +current working directory) starting with ./ or ../, or a WHATWG URL +object using file: protocol. +If options.eval is true, this is a string containing JavaScript code +rather than a path.
  • +
  • options <Object> +
      +
    • argv <any[]> List of arguments which would be stringified and appended to +process.argv in the worker. This is mostly similar to the workerData +but the values will be available on the global process.argv as if they +were passed as CLI options to the script.
    • +
    • env <Object> If set, specifies the initial value of process.env inside +the Worker thread. As a special value, worker.SHARE_ENV may be used +to specify that the parent thread and the child thread should share their +environment variables; in that case, changes to one thread’s process.env +object will affect the other thread as well. Default: process.env.
    • +
    • eval <boolean> If true and the first argument is a string, interpret +the first argument to the constructor as a script that is executed once the +worker is online.
    • +
    • execArgv <string[]> List of node CLI options passed to the worker. +V8 options (such as --max-old-space-size) and options that affect the +process (such as --title) are not supported. If set, this will be provided +as process.execArgv inside the worker. By default, options will be +inherited from the parent thread.
    • +
    • stdin <boolean> If this is set to true, then worker.stdin will +provide a writable stream whose contents will appear as process.stdin +inside the Worker. By default, no data is provided.
    • +
    • stdout <boolean> If this is set to true, then worker.stdout will +not automatically be piped through to process.stdout in the parent.
    • +
    • stderr <boolean> If this is set to true, then worker.stderr will +not automatically be piped through to process.stderr in the parent.
    • +
    • workerData <any> Any JavaScript value that will be cloned and made +available as require('worker_threads').workerData. The cloning will +occur as described in the HTML structured clone algorithm, and an error +will be thrown if the object cannot be cloned (e.g. because it contains +functions).
    • +
    • trackUnmanagedFds <boolean> If this is set to true, then the Worker will +track raw file descriptors managed through fs.open() and +fs.close(), and close them when the Worker exits, similar to other +resources like network sockets or file descriptors managed through +the FileHandle API. This option is automatically inherited by all +nested Workers. Default: false.
    • +
    • transferList <Object[]> If one or more MessagePort-like objects +are passed in workerData, a transferList is required for those +items or ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST will be thrown. +See port.postMessage() for more information.
    • +
    • resourceLimits <Object> An optional set of resource limits for the new +JS engine instance. Reaching these limits will lead to termination of the +Worker instance. These limits only affect the JS engine, and no external +data, including no ArrayBuffers. Even if these limits are set, the process +may still abort if it encounters a global out-of-memory situation. +
        +
      • maxOldGenerationSizeMb <number> The maximum size of the main heap in MB.
      • +
      • maxYoungGenerationSizeMb <number> The maximum size of a heap space for +recently created objects.
      • +
      • codeRangeSizeMb <number> The size of a pre-allocated memory range +used for generated code.
      • +
      • stackSizeMb <number> The default maximum stack size for the thread. +Small values may lead to unusable Worker instances. Default: 4.
      • +
      +
    • +
    +
  • +
+

Event: 'error'#

+ + +

The 'error' event is emitted if the worker thread throws an uncaught +exception. In that case, the worker will be terminated.

+

Event: 'exit'#

+ + +

The 'exit' event is emitted once the worker has stopped. If the worker +exited by calling process.exit(), the exitCode parameter will be the +passed exit code. If the worker was terminated, the exitCode parameter will +be 1.

+

This is the final event emitted by any Worker instance.

+

Event: 'message'#

+ +
    +
  • value <any> The transmitted value
  • +
+

The 'message' event is emitted when the worker thread has invoked +require('worker_threads').parentPort.postMessage(). +See the port.on('message') event for more details.

+

All messages sent from the worker thread will be emitted before the +'exit' event is emitted on the Worker object.

+

Event: 'messageerror'#

+ + +

The 'messageerror' event is emitted when deserializing a message failed.

+

Event: 'online'#

+ +

The 'online' event is emitted when the worker thread has started executing +JavaScript code.

+

worker.getHeapSnapshot()#

+ +
    +
  • Returns: <Promise> A promise for a Readable Stream containing +a V8 heap snapshot
  • +
+

Returns a readable stream for a V8 snapshot of the current state of the Worker. +See v8.getHeapSnapshot() for more details.

+

If the Worker thread is no longer running, which may occur before the +'exit' event is emitted, the returned Promise will be rejected +immediately with an ERR_WORKER_NOT_RUNNING error.

+

worker.performance#

+ +

An object that can be used to query performance information from a worker +instance. Similar to perf_hooks.performance.

+

performance.eventLoopUtilization([utilization1[, utilization2]])#

+ +
    +
  • utilization1 <Object> The result of a previous call to + eventLoopUtilization().
  • +
  • utilization2 <Object> The result of a previous call to + eventLoopUtilization() prior to utilization1.
  • +
  • Returns <Object> + +
  • +
+

The same call as perf_hooks eventLoopUtilization(), except the values +of the worker instance are returned.

+

One difference is that, unlike the main thread, bootstrapping within a worker +is done within the event loop. So the event loop utilization will be +immediately available once the worker's script begins execution.

+

An idle time that does not increase does not indicate that the worker is +stuck in bootstrap. The following examples shows how the worker's entire +lifetime will never accumulate any idle time, but is still be able to process +messages.

+
const { Worker, isMainThread, parentPort } = require('worker_threads');
+
+if (isMainThread) {
+  const worker = new Worker(__filename);
+  setInterval(() => {
+    worker.postMessage('hi');
+    console.log(worker.performance.eventLoopUtilization());
+  }, 100).unref();
+  return;
+}
+
+parentPort.on('message', () => console.log('msg')).unref();
+(function r(n) {
+  if (--n < 0) return;
+  const t = Date.now();
+  while (Date.now() - t < 300);
+  setImmediate(r, n);
+})(10);
+

The event loop utilization of a worker is available only after the 'online' +event emitted, and if called before this, or after the 'exit' +event, then all properties have the value of 0.

+

worker.postMessage(value[, transferList])#

+ + +

Send a message to the worker that will be received via +require('worker_threads').parentPort.on('message'). +See port.postMessage() for more details.

+

worker.ref()#

+ +

Opposite of unref(), calling ref() on a previously unref()ed worker will +not let the program exit if it's the only active handle left (the default +behavior). If the worker is ref()ed, calling ref() again will have +no effect.

+

worker.resourceLimits#

+ + +

Provides the set of JS engine resource constraints for this Worker thread. +If the resourceLimits option was passed to the Worker constructor, +this matches its values.

+

If the worker has stopped, the return value is an empty object.

+

worker.stderr#

+ + +

This is a readable stream which contains data written to process.stderr +inside the worker thread. If stderr: true was not passed to the +Worker constructor, then data will be piped to the parent thread's +process.stderr stream.

+

worker.stdin#

+ + +

If stdin: true was passed to the Worker constructor, this is a +writable stream. The data written to this stream will be made available in +the worker thread as process.stdin.

+

worker.stdout#

+ + +

This is a readable stream which contains data written to process.stdout +inside the worker thread. If stdout: true was not passed to the +Worker constructor, then data will be piped to the parent thread's +process.stdout stream.

+

worker.terminate()#

+ + +

Stop all JavaScript execution in the worker thread as soon as possible. +Returns a Promise for the exit code that is fulfilled when the +'exit' event is emitted.

+

worker.threadId#

+ + +

An integer identifier for the referenced thread. Inside the worker thread, +it is available as require('worker_threads').threadId. +This value is unique for each Worker instance inside a single process.

+

worker.unref()#

+ +

Calling unref() on a worker will allow the thread to exit if this is the only +active handle in the event system. If the worker is already unref()ed calling +unref() again will have no effect.

+ +
+
+
+ + diff --git a/doc/api/worker_threads.json b/doc/api/worker_threads.json new file mode 100644 index 0000000000000000000000000000000000000000..981ecb29bc9b7c4dafa35c1d4fbd234aad66a9e9 --- /dev/null +++ b/doc/api/worker_threads.json @@ -0,0 +1,874 @@ +{ + "type": "module", + "source": "doc/api/worker_threads.md", + "modules": [ + { + "textRaw": "Worker threads", + "name": "worker_threads", + "introduced_in": "v10.5.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

Source Code: lib/worker_threads.js

\n

The worker_threads module enables the use of threads that execute JavaScript\nin parallel. To access it:

\n
const worker = require('worker_threads');\n
\n

Workers (threads) are useful for performing CPU-intensive JavaScript operations.\nThey will not help much with I/O-intensive work. Node.js’s built-in asynchronous\nI/O operations are more efficient than Workers can be.

\n

Unlike child_process or cluster, worker_threads can share memory. They do\nso by transferring ArrayBuffer instances or sharing SharedArrayBuffer\ninstances.

\n
const {\n  Worker, isMainThread, parentPort, workerData\n} = require('worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script\n      });\n      worker.on('message', resolve);\n      worker.on('error', reject);\n      worker.on('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n
\n

The above example spawns a Worker thread for each parse() call. In actual\npractice, use a pool of Workers instead for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.

\n

When implementing a worker pool, use the AsyncResource API to inform\ndiagnostic tools (e.g. in order to provide asynchronous stack traces) about the\ncorrelation between tasks and their outcomes. See\n\"Using AsyncResource for a Worker thread pool\"\nin the async_hooks documentation for an example implementation.

\n

Worker threads inherit non-process-specific options by default. Refer to\nWorker constructor options to know how to customize worker thread options,\nspecifically argv and execArgv options.

", + "properties": [ + { + "textRaw": "`isMainThread` {boolean}", + "type": "boolean", + "name": "isMainThread", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

Is true if this code is not running inside of a Worker thread.

\n
const { Worker, isMainThread } = require('worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n
" + }, + { + "textRaw": "`parentPort` {null|MessagePort}", + "type": "null|MessagePort", + "name": "parentPort", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

If this thread was spawned as a Worker, this will be a MessagePort\nallowing communication with the parent thread. Messages sent using\nparentPort.postMessage() will be available in the parent thread\nusing worker.on('message'), and messages sent from the parent thread\nusing worker.postMessage() will be available in this thread using\nparentPort.on('message').

\n
const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n
" + }, + { + "textRaw": "`resourceLimits` {Object}", + "type": "Object", + "name": "resourceLimits", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "options": [ + { + "textRaw": "`maxYoungGenerationSizeMb` {number}", + "name": "maxYoungGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`maxOldGenerationSizeMb` {number}", + "name": "maxOldGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`codeRangeSizeMb` {number}", + "name": "codeRangeSizeMb", + "type": "number" + }, + { + "textRaw": "`stackSizeMb` {number}", + "name": "stackSizeMb", + "type": "number" + } + ], + "desc": "

Provides the set of JS engine resource constraints inside this Worker thread.\nIf the resourceLimits option was passed to the Worker constructor,\nthis matches its values.

\n

If this is used in the main thread, its value is an empty object.

" + }, + { + "textRaw": "`SHARE_ENV` {symbol}", + "type": "symbol", + "name": "SHARE_ENV", + "meta": { + "added": [ + "v11.14.0" + ], + "changes": [] + }, + "desc": "

A special value that can be passed as the env option of the Worker\nconstructor, to indicate that the current thread and the Worker thread should\nshare read and write access to the same set of environment variables.

\n
const { Worker, SHARE_ENV } = require('worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .on('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n
" + }, + { + "textRaw": "`threadId` {integer}", + "type": "integer", + "name": "threadId", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

An integer identifier for the current thread. On the corresponding worker object\n(if there is any), it is available as worker.threadId.\nThis value is unique for each Worker instance inside a single process.

" + }, + { + "textRaw": "`worker.workerData`", + "name": "workerData", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

An arbitrary JavaScript value that contains a clone of the data passed\nto this thread’s Worker constructor.

\n

The data is cloned as if using postMessage(),\naccording to the HTML structured clone algorithm.

\n
const { Worker, isMainThread, workerData } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n
" + } + ], + "methods": [ + { + "textRaw": "`worker.markAsUntransferable(object)`", + "type": "method", + "name": "markAsUntransferable", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Mark an object as not transferable. If object occurs in the transfer list of\na port.postMessage() call, it will be ignored.

\n

In particular, this makes sense for objects that can be cloned, rather than\ntransferred, and which are used by other objects on the sending side.\nFor example, Node.js marks the ArrayBuffers it uses for its\nBuffer pool with this.

\n

This operation cannot be undone.

\n
const { MessageChannel, markAsUntransferable } = require('worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\nport1.postMessage(typedArray1, [ typedArray1.buffer ]);\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has been cloned, not transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n
\n

There is no equivalent to this API in browsers.

" + }, + { + "textRaw": "`worker.moveMessagePortToContext(port, contextifiedSandbox)`", + "type": "method", + "name": "moveMessagePortToContext", + "meta": { + "added": [ + "v11.13.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {MessagePort}", + "name": "return", + "type": "MessagePort" + }, + "params": [ + { + "textRaw": "`port` {MessagePort} The message port which will be transferred.", + "name": "port", + "type": "MessagePort", + "desc": "The message port which will be transferred." + }, + { + "textRaw": "`contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", + "name": "contextifiedSandbox", + "type": "Object", + "desc": "A [contextified][] object as returned by the `vm.createContext()` method." + } + ] + } + ], + "desc": "

Transfer a MessagePort to a different vm Context. The original port\nobject will be rendered unusable, and the returned MessagePort instance will\ntake its place.

\n

The returned MessagePort will be an object in the target context, and will\ninherit from its global Object class. Objects passed to the\nport.onmessage() listener will also be created in the target context\nand inherit from its global Object class.

\n

However, the created MessagePort will no longer inherit from\nEventEmitter, and only port.onmessage() can be used to receive\nevents using it.

" + }, + { + "textRaw": "`worker.receiveMessageOnPort(port)`", + "type": "method", + "name": "receiveMessageOnPort", + "meta": { + "added": [ + "v12.3.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Object|undefined}", + "name": "return", + "type": "Object|undefined" + }, + "params": [ + { + "textRaw": "`port` {MessagePort}", + "name": "port", + "type": "MessagePort" + } + ] + } + ], + "desc": "

Receive a single message from a given MessagePort. If no message is available,\nundefined is returned, otherwise an object with a single message property\nthat contains the message payload, corresponding to the oldest message in the\nMessagePort’s queue.

\n
const { MessageChannel, receiveMessageOnPort } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n
\n

When this function is used, no 'message' event will be emitted and the\nonmessage listener will not be invoked.

" + } + ], + "classes": [ + { + "textRaw": "Class: `MessageChannel`", + "type": "class", + "name": "MessageChannel", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

Instances of the worker.MessageChannel class represent an asynchronous,\ntwo-way communications channel.\nThe MessageChannel has no methods of its own. new MessageChannel()\nyields an object with port1 and port2 properties, which refer to linked\nMessagePort instances.

\n
const { MessageChannel } = require('worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n
" + }, + { + "textRaw": "Class: `MessagePort`", + "type": "class", + "name": "MessagePort", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "\n

Instances of the worker.MessagePort class represent one end of an\nasynchronous, two-way communications channel. It can be used to transfer\nstructured data, memory regions and other MessagePorts between different\nWorkers.

\n

With the exception of MessagePorts being EventEmitters rather\nthan EventTargets, this implementation matches browser MessagePorts.

", + "events": [ + { + "textRaw": "Event: `'close'`", + "type": "event", + "name": "close", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

The 'close' event is emitted once either side of the channel has been\ndisconnected.

\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.on('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n
" + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`value` {any} The transmitted value", + "name": "value", + "type": "any", + "desc": "The transmitted value" + } + ], + "desc": "

The 'message' event is emitted for any incoming message, containing the cloned\ninput of port.postMessage().

\n

Listeners on this event will receive a clone of the value parameter as passed\nto postMessage() and no further arguments.

" + }, + { + "textRaw": "Event: `'messageerror'`", + "type": "event", + "name": "messageerror", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error} An Error object", + "name": "error", + "type": "Error", + "desc": "An Error object" + } + ], + "desc": "

The 'messageerror' event is emitted when deserializing a message failed.

" + } + ], + "methods": [ + { + "textRaw": "`port.close()`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Disables further sending of messages on either side of the connection.\nThis method can be called when no further communication will happen over this\nMessagePort.

\n

The 'close' event will be emitted on both MessagePort instances that\nare part of the channel.

" + }, + { + "textRaw": "`port.postMessage(value[, transferList])`", + "type": "method", + "name": "postMessage", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33360", + "description": "Added `KeyObject` to the list of cloneable types." + }, + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33772", + "description": "Added `FileHandle` to the list of transferable types." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + }, + { + "textRaw": "`transferList` {Object[]}", + "name": "transferList", + "type": "Object[]" + } + ] + } + ], + "desc": "

Sends a JavaScript value to the receiving side of this channel.\nvalue will be transferred in a way which is compatible with\nthe HTML structured clone algorithm.

\n

In particular, the significant differences to JSON are:

\n
    \n
  • value may contain circular references.
  • \n
  • value may contain instances of builtin JS types such as RegExps,\nBigInts, Maps, Sets, etc.
  • \n
  • value may contain typed arrays, both using ArrayBuffers\nand SharedArrayBuffers.
  • \n
  • value may contain WebAssembly.Module instances.
  • \n
  • value may not contain native (C++-backed) objects other than MessagePorts,\nFileHandles, and KeyObjects.
  • \n
\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n
\n

transferList may be a list of ArrayBuffer, MessagePort and\nFileHandle objects.\nAfter transferring, they will not be usable on the sending side of the channel\nanymore (even if they are not contained in value). Unlike with\nchild processes, transferring handles such as network sockets is currently\nnot supported.

\n

If value contains SharedArrayBuffer instances, those will be accessible\nfrom either thread. They cannot be listed in transferList.

\n

value may still contain ArrayBuffer instances that are not in\ntransferList; in that case, the underlying memory is copied rather than moved.

\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` will be accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);\n
\n

Because the object cloning uses the structured clone algorithm,\nnon-enumerable properties, property accessors, and object prototypes are\nnot preserved. In particular, Buffer objects will be read as\nplain Uint8Arrays on the receiving side.

\n

The message object will be cloned immediately, and can be modified after\nposting without having side effects.

\n

For more information on the serialization and deserialization mechanisms\nbehind this API, see the serialization API of the v8 module.

", + "modules": [ + { + "textRaw": "Considerations when transferring TypedArrays and Buffers", + "name": "considerations_when_transferring_typedarrays_and_buffers", + "desc": "

All TypedArray and Buffer instances are views over an underlying\nArrayBuffer. That is, it is the ArrayBuffer that actually stores\nthe raw data while the TypedArray and Buffer objects provide a\nway of viewing and manipulating the data. It is possible and common\nfor multiple views to be created over the same ArrayBuffer instance.\nGreat care must be taken when using a transfer list to transfer an\nArrayBuffer as doing so will cause all TypedArray and Buffer\ninstances that share that same ArrayBuffer to become unusable.

\n
const ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0\n
\n

For Buffer instances, specifically, whether the underlying\nArrayBuffer can be transferred or cloned depends entirely on how\ninstances were created, which often cannot be reliably determined.

\n

An ArrayBuffer can be marked with markAsUntransferable() to indicate\nthat it should always be cloned and never transferred.

\n

Depending on how a Buffer instance was created, it may or may\nnot own its underlying ArrayBuffer. An ArrayBuffer must not\nbe transferred unless it is known that the Buffer instance\nowns it. In particular, for Buffers created from the internal\nBuffer pool (using, for instance Buffer.from() or Buffer.alloc()),\ntransferring them is not possible and they will always be cloned,\nwhich sends a copy of the entire Buffer pool.\nThis behavior may come with unintended higher memory\nusage and possible security concerns.

\n

See Buffer.allocUnsafe() for more details on Buffer pooling.

\n

The ArrayBuffers for Buffer instances created using\nBuffer.alloc() or Buffer.allocUnsafeSlow() can always be\ntransferred but doing so will render all other existing views of\nthose ArrayBuffers unusable.

", + "type": "module", + "displayName": "Considerations when transferring TypedArrays and Buffers" + } + ] + }, + { + "textRaw": "`port.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Opposite of unref(). Calling ref() on a previously unref()ed port will\nnot let the program exit if it's the only active handle left (the default\nbehavior). If the port is ref()ed, calling ref() again will have no effect.

\n

If listeners are attached or removed using .on('message'), the port will\nbe ref()ed and unref()ed automatically depending on whether\nlisteners for the event exist.

" + }, + { + "textRaw": "`port.start()`", + "type": "method", + "name": "start", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Starts receiving messages on this MessagePort. When using this port\nas an event emitter, this will be called automatically once 'message'\nlisteners are attached.

\n

This method exists for parity with the Web MessagePort API. In Node.js,\nit is only useful for ignoring messages when no event listener is present.\nNode.js also diverges in its handling of .onmessage. Setting it will\nautomatically call .start(), but unsetting it will let messages queue up\nuntil a new handler is set or the port is discarded.

" + }, + { + "textRaw": "`port.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Calling unref() on a port will allow the thread to exit if this is the only\nactive handle in the event system. If the port is already unref()ed calling\nunref() again will have no effect.

\n

If listeners are attached or removed using .on('message'), the port will\nbe ref()ed and unref()ed automatically depending on whether\nlisteners for the event exist.

" + } + ] + }, + { + "textRaw": "Class: `Worker`", + "type": "class", + "name": "Worker", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "\n

The Worker class represents an independent JavaScript execution thread.\nMost Node.js APIs are available inside of it.

\n

Notable differences inside a Worker environment are:

\n\n

Creating Worker instances inside of other Workers is possible.

\n

Like Web Workers and the cluster module, two-way communication can be\nachieved through inter-thread message passing. Internally, a Worker has a\nbuilt-in pair of MessagePorts that are already associated with each other\nwhen the Worker is created. While the MessagePort object on the parent side\nis not directly exposed, its functionalities are exposed through\nworker.postMessage() and the worker.on('message') event\non the Worker object for the parent thread.

\n

To create custom messaging channels (which is encouraged over using the default\nglobal channel because it facilitates separation of concerns), users can create\na MessageChannel object on either thread and pass one of the\nMessagePorts on that MessageChannel to the other thread through a\npre-existing channel, such as the global one.

\n

See port.postMessage() for more information on how messages are passed,\nand what kind of JavaScript values can be successfully transported through\nthe thread barrier.

\n
const assert = require('assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort\n} = require('worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n
", + "events": [ + { + "textRaw": "Event: `'error'`", + "type": "event", + "name": "error", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`err` {Error}", + "name": "err", + "type": "Error" + } + ], + "desc": "

The 'error' event is emitted if the worker thread throws an uncaught\nexception. In that case, the worker will be terminated.

" + }, + { + "textRaw": "Event: `'exit'`", + "type": "event", + "name": "exit", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`exitCode` {integer}", + "name": "exitCode", + "type": "integer" + } + ], + "desc": "

The 'exit' event is emitted once the worker has stopped. If the worker\nexited by calling process.exit(), the exitCode parameter will be the\npassed exit code. If the worker was terminated, the exitCode parameter will\nbe 1.

\n

This is the final event emitted by any Worker instance.

" + }, + { + "textRaw": "Event: `'message'`", + "type": "event", + "name": "message", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`value` {any} The transmitted value", + "name": "value", + "type": "any", + "desc": "The transmitted value" + } + ], + "desc": "

The 'message' event is emitted when the worker thread has invoked\nrequire('worker_threads').parentPort.postMessage().\nSee the port.on('message') event for more details.

\n

All messages sent from the worker thread will be emitted before the\n'exit' event is emitted on the Worker object.

" + }, + { + "textRaw": "Event: `'messageerror'`", + "type": "event", + "name": "messageerror", + "meta": { + "added": [ + "v12.19.0" + ], + "changes": [] + }, + "params": [ + { + "textRaw": "`error` {Error} An Error object", + "name": "error", + "type": "Error", + "desc": "An Error object" + } + ], + "desc": "

The 'messageerror' event is emitted when deserializing a message failed.

" + }, + { + "textRaw": "Event: `'online'`", + "type": "event", + "name": "online", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "params": [], + "desc": "

The 'online' event is emitted when the worker thread has started executing\nJavaScript code.

" + } + ], + "methods": [ + { + "textRaw": "`worker.getHeapSnapshot()`", + "type": "method", + "name": "getHeapSnapshot", + "meta": { + "added": [ + "v12.17.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot", + "name": "return", + "type": "Promise", + "desc": "A promise for a Readable Stream containing a V8 heap snapshot" + }, + "params": [] + } + ], + "desc": "

Returns a readable stream for a V8 snapshot of the current state of the Worker.\nSee v8.getHeapSnapshot() for more details.

\n

If the Worker thread is no longer running, which may occur before the\n'exit' event is emitted, the returned Promise will be rejected\nimmediately with an ERR_WORKER_NOT_RUNNING error.

" + }, + { + "textRaw": "`worker.postMessage(value[, transferList])`", + "type": "method", + "name": "postMessage", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`value` {any}", + "name": "value", + "type": "any" + }, + { + "textRaw": "`transferList` {Object[]}", + "name": "transferList", + "type": "Object[]" + } + ] + } + ], + "desc": "

Send a message to the worker that will be received via\nrequire('worker_threads').parentPort.on('message').\nSee port.postMessage() for more details.

" + }, + { + "textRaw": "`worker.ref()`", + "type": "method", + "name": "ref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Opposite of unref(), calling ref() on a previously unref()ed worker will\nnot let the program exit if it's the only active handle left (the default\nbehavior). If the worker is ref()ed, calling ref() again will have\nno effect.

" + }, + { + "textRaw": "`worker.terminate()`", + "type": "method", + "name": "terminate", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [ + { + "version": "v12.5.0", + "pr-url": "https://github.com/nodejs/node/pull/28021", + "description": "This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation." + } + ] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns: {Promise}", + "name": "return", + "type": "Promise" + }, + "params": [] + } + ], + "desc": "

Stop all JavaScript execution in the worker thread as soon as possible.\nReturns a Promise for the exit code that is fulfilled when the\n'exit' event is emitted.

" + }, + { + "textRaw": "`worker.unref()`", + "type": "method", + "name": "unref", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Calling unref() on a worker will allow the thread to exit if this is the only\nactive handle in the event system. If the worker is already unref()ed calling\nunref() again will have no effect.

" + } + ], + "properties": [ + { + "textRaw": "`worker.performance`", + "name": "performance", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "desc": "

An object that can be used to query performance information from a worker\ninstance. Similar to perf_hooks.performance.

", + "methods": [ + { + "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", + "type": "method", + "name": "eventLoopUtilization", + "meta": { + "added": [ + "v12.22.0" + ], + "changes": [] + }, + "signatures": [ + { + "return": { + "textRaw": "Returns {Object}", + "name": "return", + "type": "Object", + "options": [ + { + "textRaw": "`idle` {number}", + "name": "idle", + "type": "number" + }, + { + "textRaw": "`active` {number}", + "name": "active", + "type": "number" + }, + { + "textRaw": "`utilization` {number}", + "name": "utilization", + "type": "number" + } + ] + }, + "params": [ + { + "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", + "name": "utilization1", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()`." + }, + { + "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", + "name": "utilization2", + "type": "Object", + "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." + } + ] + } + ], + "desc": "

The same call as perf_hooks eventLoopUtilization(), except the values\nof the worker instance are returned.

\n

One difference is that, unlike the main thread, bootstrapping within a worker\nis done within the event loop. So the event loop utilization will be\nimmediately available once the worker's script begins execution.

\n

An idle time that does not increase does not indicate that the worker is\nstuck in bootstrap. The following examples shows how the worker's entire\nlifetime will never accumulate any idle time, but is still be able to process\nmessages.

\n
const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n  return;\n}\n\nparentPort.on('message', () => console.log('msg')).unref();\n(function r(n) {\n  if (--n < 0) return;\n  const t = Date.now();\n  while (Date.now() - t < 300);\n  setImmediate(r, n);\n})(10);\n
\n

The event loop utilization of a worker is available only after the 'online'\nevent emitted, and if called before this, or after the 'exit'\nevent, then all properties have the value of 0.

" + } + ] + }, + { + "textRaw": "`resourceLimits` {Object}", + "type": "Object", + "name": "resourceLimits", + "meta": { + "added": [ + "v12.16.0" + ], + "changes": [] + }, + "options": [ + { + "textRaw": "`maxYoungGenerationSizeMb` {number}", + "name": "maxYoungGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`maxOldGenerationSizeMb` {number}", + "name": "maxOldGenerationSizeMb", + "type": "number" + }, + { + "textRaw": "`codeRangeSizeMb` {number}", + "name": "codeRangeSizeMb", + "type": "number" + }, + { + "textRaw": "`stackSizeMb` {number}", + "name": "stackSizeMb", + "type": "number" + } + ], + "desc": "

Provides the set of JS engine resource constraints for this Worker thread.\nIf the resourceLimits option was passed to the Worker constructor,\nthis matches its values.

\n

If the worker has stopped, the return value is an empty object.

" + }, + { + "textRaw": "`stderr` {stream.Readable}", + "type": "stream.Readable", + "name": "stderr", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

This is a readable stream which contains data written to process.stderr\ninside the worker thread. If stderr: true was not passed to the\nWorker constructor, then data will be piped to the parent thread's\nprocess.stderr stream.

" + }, + { + "textRaw": "`stdin` {null|stream.Writable}", + "type": "null|stream.Writable", + "name": "stdin", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

If stdin: true was passed to the Worker constructor, this is a\nwritable stream. The data written to this stream will be made available in\nthe worker thread as process.stdin.

" + }, + { + "textRaw": "`stdout` {stream.Readable}", + "type": "stream.Readable", + "name": "stdout", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

This is a readable stream which contains data written to process.stdout\ninside the worker thread. If stdout: true was not passed to the\nWorker constructor, then data will be piped to the parent thread's\nprocess.stdout stream.

" + }, + { + "textRaw": "`threadId` {integer}", + "type": "integer", + "name": "threadId", + "meta": { + "added": [ + "v10.5.0" + ], + "changes": [] + }, + "desc": "

An integer identifier for the referenced thread. Inside the worker thread,\nit is available as require('worker_threads').threadId.\nThis value is unique for each Worker instance inside a single process.

" + } + ], + "signatures": [ + { + "params": [ + { + "textRaw": "`filename` {string|URL} The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` protocol. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path.", + "name": "filename", + "type": "string|URL", + "desc": "The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` protocol. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path." + }, + { + "textRaw": "`options` {Object}", + "name": "options", + "type": "Object", + "options": [ + { + "textRaw": "`argv` {any[]} List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values will be available on the global `process.argv` as if they were passed as CLI options to the script.", + "name": "argv", + "type": "any[]", + "desc": "List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values will be available on the global `process.argv` as if they were passed as CLI options to the script." + }, + { + "textRaw": "`env` {Object} If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object will affect the other thread as well. **Default:** `process.env`.", + "name": "env", + "type": "Object", + "default": "`process.env`", + "desc": "If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object will affect the other thread as well." + }, + { + "textRaw": "`eval` {boolean} If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online.", + "name": "eval", + "type": "boolean", + "desc": "If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online." + }, + { + "textRaw": "`execArgv` {string[]} List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread.", + "name": "execArgv", + "type": "string[]", + "desc": "List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this will be provided as [`process.execArgv`][] inside the worker. By default, options will be inherited from the parent thread." + }, + { + "textRaw": "`stdin` {boolean} If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will appear as `process.stdin` inside the Worker. By default, no data is provided.", + "name": "stdin", + "type": "boolean", + "desc": "If this is set to `true`, then `worker.stdin` will provide a writable stream whose contents will appear as `process.stdin` inside the Worker. By default, no data is provided." + }, + { + "textRaw": "`stdout` {boolean} If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent.", + "name": "stdout", + "type": "boolean", + "desc": "If this is set to `true`, then `worker.stdout` will not automatically be piped through to `process.stdout` in the parent." + }, + { + "textRaw": "`stderr` {boolean} If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent.", + "name": "stderr", + "type": "boolean", + "desc": "If this is set to `true`, then `worker.stderr` will not automatically be piped through to `process.stderr` in the parent." + }, + { + "textRaw": "`workerData` {any} Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s).", + "name": "workerData", + "type": "any", + "desc": "Any JavaScript value that will be cloned and made available as [`require('worker_threads').workerData`][]. The cloning will occur as described in the [HTML structured clone algorithm][], and an error will be thrown if the object cannot be cloned (e.g. because it contains `function`s)." + }, + { + "textRaw": "`trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker will track raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default**: `false`.", + "name": "trackUnmanagedFds", + "type": "boolean", + "desc": "If this is set to `true`, then the Worker will track raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and close them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default**: `false`." + }, + { + "textRaw": "`transferList` {Object[]} If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown. See [`port.postMessage()`][] for more information.", + "name": "transferList", + "type": "Object[]", + "desc": "If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] will be thrown. See [`port.postMessage()`][] for more information." + }, + { + "textRaw": "`resourceLimits` {Object} An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", + "name": "resourceLimits", + "type": "Object", + "desc": "An optional set of resource limits for the new JS engine instance. Reaching these limits will lead to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", + "options": [ + { + "textRaw": "`maxOldGenerationSizeMb` {number} The maximum size of the main heap in MB.", + "name": "maxOldGenerationSizeMb", + "type": "number", + "desc": "The maximum size of the main heap in MB." + }, + { + "textRaw": "`maxYoungGenerationSizeMb` {number} The maximum size of a heap space for recently created objects.", + "name": "maxYoungGenerationSizeMb", + "type": "number", + "desc": "The maximum size of a heap space for recently created objects." + }, + { + "textRaw": "`codeRangeSizeMb` {number} The size of a pre-allocated memory range used for generated code.", + "name": "codeRangeSizeMb", + "type": "number", + "desc": "The size of a pre-allocated memory range used for generated code." + }, + { + "textRaw": "`stackSizeMb` {number} The default maximum stack size for the thread. Small values may lead to unusable Worker instances. **Default:** `4`.", + "name": "stackSizeMb", + "type": "number", + "default": "`4`", + "desc": "The default maximum stack size for the thread. Small values may lead to unusable Worker instances." + } + ] + } + ] + } + ] + } + ] + } + ], + "type": "module", + "displayName": "Worker threads" + } + ] +} \ No newline at end of file diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index ab016f66732ac5b5ba33b11005b834cb2f279fee..364c52c4f41c4dae98e0576286a654475b206a6f 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -767,6 +767,65 @@ If the Worker thread is no longer running, which may occur before the [`'exit'` event][] is emitted, the returned `Promise` will be rejected immediately with an [`ERR_WORKER_NOT_RUNNING`][] error. +### `worker.performance` + + +An object that can be used to query performance information from a worker +instance. Similar to [`perf_hooks.performance`][]. + +#### `performance.eventLoopUtilization([utilization1[, utilization2]])` + + +* `utilization1` {Object} The result of a previous call to + `eventLoopUtilization()`. +* `utilization2` {Object} The result of a previous call to + `eventLoopUtilization()` prior to `utilization1`. +* Returns {Object} + * `idle` {number} + * `active` {number} + * `utilization` {number} + +The same call as [`perf_hooks` `eventLoopUtilization()`][], except the values +of the worker instance are returned. + +One difference is that, unlike the main thread, bootstrapping within a worker +is done within the event loop. So the event loop utilization will be +immediately available once the worker's script begins execution. + +An `idle` time that does not increase does not indicate that the worker is +stuck in bootstrap. The following examples shows how the worker's entire +lifetime will never accumulate any `idle` time, but is still be able to process +messages. + +```js +const { Worker, isMainThread, parentPort } = require('worker_threads'); + +if (isMainThread) { + const worker = new Worker(__filename); + setInterval(() => { + worker.postMessage('hi'); + console.log(worker.performance.eventLoopUtilization()); + }, 100).unref(); + return; +} + +parentPort.on('message', () => console.log('msg')).unref(); +(function r(n) { + if (--n < 0) return; + const t = Date.now(); + while (Date.now() - t < 300); + setImmediate(r, n); +})(10); +``` + +The event loop utilization of a worker is available only after the [`'online'` +event][] emitted, and if called before this, or after the [`'exit'` +event][], then all properties have the value of `0`. + ### `worker.postMessage(value[, transferList])` +
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
+

That is: 128K for windowBits = 15 + 128K for memLevel = 8 +(default values) plus a few kilobytes for small objects.

+

For example, to reduce the default memory requirements from 256K to 128K, the +options should be set to:

+
const options = { windowBits: 14, memLevel: 7 };
+

This will, however, generally degrade compression.

+

The memory requirements for inflate are (in bytes) 1 << windowBits. +That is, 32K for windowBits = 15 (default value) plus a few kilobytes +for small objects.

+

This is in addition to a single internal output slab buffer of size +chunkSize, which defaults to 16K.

+

The speed of zlib compression is affected most dramatically by the +level setting. A higher level will result in better compression, but +will take longer to complete. A lower level will result in less +compression, but will be much faster.

+

In general, greater memory usage options will mean that Node.js has to make +fewer calls to zlib because it will be able to process more data on +each write operation. So, this is another factor that affects the +speed, at the cost of memory usage.

+

For Brotli-based streams#

+

There are equivalents to the zlib options for Brotli-based streams, although +these options have different ranges than the zlib ones:

+
    +
  • zlib’s level option matches Brotli’s BROTLI_PARAM_QUALITY option.
  • +
  • zlib’s windowBits option matches Brotli’s BROTLI_PARAM_LGWIN option.
  • +
+

See below for more details on Brotli-specific options.

+

Flushing#

+

Calling .flush() on a compression stream will make zlib return as much +output as currently possible. This may come at the cost of degraded compression +quality, but can be useful when data needs to be available as soon as possible.

+

In the following example, flush() is used to write a compressed partial +HTTP response to the client:

+
const zlib = require('zlib');
+const http = require('http');
+const { pipeline } = require('stream');
+
+http.createServer((request, response) => {
+  // For the sake of simplicity, the Accept-Encoding checks are omitted.
+  response.writeHead(200, { 'content-encoding': 'gzip' });
+  const output = zlib.createGzip();
+  let i;
+
+  pipeline(output, response, (err) => {
+    if (err) {
+      // If an error occurs, there's not much we can do because
+      // the server has already sent the 200 response code and
+      // some amount of data has already been sent to the client.
+      // The best we can do is terminate the response immediately
+      // and log the error.
+      clearInterval(i);
+      response.end();
+      console.error('An error occurred:', err);
+    }
+  });
+
+  i = setInterval(() => {
+    output.write(`The current time is ${Date()}\n`, () => {
+      // The data has been passed to zlib, but the compression algorithm may
+      // have decided to buffer the data for more efficient compression.
+      // Calling .flush() will make the data available as soon as the client
+      // is ready to receive it.
+      output.flush();
+    });
+  }, 1000);
+}).listen(1337);
+

Constants#

+ + +

zlib constants#

+

All of the constants defined in zlib.h are also defined on +require('zlib').constants. In the normal course of operations, it will not be +necessary to use these constants. They are documented so that their presence is +not surprising. This section is taken almost directly from the +zlib documentation.

+

Previously, the constants were available directly from require('zlib'), for +instance zlib.Z_NO_FLUSH. Accessing the constants directly from the module is +currently still possible but is deprecated.

+

Allowed flush values.

+
    +
  • zlib.constants.Z_NO_FLUSH
  • +
  • zlib.constants.Z_PARTIAL_FLUSH
  • +
  • zlib.constants.Z_SYNC_FLUSH
  • +
  • zlib.constants.Z_FULL_FLUSH
  • +
  • zlib.constants.Z_FINISH
  • +
  • zlib.constants.Z_BLOCK
  • +
  • zlib.constants.Z_TREES
  • +
+

Return codes for the compression/decompression functions. Negative +values are errors, positive values are used for special but normal +events.

+
    +
  • zlib.constants.Z_OK
  • +
  • zlib.constants.Z_STREAM_END
  • +
  • zlib.constants.Z_NEED_DICT
  • +
  • zlib.constants.Z_ERRNO
  • +
  • zlib.constants.Z_STREAM_ERROR
  • +
  • zlib.constants.Z_DATA_ERROR
  • +
  • zlib.constants.Z_MEM_ERROR
  • +
  • zlib.constants.Z_BUF_ERROR
  • +
  • zlib.constants.Z_VERSION_ERROR
  • +
+

Compression levels.

+
    +
  • zlib.constants.Z_NO_COMPRESSION
  • +
  • zlib.constants.Z_BEST_SPEED
  • +
  • zlib.constants.Z_BEST_COMPRESSION
  • +
  • zlib.constants.Z_DEFAULT_COMPRESSION
  • +
+

Compression strategy.

+
    +
  • zlib.constants.Z_FILTERED
  • +
  • zlib.constants.Z_HUFFMAN_ONLY
  • +
  • zlib.constants.Z_RLE
  • +
  • zlib.constants.Z_FIXED
  • +
  • zlib.constants.Z_DEFAULT_STRATEGY
  • +
+

Brotli constants#

+ +

There are several options and other constants available for Brotli-based +streams:

+

Flush operations#

+

The following values are valid flush operations for Brotli-based streams:

+
    +
  • zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)
  • +
  • zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())
  • +
  • zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)
  • +
  • zlib.constants.BROTLI_OPERATION_EMIT_METADATA +
      +
    • This particular operation may be hard to use in a Node.js context, +as the streaming layer makes it hard to know which data will end up +in this frame. Also, there is currently no way to consume this data through +the Node.js API.
    • +
    +
  • +
+

Compressor options#

+

There are several options that can be set on Brotli encoders, affecting +compression efficiency and speed. Both the keys and the values can be accessed +as properties of the zlib.constants object.

+

The most important options are:

+
    +
  • BROTLI_PARAM_MODE +
      +
    • BROTLI_MODE_GENERIC (default)
    • +
    • BROTLI_MODE_TEXT, adjusted for UTF-8 text
    • +
    • BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts
    • +
    +
  • +
  • BROTLI_PARAM_QUALITY +
      +
    • Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY, +with a default of BROTLI_DEFAULT_QUALITY.
    • +
    +
  • +
  • BROTLI_PARAM_SIZE_HINT +
      +
    • Integer value representing the expected input size; +defaults to 0 for an unknown input size.
    • +
    +
  • +
+

The following flags can be set for advanced control over the compression +algorithm and memory usage tuning:

+
    +
  • BROTLI_PARAM_LGWIN +
      +
    • Ranges from BROTLI_MIN_WINDOW_BITS to BROTLI_MAX_WINDOW_BITS, +with a default of BROTLI_DEFAULT_WINDOW, or up to +BROTLI_LARGE_MAX_WINDOW_BITS if the BROTLI_PARAM_LARGE_WINDOW flag +is set.
    • +
    +
  • +
  • BROTLI_PARAM_LGBLOCK +
      +
    • Ranges from BROTLI_MIN_INPUT_BLOCK_BITS to BROTLI_MAX_INPUT_BLOCK_BITS.
    • +
    +
  • +
  • BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING +
      +
    • Boolean flag that decreases compression ratio in favour of +decompression speed.
    • +
    +
  • +
  • BROTLI_PARAM_LARGE_WINDOW +
      +
    • Boolean flag enabling “Large Window Brotli†mode (not compatible with the +Brotli format as standardized in RFC 7932).
    • +
    +
  • +
  • BROTLI_PARAM_NPOSTFIX +
      +
    • Ranges from 0 to BROTLI_MAX_NPOSTFIX.
    • +
    +
  • +
  • BROTLI_PARAM_NDIRECT +
      +
    • Ranges from 0 to 15 << NPOSTFIX in steps of 1 << NPOSTFIX.
    • +
    +
  • +
+

Decompressor options#

+

These advanced options are available for controlling decompression:

+
    +
  • BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION +
      +
    • Boolean flag that affects internal memory allocation patterns.
    • +
    +
  • +
  • BROTLI_DECODER_PARAM_LARGE_WINDOW +
      +
    • Boolean flag enabling “Large Window Brotli†mode (not compatible with the +Brotli format as standardized in RFC 7932).
    • +
    +
  • +
+

Class: Options#

+ + +

Each zlib-based class takes an options object. No options are required.

+

Some options are only relevant when compressing and are +ignored by the decompression classes.

+ +

See the deflateInit2 and inflateInit2 documentation for more +information.

+

Class: BrotliOptions#

+ + +

Each Brotli-based class takes an options object. All options are optional.

+ +

For example:

+
const stream = zlib.createBrotliCompress({
+  chunkSize: 32 * 1024,
+  params: {
+    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
+    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
+    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
+  }
+});
+

Class: zlib.BrotliCompress#

+ +

Compress data using the Brotli algorithm.

+

Class: zlib.BrotliDecompress#

+ +

Decompress data using the Brotli algorithm.

+

Class: zlib.Deflate#

+ +

Compress data using deflate.

+

Class: zlib.DeflateRaw#

+ +

Compress data using deflate, and do not append a zlib header.

+

Class: zlib.Gunzip#

+ +

Decompress a gzip stream.

+

Class: zlib.Gzip#

+ +

Compress data using gzip.

+

Class: zlib.Inflate#

+ +

Decompress a deflate stream.

+

Class: zlib.InflateRaw#

+ +

Decompress a raw deflate stream.

+

Class: zlib.Unzip#

+ +

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting +the header.

+

Class: zlib.ZlibBase#

+ +

Not exported by the zlib module. It is documented here because it is the base +class of the compressor/decompressor classes.

+

This class inherits from stream.Transform, allowing zlib objects to be +used in pipes and similar stream operations.

+

zlib.bytesRead#

+ +

Stability: 0 - Deprecated: Use zlib.bytesWritten instead.

+ +

Deprecated alias for zlib.bytesWritten. This original name was chosen +because it also made sense to interpret the value as the number of bytes +read by the engine, but is inconsistent with other streams in Node.js that +expose values under these names.

+

zlib.bytesWritten#

+ + +

The zlib.bytesWritten property specifies the number of bytes written to +the engine, before the bytes are processed (compressed or decompressed, +as appropriate for the derived class).

+

zlib.close([callback])#

+ + +

Close the underlying handle.

+

zlib.flush([kind, ]callback)#

+ +
    +
  • kind Default: zlib.constants.Z_FULL_FLUSH for zlib-based streams, +zlib.constants.BROTLI_OPERATION_FLUSH for Brotli-based streams.
  • +
  • callback <Function>
  • +
+

Flush pending data. Don't call this frivolously, premature flushes negatively +impact the effectiveness of the compression algorithm.

+

Calling this only flushes data from the internal zlib state, and does not +perform flushing of any kind on the streams level. Rather, it behaves like a +normal call to .write(), i.e. it will be queued up behind other pending +writes and will only produce output when data is being read from the stream.

+

zlib.params(level, strategy, callback)#

+ + +

This function is only available for zlib-based streams, i.e. not Brotli.

+

Dynamically update the compression level and compression strategy. +Only applicable to deflate algorithm.

+

zlib.reset()#

+ +

Reset the compressor/decompressor to factory defaults. Only applicable to +the inflate and deflate algorithms.

+

zlib.constants#

+ +

Provides an object enumerating Zlib-related constants.

+

zlib.createBrotliCompress([options])#

+ + +

Creates and returns a new BrotliCompress object.

+

zlib.createBrotliDecompress([options])#

+ + +

Creates and returns a new BrotliDecompress object.

+

zlib.createDeflate([options])#

+ + +

Creates and returns a new Deflate object.

+

zlib.createDeflateRaw([options])#

+ + +

Creates and returns a new DeflateRaw object.

+

An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits +is set to 8 for raw deflate streams. zlib would automatically set windowBits +to 9 if was initially set to 8. Newer versions of zlib will throw an exception, +so Node.js restored the original behavior of upgrading a value of 8 to 9, +since passing windowBits = 9 to zlib actually results in a compressed stream +that effectively uses an 8-bit window only.

+

zlib.createGunzip([options])#

+ + +

Creates and returns a new Gunzip object.

+

zlib.createGzip([options])#

+ + +

Creates and returns a new Gzip object. +See example.

+

zlib.createInflate([options])#

+ + +

Creates and returns a new Inflate object.

+

zlib.createInflateRaw([options])#

+ + +

Creates and returns a new InflateRaw object.

+

zlib.createUnzip([options])#

+ + +

Creates and returns a new Unzip object.

+

Convenience methods#

+ +

All of these take a Buffer, TypedArray, DataView, +ArrayBuffer or string as the first argument, an optional second argument +to supply options to the zlib classes and will call the supplied callback +with callback(error, result).

+

Every method has a *Sync counterpart, which accept the same arguments, but +without a callback.

+

zlib.brotliCompress(buffer[, options], callback)#

+ + +

zlib.brotliCompressSync(buffer[, options])#

+ + +

Compress a chunk of data with BrotliCompress.

+

zlib.brotliDecompress(buffer[, options], callback)#

+ + +

zlib.brotliDecompressSync(buffer[, options])#

+ + +

Decompress a chunk of data with BrotliDecompress.

+

zlib.deflate(buffer[, options], callback)#

+ + +

zlib.deflateSync(buffer[, options])#

+ + +

Compress a chunk of data with Deflate.

+

zlib.deflateRaw(buffer[, options], callback)#

+ + +

zlib.deflateRawSync(buffer[, options])#

+ + +

Compress a chunk of data with DeflateRaw.

+

zlib.gunzip(buffer[, options], callback)#

+ + +

zlib.gunzipSync(buffer[, options])#

+ + +

Decompress a chunk of data with Gunzip.

+

zlib.gzip(buffer[, options], callback)#

+ + +

zlib.gzipSync(buffer[, options])#

+ + +

Compress a chunk of data with Gzip.

+

zlib.inflate(buffer[, options], callback)#

+ + +

zlib.inflateSync(buffer[, options])#

+ + +

Decompress a chunk of data with Inflate.

+

zlib.inflateRaw(buffer[, options], callback)#

+ + +

zlib.inflateRawSync(buffer[, options])#

+ + +

Decompress a chunk of data with InflateRaw.

+

zlib.unzip(buffer[, options], callback)#

+ + +

zlib.unzipSync(buffer[, options])#

+ + +

Decompress a chunk of data with Unzip.

+ + + + + + diff --git a/doc/api/zlib.json b/doc/api/zlib.json new file mode 100644 index 0000000000000000000000000000000000000000..57a9d39ed18f984de9dc56ac0b467bda1f0629d5 --- /dev/null +++ b/doc/api/zlib.json @@ -0,0 +1,2218 @@ +{ + "type": "module", + "source": "doc/api/zlib.md", + "modules": [ + { + "textRaw": "Zlib", + "name": "zlib", + "introduced_in": "v0.10.0", + "stability": 2, + "stabilityText": "Stable", + "desc": "

Source Code: lib/zlib.js

\n

The zlib module provides compression functionality implemented using Gzip,\nDeflate/Inflate, and Brotli.

\n

To access it:

\n
const zlib = require('zlib');\n
\n

Compression and decompression are built around the Node.js Streams API.

\n

Compressing or decompressing a stream (such as a file) can be accomplished by\npiping the source stream through a zlib Transform stream into a destination\nstream:

\n
const { createGzip } = require('zlib');\nconst { pipeline } = require('stream');\nconst {\n  createReadStream,\n  createWriteStream\n} = require('fs');\n\nconst gzip = createGzip();\nconst source = createReadStream('input.txt');\nconst destination = createWriteStream('input.txt.gz');\n\npipeline(source, gzip, destination, (err) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n});\n\n// Or, Promisified\n\nconst { promisify } = require('util');\nconst pipe = promisify(pipeline);\n\nasync function do_gzip(input, output) {\n  const gzip = createGzip();\n  const source = createReadStream(input);\n  const destination = createWriteStream(output);\n  await pipe(source, gzip, destination);\n}\n\ndo_gzip('input.txt', 'input.txt.gz')\n  .catch((err) => {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  });\n
\n

It is also possible to compress or decompress data in a single step:

\n
const { deflate, unzip } = require('zlib');\n\nconst input = '.................................';\ndeflate(input, (err, buffer) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n  console.log(buffer.toString('base64'));\n});\n\nconst buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');\nunzip(buffer, (err, buffer) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n  console.log(buffer.toString());\n});\n\n// Or, Promisified\n\nconst { promisify } = require('util');\nconst do_unzip = promisify(unzip);\n\ndo_unzip(buffer)\n  .then((buf) => console.log(buf.toString()))\n  .catch((err) => {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  });\n
", + "modules": [ + { + "textRaw": "Threadpool usage and performance considerations", + "name": "threadpool_usage_and_performance_considerations", + "desc": "

All zlib APIs, except those that are explicitly synchronous, use the Node.js\ninternal threadpool. This can lead to surprising effects and performance\nlimitations in some applications.

\n

Creating and using a large number of zlib objects simultaneously can cause\nsignificant memory fragmentation.

\n
const zlib = require('zlib');\n\nconst payload = Buffer.from('This is some data');\n\n// WARNING: DO NOT DO THIS!\nfor (let i = 0; i < 30000; ++i) {\n  zlib.deflate(payload, (err, buffer) => {});\n}\n
\n

In the preceding example, 30,000 deflate instances are created concurrently.\nBecause of how some operating systems handle memory allocation and\ndeallocation, this may lead to to significant memory fragmentation.

\n

It is strongly recommended that the results of compression\noperations be cached to avoid duplication of effort.

", + "type": "module", + "displayName": "Threadpool usage and performance considerations" + }, + { + "textRaw": "Compressing HTTP requests and responses", + "name": "compressing_http_requests_and_responses", + "desc": "

The zlib module can be used to implement support for the gzip, deflate\nand br content-encoding mechanisms defined by\nHTTP.

\n

The HTTP Accept-Encoding header is used within an http request to identify\nthe compression encodings accepted by the client. The Content-Encoding\nheader is used to identify the compression encodings actually applied to a\nmessage.

\n

The examples given below are drastically simplified to show the basic concept.\nUsing zlib encoding can be expensive, and the results ought to be cached.\nSee Memory usage tuning for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.

\n
// Client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst { pipeline } = require('stream');\n\nconst request = http.get({ host: 'example.com',\n                           path: '/',\n                           port: 80,\n                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });\nrequest.on('response', (response) => {\n  const output = fs.createWriteStream('example.com_index.html');\n\n  const onError = (err) => {\n    if (err) {\n      console.error('An error occurred:', err);\n      process.exitCode = 1;\n    }\n  };\n\n  switch (response.headers['content-encoding']) {\n    case 'br':\n      pipeline(response, zlib.createBrotliDecompress(), output, onError);\n      break;\n    // Or, just use zlib.createUnzip() to handle both of the following cases:\n    case 'gzip':\n      pipeline(response, zlib.createGunzip(), output, onError);\n      break;\n    case 'deflate':\n      pipeline(response, zlib.createInflate(), output, onError);\n      break;\n    default:\n      pipeline(response, output, onError);\n      break;\n  }\n});\n
\n
// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst { pipeline } = require('stream');\n\nhttp.createServer((request, response) => {\n  const raw = fs.createReadStream('index.html');\n  // Store both a compressed and an uncompressed version of the resource.\n  response.setHeader('Vary', 'Accept-Encoding');\n  let acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  const onError = (err) => {\n    if (err) {\n      // If an error occurs, there's not much we can do because\n      // the server has already sent the 200 response code and\n      // some amount of data has already been sent to the client.\n      // The best we can do is terminate the response immediately\n      // and log the error.\n      response.end();\n      console.error('An error occurred:', err);\n    }\n  };\n\n  // Note: This is not a conformant accept-encoding parser.\n  // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (/\\bdeflate\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'deflate' });\n    pipeline(raw, zlib.createDeflate(), response, onError);\n  } else if (/\\bgzip\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'gzip' });\n    pipeline(raw, zlib.createGzip(), response, onError);\n  } else if (/\\bbr\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'br' });\n    pipeline(raw, zlib.createBrotliCompress(), response, onError);\n  } else {\n    response.writeHead(200, {});\n    pipeline(raw, response, onError);\n  }\n}).listen(1337);\n
\n

By default, the zlib methods will throw an error when decompressing\ntruncated data. However, if it is known that the data is incomplete, or\nthe desire is to inspect only the beginning of a compressed file, it is\npossible to suppress the default error handling by changing the flushing\nmethod that is used to decompress the last chunk of input data:

\n
// This is a truncated version of the buffer from the above examples\nconst buffer = Buffer.from('eJzT0yMA', 'base64');\n\nzlib.unzip(\n  buffer,\n  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.\n  { finishFlush: zlib.constants.Z_SYNC_FLUSH },\n  (err, buffer) => {\n    if (err) {\n      console.error('An error occurred:', err);\n      process.exitCode = 1;\n    }\n    console.log(buffer.toString());\n  });\n
\n

This will not change the behavior in other error-throwing situations, e.g.\nwhen the input data has an invalid format. Using this method, it will not be\npossible to determine whether the input ended prematurely or lacks the\nintegrity checks, making it necessary to manually check that the\ndecompressed result is valid.

", + "type": "module", + "displayName": "Compressing HTTP requests and responses" + }, + { + "textRaw": "Flushing", + "name": "flushing", + "desc": "

Calling .flush() on a compression stream will make zlib return as much\noutput as currently possible. This may come at the cost of degraded compression\nquality, but can be useful when data needs to be available as soon as possible.

\n

In the following example, flush() is used to write a compressed partial\nHTTP response to the client:

\n
const zlib = require('zlib');\nconst http = require('http');\nconst { pipeline } = require('stream');\n\nhttp.createServer((request, response) => {\n  // For the sake of simplicity, the Accept-Encoding checks are omitted.\n  response.writeHead(200, { 'content-encoding': 'gzip' });\n  const output = zlib.createGzip();\n  let i;\n\n  pipeline(output, response, (err) => {\n    if (err) {\n      // If an error occurs, there's not much we can do because\n      // the server has already sent the 200 response code and\n      // some amount of data has already been sent to the client.\n      // The best we can do is terminate the response immediately\n      // and log the error.\n      clearInterval(i);\n      response.end();\n      console.error('An error occurred:', err);\n    }\n  });\n\n  i = setInterval(() => {\n    output.write(`The current time is ${Date()}\\n`, () => {\n      // The data has been passed to zlib, but the compression algorithm may\n      // have decided to buffer the data for more efficient compression.\n      // Calling .flush() will make the data available as soon as the client\n      // is ready to receive it.\n      output.flush();\n    });\n  }, 1000);\n}).listen(1337);\n
", + "type": "module", + "displayName": "Flushing" + } + ], + "miscs": [ + { + "textRaw": "Memory usage tuning", + "name": "Memory usage tuning", + "type": "misc", + "miscs": [ + { + "textRaw": "For zlib-based streams", + "name": "for_zlib-based_streams", + "desc": "

From zlib/zconf.h, modified for Node.js usage:

\n

The memory requirements for deflate are (in bytes):

\n\n
(1 << (windowBits + 2)) + (1 << (memLevel + 9))\n
\n

That is: 128K for windowBits = 15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.

\n

For example, to reduce the default memory requirements from 256K to 128K, the\noptions should be set to:

\n
const options = { windowBits: 14, memLevel: 7 };\n
\n

This will, however, generally degrade compression.

\n

The memory requirements for inflate are (in bytes) 1 << windowBits.\nThat is, 32K for windowBits = 15 (default value) plus a few kilobytes\nfor small objects.

\n

This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.

\n

The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.

\n

In general, greater memory usage options will mean that Node.js has to make\nfewer calls to zlib because it will be able to process more data on\neach write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.

", + "type": "misc", + "displayName": "For zlib-based streams" + }, + { + "textRaw": "For Brotli-based streams", + "name": "for_brotli-based_streams", + "desc": "

There are equivalents to the zlib options for Brotli-based streams, although\nthese options have different ranges than the zlib ones:

\n
    \n
  • zlib’s level option matches Brotli’s BROTLI_PARAM_QUALITY option.
  • \n
  • zlib’s windowBits option matches Brotli’s BROTLI_PARAM_LGWIN option.
  • \n
\n

See below for more details on Brotli-specific options.

", + "type": "misc", + "displayName": "For Brotli-based streams" + } + ] + }, + { + "textRaw": "Constants", + "name": "Constants", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "type": "misc", + "miscs": [ + { + "textRaw": "zlib constants", + "name": "zlib_constants", + "desc": "

All of the constants defined in zlib.h are also defined on\nrequire('zlib').constants. In the normal course of operations, it will not be\nnecessary to use these constants. They are documented so that their presence is\nnot surprising. This section is taken almost directly from the\nzlib documentation.

\n

Previously, the constants were available directly from require('zlib'), for\ninstance zlib.Z_NO_FLUSH. Accessing the constants directly from the module is\ncurrently still possible but is deprecated.

\n

Allowed flush values.

\n
    \n
  • zlib.constants.Z_NO_FLUSH
  • \n
  • zlib.constants.Z_PARTIAL_FLUSH
  • \n
  • zlib.constants.Z_SYNC_FLUSH
  • \n
  • zlib.constants.Z_FULL_FLUSH
  • \n
  • zlib.constants.Z_FINISH
  • \n
  • zlib.constants.Z_BLOCK
  • \n
  • zlib.constants.Z_TREES
  • \n
\n

Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.

\n
    \n
  • zlib.constants.Z_OK
  • \n
  • zlib.constants.Z_STREAM_END
  • \n
  • zlib.constants.Z_NEED_DICT
  • \n
  • zlib.constants.Z_ERRNO
  • \n
  • zlib.constants.Z_STREAM_ERROR
  • \n
  • zlib.constants.Z_DATA_ERROR
  • \n
  • zlib.constants.Z_MEM_ERROR
  • \n
  • zlib.constants.Z_BUF_ERROR
  • \n
  • zlib.constants.Z_VERSION_ERROR
  • \n
\n

Compression levels.

\n
    \n
  • zlib.constants.Z_NO_COMPRESSION
  • \n
  • zlib.constants.Z_BEST_SPEED
  • \n
  • zlib.constants.Z_BEST_COMPRESSION
  • \n
  • zlib.constants.Z_DEFAULT_COMPRESSION
  • \n
\n

Compression strategy.

\n
    \n
  • zlib.constants.Z_FILTERED
  • \n
  • zlib.constants.Z_HUFFMAN_ONLY
  • \n
  • zlib.constants.Z_RLE
  • \n
  • zlib.constants.Z_FIXED
  • \n
  • zlib.constants.Z_DEFAULT_STRATEGY
  • \n
", + "type": "misc", + "displayName": "zlib constants" + }, + { + "textRaw": "Brotli constants", + "name": "brotli_constants", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

There are several options and other constants available for Brotli-based\nstreams:

", + "modules": [ + { + "textRaw": "Flush operations", + "name": "flush_operations", + "desc": "

The following values are valid flush operations for Brotli-based streams:

\n
    \n
  • zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)
  • \n
  • zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())
  • \n
  • zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)
  • \n
  • zlib.constants.BROTLI_OPERATION_EMIT_METADATA\n
      \n
    • This particular operation may be hard to use in a Node.js context,\nas the streaming layer makes it hard to know which data will end up\nin this frame. Also, there is currently no way to consume this data through\nthe Node.js API.
    • \n
    \n
  • \n
", + "type": "module", + "displayName": "Flush operations" + }, + { + "textRaw": "Compressor options", + "name": "compressor_options", + "desc": "

There are several options that can be set on Brotli encoders, affecting\ncompression efficiency and speed. Both the keys and the values can be accessed\nas properties of the zlib.constants object.

\n

The most important options are:

\n
    \n
  • BROTLI_PARAM_MODE\n
      \n
    • BROTLI_MODE_GENERIC (default)
    • \n
    • BROTLI_MODE_TEXT, adjusted for UTF-8 text
    • \n
    • BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts
    • \n
    \n
  • \n
  • BROTLI_PARAM_QUALITY\n
      \n
    • Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY,\nwith a default of BROTLI_DEFAULT_QUALITY.
    • \n
    \n
  • \n
  • BROTLI_PARAM_SIZE_HINT\n
      \n
    • Integer value representing the expected input size;\ndefaults to 0 for an unknown input size.
    • \n
    \n
  • \n
\n

The following flags can be set for advanced control over the compression\nalgorithm and memory usage tuning:

\n
    \n
  • BROTLI_PARAM_LGWIN\n
      \n
    • Ranges from BROTLI_MIN_WINDOW_BITS to BROTLI_MAX_WINDOW_BITS,\nwith a default of BROTLI_DEFAULT_WINDOW, or up to\nBROTLI_LARGE_MAX_WINDOW_BITS if the BROTLI_PARAM_LARGE_WINDOW flag\nis set.
    • \n
    \n
  • \n
  • BROTLI_PARAM_LGBLOCK\n
      \n
    • Ranges from BROTLI_MIN_INPUT_BLOCK_BITS to BROTLI_MAX_INPUT_BLOCK_BITS.
    • \n
    \n
  • \n
  • BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING\n
      \n
    • Boolean flag that decreases compression ratio in favour of\ndecompression speed.
    • \n
    \n
  • \n
  • BROTLI_PARAM_LARGE_WINDOW\n
      \n
    • Boolean flag enabling “Large Window Brotli†mode (not compatible with the\nBrotli format as standardized in RFC 7932).
    • \n
    \n
  • \n
  • BROTLI_PARAM_NPOSTFIX\n
      \n
    • Ranges from 0 to BROTLI_MAX_NPOSTFIX.
    • \n
    \n
  • \n
  • BROTLI_PARAM_NDIRECT\n
      \n
    • Ranges from 0 to 15 << NPOSTFIX in steps of 1 << NPOSTFIX.
    • \n
    \n
  • \n
", + "type": "module", + "displayName": "Compressor options" + }, + { + "textRaw": "Decompressor options", + "name": "decompressor_options", + "desc": "

These advanced options are available for controlling decompression:

\n
    \n
  • BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION\n
      \n
    • Boolean flag that affects internal memory allocation patterns.
    • \n
    \n
  • \n
  • BROTLI_DECODER_PARAM_LARGE_WINDOW\n
      \n
    • Boolean flag enabling “Large Window Brotli†mode (not compatible with the\nBrotli format as standardized in RFC 7932).
    • \n
    \n
  • \n
", + "type": "module", + "displayName": "Decompressor options" + } + ], + "type": "misc", + "displayName": "Brotli constants" + } + ] + }, + { + "textRaw": "Class: `Options`", + "type": "misc", + "name": "Options", + "meta": { + "added": [ + "v0.11.1" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33516", + "description": "The `maxOutputLength` option is supported now." + }, + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `dictionary` option can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `dictionary` option can be an `Uint8Array` now." + }, + { + "version": "v5.11.0", + "pr-url": "https://github.com/nodejs/node/pull/6069", + "description": "The `finishFlush` option is supported now." + } + ] + }, + "desc": "

Each zlib-based class takes an options object. No options are required.

\n

Some options are only relevant when compressing and are\nignored by the decompression classes.

\n\n

See the deflateInit2 and inflateInit2 documentation for more\ninformation.

" + }, + { + "textRaw": "Class: `BrotliOptions`", + "type": "misc", + "name": "BrotliOptions", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [ + { + "version": "v12.19.0", + "pr-url": "https://github.com/nodejs/node/pull/33516", + "description": "The `maxOutputLength` option is supported now." + } + ] + }, + "desc": "

Each Brotli-based class takes an options object. All options are optional.

\n\n

For example:

\n
const stream = zlib.createBrotliCompress({\n  chunkSize: 32 * 1024,\n  params: {\n    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,\n    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,\n    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size\n  }\n});\n
" + }, + { + "textRaw": "Convenience methods", + "name": "Convenience methods", + "type": "misc", + "desc": "

All of these take a Buffer, TypedArray, DataView,\nArrayBuffer or string as the first argument, an optional second argument\nto supply options to the zlib classes and will call the supplied callback\nwith callback(error, result).

\n

Every method has a *Sync counterpart, which accept the same arguments, but\nwithout a callback.

", + "methods": [ + { + "textRaw": "`zlib.brotliCompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliCompressSync(buffer[, options])`", + "type": "method", + "name": "brotliCompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

Compress a chunk of data with BrotliCompress.

" + }, + { + "textRaw": "`zlib.brotliDecompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliDecompressSync(buffer[, options])`", + "type": "method", + "name": "brotliDecompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with BrotliDecompress.

" + }, + { + "textRaw": "`zlib.deflate(buffer[, options], callback)`", + "type": "method", + "name": "deflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateSync(buffer[, options])`", + "type": "method", + "name": "deflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Compress a chunk of data with Deflate.

" + }, + { + "textRaw": "`zlib.deflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "deflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateRawSync(buffer[, options])`", + "type": "method", + "name": "deflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Compress a chunk of data with DeflateRaw.

" + }, + { + "textRaw": "`zlib.gunzip(buffer[, options], callback)`", + "type": "method", + "name": "gunzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gunzipSync(buffer[, options])`", + "type": "method", + "name": "gunzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with Gunzip.

" + }, + { + "textRaw": "`zlib.gzip(buffer[, options], callback)`", + "type": "method", + "name": "gzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gzipSync(buffer[, options])`", + "type": "method", + "name": "gzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Compress a chunk of data with Gzip.

" + }, + { + "textRaw": "`zlib.inflate(buffer[, options], callback)`", + "type": "method", + "name": "inflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateSync(buffer[, options])`", + "type": "method", + "name": "inflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with Inflate.

" + }, + { + "textRaw": "`zlib.inflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "inflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateRawSync(buffer[, options])`", + "type": "method", + "name": "inflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with InflateRaw.

" + }, + { + "textRaw": "`zlib.unzip(buffer[, options], callback)`", + "type": "method", + "name": "unzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.unzipSync(buffer[, options])`", + "type": "method", + "name": "unzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with Unzip.

" + } + ] + } + ], + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "classes": [ + { + "textRaw": "Class: `zlib.BrotliCompress`", + "type": "class", + "name": "zlib.BrotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

Compress data using the Brotli algorithm.

" + }, + { + "textRaw": "Class: `zlib.BrotliDecompress`", + "type": "class", + "name": "zlib.BrotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "desc": "

Decompress data using the Brotli algorithm.

" + }, + { + "textRaw": "Class: `zlib.Deflate`", + "type": "class", + "name": "zlib.Deflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

Compress data using deflate.

" + }, + { + "textRaw": "Class: `zlib.DeflateRaw`", + "type": "class", + "name": "zlib.DeflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

Compress data using deflate, and do not append a zlib header.

" + }, + { + "textRaw": "Class: `zlib.Gunzip`", + "type": "class", + "name": "zlib.Gunzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v6.0.0", + "pr-url": "https://github.com/nodejs/node/pull/5883", + "description": "Trailing garbage at the end of the input stream will now result in an `'error'` event." + }, + { + "version": "v5.9.0", + "pr-url": "https://github.com/nodejs/node/pull/5120", + "description": "Multiple concatenated gzip file members are supported now." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2595", + "description": "A truncated input stream will now result in an `'error'` event." + } + ] + }, + "desc": "

Decompress a gzip stream.

" + }, + { + "textRaw": "Class: `zlib.Gzip`", + "type": "class", + "name": "zlib.Gzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

Compress data using gzip.

" + }, + { + "textRaw": "Class: `zlib.Inflate`", + "type": "class", + "name": "zlib.Inflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2595", + "description": "A truncated input stream will now result in an `'error'` event." + } + ] + }, + "desc": "

Decompress a deflate stream.

" + }, + { + "textRaw": "Class: `zlib.InflateRaw`", + "type": "class", + "name": "zlib.InflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v6.8.0", + "pr-url": "https://github.com/nodejs/node/pull/8512", + "description": "Custom dictionaries are now supported by `InflateRaw`." + }, + { + "version": "v5.0.0", + "pr-url": "https://github.com/nodejs/node/pull/2595", + "description": "A truncated input stream will now result in an `'error'` event." + } + ] + }, + "desc": "

Decompress a raw deflate stream.

" + }, + { + "textRaw": "Class: `zlib.Unzip`", + "type": "class", + "name": "zlib.Unzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.

" + }, + { + "textRaw": "Class: `zlib.ZlibBase`", + "type": "class", + "name": "zlib.ZlibBase", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [ + { + "version": "v11.7.0", + "pr-url": "https://github.com/nodejs/node/pull/24939", + "description": "This class was renamed from `Zlib` to `ZlibBase`." + } + ] + }, + "desc": "

Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.

\n

This class inherits from stream.Transform, allowing zlib objects to be\nused in pipes and similar stream operations.

", + "properties": [ + { + "textRaw": "`bytesRead` {number}", + "type": "number", + "name": "bytesRead", + "meta": { + "added": [ + "v8.1.0" + ], + "deprecated": [ + "v10.0.0" + ], + "changes": [] + }, + "stability": 0, + "stabilityText": "Deprecated: Use [`zlib.bytesWritten`][] instead.", + "desc": "

Deprecated alias for zlib.bytesWritten. This original name was chosen\nbecause it also made sense to interpret the value as the number of bytes\nread by the engine, but is inconsistent with other streams in Node.js that\nexpose values under these names.

" + }, + { + "textRaw": "`bytesWritten` {number}", + "type": "number", + "name": "bytesWritten", + "meta": { + "added": [ + "v10.0.0" + ], + "changes": [] + }, + "desc": "

The zlib.bytesWritten property specifies the number of bytes written to\nthe engine, before the bytes are processed (compressed or decompressed,\nas appropriate for the derived class).

" + } + ], + "methods": [ + { + "textRaw": "`zlib.close([callback])`", + "type": "method", + "name": "close", + "meta": { + "added": [ + "v0.9.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

Close the underlying handle.

" + }, + { + "textRaw": "`zlib.flush([kind, ]callback)`", + "type": "method", + "name": "flush", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.", + "name": "kind", + "default": "`zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.

\n

Calling this only flushes data from the internal zlib state, and does not\nperform flushing of any kind on the streams level. Rather, it behaves like a\nnormal call to .write(), i.e. it will be queued up behind other pending\nwrites and will only produce output when data is being read from the stream.

" + }, + { + "textRaw": "`zlib.params(level, strategy, callback)`", + "type": "method", + "name": "params", + "meta": { + "added": [ + "v0.11.4" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`level` {integer}", + "name": "level", + "type": "integer" + }, + { + "textRaw": "`strategy` {integer}", + "name": "strategy", + "type": "integer" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ], + "desc": "

This function is only available for zlib-based streams, i.e. not Brotli.

\n

Dynamically update the compression level and compression strategy.\nOnly applicable to deflate algorithm.

" + }, + { + "textRaw": "`zlib.reset()`", + "type": "method", + "name": "reset", + "meta": { + "added": [ + "v0.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [] + } + ], + "desc": "

Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.

" + } + ] + } + ], + "properties": [ + { + "textRaw": "`zlib.constants`", + "name": "constants", + "meta": { + "added": [ + "v7.0.0" + ], + "changes": [] + }, + "desc": "

Provides an object enumerating Zlib-related constants.

" + } + ], + "methods": [ + { + "textRaw": "`zlib.createBrotliCompress([options])`", + "type": "method", + "name": "createBrotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

Creates and returns a new BrotliCompress object.

" + }, + { + "textRaw": "`zlib.createBrotliDecompress([options])`", + "type": "method", + "name": "createBrotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

Creates and returns a new BrotliDecompress object.

" + }, + { + "textRaw": "`zlib.createDeflate([options])`", + "type": "method", + "name": "createDeflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new Deflate object.

" + }, + { + "textRaw": "`zlib.createDeflateRaw([options])`", + "type": "method", + "name": "createDeflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new DeflateRaw object.

\n

An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits\nis set to 8 for raw deflate streams. zlib would automatically set windowBits\nto 9 if was initially set to 8. Newer versions of zlib will throw an exception,\nso Node.js restored the original behavior of upgrading a value of 8 to 9,\nsince passing windowBits = 9 to zlib actually results in a compressed stream\nthat effectively uses an 8-bit window only.

" + }, + { + "textRaw": "`zlib.createGunzip([options])`", + "type": "method", + "name": "createGunzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new Gunzip object.

" + }, + { + "textRaw": "`zlib.createGzip([options])`", + "type": "method", + "name": "createGzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new Gzip object.\nSee example.

" + }, + { + "textRaw": "`zlib.createInflate([options])`", + "type": "method", + "name": "createInflate", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new Inflate object.

" + }, + { + "textRaw": "`zlib.createInflateRaw([options])`", + "type": "method", + "name": "createInflateRaw", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new InflateRaw object.

" + }, + { + "textRaw": "`zlib.createUnzip([options])`", + "type": "method", + "name": "createUnzip", + "meta": { + "added": [ + "v0.5.8" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Creates and returns a new Unzip object.

" + }, + { + "textRaw": "`zlib.brotliCompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliCompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliCompressSync(buffer[, options])`", + "type": "method", + "name": "brotliCompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

Compress a chunk of data with BrotliCompress.

" + }, + { + "textRaw": "`zlib.brotliDecompress(buffer[, options], callback)`", + "type": "method", + "name": "brotliDecompress", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.brotliDecompressSync(buffer[, options])`", + "type": "method", + "name": "brotliDecompressSync", + "meta": { + "added": [ + "v11.7.0" + ], + "changes": [] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {brotli options}", + "name": "options", + "type": "brotli options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with BrotliDecompress.

" + }, + { + "textRaw": "`zlib.deflate(buffer[, options], callback)`", + "type": "method", + "name": "deflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateSync(buffer[, options])`", + "type": "method", + "name": "deflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Compress a chunk of data with Deflate.

" + }, + { + "textRaw": "`zlib.deflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "deflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.deflateRawSync(buffer[, options])`", + "type": "method", + "name": "deflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Compress a chunk of data with DeflateRaw.

" + }, + { + "textRaw": "`zlib.gunzip(buffer[, options], callback)`", + "type": "method", + "name": "gunzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gunzipSync(buffer[, options])`", + "type": "method", + "name": "gunzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with Gunzip.

" + }, + { + "textRaw": "`zlib.gzip(buffer[, options], callback)`", + "type": "method", + "name": "gzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.gzipSync(buffer[, options])`", + "type": "method", + "name": "gzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Compress a chunk of data with Gzip.

" + }, + { + "textRaw": "`zlib.inflate(buffer[, options], callback)`", + "type": "method", + "name": "inflate", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateSync(buffer[, options])`", + "type": "method", + "name": "inflateSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with Inflate.

" + }, + { + "textRaw": "`zlib.inflateRaw(buffer[, options], callback)`", + "type": "method", + "name": "inflateRaw", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.inflateRawSync(buffer[, options])`", + "type": "method", + "name": "inflateRawSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with InflateRaw.

" + }, + { + "textRaw": "`zlib.unzip(buffer[, options], callback)`", + "type": "method", + "name": "unzip", + "meta": { + "added": [ + "v0.6.0" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + }, + { + "textRaw": "`callback` {Function}", + "name": "callback", + "type": "Function" + } + ] + } + ] + }, + { + "textRaw": "`zlib.unzipSync(buffer[, options])`", + "type": "method", + "name": "unzipSync", + "meta": { + "added": [ + "v0.11.12" + ], + "changes": [ + { + "version": "v9.4.0", + "pr-url": "https://github.com/nodejs/node/pull/16042", + "description": "The `buffer` parameter can be an `ArrayBuffer`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12223", + "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." + }, + { + "version": "v8.0.0", + "pr-url": "https://github.com/nodejs/node/pull/12001", + "description": "The `buffer` parameter can be an `Uint8Array` now." + } + ] + }, + "signatures": [ + { + "params": [ + { + "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", + "name": "buffer", + "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" + }, + { + "textRaw": "`options` {zlib options}", + "name": "options", + "type": "zlib options" + } + ] + } + ], + "desc": "

Decompress a chunk of data with Unzip.

" + } + ], + "type": "module", + "displayName": "Zlib" + } + ] +} \ No newline at end of file diff --git a/doc/changelogs/CHANGELOG_V12.md b/doc/changelogs/CHANGELOG_V12.md index 1a85a3eaab967243c13622ee787dea8689ff8122..58153dce08220596c312a3746b44438499c3fbb5 100644 --- a/doc/changelogs/CHANGELOG_V12.md +++ b/doc/changelogs/CHANGELOG_V12.md @@ -11,6 +11,14 @@ +12.22.7
+12.22.6
+12.22.5
+12.22.4
+12.22.3
+12.22.2
+12.22.1
+12.22.0
12.21.0
12.20.2
12.20.1
@@ -69,6 +77,242 @@ * [io.js](CHANGELOG_IOJS.md) * [Archive](CHANGELOG_ARCHIVE.md) + +## 2021-10-12, Version 12.22.7 'Erbium' (LTS), @danielleadams + +This is a security release. + +### Notable changes + +* **CVE-2021-22959**: HTTP Request Smuggling due to spaced in headers (Medium) + * The http parser accepts requests with a space (SP) right after the header name before the colon. This can lead to HTTP Request Smuggling (HRS). More details will be available at [CVE-2021-22959](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22959) after publication. +* **CVE-2021-22960**: HTTP Request Smuggling when parsing the body (Medium) + * The parse ignores chunk extensions when parsing the body of chunked requests. This leads to HTTP Request Smuggling (HRS) under certain conditions. More details will be available at [CVE-2021-22960](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22960) after publication. + +### Commits + +* [[`21a2e554e3`](https://github.com/nodejs/node/commit/21a2e554e3)] - **deps**: update llhttp to 2.1.4 (Fedor Indutny) [nodejs-private/node-private#286](https://github.com/nodejs-private/node-private/pull/286) +* [[`d5d3a03246`](https://github.com/nodejs/node/commit/d5d3a03246)] - **http**: add regression test for smuggling content length (Matteo Collina) [nodejs-private/node-private#286](https://github.com/nodejs-private/node-private/pull/286) +* [[`0858587f21`](https://github.com/nodejs/node/commit/0858587f21)] - **http**: add regression test for chunked smuggling (Matteo Collina) [nodejs-private/node-private#286](https://github.com/nodejs-private/node-private/pull/286) + + +## 2021-08-31, Version 12.22.6 'Erbium' (LTS), @MylesBorins + +This is a security release. + +### Notable Changes + +These are vulnerabilities in the node-tar, arborist, and npm cli modules which +are related to the initial reports and subsequent remediation of node-tar +vulnerabilities [CVE-2021-32803](https://github.com/advisories/GHSA-r628-mhmh-qjhw) +and [CVE-2021-32804](https://github.com/advisories/GHSA-3jfq-g458-7qm9). +Subsequent internal security review of node-tar and additional external bounty +reports have resulted in another 5 CVE being remediated in core npm CLI +dependencies including node-tar, and npm arborist. + +You can read more about it in: + +* [CVE-2021-37701](https://github.com/npm/node-tar/security/advisories/GHSA-9r2w-394v-53qc) +* [CVE-2021-37712](https://github.com/npm/node-tar/security/advisories/GHSA-qq89-hq3f-393p) +* [CVE-2021-37713](https://github.com/npm/node-tar/security/advisories/GHSA-5955-9wpr-37jh) +* [CVE-2021-39134](https://github.com/npm/arborist/security/advisories/GHSA-2h3h-q99f-3fhc) +* [CVE-2021-39135](https://github.com/npm/arborist/security/advisories/GHSA-gmw6-94gg-2rc2) + +### Commits + +* [[`a0154b586b`](https://github.com/nodejs/node/commit/a0154b586b)] - **deps**: update archs files for OpenSSL-1.1.1l (Richard Lau) [#39869](https://github.com/nodejs/node/pull/39869) +* [[`7a95637eb7`](https://github.com/nodejs/node/commit/7a95637eb7)] - **deps**: upgrade openssl sources to 1.1.1l (Richard Lau) [#39869](https://github.com/nodejs/node/pull/39869) +* [[`840b0ffff6`](https://github.com/nodejs/node/commit/840b0ffff6)] - **deps**: upgrade npm to 6.14.15 (Darcy Clarke) [#39856](https://github.com/nodejs/node/pull/39856) + + +## 2021-08-11, Version 12.22.5 'Erbium' (LTS), @BethGriggs + +This is a security release. + +### Notable Changes + +* **CVE-2021-3672/CVE-2021-22931**: Improper handling of untypical characters in domain names (High) + * Node.js was vulnerable to Remote Code Execution, XSS, application crashes due to missing input validation of hostnames returned by Domain Name Servers in the Node.js DNS library which can lead to the output of wrong hostnames (leading to Domain Hijacking) and injection vulnerabilities in applications using the library. You can read more about it at https://nvd.nist.gov/vuln/detail/CVE-2021-22931. +* **CVE-2021-22930**: Use after free on close http2 on stream canceling (High) + * Node.js was vulnerable to a use after free attack where an attacker might be able to exploit memory corruption to change process behavior. This release includes a follow-up fix for CVE-2021-22930 as the issue was not completely resolved by the previous fix. You can read more about it at https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22930. +* **CVE-2021-22939**: Incomplete validation of rejectUnauthorized parameter (Low) + * If the Node.js HTTPS API was used incorrectly and "undefined" was in passed for the "rejectUnauthorized" parameter, no error was returned and connections to servers with an expired certificate would have been accepted. You can read more about it at https://nvd.nist.gov/vuln/detail/CVE-2021-22939. + +### Commits + +* [[`5f947db68c`](https://github.com/nodejs/node/commit/5f947db68c)] - **deps**: update c-ares to 1.17.2 (Beth Griggs) [#39724](https://github.com/nodejs/node/pull/39724) +* [[`42695ea34b`](https://github.com/nodejs/node/commit/42695ea34b)] - **deps**: reflect c-ares source tree (Beth Griggs) [#39653](https://github.com/nodejs/node/pull/39653) +* [[`e4c9156b32`](https://github.com/nodejs/node/commit/e4c9156b32)] - **deps**: apply missed updates from c-ares 1.17.1 (Beth Griggs) [#39653](https://github.com/nodejs/node/pull/39653) +* [[`9cd1f53103`](https://github.com/nodejs/node/commit/9cd1f53103)] - **http2**: add tests for cancel event while client is paused reading (Akshay K) [#39622](https://github.com/nodejs/node/pull/39622) +* [[`2008c9722f`](https://github.com/nodejs/node/commit/2008c9722f)] - **http2**: update handling of rst\_stream with error code NGHTTP2\_CANCEL (Akshay K) [#39622](https://github.com/nodejs/node/pull/39622) +* [[`1780bbc329`](https://github.com/nodejs/node/commit/1780bbc329)] - **tls**: validate "rejectUnauthorized: undefined" (Matteo Collina) [nodejs-private/node-private#276](https://github.com/nodejs-private/node-private/pull/276) + + +## 2021-07-29, Version 12.22.4 'Erbium' (LTS), @richardlau + +This is a security release. + +### Notable Changes + +* **CVE-2021-22930**: Use after free on close http2 on stream canceling (High) + * Node.js is vulnerable to a use after free attack where an attacker might be able to exploit the memory corruption, to change process behavior. You can read more about it in https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22930 + +### Commits + +* [[`499e56babe`](https://github.com/nodejs/node/commit/499e56babe)] - **build**: fix label-pr workflow (Michaël Zasso) [#38399](https://github.com/nodejs/node/pull/38399) +* [[`98ac3c4108`](https://github.com/nodejs/node/commit/98ac3c4108)] - **build**: label PRs with GitHub Action instead of nodejs-github-bot (Phillip Johnsen) [#38301](https://github.com/nodejs/node/pull/38301) +* [[`ddc8dde150`](https://github.com/nodejs/node/commit/ddc8dde150)] - **deps**: upgrade npm to 6.14.14 (Darcy Clarke) [#39553](https://github.com/nodejs/node/pull/39553) +* [[`e11a862eed`](https://github.com/nodejs/node/commit/e11a862eed)] - **deps**: update to c-ares 1.17.1 (Danny Sonnenschein) [#36207](https://github.com/nodejs/node/pull/36207) +* [[`39e9cd540f`](https://github.com/nodejs/node/commit/39e9cd540f)] - **deps**: restore minimum ICU version to 65 (Richard Lau) [#39068](https://github.com/nodejs/node/pull/39068) +* [[`e459c79b02`](https://github.com/nodejs/node/commit/e459c79b02)] - **deps**: V8: cherry-pick 035c305ce776 (Michaël Zasso) [#38497](https://github.com/nodejs/node/pull/38497) +* [[`b3c698a5d8`](https://github.com/nodejs/node/commit/b3c698a5d8)] - **deps**: update to cjs-module-lexer@1.2.1 (Guy Bedford) [#38450](https://github.com/nodejs/node/pull/38450) +* [[`7d5a2f9588`](https://github.com/nodejs/node/commit/7d5a2f9588)] - **deps**: update to cjs-module-lexer@1.1.1 (Guy Bedford) [#37992](https://github.com/nodejs/node/pull/37992) +* [[`906b43e586`](https://github.com/nodejs/node/commit/906b43e586)] - **deps**: V8: update build dependencies (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`15b91fa3fa`](https://github.com/nodejs/node/commit/15b91fa3fa)] - **deps**: V8: backport 895949419186 (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`8046daf09f`](https://github.com/nodejs/node/commit/8046daf09f)] - **deps**: V8: cherry-pick 0b3a4ecf7083 (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`f4377b13a6`](https://github.com/nodejs/node/commit/f4377b13a6)] - **deps**: V8: cherry-pick 7c182bd65f42 (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`add7b5b4c2`](https://github.com/nodejs/node/commit/add7b5b4c2)] - **deps**: V8: cherry-pick cc641f6be756 (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`a73275f056`](https://github.com/nodejs/node/commit/a73275f056)] - **deps**: V8: cherry-pick 7b3332844212 (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`492b0d6b37`](https://github.com/nodejs/node/commit/492b0d6b37)] - **deps**: V8: cherry-pick e6f62a41f5ee (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`2b54156260`](https://github.com/nodejs/node/commit/2b54156260)] - **deps**: V8: cherry-pick 92e6d3317082 (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`bbceab4d91`](https://github.com/nodejs/node/commit/bbceab4d91)] - **deps**: V8: backport 1b1eda0876aa (Michaël Zasso) [#39245](https://github.com/nodejs/node/pull/39245) +* [[`93a1a3c5ae`](https://github.com/nodejs/node/commit/93a1a3c5ae)] - **deps**: V8: cherry-pick 530080c44af2 (Milad Fa) [#38509](https://github.com/nodejs/node/pull/38509) +* [[`b263f2585a`](https://github.com/nodejs/node/commit/b263f2585a)] - **http2**: on receiving rst\_stream with cancel code add it to pending list (Akshay K) [#39423](https://github.com/nodejs/node/pull/39423) +* [[`3e4bc1b0d3`](https://github.com/nodejs/node/commit/3e4bc1b0d3)] - **module**: fix legacy `node` specifier resolution to resolve `"main"` field (Antoine du Hamel) [#38979](https://github.com/nodejs/node/pull/38979) +* [[`f552c45676`](https://github.com/nodejs/node/commit/f552c45676)] - **src**: move CHECK in AddIsolateFinishedCallback (Fedor Indutny) [#38010](https://github.com/nodejs/node/pull/38010) +* [[`30ce0e66ae`](https://github.com/nodejs/node/commit/30ce0e66ae)] - **src**: update cares\_wrap OpenBSD defines (Anna Henningsen) [#38670](https://github.com/nodejs/node/pull/38670) + + +## 2021-07-05, Version 12.22.3 'Erbium' (LTS), @richardlau + +### Notable Changes + +Node.js 12.22.2 introduced a regression in the Windows installer on +non-English locales that is being fixed in this release. There is no +need to download this release if you are not using the Windows +installer. + +### Commits + +* [[`182f86a4d4`](https://github.com/nodejs/node/commit/182f86a4d4)] - **win,msi**: use localized "Authenticated Users" name (Richard Lau) [#39241](https://github.com/nodejs/node/pull/39241) + + +## 2021-07-01, Version 12.22.2 'Erbium' (LTS), @richardlau + +This is a security release. + +### Notable Changes + +Vulnerabilities fixed: + +* **CVE-2021-22918**: libuv upgrade - Out of bounds read (Medium) + * Node.js is vulnerable to out-of-bounds read in libuv's uv__idna_toascii() function which is used to convert strings to ASCII. This is called by Node's dns module's lookup() function and can lead to information disclosures or crashes. You can read more about it in https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22918 +* **CVE-2021-22921**: Windows installer - Node Installer Local Privilege Escalation (Medium) + * Node.js is vulnerable to local privilege escalation attacks under certain conditions on Windows platforms. More specifically, improper configuration of permissions in the installation directory allows an attacker to perform two different escalation attacks: PATH and DLL hijacking. You can read more about it in https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-22921 +* **CVE-2021-27290**: npm upgrade - ssri Regular Expression Denial of Service (ReDoS) (High) + * This is a vulnerability in the ssri npm mudule which may be vulnerable to denial of service attacks. You can read more about it in https://github.com/advisories/GHSA-vx3p-948g-6vhq +* **CVE-2021-23362**: npm upgrade - hosted-git-info Regular Expression Denial of Service (ReDoS) (Medium) + * This is a vulnerability in the hosted-git-info npm mudule which may be vulnerable to denial of service attacks. You can read more about it in https://nvd.nist.gov/vuln/detail/CVE-2021-23362 + +### Commits + +* [[`623fd1fcb5`](https://github.com/nodejs/node/commit/623fd1fcb5)] - **deps**: uv: cherry-pick 99c29c9c2c9b (Ben Noordhuis) [nodejs-private/node-private#267](https://github.com/nodejs-private/node-private/pull/267) +* [[`923b3760f8`](https://github.com/nodejs/node/commit/923b3760f8)] - **deps**: upgrade npm to 6.14.13 (Ruy Adorno) [#38214](https://github.com/nodejs/node/pull/38214) +* [[`a52790cba0`](https://github.com/nodejs/node/commit/a52790cba0)] - **win,msi**: set install directory permission (AkshayK) [nodejs-private/node-private#269](https://github.com/nodejs-private/node-private/pull/269) + + +## 2021-04-06, Version 12.22.1 'Erbium' (LTS), @mylesborins + +This is a security release. + +### Notable Changes + +Vulnerabilities fixed: + +* **CVE-2021-3450**: OpenSSL - CA certificate check bypass with X509_V_FLAG_X509_STRICT (High) + * This is a vulnerability in OpenSSL which may be exploited through Node.js. You can read more about it in https://www.openssl.org/news/secadv/20210325.txt + * Impacts: + * All versions of the 15.x, 14.x, 12.x and 10.x releases lines +* **CVE-2021-3449**: OpenSSL - NULL pointer deref in signature_algorithms processing (High) + * This is a vulnerability in OpenSSL which may be exploited through Node.js. You can read more about it in https://www.openssl.org/news/secadv/20210325.txt + * Impacts: + * All versions of the 15.x, 14.x, 12.x and 10.x releases lines +* **CVE-2020-7774**: npm upgrade - Update y18n to fix Prototype-Pollution (High) + * This is a vulnerability in the y18n npm module which may be exploited by prototype pollution. You can read more about it in https://github.com/advisories/GHSA-c4w7-xm78-47vh + * Impacts: + * All versions of the 14.x, 12.x and 10.x releases lines + +### Commits + +* [[`c947f1a0e1`](https://github.com/nodejs/node/commit/c947f1a0e1)] - **deps**: upgrade npm to 6.14.12 (Ruy Adorno) [#37918](https://github.com/nodejs/node/pull/37918) +* [[`51a753c06f`](https://github.com/nodejs/node/commit/51a753c06f)] - **deps**: update archs files for OpenSSL-1.1.1k (Tobias Nießen) [#37939](https://github.com/nodejs/node/pull/37939) +* [[`c85a519b48`](https://github.com/nodejs/node/commit/c85a519b48)] - **deps**: upgrade openssl sources to 1.1.1k (Tobias Nießen) [#37939](https://github.com/nodejs/node/pull/37939) + + +## 2021-03-30, Version 12.22.0 'Erbium' (LTS), @richardlau + +### Notable changes + +#### The legacy HTTP parser is runtime deprecated + +The legacy HTTP parser, selected by the `--http-parser=legacy` command line +option, is deprecated with the pending End-of-Life of Node.js 10.x (where it +is the only HTTP parser implementation provided) at the end of April 2021. It +will now warn on use but otherwise continue to function and may be removed in +a future Node.js 12.x release. + +The default HTTP parser based on llhttp is not affected. By default it is +stricter than the now deprecated legacy HTTP parser. If interoperability with +HTTP implementations that send invalid HTTP headers is required, the HTTP +parser can be started in a less secure mode with the +[`--insecure-http-parser`](https://nodejs.org/docs/latest-v12.x/api/cli.html#cli_insecure_http_parser) +command line option. + +Contributed by Beth Griggs [#37603](https://github.com/nodejs/node/pull/37603). + +#### ES Modules + +ES Modules are now considered stable. + +Contributed by Guy Bedford [#35781](https://github.com/nodejs/node/pull/35781) + +#### node-api + +Updated to node-api version 8 and added an experimental API to allow retrieval of the add-on file name. + +Contributed by Gabriel Schulhof [#37652](https://github.com/nodejs/node/pull/37652) and [#37195](https://github.com/nodejs/node/pull/37195). + +#### New API's to control code coverage data collection + +`v8.stopCoverage()` and `v8.takeCoverage()` have been added. + +Contributed by Joyee Cheung [#33807](https://github.com/nodejs/node/pull/33807). + +#### New API to monitor event loop utilization by Worker threads + +`worker.performance.eventLoopUtilization()` has been added. + +Contributed by Trevor Norris [#35664](https://github.com/nodejs/node/pull/35664). + +### Commits + +* [[`1872625990`](https://github.com/nodejs/node/commit/1872625990)] - **(SEMVER-MINOR)** **deps**: update to cjs-module-lexer@1.1.0 (Guy Bedford) [#37712](https://github.com/nodejs/node/pull/37712) +* [[`dfa04d9035`](https://github.com/nodejs/node/commit/dfa04d9035)] - **deps**: V8: cherry-pick beebee4f80ff (Peter Marshall) [#37293](https://github.com/nodejs/node/pull/37293) +* [[`bf8733fe22`](https://github.com/nodejs/node/commit/bf8733fe22)] - **doc**: mark modules implementation as stable (Guy Bedford) [#35781](https://github.com/nodejs/node/pull/35781) +* [[`0a35d49f56`](https://github.com/nodejs/node/commit/0a35d49f56)] - ***Revert*** "**embedding**: make Stop() stop Workers" (Anna Henningsen) [#32623](https://github.com/nodejs/node/pull/32623) +* [[`a0b610450a`](https://github.com/nodejs/node/commit/a0b610450a)] - **(SEMVER-MINOR)** **http**: runtime deprecate legacy HTTP parser (Beth Griggs) [#37603](https://github.com/nodejs/node/pull/37603) +* [[`2da24ac302`](https://github.com/nodejs/node/commit/2da24ac302)] - **lib**: add URI handling functions to primordials (Antoine du Hamel) [#37394](https://github.com/nodejs/node/pull/37394) +* [[`7b0ed4ba92`](https://github.com/nodejs/node/commit/7b0ed4ba92)] - **module**: improve support of data: URLs (Antoine du Hamel) [#37392](https://github.com/nodejs/node/pull/37392) +* [[`93dd799a86`](https://github.com/nodejs/node/commit/93dd799a86)] - **(SEMVER-MINOR)** **node-api**: define version 8 (Gabriel Schulhof) [#37652](https://github.com/nodejs/node/pull/37652) +* [[`f5692093d3`](https://github.com/nodejs/node/commit/f5692093d3)] - **(SEMVER-MINOR)** **node-api**: allow retrieval of add-on file name (Gabriel Schulhof) [#37195](https://github.com/nodejs/node/pull/37195) +* [[`6cef0e3678`](https://github.com/nodejs/node/commit/6cef0e3678)] - **src,test**: add regression test for nested Worker termination (Anna Henningsen) [#32623](https://github.com/nodejs/node/pull/32623) +* [[`364bf03a68`](https://github.com/nodejs/node/commit/364bf03a68)] - **test**: fix races in test-performance-eventlooputil (Gerhard Stoebich) [#36028](https://github.com/nodejs/node/pull/36028) +* [[`d7a4ccdf09`](https://github.com/nodejs/node/commit/d7a4ccdf09)] - **test**: correct test-worker-eventlooputil (Gerhard Stoebich) [#35891](https://github.com/nodejs/node/pull/35891) +* [[`0f6d44500c`](https://github.com/nodejs/node/commit/0f6d44500c)] - **test**: add cpu-profiler-crash test (Santiago Gimeno) [#37293](https://github.com/nodejs/node/pull/37293) +* [[`86f34ee18c`](https://github.com/nodejs/node/commit/86f34ee18c)] - **(SEMVER-MINOR)** **v8**: implement v8.stopCoverage() (Joyee Cheung) [#33807](https://github.com/nodejs/node/pull/33807) +* [[`8ddea3f16d`](https://github.com/nodejs/node/commit/8ddea3f16d)] - **(SEMVER-MINOR)** **v8**: implement v8.takeCoverage() (Joyee Cheung) [#33807](https://github.com/nodejs/node/pull/33807) +* [[`eec7542781`](https://github.com/nodejs/node/commit/eec7542781)] - **(SEMVER-MINOR)** **worker**: add eventLoopUtilization() (Trevor Norris) [#35664](https://github.com/nodejs/node/pull/35664) + ## 2021-02-23, Version 12.21.0 'Erbium' (LTS), @richardlau diff --git a/lib/.eslintrc.yaml b/lib/.eslintrc.yaml deleted file mode 100644 index 39caa3dee956fc6475bca224fb5ab5189249a16c..0000000000000000000000000000000000000000 --- a/lib/.eslintrc.yaml +++ /dev/null @@ -1,94 +0,0 @@ -env: - es6: true - -rules: - prefer-object-spread: error - no-buffer-constructor: error - no-mixed-operators: - - error - - groups: [[ "&&", "||" ]] - no-restricted-globals: - - error - - name: Array - message: "Use `const { Array } = primordials;` instead of the global." - - name: ArrayBuffer - message: "Use `const { ArrayBuffer } = primordials;` instead of the global." - - name: BigInt - message: "Use `const { BigInt } = primordials;` instead of the global." - - name: BigInt64Array - message: "Use `const { BigInt64Array } = primordials;` instead of the global." - - name: BigUint64Array - message: "Use `const { BigUint64Array } = primordials;` instead of the global." - - name: Boolean - message: "Use `const { Boolean } = primordials;` instead of the global." - - name: Error - message: "Use `const { Error } = primordials;` instead of the global." - - name: Float32Array - message: "Use `const { Float32Array } = primordials;` instead of the global." - - name: Int16Array - message: "Use `const { Int16Array } = primordials;` instead of the global." - - name: JSON - message: "Use `const { JSON } = primordials;` instead of the global." - - name: Map - message: "Use `const { Map } = primordials;` instead of the global." - - name: Math - message: "Use `const { Math } = primordials;` instead of the global." - - name: Number - message: "Use `const { Number } = primordials;` instead of the global." - - name: Object - message: "Use `const { Object } = primordials;` instead of the global." - - name: Promise - message: "Use `const { Promise } = primordials;` instead of the global." - - name: Reflect - message: "Use `const { Reflect } = primordials;` instead of the global." - - name: RegExp - message: "Use `const { RegExp } = primordials;` instead of the global." - - name: Set - message: "Use `const { Set } = primordials;` instead of the global." - - name: Symbol - message: "Use `const { Symbol } = primordials;` instead of the global." - - name: Uint16Array - message: "Use `const { Uint16Array } = primordials;` instead of the global." - - name: Uint32Array - message: "Use `const { Uint32Array } = primordials;` instead of the global." - - name: Uint8Array - message: "Use `const { Uint8Array } = primordials;` instead of the global." - - name: Uint8ClampedArray - message: "Use `const { Uint8ClampedArray } = primordials;` instead of the global." - - name: WeakMap - message: "Use `const { WeakMap } = primordials;` instead of the global." - - name: WeakSet - message: "Use `const { WeakSet } = primordials;` instead of the global." - no-restricted-syntax: - # Config copied from .eslintrc.js - - error - - selector: "CallExpression[callee.object.name='assert']:not([callee.property.name='ok']):not([callee.property.name='fail']):not([callee.property.name='ifError'])" - message: "Please only use simple assertions in ./lib" - - selector: "CallExpression[callee.name='setTimeout'][arguments.length<2]" - message: "setTimeout() must be invoked with at least two arguments." - - selector: "CallExpression[callee.name='setInterval'][arguments.length<2]" - message: "setInterval() must be invoked with at least 2 arguments." - - selector: "ThrowStatement > CallExpression[callee.name=/Error$/]" - message: "Use new keyword when throwing an Error." - # Config specific to lib - - selector: "NewExpression[callee.name=/Error$/]:not([callee.name=/^(AssertionError|NghttpError)$/])" - message: "Use an error exported by the internal/errors module." - - selector: "CallExpression[callee.object.name='Error'][callee.property.name='captureStackTrace']" - message: "Please use `require('internal/errors').hideStackFrames()` instead." - - selector: "AssignmentExpression:matches([left.name='prepareStackTrace'], [left.property.name='prepareStackTrace'])" - message: "Use 'overrideStackTrace' from 'lib/internal/errors.js' instead of 'Error.prepareStackTrace'." - - selector: "CallExpression[callee.name='isNaN']" - message: "Use NumberIsNaN() primordial instead of the global isNaN() function." - # Custom rules in tools/eslint-rules - node-core/lowercase-name-for-primitive: error - node-core/non-ascii-character: error -globals: - Intl: false - # Parameters passed to internal modules - global: false - require: false - process: false - exports: false - module: false - internalBinding: false - primordials: false diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 1982261b80e86bd59fa7b11a8b0e8d41e6dc2e3d..9ab6a198ff2bd3bee7d3a73ed85e03857f79ea9f 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -1516,7 +1516,15 @@ function onConnectSecure() { this.authorized = false; this.authorizationError = verifyError.code || verifyError.message; - if (options.rejectUnauthorized) { + // rejectUnauthorized property can be explicitly defined as `undefined` + // causing the assignment to default value (`true`) fail. Before assigning + // it to the tlssock connection options, explicitly check if it is false + // and update rejectUnauthorized property. The property gets used by + // TLSSocket connection handler to allow or reject connection if + // unauthorized. + // This check is potentially redundant, however it is better to keep it + // in case the option object gets modified somewhere. + if (options.rejectUnauthorized !== false) { this.destroy(verifyError); return; } @@ -1598,6 +1606,13 @@ exports.connect = function connect(...args) { pskCallback: options.pskCallback, }); + // rejectUnauthorized property can be explicitly defined as `undefined` + // causing the assignment to default value (`true`) fail. Before assigning + // it to the tlssock connection options, explicitly check if it is false + // and update rejectUnauthorized property. The property gets used by TLSSocket + // connection handler to allow or reject connection if unauthorized + options.rejectUnauthorized = options.rejectUnauthorized !== false; + tlssock[kConnectOptions] = options; if (cb) diff --git a/lib/internal/modules/esm/get_source.js b/lib/internal/modules/esm/get_source.js index 5e2cc3e09e76874ab185df33ee4112afb5e57973..2f7b74fb74406cb211aefa042aca760f764c876f 100644 --- a/lib/internal/modules/esm/get_source.js +++ b/lib/internal/modules/esm/get_source.js @@ -1,5 +1,8 @@ 'use strict'; +const { + decodeURIComponent, +} = primordials; const { getOptionValue } = require('internal/options'); const manifest = getOptionValue('--experimental-policy') ? require('internal/process/policy').manifest : @@ -28,8 +31,8 @@ async function defaultGetSource(url, { format } = {}, defaultGetSource) { if (!match) { throw new ERR_INVALID_URL(url); } - const [ , base64, body ] = match; - source = Buffer.from(body, base64 ? 'base64' : 'utf8'); + const { 1: base64, 2: body } = match; + source = Buffer.from(decodeURIComponent(body), base64 ? 'base64' : 'utf8'); } else { throw new ERR_INVALID_URL_SCHEME(['file', 'data']); } diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index 4576cfebf4d12435ae0f8f23cb3db926c7bb4552..bd07bc5b23694ca5bbe7ec828899608569000aa6 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -30,7 +30,7 @@ const { Stats, } = require('fs'); const { getOptionValue } = require('internal/options'); -const { sep, relative } = require('path'); +const { sep, relative, resolve } = require('path'); const preserveSymlinks = getOptionValue('--preserve-symlinks'); const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main'); const typeFlag = getOptionValue('--input-type'); @@ -160,16 +160,18 @@ function getPackageScopeConfig(resolved) { return packageConfig; } -/* +/** * Legacy CommonJS main resolution: * 1. let M = pkg_url + (json main field) * 2. TRY(M, M.js, M.json, M.node) * 3. TRY(M/index.js, M/index.json, M/index.node) * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) * 5. NOT_FOUND + * @param {string | URL} url + * @returns {boolean} */ function fileExists(url) { - return tryStatSync(fileURLToPath(url)).isFile(); + return tryStatSync(url).isFile(); } function legacyMainResolve(packageJSONUrl, packageConfig, base) { @@ -236,7 +238,19 @@ function resolveExtensions(search) { return undefined; } -function resolveIndex(search) { +function resolveDirectoryEntry(search) { + const dirPath = fileURLToPath(search); + const pkgJsonPath = resolve(dirPath, 'package.json'); + if (fileExists(pkgJsonPath)) { + const pkgJson = packageJsonReader.read(pkgJsonPath); + if (pkgJson.containsKeys) { + const { main } = JSONParse(pkgJson.string); + if (main != null) { + const mainUrl = pathToFileURL(resolve(dirPath, main)); + return resolveExtensionsWithTryExactName(mainUrl); + } + } + } return resolveExtensions(new URL('index', search)); } @@ -252,10 +266,10 @@ function finalizeResolution(resolved, base) { let file = resolveExtensionsWithTryExactName(resolved); if (file !== undefined) return file; if (!StringPrototypeEndsWith(path, '/')) { - file = resolveIndex(new URL(`${resolved}/`)); + file = resolveDirectoryEntry(new URL(`${resolved}/`)); if (file !== undefined) return file; } else { - return resolveIndex(resolved) || resolved; + return resolveDirectoryEntry(resolved) || resolved; } throw new ERR_MODULE_NOT_FOUND( resolved.pathname, fileURLToPath(base), 'module'); diff --git a/lib/internal/per_context/primordials.js b/lib/internal/per_context/primordials.js index 09bea0fc7fc523a90e1c294181c1bff976957839..6a960f36feda455fa8f956965d73a567f90d0e0d 100644 --- a/lib/internal/per_context/primordials.js +++ b/lib/internal/per_context/primordials.js @@ -106,6 +106,16 @@ primordials.SafePromise = makeSafe( class SafePromise extends Promise {} ); +// Create copies of URI handling functions +[ + decodeURI, + decodeURIComponent, + encodeURI, + encodeURIComponent, +].forEach((fn) => { + primordials[fn.name] = fn; +}); + // Create copies of the namespace objects [ 'JSON', diff --git a/lib/internal/url.js b/lib/internal/url.js index 16f5043df9c64198eb4467da09ace460c25281ee..2c0b1f518a70915cd63715153be912281f1ddb81 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -14,6 +14,7 @@ const { Symbol, SymbolIterator, SymbolToStringTag, + decodeURIComponent, } = primordials; const { inspect } = require('internal/util/inspect'); diff --git a/lib/internal/worker.js b/lib/internal/worker.js index e595749259f8590479b64fbbb9d5be92ba3c736a..a4591c03912709a2c99f7ab5334775f45e91654f 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -17,6 +17,7 @@ const { const EventEmitter = require('events'); const assert = require('internal/assert'); const path = require('path'); +const { timeOrigin } = internalBinding('performance'); const errorCodes = require('internal/errors').codes; const { @@ -67,6 +68,8 @@ const kOnMessage = Symbol('kOnMessage'); const kOnCouldNotSerializeErr = Symbol('kOnCouldNotSerializeErr'); const kOnErrorMessage = Symbol('kOnErrorMessage'); const kParentSideStdio = Symbol('kParentSideStdio'); +const kLoopStartTime = Symbol('kLoopStartTime'); +const kIsOnline = Symbol('kIsOnline'); const SHARE_ENV = SymbolFor('nodejs.worker_threads.SHARE_ENV'); let debug = require('internal/util/debuglog').debuglog('worker', (fn) => { @@ -214,6 +217,12 @@ class Worker extends EventEmitter { null, hasStdin: !!options.stdin }, transferList); + // Use this to cache the Worker's loopStart value once available. + this[kLoopStartTime] = -1; + this[kIsOnline] = false; + this.performance = { + eventLoopUtilization: eventLoopUtilization.bind(this), + }; // Actually start the new thread now that everything is in place. this[kHandle].startThread(); } @@ -245,6 +254,7 @@ class Worker extends EventEmitter { [kOnMessage](message) { switch (message.type) { case messageTypes.UP_AND_RUNNING: + this[kIsOnline] = true; return this.emit('online'); case messageTypes.COULD_NOT_SERIALIZE_ERROR: return this[kOnCouldNotSerializeErr](); @@ -406,6 +416,52 @@ function makeResourceLimits(float64arr) { }; } +function eventLoopUtilization(util1, util2) { + // TODO(trevnorris): Works to solve the thread-safe read/write issue of + // loopTime, but has the drawback that it can't be set until the event loop + // has had a chance to turn. So it will be impossible to read the ELU of + // a worker thread immediately after it's been created. + if (!this[kIsOnline] || !this[kHandle]) { + return { idle: 0, active: 0, utilization: 0 }; + } + + // Cache loopStart, since it's only written to once. + if (this[kLoopStartTime] === -1) { + this[kLoopStartTime] = this[kHandle].loopStartTime(); + if (this[kLoopStartTime] === -1) + return { idle: 0, active: 0, utilization: 0 }; + } + + if (util2) { + const idle = util1.idle - util2.idle; + const active = util1.active - util2.active; + return { idle, active, utilization: active / (idle + active) }; + } + + const idle = this[kHandle].loopIdleTime(); + + // Using performance.now() here is fine since it's always the time from + // the beginning of the process, and is why it needs to be offset by the + // loopStart time (which is also calculated from the beginning of the + // process). + const active = now() - this[kLoopStartTime] - idle; + + if (!util1) { + return { idle, active, utilization: active / (idle + active) }; + } + + const idle_delta = idle - util1.idle; + const active_delta = active - util1.active; + const utilization = active_delta / (idle_delta + active_delta); + return { idle: idle_delta, active: active_delta, utilization }; +} + +// Duplicate code from performance.now() so don't need to require perf_hooks. +function now() { + const hr = process.hrtime(); + return (hr[0] * 1000 + hr[1] / 1e6) - timeOrigin; +} + module.exports = { ownsProcessState, isMainThread, diff --git a/lib/querystring.js b/lib/querystring.js index 4d196633dcf2c765ef5a2507d8d007fcbe188f8e..7bc6684f4001740cd4d16853ff3693672fc38480 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -29,6 +29,7 @@ const { MathAbs, ObjectCreate, ObjectKeys, + decodeURIComponent, } = primordials; const { Buffer } = require('buffer'); diff --git a/lib/url.js b/lib/url.js index 735390dfd2e59b1bf91871bf63e04ad317606ed9..f7dbebea5ac125ad57929f45382f941dad444cec 100644 --- a/lib/url.js +++ b/lib/url.js @@ -25,6 +25,7 @@ const { ObjectCreate, ObjectKeys, SafeSet, + decodeURIComponent, } = primordials; const { toASCII } = require('internal/idna'); diff --git a/lib/v8.js b/lib/v8.js index fe848dad72a15cb304ee7abe8ac9c124979a6aba..2143e07274775dccbe4c9b59474a735b5a43fb7b 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -37,6 +37,12 @@ const { Serializer: _Serializer, Deserializer: _Deserializer } = internalBinding('serdes'); + +let profiler = {}; +if (internalBinding('config').hasInspector) { + profiler = internalBinding('profiler'); +} + const assert = require('internal/assert'); const { copy } = internalBinding('buffer'); const { inspect } = require('internal/util/inspect'); @@ -286,6 +292,8 @@ module.exports = { DefaultSerializer, DefaultDeserializer, deserialize, + takeCoverage: profiler.takeCoverage, + stopCoverage: profiler.stopCoverage, serialize, writeHeapSnapshot, }; diff --git a/src/api/environment.cc b/src/api/environment.cc index 57d05c963df34891c74a7dae468ae28673900166..b3c9ed72d21a946e7c63152ccc80c157af150728 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -712,7 +712,8 @@ ThreadId AllocateEnvironmentThreadId() { } void DefaultProcessExitHandler(Environment* env, int exit_code) { - Stop(env); + env->set_can_call_into_js(false); + env->stop_sub_worker_contexts(); DisposePlatform(); uv_library_shutdown(); exit(exit_code); diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index e21fc2e303897fca096fa34f1d352556576ad168..d54e7c60cff63b781bfcc339980a366dd76a096b 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -39,17 +39,13 @@ # include #endif // __POSIX__ -#if defined(__ANDROID__) || \ - defined(__MINGW32__) || \ - defined(__OpenBSD__) || \ - defined(_MSC_VER) - -# include -#else -# include -#endif +# include -#if defined(__OpenBSD__) +// OpenBSD does not define these +#ifndef AI_ALL +# define AI_ALL 0 +#endif +#ifndef AI_V4MAPPED # define AI_V4MAPPED 0 #endif diff --git a/src/env.cc b/src/env.cc index 4411a46b9ca726980f7a7036c362c4ce01870120..295b68741dc5c6cb5ef15186c91707b05ea134b9 100644 --- a/src/env.cc +++ b/src/env.cc @@ -550,10 +550,9 @@ void Environment::InitializeLibuv(bool start_profiler_idle_notifier) { } } -void Environment::Stop() { +void Environment::ExitEnv() { set_can_call_into_js(false); set_stopping(true); - stop_sub_worker_contexts(); isolate_->TerminateExecution(); SetImmediateThreadsafe([](Environment* env) { uv_stop(env->event_loop()); }); } @@ -1039,6 +1038,8 @@ void Environment::Exit(int exit_code) { } void Environment::stop_sub_worker_contexts() { + DCHECK_EQ(Isolate::GetCurrent(), isolate()); + while (!sub_worker_contexts_.empty()) { Worker* w = *sub_worker_contexts_.begin(); remove_sub_worker_context(w); diff --git a/src/env.h b/src/env.h index d0c0a187962fbaf0a6e7d0d3fffc31fc4d027e6c..ed058866e94e3d62558f99db39bd432acb9eecc3 100644 --- a/src/env.h +++ b/src/env.h @@ -253,6 +253,7 @@ constexpr size_t kFsStatsBufferLength = V(fd_string, "fd") \ V(fields_string, "fields") \ V(file_string, "file") \ + V(filename_string, "filename") \ V(fingerprint256_string, "fingerprint256") \ V(fingerprint_string, "fingerprint") \ V(flags_string, "flags") \ @@ -926,7 +927,7 @@ class Environment : public MemoryRetainer { void RegisterHandleCleanups(); void CleanupHandles(); void Exit(int code); - void Stop(); + void ExitEnv(); // Register clean-up cb to be called on environment destruction. inline void RegisterHandleCleanup(uv_handle_t* handle, diff --git a/src/inspector_profiler.cc b/src/inspector_profiler.cc index 03cf2f6e5ca76b469a0438fd77b338a40d9c6853..7640a040783b855b0912b5b83434bcdbae12ae13 100644 --- a/src/inspector_profiler.cc +++ b/src/inspector_profiler.cc @@ -9,6 +9,7 @@ #include "util-inl.h" #include "v8-inspector.h" +#include #include namespace node { @@ -36,10 +37,11 @@ V8ProfilerConnection::V8ProfilerConnection(Environment* env) false)), env_(env) {} -size_t V8ProfilerConnection::DispatchMessage(const char* method, - const char* params) { +uint32_t V8ProfilerConnection::DispatchMessage(const char* method, + const char* params, + bool is_profile_request) { std::stringstream ss; - size_t id = next_id(); + uint32_t id = next_id(); ss << R"({ "id": )" << id; DCHECK(method != nullptr); ss << R"(, "method": ")" << method << '"'; @@ -50,12 +52,15 @@ size_t V8ProfilerConnection::DispatchMessage(const char* method, std::string message = ss.str(); const uint8_t* message_data = reinterpret_cast(message.c_str()); + // Save the id of the profile request to identify its response. + if (is_profile_request) { + profile_ids_.insert(id); + } Debug(env(), DebugCategory::INSPECTOR_PROFILER, "Dispatching message %s\n", message.c_str()); session_->Dispatch(StringView(message_data, message.length())); - // TODO(joyeecheung): use this to identify the ending message. return id; } @@ -77,21 +82,10 @@ void V8ProfilerConnection::V8ProfilerSessionDelegate::SendMessageToFrontend( Environment* env = connection_->env(); Isolate* isolate = env->isolate(); HandleScope handle_scope(isolate); - Context::Scope context_scope(env->context()); + Local context = env->context(); + Context::Scope context_scope(context); - // TODO(joyeecheung): always parse the message so that we can use the id to - // identify ending messages as well as printing the message in the debug - // output when there is an error. const char* type = connection_->type(); - Debug(env, - DebugCategory::INSPECTOR_PROFILER, - "Receive %s profile message, ending = %s\n", - type, - connection_->ending() ? "true" : "false"); - if (!connection_->ending()) { - return; - } - // Convert StringView to a Local. Local message_str; if (!String::NewFromTwoByte(isolate, @@ -99,11 +93,62 @@ void V8ProfilerConnection::V8ProfilerSessionDelegate::SendMessageToFrontend( NewStringType::kNormal, message.length()) .ToLocal(&message_str)) { - fprintf(stderr, "Failed to convert %s profile message\n", type); + fprintf( + stderr, "Failed to convert %s profile message to V8 string\n", type); + return; + } + + Debug(env, + DebugCategory::INSPECTOR_PROFILER, + "Receive %s profile message\n", + type); + + Local parsed; + if (!v8::JSON::Parse(context, message_str).ToLocal(&parsed) || + !parsed->IsObject()) { + fprintf(stderr, "Failed to parse %s profile result as JSON object\n", type); + return; + } + + Local response = parsed.As(); + Local id_v; + if (!response->Get(context, FIXED_ONE_BYTE_STRING(isolate, "id")) + .ToLocal(&id_v) || + !id_v->IsUint32()) { + Utf8Value str(isolate, message_str); + fprintf( + stderr, "Cannot retrieve id from the response message:\n%s\n", *str); return; } + uint32_t id = id_v.As()->Value(); - connection_->WriteProfile(message_str); + if (!connection_->HasProfileId(id)) { + Utf8Value str(isolate, message_str); + Debug(env, DebugCategory::INSPECTOR_PROFILER, "%s\n", *str); + return; + } else { + Debug(env, + DebugCategory::INSPECTOR_PROFILER, + "Writing profile response (id = %" PRIu64 ")\n", + static_cast(id)); + } + + // Get message.result from the response. + Local result_v; + if (!response->Get(context, FIXED_ONE_BYTE_STRING(isolate, "result")) + .ToLocal(&result_v)) { + fprintf(stderr, "Failed to get 'result' from %s profile response\n", type); + return; + } + + if (!result_v->IsObject()) { + fprintf( + stderr, "'result' from %s profile response is not an object\n", type); + return; + } + + connection_->WriteProfile(result_v.As()); + connection_->RemoveProfileId(id); } static bool EnsureDirectory(const std::string& directory, const char* type) { @@ -138,45 +183,9 @@ std::string V8CoverageConnection::GetFilename() const { return filename; } -static MaybeLocal ParseProfile(Environment* env, - Local message, - const char* type) { - Local context = env->context(); - Isolate* isolate = env->isolate(); - - // Get message.result from the response - Local parsed; - if (!v8::JSON::Parse(context, message).ToLocal(&parsed) || - !parsed->IsObject()) { - fprintf(stderr, "Failed to parse %s profile result as JSON object\n", type); - return MaybeLocal(); - } - - Local result_v; - if (!parsed.As() - ->Get(context, FIXED_ONE_BYTE_STRING(isolate, "result")) - .ToLocal(&result_v)) { - fprintf(stderr, "Failed to get 'result' from %s profile message\n", type); - return MaybeLocal(); - } - - if (!result_v->IsObject()) { - fprintf( - stderr, "'result' from %s profile message is not an object\n", type); - return MaybeLocal(); - } - - return result_v.As(); -} - -void V8ProfilerConnection::WriteProfile(Local message) { +void V8ProfilerConnection::WriteProfile(Local result) { Local context = env_->context(); - // Get message.result from the response. - Local result; - if (!ParseProfile(env_, message, type()).ToLocal(&result)) { - return; - } // Generate the profile output from the subclass. Local profile; if (!GetProfile(result).ToLocal(&profile)) { @@ -203,7 +212,7 @@ void V8ProfilerConnection::WriteProfile(Local message) { WriteResult(env_, path.c_str(), result_s); } -void V8CoverageConnection::WriteProfile(Local message) { +void V8CoverageConnection::WriteProfile(Local result) { Isolate* isolate = env_->isolate(); Local context = env_->context(); HandleScope handle_scope(isolate); @@ -219,11 +228,6 @@ void V8CoverageConnection::WriteProfile(Local message) { return; } - // Get message.result from the response. - Local result; - if (!ParseProfile(env_, message, type()).ToLocal(&result)) { - return; - } // Generate the profile output from the subclass. Local profile; if (!GetProfile(result).ToLocal(&profile)) { @@ -287,10 +291,23 @@ void V8CoverageConnection::Start() { R"({ "callCount": true, "detailed": true })"); } +void V8CoverageConnection::TakeCoverage() { + DispatchMessage("Profiler.takePreciseCoverage", nullptr, true); +} + +void V8CoverageConnection::StopCoverage() { + DispatchMessage("Profiler.stopPreciseCoverage"); +} + void V8CoverageConnection::End() { - CHECK_EQ(ending_, false); + Debug(env_, + DebugCategory::INSPECTOR_PROFILER, + "V8CoverageConnection::End(), ending = %d\n", ending_); + if (ending_) { + return; + } ending_ = true; - DispatchMessage("Profiler.takePreciseCoverage"); + TakeCoverage(); } std::string V8CpuProfilerConnection::GetDirectory() const { @@ -327,9 +344,14 @@ void V8CpuProfilerConnection::Start() { } void V8CpuProfilerConnection::End() { - CHECK_EQ(ending_, false); + Debug(env_, + DebugCategory::INSPECTOR_PROFILER, + "V8CpuProfilerConnection::End(), ending = %d\n", ending_); + if (ending_) { + return; + } ending_ = true; - DispatchMessage("Profiler.stop"); + DispatchMessage("Profiler.stop", nullptr, true); } std::string V8HeapProfilerConnection::GetDirectory() const { @@ -365,31 +387,33 @@ void V8HeapProfilerConnection::Start() { } void V8HeapProfilerConnection::End() { - CHECK_EQ(ending_, false); + Debug(env_, + DebugCategory::INSPECTOR_PROFILER, + "V8HeapProfilerConnection::End(), ending = %d\n", ending_); + if (ending_) { + return; + } ending_ = true; - DispatchMessage("HeapProfiler.stopSampling"); + DispatchMessage("HeapProfiler.stopSampling", nullptr, true); } // For now, we only support coverage profiling, but we may add more // in the future. static void EndStartedProfilers(Environment* env) { + // TODO(joyeechueng): merge these connections and use one session per env. Debug(env, DebugCategory::INSPECTOR_PROFILER, "EndStartedProfilers\n"); V8ProfilerConnection* connection = env->cpu_profiler_connection(); - if (connection != nullptr && !connection->ending()) { - Debug(env, DebugCategory::INSPECTOR_PROFILER, "Ending cpu profiling\n"); + if (connection != nullptr) { connection->End(); } connection = env->heap_profiler_connection(); - if (connection != nullptr && !connection->ending()) { - Debug(env, DebugCategory::INSPECTOR_PROFILER, "Ending heap profiling\n"); + if (connection != nullptr) { connection->End(); } connection = env->coverage_connection(); - if (connection != nullptr && !connection->ending()) { - Debug( - env, DebugCategory::INSPECTOR_PROFILER, "Ending coverage collection\n"); + if (connection != nullptr) { connection->End(); } } @@ -469,6 +493,37 @@ static void SetSourceMapCacheGetter(const FunctionCallbackInfo& args) { env->set_source_map_cache_getter(args[0].As()); } +static void TakeCoverage(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + V8CoverageConnection* connection = env->coverage_connection(); + + Debug( + env, + DebugCategory::INSPECTOR_PROFILER, + "TakeCoverage, connection %s nullptr\n", + connection == nullptr ? "==" : "!="); + + if (connection != nullptr) { + Debug(env, DebugCategory::INSPECTOR_PROFILER, "taking coverage\n"); + connection->TakeCoverage(); + } +} + +static void StopCoverage(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + V8CoverageConnection* connection = env->coverage_connection(); + + Debug(env, + DebugCategory::INSPECTOR_PROFILER, + "StopCoverage, connection %s nullptr\n", + connection == nullptr ? "==" : "!="); + + if (connection != nullptr) { + Debug(env, DebugCategory::INSPECTOR_PROFILER, "Stopping coverage\n"); + connection->StopCoverage(); + } +} + static void Initialize(Local target, Local unused, Local context, @@ -476,6 +531,8 @@ static void Initialize(Local target, Environment* env = Environment::GetCurrent(context); env->SetMethod(target, "setCoverageDirectory", SetCoverageDirectory); env->SetMethod(target, "setSourceMapCacheGetter", SetSourceMapCacheGetter); + env->SetMethod(target, "takeCoverage", TakeCoverage); + env->SetMethod(target, "stopCoverage", StopCoverage); } } // namespace profiler diff --git a/src/inspector_profiler.h b/src/inspector_profiler.h index 187bc0d1c49a160e38f40c1007bc49b93cb736a1..be74153b0c37ac8c50c0112c6d3cae3b9a01a54c 100644 --- a/src/inspector_profiler.h +++ b/src/inspector_profiler.h @@ -7,6 +7,7 @@ #error("This header can only be used when inspector is enabled") #endif +#include #include "inspector_agent.h" namespace node { @@ -39,7 +40,9 @@ class V8ProfilerConnection { // The optional `params` should be formatted in JSON. // The strings should be in one byte characters - which is enough for // the commands we use here. - size_t DispatchMessage(const char* method, const char* params = nullptr); + uint32_t DispatchMessage(const char* method, + const char* params = nullptr, + bool is_profile_request = false); // Use DispatchMessage() to dispatch necessary inspector messages // to start and end the profiling. @@ -58,12 +61,19 @@ class V8ProfilerConnection { // which will be then written as a JSON. virtual v8::MaybeLocal GetProfile( v8::Local result) = 0; - virtual void WriteProfile(v8::Local message); + virtual void WriteProfile(v8::Local result); + + bool HasProfileId(uint32_t id) const { + return profile_ids_.find(id) != profile_ids_.end(); + } + + void RemoveProfileId(uint32_t id) { profile_ids_.erase(id); } private: - size_t next_id() { return id_++; } + uint32_t next_id() { return id_++; } std::unique_ptr session_; - size_t id_ = 1; + uint32_t id_ = 1; + std::unordered_set profile_ids_; protected: Environment* env_ = nullptr; @@ -82,8 +92,10 @@ class V8CoverageConnection : public V8ProfilerConnection { std::string GetDirectory() const override; std::string GetFilename() const override; v8::MaybeLocal GetProfile(v8::Local result) override; - void WriteProfile(v8::Local message) override; + void WriteProfile(v8::Local result) override; void WriteSourceMapCache(); + void TakeCoverage(); + void StopCoverage(); private: std::unique_ptr session_; diff --git a/src/js_native_api.h b/src/js_native_api.h index 5daa20f90400962b3ed18f0afc425fdb0e9f0366..e804d1d45d236519d248e3d40fa0a6c2a6d378ec 100644 --- a/src/js_native_api.h +++ b/src/js_native_api.h @@ -17,7 +17,7 @@ // functions available in a new version of N-API that is not yet ported in all // LTS versions, they can set NAPI_VERSION knowing that they have specifically // depended on that version. -#define NAPI_VERSION 7 +#define NAPI_VERSION 8 #endif #endif @@ -539,7 +539,7 @@ NAPI_EXTERN napi_status napi_is_detached_arraybuffer(napi_env env, bool* result); #endif // NAPI_VERSION >= 7 -#ifdef NAPI_EXPERIMENTAL +#if NAPI_VERSION >= 8 // Type tagging NAPI_EXTERN napi_status napi_type_tag_object(napi_env env, napi_value value, @@ -554,7 +554,7 @@ NAPI_EXTERN napi_status napi_object_freeze(napi_env env, napi_value object); NAPI_EXTERN napi_status napi_object_seal(napi_env env, napi_value object); -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_VERSION >= 8 EXTERN_C_END diff --git a/src/js_native_api_types.h b/src/js_native_api_types.h index b9eddbcba04772f2be61d63981af43087c24d6a7..179428e95a4554d74346dc68fef9a05566f78eca 100644 --- a/src/js_native_api_types.h +++ b/src/js_native_api_types.h @@ -31,7 +31,7 @@ typedef enum { // from instance properties. Ignored by napi_define_properties. napi_static = 1 << 10, -#ifdef NAPI_EXPERIMENTAL +#if NAPI_VERSION >= 8 // Default for class methods. napi_default_method = napi_writable | napi_configurable, @@ -39,7 +39,7 @@ typedef enum { napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable, -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_VERSION >= 8 } napi_property_attributes; typedef enum { @@ -146,11 +146,11 @@ typedef enum { } napi_key_conversion; #endif // NAPI_VERSION >= 6 -#ifdef NAPI_EXPERIMENTAL +#if NAPI_VERSION >= 8 typedef struct { uint64_t lower; uint64_t upper; } napi_type_tag; -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_VERSION >= 8 #endif // SRC_JS_NATIVE_API_TYPES_H_ diff --git a/src/node.cc b/src/node.cc index 00ae36cc0fe669d0cbd618c4d4b5d445738e5aea..46e8f74cc286f73f5c45132d96907250d3620568 100644 --- a/src/node.cc +++ b/src/node.cc @@ -1035,7 +1035,7 @@ int Start(int argc, char** argv) { } int Stop(Environment* env) { - env->Stop(); + env->ExitEnv(); return 0; } diff --git a/src/node.h b/src/node.h index 2fda6d125e7e0934da9a8007de25c9393dd80ee6..e41af9d2c0c49ea382ecaeb0c4a7b787ed134d72 100644 --- a/src/node.h +++ b/src/node.h @@ -218,8 +218,7 @@ class Environment; NODE_EXTERN int Start(int argc, char* argv[]); // Tear down Node.js while it is running (there are active handles -// in the loop and / or actively executing JavaScript code). This also stops -// all Workers that may have been started earlier. +// in the loop and / or actively executing JavaScript code). NODE_EXTERN int Stop(Environment* env); // TODO(addaleax): Officially deprecate this and replace it with something @@ -469,8 +468,8 @@ NODE_EXTERN void FreeEnvironment(Environment* env); // It receives the Environment* instance and the exit code as arguments. // This could e.g. call Stop(env); in order to terminate execution and stop // the event loop. -// The default handler calls Stop(), disposes of the global V8 platform -// instance, if one is being used, and calls exit(). +// The default handler disposes of the global V8 platform instance, if one is +// being used, and calls exit(). NODE_EXTERN void SetProcessExitHandler( Environment* env, std::function&& handler); diff --git a/src/node_api.cc b/src/node_api.cc index 93488146d56690c27c56a21f2795796d027cfa02..211386ba6d502d178196786ee0a5af13de16fb71 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -12,8 +12,9 @@ #include struct node_napi_env__ : public napi_env__ { - explicit node_napi_env__(v8::Local context): - napi_env__(context) { + explicit node_napi_env__(v8::Local context, + const std::string& module_filename): + napi_env__(context), filename(module_filename) { CHECK_NOT_NULL(node_env()); } @@ -43,6 +44,10 @@ struct node_napi_env__ : public napi_env__ { }); }); } + + const char* GetFilename() const { return filename.c_str(); } + + std::string filename; }; typedef node_napi_env__* node_napi_env; @@ -84,10 +89,11 @@ class BufferFinalizer : private Finalizer { }; }; -static inline napi_env NewEnv(v8::Local context) { +static inline napi_env +NewEnv(v8::Local context, const std::string& module_filename) { node_napi_env result; - result = new node_napi_env__(context); + result = new node_napi_env__(context, module_filename); // TODO(addaleax): There was previously code that tried to delete the // napi_env when its v8::Context was garbage collected; // However, as long as N-API addons using this napi_env are in place, @@ -454,16 +460,35 @@ void napi_module_register_by_symbol(v8::Local exports, v8::Local module, v8::Local context, napi_addon_register_func init) { + node::Environment* node_env = node::Environment::GetCurrent(context); + std::string module_filename = ""; if (init == nullptr) { - node::Environment* node_env = node::Environment::GetCurrent(context); CHECK_NOT_NULL(node_env); node_env->ThrowError( "Module has no declared entry point."); return; } + // We set `env->filename` from `module.filename` here, but we could just as + // easily add a private property to `exports` in `process.dlopen`, which + // receives the file name from JS, and retrieve *that* here. Thus, we are not + // endorsing commonjs here by making use of `module.filename`. + v8::Local filename_js; + v8::Local modobj; + if (module->ToObject(context).ToLocal(&modobj) && + modobj->Get(context, node_env->filename_string()).ToLocal(&filename_js) && + filename_js->IsString()) { + node::Utf8Value filename(node_env->isolate(), filename_js); // Cast + + // Turn the absolute path into a URL. Currently the absolute path is always + // a file system path. + // TODO(gabrielschulhof): Pass the `filename` through unchanged if/when we + // receive it as a URL already. + module_filename = std::string("file://") + (*filename); + } + // Create a new napi_env for this specific module. - napi_env env = v8impl::NewEnv(context); + napi_env env = v8impl::NewEnv(context, module_filename); napi_value _exports; env->CallIntoModule([&](napi_env env) { @@ -1154,3 +1179,11 @@ napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func) { CHECK_NOT_NULL(func); return reinterpret_cast(func)->Ref(); } + +napi_status node_api_get_module_file_name(napi_env env, const char** result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = static_cast(env)->GetFilename(); + return napi_clear_last_error(env); +} diff --git a/src/node_api.h b/src/node_api.h index 577a1dcd94987202819e7a36a2d9674f13d13614..61a5404314a5df4c752b330c4cb89feac7904c53 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -250,7 +250,7 @@ napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func); #endif // NAPI_VERSION >= 4 -#ifdef NAPI_EXPERIMENTAL +#if NAPI_VERSION >= 8 NAPI_EXTERN napi_status napi_add_async_cleanup_hook( napi_env env, @@ -261,6 +261,13 @@ NAPI_EXTERN napi_status napi_add_async_cleanup_hook( NAPI_EXTERN napi_status napi_remove_async_cleanup_hook( napi_async_cleanup_hook_handle remove_handle); +#endif // NAPI_VERSION >= 8 + +#ifdef NAPI_EXPERIMENTAL + +NAPI_EXTERN napi_status +node_api_get_module_file_name(napi_env env, const char** result); + #endif // NAPI_EXPERIMENTAL EXTERN_C_END diff --git a/src/node_api_types.h b/src/node_api_types.h index 0e400e9676df5ba09d350fe7a2a70a1dc9e4d3d6..58ffc61b3a5f51b71f33f6dd904d61da12089f3b 100644 --- a/src/node_api_types.h +++ b/src/node_api_types.h @@ -41,10 +41,10 @@ typedef struct { const char* release; } napi_node_version; -#ifdef NAPI_EXPERIMENTAL +#if NAPI_VERSION >= 8 typedef struct napi_async_cleanup_hook_handle__* napi_async_cleanup_hook_handle; typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle, void* data); -#endif // NAPI_EXPERIMENTAL +#endif // NAPI_VERSION >= 8 #endif // SRC_NODE_API_TYPES_H_ diff --git a/src/node_http2.cc b/src/node_http2.cc index dec6d7dab9eed7a692eb1fea35e197451ba1f94b..5156aa34df55a1bbfa33664d3d14954f04948720 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -2150,6 +2150,24 @@ int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec, void Http2Stream::SubmitRstStream(const uint32_t code) { CHECK(!this->IsDestroyed()); code_ = code; + + auto is_stream_cancel = [](const uint32_t code) { + return code == NGHTTP2_CANCEL; + }; + + // If RST_STREAM frame is received with error code NGHTTP2_CANCEL, + // add it to the pending list and don't force purge the data. It is + // to avoids the double free error due to unwanted behavior of nghttp2. + + // Add stream to the pending list only if it is received with scope + // below in the stack. The pending list may not get processed + // if RST_STREAM received is not in scope and added to the list + // causing endpoint to hang. + if (session_->is_in_scope() && is_stream_cancel(code)) { + session_->AddPendingRstStream(id_); + return; + } + // If possible, force a purge of any currently pending data here to make sure // it is sent before closing the stream. If it returns non-zero then we need // to wait until the current write finishes and try again to avoid nghttp2 diff --git a/src/node_http2.h b/src/node_http2.h index 045bdfd716da03af37bf61067f052cf64a72a3cd..a59de18f920acacdfbb2b5d21f04a58743bb53d5 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -764,6 +764,22 @@ class Http2Session : public AsyncWrap, return (flags_ & SESSION_STATE_CLOSED) || session_ == nullptr; } + + // The changes are backported and exposes APIs to check the + // status flag of `Http2Session` +#define IS_FLAG(name, flag) \ + bool is_##name() const { return flags_ & flag; } + + IS_FLAG(in_scope, SESSION_STATE_HAS_SCOPE) + IS_FLAG(write_scheduled, SESSION_STATE_WRITE_SCHEDULED) + IS_FLAG(closing, SESSION_STATE_CLOSING) + IS_FLAG(sending, SESSION_STATE_SENDING) + IS_FLAG(write_in_progress, SESSION_STATE_WRITE_IN_PROGRESS) + IS_FLAG(reading_stopped, SESSION_STATE_READING_STOPPED) + IS_FLAG(receive_paused, SESSION_STATE_NGHTTP2_RECV_PAUSED) + +#undef IS_FLAG + // Schedule a write if nghttp2 indicates it wants to write to the socket. void MaybeScheduleWrite(); diff --git a/src/node_http_parser_impl.h b/src/node_http_parser_impl.h index 7c39bc15c72a38c3f6cff89eca62fb6d52b90c84..77d09a939cb72bd8393d99825886a953a8ffe761 100644 --- a/src/node_http_parser_impl.h +++ b/src/node_http_parser_impl.h @@ -26,6 +26,9 @@ #include "node.h" #include "node_buffer.h" +#ifndef NODE_EXPERIMENTAL_HTTP +#include "node_process.h" +#endif /* NODE_EXPERIMENTAL_HTTP */ #include "util.h" #include "async_wrap-inl.h" @@ -1021,6 +1024,10 @@ void InitializeHttpParser(Local target, #ifndef NODE_EXPERIMENTAL_HTTP static uv_once_t init_once = UV_ONCE_INIT; uv_once(&init_once, InitMaxHttpHeaderSizeOnce); + ProcessEmitDeprecationWarning( + env, + "The legacy HTTP parser is deprecated.", + "DEP0131").IsNothing(); #endif /* NODE_EXPERIMENTAL_HTTP */ } diff --git a/src/node_platform.cc b/src/node_platform.cc index d7b394aae81ed936dccb73caa1556ec1c1919856..8703372818770b847c35455612100e6895546f53 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc @@ -359,10 +359,10 @@ void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate, Mutex::ScopedLock lock(per_isolate_mutex_); auto it = per_isolate_.find(isolate); if (it == per_isolate_.end()) { - CHECK(it->second); cb(data); return; } + CHECK(it->second); it->second->AddShutdownCallback(cb, data); } diff --git a/src/node_version.h b/src/node_version.h index 5bea878e82dc2ba4a51c44866dbd1d18d145577b..89368822e552677443c2e1901142ab93d3d9b208 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -23,8 +23,8 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 12 -#define NODE_MINOR_VERSION 21 -#define NODE_PATCH_VERSION 0 +#define NODE_MINOR_VERSION 22 +#define NODE_PATCH_VERSION 7 #define NODE_VERSION_IS_LTS 1 #define NODE_VERSION_LTS_CODENAME "Erbium" @@ -93,6 +93,6 @@ // The NAPI_VERSION provided by this version of the runtime. This is the version // which the Node binary being built supports. -#define NAPI_VERSION 7 +#define NAPI_VERSION 8 #endif // SRC_NODE_VERSION_H_ diff --git a/src/node_worker.cc b/src/node_worker.cc index 05b005862c377fd88679a9eee1916a4b41a40d14..bda7351d3e8fa0e3047aa6d82d531c7259284575 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -765,6 +765,39 @@ void Worker::TakeHeapSnapshot(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(scheduled ? taker->object() : Local()); } +void Worker::LoopIdleTime(const FunctionCallbackInfo& args) { + Worker* w; + ASSIGN_OR_RETURN_UNWRAP(&w, args.This()); + + Mutex::ScopedLock lock(w->mutex_); + // Using w->is_stopped() here leads to a deadlock, and checking is_stopped() + // before locking the mutex is a race condition. So manually do the same + // check. + if (w->stopped_ || w->env_ == nullptr) + return args.GetReturnValue().Set(-1); + + uint64_t idle_time = uv_metrics_idle_time(w->env_->event_loop()); + args.GetReturnValue().Set(1.0 * idle_time / 1e6); +} + +void Worker::LoopStartTime(const FunctionCallbackInfo& args) { + Worker* w; + ASSIGN_OR_RETURN_UNWRAP(&w, args.This()); + + Mutex::ScopedLock lock(w->mutex_); + // Using w->is_stopped() here leads to a deadlock, and checking is_stopped() + // before locking the mutex is a race condition. So manually do the same + // check. + if (w->stopped_ || w->env_ == nullptr) + return args.GetReturnValue().Set(-1); + + double loop_start_time = w->env_->performance_state()->milestones[ + node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START]; + CHECK_GE(loop_start_time, 0); + args.GetReturnValue().Set( + (loop_start_time - node::performance::timeOrigin) / 1e6); +} + namespace { // Return the MessagePort that is global for this Environment and communicates @@ -798,6 +831,8 @@ void InitWorker(Local target, env->SetProtoMethod(w, "unref", Worker::Unref); env->SetProtoMethod(w, "getResourceLimits", Worker::GetResourceLimits); env->SetProtoMethod(w, "takeHeapSnapshot", Worker::TakeHeapSnapshot); + env->SetProtoMethod(w, "loopIdleTime", Worker::LoopIdleTime); + env->SetProtoMethod(w, "loopStartTime", Worker::LoopStartTime); Local workerString = FIXED_ONE_BYTE_STRING(env->isolate(), "Worker"); diff --git a/src/node_worker.h b/src/node_worker.h index 78f6dd3f198bb7400976ac424b3be5d798d01c32..253ffdc48448189425ea0a95bc2e12d646fb52da 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -66,6 +66,8 @@ class Worker : public AsyncWrap { const v8::FunctionCallbackInfo& args); v8::Local GetResourceLimits(v8::Isolate* isolate) const; static void TakeHeapSnapshot(const v8::FunctionCallbackInfo& args); + static void LoopIdleTime(const v8::FunctionCallbackInfo& args); + static void LoopStartTime(const v8::FunctionCallbackInfo& args); private: void CreateEnvMessagePort(Environment* env); diff --git a/test/.eslintrc.yaml b/test/.eslintrc.yaml deleted file mode 100644 index f707caffdafde4bcc265f9292a1c7bbc74728906..0000000000000000000000000000000000000000 --- a/test/.eslintrc.yaml +++ /dev/null @@ -1,71 +0,0 @@ -## Test-specific linter rules - -env: - node: true - es6: true - -rules: - # ECMAScript 6 - # http://eslint.org/docs/rules/#ecmascript-6 - no-var: error - prefer-const: error - symbol-description: off - - no-restricted-syntax: - # Config copied from .eslintrc.js - - error - - selector: "CallExpression:matches([callee.name='deepStrictEqual'], [callee.property.name='deepStrictEqual'])[arguments.2.type='Literal']" - message: "Do not use a literal for the third argument of assert.deepStrictEqual()" - - selector: "CallExpression:matches([callee.name='doesNotThrow'], [callee.property.name='doesNotThrow'])" - message: "Do not use `assert.doesNotThrow()`. Write the code without the wrapper and add a comment instead." - - selector: "CallExpression:matches([callee.name='doesNotReject'], [callee.property.name='doesNotReject'])" - message: "Do not use `assert.doesNotReject()`. Write the code without the wrapper and add a comment instead." - - selector: "CallExpression:matches([callee.name='rejects'], [callee.property.name='rejects'])[arguments.length<2]" - message: "`assert.rejects()` must be invoked with at least two arguments." - - selector: "CallExpression[callee.property.name='strictEqual'][arguments.2.type='Literal']" - message: "Do not use a literal for the third argument of assert.strictEqual()" - - selector: "CallExpression:matches([callee.name='throws'], [callee.property.name='throws'])[arguments.1.type='Literal']:not([arguments.1.regex])" - message: "Use an object as second argument of `assert.throws()`." - - selector: "CallExpression:matches([callee.name='throws'], [callee.property.name='throws'])[arguments.length<2]" - message: "`assert.throws()` must be invoked with at least two arguments." - - selector: "CallExpression[callee.name='setTimeout'][arguments.length<2]" - message: "`setTimeout()` must be invoked with at least two arguments." - - selector: "CallExpression[callee.name='setInterval'][arguments.length<2]" - message: "`setInterval()` must be invoked with at least two arguments." - - selector: "ThrowStatement > CallExpression[callee.name=/Error$/]" - message: "Use `new` keyword when throwing an `Error`." - - selector: "CallExpression:matches([callee.name='notDeepStrictEqual'], [callee.property.name='notDeepStrictEqual'])[arguments.0.type='Literal']:not([arguments.1.type='Literal']):not([arguments.1.type='ObjectExpression']):not([arguments.1.type='ArrayExpression']):not([arguments.1.type='UnaryExpression'])" - message: "The first argument should be the `actual`, not the `expected` value." - - selector: "CallExpression:matches([callee.name='notStrictEqual'], [callee.property.name='notStrictEqual'])[arguments.0.type='Literal']:not([arguments.1.type='Literal']):not([arguments.1.type='ObjectExpression']):not([arguments.1.type='ArrayExpression']):not([arguments.1.type='UnaryExpression'])" - message: "The first argument should be the `actual`, not the `expected` value." - - selector: "CallExpression:matches([callee.name='deepStrictEqual'], [callee.property.name='deepStrictEqual'])[arguments.0.type='Literal']:not([arguments.1.type='Literal']):not([arguments.1.type='ObjectExpression']):not([arguments.1.type='ArrayExpression']):not([arguments.1.type='UnaryExpression'])" - message: "The first argument should be the `actual`, not the `expected` value." - - selector: "CallExpression:matches([callee.name='strictEqual'], [callee.property.name='strictEqual'])[arguments.0.type='Literal']:not([arguments.1.type='Literal']):not([arguments.1.type='ObjectExpression']):not([arguments.1.type='ArrayExpression']):not([arguments.1.type='UnaryExpression'])" - message: "The first argument should be the `actual`, not the `expected` value." - - selector: "CallExpression[callee.name='isNaN']" - message: "Use Number.isNaN() instead of the global isNaN() function." - - selector: "VariableDeclarator > CallExpression:matches([callee.name='debuglog'], [callee.property.name='debuglog']):not([arguments.0.value='test'])" - message: "Use 'test' as debuglog value in tests." - - # Custom rules in tools/eslint-rules - node-core/prefer-assert-iferror: error - node-core/prefer-assert-methods: error - node-core/prefer-common-mustnotcall: error - node-core/crypto-check: error - node-core/eslint-check: error - node-core/inspector-check: error - ## common module is mandatory in tests - node-core/required-modules: - - error - - common: 'common(/index\.(m)?js)?$' - node-core/require-common-first: error - node-core/no-duplicate-requires: off - -# Global scoped methods and vars -globals: - WebAssembly: false - BigInt: false - BigInt64Array: false - BigUint64Array: false - SharedArrayBuffer: false - globalThis: false diff --git a/test/addons/cpu-profiler-crash/binding.cc b/test/addons/cpu-profiler-crash/binding.cc new file mode 100644 index 0000000000000000000000000000000000000000..57358e82175e29dbf18c4238ca5029ff1b583699 --- /dev/null +++ b/test/addons/cpu-profiler-crash/binding.cc @@ -0,0 +1,16 @@ +#include "node.h" +#include "v8.h" +#include "v8-profiler.h" + +static void StartCpuProfiler(const v8::FunctionCallbackInfo& args) { + v8::CpuProfiler* profiler = v8::CpuProfiler::New(args.GetIsolate()); + v8::Local profile_title = v8::String::NewFromUtf8( + args.GetIsolate(), + "testing", + v8::NewStringType::kInternalized).ToLocalChecked(); + profiler->StartProfiling(profile_title, true); +} + +NODE_MODULE_INIT(/* exports, module, context */) { + NODE_SET_METHOD(exports, "startCpuProfiler", StartCpuProfiler); +} diff --git a/test/addons/cpu-profiler-crash/binding.gyp b/test/addons/cpu-profiler-crash/binding.gyp new file mode 100644 index 0000000000000000000000000000000000000000..55fbe7050f18e4455c16bf75569578acd15c3797 --- /dev/null +++ b/test/addons/cpu-profiler-crash/binding.gyp @@ -0,0 +1,9 @@ +{ + 'targets': [ + { + 'target_name': 'binding', + 'sources': [ 'binding.cc' ], + 'includes': ['../common.gypi'], + } + ] +} diff --git a/test/addons/cpu-profiler-crash/test.js b/test/addons/cpu-profiler-crash/test.js new file mode 100644 index 0000000000000000000000000000000000000000..e7391ebfcc9a5cce08c278de9a85d0c8b594be3d --- /dev/null +++ b/test/addons/cpu-profiler-crash/test.js @@ -0,0 +1,20 @@ +'use strict'; + +// This test crashes most of the time unless the v8 patch: +// https://github.com/v8/v8/commit/beebee4f80ff2eb91187ef1e8fa00b8ff82a20b3 +// is applied. +const common = require('../../common'); +const bindings = require(`./build/${common.buildType}/binding`); + +function fn() { setImmediate(fn); } +setInterval(function() { + for (let i = 0; i < 1000000; i++) + fn(); + clearInterval(this); + setTimeout(process.reallyExit, 2000); +}, 0); + + +setTimeout(() => { + bindings.startCpuProfiler(); +}, 1000); diff --git a/test/es-module/test-esm-data-urls.js b/test/es-module/test-esm-data-urls.js index 61da442c9e081c37adbe6d631c601b242bd5adc4..282aaf1857a0df8ab44bbd59eb39920932e0e7a7 100644 --- a/test/es-module/test-esm-data-urls.js +++ b/test/es-module/test-esm-data-urls.js @@ -102,4 +102,9 @@ function createBase64URL(mime, body) { assert.strictEqual(e.code, 'ERR_INVALID_RETURN_PROPERTY_VALUE'); } } + { + const plainESMURL = 'data:text/javascript,export%20default%202'; + const module = await import(plainESMURL); + assert.strictEqual(module.default, 2); + } })().then(common.mustCall()); diff --git a/test/es-module/test-esm-specifiers-legacy-flag.mjs b/test/es-module/test-esm-specifiers-legacy-flag.mjs index fcf0c915b649f0b6f51e7f8a6c7f881d171035c8..5351846c6a8a0485ae8232824521a9cdf0526dd4 100644 --- a/test/es-module/test-esm-specifiers-legacy-flag.mjs +++ b/test/es-module/test-esm-specifiers-legacy-flag.mjs @@ -6,12 +6,15 @@ import assert from 'assert'; import commonjs from '../fixtures/es-module-specifiers/package-type-commonjs'; // esm index.js import module from '../fixtures/es-module-specifiers/package-type-module'; +// Directory entry with main.js +import main from '../fixtures/es-module-specifiers/dir-with-main'; // Notice the trailing slash import success, { explicit, implicit, implicitModule } from '../fixtures/es-module-specifiers/'; assert.strictEqual(commonjs, 'commonjs'); assert.strictEqual(module, 'module'); +assert.strictEqual(main, 'main'); assert.strictEqual(success, 'success'); assert.strictEqual(explicit, 'esm'); assert.strictEqual(implicit, 'cjs'); diff --git a/test/fixtures/es-module-specifiers/dir-with-main/main.js b/test/fixtures/es-module-specifiers/dir-with-main/main.js new file mode 100644 index 0000000000000000000000000000000000000000..dfdd47b877319c291140aa46cccda428c3e90ba4 --- /dev/null +++ b/test/fixtures/es-module-specifiers/dir-with-main/main.js @@ -0,0 +1 @@ +module.exports = 'main'; diff --git a/test/fixtures/es-module-specifiers/dir-with-main/package.json b/test/fixtures/es-module-specifiers/dir-with-main/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2a4fe3630817ab2826173be485b9a58a445194e7 --- /dev/null +++ b/test/fixtures/es-module-specifiers/dir-with-main/package.json @@ -0,0 +1,3 @@ +{ + "main": "./main.js" +} diff --git a/test/fixtures/es-modules/cjs-exports.mjs b/test/fixtures/es-modules/cjs-exports.mjs index ac6f60e6aa9dc167d8bfb5eba9ad0e58f6ca67a6..6001ce06364454c4eb366b3e6bbee25aa7d6d367 100644 --- a/test/fixtures/es-modules/cjs-exports.mjs +++ b/test/fixtures/es-modules/cjs-exports.mjs @@ -3,11 +3,14 @@ import { strictEqual, deepEqual } from 'assert'; import m, { Ï€ } from './exports-cases.js'; import * as ns from './exports-cases.js'; -deepEqual(Object.keys(ns), ['default', 'isObject', 'z', 'Ï€']); +deepEqual(Object.keys(ns), ['?invalid', 'default', 'invalid identifier', 'isObject', 'package', 'z', 'Ï€', '\u{d83c}\u{df10}']); strictEqual(Ï€, 'yes'); strictEqual(typeof m.isObject, 'undefined'); strictEqual(m.Ï€, 'yes'); strictEqual(m.z, 'yes'); +strictEqual(m.package, 10); +strictEqual(m['invalid identifier'], 'yes'); +strictEqual(m['?invalid'], 'yes'); import m2, { __esModule as __esModule2, name as name2 } from './exports-cases2.js'; import * as ns2 from './exports-cases2.js'; diff --git a/test/fixtures/es-modules/exports-cases.js b/test/fixtures/es-modules/exports-cases.js index eec3d31bc7290c8e309c580fde8148a5a000af02..94bbde74d1d40e4166f6a2ae662fae9c65da234d 100644 --- a/test/fixtures/es-modules/exports-cases.js +++ b/test/fixtures/es-modules/exports-cases.js @@ -1,7 +1,9 @@ if (global.maybe) module.exports = require('../is-object'); -exports['invalid identifier'] = 'no'; -module.exports['?invalid'] = 'no'; +exports['invalid identifier'] = 'yes'; +module.exports['?invalid'] = 'yes'; module.exports['Ï€'] = 'yes'; -exports.package = 10; // reserved word -> not used +exports['\u{D83C}'] = 'no'; +exports['\u{D83C}\u{DF10}'] = 'yes'; +exports.package = 10; // reserved word Object.defineProperty(exports, 'z', { value: 'yes' }); diff --git a/test/fixtures/google_ssl_hello.bin b/test/fixtures/google_ssl_hello.bin index 739be3580fc80f5c892f5798c811403b467fd840..5170533ab2170fb6ea89bb6c65944a5ae59f222e 100644 Binary files a/test/fixtures/google_ssl_hello.bin and b/test/fixtures/google_ssl_hello.bin differ diff --git a/test/fixtures/v8-coverage/interval.js b/test/fixtures/v8-coverage/interval.js new file mode 100644 index 0000000000000000000000000000000000000000..8fb10cef64ddb8e31d50819346eca567fd3c7360 --- /dev/null +++ b/test/fixtures/v8-coverage/interval.js @@ -0,0 +1,14 @@ +'use strict'; +let counter = 0; +let result; +const TEST_INTERVALS = parseInt(process.env.TEST_INTERVALS) || 1; + +const i = setInterval(function interval() { + counter++; + if (counter < TEST_INTERVALS) { + result = 1; + } else { + result = process.hrtime(); + clearInterval(i); + } +}, 100); diff --git a/test/fixtures/v8-coverage/stop-coverage.js b/test/fixtures/v8-coverage/stop-coverage.js new file mode 100644 index 0000000000000000000000000000000000000000..dadfd1900bdd78e783da39945bdf73af3cb6bb8b --- /dev/null +++ b/test/fixtures/v8-coverage/stop-coverage.js @@ -0,0 +1,3 @@ +'use strict'; +const v8 = require('v8'); +v8.stopCoverage(); diff --git a/test/fixtures/v8-coverage/take-coverage.js b/test/fixtures/v8-coverage/take-coverage.js new file mode 100644 index 0000000000000000000000000000000000000000..766c1f400747a8df177cd00cb77e998f0ae65128 --- /dev/null +++ b/test/fixtures/v8-coverage/take-coverage.js @@ -0,0 +1,10 @@ +'use strict'; +const v8 = require('v8'); + +setTimeout(() => { + v8.takeCoverage(); +}, 1000); + +setTimeout(() => { + v8.takeCoverage(); +}, 2000); diff --git a/test/fixtures/wasi/subdir/input_link.txt b/test/fixtures/wasi/subdir/input_link.txt deleted file mode 120000 index 4a6d09bf82379f2369f664ac2ab83ff703c586ab..0000000000000000000000000000000000000000 --- a/test/fixtures/wasi/subdir/input_link.txt +++ /dev/null @@ -1 +0,0 @@ -../input.txt \ No newline at end of file diff --git a/test/fixtures/wasi/subdir/outside.txt b/test/fixtures/wasi/subdir/outside.txt deleted file mode 120000 index 2e0694706746f7213ebdd81109ac221f0308ef73..0000000000000000000000000000000000000000 --- a/test/fixtures/wasi/subdir/outside.txt +++ /dev/null @@ -1 +0,0 @@ -../../outside.txt \ No newline at end of file diff --git a/test/js-native-api/test_general/test.js b/test/js-native-api/test_general/test.js index 4dbdc37c918c376553197f0a65f7618210e9b103..76527bc81c7cd858daa240bb697c2f9091db141e 100644 --- a/test/js-native-api/test_general/test.js +++ b/test/js-native-api/test_general/test.js @@ -33,7 +33,7 @@ assert.notStrictEqual(test_general.testGetPrototype(baseObject), test_general.testGetPrototype(extendedObject)); // Test version management functions -assert.strictEqual(test_general.testGetVersion(), 7); +assert.strictEqual(test_general.testGetVersion(), 8); [ 123, diff --git a/test/js-native-api/test_object/test_object.c b/test/js-native-api/test_object/test_object.c index 70a85e03c725dd5a0ebb3089ee24c3230a9b6667..9a90b5689e074d3af47457a3b6b50408a0043d1f 100644 --- a/test/js-native-api/test_object/test_object.c +++ b/test/js-native-api/test_object/test_object.c @@ -1,4 +1,3 @@ -#define NAPI_EXPERIMENTAL #include #include "../common.h" #include diff --git a/test/node-api/test_async_cleanup_hook/binding.c b/test/node-api/test_async_cleanup_hook/binding.c index 7bbde56bb0ec888a97926f36425f7a1dca719514..4e88479574fb0142773c656187efcde70ba361d8 100644 --- a/test/node-api/test_async_cleanup_hook/binding.c +++ b/test/node-api/test_async_cleanup_hook/binding.c @@ -1,4 +1,3 @@ -#define NAPI_EXPERIMENTAL #include "node_api.h" #include "assert.h" #include "uv.h" diff --git a/test/node-api/test_general/test.js b/test/node-api/test_general/test.js index 108d51a1e11ac97e32cbd0706d6cbc797a28353d..dd409f010a3ada6c399b305f0f120e3d55347b7c 100644 --- a/test/node-api/test_general/test.js +++ b/test/node-api/test_general/test.js @@ -1,9 +1,14 @@ 'use strict'; const common = require('../../common'); -const test_general = require(`./build/${common.buildType}/test_general`); +const filename = require.resolve(`./build/${common.buildType}/test_general`); +const test_general = require(filename); const assert = require('assert'); +// TODO(gabrielschulhof): This test may need updating if/when the filename +// becomes a full-fledged URL. +assert.strictEqual(test_general.filename, `file://${filename}`); + const [ major, minor, patch, release ] = test_general.testGetNodeVersion(); assert.strictEqual(process.version.split('-')[0], `v${major}.${minor}.${patch}`); diff --git a/test/node-api/test_general/test_general.c b/test/node-api/test_general/test_general.c index be805f782be8d59c3357cf105a5006041efdeb54..5c2c2817312de1748637c1d9921f4f2ef5cb1d0c 100644 --- a/test/node-api/test_general/test_general.c +++ b/test/node-api/test_general/test_general.c @@ -1,3 +1,4 @@ +#define NAPI_EXPERIMENTAL #include #include #include "../../js-native-api/common.h" @@ -21,9 +22,21 @@ static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) { return result; } +static napi_value GetFilename(napi_env env, napi_callback_info info) { + const char* filename; + napi_value result; + + NAPI_CALL(env, node_api_get_module_file_name(env, &filename)); + NAPI_CALL(env, + napi_create_string_utf8(env, filename, NAPI_AUTO_LENGTH, &result)); + + return result; +} + static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("testGetNodeVersion", testGetNodeVersion), + DECLARE_NAPI_GETTER("filename", GetFilename), }; NAPI_CALL(env, napi_define_properties( diff --git a/test/parallel/test-bootstrap-modules.js b/test/parallel/test-bootstrap-modules.js index e6bf26ee0ab0168c03fb850c4d3fa4046e2f7d32..e978edf04fc90c61d2e5546dc8786dfe826b76ed 100644 --- a/test/parallel/test-bootstrap-modules.js +++ b/test/parallel/test-bootstrap-modules.js @@ -93,6 +93,7 @@ if (!common.isMainThread) { expectedModules.add('Internal Binding messaging'); expectedModules.add('Internal Binding symbols'); expectedModules.add('Internal Binding worker'); + expectedModules.add('Internal Binding performance'); expectedModules.add('NativeModule _stream_duplex'); expectedModules.add('NativeModule _stream_passthrough'); expectedModules.add('NativeModule _stream_readable'); diff --git a/test/parallel/test-http-chunked-smuggling.js b/test/parallel/test-http-chunked-smuggling.js new file mode 100644 index 0000000000000000000000000000000000000000..6ea2614835c00932dc5ae9a43af42d8694a18a75 --- /dev/null +++ b/test/parallel/test-http-chunked-smuggling.js @@ -0,0 +1,43 @@ +'use strict'; + +const common = require('../common'); +const http = require('http'); +const net = require('net'); +const assert = require('assert'); + +// Verify that a request with a space before the content length will result +// in a 400 Bad Request. + +const server = http.createServer(common.mustCall((request, response) => { + assert.notStrictEqual(request.url, '/admin'); + response.end('hello world'); +}), 1); + +server.listen(0, common.mustCall(start)); + +function start() { + const sock = net.connect(server.address().port); + + sock.write('' + + 'GET / HTTP/1.1\r\n' + + 'Host: localhost:8080\r\n' + + 'Transfer-Encoding: chunked\r\n' + + '\r\n' + + '2 \n' + + 'xx\r\n' + + '4c\r\n' + + '0\r\n' + + '\r\n' + + 'GET /admin HTTP/1.1\r\n' + + 'Host: localhost:8080\r\n' + + 'Transfer-Encoding: chunked\r\n' + + '\r\n' + + '0\r\n' + + '\r\n' + ); + + sock.resume(); + sock.on('end', common.mustCall(function() { + server.close(); + })); +} diff --git a/test/parallel/test-http-parser-legacy-deprecation.js b/test/parallel/test-http-parser-legacy-deprecation.js new file mode 100644 index 0000000000000000000000000000000000000000..6c4c690a9b916948b72df4762dd029cf2ebe4cf4 --- /dev/null +++ b/test/parallel/test-http-parser-legacy-deprecation.js @@ -0,0 +1,11 @@ +'use strict'; +const common = require('../common'); + +// Flags: --http-parser=legacy +require('http'); + +common.expectWarning({ + DeprecationWarning: + ['The legacy HTTP parser is deprecated.', + 'DEP0131'] +}); diff --git a/test/parallel/test-http-request-smuggling-content-length.js b/test/parallel/test-http-request-smuggling-content-length.js new file mode 100644 index 0000000000000000000000000000000000000000..4ae39b93f4aa995f25ab6737315c77475757ff27 --- /dev/null +++ b/test/parallel/test-http-request-smuggling-content-length.js @@ -0,0 +1,31 @@ +'use strict'; + +const common = require('../common'); +const http = require('http'); +const net = require('net'); +const assert = require('assert'); + +// Verify that a request with a space before the content length will result +// in a 400 Bad Request. + +const server = http.createServer(common.mustNotCall()); + +server.listen(0, common.mustCall(start)); + +function start() { + const sock = net.connect(server.address().port); + + sock.write('GET / HTTP/1.1\r\nHost: localhost:5000\r\n' + + 'Content-Length : 5\r\n\r\nhello'); + + let body = ''; + sock.setEncoding('utf8'); + sock.on('data', (chunk) => { + body += chunk; + }); + sock.on('end', common.mustCall(function() { + assert.strictEqual(body, 'HTTP/1.1 400 Bad Request\r\n' + + 'Connection: close\r\n\r\n'); + server.close(); + })); +} diff --git a/test/parallel/test-http2-cancel-while-client-reading.js b/test/parallel/test-http2-cancel-while-client-reading.js new file mode 100644 index 0000000000000000000000000000000000000000..0605a02e1166260ea5f72037c360d81b52a2bf7c --- /dev/null +++ b/test/parallel/test-http2-cancel-while-client-reading.js @@ -0,0 +1,36 @@ +'use strict'; +const common = require('../common'); +const fixtures = require('../common/fixtures'); +if (!common.hasCrypto) { + common.skip('missing crypto'); +} + +const http2 = require('http2'); +const key = fixtures.readKey('agent1-key.pem', 'binary'); +const cert = fixtures.readKey('agent1-cert.pem', 'binary'); + +const server = http2.createSecureServer({ key, cert }); + +let client_stream; + +server.on('stream', common.mustCall(function(stream) { + stream.resume(); + stream.on('data', function(chunk) { + stream.write(chunk); + client_stream.pause(); + client_stream.close(http2.constants.NGHTTP2_CANCEL); + }); +})); + +server.listen(0, function() { + const client = http2.connect(`https://localhost:${server.address().port}`, + { rejectUnauthorized: false } + ); + client_stream = client.request({ ':method': 'POST' }); + client_stream.on('close', common.mustCall(() => { + client.close(); + server.close(); + })); + client_stream.resume(); + client_stream.write(Buffer.alloc(1024 * 1024)); +}); diff --git a/test/parallel/test-performance-eventlooputil.js b/test/parallel/test-performance-eventlooputil.js index 1a5d86db750a9485260ae4e2eb57e358cd6c0e09..6e62a6664432897174f86e7c9f64d18cffcae2cb 100644 --- a/test/parallel/test-performance-eventlooputil.js +++ b/test/parallel/test-performance-eventlooputil.js @@ -1,8 +1,9 @@ 'use strict'; -require('../common'); +const { mustCall } = require('../common'); -const TIMEOUT = 50; +const TIMEOUT = 10; +const SPIN_DUR = 50; const assert = require('assert'); const { performance } = require('perf_hooks'); @@ -21,29 +22,32 @@ if (nodeTiming.loopStart === -1) { { idle: 0, active: 0, utilization: 0 }); } -// Place in setTimeout() to make sure there is some idle time, but not going to -// assert this since it could make the test flaky. -setTimeout(() => { - const t = Date.now(); +setTimeout(mustCall(function r() { const elu1 = eventLoopUtilization(); - while (Date.now() - t < 50) { } + // Force idle time to accumulate before allowing test to continue. + if (elu1.idle <= 0) + return setTimeout(mustCall(r), 5); - const elu2 = eventLoopUtilization(); - const elu3 = eventLoopUtilization(elu1); - const elu4 = eventLoopUtilization(elu2, elu1); + const t = Date.now(); + while (Date.now() - t < SPIN_DUR) { } + + const elu2 = eventLoopUtilization(elu1); + const elu3 = eventLoopUtilization(); + const elu4 = eventLoopUtilization(elu3, elu1); - assert.strictEqual(elu3.idle, 0); + assert.strictEqual(elu2.idle, 0); assert.strictEqual(elu4.idle, 0); - assert.strictEqual(elu3.utilization, 1); + assert.strictEqual(elu2.utilization, 1); assert.strictEqual(elu4.utilization, 1); - assert.strictEqual(elu2.active - elu1.active, elu4.active); - assert.ok(elu2.active > elu3.active); - assert.ok(elu2.active > elu4.active); - assert.ok(elu3.active > elu4.active); + assert.strictEqual(elu3.active - elu1.active, elu4.active); + assert.ok(elu2.active > SPIN_DUR - 10, `${elu2.active} <= ${SPIN_DUR - 10}`); + assert.ok(elu2.active < elu4.active, `${elu2.active} >= ${elu4.active}`); + assert.ok(elu3.active > elu2.active, `${elu3.active} <= ${elu2.active}`); + assert.ok(elu3.active > elu4.active, `${elu3.active} <= ${elu4.active}`); - setTimeout(runIdleTimeTest, TIMEOUT); -}, 5); + setTimeout(mustCall(runIdleTimeTest), TIMEOUT); +}), 5); function runIdleTimeTest() { const idleTime = nodeTiming.idleTime; @@ -55,7 +59,7 @@ function runIdleTimeTest() { assert.strictEqual(elu1.idle, idleTime); assert.strictEqual(elu1.utilization, elu1.active / sum); - setTimeout(runCalcTest, TIMEOUT, elu1); + setTimeout(mustCall(runCalcTest), TIMEOUT, elu1); } function runCalcTest(elu1) { @@ -65,18 +69,20 @@ function runCalcTest(elu1) { const active_delta = elu2.active - elu1.active; const idle_delta = elu2.idle - elu1.idle; - assert.ok(elu2.idle >= 0); - assert.ok(elu2.active >= 0); - assert.ok(elu3.idle >= 0); - assert.ok(elu3.active >= 0); - assert.ok(elu2.idle + elu2.active > elu1.idle + elu2.active); - assert.ok(elu2.idle + elu2.active >= now - nodeTiming.loopStart); + assert.ok(elu2.idle >= 0, `${elu2.idle} < 0`); + assert.ok(elu2.active >= 0, `${elu2.active} < 0`); + assert.ok(elu3.idle >= 0, `${elu3.idle} < 0`); + assert.ok(elu3.active >= 0, `${elu3.active} < 0`); + assert.ok(elu2.idle + elu2.active > elu1.idle + elu1.active, + `${elu2.idle + elu2.active} <= ${elu1.idle + elu1.active}`); + assert.ok(elu2.idle + elu2.active >= now - nodeTiming.loopStart, + `${elu2.idle + elu2.active} < ${now - nodeTiming.loopStart}`); assert.strictEqual(elu3.active, elu2.active - elu1.active); assert.strictEqual(elu3.idle, elu2.idle - elu1.idle); assert.strictEqual(elu3.utilization, active_delta / (idle_delta + active_delta)); - setImmediate(runWorkerTest); + setImmediate(mustCall(runWorkerTest)); } function runWorkerTest() { @@ -90,10 +96,11 @@ function runWorkerTest() { const elu1 = eventLoopUtilization(); const worker = new Worker(__filename, { argv: [ 'iamalive' ] }); - worker.on('message', (msg) => { + worker.on('message', mustCall((msg) => { const elu2 = eventLoopUtilization(elu1); const data = JSON.parse(msg); - assert.ok(elu2.active + elu2.idle > data.active + data.idle); - }); + assert.ok(elu2.active + elu2.idle > data.active + data.idle, + `${elu2.active + elu2.idle} <= ${data.active + data.idle}`); + })); } diff --git a/test/parallel/test-tls-client-reject.js b/test/parallel/test-tls-client-reject.js index d41ad806ea3012de607e9596b149e82c422ac2fc..ea10ef6da20834b4f9ee3342de7c6ba8e4c3b82a 100644 --- a/test/parallel/test-tls-client-reject.js +++ b/test/parallel/test-tls-client-reject.js @@ -71,6 +71,19 @@ function rejectUnauthorized() { servername: 'localhost' }, common.mustNotCall()); socket.on('data', common.mustNotCall()); + socket.on('error', common.mustCall(function(err) { + rejectUnauthorizedUndefined(); + })); + socket.end('ng'); +} + +function rejectUnauthorizedUndefined() { + console.log('reject unauthorized undefined'); + const socket = tls.connect(server.address().port, { + servername: 'localhost', + rejectUnauthorized: undefined + }, common.mustNotCall()); + socket.on('data', common.mustNotCall()); socket.on('error', common.mustCall(function(err) { authorized(); })); diff --git a/test/parallel/test-v8-stop-coverage.js b/test/parallel/test-v8-stop-coverage.js new file mode 100644 index 0000000000000000000000000000000000000000..020e18d8747eb221db3119e28e3e20104ed7c389 --- /dev/null +++ b/test/parallel/test-v8-stop-coverage.js @@ -0,0 +1,34 @@ +'use strict'; + +if (!process.features.inspector) return; + +require('../common'); +const fixtures = require('../common/fixtures'); +const tmpdir = require('../common/tmpdir'); +const assert = require('assert'); +const fs = require('fs'); +const { spawnSync } = require('child_process'); + +tmpdir.refresh(); +const intervals = 20; + +{ + const output = spawnSync(process.execPath, [ + '-r', + fixtures.path('v8-coverage', 'stop-coverage'), + '-r', + fixtures.path('v8-coverage', 'take-coverage'), + fixtures.path('v8-coverage', 'interval'), + ], { + env: { + ...process.env, + NODE_V8_COVERAGE: tmpdir.path, + NODE_DEBUG_NATIVE: 'INSPECTOR_PROFILER', + TEST_INTERVALS: intervals + }, + }); + console.log(output.stderr.toString()); + assert.strictEqual(output.status, 0); + const coverageFiles = fs.readdirSync(tmpdir.path); + assert.strictEqual(coverageFiles.length, 0); +} diff --git a/test/parallel/test-v8-take-coverage-noop.js b/test/parallel/test-v8-take-coverage-noop.js new file mode 100644 index 0000000000000000000000000000000000000000..c1c797bfd422200092ba6bb681fa357e035fbc15 --- /dev/null +++ b/test/parallel/test-v8-take-coverage-noop.js @@ -0,0 +1,32 @@ +'use strict'; + +if (!process.features.inspector) return; + +require('../common'); +const fixtures = require('../common/fixtures'); +const tmpdir = require('../common/tmpdir'); +const assert = require('assert'); +const fs = require('fs'); +const { spawnSync } = require('child_process'); + +tmpdir.refresh(); + +// v8.takeCoverage() should be a noop if NODE_V8_COVERAGE is not set. +const intervals = 40; +{ + const output = spawnSync(process.execPath, [ + '-r', + fixtures.path('v8-coverage', 'take-coverage'), + fixtures.path('v8-coverage', 'interval'), + ], { + env: { + ...process.env, + NODE_DEBUG_NATIVE: 'INSPECTOR_PROFILER', + TEST_INTERVALS: intervals + }, + }); + console.log(output.stderr.toString()); + assert.strictEqual(output.status, 0); + const coverageFiles = fs.readdirSync(tmpdir.path); + assert.strictEqual(coverageFiles.length, 0); +} diff --git a/test/parallel/test-v8-take-coverage.js b/test/parallel/test-v8-take-coverage.js new file mode 100644 index 0000000000000000000000000000000000000000..b5e99ac30a57175687cf4a592c823a4e1957ca44 --- /dev/null +++ b/test/parallel/test-v8-take-coverage.js @@ -0,0 +1,85 @@ +'use strict'; + +if (!process.features.inspector) return; + +require('../common'); +const fixtures = require('../common/fixtures'); +const tmpdir = require('../common/tmpdir'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +tmpdir.refresh(); +const intervals = 40; +// Outputs coverage when v8.takeCoverage() is invoked. +{ + const output = spawnSync(process.execPath, [ + '-r', + fixtures.path('v8-coverage', 'take-coverage'), + fixtures.path('v8-coverage', 'interval'), + ], { + env: { + ...process.env, + NODE_V8_COVERAGE: tmpdir.path, + NODE_DEBUG_NATIVE: 'INSPECTOR_PROFILER', + TEST_INTERVALS: intervals + }, + }); + console.log(output.stderr.toString()); + assert.strictEqual(output.status, 0); + const coverageFiles = fs.readdirSync(tmpdir.path); + + let coverages = []; + for (const coverageFile of coverageFiles) { + const coverage = require(path.join(tmpdir.path, coverageFile)); + for (const result of coverage.result) { + if (result.url.includes('/interval')) { + coverages.push({ + file: coverageFile, + func: result.functions.find((f) => f.functionName === 'interval'), + timestamp: coverage.timestamp + }); + } + } + } + + coverages = coverages.sort((a, b) => { return a.timestamp - b.timestamp; }); + // There should be two coverages taken, one triggered by v8.takeCoverage(), + // the other by process exit. + console.log('Coverages:', coverages); + assert.strictEqual(coverages.length, 3); + + let blockHitsTotal = 0; + for (let i = 0; i < coverages.length; ++i) { + const { ranges } = coverages[i].func; + console.log('coverage', i, ranges); + + if (i !== coverages.length - 1) { + // When the first two coverages are taken: + assert.strictEqual(ranges.length, 2); + const blockHits = ranges[0].count; + // The block inside interval() should be hit at least once. + assert.notStrictEqual(blockHits, 0); + blockHitsTotal += blockHits; + // The else branch should not be hit. + const elseBranchHits = ranges[1].count; + assert.strictEqual(elseBranchHits, 0); + } else { + // At process exit: + assert.strictEqual(ranges.length, 3); + const blockHits = ranges[0].count; + // The block inside interval() should be hit at least once more. + assert.notStrictEqual(blockHits, 0); + blockHitsTotal += blockHits; + // The else branch should be hit exactly once. + const elseBranchHits = ranges[2].count; + assert.strictEqual(elseBranchHits, 1); + const ifBranchHits = ranges[1].count; + assert.strictEqual(ifBranchHits, blockHits - elseBranchHits); + } + } + + // The block should be hit `intervals` times in total. + assert.strictEqual(blockHitsTotal, intervals); +} diff --git a/test/parallel/test-worker-eventlooputil.js b/test/parallel/test-worker-eventlooputil.js new file mode 100644 index 0000000000000000000000000000000000000000..7e012cb2b02e7af34651cc88c2a5daf3d3120fe8 --- /dev/null +++ b/test/parallel/test-worker-eventlooputil.js @@ -0,0 +1,114 @@ +'use strict'; + +const { mustCall, mustCallAtLeast } = require('../common'); + +const assert = require('assert'); +const { + Worker, + MessageChannel, + MessagePort, + parentPort, +} = require('worker_threads'); +const { eventLoopUtilization, now } = require('perf_hooks').performance; + +// Use argv to detect whether we're running as a Worker called by this test vs. +// this test also being called as a Worker. +if (process.argv[2] === 'iamalive') { + const iaElu = idleActive(eventLoopUtilization()); + // Checks that the worker bootstrap is running after the event loop started. + assert.ok(iaElu > 0, `${iaElu} <= 0`); + parentPort.once('message', mustCall((msg) => { + assert.ok(msg.metricsCh instanceof MessagePort); + msg.metricsCh.on('message', mustCallAtLeast(workerOnMetricsMsg, 1)); + })); + return; +} + +function workerOnMetricsMsg(msg) { + if (msg.cmd === 'close') { + return this.close(); + } + + if (msg.cmd === 'elu') { + return this.postMessage(eventLoopUtilization()); + } + + if (msg.cmd === 'spin') { + const elu = eventLoopUtilization(); + const t = now(); + while (now() - t < msg.dur); + return this.postMessage(eventLoopUtilization(elu)); + } +} + +let worker; +let metricsCh; +let mainElu; +let workerELU; + +(function r() { + // Force some idle time to accumulate before proceeding with test. + if (eventLoopUtilization().idle <= 0) + return setTimeout(mustCall(r), 5); + + mainElu = eventLoopUtilization(); + + worker = new Worker(__filename, { argv: [ 'iamalive' ] }); + metricsCh = new MessageChannel(); + worker.postMessage({ metricsCh: metricsCh.port1 }, [ metricsCh.port1 ]); + + workerELU = worker.performance.eventLoopUtilization; + metricsCh.port2.once('message', mustCall(checkWorkerIdle)); + metricsCh.port2.postMessage({ cmd: 'elu' }); + // Make sure it's still safe to call eventLoopUtilization() after the worker + // hass been closed. + worker.on('exit', mustCall(() => { + assert.deepStrictEqual(worker.performance.eventLoopUtilization(), + { idle: 0, active: 0, utilization: 0 }); + })); +})(); + +function checkWorkerIdle(wElu) { + const perfWorkerElu = workerELU(); + const tmpMainElu = eventLoopUtilization(mainElu); + + assert.ok(idleActive(wElu) > 0, `${idleActive(wElu)} <= 0`); + assert.ok(idleActive(workerELU(wElu)) > 0, + `${idleActive(workerELU(wElu))} <= 0`); + assert.ok(idleActive(perfWorkerElu) > idleActive(wElu), + `${idleActive(perfWorkerElu)} <= ${idleActive(wElu)}`); + assert.ok(idleActive(tmpMainElu) > idleActive(perfWorkerElu), + `${idleActive(tmpMainElu)} <= ${idleActive(perfWorkerElu)}`); + + wElu = workerELU(); + setTimeout(mustCall(() => { + wElu = workerELU(wElu); + // Some clocks fire early. Removing a few milliseconds to cover that. + assert.ok(idleActive(wElu) >= 45, `${idleActive(wElu)} < 45`); + // Cutting the idle time in half since it's possible that the call took a + // lot of resources to process? + assert.ok(wElu.idle >= 25, `${wElu.idle} < 25`); + + checkWorkerActive(); + }), 50); +} + +function checkWorkerActive() { + const w = workerELU(); + + metricsCh.port2.postMessage({ cmd: 'spin', dur: 50 }); + metricsCh.port2.once('message', (wElu) => { + const w2 = workerELU(w); + + assert.ok(w2.active >= 50, `${w2.active} < 50`); + assert.ok(wElu.active >= 50, `${wElu.active} < 50`); + assert.ok(idleActive(wElu) < idleActive(w2), + `${idleActive(wElu)} >= ${idleActive(w2)}`); + + metricsCh.port2.postMessage({ cmd: 'close' }); + }); +} + +function idleActive(elu) { + return elu.idle + elu.active; +} diff --git a/test/parallel/test-worker-terminate-nested.js b/test/parallel/test-worker-terminate-nested.js new file mode 100644 index 0000000000000000000000000000000000000000..3924528cea1ccb6b9ec23c21a1d6e4adf7656193 --- /dev/null +++ b/test/parallel/test-worker-terminate-nested.js @@ -0,0 +1,15 @@ +'use strict'; +const common = require('../common'); +const { Worker } = require('worker_threads'); + +// Check that a Worker that's running another Worker can be terminated. + +const worker = new Worker(` +const { Worker, parentPort } = require('worker_threads'); +const worker = new Worker('setInterval(() => {}, 10);', { eval: true }); +worker.on('online', () => { + parentPort.postMessage({}); +}); +`, { eval: true }); + +worker.on('message', common.mustCall(() => worker.terminate())); diff --git a/tools/.eslintrc.yaml b/tools/.eslintrc.yaml deleted file mode 100644 index fbc3738465169fa95b1da54ffcf50b5679cf4203..0000000000000000000000000000000000000000 --- a/tools/.eslintrc.yaml +++ /dev/null @@ -1,19 +0,0 @@ -env: - node: true - es6: true - -rules: - camelcase: - - error - - properties: 'never' - ignoreDestructuring: true - allow: ['child_process'] - comma-dangle: - - error - - arrays: 'always-multiline' - objects: 'only-multiline' - imports: 'only-multiline' - exports: 'only-multiline' - no-unused-vars: [error, { args: 'after-used' }] - prefer-arrow-callback: error - no-var: error diff --git a/tools/cpplint.py b/tools/cpplint.py deleted file mode 100755 index 1502ec3e057e1be7874b563395c6d2c703e9fd00..0000000000000000000000000000000000000000 --- a/tools/cpplint.py +++ /dev/null @@ -1,6722 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (c) 2009 Google Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -"""Does google-lint on c++ files. - -The goal of this script is to identify places in the code that *may* -be in non-compliance with google style. It does not attempt to fix -up these problems -- the point is to educate. It does also not -attempt to find all problems, or to ensure that everything it does -find is legitimately a problem. - -In particular, we can get very confused by /* and // inside strings! -We do a small hack, which is to ignore //'s with "'s after them on the -same line, but it is far from perfect (in either direction). -""" - -import codecs -import copy -import getopt -import glob -import itertools -import math # for log -import os -import re -import sre_compile -import string -import sys -import sysconfig -import unicodedata -import xml.etree.ElementTree - -# if empty, use defaults -_valid_extensions = set([]) - -__VERSION__ = '1.4.6' - -try: - xrange # Python 2 -except NameError: - # -- pylint: disable=redefined-builtin - xrange = range # Python 3 - - -_USAGE = """ -Syntax: cpplint.py [--verbose=#] [--output=emacs|eclipse|vs7|junit] - [--filter=-x,+y,...] - [--counting=total|toplevel|detailed] [--root=subdir] - [--repository=path] - [--linelength=digits] [--headers=x,y,...] - [--recursive] - [--exclude=path] - [--extensions=hpp,cpp,...] - [--quiet] - [--version] - [file] ... - - Style checker for C/C++ source files. - This is a fork of the Google style checker with minor extensions. - - The style guidelines this tries to follow are those in - https://google.github.io/styleguide/cppguide.html - - Every problem is given a confidence score from 1-5, with 5 meaning we are - certain of the problem, and 1 meaning it could be a legitimate construct. - This will miss some errors, and is not a substitute for a code review. - - To suppress false-positive errors of a certain category, add a - 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) - suppresses errors of all categories on that line. - - The files passed in will be linted; at least one file must be provided. - Default linted extensions are %s. - Other file types will be ignored. - Change the extensions with the --extensions flag. - - Flags: - - output=emacs|eclipse|vs7|junit - By default, the output is formatted to ease emacs parsing. Visual Studio - compatible output (vs7) may also be used. Further support exists for - eclipse (eclipse), and JUnit (junit). XML parsers such as those used - in Jenkins and Bamboo may also be used. Other formats are unsupported. - - verbose=# - Specify a number 0-5 to restrict errors to certain verbosity levels. - Errors with lower verbosity levels have lower confidence and are more - likely to be false positives. - - quiet - Don't print anything if no errors are found. - - filter=-x,+y,... - Specify a comma-separated list of category-filters to apply: only - error messages whose category names pass the filters will be printed. - (Category names are printed with the message and look like - "[whitespace/indent]".) Filters are evaluated left to right. - "-FOO" and "FOO" means "do not print categories that start with FOO". - "+FOO" means "do print categories that start with FOO". - - Examples: --filter=-whitespace,+whitespace/braces - --filter=whitespace,runtime/printf,+runtime/printf_format - --filter=-,+build/include_what_you_use - - To see a list of all the categories used in cpplint, pass no arg: - --filter= - - counting=total|toplevel|detailed - The total number of errors found is always printed. If - 'toplevel' is provided, then the count of errors in each of - the top-level categories like 'build' and 'whitespace' will - also be printed. If 'detailed' is provided, then a count - is provided for each category like 'build/class'. - - repository=path - The top level directory of the repository, used to derive the header - guard CPP variable. By default, this is determined by searching for a - path that contains .git, .hg, or .svn. When this flag is specified, the - given path is used instead. This option allows the header guard CPP - variable to remain consistent even if members of a team have different - repository root directories (such as when checking out a subdirectory - with SVN). In addition, users of non-mainstream version control systems - can use this flag to ensure readable header guard CPP variables. - - Examples: - Assuming that Alice checks out ProjectName and Bob checks out - ProjectName/trunk and trunk contains src/chrome/ui/browser.h, then - with no --repository flag, the header guard CPP variable will be: - - Alice => TRUNK_SRC_CHROME_BROWSER_UI_BROWSER_H_ - Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_ - - If Alice uses the --repository=trunk flag and Bob omits the flag or - uses --repository=. then the header guard CPP variable will be: - - Alice => SRC_CHROME_BROWSER_UI_BROWSER_H_ - Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_ - - root=subdir - The root directory used for deriving header guard CPP variable. - This directory is relative to the top level directory of the repository - which by default is determined by searching for a directory that contains - .git, .hg, or .svn but can also be controlled with the --repository flag. - If the specified directory does not exist, this flag is ignored. - - Examples: - Assuming that src is the top level directory of the repository (and - cwd=top/src), the header guard CPP variables for - src/chrome/browser/ui/browser.h are: - - No flag => CHROME_BROWSER_UI_BROWSER_H_ - --root=chrome => BROWSER_UI_BROWSER_H_ - --root=chrome/browser => UI_BROWSER_H_ - --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_ - - linelength=digits - This is the allowed line length for the project. The default value is - 80 characters. - - Examples: - --linelength=120 - - recursive - Search for files to lint recursively. Each directory given in the list - of files to be linted is replaced by all files that descend from that - directory. Files with extensions not in the valid extensions list are - excluded. - - exclude=path - Exclude the given path from the list of files to be linted. Relative - paths are evaluated relative to the current directory and shell globbing - is performed. This flag can be provided multiple times to exclude - multiple files. - - Examples: - --exclude=one.cc - --exclude=src/*.cc - --exclude=src/*.cc --exclude=test/*.cc - - extensions=extension,extension,... - The allowed file extensions that cpplint will check - - Examples: - --extensions=%s - - headers=x,y,... - The header extensions that cpplint will treat as .h in checks. Values are - automatically added to --extensions list. - (by default, only files with extensions %s will be assumed to be headers) - - Examples: - --headers=%s - --headers=hpp,hxx - --headers=hpp - - cpplint.py supports per-directory configurations specified in CPPLINT.cfg - files. CPPLINT.cfg file can contain a number of key=value pairs. - Currently the following options are supported: - - set noparent - filter=+filter1,-filter2,... - exclude_files=regex - linelength=80 - root=subdir - headers=x,y,... - - "set noparent" option prevents cpplint from traversing directory tree - upwards looking for more .cfg files in parent directories. This option - is usually placed in the top-level project directory. - - The "filter" option is similar in function to --filter flag. It specifies - message filters in addition to the |_DEFAULT_FILTERS| and those specified - through --filter command-line flag. - - "exclude_files" allows to specify a regular expression to be matched against - a file name. If the expression matches, the file is skipped and not run - through the linter. - - "linelength" allows to specify the allowed line length for the project. - - The "root" option is similar in function to the --root flag (see example - above). Paths are relative to the directory of the CPPLINT.cfg. - - The "headers" option is similar in function to the --headers flag - (see example above). - - CPPLINT.cfg has an effect on files in the same directory and all - sub-directories, unless overridden by a nested configuration file. - - Example file: - filter=-build/include_order,+build/include_alpha - exclude_files=.*\\.cc - - The above example disables build/include_order warning and enables - build/include_alpha as well as excludes all .cc from being - processed by linter, in the current directory (where the .cfg - file is located) and all sub-directories. -""" - -# We categorize each error message we print. Here are the categories. -# We want an explicit list so we can list them all in cpplint --filter=. -# If you add a new error message with a new category, add it to the list -# here! cpplint_unittest.py should tell you if you forget to do this. -_ERROR_CATEGORIES = [ - 'build/class', - 'build/c++11', - 'build/c++14', - 'build/c++tr1', - 'build/deprecated', - 'build/endif_comment', - 'build/explicit_make_pair', - 'build/forward_decl', - 'build/header_guard', - 'build/include', - 'build/include_subdir', - 'build/include_alpha', - 'build/include_inline', - 'build/include_order', - 'build/include_what_you_use', - 'build/namespaces_literals', - 'build/namespaces', - 'build/printf_format', - 'build/storage_class', - 'legal/copyright', - 'readability/alt_tokens', - 'readability/braces', - 'readability/casting', - 'readability/check', - 'readability/constructors', - 'readability/fn_size', - 'readability/inheritance', - 'readability/pointer_notation', - 'readability/multiline_comment', - 'readability/multiline_string', - 'readability/namespace', - 'readability/nolint', - 'readability/nul', - 'readability/null_usage', - 'readability/strings', - 'readability/todo', - 'readability/utf8', - 'runtime/arrays', - 'runtime/casting', - 'runtime/explicit', - 'runtime/int', - 'runtime/init', - 'runtime/invalid_increment', - 'runtime/member_string_references', - 'runtime/memset', - 'runtime/indentation_namespace', - 'runtime/operator', - 'runtime/printf', - 'runtime/printf_format', - 'runtime/references', - 'runtime/string', - 'runtime/threadsafe_fn', - 'runtime/vlog', - 'runtime/v8_persistent', - 'whitespace/blank_line', - 'whitespace/braces', - 'whitespace/comma', - 'whitespace/comments', - 'whitespace/empty_conditional_body', - 'whitespace/empty_if_body', - 'whitespace/empty_loop_body', - 'whitespace/end_of_line', - 'whitespace/ending_newline', - 'whitespace/forcolon', - 'whitespace/indent', - 'whitespace/line_length', - 'whitespace/newline', - 'whitespace/operators', - 'whitespace/parens', - 'whitespace/semicolon', - 'whitespace/tab', - 'whitespace/todo', - ] - -# These error categories are no longer enforced by cpplint, but for backwards- -# compatibility they may still appear in NOLINT comments. -_LEGACY_ERROR_CATEGORIES = [ - 'readability/streams', - 'readability/function', - ] - -# The default state of the category filter. This is overridden by the --filter= -# flag. By default all errors are on, so only add here categories that should be -# off by default (i.e., categories that must be enabled by the --filter= flags). -# All entries here should start with a '-' or '+', as in the --filter= flag. -_DEFAULT_FILTERS = ['-build/include_alpha'] - -# The default list of categories suppressed for C (not C++) files. -_DEFAULT_C_SUPPRESSED_CATEGORIES = [ - 'readability/casting', - ] - -# The default list of categories suppressed for Linux Kernel files. -_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [ - 'whitespace/tab', - ] - -# We used to check for high-bit characters, but after much discussion we -# decided those were OK, as long as they were in UTF-8 and didn't represent -# hard-coded international strings, which belong in a separate i18n file. - -# C++ headers -_CPP_HEADERS = frozenset([ - # Legacy - 'algobase.h', - 'algo.h', - 'alloc.h', - 'builtinbuf.h', - 'bvector.h', - 'complex.h', - 'defalloc.h', - 'deque.h', - 'editbuf.h', - 'fstream.h', - 'function.h', - 'hash_map', - 'hash_map.h', - 'hash_set', - 'hash_set.h', - 'hashtable.h', - 'heap.h', - 'indstream.h', - 'iomanip.h', - 'iostream.h', - 'istream.h', - 'iterator.h', - 'list.h', - 'map.h', - 'multimap.h', - 'multiset.h', - 'ostream.h', - 'pair.h', - 'parsestream.h', - 'pfstream.h', - 'procbuf.h', - 'pthread_alloc', - 'pthread_alloc.h', - 'rope', - 'rope.h', - 'ropeimpl.h', - 'set.h', - 'slist', - 'slist.h', - 'stack.h', - 'stdiostream.h', - 'stl_alloc.h', - 'stl_relops.h', - 'streambuf.h', - 'stream.h', - 'strfile.h', - 'strstream.h', - 'tempbuf.h', - 'tree.h', - 'type_traits.h', - 'vector.h', - # 17.6.1.2 C++ library headers - 'algorithm', - 'array', - 'atomic', - 'bitset', - 'chrono', - 'codecvt', - 'complex', - 'condition_variable', - 'deque', - 'exception', - 'forward_list', - 'fstream', - 'functional', - 'future', - 'initializer_list', - 'iomanip', - 'ios', - 'iosfwd', - 'iostream', - 'istream', - 'iterator', - 'limits', - 'list', - 'locale', - 'map', - 'memory', - 'mutex', - 'new', - 'numeric', - 'ostream', - 'queue', - 'random', - 'ratio', - 'regex', - 'scoped_allocator', - 'set', - 'sstream', - 'stack', - 'stdexcept', - 'streambuf', - 'string', - 'strstream', - 'system_error', - 'thread', - 'tuple', - 'typeindex', - 'typeinfo', - 'type_traits', - 'unordered_map', - 'unordered_set', - 'utility', - 'valarray', - 'vector', - # 17.6.1.2 C++14 headers - 'shared_mutex', - # 17.6.1.2 C++17 headers - 'any', - 'charconv', - 'codecvt', - 'execution', - 'filesystem', - 'memory_resource', - 'optional', - 'string_view', - 'variant', - # 17.6.1.2 C++ headers for C library facilities - 'cassert', - 'ccomplex', - 'cctype', - 'cerrno', - 'cfenv', - 'cfloat', - 'cinttypes', - 'ciso646', - 'climits', - 'clocale', - 'cmath', - 'csetjmp', - 'csignal', - 'cstdalign', - 'cstdarg', - 'cstdbool', - 'cstddef', - 'cstdint', - 'cstdio', - 'cstdlib', - 'cstring', - 'ctgmath', - 'ctime', - 'cuchar', - 'cwchar', - 'cwctype', - ]) - -# Type names -_TYPES = re.compile( - r'^(?:' - # [dcl.type.simple] - r'(char(16_t|32_t)?)|wchar_t|' - r'bool|short|int|long|signed|unsigned|float|double|' - # [support.types] - r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|' - # [cstdint.syn] - r'(u?int(_fast|_least)?(8|16|32|64)_t)|' - r'(u?int(max|ptr)_t)|' - r')$') - - -# These headers are excluded from [build/include] and [build/include_order] -# checks: -# - Anything not following google file name conventions (containing an -# uppercase character, such as Python.h or nsStringAPI.h, for example). -# - Lua headers. -_THIRD_PARTY_HEADERS_PATTERN = re.compile( - r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') - -# Pattern for matching FileInfo.BaseName() against test file name -_test_suffixes = ['_test', '_regtest', '_unittest'] -_TEST_FILE_SUFFIX = '(' + '|'.join(_test_suffixes) + r')$' - -# Pattern that matches only complete whitespace, possibly across multiple lines. -_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL) - -# Assertion macros. These are defined in base/logging.h and -# testing/base/public/gunit.h. -_CHECK_MACROS = [ - 'DCHECK', 'CHECK', - 'EXPECT_TRUE', 'ASSERT_TRUE', - 'EXPECT_FALSE', 'ASSERT_FALSE', - ] - -# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE -_CHECK_REPLACEMENT = dict([(macro_var, {}) for macro_var in _CHECK_MACROS]) - -for op, replacement in [('==', 'EQ'), ('!=', 'NE'), - ('>=', 'GE'), ('>', 'GT'), - ('<=', 'LE'), ('<', 'LT')]: - _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement - _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement - _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement - _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement - -for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), - ('>=', 'LT'), ('>', 'LE'), - ('<=', 'GT'), ('<', 'GE')]: - _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement - _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement - -# Alternative tokens and their replacements. For full list, see section 2.5 -# Alternative tokens [lex.digraph] in the C++ standard. -# -# Digraphs (such as '%:') are not included here since it's a mess to -# match those on a word boundary. -_ALT_TOKEN_REPLACEMENT = { - 'and': '&&', - 'bitor': '|', - 'or': '||', - 'xor': '^', - 'compl': '~', - 'bitand': '&', - 'and_eq': '&=', - 'or_eq': '|=', - 'xor_eq': '^=', - 'not': '!', - 'not_eq': '!=' - } - -# Compile regular expression that matches all the above keywords. The "[ =()]" -# bit is meant to avoid matching these keywords outside of boolean expressions. -# -# False positives include C-style multi-line comments and multi-line strings -# but those have always been troublesome for cpplint. -_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( - r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') - - -# These constants define types of headers for use with -# _IncludeState.CheckNextIncludeOrder(). -_C_SYS_HEADER = 1 -_CPP_SYS_HEADER = 2 -_LIKELY_MY_HEADER = 3 -_POSSIBLE_MY_HEADER = 4 -_OTHER_HEADER = 5 - -# These constants define the current inline assembly state -_NO_ASM = 0 # Outside of inline assembly block -_INSIDE_ASM = 1 # Inside inline assembly block -_END_ASM = 2 # Last line of inline assembly block -_BLOCK_ASM = 3 # The whole block is an inline assembly block - -# Match start of assembly blocks -_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' - r'(?:\s+(volatile|__volatile__))?' - r'\s*[{(]') - -# Match strings that indicate we're working on a C (not C++) file. -_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|' - r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))') - -# Match string that indicates we're working on a Linux Kernel file. -_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)') - -_NULL_TOKEN_PATTERN = re.compile(r'\bNULL\b') - -_V8_PERSISTENT_PATTERN = re.compile(r'\bv8::Persistent\b') - -_RIGHT_LEANING_POINTER_PATTERN = re.compile(r'[^=|(,\s><);&?:}]' - r'(? "suppress all" - _error_suppressions.setdefault(None, set()).add(suppressed_line) - else: - if category.startswith('(') and category.endswith(')'): - category = category[1:-1] - if category in _ERROR_CATEGORIES: - _error_suppressions.setdefault(category, set()).add(suppressed_line) - elif category not in _LEGACY_ERROR_CATEGORIES: - error(filename, linenum, 'readability/nolint', 5, - 'Unknown NOLINT error category: %s' % category) - - -def ProcessGlobalSuppresions(lines): - """Updates the list of global error suppressions. - - Parses any lint directives in the file that have global effect. - - Args: - lines: An array of strings, each representing a line of the file, with the - last element being empty if the file is terminated with a newline. - """ - for line in lines: - if _SEARCH_C_FILE.search(line): - for category in _DEFAULT_C_SUPPRESSED_CATEGORIES: - _global_error_suppressions[category] = True - if _SEARCH_KERNEL_FILE.search(line): - for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES: - _global_error_suppressions[category] = True - - -def ResetNolintSuppressions(): - """Resets the set of NOLINT suppressions to empty.""" - _error_suppressions.clear() - _global_error_suppressions.clear() - - -def IsErrorSuppressedByNolint(category, linenum): - """Returns true if the specified error category is suppressed on this line. - - Consults the global error_suppressions map populated by - ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. - - Args: - category: str, the category of the error. - linenum: int, the current line number. - Returns: - bool, True iff the error should be suppressed due to a NOLINT comment or - global suppression. - """ - return (_global_error_suppressions.get(category, False) or - linenum in _error_suppressions.get(category, set()) or - linenum in _error_suppressions.get(None, set())) - - -def Match(pattern, s): - """Matches the string with the pattern, caching the compiled regexp.""" - # The regexp compilation caching is inlined in both Match and Search for - # performance reasons; factoring it out into a separate function turns out - # to be noticeably expensive. - if pattern not in _regexp_compile_cache: - _regexp_compile_cache[pattern] = sre_compile.compile(pattern) - return _regexp_compile_cache[pattern].match(s) - - -def ReplaceAll(pattern, rep, s): - """Replaces instances of pattern in a string with a replacement. - - The compiled regex is kept in a cache shared by Match and Search. - - Args: - pattern: regex pattern - rep: replacement text - s: search string - - Returns: - string with replacements made (or original string if no replacements) - """ - if pattern not in _regexp_compile_cache: - _regexp_compile_cache[pattern] = sre_compile.compile(pattern) - return _regexp_compile_cache[pattern].sub(rep, s) - - -def Search(pattern, s): - """Searches the string for the pattern, caching the compiled regexp.""" - if pattern not in _regexp_compile_cache: - _regexp_compile_cache[pattern] = sre_compile.compile(pattern) - return _regexp_compile_cache[pattern].search(s) - - -def _IsSourceExtension(s): - """File extension (excluding dot) matches a source file extension.""" - return s in GetNonHeaderExtensions() - - -class _IncludeState(object): - """Tracks line numbers for includes, and the order in which includes appear. - - include_list contains list of lists of (header, line number) pairs. - It's a lists of lists rather than just one flat list to make it - easier to update across preprocessor boundaries. - - Call CheckNextIncludeOrder() once for each header in the file, passing - in the type constants defined above. Calls in an illegal order will - raise an _IncludeError with an appropriate error message. - - """ - # self._section will move monotonically through this set. If it ever - # needs to move backwards, CheckNextIncludeOrder will raise an error. - _INITIAL_SECTION = 0 - _MY_H_SECTION = 1 - _OTHER_H_SECTION = 2 - _C_SECTION = 3 - _CPP_SECTION = 4 - - _TYPE_NAMES = { - _C_SYS_HEADER: 'C system header', - _CPP_SYS_HEADER: 'C++ system header', - _LIKELY_MY_HEADER: 'header this file implements', - _POSSIBLE_MY_HEADER: 'header this file may implement', - _OTHER_HEADER: 'other header', - } - _SECTION_NAMES = { - _INITIAL_SECTION: "... nothing. (This can't be an error.)", - _MY_H_SECTION: 'a header this file implements', - _OTHER_H_SECTION: 'other header', - _C_SECTION: 'C system header', - _CPP_SECTION: 'C++ system header', - } - - def __init__(self): - self.include_list = [[]] - self._section = None - self._last_header = None - self.ResetSection('') - - def FindHeader(self, header): - """Check if a header has already been included. - - Args: - header: header to check. - Returns: - Line number of previous occurrence, or -1 if the header has not - been seen before. - """ - for section_list in self.include_list: - for f in section_list: - if f[0] == header: - return f[1] - return -1 - - def ResetSection(self, directive): - """Reset section checking for preprocessor directive. - - Args: - directive: preprocessor directive (e.g. "if", "else"). - """ - # The name of the current section. - self._section = self._INITIAL_SECTION - # The path of last found header. - self._last_header = '' - - # Update list of includes. Note that we never pop from the - # include list. - if directive in ('if', 'ifdef', 'ifndef'): - self.include_list.append([]) - elif directive in ('else', 'elif'): - self.include_list[-1] = [] - - def SetLastHeader(self, header_path): - self._last_header = header_path - - def CanonicalizeAlphabeticalOrder(self, header_path): - """Returns a path canonicalized for alphabetical comparison. - - - replaces "-" with "_" so they both cmp the same. - - removes '-inl' since we don't require them to be after the main header. - - lowercase everything, just in case. - - Args: - header_path: Path to be canonicalized. - - Returns: - Canonicalized path. - """ - return header_path.replace('-inl.h', '.h').replace('-', '_').lower() - - def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): - """Check if a header is in alphabetical order with the previous header. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - header_path: Canonicalized header to be checked. - - Returns: - Returns true if the header is in alphabetical order. - """ - # If previous section is different from current section, _last_header will - # be reset to empty string, so it's always less than current header. - # - # If previous line was a blank line, assume that the headers are - # intentionally sorted the way they are. - if (self._last_header > header_path and - Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): - return False - return True - - def CheckNextIncludeOrder(self, header_type): - """Returns a non-empty error message if the next header is out of order. - - This function also updates the internal state to be ready to check - the next include. - - Args: - header_type: One of the _XXX_HEADER constants defined above. - - Returns: - The empty string if the header is in the right order, or an - error message describing what's wrong. - - """ - error_message = ('Found %s after %s' % - (self._TYPE_NAMES[header_type], - self._SECTION_NAMES[self._section])) - - last_section = self._section - - if header_type == _C_SYS_HEADER: - if self._section <= self._C_SECTION: - self._section = self._C_SECTION - else: - self._last_header = '' - return error_message - elif header_type == _CPP_SYS_HEADER: - if self._section <= self._CPP_SECTION: - self._section = self._CPP_SECTION - else: - self._last_header = '' - return error_message - elif header_type == _LIKELY_MY_HEADER: - if self._section <= self._MY_H_SECTION: - self._section = self._MY_H_SECTION - else: - self._section = self._OTHER_H_SECTION - elif header_type == _POSSIBLE_MY_HEADER: - if self._section <= self._MY_H_SECTION: - self._section = self._MY_H_SECTION - else: - # This will always be the fallback because we're not sure - # enough that the header is associated with this file. - self._section = self._OTHER_H_SECTION - else: - assert header_type == _OTHER_HEADER - self._section = self._OTHER_H_SECTION - - if last_section != self._section: - self._last_header = '' - - return '' - - -class _CppLintState(object): - """Maintains module-wide state..""" - - def __init__(self): - self.verbose_level = 1 # global setting. - self.error_count = 0 # global count of reported errors - # filters to apply when emitting error messages - self.filters = _DEFAULT_FILTERS[:] - # backup of filter list. Used to restore the state after each file. - self._filters_backup = self.filters[:] - self.counting = 'total' # In what way are we counting errors? - self.errors_by_category = {} # string to int dict storing error counts - self.quiet = False # Suppress non-error messagess? - - # output format: - # "emacs" - format that emacs can parse (default) - # "eclipse" - format that eclipse can parse - # "vs7" - format that Microsoft Visual Studio 7 can parse - # "junit" - format that Jenkins, Bamboo, etc can parse - self.output_format = 'emacs' - - # For JUnit output, save errors and failures until the end so that they - # can be written into the XML - self._junit_errors = [] - self._junit_failures = [] - - def SetOutputFormat(self, output_format): - """Sets the output format for errors.""" - self.output_format = output_format - - def SetQuiet(self, quiet): - """Sets the module's quiet settings, and returns the previous setting.""" - last_quiet = self.quiet - self.quiet = quiet - return last_quiet - - def SetVerboseLevel(self, level): - """Sets the module's verbosity, and returns the previous setting.""" - last_verbose_level = self.verbose_level - self.verbose_level = level - return last_verbose_level - - def SetCountingStyle(self, counting_style): - """Sets the module's counting options.""" - self.counting = counting_style - - def SetFilters(self, filters): - """Sets the error-message filters. - - These filters are applied when deciding whether to emit a given - error message. - - Args: - filters: A string of comma-separated filters (eg "+whitespace/indent"). - Each filter should start with + or -; else we die. - - Raises: - ValueError: The comma-separated filters did not all start with '+' or '-'. - E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" - """ - # Default filters always have less priority than the flag ones. - self.filters = _DEFAULT_FILTERS[:] - self.AddFilters(filters) - - def AddFilters(self, filters): - """ Adds more filters to the existing list of error-message filters. """ - for filt in filters.split(','): - clean_filt = filt.strip() - if clean_filt: - self.filters.append(clean_filt) - for filt in self.filters: - if not (filt.startswith('+') or filt.startswith('-')): - raise ValueError('Every filter in --filters must start with + or -' - ' (%s does not)' % filt) - - def BackupFilters(self): - """ Saves the current filter list to backup storage.""" - self._filters_backup = self.filters[:] - - def RestoreFilters(self): - """ Restores filters previously backed up.""" - self.filters = self._filters_backup[:] - - def ResetErrorCounts(self): - """Sets the module's error statistic back to zero.""" - self.error_count = 0 - self.errors_by_category = {} - - def IncrementErrorCount(self, category): - """Bumps the module's error statistic.""" - self.error_count += 1 - if self.counting in ('toplevel', 'detailed'): - if self.counting != 'detailed': - category = category.split('/')[0] - if category not in self.errors_by_category: - self.errors_by_category[category] = 0 - self.errors_by_category[category] += 1 - - def PrintErrorCounts(self): - """Print a summary of errors by category, and the total.""" - for category, count in sorted(iteritems(self.errors_by_category)): - self.PrintInfo('Category \'%s\' errors found: %d\n' % - (category, count)) - if self.error_count > 0: - self.PrintInfo('Total errors found: %d\n' % self.error_count) - - def PrintInfo(self, message): - if not _quiet and self.output_format != 'junit': - sys.stdout.write(message) - - def PrintError(self, message): - if self.output_format == 'junit': - self._junit_errors.append(message) - else: - sys.stderr.write(message) - - def AddJUnitFailure(self, filename, linenum, message, category, confidence): - self._junit_failures.append((filename, linenum, message, category, - confidence)) - - def FormatJUnitXML(self): - num_errors = len(self._junit_errors) - num_failures = len(self._junit_failures) - - testsuite = xml.etree.ElementTree.Element('testsuite') - testsuite.attrib['errors'] = str(num_errors) - testsuite.attrib['failures'] = str(num_failures) - testsuite.attrib['name'] = 'cpplint' - - if num_errors == 0 and num_failures == 0: - testsuite.attrib['tests'] = str(1) - xml.etree.ElementTree.SubElement(testsuite, 'testcase', name='passed') - - else: - testsuite.attrib['tests'] = str(num_errors + num_failures) - if num_errors > 0: - testcase = xml.etree.ElementTree.SubElement(testsuite, 'testcase') - testcase.attrib['name'] = 'errors' - error = xml.etree.ElementTree.SubElement(testcase, 'error') - error.text = '\n'.join(self._junit_errors) - if num_failures > 0: - # Group failures by file - failed_file_order = [] - failures_by_file = {} - for failure in self._junit_failures: - failed_file = failure[0] - if failed_file not in failed_file_order: - failed_file_order.append(failed_file) - failures_by_file[failed_file] = [] - failures_by_file[failed_file].append(failure) - # Create a testcase for each file - for failed_file in failed_file_order: - failures = failures_by_file[failed_file] - testcase = xml.etree.ElementTree.SubElement(testsuite, 'testcase') - testcase.attrib['name'] = failed_file - failure = xml.etree.ElementTree.SubElement(testcase, 'failure') - template = '{0}: {1} [{2}] [{3}]' - texts = [template.format(f[1], f[2], f[3], f[4]) for f in failures] - failure.text = '\n'.join(texts) - - xml_decl = '\n' - return xml_decl + xml.etree.ElementTree.tostring(testsuite, 'utf-8').decode('utf-8') - - -_cpplint_state = _CppLintState() - - -def _OutputFormat(): - """Gets the module's output format.""" - return _cpplint_state.output_format - - -def _SetOutputFormat(output_format): - """Sets the module's output format.""" - _cpplint_state.SetOutputFormat(output_format) - -def _Quiet(): - """Return's the module's quiet setting.""" - return _cpplint_state.quiet - -def _SetQuiet(quiet): - """Set the module's quiet status, and return previous setting.""" - return _cpplint_state.SetQuiet(quiet) - - -def _VerboseLevel(): - """Returns the module's verbosity setting.""" - return _cpplint_state.verbose_level - - -def _SetVerboseLevel(level): - """Sets the module's verbosity, and returns the previous setting.""" - return _cpplint_state.SetVerboseLevel(level) - - -def _SetCountingStyle(level): - """Sets the module's counting options.""" - _cpplint_state.SetCountingStyle(level) - - -def _Filters(): - """Returns the module's list of output filters, as a list.""" - return _cpplint_state.filters - - -def _SetFilters(filters): - """Sets the module's error-message filters. - - These filters are applied when deciding whether to emit a given - error message. - - Args: - filters: A string of comma-separated filters (eg "whitespace/indent"). - Each filter should start with + or -; else we die. - """ - _cpplint_state.SetFilters(filters) - -def _AddFilters(filters): - """Adds more filter overrides. - - Unlike _SetFilters, this function does not reset the current list of filters - available. - - Args: - filters: A string of comma-separated filters (eg "whitespace/indent"). - Each filter should start with + or -; else we die. - """ - _cpplint_state.AddFilters(filters) - -def _BackupFilters(): - """ Saves the current filter list to backup storage.""" - _cpplint_state.BackupFilters() - -def _RestoreFilters(): - """ Restores filters previously backed up.""" - _cpplint_state.RestoreFilters() - -class _FunctionState(object): - """Tracks current function name and the number of lines in its body.""" - - _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. - _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. - - def __init__(self): - self.in_a_function = False - self.lines_in_function = 0 - self.current_function = '' - - def Begin(self, function_name): - """Start analyzing function body. - - Args: - function_name: The name of the function being tracked. - """ - self.in_a_function = True - self.lines_in_function = 0 - self.current_function = function_name - - def Count(self): - """Count line in current function body.""" - if self.in_a_function: - self.lines_in_function += 1 - - def Check(self, error, filename, linenum): - """Report if too many lines in function body. - - Args: - error: The function to call with any errors found. - filename: The name of the current file. - linenum: The number of the line to check. - """ - if not self.in_a_function: - return - - if Match(r'T(EST|est)', self.current_function): - base_trigger = self._TEST_TRIGGER - else: - base_trigger = self._NORMAL_TRIGGER - trigger = base_trigger * 2**_VerboseLevel() - - if self.lines_in_function > trigger: - error_level = int(math.log(self.lines_in_function / base_trigger, 2)) - # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... - if error_level > 5: - error_level = 5 - error(filename, linenum, 'readability/fn_size', error_level, - 'Small and focused functions are preferred:' - ' %s has %d non-comment lines' - ' (error triggered by exceeding %d lines).' % ( - self.current_function, self.lines_in_function, trigger)) - - def End(self): - """Stop analyzing function body.""" - self.in_a_function = False - - -class _IncludeError(Exception): - """Indicates a problem with the include order in a file.""" - pass - - -class FileInfo(object): - """Provides utility functions for filenames. - - FileInfo provides easy access to the components of a file's path - relative to the project root. - """ - - def __init__(self, filename): - self._filename = filename - - def FullName(self): - """Make Windows paths like Unix.""" - return os.path.abspath(self._filename).replace('\\', '/') - - def RepositoryName(self): - r"""FullName after removing the local path to the repository. - - If we have a real absolute path name here we can try to do something smart: - detecting the root of the checkout and truncating /path/to/checkout from - the name so that we get header guards that don't include things like - "C:\\Documents and Settings\\..." or "/home/username/..." in them and thus - people on different computers who have checked the source out to different - locations won't see bogus errors. - """ - fullname = self.FullName() - - if os.path.exists(fullname): - project_dir = os.path.dirname(fullname) - - # If the user specified a repository path, it exists, and the file is - # contained in it, use the specified repository path - if _repository: - repo = FileInfo(_repository).FullName() - root_dir = project_dir - while os.path.exists(root_dir): - # allow case insensitive compare on Windows - if os.path.normcase(root_dir) == os.path.normcase(repo): - return os.path.relpath(fullname, root_dir).replace('\\', '/') - one_up_dir = os.path.dirname(root_dir) - if one_up_dir == root_dir: - break - root_dir = one_up_dir - - if os.path.exists(os.path.join(project_dir, ".svn")): - # If there's a .svn file in the current directory, we recursively look - # up the directory tree for the top of the SVN checkout - root_dir = project_dir - one_up_dir = os.path.dirname(root_dir) - while os.path.exists(os.path.join(one_up_dir, ".svn")): - root_dir = os.path.dirname(root_dir) - one_up_dir = os.path.dirname(one_up_dir) - - prefix = os.path.commonprefix([root_dir, project_dir]) - return fullname[len(prefix) + 1:] - - # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by - # searching up from the current path. - root_dir = current_dir = os.path.dirname(fullname) - while current_dir != os.path.dirname(current_dir): - if (os.path.exists(os.path.join(current_dir, ".git")) or - os.path.exists(os.path.join(current_dir, ".hg")) or - os.path.exists(os.path.join(current_dir, ".svn"))): - root_dir = current_dir - current_dir = os.path.dirname(current_dir) - - if (os.path.exists(os.path.join(root_dir, ".git")) or - os.path.exists(os.path.join(root_dir, ".hg")) or - os.path.exists(os.path.join(root_dir, ".svn"))): - prefix = os.path.commonprefix([root_dir, project_dir]) - return fullname[len(prefix) + 1:] - - # Don't know what to do; header guard warnings may be wrong... - return fullname - - def Split(self): - """Splits the file into the directory, basename, and extension. - - For 'chrome/browser/browser.cc', Split() would - return ('chrome/browser', 'browser', '.cc') - - Returns: - A tuple of (directory, basename, extension). - """ - - googlename = self.RepositoryName() - project, rest = os.path.split(googlename) - return (project,) + os.path.splitext(rest) - - def BaseName(self): - """File base name - text after the final slash, before the final period.""" - return self.Split()[1] - - def Extension(self): - """File extension - text following the final period, includes that period.""" - return self.Split()[2] - - def NoExtension(self): - """File has no source file extension.""" - return '/'.join(self.Split()[0:2]) - - def IsSource(self): - """File has a source file extension.""" - return _IsSourceExtension(self.Extension()[1:]) - - -def _ShouldPrintError(category, confidence, linenum): - """If confidence >= verbose, category passes filter and is not suppressed.""" - - # There are three ways we might decide not to print an error message: - # a "NOLINT(category)" comment appears in the source, - # the verbosity level isn't high enough, or the filters filter it out. - if IsErrorSuppressedByNolint(category, linenum): - return False - - if confidence < _cpplint_state.verbose_level: - return False - - is_filtered = False - for one_filter in _Filters(): - if one_filter.startswith('-'): - if category.startswith(one_filter[1:]): - is_filtered = True - elif one_filter.startswith('+'): - if category.startswith(one_filter[1:]): - is_filtered = False - else: - assert False # should have been checked for in SetFilter. - if is_filtered: - return False - - return True - - -def Error(filename, linenum, category, confidence, message): - """Logs the fact we've found a lint error. - - We log where the error was found, and also our confidence in the error, - that is, how certain we are this is a legitimate style regression, and - not a misidentification or a use that's sometimes justified. - - False positives can be suppressed by the use of - "cpplint(category)" comments on the offending line. These are - parsed into _error_suppressions. - - Args: - filename: The name of the file containing the error. - linenum: The number of the line containing the error. - category: A string used to describe the "category" this bug - falls under: "whitespace", say, or "runtime". Categories - may have a hierarchy separated by slashes: "whitespace/indent". - confidence: A number from 1-5 representing a confidence score for - the error, with 5 meaning that we are certain of the problem, - and 1 meaning that it could be a legitimate construct. - message: The error message. - """ - if _ShouldPrintError(category, confidence, linenum): - _cpplint_state.IncrementErrorCount(category) - if _cpplint_state.output_format == 'vs7': - _cpplint_state.PrintError('%s(%s): error cpplint: [%s] %s [%d]\n' % ( - filename, linenum, category, message, confidence)) - elif _cpplint_state.output_format == 'eclipse': - sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( - filename, linenum, message, category, confidence)) - elif _cpplint_state.output_format == 'junit': - _cpplint_state.AddJUnitFailure(filename, linenum, message, category, - confidence) - else: - final_message = '%s:%s: %s [%s] [%d]\n' % ( - filename, linenum, message, category, confidence) - sys.stderr.write(final_message) - -# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. -_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( - r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') -# Match a single C style comment on the same line. -_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' -# Matches multi-line C style comments. -# This RE is a little bit more complicated than one might expect, because we -# have to take care of space removals tools so we can handle comments inside -# statements better. -# The current rule is: We only clear spaces from both sides when we're at the -# end of the line. Otherwise, we try to remove spaces from the right side, -# if this doesn't work we try on left side but only if there's a non-character -# on the right. -_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( - r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + - _RE_PATTERN_C_COMMENTS + r'\s+|' + - r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + - _RE_PATTERN_C_COMMENTS + r')') - - -def IsCppString(line): - """Does line terminate so, that the next symbol is in string constant. - - This function does not consider single-line nor multi-line comments. - - Args: - line: is a partial line of code starting from the 0..n. - - Returns: - True, if next character appended to 'line' is inside a - string constant. - """ - - line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" - return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 - - -def CleanseRawStrings(raw_lines): - """Removes C++11 raw strings from lines. - - Before: - static const char kData[] = R"( - multi-line string - )"; - - After: - static const char kData[] = "" - (replaced by blank line) - ""; - - Args: - raw_lines: list of raw lines. - - Returns: - list of lines with C++11 raw strings replaced by empty strings. - """ - - delimiter = None - lines_without_raw_strings = [] - for line in raw_lines: - if delimiter: - # Inside a raw string, look for the end - end = line.find(delimiter) - if end >= 0: - # Found the end of the string, match leading space for this - # line and resume copying the original lines, and also insert - # a "" on the last line. - leading_space = Match(r'^(\s*)\S', line) - line = leading_space.group(1) + '""' + line[end + len(delimiter):] - delimiter = None - else: - # Haven't found the end yet, append a blank line. - line = '""' - - # Look for beginning of a raw string, and replace them with - # empty strings. This is done in a loop to handle multiple raw - # strings on the same line. - while delimiter is None: - # Look for beginning of a raw string. - # See 2.14.15 [lex.string] for syntax. - # - # Once we have matched a raw string, we check the prefix of the - # line to make sure that the line is not part of a single line - # comment. It's done this way because we remove raw strings - # before removing comments as opposed to removing comments - # before removing raw strings. This is because there are some - # cpplint checks that requires the comments to be preserved, but - # we don't want to check comments that are inside raw strings. - matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) - if (matched and - not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//', - matched.group(1))): - delimiter = ')' + matched.group(2) + '"' - - end = matched.group(3).find(delimiter) - if end >= 0: - # Raw string ended on same line - line = (matched.group(1) + '""' + - matched.group(3)[end + len(delimiter):]) - delimiter = None - else: - # Start of a multi-line raw string - line = matched.group(1) + '""' - else: - break - - lines_without_raw_strings.append(line) - - # TODO(unknown): if delimiter is not None here, we might want to - # emit a warning for unterminated string. - return lines_without_raw_strings - - -def FindNextMultiLineCommentStart(lines, lineix): - """Find the beginning marker for a multiline comment.""" - while lineix < len(lines): - if lines[lineix].strip().startswith('/*'): - # Only return this marker if the comment goes beyond this line - if lines[lineix].strip().find('*/', 2) < 0: - return lineix - lineix += 1 - return len(lines) - - -def FindNextMultiLineCommentEnd(lines, lineix): - """We are inside a comment, find the end marker.""" - while lineix < len(lines): - if lines[lineix].strip().endswith('*/'): - return lineix - lineix += 1 - return len(lines) - - -def RemoveMultiLineCommentsFromRange(lines, begin, end): - """Clears a range of lines for multi-line comments.""" - # Having // dummy comments makes the lines non-empty, so we will not get - # unnecessary blank line warnings later in the code. - for i in range(begin, end): - lines[i] = '/**/' - - -def RemoveMultiLineComments(filename, lines, error): - """Removes multiline (c-style) comments from lines.""" - lineix = 0 - while lineix < len(lines): - lineix_begin = FindNextMultiLineCommentStart(lines, lineix) - if lineix_begin >= len(lines): - return - lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) - if lineix_end >= len(lines): - error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, - 'Could not find end of multi-line comment') - return - RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) - lineix = lineix_end + 1 - - -def CleanseComments(line): - """Removes //-comments and single-line C-style /* */ comments. - - Args: - line: A line of C++ source. - - Returns: - The line with single-line comments removed. - """ - commentpos = line.find('//') - if commentpos != -1 and not IsCppString(line[:commentpos]): - line = line[:commentpos].rstrip() - # get rid of /* ... */ - return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) - - -class CleansedLines(object): - """Holds 4 copies of all lines with different preprocessing applied to them. - - 1) elided member contains lines without strings and comments. - 2) lines member contains lines without comments. - 3) raw_lines member contains all the lines without processing. - 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw - strings removed. - All these members are of , and of the same length. - """ - - def __init__(self, lines): - self.elided = [] - self.lines = [] - self.raw_lines = lines - self.num_lines = len(lines) - self.lines_without_raw_strings = CleanseRawStrings(lines) - for linenum in range(len(self.lines_without_raw_strings)): - self.lines.append(CleanseComments( - self.lines_without_raw_strings[linenum])) - elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) - self.elided.append(CleanseComments(elided)) - - def NumLines(self): - """Returns the number of lines represented.""" - return self.num_lines - - @staticmethod - def _CollapseStrings(elided): - """Collapses strings and chars on a line to simple "" or '' blocks. - - We nix strings first so we're not fooled by text like '"http://"' - - Args: - elided: The line being processed. - - Returns: - The line with collapsed strings. - """ - if _RE_PATTERN_INCLUDE.match(elided): - return elided - - # Remove escaped characters first to make quote/single quote collapsing - # basic. Things that look like escaped characters shouldn't occur - # outside of strings and chars. - elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) - - # Replace quoted strings and digit separators. Both single quotes - # and double quotes are processed in the same loop, otherwise - # nested quotes wouldn't work. - collapsed = '' - while True: - # Find the first quote character - match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) - if not match: - collapsed += elided - break - head, quote, tail = match.groups() - - if quote == '"': - # Collapse double quoted strings - second_quote = tail.find('"') - if second_quote >= 0: - collapsed += head + '""' - elided = tail[second_quote + 1:] - else: - # Unmatched double quote, don't bother processing the rest - # of the line since this is probably a multiline string. - collapsed += elided - break - else: - # Found single quote, check nearby text to eliminate digit separators. - # - # There is no special handling for floating point here, because - # the integer/fractional/exponent parts would all be parsed - # correctly as long as there are digits on both sides of the - # separator. So we are fine as long as we don't see something - # like "0.'3" (gcc 4.9.0 will not allow this literal). - if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): - match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) - collapsed += head + match_literal.group(1).replace("'", '') - elided = match_literal.group(2) - else: - second_quote = tail.find('\'') - if second_quote >= 0: - collapsed += head + "''" - elided = tail[second_quote + 1:] - else: - # Unmatched single quote - collapsed += elided - break - - return collapsed - - -def FindEndOfExpressionInLine(line, startpos, stack): - """Find the position just after the end of current parenthesized expression. - - Args: - line: a CleansedLines line. - startpos: start searching at this position. - stack: nesting stack at startpos. - - Returns: - On finding matching end: (index just after matching end, None) - On finding an unclosed expression: (-1, None) - Otherwise: (-1, new stack at end of this line) - """ - for i in xrange(startpos, len(line)): - char = line[i] - if char in '([{': - # Found start of parenthesized expression, push to expression stack - stack.append(char) - elif char == '<': - # Found potential start of template argument list - if i > 0 and line[i - 1] == '<': - # Left shift operator - if stack and stack[-1] == '<': - stack.pop() - if not stack: - return (-1, None) - elif i > 0 and Search(r'\boperator\s*$', line[0:i]): - # operator<, don't add to stack - continue - else: - # Tentative start of template argument list - stack.append('<') - elif char in ')]}': - # Found end of parenthesized expression. - # - # If we are currently expecting a matching '>', the pending '<' - # must have been an operator. Remove them from expression stack. - while stack and stack[-1] == '<': - stack.pop() - if not stack: - return (-1, None) - if ((stack[-1] == '(' and char == ')') or - (stack[-1] == '[' and char == ']') or - (stack[-1] == '{' and char == '}')): - stack.pop() - if not stack: - return (i + 1, None) - else: - # Mismatched parentheses - return (-1, None) - elif char == '>': - # Found potential end of template argument list. - - # Ignore "->" and operator functions - if (i > 0 and - (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): - continue - - # Pop the stack if there is a matching '<'. Otherwise, ignore - # this '>' since it must be an operator. - if stack: - if stack[-1] == '<': - stack.pop() - if not stack: - return (i + 1, None) - elif char == ';': - # Found something that look like end of statements. If we are currently - # expecting a '>', the matching '<' must have been an operator, since - # template argument list should not contain statements. - while stack and stack[-1] == '<': - stack.pop() - if not stack: - return (-1, None) - - # Did not find end of expression or unbalanced parentheses on this line - return (-1, stack) - - -def CloseExpression(clean_lines, linenum, pos): - """If input points to ( or { or [ or <, finds the position that closes it. - - If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the - linenum/pos that correspond to the closing of the expression. - - TODO(unknown): cpplint spends a fair bit of time matching parentheses. - Ideally we would want to index all opening and closing parentheses once - and have CloseExpression be just a simple lookup, but due to preprocessor - tricks, this is not so easy. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - pos: A position on the line. - - Returns: - A tuple (line, linenum, pos) pointer *past* the closing brace, or - (line, len(lines), -1) if we never find a close. Note we ignore - strings and comments when matching; and the line we return is the - 'cleansed' line at linenum. - """ - - line = clean_lines.elided[linenum] - if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): - return (line, clean_lines.NumLines(), -1) - - # Check first line - (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) - if end_pos > -1: - return (line, linenum, end_pos) - - # Continue scanning forward - while stack and linenum < clean_lines.NumLines() - 1: - linenum += 1 - line = clean_lines.elided[linenum] - (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) - if end_pos > -1: - return (line, linenum, end_pos) - - # Did not find end of expression before end of file, give up - return (line, clean_lines.NumLines(), -1) - - -def FindStartOfExpressionInLine(line, endpos, stack): - """Find position at the matching start of current expression. - - This is almost the reverse of FindEndOfExpressionInLine, but note - that the input position and returned position differs by 1. - - Args: - line: a CleansedLines line. - endpos: start searching at this position. - stack: nesting stack at endpos. - - Returns: - On finding matching start: (index at matching start, None) - On finding an unclosed expression: (-1, None) - Otherwise: (-1, new stack at beginning of this line) - """ - i = endpos - while i >= 0: - char = line[i] - if char in ')]}': - # Found end of expression, push to expression stack - stack.append(char) - elif char == '>': - # Found potential end of template argument list. - # - # Ignore it if it's a "->" or ">=" or "operator>" - if (i > 0 and - (line[i - 1] == '-' or - Match(r'\s>=\s', line[i - 1:]) or - Search(r'\boperator\s*$', line[0:i]))): - i -= 1 - else: - stack.append('>') - elif char == '<': - # Found potential start of template argument list - if i > 0 and line[i - 1] == '<': - # Left shift operator - i -= 1 - else: - # If there is a matching '>', we can pop the expression stack. - # Otherwise, ignore this '<' since it must be an operator. - if stack and stack[-1] == '>': - stack.pop() - if not stack: - return (i, None) - elif char in '([{': - # Found start of expression. - # - # If there are any unmatched '>' on the stack, they must be - # operators. Remove those. - while stack and stack[-1] == '>': - stack.pop() - if not stack: - return (-1, None) - if ((char == '(' and stack[-1] == ')') or - (char == '[' and stack[-1] == ']') or - (char == '{' and stack[-1] == '}')): - stack.pop() - if not stack: - return (i, None) - else: - # Mismatched parentheses - return (-1, None) - elif char == ';': - # Found something that look like end of statements. If we are currently - # expecting a '<', the matching '>' must have been an operator, since - # template argument list should not contain statements. - while stack and stack[-1] == '>': - stack.pop() - if not stack: - return (-1, None) - - i -= 1 - - return (-1, stack) - - -def ReverseCloseExpression(clean_lines, linenum, pos): - """If input points to ) or } or ] or >, finds the position that opens it. - - If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the - linenum/pos that correspond to the opening of the expression. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - pos: A position on the line. - - Returns: - A tuple (line, linenum, pos) pointer *at* the opening brace, or - (line, 0, -1) if we never find the matching opening brace. Note - we ignore strings and comments when matching; and the line we - return is the 'cleansed' line at linenum. - """ - line = clean_lines.elided[linenum] - if line[pos] not in ')}]>': - return (line, 0, -1) - - # Check last line - (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) - if start_pos > -1: - return (line, linenum, start_pos) - - # Continue scanning backward - while stack and linenum > 0: - linenum -= 1 - line = clean_lines.elided[linenum] - (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) - if start_pos > -1: - return (line, linenum, start_pos) - - # Did not find start of expression before beginning of file, give up - return (line, 0, -1) - - -def CheckForCopyright(filename, lines, error): - """Logs an error if no Copyright message appears at the top of the file.""" - - # We'll say it should occur by line 10. Don't forget there's a - # dummy line at the front. - for line in xrange(1, min(len(lines), 11)): - if re.search(r'Copyright', lines[line], re.I): break - else: # means no copyright line was found - error(filename, 0, 'legal/copyright', 5, - 'No copyright message found. ' - 'You should have a line: "Copyright [year] "') - - -def GetIndentLevel(line): - """Return the number of leading spaces in line. - - Args: - line: A string to check. - - Returns: - An integer count of leading spaces, possibly zero. - """ - indent = Match(r'^( *)\S', line) - if indent: - return len(indent.group(1)) - else: - return 0 - -def PathSplitToList(path): - """Returns the path split into a list by the separator. - - Args: - path: An absolute or relative path (e.g. '/a/b/c/' or '../a') - - Returns: - A list of path components (e.g. ['a', 'b', 'c]). - """ - lst = [] - while True: - (head, tail) = os.path.split(path) - if head == path: # absolute paths end - lst.append(head) - break - if tail == path: # relative paths end - lst.append(tail) - break - - path = head - lst.append(tail) - - lst.reverse() - return lst - -def GetHeaderGuardCPPVariable(filename): - """Returns the CPP variable that should be used as a header guard. - - Args: - filename: The name of a C++ header file. - - Returns: - The CPP variable that should be used as a header guard in the - named file. - - """ - - # Restores original filename in case that cpplint is invoked from Emacs's - # flymake. - filename = re.sub(r'_flymake\.h$', '.h', filename) - filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) - # Replace 'c++' with 'cpp'. - filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') - - fileinfo = FileInfo(filename) - file_path_from_root = fileinfo.RepositoryName() - - def FixupPathFromRoot(): - if _root_debug: - sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n" - % (_root, fileinfo.RepositoryName())) - - # Process the file path with the --root flag if it was set. - if not _root: - if _root_debug: - sys.stderr.write("_root unspecified\n") - return file_path_from_root - - def StripListPrefix(lst, prefix): - # f(['x', 'y'], ['w, z']) -> None (not a valid prefix) - if lst[:len(prefix)] != prefix: - return None - # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd'] - return lst[(len(prefix)):] - - # root behavior: - # --root=subdir , lstrips subdir from the header guard - maybe_path = StripListPrefix(PathSplitToList(file_path_from_root), - PathSplitToList(_root)) - - if _root_debug: - sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," + - " _root=%s)\n") % (maybe_path, file_path_from_root, _root)) - - if maybe_path: - return os.path.join(*maybe_path) - - # --root=.. , will prepend the outer directory to the header guard - full_path = fileinfo.FullName() - root_abspath = os.path.abspath(_root) - - maybe_path = StripListPrefix(PathSplitToList(full_path), - PathSplitToList(root_abspath)) - - if _root_debug: - sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " + - "root_abspath=%s)\n") % (maybe_path, full_path, root_abspath)) - - if maybe_path: - return os.path.join(*maybe_path) - - if _root_debug: - sys.stderr.write("_root ignore, returning %s\n" % (file_path_from_root)) - - # --root=FAKE_DIR is ignored - return file_path_from_root - - file_path_from_root = FixupPathFromRoot() - return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' - - -def CheckForHeaderGuard(filename, clean_lines, error): - """Checks that the file contains a header guard. - - Logs an error if no #ifndef header guard is present. For other - headers, checks that the full pathname is used. - - Args: - filename: The name of the C++ header file. - clean_lines: A CleansedLines instance containing the file. - error: The function to call with any errors found. - """ - - # Don't check for header guards if there are error suppression - # comments somewhere in this file. - # - # Because this is silencing a warning for a nonexistent line, we - # only support the very specific NOLINT(build/header_guard) syntax, - # and not the general NOLINT or NOLINT(*) syntax. - raw_lines = clean_lines.lines_without_raw_strings - for i in raw_lines: - if Search(r'//\s*NOLINT\(build/header_guard\)', i): - return - - # Allow pragma once instead of header guards - for i in raw_lines: - if Search(r'^\s*#pragma\s+once', i): - return - - cppvar = GetHeaderGuardCPPVariable(filename) - - ifndef = '' - ifndef_linenum = 0 - define = '' - endif = '' - endif_linenum = 0 - for linenum, line in enumerate(raw_lines): - linesplit = line.split() - if len(linesplit) >= 2: - # find the first occurrence of #ifndef and #define, save arg - if not ifndef and linesplit[0] == '#ifndef': - # set ifndef to the header guard presented on the #ifndef line. - ifndef = linesplit[1] - ifndef_linenum = linenum - if not define and linesplit[0] == '#define': - define = linesplit[1] - # find the last occurrence of #endif, save entire line - if line.startswith('#endif'): - endif = line - endif_linenum = linenum - - if not ifndef or not define or ifndef != define: - error(filename, 0, 'build/header_guard', 5, - 'No #ifndef header guard found, suggested CPP variable is: %s' % - cppvar) - return - - # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ - # for backward compatibility. - if ifndef != cppvar: - error_level = 0 - if ifndef != cppvar + '_': - error_level = 5 - - ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, - error) - error(filename, ifndef_linenum, 'build/header_guard', error_level, - '#ifndef header guard has wrong style, please use: %s' % cppvar) - - # Check for "//" comments on endif line. - ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, - error) - match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) - if match: - if match.group(1) == '_': - # Issue low severity warning for deprecated double trailing underscore - error(filename, endif_linenum, 'build/header_guard', 0, - '#endif line should be "#endif // %s"' % cppvar) - return - - # Didn't find the corresponding "//" comment. If this file does not - # contain any "//" comments at all, it could be that the compiler - # only wants "/**/" comments, look for those instead. - no_single_line_comments = True - for i in xrange(1, len(raw_lines) - 1): - line = raw_lines[i] - if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): - no_single_line_comments = False - break - - if no_single_line_comments: - match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) - if match: - if match.group(1) == '_': - # Low severity warning for double trailing underscore - error(filename, endif_linenum, 'build/header_guard', 0, - '#endif line should be "#endif /* %s */"' % cppvar) - return - - # Didn't find anything - error(filename, endif_linenum, 'build/header_guard', 5, - '#endif line should be "#endif // %s"' % cppvar) - - -def CheckHeaderFileIncluded(filename, include_state, error): - """Logs an error if a source file does not include its header.""" - - # Do not check test files - fileinfo = FileInfo(filename) - if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()): - return - - for ext in GetHeaderExtensions(): - basefilename = filename[0:len(filename) - len(fileinfo.Extension())] - headerfile = basefilename + '.' + ext - if not os.path.exists(headerfile): - continue - headername = FileInfo(headerfile).RepositoryName() - first_include = None - for section_list in include_state.include_list: - for f in section_list: - if headername in f[0] or f[0] in headername: - return - if not first_include: - first_include = f[1] - - error(filename, first_include, 'build/include', 5, - '%s should include its header file %s' % (fileinfo.RepositoryName(), - headername)) - - -def CheckForBadCharacters(filename, lines, error): - """Logs an error for each line containing bad characters. - - Two kinds of bad characters: - - 1. Unicode replacement characters: These indicate that either the file - contained invalid UTF-8 (likely) or Unicode replacement characters (which - it shouldn't). Note that it's possible for this to throw off line - numbering if the invalid UTF-8 occurred adjacent to a newline. - - 2. NUL bytes. These are problematic for some tools. - - Args: - filename: The name of the current file. - lines: An array of strings, each representing a line of the file. - error: The function to call with any errors found. - """ - for linenum, line in enumerate(lines): - if unicode_escape_decode('\ufffd') in line: - error(filename, linenum, 'readability/utf8', 5, - 'Line contains invalid UTF-8 (or Unicode replacement character).') - if '\0' in line: - error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') - - -def CheckInlineHeader(filename, include_state, error): - """Logs an error if both a header and its inline variant are included.""" - - all_headers = dict(item for sublist in include_state.include_list - for item in sublist) - bad_headers = set('%s.h' % name[:-6] for name in all_headers.keys() - if name.endswith('-inl.h')) - bad_headers &= set(all_headers.keys()) - - for name in bad_headers: - err = '%s includes both %s and %s-inl.h' % (filename, name, name) - linenum = all_headers[name] - error(filename, linenum, 'build/include_inline', 5, err) - - -def CheckForNewlineAtEOF(filename, lines, error): - """Logs an error if there is no newline char at the end of the file. - - Args: - filename: The name of the current file. - lines: An array of strings, each representing a line of the file. - error: The function to call with any errors found. - """ - - # The array lines() was created by adding two newlines to the - # original file (go figure), then splitting on \n. - # To verify that the file ends in \n, we just have to make sure the - # last-but-two element of lines() exists and is empty. - if len(lines) < 3 or lines[-2]: - error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, - 'Could not find a newline character at the end of the file.') - - -def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): - """Logs an error if we see /* ... */ or "..." that extend past one line. - - /* ... */ comments are legit inside macros, for one line. - Otherwise, we prefer // comments, so it's ok to warn about the - other. Likewise, it's ok for strings to extend across multiple - lines, as long as a line continuation character (backslash) - terminates each line. Although not currently prohibited by the C++ - style guide, it's ugly and unnecessary. We don't do well with either - in this lint program, so we warn about both. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Remove all \\ (escaped backslashes) from the line. They are OK, and the - # second (escaped) slash may trigger later \" detection erroneously. - line = line.replace('\\\\', '') - - if line.count('/*') > line.count('*/'): - error(filename, linenum, 'readability/multiline_comment', 5, - 'Complex multi-line /*...*/-style comment found. ' - 'Lint may give bogus warnings. ' - 'Consider replacing these with //-style comments, ' - 'with #if 0...#endif, ' - 'or with more clearly structured multi-line comments.') - - if (line.count('"') - line.count('\\"')) % 2: - error(filename, linenum, 'readability/multiline_string', 5, - 'Multi-line string ("...") found. This lint script doesn\'t ' - 'do well with such strings, and may give bogus warnings. ' - 'Use C++11 raw strings or concatenation instead.') - - -# (non-threadsafe name, thread-safe alternative, validation pattern) -# -# The validation pattern is used to eliminate false positives such as: -# _rand(); // false positive due to substring match. -# ->rand(); // some member function rand(). -# ACMRandom rand(seed); // some variable named rand. -# ISAACRandom rand(); // another variable named rand. -# -# Basically we require the return value of these functions to be used -# in some expression context on the same line by matching on some -# operator before the function name. This eliminates constructors and -# member function calls. -_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' -_THREADING_LIST = ( - ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), - ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), - ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), - ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), - ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), - ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), - ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), - ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), - ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), - ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), - ('strtok(', 'strtok_r(', - _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), - ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), - ) - - -def CheckPosixThreading(filename, clean_lines, linenum, error): - """Checks for calls to thread-unsafe functions. - - Much code has been originally written without consideration of - multi-threading. Also, engineers are relying on their old experience; - they have learned posix before threading extensions were added. These - tests guide the engineers to use thread-safe functions (when using - posix directly). - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: - # Additional pattern matching check to confirm that this is the - # function we are looking for - if Search(pattern, line): - error(filename, linenum, 'runtime/threadsafe_fn', 2, - 'Consider using ' + multithread_safe_func + - '...) instead of ' + single_thread_func + - '...) for improved thread safety.') - - -def CheckVlogArguments(filename, clean_lines, linenum, error): - """Checks that VLOG() is only used for defining a logging level. - - For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and - VLOG(FATAL) are not. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): - error(filename, linenum, 'runtime/vlog', 5, - 'VLOG() should be used with numeric verbosity level. ' - 'Use LOG() if you want symbolic severity levels.') - -# Matches invalid increment: *count++, which moves pointer instead of -# incrementing a value. -_RE_PATTERN_INVALID_INCREMENT = re.compile( - r'^\s*\*\w+(\+\+|--);') - - -def CheckInvalidIncrement(filename, clean_lines, linenum, error): - """Checks for invalid increment *count++. - - For example following function: - void increment_counter(int* count) { - *count++; - } - is invalid, because it effectively does count++, moving pointer, and should - be replaced with ++*count, (*count)++ or *count += 1. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - if _RE_PATTERN_INVALID_INCREMENT.match(line): - error(filename, linenum, 'runtime/invalid_increment', 5, - 'Changing pointer instead of value (or unused value of operator*).') - - -def IsMacroDefinition(clean_lines, linenum): - if Search(r'^#define', clean_lines[linenum]): - return True - - if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): - return True - - return False - - -def IsForwardClassDeclaration(clean_lines, linenum): - return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) - - -class _BlockInfo(object): - """Stores information about a generic block of code.""" - - def __init__(self, linenum, seen_open_brace): - self.starting_linenum = linenum - self.seen_open_brace = seen_open_brace - self.open_parentheses = 0 - self.inline_asm = _NO_ASM - self.check_namespace_indentation = False - - def CheckBegin(self, filename, clean_lines, linenum, error): - """Run checks that applies to text up to the opening brace. - - This is mostly for checking the text after the class identifier - and the "{", usually where the base class is specified. For other - blocks, there isn't much to check, so we always pass. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - pass - - def CheckEnd(self, filename, clean_lines, linenum, error): - """Run checks that applies to text after the closing brace. - - This is mostly used for checking end of namespace comments. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - pass - - def IsBlockInfo(self): - """Returns true if this block is a _BlockInfo. - - This is convenient for verifying that an object is an instance of - a _BlockInfo, but not an instance of any of the derived classes. - - Returns: - True for this class, False for derived classes. - """ - return self.__class__ == _BlockInfo - - -class _ExternCInfo(_BlockInfo): - """Stores information about an 'extern "C"' block.""" - - def __init__(self, linenum): - _BlockInfo.__init__(self, linenum, True) - - -class _ClassInfo(_BlockInfo): - """Stores information about a class.""" - - def __init__(self, name, class_or_struct, clean_lines, linenum): - _BlockInfo.__init__(self, linenum, False) - self.name = name - self.is_derived = False - self.check_namespace_indentation = True - if class_or_struct == 'struct': - self.access = 'public' - self.is_struct = True - else: - self.access = 'private' - self.is_struct = False - - # Remember initial indentation level for this class. Using raw_lines here - # instead of elided to account for leading comments. - self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) - - # Try to find the end of the class. This will be confused by things like: - # class A { - # } *x = { ... - # - # But it's still good enough for CheckSectionSpacing. - self.last_line = 0 - depth = 0 - for i in range(linenum, clean_lines.NumLines()): - line = clean_lines.elided[i] - depth += line.count('{') - line.count('}') - if not depth: - self.last_line = i - break - - def CheckBegin(self, filename, clean_lines, linenum, error): - # Look for a bare ':' - if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): - self.is_derived = True - - def CheckEnd(self, filename, clean_lines, linenum, error): - # If there is a DISALLOW macro, it should appear near the end of - # the class. - seen_last_thing_in_class = False - for i in xrange(linenum - 1, self.starting_linenum, -1): - match = Search( - r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + - self.name + r'\)', - clean_lines.elided[i]) - if match: - if seen_last_thing_in_class: - error(filename, i, 'readability/constructors', 3, - match.group(1) + ' should be the last thing in the class') - break - - if not Match(r'^\s*$', clean_lines.elided[i]): - seen_last_thing_in_class = True - - # Check that closing brace is aligned with beginning of the class. - # Only do this if the closing brace is indented by only whitespaces. - # This means we will not check single-line class definitions. - indent = Match(r'^( *)\}', clean_lines.elided[linenum]) - if indent and len(indent.group(1)) != self.class_indent: - if self.is_struct: - parent = 'struct ' + self.name - else: - parent = 'class ' + self.name - error(filename, linenum, 'whitespace/indent', 3, - 'Closing brace should be aligned with beginning of %s' % parent) - - -class _NamespaceInfo(_BlockInfo): - """Stores information about a namespace.""" - - def __init__(self, name, linenum): - _BlockInfo.__init__(self, linenum, False) - self.name = name or '' - self.check_namespace_indentation = True - - def CheckEnd(self, filename, clean_lines, linenum, error): - """Check end of namespace comments.""" - line = clean_lines.raw_lines[linenum] - - # Check how many lines is enclosed in this namespace. Don't issue - # warning for missing namespace comments if there aren't enough - # lines. However, do apply checks if there is already an end of - # namespace comment and it's incorrect. - # - # TODO(unknown): We always want to check end of namespace comments - # if a namespace is large, but sometimes we also want to apply the - # check if a short namespace contained nontrivial things (something - # other than forward declarations). There is currently no logic on - # deciding what these nontrivial things are, so this check is - # triggered by namespace size only, which works most of the time. - if (linenum - self.starting_linenum < 10 - and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): - return - - # Look for matching comment at end of namespace. - # - # Note that we accept C style "/* */" comments for terminating - # namespaces, so that code that terminate namespaces inside - # preprocessor macros can be cpplint clean. - # - # We also accept stuff like "// end of namespace ." with the - # period at the end. - # - # Besides these, we don't accept anything else, otherwise we might - # get false negatives when existing comment is a substring of the - # expected namespace. - if self.name: - # Named namespace - if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + - re.escape(self.name) + r'[\*/\.\\\s]*$'), - line): - error(filename, linenum, 'readability/namespace', 5, - 'Namespace should be terminated with "// namespace %s"' % - self.name) - else: - # Anonymous namespace - if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): - # If "// namespace anonymous" or "// anonymous namespace (more text)", - # mention "// anonymous namespace" as an acceptable form - if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): - error(filename, linenum, 'readability/namespace', 5, - 'Anonymous namespace should be terminated with "// namespace"' - ' or "// anonymous namespace"') - else: - error(filename, linenum, 'readability/namespace', 5, - 'Anonymous namespace should be terminated with "// namespace"') - - -class _PreprocessorInfo(object): - """Stores checkpoints of nesting stacks when #if/#else is seen.""" - - def __init__(self, stack_before_if): - # The entire nesting stack before #if - self.stack_before_if = stack_before_if - - # The entire nesting stack up to #else - self.stack_before_else = [] - - # Whether we have already seen #else or #elif - self.seen_else = False - - -class NestingState(object): - """Holds states related to parsing braces.""" - - def __init__(self): - # Stack for tracking all braces. An object is pushed whenever we - # see a "{", and popped when we see a "}". Only 3 types of - # objects are possible: - # - _ClassInfo: a class or struct. - # - _NamespaceInfo: a namespace. - # - _BlockInfo: some other type of block. - self.stack = [] - - # Top of the previous stack before each Update(). - # - # Because the nesting_stack is updated at the end of each line, we - # had to do some convoluted checks to find out what is the current - # scope at the beginning of the line. This check is simplified by - # saving the previous top of nesting stack. - # - # We could save the full stack, but we only need the top. Copying - # the full nesting stack would slow down cpplint by ~10%. - self.previous_stack_top = [] - - # Stack of _PreprocessorInfo objects. - self.pp_stack = [] - - def SeenOpenBrace(self): - """Check if we have seen the opening brace for the innermost block. - - Returns: - True if we have seen the opening brace, False if the innermost - block is still expecting an opening brace. - """ - return (not self.stack) or self.stack[-1].seen_open_brace - - def InNamespaceBody(self): - """Check if we are currently one level inside a namespace body. - - Returns: - True if top of the stack is a namespace block, False otherwise. - """ - return self.stack and isinstance(self.stack[-1], _NamespaceInfo) - - def InExternC(self): - """Check if we are currently one level inside an 'extern "C"' block. - - Returns: - True if top of the stack is an extern block, False otherwise. - """ - return self.stack and isinstance(self.stack[-1], _ExternCInfo) - - def InClassDeclaration(self): - """Check if we are currently one level inside a class or struct declaration. - - Returns: - True if top of the stack is a class/struct, False otherwise. - """ - return self.stack and isinstance(self.stack[-1], _ClassInfo) - - def InAsmBlock(self): - """Check if we are currently one level inside an inline ASM block. - - Returns: - True if the top of the stack is a block containing inline ASM. - """ - return self.stack and self.stack[-1].inline_asm != _NO_ASM - - def InTemplateArgumentList(self, clean_lines, linenum, pos): - """Check if current position is inside template argument list. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - pos: position just after the suspected template argument. - Returns: - True if (linenum, pos) is inside template arguments. - """ - while linenum < clean_lines.NumLines(): - # Find the earliest character that might indicate a template argument - line = clean_lines.elided[linenum] - match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) - if not match: - linenum += 1 - pos = 0 - continue - token = match.group(1) - pos += len(match.group(0)) - - # These things do not look like template argument list: - # class Suspect { - # class Suspect x; } - if token in ('{', '}', ';'): return False - - # These things look like template argument list: - # template - # template - # template - # template - if token in ('>', '=', '[', ']', '.'): return True - - # Check if token is an unmatched '<'. - # If not, move on to the next character. - if token != '<': - pos += 1 - if pos >= len(line): - linenum += 1 - pos = 0 - continue - - # We can't be sure if we just find a single '<', and need to - # find the matching '>'. - (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) - if end_pos < 0: - # Not sure if template argument list or syntax error in file - return False - linenum = end_line - pos = end_pos - return False - - def UpdatePreprocessor(self, line): - """Update preprocessor stack. - - We need to handle preprocessors due to classes like this: - #ifdef SWIG - struct ResultDetailsPageElementExtensionPoint { - #else - struct ResultDetailsPageElementExtensionPoint : public Extension { - #endif - - We make the following assumptions (good enough for most files): - - Preprocessor condition evaluates to true from #if up to first - #else/#elif/#endif. - - - Preprocessor condition evaluates to false from #else/#elif up - to #endif. We still perform lint checks on these lines, but - these do not affect nesting stack. - - Args: - line: current line to check. - """ - if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): - # Beginning of #if block, save the nesting stack here. The saved - # stack will allow us to restore the parsing state in the #else case. - self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) - elif Match(r'^\s*#\s*(else|elif)\b', line): - # Beginning of #else block - if self.pp_stack: - if not self.pp_stack[-1].seen_else: - # This is the first #else or #elif block. Remember the - # whole nesting stack up to this point. This is what we - # keep after the #endif. - self.pp_stack[-1].seen_else = True - self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) - - # Restore the stack to how it was before the #if - self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) - else: - # TODO(unknown): unexpected #else, issue warning? - pass - elif Match(r'^\s*#\s*endif\b', line): - # End of #if or #else blocks. - if self.pp_stack: - # If we saw an #else, we will need to restore the nesting - # stack to its former state before the #else, otherwise we - # will just continue from where we left off. - if self.pp_stack[-1].seen_else: - # Here we can just use a shallow copy since we are the last - # reference to it. - self.stack = self.pp_stack[-1].stack_before_else - # Drop the corresponding #if - self.pp_stack.pop() - else: - # TODO(unknown): unexpected #endif, issue warning? - pass - - # TODO(unknown): Update() is too long, but we will refactor later. - def Update(self, filename, clean_lines, linenum, error): - """Update nesting state with current line. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Remember top of the previous nesting stack. - # - # The stack is always pushed/popped and not modified in place, so - # we can just do a shallow copy instead of copy.deepcopy. Using - # deepcopy would slow down cpplint by ~28%. - if self.stack: - self.previous_stack_top = self.stack[-1] - else: - self.previous_stack_top = None - - # Update pp_stack - self.UpdatePreprocessor(line) - - # Count parentheses. This is to avoid adding struct arguments to - # the nesting stack. - if self.stack: - inner_block = self.stack[-1] - depth_change = line.count('(') - line.count(')') - inner_block.open_parentheses += depth_change - - # Also check if we are starting or ending an inline assembly block. - if inner_block.inline_asm in (_NO_ASM, _END_ASM): - if (depth_change != 0 and - inner_block.open_parentheses == 1 and - _MATCH_ASM.match(line)): - # Enter assembly block - inner_block.inline_asm = _INSIDE_ASM - else: - # Not entering assembly block. If previous line was _END_ASM, - # we will now shift to _NO_ASM state. - inner_block.inline_asm = _NO_ASM - elif (inner_block.inline_asm == _INSIDE_ASM and - inner_block.open_parentheses == 0): - # Exit assembly block - inner_block.inline_asm = _END_ASM - - # Consume namespace declaration at the beginning of the line. Do - # this in a loop so that we catch same line declarations like this: - # namespace proto2 { namespace bridge { class MessageSet; } } - while True: - # Match start of namespace. The "\b\s*" below catches namespace - # declarations even if it weren't followed by a whitespace, this - # is so that we don't confuse our namespace checker. The - # missing spaces will be flagged by CheckSpacing. - namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) - if not namespace_decl_match: - break - - new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) - self.stack.append(new_namespace) - - line = namespace_decl_match.group(2) - if line.find('{') != -1: - new_namespace.seen_open_brace = True - line = line[line.find('{') + 1:] - - # Look for a class declaration in whatever is left of the line - # after parsing namespaces. The regexp accounts for decorated classes - # such as in: - # class LOCKABLE API Object { - # }; - class_decl_match = Match( - r'^(\s*(?:template\s*<[\w\s<>,:=]*>\s*)?' - r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' - r'(.*)$', line) - if (class_decl_match and - (not self.stack or self.stack[-1].open_parentheses == 0)): - # We do not want to accept classes that are actually template arguments: - # template , - # template class Ignore3> - # void Function() {}; - # - # To avoid template argument cases, we scan forward and look for - # an unmatched '>'. If we see one, assume we are inside a - # template argument list. - end_declaration = len(class_decl_match.group(1)) - if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): - self.stack.append(_ClassInfo( - class_decl_match.group(3), class_decl_match.group(2), - clean_lines, linenum)) - line = class_decl_match.group(4) - - # If we have not yet seen the opening brace for the innermost block, - # run checks here. - if not self.SeenOpenBrace(): - self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) - - # Update access control if we are inside a class/struct - if self.stack and isinstance(self.stack[-1], _ClassInfo): - classinfo = self.stack[-1] - access_match = Match( - r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' - r':(?:[^:]|$)', - line) - if access_match: - classinfo.access = access_match.group(2) - - # Check that access keywords are indented +1 space. Skip this - # check if the keywords are not preceded by whitespaces. - indent = access_match.group(1) - if (len(indent) != classinfo.class_indent + 1 and - Match(r'^\s*$', indent)): - if classinfo.is_struct: - parent = 'struct ' + classinfo.name - else: - parent = 'class ' + classinfo.name - slots = '' - if access_match.group(3): - slots = access_match.group(3) - error(filename, linenum, 'whitespace/indent', 3, - '%s%s: should be indented +1 space inside %s' % ( - access_match.group(2), slots, parent)) - - # Consume braces or semicolons from what's left of the line - while True: - # Match first brace, semicolon, or closed parenthesis. - matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) - if not matched: - break - - token = matched.group(1) - if token == '{': - # If namespace or class hasn't seen a opening brace yet, mark - # namespace/class head as complete. Push a new block onto the - # stack otherwise. - if not self.SeenOpenBrace(): - self.stack[-1].seen_open_brace = True - elif Match(r'^extern\s*"[^"]*"\s*\{', line): - self.stack.append(_ExternCInfo(linenum)) - else: - self.stack.append(_BlockInfo(linenum, True)) - if _MATCH_ASM.match(line): - self.stack[-1].inline_asm = _BLOCK_ASM - - elif token == ';' or token == ')': - # If we haven't seen an opening brace yet, but we already saw - # a semicolon, this is probably a forward declaration. Pop - # the stack for these. - # - # Similarly, if we haven't seen an opening brace yet, but we - # already saw a closing parenthesis, then these are probably - # function arguments with extra "class" or "struct" keywords. - # Also pop these stack for these. - if not self.SeenOpenBrace(): - self.stack.pop() - else: # token == '}' - # Perform end of block checks and pop the stack. - if self.stack: - self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) - self.stack.pop() - line = matched.group(2) - - def InnermostClass(self): - """Get class info on the top of the stack. - - Returns: - A _ClassInfo object if we are inside a class, or None otherwise. - """ - for i in range(len(self.stack), 0, -1): - classinfo = self.stack[i - 1] - if isinstance(classinfo, _ClassInfo): - return classinfo - return None - - def CheckCompletedBlocks(self, filename, error): - """Checks that all classes and namespaces have been completely parsed. - - Call this when all lines in a file have been processed. - Args: - filename: The name of the current file. - error: The function to call with any errors found. - """ - # Note: This test can result in false positives if #ifdef constructs - # get in the way of brace matching. See the testBuildClass test in - # cpplint_unittest.py for an example of this. - for obj in self.stack: - if isinstance(obj, _ClassInfo): - error(filename, obj.starting_linenum, 'build/class', 5, - 'Failed to find complete declaration of class %s' % - obj.name) - elif isinstance(obj, _NamespaceInfo): - error(filename, obj.starting_linenum, 'build/namespaces', 5, - 'Failed to find complete declaration of namespace %s' % - obj.name) - - -def CheckForNonStandardConstructs(filename, clean_lines, linenum, - nesting_state, error): - r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. - - Complain about several constructs which gcc-2 accepts, but which are - not standard C++. Warning about these in lint is one way to ease the - transition to new compilers. - - put storage class first (e.g. "static const" instead of "const static"). - - "%lld" instead of %qd" in printf-type functions. - - "%1$d" is non-standard in printf-type functions. - - "\%" is an undefined character escape sequence. - - text after #endif is not allowed. - - invalid inner-style forward declaration. - - >? and ?= and )\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', - line): - error(filename, linenum, 'build/deprecated', 3, - '>? and ))?' - # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' - error(filename, linenum, 'runtime/member_string_references', 2, - 'const string& members are dangerous. It is much better to use ' - 'alternatives, such as pointers or simple constants.') - - # Everything else in this function operates on class declarations. - # Return early if the top of the nesting stack is not a class, or if - # the class head is not completed yet. - classinfo = nesting_state.InnermostClass() - if not classinfo or not classinfo.seen_open_brace: - return - - # The class may have been declared with namespace or classname qualifiers. - # The constructor and destructor will not have those qualifiers. - base_classname = classinfo.name.split('::')[-1] - - # Look for single-argument constructors that aren't marked explicit. - # Technically a valid construct, but against style. - explicit_constructor_match = Match( - r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?' - r'(?:(?:inline|constexpr)\s+)*%s\s*' - r'\(((?:[^()]|\([^()]*\))*)\)' - % re.escape(base_classname), - line) - - if explicit_constructor_match: - is_marked_explicit = explicit_constructor_match.group(1) - - if not explicit_constructor_match.group(2): - constructor_args = [] - else: - constructor_args = explicit_constructor_match.group(2).split(',') - - # collapse arguments so that commas in template parameter lists and function - # argument parameter lists don't split arguments in two - i = 0 - while i < len(constructor_args): - constructor_arg = constructor_args[i] - while (constructor_arg.count('<') > constructor_arg.count('>') or - constructor_arg.count('(') > constructor_arg.count(')')): - constructor_arg += ',' + constructor_args[i + 1] - del constructor_args[i + 1] - constructor_args[i] = constructor_arg - i += 1 - - variadic_args = [arg for arg in constructor_args if '&&...' in arg] - defaulted_args = [arg for arg in constructor_args if '=' in arg] - noarg_constructor = (not constructor_args or # empty arg list - # 'void' arg specifier - (len(constructor_args) == 1 and - constructor_args[0].strip() == 'void')) - onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg - not noarg_constructor) or - # all but at most one arg defaulted - (len(constructor_args) >= 1 and - not noarg_constructor and - len(defaulted_args) >= len(constructor_args) - 1) or - # variadic arguments with zero or one argument - (len(constructor_args) <= 2 and - len(variadic_args) >= 1)) - initializer_list_constructor = bool( - onearg_constructor and - Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) - copy_constructor = bool( - onearg_constructor and - Match(r'((const\s+(volatile\s+)?)?|(volatile\s+(const\s+)?))?' - r'%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' - % re.escape(base_classname), constructor_args[0].strip())) - - if (not is_marked_explicit and - onearg_constructor and - not initializer_list_constructor and - not copy_constructor): - if defaulted_args or variadic_args: - error(filename, linenum, 'runtime/explicit', 5, - 'Constructors callable with one argument ' - 'should be marked explicit.') - else: - error(filename, linenum, 'runtime/explicit', 5, - 'Single-parameter constructors should be marked explicit.') - elif is_marked_explicit and not onearg_constructor: - if noarg_constructor: - error(filename, linenum, 'runtime/explicit', 5, - 'Zero-parameter constructors should not be marked explicit.') - - -def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): - """Checks for the correctness of various spacing around function calls. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Since function calls often occur inside if/for/while/switch - # expressions - which have their own, more liberal conventions - we - # first see if we should be looking inside such an expression for a - # function call, to which we can apply more strict standards. - fncall = line # if there's no control flow construct, look at whole line - for pattern in (r'\bif\s*\((.*)\)\s*{', - r'\bfor\s*\((.*)\)\s*{', - r'\bwhile\s*\((.*)\)\s*[{;]', - r'\bswitch\s*\((.*)\)\s*{'): - match = Search(pattern, line) - if match: - fncall = match.group(1) # look inside the parens for function calls - break - - # Except in if/for/while/switch, there should never be space - # immediately inside parens (eg "f( 3, 4 )"). We make an exception - # for nested parens ( (a+b) + c ). Likewise, there should never be - # a space before a ( when it's a function argument. I assume it's a - # function argument when the char before the whitespace is legal in - # a function name (alnum + _) and we're not starting a macro. Also ignore - # pointers and references to arrays and functions coz they're too tricky: - # we use a very simple way to recognize these: - # " (something)(maybe-something)" or - # " (something)(maybe-something," or - # " (something)[something]" - # Note that we assume the contents of [] to be short enough that - # they'll never need to wrap. - if ( # Ignore control structures. - not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', - fncall) and - # Ignore pointers/references to functions. - not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and - # Ignore pointers/references to arrays. - not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): - if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call - error(filename, linenum, 'whitespace/parens', 4, - 'Extra space after ( in function call') - elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): - error(filename, linenum, 'whitespace/parens', 2, - 'Extra space after (') - if (Search(r'\w\s+\(', fncall) and - not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and - not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and - not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and - not Search(r'\bcase\s+\(', fncall)): - # TODO(unknown): Space after an operator function seem to be a common - # error, silence those for now by restricting them to highest verbosity. - if Search(r'\boperator_*\b', line): - error(filename, linenum, 'whitespace/parens', 0, - 'Extra space before ( in function call') - else: - error(filename, linenum, 'whitespace/parens', 4, - 'Extra space before ( in function call') - # If the ) is followed only by a newline or a { + newline, assume it's - # part of a control statement (if/while/etc), and don't complain - if Search(r'[^)]\s+\)\s*[^{\s]', fncall): - # If the closing parenthesis is preceded by only whitespaces, - # try to give a more descriptive error message. - if Search(r'^\s+\)', fncall): - error(filename, linenum, 'whitespace/parens', 2, - 'Closing ) should be moved to the previous line') - else: - error(filename, linenum, 'whitespace/parens', 2, - 'Extra space before )') - - -def IsBlankLine(line): - """Returns true if the given line is blank. - - We consider a line to be blank if the line is empty or consists of - only white spaces. - - Args: - line: A line of a string. - - Returns: - True, if the given line is blank. - """ - return not line or line.isspace() - - -def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, - error): - is_namespace_indent_item = ( - len(nesting_state.stack) > 1 and - nesting_state.stack[-1].check_namespace_indentation and - isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and - nesting_state.previous_stack_top == nesting_state.stack[-2]) - - if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, - clean_lines.elided, line): - CheckItemIndentationInNamespace(filename, clean_lines.elided, - line, error) - - -def CheckForFunctionLengths(filename, clean_lines, linenum, - function_state, error): - """Reports for long function bodies. - - For an overview why this is done, see: - https://google.github.io/styleguide/cppguide.html#Write_Short_Functions - - Uses a simplistic algorithm assuming other style guidelines - (especially spacing) are followed. - Only checks unindented functions, so class members are unchecked. - Trivial bodies are unchecked, so constructors with huge initializer lists - may be missed. - Blank/comment lines are not counted so as to avoid encouraging the removal - of vertical space and comments just to get through a lint check. - NOLINT *on the last line of a function* disables this check. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - function_state: Current function name and lines in body so far. - error: The function to call with any errors found. - """ - lines = clean_lines.lines - line = lines[linenum] - joined_line = '' - - starting_func = False - regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... - match_result = Match(regexp, line) - if match_result: - # If the name is all caps and underscores, figure it's a macro and - # ignore it, unless it's TEST or TEST_F. - function_name = match_result.group(1).split()[-1] - if function_name == 'TEST' or function_name == 'TEST_F' or ( - not Match(r'[A-Z_]+$', function_name)): - starting_func = True - - if starting_func: - body_found = False - for start_linenum in xrange(linenum, clean_lines.NumLines()): - start_line = lines[start_linenum] - joined_line += ' ' + start_line.lstrip() - if Search(r'(;|})', start_line): # Declarations and trivial functions - body_found = True - break # ... ignore - if Search(r'{', start_line): - body_found = True - function = Search(r'((\w|:)*)\(', line).group(1) - if Match(r'TEST', function): # Handle TEST... macros - parameter_regexp = Search(r'(\(.*\))', joined_line) - if parameter_regexp: # Ignore bad syntax - function += parameter_regexp.group(1) - else: - function += '()' - function_state.Begin(function) - break - if not body_found: - # No body for the function (or evidence of a non-function) was found. - error(filename, linenum, 'readability/fn_size', 5, - 'Lint failed to find start of function body.') - elif Match(r'^\}\s*$', line): # function end - function_state.Check(error, filename, linenum) - function_state.End() - elif not Match(r'^\s*$', line): - function_state.Count() # Count non-blank/non-comment lines. - - -_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') - - -def CheckComment(line, filename, linenum, next_line_start, error): - """Checks for common mistakes in comments. - - Args: - line: The line in question. - filename: The name of the current file. - linenum: The number of the line to check. - next_line_start: The first non-whitespace column of the next line. - error: The function to call with any errors found. - """ - commentpos = line.find('//') - if commentpos != -1: - # Check if the // may be in quotes. If so, ignore it - if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: - # Allow one space for new scopes, two spaces otherwise: - if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and - ((commentpos >= 1 and - line[commentpos-1] not in string.whitespace) or - (commentpos >= 2 and - line[commentpos-2] not in string.whitespace))): - error(filename, linenum, 'whitespace/comments', 2, - 'At least two spaces is best between code and comments') - - # Checks for common mistakes in TODO comments. - comment = line[commentpos:] - match = _RE_PATTERN_TODO.match(comment) - if match: - # One whitespace is correct; zero whitespace is handled elsewhere. - leading_whitespace = match.group(1) - if len(leading_whitespace) > 1: - error(filename, linenum, 'whitespace/todo', 2, - 'Too many spaces before TODO') - - username = match.group(2) - if not username: - error(filename, linenum, 'readability/todo', 2, - 'Missing username in TODO; it should look like ' - '"// TODO(my_username): Stuff."') - - middle_whitespace = match.group(3) - # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison - if middle_whitespace != ' ' and middle_whitespace != '': - error(filename, linenum, 'whitespace/todo', 2, - 'TODO(my_username) should be followed by a space') - - # If the comment contains an alphanumeric character, there - # should be a space somewhere between it and the // unless - # it's a /// or //! Doxygen comment. - if (Match(r'//[^ ]*\w', comment) and - not Match(r'(///|//\!)(\s+|$)', comment)): - error(filename, linenum, 'whitespace/comments', 4, - 'Should have a space between // and comment') - - -def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): - """Checks for the correctness of various spacing issues in the code. - - Things we check for: spaces around operators, spaces after - if/for/while/switch, no spaces around parens in function calls, two - spaces between code and comment, don't start a block with a blank - line, don't end a function with a blank line, don't add a blank line - after public/protected/private, don't have too many blank lines in a row. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - error: The function to call with any errors found. - """ - - # Don't use "elided" lines here, otherwise we can't check commented lines. - # Don't want to use "raw" either, because we don't want to check inside C++11 - # raw strings, - raw = clean_lines.lines_without_raw_strings - line = raw[linenum] - - # Before nixing comments, check if the line is blank for no good - # reason. This includes the first line after a block is opened, and - # blank lines at the end of a function (ie, right before a line like '}' - # - # Skip all the blank line checks if we are immediately inside a - # namespace body. In other words, don't issue blank line warnings - # for this block: - # namespace { - # - # } - # - # A warning about missing end of namespace comments will be issued instead. - # - # Also skip blank line checks for 'extern "C"' blocks, which are formatted - # like namespaces. - if (IsBlankLine(line) and - not nesting_state.InNamespaceBody() and - not nesting_state.InExternC()): - elided = clean_lines.elided - prev_line = elided[linenum - 1] - prevbrace = prev_line.rfind('{') - # TODO(unknown): Don't complain if line before blank line, and line after, - # both start with alnums and are indented the same amount. - # This ignores whitespace at the start of a namespace block - # because those are not usually indented. - if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: - # OK, we have a blank line at the start of a code block. Before we - # complain, we check if it is an exception to the rule: The previous - # non-empty line has the parameters of a function header that are indented - # 4 spaces (because they did not fit in a 80 column line when placed on - # the same line as the function name). We also check for the case where - # the previous line is indented 6 spaces, which may happen when the - # initializers of a constructor do not fit into a 80 column line. - exception = False - if Match(r' {6}\w', prev_line): # Initializer list? - # We are looking for the opening column of initializer list, which - # should be indented 4 spaces to cause 6 space indentation afterwards. - search_position = linenum-2 - while (search_position >= 0 - and Match(r' {6}\w', elided[search_position])): - search_position -= 1 - exception = (search_position >= 0 - and elided[search_position][:5] == ' :') - else: - # Search for the function arguments or an initializer list. We use a - # simple heuristic here: If the line is indented 4 spaces; and we have a - # closing paren, without the opening paren, followed by an opening brace - # or colon (for initializer lists) we assume that it is the last line of - # a function header. If we have a colon indented 4 spaces, it is an - # initializer list. - exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', - prev_line) - or Match(r' {4}:', prev_line)) - - if not exception: - error(filename, linenum, 'whitespace/blank_line', 2, - 'Redundant blank line at the start of a code block ' - 'should be deleted.') - # Ignore blank lines at the end of a block in a long if-else - # chain, like this: - # if (condition1) { - # // Something followed by a blank line - # - # } else if (condition2) { - # // Something else - # } - if linenum + 1 < clean_lines.NumLines(): - next_line = raw[linenum + 1] - if (next_line - and Match(r'\s*}', next_line) - and next_line.find('} else ') == -1): - error(filename, linenum, 'whitespace/blank_line', 3, - 'Redundant blank line at the end of a code block ' - 'should be deleted.') - - matched = Match(r'\s*(public|protected|private):', prev_line) - if matched: - error(filename, linenum, 'whitespace/blank_line', 3, - 'Do not leave a blank line after "%s:"' % matched.group(1)) - - # Next, check comments - next_line_start = 0 - if linenum + 1 < clean_lines.NumLines(): - next_line = raw[linenum + 1] - next_line_start = len(next_line) - len(next_line.lstrip()) - CheckComment(line, filename, linenum, next_line_start, error) - - # get rid of comments and strings - line = clean_lines.elided[linenum] - - # You shouldn't have spaces before your brackets, except maybe after - # 'delete []', 'return []() {};', or 'auto [abc, ...] = ...;'. - if Search(r'\w\s+\[', line) and not Search(r'(?:auto&?|delete|return)\s+\[', line): - error(filename, linenum, 'whitespace/braces', 5, - 'Extra space before [') - - # In range-based for, we wanted spaces before and after the colon, but - # not around "::" tokens that might appear. - if (Search(r'for *\(.*[^:]:[^: ]', line) or - Search(r'for *\(.*[^: ]:[^:]', line)): - error(filename, linenum, 'whitespace/forcolon', 2, - 'Missing space around colon in range-based for loop') - - -def CheckOperatorSpacing(filename, clean_lines, linenum, error): - """Checks for horizontal spacing around operators. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Don't try to do spacing checks for operator methods. Do this by - # replacing the troublesome characters with something else, - # preserving column position for all other characters. - # - # The replacement is done repeatedly to avoid false positives from - # operators that call operators. - while True: - match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) - if match: - line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) - else: - break - - # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". - # Otherwise not. Note we only check for non-spaces on *both* sides; - # sometimes people put non-spaces on one side when aligning ='s among - # many lines (not that this is behavior that I approve of...) - if ((Search(r'[\w.]=', line) or - Search(r'=[\w.]', line)) - and not Search(r'\b(if|while|for) ', line) - # Operators taken from [lex.operators] in C++11 standard. - and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) - and not Search(r'operator=', line)): - error(filename, linenum, 'whitespace/operators', 4, - 'Missing spaces around =') - - # It's ok not to have spaces around binary operators like + - * /, but if - # there's too little whitespace, we get concerned. It's hard to tell, - # though, so we punt on this one for now. TODO. - - # You should always have whitespace around binary operators. - # - # Check <= and >= first to avoid false positives with < and >, then - # check non-include lines for spacing around < and >. - # - # If the operator is followed by a comma, assume it's be used in a - # macro context and don't do any checks. This avoids false - # positives. - # - # Note that && is not included here. This is because there are too - # many false positives due to RValue references. - match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) - if match: - error(filename, linenum, 'whitespace/operators', 3, - 'Missing spaces around %s' % match.group(1)) - elif not Match(r'#.*include', line): - # Look for < that is not surrounded by spaces. This is only - # triggered if both sides are missing spaces, even though - # technically should should flag if at least one side is missing a - # space. This is done to avoid some false positives with shifts. - match = Match(r'^(.*[^\s<])<[^\s=<,]', line) - if match: - (_, _, end_pos) = CloseExpression( - clean_lines, linenum, len(match.group(1))) - if end_pos <= -1: - error(filename, linenum, 'whitespace/operators', 3, - 'Missing spaces around <') - - # Look for > that is not surrounded by spaces. Similar to the - # above, we only trigger if both sides are missing spaces to avoid - # false positives with shifts. - match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) - if match: - (_, _, start_pos) = ReverseCloseExpression( - clean_lines, linenum, len(match.group(1))) - if start_pos <= -1: - error(filename, linenum, 'whitespace/operators', 3, - 'Missing spaces around >') - - # We allow no-spaces around << when used like this: 10<<20, but - # not otherwise (particularly, not when used as streams) - # - # We also allow operators following an opening parenthesis, since - # those tend to be macros that deal with operators. - match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line) - if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and - not (match.group(1) == 'operator' and match.group(2) == ';')): - error(filename, linenum, 'whitespace/operators', 3, - 'Missing spaces around <<') - - # We allow no-spaces around >> for almost anything. This is because - # C++11 allows ">>" to close nested templates, which accounts for - # most cases when ">>" is not followed by a space. - # - # We still warn on ">>" followed by alpha character, because that is - # likely due to ">>" being used for right shifts, e.g.: - # value >> alpha - # - # When ">>" is used to close templates, the alphanumeric letter that - # follows would be part of an identifier, and there should still be - # a space separating the template type and the identifier. - # type> alpha - match = Search(r'>>[a-zA-Z_]', line) - if match: - error(filename, linenum, 'whitespace/operators', 3, - 'Missing spaces around >>') - - # There shouldn't be space around unary operators - match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) - if match: - error(filename, linenum, 'whitespace/operators', 4, - 'Extra space for operator %s' % match.group(1)) - - -def CheckParenthesisSpacing(filename, clean_lines, linenum, error): - """Checks for horizontal spacing around parentheses. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # No spaces after an if, while, switch, or for - match = Search(r' (if\(|for\(|while\(|switch\()', line) - if match: - error(filename, linenum, 'whitespace/parens', 5, - 'Missing space before ( in %s' % match.group(1)) - - # For if/for/while/switch, the left and right parens should be - # consistent about how many spaces are inside the parens, and - # there should either be zero or one spaces inside the parens. - # We don't want: "if ( foo)" or "if ( foo )". - # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. - match = Search(r'\b(if|for|while|switch)\s*' - r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', - line) - if match: - if len(match.group(2)) != len(match.group(4)): - if not (match.group(3) == ';' and - len(match.group(2)) == 1 + len(match.group(4)) or - not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): - error(filename, linenum, 'whitespace/parens', 5, - 'Mismatching spaces inside () in %s' % match.group(1)) - if len(match.group(2)) not in [0, 1]: - error(filename, linenum, 'whitespace/parens', 5, - 'Should have zero or one spaces inside ( and ) in %s' % - match.group(1)) - - -def CheckCommaSpacing(filename, clean_lines, linenum, error): - """Checks for horizontal spacing near commas and semicolons. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - raw = clean_lines.lines_without_raw_strings - line = clean_lines.elided[linenum] - - # You should always have a space after a comma (either as fn arg or operator) - # - # This does not apply when the non-space character following the - # comma is another comma, since the only time when that happens is - # for empty macro arguments. - # - # We run this check in two passes: first pass on elided lines to - # verify that lines contain missing whitespaces, second pass on raw - # lines to confirm that those missing whitespaces are not due to - # elided comments. - if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and - Search(r',[^,\s]', raw[linenum])): - error(filename, linenum, 'whitespace/comma', 3, - 'Missing space after ,') - - # You should always have a space after a semicolon - # except for few corner cases - # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more - # space after ; - if Search(r';[^\s};\\)/]', line): - error(filename, linenum, 'whitespace/semicolon', 3, - 'Missing space after ;') - - -def _IsType(clean_lines, nesting_state, expr): - """Check if expression looks like a type name, returns true if so. - - Args: - clean_lines: A CleansedLines instance containing the file. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - expr: The expression to check. - Returns: - True, if token looks like a type. - """ - # Keep only the last token in the expression - last_word = Match(r'^.*(\b\S+)$', expr) - if last_word: - token = last_word.group(1) - else: - token = expr - - # Match native types and stdint types - if _TYPES.match(token): - return True - - # Try a bit harder to match templated types. Walk up the nesting - # stack until we find something that resembles a typename - # declaration for what we are looking for. - typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) + - r'\b') - block_index = len(nesting_state.stack) - 1 - while block_index >= 0: - if isinstance(nesting_state.stack[block_index], _NamespaceInfo): - return False - - # Found where the opening brace is. We want to scan from this - # line up to the beginning of the function, minus a few lines. - # template - # class C - # : public ... { // start scanning here - last_line = nesting_state.stack[block_index].starting_linenum - - next_block_start = 0 - if block_index > 0: - next_block_start = nesting_state.stack[block_index - 1].starting_linenum - first_line = last_line - while first_line >= next_block_start: - if clean_lines.elided[first_line].find('template') >= 0: - break - first_line -= 1 - if first_line < next_block_start: - # Didn't find any "template" keyword before reaching the next block, - # there are probably no template things to check for this block - block_index -= 1 - continue - - # Look for typename in the specified range - for i in xrange(first_line, last_line + 1, 1): - if Search(typename_pattern, clean_lines.elided[i]): - return True - block_index -= 1 - - return False - - -def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): - """Checks for horizontal spacing near commas. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Except after an opening paren, or after another opening brace (in case of - # an initializer list, for instance), you should have spaces before your - # braces when they are delimiting blocks, classes, namespaces etc. - # And since you should never have braces at the beginning of a line, - # this is an easy test. Except that braces used for initialization don't - # follow the same rule; we often don't want spaces before those. - match = Match(r'^(.*[^ ({>]){', line) - - if match: - # Try a bit harder to check for brace initialization. This - # happens in one of the following forms: - # Constructor() : initializer_list_{} { ... } - # Constructor{}.MemberFunction() - # Type variable{}; - # FunctionCall(type{}, ...); - # LastArgument(..., type{}); - # LOG(INFO) << type{} << " ..."; - # map_of_type[{...}] = ...; - # ternary = expr ? new type{} : nullptr; - # OuterTemplate{}> - # - # We check for the character following the closing brace, and - # silence the warning if it's one of those listed above, i.e. - # "{.;,)<>]:". - # - # To account for nested initializer list, we allow any number of - # closing braces up to "{;,)<". We can't simply silence the - # warning on first sight of closing brace, because that would - # cause false negatives for things that are not initializer lists. - # Silence this: But not this: - # Outer{ if (...) { - # Inner{...} if (...){ // Missing space before { - # }; } - # - # There is a false negative with this approach if people inserted - # spurious semicolons, e.g. "if (cond){};", but we will catch the - # spurious semicolon with a separate check. - leading_text = match.group(1) - (endline, endlinenum, endpos) = CloseExpression( - clean_lines, linenum, len(match.group(1))) - trailing_text = '' - if endpos > -1: - trailing_text = endline[endpos:] - for offset in xrange(endlinenum + 1, - min(endlinenum + 3, clean_lines.NumLines() - 1)): - trailing_text += clean_lines.elided[offset] - # We also suppress warnings for `uint64_t{expression}` etc., as the style - # guide recommends brace initialization for integral types to avoid - # overflow/truncation. - if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text) - and not _IsType(clean_lines, nesting_state, leading_text)): - error(filename, linenum, 'whitespace/braces', 5, - 'Missing space before {') - - # Make sure '} else {' has spaces. - if Search(r'}else', line): - error(filename, linenum, 'whitespace/braces', 5, - 'Missing space before else') - - # You shouldn't have a space before a semicolon at the end of the line. - # There's a special case for "for" since the style guide allows space before - # the semicolon there. - if Search(r':\s*;\s*$', line): - error(filename, linenum, 'whitespace/semicolon', 5, - 'Semicolon defining empty statement. Use {} instead.') - elif Search(r'^\s*;\s*$', line): - error(filename, linenum, 'whitespace/semicolon', 5, - 'Line contains only semicolon. If this should be an empty statement, ' - 'use {} instead.') - elif (Search(r'\s+;\s*$', line) and - not Search(r'\bfor\b', line)): - error(filename, linenum, 'whitespace/semicolon', 5, - 'Extra space before last semicolon. If this should be an empty ' - 'statement, use {} instead.') - - -def IsDecltype(clean_lines, linenum, column): - """Check if the token ending on (linenum, column) is decltype(). - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: the number of the line to check. - column: end column of the token to check. - Returns: - True if this token is decltype() expression, False otherwise. - """ - (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) - if start_col < 0: - return False - if Search(r'\bdecltype\s*$', text[0:start_col]): - return True - return False - -def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): - """Checks for additional blank line issues related to sections. - - Currently the only thing checked here is blank line before protected/private. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - class_info: A _ClassInfo objects. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - # Skip checks if the class is small, where small means 25 lines or less. - # 25 lines seems like a good cutoff since that's the usual height of - # terminals, and any class that can't fit in one screen can't really - # be considered "small". - # - # Also skip checks if we are on the first line. This accounts for - # classes that look like - # class Foo { public: ... }; - # - # If we didn't find the end of the class, last_line would be zero, - # and the check will be skipped by the first condition. - if (class_info.last_line - class_info.starting_linenum <= 24 or - linenum <= class_info.starting_linenum): - return - - matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) - if matched: - # Issue warning if the line before public/protected/private was - # not a blank line, but don't do this if the previous line contains - # "class" or "struct". This can happen two ways: - # - We are at the beginning of the class. - # - We are forward-declaring an inner class that is semantically - # private, but needed to be public for implementation reasons. - # Also ignores cases where the previous line ends with a backslash as can be - # common when defining classes in C macros. - prev_line = clean_lines.lines[linenum - 1] - if (not IsBlankLine(prev_line) and - not Search(r'\b(class|struct)\b', prev_line) and - not Search(r'\\$', prev_line)): - # Try a bit harder to find the beginning of the class. This is to - # account for multi-line base-specifier lists, e.g.: - # class Derived - # : public Base { - end_class_head = class_info.starting_linenum - for i in range(class_info.starting_linenum, linenum): - if Search(r'\{\s*$', clean_lines.lines[i]): - end_class_head = i - break - if end_class_head < linenum - 1: - error(filename, linenum, 'whitespace/blank_line', 3, - '"%s:" should be preceded by a blank line' % matched.group(1)) - - -def GetPreviousNonBlankLine(clean_lines, linenum): - """Return the most recent non-blank line and its line number. - - Args: - clean_lines: A CleansedLines instance containing the file contents. - linenum: The number of the line to check. - - Returns: - A tuple with two elements. The first element is the contents of the last - non-blank line before the current line, or the empty string if this is the - first non-blank line. The second is the line number of that line, or -1 - if this is the first non-blank line. - """ - - prevlinenum = linenum - 1 - while prevlinenum >= 0: - prevline = clean_lines.elided[prevlinenum] - if not IsBlankLine(prevline): # if not a blank line... - return (prevline, prevlinenum) - prevlinenum -= 1 - return ('', -1) - - -def CheckBraces(filename, clean_lines, linenum, error): - """Looks for misplaced braces (e.g. at the end of line). - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - - line = clean_lines.elided[linenum] # get rid of comments and strings - - if Match(r'\s*{\s*$', line): - # We allow an open brace to start a line in the case where someone is using - # braces in a block to explicitly create a new scope, which is commonly used - # to control the lifetime of stack-allocated variables. Braces are also - # used for brace initializers inside function calls. We don't detect this - # perfectly: we just don't complain if the last non-whitespace character on - # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the - # previous line starts a preprocessor block. We also allow a brace on the - # following line if it is part of an array initialization and would not fit - # within the 80 character limit of the preceding line. - prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] - if (not Search(r'[,;:}{(]\s*$', prevline) and - not Match(r'\s*#', prevline) and - not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)): - error(filename, linenum, 'whitespace/braces', 4, - '{ should almost always be at the end of the previous line') - - # An else clause should be on the same line as the preceding closing brace. - if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): - prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] - if Match(r'\s*}\s*$', prevline): - error(filename, linenum, 'whitespace/newline', 4, - 'An else should appear on the same line as the preceding }') - - # If braces come on one side of an else, they should be on both. - # However, we have to worry about "else if" that spans multiple lines! - if Search(r'else if\s*\(', line): # could be multi-line if - brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) - # find the ( after the if - pos = line.find('else if') - pos = line.find('(', pos) - if pos > 0: - (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) - brace_on_right = endline[endpos:].find('{') != -1 - if brace_on_left != brace_on_right: # must be brace after if - error(filename, linenum, 'readability/braces', 5, - 'If an else has a brace on one side, it should have it on both') - elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): - error(filename, linenum, 'readability/braces', 5, - 'If an else has a brace on one side, it should have it on both') - - # Likewise, an else should never have the else clause on the same line - if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): - error(filename, linenum, 'whitespace/newline', 4, - 'Else clause should never be on same line as else (use 2 lines)') - - # In the same way, a do/while should never be on one line - if Match(r'\s*do [^\s{]', line): - error(filename, linenum, 'whitespace/newline', 4, - 'do/while clauses should not be on a single line') - - # Check single-line if/else bodies. The style guide says 'curly braces are not - # required for single-line statements'. We additionally allow multi-line, - # single statements, but we reject anything with more than one semicolon in - # it. This means that the first semicolon after the if should be at the end of - # its line, and the line after that should have an indent level equal to or - # lower than the if. We also check for ambiguous if/else nesting without - # braces. - if_else_match = Search(r'\b(if\s*(|constexpr)\s*\(|else\b)', line) - if if_else_match and not Match(r'\s*#', line): - if_indent = GetIndentLevel(line) - endline, endlinenum, endpos = line, linenum, if_else_match.end() - if_match = Search(r'\bif\s*(|constexpr)\s*\(', line) - if if_match: - # This could be a multiline if condition, so find the end first. - pos = if_match.end() - 1 - (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) - # Check for an opening brace, either directly after the if or on the next - # line. If found, this isn't a single-statement conditional. - if (not Match(r'\s*{', endline[endpos:]) - and not (Match(r'\s*$', endline[endpos:]) - and endlinenum < (len(clean_lines.elided) - 1) - and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): - while (endlinenum < len(clean_lines.elided) - and ';' not in clean_lines.elided[endlinenum][endpos:]): - endlinenum += 1 - endpos = 0 - if endlinenum < len(clean_lines.elided): - endline = clean_lines.elided[endlinenum] - # We allow a mix of whitespace and closing braces (e.g. for one-liner - # methods) and a single \ after the semicolon (for macros) - endpos = endline.find(';') - if not Match(r';[\s}]*(\\?)$', endline[endpos:]): - # Semicolon isn't the last character, there's something trailing. - # Output a warning if the semicolon is not contained inside - # a lambda expression. - if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', - endline): - error(filename, linenum, 'readability/braces', 4, - 'If/else bodies with multiple statements require braces') - elif endlinenum < len(clean_lines.elided) - 1: - # Make sure the next line is dedented - next_line = clean_lines.elided[endlinenum + 1] - next_indent = GetIndentLevel(next_line) - # With ambiguous nested if statements, this will error out on the - # if that *doesn't* match the else, regardless of whether it's the - # inner one or outer one. - if (if_match and Match(r'\s*else\b', next_line) - and next_indent != if_indent): - error(filename, linenum, 'readability/braces', 4, - 'Else clause should be indented at the same level as if. ' - 'Ambiguous nested if/else chains require braces.') - elif next_indent > if_indent: - error(filename, linenum, 'readability/braces', 4, - 'If/else bodies with multiple statements require braces') - - -def CheckTrailingSemicolon(filename, clean_lines, linenum, error): - """Looks for redundant trailing semicolon. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - - line = clean_lines.elided[linenum] - - # Block bodies should not be followed by a semicolon. Due to C++11 - # brace initialization, there are more places where semicolons are - # required than not, so we use a whitelist approach to check these - # rather than a blacklist. These are the places where "};" should - # be replaced by just "}": - # 1. Some flavor of block following closing parenthesis: - # for (;;) {}; - # while (...) {}; - # switch (...) {}; - # Function(...) {}; - # if (...) {}; - # if (...) else if (...) {}; - # - # 2. else block: - # if (...) else {}; - # - # 3. const member function: - # Function(...) const {}; - # - # 4. Block following some statement: - # x = 42; - # {}; - # - # 5. Block at the beginning of a function: - # Function(...) { - # {}; - # } - # - # Note that naively checking for the preceding "{" will also match - # braces inside multi-dimensional arrays, but this is fine since - # that expression will not contain semicolons. - # - # 6. Block following another block: - # while (true) {} - # {}; - # - # 7. End of namespaces: - # namespace {}; - # - # These semicolons seems far more common than other kinds of - # redundant semicolons, possibly due to people converting classes - # to namespaces. For now we do not warn for this case. - # - # Try matching case 1 first. - match = Match(r'^(.*\)\s*)\{', line) - if match: - # Matched closing parenthesis (case 1). Check the token before the - # matching opening parenthesis, and don't warn if it looks like a - # macro. This avoids these false positives: - # - macro that defines a base class - # - multi-line macro that defines a base class - # - macro that defines the whole class-head - # - # But we still issue warnings for macros that we know are safe to - # warn, specifically: - # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P - # - TYPED_TEST - # - INTERFACE_DEF - # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: - # - # We implement a whitelist of safe macros instead of a blacklist of - # unsafe macros, even though the latter appears less frequently in - # google code and would have been easier to implement. This is because - # the downside for getting the whitelist wrong means some extra - # semicolons, while the downside for getting the blacklist wrong - # would result in compile errors. - # - # In addition to macros, we also don't want to warn on - # - Compound literals - # - Lambdas - # - alignas specifier with anonymous structs - # - decltype - closing_brace_pos = match.group(1).rfind(')') - opening_parenthesis = ReverseCloseExpression( - clean_lines, linenum, closing_brace_pos) - if opening_parenthesis[2] > -1: - line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] - macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix) - func = Match(r'^(.*\])\s*$', line_prefix) - if ((macro and - macro.group(1) not in ( - 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', - 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', - 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or - (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or - Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or - Search(r'\bdecltype$', line_prefix) or - Search(r'\s+=\s*$', line_prefix)): - match = None - if (match and - opening_parenthesis[1] > 1 and - Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): - # Multi-line lambda-expression - match = None - - else: - # Try matching cases 2-3. - match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) - if not match: - # Try matching cases 4-6. These are always matched on separate lines. - # - # Note that we can't simply concatenate the previous line to the - # current line and do a single match, otherwise we may output - # duplicate warnings for the blank line case: - # if (cond) { - # // blank line - # } - prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] - if prevline and Search(r'[;{}]\s*$', prevline): - match = Match(r'^(\s*)\{', line) - - # Check matching closing brace - if match: - (endline, endlinenum, endpos) = CloseExpression( - clean_lines, linenum, len(match.group(1))) - if endpos > -1 and Match(r'^\s*;', endline[endpos:]): - # Current {} pair is eligible for semicolon check, and we have found - # the redundant semicolon, output warning here. - # - # Note: because we are scanning forward for opening braces, and - # outputting warnings for the matching closing brace, if there are - # nested blocks with trailing semicolons, we will get the error - # messages in reversed order. - - # We need to check the line forward for NOLINT - raw_lines = clean_lines.raw_lines - ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1, - error) - ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum, - error) - - error(filename, endlinenum, 'readability/braces', 4, - "You don't need a ; after a }") - - -def CheckEmptyBlockBody(filename, clean_lines, linenum, error): - """Look for empty loop/conditional body with only a single semicolon. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - - # Search for loop keywords at the beginning of the line. Because only - # whitespaces are allowed before the keywords, this will also ignore most - # do-while-loops, since those lines should start with closing brace. - # - # We also check "if" blocks here, since an empty conditional block - # is likely an error. - line = clean_lines.elided[linenum] - matched = Match(r'\s*(for|while|if)\s*\(', line) - if matched: - # Find the end of the conditional expression. - (end_line, end_linenum, end_pos) = CloseExpression( - clean_lines, linenum, line.find('(')) - - # Output warning if what follows the condition expression is a semicolon. - # No warning for all other cases, including whitespace or newline, since we - # have a separate check for semicolons preceded by whitespace. - if end_pos >= 0 and Match(r';', end_line[end_pos:]): - if matched.group(1) == 'if': - error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, - 'Empty conditional bodies should use {}') - else: - error(filename, end_linenum, 'whitespace/empty_loop_body', 5, - 'Empty loop bodies should use {} or continue') - - # Check for if statements that have completely empty bodies (no comments) - # and no else clauses. - if end_pos >= 0 and matched.group(1) == 'if': - # Find the position of the opening { for the if statement. - # Return without logging an error if it has no brackets. - opening_linenum = end_linenum - opening_line_fragment = end_line[end_pos:] - # Loop until EOF or find anything that's not whitespace or opening {. - while not Search(r'^\s*\{', opening_line_fragment): - if Search(r'^(?!\s*$)', opening_line_fragment): - # Conditional has no brackets. - return - opening_linenum += 1 - if opening_linenum == len(clean_lines.elided): - # Couldn't find conditional's opening { or any code before EOF. - return - opening_line_fragment = clean_lines.elided[opening_linenum] - # Set opening_line (opening_line_fragment may not be entire opening line). - opening_line = clean_lines.elided[opening_linenum] - - # Find the position of the closing }. - opening_pos = opening_line_fragment.find('{') - if opening_linenum == end_linenum: - # We need to make opening_pos relative to the start of the entire line. - opening_pos += end_pos - (closing_line, closing_linenum, closing_pos) = CloseExpression( - clean_lines, opening_linenum, opening_pos) - if closing_pos < 0: - return - - # Now construct the body of the conditional. This consists of the portion - # of the opening line after the {, all lines until the closing line, - # and the portion of the closing line before the }. - if (clean_lines.raw_lines[opening_linenum] != - CleanseComments(clean_lines.raw_lines[opening_linenum])): - # Opening line ends with a comment, so conditional isn't empty. - return - if closing_linenum > opening_linenum: - # Opening line after the {. Ignore comments here since we checked above. - bodylist = list(opening_line[opening_pos+1:]) - # All lines until closing line, excluding closing line, with comments. - bodylist.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum]) - # Closing line before the }. Won't (and can't) have comments. - bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1]) - body = '\n'.join(bodylist) - else: - # If statement has brackets and fits on a single line. - body = opening_line[opening_pos+1:closing_pos-1] - - # Check if the body is empty - if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body): - return - # The body is empty. Now make sure there's not an else clause. - current_linenum = closing_linenum - current_line_fragment = closing_line[closing_pos:] - # Loop until EOF or find anything that's not whitespace or else clause. - while Search(r'^\s*$|^(?=\s*else)', current_line_fragment): - if Search(r'^(?=\s*else)', current_line_fragment): - # Found an else clause, so don't log an error. - return - current_linenum += 1 - if current_linenum == len(clean_lines.elided): - break - current_line_fragment = clean_lines.elided[current_linenum] - - # The body is empty and there's no else clause until EOF or other code. - error(filename, end_linenum, 'whitespace/empty_if_body', 4, - ('If statement had no body and no else clause')) - - -def FindCheckMacro(line): - """Find a replaceable CHECK-like macro. - - Args: - line: line to search on. - Returns: - (macro name, start position), or (None, -1) if no replaceable - macro is found. - """ - for macro in _CHECK_MACROS: - i = line.find(macro) - if i >= 0: - # Find opening parenthesis. Do a regular expression match here - # to make sure that we are matching the expected CHECK macro, as - # opposed to some other macro that happens to contain the CHECK - # substring. - matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) - if not matched: - continue - return (macro, len(matched.group(1))) - return (None, -1) - - -def CheckCheck(filename, clean_lines, linenum, error): - """Checks the use of CHECK and EXPECT macros. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - - # Decide the set of replacement macros that should be suggested - lines = clean_lines.elided - (check_macro, start_pos) = FindCheckMacro(lines[linenum]) - if not check_macro: - return - - # Find end of the boolean expression by matching parentheses - (last_line, end_line, end_pos) = CloseExpression( - clean_lines, linenum, start_pos) - if end_pos < 0: - return - - # If the check macro is followed by something other than a - # semicolon, assume users will log their own custom error messages - # and don't suggest any replacements. - if not Match(r'\s*;', last_line[end_pos:]): - return - - if linenum == end_line: - expression = lines[linenum][start_pos + 1:end_pos - 1] - else: - expression = lines[linenum][start_pos + 1:] - for i in xrange(linenum + 1, end_line): - expression += lines[i] - expression += last_line[0:end_pos - 1] - - # Parse expression so that we can take parentheses into account. - # This avoids false positives for inputs like "CHECK((a < 4) == b)", - # which is not replaceable by CHECK_LE. - lhs = '' - rhs = '' - operator = None - while expression: - matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' - r'==|!=|>=|>|<=|<|\()(.*)$', expression) - if matched: - token = matched.group(1) - if token == '(': - # Parenthesized operand - expression = matched.group(2) - (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) - if end < 0: - return # Unmatched parenthesis - lhs += '(' + expression[0:end] - expression = expression[end:] - elif token in ('&&', '||'): - # Logical and/or operators. This means the expression - # contains more than one term, for example: - # CHECK(42 < a && a < b); - # - # These are not replaceable with CHECK_LE, so bail out early. - return - elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): - # Non-relational operator - lhs += token - expression = matched.group(2) - else: - # Relational operator - operator = token - rhs = matched.group(2) - break - else: - # Unparenthesized operand. Instead of appending to lhs one character - # at a time, we do another regular expression match to consume several - # characters at once if possible. Trivial benchmark shows that this - # is more efficient when the operands are longer than a single - # character, which is generally the case. - matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) - if not matched: - matched = Match(r'^(\s*\S)(.*)$', expression) - if not matched: - break - lhs += matched.group(1) - expression = matched.group(2) - - # Only apply checks if we got all parts of the boolean expression - if not (lhs and operator and rhs): - return - - # Check that rhs do not contain logical operators. We already know - # that lhs is fine since the loop above parses out && and ||. - if rhs.find('&&') > -1 or rhs.find('||') > -1: - return - - # At least one of the operands must be a constant literal. This is - # to avoid suggesting replacements for unprintable things like - # CHECK(variable != iterator) - # - # The following pattern matches decimal, hex integers, strings, and - # characters (in that order). - lhs = lhs.strip() - rhs = rhs.strip() - match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' - if Match(match_constant, lhs) or Match(match_constant, rhs): - # Note: since we know both lhs and rhs, we can provide a more - # descriptive error message like: - # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) - # Instead of: - # Consider using CHECK_EQ instead of CHECK(a == b) - # - # We are still keeping the less descriptive message because if lhs - # or rhs gets long, the error message might become unreadable. - error(filename, linenum, 'readability/check', 2, - 'Consider using %s instead of %s(a %s b)' % ( - _CHECK_REPLACEMENT[check_macro][operator], - check_macro, operator)) - - -def CheckAltTokens(filename, clean_lines, linenum, error): - """Check alternative keywords being used in boolean expressions. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Avoid preprocessor lines - if Match(r'^\s*#', line): - return - - # Last ditch effort to avoid multi-line comments. This will not help - # if the comment started before the current line or ended after the - # current line, but it catches most of the false positives. At least, - # it provides a way to workaround this warning for people who use - # multi-line comments in preprocessor macros. - # - # TODO(unknown): remove this once cpplint has better support for - # multi-line comments. - if line.find('/*') >= 0 or line.find('*/') >= 0: - return - - for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): - error(filename, linenum, 'readability/alt_tokens', 2, - 'Use operator %s instead of %s' % ( - _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) - -def CheckNullTokens(filename, clean_lines, linenum, error): - """Check NULL usage. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Avoid preprocessor lines - if Match(r'^\s*#', line): - return - - if line.find('/*') >= 0 or line.find('*/') >= 0: - return - - for match in _NULL_TOKEN_PATTERN.finditer(line): - error(filename, linenum, 'readability/null_usage', 2, - 'Use nullptr instead of NULL') - -def CheckV8PersistentTokens(filename, clean_lines, linenum, error): - """Check v8::Persistent usage. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Avoid preprocessor lines - if Match(r'^\s*#', line): - return - - if line.find('/*') >= 0 or line.find('*/') >= 0: - return - - for match in _V8_PERSISTENT_PATTERN.finditer(line): - error(filename, linenum, 'runtime/v8_persistent', 2, - 'Use v8::Global instead of v8::Persistent') - -def CheckLeftLeaningPointer(filename, clean_lines, linenum, error): - """Check for left-leaning pointer placement. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Avoid preprocessor lines - if Match(r'^\s*#', line): - return - - if '/*' in line or '*/' in line: - return - - for match in _RIGHT_LEANING_POINTER_PATTERN.finditer(line): - error(filename, linenum, 'readability/pointer_notation', 2, - 'Use left leaning pointer instead of right leaning') - -def GetLineWidth(line): - """Determines the width of the line in column positions. - - Args: - line: A string, which may be a Unicode string. - - Returns: - The width of the line in column positions, accounting for Unicode - combining characters and wide characters. - """ - if isinstance(line, unicode): - width = 0 - for uc in unicodedata.normalize('NFC', line): - if unicodedata.east_asian_width(uc) in ('W', 'F'): - width += 2 - elif not unicodedata.combining(uc): - # Issue 337 - # https://mail.python.org/pipermail/python-list/2012-August/628809.html - if (sys.version_info.major, sys.version_info.minor) <= (3, 2): - # https://github.com/python/cpython/blob/2.7/Include/unicodeobject.h#L81 - is_wide_build = sysconfig.get_config_var("Py_UNICODE_SIZE") >= 4 - # https://github.com/python/cpython/blob/2.7/Objects/unicodeobject.c#L564 - is_low_surrogate = 0xDC00 <= ord(uc) <= 0xDFFF - if not is_wide_build and is_low_surrogate: - width -= 1 - - width += 1 - return width - else: - return len(line) - - -def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, - error): - """Checks rules from the 'C++ style rules' section of cppguide.html. - - Most of these rules are hard to test (naming, comment style), but we - do what we can. In particular we check for 2-space indents, line lengths, - tab usage, spaces inside code, etc. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - file_extension: The extension (without the dot) of the filename. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - error: The function to call with any errors found. - """ - - # Don't use "elided" lines here, otherwise we can't check commented lines. - # Don't want to use "raw" either, because we don't want to check inside C++11 - # raw strings, - raw_lines = clean_lines.lines_without_raw_strings - line = raw_lines[linenum] - prev = raw_lines[linenum - 1] if linenum > 0 else '' - - if line.find('\t') != -1: - error(filename, linenum, 'whitespace/tab', 1, - 'Tab found; better to use spaces') - - # One or three blank spaces at the beginning of the line is weird; it's - # hard to reconcile that with 2-space indents. - # NOTE: here are the conditions rob pike used for his tests. Mine aren't - # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces - # if(RLENGTH > 20) complain = 0; - # if(match($0, " +(error|private|public|protected):")) complain = 0; - # if(match(prev, "&& *$")) complain = 0; - # if(match(prev, "\\|\\| *$")) complain = 0; - # if(match(prev, "[\",=><] *$")) complain = 0; - # if(match($0, " <<")) complain = 0; - # if(match(prev, " +for \\(")) complain = 0; - # if(prevodd && match(prevprev, " +for \\(")) complain = 0; - scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' - classinfo = nesting_state.InnermostClass() - initial_spaces = 0 - cleansed_line = clean_lines.elided[linenum] - while initial_spaces < len(line) and line[initial_spaces] == ' ': - initial_spaces += 1 - # There are certain situations we allow one space, notably for - # section labels, and also lines containing multi-line raw strings. - # We also don't check for lines that look like continuation lines - # (of lines ending in double quotes, commas, equals, or angle brackets) - # because the rules for how to indent those are non-trivial. - if (not Search(r'[",=><] *$', prev) and - (initial_spaces == 1 or initial_spaces == 3) and - not Match(scope_or_label_pattern, cleansed_line) and - not (clean_lines.raw_lines[linenum] != line and - Match(r'^\s*""', line))): - error(filename, linenum, 'whitespace/indent', 3, - 'Weird number of spaces at line-start. ' - 'Are you using a 2-space indent?') - - if line and line[-1].isspace(): - error(filename, linenum, 'whitespace/end_of_line', 4, - 'Line ends in whitespace. Consider deleting these extra spaces.') - - # Check if the line is a header guard. - is_header_guard = False - if IsHeaderExtension(file_extension): - cppvar = GetHeaderGuardCPPVariable(filename) - if (line.startswith('#ifndef %s' % cppvar) or - line.startswith('#define %s' % cppvar) or - line.startswith('#endif // %s' % cppvar)): - is_header_guard = True - # #include lines and header guards can be long, since there's no clean way to - # split them. - # - # URLs can be long too. It's possible to split these, but it makes them - # harder to cut&paste. - # - # The "$Id:...$" comment may also get very long without it being the - # developers fault. - # - # Doxygen documentation copying can get pretty long when using an overloaded - # function declaration - if (not line.startswith('#include') and not is_header_guard and - not Match(r'^\s*//.*http(s?)://\S*$', line) and - not Match(r'^\s*//\s*[^\s]*$', line) and - not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and - not Match(r'^\s*/// [@\\](copydoc|copydetails|copybrief) .*$', line)): - line_width = GetLineWidth(line) - if line_width > _line_length: - error(filename, linenum, 'whitespace/line_length', 2, - 'Lines should be <= %i characters long' % _line_length) - - if (cleansed_line.count(';') > 1 and - # allow simple single line lambdas - not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}\n\r]*\}', - line) and - # for loops are allowed two ;'s (and may run over two lines). - cleansed_line.find('for') == -1 and - (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or - GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and - # It's ok to have many commands in a switch case that fits in 1 line - not ((cleansed_line.find('case ') != -1 or - cleansed_line.find('default:') != -1) and - cleansed_line.find('break;') != -1)): - error(filename, linenum, 'whitespace/newline', 0, - 'More than one command on the same line') - - # Some more style checks - CheckBraces(filename, clean_lines, linenum, error) - CheckTrailingSemicolon(filename, clean_lines, linenum, error) - CheckEmptyBlockBody(filename, clean_lines, linenum, error) - CheckSpacing(filename, clean_lines, linenum, nesting_state, error) - CheckOperatorSpacing(filename, clean_lines, linenum, error) - CheckParenthesisSpacing(filename, clean_lines, linenum, error) - CheckCommaSpacing(filename, clean_lines, linenum, error) - CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error) - CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) - CheckCheck(filename, clean_lines, linenum, error) - CheckAltTokens(filename, clean_lines, linenum, error) - CheckNullTokens(filename, clean_lines, linenum, error) - CheckV8PersistentTokens(filename, clean_lines, linenum, error) - CheckLeftLeaningPointer(filename, clean_lines, linenum, error) - classinfo = nesting_state.InnermostClass() - if classinfo: - CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) - - -_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') -# Matches the first component of a filename delimited by -s and _s. That is: -# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' -# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' -# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' -# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' -_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') - - -def _DropCommonSuffixes(filename): - """Drops common suffixes like _test.cc or -inl.h from filename. - - For example: - >>> _DropCommonSuffixes('foo/foo-inl.h') - 'foo/foo' - >>> _DropCommonSuffixes('foo/bar/foo.cc') - 'foo/bar/foo' - >>> _DropCommonSuffixes('foo/foo_internal.h') - 'foo/foo' - >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') - 'foo/foo_unusualinternal' - - Args: - filename: The input filename. - - Returns: - The filename with the common suffix removed. - """ - for suffix in itertools.chain( - ('%s.%s' % (test_suffix.lstrip('_'), ext) - for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())), - ('%s.%s' % (suffix, ext) - for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))): - if (filename.endswith(suffix) and len(filename) > len(suffix) and - filename[-len(suffix) - 1] in ('-', '_')): - return filename[:-len(suffix) - 1] - return os.path.splitext(filename)[0] - - -def _ClassifyInclude(fileinfo, include, is_system): - """Figures out what kind of header 'include' is. - - Args: - fileinfo: The current file cpplint is running over. A FileInfo instance. - include: The path to a #included file. - is_system: True if the #include used <> rather than "". - - Returns: - One of the _XXX_HEADER constants. - - For example: - >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) - _C_SYS_HEADER - >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) - _CPP_SYS_HEADER - >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) - _LIKELY_MY_HEADER - >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), - ... 'bar/foo_other_ext.h', False) - _POSSIBLE_MY_HEADER - >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) - _OTHER_HEADER - """ - # This is a list of all standard c++ header files, except - # those already checked for above. - is_cpp_h = include in _CPP_HEADERS - - # Headers with C++ extensions shouldn't be considered C system headers - if is_system and os.path.splitext(include)[1] in ['.hpp', '.hxx', '.h++']: - is_system = False - - if is_system: - if is_cpp_h: - return _CPP_SYS_HEADER - else: - return _C_SYS_HEADER - - # If the target file and the include we're checking share a - # basename when we drop common extensions, and the include - # lives in . , then it's likely to be owned by the target file. - target_dir, target_base = ( - os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) - include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) - target_dir_pub = os.path.normpath(target_dir + '/../public') - target_dir_pub = target_dir_pub.replace('\\', '/') - if target_base == include_base and ( - include_dir == target_dir or - include_dir == target_dir_pub): - return _LIKELY_MY_HEADER - - # If the target and include share some initial basename - # component, it's possible the target is implementing the - # include, so it's allowed to be first, but we'll never - # complain if it's not there. - target_first_component = _RE_FIRST_COMPONENT.match(target_base) - include_first_component = _RE_FIRST_COMPONENT.match(include_base) - if (target_first_component and include_first_component and - target_first_component.group(0) == - include_first_component.group(0)): - return _POSSIBLE_MY_HEADER - - return _OTHER_HEADER - - - -def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): - """Check rules that are applicable to #include lines. - - Strings on #include lines are NOT removed from elided line, to make - certain tasks easier. However, to prevent false positives, checks - applicable to #include lines in CheckLanguage must be put here. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - include_state: An _IncludeState instance in which the headers are inserted. - error: The function to call with any errors found. - """ - fileinfo = FileInfo(filename) - line = clean_lines.lines[linenum] - - # "include" should use the new style "foo/bar.h" instead of just "bar.h" - # Only do this check if the included header follows google naming - # conventions. If not, assume that it's a 3rd party API that - # requires special include conventions. - # - # We also make an exception for Lua headers, which follow google - # naming convention but not the include convention. - match = Match(r'#include\s*"([^/]+\.h)"', line) - if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): - error(filename, linenum, 'build/include_subdir', 4, - 'Include the directory when naming .h files') - - # we shouldn't include a file more than once. actually, there are a - # handful of instances where doing so is okay, but in general it's - # not. - match = _RE_PATTERN_INCLUDE.search(line) - if match: - include = match.group(2) - is_system = (match.group(1) == '<') - duplicate_line = include_state.FindHeader(include) - if duplicate_line >= 0: - error(filename, linenum, 'build/include', 4, - '"%s" already included at %s:%s' % - (include, filename, duplicate_line)) - return - - for extension in GetNonHeaderExtensions(): - if (include.endswith('.' + extension) and - os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): - error(filename, linenum, 'build/include', 4, - 'Do not include .' + extension + ' files from other packages') - return - - # We DO want to include a 3rd party looking header if it matches the - # filename. Otherwise we get an erroneous error "...should include its - # header" error later. - third_src_header = False - for ext in GetHeaderExtensions(): - basefilename = filename[0:len(filename) - len(fileinfo.Extension())] - headerfile = basefilename + '.' + ext - headername = FileInfo(headerfile).RepositoryName() - if headername in include or include in headername: - third_src_header = True - break - - if third_src_header or not _THIRD_PARTY_HEADERS_PATTERN.match(include): - include_state.include_list[-1].append((include, linenum)) - - # We want to ensure that headers appear in the right order: - # 1) for foo.cc, foo.h - # 2) other project headers - # 3) c system files - # 4) cpp system files - # - # We classify each include statement as one of those 5 types - # using a number of techniques. The include_state object keeps - # track of the highest type seen, and complains if we see a - # lower type after that. - error_message = include_state.CheckNextIncludeOrder( - _ClassifyInclude(fileinfo, include, is_system)) - if error_message: - error(filename, linenum, 'build/include_order', 4, - '%s. Should be: %s.h, c system, c++ system, other.' % - (error_message, fileinfo.BaseName())) - canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) - if not include_state.IsInAlphabeticalOrder( - clean_lines, linenum, canonical_include): - error(filename, linenum, 'build/include_alpha', 4, - 'Include "%s" not in alphabetical order' % include) - include_state.SetLastHeader(canonical_include) - - - -def _GetTextInside(text, start_pattern): - r"""Retrieves all the text between matching open and close parentheses. - - Given a string of lines and a regular expression string, retrieve all the text - following the expression and between opening punctuation symbols like - (, [, or {, and the matching close-punctuation symbol. This properly nested - occurrences of the punctuations, so for the text like - printf(a(), b(c())); - a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. - start_pattern must match string having an open punctuation symbol at the end. - - Args: - text: The lines to extract text. Its comments and strings must be elided. - It can be single line and can span multiple lines. - start_pattern: The regexp string indicating where to start extracting - the text. - Returns: - The extracted text. - None if either the opening string or ending punctuation could not be found. - """ - # TODO(unknown): Audit cpplint.py to see what places could be profitably - # rewritten to use _GetTextInside (and use inferior regexp matching today). - - # Give opening punctuations to get the matching close-punctuations. - matching_punctuation = {'(': ')', '{': '}', '[': ']'} - closing_punctuation = set(itervalues(matching_punctuation)) - - # Find the position to start extracting text. - match = re.search(start_pattern, text, re.M) - if not match: # start_pattern not found in text. - return None - start_position = match.end(0) - - assert start_position > 0, ( - 'start_pattern must ends with an opening punctuation.') - assert text[start_position - 1] in matching_punctuation, ( - 'start_pattern must ends with an opening punctuation.') - # Stack of closing punctuations we expect to have in text after position. - punctuation_stack = [matching_punctuation[text[start_position - 1]]] - position = start_position - while punctuation_stack and position < len(text): - if text[position] == punctuation_stack[-1]: - punctuation_stack.pop() - elif text[position] in closing_punctuation: - # A closing punctuation without matching opening punctuations. - return None - elif text[position] in matching_punctuation: - punctuation_stack.append(matching_punctuation[text[position]]) - position += 1 - if punctuation_stack: - # Opening punctuations left without matching close-punctuations. - return None - # punctuations match. - return text[start_position:position - 1] - - -# Patterns for matching call-by-reference parameters. -# -# Supports nested templates up to 2 levels deep using this messy pattern: -# < (?: < (?: < [^<>]* -# > -# | [^<>] )* -# > -# | [^<>] )* -# > -_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* -_RE_PATTERN_TYPE = ( - r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' - r'(?:\w|' - r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' - r'::)+') -# A call-by-reference parameter ends with '& identifier'. -_RE_PATTERN_REF_PARAM = re.compile( - r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' - r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') -# A call-by-const-reference parameter either ends with 'const& identifier' -# or looks like 'const type& identifier' when 'type' is atomic. -_RE_PATTERN_CONST_REF_PARAM = ( - r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + - r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') -# Stream types. -_RE_PATTERN_REF_STREAM_PARAM = ( - r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')') - - -def CheckLanguage(filename, clean_lines, linenum, file_extension, - include_state, nesting_state, error): - """Checks rules from the 'C++ language rules' section of cppguide.html. - - Some of these rules are hard to test (function overloading, using - uint32 inappropriately), but we do the best we can. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - file_extension: The extension (without the dot) of the filename. - include_state: An _IncludeState instance in which the headers are inserted. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - error: The function to call with any errors found. - """ - # If the line is empty or consists of entirely a comment, no need to - # check it. - line = clean_lines.elided[linenum] - if not line: - return - - match = _RE_PATTERN_INCLUDE.search(line) - if match: - CheckIncludeLine(filename, clean_lines, linenum, include_state, error) - return - - # Reset include state across preprocessor directives. This is meant - # to silence warnings for conditional includes. - match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) - if match: - include_state.ResetSection(match.group(1)) - - - # Perform other checks now that we are sure that this is not an include line - CheckCasts(filename, clean_lines, linenum, error) - CheckGlobalStatic(filename, clean_lines, linenum, error) - CheckPrintf(filename, clean_lines, linenum, error) - - if IsHeaderExtension(file_extension): - # TODO(unknown): check that 1-arg constructors are explicit. - # How to tell it's a constructor? - # (handled in CheckForNonStandardConstructs for now) - # TODO(unknown): check that classes declare or disable copy/assign - # (level 1 error) - pass - - # Check if people are using the verboten C basic types. The only exception - # we regularly allow is "unsigned short port" for port. - if Search(r'\bshort port\b', line): - if not Search(r'\bunsigned short port\b', line): - error(filename, linenum, 'runtime/int', 4, - 'Use "unsigned short" for ports, not "short"') - else: - match = Search(r'\b(short|long(?! +double)|long long)\b', line) - if match: - error(filename, linenum, 'runtime/int', 4, - 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) - - # Check if some verboten operator overloading is going on - # TODO(unknown): catch out-of-line unary operator&: - # class X {}; - # int operator&(const X& x) { return 42; } // unary operator& - # The trick is it's hard to tell apart from binary operator&: - # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& - if Search(r'\boperator\s*&\s*\(\s*\)', line): - error(filename, linenum, 'runtime/operator', 4, - 'Unary operator& is dangerous. Do not use it.') - - # Check for suspicious usage of "if" like - # } if (a == b) { - if Search(r'\}\s*if\s*\(', line): - error(filename, linenum, 'readability/braces', 4, - 'Did you mean "else if"? If not, start a new line for "if".') - - # Check for potential format string bugs like printf(foo). - # We constrain the pattern not to pick things like DocidForPrintf(foo). - # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) - # TODO(unknown): Catch the following case. Need to change the calling - # convention of the whole function to process multiple line to handle it. - # printf( - # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); - printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') - if printf_args: - match = Match(r'([\w.\->()]+)$', printf_args) - if match and match.group(1) != '__VA_ARGS__': - function_name = re.search(r'\b((?:string)?printf)\s*\(', - line, re.I).group(1) - error(filename, linenum, 'runtime/printf', 4, - 'Potential format string bug. Do %s("%%s", %s) instead.' - % (function_name, match.group(1))) - - # Check for potential memset bugs like memset(buf, sizeof(buf), 0). - match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) - if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): - error(filename, linenum, 'runtime/memset', 4, - 'Did you mean "memset(%s, 0, %s)"?' - % (match.group(1), match.group(2))) - - if Search(r'\busing namespace\b', line): - if Search(r'\bliterals\b', line): - error(filename, linenum, 'build/namespaces_literals', 5, - 'Do not use namespace using-directives. ' - 'Use using-declarations instead.') - else: - error(filename, linenum, 'build/namespaces', 5, - 'Do not use namespace using-directives. ' - 'Use using-declarations instead.') - - # Detect variable-length arrays. - match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) - if (match and match.group(2) != 'return' and match.group(2) != 'delete' and - match.group(3).find(']') == -1): - # Split the size using space and arithmetic operators as delimiters. - # If any of the resulting tokens are not compile time constants then - # report the error. - tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) - is_const = True - skip_next = False - for tok in tokens: - if skip_next: - skip_next = False - continue - - if Search(r'sizeof\(.+\)', tok): continue - if Search(r'arraysize\(\w+\)', tok): continue - - tok = tok.lstrip('(') - tok = tok.rstrip(')') - if not tok: continue - if Match(r'\d+', tok): continue - if Match(r'0[xX][0-9a-fA-F]+', tok): continue - if Match(r'k[A-Z0-9]\w*', tok): continue - if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue - if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue - # A catch all for tricky sizeof cases, including 'sizeof expression', - # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' - # requires skipping the next token because we split on ' ' and '*'. - if tok.startswith('sizeof'): - skip_next = True - continue - is_const = False - break - if not is_const: - error(filename, linenum, 'runtime/arrays', 1, - 'Do not use variable-length arrays. Use an appropriately named ' - "('k' followed by CamelCase) compile-time constant for the size.") - - # Check for use of unnamed namespaces in header files. Registration - # macros are typically OK, so we allow use of "namespace {" on lines - # that end with backslashes. - if (IsHeaderExtension(file_extension) - and Search(r'\bnamespace\s*{', line) - and line[-1] != '\\'): - error(filename, linenum, 'build/namespaces', 4, - 'Do not use unnamed namespaces in header files. See ' - 'https://google.github.io/styleguide/cppguide.html#Namespaces' - ' for more information.') - - -def CheckGlobalStatic(filename, clean_lines, linenum, error): - """Check for unsafe global or static objects. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Match two lines at a time to support multiline declarations - if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): - line += clean_lines.elided[linenum + 1].strip() - - # Check for people declaring static/global STL strings at the top level. - # This is dangerous because the C++ language does not guarantee that - # globals with constructors are initialized before the first access, and - # also because globals can be destroyed when some threads are still running. - # TODO(unknown): Generalize this to also find static unique_ptr instances. - # TODO(unknown): File bugs for clang-tidy to find these. - match = Match( - r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +' - r'([a-zA-Z0-9_:]+)\b(.*)', - line) - - # Remove false positives: - # - String pointers (as opposed to values). - # string *pointer - # const string *pointer - # string const *pointer - # string *const pointer - # - # - Functions and template specializations. - # string Function(... - # string Class::Method(... - # - # - Operators. These are matched separately because operator names - # cross non-word boundaries, and trying to match both operators - # and functions at the same time would decrease accuracy of - # matching identifiers. - # string Class::operator*() - if (match and - not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and - not Search(r'\boperator\W', line) and - not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))): - if Search(r'\bconst\b', line): - error(filename, linenum, 'runtime/string', 4, - 'For a static/global string constant, use a C style string ' - 'instead: "%schar%s %s[]".' % - (match.group(1), match.group(2) or '', match.group(3))) - else: - error(filename, linenum, 'runtime/string', 4, - 'Static/global string variables are not permitted.') - - if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or - Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)): - error(filename, linenum, 'runtime/init', 4, - 'You seem to be initializing a member variable with itself.') - - -def CheckPrintf(filename, clean_lines, linenum, error): - """Check for printf related issues. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # When snprintf is used, the second argument shouldn't be a literal. - match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) - if match and match.group(2) != '0': - # If 2nd arg is zero, snprintf is used to calculate size. - error(filename, linenum, 'runtime/printf', 3, - 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' - 'to snprintf.' % (match.group(1), match.group(2))) - - # Check if some verboten C functions are being used. - if Search(r'\bsprintf\s*\(', line): - error(filename, linenum, 'runtime/printf', 5, - 'Never use sprintf. Use snprintf instead.') - match = Search(r'\b(strcpy|strcat)\s*\(', line) - if match: - error(filename, linenum, 'runtime/printf', 4, - 'Almost always, snprintf is better than %s' % match.group(1)) - - -def IsDerivedFunction(clean_lines, linenum): - """Check if current line contains an inherited function. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - Returns: - True if current line contains a function with "override" - virt-specifier. - """ - # Scan back a few lines for start of current function - for i in xrange(linenum, max(-1, linenum - 10), -1): - match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) - if match: - # Look for "override" after the matching closing parenthesis - line, _, closing_paren = CloseExpression( - clean_lines, i, len(match.group(1))) - return (closing_paren >= 0 and - Search(r'\boverride\b', line[closing_paren:])) - return False - - -def IsOutOfLineMethodDefinition(clean_lines, linenum): - """Check if current line contains an out-of-line method definition. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - Returns: - True if current line contains an out-of-line method definition. - """ - # Scan back a few lines for start of current function - for i in xrange(linenum, max(-1, linenum - 10), -1): - if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): - return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None - return False - - -def IsInitializerList(clean_lines, linenum): - """Check if current line is inside constructor initializer list. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - Returns: - True if current line appears to be inside constructor initializer - list, False otherwise. - """ - for i in xrange(linenum, 1, -1): - line = clean_lines.elided[i] - if i == linenum: - remove_function_body = Match(r'^(.*)\{\s*$', line) - if remove_function_body: - line = remove_function_body.group(1) - - if Search(r'\s:\s*\w+[({]', line): - # A lone colon tend to indicate the start of a constructor - # initializer list. It could also be a ternary operator, which - # also tend to appear in constructor initializer lists as - # opposed to parameter lists. - return True - if Search(r'\}\s*,\s*$', line): - # A closing brace followed by a comma is probably the end of a - # brace-initialized member in constructor initializer list. - return True - if Search(r'[{};]\s*$', line): - # Found one of the following: - # - A closing brace or semicolon, probably the end of the previous - # function. - # - An opening brace, probably the start of current class or namespace. - # - # Current line is probably not inside an initializer list since - # we saw one of those things without seeing the starting colon. - return False - - # Got to the beginning of the file without seeing the start of - # constructor initializer list. - return False - - -def CheckForNonConstReference(filename, clean_lines, linenum, - nesting_state, error): - """Check for non-const references. - - Separate from CheckLanguage since it scans backwards from current - line, instead of scanning forward. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - error: The function to call with any errors found. - """ - # Do nothing if there is no '&' on current line. - line = clean_lines.elided[linenum] - if '&' not in line: - return - - # If a function is inherited, current function doesn't have much of - # a choice, so any non-const references should not be blamed on - # derived function. - if IsDerivedFunction(clean_lines, linenum): - return - - # Don't warn on out-of-line method definitions, as we would warn on the - # in-line declaration, if it isn't marked with 'override'. - if IsOutOfLineMethodDefinition(clean_lines, linenum): - return - - # Long type names may be broken across multiple lines, usually in one - # of these forms: - # LongType - # ::LongTypeContinued &identifier - # LongType:: - # LongTypeContinued &identifier - # LongType< - # ...>::LongTypeContinued &identifier - # - # If we detected a type split across two lines, join the previous - # line to current line so that we can match const references - # accordingly. - # - # Note that this only scans back one line, since scanning back - # arbitrary number of lines would be expensive. If you have a type - # that spans more than 2 lines, please use a typedef. - if linenum > 1: - previous = None - if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): - # previous_line\n + ::current_line - previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', - clean_lines.elided[linenum - 1]) - elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): - # previous_line::\n + current_line - previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', - clean_lines.elided[linenum - 1]) - if previous: - line = previous.group(1) + line.lstrip() - else: - # Check for templated parameter that is split across multiple lines - endpos = line.rfind('>') - if endpos > -1: - (_, startline, startpos) = ReverseCloseExpression( - clean_lines, linenum, endpos) - if startpos > -1 and startline < linenum: - # Found the matching < on an earlier line, collect all - # pieces up to current line. - line = '' - for i in xrange(startline, linenum + 1): - line += clean_lines.elided[i].strip() - - # Check for non-const references in function parameters. A single '&' may - # found in the following places: - # inside expression: binary & for bitwise AND - # inside expression: unary & for taking the address of something - # inside declarators: reference parameter - # We will exclude the first two cases by checking that we are not inside a - # function body, including one that was just introduced by a trailing '{'. - # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. - if (nesting_state.previous_stack_top and - not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or - isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): - # Not at toplevel, not within a class, and not within a namespace - return - - # Avoid initializer lists. We only need to scan back from the - # current line for something that starts with ':'. - # - # We don't need to check the current line, since the '&' would - # appear inside the second set of parentheses on the current line as - # opposed to the first set. - if linenum > 0: - for i in xrange(linenum - 1, max(0, linenum - 10), -1): - previous_line = clean_lines.elided[i] - if not Search(r'[),]\s*$', previous_line): - break - if Match(r'^\s*:\s+\S', previous_line): - return - - # Avoid preprocessors - if Search(r'\\\s*$', line): - return - - # Avoid constructor initializer lists - if IsInitializerList(clean_lines, linenum): - return - - # We allow non-const references in a few standard places, like functions - # called "swap()" or iostream operators like "<<" or ">>". Do not check - # those function parameters. - # - # We also accept & in static_assert, which looks like a function but - # it's actually a declaration expression. - whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' - r'operator\s*[<>][<>]|' - r'static_assert|COMPILE_ASSERT' - r')\s*\(') - if Search(whitelisted_functions, line): - return - elif not Search(r'\S+\([^)]*$', line): - # Don't see a whitelisted function on this line. Actually we - # didn't see any function name on this line, so this is likely a - # multi-line parameter list. Try a bit harder to catch this case. - for i in xrange(2): - if (linenum > i and - Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): - return - - decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body - for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): - if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and - not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)): - error(filename, linenum, 'runtime/references', 2, - 'Is this a non-const reference? ' - 'If so, make const or use a pointer: ' + - ReplaceAll(' *<', '<', parameter)) - - -def CheckCasts(filename, clean_lines, linenum, error): - """Various cast related checks. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - # Check to see if they're using an conversion function cast. - # I just try to capture the most common basic types, though there are more. - # Parameterless conversion functions, such as bool(), are allowed as they are - # probably a member operator declaration or default constructor. - match = Search( - r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' - r'(int|float|double|bool|char|int32|uint32|int64|uint64)' - r'(\([^)].*)', line) - expecting_function = ExpectingFunctionArgs(clean_lines, linenum) - if match and not expecting_function: - matched_type = match.group(2) - - # matched_new_or_template is used to silence two false positives: - # - New operators - # - Template arguments with function types - # - # For template arguments, we match on types immediately following - # an opening bracket without any spaces. This is a fast way to - # silence the common case where the function type is the first - # template argument. False negative with less-than comparison is - # avoided because those operators are usually followed by a space. - # - # function // bracket + no space = false positive - # value < double(42) // bracket + space = true positive - matched_new_or_template = match.group(1) - - # Avoid arrays by looking for brackets that come after the closing - # parenthesis. - if Match(r'\([^()]+\)\s*\[', match.group(3)): - return - - # Other things to ignore: - # - Function pointers - # - Casts to pointer types - # - Placement new - # - Alias declarations - matched_funcptr = match.group(3) - if (matched_new_or_template is None and - not (matched_funcptr and - (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', - matched_funcptr) or - matched_funcptr.startswith('(*)'))) and - not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and - not Search(r'new\(\S+\)\s*' + matched_type, line)): - error(filename, linenum, 'readability/casting', 4, - 'Using deprecated casting style. ' - 'Use static_cast<%s>(...) instead' % - matched_type) - - if not expecting_function: - CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', - r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) - - # This doesn't catch all cases. Consider (const char * const)"hello". - # - # (char *) "foo" should always be a const_cast (reinterpret_cast won't - # compile). - if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', - r'\((char\s?\*+\s?)\)\s*"', error): - pass - else: - # Check pointer casts for other than string constants - CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', - r'\((\w+\s?\*+\s?)\)', error) - - # In addition, we look for people taking the address of a cast. This - # is dangerous -- casts can assign to temporaries, so the pointer doesn't - # point where you think. - # - # Some non-identifier character is required before the '&' for the - # expression to be recognized as a cast. These are casts: - # expression = &static_cast(temporary()); - # function(&(int*)(temporary())); - # - # This is not a cast: - # reference_type&(int* function_param); - match = Search( - r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' - r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) - if match: - # Try a better error message when the & is bound to something - # dereferenced by the casted pointer, as opposed to the casted - # pointer itself. - parenthesis_error = False - match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) - if match: - _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) - if x1 >= 0 and clean_lines.elided[y1][x1] == '(': - _, y2, x2 = CloseExpression(clean_lines, y1, x1) - if x2 >= 0: - extended_line = clean_lines.elided[y2][x2:] - if y2 < clean_lines.NumLines() - 1: - extended_line += clean_lines.elided[y2 + 1] - if Match(r'\s*(?:->|\[)', extended_line): - parenthesis_error = True - - if parenthesis_error: - error(filename, linenum, 'readability/casting', 4, - ('Are you taking an address of something dereferenced ' - 'from a cast? Wrapping the dereferenced expression in ' - 'parentheses will make the binding more obvious')) - else: - error(filename, linenum, 'runtime/casting', 4, - ('Are you taking an address of a cast? ' - 'This is dangerous: could be a temp var. ' - 'Take the address before doing the cast, rather than after')) - - -def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): - """Checks for a C-style cast by looking for the pattern. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - cast_type: The string for the C++ cast to recommend. This is either - reinterpret_cast, static_cast, or const_cast, depending. - pattern: The regular expression used to find C-style casts. - error: The function to call with any errors found. - - Returns: - True if an error was emitted. - False otherwise. - """ - line = clean_lines.elided[linenum] - match = Search(pattern, line) - if not match: - return False - - # Exclude lines with keywords that tend to look like casts - context = line[0:match.start(1) - 1] - if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): - return False - - # Try expanding current context to see if we one level of - # parentheses inside a macro. - if linenum > 0: - for i in xrange(linenum - 1, max(0, linenum - 5), -1): - context = clean_lines.elided[i] + context - if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): - return False - - # operator++(int) and operator--(int) - if context.endswith(' operator++') or context.endswith(' operator--'): - return False - - # A single unnamed argument for a function tends to look like old style cast. - # If we see those, don't issue warnings for deprecated casts. - remainder = line[match.end(0):] - if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', - remainder): - return False - - # At this point, all that should be left is actual casts. - error(filename, linenum, 'readability/casting', 4, - 'Using C-style cast. Use %s<%s>(...) instead' % - (cast_type, match.group(1))) - - return True - - -def ExpectingFunctionArgs(clean_lines, linenum): - """Checks whether where function type arguments are expected. - - Args: - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - - Returns: - True if the line at 'linenum' is inside something that expects arguments - of function types. - """ - line = clean_lines.elided[linenum] - return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or - (linenum >= 2 and - (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', - clean_lines.elided[linenum - 1]) or - Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', - clean_lines.elided[linenum - 2]) or - Search(r'\bstd::m?function\s*\<\s*$', - clean_lines.elided[linenum - 1])))) - - -_HEADERS_CONTAINING_TEMPLATES = ( - ('', ('deque',)), - ('', ('unary_function', 'binary_function', - 'plus', 'minus', 'multiplies', 'divides', 'modulus', - 'negate', - 'equal_to', 'not_equal_to', 'greater', 'less', - 'greater_equal', 'less_equal', - 'logical_and', 'logical_or', 'logical_not', - 'unary_negate', 'not1', 'binary_negate', 'not2', - 'bind1st', 'bind2nd', - 'pointer_to_unary_function', - 'pointer_to_binary_function', - 'ptr_fun', - 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', - 'mem_fun_ref_t', - 'const_mem_fun_t', 'const_mem_fun1_t', - 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', - 'mem_fun_ref', - )), - ('', ('numeric_limits',)), - ('', ('list',)), - ('', ('multimap',)), - ('', ('allocator', 'make_shared', 'make_unique', 'shared_ptr', - 'unique_ptr', 'weak_ptr')), - ('', ('queue', 'priority_queue',)), - ('', ('multiset',)), - ('', ('stack',)), - ('', ('char_traits', 'basic_string',)), - ('', ('tuple',)), - ('', ('unordered_map', 'unordered_multimap')), - ('', ('unordered_set', 'unordered_multiset')), - ('', ('pair',)), - ('', ('vector',)), - - # gcc extensions. - # Note: std::hash is their hash, ::hash is our hash - ('', ('hash_map', 'hash_multimap',)), - ('', ('hash_set', 'hash_multiset',)), - ('', ('slist',)), - ) - -_HEADERS_MAYBE_TEMPLATES = ( - ('', ('copy', 'max', 'min', 'min_element', 'sort', - 'transform', - )), - ('', ('forward', 'make_pair', 'move', 'swap')), - ) - -_RE_PATTERN_STRING = re.compile(r'\bstring\b') - -_re_pattern_headers_maybe_templates = [] -for _header, _templates in _HEADERS_MAYBE_TEMPLATES: - for _template in _templates: - # Match max(..., ...), max(..., ...), but not foo->max, foo.max or - # 'type::max()'. - _re_pattern_headers_maybe_templates.append( - (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), - _template, - _header)) -# Match set, but not foo->set, foo.set -_re_pattern_headers_maybe_templates.append( - (re.compile(r'[^>.]\bset\s*\<'), - 'set<>', - '')) -# Match 'map var' and 'std::map(...)', but not 'map(...)'' -_re_pattern_headers_maybe_templates.append( - (re.compile(r'(std\b::\bmap\s*\<)|(^(std\b::\b)map\b\(\s*\<)'), - 'map<>', - '')) - -# Other scripts may reach in and modify this pattern. -_re_pattern_templates = [] -for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: - for _template in _templates: - _re_pattern_templates.append( - (re.compile(r'(\<|\b)' + _template + r'\s*\<'), - _template + '<>', - _header)) - - -def FilesBelongToSameModule(filename_cc, filename_h): - """Check if these two filenames belong to the same module. - - The concept of a 'module' here is a as follows: - foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the - same 'module' if they are in the same directory. - some/path/public/xyzzy and some/path/internal/xyzzy are also considered - to belong to the same module here. - - If the filename_cc contains a longer path than the filename_h, for example, - '/absolute/path/to/base/sysinfo.cc', and this file would include - 'base/sysinfo.h', this function also produces the prefix needed to open the - header. This is used by the caller of this function to more robustly open the - header file. We don't have access to the real include paths in this context, - so we need this guesswork here. - - Known bugs: tools/base/bar.cc and base/bar.h belong to the same module - according to this implementation. Because of this, this function gives - some false positives. This should be sufficiently rare in practice. - - Args: - filename_cc: is the path for the source (e.g. .cc) file - filename_h: is the path for the header path - - Returns: - Tuple with a bool and a string: - bool: True if filename_cc and filename_h belong to the same module. - string: the additional prefix needed to open the header file. - """ - fileinfo_cc = FileInfo(filename_cc) - if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions(): - return (False, '') - - fileinfo_h = FileInfo(filename_h) - if not IsHeaderExtension(fileinfo_h.Extension().lstrip('.')): - return (False, '') - - filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))] - matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()) - if matched_test_suffix: - filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] - - filename_cc = filename_cc.replace('/public/', '/') - filename_cc = filename_cc.replace('/internal/', '/') - - filename_h = filename_h[:-(len(fileinfo_h.Extension()))] - if filename_h.endswith('-inl'): - filename_h = filename_h[:-len('-inl')] - filename_h = filename_h.replace('/public/', '/') - filename_h = filename_h.replace('/internal/', '/') - - files_belong_to_same_module = filename_cc.endswith(filename_h) - common_path = '' - if files_belong_to_same_module: - common_path = filename_cc[:-len(filename_h)] - return files_belong_to_same_module, common_path - - -def UpdateIncludeState(filename, include_dict, io=codecs): - """Fill up the include_dict with new includes found from the file. - - Args: - filename: the name of the header to read. - include_dict: a dictionary in which the headers are inserted. - io: The io factory to use to read the file. Provided for testability. - - Returns: - True if a header was successfully added. False otherwise. - """ - headerfile = None - try: - with io.open(filename, 'r', 'utf8', 'replace') as headerfile: - linenum = 0 - for line in headerfile: - linenum += 1 - clean_line = CleanseComments(line) - match = _RE_PATTERN_INCLUDE.search(clean_line) - if match: - include = match.group(2) - include_dict.setdefault(include, linenum) - return True - except IOError: - return False - - - -def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, - io=codecs): - """Reports for missing stl includes. - - This function will output warnings to make sure you are including the headers - necessary for the stl containers and functions that you use. We only give one - reason to include a header. For example, if you use both equal_to<> and - less<> in a .h file, only one (the latter in the file) of these will be - reported as a reason to include the . - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - include_state: An _IncludeState instance. - error: The function to call with any errors found. - io: The IO factory to use to read the header file. Provided for unittest - injection. - """ - required = {} # A map of header name to linenumber and the template entity. - # Example of required: { '': (1219, 'less<>') } - - for linenum in xrange(clean_lines.NumLines()): - line = clean_lines.elided[linenum] - if not line or line[0] == '#': - continue - - # String is special -- it is a non-templatized type in STL. - matched = _RE_PATTERN_STRING.search(line) - if matched: - # Don't warn about strings in non-STL namespaces: - # (We check only the first match per line; good enough.) - prefix = line[:matched.start()] - if prefix.endswith('std::') or not prefix.endswith('::'): - required[''] = (linenum, 'string') - - for pattern, template, header in _re_pattern_headers_maybe_templates: - if pattern.search(line): - required[header] = (linenum, template) - - # The following function is just a speed up, no semantics are changed. - if not '<' in line: # Reduces the cpu time usage by skipping lines. - continue - - for pattern, template, header in _re_pattern_templates: - matched = pattern.search(line) - if matched: - # Don't warn about IWYU in non-STL namespaces: - # (We check only the first match per line; good enough.) - prefix = line[:matched.start()] - if prefix.endswith('std::') or not prefix.endswith('::'): - required[header] = (linenum, template) - - # The policy is that if you #include something in foo.h you don't need to - # include it again in foo.cc. Here, we will look at possible includes. - # Let's flatten the include_state include_list and copy it into a dictionary. - include_dict = dict([item for sublist in include_state.include_list - for item in sublist]) - - # Did we find the header for this file (if any) and successfully load it? - header_found = False - - # Use the absolute path so that matching works properly. - abs_filename = FileInfo(filename).FullName() - - # For Emacs's flymake. - # If cpplint is invoked from Emacs's flymake, a temporary file is generated - # by flymake and that file name might end with '_flymake.cc'. In that case, - # restore original file name here so that the corresponding header file can be - # found. - # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' - # instead of 'foo_flymake.h' - abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) - - # include_dict is modified during iteration, so we iterate over a copy of - # the keys. - header_keys = list(include_dict.keys()) - for header in header_keys: - (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) - fullpath = common_path + header - if same_module and UpdateIncludeState(fullpath, include_dict, io): - header_found = True - - # If we can't find the header file for a .cc, assume it's because we don't - # know where to look. In that case we'll give up as we're not sure they - # didn't include it in the .h file. - # TODO(unknown): Do a better job of finding .h files so we are confident that - # not having the .h file means there isn't one. - if not header_found: - for extension in GetNonHeaderExtensions(): - if filename.endswith('.' + extension): - return - - # All the lines have been processed, report the errors found. - for required_header_unstripped in sorted(required, key=required.__getitem__): - template = required[required_header_unstripped][1] - if required_header_unstripped.strip('<>"') not in include_dict: - error(filename, required[required_header_unstripped][0], - 'build/include_what_you_use', 4, - 'Add #include ' + required_header_unstripped + ' for ' + template) - - -_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') - - -def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): - """Check that make_pair's template arguments are deduced. - - G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are - specified explicitly, and such use isn't intended in any case. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) - if match: - error(filename, linenum, 'build/explicit_make_pair', - 4, # 4 = high confidence - 'For C++11-compatibility, omit template arguments from make_pair' - ' OR use pair directly OR if appropriate, construct a pair directly') - - -def CheckRedundantVirtual(filename, clean_lines, linenum, error): - """Check if line contains a redundant "virtual" function-specifier. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - # Look for "virtual" on current line. - line = clean_lines.elided[linenum] - virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) - if not virtual: return - - # Ignore "virtual" keywords that are near access-specifiers. These - # are only used in class base-specifier and do not apply to member - # functions. - if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or - Match(r'^\s+(public|protected|private)\b', virtual.group(3))): - return - - # Ignore the "virtual" keyword from virtual base classes. Usually - # there is a column on the same line in these cases (virtual base - # classes are rare in google3 because multiple inheritance is rare). - if Match(r'^.*[^:]:[^:].*$', line): return - - # Look for the next opening parenthesis. This is the start of the - # parameter list (possibly on the next line shortly after virtual). - # TODO(unknown): doesn't work if there are virtual functions with - # decltype() or other things that use parentheses, but csearch suggests - # that this is rare. - end_col = -1 - end_line = -1 - start_col = len(virtual.group(2)) - for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): - line = clean_lines.elided[start_line][start_col:] - parameter_list = Match(r'^([^(]*)\(', line) - if parameter_list: - # Match parentheses to find the end of the parameter list - (_, end_line, end_col) = CloseExpression( - clean_lines, start_line, start_col + len(parameter_list.group(1))) - break - start_col = 0 - - if end_col < 0: - return # Couldn't find end of parameter list, give up - - # Look for "override" or "final" after the parameter list - # (possibly on the next few lines). - for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): - line = clean_lines.elided[i][end_col:] - match = Search(r'\b(override|final)\b', line) - if match: - error(filename, linenum, 'readability/inheritance', 4, - ('"virtual" is redundant since function is ' - 'already declared as "%s"' % match.group(1))) - - # Set end_col to check whole lines after we are done with the - # first line. - end_col = 0 - if Search(r'[^\w]\s*$', line): - break - - -def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): - """Check if line contains a redundant "override" or "final" virt-specifier. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - # Look for closing parenthesis nearby. We need one to confirm where - # the declarator ends and where the virt-specifier starts to avoid - # false positives. - line = clean_lines.elided[linenum] - declarator_end = line.rfind(')') - if declarator_end >= 0: - fragment = line[declarator_end:] - else: - if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: - fragment = line - else: - return - - # Check that at most one of "override" or "final" is present, not both - if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): - error(filename, linenum, 'readability/inheritance', 4, - ('"override" is redundant since function is ' - 'already declared as "final"')) - - - - -# Returns true if we are at a new block, and it is directly -# inside of a namespace. -def IsBlockInNameSpace(nesting_state, is_forward_declaration): - """Checks that the new block is directly in a namespace. - - Args: - nesting_state: The _NestingState object that contains info about our state. - is_forward_declaration: If the class is a forward declared class. - Returns: - Whether or not the new block is directly in a namespace. - """ - if is_forward_declaration: - return len(nesting_state.stack) >= 1 and ( - isinstance(nesting_state.stack[-1], _NamespaceInfo)) - - - return (len(nesting_state.stack) > 1 and - nesting_state.stack[-1].check_namespace_indentation and - isinstance(nesting_state.stack[-2], _NamespaceInfo)) - - -def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, - raw_lines_no_comments, linenum): - """This method determines if we should apply our namespace indentation check. - - Args: - nesting_state: The current nesting state. - is_namespace_indent_item: If we just put a new class on the stack, True. - If the top of the stack is not a class, or we did not recently - add the class, False. - raw_lines_no_comments: The lines without the comments. - linenum: The current line number we are processing. - - Returns: - True if we should apply our namespace indentation check. Currently, it - only works for classes and namespaces inside of a namespace. - """ - - is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, - linenum) - - if not (is_namespace_indent_item or is_forward_declaration): - return False - - # If we are in a macro, we do not want to check the namespace indentation. - if IsMacroDefinition(raw_lines_no_comments, linenum): - return False - - return IsBlockInNameSpace(nesting_state, is_forward_declaration) - - -# Call this method if the line is directly inside of a namespace. -# If the line above is blank (excluding comments) or the start of -# an inner namespace, it cannot be indented. -def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, - error): - line = raw_lines_no_comments[linenum] - if Match(r'^\s+', line): - error(filename, linenum, 'runtime/indentation_namespace', 4, - 'Do not indent within a namespace') - - -def ProcessLine(filename, file_extension, clean_lines, line, - include_state, function_state, nesting_state, error, - extra_check_functions=None): - """Processes a single line in the file. - - Args: - filename: Filename of the file that is being processed. - file_extension: The extension (dot not included) of the file. - clean_lines: An array of strings, each representing a line of the file, - with comments stripped. - line: Number of line being processed. - include_state: An _IncludeState instance in which the headers are inserted. - function_state: A _FunctionState instance which counts function lines, etc. - nesting_state: A NestingState instance which maintains information about - the current stack of nested blocks being parsed. - error: A callable to which errors are reported, which takes 4 arguments: - filename, line number, error level, and message - extra_check_functions: An array of additional check functions that will be - run on each source line. Each function takes 4 - arguments: filename, clean_lines, line, error - """ - raw_lines = clean_lines.raw_lines - ParseNolintSuppressions(filename, raw_lines[line], line, error) - nesting_state.Update(filename, clean_lines, line, error) - CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, - error) - if nesting_state.InAsmBlock(): return - CheckForFunctionLengths(filename, clean_lines, line, function_state, error) - CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) - CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) - CheckLanguage(filename, clean_lines, line, file_extension, include_state, - nesting_state, error) - CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) - CheckForNonStandardConstructs(filename, clean_lines, line, - nesting_state, error) - CheckVlogArguments(filename, clean_lines, line, error) - CheckPosixThreading(filename, clean_lines, line, error) - CheckInvalidIncrement(filename, clean_lines, line, error) - CheckMakePairUsesDeduction(filename, clean_lines, line, error) - CheckRedundantVirtual(filename, clean_lines, line, error) - CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) - if extra_check_functions: - for check_fn in extra_check_functions: - check_fn(filename, clean_lines, line, error) - -def FlagCxx11Features(filename, clean_lines, linenum, error): - """Flag those c++11 features that we only allow in certain places. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) - - # Flag unapproved C++ TR1 headers. - if include and include.group(1).startswith('tr1/'): - error(filename, linenum, 'build/c++tr1', 5, - ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1)) - - # Flag unapproved C++11 headers. - if include and include.group(1) in ('cfenv', - 'condition_variable', - 'fenv.h', - 'future', - 'mutex', - 'thread', - 'chrono', - 'ratio', - 'regex', - 'system_error', - ): - error(filename, linenum, 'build/c++11', 5, - ('<%s> is an unapproved C++11 header.') % include.group(1)) - - # The only place where we need to worry about C++11 keywords and library - # features in preprocessor directives is in macro definitions. - if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return - - # These are classes and free functions. The classes are always - # mentioned as std::*, but we only catch the free functions if - # they're not found by ADL. They're alphabetical by header. - for top_name in ( - # type_traits - 'alignment_of', - 'aligned_union', - ): - if Search(r'\bstd::%s\b' % top_name, line): - error(filename, linenum, 'build/c++11', 5, - ('std::%s is an unapproved C++11 class or function. Send c-style ' - 'an example of where it would make your code more readable, and ' - 'they may let you use it.') % top_name) - - -def FlagCxx14Features(filename, clean_lines, linenum, error): - """Flag those C++14 features that we restrict. - - Args: - filename: The name of the current file. - clean_lines: A CleansedLines instance containing the file. - linenum: The number of the line to check. - error: The function to call with any errors found. - """ - line = clean_lines.elided[linenum] - - include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) - - # Flag unapproved C++14 headers. - if include and include.group(1) in ('scoped_allocator', 'shared_mutex'): - error(filename, linenum, 'build/c++14', 5, - ('<%s> is an unapproved C++14 header.') % include.group(1)) - - -def ProcessFileData(filename, file_extension, lines, error, - extra_check_functions=None): - """Performs lint checks and reports any errors to the given error function. - - Args: - filename: Filename of the file that is being processed. - file_extension: The extension (dot not included) of the file. - lines: An array of strings, each representing a line of the file, with the - last element being empty if the file is terminated with a newline. - error: A callable to which errors are reported, which takes 4 arguments: - filename, line number, error level, and message - extra_check_functions: An array of additional check functions that will be - run on each source line. Each function takes 4 - arguments: filename, clean_lines, line, error - """ - lines = (['// marker so line numbers and indices both start at 1'] + lines + - ['// marker so line numbers end in a known way']) - - include_state = _IncludeState() - function_state = _FunctionState() - nesting_state = NestingState() - - ResetNolintSuppressions() - - CheckForCopyright(filename, lines, error) - ProcessGlobalSuppresions(lines) - RemoveMultiLineComments(filename, lines, error) - clean_lines = CleansedLines(lines) - - if IsHeaderExtension(file_extension): - CheckForHeaderGuard(filename, clean_lines, error) - - for line in xrange(clean_lines.NumLines()): - ProcessLine(filename, file_extension, clean_lines, line, - include_state, function_state, nesting_state, error, - extra_check_functions) - FlagCxx11Features(filename, clean_lines, line, error) - nesting_state.CheckCompletedBlocks(filename, error) - - CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) - - # Check that the .cc file has included its header if it exists. - if _IsSourceExtension(file_extension): - CheckHeaderFileIncluded(filename, include_state, error) - - # We check here rather than inside ProcessLine so that we see raw - # lines rather than "cleaned" lines. - CheckForBadCharacters(filename, lines, error) - - CheckForNewlineAtEOF(filename, lines, error) - - CheckInlineHeader(filename, include_state, error) - -def ProcessConfigOverrides(filename): - """ Loads the configuration files and processes the config overrides. - - Args: - filename: The name of the file being processed by the linter. - - Returns: - False if the current |filename| should not be processed further. - """ - - abs_filename = os.path.abspath(filename) - cfg_filters = [] - keep_looking = True - while keep_looking: - abs_path, base_name = os.path.split(abs_filename) - if not base_name: - break # Reached the root directory. - - cfg_file = os.path.join(abs_path, ".cpplint") - abs_filename = abs_path - if not os.path.isfile(cfg_file): - continue - - try: - with open(cfg_file) as file_handle: - for line in file_handle: - line, _, _ = line.partition('#') # Remove comments. - if not line.strip(): - continue - - name, _, val = line.partition('=') - name = name.strip() - val = val.strip() - if name == 'set noparent': - keep_looking = False - elif name == 'filter': - cfg_filters.append(val) - elif name == 'exclude_files': - # When matching exclude_files pattern, use the base_name of - # the current file name or the directory name we are processing. - # For example, if we are checking for lint errors in /foo/bar/baz.cc - # and we found the .cfg file at /foo/CPPLINT.cfg, then the config - # file's "exclude_files" filter is meant to be checked against "bar" - # and not "baz" nor "bar/baz.cc". - if base_name: - pattern = re.compile(val) - if pattern.match(base_name): - if _cpplint_state.quiet: - # Suppress "Ignoring file" warning when using --quiet. - return False - _cpplint_state.PrintInfo('Ignoring "%s": file excluded by "%s". ' - 'File path component "%s" matches ' - 'pattern "%s"\n' % - (filename, cfg_file, base_name, val)) - return False - elif name == 'linelength': - global _line_length - try: - _line_length = int(val) - except ValueError: - _cpplint_state.PrintError('Line length must be numeric.') - elif name == 'extensions': - ProcessExtensionsOption(val) - elif name == 'root': - global _root - # root directories are specified relative to CPPLINT.cfg dir. - _root = os.path.join(os.path.dirname(cfg_file), val) - elif name == 'headers': - ProcessHppHeadersOption(val) - else: - _cpplint_state.PrintError( - 'Invalid configuration option (%s) in file %s\n' % - (name, cfg_file)) - - except IOError: - _cpplint_state.PrintError( - "Skipping config file '%s': Can't open for reading\n" % cfg_file) - keep_looking = False - - # Apply all the accumulated filters in reverse order (top-level directory - # config options having the least priority). - for cfg_filter in reversed(cfg_filters): - _AddFilters(cfg_filter) - - return True - - -def ProcessFile(filename, vlevel, extra_check_functions=None): - """Does google-lint on a single file. - - Args: - filename: The name of the file to parse. - - vlevel: The level of errors to report. Every error of confidence - >= verbose_level will be reported. 0 is a good default. - - extra_check_functions: An array of additional check functions that will be - run on each source line. Each function takes 4 - arguments: filename, clean_lines, line, error - """ - - _SetVerboseLevel(vlevel) - _BackupFilters() - old_errors = _cpplint_state.error_count - - if not ProcessConfigOverrides(filename): - _RestoreFilters() - return - - lf_lines = [] - crlf_lines = [] - try: - # Support the UNIX convention of using "-" for stdin. Note that - # we are not opening the file with universal newline support - # (which codecs doesn't support anyway), so the resulting lines do - # contain trailing '\r' characters if we are reading a file that - # has CRLF endings. - # If after the split a trailing '\r' is present, it is removed - # below. - if filename == '-': - lines = codecs.StreamReaderWriter(sys.stdin, - codecs.getreader('utf8'), - codecs.getwriter('utf8'), - 'replace').read().split('\n') - else: - with codecs.open(filename, 'r', 'utf8', 'replace') as target_file: - lines = target_file.read().split('\n') - - # Remove trailing '\r'. - # The -1 accounts for the extra trailing blank line we get from split() - for linenum in range(len(lines) - 1): - if lines[linenum].endswith('\r'): - lines[linenum] = lines[linenum].rstrip('\r') - crlf_lines.append(linenum + 1) - else: - lf_lines.append(linenum + 1) - - except IOError: - _cpplint_state.PrintError( - "Skipping input '%s': Can't open for reading\n" % filename) - _RestoreFilters() - return - - # Note, if no dot is found, this will give the entire filename as the ext. - file_extension = filename[filename.rfind('.') + 1:] - - # When reading from stdin, the extension is unknown, so no cpplint tests - # should rely on the extension. - if filename != '-' and file_extension not in GetAllExtensions(): - _cpplint_state.PrintError('Ignoring %s; not a valid file name ' - '(%s)\n' % (filename, ', '.join(GetAllExtensions()))) - else: - ProcessFileData(filename, file_extension, lines, Error, - extra_check_functions) - - # If end-of-line sequences are a mix of LF and CR-LF, issue - # warnings on the lines with CR. - # - # Don't issue any warnings if all lines are uniformly LF or CR-LF, - # since critique can handle these just fine, and the style guide - # doesn't dictate a particular end of line sequence. - # - # We can't depend on os.linesep to determine what the desired - # end-of-line sequence should be, since that will return the - # server-side end-of-line sequence. - if lf_lines and crlf_lines: - # Warn on every line with CR. An alternative approach might be to - # check whether the file is mostly CRLF or just LF, and warn on the - # minority, we bias toward LF here since most tools prefer LF. - for linenum in crlf_lines: - Error(filename, linenum, 'whitespace/newline', 1, - 'Unexpected \\r (^M) found; better to use only \\n') - - # Suppress printing anything if --quiet was passed unless the error - # count has increased after processing this file. - if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count: - _cpplint_state.PrintInfo('Done processing %s\n' % filename) - _RestoreFilters() - - -def PrintUsage(message): - """Prints a brief usage string and exits, optionally with an error message. - - Args: - message: The optional error message. - """ - sys.stderr.write(_USAGE % (list(GetAllExtensions()), - ','.join(list(GetAllExtensions())), - GetHeaderExtensions(), - ','.join(GetHeaderExtensions()))) - - if message: - sys.exit('\nFATAL ERROR: ' + message) - else: - sys.exit(0) - -def PrintVersion(): - sys.stdout.write('Cpplint fork (https://github.com/cpplint/cpplint)\n') - sys.stdout.write('cpplint ' + __VERSION__ + '\n') - sys.stdout.write('Python ' + sys.version + '\n') - sys.exit(0) - -def PrintCategories(): - """Prints a list of all the error-categories used by error messages. - - These are the categories used to filter messages via --filter. - """ - sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) - sys.exit(0) - - -def ParseArguments(args): - """Parses the command line arguments. - - This may set the output format and verbosity level as side-effects. - - Args: - args: The command line arguments: - - Returns: - The list of filenames to lint. - """ - try: - (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', - 'v=', - 'version', - 'counting=', - 'filter=', - 'root=', - 'repository=', - 'linelength=', - 'extensions=', - 'exclude=', - 'recursive', - 'headers=', - 'quiet']) - except getopt.GetoptError: - PrintUsage('Invalid arguments.') - - verbosity = _VerboseLevel() - output_format = _OutputFormat() - filters = '' - quiet = _Quiet() - counting_style = '' - recursive = False - - for (opt, val) in opts: - if opt == '--help': - PrintUsage(None) - if opt == '--version': - PrintVersion() - elif opt == '--output': - if val not in ('emacs', 'vs7', 'eclipse', 'junit'): - PrintUsage('The only allowed output formats are emacs, vs7, eclipse ' - 'and junit.') - output_format = val - elif opt == '--quiet': - quiet = True - elif opt == '--verbose' or opt == '--v': - verbosity = int(val) - elif opt == '--filter': - filters = val - if not filters: - PrintCategories() - elif opt == '--counting': - if val not in ('total', 'toplevel', 'detailed'): - PrintUsage('Valid counting options are total, toplevel, and detailed') - counting_style = val - elif opt == '--root': - global _root - _root = val - elif opt == '--repository': - global _repository - _repository = val - elif opt == '--linelength': - global _line_length - try: - _line_length = int(val) - except ValueError: - PrintUsage('Line length must be digits.') - elif opt == '--exclude': - global _excludes - if not _excludes: - _excludes = set() - _excludes.update(glob.glob(val)) - elif opt == '--extensions': - ProcessExtensionsOption(val) - elif opt == '--headers': - ProcessHppHeadersOption(val) - elif opt == '--recursive': - recursive = True - - if not filenames: - PrintUsage('No files were specified.') - - if recursive: - filenames = _ExpandDirectories(filenames) - - if _excludes: - filenames = _FilterExcludedFiles(filenames) - - _SetOutputFormat(output_format) - _SetQuiet(quiet) - _SetVerboseLevel(verbosity) - _SetFilters(filters) - _SetCountingStyle(counting_style) - - return filenames - -def _ExpandDirectories(filenames): - """Searches a list of filenames and replaces directories in the list with - all files descending from those directories. Files with extensions not in - the valid extensions list are excluded. - - Args: - filenames: A list of files or directories - - Returns: - A list of all files that are members of filenames or descended from a - directory in filenames - """ - expanded = set() - for filename in filenames: - if not os.path.isdir(filename): - expanded.add(filename) - continue - - for root, _, files in os.walk(filename): - for loopfile in files: - fullname = os.path.join(root, loopfile) - if fullname.startswith('.' + os.path.sep): - fullname = fullname[len('.' + os.path.sep):] - expanded.add(fullname) - - filtered = [] - for filename in expanded: - if os.path.splitext(filename)[1][1:] in GetAllExtensions(): - filtered.append(filename) - return filtered - -def _FilterExcludedFiles(fnames): - """Filters out files listed in the --exclude command line switch. File paths - in the switch are evaluated relative to the current working directory - """ - exclude_paths = [os.path.abspath(f) for f in _excludes] - # because globbing does not work recursively, exclude all subpath of all excluded entries - return [f for f in fnames - if not any(e for e in exclude_paths - if _IsParentOrSame(e, os.path.abspath(f)))] - -def _IsParentOrSame(parent, child): - """Return true if child is subdirectory of parent. - Assumes both paths are absolute and don't contain symlinks. - """ - parent = os.path.normpath(parent) - child = os.path.normpath(child) - if parent == child: - return True - - prefix = os.path.commonprefix([parent, child]) - if prefix != parent: - return False - # Note: os.path.commonprefix operates on character basis, so - # take extra care of situations like '/foo/ba' and '/foo/bar/baz' - child_suffix = child[len(prefix):] - child_suffix = child_suffix.lstrip(os.sep) - return child == os.path.join(prefix, child_suffix) - -def main(): - filenames = ParseArguments(sys.argv[1:]) - backup_err = sys.stderr - try: - # Change stderr to write with replacement characters so we don't die - # if we try to print something containing non-ASCII characters. - sys.stderr = codecs.StreamReader(sys.stderr, 'replace') - - _cpplint_state.ResetErrorCounts() - for filename in filenames: - ProcessFile(filename, _cpplint_state.verbose_level) - # If --quiet is passed, suppress printing error count unless there are errors. - if not _cpplint_state.quiet or _cpplint_state.error_count > 0: - _cpplint_state.PrintErrorCounts() - - if _cpplint_state.output_format == 'junit': - sys.stderr.write(_cpplint_state.FormatJUnitXML()) - - finally: - sys.stderr = backup_err - - sys.exit(_cpplint_state.error_count > 0) - - -if __name__ == '__main__': - main() diff --git a/tools/eslint-rules/alphabetize-errors.js b/tools/eslint-rules/alphabetize-errors.js deleted file mode 100644 index b2dcacbb86681614bf09f9b8c17022e1f0d67d64..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/alphabetize-errors.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const { isDefiningError } = require('./rules-utils.js'); - -const prefix = 'Out of ASCIIbetical order - '; -const opStr = ' >= '; - -function errorForNode(node) { - return node.expression.arguments[0].value; -} - -module.exports = { - create: function(context) { - let previousNode; - return { - ExpressionStatement: function(node) { - if (!isDefiningError(node)) return; - if (!previousNode) { - previousNode = node; - return; - } - const prev = errorForNode(previousNode); - const curr = errorForNode(node); - previousNode = node; - if (prev >= curr) { - const message = [prefix, prev, opStr, curr].join(''); - context.report({ node, message }); - } - } - }; - } -}; diff --git a/tools/eslint-rules/crypto-check.js b/tools/eslint-rules/crypto-check.js deleted file mode 100644 index 4704b550a360e971a16be2661a25a38d7378cf6f..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/crypto-check.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview Check that common.hasCrypto is used if crypto, tls, - * https, or http2 modules are required. - * - * This rule can be ignored using // eslint-disable-line crypto-check - * - * @author Daniel Bevenius - */ -'use strict'; - -const utils = require('./rules-utils.js'); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -const msg = 'Please add a hasCrypto check to allow this test to be skipped ' + - 'when Node is built "--without-ssl".'; - -const cryptoModules = ['crypto', 'http2']; -const requireModules = cryptoModules.concat(['tls', 'https']); -const bindingModules = cryptoModules.concat(['tls_wrap']); - -module.exports = function(context) { - const missingCheckNodes = []; - const requireNodes = []; - let commonModuleNode = null; - let hasSkipCall = false; - - function testCryptoUsage(node) { - if (utils.isRequired(node, requireModules) || - utils.isBinding(node, bindingModules)) { - requireNodes.push(node); - } - - if (utils.isCommonModule(node)) { - commonModuleNode = node; - } - } - - function testIfStatement(node) { - if (node.test.argument === undefined) { - return; - } - if (isCryptoCheck(node.test.argument)) { - checkCryptoCall(node); - } - } - - function isCryptoCheck(node) { - return utils.usesCommonProperty(node, ['hasCrypto', 'hasFipsCrypto']); - } - - function checkCryptoCall(node) { - if (utils.inSkipBlock(node)) { - hasSkipCall = true; - } else { - missingCheckNodes.push(node); - } - } - - function testMemberExpression(node) { - if (isCryptoCheck(node)) { - checkCryptoCall(node); - } - } - - function reportIfMissingCheck() { - if (hasSkipCall) { - // There is a skip, which is good, but verify that the require() calls - // in question come after at least one check. - if (missingCheckNodes.length > 0) { - requireNodes.forEach((requireNode) => { - const beforeAllChecks = missingCheckNodes.every((checkNode) => { - return requireNode.range[0] < checkNode.range[0]; - }); - - if (beforeAllChecks) { - context.report({ - node: requireNode, - message: msg - }); - } - }); - } - return; - } - - if (requireNodes.length > 0) { - if (missingCheckNodes.length > 0) { - report(missingCheckNodes); - } else { - report(requireNodes); - } - } - } - - function report(nodes) { - nodes.forEach((node) => { - context.report({ - node, - message: msg, - fix: (fixer) => { - if (commonModuleNode) { - return fixer.insertTextAfter( - commonModuleNode, - '\nif (!common.hasCrypto) {' + - ' common.skip("missing crypto");' + - '}' - ); - } - } - }); - }); - } - - return { - 'CallExpression': (node) => testCryptoUsage(node), - 'IfStatement:exit': (node) => testIfStatement(node), - 'MemberExpression:exit': (node) => testMemberExpression(node), - 'Program:exit': () => reportIfMissingCheck() - }; -}; - -module.exports.meta = { - fixable: 'code' -}; diff --git a/tools/eslint-rules/documented-errors.js b/tools/eslint-rules/documented-errors.js deleted file mode 100644 index dad60367cd958a00b2fdf76fe05f1586983aee77..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/documented-errors.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const { isDefiningError } = require('./rules-utils.js'); - -const doc = fs.readFileSync(path.resolve(__dirname, '../../doc/api/errors.md'), - 'utf8'); - -function isInDoc(code) { - return doc.includes(`### \`${code}\``); -} - -function includesAnchor(code) { - return doc.includes(``); -} - -function errorForNode(node) { - return node.expression.arguments[0].value; -} - -module.exports = { - create: function(context) { - return { - ExpressionStatement: function(node) { - if (!isDefiningError(node) || !errorForNode(node)) return; - const code = errorForNode(node); - if (!isInDoc(code)) { - const message = `"${code}" is not documented in doc/api/errors.md`; - context.report({ node, message }); - } - if (!includesAnchor(code)) { - const message = - `doc/api/errors.md does not have an anchor for "${code}"`; - context.report({ node, message }); - } - } - }; - } -}; diff --git a/tools/eslint-rules/eslint-check.js b/tools/eslint-rules/eslint-check.js deleted file mode 100644 index 0edf7d2899cbf9891e8d7cab6d3daa443646912e..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/eslint-check.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Check that common.skipIfEslintMissing is used if - * the eslint module is required. - */ -'use strict'; - -const utils = require('./rules-utils.js'); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -const msg = 'Please add a skipIfEslintMissing() call to allow this test to ' + - 'be skipped when Node.js is built from a source tarball.'; - -module.exports = function(context) { - const missingCheckNodes = []; - let commonModuleNode = null; - let hasEslintCheck = false; - - function testEslintUsage(context, node) { - if (utils.isRequired(node, ['../../tools/node_modules/eslint'])) { - missingCheckNodes.push(node); - } - - if (utils.isCommonModule(node)) { - commonModuleNode = node; - } - } - - function checkMemberExpression(context, node) { - if (utils.usesCommonProperty(node, ['skipIfEslintMissing'])) { - hasEslintCheck = true; - } - } - - function reportIfMissing(context) { - if (!hasEslintCheck) { - missingCheckNodes.forEach((node) => { - context.report({ - node, - message: msg, - fix: (fixer) => { - if (commonModuleNode) { - return fixer.insertTextAfter( - commonModuleNode, - '\ncommon.skipIfEslintMissing();' - ); - } - } - }); - }); - } - } - - return { - 'CallExpression': (node) => testEslintUsage(context, node), - 'MemberExpression': (node) => checkMemberExpression(context, node), - 'Program:exit': () => reportIfMissing(context) - }; -}; - -module.exports.meta = { - fixable: 'code' -}; diff --git a/tools/eslint-rules/inspector-check.js b/tools/eslint-rules/inspector-check.js deleted file mode 100644 index bb5dc27bff5cef73c4cca20b99401a3bd4a7ca20..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/inspector-check.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Check that common.skipIfInspectorDisabled is used if - * the inspector module is required. - * @author Daniel Bevenius - */ -'use strict'; - -const utils = require('./rules-utils.js'); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -const msg = 'Please add a skipIfInspectorDisabled() call to allow this ' + - 'test to be skipped when Node is built \'--without-inspector\'.'; - -module.exports = function(context) { - const missingCheckNodes = []; - let commonModuleNode = null; - let hasInspectorCheck = false; - - function testInspectorUsage(context, node) { - if (utils.isRequired(node, ['inspector'])) { - missingCheckNodes.push(node); - } - - if (utils.isCommonModule(node)) { - commonModuleNode = node; - } - } - - function checkMemberExpression(context, node) { - if (utils.usesCommonProperty(node, ['skipIfInspectorDisabled'])) { - hasInspectorCheck = true; - } - } - - function reportIfMissing(context) { - if (!hasInspectorCheck) { - missingCheckNodes.forEach((node) => { - context.report({ - node, - message: msg, - fix: (fixer) => { - if (commonModuleNode) { - return fixer.insertTextAfter( - commonModuleNode, - '\ncommon.skipIfInspectorDisabled();' - ); - } - } - }); - }); - } - } - - return { - 'CallExpression': (node) => testInspectorUsage(context, node), - 'MemberExpression': (node) => checkMemberExpression(context, node), - 'Program:exit': () => reportIfMissing(context) - }; -}; - -module.exports.meta = { - fixable: 'code' -}; diff --git a/tools/eslint-rules/lowercase-name-for-primitive.js b/tools/eslint-rules/lowercase-name-for-primitive.js deleted file mode 100644 index 274dcd1c9dce6e61dc2a56dedae222346c64cdb9..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/lowercase-name-for-primitive.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @fileoverview Check that TypeError[ERR_INVALID_ARG_TYPE] uses - * lowercase for primitive types - * @author Weijia Wang - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const astSelector = 'NewExpression[callee.property.name="TypeError"]' + - '[arguments.0.value="ERR_INVALID_ARG_TYPE"]'; - -const primitives = [ 'number', 'string', 'boolean', 'null', 'undefined' ]; - -module.exports = function(context) { - function checkNamesArgument(node) { - const names = node.arguments[2]; - - switch (names.type) { - case 'Literal': - checkName(names); - break; - case 'ArrayExpression': - names.elements.forEach((name) => { - checkName(name); - }); - break; - } - } - - function checkName(node) { - const name = node.value; - const lowercaseName = name.toLowerCase(); - if (name !== lowercaseName && primitives.includes(lowercaseName)) { - const msg = `primitive should use lowercase: ${name}`; - context.report({ - node, - message: msg, - fix: (fixer) => { - return fixer.replaceText( - node, - `'${lowercaseName}'` - ); - } - }); - } - - } - - return { - [astSelector]: (node) => checkNamesArgument(node) - }; -}; - -module.exports.meta = { - fixable: 'code' -}; diff --git a/tools/eslint-rules/no-duplicate-requires.js b/tools/eslint-rules/no-duplicate-requires.js deleted file mode 100644 index 8c4b7a4c2734572bb4f66be650f2020cd6b56143..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/no-duplicate-requires.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Ensure modules are not required twice at top level of a module - * @author devsnek - */ -'use strict'; - -const { isRequireCall, isString } = require('./rules-utils.js'); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - - -function isTopLevel(node) { - do { - if (node.type === 'FunctionDeclaration' || - node.type === 'FunctionExpression' || - node.type === 'ArrowFunctionExpression' || - node.type === 'ClassBody' || - node.type === 'MethodDefinition') { - return false; - } - } while (node = node.parent); - return true; -} - -module.exports = (context) => { - if (context.parserOptions.sourceType === 'module') { - return {}; - } - - function getRequiredModuleNameFromCall(node) { - // Node has arguments and first argument is string - if (node.arguments.length && isString(node.arguments[0])) { - return node.arguments[0].value.trim(); - } - - return undefined; - } - - const required = new Set(); - - const rules = { - CallExpression: (node) => { - if (isRequireCall(node) && isTopLevel(node)) { - const moduleName = getRequiredModuleNameFromCall(node); - if (moduleName === undefined) { - return; - } - if (required.has(moduleName)) { - context.report( - node, - '\'{{moduleName}}\' require is duplicated.', - { moduleName } - ); - } else { - required.add(moduleName); - } - } - }, - }; - - return rules; -}; diff --git a/tools/eslint-rules/no-unescaped-regexp-dot.js b/tools/eslint-rules/no-unescaped-regexp-dot.js deleted file mode 100644 index e9349713bfa3fa7a1fd3059fa7a244f3483edfcd..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/no-unescaped-regexp-dot.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @fileoverview Look for unescaped "literal" dots in regular expressions - * @author Brian White - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = function(context) { - const sourceCode = context.getSourceCode(); - const regexpStack = []; - let regexpBuffer = []; - let inRegExp = false; - - function report(node, startOffset) { - const indexOfDot = sourceCode.getIndexFromLoc(node.loc.start) + startOffset; - context.report({ - node, - loc: sourceCode.getLocFromIndex(indexOfDot), - message: 'Unescaped dot character in regular expression' - }); - } - - const allowedModifiers = ['+', '*', '?', '{']; - function checkRegExp(nodes) { - let escaping = false; - let inCharClass = false; - for (let n = 0; n < nodes.length; ++n) { - const pair = nodes[n]; - const node = pair[0]; - const str = pair[1]; - for (let i = 0; i < str.length; ++i) { - switch (str[i]) { - case '[': - if (!escaping) - inCharClass = true; - else - escaping = false; - break; - case ']': - if (!escaping) { - if (inCharClass) - inCharClass = false; - } else { - escaping = false; - } - break; - case '\\': - escaping = !escaping; - break; - case '.': - if (!escaping) { - if (!inCharClass && - ((i + 1) === str.length || - allowedModifiers.indexOf(str[i + 1]) === -1)) { - report(node, i); - } - } else { - escaping = false; - } - break; - default: - if (escaping) - escaping = false; - } - } - } - } - - function checkRegExpStart(node) { - if (node.callee && node.callee.name === 'RegExp') { - if (inRegExp) { - regexpStack.push(regexpBuffer); - regexpBuffer = []; - } - inRegExp = true; - } - } - - function checkRegExpEnd(node) { - if (node.callee && node.callee.name === 'RegExp') { - checkRegExp(regexpBuffer); - if (regexpStack.length) { - regexpBuffer = regexpStack.pop(); - } else { - inRegExp = false; - regexpBuffer = []; - } - } - } - - function checkLiteral(node) { - const isTemplate = (node.type === 'TemplateLiteral' && node.quasis && - node.quasis.length); - if (inRegExp && - (isTemplate || (typeof node.value === 'string' && node.value.length))) { - let p = node.parent; - while (p && p.type === 'BinaryExpression') { - p = p.parent; - } - if (p && (p.type === 'NewExpression' || p.type === 'CallExpression') && - p.callee && p.callee.type === 'Identifier' && - p.callee.name === 'RegExp') { - if (isTemplate) { - const quasis = node.quasis; - for (let i = 0; i < quasis.length; ++i) { - const el = quasis[i]; - if (el.type === 'TemplateElement' && el.value && el.value.cooked) - regexpBuffer.push([el, el.value.cooked]); - } - } else { - regexpBuffer.push([node, node.value]); - } - } - } else if (node.regex) { - checkRegExp([[node, node.regex.pattern]]); - } - } - - return { - 'TemplateLiteral': checkLiteral, - 'Literal': checkLiteral, - 'CallExpression': checkRegExpStart, - 'NewExpression': checkRegExpStart, - 'CallExpression:exit': checkRegExpEnd, - 'NewExpression:exit': checkRegExpEnd - }; -}; diff --git a/tools/eslint-rules/non-ascii-character.js b/tools/eslint-rules/non-ascii-character.js deleted file mode 100644 index 6588125d33d201c64840827b28b0d74ac1542185..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/non-ascii-character.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileOverview Any non-ASCII characters in lib/ will increase the size - * of the compiled node binary. This linter rule ensures that - * any such character is reported. - * @author Sarat Addepalli - */ - -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const nonAsciiRegexPattern = /[^\r\n\x20-\x7e]/; -const suggestions = { - '’': '\'', - '‛': '\'', - '‘': '\'', - '“': '"', - '‟': '"', - 'â€': '"', - '«': '"', - '»': '"', - '—': '-' -}; - -module.exports = (context) => { - - const reportIfError = (node, sourceCode) => { - - const matches = sourceCode.text.match(nonAsciiRegexPattern); - - if (!matches) return; - - const offendingCharacter = matches[0]; - const offendingCharacterPosition = matches.index; - const suggestion = suggestions[offendingCharacter]; - - let message = `Non-ASCII character '${offendingCharacter}' detected.`; - - message = suggestion ? - `${message} Consider replacing with: ${suggestion}` : - message; - - context.report({ - node, - message, - loc: sourceCode.getLocFromIndex(offendingCharacterPosition), - fix: (fixer) => { - return fixer.replaceText( - node, - suggestion ? `${suggestion}` : '' - ); - } - }); - }; - - return { - Program: (node) => reportIfError(node, context.getSourceCode()) - }; -}; - -module.exports.meta = { - fixable: 'code' -}; diff --git a/tools/eslint-rules/prefer-assert-iferror.js b/tools/eslint-rules/prefer-assert-iferror.js deleted file mode 100644 index 63430d70af93e4c87d3e75f058aa7958be5e91e2..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/prefer-assert-iferror.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Prohibit the `if (err) throw err;` pattern - * @author Teddy Katz - */ - -'use strict'; - -const utils = require('./rules-utils.js'); - -module.exports = { - meta: { - fixable: 'code' - }, - create(context) { - const sourceCode = context.getSourceCode(); - let assertImported = false; - - function hasSameTokens(nodeA, nodeB) { - const aTokens = sourceCode.getTokens(nodeA); - const bTokens = sourceCode.getTokens(nodeB); - - return aTokens.length === bTokens.length && - aTokens.every((token, index) => { - return token.type === bTokens[index].type && - token.value === bTokens[index].value; - }); - } - - function checkAssertNode(node) { - if (utils.isRequired(node, ['assert'])) { - assertImported = true; - } - } - - return { - 'CallExpression': (node) => checkAssertNode(node), - 'IfStatement': (node) => { - const firstStatement = node.consequent.type === 'BlockStatement' ? - node.consequent.body[0] : - node.consequent; - if ( - firstStatement && - firstStatement.type === 'ThrowStatement' && - hasSameTokens(node.test, firstStatement.argument) - ) { - const argument = sourceCode.getText(node.test); - context.report({ - node: firstStatement, - message: 'Use assert.ifError({{argument}}) instead.', - data: { argument }, - fix: (fixer) => { - if (assertImported) { - return fixer.replaceText( - node, - `assert.ifError(${argument});` - ); - } - } - }); - } - } - }; - } -}; diff --git a/tools/eslint-rules/prefer-assert-methods.js b/tools/eslint-rules/prefer-assert-methods.js deleted file mode 100644 index 400a5d54759c8651333dfebbd0e9763a1fa0313c..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/prefer-assert-methods.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @fileoverview Prohibit the use of assert operators ( ===, !==, ==, != ) - */ - -'use strict'; - -const astSelector = 'ExpressionStatement[expression.type="CallExpression"]' + - '[expression.callee.name="assert"]' + - '[expression.arguments.0.type="BinaryExpression"]'; - -function parseError(method, op) { - return `'assert.${method}' should be used instead of '${op}'`; -} - -const preferedAssertMethod = { - '===': 'strictEqual', - '!==': 'notStrictEqual', - '==': 'equal', - '!=': 'notEqual' -}; - -module.exports = function(context) { - return { - [astSelector]: function(node) { - const arg = node.expression.arguments[0]; - const assertMethod = preferedAssertMethod[arg.operator]; - if (assertMethod) { - context.report({ - node, - message: parseError(assertMethod, arg.operator), - fix: (fixer) => { - const sourceCode = context.getSourceCode(); - const left = sourceCode.getText(arg.left); - const right = sourceCode.getText(arg.right); - return fixer.replaceText( - node, - `assert.${assertMethod}(${left}, ${right});` - ); - } - }); - } - } - }; -}; - -module.exports.meta = { - fixable: 'code' -}; diff --git a/tools/eslint-rules/prefer-common-mustnotcall.js b/tools/eslint-rules/prefer-common-mustnotcall.js deleted file mode 100644 index ef3c5fb729f31f835770417fb0b822e7b67273c5..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/prefer-common-mustnotcall.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @fileoverview Prefer common.mustNotCall(msg) over common.mustCall(fn, 0) - * @author James M Snell - */ -'use strict'; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const msg = 'Please use common.mustNotCall(msg) instead of ' + - 'common.mustCall(fn, 0) or common.mustCall(0).'; -const mustCallSelector = 'CallExpression[callee.object.name="common"]' + - '[callee.property.name="mustCall"]'; -const arg0Selector = `${mustCallSelector}[arguments.0.value=0]`; -const arg1Selector = `${mustCallSelector}[arguments.1.value=0]`; - -module.exports = function(context) { - function report(node) { - context.report(node, msg); - } - - return { - // Catch common.mustCall(0) - [arg0Selector]: report, - - // Catch common.mustCall(fn, 0) - [arg1Selector]: report - }; -}; diff --git a/tools/eslint-rules/prefer-util-format-errors.js b/tools/eslint-rules/prefer-util-format-errors.js deleted file mode 100644 index 407b6e20dd23eade91fcc4236d40df04219164b6..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/prefer-util-format-errors.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const { isDefiningError } = require('./rules-utils.js'); - -const errMsg = 'Please use a printf-like formatted string that util.format' + - ' can consume.'; - -function isArrowFunctionWithTemplateLiteral(node) { - return node.type === 'ArrowFunctionExpression' && - node.body.type === 'TemplateLiteral'; -} - -module.exports = { - create: function(context) { - return { - ExpressionStatement: function(node) { - if (!isDefiningError(node) || node.expression.arguments.length < 2) - return; - - const msg = node.expression.arguments[1]; - if (!isArrowFunctionWithTemplateLiteral(msg)) - return; - - // Checks to see if order of arguments to function is the same as the - // order of them being concatenated in the template string. The idea is - // that if both match, then you can use `util.format`-style args. - // Would pass rule: (a, b) => `${b}${a}`. - // Would fail rule: (a, b) => `${a}${b}`, and needs to be rewritten. - const { expressions } = msg.body; - const hasSequentialParams = msg.params.every((param, index) => { - const expr = expressions[index]; - return expr && expr.type === 'Identifier' && param.name === expr.name; - }); - if (hasSequentialParams) - context.report(msg, errMsg); - } - }; - } -}; diff --git a/tools/eslint-rules/require-common-first.js b/tools/eslint-rules/require-common-first.js deleted file mode 100644 index 4096ee2771078177cd2f90389a4209e27b452992..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/require-common-first.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @fileoverview Require `common` module first in our tests. - */ -'use strict'; - -const path = require('path'); -const { isRequireCall, isString } = require('./rules-utils.js'); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = function(context) { - const requiredModule = 'common'; - const isESM = context.parserOptions.sourceType === 'module'; - const foundModules = []; - - /** - * Function to check if the path is a module and return its name. - * @param {String} str The path to check - * @returns {String} module name - */ - function getModuleName(str) { - if (str === '../common/index.mjs') { - return 'common'; - } - - return path.basename(str); - } - - /** - * Function to check if a node has an argument that is a module and - * return its name. - * @param {ASTNode} node The node to check - * @returns {undefined|String} module name or undefined - */ - function getModuleNameFromCall(node) { - // Node has arguments and first argument is string - if (node.arguments.length && isString(node.arguments[0])) { - return getModuleName(node.arguments[0].value.trim()); - } - - return undefined; - } - - const rules = { - 'Program:exit'(node) { - // The common module should be loaded in the first place. - const notLoadedFirst = foundModules.indexOf(requiredModule) !== 0; - if (notLoadedFirst) { - context.report( - node, - 'Mandatory module "{{moduleName}}" must be loaded ' + - 'before any other modules.', - { moduleName: requiredModule } - ); - } - } - }; - - if (isESM) { - rules.ImportDeclaration = (node) => { - const moduleName = getModuleName(node.source.value); - if (moduleName) { - foundModules.push(moduleName); - } - }; - } else { - rules.CallExpression = (node) => { - if (isRequireCall(node)) { - const moduleName = getModuleNameFromCall(node); - - if (moduleName) { - foundModules.push(moduleName); - } - } - }; - } - - return rules; -}; diff --git a/tools/eslint-rules/required-modules.js b/tools/eslint-rules/required-modules.js deleted file mode 100644 index 06c998c7f5a182b9d896bcb937d1c5deaf343510..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/required-modules.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @fileoverview Require usage of specified node modules. - * @author Rich Trott - */ -'use strict'; - -const { isRequireCall, isString } = require('./rules-utils.js'); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = function(context) { - // Trim required module names - const options = context.options[0]; - const requiredModules = options ? Object.keys(options).map((x) => { - return [ x, new RegExp(options[x]) ]; - }) : []; - const isESM = context.parserOptions.sourceType === 'module'; - - const foundModules = []; - - // If no modules are required we don't need to check the CallExpressions - if (requiredModules.length === 0) { - return {}; - } - - /** - * Function to check if the path is a required module and return its name. - * @param {String} str The path to check - * @returns {undefined|String} required module name or undefined - */ - function getRequiredModuleName(str) { - const match = requiredModules.find(([, test]) => { - return test.test(str); - }); - return match ? match[0] : undefined; - } - - /** - * Function to check if a node has an argument that is a required module and - * return its name. - * @param {ASTNode} node The node to check - * @returns {undefined|String} required module name or undefined - */ - function getRequiredModuleNameFromCall(node) { - // Node has arguments and first argument is string - if (node.arguments.length && isString(node.arguments[0])) { - return getRequiredModuleName(node.arguments[0].value.trim()); - } - - return undefined; - } - - const rules = { - 'Program:exit'(node) { - if (foundModules.length < requiredModules.length) { - const missingModules = requiredModules.filter( - ([module]) => foundModules.indexOf(module) === -1 - ); - missingModules.forEach(([moduleName]) => { - context.report( - node, - 'Mandatory module "{{moduleName}}" must be loaded.', - { moduleName: moduleName } - ); - }); - } - } - }; - - if (isESM) { - rules.ImportDeclaration = (node) => { - const requiredModuleName = getRequiredModuleName(node.source.value); - if (requiredModuleName) { - foundModules.push(requiredModuleName); - } - }; - } else { - rules.CallExpression = (node) => { - if (isRequireCall(node)) { - const requiredModuleName = getRequiredModuleNameFromCall(node); - - if (requiredModuleName) { - foundModules.push(requiredModuleName); - } - } - }; - } - - return rules; -}; - -module.exports.meta = { - schema: [{ - 'type': 'object', - 'additionalProperties': { - 'type': 'string' - }, - }], -}; diff --git a/tools/eslint-rules/rules-utils.js b/tools/eslint-rules/rules-utils.js deleted file mode 100644 index 462ab7c2ff3ab8c7e31a6d780e34033e2a655d99..0000000000000000000000000000000000000000 --- a/tools/eslint-rules/rules-utils.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Utility functions common to ESLint rules. - */ -'use strict'; - -function isRequireCall(node) { - return node.callee.type === 'Identifier' && node.callee.name === 'require'; -} -module.exports.isRequireCall = isRequireCall; - -module.exports.isString = function(node) { - return node && node.type === 'Literal' && typeof node.value === 'string'; -}; - -module.exports.isDefiningError = function(node) { - return node.expression && - node.expression.type === 'CallExpression' && - node.expression.callee && - node.expression.callee.name === 'E' && - node.expression.arguments.length !== 0; -}; - -/** - * Returns true if any of the passed in modules are used in - * require calls. - */ -module.exports.isRequired = function(node, modules) { - return isRequireCall(node) && node.arguments.length !== 0 && - modules.includes(node.arguments[0].value); -}; - -/** -* Return true if common module is required -* in AST Node under inspection -*/ -const commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/); -module.exports.isCommonModule = function(node) { - return isRequireCall(node) && - node.arguments.length !== 0 && - commonModuleRegExp.test(node.arguments[0].value); -}; - -/** - * Returns true if any of the passed in modules are used in - * process.binding() or internalBinding() calls. - */ -module.exports.isBinding = function(node, modules) { - const isProcessBinding = node.callee.object && - node.callee.object.name === 'process' && - node.callee.property.name === 'binding'; - - return (isProcessBinding || node.callee.name === 'internalBinding') && - modules.includes(node.arguments[0].value); -}; - -/** - * Returns true is the node accesses any property in the properties - * array on the 'common' object. - */ -module.exports.usesCommonProperty = function(node, properties) { - if (node.name) { - return properties.includes(node.name); - } - if (node.property) { - return properties.includes(node.property.name); - } - return false; -}; - -/** - * Returns true if the passed in node is inside an if statement block, - * and the block also has a call to skip. - */ -module.exports.inSkipBlock = function(node) { - let hasSkipBlock = false; - if (node.test && - node.test.type === 'UnaryExpression' && - node.test.operator === '!') { - const consequent = node.consequent; - if (consequent.body) { - consequent.body.some((expressionStatement) => { - if (hasSkip(expressionStatement.expression)) { - return hasSkipBlock = true; - } - return false; - }); - } else if (hasSkip(consequent.expression)) { - hasSkipBlock = true; - } - } - return hasSkipBlock; -}; - -function hasSkip(expression) { - return expression && - expression.callee && - (expression.callee.name === 'skip' || - expression.callee.property && - expression.callee.property.name === 'skip'); -} diff --git a/tools/license-builder.sh b/tools/license-builder.sh deleted file mode 100755 index e9f4e1fb9540218c2d0aa57008f34cb363019b5e..0000000000000000000000000000000000000000 --- a/tools/license-builder.sh +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env bash - -set -e - -rootdir="$(CDPATH= cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -licensefile="${rootdir}/LICENSE" -licensehead="$(sed '/^- /,$d' ${licensefile})" -tmplicense="${rootdir}/~LICENSE.$$" -echo -e "$licensehead" > $tmplicense - - -# addlicense -function addlicense { - - echo " -- ${1}, located at ${2}, is licensed as follows: - \"\"\" -$(echo -e "$3" | sed -e 's/^/ /' -e 's/^ $//' -e 's/ *$//' | sed -e '/./,$!d' | sed -e '/^$/N;/^\n$/D') - \"\"\"\ -" >> $tmplicense - -} - - -if ! [ -d "${rootdir}/deps/icu/" ] && ! [ -d "${rootdir}/deps/icu-small/" ]; then - echo "ICU not installed, run configure to download it, e.g. ./configure --with-intl=small-icu --download=icu" - exit 1 -fi - - -# Dependencies bundled in distributions -addlicense "Acorn" "deps/acorn" "$(cat ${rootdir}/deps/acorn/acorn/LICENSE)" -addlicense "Acorn plugins" "deps/acorn-plugins" "$(cat ${rootdir}/deps/acorn-plugins/acorn-class-fields/LICENSE)" -addlicense "c-ares" "deps/cares" "$(tail -n +3 ${rootdir}/deps/cares/LICENSE.md)" -addlicense "HTTP Parser" "deps/http_parser" "$(cat deps/http_parser/LICENSE-MIT)" -addlicense "cjs-module-lexer" "deps/cjs-module-lexer" "$(cat ${rootdir}/deps/cjs-module-lexer/LICENSE)" -if [ -f "${rootdir}/deps/icu/LICENSE" ]; then - # ICU 57 and following. Drop the BOM - addlicense "ICU" "deps/icu" \ - "$(sed -e '1s/^[^a-zA-Z ]*ICU/ICU/' -e :a \ - -e 's/<[^>]*>//g;s/ / /g;s/ +$//;/]*>//g;s/ / /g;s/ +$//;/]*>//g;s/ / /g;s/ +$//;/]*>//g;s/ / /g;s/ +$//;/ #include #include +#include +#include #define GUID_BUFFER_SIZE 39 // {8-4-4-4-12}\0 @@ -96,6 +98,35 @@ LExit: return WcaFinalize(er); } +#define AUTHENTICATED_USERS_SID L"S-1-5-11" + +extern "C" UINT WINAPI GetLocalizedUserNames(MSIHANDLE hInstall) { + HRESULT hr = S_OK; + UINT er = ERROR_SUCCESS; + TCHAR userName[UNLEN + 1] = {0}; + DWORD userNameSize = UNLEN + 1; + TCHAR domain[DNLEN + 1] = {0}; + DWORD domainSize = DNLEN + 1; + PSID sid; + SID_NAME_USE nameUse; + + hr = WcaInitialize(hInstall, "GetLocalizedUserNames"); + ExitOnFailure(hr, "Failed to initialize"); + + er = ConvertStringSidToSidW(AUTHENTICATED_USERS_SID, &sid); + ExitOnLastError(er, "Failed to convert security identifier"); + + er = LookupAccountSidW(NULL, sid, userName, &userNameSize, domain, &domainSize, &nameUse); + ExitOnLastError(er, "Failed to lookup security identifier"); + + MsiSetProperty(hInstall, L"AUTHENTICATED_USERS", userName); + ExitOnWin32Error(er, hr, "Failed to set localized Authenticated User name"); + +LExit: + er = SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE; + LocalFree(sid); + return WcaFinalize(er); +} extern "C" BOOL WINAPI DllMain(HINSTANCE hInst, ULONG ulReason, VOID* dummy) { switch (ulReason) { diff --git a/tools/msvs/msi/custom_actions.def b/tools/msvs/msi/custom_actions.def index 5f6b25fc423492278996a5f187965f569e8f8401..93f2a28f45e45ebac90756ecc66b7719fa2ba9c3 100644 --- a/tools/msvs/msi/custom_actions.def +++ b/tools/msvs/msi/custom_actions.def @@ -3,3 +3,4 @@ LIBRARY "custom_actions" EXPORTS SetInstallScope BroadcastEnvironmentUpdate +GetLocalizedUserNames diff --git a/tools/msvs/msi/product.wxs b/tools/msvs/msi/product.wxs index f008ea7f9adff75c416a4eab06aaad50475f5ee4..61909bbeb61c9f122699ffb5d9249de193341029 100755 --- a/tools/msvs/msi/product.wxs +++ b/tools/msvs/msi/product.wxs @@ -46,6 +46,11 @@ + + + + + + + @@ -169,6 +176,20 @@ + + + + + + + + + + + + - - - -## Table of Contents - -- [Examples](#examples) - - [Consuming a source map](#consuming-a-source-map) - - [Generating a source map](#generating-a-source-map) - - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) -- [API](#api) - - [SourceMapConsumer](#sourcemapconsumer) - - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - - [SourceMapGenerator](#sourcemapgenerator) - - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - - [SourceNode](#sourcenode) - - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) - - - -## Examples - -### Consuming a source map - -```js -var rawSourceMap = { - version: 3, - file: 'min.js', - names: ['bar', 'baz', 'n'], - sources: ['one.js', 'two.js'], - sourceRoot: 'http://example.com/www/js/', - mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' -}; - -var smc = new SourceMapConsumer(rawSourceMap); - -console.log(smc.sources); -// [ 'http://example.com/www/js/one.js', -// 'http://example.com/www/js/two.js' ] - -console.log(smc.originalPositionFor({ - line: 2, - column: 28 -})); -// { source: 'http://example.com/www/js/two.js', -// line: 2, -// column: 10, -// name: 'n' } - -console.log(smc.generatedPositionFor({ - source: 'http://example.com/www/js/two.js', - line: 2, - column: 10 -})); -// { line: 2, column: 28 } - -smc.eachMapping(function (m) { - // ... -}); -``` - -### Generating a source map - -In depth guide: -[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) - -#### With SourceNode (high level API) - -```js -function compile(ast) { - switch (ast.type) { - case 'BinaryExpression': - return new SourceNode( - ast.location.line, - ast.location.column, - ast.location.source, - [compile(ast.left), " + ", compile(ast.right)] - ); - case 'Literal': - return new SourceNode( - ast.location.line, - ast.location.column, - ast.location.source, - String(ast.value) - ); - // ... - default: - throw new Error("Bad AST"); - } -} - -var ast = parse("40 + 2", "add.js"); -console.log(compile(ast).toStringWithSourceMap({ - file: 'add.js' -})); -// { code: '40 + 2', -// map: [object SourceMapGenerator] } -``` - -#### With SourceMapGenerator (low level API) - -```js -var map = new SourceMapGenerator({ - file: "source-mapped.js" -}); - -map.addMapping({ - generated: { - line: 10, - column: 35 - }, - source: "foo.js", - original: { - line: 33, - column: 2 - }, - name: "christopher" -}); - -console.log(map.toString()); -// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' -``` - -## API - -Get a reference to the module: - -```js -// Node.js -var sourceMap = require('source-map'); - -// Browser builds -var sourceMap = window.sourceMap; - -// Inside Firefox -const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); -``` - -### SourceMapConsumer - -A SourceMapConsumer instance represents a parsed source map which we can query -for information about the original file positions by giving it a file position -in the generated source. - -#### new SourceMapConsumer(rawSourceMap) - -The only parameter is the raw source map (either as a string which can be -`JSON.parse`'d, or an object). According to the spec, source maps have the -following attributes: - -* `version`: Which version of the source map spec this map is following. - -* `sources`: An array of URLs to the original source files. - -* `names`: An array of identifiers which can be referenced by individual - mappings. - -* `sourceRoot`: Optional. The URL root from which all sources are relative. - -* `sourcesContent`: Optional. An array of contents of the original source files. - -* `mappings`: A string of base64 VLQs which contain the actual mappings. - -* `file`: Optional. The generated filename this source map is associated with. - -```js -var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); -``` - -#### SourceMapConsumer.prototype.computeColumnSpans() - -Compute the last column for each generated mapping. The last column is -inclusive. - -```js -// Before: -consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) -// [ { line: 2, -// column: 1 }, -// { line: 2, -// column: 10 }, -// { line: 2, -// column: 20 } ] - -consumer.computeColumnSpans(); - -// After: -consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) -// [ { line: 2, -// column: 1, -// lastColumn: 9 }, -// { line: 2, -// column: 10, -// lastColumn: 19 }, -// { line: 2, -// column: 20, -// lastColumn: Infinity } ] - -``` - -#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) - -Returns the original source, line, and column information for the generated -source's line and column positions provided. The only argument is an object with -the following properties: - -* `line`: The line number in the generated source. - -* `column`: The column number in the generated source. - -* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or - `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest - element that is smaller than or greater than the one we are searching for, - respectively, if the exact element cannot be found. Defaults to - `SourceMapConsumer.GREATEST_LOWER_BOUND`. - -and an object is returned with the following properties: - -* `source`: The original source file, or null if this information is not - available. - -* `line`: The line number in the original source, or null if this information is - not available. - -* `column`: The column number in the original source, or null if this - information is not available. - -* `name`: The original identifier, or null if this information is not available. - -```js -consumer.originalPositionFor({ line: 2, column: 10 }) -// { source: 'foo.coffee', -// line: 2, -// column: 2, -// name: null } - -consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) -// { source: null, -// line: null, -// column: null, -// name: null } -``` - -#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) - -Returns the generated line and column information for the original source, -line, and column positions provided. The only argument is an object with -the following properties: - -* `source`: The filename of the original source. - -* `line`: The line number in the original source. - -* `column`: The column number in the original source. - -and an object is returned with the following properties: - -* `line`: The line number in the generated source, or null. - -* `column`: The column number in the generated source, or null. - -```js -consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) -// { line: 1, -// column: 56 } -``` - -#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) - -Returns all generated line and column information for the original source, line, -and column provided. If no column is provided, returns all mappings -corresponding to a either the line we are searching for or the next closest line -that has any mappings. Otherwise, returns all mappings corresponding to the -given line and either the column we are searching for or the next closest column -that has any offsets. - -The only argument is an object with the following properties: - -* `source`: The filename of the original source. - -* `line`: The line number in the original source. - -* `column`: Optional. The column number in the original source. - -and an array of objects is returned, each with the following properties: - -* `line`: The line number in the generated source, or null. - -* `column`: The column number in the generated source, or null. - -```js -consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) -// [ { line: 2, -// column: 1 }, -// { line: 2, -// column: 10 }, -// { line: 2, -// column: 20 } ] -``` - -#### SourceMapConsumer.prototype.hasContentsOfAllSources() - -Return true if we have the embedded source content for every source listed in -the source map, false otherwise. - -In other words, if this method returns `true`, then -`consumer.sourceContentFor(s)` will succeed for every source `s` in -`consumer.sources`. - -```js -// ... -if (consumer.hasContentsOfAllSources()) { - consumerReadyCallback(consumer); -} else { - fetchSources(consumer, consumerReadyCallback); -} -// ... -``` - -#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) - -Returns the original source content for the source provided. The only -argument is the URL of the original source file. - -If the source content for the given source is not found, then an error is -thrown. Optionally, pass `true` as the second param to have `null` returned -instead. - -```js -consumer.sources -// [ "my-cool-lib.clj" ] - -consumer.sourceContentFor("my-cool-lib.clj") -// "..." - -consumer.sourceContentFor("this is not in the source map"); -// Error: "this is not in the source map" is not in the source map - -consumer.sourceContentFor("this is not in the source map", true); -// null -``` - -#### SourceMapConsumer.prototype.eachMapping(callback, context, order) - -Iterate over each mapping between an original source/line/column and a -generated line/column in this source map. - -* `callback`: The function that is called with each mapping. Mappings have the - form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, - name }` - -* `context`: Optional. If specified, this object will be the value of `this` - every time that `callback` is called. - -* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or - `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over - the mappings sorted by the generated file's line/column order or the - original's source/line/column order, respectively. Defaults to - `SourceMapConsumer.GENERATED_ORDER`. - -```js -consumer.eachMapping(function (m) { console.log(m); }) -// ... -// { source: 'illmatic.js', -// generatedLine: 1, -// generatedColumn: 0, -// originalLine: 1, -// originalColumn: 0, -// name: null } -// { source: 'illmatic.js', -// generatedLine: 2, -// generatedColumn: 0, -// originalLine: 2, -// originalColumn: 0, -// name: null } -// ... -``` -### SourceMapGenerator - -An instance of the SourceMapGenerator represents a source map which is being -built incrementally. - -#### new SourceMapGenerator([startOfSourceMap]) - -You may pass an object with the following properties: - -* `file`: The filename of the generated source that this source map is - associated with. - -* `sourceRoot`: A root for all relative URLs in this source map. - -* `skipValidation`: Optional. When `true`, disables validation of mappings as - they are added. This can improve performance but should be used with - discretion, as a last resort. Even then, one should avoid using this flag when - running tests, if possible. - -```js -var generator = new sourceMap.SourceMapGenerator({ - file: "my-generated-javascript-file.js", - sourceRoot: "http://example.com/app/js/" -}); -``` - -#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) - -Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. - -* `sourceMapConsumer` The SourceMap. - -```js -var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); -``` - -#### SourceMapGenerator.prototype.addMapping(mapping) - -Add a single mapping from original source line and column to the generated -source's line and column for this source map being created. The mapping object -should have the following properties: - -* `generated`: An object with the generated line and column positions. - -* `original`: An object with the original line and column positions. - -* `source`: The original source file (relative to the sourceRoot). - -* `name`: An optional original token name for this mapping. - -```js -generator.addMapping({ - source: "module-one.scm", - original: { line: 128, column: 0 }, - generated: { line: 3, column: 456 } -}) -``` - -#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) - -Set the source content for an original source file. - -* `sourceFile` the URL of the original source file. - -* `sourceContent` the content of the source file. - -```js -generator.setSourceContent("module-one.scm", - fs.readFileSync("path/to/module-one.scm")) -``` - -#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) - -Applies a SourceMap for a source file to the SourceMap. -Each mapping to the supplied source file is rewritten using the -supplied SourceMap. Note: The resolution for the resulting mappings -is the minimum of this map and the supplied map. - -* `sourceMapConsumer`: The SourceMap to be applied. - -* `sourceFile`: Optional. The filename of the source file. - If omitted, sourceMapConsumer.file will be used, if it exists. - Otherwise an error will be thrown. - -* `sourceMapPath`: Optional. The dirname of the path to the SourceMap - to be applied. If relative, it is relative to the SourceMap. - - This parameter is needed when the two SourceMaps aren't in the same - directory, and the SourceMap to be applied contains relative source - paths. If so, those relative source paths need to be rewritten - relative to the SourceMap. - - If omitted, it is assumed that both SourceMaps are in the same directory, - thus not needing any rewriting. (Supplying `'.'` has the same effect.) - -#### SourceMapGenerator.prototype.toString() - -Renders the source map being generated to a string. - -```js -generator.toString() -// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' -``` - -### SourceNode - -SourceNodes provide a way to abstract over interpolating and/or concatenating -snippets of generated JavaScript source code, while maintaining the line and -column information associated between those snippets and the original source -code. This is useful as the final intermediate representation a compiler might -use before outputting the generated JS and source map. - -#### new SourceNode([line, column, source[, chunk[, name]]]) - -* `line`: The original line number associated with this source node, or null if - it isn't associated with an original line. - -* `column`: The original column number associated with this source node, or null - if it isn't associated with an original column. - -* `source`: The original source's filename; null if no filename is provided. - -* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see - below. - -* `name`: Optional. The original identifier. - -```js -var node = new SourceNode(1, 2, "a.cpp", [ - new SourceNode(3, 4, "b.cpp", "extern int status;\n"), - new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), - new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), -]); -``` - -#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) - -Creates a SourceNode from generated code and a SourceMapConsumer. - -* `code`: The generated code - -* `sourceMapConsumer` The SourceMap for the generated code - -* `relativePath` The optional path that relative sources in `sourceMapConsumer` - should be relative to. - -```js -var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); -var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), - consumer); -``` - -#### SourceNode.prototype.add(chunk) - -Add a chunk of generated JS to this source node. - -* `chunk`: A string snippet of generated JS code, another instance of - `SourceNode`, or an array where each member is one of those things. - -```js -node.add(" + "); -node.add(otherNode); -node.add([leftHandOperandNode, " + ", rightHandOperandNode]); -``` - -#### SourceNode.prototype.prepend(chunk) - -Prepend a chunk of generated JS to this source node. - -* `chunk`: A string snippet of generated JS code, another instance of - `SourceNode`, or an array where each member is one of those things. - -```js -node.prepend("/** Build Id: f783haef86324gf **/\n\n"); -``` - -#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) - -Set the source content for a source file. This will be added to the -`SourceMap` in the `sourcesContent` field. - -* `sourceFile`: The filename of the source file - -* `sourceContent`: The content of the source file - -```js -node.setSourceContent("module-one.scm", - fs.readFileSync("path/to/module-one.scm")) -``` - -#### SourceNode.prototype.walk(fn) - -Walk over the tree of JS snippets in this node and its children. The walking -function is called once for each snippet of JS and is passed that snippet and -the its original associated source's line/column location. - -* `fn`: The traversal function. - -```js -var node = new SourceNode(1, 2, "a.js", [ - new SourceNode(3, 4, "b.js", "uno"), - "dos", - [ - "tres", - new SourceNode(5, 6, "c.js", "quatro") - ] -]); - -node.walk(function (code, loc) { console.log("WALK:", code, loc); }) -// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } -// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } -// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } -// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } -``` - -#### SourceNode.prototype.walkSourceContents(fn) - -Walk over the tree of SourceNodes. The walking function is called for each -source file content and is passed the filename and source content. - -* `fn`: The traversal function. - -```js -var a = new SourceNode(1, 2, "a.js", "generated from a"); -a.setSourceContent("a.js", "original a"); -var b = new SourceNode(1, 2, "b.js", "generated from b"); -b.setSourceContent("b.js", "original b"); -var c = new SourceNode(1, 2, "c.js", "generated from c"); -c.setSourceContent("c.js", "original c"); - -var node = new SourceNode(null, null, null, [a, b, c]); -node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) -// WALK: a.js : original a -// WALK: b.js : original b -// WALK: c.js : original c -``` - -#### SourceNode.prototype.join(sep) - -Like `Array.prototype.join` except for SourceNodes. Inserts the separator -between each of this source node's children. - -* `sep`: The separator. - -```js -var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); -var operand = new SourceNode(3, 4, "a.rs", "="); -var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); - -var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); -var joinedNode = node.join(" "); -``` - -#### SourceNode.prototype.replaceRight(pattern, replacement) - -Call `String.prototype.replace` on the very right-most source snippet. Useful -for trimming white space from the end of a source node, etc. - -* `pattern`: The pattern to replace. - -* `replacement`: The thing to replace the pattern with. - -```js -// Trim trailing white space. -node.replaceRight(/\s*$/, ""); -``` - -#### SourceNode.prototype.toString() - -Return the string representation of this source node. Walks over the tree and -concatenates all the various snippets together to one string. - -```js -var node = new SourceNode(1, 2, "a.js", [ - new SourceNode(3, 4, "b.js", "uno"), - "dos", - [ - "tres", - new SourceNode(5, 6, "c.js", "quatro") - ] -]); - -node.toString() -// 'unodostresquatro' -``` - -#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) - -Returns the string representation of this tree of source nodes, plus a -SourceMapGenerator which contains all the mappings between the generated and -original sources. - -The arguments are the same as those to `new SourceMapGenerator`. - -```js -var node = new SourceNode(1, 2, "a.js", [ - new SourceNode(3, 4, "b.js", "uno"), - "dos", - [ - "tres", - new SourceNode(5, 6, "c.js", "quatro") - ] -]); - -node.toStringWithSourceMap({ file: "my-output-file.js" }) -// { code: 'unodostresquatro', -// map: [object SourceMapGenerator] } -``` diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.debug.js b/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.debug.js deleted file mode 100644 index b5ab6382abbabc8c86b1c306c1ca1b257d489fe4..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.debug.js +++ /dev/null @@ -1,3091 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["sourceMap"] = factory(); - else - root["sourceMap"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; -/******/ -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - /* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ - exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; - exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; - exports.SourceNode = __webpack_require__(10).SourceNode; - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var base64VLQ = __webpack_require__(2); - var util = __webpack_require__(4); - var ArraySet = __webpack_require__(5).ArraySet; - var MappingList = __webpack_require__(6).MappingList; - - /** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ - function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; - } - - SourceMapGenerator.prototype._version = 3; - - /** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ - SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - - /** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ - SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - - /** - * Set the source content for a source file. - */ - SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - - /** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ - SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - - /** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ - SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - - /** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ - SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - - SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - - /** - * Externalize the source map. - */ - SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - - /** - * Render the source map being generated to a string. - */ - SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - - exports.SourceMapGenerator = SourceMapGenerator; - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - var base64 = __webpack_require__(3); - - // A single base 64 digit can contain 6 bits of data. For the base 64 variable - // length quantities we use in the source map spec, the first bit is the sign, - // the next four bits are the actual value, and the 6th bit is the - // continuation bit. The continuation bit tells us whether there are more - // digits in this value following this digit. - // - // Continuation - // | Sign - // | | - // V V - // 101011 - - var VLQ_BASE_SHIFT = 5; - - // binary: 100000 - var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - - // binary: 011111 - var VLQ_BASE_MASK = VLQ_BASE - 1; - - // binary: 100000 - var VLQ_CONTINUATION_BIT = VLQ_BASE; - - /** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ - function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; - } - - /** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ - function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; - } - - /** - * Returns the base 64 VLQ encoded value. - */ - exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; - }; - - /** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ - exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; - }; - - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - - /** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ - exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); - }; - - /** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ - exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; - }; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - /** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ - function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } - } - exports.getArg = getArg; - - var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; - var dataUrlRegexp = /^data:.+\,.+$/; - - function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; - } - exports.urlParse = urlParse; - - function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; - } - exports.urlGenerate = urlGenerate; - - /** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ - function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; - } - exports.normalize = normalize; - - /** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ - function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; - } - exports.join = join; - - exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); - }; - - /** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ - function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); - } - exports.relative = relative; - - var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); - }()); - - function identity (s) { - return s; - } - - /** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ - function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; - } - exports.toSetString = supportsNullProto ? identity : toSetString; - - function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; - } - exports.fromSetString = supportsNullProto ? identity : fromSetString; - - function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; - } - - /** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ - function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; - } - exports.compareByOriginalPositions = compareByOriginalPositions; - - /** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ - function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; - } - exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - - function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; - } - - /** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ - function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util = __webpack_require__(4); - var has = Object.prototype.hasOwnProperty; - var hasNativeMap = typeof Map !== "undefined"; - - /** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ - function ArraySet() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); - } - - /** - * Static method for creating ArraySet instances from an existing array. - */ - ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; - }; - - /** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ - ArraySet.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; - }; - - /** - * Add the given string to this set. - * - * @param String aStr - */ - ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } - }; - - /** - * Is the given string a member of this set? - * - * @param String aStr - */ - ArraySet.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); - } - }; - - /** - * What is the index of the given string in the array? - * - * @param String aStr - */ - ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); - }; - - /** - * What is the element at the given index? - * - * @param Number aIdx - */ - ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); - }; - - /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ - ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); - }; - - exports.ArraySet = ArraySet; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util = __webpack_require__(4); - - /** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ - function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; - } - - /** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ - function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; - } - - /** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ - MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - - /** - * Add the given source mapping. - * - * @param Object aMapping - */ - MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } - }; - - /** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ - MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; - }; - - exports.MappingList = MappingList; - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util = __webpack_require__(4); - var binarySearch = __webpack_require__(8); - var ArraySet = __webpack_require__(5).ArraySet; - var base64VLQ = __webpack_require__(2); - var quickSort = __webpack_require__(9).quickSort; - - function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); - } - - SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); - } - - /** - * The version of the source mapping spec that we are consuming. - */ - SourceMapConsumer.prototype._version = 3; - - // `__generatedMappings` and `__originalMappings` are arrays that hold the - // parsed mapping coordinates from the source map's "mappings" attribute. They - // are lazily instantiated, accessed via the `_generatedMappings` and - // `_originalMappings` getters respectively, and we only parse the mappings - // and create these arrays once queried for a source location. We jump through - // these hoops because there can be many thousands of mappings, and parsing - // them is expensive, so we only want to do it if we must. - // - // Each object in the arrays is of the form: - // - // { - // generatedLine: The line number in the generated code, - // generatedColumn: The column number in the generated code, - // source: The path to the original source file that generated this - // chunk of code, - // originalLine: The line number in the original source that - // corresponds to this chunk of generated code, - // originalColumn: The column number in the original source that - // corresponds to this chunk of generated code, - // name: The name of the original symbol which generated this chunk of - // code. - // } - // - // All properties except for `generatedLine` and `generatedColumn` can be - // `null`. - // - // `_generatedMappings` is ordered by the generated positions. - // - // `_originalMappings` is ordered by the original positions. - - SourceMapConsumer.prototype.__generatedMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } - }); - - SourceMapConsumer.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } - }); - - SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - - SourceMapConsumer.GENERATED_ORDER = 1; - SourceMapConsumer.ORIGINAL_ORDER = 2; - - SourceMapConsumer.GREATEST_LOWER_BOUND = 1; - SourceMapConsumer.LEAST_UPPER_BOUND = 2; - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - - /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; - } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - - exports.SourceMapConsumer = SourceMapConsumer; - - /** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ - function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; - } - - BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); - BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer - */ - BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - BasicSourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); - } - }); - - /** - * Provide the JIT with a nice shape / hidden class. - */ - function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - - /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ - BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - - /** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ - BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ - BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - - exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - - /** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ - function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); - } - - IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); - IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - - /** - * The version of the source mapping spec that we are consuming. - */ - IndexedSourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } - }); - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ - IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - - exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - exports.GREATEST_LOWER_BOUND = 1; - exports.LEAST_UPPER_BOUND = 2; - - /** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ - function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } - } - - /** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ - exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; - }; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - // It turns out that some (most?) JavaScript engines don't self-host - // `Array.prototype.sort`. This makes sense because C++ will likely remain - // faster than JS when doing raw CPU-intensive sorting. However, when using a - // custom comparator function, calling back and forth between the VM's C++ and - // JIT'd JS is rather slow *and* loses JIT type information, resulting in - // worse generated code for the comparator function than would be optimal. In - // fact, when sorting with a comparator, these costs outweigh the benefits of - // sorting in C++. By using our own JS-implemented Quick Sort (below), we get - // a ~3500ms mean speed-up in `bench/bench.html`. - - /** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ - function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; - } - - /** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ - function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); - } - - /** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ - function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } - } - - /** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ - exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); - }; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; - var util = __webpack_require__(4); - - // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other - // operating systems these days (capturing the result). - var REGEX_NEWLINE = /(\r?\n)/; - - // Newline character code for charCodeAt() comparisons - var NEWLINE_CODE = 10; - - // Private symbol for identifying `SourceNode`s when multiple versions of - // the source-map library are loaded. This MUST NOT CHANGE across - // versions! - var isSourceNode = "$$$isSourceNode$$$"; - - /** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ - function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); - } - - /** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ - SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - - /** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } - }; - - /** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ - SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; - }; - - /** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ - SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; - }; - - /** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ - SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - - /** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - - /** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ - SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; - }; - - /** - * Returns the string representation of this source node along with a source - * map. - */ - SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; - }; - - exports.SourceNode = SourceNode; - - -/***/ }) -/******/ ]) -}); -; -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCBlNDczOGZjNzJhN2IyMzAzOTg4OSIsIndlYnBhY2s6Ly8vLi9zb3VyY2UtbWFwLmpzIiwid2VicGFjazovLy8uL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LXZscS5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmFzZTY0LmpzIiwid2VicGFjazovLy8uL2xpYi91dGlsLmpzIiwid2VicGFjazovLy8uL2xpYi9hcnJheS1zZXQuanMiLCJ3ZWJwYWNrOi8vLy4vbGliL21hcHBpbmctbGlzdC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qcyIsIndlYnBhY2s6Ly8vLi9saWIvYmluYXJ5LXNlYXJjaC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvcXVpY2stc29ydC5qcyIsIndlYnBhY2s6Ly8vLi9saWIvc291cmNlLW5vZGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsQ0FBQztBQUNELE87QUNWQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSx1QkFBZTtBQUNmO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOzs7QUFHQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOzs7Ozs7O0FDdENBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNQQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUEsTUFBSztBQUNMO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0EsMkNBQTBDLFNBQVM7QUFDbkQ7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxxQkFBb0I7QUFDcEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOzs7Ozs7O0FDL1pBLGlCQUFnQixvQkFBb0I7QUFDcEM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDREQUEyRDtBQUMzRCxxQkFBb0I7QUFDcEI7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFHOztBQUVIO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRzs7QUFFSDtBQUNBO0FBQ0E7Ozs7Ozs7QUMzSUEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUJBQWdCO0FBQ2hCLGlCQUFnQjs7QUFFaEIsb0JBQW1CO0FBQ25CLHFCQUFvQjs7QUFFcEIsaUJBQWdCO0FBQ2hCLGlCQUFnQjs7QUFFaEIsaUJBQWdCO0FBQ2hCLGtCQUFpQjs7QUFFakI7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNsRUEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0EsK0NBQThDLFFBQVE7QUFDdEQ7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxFQUFDOztBQUVEO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLDRCQUEyQixRQUFRO0FBQ25DO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNoYUEsaUJBQWdCLG9CQUFvQjtBQUNwQztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsdUNBQXNDLFNBQVM7QUFDL0M7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQ3hIQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUJBQWdCO0FBQ2hCOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUc7QUFDSDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7Ozs7OztBQzlFQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSx1REFBc0Q7QUFDdEQ7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQSxFQUFDOztBQUVEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsRUFBQzs7QUFFRDtBQUNBO0FBQ0E7QUFDQSxvQkFBbUI7QUFDbkI7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFlBQVc7O0FBRVg7QUFDQTtBQUNBLFFBQU87QUFDUDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsWUFBVzs7QUFFWDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNEJBQTJCLE1BQU07QUFDakM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSx1REFBc0Q7QUFDdEQ7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7O0FBRUw7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBLHVEQUFzRCxZQUFZO0FBQ2xFO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBLEVBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0Esb0NBQW1DO0FBQ25DO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwwQkFBeUIsY0FBYztBQUN2QztBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esd0JBQXVCLHdDQUF3QztBQUMvRDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0RBQStDLG1CQUFtQixFQUFFO0FBQ3BFOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGtCQUFpQixvQkFBb0I7QUFDckM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDhCQUE2QixNQUFNO0FBQ25DO0FBQ0EsUUFBTztBQUNQO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsdURBQXNEO0FBQ3REOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxRQUFPO0FBQ1A7QUFDQTtBQUNBLElBQUc7QUFDSDs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFtQiwyQkFBMkI7QUFDOUMsc0JBQXFCLCtDQUErQztBQUNwRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQzs7QUFFRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsUUFBTztBQUNQOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE1BQUs7QUFDTDs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0JBQW1CLDJCQUEyQjtBQUM5Qzs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQkFBbUIsMkJBQTJCO0FBQzlDOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFtQiwyQkFBMkI7QUFDOUM7QUFDQTtBQUNBLHNCQUFxQiw0QkFBNEI7QUFDakQ7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBOzs7Ozs7O0FDempDQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7Ozs7OztBQzlHQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFlBQVcsTUFBTTtBQUNqQjtBQUNBLFlBQVcsT0FBTztBQUNsQjtBQUNBLFlBQVcsT0FBTztBQUNsQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxZQUFXLE1BQU07QUFDakI7QUFDQSxZQUFXLFNBQVM7QUFDcEI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQSxZQUFXLE9BQU87QUFDbEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9CQUFtQixPQUFPO0FBQzFCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxZQUFXLE1BQU07QUFDakI7QUFDQSxZQUFXLFNBQVM7QUFDcEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQ2pIQSxpQkFBZ0Isb0JBQW9CO0FBQ3BDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLOztBQUVMOztBQUVBO0FBQ0E7QUFDQTtBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxrQ0FBaUMsUUFBUTtBQUN6QztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw4Q0FBNkMsU0FBUztBQUN0RDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxxQkFBb0I7QUFDcEI7QUFDQTtBQUNBLHVDQUFzQztBQUN0QztBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxnQkFBZSxXQUFXO0FBQzFCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxnREFBK0MsU0FBUztBQUN4RDtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBLDBDQUF5QyxTQUFTO0FBQ2xEO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBRztBQUNIO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsWUFBVztBQUNYO0FBQ0E7QUFDQTtBQUNBLFlBQVc7QUFDWDtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQSw2Q0FBNEMsY0FBYztBQUMxRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsY0FBYTtBQUNiO0FBQ0E7QUFDQTtBQUNBLGNBQWE7QUFDYjtBQUNBLFlBQVc7QUFDWDtBQUNBLFFBQU87QUFDUDtBQUNBO0FBQ0E7QUFDQSxJQUFHO0FBQ0g7QUFDQTtBQUNBLElBQUc7O0FBRUgsV0FBVTtBQUNWOztBQUVBIiwiZmlsZSI6InNvdXJjZS1tYXAuZGVidWcuanMiLCJzb3VyY2VzQ29udGVudCI6WyIoZnVuY3Rpb24gd2VicGFja1VuaXZlcnNhbE1vZHVsZURlZmluaXRpb24ocm9vdCwgZmFjdG9yeSkge1xuXHRpZih0eXBlb2YgZXhwb3J0cyA9PT0gJ29iamVjdCcgJiYgdHlwZW9mIG1vZHVsZSA9PT0gJ29iamVjdCcpXG5cdFx0bW9kdWxlLmV4cG9ydHMgPSBmYWN0b3J5KCk7XG5cdGVsc2UgaWYodHlwZW9mIGRlZmluZSA9PT0gJ2Z1bmN0aW9uJyAmJiBkZWZpbmUuYW1kKVxuXHRcdGRlZmluZShbXSwgZmFjdG9yeSk7XG5cdGVsc2UgaWYodHlwZW9mIGV4cG9ydHMgPT09ICdvYmplY3QnKVxuXHRcdGV4cG9ydHNbXCJzb3VyY2VNYXBcIl0gPSBmYWN0b3J5KCk7XG5cdGVsc2Vcblx0XHRyb290W1wic291cmNlTWFwXCJdID0gZmFjdG9yeSgpO1xufSkodGhpcywgZnVuY3Rpb24oKSB7XG5yZXR1cm4gXG5cblxuLy8gV0VCUEFDSyBGT09URVIgLy9cbi8vIHdlYnBhY2svdW5pdmVyc2FsTW9kdWxlRGVmaW5pdGlvbiIsIiBcdC8vIFRoZSBtb2R1bGUgY2FjaGVcbiBcdHZhciBpbnN0YWxsZWRNb2R1bGVzID0ge307XG5cbiBcdC8vIFRoZSByZXF1aXJlIGZ1bmN0aW9uXG4gXHRmdW5jdGlvbiBfX3dlYnBhY2tfcmVxdWlyZV9fKG1vZHVsZUlkKSB7XG5cbiBcdFx0Ly8gQ2hlY2sgaWYgbW9kdWxlIGlzIGluIGNhY2hlXG4gXHRcdGlmKGluc3RhbGxlZE1vZHVsZXNbbW9kdWxlSWRdKVxuIFx0XHRcdHJldHVybiBpbnN0YWxsZWRNb2R1bGVzW21vZHVsZUlkXS5leHBvcnRzO1xuXG4gXHRcdC8vIENyZWF0ZSBhIG5ldyBtb2R1bGUgKGFuZCBwdXQgaXQgaW50byB0aGUgY2FjaGUpXG4gXHRcdHZhciBtb2R1bGUgPSBpbnN0YWxsZWRNb2R1bGVzW21vZHVsZUlkXSA9IHtcbiBcdFx0XHRleHBvcnRzOiB7fSxcbiBcdFx0XHRpZDogbW9kdWxlSWQsXG4gXHRcdFx0bG9hZGVkOiBmYWxzZVxuIFx0XHR9O1xuXG4gXHRcdC8vIEV4ZWN1dGUgdGhlIG1vZHVsZSBmdW5jdGlvblxuIFx0XHRtb2R1bGVzW21vZHVsZUlkXS5jYWxsKG1vZHVsZS5leHBvcnRzLCBtb2R1bGUsIG1vZHVsZS5leHBvcnRzLCBfX3dlYnBhY2tfcmVxdWlyZV9fKTtcblxuIFx0XHQvLyBGbGFnIHRoZSBtb2R1bGUgYXMgbG9hZGVkXG4gXHRcdG1vZHVsZS5sb2FkZWQgPSB0cnVlO1xuXG4gXHRcdC8vIFJldHVybiB0aGUgZXhwb3J0cyBvZiB0aGUgbW9kdWxlXG4gXHRcdHJldHVybiBtb2R1bGUuZXhwb3J0cztcbiBcdH1cblxuXG4gXHQvLyBleHBvc2UgdGhlIG1vZHVsZXMgb2JqZWN0IChfX3dlYnBhY2tfbW9kdWxlc19fKVxuIFx0X193ZWJwYWNrX3JlcXVpcmVfXy5tID0gbW9kdWxlcztcblxuIFx0Ly8gZXhwb3NlIHRoZSBtb2R1bGUgY2FjaGVcbiBcdF9fd2VicGFja19yZXF1aXJlX18uYyA9IGluc3RhbGxlZE1vZHVsZXM7XG5cbiBcdC8vIF9fd2VicGFja19wdWJsaWNfcGF0aF9fXG4gXHRfX3dlYnBhY2tfcmVxdWlyZV9fLnAgPSBcIlwiO1xuXG4gXHQvLyBMb2FkIGVudHJ5IG1vZHVsZSBhbmQgcmV0dXJuIGV4cG9ydHNcbiBcdHJldHVybiBfX3dlYnBhY2tfcmVxdWlyZV9fKDApO1xuXG5cblxuLy8gV0VCUEFDSyBGT09URVIgLy9cbi8vIHdlYnBhY2svYm9vdHN0cmFwIGU0NzM4ZmM3MmE3YjIzMDM5ODg5IiwiLypcbiAqIENvcHlyaWdodCAyMDA5LTIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFLnR4dCBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuZXhwb3J0cy5Tb3VyY2VNYXBHZW5lcmF0b3IgPSByZXF1aXJlKCcuL2xpYi9zb3VyY2UtbWFwLWdlbmVyYXRvcicpLlNvdXJjZU1hcEdlbmVyYXRvcjtcbmV4cG9ydHMuU291cmNlTWFwQ29uc3VtZXIgPSByZXF1aXJlKCcuL2xpYi9zb3VyY2UtbWFwLWNvbnN1bWVyJykuU291cmNlTWFwQ29uc3VtZXI7XG5leHBvcnRzLlNvdXJjZU5vZGUgPSByZXF1aXJlKCcuL2xpYi9zb3VyY2Utbm9kZScpLlNvdXJjZU5vZGU7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL3NvdXJjZS1tYXAuanNcbi8vIG1vZHVsZSBpZCA9IDBcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgYmFzZTY0VkxRID0gcmVxdWlyZSgnLi9iYXNlNjQtdmxxJyk7XG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIEFycmF5U2V0ID0gcmVxdWlyZSgnLi9hcnJheS1zZXQnKS5BcnJheVNldDtcbnZhciBNYXBwaW5nTGlzdCA9IHJlcXVpcmUoJy4vbWFwcGluZy1saXN0JykuTWFwcGluZ0xpc3Q7XG5cbi8qKlxuICogQW4gaW5zdGFuY2Ugb2YgdGhlIFNvdXJjZU1hcEdlbmVyYXRvciByZXByZXNlbnRzIGEgc291cmNlIG1hcCB3aGljaCBpc1xuICogYmVpbmcgYnVpbHQgaW5jcmVtZW50YWxseS4gWW91IG1heSBwYXNzIGFuIG9iamVjdCB3aXRoIHRoZSBmb2xsb3dpbmdcbiAqIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGZpbGU6IFRoZSBmaWxlbmFtZSBvZiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS5cbiAqICAgLSBzb3VyY2VSb290OiBBIHJvb3QgZm9yIGFsbCByZWxhdGl2ZSBVUkxzIGluIHRoaXMgc291cmNlIG1hcC5cbiAqL1xuZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yKGFBcmdzKSB7XG4gIGlmICghYUFyZ3MpIHtcbiAgICBhQXJncyA9IHt9O1xuICB9XG4gIHRoaXMuX2ZpbGUgPSB1dGlsLmdldEFyZyhhQXJncywgJ2ZpbGUnLCBudWxsKTtcbiAgdGhpcy5fc291cmNlUm9vdCA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlUm9vdCcsIG51bGwpO1xuICB0aGlzLl9za2lwVmFsaWRhdGlvbiA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc2tpcFZhbGlkYXRpb24nLCBmYWxzZSk7XG4gIHRoaXMuX3NvdXJjZXMgPSBuZXcgQXJyYXlTZXQoKTtcbiAgdGhpcy5fbmFtZXMgPSBuZXcgQXJyYXlTZXQoKTtcbiAgdGhpcy5fbWFwcGluZ3MgPSBuZXcgTWFwcGluZ0xpc3QoKTtcbiAgdGhpcy5fc291cmNlc0NvbnRlbnRzID0gbnVsbDtcbn1cblxuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogQ3JlYXRlcyBhIG5ldyBTb3VyY2VNYXBHZW5lcmF0b3IgYmFzZWQgb24gYSBTb3VyY2VNYXBDb25zdW1lclxuICpcbiAqIEBwYXJhbSBhU291cmNlTWFwQ29uc3VtZXIgVGhlIFNvdXJjZU1hcC5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLmZyb21Tb3VyY2VNYXAgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfZnJvbVNvdXJjZU1hcChhU291cmNlTWFwQ29uc3VtZXIpIHtcbiAgICB2YXIgc291cmNlUm9vdCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VSb290O1xuICAgIHZhciBnZW5lcmF0b3IgPSBuZXcgU291cmNlTWFwR2VuZXJhdG9yKHtcbiAgICAgIGZpbGU6IGFTb3VyY2VNYXBDb25zdW1lci5maWxlLFxuICAgICAgc291cmNlUm9vdDogc291cmNlUm9vdFxuICAgIH0pO1xuICAgIGFTb3VyY2VNYXBDb25zdW1lci5lYWNoTWFwcGluZyhmdW5jdGlvbiAobWFwcGluZykge1xuICAgICAgdmFyIG5ld01hcHBpbmcgPSB7XG4gICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgIGxpbmU6IG1hcHBpbmcuZ2VuZXJhdGVkTGluZSxcbiAgICAgICAgICBjb2x1bW46IG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uXG4gICAgICAgIH1cbiAgICAgIH07XG5cbiAgICAgIGlmIChtYXBwaW5nLnNvdXJjZSAhPSBudWxsKSB7XG4gICAgICAgIG5ld01hcHBpbmcuc291cmNlID0gbWFwcGluZy5zb3VyY2U7XG4gICAgICAgIGlmIChzb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgICAgICBuZXdNYXBwaW5nLnNvdXJjZSA9IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgbmV3TWFwcGluZy5zb3VyY2UpO1xuICAgICAgICB9XG5cbiAgICAgICAgbmV3TWFwcGluZy5vcmlnaW5hbCA9IHtcbiAgICAgICAgICBsaW5lOiBtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICBjb2x1bW46IG1hcHBpbmcub3JpZ2luYWxDb2x1bW5cbiAgICAgICAgfTtcblxuICAgICAgICBpZiAobWFwcGluZy5uYW1lICE9IG51bGwpIHtcbiAgICAgICAgICBuZXdNYXBwaW5nLm5hbWUgPSBtYXBwaW5nLm5hbWU7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgZ2VuZXJhdG9yLmFkZE1hcHBpbmcobmV3TWFwcGluZyk7XG4gICAgfSk7XG4gICAgYVNvdXJjZU1hcENvbnN1bWVyLnNvdXJjZXMuZm9yRWFjaChmdW5jdGlvbiAoc291cmNlRmlsZSkge1xuICAgICAgdmFyIGNvbnRlbnQgPSBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlQ29udGVudEZvcihzb3VyY2VGaWxlKTtcbiAgICAgIGlmIChjb250ZW50ICE9IG51bGwpIHtcbiAgICAgICAgZ2VuZXJhdG9yLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG4gICAgcmV0dXJuIGdlbmVyYXRvcjtcbiAgfTtcblxuLyoqXG4gKiBBZGQgYSBzaW5nbGUgbWFwcGluZyBmcm9tIG9yaWdpbmFsIHNvdXJjZSBsaW5lIGFuZCBjb2x1bW4gdG8gdGhlIGdlbmVyYXRlZFxuICogc291cmNlJ3MgbGluZSBhbmQgY29sdW1uIGZvciB0aGlzIHNvdXJjZSBtYXAgYmVpbmcgY3JlYXRlZC4gVGhlIG1hcHBpbmdcbiAqIG9iamVjdCBzaG91bGQgaGF2ZSB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGdlbmVyYXRlZDogQW4gb2JqZWN0IHdpdGggdGhlIGdlbmVyYXRlZCBsaW5lIGFuZCBjb2x1bW4gcG9zaXRpb25zLlxuICogICAtIG9yaWdpbmFsOiBBbiBvYmplY3Qgd2l0aCB0aGUgb3JpZ2luYWwgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucy5cbiAqICAgLSBzb3VyY2U6IFRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZSAocmVsYXRpdmUgdG8gdGhlIHNvdXJjZVJvb3QpLlxuICogICAtIG5hbWU6IEFuIG9wdGlvbmFsIG9yaWdpbmFsIHRva2VuIG5hbWUgZm9yIHRoaXMgbWFwcGluZy5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5hZGRNYXBwaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX2FkZE1hcHBpbmcoYUFyZ3MpIHtcbiAgICB2YXIgZ2VuZXJhdGVkID0gdXRpbC5nZXRBcmcoYUFyZ3MsICdnZW5lcmF0ZWQnKTtcbiAgICB2YXIgb3JpZ2luYWwgPSB1dGlsLmdldEFyZyhhQXJncywgJ29yaWdpbmFsJywgbnVsbCk7XG4gICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJywgbnVsbCk7XG4gICAgdmFyIG5hbWUgPSB1dGlsLmdldEFyZyhhQXJncywgJ25hbWUnLCBudWxsKTtcblxuICAgIGlmICghdGhpcy5fc2tpcFZhbGlkYXRpb24pIHtcbiAgICAgIHRoaXMuX3ZhbGlkYXRlTWFwcGluZyhnZW5lcmF0ZWQsIG9yaWdpbmFsLCBzb3VyY2UsIG5hbWUpO1xuICAgIH1cblxuICAgIGlmIChzb3VyY2UgIT0gbnVsbCkge1xuICAgICAgc291cmNlID0gU3RyaW5nKHNvdXJjZSk7XG4gICAgICBpZiAoIXRoaXMuX3NvdXJjZXMuaGFzKHNvdXJjZSkpIHtcbiAgICAgICAgdGhpcy5fc291cmNlcy5hZGQoc291cmNlKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICBpZiAobmFtZSAhPSBudWxsKSB7XG4gICAgICBuYW1lID0gU3RyaW5nKG5hbWUpO1xuICAgICAgaWYgKCF0aGlzLl9uYW1lcy5oYXMobmFtZSkpIHtcbiAgICAgICAgdGhpcy5fbmFtZXMuYWRkKG5hbWUpO1xuICAgICAgfVxuICAgIH1cblxuICAgIHRoaXMuX21hcHBpbmdzLmFkZCh7XG4gICAgICBnZW5lcmF0ZWRMaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgIGdlbmVyYXRlZENvbHVtbjogZ2VuZXJhdGVkLmNvbHVtbixcbiAgICAgIG9yaWdpbmFsTGluZTogb3JpZ2luYWwgIT0gbnVsbCAmJiBvcmlnaW5hbC5saW5lLFxuICAgICAgb3JpZ2luYWxDb2x1bW46IG9yaWdpbmFsICE9IG51bGwgJiYgb3JpZ2luYWwuY29sdW1uLFxuICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICBuYW1lOiBuYW1lXG4gICAgfSk7XG4gIH07XG5cbi8qKlxuICogU2V0IHRoZSBzb3VyY2UgY29udGVudCBmb3IgYSBzb3VyY2UgZmlsZS5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5zZXRTb3VyY2VDb250ZW50ID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX3NldFNvdXJjZUNvbnRlbnQoYVNvdXJjZUZpbGUsIGFTb3VyY2VDb250ZW50KSB7XG4gICAgdmFyIHNvdXJjZSA9IGFTb3VyY2VGaWxlO1xuICAgIGlmICh0aGlzLl9zb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgIHNvdXJjZSA9IHV0aWwucmVsYXRpdmUodGhpcy5fc291cmNlUm9vdCwgc291cmNlKTtcbiAgICB9XG5cbiAgICBpZiAoYVNvdXJjZUNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgLy8gQWRkIHRoZSBzb3VyY2UgY29udGVudCB0byB0aGUgX3NvdXJjZXNDb250ZW50cyBtYXAuXG4gICAgICAvLyBDcmVhdGUgYSBuZXcgX3NvdXJjZXNDb250ZW50cyBtYXAgaWYgdGhlIHByb3BlcnR5IGlzIG51bGwuXG4gICAgICBpZiAoIXRoaXMuX3NvdXJjZXNDb250ZW50cykge1xuICAgICAgICB0aGlzLl9zb3VyY2VzQ29udGVudHMgPSBPYmplY3QuY3JlYXRlKG51bGwpO1xuICAgICAgfVxuICAgICAgdGhpcy5fc291cmNlc0NvbnRlbnRzW3V0aWwudG9TZXRTdHJpbmcoc291cmNlKV0gPSBhU291cmNlQ29udGVudDtcbiAgICB9IGVsc2UgaWYgKHRoaXMuX3NvdXJjZXNDb250ZW50cykge1xuICAgICAgLy8gUmVtb3ZlIHRoZSBzb3VyY2UgZmlsZSBmcm9tIHRoZSBfc291cmNlc0NvbnRlbnRzIG1hcC5cbiAgICAgIC8vIElmIHRoZSBfc291cmNlc0NvbnRlbnRzIG1hcCBpcyBlbXB0eSwgc2V0IHRoZSBwcm9wZXJ0eSB0byBudWxsLlxuICAgICAgZGVsZXRlIHRoaXMuX3NvdXJjZXNDb250ZW50c1t1dGlsLnRvU2V0U3RyaW5nKHNvdXJjZSldO1xuICAgICAgaWYgKE9iamVjdC5rZXlzKHRoaXMuX3NvdXJjZXNDb250ZW50cykubGVuZ3RoID09PSAwKSB7XG4gICAgICAgIHRoaXMuX3NvdXJjZXNDb250ZW50cyA9IG51bGw7XG4gICAgICB9XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIEFwcGxpZXMgdGhlIG1hcHBpbmdzIG9mIGEgc3ViLXNvdXJjZS1tYXAgZm9yIGEgc3BlY2lmaWMgc291cmNlIGZpbGUgdG8gdGhlXG4gKiBzb3VyY2UgbWFwIGJlaW5nIGdlbmVyYXRlZC4gRWFjaCBtYXBwaW5nIHRvIHRoZSBzdXBwbGllZCBzb3VyY2UgZmlsZSBpc1xuICogcmV3cml0dGVuIHVzaW5nIHRoZSBzdXBwbGllZCBzb3VyY2UgbWFwLiBOb3RlOiBUaGUgcmVzb2x1dGlvbiBmb3IgdGhlXG4gKiByZXN1bHRpbmcgbWFwcGluZ3MgaXMgdGhlIG1pbmltaXVtIG9mIHRoaXMgbWFwIGFuZCB0aGUgc3VwcGxpZWQgbWFwLlxuICpcbiAqIEBwYXJhbSBhU291cmNlTWFwQ29uc3VtZXIgVGhlIHNvdXJjZSBtYXAgdG8gYmUgYXBwbGllZC5cbiAqIEBwYXJhbSBhU291cmNlRmlsZSBPcHRpb25hbC4gVGhlIGZpbGVuYW1lIG9mIHRoZSBzb3VyY2UgZmlsZS5cbiAqICAgICAgICBJZiBvbWl0dGVkLCBTb3VyY2VNYXBDb25zdW1lcidzIGZpbGUgcHJvcGVydHkgd2lsbCBiZSB1c2VkLlxuICogQHBhcmFtIGFTb3VyY2VNYXBQYXRoIE9wdGlvbmFsLiBUaGUgZGlybmFtZSBvZiB0aGUgcGF0aCB0byB0aGUgc291cmNlIG1hcFxuICogICAgICAgIHRvIGJlIGFwcGxpZWQuIElmIHJlbGF0aXZlLCBpdCBpcyByZWxhdGl2ZSB0byB0aGUgU291cmNlTWFwQ29uc3VtZXIuXG4gKiAgICAgICAgVGhpcyBwYXJhbWV0ZXIgaXMgbmVlZGVkIHdoZW4gdGhlIHR3byBzb3VyY2UgbWFwcyBhcmVuJ3QgaW4gdGhlIHNhbWVcbiAqICAgICAgICBkaXJlY3RvcnksIGFuZCB0aGUgc291cmNlIG1hcCB0byBiZSBhcHBsaWVkIGNvbnRhaW5zIHJlbGF0aXZlIHNvdXJjZVxuICogICAgICAgIHBhdGhzLiBJZiBzbywgdGhvc2UgcmVsYXRpdmUgc291cmNlIHBhdGhzIG5lZWQgdG8gYmUgcmV3cml0dGVuXG4gKiAgICAgICAgcmVsYXRpdmUgdG8gdGhlIFNvdXJjZU1hcEdlbmVyYXRvci5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5hcHBseVNvdXJjZU1hcCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9hcHBseVNvdXJjZU1hcChhU291cmNlTWFwQ29uc3VtZXIsIGFTb3VyY2VGaWxlLCBhU291cmNlTWFwUGF0aCkge1xuICAgIHZhciBzb3VyY2VGaWxlID0gYVNvdXJjZUZpbGU7XG4gICAgLy8gSWYgYVNvdXJjZUZpbGUgaXMgb21pdHRlZCwgd2Ugd2lsbCB1c2UgdGhlIGZpbGUgcHJvcGVydHkgb2YgdGhlIFNvdXJjZU1hcFxuICAgIGlmIChhU291cmNlRmlsZSA9PSBudWxsKSB7XG4gICAgICBpZiAoYVNvdXJjZU1hcENvbnN1bWVyLmZpbGUgPT0gbnVsbCkge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoXG4gICAgICAgICAgJ1NvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUuYXBwbHlTb3VyY2VNYXAgcmVxdWlyZXMgZWl0aGVyIGFuIGV4cGxpY2l0IHNvdXJjZSBmaWxlLCAnICtcbiAgICAgICAgICAnb3IgdGhlIHNvdXJjZSBtYXBcXCdzIFwiZmlsZVwiIHByb3BlcnR5LiBCb3RoIHdlcmUgb21pdHRlZC4nXG4gICAgICAgICk7XG4gICAgICB9XG4gICAgICBzb3VyY2VGaWxlID0gYVNvdXJjZU1hcENvbnN1bWVyLmZpbGU7XG4gICAgfVxuICAgIHZhciBzb3VyY2VSb290ID0gdGhpcy5fc291cmNlUm9vdDtcbiAgICAvLyBNYWtlIFwic291cmNlRmlsZVwiIHJlbGF0aXZlIGlmIGFuIGFic29sdXRlIFVybCBpcyBwYXNzZWQuXG4gICAgaWYgKHNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgc291cmNlRmlsZSA9IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgc291cmNlRmlsZSk7XG4gICAgfVxuICAgIC8vIEFwcGx5aW5nIHRoZSBTb3VyY2VNYXAgY2FuIGFkZCBhbmQgcmVtb3ZlIGl0ZW1zIGZyb20gdGhlIHNvdXJjZXMgYW5kXG4gICAgLy8gdGhlIG5hbWVzIGFycmF5LlxuICAgIHZhciBuZXdTb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gICAgdmFyIG5ld05hbWVzID0gbmV3IEFycmF5U2V0KCk7XG5cbiAgICAvLyBGaW5kIG1hcHBpbmdzIGZvciB0aGUgXCJzb3VyY2VGaWxlXCJcbiAgICB0aGlzLl9tYXBwaW5ncy51bnNvcnRlZEZvckVhY2goZnVuY3Rpb24gKG1hcHBpbmcpIHtcbiAgICAgIGlmIChtYXBwaW5nLnNvdXJjZSA9PT0gc291cmNlRmlsZSAmJiBtYXBwaW5nLm9yaWdpbmFsTGluZSAhPSBudWxsKSB7XG4gICAgICAgIC8vIENoZWNrIGlmIGl0IGNhbiBiZSBtYXBwZWQgYnkgdGhlIHNvdXJjZSBtYXAsIHRoZW4gdXBkYXRlIHRoZSBtYXBwaW5nLlxuICAgICAgICB2YXIgb3JpZ2luYWwgPSBhU291cmNlTWFwQ29uc3VtZXIub3JpZ2luYWxQb3NpdGlvbkZvcih7XG4gICAgICAgICAgbGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgICAgY29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uXG4gICAgICAgIH0pO1xuICAgICAgICBpZiAob3JpZ2luYWwuc291cmNlICE9IG51bGwpIHtcbiAgICAgICAgICAvLyBDb3B5IG1hcHBpbmdcbiAgICAgICAgICBtYXBwaW5nLnNvdXJjZSA9IG9yaWdpbmFsLnNvdXJjZTtcbiAgICAgICAgICBpZiAoYVNvdXJjZU1hcFBhdGggIT0gbnVsbCkge1xuICAgICAgICAgICAgbWFwcGluZy5zb3VyY2UgPSB1dGlsLmpvaW4oYVNvdXJjZU1hcFBhdGgsIG1hcHBpbmcuc291cmNlKVxuICAgICAgICAgIH1cbiAgICAgICAgICBpZiAoc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICAgICAgICBtYXBwaW5nLnNvdXJjZSA9IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgbWFwcGluZy5zb3VyY2UpO1xuICAgICAgICAgIH1cbiAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsTGluZSA9IG9yaWdpbmFsLmxpbmU7XG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbiA9IG9yaWdpbmFsLmNvbHVtbjtcbiAgICAgICAgICBpZiAob3JpZ2luYWwubmFtZSAhPSBudWxsKSB7XG4gICAgICAgICAgICBtYXBwaW5nLm5hbWUgPSBvcmlnaW5hbC5uYW1lO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICB2YXIgc291cmNlID0gbWFwcGluZy5zb3VyY2U7XG4gICAgICBpZiAoc291cmNlICE9IG51bGwgJiYgIW5ld1NvdXJjZXMuaGFzKHNvdXJjZSkpIHtcbiAgICAgICAgbmV3U291cmNlcy5hZGQoc291cmNlKTtcbiAgICAgIH1cblxuICAgICAgdmFyIG5hbWUgPSBtYXBwaW5nLm5hbWU7XG4gICAgICBpZiAobmFtZSAhPSBudWxsICYmICFuZXdOYW1lcy5oYXMobmFtZSkpIHtcbiAgICAgICAgbmV3TmFtZXMuYWRkKG5hbWUpO1xuICAgICAgfVxuXG4gICAgfSwgdGhpcyk7XG4gICAgdGhpcy5fc291cmNlcyA9IG5ld1NvdXJjZXM7XG4gICAgdGhpcy5fbmFtZXMgPSBuZXdOYW1lcztcblxuICAgIC8vIENvcHkgc291cmNlc0NvbnRlbnRzIG9mIGFwcGxpZWQgbWFwLlxuICAgIGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VzLmZvckVhY2goZnVuY3Rpb24gKHNvdXJjZUZpbGUpIHtcbiAgICAgIHZhciBjb250ZW50ID0gYVNvdXJjZU1hcENvbnN1bWVyLnNvdXJjZUNvbnRlbnRGb3Ioc291cmNlRmlsZSk7XG4gICAgICBpZiAoY29udGVudCAhPSBudWxsKSB7XG4gICAgICAgIGlmIChhU291cmNlTWFwUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhU291cmNlTWFwUGF0aCwgc291cmNlRmlsZSk7XG4gICAgICAgIH1cbiAgICAgICAgaWYgKHNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZUZpbGUgPSB1dGlsLnJlbGF0aXZlKHNvdXJjZVJvb3QsIHNvdXJjZUZpbGUpO1xuICAgICAgICB9XG4gICAgICAgIHRoaXMuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBjb250ZW50KTtcbiAgICAgIH1cbiAgICB9LCB0aGlzKTtcbiAgfTtcblxuLyoqXG4gKiBBIG1hcHBpbmcgY2FuIGhhdmUgb25lIG9mIHRoZSB0aHJlZSBsZXZlbHMgb2YgZGF0YTpcbiAqXG4gKiAgIDEuIEp1c3QgdGhlIGdlbmVyYXRlZCBwb3NpdGlvbi5cbiAqICAgMi4gVGhlIEdlbmVyYXRlZCBwb3NpdGlvbiwgb3JpZ2luYWwgcG9zaXRpb24sIGFuZCBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIDMuIEdlbmVyYXRlZCBhbmQgb3JpZ2luYWwgcG9zaXRpb24sIG9yaWdpbmFsIHNvdXJjZSwgYXMgd2VsbCBhcyBhIG5hbWVcbiAqICAgICAgdG9rZW4uXG4gKlxuICogVG8gbWFpbnRhaW4gY29uc2lzdGVuY3ksIHdlIHZhbGlkYXRlIHRoYXQgYW55IG5ldyBtYXBwaW5nIGJlaW5nIGFkZGVkIGZhbGxzXG4gKiBpbiB0byBvbmUgb2YgdGhlc2UgY2F0ZWdvcmllcy5cbiAqL1xuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5fdmFsaWRhdGVNYXBwaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwR2VuZXJhdG9yX3ZhbGlkYXRlTWFwcGluZyhhR2VuZXJhdGVkLCBhT3JpZ2luYWwsIGFTb3VyY2UsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYU5hbWUpIHtcbiAgICAvLyBXaGVuIGFPcmlnaW5hbCBpcyB0cnV0aHkgYnV0IGhhcyBlbXB0eSB2YWx1ZXMgZm9yIC5saW5lIGFuZCAuY29sdW1uLFxuICAgIC8vIGl0IGlzIG1vc3QgbGlrZWx5IGEgcHJvZ3JhbW1lciBlcnJvci4gSW4gdGhpcyBjYXNlIHdlIHRocm93IGEgdmVyeVxuICAgIC8vIHNwZWNpZmljIGVycm9yIG1lc3NhZ2UgdG8gdHJ5IHRvIGd1aWRlIHRoZW0gdGhlIHJpZ2h0IHdheS5cbiAgICAvLyBGb3IgZXhhbXBsZTogaHR0cHM6Ly9naXRodWIuY29tL1BvbHltZXIvcG9seW1lci1idW5kbGVyL3B1bGwvNTE5XG4gICAgaWYgKGFPcmlnaW5hbCAmJiB0eXBlb2YgYU9yaWdpbmFsLmxpbmUgIT09ICdudW1iZXInICYmIHR5cGVvZiBhT3JpZ2luYWwuY29sdW1uICE9PSAnbnVtYmVyJykge1xuICAgICAgICB0aHJvdyBuZXcgRXJyb3IoXG4gICAgICAgICAgICAnb3JpZ2luYWwubGluZSBhbmQgb3JpZ2luYWwuY29sdW1uIGFyZSBub3QgbnVtYmVycyAtLSB5b3UgcHJvYmFibHkgbWVhbnQgdG8gb21pdCAnICtcbiAgICAgICAgICAgICd0aGUgb3JpZ2luYWwgbWFwcGluZyBlbnRpcmVseSBhbmQgb25seSBtYXAgdGhlIGdlbmVyYXRlZCBwb3NpdGlvbi4gSWYgc28sIHBhc3MgJyArXG4gICAgICAgICAgICAnbnVsbCBmb3IgdGhlIG9yaWdpbmFsIG1hcHBpbmcgaW5zdGVhZCBvZiBhbiBvYmplY3Qgd2l0aCBlbXB0eSBvciBudWxsIHZhbHVlcy4nXG4gICAgICAgICk7XG4gICAgfVxuXG4gICAgaWYgKGFHZW5lcmF0ZWQgJiYgJ2xpbmUnIGluIGFHZW5lcmF0ZWQgJiYgJ2NvbHVtbicgaW4gYUdlbmVyYXRlZFxuICAgICAgICAmJiBhR2VuZXJhdGVkLmxpbmUgPiAwICYmIGFHZW5lcmF0ZWQuY29sdW1uID49IDBcbiAgICAgICAgJiYgIWFPcmlnaW5hbCAmJiAhYVNvdXJjZSAmJiAhYU5hbWUpIHtcbiAgICAgIC8vIENhc2UgMS5cbiAgICAgIHJldHVybjtcbiAgICB9XG4gICAgZWxzZSBpZiAoYUdlbmVyYXRlZCAmJiAnbGluZScgaW4gYUdlbmVyYXRlZCAmJiAnY29sdW1uJyBpbiBhR2VuZXJhdGVkXG4gICAgICAgICAgICAgJiYgYU9yaWdpbmFsICYmICdsaW5lJyBpbiBhT3JpZ2luYWwgJiYgJ2NvbHVtbicgaW4gYU9yaWdpbmFsXG4gICAgICAgICAgICAgJiYgYUdlbmVyYXRlZC5saW5lID4gMCAmJiBhR2VuZXJhdGVkLmNvbHVtbiA+PSAwXG4gICAgICAgICAgICAgJiYgYU9yaWdpbmFsLmxpbmUgPiAwICYmIGFPcmlnaW5hbC5jb2x1bW4gPj0gMFxuICAgICAgICAgICAgICYmIGFTb3VyY2UpIHtcbiAgICAgIC8vIENhc2VzIDIgYW5kIDMuXG4gICAgICByZXR1cm47XG4gICAgfVxuICAgIGVsc2Uge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKCdJbnZhbGlkIG1hcHBpbmc6ICcgKyBKU09OLnN0cmluZ2lmeSh7XG4gICAgICAgIGdlbmVyYXRlZDogYUdlbmVyYXRlZCxcbiAgICAgICAgc291cmNlOiBhU291cmNlLFxuICAgICAgICBvcmlnaW5hbDogYU9yaWdpbmFsLFxuICAgICAgICBuYW1lOiBhTmFtZVxuICAgICAgfSkpO1xuICAgIH1cbiAgfTtcblxuLyoqXG4gKiBTZXJpYWxpemUgdGhlIGFjY3VtdWxhdGVkIG1hcHBpbmdzIGluIHRvIHRoZSBzdHJlYW0gb2YgYmFzZSA2NCBWTFFzXG4gKiBzcGVjaWZpZWQgYnkgdGhlIHNvdXJjZSBtYXAgZm9ybWF0LlxuICovXG5Tb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLl9zZXJpYWxpemVNYXBwaW5ncyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9zZXJpYWxpemVNYXBwaW5ncygpIHtcbiAgICB2YXIgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSAwO1xuICAgIHZhciBwcmV2aW91c0dlbmVyYXRlZExpbmUgPSAxO1xuICAgIHZhciBwcmV2aW91c09yaWdpbmFsQ29sdW1uID0gMDtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbExpbmUgPSAwO1xuICAgIHZhciBwcmV2aW91c05hbWUgPSAwO1xuICAgIHZhciBwcmV2aW91c1NvdXJjZSA9IDA7XG4gICAgdmFyIHJlc3VsdCA9ICcnO1xuICAgIHZhciBuZXh0O1xuICAgIHZhciBtYXBwaW5nO1xuICAgIHZhciBuYW1lSWR4O1xuICAgIHZhciBzb3VyY2VJZHg7XG5cbiAgICB2YXIgbWFwcGluZ3MgPSB0aGlzLl9tYXBwaW5ncy50b0FycmF5KCk7XG4gICAgZm9yICh2YXIgaSA9IDAsIGxlbiA9IG1hcHBpbmdzLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICBtYXBwaW5nID0gbWFwcGluZ3NbaV07XG4gICAgICBuZXh0ID0gJydcblxuICAgICAgaWYgKG1hcHBpbmcuZ2VuZXJhdGVkTGluZSAhPT0gcHJldmlvdXNHZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgIHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgICAgICAgd2hpbGUgKG1hcHBpbmcuZ2VuZXJhdGVkTGluZSAhPT0gcHJldmlvdXNHZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgICAgbmV4dCArPSAnOyc7XG4gICAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRMaW5lKys7XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIGVsc2Uge1xuICAgICAgICBpZiAoaSA+IDApIHtcbiAgICAgICAgICBpZiAoIXV0aWwuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zSW5mbGF0ZWQobWFwcGluZywgbWFwcGluZ3NbaSAtIDFdKSkge1xuICAgICAgICAgICAgY29udGludWU7XG4gICAgICAgICAgfVxuICAgICAgICAgIG5leHQgKz0gJywnO1xuICAgICAgICB9XG4gICAgICB9XG5cbiAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShtYXBwaW5nLmdlbmVyYXRlZENvbHVtblxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLSBwcmV2aW91c0dlbmVyYXRlZENvbHVtbik7XG4gICAgICBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uO1xuXG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgIT0gbnVsbCkge1xuICAgICAgICBzb3VyY2VJZHggPSB0aGlzLl9zb3VyY2VzLmluZGV4T2YobWFwcGluZy5zb3VyY2UpO1xuICAgICAgICBuZXh0ICs9IGJhc2U2NFZMUS5lbmNvZGUoc291cmNlSWR4IC0gcHJldmlvdXNTb3VyY2UpO1xuICAgICAgICBwcmV2aW91c1NvdXJjZSA9IHNvdXJjZUlkeDtcblxuICAgICAgICAvLyBsaW5lcyBhcmUgc3RvcmVkIDAtYmFzZWQgaW4gU291cmNlTWFwIHNwZWMgdmVyc2lvbiAzXG4gICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShtYXBwaW5nLm9yaWdpbmFsTGluZSAtIDFcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLSBwcmV2aW91c09yaWdpbmFsTGluZSk7XG4gICAgICAgIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gbWFwcGluZy5vcmlnaW5hbExpbmUgLSAxO1xuXG4gICAgICAgIG5leHQgKz0gYmFzZTY0VkxRLmVuY29kZShtYXBwaW5nLm9yaWdpbmFsQ29sdW1uXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0gcHJldmlvdXNPcmlnaW5hbENvbHVtbik7XG4gICAgICAgIHByZXZpb3VzT3JpZ2luYWxDb2x1bW4gPSBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uO1xuXG4gICAgICAgIGlmIChtYXBwaW5nLm5hbWUgIT0gbnVsbCkge1xuICAgICAgICAgIG5hbWVJZHggPSB0aGlzLl9uYW1lcy5pbmRleE9mKG1hcHBpbmcubmFtZSk7XG4gICAgICAgICAgbmV4dCArPSBiYXNlNjRWTFEuZW5jb2RlKG5hbWVJZHggLSBwcmV2aW91c05hbWUpO1xuICAgICAgICAgIHByZXZpb3VzTmFtZSA9IG5hbWVJZHg7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgcmVzdWx0ICs9IG5leHQ7XG4gICAgfVxuXG4gICAgcmV0dXJuIHJlc3VsdDtcbiAgfTtcblxuU291cmNlTWFwR2VuZXJhdG9yLnByb3RvdHlwZS5fZ2VuZXJhdGVTb3VyY2VzQ29udGVudCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl9nZW5lcmF0ZVNvdXJjZXNDb250ZW50KGFTb3VyY2VzLCBhU291cmNlUm9vdCkge1xuICAgIHJldHVybiBhU291cmNlcy5tYXAoZnVuY3Rpb24gKHNvdXJjZSkge1xuICAgICAgaWYgKCF0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgICAgcmV0dXJuIG51bGw7XG4gICAgICB9XG4gICAgICBpZiAoYVNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgICBzb3VyY2UgPSB1dGlsLnJlbGF0aXZlKGFTb3VyY2VSb290LCBzb3VyY2UpO1xuICAgICAgfVxuICAgICAgdmFyIGtleSA9IHV0aWwudG9TZXRTdHJpbmcoc291cmNlKTtcbiAgICAgIHJldHVybiBPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwodGhpcy5fc291cmNlc0NvbnRlbnRzLCBrZXkpXG4gICAgICAgID8gdGhpcy5fc291cmNlc0NvbnRlbnRzW2tleV1cbiAgICAgICAgOiBudWxsO1xuICAgIH0sIHRoaXMpO1xuICB9O1xuXG4vKipcbiAqIEV4dGVybmFsaXplIHRoZSBzb3VyY2UgbWFwLlxuICovXG5Tb3VyY2VNYXBHZW5lcmF0b3IucHJvdG90eXBlLnRvSlNPTiA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcEdlbmVyYXRvcl90b0pTT04oKSB7XG4gICAgdmFyIG1hcCA9IHtcbiAgICAgIHZlcnNpb246IHRoaXMuX3ZlcnNpb24sXG4gICAgICBzb3VyY2VzOiB0aGlzLl9zb3VyY2VzLnRvQXJyYXkoKSxcbiAgICAgIG5hbWVzOiB0aGlzLl9uYW1lcy50b0FycmF5KCksXG4gICAgICBtYXBwaW5nczogdGhpcy5fc2VyaWFsaXplTWFwcGluZ3MoKVxuICAgIH07XG4gICAgaWYgKHRoaXMuX2ZpbGUgIT0gbnVsbCkge1xuICAgICAgbWFwLmZpbGUgPSB0aGlzLl9maWxlO1xuICAgIH1cbiAgICBpZiAodGhpcy5fc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICBtYXAuc291cmNlUm9vdCA9IHRoaXMuX3NvdXJjZVJvb3Q7XG4gICAgfVxuICAgIGlmICh0aGlzLl9zb3VyY2VzQ29udGVudHMpIHtcbiAgICAgIG1hcC5zb3VyY2VzQ29udGVudCA9IHRoaXMuX2dlbmVyYXRlU291cmNlc0NvbnRlbnQobWFwLnNvdXJjZXMsIG1hcC5zb3VyY2VSb290KTtcbiAgICB9XG5cbiAgICByZXR1cm4gbWFwO1xuICB9O1xuXG4vKipcbiAqIFJlbmRlciB0aGUgc291cmNlIG1hcCBiZWluZyBnZW5lcmF0ZWQgdG8gYSBzdHJpbmcuXG4gKi9cblNvdXJjZU1hcEdlbmVyYXRvci5wcm90b3R5cGUudG9TdHJpbmcgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBHZW5lcmF0b3JfdG9TdHJpbmcoKSB7XG4gICAgcmV0dXJuIEpTT04uc3RyaW5naWZ5KHRoaXMudG9KU09OKCkpO1xuICB9O1xuXG5leHBvcnRzLlNvdXJjZU1hcEdlbmVyYXRvciA9IFNvdXJjZU1hcEdlbmVyYXRvcjtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL3NvdXJjZS1tYXAtZ2VuZXJhdG9yLmpzXG4vLyBtb2R1bGUgaWQgPSAxXG4vLyBtb2R1bGUgY2h1bmtzID0gMCIsIi8qIC0qLSBNb2RlOiBqczsganMtaW5kZW50LWxldmVsOiAyOyAtKi0gKi9cbi8qXG4gKiBDb3B5cmlnaHQgMjAxMSBNb3ppbGxhIEZvdW5kYXRpb24gYW5kIGNvbnRyaWJ1dG9yc1xuICogTGljZW5zZWQgdW5kZXIgdGhlIE5ldyBCU0QgbGljZW5zZS4gU2VlIExJQ0VOU0Ugb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKlxuICogQmFzZWQgb24gdGhlIEJhc2UgNjQgVkxRIGltcGxlbWVudGF0aW9uIGluIENsb3N1cmUgQ29tcGlsZXI6XG4gKiBodHRwczovL2NvZGUuZ29vZ2xlLmNvbS9wL2Nsb3N1cmUtY29tcGlsZXIvc291cmNlL2Jyb3dzZS90cnVuay9zcmMvY29tL2dvb2dsZS9kZWJ1Z2dpbmcvc291cmNlbWFwL0Jhc2U2NFZMUS5qYXZhXG4gKlxuICogQ29weXJpZ2h0IDIwMTEgVGhlIENsb3N1cmUgQ29tcGlsZXIgQXV0aG9ycy4gQWxsIHJpZ2h0cyByZXNlcnZlZC5cbiAqIFJlZGlzdHJpYnV0aW9uIGFuZCB1c2UgaW4gc291cmNlIGFuZCBiaW5hcnkgZm9ybXMsIHdpdGggb3Igd2l0aG91dFxuICogbW9kaWZpY2F0aW9uLCBhcmUgcGVybWl0dGVkIHByb3ZpZGVkIHRoYXQgdGhlIGZvbGxvd2luZyBjb25kaXRpb25zIGFyZVxuICogbWV0OlxuICpcbiAqICAqIFJlZGlzdHJpYnV0aW9ucyBvZiBzb3VyY2UgY29kZSBtdXN0IHJldGFpbiB0aGUgYWJvdmUgY29weXJpZ2h0XG4gKiAgICBub3RpY2UsIHRoaXMgbGlzdCBvZiBjb25kaXRpb25zIGFuZCB0aGUgZm9sbG93aW5nIGRpc2NsYWltZXIuXG4gKiAgKiBSZWRpc3RyaWJ1dGlvbnMgaW4gYmluYXJ5IGZvcm0gbXVzdCByZXByb2R1Y2UgdGhlIGFib3ZlXG4gKiAgICBjb3B5cmlnaHQgbm90aWNlLCB0aGlzIGxpc3Qgb2YgY29uZGl0aW9ucyBhbmQgdGhlIGZvbGxvd2luZ1xuICogICAgZGlzY2xhaW1lciBpbiB0aGUgZG9jdW1lbnRhdGlvbiBhbmQvb3Igb3RoZXIgbWF0ZXJpYWxzIHByb3ZpZGVkXG4gKiAgICB3aXRoIHRoZSBkaXN0cmlidXRpb24uXG4gKiAgKiBOZWl0aGVyIHRoZSBuYW1lIG9mIEdvb2dsZSBJbmMuIG5vciB0aGUgbmFtZXMgb2YgaXRzXG4gKiAgICBjb250cmlidXRvcnMgbWF5IGJlIHVzZWQgdG8gZW5kb3JzZSBvciBwcm9tb3RlIHByb2R1Y3RzIGRlcml2ZWRcbiAqICAgIGZyb20gdGhpcyBzb2Z0d2FyZSB3aXRob3V0IHNwZWNpZmljIHByaW9yIHdyaXR0ZW4gcGVybWlzc2lvbi5cbiAqXG4gKiBUSElTIFNPRlRXQVJFIElTIFBST1ZJREVEIEJZIFRIRSBDT1BZUklHSFQgSE9MREVSUyBBTkQgQ09OVFJJQlVUT1JTXG4gKiBcIkFTIElTXCIgQU5EIEFOWSBFWFBSRVNTIE9SIElNUExJRUQgV0FSUkFOVElFUywgSU5DTFVESU5HLCBCVVQgTk9UXG4gKiBMSU1JVEVEIFRPLCBUSEUgSU1QTElFRCBXQVJSQU5USUVTIE9GIE1FUkNIQU5UQUJJTElUWSBBTkQgRklUTkVTUyBGT1JcbiAqIEEgUEFSVElDVUxBUiBQVVJQT1NFIEFSRSBESVNDTEFJTUVELiBJTiBOTyBFVkVOVCBTSEFMTCBUSEUgQ09QWVJJR0hUXG4gKiBPV05FUiBPUiBDT05UUklCVVRPUlMgQkUgTElBQkxFIEZPUiBBTlkgRElSRUNULCBJTkRJUkVDVCwgSU5DSURFTlRBTCxcbiAqIFNQRUNJQUwsIEVYRU1QTEFSWSwgT1IgQ09OU0VRVUVOVElBTCBEQU1BR0VTIChJTkNMVURJTkcsIEJVVCBOT1RcbiAqIExJTUlURUQgVE8sIFBST0NVUkVNRU5UIE9GIFNVQlNUSVRVVEUgR09PRFMgT1IgU0VSVklDRVM7IExPU1MgT0YgVVNFLFxuICogREFUQSwgT1IgUFJPRklUUzsgT1IgQlVTSU5FU1MgSU5URVJSVVBUSU9OKSBIT1dFVkVSIENBVVNFRCBBTkQgT04gQU5ZXG4gKiBUSEVPUlkgT0YgTElBQklMSVRZLCBXSEVUSEVSIElOIENPTlRSQUNULCBTVFJJQ1QgTElBQklMSVRZLCBPUiBUT1JUXG4gKiAoSU5DTFVESU5HIE5FR0xJR0VOQ0UgT1IgT1RIRVJXSVNFKSBBUklTSU5HIElOIEFOWSBXQVkgT1VUIE9GIFRIRSBVU0VcbiAqIE9GIFRISVMgU09GVFdBUkUsIEVWRU4gSUYgQURWSVNFRCBPRiBUSEUgUE9TU0lCSUxJVFkgT0YgU1VDSCBEQU1BR0UuXG4gKi9cblxudmFyIGJhc2U2NCA9IHJlcXVpcmUoJy4vYmFzZTY0Jyk7XG5cbi8vIEEgc2luZ2xlIGJhc2UgNjQgZGlnaXQgY2FuIGNvbnRhaW4gNiBiaXRzIG9mIGRhdGEuIEZvciB0aGUgYmFzZSA2NCB2YXJpYWJsZVxuLy8gbGVuZ3RoIHF1YW50aXRpZXMgd2UgdXNlIGluIHRoZSBzb3VyY2UgbWFwIHNwZWMsIHRoZSBmaXJzdCBiaXQgaXMgdGhlIHNpZ24sXG4vLyB0aGUgbmV4dCBmb3VyIGJpdHMgYXJlIHRoZSBhY3R1YWwgdmFsdWUsIGFuZCB0aGUgNnRoIGJpdCBpcyB0aGVcbi8vIGNvbnRpbnVhdGlvbiBiaXQuIFRoZSBjb250aW51YXRpb24gYml0IHRlbGxzIHVzIHdoZXRoZXIgdGhlcmUgYXJlIG1vcmVcbi8vIGRpZ2l0cyBpbiB0aGlzIHZhbHVlIGZvbGxvd2luZyB0aGlzIGRpZ2l0LlxuLy9cbi8vICAgQ29udGludWF0aW9uXG4vLyAgIHwgICAgU2lnblxuLy8gICB8ICAgIHxcbi8vICAgViAgICBWXG4vLyAgIDEwMTAxMVxuXG52YXIgVkxRX0JBU0VfU0hJRlQgPSA1O1xuXG4vLyBiaW5hcnk6IDEwMDAwMFxudmFyIFZMUV9CQVNFID0gMSA8PCBWTFFfQkFTRV9TSElGVDtcblxuLy8gYmluYXJ5OiAwMTExMTFcbnZhciBWTFFfQkFTRV9NQVNLID0gVkxRX0JBU0UgLSAxO1xuXG4vLyBiaW5hcnk6IDEwMDAwMFxudmFyIFZMUV9DT05USU5VQVRJT05fQklUID0gVkxRX0JBU0U7XG5cbi8qKlxuICogQ29udmVydHMgZnJvbSBhIHR3by1jb21wbGVtZW50IHZhbHVlIHRvIGEgdmFsdWUgd2hlcmUgdGhlIHNpZ24gYml0IGlzXG4gKiBwbGFjZWQgaW4gdGhlIGxlYXN0IHNpZ25pZmljYW50IGJpdC4gIEZvciBleGFtcGxlLCBhcyBkZWNpbWFsczpcbiAqICAgMSBiZWNvbWVzIDIgKDEwIGJpbmFyeSksIC0xIGJlY29tZXMgMyAoMTEgYmluYXJ5KVxuICogICAyIGJlY29tZXMgNCAoMTAwIGJpbmFyeSksIC0yIGJlY29tZXMgNSAoMTAxIGJpbmFyeSlcbiAqL1xuZnVuY3Rpb24gdG9WTFFTaWduZWQoYVZhbHVlKSB7XG4gIHJldHVybiBhVmFsdWUgPCAwXG4gICAgPyAoKC1hVmFsdWUpIDw8IDEpICsgMVxuICAgIDogKGFWYWx1ZSA8PCAxKSArIDA7XG59XG5cbi8qKlxuICogQ29udmVydHMgdG8gYSB0d28tY29tcGxlbWVudCB2YWx1ZSBmcm9tIGEgdmFsdWUgd2hlcmUgdGhlIHNpZ24gYml0IGlzXG4gKiBwbGFjZWQgaW4gdGhlIGxlYXN0IHNpZ25pZmljYW50IGJpdC4gIEZvciBleGFtcGxlLCBhcyBkZWNpbWFsczpcbiAqICAgMiAoMTAgYmluYXJ5KSBiZWNvbWVzIDEsIDMgKDExIGJpbmFyeSkgYmVjb21lcyAtMVxuICogICA0ICgxMDAgYmluYXJ5KSBiZWNvbWVzIDIsIDUgKDEwMSBiaW5hcnkpIGJlY29tZXMgLTJcbiAqL1xuZnVuY3Rpb24gZnJvbVZMUVNpZ25lZChhVmFsdWUpIHtcbiAgdmFyIGlzTmVnYXRpdmUgPSAoYVZhbHVlICYgMSkgPT09IDE7XG4gIHZhciBzaGlmdGVkID0gYVZhbHVlID4+IDE7XG4gIHJldHVybiBpc05lZ2F0aXZlXG4gICAgPyAtc2hpZnRlZFxuICAgIDogc2hpZnRlZDtcbn1cblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBiYXNlIDY0IFZMUSBlbmNvZGVkIHZhbHVlLlxuICovXG5leHBvcnRzLmVuY29kZSA9IGZ1bmN0aW9uIGJhc2U2NFZMUV9lbmNvZGUoYVZhbHVlKSB7XG4gIHZhciBlbmNvZGVkID0gXCJcIjtcbiAgdmFyIGRpZ2l0O1xuXG4gIHZhciB2bHEgPSB0b1ZMUVNpZ25lZChhVmFsdWUpO1xuXG4gIGRvIHtcbiAgICBkaWdpdCA9IHZscSAmIFZMUV9CQVNFX01BU0s7XG4gICAgdmxxID4+Pj0gVkxRX0JBU0VfU0hJRlQ7XG4gICAgaWYgKHZscSA+IDApIHtcbiAgICAgIC8vIFRoZXJlIGFyZSBzdGlsbCBtb3JlIGRpZ2l0cyBpbiB0aGlzIHZhbHVlLCBzbyB3ZSBtdXN0IG1ha2Ugc3VyZSB0aGVcbiAgICAgIC8vIGNvbnRpbnVhdGlvbiBiaXQgaXMgbWFya2VkLlxuICAgICAgZGlnaXQgfD0gVkxRX0NPTlRJTlVBVElPTl9CSVQ7XG4gICAgfVxuICAgIGVuY29kZWQgKz0gYmFzZTY0LmVuY29kZShkaWdpdCk7XG4gIH0gd2hpbGUgKHZscSA+IDApO1xuXG4gIHJldHVybiBlbmNvZGVkO1xufTtcblxuLyoqXG4gKiBEZWNvZGVzIHRoZSBuZXh0IGJhc2UgNjQgVkxRIHZhbHVlIGZyb20gdGhlIGdpdmVuIHN0cmluZyBhbmQgcmV0dXJucyB0aGVcbiAqIHZhbHVlIGFuZCB0aGUgcmVzdCBvZiB0aGUgc3RyaW5nIHZpYSB0aGUgb3V0IHBhcmFtZXRlci5cbiAqL1xuZXhwb3J0cy5kZWNvZGUgPSBmdW5jdGlvbiBiYXNlNjRWTFFfZGVjb2RlKGFTdHIsIGFJbmRleCwgYU91dFBhcmFtKSB7XG4gIHZhciBzdHJMZW4gPSBhU3RyLmxlbmd0aDtcbiAgdmFyIHJlc3VsdCA9IDA7XG4gIHZhciBzaGlmdCA9IDA7XG4gIHZhciBjb250aW51YXRpb24sIGRpZ2l0O1xuXG4gIGRvIHtcbiAgICBpZiAoYUluZGV4ID49IHN0ckxlbikge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiRXhwZWN0ZWQgbW9yZSBkaWdpdHMgaW4gYmFzZSA2NCBWTFEgdmFsdWUuXCIpO1xuICAgIH1cblxuICAgIGRpZ2l0ID0gYmFzZTY0LmRlY29kZShhU3RyLmNoYXJDb2RlQXQoYUluZGV4KyspKTtcbiAgICBpZiAoZGlnaXQgPT09IC0xKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoXCJJbnZhbGlkIGJhc2U2NCBkaWdpdDogXCIgKyBhU3RyLmNoYXJBdChhSW5kZXggLSAxKSk7XG4gICAgfVxuXG4gICAgY29udGludWF0aW9uID0gISEoZGlnaXQgJiBWTFFfQ09OVElOVUFUSU9OX0JJVCk7XG4gICAgZGlnaXQgJj0gVkxRX0JBU0VfTUFTSztcbiAgICByZXN1bHQgPSByZXN1bHQgKyAoZGlnaXQgPDwgc2hpZnQpO1xuICAgIHNoaWZ0ICs9IFZMUV9CQVNFX1NISUZUO1xuICB9IHdoaWxlIChjb250aW51YXRpb24pO1xuXG4gIGFPdXRQYXJhbS52YWx1ZSA9IGZyb21WTFFTaWduZWQocmVzdWx0KTtcbiAgYU91dFBhcmFtLnJlc3QgPSBhSW5kZXg7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvYmFzZTY0LXZscS5qc1xuLy8gbW9kdWxlIGlkID0gMlxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciBpbnRUb0NoYXJNYXAgPSAnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLycuc3BsaXQoJycpO1xuXG4vKipcbiAqIEVuY29kZSBhbiBpbnRlZ2VyIGluIHRoZSByYW5nZSBvZiAwIHRvIDYzIHRvIGEgc2luZ2xlIGJhc2UgNjQgZGlnaXQuXG4gKi9cbmV4cG9ydHMuZW5jb2RlID0gZnVuY3Rpb24gKG51bWJlcikge1xuICBpZiAoMCA8PSBudW1iZXIgJiYgbnVtYmVyIDwgaW50VG9DaGFyTWFwLmxlbmd0aCkge1xuICAgIHJldHVybiBpbnRUb0NoYXJNYXBbbnVtYmVyXTtcbiAgfVxuICB0aHJvdyBuZXcgVHlwZUVycm9yKFwiTXVzdCBiZSBiZXR3ZWVuIDAgYW5kIDYzOiBcIiArIG51bWJlcik7XG59O1xuXG4vKipcbiAqIERlY29kZSBhIHNpbmdsZSBiYXNlIDY0IGNoYXJhY3RlciBjb2RlIGRpZ2l0IHRvIGFuIGludGVnZXIuIFJldHVybnMgLTEgb25cbiAqIGZhaWx1cmUuXG4gKi9cbmV4cG9ydHMuZGVjb2RlID0gZnVuY3Rpb24gKGNoYXJDb2RlKSB7XG4gIHZhciBiaWdBID0gNjU7ICAgICAvLyAnQSdcbiAgdmFyIGJpZ1ogPSA5MDsgICAgIC8vICdaJ1xuXG4gIHZhciBsaXR0bGVBID0gOTc7ICAvLyAnYSdcbiAgdmFyIGxpdHRsZVogPSAxMjI7IC8vICd6J1xuXG4gIHZhciB6ZXJvID0gNDg7ICAgICAvLyAnMCdcbiAgdmFyIG5pbmUgPSA1NzsgICAgIC8vICc5J1xuXG4gIHZhciBwbHVzID0gNDM7ICAgICAvLyAnKydcbiAgdmFyIHNsYXNoID0gNDc7ICAgIC8vICcvJ1xuXG4gIHZhciBsaXR0bGVPZmZzZXQgPSAyNjtcbiAgdmFyIG51bWJlck9mZnNldCA9IDUyO1xuXG4gIC8vIDAgLSAyNTogQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpcbiAgaWYgKGJpZ0EgPD0gY2hhckNvZGUgJiYgY2hhckNvZGUgPD0gYmlnWikge1xuICAgIHJldHVybiAoY2hhckNvZGUgLSBiaWdBKTtcbiAgfVxuXG4gIC8vIDI2IC0gNTE6IGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6XG4gIGlmIChsaXR0bGVBIDw9IGNoYXJDb2RlICYmIGNoYXJDb2RlIDw9IGxpdHRsZVopIHtcbiAgICByZXR1cm4gKGNoYXJDb2RlIC0gbGl0dGxlQSArIGxpdHRsZU9mZnNldCk7XG4gIH1cblxuICAvLyA1MiAtIDYxOiAwMTIzNDU2Nzg5XG4gIGlmICh6ZXJvIDw9IGNoYXJDb2RlICYmIGNoYXJDb2RlIDw9IG5pbmUpIHtcbiAgICByZXR1cm4gKGNoYXJDb2RlIC0gemVybyArIG51bWJlck9mZnNldCk7XG4gIH1cblxuICAvLyA2MjogK1xuICBpZiAoY2hhckNvZGUgPT0gcGx1cykge1xuICAgIHJldHVybiA2MjtcbiAgfVxuXG4gIC8vIDYzOiAvXG4gIGlmIChjaGFyQ29kZSA9PSBzbGFzaCkge1xuICAgIHJldHVybiA2MztcbiAgfVxuXG4gIC8vIEludmFsaWQgYmFzZTY0IGRpZ2l0LlxuICByZXR1cm4gLTE7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvYmFzZTY0LmpzXG4vLyBtb2R1bGUgaWQgPSAzXG4vLyBtb2R1bGUgY2h1bmtzID0gMCIsIi8qIC0qLSBNb2RlOiBqczsganMtaW5kZW50LWxldmVsOiAyOyAtKi0gKi9cbi8qXG4gKiBDb3B5cmlnaHQgMjAxMSBNb3ppbGxhIEZvdW5kYXRpb24gYW5kIGNvbnRyaWJ1dG9yc1xuICogTGljZW5zZWQgdW5kZXIgdGhlIE5ldyBCU0QgbGljZW5zZS4gU2VlIExJQ0VOU0Ugb3I6XG4gKiBodHRwOi8vb3BlbnNvdXJjZS5vcmcvbGljZW5zZXMvQlNELTMtQ2xhdXNlXG4gKi9cblxuLyoqXG4gKiBUaGlzIGlzIGEgaGVscGVyIGZ1bmN0aW9uIGZvciBnZXR0aW5nIHZhbHVlcyBmcm9tIHBhcmFtZXRlci9vcHRpb25zXG4gKiBvYmplY3RzLlxuICpcbiAqIEBwYXJhbSBhcmdzIFRoZSBvYmplY3Qgd2UgYXJlIGV4dHJhY3RpbmcgdmFsdWVzIGZyb21cbiAqIEBwYXJhbSBuYW1lIFRoZSBuYW1lIG9mIHRoZSBwcm9wZXJ0eSB3ZSBhcmUgZ2V0dGluZy5cbiAqIEBwYXJhbSBkZWZhdWx0VmFsdWUgQW4gb3B0aW9uYWwgdmFsdWUgdG8gcmV0dXJuIGlmIHRoZSBwcm9wZXJ0eSBpcyBtaXNzaW5nXG4gKiBmcm9tIHRoZSBvYmplY3QuIElmIHRoaXMgaXMgbm90IHNwZWNpZmllZCBhbmQgdGhlIHByb3BlcnR5IGlzIG1pc3NpbmcsIGFuXG4gKiBlcnJvciB3aWxsIGJlIHRocm93bi5cbiAqL1xuZnVuY3Rpb24gZ2V0QXJnKGFBcmdzLCBhTmFtZSwgYURlZmF1bHRWYWx1ZSkge1xuICBpZiAoYU5hbWUgaW4gYUFyZ3MpIHtcbiAgICByZXR1cm4gYUFyZ3NbYU5hbWVdO1xuICB9IGVsc2UgaWYgKGFyZ3VtZW50cy5sZW5ndGggPT09IDMpIHtcbiAgICByZXR1cm4gYURlZmF1bHRWYWx1ZTtcbiAgfSBlbHNlIHtcbiAgICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFOYW1lICsgJ1wiIGlzIGEgcmVxdWlyZWQgYXJndW1lbnQuJyk7XG4gIH1cbn1cbmV4cG9ydHMuZ2V0QXJnID0gZ2V0QXJnO1xuXG52YXIgdXJsUmVnZXhwID0gL14oPzooW1xcdytcXC0uXSspOik/XFwvXFwvKD86KFxcdys6XFx3KylAKT8oW1xcdy5dKikoPzo6KFxcZCspKT8oXFxTKikkLztcbnZhciBkYXRhVXJsUmVnZXhwID0gL15kYXRhOi4rXFwsLiskLztcblxuZnVuY3Rpb24gdXJsUGFyc2UoYVVybCkge1xuICB2YXIgbWF0Y2ggPSBhVXJsLm1hdGNoKHVybFJlZ2V4cCk7XG4gIGlmICghbWF0Y2gpIHtcbiAgICByZXR1cm4gbnVsbDtcbiAgfVxuICByZXR1cm4ge1xuICAgIHNjaGVtZTogbWF0Y2hbMV0sXG4gICAgYXV0aDogbWF0Y2hbMl0sXG4gICAgaG9zdDogbWF0Y2hbM10sXG4gICAgcG9ydDogbWF0Y2hbNF0sXG4gICAgcGF0aDogbWF0Y2hbNV1cbiAgfTtcbn1cbmV4cG9ydHMudXJsUGFyc2UgPSB1cmxQYXJzZTtcblxuZnVuY3Rpb24gdXJsR2VuZXJhdGUoYVBhcnNlZFVybCkge1xuICB2YXIgdXJsID0gJyc7XG4gIGlmIChhUGFyc2VkVXJsLnNjaGVtZSkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLnNjaGVtZSArICc6JztcbiAgfVxuICB1cmwgKz0gJy8vJztcbiAgaWYgKGFQYXJzZWRVcmwuYXV0aCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmF1dGggKyAnQCc7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwuaG9zdCkge1xuICAgIHVybCArPSBhUGFyc2VkVXJsLmhvc3Q7XG4gIH1cbiAgaWYgKGFQYXJzZWRVcmwucG9ydCkge1xuICAgIHVybCArPSBcIjpcIiArIGFQYXJzZWRVcmwucG9ydFxuICB9XG4gIGlmIChhUGFyc2VkVXJsLnBhdGgpIHtcbiAgICB1cmwgKz0gYVBhcnNlZFVybC5wYXRoO1xuICB9XG4gIHJldHVybiB1cmw7XG59XG5leHBvcnRzLnVybEdlbmVyYXRlID0gdXJsR2VuZXJhdGU7XG5cbi8qKlxuICogTm9ybWFsaXplcyBhIHBhdGgsIG9yIHRoZSBwYXRoIHBvcnRpb24gb2YgYSBVUkw6XG4gKlxuICogLSBSZXBsYWNlcyBjb25zZWN1dGl2ZSBzbGFzaGVzIHdpdGggb25lIHNsYXNoLlxuICogLSBSZW1vdmVzIHVubmVjZXNzYXJ5ICcuJyBwYXJ0cy5cbiAqIC0gUmVtb3ZlcyB1bm5lY2Vzc2FyeSAnPGRpcj4vLi4nIHBhcnRzLlxuICpcbiAqIEJhc2VkIG9uIGNvZGUgaW4gdGhlIE5vZGUuanMgJ3BhdGgnIGNvcmUgbW9kdWxlLlxuICpcbiAqIEBwYXJhbSBhUGF0aCBUaGUgcGF0aCBvciB1cmwgdG8gbm9ybWFsaXplLlxuICovXG5mdW5jdGlvbiBub3JtYWxpemUoYVBhdGgpIHtcbiAgdmFyIHBhdGggPSBhUGF0aDtcbiAgdmFyIHVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgaWYgKHVybCkge1xuICAgIGlmICghdXJsLnBhdGgpIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG4gICAgcGF0aCA9IHVybC5wYXRoO1xuICB9XG4gIHZhciBpc0Fic29sdXRlID0gZXhwb3J0cy5pc0Fic29sdXRlKHBhdGgpO1xuXG4gIHZhciBwYXJ0cyA9IHBhdGguc3BsaXQoL1xcLysvKTtcbiAgZm9yICh2YXIgcGFydCwgdXAgPSAwLCBpID0gcGFydHMubGVuZ3RoIC0gMTsgaSA+PSAwOyBpLS0pIHtcbiAgICBwYXJ0ID0gcGFydHNbaV07XG4gICAgaWYgKHBhcnQgPT09ICcuJykge1xuICAgICAgcGFydHMuc3BsaWNlKGksIDEpO1xuICAgIH0gZWxzZSBpZiAocGFydCA9PT0gJy4uJykge1xuICAgICAgdXArKztcbiAgICB9IGVsc2UgaWYgKHVwID4gMCkge1xuICAgICAgaWYgKHBhcnQgPT09ICcnKSB7XG4gICAgICAgIC8vIFRoZSBmaXJzdCBwYXJ0IGlzIGJsYW5rIGlmIHRoZSBwYXRoIGlzIGFic29sdXRlLiBUcnlpbmcgdG8gZ29cbiAgICAgICAgLy8gYWJvdmUgdGhlIHJvb3QgaXMgYSBuby1vcC4gVGhlcmVmb3JlIHdlIGNhbiByZW1vdmUgYWxsICcuLicgcGFydHNcbiAgICAgICAgLy8gZGlyZWN0bHkgYWZ0ZXIgdGhlIHJvb3QuXG4gICAgICAgIHBhcnRzLnNwbGljZShpICsgMSwgdXApO1xuICAgICAgICB1cCA9IDA7XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBwYXJ0cy5zcGxpY2UoaSwgMik7XG4gICAgICAgIHVwLS07XG4gICAgICB9XG4gICAgfVxuICB9XG4gIHBhdGggPSBwYXJ0cy5qb2luKCcvJyk7XG5cbiAgaWYgKHBhdGggPT09ICcnKSB7XG4gICAgcGF0aCA9IGlzQWJzb2x1dGUgPyAnLycgOiAnLic7XG4gIH1cblxuICBpZiAodXJsKSB7XG4gICAgdXJsLnBhdGggPSBwYXRoO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZSh1cmwpO1xuICB9XG4gIHJldHVybiBwYXRoO1xufVxuZXhwb3J0cy5ub3JtYWxpemUgPSBub3JtYWxpemU7XG5cbi8qKlxuICogSm9pbnMgdHdvIHBhdGhzL1VSTHMuXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBqb2luZWQgd2l0aCB0aGUgcm9vdC5cbiAqXG4gKiAtIElmIGFQYXRoIGlzIGEgVVJMIG9yIGEgZGF0YSBVUkksIGFQYXRoIGlzIHJldHVybmVkLCB1bmxlc3MgYVBhdGggaXMgYVxuICogICBzY2hlbWUtcmVsYXRpdmUgVVJMOiBUaGVuIHRoZSBzY2hlbWUgb2YgYVJvb3QsIGlmIGFueSwgaXMgcHJlcGVuZGVkXG4gKiAgIGZpcnN0LlxuICogLSBPdGhlcndpc2UgYVBhdGggaXMgYSBwYXRoLiBJZiBhUm9vdCBpcyBhIFVSTCwgdGhlbiBpdHMgcGF0aCBwb3J0aW9uXG4gKiAgIGlzIHVwZGF0ZWQgd2l0aCB0aGUgcmVzdWx0IGFuZCBhUm9vdCBpcyByZXR1cm5lZC4gT3RoZXJ3aXNlIHRoZSByZXN1bHRcbiAqICAgaXMgcmV0dXJuZWQuXG4gKiAgIC0gSWYgYVBhdGggaXMgYWJzb2x1dGUsIHRoZSByZXN1bHQgaXMgYVBhdGguXG4gKiAgIC0gT3RoZXJ3aXNlIHRoZSB0d28gcGF0aHMgYXJlIGpvaW5lZCB3aXRoIGEgc2xhc2guXG4gKiAtIEpvaW5pbmcgZm9yIGV4YW1wbGUgJ2h0dHA6Ly8nIGFuZCAnd3d3LmV4YW1wbGUuY29tJyBpcyBhbHNvIHN1cHBvcnRlZC5cbiAqL1xuZnVuY3Rpb24gam9pbihhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuICBpZiAoYVBhdGggPT09IFwiXCIpIHtcbiAgICBhUGF0aCA9IFwiLlwiO1xuICB9XG4gIHZhciBhUGF0aFVybCA9IHVybFBhcnNlKGFQYXRoKTtcbiAgdmFyIGFSb290VXJsID0gdXJsUGFyc2UoYVJvb3QpO1xuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdCA9IGFSb290VXJsLnBhdGggfHwgJy8nO1xuICB9XG5cbiAgLy8gYGpvaW4oZm9vLCAnLy93d3cuZXhhbXBsZS5vcmcnKWBcbiAgaWYgKGFQYXRoVXJsICYmICFhUGF0aFVybC5zY2hlbWUpIHtcbiAgICBpZiAoYVJvb3RVcmwpIHtcbiAgICAgIGFQYXRoVXJsLnNjaGVtZSA9IGFSb290VXJsLnNjaGVtZTtcbiAgICB9XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFQYXRoVXJsKTtcbiAgfVxuXG4gIGlmIChhUGF0aFVybCB8fCBhUGF0aC5tYXRjaChkYXRhVXJsUmVnZXhwKSkge1xuICAgIHJldHVybiBhUGF0aDtcbiAgfVxuXG4gIC8vIGBqb2luKCdodHRwOi8vJywgJ3d3dy5leGFtcGxlLmNvbScpYFxuICBpZiAoYVJvb3RVcmwgJiYgIWFSb290VXJsLmhvc3QgJiYgIWFSb290VXJsLnBhdGgpIHtcbiAgICBhUm9vdFVybC5ob3N0ID0gYVBhdGg7XG4gICAgcmV0dXJuIHVybEdlbmVyYXRlKGFSb290VXJsKTtcbiAgfVxuXG4gIHZhciBqb2luZWQgPSBhUGF0aC5jaGFyQXQoMCkgPT09ICcvJ1xuICAgID8gYVBhdGhcbiAgICA6IG5vcm1hbGl6ZShhUm9vdC5yZXBsYWNlKC9cXC8rJC8sICcnKSArICcvJyArIGFQYXRoKTtcblxuICBpZiAoYVJvb3RVcmwpIHtcbiAgICBhUm9vdFVybC5wYXRoID0gam9pbmVkO1xuICAgIHJldHVybiB1cmxHZW5lcmF0ZShhUm9vdFVybCk7XG4gIH1cbiAgcmV0dXJuIGpvaW5lZDtcbn1cbmV4cG9ydHMuam9pbiA9IGpvaW47XG5cbmV4cG9ydHMuaXNBYnNvbHV0ZSA9IGZ1bmN0aW9uIChhUGF0aCkge1xuICByZXR1cm4gYVBhdGguY2hhckF0KDApID09PSAnLycgfHwgISFhUGF0aC5tYXRjaCh1cmxSZWdleHApO1xufTtcblxuLyoqXG4gKiBNYWtlIGEgcGF0aCByZWxhdGl2ZSB0byBhIFVSTCBvciBhbm90aGVyIHBhdGguXG4gKlxuICogQHBhcmFtIGFSb290IFRoZSByb290IHBhdGggb3IgVVJMLlxuICogQHBhcmFtIGFQYXRoIFRoZSBwYXRoIG9yIFVSTCB0byBiZSBtYWRlIHJlbGF0aXZlIHRvIGFSb290LlxuICovXG5mdW5jdGlvbiByZWxhdGl2ZShhUm9vdCwgYVBhdGgpIHtcbiAgaWYgKGFSb290ID09PSBcIlwiKSB7XG4gICAgYVJvb3QgPSBcIi5cIjtcbiAgfVxuXG4gIGFSb290ID0gYVJvb3QucmVwbGFjZSgvXFwvJC8sICcnKTtcblxuICAvLyBJdCBpcyBwb3NzaWJsZSBmb3IgdGhlIHBhdGggdG8gYmUgYWJvdmUgdGhlIHJvb3QuIEluIHRoaXMgY2FzZSwgc2ltcGx5XG4gIC8vIGNoZWNraW5nIHdoZXRoZXIgdGhlIHJvb3QgaXMgYSBwcmVmaXggb2YgdGhlIHBhdGggd29uJ3Qgd29yay4gSW5zdGVhZCwgd2VcbiAgLy8gbmVlZCB0byByZW1vdmUgY29tcG9uZW50cyBmcm9tIHRoZSByb290IG9uZSBieSBvbmUsIHVudGlsIGVpdGhlciB3ZSBmaW5kXG4gIC8vIGEgcHJlZml4IHRoYXQgZml0cywgb3Igd2UgcnVuIG91dCBvZiBjb21wb25lbnRzIHRvIHJlbW92ZS5cbiAgdmFyIGxldmVsID0gMDtcbiAgd2hpbGUgKGFQYXRoLmluZGV4T2YoYVJvb3QgKyAnLycpICE9PSAwKSB7XG4gICAgdmFyIGluZGV4ID0gYVJvb3QubGFzdEluZGV4T2YoXCIvXCIpO1xuICAgIGlmIChpbmRleCA8IDApIHtcbiAgICAgIHJldHVybiBhUGF0aDtcbiAgICB9XG5cbiAgICAvLyBJZiB0aGUgb25seSBwYXJ0IG9mIHRoZSByb290IHRoYXQgaXMgbGVmdCBpcyB0aGUgc2NoZW1lIChpLmUuIGh0dHA6Ly8sXG4gICAgLy8gZmlsZTovLy8sIGV0Yy4pLCBvbmUgb3IgbW9yZSBzbGFzaGVzICgvKSwgb3Igc2ltcGx5IG5vdGhpbmcgYXQgYWxsLCB3ZVxuICAgIC8vIGhhdmUgZXhoYXVzdGVkIGFsbCBjb21wb25lbnRzLCBzbyB0aGUgcGF0aCBpcyBub3QgcmVsYXRpdmUgdG8gdGhlIHJvb3QuXG4gICAgYVJvb3QgPSBhUm9vdC5zbGljZSgwLCBpbmRleCk7XG4gICAgaWYgKGFSb290Lm1hdGNoKC9eKFteXFwvXSs6XFwvKT9cXC8qJC8pKSB7XG4gICAgICByZXR1cm4gYVBhdGg7XG4gICAgfVxuXG4gICAgKytsZXZlbDtcbiAgfVxuXG4gIC8vIE1ha2Ugc3VyZSB3ZSBhZGQgYSBcIi4uL1wiIGZvciBlYWNoIGNvbXBvbmVudCB3ZSByZW1vdmVkIGZyb20gdGhlIHJvb3QuXG4gIHJldHVybiBBcnJheShsZXZlbCArIDEpLmpvaW4oXCIuLi9cIikgKyBhUGF0aC5zdWJzdHIoYVJvb3QubGVuZ3RoICsgMSk7XG59XG5leHBvcnRzLnJlbGF0aXZlID0gcmVsYXRpdmU7XG5cbnZhciBzdXBwb3J0c051bGxQcm90byA9IChmdW5jdGlvbiAoKSB7XG4gIHZhciBvYmogPSBPYmplY3QuY3JlYXRlKG51bGwpO1xuICByZXR1cm4gISgnX19wcm90b19fJyBpbiBvYmopO1xufSgpKTtcblxuZnVuY3Rpb24gaWRlbnRpdHkgKHMpIHtcbiAgcmV0dXJuIHM7XG59XG5cbi8qKlxuICogQmVjYXVzZSBiZWhhdmlvciBnb2VzIHdhY2t5IHdoZW4geW91IHNldCBgX19wcm90b19fYCBvbiBvYmplY3RzLCB3ZVxuICogaGF2ZSB0byBwcmVmaXggYWxsIHRoZSBzdHJpbmdzIGluIG91ciBzZXQgd2l0aCBhbiBhcmJpdHJhcnkgY2hhcmFjdGVyLlxuICpcbiAqIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL3B1bGwvMzEgYW5kXG4gKiBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8zMFxuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5mdW5jdGlvbiB0b1NldFN0cmluZyhhU3RyKSB7XG4gIGlmIChpc1Byb3RvU3RyaW5nKGFTdHIpKSB7XG4gICAgcmV0dXJuICckJyArIGFTdHI7XG4gIH1cblxuICByZXR1cm4gYVN0cjtcbn1cbmV4cG9ydHMudG9TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogdG9TZXRTdHJpbmc7XG5cbmZ1bmN0aW9uIGZyb21TZXRTdHJpbmcoYVN0cikge1xuICBpZiAoaXNQcm90b1N0cmluZyhhU3RyKSkge1xuICAgIHJldHVybiBhU3RyLnNsaWNlKDEpO1xuICB9XG5cbiAgcmV0dXJuIGFTdHI7XG59XG5leHBvcnRzLmZyb21TZXRTdHJpbmcgPSBzdXBwb3J0c051bGxQcm90byA/IGlkZW50aXR5IDogZnJvbVNldFN0cmluZztcblxuZnVuY3Rpb24gaXNQcm90b1N0cmluZyhzKSB7XG4gIGlmICghcykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIHZhciBsZW5ndGggPSBzLmxlbmd0aDtcblxuICBpZiAobGVuZ3RoIDwgOSAvKiBcIl9fcHJvdG9fX1wiLmxlbmd0aCAqLykge1xuICAgIHJldHVybiBmYWxzZTtcbiAgfVxuXG4gIGlmIChzLmNoYXJDb2RlQXQobGVuZ3RoIC0gMSkgIT09IDk1ICAvKiAnXycgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSAyKSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDMpICE9PSAxMTEgLyogJ28nICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNCkgIT09IDExNiAvKiAndCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA1KSAhPT0gMTExIC8qICdvJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDYpICE9PSAxMTQgLyogJ3InICovIHx8XG4gICAgICBzLmNoYXJDb2RlQXQobGVuZ3RoIC0gNykgIT09IDExMiAvKiAncCcgKi8gfHxcbiAgICAgIHMuY2hhckNvZGVBdChsZW5ndGggLSA4KSAhPT0gOTUgIC8qICdfJyAqLyB8fFxuICAgICAgcy5jaGFyQ29kZUF0KGxlbmd0aCAtIDkpICE9PSA5NSAgLyogJ18nICovKSB7XG4gICAgcmV0dXJuIGZhbHNlO1xuICB9XG5cbiAgZm9yICh2YXIgaSA9IGxlbmd0aCAtIDEwOyBpID49IDA7IGktLSkge1xuICAgIGlmIChzLmNoYXJDb2RlQXQoaSkgIT09IDM2IC8qICckJyAqLykge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuXG4vKipcbiAqIENvbXBhcmF0b3IgYmV0d2VlbiB0d28gbWFwcGluZ3Mgd2hlcmUgdGhlIG9yaWdpbmFsIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKlxuICogT3B0aW9uYWxseSBwYXNzIGluIGB0cnVlYCBhcyBgb25seUNvbXBhcmVHZW5lcmF0ZWRgIHRvIGNvbnNpZGVyIHR3b1xuICogbWFwcGluZ3Mgd2l0aCB0aGUgc2FtZSBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4sIGJ1dCBkaWZmZXJlbnQgZ2VuZXJhdGVkXG4gKiBsaW5lIGFuZCBjb2x1bW4gdGhlIHNhbWUuIFVzZWZ1bCB3aGVuIHNlYXJjaGluZyBmb3IgYSBtYXBwaW5nIHdpdGggYVxuICogc3R1YmJlZCBvdXQgbWFwcGluZy5cbiAqL1xuZnVuY3Rpb24gY29tcGFyZUJ5T3JpZ2luYWxQb3NpdGlvbnMobWFwcGluZ0EsIG1hcHBpbmdCLCBvbmx5Q29tcGFyZU9yaWdpbmFsKSB7XG4gIHZhciBjbXAgPSBtYXBwaW5nQS5zb3VyY2UgLSBtYXBwaW5nQi5zb3VyY2U7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDAgfHwgb25seUNvbXBhcmVPcmlnaW5hbCkge1xuICAgIHJldHVybiBjbXA7XG4gIH1cblxuICBjbXAgPSBtYXBwaW5nQS5nZW5lcmF0ZWRDb2x1bW4gLSBtYXBwaW5nQi5nZW5lcmF0ZWRDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIG1hcHBpbmdBLm5hbWUgLSBtYXBwaW5nQi5uYW1lO1xufVxuZXhwb3J0cy5jb21wYXJlQnlPcmlnaW5hbFBvc2l0aW9ucyA9IGNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zO1xuXG4vKipcbiAqIENvbXBhcmF0b3IgYmV0d2VlbiB0d28gbWFwcGluZ3Mgd2l0aCBkZWZsYXRlZCBzb3VyY2UgYW5kIG5hbWUgaW5kaWNlcyB3aGVyZVxuICogdGhlIGdlbmVyYXRlZCBwb3NpdGlvbnMgYXJlIGNvbXBhcmVkLlxuICpcbiAqIE9wdGlvbmFsbHkgcGFzcyBpbiBgdHJ1ZWAgYXMgYG9ubHlDb21wYXJlR2VuZXJhdGVkYCB0byBjb25zaWRlciB0d29cbiAqIG1hcHBpbmdzIHdpdGggdGhlIHNhbWUgZ2VuZXJhdGVkIGxpbmUgYW5kIGNvbHVtbiwgYnV0IGRpZmZlcmVudFxuICogc291cmNlL25hbWUvb3JpZ2luYWwgbGluZSBhbmQgY29sdW1uIHRoZSBzYW1lLiBVc2VmdWwgd2hlbiBzZWFyY2hpbmcgZm9yIGFcbiAqIG1hcHBpbmcgd2l0aCBhIHN0dWJiZWQgb3V0IG1hcHBpbmcuXG4gKi9cbmZ1bmN0aW9uIGNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkKG1hcHBpbmdBLCBtYXBwaW5nQiwgb25seUNvbXBhcmVHZW5lcmF0ZWQpIHtcbiAgdmFyIGNtcCA9IG1hcHBpbmdBLmdlbmVyYXRlZExpbmUgLSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLmdlbmVyYXRlZENvbHVtbiAtIG1hcHBpbmdCLmdlbmVyYXRlZENvbHVtbjtcbiAgaWYgKGNtcCAhPT0gMCB8fCBvbmx5Q29tcGFyZUdlbmVyYXRlZCkge1xuICAgIHJldHVybiBjbXA7XG4gIH1cblxuICBjbXAgPSBtYXBwaW5nQS5zb3VyY2UgLSBtYXBwaW5nQi5zb3VyY2U7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIG1hcHBpbmdBLm5hbWUgLSBtYXBwaW5nQi5uYW1lO1xufVxuZXhwb3J0cy5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNEZWZsYXRlZCA9IGNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkO1xuXG5mdW5jdGlvbiBzdHJjbXAoYVN0cjEsIGFTdHIyKSB7XG4gIGlmIChhU3RyMSA9PT0gYVN0cjIpIHtcbiAgICByZXR1cm4gMDtcbiAgfVxuXG4gIGlmIChhU3RyMSA+IGFTdHIyKSB7XG4gICAgcmV0dXJuIDE7XG4gIH1cblxuICByZXR1cm4gLTE7XG59XG5cbi8qKlxuICogQ29tcGFyYXRvciBiZXR3ZWVuIHR3byBtYXBwaW5ncyB3aXRoIGluZmxhdGVkIHNvdXJjZSBhbmQgbmFtZSBzdHJpbmdzIHdoZXJlXG4gKiB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucyBhcmUgY29tcGFyZWQuXG4gKi9cbmZ1bmN0aW9uIGNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0luZmxhdGVkKG1hcHBpbmdBLCBtYXBwaW5nQikge1xuICB2YXIgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkTGluZSAtIG1hcHBpbmdCLmdlbmVyYXRlZExpbmU7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0EuZ2VuZXJhdGVkQ29sdW1uIC0gbWFwcGluZ0IuZ2VuZXJhdGVkQ29sdW1uO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IHN0cmNtcChtYXBwaW5nQS5zb3VyY2UsIG1hcHBpbmdCLnNvdXJjZSk7XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgY21wID0gbWFwcGluZ0Eub3JpZ2luYWxMaW5lIC0gbWFwcGluZ0Iub3JpZ2luYWxMaW5lO1xuICBpZiAoY21wICE9PSAwKSB7XG4gICAgcmV0dXJuIGNtcDtcbiAgfVxuXG4gIGNtcCA9IG1hcHBpbmdBLm9yaWdpbmFsQ29sdW1uIC0gbWFwcGluZ0Iub3JpZ2luYWxDb2x1bW47XG4gIGlmIChjbXAgIT09IDApIHtcbiAgICByZXR1cm4gY21wO1xuICB9XG5cbiAgcmV0dXJuIHN0cmNtcChtYXBwaW5nQS5uYW1lLCBtYXBwaW5nQi5uYW1lKTtcbn1cbmV4cG9ydHMuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zSW5mbGF0ZWQgPSBjb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL3V0aWwuanNcbi8vIG1vZHVsZSBpZCA9IDRcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGhhcyA9IE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHk7XG52YXIgaGFzTmF0aXZlTWFwID0gdHlwZW9mIE1hcCAhPT0gXCJ1bmRlZmluZWRcIjtcblxuLyoqXG4gKiBBIGRhdGEgc3RydWN0dXJlIHdoaWNoIGlzIGEgY29tYmluYXRpb24gb2YgYW4gYXJyYXkgYW5kIGEgc2V0LiBBZGRpbmcgYSBuZXdcbiAqIG1lbWJlciBpcyBPKDEpLCB0ZXN0aW5nIGZvciBtZW1iZXJzaGlwIGlzIE8oMSksIGFuZCBmaW5kaW5nIHRoZSBpbmRleCBvZiBhblxuICogZWxlbWVudCBpcyBPKDEpLiBSZW1vdmluZyBlbGVtZW50cyBmcm9tIHRoZSBzZXQgaXMgbm90IHN1cHBvcnRlZC4gT25seVxuICogc3RyaW5ncyBhcmUgc3VwcG9ydGVkIGZvciBtZW1iZXJzaGlwLlxuICovXG5mdW5jdGlvbiBBcnJheVNldCgpIHtcbiAgdGhpcy5fYXJyYXkgPSBbXTtcbiAgdGhpcy5fc2V0ID0gaGFzTmF0aXZlTWFwID8gbmV3IE1hcCgpIDogT2JqZWN0LmNyZWF0ZShudWxsKTtcbn1cblxuLyoqXG4gKiBTdGF0aWMgbWV0aG9kIGZvciBjcmVhdGluZyBBcnJheVNldCBpbnN0YW5jZXMgZnJvbSBhbiBleGlzdGluZyBhcnJheS5cbiAqL1xuQXJyYXlTZXQuZnJvbUFycmF5ID0gZnVuY3Rpb24gQXJyYXlTZXRfZnJvbUFycmF5KGFBcnJheSwgYUFsbG93RHVwbGljYXRlcykge1xuICB2YXIgc2V0ID0gbmV3IEFycmF5U2V0KCk7XG4gIGZvciAodmFyIGkgPSAwLCBsZW4gPSBhQXJyYXkubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICBzZXQuYWRkKGFBcnJheVtpXSwgYUFsbG93RHVwbGljYXRlcyk7XG4gIH1cbiAgcmV0dXJuIHNldDtcbn07XG5cbi8qKlxuICogUmV0dXJuIGhvdyBtYW55IHVuaXF1ZSBpdGVtcyBhcmUgaW4gdGhpcyBBcnJheVNldC4gSWYgZHVwbGljYXRlcyBoYXZlIGJlZW5cbiAqIGFkZGVkLCB0aGFuIHRob3NlIGRvIG5vdCBjb3VudCB0b3dhcmRzIHRoZSBzaXplLlxuICpcbiAqIEByZXR1cm5zIE51bWJlclxuICovXG5BcnJheVNldC5wcm90b3R5cGUuc2l6ZSA9IGZ1bmN0aW9uIEFycmF5U2V0X3NpemUoKSB7XG4gIHJldHVybiBoYXNOYXRpdmVNYXAgPyB0aGlzLl9zZXQuc2l6ZSA6IE9iamVjdC5nZXRPd25Qcm9wZXJ0eU5hbWVzKHRoaXMuX3NldCkubGVuZ3RoO1xufTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHN0cmluZyB0byB0aGlzIHNldC5cbiAqXG4gKiBAcGFyYW0gU3RyaW5nIGFTdHJcbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIEFycmF5U2V0X2FkZChhU3RyLCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gIHZhciBzU3RyID0gaGFzTmF0aXZlTWFwID8gYVN0ciA6IHV0aWwudG9TZXRTdHJpbmcoYVN0cik7XG4gIHZhciBpc0R1cGxpY2F0ZSA9IGhhc05hdGl2ZU1hcCA/IHRoaXMuaGFzKGFTdHIpIDogaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKTtcbiAgdmFyIGlkeCA9IHRoaXMuX2FycmF5Lmxlbmd0aDtcbiAgaWYgKCFpc0R1cGxpY2F0ZSB8fCBhQWxsb3dEdXBsaWNhdGVzKSB7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhU3RyKTtcbiAgfVxuICBpZiAoIWlzRHVwbGljYXRlKSB7XG4gICAgaWYgKGhhc05hdGl2ZU1hcCkge1xuICAgICAgdGhpcy5fc2V0LnNldChhU3RyLCBpZHgpO1xuICAgIH0gZWxzZSB7XG4gICAgICB0aGlzLl9zZXRbc1N0cl0gPSBpZHg7XG4gICAgfVxuICB9XG59O1xuXG4vKipcbiAqIElzIHRoZSBnaXZlbiBzdHJpbmcgYSBtZW1iZXIgb2YgdGhpcyBzZXQ/XG4gKlxuICogQHBhcmFtIFN0cmluZyBhU3RyXG4gKi9cbkFycmF5U2V0LnByb3RvdHlwZS5oYXMgPSBmdW5jdGlvbiBBcnJheVNldF9oYXMoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgcmV0dXJuIHRoaXMuX3NldC5oYXMoYVN0cik7XG4gIH0gZWxzZSB7XG4gICAgdmFyIHNTdHIgPSB1dGlsLnRvU2V0U3RyaW5nKGFTdHIpO1xuICAgIHJldHVybiBoYXMuY2FsbCh0aGlzLl9zZXQsIHNTdHIpO1xuICB9XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGluZGV4IG9mIHRoZSBnaXZlbiBzdHJpbmcgaW4gdGhlIGFycmF5P1xuICpcbiAqIEBwYXJhbSBTdHJpbmcgYVN0clxuICovXG5BcnJheVNldC5wcm90b3R5cGUuaW5kZXhPZiA9IGZ1bmN0aW9uIEFycmF5U2V0X2luZGV4T2YoYVN0cikge1xuICBpZiAoaGFzTmF0aXZlTWFwKSB7XG4gICAgdmFyIGlkeCA9IHRoaXMuX3NldC5nZXQoYVN0cik7XG4gICAgaWYgKGlkeCA+PSAwKSB7XG4gICAgICAgIHJldHVybiBpZHg7XG4gICAgfVxuICB9IGVsc2Uge1xuICAgIHZhciBzU3RyID0gdXRpbC50b1NldFN0cmluZyhhU3RyKTtcbiAgICBpZiAoaGFzLmNhbGwodGhpcy5fc2V0LCBzU3RyKSkge1xuICAgICAgcmV0dXJuIHRoaXMuX3NldFtzU3RyXTtcbiAgICB9XG4gIH1cblxuICB0aHJvdyBuZXcgRXJyb3IoJ1wiJyArIGFTdHIgKyAnXCIgaXMgbm90IGluIHRoZSBzZXQuJyk7XG59O1xuXG4vKipcbiAqIFdoYXQgaXMgdGhlIGVsZW1lbnQgYXQgdGhlIGdpdmVuIGluZGV4P1xuICpcbiAqIEBwYXJhbSBOdW1iZXIgYUlkeFxuICovXG5BcnJheVNldC5wcm90b3R5cGUuYXQgPSBmdW5jdGlvbiBBcnJheVNldF9hdChhSWR4KSB7XG4gIGlmIChhSWR4ID49IDAgJiYgYUlkeCA8IHRoaXMuX2FycmF5Lmxlbmd0aCkge1xuICAgIHJldHVybiB0aGlzLl9hcnJheVthSWR4XTtcbiAgfVxuICB0aHJvdyBuZXcgRXJyb3IoJ05vIGVsZW1lbnQgaW5kZXhlZCBieSAnICsgYUlkeCk7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIGFycmF5IHJlcHJlc2VudGF0aW9uIG9mIHRoaXMgc2V0ICh3aGljaCBoYXMgdGhlIHByb3BlciBpbmRpY2VzXG4gKiBpbmRpY2F0ZWQgYnkgaW5kZXhPZikuIE5vdGUgdGhhdCB0aGlzIGlzIGEgY29weSBvZiB0aGUgaW50ZXJuYWwgYXJyYXkgdXNlZFxuICogZm9yIHN0b3JpbmcgdGhlIG1lbWJlcnMgc28gdGhhdCBubyBvbmUgY2FuIG1lc3Mgd2l0aCBpbnRlcm5hbCBzdGF0ZS5cbiAqL1xuQXJyYXlTZXQucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBBcnJheVNldF90b0FycmF5KCkge1xuICByZXR1cm4gdGhpcy5fYXJyYXkuc2xpY2UoKTtcbn07XG5cbmV4cG9ydHMuQXJyYXlTZXQgPSBBcnJheVNldDtcblxuXG5cbi8vLy8vLy8vLy8vLy8vLy8vL1xuLy8gV0VCUEFDSyBGT09URVJcbi8vIC4vbGliL2FycmF5LXNldC5qc1xuLy8gbW9kdWxlIGlkID0gNVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTQgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciB1dGlsID0gcmVxdWlyZSgnLi91dGlsJyk7XG5cbi8qKlxuICogRGV0ZXJtaW5lIHdoZXRoZXIgbWFwcGluZ0IgaXMgYWZ0ZXIgbWFwcGluZ0Egd2l0aCByZXNwZWN0IHRvIGdlbmVyYXRlZFxuICogcG9zaXRpb24uXG4gKi9cbmZ1bmN0aW9uIGdlbmVyYXRlZFBvc2l0aW9uQWZ0ZXIobWFwcGluZ0EsIG1hcHBpbmdCKSB7XG4gIC8vIE9wdGltaXplZCBmb3IgbW9zdCBjb21tb24gY2FzZVxuICB2YXIgbGluZUEgPSBtYXBwaW5nQS5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgbGluZUIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRMaW5lO1xuICB2YXIgY29sdW1uQSA9IG1hcHBpbmdBLmdlbmVyYXRlZENvbHVtbjtcbiAgdmFyIGNvbHVtbkIgPSBtYXBwaW5nQi5nZW5lcmF0ZWRDb2x1bW47XG4gIHJldHVybiBsaW5lQiA+IGxpbmVBIHx8IGxpbmVCID09IGxpbmVBICYmIGNvbHVtbkIgPj0gY29sdW1uQSB8fFxuICAgICAgICAgdXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZChtYXBwaW5nQSwgbWFwcGluZ0IpIDw9IDA7XG59XG5cbi8qKlxuICogQSBkYXRhIHN0cnVjdHVyZSB0byBwcm92aWRlIGEgc29ydGVkIHZpZXcgb2YgYWNjdW11bGF0ZWQgbWFwcGluZ3MgaW4gYVxuICogcGVyZm9ybWFuY2UgY29uc2Npb3VzIG1hbm5lci4gSXQgdHJhZGVzIGEgbmVnbGliYWJsZSBvdmVyaGVhZCBpbiBnZW5lcmFsXG4gKiBjYXNlIGZvciBhIGxhcmdlIHNwZWVkdXAgaW4gY2FzZSBvZiBtYXBwaW5ncyBiZWluZyBhZGRlZCBpbiBvcmRlci5cbiAqL1xuZnVuY3Rpb24gTWFwcGluZ0xpc3QoKSB7XG4gIHRoaXMuX2FycmF5ID0gW107XG4gIHRoaXMuX3NvcnRlZCA9IHRydWU7XG4gIC8vIFNlcnZlcyBhcyBpbmZpbXVtXG4gIHRoaXMuX2xhc3QgPSB7Z2VuZXJhdGVkTGluZTogLTEsIGdlbmVyYXRlZENvbHVtbjogMH07XG59XG5cbi8qKlxuICogSXRlcmF0ZSB0aHJvdWdoIGludGVybmFsIGl0ZW1zLiBUaGlzIG1ldGhvZCB0YWtlcyB0aGUgc2FtZSBhcmd1bWVudHMgdGhhdFxuICogYEFycmF5LnByb3RvdHlwZS5mb3JFYWNoYCB0YWtlcy5cbiAqXG4gKiBOT1RFOiBUaGUgb3JkZXIgb2YgdGhlIG1hcHBpbmdzIGlzIE5PVCBndWFyYW50ZWVkLlxuICovXG5NYXBwaW5nTGlzdC5wcm90b3R5cGUudW5zb3J0ZWRGb3JFYWNoID1cbiAgZnVuY3Rpb24gTWFwcGluZ0xpc3RfZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKSB7XG4gICAgdGhpcy5fYXJyYXkuZm9yRWFjaChhQ2FsbGJhY2ssIGFUaGlzQXJnKTtcbiAgfTtcblxuLyoqXG4gKiBBZGQgdGhlIGdpdmVuIHNvdXJjZSBtYXBwaW5nLlxuICpcbiAqIEBwYXJhbSBPYmplY3QgYU1hcHBpbmdcbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLmFkZCA9IGZ1bmN0aW9uIE1hcHBpbmdMaXN0X2FkZChhTWFwcGluZykge1xuICBpZiAoZ2VuZXJhdGVkUG9zaXRpb25BZnRlcih0aGlzLl9sYXN0LCBhTWFwcGluZykpIHtcbiAgICB0aGlzLl9sYXN0ID0gYU1hcHBpbmc7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH0gZWxzZSB7XG4gICAgdGhpcy5fc29ydGVkID0gZmFsc2U7XG4gICAgdGhpcy5fYXJyYXkucHVzaChhTWFwcGluZyk7XG4gIH1cbn07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgZmxhdCwgc29ydGVkIGFycmF5IG9mIG1hcHBpbmdzLiBUaGUgbWFwcGluZ3MgYXJlIHNvcnRlZCBieVxuICogZ2VuZXJhdGVkIHBvc2l0aW9uLlxuICpcbiAqIFdBUk5JTkc6IFRoaXMgbWV0aG9kIHJldHVybnMgaW50ZXJuYWwgZGF0YSB3aXRob3V0IGNvcHlpbmcsIGZvclxuICogcGVyZm9ybWFuY2UuIFRoZSByZXR1cm4gdmFsdWUgbXVzdCBOT1QgYmUgbXV0YXRlZCwgYW5kIHNob3VsZCBiZSB0cmVhdGVkIGFzXG4gKiBhbiBpbW11dGFibGUgYm9ycm93LiBJZiB5b3Ugd2FudCB0byB0YWtlIG93bmVyc2hpcCwgeW91IG11c3QgbWFrZSB5b3VyIG93blxuICogY29weS5cbiAqL1xuTWFwcGluZ0xpc3QucHJvdG90eXBlLnRvQXJyYXkgPSBmdW5jdGlvbiBNYXBwaW5nTGlzdF90b0FycmF5KCkge1xuICBpZiAoIXRoaXMuX3NvcnRlZCkge1xuICAgIHRoaXMuX2FycmF5LnNvcnQodXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNJbmZsYXRlZCk7XG4gICAgdGhpcy5fc29ydGVkID0gdHJ1ZTtcbiAgfVxuICByZXR1cm4gdGhpcy5fYXJyYXk7XG59O1xuXG5leHBvcnRzLk1hcHBpbmdMaXN0ID0gTWFwcGluZ0xpc3Q7XG5cblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2xpYi9tYXBwaW5nLWxpc3QuanNcbi8vIG1vZHVsZSBpZCA9IDZcbi8vIG1vZHVsZSBjaHVua3MgPSAwIiwiLyogLSotIE1vZGU6IGpzOyBqcy1pbmRlbnQtbGV2ZWw6IDI7IC0qLSAqL1xuLypcbiAqIENvcHlyaWdodCAyMDExIE1vemlsbGEgRm91bmRhdGlvbiBhbmQgY29udHJpYnV0b3JzXG4gKiBMaWNlbnNlZCB1bmRlciB0aGUgTmV3IEJTRCBsaWNlbnNlLiBTZWUgTElDRU5TRSBvcjpcbiAqIGh0dHA6Ly9vcGVuc291cmNlLm9yZy9saWNlbnNlcy9CU0QtMy1DbGF1c2VcbiAqL1xuXG52YXIgdXRpbCA9IHJlcXVpcmUoJy4vdXRpbCcpO1xudmFyIGJpbmFyeVNlYXJjaCA9IHJlcXVpcmUoJy4vYmluYXJ5LXNlYXJjaCcpO1xudmFyIEFycmF5U2V0ID0gcmVxdWlyZSgnLi9hcnJheS1zZXQnKS5BcnJheVNldDtcbnZhciBiYXNlNjRWTFEgPSByZXF1aXJlKCcuL2Jhc2U2NC12bHEnKTtcbnZhciBxdWlja1NvcnQgPSByZXF1aXJlKCcuL3F1aWNrLXNvcnQnKS5xdWlja1NvcnQ7XG5cbmZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyKGFTb3VyY2VNYXApIHtcbiAgdmFyIHNvdXJjZU1hcCA9IGFTb3VyY2VNYXA7XG4gIGlmICh0eXBlb2YgYVNvdXJjZU1hcCA9PT0gJ3N0cmluZycpIHtcbiAgICBzb3VyY2VNYXAgPSBKU09OLnBhcnNlKGFTb3VyY2VNYXAucmVwbGFjZSgvXlxcKVxcXVxcfScvLCAnJykpO1xuICB9XG5cbiAgcmV0dXJuIHNvdXJjZU1hcC5zZWN0aW9ucyAhPSBudWxsXG4gICAgPyBuZXcgSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyKHNvdXJjZU1hcClcbiAgICA6IG5ldyBCYXNpY1NvdXJjZU1hcENvbnN1bWVyKHNvdXJjZU1hcCk7XG59XG5cblNvdXJjZU1hcENvbnN1bWVyLmZyb21Tb3VyY2VNYXAgPSBmdW5jdGlvbihhU291cmNlTWFwKSB7XG4gIHJldHVybiBCYXNpY1NvdXJjZU1hcENvbnN1bWVyLmZyb21Tb3VyY2VNYXAoYVNvdXJjZU1hcCk7XG59XG5cbi8qKlxuICogVGhlIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXBwaW5nIHNwZWMgdGhhdCB3ZSBhcmUgY29uc3VtaW5nLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3ZlcnNpb24gPSAzO1xuXG4vLyBgX19nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kIGBfX29yaWdpbmFsTWFwcGluZ3NgIGFyZSBhcnJheXMgdGhhdCBob2xkIHRoZVxuLy8gcGFyc2VkIG1hcHBpbmcgY29vcmRpbmF0ZXMgZnJvbSB0aGUgc291cmNlIG1hcCdzIFwibWFwcGluZ3NcIiBhdHRyaWJ1dGUuIFRoZXlcbi8vIGFyZSBsYXppbHkgaW5zdGFudGlhdGVkLCBhY2Nlc3NlZCB2aWEgdGhlIGBfZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuLy8gYF9vcmlnaW5hbE1hcHBpbmdzYCBnZXR0ZXJzIHJlc3BlY3RpdmVseSwgYW5kIHdlIG9ubHkgcGFyc2UgdGhlIG1hcHBpbmdzXG4vLyBhbmQgY3JlYXRlIHRoZXNlIGFycmF5cyBvbmNlIHF1ZXJpZWQgZm9yIGEgc291cmNlIGxvY2F0aW9uLiBXZSBqdW1wIHRocm91Z2hcbi8vIHRoZXNlIGhvb3BzIGJlY2F1c2UgdGhlcmUgY2FuIGJlIG1hbnkgdGhvdXNhbmRzIG9mIG1hcHBpbmdzLCBhbmQgcGFyc2luZ1xuLy8gdGhlbSBpcyBleHBlbnNpdmUsIHNvIHdlIG9ubHkgd2FudCB0byBkbyBpdCBpZiB3ZSBtdXN0LlxuLy9cbi8vIEVhY2ggb2JqZWN0IGluIHRoZSBhcnJheXMgaXMgb2YgdGhlIGZvcm06XG4vL1xuLy8gICAgIHtcbi8vICAgICAgIGdlbmVyYXRlZExpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIGNvZGUsXG4vLyAgICAgICBnZW5lcmF0ZWRDb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgY29kZSxcbi8vICAgICAgIHNvdXJjZTogVGhlIHBhdGggdG8gdGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlIHRoYXQgZ2VuZXJhdGVkIHRoaXNcbi8vICAgICAgICAgICAgICAgY2h1bmsgb2YgY29kZSxcbi8vICAgICAgIG9yaWdpbmFsTGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UgdGhhdFxuLy8gICAgICAgICAgICAgICAgICAgICBjb3JyZXNwb25kcyB0byB0aGlzIGNodW5rIG9mIGdlbmVyYXRlZCBjb2RlLFxuLy8gICAgICAgb3JpZ2luYWxDb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UgdGhhdFxuLy8gICAgICAgICAgICAgICAgICAgICAgIGNvcnJlc3BvbmRzIHRvIHRoaXMgY2h1bmsgb2YgZ2VuZXJhdGVkIGNvZGUsXG4vLyAgICAgICBuYW1lOiBUaGUgbmFtZSBvZiB0aGUgb3JpZ2luYWwgc3ltYm9sIHdoaWNoIGdlbmVyYXRlZCB0aGlzIGNodW5rIG9mXG4vLyAgICAgICAgICAgICBjb2RlLlxuLy8gICAgIH1cbi8vXG4vLyBBbGwgcHJvcGVydGllcyBleGNlcHQgZm9yIGBnZW5lcmF0ZWRMaW5lYCBhbmQgYGdlbmVyYXRlZENvbHVtbmAgY2FuIGJlXG4vLyBgbnVsbGAuXG4vL1xuLy8gYF9nZW5lcmF0ZWRNYXBwaW5nc2AgaXMgb3JkZXJlZCBieSB0aGUgZ2VuZXJhdGVkIHBvc2l0aW9ucy5cbi8vXG4vLyBgX29yaWdpbmFsTWFwcGluZ3NgIGlzIG9yZGVyZWQgYnkgdGhlIG9yaWdpbmFsIHBvc2l0aW9ucy5cblxuU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBudWxsO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSwgJ19nZW5lcmF0ZWRNYXBwaW5ncycsIHtcbiAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgaWYgKCF0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MpIHtcbiAgICAgIHRoaXMuX3BhcnNlTWFwcGluZ3ModGhpcy5fbWFwcGluZ3MsIHRoaXMuc291cmNlUm9vdCk7XG4gICAgfVxuXG4gICAgcmV0dXJuIHRoaXMuX19nZW5lcmF0ZWRNYXBwaW5ncztcbiAgfVxufSk7XG5cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fX29yaWdpbmFsTWFwcGluZ3MgPSBudWxsO1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSwgJ19vcmlnaW5hbE1hcHBpbmdzJywge1xuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICBpZiAoIXRoaXMuX19vcmlnaW5hbE1hcHBpbmdzKSB7XG4gICAgICB0aGlzLl9wYXJzZU1hcHBpbmdzKHRoaXMuX21hcHBpbmdzLCB0aGlzLnNvdXJjZVJvb3QpO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncztcbiAgfVxufSk7XG5cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fY2hhcklzTWFwcGluZ1NlcGFyYXRvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NoYXJJc01hcHBpbmdTZXBhcmF0b3IoYVN0ciwgaW5kZXgpIHtcbiAgICB2YXIgYyA9IGFTdHIuY2hhckF0KGluZGV4KTtcbiAgICByZXR1cm4gYyA9PT0gXCI7XCIgfHwgYyA9PT0gXCIsXCI7XG4gIH07XG5cbi8qKlxuICogUGFyc2UgdGhlIG1hcHBpbmdzIGluIGEgc3RyaW5nIGluIHRvIGEgZGF0YSBzdHJ1Y3R1cmUgd2hpY2ggd2UgY2FuIGVhc2lseVxuICogcXVlcnkgKHRoZSBvcmRlcmVkIGFycmF5cyBpbiB0aGUgYHRoaXMuX19nZW5lcmF0ZWRNYXBwaW5nc2AgYW5kXG4gKiBgdGhpcy5fX29yaWdpbmFsTWFwcGluZ3NgIHByb3BlcnRpZXMpLlxuICovXG5Tb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKFwiU3ViY2xhc3NlcyBtdXN0IGltcGxlbWVudCBfcGFyc2VNYXBwaW5nc1wiKTtcbiAgfTtcblxuU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSID0gMTtcblNvdXJjZU1hcENvbnN1bWVyLk9SSUdJTkFMX09SREVSID0gMjtcblxuU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuU291cmNlTWFwQ29uc3VtZXIuTEVBU1RfVVBQRVJfQk9VTkQgPSAyO1xuXG4vKipcbiAqIEl0ZXJhdGUgb3ZlciBlYWNoIG1hcHBpbmcgYmV0d2VlbiBhbiBvcmlnaW5hbCBzb3VyY2UvbGluZS9jb2x1bW4gYW5kIGFcbiAqIGdlbmVyYXRlZCBsaW5lL2NvbHVtbiBpbiB0aGlzIHNvdXJjZSBtYXAuXG4gKlxuICogQHBhcmFtIEZ1bmN0aW9uIGFDYWxsYmFja1xuICogICAgICAgIFRoZSBmdW5jdGlvbiB0aGF0IGlzIGNhbGxlZCB3aXRoIGVhY2ggbWFwcGluZy5cbiAqIEBwYXJhbSBPYmplY3QgYUNvbnRleHRcbiAqICAgICAgICBPcHRpb25hbC4gSWYgc3BlY2lmaWVkLCB0aGlzIG9iamVjdCB3aWxsIGJlIHRoZSB2YWx1ZSBvZiBgdGhpc2AgZXZlcnlcbiAqICAgICAgICB0aW1lIHRoYXQgYGFDYWxsYmFja2AgaXMgY2FsbGVkLlxuICogQHBhcmFtIGFPcmRlclxuICogICAgICAgIEVpdGhlciBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYCBvclxuICogICAgICAgIGBTb3VyY2VNYXBDb25zdW1lci5PUklHSU5BTF9PUkRFUmAuIFNwZWNpZmllcyB3aGV0aGVyIHlvdSB3YW50IHRvXG4gKiAgICAgICAgaXRlcmF0ZSBvdmVyIHRoZSBtYXBwaW5ncyBzb3J0ZWQgYnkgdGhlIGdlbmVyYXRlZCBmaWxlJ3MgbGluZS9jb2x1bW5cbiAqICAgICAgICBvcmRlciBvciB0aGUgb3JpZ2luYWwncyBzb3VyY2UvbGluZS9jb2x1bW4gb3JkZXIsIHJlc3BlY3RpdmVseS4gRGVmYXVsdHMgdG9cbiAqICAgICAgICBgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSYC5cbiAqL1xuU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmVhY2hNYXBwaW5nID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfZWFjaE1hcHBpbmcoYUNhbGxiYWNrLCBhQ29udGV4dCwgYU9yZGVyKSB7XG4gICAgdmFyIGNvbnRleHQgPSBhQ29udGV4dCB8fCBudWxsO1xuICAgIHZhciBvcmRlciA9IGFPcmRlciB8fCBTb3VyY2VNYXBDb25zdW1lci5HRU5FUkFURURfT1JERVI7XG5cbiAgICB2YXIgbWFwcGluZ3M7XG4gICAgc3dpdGNoIChvcmRlcikge1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuR0VORVJBVEVEX09SREVSOlxuICAgICAgbWFwcGluZ3MgPSB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncztcbiAgICAgIGJyZWFrO1xuICAgIGNhc2UgU291cmNlTWFwQ29uc3VtZXIuT1JJR0lOQUxfT1JERVI6XG4gICAgICBtYXBwaW5ncyA9IHRoaXMuX29yaWdpbmFsTWFwcGluZ3M7XG4gICAgICBicmVhaztcbiAgICBkZWZhdWx0OlxuICAgICAgdGhyb3cgbmV3IEVycm9yKFwiVW5rbm93biBvcmRlciBvZiBpdGVyYXRpb24uXCIpO1xuICAgIH1cblxuICAgIHZhciBzb3VyY2VSb290ID0gdGhpcy5zb3VyY2VSb290O1xuICAgIG1hcHBpbmdzLm1hcChmdW5jdGlvbiAobWFwcGluZykge1xuICAgICAgdmFyIHNvdXJjZSA9IG1hcHBpbmcuc291cmNlID09PSBudWxsID8gbnVsbCA6IHRoaXMuX3NvdXJjZXMuYXQobWFwcGluZy5zb3VyY2UpO1xuICAgICAgaWYgKHNvdXJjZSAhPSBudWxsICYmIHNvdXJjZVJvb3QgIT0gbnVsbCkge1xuICAgICAgICBzb3VyY2UgPSB1dGlsLmpvaW4oc291cmNlUm9vdCwgc291cmNlKTtcbiAgICAgIH1cbiAgICAgIHJldHVybiB7XG4gICAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgICBnZW5lcmF0ZWRMaW5lOiBtYXBwaW5nLmdlbmVyYXRlZExpbmUsXG4gICAgICAgIGdlbmVyYXRlZENvbHVtbjogbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4sXG4gICAgICAgIG9yaWdpbmFsTGluZTogbWFwcGluZy5vcmlnaW5hbExpbmUsXG4gICAgICAgIG9yaWdpbmFsQ29sdW1uOiBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uLFxuICAgICAgICBuYW1lOiBtYXBwaW5nLm5hbWUgPT09IG51bGwgPyBudWxsIDogdGhpcy5fbmFtZXMuYXQobWFwcGluZy5uYW1lKVxuICAgICAgfTtcbiAgICB9LCB0aGlzKS5mb3JFYWNoKGFDYWxsYmFjaywgY29udGV4dCk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyBhbGwgZ2VuZXJhdGVkIGxpbmUgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIG9yaWdpbmFsIHNvdXJjZSxcbiAqIGxpbmUsIGFuZCBjb2x1bW4gcHJvdmlkZWQuIElmIG5vIGNvbHVtbiBpcyBwcm92aWRlZCwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gYSBlaXRoZXIgdGhlIGxpbmUgd2UgYXJlIHNlYXJjaGluZyBmb3Igb3IgdGhlIG5leHRcbiAqIGNsb3Nlc3QgbGluZSB0aGF0IGhhcyBhbnkgbWFwcGluZ3MuIE90aGVyd2lzZSwgcmV0dXJucyBhbGwgbWFwcGluZ3NcbiAqIGNvcnJlc3BvbmRpbmcgdG8gdGhlIGdpdmVuIGxpbmUgYW5kIGVpdGhlciB0aGUgY29sdW1uIHdlIGFyZSBzZWFyY2hpbmcgZm9yXG4gKiBvciB0aGUgbmV4dCBjbG9zZXN0IGNvbHVtbiB0aGF0IGhhcyBhbnkgb2Zmc2V0cy5cbiAqXG4gKiBUaGUgb25seSBhcmd1bWVudCBpcyBhbiBvYmplY3Qgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIGZpbGVuYW1lIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gY29sdW1uOiBPcHRpb25hbC4gdGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZS5cbiAqXG4gKiBhbmQgYW4gYXJyYXkgb2Ygb2JqZWN0cyBpcyByZXR1cm5lZCwgZWFjaCB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLCBvciBudWxsLlxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UsIG9yIG51bGwuXG4gKi9cblNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5hbGxHZW5lcmF0ZWRQb3NpdGlvbnNGb3IgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9hbGxHZW5lcmF0ZWRQb3NpdGlvbnNGb3IoYUFyZ3MpIHtcbiAgICB2YXIgbGluZSA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnbGluZScpO1xuXG4gICAgLy8gV2hlbiB0aGVyZSBpcyBubyBleGFjdCBtYXRjaCwgQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX2ZpbmRNYXBwaW5nXG4gICAgLy8gcmV0dXJucyB0aGUgaW5kZXggb2YgdGhlIGNsb3Nlc3QgbWFwcGluZyBsZXNzIHRoYW4gdGhlIG5lZWRsZS4gQnlcbiAgICAvLyBzZXR0aW5nIG5lZWRsZS5vcmlnaW5hbENvbHVtbiB0byAwLCB3ZSB0aHVzIGZpbmQgdGhlIGxhc3QgbWFwcGluZyBmb3JcbiAgICAvLyB0aGUgZ2l2ZW4gbGluZSwgcHJvdmlkZWQgc3VjaCBhIG1hcHBpbmcgZXhpc3RzLlxuICAgIHZhciBuZWVkbGUgPSB7XG4gICAgICBzb3VyY2U6IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJyksXG4gICAgICBvcmlnaW5hbExpbmU6IGxpbmUsXG4gICAgICBvcmlnaW5hbENvbHVtbjogdXRpbC5nZXRBcmcoYUFyZ3MsICdjb2x1bW4nLCAwKVxuICAgIH07XG5cbiAgICBpZiAodGhpcy5zb3VyY2VSb290ICE9IG51bGwpIHtcbiAgICAgIG5lZWRsZS5zb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHRoaXMuc291cmNlUm9vdCwgbmVlZGxlLnNvdXJjZSk7XG4gICAgfVxuICAgIGlmICghdGhpcy5fc291cmNlcy5oYXMobmVlZGxlLnNvdXJjZSkpIHtcbiAgICAgIHJldHVybiBbXTtcbiAgICB9XG4gICAgbmVlZGxlLnNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuaW5kZXhPZihuZWVkbGUuc291cmNlKTtcblxuICAgIHZhciBtYXBwaW5ncyA9IFtdO1xuXG4gICAgdmFyIGluZGV4ID0gdGhpcy5fZmluZE1hcHBpbmcobmVlZGxlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuX29yaWdpbmFsTWFwcGluZ3MsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJvcmlnaW5hbExpbmVcIixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIm9yaWdpbmFsQ29sdW1uXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdXRpbC5jb21wYXJlQnlPcmlnaW5hbFBvc2l0aW9ucyxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBiaW5hcnlTZWFyY2guTEVBU1RfVVBQRVJfQk9VTkQpO1xuICAgIGlmIChpbmRleCA+PSAwKSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX29yaWdpbmFsTWFwcGluZ3NbaW5kZXhdO1xuXG4gICAgICBpZiAoYUFyZ3MuY29sdW1uID09PSB1bmRlZmluZWQpIHtcbiAgICAgICAgdmFyIG9yaWdpbmFsTGluZSA9IG1hcHBpbmcub3JpZ2luYWxMaW5lO1xuXG4gICAgICAgIC8vIEl0ZXJhdGUgdW50aWwgZWl0aGVyIHdlIHJ1biBvdXQgb2YgbWFwcGluZ3MsIG9yIHdlIHJ1biBpbnRvXG4gICAgICAgIC8vIGEgbWFwcGluZyBmb3IgYSBkaWZmZXJlbnQgbGluZSB0aGFuIHRoZSBvbmUgd2UgZm91bmQuIFNpbmNlXG4gICAgICAgIC8vIG1hcHBpbmdzIGFyZSBzb3J0ZWQsIHRoaXMgaXMgZ3VhcmFudGVlZCB0byBmaW5kIGFsbCBtYXBwaW5ncyBmb3JcbiAgICAgICAgLy8gdGhlIGxpbmUgd2UgZm91bmQuXG4gICAgICAgIHdoaWxlIChtYXBwaW5nICYmIG1hcHBpbmcub3JpZ2luYWxMaW5lID09PSBvcmlnaW5hbExpbmUpIHtcbiAgICAgICAgICBtYXBwaW5ncy5wdXNoKHtcbiAgICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRMaW5lJywgbnVsbCksXG4gICAgICAgICAgICBjb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRDb2x1bW4nLCBudWxsKSxcbiAgICAgICAgICAgIGxhc3RDb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdsYXN0R2VuZXJhdGVkQ29sdW1uJywgbnVsbClcbiAgICAgICAgICB9KTtcblxuICAgICAgICAgIG1hcHBpbmcgPSB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzWysraW5kZXhdO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICB2YXIgb3JpZ2luYWxDb2x1bW4gPSBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uO1xuXG4gICAgICAgIC8vIEl0ZXJhdGUgdW50aWwgZWl0aGVyIHdlIHJ1biBvdXQgb2YgbWFwcGluZ3MsIG9yIHdlIHJ1biBpbnRvXG4gICAgICAgIC8vIGEgbWFwcGluZyBmb3IgYSBkaWZmZXJlbnQgbGluZSB0aGFuIHRoZSBvbmUgd2Ugd2VyZSBzZWFyY2hpbmcgZm9yLlxuICAgICAgICAvLyBTaW5jZSBtYXBwaW5ncyBhcmUgc29ydGVkLCB0aGlzIGlzIGd1YXJhbnRlZWQgdG8gZmluZCBhbGwgbWFwcGluZ3MgZm9yXG4gICAgICAgIC8vIHRoZSBsaW5lIHdlIGFyZSBzZWFyY2hpbmcgZm9yLlxuICAgICAgICB3aGlsZSAobWFwcGluZyAmJlxuICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgPT09IGxpbmUgJiZcbiAgICAgICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxDb2x1bW4gPT0gb3JpZ2luYWxDb2x1bW4pIHtcbiAgICAgICAgICBtYXBwaW5ncy5wdXNoKHtcbiAgICAgICAgICAgIGxpbmU6IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRMaW5lJywgbnVsbCksXG4gICAgICAgICAgICBjb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdnZW5lcmF0ZWRDb2x1bW4nLCBudWxsKSxcbiAgICAgICAgICAgIGxhc3RDb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdsYXN0R2VuZXJhdGVkQ29sdW1uJywgbnVsbClcbiAgICAgICAgICB9KTtcblxuICAgICAgICAgIG1hcHBpbmcgPSB0aGlzLl9vcmlnaW5hbE1hcHBpbmdzWysraW5kZXhdO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuXG4gICAgcmV0dXJuIG1hcHBpbmdzO1xuICB9O1xuXG5leHBvcnRzLlNvdXJjZU1hcENvbnN1bWVyID0gU291cmNlTWFwQ29uc3VtZXI7XG5cbi8qKlxuICogQSBCYXNpY1NvdXJjZU1hcENvbnN1bWVyIGluc3RhbmNlIHJlcHJlc2VudHMgYSBwYXJzZWQgc291cmNlIG1hcCB3aGljaCB3ZSBjYW5cbiAqIHF1ZXJ5IGZvciBpbmZvcm1hdGlvbiBhYm91dCB0aGUgb3JpZ2luYWwgZmlsZSBwb3NpdGlvbnMgYnkgZ2l2aW5nIGl0IGEgZmlsZVxuICogcG9zaXRpb24gaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UuXG4gKlxuICogVGhlIG9ubHkgcGFyYW1ldGVyIGlzIHRoZSByYXcgc291cmNlIG1hcCAoZWl0aGVyIGFzIGEgSlNPTiBzdHJpbmcsIG9yXG4gKiBhbHJlYWR5IHBhcnNlZCB0byBhbiBvYmplY3QpLiBBY2NvcmRpbmcgdG8gdGhlIHNwZWMsIHNvdXJjZSBtYXBzIGhhdmUgdGhlXG4gKiBmb2xsb3dpbmcgYXR0cmlidXRlczpcbiAqXG4gKiAgIC0gdmVyc2lvbjogV2hpY2ggdmVyc2lvbiBvZiB0aGUgc291cmNlIG1hcCBzcGVjIHRoaXMgbWFwIGlzIGZvbGxvd2luZy5cbiAqICAgLSBzb3VyY2VzOiBBbiBhcnJheSBvZiBVUkxzIHRvIHRoZSBvcmlnaW5hbCBzb3VyY2UgZmlsZXMuXG4gKiAgIC0gbmFtZXM6IEFuIGFycmF5IG9mIGlkZW50aWZpZXJzIHdoaWNoIGNhbiBiZSByZWZlcnJlbmNlZCBieSBpbmRpdmlkdWFsIG1hcHBpbmdzLlxuICogICAtIHNvdXJjZVJvb3Q6IE9wdGlvbmFsLiBUaGUgVVJMIHJvb3QgZnJvbSB3aGljaCBhbGwgc291cmNlcyBhcmUgcmVsYXRpdmUuXG4gKiAgIC0gc291cmNlc0NvbnRlbnQ6IE9wdGlvbmFsLiBBbiBhcnJheSBvZiBjb250ZW50cyBvZiB0aGUgb3JpZ2luYWwgc291cmNlIGZpbGVzLlxuICogICAtIG1hcHBpbmdzOiBBIHN0cmluZyBvZiBiYXNlNjQgVkxRcyB3aGljaCBjb250YWluIHRoZSBhY3R1YWwgbWFwcGluZ3MuXG4gKiAgIC0gZmlsZTogT3B0aW9uYWwuIFRoZSBnZW5lcmF0ZWQgZmlsZSB0aGlzIHNvdXJjZSBtYXAgaXMgYXNzb2NpYXRlZCB3aXRoLlxuICpcbiAqIEhlcmUgaXMgYW4gZXhhbXBsZSBzb3VyY2UgbWFwLCB0YWtlbiBmcm9tIHRoZSBzb3VyY2UgbWFwIHNwZWNbMF06XG4gKlxuICogICAgIHtcbiAqICAgICAgIHZlcnNpb24gOiAzLFxuICogICAgICAgZmlsZTogXCJvdXQuanNcIixcbiAqICAgICAgIHNvdXJjZVJvb3QgOiBcIlwiLFxuICogICAgICAgc291cmNlczogW1wiZm9vLmpzXCIsIFwiYmFyLmpzXCJdLFxuICogICAgICAgbmFtZXM6IFtcInNyY1wiLCBcIm1hcHNcIiwgXCJhcmVcIiwgXCJmdW5cIl0sXG4gKiAgICAgICBtYXBwaW5nczogXCJBQSxBQjs7QUJDREU7XCJcbiAqICAgICB9XG4gKlxuICogWzBdOiBodHRwczovL2RvY3MuZ29vZ2xlLmNvbS9kb2N1bWVudC9kLzFVMVJHQWVoUXdSeXBVVG92RjFLUmxwaU9GemUwYi1fMmdjNmZBSDBLWTBrL2VkaXQ/cGxpPTEjXG4gKi9cbmZ1bmN0aW9uIEJhc2ljU291cmNlTWFwQ29uc3VtZXIoYVNvdXJjZU1hcCkge1xuICB2YXIgc291cmNlTWFwID0gYVNvdXJjZU1hcDtcbiAgaWYgKHR5cGVvZiBhU291cmNlTWFwID09PSAnc3RyaW5nJykge1xuICAgIHNvdXJjZU1hcCA9IEpTT04ucGFyc2UoYVNvdXJjZU1hcC5yZXBsYWNlKC9eXFwpXFxdXFx9Jy8sICcnKSk7XG4gIH1cblxuICB2YXIgdmVyc2lvbiA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3ZlcnNpb24nKTtcbiAgdmFyIHNvdXJjZXMgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICdzb3VyY2VzJyk7XG4gIC8vIFNhc3MgMy4zIGxlYXZlcyBvdXQgdGhlICduYW1lcycgYXJyYXksIHNvIHdlIGRldmlhdGUgZnJvbSB0aGUgc3BlYyAod2hpY2hcbiAgLy8gcmVxdWlyZXMgdGhlIGFycmF5KSB0byBwbGF5IG5pY2UgaGVyZS5cbiAgdmFyIG5hbWVzID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnbmFtZXMnLCBbXSk7XG4gIHZhciBzb3VyY2VSb290ID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnc291cmNlUm9vdCcsIG51bGwpO1xuICB2YXIgc291cmNlc0NvbnRlbnQgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICdzb3VyY2VzQ29udGVudCcsIG51bGwpO1xuICB2YXIgbWFwcGluZ3MgPSB1dGlsLmdldEFyZyhzb3VyY2VNYXAsICdtYXBwaW5ncycpO1xuICB2YXIgZmlsZSA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ2ZpbGUnLCBudWxsKTtcblxuICAvLyBPbmNlIGFnYWluLCBTYXNzIGRldmlhdGVzIGZyb20gdGhlIHNwZWMgYW5kIHN1cHBsaWVzIHRoZSB2ZXJzaW9uIGFzIGFcbiAgLy8gc3RyaW5nIHJhdGhlciB0aGFuIGEgbnVtYmVyLCBzbyB3ZSB1c2UgbG9vc2UgZXF1YWxpdHkgY2hlY2tpbmcgaGVyZS5cbiAgaWYgKHZlcnNpb24gIT0gdGhpcy5fdmVyc2lvbikge1xuICAgIHRocm93IG5ldyBFcnJvcignVW5zdXBwb3J0ZWQgdmVyc2lvbjogJyArIHZlcnNpb24pO1xuICB9XG5cbiAgc291cmNlcyA9IHNvdXJjZXNcbiAgICAubWFwKFN0cmluZylcbiAgICAvLyBTb21lIHNvdXJjZSBtYXBzIHByb2R1Y2UgcmVsYXRpdmUgc291cmNlIHBhdGhzIGxpa2UgXCIuL2Zvby5qc1wiIGluc3RlYWQgb2ZcbiAgICAvLyBcImZvby5qc1wiLiAgTm9ybWFsaXplIHRoZXNlIGZpcnN0IHNvIHRoYXQgZnV0dXJlIGNvbXBhcmlzb25zIHdpbGwgc3VjY2VlZC5cbiAgICAvLyBTZWUgYnVnemlsLmxhLzEwOTA3NjguXG4gICAgLm1hcCh1dGlsLm5vcm1hbGl6ZSlcbiAgICAvLyBBbHdheXMgZW5zdXJlIHRoYXQgYWJzb2x1dGUgc291cmNlcyBhcmUgaW50ZXJuYWxseSBzdG9yZWQgcmVsYXRpdmUgdG9cbiAgICAvLyB0aGUgc291cmNlIHJvb3QsIGlmIHRoZSBzb3VyY2Ugcm9vdCBpcyBhYnNvbHV0ZS4gTm90IGRvaW5nIHRoaXMgd291bGRcbiAgICAvLyBiZSBwYXJ0aWN1bGFybHkgcHJvYmxlbWF0aWMgd2hlbiB0aGUgc291cmNlIHJvb3QgaXMgYSBwcmVmaXggb2YgdGhlXG4gICAgLy8gc291cmNlICh2YWxpZCwgYnV0IHdoeT8/KS4gU2VlIGdpdGh1YiBpc3N1ZSAjMTk5IGFuZCBidWd6aWwubGEvMTE4ODk4Mi5cbiAgICAubWFwKGZ1bmN0aW9uIChzb3VyY2UpIHtcbiAgICAgIHJldHVybiBzb3VyY2VSb290ICYmIHV0aWwuaXNBYnNvbHV0ZShzb3VyY2VSb290KSAmJiB1dGlsLmlzQWJzb2x1dGUoc291cmNlKVxuICAgICAgICA/IHV0aWwucmVsYXRpdmUoc291cmNlUm9vdCwgc291cmNlKVxuICAgICAgICA6IHNvdXJjZTtcbiAgICB9KTtcblxuICAvLyBQYXNzIGB0cnVlYCBiZWxvdyB0byBhbGxvdyBkdXBsaWNhdGUgbmFtZXMgYW5kIHNvdXJjZXMuIFdoaWxlIHNvdXJjZSBtYXBzXG4gIC8vIGFyZSBpbnRlbmRlZCB0byBiZSBjb21wcmVzc2VkIGFuZCBkZWR1cGxpY2F0ZWQsIHRoZSBUeXBlU2NyaXB0IGNvbXBpbGVyXG4gIC8vIHNvbWV0aW1lcyBnZW5lcmF0ZXMgc291cmNlIG1hcHMgd2l0aCBkdXBsaWNhdGVzIGluIHRoZW0uIFNlZSBHaXRodWIgaXNzdWVcbiAgLy8gIzcyIGFuZCBidWd6aWwubGEvODg5NDkyLlxuICB0aGlzLl9uYW1lcyA9IEFycmF5U2V0LmZyb21BcnJheShuYW1lcy5tYXAoU3RyaW5nKSwgdHJ1ZSk7XG4gIHRoaXMuX3NvdXJjZXMgPSBBcnJheVNldC5mcm9tQXJyYXkoc291cmNlcywgdHJ1ZSk7XG5cbiAgdGhpcy5zb3VyY2VSb290ID0gc291cmNlUm9vdDtcbiAgdGhpcy5zb3VyY2VzQ29udGVudCA9IHNvdXJjZXNDb250ZW50O1xuICB0aGlzLl9tYXBwaW5ncyA9IG1hcHBpbmdzO1xuICB0aGlzLmZpbGUgPSBmaWxlO1xufVxuXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZSA9IE9iamVjdC5jcmVhdGUoU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlKTtcbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmNvbnN1bWVyID0gU291cmNlTWFwQ29uc3VtZXI7XG5cbi8qKlxuICogQ3JlYXRlIGEgQmFzaWNTb3VyY2VNYXBDb25zdW1lciBmcm9tIGEgU291cmNlTWFwR2VuZXJhdG9yLlxuICpcbiAqIEBwYXJhbSBTb3VyY2VNYXBHZW5lcmF0b3IgYVNvdXJjZU1hcFxuICogICAgICAgIFRoZSBzb3VyY2UgbWFwIHRoYXQgd2lsbCBiZSBjb25zdW1lZC5cbiAqIEByZXR1cm5zIEJhc2ljU291cmNlTWFwQ29uc3VtZXJcbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5mcm9tU291cmNlTWFwID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfZnJvbVNvdXJjZU1hcChhU291cmNlTWFwKSB7XG4gICAgdmFyIHNtYyA9IE9iamVjdC5jcmVhdGUoQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUpO1xuXG4gICAgdmFyIG5hbWVzID0gc21jLl9uYW1lcyA9IEFycmF5U2V0LmZyb21BcnJheShhU291cmNlTWFwLl9uYW1lcy50b0FycmF5KCksIHRydWUpO1xuICAgIHZhciBzb3VyY2VzID0gc21jLl9zb3VyY2VzID0gQXJyYXlTZXQuZnJvbUFycmF5KGFTb3VyY2VNYXAuX3NvdXJjZXMudG9BcnJheSgpLCB0cnVlKTtcbiAgICBzbWMuc291cmNlUm9vdCA9IGFTb3VyY2VNYXAuX3NvdXJjZVJvb3Q7XG4gICAgc21jLnNvdXJjZXNDb250ZW50ID0gYVNvdXJjZU1hcC5fZ2VuZXJhdGVTb3VyY2VzQ29udGVudChzbWMuX3NvdXJjZXMudG9BcnJheSgpLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc21jLnNvdXJjZVJvb3QpO1xuICAgIHNtYy5maWxlID0gYVNvdXJjZU1hcC5fZmlsZTtcblxuICAgIC8vIEJlY2F1c2Ugd2UgYXJlIG1vZGlmeWluZyB0aGUgZW50cmllcyAoYnkgY29udmVydGluZyBzdHJpbmcgc291cmNlcyBhbmRcbiAgICAvLyBuYW1lcyB0byBpbmRpY2VzIGludG8gdGhlIHNvdXJjZXMgYW5kIG5hbWVzIEFycmF5U2V0cyksIHdlIGhhdmUgdG8gbWFrZVxuICAgIC8vIGEgY29weSBvZiB0aGUgZW50cnkgb3IgZWxzZSBiYWQgdGhpbmdzIGhhcHBlbi4gU2hhcmVkIG11dGFibGUgc3RhdGVcbiAgICAvLyBzdHJpa2VzIGFnYWluISBTZWUgZ2l0aHViIGlzc3VlICMxOTEuXG5cbiAgICB2YXIgZ2VuZXJhdGVkTWFwcGluZ3MgPSBhU291cmNlTWFwLl9tYXBwaW5ncy50b0FycmF5KCkuc2xpY2UoKTtcbiAgICB2YXIgZGVzdEdlbmVyYXRlZE1hcHBpbmdzID0gc21jLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBbXTtcbiAgICB2YXIgZGVzdE9yaWdpbmFsTWFwcGluZ3MgPSBzbWMuX19vcmlnaW5hbE1hcHBpbmdzID0gW107XG5cbiAgICBmb3IgKHZhciBpID0gMCwgbGVuZ3RoID0gZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyBpIDwgbGVuZ3RoOyBpKyspIHtcbiAgICAgIHZhciBzcmNNYXBwaW5nID0gZ2VuZXJhdGVkTWFwcGluZ3NbaV07XG4gICAgICB2YXIgZGVzdE1hcHBpbmcgPSBuZXcgTWFwcGluZztcbiAgICAgIGRlc3RNYXBwaW5nLmdlbmVyYXRlZExpbmUgPSBzcmNNYXBwaW5nLmdlbmVyYXRlZExpbmU7XG4gICAgICBkZXN0TWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gPSBzcmNNYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgaWYgKHNyY01hcHBpbmcuc291cmNlKSB7XG4gICAgICAgIGRlc3RNYXBwaW5nLnNvdXJjZSA9IHNvdXJjZXMuaW5kZXhPZihzcmNNYXBwaW5nLnNvdXJjZSk7XG4gICAgICAgIGRlc3RNYXBwaW5nLm9yaWdpbmFsTGluZSA9IHNyY01hcHBpbmcub3JpZ2luYWxMaW5lO1xuICAgICAgICBkZXN0TWFwcGluZy5vcmlnaW5hbENvbHVtbiA9IHNyY01hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgaWYgKHNyY01hcHBpbmcubmFtZSkge1xuICAgICAgICAgIGRlc3RNYXBwaW5nLm5hbWUgPSBuYW1lcy5pbmRleE9mKHNyY01hcHBpbmcubmFtZSk7XG4gICAgICAgIH1cblxuICAgICAgICBkZXN0T3JpZ2luYWxNYXBwaW5ncy5wdXNoKGRlc3RNYXBwaW5nKTtcbiAgICAgIH1cblxuICAgICAgZGVzdEdlbmVyYXRlZE1hcHBpbmdzLnB1c2goZGVzdE1hcHBpbmcpO1xuICAgIH1cblxuICAgIHF1aWNrU29ydChzbWMuX19vcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcblxuICAgIHJldHVybiBzbWM7XG4gIH07XG5cbi8qKlxuICogVGhlIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXBwaW5nIHNwZWMgdGhhdCB3ZSBhcmUgY29uc3VtaW5nLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLCAnc291cmNlcycsIHtcbiAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgcmV0dXJuIHRoaXMuX3NvdXJjZXMudG9BcnJheSgpLm1hcChmdW5jdGlvbiAocykge1xuICAgICAgcmV0dXJuIHRoaXMuc291cmNlUm9vdCAhPSBudWxsID8gdXRpbC5qb2luKHRoaXMuc291cmNlUm9vdCwgcykgOiBzO1xuICAgIH0sIHRoaXMpO1xuICB9XG59KTtcblxuLyoqXG4gKiBQcm92aWRlIHRoZSBKSVQgd2l0aCBhIG5pY2Ugc2hhcGUgLyBoaWRkZW4gY2xhc3MuXG4gKi9cbmZ1bmN0aW9uIE1hcHBpbmcoKSB7XG4gIHRoaXMuZ2VuZXJhdGVkTGluZSA9IDA7XG4gIHRoaXMuZ2VuZXJhdGVkQ29sdW1uID0gMDtcbiAgdGhpcy5zb3VyY2UgPSBudWxsO1xuICB0aGlzLm9yaWdpbmFsTGluZSA9IG51bGw7XG4gIHRoaXMub3JpZ2luYWxDb2x1bW4gPSBudWxsO1xuICB0aGlzLm5hbWUgPSBudWxsO1xufVxuXG4vKipcbiAqIFBhcnNlIHRoZSBtYXBwaW5ncyBpbiBhIHN0cmluZyBpbiB0byBhIGRhdGEgc3RydWN0dXJlIHdoaWNoIHdlIGNhbiBlYXNpbHlcbiAqIHF1ZXJ5ICh0aGUgb3JkZXJlZCBhcnJheXMgaW4gdGhlIGB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3NgIGFuZFxuICogYHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzYCBwcm9wZXJ0aWVzKS5cbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9wYXJzZU1hcHBpbmdzKGFTdHIsIGFTb3VyY2VSb290KSB7XG4gICAgdmFyIGdlbmVyYXRlZExpbmUgPSAxO1xuICAgIHZhciBwcmV2aW91c0dlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gMDtcbiAgICB2YXIgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IDA7XG4gICAgdmFyIHByZXZpb3VzU291cmNlID0gMDtcbiAgICB2YXIgcHJldmlvdXNOYW1lID0gMDtcbiAgICB2YXIgbGVuZ3RoID0gYVN0ci5sZW5ndGg7XG4gICAgdmFyIGluZGV4ID0gMDtcbiAgICB2YXIgY2FjaGVkU2VnbWVudHMgPSB7fTtcbiAgICB2YXIgdGVtcCA9IHt9O1xuICAgIHZhciBvcmlnaW5hbE1hcHBpbmdzID0gW107XG4gICAgdmFyIGdlbmVyYXRlZE1hcHBpbmdzID0gW107XG4gICAgdmFyIG1hcHBpbmcsIHN0ciwgc2VnbWVudCwgZW5kLCB2YWx1ZTtcblxuICAgIHdoaWxlIChpbmRleCA8IGxlbmd0aCkge1xuICAgICAgaWYgKGFTdHIuY2hhckF0KGluZGV4KSA9PT0gJzsnKSB7XG4gICAgICAgIGdlbmVyYXRlZExpbmUrKztcbiAgICAgICAgaW5kZXgrKztcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSAwO1xuICAgICAgfVxuICAgICAgZWxzZSBpZiAoYVN0ci5jaGFyQXQoaW5kZXgpID09PSAnLCcpIHtcbiAgICAgICAgaW5kZXgrKztcbiAgICAgIH1cbiAgICAgIGVsc2Uge1xuICAgICAgICBtYXBwaW5nID0gbmV3IE1hcHBpbmcoKTtcbiAgICAgICAgbWFwcGluZy5nZW5lcmF0ZWRMaW5lID0gZ2VuZXJhdGVkTGluZTtcblxuICAgICAgICAvLyBCZWNhdXNlIGVhY2ggb2Zmc2V0IGlzIGVuY29kZWQgcmVsYXRpdmUgdG8gdGhlIHByZXZpb3VzIG9uZSxcbiAgICAgICAgLy8gbWFueSBzZWdtZW50cyBvZnRlbiBoYXZlIHRoZSBzYW1lIGVuY29kaW5nLiBXZSBjYW4gZXhwbG9pdCB0aGlzXG4gICAgICAgIC8vIGZhY3QgYnkgY2FjaGluZyB0aGUgcGFyc2VkIHZhcmlhYmxlIGxlbmd0aCBmaWVsZHMgb2YgZWFjaCBzZWdtZW50LFxuICAgICAgICAvLyBhbGxvd2luZyB1cyB0byBhdm9pZCBhIHNlY29uZCBwYXJzZSBpZiB3ZSBlbmNvdW50ZXIgdGhlIHNhbWVcbiAgICAgICAgLy8gc2VnbWVudCBhZ2Fpbi5cbiAgICAgICAgZm9yIChlbmQgPSBpbmRleDsgZW5kIDwgbGVuZ3RoOyBlbmQrKykge1xuICAgICAgICAgIGlmICh0aGlzLl9jaGFySXNNYXBwaW5nU2VwYXJhdG9yKGFTdHIsIGVuZCkpIHtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBzdHIgPSBhU3RyLnNsaWNlKGluZGV4LCBlbmQpO1xuXG4gICAgICAgIHNlZ21lbnQgPSBjYWNoZWRTZWdtZW50c1tzdHJdO1xuICAgICAgICBpZiAoc2VnbWVudCkge1xuICAgICAgICAgIGluZGV4ICs9IHN0ci5sZW5ndGg7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgc2VnbWVudCA9IFtdO1xuICAgICAgICAgIHdoaWxlIChpbmRleCA8IGVuZCkge1xuICAgICAgICAgICAgYmFzZTY0VkxRLmRlY29kZShhU3RyLCBpbmRleCwgdGVtcCk7XG4gICAgICAgICAgICB2YWx1ZSA9IHRlbXAudmFsdWU7XG4gICAgICAgICAgICBpbmRleCA9IHRlbXAucmVzdDtcbiAgICAgICAgICAgIHNlZ21lbnQucHVzaCh2YWx1ZSk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlLCBidXQgbm8gbGluZSBhbmQgY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHNlZ21lbnQubGVuZ3RoID09PSAzKSB7XG4gICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ0ZvdW5kIGEgc291cmNlIGFuZCBsaW5lLCBidXQgbm8gY29sdW1uJyk7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2FjaGVkU2VnbWVudHNbc3RyXSA9IHNlZ21lbnQ7XG4gICAgICAgIH1cblxuICAgICAgICAvLyBHZW5lcmF0ZWQgY29sdW1uLlxuICAgICAgICBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiA9IHByZXZpb3VzR2VuZXJhdGVkQ29sdW1uICsgc2VnbWVudFswXTtcbiAgICAgICAgcHJldmlvdXNHZW5lcmF0ZWRDb2x1bW4gPSBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbjtcblxuICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiAxKSB7XG4gICAgICAgICAgLy8gT3JpZ2luYWwgc291cmNlLlxuICAgICAgICAgIG1hcHBpbmcuc291cmNlID0gcHJldmlvdXNTb3VyY2UgKyBzZWdtZW50WzFdO1xuICAgICAgICAgIHByZXZpb3VzU291cmNlICs9IHNlZ21lbnRbMV07XG5cbiAgICAgICAgICAvLyBPcmlnaW5hbCBsaW5lLlxuICAgICAgICAgIG1hcHBpbmcub3JpZ2luYWxMaW5lID0gcHJldmlvdXNPcmlnaW5hbExpbmUgKyBzZWdtZW50WzJdO1xuICAgICAgICAgIHByZXZpb3VzT3JpZ2luYWxMaW5lID0gbWFwcGluZy5vcmlnaW5hbExpbmU7XG4gICAgICAgICAgLy8gTGluZXMgYXJlIHN0b3JlZCAwLWJhc2VkXG4gICAgICAgICAgbWFwcGluZy5vcmlnaW5hbExpbmUgKz0gMTtcblxuICAgICAgICAgIC8vIE9yaWdpbmFsIGNvbHVtbi5cbiAgICAgICAgICBtYXBwaW5nLm9yaWdpbmFsQ29sdW1uID0gcHJldmlvdXNPcmlnaW5hbENvbHVtbiArIHNlZ21lbnRbM107XG4gICAgICAgICAgcHJldmlvdXNPcmlnaW5hbENvbHVtbiA9IG1hcHBpbmcub3JpZ2luYWxDb2x1bW47XG5cbiAgICAgICAgICBpZiAoc2VnbWVudC5sZW5ndGggPiA0KSB7XG4gICAgICAgICAgICAvLyBPcmlnaW5hbCBuYW1lLlxuICAgICAgICAgICAgbWFwcGluZy5uYW1lID0gcHJldmlvdXNOYW1lICsgc2VnbWVudFs0XTtcbiAgICAgICAgICAgIHByZXZpb3VzTmFtZSArPSBzZWdtZW50WzRdO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuXG4gICAgICAgIGdlbmVyYXRlZE1hcHBpbmdzLnB1c2gobWFwcGluZyk7XG4gICAgICAgIGlmICh0eXBlb2YgbWFwcGluZy5vcmlnaW5hbExpbmUgPT09ICdudW1iZXInKSB7XG4gICAgICAgICAgb3JpZ2luYWxNYXBwaW5ncy5wdXNoKG1hcHBpbmcpO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuXG4gICAgcXVpY2tTb3J0KGdlbmVyYXRlZE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeUdlbmVyYXRlZFBvc2l0aW9uc0RlZmxhdGVkKTtcbiAgICB0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MgPSBnZW5lcmF0ZWRNYXBwaW5ncztcblxuICAgIHF1aWNrU29ydChvcmlnaW5hbE1hcHBpbmdzLCB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zKTtcbiAgICB0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncyA9IG9yaWdpbmFsTWFwcGluZ3M7XG4gIH07XG5cbi8qKlxuICogRmluZCB0aGUgbWFwcGluZyB0aGF0IGJlc3QgbWF0Y2hlcyB0aGUgaHlwb3RoZXRpY2FsIFwibmVlZGxlXCIgbWFwcGluZyB0aGF0XG4gKiB3ZSBhcmUgc2VhcmNoaW5nIGZvciBpbiB0aGUgZ2l2ZW4gXCJoYXlzdGFja1wiIG9mIG1hcHBpbmdzLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fZmluZE1hcHBpbmcgPVxuICBmdW5jdGlvbiBTb3VyY2VNYXBDb25zdW1lcl9maW5kTWFwcGluZyhhTmVlZGxlLCBhTWFwcGluZ3MsIGFMaW5lTmFtZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgYUNvbHVtbk5hbWUsIGFDb21wYXJhdG9yLCBhQmlhcykge1xuICAgIC8vIFRvIHJldHVybiB0aGUgcG9zaXRpb24gd2UgYXJlIHNlYXJjaGluZyBmb3IsIHdlIG11c3QgZmlyc3QgZmluZCB0aGVcbiAgICAvLyBtYXBwaW5nIGZvciB0aGUgZ2l2ZW4gcG9zaXRpb24gYW5kIHRoZW4gcmV0dXJuIHRoZSBvcHBvc2l0ZSBwb3NpdGlvbiBpdFxuICAgIC8vIHBvaW50cyB0by4gQmVjYXVzZSB0aGUgbWFwcGluZ3MgYXJlIHNvcnRlZCwgd2UgY2FuIHVzZSBiaW5hcnkgc2VhcmNoIHRvXG4gICAgLy8gZmluZCB0aGUgYmVzdCBtYXBwaW5nLlxuXG4gICAgaWYgKGFOZWVkbGVbYUxpbmVOYW1lXSA8PSAwKSB7XG4gICAgICB0aHJvdyBuZXcgVHlwZUVycm9yKCdMaW5lIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDEsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthTGluZU5hbWVdKTtcbiAgICB9XG4gICAgaWYgKGFOZWVkbGVbYUNvbHVtbk5hbWVdIDwgMCkge1xuICAgICAgdGhyb3cgbmV3IFR5cGVFcnJvcignQ29sdW1uIG11c3QgYmUgZ3JlYXRlciB0aGFuIG9yIGVxdWFsIHRvIDAsIGdvdCAnXG4gICAgICAgICAgICAgICAgICAgICAgICAgICsgYU5lZWRsZVthQ29sdW1uTmFtZV0pO1xuICAgIH1cblxuICAgIHJldHVybiBiaW5hcnlTZWFyY2guc2VhcmNoKGFOZWVkbGUsIGFNYXBwaW5ncywgYUNvbXBhcmF0b3IsIGFCaWFzKTtcbiAgfTtcblxuLyoqXG4gKiBDb21wdXRlIHRoZSBsYXN0IGNvbHVtbiBmb3IgZWFjaCBnZW5lcmF0ZWQgbWFwcGluZy4gVGhlIGxhc3QgY29sdW1uIGlzXG4gKiBpbmNsdXNpdmUuXG4gKi9cbkJhc2ljU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmNvbXB1dGVDb2x1bW5TcGFucyA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2NvbXB1dGVDb2x1bW5TcGFucygpIHtcbiAgICBmb3IgKHZhciBpbmRleCA9IDA7IGluZGV4IDwgdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3MubGVuZ3RoOyArK2luZGV4KSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzW2luZGV4XTtcblxuICAgICAgLy8gTWFwcGluZ3MgZG8gbm90IGNvbnRhaW4gYSBmaWVsZCBmb3IgdGhlIGxhc3QgZ2VuZXJhdGVkIGNvbHVtbnQuIFdlXG4gICAgICAvLyBjYW4gY29tZSB1cCB3aXRoIGFuIG9wdGltaXN0aWMgZXN0aW1hdGUsIGhvd2V2ZXIsIGJ5IGFzc3VtaW5nIHRoYXRcbiAgICAgIC8vIG1hcHBpbmdzIGFyZSBjb250aWd1b3VzIChpLmUuIGdpdmVuIHR3byBjb25zZWN1dGl2ZSBtYXBwaW5ncywgdGhlXG4gICAgICAvLyBmaXJzdCBtYXBwaW5nIGVuZHMgd2hlcmUgdGhlIHNlY29uZCBvbmUgc3RhcnRzKS5cbiAgICAgIGlmIChpbmRleCArIDEgPCB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5ncy5sZW5ndGgpIHtcbiAgICAgICAgdmFyIG5leHRNYXBwaW5nID0gdGhpcy5fZ2VuZXJhdGVkTWFwcGluZ3NbaW5kZXggKyAxXTtcblxuICAgICAgICBpZiAobWFwcGluZy5nZW5lcmF0ZWRMaW5lID09PSBuZXh0TWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gbmV4dE1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC0gMTtcbiAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICAvLyBUaGUgbGFzdCBtYXBwaW5nIGZvciBlYWNoIGxpbmUgc3BhbnMgdGhlIGVudGlyZSBsaW5lLlxuICAgICAgbWFwcGluZy5sYXN0R2VuZXJhdGVkQ29sdW1uID0gSW5maW5pdHk7XG4gICAgfVxuICB9O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIG9yaWdpbmFsIHNvdXJjZSwgbGluZSwgYW5kIGNvbHVtbiBpbmZvcm1hdGlvbiBmb3IgdGhlIGdlbmVyYXRlZFxuICogc291cmNlJ3MgbGluZSBhbmQgY29sdW1uIHBvc2l0aW9ucyBwcm92aWRlZC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgYW4gb2JqZWN0XG4gKiB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLlxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIGdlbmVyYXRlZCBzb3VyY2UuXG4gKiAgIC0gYmlhczogRWl0aGVyICdTb3VyY2VNYXBDb25zdW1lci5HUkVBVEVTVF9MT1dFUl9CT1VORCcgb3JcbiAqICAgICAnU291cmNlTWFwQ29uc3VtZXIuTEVBU1RfVVBQRVJfQk9VTkQnLiBTcGVjaWZpZXMgd2hldGhlciB0byByZXR1cm4gdGhlXG4gKiAgICAgY2xvc2VzdCBlbGVtZW50IHRoYXQgaXMgc21hbGxlciB0aGFuIG9yIGdyZWF0ZXIgdGhhbiB0aGUgb25lIHdlIGFyZVxuICogICAgIHNlYXJjaGluZyBmb3IsIHJlc3BlY3RpdmVseSwgaWYgdGhlIGV4YWN0IGVsZW1lbnQgY2Fubm90IGJlIGZvdW5kLlxuICogICAgIERlZmF1bHRzIHRvICdTb3VyY2VNYXBDb25zdW1lci5HUkVBVEVTVF9MT1dFUl9CT1VORCcuXG4gKlxuICogYW5kIGFuIG9iamVjdCBpcyByZXR1cm5lZCB3aXRoIHRoZSBmb2xsb3dpbmcgcHJvcGVydGllczpcbiAqXG4gKiAgIC0gc291cmNlOiBUaGUgb3JpZ2luYWwgc291cmNlIGZpbGUsIG9yIG51bGwuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UsIG9yIG51bGwuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLlxuICogICAtIG5hbWU6IFRoZSBvcmlnaW5hbCBpZGVudGlmaWVyLCBvciBudWxsLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5vcmlnaW5hbFBvc2l0aW9uRm9yID1cbiAgZnVuY3Rpb24gU291cmNlTWFwQ29uc3VtZXJfb3JpZ2luYWxQb3NpdGlvbkZvcihhQXJncykge1xuICAgIHZhciBuZWVkbGUgPSB7XG4gICAgICBnZW5lcmF0ZWRMaW5lOiB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKSxcbiAgICAgIGdlbmVyYXRlZENvbHVtbjogdXRpbC5nZXRBcmcoYUFyZ3MsICdjb2x1bW4nKVxuICAgIH07XG5cbiAgICB2YXIgaW5kZXggPSB0aGlzLl9maW5kTWFwcGluZyhcbiAgICAgIG5lZWRsZSxcbiAgICAgIHRoaXMuX2dlbmVyYXRlZE1hcHBpbmdzLFxuICAgICAgXCJnZW5lcmF0ZWRMaW5lXCIsXG4gICAgICBcImdlbmVyYXRlZENvbHVtblwiLFxuICAgICAgdXRpbC5jb21wYXJlQnlHZW5lcmF0ZWRQb3NpdGlvbnNEZWZsYXRlZCxcbiAgICAgIHV0aWwuZ2V0QXJnKGFBcmdzLCAnYmlhcycsIFNvdXJjZU1hcENvbnN1bWVyLkdSRUFURVNUX0xPV0VSX0JPVU5EKVxuICAgICk7XG5cbiAgICBpZiAoaW5kZXggPj0gMCkge1xuICAgICAgdmFyIG1hcHBpbmcgPSB0aGlzLl9nZW5lcmF0ZWRNYXBwaW5nc1tpbmRleF07XG5cbiAgICAgIGlmIChtYXBwaW5nLmdlbmVyYXRlZExpbmUgPT09IG5lZWRsZS5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgIHZhciBzb3VyY2UgPSB1dGlsLmdldEFyZyhtYXBwaW5nLCAnc291cmNlJywgbnVsbCk7XG4gICAgICAgIGlmIChzb3VyY2UgIT09IG51bGwpIHtcbiAgICAgICAgICBzb3VyY2UgPSB0aGlzLl9zb3VyY2VzLmF0KHNvdXJjZSk7XG4gICAgICAgICAgaWYgKHRoaXMuc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICAgICAgICBzb3VyY2UgPSB1dGlsLmpvaW4odGhpcy5zb3VyY2VSb290LCBzb3VyY2UpO1xuICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB2YXIgbmFtZSA9IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICduYW1lJywgbnVsbCk7XG4gICAgICAgIGlmIChuYW1lICE9PSBudWxsKSB7XG4gICAgICAgICAgbmFtZSA9IHRoaXMuX25hbWVzLmF0KG5hbWUpO1xuICAgICAgICB9XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICAgICAgbGluZTogdXRpbC5nZXRBcmcobWFwcGluZywgJ29yaWdpbmFsTGluZScsIG51bGwpLFxuICAgICAgICAgIGNvbHVtbjogdXRpbC5nZXRBcmcobWFwcGluZywgJ29yaWdpbmFsQ29sdW1uJywgbnVsbCksXG4gICAgICAgICAgbmFtZTogbmFtZVxuICAgICAgICB9O1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB7XG4gICAgICBzb3VyY2U6IG51bGwsXG4gICAgICBsaW5lOiBudWxsLFxuICAgICAgY29sdW1uOiBudWxsLFxuICAgICAgbmFtZTogbnVsbFxuICAgIH07XG4gIH07XG5cbi8qKlxuICogUmV0dXJuIHRydWUgaWYgd2UgaGF2ZSB0aGUgc291cmNlIGNvbnRlbnQgZm9yIGV2ZXJ5IHNvdXJjZSBpbiB0aGUgc291cmNlXG4gKiBtYXAsIGZhbHNlIG90aGVyd2lzZS5cbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuaGFzQ29udGVudHNPZkFsbFNvdXJjZXMgPVxuICBmdW5jdGlvbiBCYXNpY1NvdXJjZU1hcENvbnN1bWVyX2hhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzKCkge1xuICAgIGlmICghdGhpcy5zb3VyY2VzQ29udGVudCkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgICByZXR1cm4gdGhpcy5zb3VyY2VzQ29udGVudC5sZW5ndGggPj0gdGhpcy5fc291cmNlcy5zaXplKCkgJiZcbiAgICAgICF0aGlzLnNvdXJjZXNDb250ZW50LnNvbWUoZnVuY3Rpb24gKHNjKSB7IHJldHVybiBzYyA9PSBudWxsOyB9KTtcbiAgfTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UgY29udGVudC4gVGhlIG9ubHkgYXJndW1lbnQgaXMgdGhlIHVybCBvZiB0aGVcbiAqIG9yaWdpbmFsIHNvdXJjZSBmaWxlLiBSZXR1cm5zIG51bGwgaWYgbm8gb3JpZ2luYWwgc291cmNlIGNvbnRlbnQgaXNcbiAqIGF2YWlsYWJsZS5cbiAqL1xuQmFzaWNTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuc291cmNlQ29udGVudEZvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX3NvdXJjZUNvbnRlbnRGb3IoYVNvdXJjZSwgbnVsbE9uTWlzc2luZykge1xuICAgIGlmICghdGhpcy5zb3VyY2VzQ29udGVudCkge1xuICAgICAgcmV0dXJuIG51bGw7XG4gICAgfVxuXG4gICAgaWYgKHRoaXMuc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICBhU291cmNlID0gdXRpbC5yZWxhdGl2ZSh0aGlzLnNvdXJjZVJvb3QsIGFTb3VyY2UpO1xuICAgIH1cblxuICAgIGlmICh0aGlzLl9zb3VyY2VzLmhhcyhhU291cmNlKSkge1xuICAgICAgcmV0dXJuIHRoaXMuc291cmNlc0NvbnRlbnRbdGhpcy5fc291cmNlcy5pbmRleE9mKGFTb3VyY2UpXTtcbiAgICB9XG5cbiAgICB2YXIgdXJsO1xuICAgIGlmICh0aGlzLnNvdXJjZVJvb3QgIT0gbnVsbFxuICAgICAgICAmJiAodXJsID0gdXRpbC51cmxQYXJzZSh0aGlzLnNvdXJjZVJvb3QpKSkge1xuICAgICAgLy8gWFhYOiBmaWxlOi8vIFVSSXMgYW5kIGFic29sdXRlIHBhdGhzIGxlYWQgdG8gdW5leHBlY3RlZCBiZWhhdmlvciBmb3JcbiAgICAgIC8vIG1hbnkgdXNlcnMuIFdlIGNhbiBoZWxwIHRoZW0gb3V0IHdoZW4gdGhleSBleHBlY3QgZmlsZTovLyBVUklzIHRvXG4gICAgICAvLyBiZWhhdmUgbGlrZSBpdCB3b3VsZCBpZiB0aGV5IHdlcmUgcnVubmluZyBhIGxvY2FsIEhUVFAgc2VydmVyLiBTZWVcbiAgICAgIC8vIGh0dHBzOi8vYnVnemlsbGEubW96aWxsYS5vcmcvc2hvd19idWcuY2dpP2lkPTg4NTU5Ny5cbiAgICAgIHZhciBmaWxlVXJpQWJzUGF0aCA9IGFTb3VyY2UucmVwbGFjZSgvXmZpbGU6XFwvXFwvLywgXCJcIik7XG4gICAgICBpZiAodXJsLnNjaGVtZSA9PSBcImZpbGVcIlxuICAgICAgICAgICYmIHRoaXMuX3NvdXJjZXMuaGFzKGZpbGVVcmlBYnNQYXRoKSkge1xuICAgICAgICByZXR1cm4gdGhpcy5zb3VyY2VzQ29udGVudFt0aGlzLl9zb3VyY2VzLmluZGV4T2YoZmlsZVVyaUFic1BhdGgpXVxuICAgICAgfVxuXG4gICAgICBpZiAoKCF1cmwucGF0aCB8fCB1cmwucGF0aCA9PSBcIi9cIilcbiAgICAgICAgICAmJiB0aGlzLl9zb3VyY2VzLmhhcyhcIi9cIiArIGFTb3VyY2UpKSB7XG4gICAgICAgIHJldHVybiB0aGlzLnNvdXJjZXNDb250ZW50W3RoaXMuX3NvdXJjZXMuaW5kZXhPZihcIi9cIiArIGFTb3VyY2UpXTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICAvLyBUaGlzIGZ1bmN0aW9uIGlzIHVzZWQgcmVjdXJzaXZlbHkgZnJvbVxuICAgIC8vIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuc291cmNlQ29udGVudEZvci4gSW4gdGhhdCBjYXNlLCB3ZVxuICAgIC8vIGRvbid0IHdhbnQgdG8gdGhyb3cgaWYgd2UgY2FuJ3QgZmluZCB0aGUgc291cmNlIC0gd2UganVzdCB3YW50IHRvXG4gICAgLy8gcmV0dXJuIG51bGwsIHNvIHdlIHByb3ZpZGUgYSBmbGFnIHRvIGV4aXQgZ3JhY2VmdWxseS5cbiAgICBpZiAobnVsbE9uTWlzc2luZykge1xuICAgICAgcmV0dXJuIG51bGw7XG4gICAgfVxuICAgIGVsc2Uge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKCdcIicgKyBhU291cmNlICsgJ1wiIGlzIG5vdCBpbiB0aGUgU291cmNlTWFwLicpO1xuICAgIH1cbiAgfTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uIGluZm9ybWF0aW9uIGZvciB0aGUgb3JpZ2luYWwgc291cmNlLFxuICogbGluZSwgYW5kIGNvbHVtbiBwb3NpdGlvbnMgcHJvdmlkZWQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIGFuIG9iamVjdCB3aXRoXG4gKiB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIGZpbGVuYW1lIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLlxuICogICAtIGJpYXM6IEVpdGhlciAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnIG9yXG4gKiAgICAgJ1NvdXJjZU1hcENvbnN1bWVyLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQnLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLCBvciBudWxsLlxuICovXG5CYXNpY1NvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5nZW5lcmF0ZWRQb3NpdGlvbkZvciA9XG4gIGZ1bmN0aW9uIFNvdXJjZU1hcENvbnN1bWVyX2dlbmVyYXRlZFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgdmFyIHNvdXJjZSA9IHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJyk7XG4gICAgaWYgKHRoaXMuc291cmNlUm9vdCAhPSBudWxsKSB7XG4gICAgICBzb3VyY2UgPSB1dGlsLnJlbGF0aXZlKHRoaXMuc291cmNlUm9vdCwgc291cmNlKTtcbiAgICB9XG4gICAgaWYgKCF0aGlzLl9zb3VyY2VzLmhhcyhzb3VyY2UpKSB7XG4gICAgICByZXR1cm4ge1xuICAgICAgICBsaW5lOiBudWxsLFxuICAgICAgICBjb2x1bW46IG51bGwsXG4gICAgICAgIGxhc3RDb2x1bW46IG51bGxcbiAgICAgIH07XG4gICAgfVxuICAgIHNvdXJjZSA9IHRoaXMuX3NvdXJjZXMuaW5kZXhPZihzb3VyY2UpO1xuXG4gICAgdmFyIG5lZWRsZSA9IHtcbiAgICAgIHNvdXJjZTogc291cmNlLFxuICAgICAgb3JpZ2luYWxMaW5lOiB1dGlsLmdldEFyZyhhQXJncywgJ2xpbmUnKSxcbiAgICAgIG9yaWdpbmFsQ29sdW1uOiB1dGlsLmdldEFyZyhhQXJncywgJ2NvbHVtbicpXG4gICAgfTtcblxuICAgIHZhciBpbmRleCA9IHRoaXMuX2ZpbmRNYXBwaW5nKFxuICAgICAgbmVlZGxlLFxuICAgICAgdGhpcy5fb3JpZ2luYWxNYXBwaW5ncyxcbiAgICAgIFwib3JpZ2luYWxMaW5lXCIsXG4gICAgICBcIm9yaWdpbmFsQ29sdW1uXCIsXG4gICAgICB1dGlsLmNvbXBhcmVCeU9yaWdpbmFsUG9zaXRpb25zLFxuICAgICAgdXRpbC5nZXRBcmcoYUFyZ3MsICdiaWFzJywgU291cmNlTWFwQ29uc3VtZXIuR1JFQVRFU1RfTE9XRVJfQk9VTkQpXG4gICAgKTtcblxuICAgIGlmIChpbmRleCA+PSAwKSB7XG4gICAgICB2YXIgbWFwcGluZyA9IHRoaXMuX29yaWdpbmFsTWFwcGluZ3NbaW5kZXhdO1xuXG4gICAgICBpZiAobWFwcGluZy5zb3VyY2UgPT09IG5lZWRsZS5zb3VyY2UpIHtcbiAgICAgICAgcmV0dXJuIHtcbiAgICAgICAgICBsaW5lOiB1dGlsLmdldEFyZyhtYXBwaW5nLCAnZ2VuZXJhdGVkTGluZScsIG51bGwpLFxuICAgICAgICAgIGNvbHVtbjogdXRpbC5nZXRBcmcobWFwcGluZywgJ2dlbmVyYXRlZENvbHVtbicsIG51bGwpLFxuICAgICAgICAgIGxhc3RDb2x1bW46IHV0aWwuZ2V0QXJnKG1hcHBpbmcsICdsYXN0R2VuZXJhdGVkQ29sdW1uJywgbnVsbClcbiAgICAgICAgfTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4ge1xuICAgICAgbGluZTogbnVsbCxcbiAgICAgIGNvbHVtbjogbnVsbCxcbiAgICAgIGxhc3RDb2x1bW46IG51bGxcbiAgICB9O1xuICB9O1xuXG5leHBvcnRzLkJhc2ljU291cmNlTWFwQ29uc3VtZXIgPSBCYXNpY1NvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIEFuIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lciBpbnN0YW5jZSByZXByZXNlbnRzIGEgcGFyc2VkIHNvdXJjZSBtYXAgd2hpY2hcbiAqIHdlIGNhbiBxdWVyeSBmb3IgaW5mb3JtYXRpb24uIEl0IGRpZmZlcnMgZnJvbSBCYXNpY1NvdXJjZU1hcENvbnN1bWVyIGluXG4gKiB0aGF0IGl0IHRha2VzIFwiaW5kZXhlZFwiIHNvdXJjZSBtYXBzIChpLmUuIG9uZXMgd2l0aCBhIFwic2VjdGlvbnNcIiBmaWVsZCkgYXNcbiAqIGlucHV0LlxuICpcbiAqIFRoZSBvbmx5IHBhcmFtZXRlciBpcyBhIHJhdyBzb3VyY2UgbWFwIChlaXRoZXIgYXMgYSBKU09OIHN0cmluZywgb3IgYWxyZWFkeVxuICogcGFyc2VkIHRvIGFuIG9iamVjdCkuIEFjY29yZGluZyB0byB0aGUgc3BlYyBmb3IgaW5kZXhlZCBzb3VyY2UgbWFwcywgdGhleVxuICogaGF2ZSB0aGUgZm9sbG93aW5nIGF0dHJpYnV0ZXM6XG4gKlxuICogICAtIHZlcnNpb246IFdoaWNoIHZlcnNpb24gb2YgdGhlIHNvdXJjZSBtYXAgc3BlYyB0aGlzIG1hcCBpcyBmb2xsb3dpbmcuXG4gKiAgIC0gZmlsZTogT3B0aW9uYWwuIFRoZSBnZW5lcmF0ZWQgZmlsZSB0aGlzIHNvdXJjZSBtYXAgaXMgYXNzb2NpYXRlZCB3aXRoLlxuICogICAtIHNlY3Rpb25zOiBBIGxpc3Qgb2Ygc2VjdGlvbiBkZWZpbml0aW9ucy5cbiAqXG4gKiBFYWNoIHZhbHVlIHVuZGVyIHRoZSBcInNlY3Rpb25zXCIgZmllbGQgaGFzIHR3byBmaWVsZHM6XG4gKiAgIC0gb2Zmc2V0OiBUaGUgb2Zmc2V0IGludG8gdGhlIG9yaWdpbmFsIHNwZWNpZmllZCBhdCB3aGljaCB0aGlzIHNlY3Rpb25cbiAqICAgICAgIGJlZ2lucyB0byBhcHBseSwgZGVmaW5lZCBhcyBhbiBvYmplY3Qgd2l0aCBhIFwibGluZVwiIGFuZCBcImNvbHVtblwiXG4gKiAgICAgICBmaWVsZC5cbiAqICAgLSBtYXA6IEEgc291cmNlIG1hcCBkZWZpbml0aW9uLiBUaGlzIHNvdXJjZSBtYXAgY291bGQgYWxzbyBiZSBpbmRleGVkLFxuICogICAgICAgYnV0IGRvZXNuJ3QgaGF2ZSB0byBiZS5cbiAqXG4gKiBJbnN0ZWFkIG9mIHRoZSBcIm1hcFwiIGZpZWxkLCBpdCdzIGFsc28gcG9zc2libGUgdG8gaGF2ZSBhIFwidXJsXCIgZmllbGRcbiAqIHNwZWNpZnlpbmcgYSBVUkwgdG8gcmV0cmlldmUgYSBzb3VyY2UgbWFwIGZyb20sIGJ1dCB0aGF0J3MgY3VycmVudGx5XG4gKiB1bnN1cHBvcnRlZC5cbiAqXG4gKiBIZXJlJ3MgYW4gZXhhbXBsZSBzb3VyY2UgbWFwLCB0YWtlbiBmcm9tIHRoZSBzb3VyY2UgbWFwIHNwZWNbMF0sIGJ1dFxuICogbW9kaWZpZWQgdG8gb21pdCBhIHNlY3Rpb24gd2hpY2ggdXNlcyB0aGUgXCJ1cmxcIiBmaWVsZC5cbiAqXG4gKiAge1xuICogICAgdmVyc2lvbiA6IDMsXG4gKiAgICBmaWxlOiBcImFwcC5qc1wiLFxuICogICAgc2VjdGlvbnM6IFt7XG4gKiAgICAgIG9mZnNldDoge2xpbmU6MTAwLCBjb2x1bW46MTB9LFxuICogICAgICBtYXA6IHtcbiAqICAgICAgICB2ZXJzaW9uIDogMyxcbiAqICAgICAgICBmaWxlOiBcInNlY3Rpb24uanNcIixcbiAqICAgICAgICBzb3VyY2VzOiBbXCJmb28uanNcIiwgXCJiYXIuanNcIl0sXG4gKiAgICAgICAgbmFtZXM6IFtcInNyY1wiLCBcIm1hcHNcIiwgXCJhcmVcIiwgXCJmdW5cIl0sXG4gKiAgICAgICAgbWFwcGluZ3M6IFwiQUFBQSxFOztBQkNERTtcIlxuICogICAgICB9XG4gKiAgICB9XSxcbiAqICB9XG4gKlxuICogWzBdOiBodHRwczovL2RvY3MuZ29vZ2xlLmNvbS9kb2N1bWVudC9kLzFVMVJHQWVoUXdSeXBVVG92RjFLUmxwaU9GemUwYi1fMmdjNmZBSDBLWTBrL2VkaXQjaGVhZGluZz1oLjUzNWVzM3hlcHJndFxuICovXG5mdW5jdGlvbiBJbmRleGVkU291cmNlTWFwQ29uc3VtZXIoYVNvdXJjZU1hcCkge1xuICB2YXIgc291cmNlTWFwID0gYVNvdXJjZU1hcDtcbiAgaWYgKHR5cGVvZiBhU291cmNlTWFwID09PSAnc3RyaW5nJykge1xuICAgIHNvdXJjZU1hcCA9IEpTT04ucGFyc2UoYVNvdXJjZU1hcC5yZXBsYWNlKC9eXFwpXFxdXFx9Jy8sICcnKSk7XG4gIH1cblxuICB2YXIgdmVyc2lvbiA9IHV0aWwuZ2V0QXJnKHNvdXJjZU1hcCwgJ3ZlcnNpb24nKTtcbiAgdmFyIHNlY3Rpb25zID0gdXRpbC5nZXRBcmcoc291cmNlTWFwLCAnc2VjdGlvbnMnKTtcblxuICBpZiAodmVyc2lvbiAhPSB0aGlzLl92ZXJzaW9uKSB7XG4gICAgdGhyb3cgbmV3IEVycm9yKCdVbnN1cHBvcnRlZCB2ZXJzaW9uOiAnICsgdmVyc2lvbik7XG4gIH1cblxuICB0aGlzLl9zb3VyY2VzID0gbmV3IEFycmF5U2V0KCk7XG4gIHRoaXMuX25hbWVzID0gbmV3IEFycmF5U2V0KCk7XG5cbiAgdmFyIGxhc3RPZmZzZXQgPSB7XG4gICAgbGluZTogLTEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHRoaXMuX3NlY3Rpb25zID0gc2VjdGlvbnMubWFwKGZ1bmN0aW9uIChzKSB7XG4gICAgaWYgKHMudXJsKSB7XG4gICAgICAvLyBUaGUgdXJsIGZpZWxkIHdpbGwgcmVxdWlyZSBzdXBwb3J0IGZvciBhc3luY2hyb25pY2l0eS5cbiAgICAgIC8vIFNlZSBodHRwczovL2dpdGh1Yi5jb20vbW96aWxsYS9zb3VyY2UtbWFwL2lzc3Vlcy8xNlxuICAgICAgdGhyb3cgbmV3IEVycm9yKCdTdXBwb3J0IGZvciB1cmwgZmllbGQgaW4gc2VjdGlvbnMgbm90IGltcGxlbWVudGVkLicpO1xuICAgIH1cbiAgICB2YXIgb2Zmc2V0ID0gdXRpbC5nZXRBcmcocywgJ29mZnNldCcpO1xuICAgIHZhciBvZmZzZXRMaW5lID0gdXRpbC5nZXRBcmcob2Zmc2V0LCAnbGluZScpO1xuICAgIHZhciBvZmZzZXRDb2x1bW4gPSB1dGlsLmdldEFyZyhvZmZzZXQsICdjb2x1bW4nKTtcblxuICAgIGlmIChvZmZzZXRMaW5lIDwgbGFzdE9mZnNldC5saW5lIHx8XG4gICAgICAgIChvZmZzZXRMaW5lID09PSBsYXN0T2Zmc2V0LmxpbmUgJiYgb2Zmc2V0Q29sdW1uIDwgbGFzdE9mZnNldC5jb2x1bW4pKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoJ1NlY3Rpb24gb2Zmc2V0cyBtdXN0IGJlIG9yZGVyZWQgYW5kIG5vbi1vdmVybGFwcGluZy4nKTtcbiAgICB9XG4gICAgbGFzdE9mZnNldCA9IG9mZnNldDtcblxuICAgIHJldHVybiB7XG4gICAgICBnZW5lcmF0ZWRPZmZzZXQ6IHtcbiAgICAgICAgLy8gVGhlIG9mZnNldCBmaWVsZHMgYXJlIDAtYmFzZWQsIGJ1dCB3ZSB1c2UgMS1iYXNlZCBpbmRpY2VzIHdoZW5cbiAgICAgICAgLy8gZW5jb2RpbmcvZGVjb2RpbmcgZnJvbSBWTFEuXG4gICAgICAgIGdlbmVyYXRlZExpbmU6IG9mZnNldExpbmUgKyAxLFxuICAgICAgICBnZW5lcmF0ZWRDb2x1bW46IG9mZnNldENvbHVtbiArIDFcbiAgICAgIH0sXG4gICAgICBjb25zdW1lcjogbmV3IFNvdXJjZU1hcENvbnN1bWVyKHV0aWwuZ2V0QXJnKHMsICdtYXAnKSlcbiAgICB9XG4gIH0pO1xufVxuXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlID0gT2JqZWN0LmNyZWF0ZShTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUpO1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5jb25zdHJ1Y3RvciA9IFNvdXJjZU1hcENvbnN1bWVyO1xuXG4vKipcbiAqIFRoZSB2ZXJzaW9uIG9mIHRoZSBzb3VyY2UgbWFwcGluZyBzcGVjIHRoYXQgd2UgYXJlIGNvbnN1bWluZy5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5fdmVyc2lvbiA9IDM7XG5cbi8qKlxuICogVGhlIGxpc3Qgb2Ygb3JpZ2luYWwgc291cmNlcy5cbiAqL1xuT2JqZWN0LmRlZmluZVByb3BlcnR5KEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUsICdzb3VyY2VzJywge1xuICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICB2YXIgc291cmNlcyA9IFtdO1xuICAgIGZvciAodmFyIGkgPSAwOyBpIDwgdGhpcy5fc2VjdGlvbnMubGVuZ3RoOyBpKyspIHtcbiAgICAgIGZvciAodmFyIGogPSAwOyBqIDwgdGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlcy5sZW5ndGg7IGorKykge1xuICAgICAgICBzb3VyY2VzLnB1c2godGhpcy5fc2VjdGlvbnNbaV0uY29uc3VtZXIuc291cmNlc1tqXSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiBzb3VyY2VzO1xuICB9XG59KTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBvcmlnaW5hbCBzb3VyY2UsIGxpbmUsIGFuZCBjb2x1bW4gaW5mb3JtYXRpb24gZm9yIHRoZSBnZW5lcmF0ZWRcbiAqIHNvdXJjZSdzIGxpbmUgYW5kIGNvbHVtbiBwb3NpdGlvbnMgcHJvdmlkZWQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIGFuIG9iamVjdFxuICogd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZS5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIG9yaWdpbmFsIHNvdXJjZSBmaWxlLCBvciBudWxsLlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLCBvciBudWxsLlxuICogICAtIGNvbHVtbjogVGhlIGNvbHVtbiBudW1iZXIgaW4gdGhlIG9yaWdpbmFsIHNvdXJjZSwgb3IgbnVsbC5cbiAqICAgLSBuYW1lOiBUaGUgb3JpZ2luYWwgaWRlbnRpZmllciwgb3IgbnVsbC5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5vcmlnaW5hbFBvc2l0aW9uRm9yID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX29yaWdpbmFsUG9zaXRpb25Gb3IoYUFyZ3MpIHtcbiAgICB2YXIgbmVlZGxlID0ge1xuICAgICAgZ2VuZXJhdGVkTGluZTogdXRpbC5nZXRBcmcoYUFyZ3MsICdsaW5lJyksXG4gICAgICBnZW5lcmF0ZWRDb2x1bW46IHV0aWwuZ2V0QXJnKGFBcmdzLCAnY29sdW1uJylcbiAgICB9O1xuXG4gICAgLy8gRmluZCB0aGUgc2VjdGlvbiBjb250YWluaW5nIHRoZSBnZW5lcmF0ZWQgcG9zaXRpb24gd2UncmUgdHJ5aW5nIHRvIG1hcFxuICAgIC8vIHRvIGFuIG9yaWdpbmFsIHBvc2l0aW9uLlxuICAgIHZhciBzZWN0aW9uSW5kZXggPSBiaW5hcnlTZWFyY2guc2VhcmNoKG5lZWRsZSwgdGhpcy5fc2VjdGlvbnMsXG4gICAgICBmdW5jdGlvbihuZWVkbGUsIHNlY3Rpb24pIHtcbiAgICAgICAgdmFyIGNtcCA9IG5lZWRsZS5nZW5lcmF0ZWRMaW5lIC0gc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZTtcbiAgICAgICAgaWYgKGNtcCkge1xuICAgICAgICAgIHJldHVybiBjbXA7XG4gICAgICAgIH1cblxuICAgICAgICByZXR1cm4gKG5lZWRsZS5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAgICAgICAgIHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbik7XG4gICAgICB9KTtcbiAgICB2YXIgc2VjdGlvbiA9IHRoaXMuX3NlY3Rpb25zW3NlY3Rpb25JbmRleF07XG5cbiAgICBpZiAoIXNlY3Rpb24pIHtcbiAgICAgIHJldHVybiB7XG4gICAgICAgIHNvdXJjZTogbnVsbCxcbiAgICAgICAgbGluZTogbnVsbCxcbiAgICAgICAgY29sdW1uOiBudWxsLFxuICAgICAgICBuYW1lOiBudWxsXG4gICAgICB9O1xuICAgIH1cblxuICAgIHJldHVybiBzZWN0aW9uLmNvbnN1bWVyLm9yaWdpbmFsUG9zaXRpb25Gb3Ioe1xuICAgICAgbGluZTogbmVlZGxlLmdlbmVyYXRlZExpbmUgLVxuICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSAtIDEpLFxuICAgICAgY29sdW1uOiBuZWVkbGUuZ2VuZXJhdGVkQ29sdW1uIC1cbiAgICAgICAgKHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZExpbmUgPT09IG5lZWRsZS5nZW5lcmF0ZWRMaW5lXG4gICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgIDogMCksXG4gICAgICBiaWFzOiBhQXJncy5iaWFzXG4gICAgfSk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJuIHRydWUgaWYgd2UgaGF2ZSB0aGUgc291cmNlIGNvbnRlbnQgZm9yIGV2ZXJ5IHNvdXJjZSBpbiB0aGUgc291cmNlXG4gKiBtYXAsIGZhbHNlIG90aGVyd2lzZS5cbiAqL1xuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyLnByb3RvdHlwZS5oYXNDb250ZW50c09mQWxsU291cmNlcyA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9oYXNDb250ZW50c09mQWxsU291cmNlcygpIHtcbiAgICByZXR1cm4gdGhpcy5fc2VjdGlvbnMuZXZlcnkoZnVuY3Rpb24gKHMpIHtcbiAgICAgIHJldHVybiBzLmNvbnN1bWVyLmhhc0NvbnRlbnRzT2ZBbGxTb3VyY2VzKCk7XG4gICAgfSk7XG4gIH07XG5cbi8qKlxuICogUmV0dXJucyB0aGUgb3JpZ2luYWwgc291cmNlIGNvbnRlbnQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIHRoZSB1cmwgb2YgdGhlXG4gKiBvcmlnaW5hbCBzb3VyY2UgZmlsZS4gUmV0dXJucyBudWxsIGlmIG5vIG9yaWdpbmFsIHNvdXJjZSBjb250ZW50IGlzXG4gKiBhdmFpbGFibGUuXG4gKi9cbkluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuc291cmNlQ29udGVudEZvciA9XG4gIGZ1bmN0aW9uIEluZGV4ZWRTb3VyY2VNYXBDb25zdW1lcl9zb3VyY2VDb250ZW50Rm9yKGFTb3VyY2UsIG51bGxPbk1pc3NpbmcpIHtcbiAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMuX3NlY3Rpb25zLmxlbmd0aDsgaSsrKSB7XG4gICAgICB2YXIgc2VjdGlvbiA9IHRoaXMuX3NlY3Rpb25zW2ldO1xuXG4gICAgICB2YXIgY29udGVudCA9IHNlY3Rpb24uY29uc3VtZXIuc291cmNlQ29udGVudEZvcihhU291cmNlLCB0cnVlKTtcbiAgICAgIGlmIChjb250ZW50KSB7XG4gICAgICAgIHJldHVybiBjb250ZW50O1xuICAgICAgfVxuICAgIH1cbiAgICBpZiAobnVsbE9uTWlzc2luZykge1xuICAgICAgcmV0dXJuIG51bGw7XG4gICAgfVxuICAgIGVsc2Uge1xuICAgICAgdGhyb3cgbmV3IEVycm9yKCdcIicgKyBhU291cmNlICsgJ1wiIGlzIG5vdCBpbiB0aGUgU291cmNlTWFwLicpO1xuICAgIH1cbiAgfTtcblxuLyoqXG4gKiBSZXR1cm5zIHRoZSBnZW5lcmF0ZWQgbGluZSBhbmQgY29sdW1uIGluZm9ybWF0aW9uIGZvciB0aGUgb3JpZ2luYWwgc291cmNlLFxuICogbGluZSwgYW5kIGNvbHVtbiBwb3NpdGlvbnMgcHJvdmlkZWQuIFRoZSBvbmx5IGFyZ3VtZW50IGlzIGFuIG9iamVjdCB3aXRoXG4gKiB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIHNvdXJjZTogVGhlIGZpbGVuYW1lIG9mIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gbGluZTogVGhlIGxpbmUgbnVtYmVyIGluIHRoZSBvcmlnaW5hbCBzb3VyY2UuXG4gKiAgIC0gY29sdW1uOiBUaGUgY29sdW1uIG51bWJlciBpbiB0aGUgb3JpZ2luYWwgc291cmNlLlxuICpcbiAqIGFuZCBhbiBvYmplY3QgaXMgcmV0dXJuZWQgd2l0aCB0aGUgZm9sbG93aW5nIHByb3BlcnRpZXM6XG4gKlxuICogICAtIGxpbmU6IFRoZSBsaW5lIG51bWJlciBpbiB0aGUgZ2VuZXJhdGVkIHNvdXJjZSwgb3IgbnVsbC5cbiAqICAgLSBjb2x1bW46IFRoZSBjb2x1bW4gbnVtYmVyIGluIHRoZSBnZW5lcmF0ZWQgc291cmNlLCBvciBudWxsLlxuICovXG5JbmRleGVkU291cmNlTWFwQ29uc3VtZXIucHJvdG90eXBlLmdlbmVyYXRlZFBvc2l0aW9uRm9yID1cbiAgZnVuY3Rpb24gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyX2dlbmVyYXRlZFBvc2l0aW9uRm9yKGFBcmdzKSB7XG4gICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0aGlzLl9zZWN0aW9ucy5sZW5ndGg7IGkrKykge1xuICAgICAgdmFyIHNlY3Rpb24gPSB0aGlzLl9zZWN0aW9uc1tpXTtcblxuICAgICAgLy8gT25seSBjb25zaWRlciB0aGlzIHNlY3Rpb24gaWYgdGhlIHJlcXVlc3RlZCBzb3VyY2UgaXMgaW4gdGhlIGxpc3Qgb2ZcbiAgICAgIC8vIHNvdXJjZXMgb2YgdGhlIGNvbnN1bWVyLlxuICAgICAgaWYgKHNlY3Rpb24uY29uc3VtZXIuc291cmNlcy5pbmRleE9mKHV0aWwuZ2V0QXJnKGFBcmdzLCAnc291cmNlJykpID09PSAtMSkge1xuICAgICAgICBjb250aW51ZTtcbiAgICAgIH1cbiAgICAgIHZhciBnZW5lcmF0ZWRQb3NpdGlvbiA9IHNlY3Rpb24uY29uc3VtZXIuZ2VuZXJhdGVkUG9zaXRpb25Gb3IoYUFyZ3MpO1xuICAgICAgaWYgKGdlbmVyYXRlZFBvc2l0aW9uKSB7XG4gICAgICAgIHZhciByZXQgPSB7XG4gICAgICAgICAgbGluZTogZ2VuZXJhdGVkUG9zaXRpb24ubGluZSArXG4gICAgICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSAtIDEpLFxuICAgICAgICAgIGNvbHVtbjogZ2VuZXJhdGVkUG9zaXRpb24uY29sdW1uICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lID09PSBnZW5lcmF0ZWRQb3NpdGlvbi5saW5lXG4gICAgICAgICAgICAgPyBzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRDb2x1bW4gLSAxXG4gICAgICAgICAgICAgOiAwKVxuICAgICAgICB9O1xuICAgICAgICByZXR1cm4gcmV0O1xuICAgICAgfVxuICAgIH1cblxuICAgIHJldHVybiB7XG4gICAgICBsaW5lOiBudWxsLFxuICAgICAgY29sdW1uOiBudWxsXG4gICAgfTtcbiAgfTtcblxuLyoqXG4gKiBQYXJzZSB0aGUgbWFwcGluZ3MgaW4gYSBzdHJpbmcgaW4gdG8gYSBkYXRhIHN0cnVjdHVyZSB3aGljaCB3ZSBjYW4gZWFzaWx5XG4gKiBxdWVyeSAodGhlIG9yZGVyZWQgYXJyYXlzIGluIHRoZSBgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzYCBhbmRcbiAqIGB0aGlzLl9fb3JpZ2luYWxNYXBwaW5nc2AgcHJvcGVydGllcykuXG4gKi9cbkluZGV4ZWRTb3VyY2VNYXBDb25zdW1lci5wcm90b3R5cGUuX3BhcnNlTWFwcGluZ3MgPVxuICBmdW5jdGlvbiBJbmRleGVkU291cmNlTWFwQ29uc3VtZXJfcGFyc2VNYXBwaW5ncyhhU3RyLCBhU291cmNlUm9vdCkge1xuICAgIHRoaXMuX19nZW5lcmF0ZWRNYXBwaW5ncyA9IFtdO1xuICAgIHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzID0gW107XG4gICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0aGlzLl9zZWN0aW9ucy5sZW5ndGg7IGkrKykge1xuICAgICAgdmFyIHNlY3Rpb24gPSB0aGlzLl9zZWN0aW9uc1tpXTtcbiAgICAgIHZhciBzZWN0aW9uTWFwcGluZ3MgPSBzZWN0aW9uLmNvbnN1bWVyLl9nZW5lcmF0ZWRNYXBwaW5ncztcbiAgICAgIGZvciAodmFyIGogPSAwOyBqIDwgc2VjdGlvbk1hcHBpbmdzLmxlbmd0aDsgaisrKSB7XG4gICAgICAgIHZhciBtYXBwaW5nID0gc2VjdGlvbk1hcHBpbmdzW2pdO1xuXG4gICAgICAgIHZhciBzb3VyY2UgPSBzZWN0aW9uLmNvbnN1bWVyLl9zb3VyY2VzLmF0KG1hcHBpbmcuc291cmNlKTtcbiAgICAgICAgaWYgKHNlY3Rpb24uY29uc3VtZXIuc291cmNlUm9vdCAhPT0gbnVsbCkge1xuICAgICAgICAgIHNvdXJjZSA9IHV0aWwuam9pbihzZWN0aW9uLmNvbnN1bWVyLnNvdXJjZVJvb3QsIHNvdXJjZSk7XG4gICAgICAgIH1cbiAgICAgICAgdGhpcy5fc291cmNlcy5hZGQoc291cmNlKTtcbiAgICAgICAgc291cmNlID0gdGhpcy5fc291cmNlcy5pbmRleE9mKHNvdXJjZSk7XG5cbiAgICAgICAgdmFyIG5hbWUgPSBzZWN0aW9uLmNvbnN1bWVyLl9uYW1lcy5hdChtYXBwaW5nLm5hbWUpO1xuICAgICAgICB0aGlzLl9uYW1lcy5hZGQobmFtZSk7XG4gICAgICAgIG5hbWUgPSB0aGlzLl9uYW1lcy5pbmRleE9mKG5hbWUpO1xuXG4gICAgICAgIC8vIFRoZSBtYXBwaW5ncyBjb21pbmcgZnJvbSB0aGUgY29uc3VtZXIgZm9yIHRoZSBzZWN0aW9uIGhhdmVcbiAgICAgICAgLy8gZ2VuZXJhdGVkIHBvc2l0aW9ucyByZWxhdGl2ZSB0byB0aGUgc3RhcnQgb2YgdGhlIHNlY3Rpb24sIHNvIHdlXG4gICAgICAgIC8vIG5lZWQgdG8gb2Zmc2V0IHRoZW0gdG8gYmUgcmVsYXRpdmUgdG8gdGhlIHN0YXJ0IG9mIHRoZSBjb25jYXRlbmF0ZWRcbiAgICAgICAgLy8gZ2VuZXJhdGVkIGZpbGUuXG4gICAgICAgIHZhciBhZGp1c3RlZE1hcHBpbmcgPSB7XG4gICAgICAgICAgc291cmNlOiBzb3VyY2UsXG4gICAgICAgICAgZ2VuZXJhdGVkTGluZTogbWFwcGluZy5nZW5lcmF0ZWRMaW5lICtcbiAgICAgICAgICAgIChzZWN0aW9uLmdlbmVyYXRlZE9mZnNldC5nZW5lcmF0ZWRMaW5lIC0gMSksXG4gICAgICAgICAgZ2VuZXJhdGVkQ29sdW1uOiBtYXBwaW5nLmdlbmVyYXRlZENvbHVtbiArXG4gICAgICAgICAgICAoc2VjdGlvbi5nZW5lcmF0ZWRPZmZzZXQuZ2VuZXJhdGVkTGluZSA9PT0gbWFwcGluZy5nZW5lcmF0ZWRMaW5lXG4gICAgICAgICAgICA/IHNlY3Rpb24uZ2VuZXJhdGVkT2Zmc2V0LmdlbmVyYXRlZENvbHVtbiAtIDFcbiAgICAgICAgICAgIDogMCksXG4gICAgICAgICAgb3JpZ2luYWxMaW5lOiBtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICBvcmlnaW5hbENvbHVtbjogbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICBuYW1lOiBuYW1lXG4gICAgICAgIH07XG5cbiAgICAgICAgdGhpcy5fX2dlbmVyYXRlZE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgaWYgKHR5cGVvZiBhZGp1c3RlZE1hcHBpbmcub3JpZ2luYWxMaW5lID09PSAnbnVtYmVyJykge1xuICAgICAgICAgIHRoaXMuX19vcmlnaW5hbE1hcHBpbmdzLnB1c2goYWRqdXN0ZWRNYXBwaW5nKTtcbiAgICAgICAgfVxuICAgICAgfVxuICAgIH1cblxuICAgIHF1aWNrU29ydCh0aGlzLl9fZ2VuZXJhdGVkTWFwcGluZ3MsIHV0aWwuY29tcGFyZUJ5R2VuZXJhdGVkUG9zaXRpb25zRGVmbGF0ZWQpO1xuICAgIHF1aWNrU29ydCh0aGlzLl9fb3JpZ2luYWxNYXBwaW5ncywgdXRpbC5jb21wYXJlQnlPcmlnaW5hbFBvc2l0aW9ucyk7XG4gIH07XG5cbmV4cG9ydHMuSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyID0gSW5kZXhlZFNvdXJjZU1hcENvbnN1bWVyO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW1hcC1jb25zdW1lci5qc1xuLy8gbW9kdWxlIGlkID0gN1xuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbmV4cG9ydHMuR1JFQVRFU1RfTE9XRVJfQk9VTkQgPSAxO1xuZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCA9IDI7XG5cbi8qKlxuICogUmVjdXJzaXZlIGltcGxlbWVudGF0aW9uIG9mIGJpbmFyeSBzZWFyY2guXG4gKlxuICogQHBhcmFtIGFMb3cgSW5kaWNlcyBoZXJlIGFuZCBsb3dlciBkbyBub3QgY29udGFpbiB0aGUgbmVlZGxlLlxuICogQHBhcmFtIGFIaWdoIEluZGljZXMgaGVyZSBhbmQgaGlnaGVyIGRvIG5vdCBjb250YWluIHRoZSBuZWVkbGUuXG4gKiBAcGFyYW0gYU5lZWRsZSBUaGUgZWxlbWVudCBiZWluZyBzZWFyY2hlZCBmb3IuXG4gKiBAcGFyYW0gYUhheXN0YWNrIFRoZSBub24tZW1wdHkgYXJyYXkgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgRnVuY3Rpb24gd2hpY2ggdGFrZXMgdHdvIGVsZW1lbnRzIGFuZCByZXR1cm5zIC0xLCAwLCBvciAxLlxuICogQHBhcmFtIGFCaWFzIEVpdGhlciAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJyBvclxuICogICAgICdiaW5hcnlTZWFyY2guTEVBU1RfVVBQRVJfQk9VTkQnLiBTcGVjaWZpZXMgd2hldGhlciB0byByZXR1cm4gdGhlXG4gKiAgICAgY2xvc2VzdCBlbGVtZW50IHRoYXQgaXMgc21hbGxlciB0aGFuIG9yIGdyZWF0ZXIgdGhhbiB0aGUgb25lIHdlIGFyZVxuICogICAgIHNlYXJjaGluZyBmb3IsIHJlc3BlY3RpdmVseSwgaWYgdGhlIGV4YWN0IGVsZW1lbnQgY2Fubm90IGJlIGZvdW5kLlxuICovXG5mdW5jdGlvbiByZWN1cnNpdmVTZWFyY2goYUxvdywgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKSB7XG4gIC8vIFRoaXMgZnVuY3Rpb24gdGVybWluYXRlcyB3aGVuIG9uZSBvZiB0aGUgZm9sbG93aW5nIGlzIHRydWU6XG4gIC8vXG4gIC8vICAgMS4gV2UgZmluZCB0aGUgZXhhY3QgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gIC8vXG4gIC8vICAgMi4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBidXQgd2UgY2FuIHJldHVybiB0aGUgaW5kZXggb2ZcbiAgLy8gICAgICB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQuXG4gIC8vXG4gIC8vICAgMy4gV2UgZGlkIG5vdCBmaW5kIHRoZSBleGFjdCBlbGVtZW50LCBhbmQgdGhlcmUgaXMgbm8gbmV4dC1jbG9zZXN0XG4gIC8vICAgICAgZWxlbWVudCB0aGFuIHRoZSBvbmUgd2UgYXJlIHNlYXJjaGluZyBmb3IsIHNvIHdlIHJldHVybiAtMS5cbiAgdmFyIG1pZCA9IE1hdGguZmxvb3IoKGFIaWdoIC0gYUxvdykgLyAyKSArIGFMb3c7XG4gIHZhciBjbXAgPSBhQ29tcGFyZShhTmVlZGxlLCBhSGF5c3RhY2tbbWlkXSwgdHJ1ZSk7XG4gIGlmIChjbXAgPT09IDApIHtcbiAgICAvLyBGb3VuZCB0aGUgZWxlbWVudCB3ZSBhcmUgbG9va2luZyBmb3IuXG4gICAgcmV0dXJuIG1pZDtcbiAgfVxuICBlbHNlIGlmIChjbXAgPiAwKSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBncmVhdGVyIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKGFIaWdoIC0gbWlkID4gMSkge1xuICAgICAgLy8gVGhlIGVsZW1lbnQgaXMgaW4gdGhlIHVwcGVyIGhhbGYuXG4gICAgICByZXR1cm4gcmVjdXJzaXZlU2VhcmNoKG1pZCwgYUhpZ2gsIGFOZWVkbGUsIGFIYXlzdGFjaywgYUNvbXBhcmUsIGFCaWFzKTtcbiAgICB9XG5cbiAgICAvLyBUaGUgZXhhY3QgbmVlZGxlIGVsZW1lbnQgd2FzIG5vdCBmb3VuZCBpbiB0aGlzIGhheXN0YWNrLiBEZXRlcm1pbmUgaWZcbiAgICAvLyB3ZSBhcmUgaW4gdGVybWluYXRpb24gY2FzZSAoMykgb3IgKDIpIGFuZCByZXR1cm4gdGhlIGFwcHJvcHJpYXRlIHRoaW5nLlxuICAgIGlmIChhQmlhcyA9PSBleHBvcnRzLkxFQVNUX1VQUEVSX0JPVU5EKSB7XG4gICAgICByZXR1cm4gYUhpZ2ggPCBhSGF5c3RhY2subGVuZ3RoID8gYUhpZ2ggOiAtMTtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9XG4gIH1cbiAgZWxzZSB7XG4gICAgLy8gT3VyIG5lZWRsZSBpcyBsZXNzIHRoYW4gYUhheXN0YWNrW21pZF0uXG4gICAgaWYgKG1pZCAtIGFMb3cgPiAxKSB7XG4gICAgICAvLyBUaGUgZWxlbWVudCBpcyBpbiB0aGUgbG93ZXIgaGFsZi5cbiAgICAgIHJldHVybiByZWN1cnNpdmVTZWFyY2goYUxvdywgbWlkLCBhTmVlZGxlLCBhSGF5c3RhY2ssIGFDb21wYXJlLCBhQmlhcyk7XG4gICAgfVxuXG4gICAgLy8gd2UgYXJlIGluIHRlcm1pbmF0aW9uIGNhc2UgKDMpIG9yICgyKSBhbmQgcmV0dXJuIHRoZSBhcHByb3ByaWF0ZSB0aGluZy5cbiAgICBpZiAoYUJpYXMgPT0gZXhwb3J0cy5MRUFTVF9VUFBFUl9CT1VORCkge1xuICAgICAgcmV0dXJuIG1pZDtcbiAgICB9IGVsc2Uge1xuICAgICAgcmV0dXJuIGFMb3cgPCAwID8gLTEgOiBhTG93O1xuICAgIH1cbiAgfVxufVxuXG4vKipcbiAqIFRoaXMgaXMgYW4gaW1wbGVtZW50YXRpb24gb2YgYmluYXJ5IHNlYXJjaCB3aGljaCB3aWxsIGFsd2F5cyB0cnkgYW5kIHJldHVyblxuICogdGhlIGluZGV4IG9mIHRoZSBjbG9zZXN0IGVsZW1lbnQgaWYgdGhlcmUgaXMgbm8gZXhhY3QgaGl0LiBUaGlzIGlzIGJlY2F1c2VcbiAqIG1hcHBpbmdzIGJldHdlZW4gb3JpZ2luYWwgYW5kIGdlbmVyYXRlZCBsaW5lL2NvbCBwYWlycyBhcmUgc2luZ2xlIHBvaW50cyxcbiAqIGFuZCB0aGVyZSBpcyBhbiBpbXBsaWNpdCByZWdpb24gYmV0d2VlbiBlYWNoIG9mIHRoZW0sIHNvIGEgbWlzcyBqdXN0IG1lYW5zXG4gKiB0aGF0IHlvdSBhcmVuJ3Qgb24gdGhlIHZlcnkgc3RhcnQgb2YgYSByZWdpb24uXG4gKlxuICogQHBhcmFtIGFOZWVkbGUgVGhlIGVsZW1lbnQgeW91IGFyZSBsb29raW5nIGZvci5cbiAqIEBwYXJhbSBhSGF5c3RhY2sgVGhlIGFycmF5IHRoYXQgaXMgYmVpbmcgc2VhcmNoZWQuXG4gKiBAcGFyYW0gYUNvbXBhcmUgQSBmdW5jdGlvbiB3aGljaCB0YWtlcyB0aGUgbmVlZGxlIGFuZCBhbiBlbGVtZW50IGluIHRoZVxuICogICAgIGFycmF5IGFuZCByZXR1cm5zIC0xLCAwLCBvciAxIGRlcGVuZGluZyBvbiB3aGV0aGVyIHRoZSBuZWVkbGUgaXMgbGVzc1xuICogICAgIHRoYW4sIGVxdWFsIHRvLCBvciBncmVhdGVyIHRoYW4gdGhlIGVsZW1lbnQsIHJlc3BlY3RpdmVseS5cbiAqIEBwYXJhbSBhQmlhcyBFaXRoZXIgJ2JpbmFyeVNlYXJjaC5HUkVBVEVTVF9MT1dFUl9CT1VORCcgb3JcbiAqICAgICAnYmluYXJ5U2VhcmNoLkxFQVNUX1VQUEVSX0JPVU5EJy4gU3BlY2lmaWVzIHdoZXRoZXIgdG8gcmV0dXJuIHRoZVxuICogICAgIGNsb3Nlc3QgZWxlbWVudCB0aGF0IGlzIHNtYWxsZXIgdGhhbiBvciBncmVhdGVyIHRoYW4gdGhlIG9uZSB3ZSBhcmVcbiAqICAgICBzZWFyY2hpbmcgZm9yLCByZXNwZWN0aXZlbHksIGlmIHRoZSBleGFjdCBlbGVtZW50IGNhbm5vdCBiZSBmb3VuZC5cbiAqICAgICBEZWZhdWx0cyB0byAnYmluYXJ5U2VhcmNoLkdSRUFURVNUX0xPV0VSX0JPVU5EJy5cbiAqL1xuZXhwb3J0cy5zZWFyY2ggPSBmdW5jdGlvbiBzZWFyY2goYU5lZWRsZSwgYUhheXN0YWNrLCBhQ29tcGFyZSwgYUJpYXMpIHtcbiAgaWYgKGFIYXlzdGFjay5sZW5ndGggPT09IDApIHtcbiAgICByZXR1cm4gLTE7XG4gIH1cblxuICB2YXIgaW5kZXggPSByZWN1cnNpdmVTZWFyY2goLTEsIGFIYXlzdGFjay5sZW5ndGgsIGFOZWVkbGUsIGFIYXlzdGFjayxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFDb21wYXJlLCBhQmlhcyB8fCBleHBvcnRzLkdSRUFURVNUX0xPV0VSX0JPVU5EKTtcbiAgaWYgKGluZGV4IDwgMCkge1xuICAgIHJldHVybiAtMTtcbiAgfVxuXG4gIC8vIFdlIGhhdmUgZm91bmQgZWl0aGVyIHRoZSBleGFjdCBlbGVtZW50LCBvciB0aGUgbmV4dC1jbG9zZXN0IGVsZW1lbnQgdGhhblxuICAvLyB0aGUgb25lIHdlIGFyZSBzZWFyY2hpbmcgZm9yLiBIb3dldmVyLCB0aGVyZSBtYXkgYmUgbW9yZSB0aGFuIG9uZSBzdWNoXG4gIC8vIGVsZW1lbnQuIE1ha2Ugc3VyZSB3ZSBhbHdheXMgcmV0dXJuIHRoZSBzbWFsbGVzdCBvZiB0aGVzZS5cbiAgd2hpbGUgKGluZGV4IC0gMSA+PSAwKSB7XG4gICAgaWYgKGFDb21wYXJlKGFIYXlzdGFja1tpbmRleF0sIGFIYXlzdGFja1tpbmRleCAtIDFdLCB0cnVlKSAhPT0gMCkge1xuICAgICAgYnJlYWs7XG4gICAgfVxuICAgIC0taW5kZXg7XG4gIH1cblxuICByZXR1cm4gaW5kZXg7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvYmluYXJ5LXNlYXJjaC5qc1xuLy8gbW9kdWxlIGlkID0gOFxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbi8vIEl0IHR1cm5zIG91dCB0aGF0IHNvbWUgKG1vc3Q/KSBKYXZhU2NyaXB0IGVuZ2luZXMgZG9uJ3Qgc2VsZi1ob3N0XG4vLyBgQXJyYXkucHJvdG90eXBlLnNvcnRgLiBUaGlzIG1ha2VzIHNlbnNlIGJlY2F1c2UgQysrIHdpbGwgbGlrZWx5IHJlbWFpblxuLy8gZmFzdGVyIHRoYW4gSlMgd2hlbiBkb2luZyByYXcgQ1BVLWludGVuc2l2ZSBzb3J0aW5nLiBIb3dldmVyLCB3aGVuIHVzaW5nIGFcbi8vIGN1c3RvbSBjb21wYXJhdG9yIGZ1bmN0aW9uLCBjYWxsaW5nIGJhY2sgYW5kIGZvcnRoIGJldHdlZW4gdGhlIFZNJ3MgQysrIGFuZFxuLy8gSklUJ2QgSlMgaXMgcmF0aGVyIHNsb3cgKmFuZCogbG9zZXMgSklUIHR5cGUgaW5mb3JtYXRpb24sIHJlc3VsdGluZyBpblxuLy8gd29yc2UgZ2VuZXJhdGVkIGNvZGUgZm9yIHRoZSBjb21wYXJhdG9yIGZ1bmN0aW9uIHRoYW4gd291bGQgYmUgb3B0aW1hbC4gSW5cbi8vIGZhY3QsIHdoZW4gc29ydGluZyB3aXRoIGEgY29tcGFyYXRvciwgdGhlc2UgY29zdHMgb3V0d2VpZ2ggdGhlIGJlbmVmaXRzIG9mXG4vLyBzb3J0aW5nIGluIEMrKy4gQnkgdXNpbmcgb3VyIG93biBKUy1pbXBsZW1lbnRlZCBRdWljayBTb3J0IChiZWxvdyksIHdlIGdldFxuLy8gYSB+MzUwMG1zIG1lYW4gc3BlZWQtdXAgaW4gYGJlbmNoL2JlbmNoLmh0bWxgLlxuXG4vKipcbiAqIFN3YXAgdGhlIGVsZW1lbnRzIGluZGV4ZWQgYnkgYHhgIGFuZCBgeWAgaW4gdGhlIGFycmF5IGBhcnlgLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIFRoZSBhcnJheS5cbiAqIEBwYXJhbSB7TnVtYmVyfSB4XG4gKiAgICAgICAgVGhlIGluZGV4IG9mIHRoZSBmaXJzdCBpdGVtLlxuICogQHBhcmFtIHtOdW1iZXJ9IHlcbiAqICAgICAgICBUaGUgaW5kZXggb2YgdGhlIHNlY29uZCBpdGVtLlxuICovXG5mdW5jdGlvbiBzd2FwKGFyeSwgeCwgeSkge1xuICB2YXIgdGVtcCA9IGFyeVt4XTtcbiAgYXJ5W3hdID0gYXJ5W3ldO1xuICBhcnlbeV0gPSB0ZW1wO1xufVxuXG4vKipcbiAqIFJldHVybnMgYSByYW5kb20gaW50ZWdlciB3aXRoaW4gdGhlIHJhbmdlIGBsb3cgLi4gaGlnaGAgaW5jbHVzaXZlLlxuICpcbiAqIEBwYXJhbSB7TnVtYmVyfSBsb3dcbiAqICAgICAgICBUaGUgbG93ZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICogQHBhcmFtIHtOdW1iZXJ9IGhpZ2hcbiAqICAgICAgICBUaGUgdXBwZXIgYm91bmQgb24gdGhlIHJhbmdlLlxuICovXG5mdW5jdGlvbiByYW5kb21JbnRJblJhbmdlKGxvdywgaGlnaCkge1xuICByZXR1cm4gTWF0aC5yb3VuZChsb3cgKyAoTWF0aC5yYW5kb20oKSAqIChoaWdoIC0gbG93KSkpO1xufVxuXG4vKipcbiAqIFRoZSBRdWljayBTb3J0IGFsZ29yaXRobS5cbiAqXG4gKiBAcGFyYW0ge0FycmF5fSBhcnlcbiAqICAgICAgICBBbiBhcnJheSB0byBzb3J0LlxuICogQHBhcmFtIHtmdW5jdGlvbn0gY29tcGFyYXRvclxuICogICAgICAgIEZ1bmN0aW9uIHRvIHVzZSB0byBjb21wYXJlIHR3byBpdGVtcy5cbiAqIEBwYXJhbSB7TnVtYmVyfSBwXG4gKiAgICAgICAgU3RhcnQgaW5kZXggb2YgdGhlIGFycmF5XG4gKiBAcGFyYW0ge051bWJlcn0gclxuICogICAgICAgIEVuZCBpbmRleCBvZiB0aGUgYXJyYXlcbiAqL1xuZnVuY3Rpb24gZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCByKSB7XG4gIC8vIElmIG91ciBsb3dlciBib3VuZCBpcyBsZXNzIHRoYW4gb3VyIHVwcGVyIGJvdW5kLCB3ZSAoMSkgcGFydGl0aW9uIHRoZVxuICAvLyBhcnJheSBpbnRvIHR3byBwaWVjZXMgYW5kICgyKSByZWN1cnNlIG9uIGVhY2ggaGFsZi4gSWYgaXQgaXMgbm90LCB0aGlzIGlzXG4gIC8vIHRoZSBlbXB0eSBhcnJheSBhbmQgb3VyIGJhc2UgY2FzZS5cblxuICBpZiAocCA8IHIpIHtcbiAgICAvLyAoMSkgUGFydGl0aW9uaW5nLlxuICAgIC8vXG4gICAgLy8gVGhlIHBhcnRpdGlvbmluZyBjaG9vc2VzIGEgcGl2b3QgYmV0d2VlbiBgcGAgYW5kIGByYCBhbmQgbW92ZXMgYWxsXG4gICAgLy8gZWxlbWVudHMgdGhhdCBhcmUgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdCB0byB0aGUgYmVmb3JlIGl0LCBhbmRcbiAgICAvLyBhbGwgdGhlIGVsZW1lbnRzIHRoYXQgYXJlIGdyZWF0ZXIgdGhhbiBpdCBhZnRlciBpdC4gVGhlIGVmZmVjdCBpcyB0aGF0XG4gICAgLy8gb25jZSBwYXJ0aXRpb24gaXMgZG9uZSwgdGhlIHBpdm90IGlzIGluIHRoZSBleGFjdCBwbGFjZSBpdCB3aWxsIGJlIHdoZW5cbiAgICAvLyB0aGUgYXJyYXkgaXMgcHV0IGluIHNvcnRlZCBvcmRlciwgYW5kIGl0IHdpbGwgbm90IG5lZWQgdG8gYmUgbW92ZWRcbiAgICAvLyBhZ2Fpbi4gVGhpcyBydW5zIGluIE8obikgdGltZS5cblxuICAgIC8vIEFsd2F5cyBjaG9vc2UgYSByYW5kb20gcGl2b3Qgc28gdGhhdCBhbiBpbnB1dCBhcnJheSB3aGljaCBpcyByZXZlcnNlXG4gICAgLy8gc29ydGVkIGRvZXMgbm90IGNhdXNlIE8obl4yKSBydW5uaW5nIHRpbWUuXG4gICAgdmFyIHBpdm90SW5kZXggPSByYW5kb21JbnRJblJhbmdlKHAsIHIpO1xuICAgIHZhciBpID0gcCAtIDE7XG5cbiAgICBzd2FwKGFyeSwgcGl2b3RJbmRleCwgcik7XG4gICAgdmFyIHBpdm90ID0gYXJ5W3JdO1xuXG4gICAgLy8gSW1tZWRpYXRlbHkgYWZ0ZXIgYGpgIGlzIGluY3JlbWVudGVkIGluIHRoaXMgbG9vcCwgdGhlIGZvbGxvd2luZyBob2xkXG4gICAgLy8gdHJ1ZTpcbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbcCAuLiBpXWAgaXMgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIHRoZSBwaXZvdC5cbiAgICAvL1xuICAgIC8vICAgKiBFdmVyeSBlbGVtZW50IGluIGBhcnlbaSsxIC4uIGotMV1gIGlzIGdyZWF0ZXIgdGhhbiB0aGUgcGl2b3QuXG4gICAgZm9yICh2YXIgaiA9IHA7IGogPCByOyBqKyspIHtcbiAgICAgIGlmIChjb21wYXJhdG9yKGFyeVtqXSwgcGl2b3QpIDw9IDApIHtcbiAgICAgICAgaSArPSAxO1xuICAgICAgICBzd2FwKGFyeSwgaSwgaik7XG4gICAgICB9XG4gICAgfVxuXG4gICAgc3dhcChhcnksIGkgKyAxLCBqKTtcbiAgICB2YXIgcSA9IGkgKyAxO1xuXG4gICAgLy8gKDIpIFJlY3Vyc2Ugb24gZWFjaCBoYWxmLlxuXG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBwLCBxIC0gMSk7XG4gICAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCBxICsgMSwgcik7XG4gIH1cbn1cblxuLyoqXG4gKiBTb3J0IHRoZSBnaXZlbiBhcnJheSBpbi1wbGFjZSB3aXRoIHRoZSBnaXZlbiBjb21wYXJhdG9yIGZ1bmN0aW9uLlxuICpcbiAqIEBwYXJhbSB7QXJyYXl9IGFyeVxuICogICAgICAgIEFuIGFycmF5IHRvIHNvcnQuXG4gKiBAcGFyYW0ge2Z1bmN0aW9ufSBjb21wYXJhdG9yXG4gKiAgICAgICAgRnVuY3Rpb24gdG8gdXNlIHRvIGNvbXBhcmUgdHdvIGl0ZW1zLlxuICovXG5leHBvcnRzLnF1aWNrU29ydCA9IGZ1bmN0aW9uIChhcnksIGNvbXBhcmF0b3IpIHtcbiAgZG9RdWlja1NvcnQoYXJ5LCBjb21wYXJhdG9yLCAwLCBhcnkubGVuZ3RoIC0gMSk7XG59O1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvcXVpY2stc29ydC5qc1xuLy8gbW9kdWxlIGlkID0gOVxuLy8gbW9kdWxlIGNodW5rcyA9IDAiLCIvKiAtKi0gTW9kZToganM7IGpzLWluZGVudC1sZXZlbDogMjsgLSotICovXG4vKlxuICogQ29weXJpZ2h0IDIwMTEgTW96aWxsYSBGb3VuZGF0aW9uIGFuZCBjb250cmlidXRvcnNcbiAqIExpY2Vuc2VkIHVuZGVyIHRoZSBOZXcgQlNEIGxpY2Vuc2UuIFNlZSBMSUNFTlNFIG9yOlxuICogaHR0cDovL29wZW5zb3VyY2Uub3JnL2xpY2Vuc2VzL0JTRC0zLUNsYXVzZVxuICovXG5cbnZhciBTb3VyY2VNYXBHZW5lcmF0b3IgPSByZXF1aXJlKCcuL3NvdXJjZS1tYXAtZ2VuZXJhdG9yJykuU291cmNlTWFwR2VuZXJhdG9yO1xudmFyIHV0aWwgPSByZXF1aXJlKCcuL3V0aWwnKTtcblxuLy8gTWF0Y2hlcyBhIFdpbmRvd3Mtc3R5bGUgYFxcclxcbmAgbmV3bGluZSBvciBhIGBcXG5gIG5ld2xpbmUgdXNlZCBieSBhbGwgb3RoZXJcbi8vIG9wZXJhdGluZyBzeXN0ZW1zIHRoZXNlIGRheXMgKGNhcHR1cmluZyB0aGUgcmVzdWx0KS5cbnZhciBSRUdFWF9ORVdMSU5FID0gLyhcXHI/XFxuKS87XG5cbi8vIE5ld2xpbmUgY2hhcmFjdGVyIGNvZGUgZm9yIGNoYXJDb2RlQXQoKSBjb21wYXJpc29uc1xudmFyIE5FV0xJTkVfQ09ERSA9IDEwO1xuXG4vLyBQcml2YXRlIHN5bWJvbCBmb3IgaWRlbnRpZnlpbmcgYFNvdXJjZU5vZGVgcyB3aGVuIG11bHRpcGxlIHZlcnNpb25zIG9mXG4vLyB0aGUgc291cmNlLW1hcCBsaWJyYXJ5IGFyZSBsb2FkZWQuIFRoaXMgTVVTVCBOT1QgQ0hBTkdFIGFjcm9zc1xuLy8gdmVyc2lvbnMhXG52YXIgaXNTb3VyY2VOb2RlID0gXCIkJCRpc1NvdXJjZU5vZGUkJCRcIjtcblxuLyoqXG4gKiBTb3VyY2VOb2RlcyBwcm92aWRlIGEgd2F5IHRvIGFic3RyYWN0IG92ZXIgaW50ZXJwb2xhdGluZy9jb25jYXRlbmF0aW5nXG4gKiBzbmlwcGV0cyBvZiBnZW5lcmF0ZWQgSmF2YVNjcmlwdCBzb3VyY2UgY29kZSB3aGlsZSBtYWludGFpbmluZyB0aGUgbGluZSBhbmRcbiAqIGNvbHVtbiBpbmZvcm1hdGlvbiBhc3NvY2lhdGVkIHdpdGggdGhlIG9yaWdpbmFsIHNvdXJjZSBjb2RlLlxuICpcbiAqIEBwYXJhbSBhTGluZSBUaGUgb3JpZ2luYWwgbGluZSBudW1iZXIuXG4gKiBAcGFyYW0gYUNvbHVtbiBUaGUgb3JpZ2luYWwgY29sdW1uIG51bWJlci5cbiAqIEBwYXJhbSBhU291cmNlIFRoZSBvcmlnaW5hbCBzb3VyY2UncyBmaWxlbmFtZS5cbiAqIEBwYXJhbSBhQ2h1bmtzIE9wdGlvbmFsLiBBbiBhcnJheSBvZiBzdHJpbmdzIHdoaWNoIGFyZSBzbmlwcGV0cyBvZlxuICogICAgICAgIGdlbmVyYXRlZCBKUywgb3Igb3RoZXIgU291cmNlTm9kZXMuXG4gKiBAcGFyYW0gYU5hbWUgVGhlIG9yaWdpbmFsIGlkZW50aWZpZXIuXG4gKi9cbmZ1bmN0aW9uIFNvdXJjZU5vZGUoYUxpbmUsIGFDb2x1bW4sIGFTb3VyY2UsIGFDaHVua3MsIGFOYW1lKSB7XG4gIHRoaXMuY2hpbGRyZW4gPSBbXTtcbiAgdGhpcy5zb3VyY2VDb250ZW50cyA9IHt9O1xuICB0aGlzLmxpbmUgPSBhTGluZSA9PSBudWxsID8gbnVsbCA6IGFMaW5lO1xuICB0aGlzLmNvbHVtbiA9IGFDb2x1bW4gPT0gbnVsbCA/IG51bGwgOiBhQ29sdW1uO1xuICB0aGlzLnNvdXJjZSA9IGFTb3VyY2UgPT0gbnVsbCA/IG51bGwgOiBhU291cmNlO1xuICB0aGlzLm5hbWUgPSBhTmFtZSA9PSBudWxsID8gbnVsbCA6IGFOYW1lO1xuICB0aGlzW2lzU291cmNlTm9kZV0gPSB0cnVlO1xuICBpZiAoYUNodW5rcyAhPSBudWxsKSB0aGlzLmFkZChhQ2h1bmtzKTtcbn1cblxuLyoqXG4gKiBDcmVhdGVzIGEgU291cmNlTm9kZSBmcm9tIGdlbmVyYXRlZCBjb2RlIGFuZCBhIFNvdXJjZU1hcENvbnN1bWVyLlxuICpcbiAqIEBwYXJhbSBhR2VuZXJhdGVkQ29kZSBUaGUgZ2VuZXJhdGVkIGNvZGVcbiAqIEBwYXJhbSBhU291cmNlTWFwQ29uc3VtZXIgVGhlIFNvdXJjZU1hcCBmb3IgdGhlIGdlbmVyYXRlZCBjb2RlXG4gKiBAcGFyYW0gYVJlbGF0aXZlUGF0aCBPcHRpb25hbC4gVGhlIHBhdGggdGhhdCByZWxhdGl2ZSBzb3VyY2VzIGluIHRoZVxuICogICAgICAgIFNvdXJjZU1hcENvbnN1bWVyIHNob3VsZCBiZSByZWxhdGl2ZSB0by5cbiAqL1xuU291cmNlTm9kZS5mcm9tU3RyaW5nV2l0aFNvdXJjZU1hcCA9XG4gIGZ1bmN0aW9uIFNvdXJjZU5vZGVfZnJvbVN0cmluZ1dpdGhTb3VyY2VNYXAoYUdlbmVyYXRlZENvZGUsIGFTb3VyY2VNYXBDb25zdW1lciwgYVJlbGF0aXZlUGF0aCkge1xuICAgIC8vIFRoZSBTb3VyY2VOb2RlIHdlIHdhbnQgdG8gZmlsbCB3aXRoIHRoZSBnZW5lcmF0ZWQgY29kZVxuICAgIC8vIGFuZCB0aGUgU291cmNlTWFwXG4gICAgdmFyIG5vZGUgPSBuZXcgU291cmNlTm9kZSgpO1xuXG4gICAgLy8gQWxsIGV2ZW4gaW5kaWNlcyBvZiB0aGlzIGFycmF5IGFyZSBvbmUgbGluZSBvZiB0aGUgZ2VuZXJhdGVkIGNvZGUsXG4gICAgLy8gd2hpbGUgYWxsIG9kZCBpbmRpY2VzIGFyZSB0aGUgbmV3bGluZXMgYmV0d2VlbiB0d28gYWRqYWNlbnQgbGluZXNcbiAgICAvLyAoc2luY2UgYFJFR0VYX05FV0xJTkVgIGNhcHR1cmVzIGl0cyBtYXRjaCkuXG4gICAgLy8gUHJvY2Vzc2VkIGZyYWdtZW50cyBhcmUgYWNjZXNzZWQgYnkgY2FsbGluZyBgc2hpZnROZXh0TGluZWAuXG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzID0gYUdlbmVyYXRlZENvZGUuc3BsaXQoUkVHRVhfTkVXTElORSk7XG4gICAgdmFyIHJlbWFpbmluZ0xpbmVzSW5kZXggPSAwO1xuICAgIHZhciBzaGlmdE5leHRMaW5lID0gZnVuY3Rpb24oKSB7XG4gICAgICB2YXIgbGluZUNvbnRlbnRzID0gZ2V0TmV4dExpbmUoKTtcbiAgICAgIC8vIFRoZSBsYXN0IGxpbmUgb2YgYSBmaWxlIG1pZ2h0IG5vdCBoYXZlIGEgbmV3bGluZS5cbiAgICAgIHZhciBuZXdMaW5lID0gZ2V0TmV4dExpbmUoKSB8fCBcIlwiO1xuICAgICAgcmV0dXJuIGxpbmVDb250ZW50cyArIG5ld0xpbmU7XG5cbiAgICAgIGZ1bmN0aW9uIGdldE5leHRMaW5lKCkge1xuICAgICAgICByZXR1cm4gcmVtYWluaW5nTGluZXNJbmRleCA8IHJlbWFpbmluZ0xpbmVzLmxlbmd0aCA/XG4gICAgICAgICAgICByZW1haW5pbmdMaW5lc1tyZW1haW5pbmdMaW5lc0luZGV4KytdIDogdW5kZWZpbmVkO1xuICAgICAgfVxuICAgIH07XG5cbiAgICAvLyBXZSBuZWVkIHRvIHJlbWVtYmVyIHRoZSBwb3NpdGlvbiBvZiBcInJlbWFpbmluZ0xpbmVzXCJcbiAgICB2YXIgbGFzdEdlbmVyYXRlZExpbmUgPSAxLCBsYXN0R2VuZXJhdGVkQ29sdW1uID0gMDtcblxuICAgIC8vIFRoZSBnZW5lcmF0ZSBTb3VyY2VOb2RlcyB3ZSBuZWVkIGEgY29kZSByYW5nZS5cbiAgICAvLyBUbyBleHRyYWN0IGl0IGN1cnJlbnQgYW5kIGxhc3QgbWFwcGluZyBpcyB1c2VkLlxuICAgIC8vIEhlcmUgd2Ugc3RvcmUgdGhlIGxhc3QgbWFwcGluZy5cbiAgICB2YXIgbGFzdE1hcHBpbmcgPSBudWxsO1xuXG4gICAgYVNvdXJjZU1hcENvbnN1bWVyLmVhY2hNYXBwaW5nKGZ1bmN0aW9uIChtYXBwaW5nKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcgIT09IG51bGwpIHtcbiAgICAgICAgLy8gV2UgYWRkIHRoZSBjb2RlIGZyb20gXCJsYXN0TWFwcGluZ1wiIHRvIFwibWFwcGluZ1wiOlxuICAgICAgICAvLyBGaXJzdCBjaGVjayBpZiB0aGVyZSBpcyBhIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgIGlmIChsYXN0R2VuZXJhdGVkTGluZSA8IG1hcHBpbmcuZ2VuZXJhdGVkTGluZSkge1xuICAgICAgICAgIC8vIEFzc29jaWF0ZSBmaXJzdCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBzaGlmdE5leHRMaW5lKCkpO1xuICAgICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICAgICAgbGFzdEdlbmVyYXRlZENvbHVtbiA9IDA7XG4gICAgICAgICAgLy8gVGhlIHJlbWFpbmluZyBjb2RlIGlzIGFkZGVkIHdpdGhvdXQgbWFwcGluZ1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIC8vIFRoZXJlIGlzIG5vIG5ldyBsaW5lIGluIGJldHdlZW4uXG4gICAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSBjb2RlIGJldHdlZW4gXCJsYXN0R2VuZXJhdGVkQ29sdW1uXCIgYW5kXG4gICAgICAgICAgLy8gXCJtYXBwaW5nLmdlbmVyYXRlZENvbHVtblwiIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgICAgdmFyIG5leHRMaW5lID0gcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF07XG4gICAgICAgICAgdmFyIGNvZGUgPSBuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4gLVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxhc3RHZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICAgIHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdID0gbmV4dExpbmUuc3Vic3RyKG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uIC1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uKTtcbiAgICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICAgICAgYWRkTWFwcGluZ1dpdGhDb2RlKGxhc3RNYXBwaW5nLCBjb2RlKTtcbiAgICAgICAgICAvLyBObyBtb3JlIHJlbWFpbmluZyBjb2RlLCBjb250aW51ZVxuICAgICAgICAgIGxhc3RNYXBwaW5nID0gbWFwcGluZztcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICAgIC8vIFdlIGFkZCB0aGUgZ2VuZXJhdGVkIGNvZGUgdW50aWwgdGhlIGZpcnN0IG1hcHBpbmdcbiAgICAgIC8vIHRvIHRoZSBTb3VyY2VOb2RlIHdpdGhvdXQgYW55IG1hcHBpbmcuXG4gICAgICAvLyBFYWNoIGxpbmUgaXMgYWRkZWQgYXMgc2VwYXJhdGUgc3RyaW5nLlxuICAgICAgd2hpbGUgKGxhc3RHZW5lcmF0ZWRMaW5lIDwgbWFwcGluZy5nZW5lcmF0ZWRMaW5lKSB7XG4gICAgICAgIG5vZGUuYWRkKHNoaWZ0TmV4dExpbmUoKSk7XG4gICAgICAgIGxhc3RHZW5lcmF0ZWRMaW5lKys7XG4gICAgICB9XG4gICAgICBpZiAobGFzdEdlbmVyYXRlZENvbHVtbiA8IG1hcHBpbmcuZ2VuZXJhdGVkQ29sdW1uKSB7XG4gICAgICAgIHZhciBuZXh0TGluZSA9IHJlbWFpbmluZ0xpbmVzW3JlbWFpbmluZ0xpbmVzSW5kZXhdO1xuICAgICAgICBub2RlLmFkZChuZXh0TGluZS5zdWJzdHIoMCwgbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pKTtcbiAgICAgICAgcmVtYWluaW5nTGluZXNbcmVtYWluaW5nTGluZXNJbmRleF0gPSBuZXh0TGluZS5zdWJzdHIobWFwcGluZy5nZW5lcmF0ZWRDb2x1bW4pO1xuICAgICAgICBsYXN0R2VuZXJhdGVkQ29sdW1uID0gbWFwcGluZy5nZW5lcmF0ZWRDb2x1bW47XG4gICAgICB9XG4gICAgICBsYXN0TWFwcGluZyA9IG1hcHBpbmc7XG4gICAgfSwgdGhpcyk7XG4gICAgLy8gV2UgaGF2ZSBwcm9jZXNzZWQgYWxsIG1hcHBpbmdzLlxuICAgIGlmIChyZW1haW5pbmdMaW5lc0luZGV4IDwgcmVtYWluaW5nTGluZXMubGVuZ3RoKSB7XG4gICAgICBpZiAobGFzdE1hcHBpbmcpIHtcbiAgICAgICAgLy8gQXNzb2NpYXRlIHRoZSByZW1haW5pbmcgY29kZSBpbiB0aGUgY3VycmVudCBsaW5lIHdpdGggXCJsYXN0TWFwcGluZ1wiXG4gICAgICAgIGFkZE1hcHBpbmdXaXRoQ29kZShsYXN0TWFwcGluZywgc2hpZnROZXh0TGluZSgpKTtcbiAgICAgIH1cbiAgICAgIC8vIGFuZCBhZGQgdGhlIHJlbWFpbmluZyBsaW5lcyB3aXRob3V0IGFueSBtYXBwaW5nXG4gICAgICBub2RlLmFkZChyZW1haW5pbmdMaW5lcy5zcGxpY2UocmVtYWluaW5nTGluZXNJbmRleCkuam9pbihcIlwiKSk7XG4gICAgfVxuXG4gICAgLy8gQ29weSBzb3VyY2VzQ29udGVudCBpbnRvIFNvdXJjZU5vZGVcbiAgICBhU291cmNlTWFwQ29uc3VtZXIuc291cmNlcy5mb3JFYWNoKGZ1bmN0aW9uIChzb3VyY2VGaWxlKSB7XG4gICAgICB2YXIgY29udGVudCA9IGFTb3VyY2VNYXBDb25zdW1lci5zb3VyY2VDb250ZW50Rm9yKHNvdXJjZUZpbGUpO1xuICAgICAgaWYgKGNvbnRlbnQgIT0gbnVsbCkge1xuICAgICAgICBpZiAoYVJlbGF0aXZlUGF0aCAhPSBudWxsKSB7XG4gICAgICAgICAgc291cmNlRmlsZSA9IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBzb3VyY2VGaWxlKTtcbiAgICAgICAgfVxuICAgICAgICBub2RlLnNldFNvdXJjZUNvbnRlbnQoc291cmNlRmlsZSwgY29udGVudCk7XG4gICAgICB9XG4gICAgfSk7XG5cbiAgICByZXR1cm4gbm9kZTtcblxuICAgIGZ1bmN0aW9uIGFkZE1hcHBpbmdXaXRoQ29kZShtYXBwaW5nLCBjb2RlKSB7XG4gICAgICBpZiAobWFwcGluZyA9PT0gbnVsbCB8fCBtYXBwaW5nLnNvdXJjZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgIG5vZGUuYWRkKGNvZGUpO1xuICAgICAgfSBlbHNlIHtcbiAgICAgICAgdmFyIHNvdXJjZSA9IGFSZWxhdGl2ZVBhdGhcbiAgICAgICAgICA/IHV0aWwuam9pbihhUmVsYXRpdmVQYXRoLCBtYXBwaW5nLnNvdXJjZSlcbiAgICAgICAgICA6IG1hcHBpbmcuc291cmNlO1xuICAgICAgICBub2RlLmFkZChuZXcgU291cmNlTm9kZShtYXBwaW5nLm9yaWdpbmFsTGluZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbWFwcGluZy5vcmlnaW5hbENvbHVtbixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc291cmNlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtYXBwaW5nLm5hbWUpKTtcbiAgICAgIH1cbiAgICB9XG4gIH07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoaXMgc291cmNlIG5vZGUuXG4gKlxuICogQHBhcmFtIGFDaHVuayBBIHN0cmluZyBzbmlwcGV0IG9mIGdlbmVyYXRlZCBKUyBjb2RlLCBhbm90aGVyIGluc3RhbmNlIG9mXG4gKiAgICAgICAgU291cmNlTm9kZSwgb3IgYW4gYXJyYXkgd2hlcmUgZWFjaCBtZW1iZXIgaXMgb25lIG9mIHRob3NlIHRoaW5ncy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUuYWRkID0gZnVuY3Rpb24gU291cmNlTm9kZV9hZGQoYUNodW5rKSB7XG4gIGlmIChBcnJheS5pc0FycmF5KGFDaHVuaykpIHtcbiAgICBhQ2h1bmsuZm9yRWFjaChmdW5jdGlvbiAoY2h1bmspIHtcbiAgICAgIHRoaXMuYWRkKGNodW5rKTtcbiAgICB9LCB0aGlzKTtcbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgaWYgKGFDaHVuaykge1xuICAgICAgdGhpcy5jaGlsZHJlbi5wdXNoKGFDaHVuayk7XG4gICAgfVxuICB9XG4gIGVsc2Uge1xuICAgIHRocm93IG5ldyBUeXBlRXJyb3IoXG4gICAgICBcIkV4cGVjdGVkIGEgU291cmNlTm9kZSwgc3RyaW5nLCBvciBhbiBhcnJheSBvZiBTb3VyY2VOb2RlcyBhbmQgc3RyaW5ncy4gR290IFwiICsgYUNodW5rXG4gICAgKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogQWRkIGEgY2h1bmsgb2YgZ2VuZXJhdGVkIEpTIHRvIHRoZSBiZWdpbm5pbmcgb2YgdGhpcyBzb3VyY2Ugbm9kZS5cbiAqXG4gKiBAcGFyYW0gYUNodW5rIEEgc3RyaW5nIHNuaXBwZXQgb2YgZ2VuZXJhdGVkIEpTIGNvZGUsIGFub3RoZXIgaW5zdGFuY2Ugb2ZcbiAqICAgICAgICBTb3VyY2VOb2RlLCBvciBhbiBhcnJheSB3aGVyZSBlYWNoIG1lbWJlciBpcyBvbmUgb2YgdGhvc2UgdGhpbmdzLlxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5wcmVwZW5kID0gZnVuY3Rpb24gU291cmNlTm9kZV9wcmVwZW5kKGFDaHVuaykge1xuICBpZiAoQXJyYXkuaXNBcnJheShhQ2h1bmspKSB7XG4gICAgZm9yICh2YXIgaSA9IGFDaHVuay5sZW5ndGgtMTsgaSA+PSAwOyBpLS0pIHtcbiAgICAgIHRoaXMucHJlcGVuZChhQ2h1bmtbaV0pO1xuICAgIH1cbiAgfVxuICBlbHNlIGlmIChhQ2h1bmtbaXNTb3VyY2VOb2RlXSB8fCB0eXBlb2YgYUNodW5rID09PSBcInN0cmluZ1wiKSB7XG4gICAgdGhpcy5jaGlsZHJlbi51bnNoaWZ0KGFDaHVuayk7XG4gIH1cbiAgZWxzZSB7XG4gICAgdGhyb3cgbmV3IFR5cGVFcnJvcihcbiAgICAgIFwiRXhwZWN0ZWQgYSBTb3VyY2VOb2RlLCBzdHJpbmcsIG9yIGFuIGFycmF5IG9mIFNvdXJjZU5vZGVzIGFuZCBzdHJpbmdzLiBHb3QgXCIgKyBhQ2h1bmtcbiAgICApO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBXYWxrIG92ZXIgdGhlIHRyZWUgb2YgSlMgc25pcHBldHMgaW4gdGhpcyBub2RlIGFuZCBpdHMgY2hpbGRyZW4uIFRoZVxuICogd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgb25jZSBmb3IgZWFjaCBzbmlwcGV0IG9mIEpTIGFuZCBpcyBwYXNzZWQgdGhhdFxuICogc25pcHBldCBhbmQgdGhlIGl0cyBvcmlnaW5hbCBhc3NvY2lhdGVkIHNvdXJjZSdzIGxpbmUvY29sdW1uIGxvY2F0aW9uLlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2FsayA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfd2FsayhhRm4pIHtcbiAgdmFyIGNodW5rO1xuICBmb3IgKHZhciBpID0gMCwgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7IGkgPCBsZW47IGkrKykge1xuICAgIGNodW5rID0gdGhpcy5jaGlsZHJlbltpXTtcbiAgICBpZiAoY2h1bmtbaXNTb3VyY2VOb2RlXSkge1xuICAgICAgY2h1bmsud2FsayhhRm4pO1xuICAgIH1cbiAgICBlbHNlIHtcbiAgICAgIGlmIChjaHVuayAhPT0gJycpIHtcbiAgICAgICAgYUZuKGNodW5rLCB7IHNvdXJjZTogdGhpcy5zb3VyY2UsXG4gICAgICAgICAgICAgICAgICAgICBsaW5lOiB0aGlzLmxpbmUsXG4gICAgICAgICAgICAgICAgICAgICBjb2x1bW46IHRoaXMuY29sdW1uLFxuICAgICAgICAgICAgICAgICAgICAgbmFtZTogdGhpcy5uYW1lIH0pO1xuICAgICAgfVxuICAgIH1cbiAgfVxufTtcblxuLyoqXG4gKiBMaWtlIGBTdHJpbmcucHJvdG90eXBlLmpvaW5gIGV4Y2VwdCBmb3IgU291cmNlTm9kZXMuIEluc2VydHMgYGFTdHJgIGJldHdlZW5cbiAqIGVhY2ggb2YgYHRoaXMuY2hpbGRyZW5gLlxuICpcbiAqIEBwYXJhbSBhU2VwIFRoZSBzZXBhcmF0b3IuXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLmpvaW4gPSBmdW5jdGlvbiBTb3VyY2VOb2RlX2pvaW4oYVNlcCkge1xuICB2YXIgbmV3Q2hpbGRyZW47XG4gIHZhciBpO1xuICB2YXIgbGVuID0gdGhpcy5jaGlsZHJlbi5sZW5ndGg7XG4gIGlmIChsZW4gPiAwKSB7XG4gICAgbmV3Q2hpbGRyZW4gPSBbXTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgbGVuLTE7IGkrKykge1xuICAgICAgbmV3Q2hpbGRyZW4ucHVzaCh0aGlzLmNoaWxkcmVuW2ldKTtcbiAgICAgIG5ld0NoaWxkcmVuLnB1c2goYVNlcCk7XG4gICAgfVxuICAgIG5ld0NoaWxkcmVuLnB1c2godGhpcy5jaGlsZHJlbltpXSk7XG4gICAgdGhpcy5jaGlsZHJlbiA9IG5ld0NoaWxkcmVuO1xuICB9XG4gIHJldHVybiB0aGlzO1xufTtcblxuLyoqXG4gKiBDYWxsIFN0cmluZy5wcm90b3R5cGUucmVwbGFjZSBvbiB0aGUgdmVyeSByaWdodC1tb3N0IHNvdXJjZSBzbmlwcGV0LiBVc2VmdWxcbiAqIGZvciB0cmltbWluZyB3aGl0ZXNwYWNlIGZyb20gdGhlIGVuZCBvZiBhIHNvdXJjZSBub2RlLCBldGMuXG4gKlxuICogQHBhcmFtIGFQYXR0ZXJuIFRoZSBwYXR0ZXJuIHRvIHJlcGxhY2UuXG4gKiBAcGFyYW0gYVJlcGxhY2VtZW50IFRoZSB0aGluZyB0byByZXBsYWNlIHRoZSBwYXR0ZXJuIHdpdGguXG4gKi9cblNvdXJjZU5vZGUucHJvdG90eXBlLnJlcGxhY2VSaWdodCA9IGZ1bmN0aW9uIFNvdXJjZU5vZGVfcmVwbGFjZVJpZ2h0KGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpIHtcbiAgdmFyIGxhc3RDaGlsZCA9IHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXTtcbiAgaWYgKGxhc3RDaGlsZFtpc1NvdXJjZU5vZGVdKSB7XG4gICAgbGFzdENoaWxkLnJlcGxhY2VSaWdodChhUGF0dGVybiwgYVJlcGxhY2VtZW50KTtcbiAgfVxuICBlbHNlIGlmICh0eXBlb2YgbGFzdENoaWxkID09PSAnc3RyaW5nJykge1xuICAgIHRoaXMuY2hpbGRyZW5bdGhpcy5jaGlsZHJlbi5sZW5ndGggLSAxXSA9IGxhc3RDaGlsZC5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpO1xuICB9XG4gIGVsc2Uge1xuICAgIHRoaXMuY2hpbGRyZW4ucHVzaCgnJy5yZXBsYWNlKGFQYXR0ZXJuLCBhUmVwbGFjZW1lbnQpKTtcbiAgfVxuICByZXR1cm4gdGhpcztcbn07XG5cbi8qKlxuICogU2V0IHRoZSBzb3VyY2UgY29udGVudCBmb3IgYSBzb3VyY2UgZmlsZS4gVGhpcyB3aWxsIGJlIGFkZGVkIHRvIHRoZSBTb3VyY2VNYXBHZW5lcmF0b3JcbiAqIGluIHRoZSBzb3VyY2VzQ29udGVudCBmaWVsZC5cbiAqXG4gKiBAcGFyYW0gYVNvdXJjZUZpbGUgVGhlIGZpbGVuYW1lIG9mIHRoZSBzb3VyY2UgZmlsZVxuICogQHBhcmFtIGFTb3VyY2VDb250ZW50IFRoZSBjb250ZW50IG9mIHRoZSBzb3VyY2UgZmlsZVxuICovXG5Tb3VyY2VOb2RlLnByb3RvdHlwZS5zZXRTb3VyY2VDb250ZW50ID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV9zZXRTb3VyY2VDb250ZW50KGFTb3VyY2VGaWxlLCBhU291cmNlQ29udGVudCkge1xuICAgIHRoaXMuc291cmNlQ29udGVudHNbdXRpbC50b1NldFN0cmluZyhhU291cmNlRmlsZSldID0gYVNvdXJjZUNvbnRlbnQ7XG4gIH07XG5cbi8qKlxuICogV2FsayBvdmVyIHRoZSB0cmVlIG9mIFNvdXJjZU5vZGVzLiBUaGUgd2Fsa2luZyBmdW5jdGlvbiBpcyBjYWxsZWQgZm9yIGVhY2hcbiAqIHNvdXJjZSBmaWxlIGNvbnRlbnQgYW5kIGlzIHBhc3NlZCB0aGUgZmlsZW5hbWUgYW5kIHNvdXJjZSBjb250ZW50LlxuICpcbiAqIEBwYXJhbSBhRm4gVGhlIHRyYXZlcnNhbCBmdW5jdGlvbi5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUud2Fsa1NvdXJjZUNvbnRlbnRzID1cbiAgZnVuY3Rpb24gU291cmNlTm9kZV93YWxrU291cmNlQ29udGVudHMoYUZuKSB7XG4gICAgZm9yICh2YXIgaSA9IDAsIGxlbiA9IHRoaXMuY2hpbGRyZW4ubGVuZ3RoOyBpIDwgbGVuOyBpKyspIHtcbiAgICAgIGlmICh0aGlzLmNoaWxkcmVuW2ldW2lzU291cmNlTm9kZV0pIHtcbiAgICAgICAgdGhpcy5jaGlsZHJlbltpXS53YWxrU291cmNlQ29udGVudHMoYUZuKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICB2YXIgc291cmNlcyA9IE9iamVjdC5rZXlzKHRoaXMuc291cmNlQ29udGVudHMpO1xuICAgIGZvciAodmFyIGkgPSAwLCBsZW4gPSBzb3VyY2VzLmxlbmd0aDsgaSA8IGxlbjsgaSsrKSB7XG4gICAgICBhRm4odXRpbC5mcm9tU2V0U3RyaW5nKHNvdXJjZXNbaV0pLCB0aGlzLnNvdXJjZUNvbnRlbnRzW3NvdXJjZXNbaV1dKTtcbiAgICB9XG4gIH07XG5cbi8qKlxuICogUmV0dXJuIHRoZSBzdHJpbmcgcmVwcmVzZW50YXRpb24gb2YgdGhpcyBzb3VyY2Ugbm9kZS4gV2Fsa3Mgb3ZlciB0aGUgdHJlZVxuICogYW5kIGNvbmNhdGVuYXRlcyBhbGwgdGhlIHZhcmlvdXMgc25pcHBldHMgdG9nZXRoZXIgdG8gb25lIHN0cmluZy5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmcgPSBmdW5jdGlvbiBTb3VyY2VOb2RlX3RvU3RyaW5nKCkge1xuICB2YXIgc3RyID0gXCJcIjtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaykge1xuICAgIHN0ciArPSBjaHVuaztcbiAgfSk7XG4gIHJldHVybiBzdHI7XG59O1xuXG4vKipcbiAqIFJldHVybnMgdGhlIHN0cmluZyByZXByZXNlbnRhdGlvbiBvZiB0aGlzIHNvdXJjZSBub2RlIGFsb25nIHdpdGggYSBzb3VyY2VcbiAqIG1hcC5cbiAqL1xuU291cmNlTm9kZS5wcm90b3R5cGUudG9TdHJpbmdXaXRoU291cmNlTWFwID0gZnVuY3Rpb24gU291cmNlTm9kZV90b1N0cmluZ1dpdGhTb3VyY2VNYXAoYUFyZ3MpIHtcbiAgdmFyIGdlbmVyYXRlZCA9IHtcbiAgICBjb2RlOiBcIlwiLFxuICAgIGxpbmU6IDEsXG4gICAgY29sdW1uOiAwXG4gIH07XG4gIHZhciBtYXAgPSBuZXcgU291cmNlTWFwR2VuZXJhdG9yKGFBcmdzKTtcbiAgdmFyIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgdmFyIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxMaW5lID0gbnVsbDtcbiAgdmFyIGxhc3RPcmlnaW5hbENvbHVtbiA9IG51bGw7XG4gIHZhciBsYXN0T3JpZ2luYWxOYW1lID0gbnVsbDtcbiAgdGhpcy53YWxrKGZ1bmN0aW9uIChjaHVuaywgb3JpZ2luYWwpIHtcbiAgICBnZW5lcmF0ZWQuY29kZSArPSBjaHVuaztcbiAgICBpZiAob3JpZ2luYWwuc291cmNlICE9PSBudWxsXG4gICAgICAgICYmIG9yaWdpbmFsLmxpbmUgIT09IG51bGxcbiAgICAgICAgJiYgb3JpZ2luYWwuY29sdW1uICE9PSBudWxsKSB7XG4gICAgICBpZihsYXN0T3JpZ2luYWxTb3VyY2UgIT09IG9yaWdpbmFsLnNvdXJjZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsTGluZSAhPT0gb3JpZ2luYWwubGluZVxuICAgICAgICAgfHwgbGFzdE9yaWdpbmFsQ29sdW1uICE9PSBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgIHx8IGxhc3RPcmlnaW5hbE5hbWUgIT09IG9yaWdpbmFsLm5hbWUpIHtcbiAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgIHNvdXJjZTogb3JpZ2luYWwuc291cmNlLFxuICAgICAgICAgIG9yaWdpbmFsOiB7XG4gICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgY29sdW1uOiBvcmlnaW5hbC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgbGluZTogZ2VuZXJhdGVkLmxpbmUsXG4gICAgICAgICAgICBjb2x1bW46IGdlbmVyYXRlZC5jb2x1bW5cbiAgICAgICAgICB9LFxuICAgICAgICAgIG5hbWU6IG9yaWdpbmFsLm5hbWVcbiAgICAgICAgfSk7XG4gICAgICB9XG4gICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBvcmlnaW5hbC5zb3VyY2U7XG4gICAgICBsYXN0T3JpZ2luYWxMaW5lID0gb3JpZ2luYWwubGluZTtcbiAgICAgIGxhc3RPcmlnaW5hbENvbHVtbiA9IG9yaWdpbmFsLmNvbHVtbjtcbiAgICAgIGxhc3RPcmlnaW5hbE5hbWUgPSBvcmlnaW5hbC5uYW1lO1xuICAgICAgc291cmNlTWFwcGluZ0FjdGl2ZSA9IHRydWU7XG4gICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICBtYXAuYWRkTWFwcGluZyh7XG4gICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgIGxpbmU6IGdlbmVyYXRlZC5saW5lLFxuICAgICAgICAgIGNvbHVtbjogZ2VuZXJhdGVkLmNvbHVtblxuICAgICAgICB9XG4gICAgICB9KTtcbiAgICAgIGxhc3RPcmlnaW5hbFNvdXJjZSA9IG51bGw7XG4gICAgICBzb3VyY2VNYXBwaW5nQWN0aXZlID0gZmFsc2U7XG4gICAgfVxuICAgIGZvciAodmFyIGlkeCA9IDAsIGxlbmd0aCA9IGNodW5rLmxlbmd0aDsgaWR4IDwgbGVuZ3RoOyBpZHgrKykge1xuICAgICAgaWYgKGNodW5rLmNoYXJDb2RlQXQoaWR4KSA9PT0gTkVXTElORV9DT0RFKSB7XG4gICAgICAgIGdlbmVyYXRlZC5saW5lKys7XG4gICAgICAgIGdlbmVyYXRlZC5jb2x1bW4gPSAwO1xuICAgICAgICAvLyBNYXBwaW5ncyBlbmQgYXQgZW9sXG4gICAgICAgIGlmIChpZHggKyAxID09PSBsZW5ndGgpIHtcbiAgICAgICAgICBsYXN0T3JpZ2luYWxTb3VyY2UgPSBudWxsO1xuICAgICAgICAgIHNvdXJjZU1hcHBpbmdBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmIChzb3VyY2VNYXBwaW5nQWN0aXZlKSB7XG4gICAgICAgICAgbWFwLmFkZE1hcHBpbmcoe1xuICAgICAgICAgICAgc291cmNlOiBvcmlnaW5hbC5zb3VyY2UsXG4gICAgICAgICAgICBvcmlnaW5hbDoge1xuICAgICAgICAgICAgICBsaW5lOiBvcmlnaW5hbC5saW5lLFxuICAgICAgICAgICAgICBjb2x1bW46IG9yaWdpbmFsLmNvbHVtblxuICAgICAgICAgICAgfSxcbiAgICAgICAgICAgIGdlbmVyYXRlZDoge1xuICAgICAgICAgICAgICBsaW5lOiBnZW5lcmF0ZWQubGluZSxcbiAgICAgICAgICAgICAgY29sdW1uOiBnZW5lcmF0ZWQuY29sdW1uXG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgbmFtZTogb3JpZ2luYWwubmFtZVxuICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICB9IGVsc2Uge1xuICAgICAgICBnZW5lcmF0ZWQuY29sdW1uKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcbiAgdGhpcy53YWxrU291cmNlQ29udGVudHMoZnVuY3Rpb24gKHNvdXJjZUZpbGUsIHNvdXJjZUNvbnRlbnQpIHtcbiAgICBtYXAuc2V0U291cmNlQ29udGVudChzb3VyY2VGaWxlLCBzb3VyY2VDb250ZW50KTtcbiAgfSk7XG5cbiAgcmV0dXJuIHsgY29kZTogZ2VuZXJhdGVkLmNvZGUsIG1hcDogbWFwIH07XG59O1xuXG5leHBvcnRzLlNvdXJjZU5vZGUgPSBTb3VyY2VOb2RlO1xuXG5cblxuLy8vLy8vLy8vLy8vLy8vLy8vXG4vLyBXRUJQQUNLIEZPT1RFUlxuLy8gLi9saWIvc291cmNlLW5vZGUuanNcbi8vIG1vZHVsZSBpZCA9IDEwXG4vLyBtb2R1bGUgY2h1bmtzID0gMCJdLCJzb3VyY2VSb290IjoiIn0= \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.js b/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.js deleted file mode 100644 index 4e630e29434ca587a468ecc1b56057029748b1d9..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.js +++ /dev/null @@ -1,3090 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else if(typeof exports === 'object') - exports["sourceMap"] = factory(); - else - root["sourceMap"] = factory(); -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - /* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ - exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; - exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; - exports.SourceNode = __webpack_require__(10).SourceNode; - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var base64VLQ = __webpack_require__(2); - var util = __webpack_require__(4); - var ArraySet = __webpack_require__(5).ArraySet; - var MappingList = __webpack_require__(6).MappingList; - - /** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ - function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; - } - - SourceMapGenerator.prototype._version = 3; - - /** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ - SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - - /** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ - SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - - /** - * Set the source content for a source file. - */ - SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - - /** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ - SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - - /** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ - SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - - /** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ - SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - - SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - - /** - * Externalize the source map. - */ - SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - - /** - * Render the source map being generated to a string. - */ - SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - - exports.SourceMapGenerator = SourceMapGenerator; - - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - var base64 = __webpack_require__(3); - - // A single base 64 digit can contain 6 bits of data. For the base 64 variable - // length quantities we use in the source map spec, the first bit is the sign, - // the next four bits are the actual value, and the 6th bit is the - // continuation bit. The continuation bit tells us whether there are more - // digits in this value following this digit. - // - // Continuation - // | Sign - // | | - // V V - // 101011 - - var VLQ_BASE_SHIFT = 5; - - // binary: 100000 - var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - - // binary: 011111 - var VLQ_BASE_MASK = VLQ_BASE - 1; - - // binary: 100000 - var VLQ_CONTINUATION_BIT = VLQ_BASE; - - /** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ - function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; - } - - /** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ - function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; - } - - /** - * Returns the base 64 VLQ encoded value. - */ - exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; - }; - - /** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ - exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; - }; - - -/***/ }), -/* 3 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - - /** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ - exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); - }; - - /** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ - exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; - }; - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - /** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ - function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } - } - exports.getArg = getArg; - - var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; - var dataUrlRegexp = /^data:.+\,.+$/; - - function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; - } - exports.urlParse = urlParse; - - function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; - } - exports.urlGenerate = urlGenerate; - - /** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ - function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; - } - exports.normalize = normalize; - - /** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ - function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; - } - exports.join = join; - - exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); - }; - - /** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ - function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); - } - exports.relative = relative; - - var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); - }()); - - function identity (s) { - return s; - } - - /** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ - function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; - } - exports.toSetString = supportsNullProto ? identity : toSetString; - - function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; - } - exports.fromSetString = supportsNullProto ? identity : fromSetString; - - function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; - } - - /** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ - function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; - } - exports.compareByOriginalPositions = compareByOriginalPositions; - - /** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ - function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; - } - exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - - function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; - } - - /** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ - function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - } - exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util = __webpack_require__(4); - var has = Object.prototype.hasOwnProperty; - var hasNativeMap = typeof Map !== "undefined"; - - /** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ - function ArraySet() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); - } - - /** - * Static method for creating ArraySet instances from an existing array. - */ - ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; - }; - - /** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ - ArraySet.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; - }; - - /** - * Add the given string to this set. - * - * @param String aStr - */ - ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } - }; - - /** - * Is the given string a member of this set? - * - * @param String aStr - */ - ArraySet.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); - } - }; - - /** - * What is the index of the given string in the array? - * - * @param String aStr - */ - ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); - }; - - /** - * What is the element at the given index? - * - * @param Number aIdx - */ - ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); - }; - - /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ - ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); - }; - - exports.ArraySet = ArraySet; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util = __webpack_require__(4); - - /** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ - function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; - } - - /** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ - function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; - } - - /** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ - MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - - /** - * Add the given source mapping. - * - * @param Object aMapping - */ - MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } - }; - - /** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ - MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; - }; - - exports.MappingList = MappingList; - - -/***/ }), -/* 7 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var util = __webpack_require__(4); - var binarySearch = __webpack_require__(8); - var ArraySet = __webpack_require__(5).ArraySet; - var base64VLQ = __webpack_require__(2); - var quickSort = __webpack_require__(9).quickSort; - - function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); - } - - SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); - } - - /** - * The version of the source mapping spec that we are consuming. - */ - SourceMapConsumer.prototype._version = 3; - - // `__generatedMappings` and `__originalMappings` are arrays that hold the - // parsed mapping coordinates from the source map's "mappings" attribute. They - // are lazily instantiated, accessed via the `_generatedMappings` and - // `_originalMappings` getters respectively, and we only parse the mappings - // and create these arrays once queried for a source location. We jump through - // these hoops because there can be many thousands of mappings, and parsing - // them is expensive, so we only want to do it if we must. - // - // Each object in the arrays is of the form: - // - // { - // generatedLine: The line number in the generated code, - // generatedColumn: The column number in the generated code, - // source: The path to the original source file that generated this - // chunk of code, - // originalLine: The line number in the original source that - // corresponds to this chunk of generated code, - // originalColumn: The column number in the original source that - // corresponds to this chunk of generated code, - // name: The name of the original symbol which generated this chunk of - // code. - // } - // - // All properties except for `generatedLine` and `generatedColumn` can be - // `null`. - // - // `_generatedMappings` is ordered by the generated positions. - // - // `_originalMappings` is ordered by the original positions. - - SourceMapConsumer.prototype.__generatedMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } - }); - - SourceMapConsumer.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } - }); - - SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - - SourceMapConsumer.GENERATED_ORDER = 1; - SourceMapConsumer.ORIGINAL_ORDER = 2; - - SourceMapConsumer.GREATEST_LOWER_BOUND = 1; - SourceMapConsumer.LEAST_UPPER_BOUND = 2; - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - - /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; - } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - - exports.SourceMapConsumer = SourceMapConsumer; - - /** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ - function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; - } - - BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); - BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer - */ - BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - BasicSourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); - } - }); - - /** - * Provide the JIT with a nice shape / hidden class. - */ - function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - - /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ - BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - - /** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ - BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ - BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - - exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - - /** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ - function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); - } - - IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); - IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - - /** - * The version of the source mapping spec that we are consuming. - */ - IndexedSourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } - }); - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ - IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - - exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - exports.GREATEST_LOWER_BOUND = 1; - exports.LEAST_UPPER_BOUND = 2; - - /** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ - function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } - } - - /** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ - exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; - }; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - // It turns out that some (most?) JavaScript engines don't self-host - // `Array.prototype.sort`. This makes sense because C++ will likely remain - // faster than JS when doing raw CPU-intensive sorting. However, when using a - // custom comparator function, calling back and forth between the VM's C++ and - // JIT'd JS is rather slow *and* loses JIT type information, resulting in - // worse generated code for the comparator function than would be optimal. In - // fact, when sorting with a comparator, these costs outweigh the benefits of - // sorting in C++. By using our own JS-implemented Quick Sort (below), we get - // a ~3500ms mean speed-up in `bench/bench.html`. - - /** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ - function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; - } - - /** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ - function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); - } - - /** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ - function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } - } - - /** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ - exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); - }; - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - /* -*- Mode: js; js-indent-level: 2; -*- */ - /* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; - var util = __webpack_require__(4); - - // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other - // operating systems these days (capturing the result). - var REGEX_NEWLINE = /(\r?\n)/; - - // Newline character code for charCodeAt() comparisons - var NEWLINE_CODE = 10; - - // Private symbol for identifying `SourceNode`s when multiple versions of - // the source-map library are loaded. This MUST NOT CHANGE across - // versions! - var isSourceNode = "$$$isSourceNode$$$"; - - /** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ - function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); - } - - /** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ - SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - - /** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } - }; - - /** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ - SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; - }; - - /** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ - SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; - }; - - /** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ - SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - - /** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - - /** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ - SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; - }; - - /** - * Returns the string representation of this source node along with a source - * map. - */ - SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; - }; - - exports.SourceNode = SourceNode; - - -/***/ }) -/******/ ]) -}); -; \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.min.js b/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.min.js deleted file mode 100644 index f2a46bd02536a368382443b6bb9ade49ae158753..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/dist/source-map.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&r.setSourceContent(n,t)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if(n&&"number"!=typeof n.line&&"number"!=typeof n.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;f0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),a===-1)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a<=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(_))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(t<0)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(n<9)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=e.source-n.source;return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:e.name-n.name))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=e.source-n.source,0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:e.name-n.name))))}function f(e,n){return e===n?0:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}n.getArg=r;var m=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,_=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(m)},n.relative=a;var v=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=v?u:l,n.fromSetString=v?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d},function(e,n,r){function t(){this._array=[],this._set=s?new Map:Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty,s="undefined"!=typeof Map;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;o=0)return n}else{var r=o.toSetString(e);if(i.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e){var n=e;return"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=n.sections?new s(n):new o(n)}function o(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=a.getArg(n,"version"),t=a.getArg(n,"sources"),o=a.getArg(n,"names",[]),i=a.getArg(n,"sourceRoot",null),s=a.getArg(n,"sourcesContent",null),u=a.getArg(n,"mappings"),c=a.getArg(n,"file",null);if(r!=this._version)throw new Error("Unsupported version: "+r);t=t.map(String).map(a.normalize).map(function(e){return i&&a.isAbsolute(i)&&a.isAbsolute(e)?a.relative(i,e):e}),this._names=l.fromArray(o.map(String),!0),this._sources=l.fromArray(t,!0),this.sourceRoot=i,this.sourcesContent=s,this._mappings=u,this.file=c}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=a.getArg(n,"version"),o=a.getArg(n,"sections");if(r!=this._version)throw new Error("Unsupported version: "+r);this._sources=new l,this._names=new l;var i={line:-1,column:0};this._sections=o.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var n=a.getArg(e,"offset"),r=a.getArg(n,"line"),o=a.getArg(n,"column");if(r=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.fromSourceMap=function(e){var n=Object.create(o.prototype),r=n._names=l.fromArray(e._names.toArray(),!0),t=n._sources=l.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file;for(var s=e._mappings.toArray().slice(),u=n.__generatedMappings=[],c=n.__originalMappings=[],p=0,h=s.length;p1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),S.push(r),"number"==typeof r.originalLine&&A.push(r)}g(S,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=S,g(A,a.compareByOriginalPositions),this.__originalMappings=A},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),null!=this.sourceRoot&&(i=a.join(this.sourceRoot,i)));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=a.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var r;if(null!=this.sourceRoot&&(r=a.urlParse(this.sourceRoot))){var t=e.replace(/^file:\/\//,"");if("file"==r.scheme&&this._sources.has(t))return this.sourcesContent[this._sources.indexOf(t)];if((!r.path||"/"==r.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(n)return null;throw new Error('"'+e+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),!this._sources.has(n))return{line:null,column:null,lastColumn:null};n=this._sources.indexOf(n);var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(s<0)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(i=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;r0){for(n=[],r=0;r= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); -}; - -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; - -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -exports.ArraySet = ArraySet; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/base64-vlq.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/base64-vlq.js deleted file mode 100644 index 612b404018ece911ab71fc0a8db326d16e6b1287..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/base64-vlq.js +++ /dev/null @@ -1,140 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -var base64 = require('./base64'); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; - -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; - -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; - -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} - -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; - -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/base64.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/base64.js deleted file mode 100644 index 8aa86b30264363990334a7df0aa0d0c9cc1aecfc..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/base64.js +++ /dev/null @@ -1,67 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/binary-search.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/binary-search.js deleted file mode 100644 index 010ac941e1568d59c89b67cb649051a14608ee79..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/binary-search.js +++ /dev/null @@ -1,111 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; - -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } -} - -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; -}; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/mapping-list.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/mapping-list.js deleted file mode 100644 index 06d1274a025a8a30879f31c9c6703a14f79f73b9..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/mapping-list.js +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); - -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} - -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} - -/** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; - -/** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ -MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -exports.MappingList = MappingList; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/quick-sort.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/quick-sort.js deleted file mode 100644 index 6a7caadbbdbea1865cfb947cb21fbf0c8da1289a..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/quick-sort.js +++ /dev/null @@ -1,114 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - -/** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} - -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); -} - -/** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } -} - -/** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-map-consumer.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-map-consumer.js deleted file mode 100644 index 6abcc280eea1603086852633e89ec60bacf81098..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-map-consumer.js +++ /dev/null @@ -1,1082 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); -var binarySearch = require('./binary-search'); -var ArraySet = require('./array-set').ArraySet; -var base64VLQ = require('./base64-vlq'); -var quickSort = require('./quick-sort').quickSort; - -function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); -} - -SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); -} - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. - -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } -}); - -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } -}); - -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; - -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; - } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -exports.SourceMapConsumer = SourceMapConsumer; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; -} - -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); - } -}); - -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); -} - -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } -}); - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-map-generator.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-map-generator.js deleted file mode 100644 index aff1e7fb268acc98f852ce40f90118ccf4bfa145..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-map-generator.js +++ /dev/null @@ -1,416 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var base64VLQ = require('./base64-vlq'); -var util = require('./util'); -var ArraySet = require('./array-set').ArraySet; -var MappingList = require('./mapping-list').MappingList; - -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} - -SourceMapGenerator.prototype._version = 3; - -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - -/** - * Externalize the source map. - */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - -exports.SourceMapGenerator = SourceMapGenerator; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-node.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-node.js deleted file mode 100644 index d196a53f8c0eda12892613a2ed65b812db89c95d..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/source-node.js +++ /dev/null @@ -1,413 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; -var util = require('./util'); - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; - -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); -} - -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; - -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; - -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; -}; - -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; - -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; -}; - -exports.SourceNode = SourceNode; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/lib/util.js b/tools/node_modules/babel-eslint/node_modules/source-map/lib/util.js deleted file mode 100644 index 44e0e45205233ef28d7dbe96fbfe8b5ffc48af84..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/lib/util.js +++ /dev/null @@ -1,417 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; - -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; - -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; - -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; - -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; - -/** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; -} -exports.join = join; - -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); -}; - -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; - -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); - -function identity (s) { - return s; -} - -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; - -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; - -function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; -} - -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByOriginalPositions = compareByOriginalPositions; - -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; -} - -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/package.json b/tools/node_modules/babel-eslint/node_modules/source-map/package.json deleted file mode 100644 index 9e2674cec8bd3c0bcdc60f54df592e4fd9266b7b..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/package.json +++ /dev/null @@ -1,188 +0,0 @@ -{ - "author": { - "name": "Nick Fitzgerald", - "email": "nfitzgerald@mozilla.com" - }, - "bugs": { - "url": "https://github.com/mozilla/source-map/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Tobias Koppers", - "email": "tobias.koppers@googlemail.com" - }, - { - "name": "Duncan Beevers", - "email": "duncan@dweebd.com" - }, - { - "name": "Stephen Crane", - "email": "scrane@mozilla.com" - }, - { - "name": "Ryan Seddon", - "email": "seddon.ryan@gmail.com" - }, - { - "name": "Miles Elam", - "email": "miles.elam@deem.com" - }, - { - "name": "Mihai Bazon", - "email": "mihai.bazon@gmail.com" - }, - { - "name": "Michael Ficarra", - "email": "github.public.email@michael.ficarra.me" - }, - { - "name": "Todd Wolfson", - "email": "todd@twolfson.com" - }, - { - "name": "Alexander Solovyov", - "email": "alexander@solovyov.net" - }, - { - "name": "Felix Gnass", - "email": "fgnass@gmail.com" - }, - { - "name": "Conrad Irwin", - "email": "conrad.irwin@gmail.com" - }, - { - "name": "usrbincc", - "email": "usrbincc@yahoo.com" - }, - { - "name": "David Glasser", - "email": "glasser@davidglasser.net" - }, - { - "name": "Chase Douglas", - "email": "chase@newrelic.com" - }, - { - "name": "Evan Wallace", - "email": "evan.exe@gmail.com" - }, - { - "name": "Heather Arthur", - "email": "fayearthur@gmail.com" - }, - { - "name": "Hugh Kennedy", - "email": "hughskennedy@gmail.com" - }, - { - "name": "David Glasser", - "email": "glasser@davidglasser.net" - }, - { - "name": "Simon Lydell", - "email": "simon.lydell@gmail.com" - }, - { - "name": "Jmeas Smith", - "email": "jellyes2@gmail.com" - }, - { - "name": "Michael Z Goddard", - "email": "mzgoddard@gmail.com" - }, - { - "name": "azu", - "email": "azu@users.noreply.github.com" - }, - { - "name": "John Gozde", - "email": "john@gozde.ca" - }, - { - "name": "Adam Kirkton", - "email": "akirkton@truefitinnovation.com" - }, - { - "name": "Chris Montgomery", - "email": "christopher.montgomery@dowjones.com" - }, - { - "name": "J. Ryan Stinnett", - "email": "jryans@gmail.com" - }, - { - "name": "Jack Herrington", - "email": "jherrington@walmartlabs.com" - }, - { - "name": "Chris Truter", - "email": "jeffpalentine@gmail.com" - }, - { - "name": "Daniel Espeset", - "email": "daniel@danielespeset.com" - }, - { - "name": "Jamie Wong", - "email": "jamie.lf.wong@gmail.com" - }, - { - "name": "Eddy Bruël", - "email": "ejpbruel@mozilla.com" - }, - { - "name": "Hawken Rives", - "email": "hawkrives@gmail.com" - }, - { - "name": "Gilad Peleg", - "email": "giladp007@gmail.com" - }, - { - "name": "djchie", - "email": "djchie.dev@gmail.com" - }, - { - "name": "Gary Ye", - "email": "garysye@gmail.com" - }, - { - "name": "Nicolas LaleveÌe", - "email": "nicolas.lalevee@hibnet.org" - } - ], - "deprecated": false, - "description": "Generates and consumes source maps", - "devDependencies": { - "doctoc": "^0.15.0", - "webpack": "^1.12.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "source-map.js", - "lib/", - "dist/source-map.debug.js", - "dist/source-map.js", - "dist/source-map.min.js", - "dist/source-map.min.js.map" - ], - "homepage": "https://github.com/mozilla/source-map", - "license": "BSD-3-Clause", - "main": "./source-map.js", - "name": "source-map", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mozilla/source-map.git" - }, - "scripts": { - "build": "webpack --color", - "test": "npm run build && node test/run-tests.js", - "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" - }, - "typings": "source-map", - "version": "0.5.7" -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/source-map/source-map.js b/tools/node_modules/babel-eslint/node_modules/source-map/source-map.js deleted file mode 100644 index bc88fe820c87a217d27eb010281fe39b71163835..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/source-map/source-map.js +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; -exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; -exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/tools/node_modules/babel-eslint/node_modules/supports-color/browser.js b/tools/node_modules/babel-eslint/node_modules/supports-color/browser.js deleted file mode 100644 index 62afa3a7425dc6a1eeafd1333afc15d429c5d10d..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/supports-color/browser.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; -module.exports = { - stdout: false, - stderr: false -}; diff --git a/tools/node_modules/babel-eslint/node_modules/supports-color/index.js b/tools/node_modules/babel-eslint/node_modules/supports-color/index.js deleted file mode 100644 index 1704131bdf6c8f1bddd360ed0ce42185590d2787..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/supports-color/index.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; -const os = require('os'); -const hasFlag = require('has-flag'); - -const env = process.env; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } - - const min = forceColor ? 1 : 0; - - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - if (env.TERM === 'dumb') { - return min; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} - -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; diff --git a/tools/node_modules/babel-eslint/node_modules/supports-color/license b/tools/node_modules/babel-eslint/node_modules/supports-color/license deleted file mode 100644 index e7af2f77107d73046421ef56c4684cbfdd3c1e89..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/supports-color/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/node_modules/babel-eslint/node_modules/supports-color/package.json b/tools/node_modules/babel-eslint/node_modules/supports-color/package.json deleted file mode 100644 index 9e4eafa8573232c735ea1835222fc7696a7f537b..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/supports-color/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "browser": "browser.js", - "bugs": { - "url": "https://github.com/chalk/supports-color/issues" - }, - "bundleDependencies": false, - "dependencies": { - "has-flag": "^3.0.0" - }, - "deprecated": false, - "description": "Detect whether a terminal supports color", - "devDependencies": { - "ava": "^0.25.0", - "import-fresh": "^2.0.0", - "xo": "^0.20.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "browser.js" - ], - "homepage": "https://github.com/chalk/supports-color#readme", - "keywords": [ - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "ansi", - "styles", - "tty", - "rgb", - "256", - "shell", - "xterm", - "command-line", - "support", - "supports", - "capability", - "detect", - "truecolor", - "16m" - ], - "license": "MIT", - "name": "supports-color", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/supports-color.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "5.5.0" -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/supports-color/readme.md b/tools/node_modules/babel-eslint/node_modules/supports-color/readme.md deleted file mode 100644 index f6e40195730ae8c665bdd898cfe0442e9ac08105..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/supports-color/readme.md +++ /dev/null @@ -1,66 +0,0 @@ -# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) - -> Detect whether a terminal supports color - - -## Install - -``` -$ npm install supports-color -``` - - -## Usage - -```js -const supportsColor = require('supports-color'); - -if (supportsColor.stdout) { - console.log('Terminal stdout supports color'); -} - -if (supportsColor.stdout.has256) { - console.log('Terminal stdout supports 256 colors'); -} - -if (supportsColor.stderr.has16m) { - console.log('Terminal stderr supports 16 million colors (truecolor)'); -} -``` - - -## API - -Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. - -The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: - -- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) -- `.level = 2` and `.has256 = true`: 256 color support -- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) - - -## Info - -It obeys the `--color` and `--no-color` CLI flags. - -Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. - -Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. - - -## Related - -- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module -- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - - -## License - -MIT diff --git a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/index.js b/tools/node_modules/babel-eslint/node_modules/to-fast-properties/index.js deleted file mode 100644 index 028c88af01d817eb7db3df23d752f6f07d4aa0e7..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/index.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -let fastProto = null; - -// Creates an object with permanently fast properties in V8. See Toon Verwaest's -// post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62 -// for more details. Use %HasFastProperties(object) and the Node.js flag -// --allow-natives-syntax to check whether an object has fast properties. -function FastObject(o) { - // A prototype object will have "fast properties" enabled once it is checked - // against the inline property cache of a function, e.g. fastProto.property: - // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63 - if (fastProto !== null && typeof fastProto.property) { - const result = fastProto; - fastProto = FastObject.prototype = null; - return result; - } - fastProto = FastObject.prototype = o == null ? Object.create(null) : o; - return new FastObject; -} - -// Initialize the inline property cache of FastObject -FastObject(); - -module.exports = function toFastproperties(o) { - return FastObject(o); -}; diff --git a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/license b/tools/node_modules/babel-eslint/node_modules/to-fast-properties/license deleted file mode 100644 index cef79eff984180dee3928e099b70d943dfc912d2..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/license +++ /dev/null @@ -1,10 +0,0 @@ -MIT License - -Copyright (c) 2014 Petka Antonov - 2015 Sindre Sorhus - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/package.json b/tools/node_modules/babel-eslint/node_modules/to-fast-properties/package.json deleted file mode 100644 index 2c80c243891203ef4a37df4ce55f6df2be5daf44..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/to-fast-properties/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Force V8 to use fast properties for an object", - "devDependencies": { - "ava": "0.0.4" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/to-fast-properties#readme", - "keywords": [ - "object", - "obj", - "properties", - "props", - "v8", - "optimize", - "fast", - "convert", - "mode" - ], - "license": "MIT", - "name": "to-fast-properties", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/to-fast-properties.git" - }, - "scripts": { - "test": "node --allow-natives-syntax test.js" - }, - "version": "2.0.0" -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/readme.md b/tools/node_modules/babel-eslint/node_modules/to-fast-properties/readme.md deleted file mode 100644 index 692101d661d398cb14d0b1342fa108a35ed87299..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/to-fast-properties/readme.md +++ /dev/null @@ -1,37 +0,0 @@ -# to-fast-properties [![Build Status](https://travis-ci.org/sindresorhus/to-fast-properties.svg?branch=master)](https://travis-ci.org/sindresorhus/to-fast-properties) - -> Force V8 to use fast properties for an object - -[Read more.](http://stackoverflow.com/questions/24987896/) - -Use `%HasFastProperties(object)` and `--allow-natives-syntax` to check whether an object already has fast properties. - - -## Install - -``` -$ npm install --save to-fast-properties -``` - - -## Usage - -```js -const toFastProperties = require('to-fast-properties'); - -const obj = { - foo: true, - bar: true -}; - -delete obj.foo; -// `obj` now has slow properties - -toFastProperties(obj); -// `obj` now has fast properties -``` - - -## License - -MIT © Petka Antonov, John-David Dalton, Sindre Sorhus diff --git a/tools/node_modules/babel-eslint/node_modules/trim-right/index.js b/tools/node_modules/babel-eslint/node_modules/trim-right/index.js deleted file mode 100644 index 666f4b2f4eeb6ae87c057f76dc1e902e803f145c..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/trim-right/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; -module.exports = function (str) { - var tail = str.length; - - while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { - tail--; - } - - return str.slice(0, tail); -}; diff --git a/tools/node_modules/babel-eslint/node_modules/trim-right/license b/tools/node_modules/babel-eslint/node_modules/trim-right/license deleted file mode 100644 index 654d0bfe943437d43242325b1fbcff5f400d84ee..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/trim-right/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/tools/node_modules/babel-eslint/node_modules/trim-right/package.json b/tools/node_modules/babel-eslint/node_modules/trim-right/package.json deleted file mode 100644 index 4ed056783bb5846089aee0c82ae181c41418a101..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/trim-right/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/trim-right/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Similar to String#trim() but removes only whitespace on the right", - "devDependencies": { - "ava": "0.0.4" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/trim-right#readme", - "keywords": [ - "trim", - "right", - "string", - "str", - "util", - "utils", - "utility", - "whitespace", - "space", - "remove", - "delete" - ], - "license": "MIT", - "name": "trim-right", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/trim-right.git" - }, - "scripts": { - "test": "node test.js" - }, - "version": "1.0.1" -} \ No newline at end of file diff --git a/tools/node_modules/babel-eslint/node_modules/trim-right/readme.md b/tools/node_modules/babel-eslint/node_modules/trim-right/readme.md deleted file mode 100644 index 0a4438acd7a898395d15d01b5e34999155619e06..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/node_modules/trim-right/readme.md +++ /dev/null @@ -1,30 +0,0 @@ -# trim-right [![Build Status](https://travis-ci.org/sindresorhus/trim-right.svg?branch=master)](https://travis-ci.org/sindresorhus/trim-right) - -> Similar to [`String#trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) but removes only whitespace on the right - - -## Install - -``` -$ npm install --save trim-right -``` - - -## Usage - -```js -var trimRight = require('trim-right'); - -trimRight(' unicorn '); -//=> ' unicorn' -``` - - -## Related - -- [`trim-left`](https://github.com/sindresorhus/trim-left) - Similar to `String#trim()` but removes only whitespace on the left - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/tools/node_modules/babel-eslint/package.json b/tools/node_modules/babel-eslint/package.json deleted file mode 100644 index fae7c72dbbf113a06ccf556d6ff9db78d70d69f9..0000000000000000000000000000000000000000 --- a/tools/node_modules/babel-eslint/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bugs": { - "url": "https://github.com/babel/babel-eslint/issues" - }, - "bundleDependencies": false, - "dependencies": { - "@babel/code-frame": "^7.0.0", - "@babel/parser": "^7.0.0", - "@babel/traverse": "^7.0.0", - "@babel/types": "^7.0.0", - "eslint-visitor-keys": "^1.0.0", - "resolve": "^1.12.0" - }, - "deprecated": false, - "description": "Custom parser for ESLint", - "devDependencies": { - "babel-eslint": "^8.2.6", - "dedent": "^0.7.0", - "eslint": "^5.6.0", - "eslint-config-babel": "^7.0.1", - "eslint-plugin-flowtype": "^2.30.3", - "eslint-plugin-import": "^2.14.0", - "eslint-plugin-prettier": "^2.1.2", - "espree": "^3.5.2", - "husky": "^1.0.0-rc.13", - "lint-staged": "^7.2.2", - "mocha": "^5.0.1", - "prettier": "^1.4.4" - }, - "engines": { - "node": ">=6" - }, - "files": [ - "lib" - ], - "homepage": "https://github.com/babel/babel-eslint", - "license": "MIT", - "lint-staged": { - "*.js": [ - "eslint --format=codeframe --fix", - "git add" - ] - }, - "main": "lib/index.js", - "name": "babel-eslint", - "peerDependencies": { - "eslint": ">= 4.12.1" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/babel/babel-eslint.git" - }, - "scripts": { - "changelog": "git log `git describe --tags --abbrev=0`..HEAD --pretty=format:' * %s (%an)' | grep -v 'Merge pull request'", - "fix": "eslint lib test --fix", - "lint": "eslint lib test", - "precommit": "lint-staged", - "preversion": "npm test", - "test": "npm run lint && npm run test-only", - "test-only": "mocha && mocha --require test/fixtures/preprocess-to-patch.js" - }, - "version": "10.0.3" -} \ No newline at end of file diff --git a/tools/node_modules/eslint-plugin-node-core/index.js b/tools/node_modules/eslint-plugin-node-core/index.js deleted file mode 100644 index e27945688ee6917ff29e4380bc4b25de82d06a42..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint-plugin-node-core/index.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); - -let cache; -module.exports = { - get rules() { - const RULES_DIR = module.exports.RULES_DIR; - if (!RULES_DIR) - return {}; - - if (!cache) { - cache = {}; - const files = fs.readdirSync(RULES_DIR) - .filter(filename => filename.endsWith('.js')) - for (const file of files) { - const name = file.slice(0, -3); - cache[name] = require(path.resolve(RULES_DIR, file)); - } - } - return cache; - }, -}; diff --git a/tools/node_modules/eslint/LICENSE b/tools/node_modules/eslint/LICENSE deleted file mode 100644 index 7fe552a86615053f376bbc3f0aa87d5fd172edc4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright JS Foundation and other contributors, https://js.foundation - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/tools/node_modules/eslint/README.md b/tools/node_modules/eslint/README.md deleted file mode 100644 index 1f778efdf4b8d18862adabf034dc41021981259d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/README.md +++ /dev/null @@ -1,261 +0,0 @@ -[![NPM version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) -[![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) -[![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) -
-[![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) -[![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) -[![Follow us on Twitter](https://img.shields.io/twitter/follow/geteslint?label=Follow&style=social)](https://twitter.com/intent/user?screen_name=geteslint) - -# ESLint - -[Website](https://eslint.org) | -[Configuring](https://eslint.org/docs/user-guide/configuring) | -[Rules](https://eslint.org/docs/rules/) | -[Contributing](https://eslint.org/docs/developer-guide/contributing) | -[Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | -[Code of Conduct](https://js.foundation/community/code-of-conduct) | -[Twitter](https://twitter.com/geteslint) | -[Mailing List](https://groups.google.com/group/eslint) | -[Chat Room](https://eslint.org/chat) - -ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: - -* ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. -* ESLint uses an AST to evaluate patterns in code. -* ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. - -## Table of Contents - -1. [Installation and Usage](#installation-and-usage) -2. [Configuration](#configuration) -3. [Code of Conduct](#code-of-conduct) -4. [Filing Issues](#filing-issues) -5. [Frequently Asked Questions](#faq) -6. [Releases](#releases) -7. [Semantic Versioning Policy](#semantic-versioning-policy) -8. [License](#license) -9. [Team](#team) -10. [Sponsors](#sponsors) -11. [Technology Sponsors](#technology-sponsors) - -## Installation and Usage - -Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) - -You can install ESLint using npm: - -``` -$ npm install eslint --save-dev -``` - -You should then set up a configuration file: - -``` -$ ./node_modules/.bin/eslint --init -``` - -After that, you can run ESLint on any file or directory like this: - -``` -$ ./node_modules/.bin/eslint yourfile.js -``` - -## Configuration - -After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: - -```json -{ - "rules": { - "semi": ["error", "always"], - "quotes": ["error", "double"] - } -} -``` - -The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: - -* `"off"` or `0` - turn the rule off -* `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) -* `"error"` or `2` - turn the rule on as an error (exit code will be 1) - -The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). - -## Code of Conduct - -ESLint adheres to the [JS Foundation Code of Conduct](https://js.foundation/community/code-of-conduct). - -## Filing Issues - -Before filing an issue, please be sure to read the guidelines for what you're reporting: - -* [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) -* [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) -* [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) -* [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) - -## Frequently Asked Questions - -### I'm using JSCS, should I migrate to ESLint? - -Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. - -We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. - -We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. - -### Does Prettier replace ESLint? - -No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors. - -### Why can't ESLint find my plugins? - -* Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). -* Make sure you have run `npm install` and all your dependencies are installed. -* Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. - -### Does ESLint support JSX? - -Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. - -### What ECMAScript versions does ESLint support? - -ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring). - -### What about experimental features? - -ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. - -In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use the [babel-eslint](https://github.com/babel/babel-eslint) parser and [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) to use any option available in Babel. - -Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. - -### Where to ask for help? - -Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://eslint.org/chat). - -## Releases - -We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. - -## Semantic Versioning Policy - -ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: - -* Patch release (intended to not break your lint build) - * A bug fix in a rule that results in ESLint reporting fewer errors. - * A bug fix to the CLI or core (including formatters). - * Improvements to documentation. - * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. - * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). -* Minor release (might break your lint build) - * A bug fix in a rule that results in ESLint reporting more errors. - * A new rule is created. - * A new option to an existing rule that does not result in ESLint reporting more errors by default. - * An existing rule is deprecated. - * A new CLI capability is created. - * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). - * A new formatter is created. - * `eslint:recommended` is updated and will result in strictly fewer errors (e.g., rule removals). -* Major release (likely to break your lint build) - * `eslint:recommended` is updated and may result in new errors (e.g., rule additions, most rule option updates). - * A new option to an existing rule that results in ESLint reporting more errors by default. - * An existing formatter is removed. - * Part of the public API is removed or changed in an incompatible way. - -According to our policy, any minor update may report more errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. - -## License - -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) - -## Team - -These folks keep the project moving and are resources for help. - - - - -### Technical Steering Committee (TSC) - -The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. - -
- -
-Nicholas C. Zakas -
-
- -
-Brandon Mills -
-
- -
-Toru Nagashima -
-
- -
-Kai Cataldo -
-
- - -### Reviewers - -The people who review and implement new features. - -
- -
-薛定谔的猫 -
-
- -
-Milos Djermanovic -
-
- - - - -### Committers - -The people who review and fix bugs and help triage issues. - -
- -
-Pig Fang -
-
- -
-YeonJuan -
-
- - - - -## Sponsors - -The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. - - - -

Gold Sponsors

-

Salesforce Airbnb Microsoft FOSS Fund Sponsorships

Silver Sponsors

-

Liftoff AMP Project

Bronze Sponsors

-

2021 calendar Buy.Fineproxy.Org Veikkaajat.com Nettikasinot.media My True Media Norgekasino Japanesecasino CasinoTop.com Casino Topp Anagram Solver Kasinot.fi Pelisivut Nettikasinot.org BonusFinder Deutschland Bugsnag Stability Monitoring Mixpanel VPS Server Icons8: free icons, photos, illustrations, and music Discord ThemeIsle Marfeel Fire Stick Tricks

- - -## Technology Sponsors - -* Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) -* Hosting for ([eslint.org](https://eslint.org)) is sponsored by [Netlify](https://www.netlify.com) -* Password management is sponsored by [1Password](https://www.1password.com) diff --git a/tools/node_modules/eslint/bin/eslint.js b/tools/node_modules/eslint/bin/eslint.js deleted file mode 100755 index 75b413148695e564664fc168130158071fb69480..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/bin/eslint.js +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env node - -/** - * @fileoverview Main CLI that is run via the eslint command. - * @author Nicholas C. Zakas - */ - -/* eslint no-console:off */ - -"use strict"; - -// to use V8's code cache to speed up instantiation time -require("v8-compile-cache"); - -// must do this initialization *before* other requires in order to work -if (process.argv.includes("--debug")) { - require("debug").enable("eslint:*,-eslint:code-path"); -} - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Read data from stdin til the end. - * - * Note: See - * - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin - * - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io - * - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html - * - https://github.com/nodejs/node/issues/7439 (historical) - * - * On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems - * to read 4096 bytes before blocking and never drains to read further data. - * - * The investigation on the Emacs thread indicates: - * - * > Emacs on MS-Windows uses pipes to communicate with subprocesses; a - * > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than - * > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for - * > the subprocess to read its end of the pipe, at which time Emacs will - * > write the rest of the stuff. - * @returns {Promise} The read text. - */ -function readStdin() { - return new Promise((resolve, reject) => { - let content = ""; - let chunk = ""; - - process.stdin - .setEncoding("utf8") - .on("readable", () => { - while ((chunk = process.stdin.read()) !== null) { - content += chunk; - } - }) - .on("end", () => resolve(content)) - .on("error", reject); - }); -} - -/** - * Get the error message of a given value. - * @param {any} error The value to get. - * @returns {string} The error message. - */ -function getErrorMessage(error) { - - // Lazy loading because those are used only if error happened. - const fs = require("fs"); - const path = require("path"); - const util = require("util"); - const lodash = require("lodash"); - - // Foolproof -- thirdparty module might throw non-object. - if (typeof error !== "object" || error === null) { - return String(error); - } - - // Use templates if `error.messageTemplate` is present. - if (typeof error.messageTemplate === "string") { - try { - const templateFilePath = path.resolve( - __dirname, - `../messages/${error.messageTemplate}.txt` - ); - - // Use sync API because Node.js should exit at this tick. - const templateText = fs.readFileSync(templateFilePath, "utf-8"); - const template = lodash.template(templateText); - - return template(error.messageData || {}); - } catch { - - // Ignore template error then fallback to use `error.stack`. - } - } - - // Use the stacktrace if it's an error object. - if (typeof error.stack === "string") { - return error.stack; - } - - // Otherwise, dump the object. - return util.format("%o", error); -} - -/** - * Catch and report unexpected error. - * @param {any} error The thrown error object. - * @returns {void} - */ -function onFatalError(error) { - process.exitCode = 2; - - const { version } = require("../package.json"); - const message = getErrorMessage(error); - - console.error(` -Oops! Something went wrong! :( - -ESLint: ${version} - -${message}`); -} - -//------------------------------------------------------------------------------ -// Execution -//------------------------------------------------------------------------------ - -(async function main() { - process.on("uncaughtException", onFatalError); - process.on("unhandledRejection", onFatalError); - - // Call the config initializer if `--init` is present. - if (process.argv.includes("--init")) { - await require("../lib/init/config-initializer").initializeConfig(); - return; - } - - // Otherwise, call the CLI. - process.exitCode = await require("../lib/cli").execute( - process.argv, - process.argv.includes("--stdin") ? await readStdin() : null - ); -}()).catch(onFatalError); diff --git a/tools/node_modules/eslint/conf/category-list.json b/tools/node_modules/eslint/conf/category-list.json deleted file mode 100644 index cd3b816b6570a21c93037e92114a6c9c2b433043..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/conf/category-list.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "categories": [ - { "name": "Possible Errors", "description": "These rules relate to possible syntax or logic errors in JavaScript code:" }, - { "name": "Best Practices", "description": "These rules relate to better ways of doing things to help you avoid problems:" }, - { "name": "Strict Mode", "description": "These rules relate to strict mode directives:" }, - { "name": "Variables", "description": "These rules relate to variable declarations:" }, - { "name": "Stylistic Issues", "description": "These rules relate to style guidelines, and are therefore quite subjective:" }, - { "name": "ECMAScript 6", "description": "These rules relate to ES6, also known as ES2015:" } - ], - "deprecated": { - "name": "Deprecated", - "description": "These rules have been deprecated in accordance with the deprecation policy, and replaced by newer rules:", - "rules": [] - }, - "removed": { - "name": "Removed", - "description": "These rules from older versions of ESLint (before the deprecation policy existed) have been replaced by newer rules:", - "rules": [ - { "removed": "generator-star", "replacedBy": ["generator-star-spacing"] }, - { "removed": "global-strict", "replacedBy": ["strict"] }, - { "removed": "no-arrow-condition", "replacedBy": ["no-confusing-arrow", "no-constant-condition"] }, - { "removed": "no-comma-dangle", "replacedBy": ["comma-dangle"] }, - { "removed": "no-empty-class", "replacedBy": ["no-empty-character-class"] }, - { "removed": "no-empty-label", "replacedBy": ["no-labels"] }, - { "removed": "no-extra-strict", "replacedBy": ["strict"] }, - { "removed": "no-reserved-keys", "replacedBy": ["quote-props"] }, - { "removed": "no-space-before-semi", "replacedBy": ["semi-spacing"] }, - { "removed": "no-wrap-func", "replacedBy": ["no-extra-parens"] }, - { "removed": "space-after-function-name", "replacedBy": ["space-before-function-paren"] }, - { "removed": "space-after-keywords", "replacedBy": ["keyword-spacing"] }, - { "removed": "space-before-function-parentheses", "replacedBy": ["space-before-function-paren"] }, - { "removed": "space-before-keywords", "replacedBy": ["keyword-spacing"] }, - { "removed": "space-in-brackets", "replacedBy": ["object-curly-spacing", "array-bracket-spacing"] }, - { "removed": "space-return-throw-case", "replacedBy": ["keyword-spacing"] }, - { "removed": "space-unary-word-ops", "replacedBy": ["space-unary-ops"] }, - { "removed": "spaced-line-comment", "replacedBy": ["spaced-comment"] } - ] - } -} diff --git a/tools/node_modules/eslint/conf/config-schema.js b/tools/node_modules/eslint/conf/config-schema.js deleted file mode 100644 index b83f6578832df91536329f30ee222e112f7c4dca..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/conf/config-schema.js +++ /dev/null @@ -1,93 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview Defines a schema for configs. - * @author Sylvan Mably - */ - -"use strict"; - -const baseConfigProperties = { - $schema: { type: "string" }, - env: { type: "object" }, - extends: { $ref: "#/definitions/stringOrStrings" }, - globals: { type: "object" }, - overrides: { - type: "array", - items: { $ref: "#/definitions/overrideConfig" }, - additionalItems: false - }, - parser: { type: ["string", "null"] }, - parserOptions: { type: "object" }, - plugins: { type: "array" }, - processor: { type: "string" }, - rules: { type: "object" }, - settings: { type: "object" }, - noInlineConfig: { type: "boolean" }, - reportUnusedDisableDirectives: { type: "boolean" }, - - ecmaFeatures: { type: "object" } // deprecated; logs a warning when used -}; - -const configSchema = { - definitions: { - stringOrStrings: { - oneOf: [ - { type: "string" }, - { - type: "array", - items: { type: "string" }, - additionalItems: false - } - ] - }, - stringOrStringsRequired: { - oneOf: [ - { type: "string" }, - { - type: "array", - items: { type: "string" }, - additionalItems: false, - minItems: 1 - } - ] - }, - - // Config at top-level. - objectConfig: { - type: "object", - properties: { - root: { type: "boolean" }, - ignorePatterns: { $ref: "#/definitions/stringOrStrings" }, - ...baseConfigProperties - }, - additionalProperties: false - }, - - // Config in `overrides`. - overrideConfig: { - type: "object", - properties: { - excludedFiles: { $ref: "#/definitions/stringOrStrings" }, - files: { $ref: "#/definitions/stringOrStringsRequired" }, - ...baseConfigProperties - }, - required: ["files"], - additionalProperties: false - } - }, - - $ref: "#/definitions/objectConfig" -}; - -module.exports = configSchema; diff --git a/tools/node_modules/eslint/conf/default-cli-options.js b/tools/node_modules/eslint/conf/default-cli-options.js deleted file mode 100644 index e09a829d17cee292f804b00a2110e97d36a98071..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/conf/default-cli-options.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @fileoverview Default CLIEngineOptions. - * @author Ian VanSchooten - */ - -"use strict"; - -module.exports = { - configFile: null, - baseConfig: false, - rulePaths: [], - useEslintrc: true, - envs: [], - globals: [], - extensions: null, - ignore: true, - ignorePath: void 0, - cache: false, - - /* - * in order to honor the cacheFile option if specified - * this option should not have a default value otherwise - * it will always be used - */ - cacheLocation: "", - cacheFile: ".eslintcache", - fix: false, - allowInlineConfig: true, - reportUnusedDisableDirectives: void 0, - globInputPaths: true -}; diff --git a/tools/node_modules/eslint/conf/eslint-all.js b/tools/node_modules/eslint/conf/eslint-all.js deleted file mode 100644 index 10c5304fd3f2430059ea353c5c2772a1382ee17c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/conf/eslint-all.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @fileoverview Config to enable all rules. - * @author Robert Fletcher - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const builtInRules = require("../lib/rules"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const allRules = {}; - -for (const [ruleId, rule] of builtInRules) { - if (!rule.meta.deprecated) { - allRules[ruleId] = "error"; - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** @type {import("../lib/shared/types").ConfigData} */ -module.exports = { rules: allRules }; diff --git a/tools/node_modules/eslint/conf/eslint-recommended.js b/tools/node_modules/eslint/conf/eslint-recommended.js deleted file mode 100644 index 2137685fb7c63e77191e6933a1138eae377ca60a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/conf/eslint-recommended.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @fileoverview Configuration applied when a user configuration extends from - * eslint:recommended. - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* eslint sort-keys: ["error", "asc"] */ - -/** @type {import("../lib/shared/types").ConfigData} */ -module.exports = { - rules: { - "constructor-super": "error", - "for-direction": "error", - "getter-return": "error", - "no-async-promise-executor": "error", - "no-case-declarations": "error", - "no-class-assign": "error", - "no-compare-neg-zero": "error", - "no-cond-assign": "error", - "no-const-assign": "error", - "no-constant-condition": "error", - "no-control-regex": "error", - "no-debugger": "error", - "no-delete-var": "error", - "no-dupe-args": "error", - "no-dupe-class-members": "error", - "no-dupe-else-if": "error", - "no-dupe-keys": "error", - "no-duplicate-case": "error", - "no-empty": "error", - "no-empty-character-class": "error", - "no-empty-pattern": "error", - "no-ex-assign": "error", - "no-extra-boolean-cast": "error", - "no-extra-semi": "error", - "no-fallthrough": "error", - "no-func-assign": "error", - "no-global-assign": "error", - "no-import-assign": "error", - "no-inner-declarations": "error", - "no-invalid-regexp": "error", - "no-irregular-whitespace": "error", - "no-misleading-character-class": "error", - "no-mixed-spaces-and-tabs": "error", - "no-new-symbol": "error", - "no-obj-calls": "error", - "no-octal": "error", - "no-prototype-builtins": "error", - "no-redeclare": "error", - "no-regex-spaces": "error", - "no-self-assign": "error", - "no-setter-return": "error", - "no-shadow-restricted-names": "error", - "no-sparse-arrays": "error", - "no-this-before-super": "error", - "no-undef": "error", - "no-unexpected-multiline": "error", - "no-unreachable": "error", - "no-unsafe-finally": "error", - "no-unsafe-negation": "error", - "no-unused-labels": "error", - "no-unused-vars": "error", - "no-useless-catch": "error", - "no-useless-escape": "error", - "no-with": "error", - "require-yield": "error", - "use-isnan": "error", - "valid-typeof": "error" - } -}; diff --git a/tools/node_modules/eslint/conf/replacements.json b/tools/node_modules/eslint/conf/replacements.json deleted file mode 100644 index c047811e602d41c655dfe3b5d515dd507e20c90b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/conf/replacements.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "rules": { - "generator-star": ["generator-star-spacing"], - "global-strict": ["strict"], - "no-arrow-condition": ["no-confusing-arrow", "no-constant-condition"], - "no-comma-dangle": ["comma-dangle"], - "no-empty-class": ["no-empty-character-class"], - "no-empty-label": ["no-labels"], - "no-extra-strict": ["strict"], - "no-reserved-keys": ["quote-props"], - "no-space-before-semi": ["semi-spacing"], - "no-wrap-func": ["no-extra-parens"], - "space-after-function-name": ["space-before-function-paren"], - "space-after-keywords": ["keyword-spacing"], - "space-before-function-parentheses": ["space-before-function-paren"], - "space-before-keywords": ["keyword-spacing"], - "space-in-brackets": ["object-curly-spacing", "array-bracket-spacing", "computed-property-spacing"], - "space-return-throw-case": ["keyword-spacing"], - "space-unary-word-ops": ["space-unary-ops"], - "spaced-line-comment": ["spaced-comment"] - } -} diff --git a/tools/node_modules/eslint/lib/api.js b/tools/node_modules/eslint/lib/api.js deleted file mode 100644 index e4b6643b44780a176bd6f0c2ef58de78748fe920..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/api.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @fileoverview Expose out ESLint and CLI to require. - * @author Ian Christian Myers - */ - -"use strict"; - -const { CLIEngine } = require("./cli-engine"); -const { ESLint } = require("./eslint"); -const { Linter } = require("./linter"); -const { RuleTester } = require("./rule-tester"); -const { SourceCode } = require("./source-code"); - -module.exports = { - Linter, - CLIEngine, - ESLint, - RuleTester, - SourceCode -}; - -// DOTO: remove deprecated API. -let deprecatedLinterInstance = null; - -Object.defineProperty(module.exports, "linter", { - enumerable: false, - get() { - if (!deprecatedLinterInstance) { - deprecatedLinterInstance = new Linter(); - } - - return deprecatedLinterInstance; - } -}); diff --git a/tools/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js b/tools/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js deleted file mode 100644 index df49c27772ac838d269eb9f3c6fe70d9901f4c30..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js +++ /dev/null @@ -1,502 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `CascadingConfigArrayFactory` class. - * - * `CascadingConfigArrayFactory` class has a responsibility: - * - * 1. Handles cascading of config files. - * - * It provides two methods: - * - * - `getConfigArrayForFile(filePath)` - * Get the corresponded configuration of a given file. This method doesn't - * throw even if the given file didn't exist. - * - `clearCache()` - * Clear the internal cache. You have to call this method when - * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends - * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.) - * - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const os = require("os"); -const path = require("path"); -const { validateConfigArray } = require("../shared/config-validator"); -const { emitDeprecationWarning } = require("../shared/deprecation-warnings"); -const { ConfigArrayFactory } = require("./config-array-factory"); -const { ConfigArray, ConfigDependency, IgnorePattern } = require("./config-array"); -const loadRules = require("./load-rules"); -const debug = require("debug")("eslint:cascading-config-array-factory"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -// Define types for VSCode IntelliSense. -/** @typedef {import("../shared/types").ConfigData} ConfigData */ -/** @typedef {import("../shared/types").Parser} Parser */ -/** @typedef {import("../shared/types").Plugin} Plugin */ -/** @typedef {ReturnType} ConfigArray */ - -/** - * @typedef {Object} CascadingConfigArrayFactoryOptions - * @property {Map} [additionalPluginPool] The map for additional plugins. - * @property {ConfigData} [baseConfig] The config by `baseConfig` option. - * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files. - * @property {string} [cwd] The base directory to start lookup. - * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. - * @property {string[]} [rulePaths] The value of `--rulesdir` option. - * @property {string} [specificConfigPath] The value of `--config` option. - * @property {boolean} [useEslintrc] if `false` then it doesn't load config files. - */ - -/** - * @typedef {Object} CascadingConfigArrayFactoryInternalSlots - * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option. - * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`. - * @property {ConfigArray} cliConfigArray The config array of CLI options. - * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`. - * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays. - * @property {Map} configCache The cache from directory paths to config arrays. - * @property {string} cwd The base directory to start lookup. - * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays. - * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. - * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`. - * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`. - * @property {boolean} useEslintrc if `false` then it doesn't load config files. - */ - -/** @type {WeakMap} */ -const internalSlotsMap = new WeakMap(); - -/** - * Create the config array from `baseConfig` and `rulePaths`. - * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. - * @returns {ConfigArray} The config array of the base configs. - */ -function createBaseConfigArray({ - configArrayFactory, - baseConfigData, - rulePaths, - cwd -}) { - const baseConfigArray = configArrayFactory.create( - baseConfigData, - { name: "BaseConfig" } - ); - - /* - * Create the config array element for the default ignore patterns. - * This element has `ignorePattern` property that ignores the default - * patterns in the current working directory. - */ - baseConfigArray.unshift(configArrayFactory.create( - { ignorePatterns: IgnorePattern.DefaultPatterns }, - { name: "DefaultIgnorePattern" } - )[0]); - - /* - * Load rules `--rulesdir` option as a pseudo plugin. - * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate - * the rule's options with only information in the config array. - */ - if (rulePaths && rulePaths.length > 0) { - baseConfigArray.push({ - type: "config", - name: "--rulesdir", - filePath: "", - plugins: { - "": new ConfigDependency({ - definition: { - rules: rulePaths.reduce( - (map, rulesPath) => Object.assign( - map, - loadRules(rulesPath, cwd) - ), - {} - ) - }, - filePath: "", - id: "", - importerName: "--rulesdir", - importerPath: "" - }) - } - }); - } - - return baseConfigArray; -} - -/** - * Create the config array from CLI options. - * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. - * @returns {ConfigArray} The config array of the base configs. - */ -function createCLIConfigArray({ - cliConfigData, - configArrayFactory, - cwd, - ignorePath, - specificConfigPath -}) { - const cliConfigArray = configArrayFactory.create( - cliConfigData, - { name: "CLIOptions" } - ); - - cliConfigArray.unshift( - ...(ignorePath - ? configArrayFactory.loadESLintIgnore(ignorePath) - : configArrayFactory.loadDefaultESLintIgnore()) - ); - - if (specificConfigPath) { - cliConfigArray.unshift( - ...configArrayFactory.loadFile( - specificConfigPath, - { name: "--config", basePath: cwd } - ) - ); - } - - return cliConfigArray; -} - -/** - * The error type when there are files matched by a glob, but all of them have been ignored. - */ -class ConfigurationNotFoundError extends Error { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} directoryPath The directory path. - */ - constructor(directoryPath) { - super(`No ESLint configuration found in ${directoryPath}.`); - this.messageTemplate = "no-config-found"; - this.messageData = { directoryPath }; - } -} - -/** - * This class provides the functionality that enumerates every file which is - * matched by given glob patterns and that configuration. - */ -class CascadingConfigArrayFactory { - - /** - * Initialize this enumerator. - * @param {CascadingConfigArrayFactoryOptions} options The options. - */ - constructor({ - additionalPluginPool = new Map(), - baseConfig: baseConfigData = null, - cliConfig: cliConfigData = null, - cwd = process.cwd(), - ignorePath, - resolvePluginsRelativeTo, - rulePaths = [], - specificConfigPath = null, - useEslintrc = true - } = {}) { - const configArrayFactory = new ConfigArrayFactory({ - additionalPluginPool, - cwd, - resolvePluginsRelativeTo - }); - - internalSlotsMap.set(this, { - baseConfigArray: createBaseConfigArray({ - baseConfigData, - configArrayFactory, - cwd, - rulePaths - }), - baseConfigData, - cliConfigArray: createCLIConfigArray({ - cliConfigData, - configArrayFactory, - cwd, - ignorePath, - specificConfigPath - }), - cliConfigData, - configArrayFactory, - configCache: new Map(), - cwd, - finalizeCache: new WeakMap(), - ignorePath, - rulePaths, - specificConfigPath, - useEslintrc - }); - } - - /** - * The path to the current working directory. - * This is used by tests. - * @type {string} - */ - get cwd() { - const { cwd } = internalSlotsMap.get(this); - - return cwd; - } - - /** - * Get the config array of a given file. - * If `filePath` was not given, it returns the config which contains only - * `baseConfigData` and `cliConfigData`. - * @param {string} [filePath] The file path to a file. - * @param {Object} [options] The options. - * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`. - * @returns {ConfigArray} The config array of the file. - */ - getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) { - const { - baseConfigArray, - cliConfigArray, - cwd - } = internalSlotsMap.get(this); - - if (!filePath) { - return new ConfigArray(...baseConfigArray, ...cliConfigArray); - } - - const directoryPath = path.dirname(path.resolve(cwd, filePath)); - - debug(`Load config files for ${directoryPath}.`); - - return this._finalizeConfigArray( - this._loadConfigInAncestors(directoryPath), - directoryPath, - ignoreNotFoundError - ); - } - - /** - * Set the config data to override all configs. - * Require to call `clearCache()` method after this method is called. - * @param {ConfigData} configData The config data to override all configs. - * @returns {void} - */ - setOverrideConfig(configData) { - const slots = internalSlotsMap.get(this); - - slots.cliConfigData = configData; - } - - /** - * Clear config cache. - * @returns {void} - */ - clearCache() { - const slots = internalSlotsMap.get(this); - - slots.baseConfigArray = createBaseConfigArray(slots); - slots.cliConfigArray = createCLIConfigArray(slots); - slots.configCache.clear(); - } - - /** - * Load and normalize config files from the ancestor directories. - * @param {string} directoryPath The path to a leaf directory. - * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories. - * @returns {ConfigArray} The loaded config. - * @private - */ - _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) { - const { - baseConfigArray, - configArrayFactory, - configCache, - cwd, - useEslintrc - } = internalSlotsMap.get(this); - - if (!useEslintrc) { - return baseConfigArray; - } - - let configArray = configCache.get(directoryPath); - - // Hit cache. - if (configArray) { - debug(`Cache hit: ${directoryPath}.`); - return configArray; - } - debug(`No cache found: ${directoryPath}.`); - - const homePath = os.homedir(); - - // Consider this is root. - if (directoryPath === homePath && cwd !== homePath) { - debug("Stop traversing because of considered root."); - if (configsExistInSubdirs) { - const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath); - - if (filePath) { - emitDeprecationWarning( - filePath, - "ESLINT_PERSONAL_CONFIG_SUPPRESS" - ); - } - } - return this._cacheConfig(directoryPath, baseConfigArray); - } - - // Load the config on this directory. - try { - configArray = configArrayFactory.loadInDirectory(directoryPath); - } catch (error) { - /* istanbul ignore next */ - if (error.code === "EACCES") { - debug("Stop traversing because of 'EACCES' error."); - return this._cacheConfig(directoryPath, baseConfigArray); - } - throw error; - } - - if (configArray.length > 0 && configArray.isRoot()) { - debug("Stop traversing because of 'root:true'."); - configArray.unshift(...baseConfigArray); - return this._cacheConfig(directoryPath, configArray); - } - - // Load from the ancestors and merge it. - const parentPath = path.dirname(directoryPath); - const parentConfigArray = parentPath && parentPath !== directoryPath - ? this._loadConfigInAncestors( - parentPath, - configsExistInSubdirs || configArray.length > 0 - ) - : baseConfigArray; - - if (configArray.length > 0) { - configArray.unshift(...parentConfigArray); - } else { - configArray = parentConfigArray; - } - - // Cache and return. - return this._cacheConfig(directoryPath, configArray); - } - - /** - * Freeze and cache a given config. - * @param {string} directoryPath The path to a directory as a cache key. - * @param {ConfigArray} configArray The config array as a cache value. - * @returns {ConfigArray} The `configArray` (frozen). - */ - _cacheConfig(directoryPath, configArray) { - const { configCache } = internalSlotsMap.get(this); - - Object.freeze(configArray); - configCache.set(directoryPath, configArray); - - return configArray; - } - - /** - * Finalize a given config array. - * Concatenate `--config` and other CLI options. - * @param {ConfigArray} configArray The parent config array. - * @param {string} directoryPath The path to the leaf directory to find config files. - * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`. - * @returns {ConfigArray} The loaded config. - * @private - */ - _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) { - const { - cliConfigArray, - configArrayFactory, - finalizeCache, - useEslintrc - } = internalSlotsMap.get(this); - - let finalConfigArray = finalizeCache.get(configArray); - - if (!finalConfigArray) { - finalConfigArray = configArray; - - // Load the personal config if there are no regular config files. - if ( - useEslintrc && - configArray.every(c => !c.filePath) && - cliConfigArray.every(c => !c.filePath) // `--config` option can be a file. - ) { - const homePath = os.homedir(); - - debug("Loading the config file of the home directory:", homePath); - - const personalConfigArray = configArrayFactory.loadInDirectory( - homePath, - { name: "PersonalConfig" } - ); - - if ( - personalConfigArray.length > 0 && - !directoryPath.startsWith(homePath) - ) { - const lastElement = - personalConfigArray[personalConfigArray.length - 1]; - - emitDeprecationWarning( - lastElement.filePath, - "ESLINT_PERSONAL_CONFIG_LOAD" - ); - } - - finalConfigArray = finalConfigArray.concat(personalConfigArray); - } - - // Apply CLI options. - if (cliConfigArray.length > 0) { - finalConfigArray = finalConfigArray.concat(cliConfigArray); - } - - // Validate rule settings and environments. - validateConfigArray(finalConfigArray); - - // Cache it. - Object.freeze(finalConfigArray); - finalizeCache.set(configArray, finalConfigArray); - - debug( - "Configuration was determined: %o on %s", - finalConfigArray, - directoryPath - ); - } - - // At least one element (the default ignore patterns) exists. - if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) { - throw new ConfigurationNotFoundError(directoryPath); - } - - return finalConfigArray; - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { CascadingConfigArrayFactory }; diff --git a/tools/node_modules/eslint/lib/cli-engine/cli-engine.js b/tools/node_modules/eslint/lib/cli-engine/cli-engine.js deleted file mode 100644 index 70c6f6f39f7643a239fc9406dcca524cdf47b3cf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/cli-engine.js +++ /dev/null @@ -1,1026 +0,0 @@ -/** - * @fileoverview Main CLI object. - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* - * The CLI object should *not* call process.exit() directly. It should only return - * exit codes. This allows other programs to use the CLI object and still control - * when the program exits. - */ - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"); -const path = require("path"); -const defaultOptions = require("../../conf/default-cli-options"); -const pkg = require("../../package.json"); -const ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"); -const naming = require("@eslint/eslintrc/lib/shared/naming"); -const ModuleResolver = require("../shared/relative-module-resolver"); -const { Linter } = require("../linter"); -const builtInRules = require("../rules"); -const { CascadingConfigArrayFactory } = require("./cascading-config-array-factory"); -const { IgnorePattern, getUsedExtractedConfigs } = require("./config-array"); -const { FileEnumerator } = require("./file-enumerator"); -const hash = require("./hash"); -const LintResultCache = require("./lint-result-cache"); - -const debug = require("debug")("eslint:cli-engine"); -const validFixTypes = new Set(["problem", "suggestion", "layout"]); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -// For VSCode IntelliSense -/** @typedef {import("../shared/types").ConfigData} ConfigData */ -/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */ -/** @typedef {import("../shared/types").LintMessage} LintMessage */ -/** @typedef {import("../shared/types").ParserOptions} ParserOptions */ -/** @typedef {import("../shared/types").Plugin} Plugin */ -/** @typedef {import("../shared/types").RuleConf} RuleConf */ -/** @typedef {import("../shared/types").Rule} Rule */ -/** @typedef {ReturnType} ConfigArray */ -/** @typedef {ReturnType} ExtractedConfig */ - -/** - * The options to configure a CLI engine with. - * @typedef {Object} CLIEngineOptions - * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. - * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance - * @property {boolean} [cache] Enable result caching. - * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. - * @property {string} [configFile] The configuration file to use. - * @property {string} [cwd] The value to use for the current working directory. - * @property {string[]} [envs] An array of environments to load. - * @property {string[]|null} [extensions] An array of file extensions to check. - * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. - * @property {string[]} [fixTypes] Array of rule types to apply fixes for. - * @property {string[]} [globals] An array of global variables to declare. - * @property {boolean} [ignore] False disables use of .eslintignore. - * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. - * @property {string|string[]} [ignorePattern] One or more glob patterns to ignore. - * @property {boolean} [useEslintrc] False disables looking for .eslintrc - * @property {string} [parser] The name of the parser to use. - * @property {ParserOptions} [parserOptions] An object of parserOption settings to use. - * @property {string[]} [plugins] An array of plugins to load. - * @property {Record} [rules] An object of rules to use. - * @property {string[]} [rulePaths] An array of directories to load custom rules from. - * @property {boolean} [reportUnusedDisableDirectives] `true` adds reports for unused eslint-disable directives - * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. - * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD - */ - -/** - * A linting result. - * @typedef {Object} LintResult - * @property {string} filePath The path to the file that was linted. - * @property {LintMessage[]} messages All of the messages for the result. - * @property {number} errorCount Number of errors for the result. - * @property {number} warningCount Number of warnings for the result. - * @property {number} fixableErrorCount Number of fixable errors for the result. - * @property {number} fixableWarningCount Number of fixable warnings for the result. - * @property {string} [source] The source code of the file that was linted. - * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible. - */ - -/** - * Linting results. - * @typedef {Object} LintReport - * @property {LintResult[]} results All of the result. - * @property {number} errorCount Number of errors for the result. - * @property {number} warningCount Number of warnings for the result. - * @property {number} fixableErrorCount Number of fixable errors for the result. - * @property {number} fixableWarningCount Number of fixable warnings for the result. - * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules. - */ - -/** - * Private data for CLIEngine. - * @typedef {Object} CLIEngineInternalSlots - * @property {Map} additionalPluginPool The map for additional plugins. - * @property {string} cacheFilePath The path to the cache of lint results. - * @property {CascadingConfigArrayFactory} configArrayFactory The factory of configs. - * @property {(filePath: string) => boolean} defaultIgnores The default predicate function to check if a file ignored or not. - * @property {FileEnumerator} fileEnumerator The file enumerator. - * @property {ConfigArray[]} lastConfigArrays The list of config arrays that the last `executeOnFiles` or `executeOnText` used. - * @property {LintResultCache|null} lintResultCache The cache of lint results. - * @property {Linter} linter The linter instance which has loaded rules. - * @property {CLIEngineOptions} options The normalized options of this instance. - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** @type {WeakMap} */ -const internalSlotsMap = new WeakMap(); - -/** - * Determines if each fix type in an array is supported by ESLint and throws - * an error if not. - * @param {string[]} fixTypes An array of fix types to check. - * @returns {void} - * @throws {Error} If an invalid fix type is found. - */ -function validateFixTypes(fixTypes) { - for (const fixType of fixTypes) { - if (!validFixTypes.has(fixType)) { - throw new Error(`Invalid fix type "${fixType}" found.`); - } - } -} - -/** - * It will calculate the error and warning count for collection of messages per file - * @param {LintMessage[]} messages Collection of messages - * @returns {Object} Contains the stats - * @private - */ -function calculateStatsPerFile(messages) { - return messages.reduce((stat, message) => { - if (message.fatal || message.severity === 2) { - stat.errorCount++; - if (message.fix) { - stat.fixableErrorCount++; - } - } else { - stat.warningCount++; - if (message.fix) { - stat.fixableWarningCount++; - } - } - return stat; - }, { - errorCount: 0, - warningCount: 0, - fixableErrorCount: 0, - fixableWarningCount: 0 - }); -} - -/** - * It will calculate the error and warning count for collection of results from all files - * @param {LintResult[]} results Collection of messages from all the files - * @returns {Object} Contains the stats - * @private - */ -function calculateStatsPerRun(results) { - return results.reduce((stat, result) => { - stat.errorCount += result.errorCount; - stat.warningCount += result.warningCount; - stat.fixableErrorCount += result.fixableErrorCount; - stat.fixableWarningCount += result.fixableWarningCount; - return stat; - }, { - errorCount: 0, - warningCount: 0, - fixableErrorCount: 0, - fixableWarningCount: 0 - }); -} - -/** - * Processes an source code using ESLint. - * @param {Object} config The config object. - * @param {string} config.text The source code to verify. - * @param {string} config.cwd The path to the current working directory. - * @param {string|undefined} config.filePath The path to the file of `text`. If this is undefined, it uses ``. - * @param {ConfigArray} config.config The config. - * @param {boolean} config.fix If `true` then it does fix. - * @param {boolean} config.allowInlineConfig If `true` then it uses directive comments. - * @param {boolean} config.reportUnusedDisableDirectives If `true` then it reports unused `eslint-disable` comments. - * @param {FileEnumerator} config.fileEnumerator The file enumerator to check if a path is a target or not. - * @param {Linter} config.linter The linter instance to verify. - * @returns {LintResult} The result of linting. - * @private - */ -function verifyText({ - text, - cwd, - filePath: providedFilePath, - config, - fix, - allowInlineConfig, - reportUnusedDisableDirectives, - fileEnumerator, - linter -}) { - const filePath = providedFilePath || ""; - - debug(`Lint ${filePath}`); - - /* - * Verify. - * `config.extractConfig(filePath)` requires an absolute path, but `linter` - * doesn't know CWD, so it gives `linter` an absolute path always. - */ - const filePathToVerify = filePath === "" ? path.join(cwd, filePath) : filePath; - const { fixed, messages, output } = linter.verifyAndFix( - text, - config, - { - allowInlineConfig, - filename: filePathToVerify, - fix, - reportUnusedDisableDirectives, - - /** - * Check if the linter should adopt a given code block or not. - * @param {string} blockFilename The virtual filename of a code block. - * @returns {boolean} `true` if the linter should adopt the code block. - */ - filterCodeBlock(blockFilename) { - return fileEnumerator.isTargetPath(blockFilename); - } - } - ); - - // Tweak and return. - const result = { - filePath, - messages, - ...calculateStatsPerFile(messages) - }; - - if (fixed) { - result.output = output; - } - if ( - result.errorCount + result.warningCount > 0 && - typeof result.output === "undefined" - ) { - result.source = text; - } - - return result; -} - -/** - * Returns result with warning by ignore settings - * @param {string} filePath File path of checked code - * @param {string} baseDir Absolute path of base directory - * @returns {LintResult} Result with single warning - * @private - */ -function createIgnoreResult(filePath, baseDir) { - let message; - const isHidden = filePath.split(path.sep) - .find(segment => /^\./u.test(segment)); - const isInNodeModules = baseDir && path.relative(baseDir, filePath).startsWith("node_modules"); - - if (isHidden) { - message = "File ignored by default. Use a negated ignore pattern (like \"--ignore-pattern '!'\") to override."; - } else if (isInNodeModules) { - message = "File ignored by default. Use \"--ignore-pattern '!node_modules/*'\" to override."; - } else { - message = "File ignored because of a matching ignore pattern. Use \"--no-ignore\" to override."; - } - - return { - filePath: path.resolve(filePath), - messages: [ - { - fatal: false, - severity: 1, - message - } - ], - errorCount: 0, - warningCount: 1, - fixableErrorCount: 0, - fixableWarningCount: 0 - }; -} - -/** - * Get a rule. - * @param {string} ruleId The rule ID to get. - * @param {ConfigArray[]} configArrays The config arrays that have plugin rules. - * @returns {Rule|null} The rule or null. - */ -function getRule(ruleId, configArrays) { - for (const configArray of configArrays) { - const rule = configArray.pluginRules.get(ruleId); - - if (rule) { - return rule; - } - } - return builtInRules.get(ruleId) || null; -} - -/** - * Collect used deprecated rules. - * @param {ConfigArray[]} usedConfigArrays The config arrays which were used. - * @returns {IterableIterator} Used deprecated rules. - */ -function *iterateRuleDeprecationWarnings(usedConfigArrays) { - const processedRuleIds = new Set(); - - // Flatten used configs. - /** @type {ExtractedConfig[]} */ - const configs = [].concat( - ...usedConfigArrays.map(getUsedExtractedConfigs) - ); - - // Traverse rule configs. - for (const config of configs) { - for (const [ruleId, ruleConfig] of Object.entries(config.rules)) { - - // Skip if it was processed. - if (processedRuleIds.has(ruleId)) { - continue; - } - processedRuleIds.add(ruleId); - - // Skip if it's not used. - if (!ConfigOps.getRuleSeverity(ruleConfig)) { - continue; - } - const rule = getRule(ruleId, usedConfigArrays); - - // Skip if it's not deprecated. - if (!(rule && rule.meta && rule.meta.deprecated)) { - continue; - } - - // This rule was used and deprecated. - yield { - ruleId, - replacedBy: rule.meta.replacedBy || [] - }; - } - } -} - -/** - * Checks if the given message is an error message. - * @param {LintMessage} message The message to check. - * @returns {boolean} Whether or not the message is an error message. - * @private - */ -function isErrorMessage(message) { - return message.severity === 2; -} - - -/** - * return the cacheFile to be used by eslint, based on whether the provided parameter is - * a directory or looks like a directory (ends in `path.sep`), in which case the file - * name will be the `cacheFile/.cache_hashOfCWD` - * - * if cacheFile points to a file or looks like a file then in will just use that file - * @param {string} cacheFile The name of file to be used to store the cache - * @param {string} cwd Current working directory - * @returns {string} the resolved path to the cache file - */ -function getCacheFile(cacheFile, cwd) { - - /* - * make sure the path separators are normalized for the environment/os - * keeping the trailing path separator if present - */ - const normalizedCacheFile = path.normalize(cacheFile); - - const resolvedCacheFile = path.resolve(cwd, normalizedCacheFile); - const looksLikeADirectory = normalizedCacheFile.slice(-1) === path.sep; - - /** - * return the name for the cache file in case the provided parameter is a directory - * @returns {string} the resolved path to the cacheFile - */ - function getCacheFileForDirectory() { - return path.join(resolvedCacheFile, `.cache_${hash(cwd)}`); - } - - let fileStats; - - try { - fileStats = fs.lstatSync(resolvedCacheFile); - } catch { - fileStats = null; - } - - - /* - * in case the file exists we need to verify if the provided path - * is a directory or a file. If it is a directory we want to create a file - * inside that directory - */ - if (fileStats) { - - /* - * is a directory or is a file, but the original file the user provided - * looks like a directory but `path.resolve` removed the `last path.sep` - * so we need to still treat this like a directory - */ - if (fileStats.isDirectory() || looksLikeADirectory) { - return getCacheFileForDirectory(); - } - - // is file so just use that file - return resolvedCacheFile; - } - - /* - * here we known the file or directory doesn't exist, - * so we will try to infer if its a directory if it looks like a directory - * for the current operating system. - */ - - // if the last character passed is a path separator we assume is a directory - if (looksLikeADirectory) { - return getCacheFileForDirectory(); - } - - return resolvedCacheFile; -} - -/** - * Convert a string array to a boolean map. - * @param {string[]|null} keys The keys to assign true. - * @param {boolean} defaultValue The default value for each property. - * @param {string} displayName The property name which is used in error message. - * @returns {Record} The boolean map. - */ -function toBooleanMap(keys, defaultValue, displayName) { - if (keys && !Array.isArray(keys)) { - throw new Error(`${displayName} must be an array.`); - } - if (keys && keys.length > 0) { - return keys.reduce((map, def) => { - const [key, value] = def.split(":"); - - if (key !== "__proto__") { - map[key] = value === void 0 - ? defaultValue - : value === "true"; - } - - return map; - }, {}); - } - return void 0; -} - -/** - * Create a config data from CLI options. - * @param {CLIEngineOptions} options The options - * @returns {ConfigData|null} The created config data. - */ -function createConfigDataFromOptions(options) { - const { - ignorePattern, - parser, - parserOptions, - plugins, - rules - } = options; - const env = toBooleanMap(options.envs, true, "envs"); - const globals = toBooleanMap(options.globals, false, "globals"); - - if ( - env === void 0 && - globals === void 0 && - (ignorePattern === void 0 || ignorePattern.length === 0) && - parser === void 0 && - parserOptions === void 0 && - plugins === void 0 && - rules === void 0 - ) { - return null; - } - return { - env, - globals, - ignorePatterns: ignorePattern, - parser, - parserOptions, - plugins, - rules - }; -} - -/** - * Checks whether a directory exists at the given location - * @param {string} resolvedPath A path from the CWD - * @returns {boolean} `true` if a directory exists - */ -function directoryExists(resolvedPath) { - try { - return fs.statSync(resolvedPath).isDirectory(); - } catch (error) { - if (error && error.code === "ENOENT") { - return false; - } - throw error; - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class CLIEngine { - - /** - * Creates a new instance of the core CLI engine. - * @param {CLIEngineOptions} providedOptions The options for this instance. - */ - constructor(providedOptions) { - const options = Object.assign( - Object.create(null), - defaultOptions, - { cwd: process.cwd() }, - providedOptions - ); - - if (options.fix === void 0) { - options.fix = false; - } - - const additionalPluginPool = new Map(); - const cacheFilePath = getCacheFile( - options.cacheLocation || options.cacheFile, - options.cwd - ); - const configArrayFactory = new CascadingConfigArrayFactory({ - additionalPluginPool, - baseConfig: options.baseConfig || null, - cliConfig: createConfigDataFromOptions(options), - cwd: options.cwd, - ignorePath: options.ignorePath, - resolvePluginsRelativeTo: options.resolvePluginsRelativeTo, - rulePaths: options.rulePaths, - specificConfigPath: options.configFile, - useEslintrc: options.useEslintrc - }); - const fileEnumerator = new FileEnumerator({ - configArrayFactory, - cwd: options.cwd, - extensions: options.extensions, - globInputPaths: options.globInputPaths, - errorOnUnmatchedPattern: options.errorOnUnmatchedPattern, - ignore: options.ignore - }); - const lintResultCache = - options.cache ? new LintResultCache(cacheFilePath) : null; - const linter = new Linter({ cwd: options.cwd }); - - /** @type {ConfigArray[]} */ - const lastConfigArrays = [configArrayFactory.getConfigArrayForFile()]; - - // Store private data. - internalSlotsMap.set(this, { - additionalPluginPool, - cacheFilePath, - configArrayFactory, - defaultIgnores: IgnorePattern.createDefaultIgnore(options.cwd), - fileEnumerator, - lastConfigArrays, - lintResultCache, - linter, - options - }); - - // setup special filter for fixes - if (options.fix && options.fixTypes && options.fixTypes.length > 0) { - debug(`Using fix types ${options.fixTypes}`); - - // throw an error if any invalid fix types are found - validateFixTypes(options.fixTypes); - - // convert to Set for faster lookup - const fixTypes = new Set(options.fixTypes); - - // save original value of options.fix in case it's a function - const originalFix = (typeof options.fix === "function") - ? options.fix : () => true; - - options.fix = message => { - const rule = message.ruleId && getRule(message.ruleId, lastConfigArrays); - const matches = rule && rule.meta && fixTypes.has(rule.meta.type); - - return matches && originalFix(message); - }; - } - } - - getRules() { - const { lastConfigArrays } = internalSlotsMap.get(this); - - return new Map(function *() { - yield* builtInRules; - - for (const configArray of lastConfigArrays) { - yield* configArray.pluginRules; - } - }()); - } - - /** - * Returns results that only contains errors. - * @param {LintResult[]} results The results to filter. - * @returns {LintResult[]} The filtered results. - */ - static getErrorResults(results) { - const filtered = []; - - results.forEach(result => { - const filteredMessages = result.messages.filter(isErrorMessage); - - if (filteredMessages.length > 0) { - filtered.push({ - ...result, - messages: filteredMessages, - errorCount: filteredMessages.length, - warningCount: 0, - fixableErrorCount: result.fixableErrorCount, - fixableWarningCount: 0 - }); - } - }); - - return filtered; - } - - /** - * Outputs fixes from the given results to files. - * @param {LintReport} report The report object created by CLIEngine. - * @returns {void} - */ - static outputFixes(report) { - report.results.filter(result => Object.prototype.hasOwnProperty.call(result, "output")).forEach(result => { - fs.writeFileSync(result.filePath, result.output); - }); - } - - - /** - * Add a plugin by passing its configuration - * @param {string} name Name of the plugin. - * @param {Plugin} pluginObject Plugin configuration object. - * @returns {void} - */ - addPlugin(name, pluginObject) { - const { - additionalPluginPool, - configArrayFactory, - lastConfigArrays - } = internalSlotsMap.get(this); - - additionalPluginPool.set(name, pluginObject); - configArrayFactory.clearCache(); - lastConfigArrays.length = 1; - lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile(); - } - - /** - * Resolves the patterns passed into executeOnFiles() into glob-based patterns - * for easier handling. - * @param {string[]} patterns The file patterns passed on the command line. - * @returns {string[]} The equivalent glob patterns. - */ - resolveFileGlobPatterns(patterns) { - const { options } = internalSlotsMap.get(this); - - if (options.globInputPaths === false) { - return patterns.filter(Boolean); - } - - const extensions = (options.extensions || [".js"]).map(ext => ext.replace(/^\./u, "")); - const dirSuffix = `/**/*.{${extensions.join(",")}}`; - - return patterns.filter(Boolean).map(pathname => { - const resolvedPath = path.resolve(options.cwd, pathname); - const newPath = directoryExists(resolvedPath) - ? pathname.replace(/[/\\]$/u, "") + dirSuffix - : pathname; - - return path.normalize(newPath).replace(/\\/gu, "/"); - }); - } - - /** - * Executes the current configuration on an array of file and directory names. - * @param {string[]} patterns An array of file and directory names. - * @returns {LintReport} The results for all files that were linted. - */ - executeOnFiles(patterns) { - const { - cacheFilePath, - fileEnumerator, - lastConfigArrays, - lintResultCache, - linter, - options: { - allowInlineConfig, - cache, - cwd, - fix, - reportUnusedDisableDirectives - } - } = internalSlotsMap.get(this); - const results = []; - const startTime = Date.now(); - - // Clear the last used config arrays. - lastConfigArrays.length = 0; - - // Delete cache file; should this do here? - if (!cache) { - try { - fs.unlinkSync(cacheFilePath); - } catch (error) { - const errorCode = error && error.code; - - // Ignore errors when no such file exists or file system is read only (and cache file does not exist) - if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath))) { - throw error; - } - } - } - - // Iterate source code files. - for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) { - if (ignored) { - results.push(createIgnoreResult(filePath, cwd)); - continue; - } - - /* - * Store used configs for: - * - this method uses to collect used deprecated rules. - * - `getRules()` method uses to collect all loaded rules. - * - `--fix-type` option uses to get the loaded rule's meta data. - */ - if (!lastConfigArrays.includes(config)) { - lastConfigArrays.push(config); - } - - // Skip if there is cached result. - if (lintResultCache) { - const cachedResult = - lintResultCache.getCachedLintResults(filePath, config); - - if (cachedResult) { - const hadMessages = - cachedResult.messages && - cachedResult.messages.length > 0; - - if (hadMessages && fix) { - debug(`Reprocessing cached file to allow autofix: ${filePath}`); - } else { - debug(`Skipping file since it hasn't changed: ${filePath}`); - results.push(cachedResult); - continue; - } - } - } - - // Do lint. - const result = verifyText({ - text: fs.readFileSync(filePath, "utf8"), - filePath, - config, - cwd, - fix, - allowInlineConfig, - reportUnusedDisableDirectives, - fileEnumerator, - linter - }); - - results.push(result); - - /* - * Store the lint result in the LintResultCache. - * NOTE: The LintResultCache will remove the file source and any - * other properties that are difficult to serialize, and will - * hydrate those properties back in on future lint runs. - */ - if (lintResultCache) { - lintResultCache.setCachedLintResults(filePath, config, result); - } - } - - // Persist the cache to disk. - if (lintResultCache) { - lintResultCache.reconcile(); - } - - debug(`Linting complete in: ${Date.now() - startTime}ms`); - let usedDeprecatedRules; - - return { - results, - ...calculateStatsPerRun(results), - - // Initialize it lazily because CLI and `ESLint` API don't use it. - get usedDeprecatedRules() { - if (!usedDeprecatedRules) { - usedDeprecatedRules = Array.from( - iterateRuleDeprecationWarnings(lastConfigArrays) - ); - } - return usedDeprecatedRules; - } - }; - } - - /** - * Executes the current configuration on text. - * @param {string} text A string of JavaScript code to lint. - * @param {string} [filename] An optional string representing the texts filename. - * @param {boolean} [warnIgnored] Always warn when a file is ignored - * @returns {LintReport} The results for the linting. - */ - executeOnText(text, filename, warnIgnored) { - const { - configArrayFactory, - fileEnumerator, - lastConfigArrays, - linter, - options: { - allowInlineConfig, - cwd, - fix, - reportUnusedDisableDirectives - } - } = internalSlotsMap.get(this); - const results = []; - const startTime = Date.now(); - const resolvedFilename = filename && path.resolve(cwd, filename); - - - // Clear the last used config arrays. - lastConfigArrays.length = 0; - if (resolvedFilename && this.isPathIgnored(resolvedFilename)) { - if (warnIgnored) { - results.push(createIgnoreResult(resolvedFilename, cwd)); - } - } else { - const config = configArrayFactory.getConfigArrayForFile( - resolvedFilename || "__placeholder__.js" - ); - - /* - * Store used configs for: - * - this method uses to collect used deprecated rules. - * - `getRules()` method uses to collect all loaded rules. - * - `--fix-type` option uses to get the loaded rule's meta data. - */ - lastConfigArrays.push(config); - - // Do lint. - results.push(verifyText({ - text, - filePath: resolvedFilename, - config, - cwd, - fix, - allowInlineConfig, - reportUnusedDisableDirectives, - fileEnumerator, - linter - })); - } - - debug(`Linting complete in: ${Date.now() - startTime}ms`); - let usedDeprecatedRules; - - return { - results, - ...calculateStatsPerRun(results), - - // Initialize it lazily because CLI and `ESLint` API don't use it. - get usedDeprecatedRules() { - if (!usedDeprecatedRules) { - usedDeprecatedRules = Array.from( - iterateRuleDeprecationWarnings(lastConfigArrays) - ); - } - return usedDeprecatedRules; - } - }; - } - - /** - * Returns a configuration object for the given file based on the CLI options. - * This is the same logic used by the ESLint CLI executable to determine - * configuration for each file it processes. - * @param {string} filePath The path of the file to retrieve a config object for. - * @returns {ConfigData} A configuration object for the file. - */ - getConfigForFile(filePath) { - const { configArrayFactory, options } = internalSlotsMap.get(this); - const absolutePath = path.resolve(options.cwd, filePath); - - if (directoryExists(absolutePath)) { - throw Object.assign( - new Error("'filePath' should not be a directory path."), - { messageTemplate: "print-config-with-directory-path" } - ); - } - - return configArrayFactory - .getConfigArrayForFile(absolutePath) - .extractConfig(absolutePath) - .toCompatibleObjectAsConfigFileContent(); - } - - /** - * Checks if a given path is ignored by ESLint. - * @param {string} filePath The path of the file to check. - * @returns {boolean} Whether or not the given path is ignored. - */ - isPathIgnored(filePath) { - const { - configArrayFactory, - defaultIgnores, - options: { cwd, ignore } - } = internalSlotsMap.get(this); - const absolutePath = path.resolve(cwd, filePath); - - if (ignore) { - const config = configArrayFactory - .getConfigArrayForFile(absolutePath) - .extractConfig(absolutePath); - const ignores = config.ignores || defaultIgnores; - - return ignores(absolutePath); - } - - return defaultIgnores(absolutePath); - } - - /** - * Returns the formatter representing the given format or null if the `format` is not a string. - * @param {string} [format] The name of the format to load or the path to a - * custom formatter. - * @returns {(Function|null)} The formatter function or null if the `format` is not a string. - */ - getFormatter(format) { - - // default is stylish - const resolvedFormatName = format || "stylish"; - - // only strings are valid formatters - if (typeof resolvedFormatName === "string") { - - // replace \ with / for Windows compatibility - const normalizedFormatName = resolvedFormatName.replace(/\\/gu, "/"); - - const slots = internalSlotsMap.get(this); - const cwd = slots ? slots.options.cwd : process.cwd(); - const namespace = naming.getNamespaceFromTerm(normalizedFormatName); - - let formatterPath; - - // if there's a slash, then it's a file (TODO: this check seems dubious for scoped npm packages) - if (!namespace && normalizedFormatName.indexOf("/") > -1) { - formatterPath = path.resolve(cwd, normalizedFormatName); - } else { - try { - const npmFormat = naming.normalizePackageName(normalizedFormatName, "eslint-formatter"); - - formatterPath = ModuleResolver.resolve(npmFormat, path.join(cwd, "__placeholder__.js")); - } catch { - formatterPath = path.resolve(__dirname, "formatters", normalizedFormatName); - } - } - - try { - return require(formatterPath); - } catch (ex) { - ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`; - throw ex; - } - - } else { - return null; - } - } -} - -CLIEngine.version = pkg.version; -CLIEngine.getFormatter = CLIEngine.prototype.getFormatter; - -module.exports = { - CLIEngine, - - /** - * Get the internal slots of a given CLIEngine instance for tests. - * @param {CLIEngine} instance The CLIEngine instance to get. - * @returns {CLIEngineInternalSlots} The internal slots. - */ - getCLIEngineInternalSlots(instance) { - return internalSlotsMap.get(instance); - } -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array-factory.js b/tools/node_modules/eslint/lib/cli-engine/config-array-factory.js deleted file mode 100644 index 2c7a79b491ecb32621b8ee1a366f47b8c5d2fa9c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array-factory.js +++ /dev/null @@ -1,1092 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview The factory of `ConfigArray` objects. - * - * This class provides methods to create `ConfigArray` instance. - * - * - `create(configData, options)` - * Create a `ConfigArray` instance from a config data. This is to handle CLI - * options except `--config`. - * - `loadFile(filePath, options)` - * Create a `ConfigArray` instance from a config file. This is to handle - * `--config` option. If the file was not found, throws the following error: - * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error. - * - If the filename was `package.json`, an IO error or an - * `ESLINT_CONFIG_FIELD_NOT_FOUND` error. - * - Otherwise, an IO error such as `ENOENT`. - * - `loadInDirectory(directoryPath, options)` - * Create a `ConfigArray` instance from a config file which is on a given - * directory. This tries to load `.eslintrc.*` or `package.json`. If not - * found, returns an empty `ConfigArray`. - * - `loadESLintIgnore(filePath)` - * Create a `ConfigArray` instance from a config file that is `.eslintignore` - * format. This is to handle `--ignore-path` option. - * - `loadDefaultESLintIgnore()` - * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in - * the current working directory. - * - * `ConfigArrayFactory` class has the responsibility that loads configuration - * files, including loading `extends`, `parser`, and `plugins`. The created - * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`. - * - * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class - * handles cascading and hierarchy. - * - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"); -const path = require("path"); -const importFresh = require("import-fresh"); -const stripComments = require("strip-json-comments"); -const { validateConfigSchema } = require("../shared/config-validator"); -const naming = require("@eslint/eslintrc/lib/shared/naming"); -const ModuleResolver = require("../shared/relative-module-resolver"); -const { - ConfigArray, - ConfigDependency, - IgnorePattern, - OverrideTester -} = require("./config-array"); -const debug = require("debug")("eslint:config-array-factory"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const eslintRecommendedPath = path.resolve(__dirname, "../../conf/eslint-recommended.js"); -const eslintAllPath = path.resolve(__dirname, "../../conf/eslint-all.js"); -const configFilenames = [ - ".eslintrc.js", - ".eslintrc.cjs", - ".eslintrc.yaml", - ".eslintrc.yml", - ".eslintrc.json", - ".eslintrc", - "package.json" -]; - -// Define types for VSCode IntelliSense. -/** @typedef {import("../shared/types").ConfigData} ConfigData */ -/** @typedef {import("../shared/types").OverrideConfigData} OverrideConfigData */ -/** @typedef {import("../shared/types").Parser} Parser */ -/** @typedef {import("../shared/types").Plugin} Plugin */ -/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */ -/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */ -/** @typedef {ConfigArray[0]} ConfigArrayElement */ - -/** - * @typedef {Object} ConfigArrayFactoryOptions - * @property {Map} [additionalPluginPool] The map for additional plugins. - * @property {string} [cwd] The path to the current working directory. - * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`. - */ - -/** - * @typedef {Object} ConfigArrayFactoryInternalSlots - * @property {Map} additionalPluginPool The map for additional plugins. - * @property {string} cwd The path to the current working directory. - * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from. - */ - -/** - * @typedef {Object} ConfigArrayFactoryLoadingContext - * @property {string} filePath The path to the current configuration. - * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. - * @property {string} name The name of the current configuration. - * @property {string} pluginBasePath The base path to resolve plugins. - * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. - */ - -/** - * @typedef {Object} ConfigArrayFactoryLoadingContext - * @property {string} filePath The path to the current configuration. - * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. - * @property {string} name The name of the current configuration. - * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. - */ - -/** @type {WeakMap} */ -const internalSlotsMap = new WeakMap(); - -/** - * Check if a given string is a file path. - * @param {string} nameOrPath A module name or file path. - * @returns {boolean} `true` if the `nameOrPath` is a file path. - */ -function isFilePath(nameOrPath) { - return ( - /^\.{1,2}[/\\]/u.test(nameOrPath) || - path.isAbsolute(nameOrPath) - ); -} - -/** - * Convenience wrapper for synchronously reading file contents. - * @param {string} filePath The filename to read. - * @returns {string} The file contents, with the BOM removed. - * @private - */ -function readFile(filePath) { - return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, ""); -} - -/** - * Loads a YAML configuration from a file. - * @param {string} filePath The filename to load. - * @returns {ConfigData} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadYAMLConfigFile(filePath) { - debug(`Loading YAML config file: ${filePath}`); - - // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); - - try { - - // empty YAML file can be null, so always use - return yaml.safeLoad(readFile(filePath)) || {}; - } catch (e) { - debug(`Error reading YAML file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a JSON configuration from a file. - * @param {string} filePath The filename to load. - * @returns {ConfigData} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadJSONConfigFile(filePath) { - debug(`Loading JSON config file: ${filePath}`); - - try { - return JSON.parse(stripComments(readFile(filePath))); - } catch (e) { - debug(`Error reading JSON file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - e.messageTemplate = "failed-to-read-json"; - e.messageData = { - path: filePath, - message: e.message - }; - throw e; - } -} - -/** - * Loads a legacy (.eslintrc) configuration from a file. - * @param {string} filePath The filename to load. - * @returns {ConfigData} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadLegacyConfigFile(filePath) { - debug(`Loading legacy config file: ${filePath}`); - - // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); - - try { - return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {}; - } catch (e) { - debug("Error reading YAML file: %s\n%o", filePath, e); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a JavaScript configuration from a file. - * @param {string} filePath The filename to load. - * @returns {ConfigData} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadJSConfigFile(filePath) { - debug(`Loading JS config file: ${filePath}`); - try { - return importFresh(filePath); - } catch (e) { - debug(`Error reading JavaScript file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a configuration from a package.json file. - * @param {string} filePath The filename to load. - * @returns {ConfigData} The configuration object from the file. - * @throws {Error} If the file cannot be read. - * @private - */ -function loadPackageJSONConfigFile(filePath) { - debug(`Loading package.json config file: ${filePath}`); - try { - const packageData = loadJSONConfigFile(filePath); - - if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) { - throw Object.assign( - new Error("package.json file doesn't have 'eslintConfig' field."), - { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" } - ); - } - - return packageData.eslintConfig; - } catch (e) { - debug(`Error reading package.json file: ${filePath}`); - e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Loads a `.eslintignore` from a file. - * @param {string} filePath The filename to load. - * @returns {string[]} The ignore patterns from the file. - * @private - */ -function loadESLintIgnoreFile(filePath) { - debug(`Loading .eslintignore file: ${filePath}`); - - try { - return readFile(filePath) - .split(/\r?\n/gu) - .filter(line => line.trim() !== "" && !line.startsWith("#")); - } catch (e) { - debug(`Error reading .eslintignore file: ${filePath}`); - e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`; - throw e; - } -} - -/** - * Creates an error to notify about a missing config to extend from. - * @param {string} configName The name of the missing config. - * @param {string} importerName The name of the config that imported the missing config - * @param {string} messageTemplate The text template to source error strings from. - * @returns {Error} The error object to throw - * @private - */ -function configInvalidError(configName, importerName, messageTemplate) { - return Object.assign( - new Error(`Failed to load config "${configName}" to extend from.`), - { - messageTemplate, - messageData: { configName, importerName } - } - ); -} - -/** - * Loads a configuration file regardless of the source. Inspects the file path - * to determine the correctly way to load the config file. - * @param {string} filePath The path to the configuration. - * @returns {ConfigData|null} The configuration information. - * @private - */ -function loadConfigFile(filePath) { - switch (path.extname(filePath)) { - case ".js": - case ".cjs": - return loadJSConfigFile(filePath); - - case ".json": - if (path.basename(filePath) === "package.json") { - return loadPackageJSONConfigFile(filePath); - } - return loadJSONConfigFile(filePath); - - case ".yaml": - case ".yml": - return loadYAMLConfigFile(filePath); - - default: - return loadLegacyConfigFile(filePath); - } -} - -/** - * Write debug log. - * @param {string} request The requested module name. - * @param {string} relativeTo The file path to resolve the request relative to. - * @param {string} filePath The resolved file path. - * @returns {void} - */ -function writeDebugLogForLoading(request, relativeTo, filePath) { - /* istanbul ignore next */ - if (debug.enabled) { - let nameAndVersion = null; - - try { - const packageJsonPath = ModuleResolver.resolve( - `${request}/package.json`, - relativeTo - ); - const { version = "unknown" } = require(packageJsonPath); - - nameAndVersion = `${request}@${version}`; - } catch (error) { - debug("package.json was not found:", error.message); - nameAndVersion = request; - } - - debug("Loaded: %s (%s)", nameAndVersion, filePath); - } -} - -/** - * Create a new context with default values. - * @param {ConfigArrayFactoryInternalSlots} slots The internal slots. - * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`. - * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`. - * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string. - * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`. - * @returns {ConfigArrayFactoryLoadingContext} The created context. - */ -function createContext( - { cwd, resolvePluginsRelativeTo }, - providedType, - providedName, - providedFilePath, - providedMatchBasePath -) { - const filePath = providedFilePath - ? path.resolve(cwd, providedFilePath) - : ""; - const matchBasePath = - (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) || - (filePath && path.dirname(filePath)) || - cwd; - const name = - providedName || - (filePath && path.relative(cwd, filePath)) || - ""; - const pluginBasePath = - resolvePluginsRelativeTo || - (filePath && path.dirname(filePath)) || - cwd; - const type = providedType || "config"; - - return { filePath, matchBasePath, name, pluginBasePath, type }; -} - -/** - * Normalize a given plugin. - * - Ensure the object to have four properties: configs, environments, processors, and rules. - * - Ensure the object to not have other properties. - * @param {Plugin} plugin The plugin to normalize. - * @returns {Plugin} The normalized plugin. - */ -function normalizePlugin(plugin) { - return { - configs: plugin.configs || {}, - environments: plugin.environments || {}, - processors: plugin.processors || {}, - rules: plugin.rules || {} - }; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * The factory of `ConfigArray` objects. - */ -class ConfigArrayFactory { - - /** - * Initialize this instance. - * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins. - */ - constructor({ - additionalPluginPool = new Map(), - cwd = process.cwd(), - resolvePluginsRelativeTo - } = {}) { - internalSlotsMap.set(this, { - additionalPluginPool, - cwd, - resolvePluginsRelativeTo: - resolvePluginsRelativeTo && - path.resolve(cwd, resolvePluginsRelativeTo) - }); - } - - /** - * Create `ConfigArray` instance from a config data. - * @param {ConfigData|null} configData The config data to create. - * @param {Object} [options] The options. - * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. - * @param {string} [options.filePath] The path to this config data. - * @param {string} [options.name] The config name. - * @returns {ConfigArray} Loaded config. - */ - create(configData, { basePath, filePath, name } = {}) { - if (!configData) { - return new ConfigArray(); - } - - const slots = internalSlotsMap.get(this); - const ctx = createContext(slots, "config", name, filePath, basePath); - const elements = this._normalizeConfigData(configData, ctx); - - return new ConfigArray(...elements); - } - - /** - * Load a config file. - * @param {string} filePath The path to a config file. - * @param {Object} [options] The options. - * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. - * @param {string} [options.name] The config name. - * @returns {ConfigArray} Loaded config. - */ - loadFile(filePath, { basePath, name } = {}) { - const slots = internalSlotsMap.get(this); - const ctx = createContext(slots, "config", name, filePath, basePath); - - return new ConfigArray(...this._loadConfigData(ctx)); - } - - /** - * Load the config file on a given directory if exists. - * @param {string} directoryPath The path to a directory. - * @param {Object} [options] The options. - * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. - * @param {string} [options.name] The config name. - * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. - */ - loadInDirectory(directoryPath, { basePath, name } = {}) { - const slots = internalSlotsMap.get(this); - - for (const filename of configFilenames) { - const ctx = createContext( - slots, - "config", - name, - path.join(directoryPath, filename), - basePath - ); - - if (fs.existsSync(ctx.filePath)) { - let configData; - - try { - configData = loadConfigFile(ctx.filePath); - } catch (error) { - if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") { - throw error; - } - } - - if (configData) { - debug(`Config file found: ${ctx.filePath}`); - return new ConfigArray( - ...this._normalizeConfigData(configData, ctx) - ); - } - } - } - - debug(`Config file not found on ${directoryPath}`); - return new ConfigArray(); - } - - /** - * Check if a config file on a given directory exists or not. - * @param {string} directoryPath The path to a directory. - * @returns {string | null} The path to the found config file. If not found then null. - */ - static getPathToConfigFileInDirectory(directoryPath) { - for (const filename of configFilenames) { - const filePath = path.join(directoryPath, filename); - - if (fs.existsSync(filePath)) { - if (filename === "package.json") { - try { - loadPackageJSONConfigFile(filePath); - return filePath; - } catch { /* ignore */ } - } else { - return filePath; - } - } - } - return null; - } - - /** - * Load `.eslintignore` file. - * @param {string} filePath The path to a `.eslintignore` file to load. - * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. - */ - loadESLintIgnore(filePath) { - const slots = internalSlotsMap.get(this); - const ctx = createContext( - slots, - "ignore", - void 0, - filePath, - slots.cwd - ); - const ignorePatterns = loadESLintIgnoreFile(ctx.filePath); - - return new ConfigArray( - ...this._normalizeESLintIgnoreData(ignorePatterns, ctx) - ); - } - - /** - * Load `.eslintignore` file in the current working directory. - * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. - */ - loadDefaultESLintIgnore() { - const slots = internalSlotsMap.get(this); - const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore"); - const packageJsonPath = path.resolve(slots.cwd, "package.json"); - - if (fs.existsSync(eslintIgnorePath)) { - return this.loadESLintIgnore(eslintIgnorePath); - } - if (fs.existsSync(packageJsonPath)) { - const data = loadJSONConfigFile(packageJsonPath); - - if (Object.hasOwnProperty.call(data, "eslintIgnore")) { - if (!Array.isArray(data.eslintIgnore)) { - throw new Error("Package.json eslintIgnore property requires an array of paths"); - } - const ctx = createContext( - slots, - "ignore", - "eslintIgnore in package.json", - packageJsonPath, - slots.cwd - ); - - return new ConfigArray( - ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx) - ); - } - } - - return new ConfigArray(); - } - - /** - * Load a given config file. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} Loaded config. - * @private - */ - _loadConfigData(ctx) { - return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx); - } - - /** - * Normalize a given `.eslintignore` data to config array elements. - * @param {string[]} ignorePatterns The patterns to ignore files. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - *_normalizeESLintIgnoreData(ignorePatterns, ctx) { - const elements = this._normalizeObjectConfigData( - { ignorePatterns }, - ctx - ); - - // Set `ignorePattern.loose` flag for backward compatibility. - for (const element of elements) { - if (element.ignorePattern) { - element.ignorePattern.loose = true; - } - yield element; - } - } - - /** - * Normalize a given config to an array. - * @param {ConfigData} configData The config data to normalize. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - _normalizeConfigData(configData, ctx) { - validateConfigSchema(configData, ctx.name || ctx.filePath); - return this._normalizeObjectConfigData(configData, ctx); - } - - /** - * Normalize a given config to an array. - * @param {ConfigData|OverrideConfigData} configData The config data to normalize. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - *_normalizeObjectConfigData(configData, ctx) { - const { files, excludedFiles, ...configBody } = configData; - const criteria = OverrideTester.create( - files, - excludedFiles, - ctx.matchBasePath - ); - const elements = this._normalizeObjectConfigDataBody(configBody, ctx); - - // Apply the criteria to every element. - for (const element of elements) { - - /* - * Merge the criteria. - * This is for the `overrides` entries that came from the - * configurations of `overrides[].extends`. - */ - element.criteria = OverrideTester.and(criteria, element.criteria); - - /* - * Remove `root` property to ignore `root` settings which came from - * `extends` in `overrides`. - */ - if (element.criteria) { - element.root = void 0; - } - - yield element; - } - } - - /** - * Normalize a given config to an array. - * @param {ConfigData} configData The config data to normalize. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - *_normalizeObjectConfigDataBody( - { - env, - extends: extend, - globals, - ignorePatterns, - noInlineConfig, - parser: parserName, - parserOptions, - plugins: pluginList, - processor, - reportUnusedDisableDirectives, - root, - rules, - settings, - overrides: overrideList = [] - }, - ctx - ) { - const extendList = Array.isArray(extend) ? extend : [extend]; - const ignorePattern = ignorePatterns && new IgnorePattern( - Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns], - ctx.matchBasePath - ); - - // Flatten `extends`. - for (const extendName of extendList.filter(Boolean)) { - yield* this._loadExtends(extendName, ctx); - } - - // Load parser & plugins. - const parser = parserName && this._loadParser(parserName, ctx); - const plugins = pluginList && this._loadPlugins(pluginList, ctx); - - // Yield pseudo config data for file extension processors. - if (plugins) { - yield* this._takeFileExtensionProcessors(plugins, ctx); - } - - // Yield the config data except `extends` and `overrides`. - yield { - - // Debug information. - type: ctx.type, - name: ctx.name, - filePath: ctx.filePath, - - // Config data. - criteria: null, - env, - globals, - ignorePattern, - noInlineConfig, - parser, - parserOptions, - plugins, - processor, - reportUnusedDisableDirectives, - root, - rules, - settings - }; - - // Flatten `overries`. - for (let i = 0; i < overrideList.length; ++i) { - yield* this._normalizeObjectConfigData( - overrideList[i], - { ...ctx, name: `${ctx.name}#overrides[${i}]` } - ); - } - } - - /** - * Load configs of an element in `extends`. - * @param {string} extendName The name of a base config. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - _loadExtends(extendName, ctx) { - debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath); - try { - if (extendName.startsWith("eslint:")) { - return this._loadExtendedBuiltInConfig(extendName, ctx); - } - if (extendName.startsWith("plugin:")) { - return this._loadExtendedPluginConfig(extendName, ctx); - } - return this._loadExtendedShareableConfig(extendName, ctx); - } catch (error) { - error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`; - throw error; - } - } - - /** - * Load configs of an element in `extends`. - * @param {string} extendName The name of a base config. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - _loadExtendedBuiltInConfig(extendName, ctx) { - if (extendName === "eslint:recommended") { - return this._loadConfigData({ - ...ctx, - filePath: eslintRecommendedPath, - name: `${ctx.name} » ${extendName}` - }); - } - if (extendName === "eslint:all") { - return this._loadConfigData({ - ...ctx, - filePath: eslintAllPath, - name: `${ctx.name} » ${extendName}` - }); - } - - throw configInvalidError(extendName, ctx.name, "extend-config-missing"); - } - - /** - * Load configs of an element in `extends`. - * @param {string} extendName The name of a base config. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - _loadExtendedPluginConfig(extendName, ctx) { - const slashIndex = extendName.lastIndexOf("/"); - - if (slashIndex === -1) { - throw configInvalidError(extendName, ctx.filePath, "plugin-invalid"); - } - - const pluginName = extendName.slice("plugin:".length, slashIndex); - const configName = extendName.slice(slashIndex + 1); - - if (isFilePath(pluginName)) { - throw new Error("'extends' cannot use a file path for plugins."); - } - - const plugin = this._loadPlugin(pluginName, ctx); - const configData = - plugin.definition && - plugin.definition.configs[configName]; - - if (configData) { - return this._normalizeConfigData(configData, { - ...ctx, - filePath: plugin.filePath || ctx.filePath, - name: `${ctx.name} » plugin:${plugin.id}/${configName}` - }); - } - - throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing"); - } - - /** - * Load configs of an element in `extends`. - * @param {string} extendName The name of a base config. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The normalized config. - * @private - */ - _loadExtendedShareableConfig(extendName, ctx) { - const { cwd } = internalSlotsMap.get(this); - const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js"); - let request; - - if (isFilePath(extendName)) { - request = extendName; - } else if (extendName.startsWith(".")) { - request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior. - } else { - request = naming.normalizePackageName( - extendName, - "eslint-config" - ); - } - - let filePath; - - try { - filePath = ModuleResolver.resolve(request, relativeTo); - } catch (error) { - /* istanbul ignore else */ - if (error && error.code === "MODULE_NOT_FOUND") { - throw configInvalidError(extendName, ctx.filePath, "extend-config-missing"); - } - throw error; - } - - writeDebugLogForLoading(request, relativeTo, filePath); - return this._loadConfigData({ - ...ctx, - filePath, - name: `${ctx.name} » ${request}` - }); - } - - /** - * Load given plugins. - * @param {string[]} names The plugin names to load. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {Record} The loaded parser. - * @private - */ - _loadPlugins(names, ctx) { - return names.reduce((map, name) => { - if (isFilePath(name)) { - throw new Error("Plugins array cannot includes file paths."); - } - const plugin = this._loadPlugin(name, ctx); - - map[plugin.id] = plugin; - - return map; - }, {}); - } - - /** - * Load a given parser. - * @param {string} nameOrPath The package name or the path to a parser file. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {DependentParser} The loaded parser. - */ - _loadParser(nameOrPath, ctx) { - debug("Loading parser %j from %s", nameOrPath, ctx.filePath); - - const { cwd } = internalSlotsMap.get(this); - const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js"); - - try { - const filePath = ModuleResolver.resolve(nameOrPath, relativeTo); - - writeDebugLogForLoading(nameOrPath, relativeTo, filePath); - - return new ConfigDependency({ - definition: require(filePath), - filePath, - id: nameOrPath, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } catch (error) { - - // If the parser name is "espree", load the espree of ESLint. - if (nameOrPath === "espree") { - debug("Fallback espree."); - return new ConfigDependency({ - definition: require("espree"), - filePath: require.resolve("espree"), - id: nameOrPath, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } - - debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name); - error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`; - - return new ConfigDependency({ - error, - id: nameOrPath, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } - } - - /** - * Load a given plugin. - * @param {string} name The plugin name to load. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {DependentPlugin} The loaded plugin. - * @private - */ - _loadPlugin(name, ctx) { - debug("Loading plugin %j from %s", name, ctx.filePath); - - const { additionalPluginPool } = internalSlotsMap.get(this); - const request = naming.normalizePackageName(name, "eslint-plugin"); - const id = naming.getShorthandName(request, "eslint-plugin"); - const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js"); - - if (name.match(/\s+/u)) { - const error = Object.assign( - new Error(`Whitespace found in plugin name '${name}'`), - { - messageTemplate: "whitespace-found", - messageData: { pluginName: request } - } - ); - - return new ConfigDependency({ - error, - id, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } - - // Check for additional pool. - const plugin = - additionalPluginPool.get(request) || - additionalPluginPool.get(id); - - if (plugin) { - return new ConfigDependency({ - definition: normalizePlugin(plugin), - filePath: "", // It's unknown where the plugin came from. - id, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } - - let filePath; - let error; - - try { - filePath = ModuleResolver.resolve(request, relativeTo); - } catch (resolveError) { - error = resolveError; - /* istanbul ignore else */ - if (error && error.code === "MODULE_NOT_FOUND") { - error.messageTemplate = "plugin-missing"; - error.messageData = { - pluginName: request, - resolvePluginsRelativeTo: ctx.pluginBasePath, - importerName: ctx.name - }; - } - } - - if (filePath) { - try { - writeDebugLogForLoading(request, relativeTo, filePath); - - const startTime = Date.now(); - const pluginDefinition = require(filePath); - - debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`); - - return new ConfigDependency({ - definition: normalizePlugin(pluginDefinition), - filePath, - id, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } catch (loadError) { - error = loadError; - } - } - - debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name); - error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`; - return new ConfigDependency({ - error, - id, - importerName: ctx.name, - importerPath: ctx.filePath - }); - } - - /** - * Take file expression processors as config array elements. - * @param {Record} plugins The plugin definitions. - * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. - * @returns {IterableIterator} The config array elements of file expression processors. - * @private - */ - *_takeFileExtensionProcessors(plugins, ctx) { - for (const pluginId of Object.keys(plugins)) { - const processors = - plugins[pluginId] && - plugins[pluginId].definition && - plugins[pluginId].definition.processors; - - if (!processors) { - continue; - } - - for (const processorId of Object.keys(processors)) { - if (processorId.startsWith(".")) { - yield* this._normalizeObjectConfigData( - { - files: [`*${processorId}`], - processor: `${pluginId}/${processorId}` - }, - { - ...ctx, - type: "implicit-processor", - name: `${ctx.name}#processors["${pluginId}/${processorId}"]` - } - ); - } - } - } - } -} - -module.exports = { ConfigArrayFactory, createContext }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/config-array.js b/tools/node_modules/eslint/lib/cli-engine/config-array/config-array.js deleted file mode 100644 index c2ef6c94ab04149e349260386f31ce173011e642..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array/config-array.js +++ /dev/null @@ -1,536 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `ConfigArray` class. - * - * `ConfigArray` class expresses the full of a configuration. It has the entry - * config file, base config files that were extended, loaded parsers, and loaded - * plugins. - * - * `ConfigArray` class provides three properties and two methods. - * - * - `pluginEnvironments` - * - `pluginProcessors` - * - `pluginRules` - * The `Map` objects that contain the members of all plugins that this - * config array contains. Those map objects don't have mutation methods. - * Those keys are the member ID such as `pluginId/memberName`. - * - `isRoot()` - * If `true` then this configuration has `root:true` property. - * - `extractConfig(filePath)` - * Extract the final configuration for a given file. This means merging - * every config array element which that `criteria` property matched. The - * `filePath` argument must be an absolute path. - * - * `ConfigArrayFactory` provides the loading logic of config files. - * - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { ExtractedConfig } = require("./extracted-config"); -const { IgnorePattern } = require("./ignore-pattern"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -// Define types for VSCode IntelliSense. -/** @typedef {import("../../shared/types").Environment} Environment */ -/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ -/** @typedef {import("../../shared/types").RuleConf} RuleConf */ -/** @typedef {import("../../shared/types").Rule} Rule */ -/** @typedef {import("../../shared/types").Plugin} Plugin */ -/** @typedef {import("../../shared/types").Processor} Processor */ -/** @typedef {import("./config-dependency").DependentParser} DependentParser */ -/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ -/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */ - -/** - * @typedef {Object} ConfigArrayElement - * @property {string} name The name of this config element. - * @property {string} filePath The path to the source file of this config element. - * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element. - * @property {Record|undefined} env The environment settings. - * @property {Record|undefined} globals The global variable settings. - * @property {IgnorePattern|undefined} ignorePattern The ignore patterns. - * @property {boolean|undefined} noInlineConfig The flag that disables directive comments. - * @property {DependentParser|undefined} parser The parser loader. - * @property {Object|undefined} parserOptions The parser options. - * @property {Record|undefined} plugins The plugin loaders. - * @property {string|undefined} processor The processor name to refer plugin's processor. - * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments. - * @property {boolean|undefined} root The flag to express root. - * @property {Record|undefined} rules The rule settings - * @property {Object|undefined} settings The shared settings. - * @property {"config" | "ignore" | "implicit-processor"} type The element type. - */ - -/** - * @typedef {Object} ConfigArrayInternalSlots - * @property {Map} cache The cache to extract configs. - * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition. - * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition. - * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition. - */ - -/** @type {WeakMap} */ -const internalSlotsMap = new class extends WeakMap { - get(key) { - let value = super.get(key); - - if (!value) { - value = { - cache: new Map(), - envMap: null, - processorMap: null, - ruleMap: null - }; - super.set(key, value); - } - - return value; - } -}(); - -/** - * Get the indices which are matched to a given file. - * @param {ConfigArrayElement[]} elements The elements. - * @param {string} filePath The path to a target file. - * @returns {number[]} The indices. - */ -function getMatchedIndices(elements, filePath) { - const indices = []; - - for (let i = elements.length - 1; i >= 0; --i) { - const element = elements[i]; - - if (!element.criteria || (filePath && element.criteria.test(filePath))) { - indices.push(i); - } - } - - return indices; -} - -/** - * Check if a value is a non-null object. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is a non-null object. - */ -function isNonNullObject(x) { - return typeof x === "object" && x !== null; -} - -/** - * Merge two objects. - * - * Assign every property values of `y` to `x` if `x` doesn't have the property. - * If `x`'s property value is an object, it does recursive. - * @param {Object} target The destination to merge - * @param {Object|undefined} source The source to merge. - * @returns {void} - */ -function mergeWithoutOverwrite(target, source) { - if (!isNonNullObject(source)) { - return; - } - - for (const key of Object.keys(source)) { - if (key === "__proto__") { - continue; - } - - if (isNonNullObject(target[key])) { - mergeWithoutOverwrite(target[key], source[key]); - } else if (target[key] === void 0) { - if (isNonNullObject(source[key])) { - target[key] = Array.isArray(source[key]) ? [] : {}; - mergeWithoutOverwrite(target[key], source[key]); - } else if (source[key] !== void 0) { - target[key] = source[key]; - } - } - } -} - -/** - * The error for plugin conflicts. - */ -class PluginConflictError extends Error { - - /** - * Initialize this error object. - * @param {string} pluginId The plugin ID. - * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins. - */ - constructor(pluginId, plugins) { - super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`); - this.messageTemplate = "plugin-conflict"; - this.messageData = { pluginId, plugins }; - } -} - -/** - * Merge plugins. - * `target`'s definition is prior to `source`'s. - * @param {Record} target The destination to merge - * @param {Record|undefined} source The source to merge. - * @returns {void} - */ -function mergePlugins(target, source) { - if (!isNonNullObject(source)) { - return; - } - - for (const key of Object.keys(source)) { - if (key === "__proto__") { - continue; - } - const targetValue = target[key]; - const sourceValue = source[key]; - - // Adopt the plugin which was found at first. - if (targetValue === void 0) { - if (sourceValue.error) { - throw sourceValue.error; - } - target[key] = sourceValue; - } else if (sourceValue.filePath !== targetValue.filePath) { - throw new PluginConflictError(key, [ - { - filePath: targetValue.filePath, - importerName: targetValue.importerName - }, - { - filePath: sourceValue.filePath, - importerName: sourceValue.importerName - } - ]); - } - } -} - -/** - * Merge rule configs. - * `target`'s definition is prior to `source`'s. - * @param {Record} target The destination to merge - * @param {Record|undefined} source The source to merge. - * @returns {void} - */ -function mergeRuleConfigs(target, source) { - if (!isNonNullObject(source)) { - return; - } - - for (const key of Object.keys(source)) { - if (key === "__proto__") { - continue; - } - const targetDef = target[key]; - const sourceDef = source[key]; - - // Adopt the rule config which was found at first. - if (targetDef === void 0) { - if (Array.isArray(sourceDef)) { - target[key] = [...sourceDef]; - } else { - target[key] = [sourceDef]; - } - - /* - * If the first found rule config is severity only and the current rule - * config has options, merge the severity and the options. - */ - } else if ( - targetDef.length === 1 && - Array.isArray(sourceDef) && - sourceDef.length >= 2 - ) { - targetDef.push(...sourceDef.slice(1)); - } - } -} - -/** - * Create the extracted config. - * @param {ConfigArray} instance The config elements. - * @param {number[]} indices The indices to use. - * @returns {ExtractedConfig} The extracted config. - */ -function createConfig(instance, indices) { - const config = new ExtractedConfig(); - const ignorePatterns = []; - - // Merge elements. - for (const index of indices) { - const element = instance[index]; - - // Adopt the parser which was found at first. - if (!config.parser && element.parser) { - if (element.parser.error) { - throw element.parser.error; - } - config.parser = element.parser; - } - - // Adopt the processor which was found at first. - if (!config.processor && element.processor) { - config.processor = element.processor; - } - - // Adopt the noInlineConfig which was found at first. - if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) { - config.noInlineConfig = element.noInlineConfig; - config.configNameOfNoInlineConfig = element.name; - } - - // Adopt the reportUnusedDisableDirectives which was found at first. - if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) { - config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives; - } - - // Collect ignorePatterns - if (element.ignorePattern) { - ignorePatterns.push(element.ignorePattern); - } - - // Merge others. - mergeWithoutOverwrite(config.env, element.env); - mergeWithoutOverwrite(config.globals, element.globals); - mergeWithoutOverwrite(config.parserOptions, element.parserOptions); - mergeWithoutOverwrite(config.settings, element.settings); - mergePlugins(config.plugins, element.plugins); - mergeRuleConfigs(config.rules, element.rules); - } - - // Create the predicate function for ignore patterns. - if (ignorePatterns.length > 0) { - config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse()); - } - - return config; -} - -/** - * Collect definitions. - * @template T, U - * @param {string} pluginId The plugin ID for prefix. - * @param {Record} defs The definitions to collect. - * @param {Map} map The map to output. - * @param {function(T): U} [normalize] The normalize function for each value. - * @returns {void} - */ -function collect(pluginId, defs, map, normalize) { - if (defs) { - const prefix = pluginId && `${pluginId}/`; - - for (const [key, value] of Object.entries(defs)) { - map.set( - `${prefix}${key}`, - normalize ? normalize(value) : value - ); - } - } -} - -/** - * Normalize a rule definition. - * @param {Function|Rule} rule The rule definition to normalize. - * @returns {Rule} The normalized rule definition. - */ -function normalizePluginRule(rule) { - return typeof rule === "function" ? { create: rule } : rule; -} - -/** - * Delete the mutation methods from a given map. - * @param {Map} map The map object to delete. - * @returns {void} - */ -function deleteMutationMethods(map) { - Object.defineProperties(map, { - clear: { configurable: true, value: void 0 }, - delete: { configurable: true, value: void 0 }, - set: { configurable: true, value: void 0 } - }); -} - -/** - * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. - * @param {ConfigArrayElement[]} elements The config elements. - * @param {ConfigArrayInternalSlots} slots The internal slots. - * @returns {void} - */ -function initPluginMemberMaps(elements, slots) { - const processed = new Set(); - - slots.envMap = new Map(); - slots.processorMap = new Map(); - slots.ruleMap = new Map(); - - for (const element of elements) { - if (!element.plugins) { - continue; - } - - for (const [pluginId, value] of Object.entries(element.plugins)) { - const plugin = value.definition; - - if (!plugin || processed.has(pluginId)) { - continue; - } - processed.add(pluginId); - - collect(pluginId, plugin.environments, slots.envMap); - collect(pluginId, plugin.processors, slots.processorMap); - collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule); - } - } - - deleteMutationMethods(slots.envMap); - deleteMutationMethods(slots.processorMap); - deleteMutationMethods(slots.ruleMap); -} - -/** - * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. - * @param {ConfigArray} instance The config elements. - * @returns {ConfigArrayInternalSlots} The extracted config. - */ -function ensurePluginMemberMaps(instance) { - const slots = internalSlotsMap.get(instance); - - if (!slots.ruleMap) { - initPluginMemberMaps(instance, slots); - } - - return slots; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * The Config Array. - * - * `ConfigArray` instance contains all settings, parsers, and plugins. - * You need to call `ConfigArray#extractConfig(filePath)` method in order to - * extract, merge and get only the config data which is related to an arbitrary - * file. - * @extends {Array} - */ -class ConfigArray extends Array { - - /** - * Get the plugin environments. - * The returned map cannot be mutated. - * @type {ReadonlyMap} The plugin environments. - */ - get pluginEnvironments() { - return ensurePluginMemberMaps(this).envMap; - } - - /** - * Get the plugin processors. - * The returned map cannot be mutated. - * @type {ReadonlyMap} The plugin processors. - */ - get pluginProcessors() { - return ensurePluginMemberMaps(this).processorMap; - } - - /** - * Get the plugin rules. - * The returned map cannot be mutated. - * @returns {ReadonlyMap} The plugin rules. - */ - get pluginRules() { - return ensurePluginMemberMaps(this).ruleMap; - } - - /** - * Check if this config has `root` flag. - * @returns {boolean} `true` if this config array is root. - */ - isRoot() { - for (let i = this.length - 1; i >= 0; --i) { - const root = this[i].root; - - if (typeof root === "boolean") { - return root; - } - } - return false; - } - - /** - * Extract the config data which is related to a given file. - * @param {string} filePath The absolute path to the target file. - * @returns {ExtractedConfig} The extracted config data. - */ - extractConfig(filePath) { - const { cache } = internalSlotsMap.get(this); - const indices = getMatchedIndices(this, filePath); - const cacheKey = indices.join(","); - - if (!cache.has(cacheKey)) { - cache.set(cacheKey, createConfig(this, indices)); - } - - return cache.get(cacheKey); - } - - /** - * Check if a given path is an additional lint target. - * @param {string} filePath The absolute path to the target file. - * @returns {boolean} `true` if the file is an additional lint target. - */ - isAdditionalTargetPath(filePath) { - for (const { criteria, type } of this) { - if ( - type === "config" && - criteria && - !criteria.endsWithWildcard && - criteria.test(filePath) - ) { - return true; - } - } - return false; - } -} - -const exportObject = { - ConfigArray, - - /** - * Get the used extracted configs. - * CLIEngine will use this method to collect used deprecated rules. - * @param {ConfigArray} instance The config array object to get. - * @returns {ExtractedConfig[]} The used extracted configs. - * @private - */ - getUsedExtractedConfigs(instance) { - const { cache } = internalSlotsMap.get(instance); - - return Array.from(cache.values()); - } -}; - -module.exports = exportObject; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/config-dependency.js b/tools/node_modules/eslint/lib/cli-engine/config-array/config-dependency.js deleted file mode 100644 index 9fc67b0105792df43283ef1f39ff371a442a8ca2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array/config-dependency.js +++ /dev/null @@ -1,128 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `ConfigDependency` class. - * - * `ConfigDependency` class expresses a loaded parser or plugin. - * - * If the parser or plugin was loaded successfully, it has `definition` property - * and `filePath` property. Otherwise, it has `error` property. - * - * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it - * omits `definition` property. - * - * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers - * or plugins. - * - * @author Toru Nagashima - */ -"use strict"; - -const util = require("util"); - -/** - * The class is to store parsers or plugins. - * This class hides the loaded object from `JSON.stringify()` and `console.log`. - * @template T - */ -class ConfigDependency { - - /** - * Initialize this instance. - * @param {Object} data The dependency data. - * @param {T} [data.definition] The dependency if the loading succeeded. - * @param {Error} [data.error] The error object if the loading failed. - * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded. - * @param {string} data.id The ID of this dependency. - * @param {string} data.importerName The name of the config file which loads this dependency. - * @param {string} data.importerPath The path to the config file which loads this dependency. - */ - constructor({ - definition = null, - error = null, - filePath = null, - id, - importerName, - importerPath - }) { - - /** - * The loaded dependency if the loading succeeded. - * @type {T|null} - */ - this.definition = definition; - - /** - * The error object if the loading failed. - * @type {Error|null} - */ - this.error = error; - - /** - * The loaded dependency if the loading succeeded. - * @type {string|null} - */ - this.filePath = filePath; - - /** - * The ID of this dependency. - * @type {string} - */ - this.id = id; - - /** - * The name of the config file which loads this dependency. - * @type {string} - */ - this.importerName = importerName; - - /** - * The path to the config file which loads this dependency. - * @type {string} - */ - this.importerPath = importerPath; - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @returns {Object} a JSON compatible object. - */ - toJSON() { - const obj = this[util.inspect.custom](); - - // Display `error.message` (`Error#message` is unenumerable). - if (obj.error instanceof Error) { - obj.error = { ...obj.error, message: obj.error.message }; - } - - return obj; - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @returns {Object} an object to display by `console.log()`. - */ - [util.inspect.custom]() { - const { - definition: _ignore, // eslint-disable-line no-unused-vars - ...obj - } = this; - - return obj; - } -} - -/** @typedef {ConfigDependency} DependentParser */ -/** @typedef {ConfigDependency} DependentPlugin */ - -module.exports = { ConfigDependency }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/extracted-config.js b/tools/node_modules/eslint/lib/cli-engine/config-array/extracted-config.js deleted file mode 100644 index fd7cabab3e97b282aa20aac2c9a29caacab614d5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array/extracted-config.js +++ /dev/null @@ -1,158 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `ExtractedConfig` class. - * - * `ExtractedConfig` class expresses a final configuration for a specific file. - * - * It provides one method. - * - * - `toCompatibleObjectAsConfigFileContent()` - * Convert this configuration to the compatible object as the content of - * config files. It converts the loaded parser and plugins to strings. - * `CLIEngine#getConfigForFile(filePath)` method uses this method. - * - * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance. - * - * @author Toru Nagashima - */ -"use strict"; - -const { IgnorePattern } = require("./ignore-pattern"); - -// For VSCode intellisense -/** @typedef {import("../../shared/types").ConfigData} ConfigData */ -/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ -/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */ -/** @typedef {import("./config-dependency").DependentParser} DependentParser */ -/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ - -/** - * Check if `xs` starts with `ys`. - * @template T - * @param {T[]} xs The array to check. - * @param {T[]} ys The array that may be the first part of `xs`. - * @returns {boolean} `true` if `xs` starts with `ys`. - */ -function startsWith(xs, ys) { - return xs.length >= ys.length && ys.every((y, i) => y === xs[i]); -} - -/** - * The class for extracted config data. - */ -class ExtractedConfig { - constructor() { - - /** - * The config name what `noInlineConfig` setting came from. - * @type {string} - */ - this.configNameOfNoInlineConfig = ""; - - /** - * Environments. - * @type {Record} - */ - this.env = {}; - - /** - * Global variables. - * @type {Record} - */ - this.globals = {}; - - /** - * The glob patterns that ignore to lint. - * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined} - */ - this.ignores = void 0; - - /** - * The flag that disables directive comments. - * @type {boolean|undefined} - */ - this.noInlineConfig = void 0; - - /** - * Parser definition. - * @type {DependentParser|null} - */ - this.parser = null; - - /** - * Options for the parser. - * @type {Object} - */ - this.parserOptions = {}; - - /** - * Plugin definitions. - * @type {Record} - */ - this.plugins = {}; - - /** - * Processor ID. - * @type {string|null} - */ - this.processor = null; - - /** - * The flag that reports unused `eslint-disable` directive comments. - * @type {boolean|undefined} - */ - this.reportUnusedDisableDirectives = void 0; - - /** - * Rule settings. - * @type {Record} - */ - this.rules = {}; - - /** - * Shared settings. - * @type {Object} - */ - this.settings = {}; - } - - /** - * Convert this config to the compatible object as a config file content. - * @returns {ConfigData} The converted object. - */ - toCompatibleObjectAsConfigFileContent() { - const { - /* eslint-disable no-unused-vars */ - configNameOfNoInlineConfig: _ignore1, - processor: _ignore2, - /* eslint-enable no-unused-vars */ - ignores, - ...config - } = this; - - config.parser = config.parser && config.parser.filePath; - config.plugins = Object.keys(config.plugins).filter(Boolean).reverse(); - config.ignorePatterns = ignores ? ignores.patterns : []; - - // Strip the default patterns from `ignorePatterns`. - if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) { - config.ignorePatterns = - config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length); - } - - return config; - } -} - -module.exports = { ExtractedConfig }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/ignore-pattern.js b/tools/node_modules/eslint/lib/cli-engine/config-array/ignore-pattern.js deleted file mode 100644 index 37d686dd1bb9cf615278d5366453fc79149b19c9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array/ignore-pattern.js +++ /dev/null @@ -1,249 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `IgnorePattern` class. - * - * `IgnorePattern` class has the set of glob patterns and the base path. - * - * It provides two static methods. - * - * - `IgnorePattern.createDefaultIgnore(cwd)` - * Create the default predicate function. - * - `IgnorePattern.createIgnore(ignorePatterns)` - * Create the predicate function from multiple `IgnorePattern` objects. - * - * It provides two properties and a method. - * - * - `patterns` - * The glob patterns that ignore to lint. - * - `basePath` - * The base path of the glob patterns. If absolute paths existed in the - * glob patterns, those are handled as relative paths to the base path. - * - `getPatternsRelativeTo(basePath)` - * Get `patterns` as modified for a given base path. It modifies the - * absolute paths in the patterns as prepending the difference of two base - * paths. - * - * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes - * `ignorePatterns` properties. - * - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"); -const path = require("path"); -const ignore = require("ignore"); -const debug = require("debug")("eslint:ignore-pattern"); - -/** @typedef {ReturnType} Ignore */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Get the path to the common ancestor directory of given paths. - * @param {string[]} sourcePaths The paths to calculate the common ancestor. - * @returns {string} The path to the common ancestor directory. - */ -function getCommonAncestorPath(sourcePaths) { - let result = sourcePaths[0]; - - for (let i = 1; i < sourcePaths.length; ++i) { - const a = result; - const b = sourcePaths[i]; - - // Set the shorter one (it's the common ancestor if one includes the other). - result = a.length < b.length ? a : b; - - // Set the common ancestor. - for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) { - if (a[j] !== b[j]) { - result = a.slice(0, lastSepPos); - break; - } - if (a[j] === path.sep) { - lastSepPos = j; - } - } - } - - let resolvedResult = result || path.sep; - - // if Windows common ancestor is root of drive must have trailing slash to be absolute. - if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") { - resolvedResult += path.sep; - } - return resolvedResult; -} - -/** - * Make relative path. - * @param {string} from The source path to get relative path. - * @param {string} to The destination path to get relative path. - * @returns {string} The relative path. - */ -function relative(from, to) { - const relPath = path.relative(from, to); - - if (path.sep === "/") { - return relPath; - } - return relPath.split(path.sep).join("/"); -} - -/** - * Get the trailing slash if existed. - * @param {string} filePath The path to check. - * @returns {string} The trailing slash if existed. - */ -function dirSuffix(filePath) { - const isDir = ( - filePath.endsWith(path.sep) || - (process.platform === "win32" && filePath.endsWith("/")) - ); - - return isDir ? "/" : ""; -} - -const DefaultPatterns = Object.freeze(["/**/node_modules/*"]); -const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]); - -//------------------------------------------------------------------------------ -// Public -//------------------------------------------------------------------------------ - -class IgnorePattern { - - /** - * The default patterns. - * @type {string[]} - */ - static get DefaultPatterns() { - return DefaultPatterns; - } - - /** - * Create the default predicate function. - * @param {string} cwd The current working directory. - * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}} - * The preficate function. - * The first argument is an absolute path that is checked. - * The second argument is the flag to not ignore dotfiles. - * If the predicate function returned `true`, it means the path should be ignored. - */ - static createDefaultIgnore(cwd) { - return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]); - } - - /** - * Create the predicate function from multiple `IgnorePattern` objects. - * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns. - * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}} - * The preficate function. - * The first argument is an absolute path that is checked. - * The second argument is the flag to not ignore dotfiles. - * If the predicate function returned `true`, it means the path should be ignored. - */ - static createIgnore(ignorePatterns) { - debug("Create with: %o", ignorePatterns); - - const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath)); - const patterns = [].concat( - ...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath)) - ); - const ig = ignore().add([...DotPatterns, ...patterns]); - const dotIg = ignore().add(patterns); - - debug(" processed: %o", { basePath, patterns }); - - return Object.assign( - (filePath, dot = false) => { - assert(path.isAbsolute(filePath), "'filePath' should be an absolute path."); - const relPathRaw = relative(basePath, filePath); - const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath)); - const adoptedIg = dot ? dotIg : ig; - const result = relPath !== "" && adoptedIg.ignores(relPath); - - debug("Check", { filePath, dot, relativePath: relPath, result }); - return result; - }, - { basePath, patterns } - ); - } - - /** - * Initialize a new `IgnorePattern` instance. - * @param {string[]} patterns The glob patterns that ignore to lint. - * @param {string} basePath The base path of `patterns`. - */ - constructor(patterns, basePath) { - assert(path.isAbsolute(basePath), "'basePath' should be an absolute path."); - - /** - * The glob patterns that ignore to lint. - * @type {string[]} - */ - this.patterns = patterns; - - /** - * The base path of `patterns`. - * @type {string} - */ - this.basePath = basePath; - - /** - * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`. - * - * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility. - * It's `false` as-is for `ignorePatterns` property in config files. - * @type {boolean} - */ - this.loose = false; - } - - /** - * Get `patterns` as modified for a given base path. It modifies the - * absolute paths in the patterns as prepending the difference of two base - * paths. - * @param {string} newBasePath The base path. - * @returns {string[]} Modifired patterns. - */ - getPatternsRelativeTo(newBasePath) { - assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path."); - const { basePath, loose, patterns } = this; - - if (newBasePath === basePath) { - return patterns; - } - const prefix = `/${relative(newBasePath, basePath)}`; - - return patterns.map(pattern => { - const negative = pattern.startsWith("!"); - const head = negative ? "!" : ""; - const body = negative ? pattern.slice(1) : pattern; - - if (body.startsWith("/") || body.startsWith("../")) { - return `${head}${prefix}${body}`; - } - return loose ? pattern : `${head}${prefix}/**/${body}`; - }); - } -} - -module.exports = { IgnorePattern }; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/index.js b/tools/node_modules/eslint/lib/cli-engine/config-array/index.js deleted file mode 100644 index 146c6f8927967ec9066cc4554810437ae4f6bdb2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array/index.js +++ /dev/null @@ -1,32 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `ConfigArray` class. - * @author Toru Nagashima - */ -"use strict"; - -const { ConfigArray, getUsedExtractedConfigs } = require("./config-array"); -const { ConfigDependency } = require("./config-dependency"); -const { ExtractedConfig } = require("./extracted-config"); -const { IgnorePattern } = require("./ignore-pattern"); -const { OverrideTester } = require("./override-tester"); - -module.exports = { - ConfigArray, - ConfigDependency, - ExtractedConfig, - IgnorePattern, - OverrideTester, - getUsedExtractedConfigs -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/config-array/override-tester.js b/tools/node_modules/eslint/lib/cli-engine/config-array/override-tester.js deleted file mode 100644 index 75dffe2352e9acc05d52b90fa3d83e98fefef130..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/config-array/override-tester.js +++ /dev/null @@ -1,235 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview `OverrideTester` class. - * - * `OverrideTester` class handles `files` property and `excludedFiles` property - * of `overrides` config. - * - * It provides one method. - * - * - `test(filePath)` - * Test if a file path matches the pair of `files` property and - * `excludedFiles` property. The `filePath` argument must be an absolute - * path. - * - * `ConfigArrayFactory` creates `OverrideTester` objects when it processes - * `overrides` properties. - * - * @author Toru Nagashima - */ -"use strict"; - -const assert = require("assert"); -const path = require("path"); -const util = require("util"); -const { Minimatch } = require("minimatch"); -const minimatchOpts = { dot: true, matchBase: true }; - -/** - * @typedef {Object} Pattern - * @property {InstanceType[] | null} includes The positive matchers. - * @property {InstanceType[] | null} excludes The negative matchers. - */ - -/** - * Normalize a given pattern to an array. - * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns. - * @returns {string[]|null} Normalized patterns. - * @private - */ -function normalizePatterns(patterns) { - if (Array.isArray(patterns)) { - return patterns.filter(Boolean); - } - if (typeof patterns === "string" && patterns) { - return [patterns]; - } - return []; -} - -/** - * Create the matchers of given patterns. - * @param {string[]} patterns The patterns. - * @returns {InstanceType[] | null} The matchers. - */ -function toMatcher(patterns) { - if (patterns.length === 0) { - return null; - } - return patterns.map(pattern => { - if (/^\.[/\\]/u.test(pattern)) { - return new Minimatch( - pattern.slice(2), - - // `./*.js` should not match with `subdir/foo.js` - { ...minimatchOpts, matchBase: false } - ); - } - return new Minimatch(pattern, minimatchOpts); - }); -} - -/** - * Convert a given matcher to string. - * @param {Pattern} matchers The matchers. - * @returns {string} The string expression of the matcher. - */ -function patternToJson({ includes, excludes }) { - return { - includes: includes && includes.map(m => m.pattern), - excludes: excludes && excludes.map(m => m.pattern) - }; -} - -/** - * The class to test given paths are matched by the patterns. - */ -class OverrideTester { - - /** - * Create a tester with given criteria. - * If there are no criteria, returns `null`. - * @param {string|string[]} files The glob patterns for included files. - * @param {string|string[]} excludedFiles The glob patterns for excluded files. - * @param {string} basePath The path to the base directory to test paths. - * @returns {OverrideTester|null} The created instance or `null`. - */ - static create(files, excludedFiles, basePath) { - const includePatterns = normalizePatterns(files); - const excludePatterns = normalizePatterns(excludedFiles); - let endsWithWildcard = false; - - if (includePatterns.length === 0) { - return null; - } - - // Rejects absolute paths or relative paths to parents. - for (const pattern of includePatterns) { - if (path.isAbsolute(pattern) || pattern.includes("..")) { - throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); - } - if (pattern.endsWith("*")) { - endsWithWildcard = true; - } - } - for (const pattern of excludePatterns) { - if (path.isAbsolute(pattern) || pattern.includes("..")) { - throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); - } - } - - const includes = toMatcher(includePatterns); - const excludes = toMatcher(excludePatterns); - - return new OverrideTester( - [{ includes, excludes }], - basePath, - endsWithWildcard - ); - } - - /** - * Combine two testers by logical and. - * If either of the testers was `null`, returns the other tester. - * The `basePath` property of the two must be the same value. - * @param {OverrideTester|null} a A tester. - * @param {OverrideTester|null} b Another tester. - * @returns {OverrideTester|null} Combined tester. - */ - static and(a, b) { - if (!b) { - return a && new OverrideTester( - a.patterns, - a.basePath, - a.endsWithWildcard - ); - } - if (!a) { - return new OverrideTester( - b.patterns, - b.basePath, - b.endsWithWildcard - ); - } - - assert.strictEqual(a.basePath, b.basePath); - return new OverrideTester( - a.patterns.concat(b.patterns), - a.basePath, - a.endsWithWildcard || b.endsWithWildcard - ); - } - - /** - * Initialize this instance. - * @param {Pattern[]} patterns The matchers. - * @param {string} basePath The base path. - * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`. - */ - constructor(patterns, basePath, endsWithWildcard = false) { - - /** @type {Pattern[]} */ - this.patterns = patterns; - - /** @type {string} */ - this.basePath = basePath; - - /** @type {boolean} */ - this.endsWithWildcard = endsWithWildcard; - } - - /** - * Test if a given path is matched or not. - * @param {string} filePath The absolute path to the target file. - * @returns {boolean} `true` if the path was matched. - */ - test(filePath) { - if (typeof filePath !== "string" || !path.isAbsolute(filePath)) { - throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`); - } - const relativePath = path.relative(this.basePath, filePath); - - return this.patterns.every(({ includes, excludes }) => ( - (!includes || includes.some(m => m.match(relativePath))) && - (!excludes || !excludes.some(m => m.match(relativePath))) - )); - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @returns {Object} a JSON compatible object. - */ - toJSON() { - if (this.patterns.length === 1) { - return { - ...patternToJson(this.patterns[0]), - basePath: this.basePath - }; - } - return { - AND: this.patterns.map(patternToJson), - basePath: this.basePath - }; - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @returns {Object} an object to display by `console.log()`. - */ - [util.inspect.custom]() { - return this.toJSON(); - } -} - -module.exports = { OverrideTester }; diff --git a/tools/node_modules/eslint/lib/cli-engine/file-enumerator.js b/tools/node_modules/eslint/lib/cli-engine/file-enumerator.js deleted file mode 100644 index 7c433d32f44b1cbd394a29eb0a30260956ec994b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/file-enumerator.js +++ /dev/null @@ -1,528 +0,0 @@ -/** - * @fileoverview `FileEnumerator` class. - * - * `FileEnumerator` class has two responsibilities: - * - * 1. Find target files by processing glob patterns. - * 2. Tie each target file and appropriate configuration. - * - * It provides a method: - * - * - `iterateFiles(patterns)` - * Iterate files which are matched by given patterns together with the - * corresponded configuration. This is for `CLIEngine#executeOnFiles()`. - * While iterating files, it loads the configuration file of each directory - * before iterate files on the directory, so we can use the configuration - * files to determine target files. - * - * @example - * const enumerator = new FileEnumerator(); - * const linter = new Linter(); - * - * for (const { config, filePath } of enumerator.iterateFiles(["*.js"])) { - * const code = fs.readFileSync(filePath, "utf8"); - * const messages = linter.verify(code, config, filePath); - * - * console.log(messages); - * } - * - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"); -const path = require("path"); -const getGlobParent = require("glob-parent"); -const isGlob = require("is-glob"); -const { escapeRegExp } = require("lodash"); -const { Minimatch } = require("minimatch"); -const { IgnorePattern } = require("./config-array"); -const { CascadingConfigArrayFactory } = require("./cascading-config-array-factory"); -const debug = require("debug")("eslint:file-enumerator"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const minimatchOpts = { dot: true, matchBase: true }; -const dotfilesPattern = /(?:(?:^\.)|(?:[/\\]\.))[^/\\.].*/u; -const NONE = 0; -const IGNORED_SILENTLY = 1; -const IGNORED = 2; - -// For VSCode intellisense -/** @typedef {ReturnType} ConfigArray */ - -/** - * @typedef {Object} FileEnumeratorOptions - * @property {CascadingConfigArrayFactory} [configArrayFactory] The factory for config arrays. - * @property {string} [cwd] The base directory to start lookup. - * @property {string[]} [extensions] The extensions to match files for directory patterns. - * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. - * @property {boolean} [ignore] The flag to check ignored files. - * @property {string[]} [rulePaths] The value of `--rulesdir` option. - */ - -/** - * @typedef {Object} FileAndConfig - * @property {string} filePath The path to a target file. - * @property {ConfigArray} config The config entries of that file. - * @property {boolean} ignored If `true` then this file should be ignored and warned because it was directly specified. - */ - -/** - * @typedef {Object} FileEntry - * @property {string} filePath The path to a target file. - * @property {ConfigArray} config The config entries of that file. - * @property {NONE|IGNORED_SILENTLY|IGNORED} flag The flag. - * - `NONE` means the file is a target file. - * - `IGNORED_SILENTLY` means the file should be ignored silently. - * - `IGNORED` means the file should be ignored and warned because it was directly specified. - */ - -/** - * @typedef {Object} FileEnumeratorInternalSlots - * @property {CascadingConfigArrayFactory} configArrayFactory The factory for config arrays. - * @property {string} cwd The base directory to start lookup. - * @property {RegExp|null} extensionRegExp The RegExp to test if a string ends with specific file extensions. - * @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. - * @property {boolean} ignoreFlag The flag to check ignored files. - * @property {(filePath:string, dot:boolean) => boolean} defaultIgnores The default predicate function to ignore files. - */ - -/** @type {WeakMap} */ -const internalSlotsMap = new WeakMap(); - -/** - * Check if a string is a glob pattern or not. - * @param {string} pattern A glob pattern. - * @returns {boolean} `true` if the string is a glob pattern. - */ -function isGlobPattern(pattern) { - return isGlob(path.sep === "\\" ? pattern.replace(/\\/gu, "/") : pattern); -} - -/** - * Get stats of a given path. - * @param {string} filePath The path to target file. - * @returns {fs.Stats|null} The stats. - * @private - */ -function statSafeSync(filePath) { - try { - return fs.statSync(filePath); - } catch (error) { - /* istanbul ignore next */ - if (error.code !== "ENOENT") { - throw error; - } - return null; - } -} - -/** - * Get filenames in a given path to a directory. - * @param {string} directoryPath The path to target directory. - * @returns {import("fs").Dirent[]} The filenames. - * @private - */ -function readdirSafeSync(directoryPath) { - try { - return fs.readdirSync(directoryPath, { withFileTypes: true }); - } catch (error) { - /* istanbul ignore next */ - if (error.code !== "ENOENT") { - throw error; - } - return []; - } -} - -/** - * Create a `RegExp` object to detect extensions. - * @param {string[] | null} extensions The extensions to create. - * @returns {RegExp | null} The created `RegExp` object or null. - */ -function createExtensionRegExp(extensions) { - if (extensions) { - const normalizedExts = extensions.map(ext => escapeRegExp( - ext.startsWith(".") - ? ext.slice(1) - : ext - )); - - return new RegExp( - `.\\.(?:${normalizedExts.join("|")})$`, - "u" - ); - } - return null; -} - -/** - * The error type when no files match a glob. - */ -class NoFilesFoundError extends Error { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} pattern The glob pattern which was not found. - * @param {boolean} globDisabled If `true` then the pattern was a glob pattern, but glob was disabled. - */ - constructor(pattern, globDisabled) { - super(`No files matching '${pattern}' were found${globDisabled ? " (glob was disabled)" : ""}.`); - this.messageTemplate = "file-not-found"; - this.messageData = { pattern, globDisabled }; - } -} - -/** - * The error type when there are files matched by a glob, but all of them have been ignored. - */ -class AllFilesIgnoredError extends Error { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} pattern The glob pattern which was not found. - */ - constructor(pattern) { - super(`All files matched by '${pattern}' are ignored.`); - this.messageTemplate = "all-files-ignored"; - this.messageData = { pattern }; - } -} - -/** - * This class provides the functionality that enumerates every file which is - * matched by given glob patterns and that configuration. - */ -class FileEnumerator { - - /** - * Initialize this enumerator. - * @param {FileEnumeratorOptions} options The options. - */ - constructor({ - cwd = process.cwd(), - configArrayFactory = new CascadingConfigArrayFactory({ cwd }), - extensions = null, - globInputPaths = true, - errorOnUnmatchedPattern = true, - ignore = true - } = {}) { - internalSlotsMap.set(this, { - configArrayFactory, - cwd, - defaultIgnores: IgnorePattern.createDefaultIgnore(cwd), - extensionRegExp: createExtensionRegExp(extensions), - globInputPaths, - errorOnUnmatchedPattern, - ignoreFlag: ignore - }); - } - - /** - * Check if a given file is target or not. - * @param {string} filePath The path to a candidate file. - * @param {ConfigArray} [providedConfig] Optional. The configuration for the file. - * @returns {boolean} `true` if the file is a target. - */ - isTargetPath(filePath, providedConfig) { - const { - configArrayFactory, - extensionRegExp - } = internalSlotsMap.get(this); - - // If `--ext` option is present, use it. - if (extensionRegExp) { - return extensionRegExp.test(filePath); - } - - // `.js` file is target by default. - if (filePath.endsWith(".js")) { - return true; - } - - // use `overrides[].files` to check additional targets. - const config = - providedConfig || - configArrayFactory.getConfigArrayForFile( - filePath, - { ignoreNotFoundError: true } - ); - - return config.isAdditionalTargetPath(filePath); - } - - /** - * Iterate files which are matched by given glob patterns. - * @param {string|string[]} patternOrPatterns The glob patterns to iterate files. - * @returns {IterableIterator} The found files. - */ - *iterateFiles(patternOrPatterns) { - const { globInputPaths, errorOnUnmatchedPattern } = internalSlotsMap.get(this); - const patterns = Array.isArray(patternOrPatterns) - ? patternOrPatterns - : [patternOrPatterns]; - - debug("Start to iterate files: %o", patterns); - - // The set of paths to remove duplicate. - const set = new Set(); - - for (const pattern of patterns) { - let foundRegardlessOfIgnored = false; - let found = false; - - // Skip empty string. - if (!pattern) { - continue; - } - - // Iterate files of this pattern. - for (const { config, filePath, flag } of this._iterateFiles(pattern)) { - foundRegardlessOfIgnored = true; - if (flag === IGNORED_SILENTLY) { - continue; - } - found = true; - - // Remove duplicate paths while yielding paths. - if (!set.has(filePath)) { - set.add(filePath); - yield { - config, - filePath, - ignored: flag === IGNORED - }; - } - } - - // Raise an error if any files were not found. - if (errorOnUnmatchedPattern) { - if (!foundRegardlessOfIgnored) { - throw new NoFilesFoundError( - pattern, - !globInputPaths && isGlob(pattern) - ); - } - if (!found) { - throw new AllFilesIgnoredError(pattern); - } - } - } - - debug(`Complete iterating files: ${JSON.stringify(patterns)}`); - } - - /** - * Iterate files which are matched by a given glob pattern. - * @param {string} pattern The glob pattern to iterate files. - * @returns {IterableIterator} The found files. - */ - _iterateFiles(pattern) { - const { cwd, globInputPaths } = internalSlotsMap.get(this); - const absolutePath = path.resolve(cwd, pattern); - const isDot = dotfilesPattern.test(pattern); - const stat = statSafeSync(absolutePath); - - if (stat && stat.isDirectory()) { - return this._iterateFilesWithDirectory(absolutePath, isDot); - } - if (stat && stat.isFile()) { - return this._iterateFilesWithFile(absolutePath); - } - if (globInputPaths && isGlobPattern(pattern)) { - return this._iterateFilesWithGlob(absolutePath, isDot); - } - - return []; - } - - /** - * Iterate a file which is matched by a given path. - * @param {string} filePath The path to the target file. - * @returns {IterableIterator} The found files. - * @private - */ - _iterateFilesWithFile(filePath) { - debug(`File: ${filePath}`); - - const { configArrayFactory } = internalSlotsMap.get(this); - const config = configArrayFactory.getConfigArrayForFile(filePath); - const ignored = this._isIgnoredFile(filePath, { config, direct: true }); - const flag = ignored ? IGNORED : NONE; - - return [{ config, filePath, flag }]; - } - - /** - * Iterate files in a given path. - * @param {string} directoryPath The path to the target directory. - * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. - * @returns {IterableIterator} The found files. - * @private - */ - _iterateFilesWithDirectory(directoryPath, dotfiles) { - debug(`Directory: ${directoryPath}`); - - return this._iterateFilesRecursive( - directoryPath, - { dotfiles, recursive: true, selector: null } - ); - } - - /** - * Iterate files which are matched by a given glob pattern. - * @param {string} pattern The glob pattern to iterate files. - * @param {boolean} dotfiles If `true` then it doesn't skip dot files by default. - * @returns {IterableIterator} The found files. - * @private - */ - _iterateFilesWithGlob(pattern, dotfiles) { - debug(`Glob: ${pattern}`); - - const directoryPath = path.resolve(getGlobParent(pattern)); - const globPart = pattern.slice(directoryPath.length + 1); - - /* - * recursive if there are `**` or path separators in the glob part. - * Otherwise, patterns such as `src/*.js`, it doesn't need recursive. - */ - const recursive = /\*\*|\/|\\/u.test(globPart); - const selector = new Minimatch(pattern, minimatchOpts); - - debug(`recursive? ${recursive}`); - - return this._iterateFilesRecursive( - directoryPath, - { dotfiles, recursive, selector } - ); - } - - /** - * Iterate files in a given path. - * @param {string} directoryPath The path to the target directory. - * @param {Object} options The options to iterate files. - * @param {boolean} [options.dotfiles] If `true` then it doesn't skip dot files by default. - * @param {boolean} [options.recursive] If `true` then it dives into sub directories. - * @param {InstanceType} [options.selector] The matcher to choose files. - * @returns {IterableIterator} The found files. - * @private - */ - *_iterateFilesRecursive(directoryPath, options) { - debug(`Enter the directory: ${directoryPath}`); - const { configArrayFactory } = internalSlotsMap.get(this); - - /** @type {ConfigArray|null} */ - let config = null; - - // Enumerate the files of this directory. - for (const entry of readdirSafeSync(directoryPath)) { - const filePath = path.join(directoryPath, entry.name); - - // Check if the file is matched. - if (entry.isFile()) { - if (!config) { - config = configArrayFactory.getConfigArrayForFile( - filePath, - - /* - * We must ignore `ConfigurationNotFoundError` at this - * point because we don't know if target files exist in - * this directory. - */ - { ignoreNotFoundError: true } - ); - } - const matched = options.selector - - // Started with a glob pattern; choose by the pattern. - ? options.selector.match(filePath) - - // Started with a directory path; choose by file extensions. - : this.isTargetPath(filePath, config); - - if (matched) { - const ignored = this._isIgnoredFile(filePath, { ...options, config }); - const flag = ignored ? IGNORED_SILENTLY : NONE; - - debug(`Yield: ${entry.name}${ignored ? " but ignored" : ""}`); - yield { - config: configArrayFactory.getConfigArrayForFile(filePath), - filePath, - flag - }; - } else { - debug(`Didn't match: ${entry.name}`); - } - - // Dive into the sub directory. - } else if (options.recursive && entry.isDirectory()) { - if (!config) { - config = configArrayFactory.getConfigArrayForFile( - filePath, - { ignoreNotFoundError: true } - ); - } - const ignored = this._isIgnoredFile( - filePath + path.sep, - { ...options, config } - ); - - if (!ignored) { - yield* this._iterateFilesRecursive(filePath, options); - } - } - } - - debug(`Leave the directory: ${directoryPath}`); - } - - /** - * Check if a given file should be ignored. - * @param {string} filePath The path to a file to check. - * @param {Object} options Options - * @param {ConfigArray} [options.config] The config for this file. - * @param {boolean} [options.dotfiles] If `true` then this is not ignore dot files by default. - * @param {boolean} [options.direct] If `true` then this is a direct specified file. - * @returns {boolean} `true` if the file should be ignored. - * @private - */ - _isIgnoredFile(filePath, { - config: providedConfig, - dotfiles = false, - direct = false - }) { - const { - configArrayFactory, - defaultIgnores, - ignoreFlag - } = internalSlotsMap.get(this); - - if (ignoreFlag) { - const config = - providedConfig || - configArrayFactory.getConfigArrayForFile( - filePath, - { ignoreNotFoundError: true } - ); - const ignores = - config.extractConfig(filePath).ignores || defaultIgnores; - - return ignores(filePath, dotfiles); - } - - return !direct && defaultIgnores(filePath, dotfiles); - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { FileEnumerator }; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js b/tools/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js deleted file mode 100644 index f19b6fc0957e5dd7d90731a3e9b0c75283a5514c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/checkstyle.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview CheckStyle XML reporter - * @author Ian Christian Myers - */ -"use strict"; - -const xmlEscape = require("../xml-escape"); - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "error"; - } - return "warning"; - -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = ""; - - output += ""; - output += ""; - - results.forEach(result => { - const messages = result.messages; - - output += ``; - - messages.forEach(message => { - output += [ - `` - ].join(" "); - }); - - output += ""; - - }); - - output += ""; - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/codeframe.js b/tools/node_modules/eslint/lib/cli-engine/formatters/codeframe.js deleted file mode 100644 index 41e3ab7b0afe813f1199bd1cfc4421646bf6710b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/codeframe.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @fileoverview Codeframe reporter - * @author Vitor Balocco - */ -"use strict"; - -const chalk = require("chalk"); -const { codeFrameColumns } = require("@babel/code-frame"); -const path = require("path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Given a word and a count, append an s if count is not one. - * @param {string} word A word in its singular form. - * @param {number} count A number controlling whether word should be pluralized. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -/** - * Gets a formatted relative file path from an absolute path and a line/column in the file. - * @param {string} filePath The absolute file path to format. - * @param {number} line The line from the file to use for formatting. - * @param {number} column The column from the file to use for formatting. - * @returns {string} The formatted file path. - */ -function formatFilePath(filePath, line, column) { - let relPath = path.relative(process.cwd(), filePath); - - if (line && column) { - relPath += `:${line}:${column}`; - } - - return chalk.green(relPath); -} - -/** - * Gets the formatted output for a given message. - * @param {Object} message The object that represents this message. - * @param {Object} parentResult The result object that this message belongs to. - * @returns {string} The formatted output. - */ -function formatMessage(message, parentResult) { - const type = (message.fatal || message.severity === 2) ? chalk.red("error") : chalk.yellow("warning"); - const msg = `${chalk.bold(message.message.replace(/([^ ])\.$/u, "$1"))}`; - const ruleId = message.fatal ? "" : chalk.dim(`(${message.ruleId})`); - const filePath = formatFilePath(parentResult.filePath, message.line, message.column); - const sourceCode = parentResult.output ? parentResult.output : parentResult.source; - - const firstLine = [ - `${type}:`, - `${msg}`, - ruleId ? `${ruleId}` : "", - sourceCode ? `at ${filePath}:` : `at ${filePath}` - ].filter(String).join(" "); - - const result = [firstLine]; - - if (sourceCode) { - result.push( - codeFrameColumns(sourceCode, { start: { line: message.line, column: message.column } }, { highlightCode: false }) - ); - } - - return result.join("\n"); -} - -/** - * Gets the formatted output summary for a given number of errors and warnings. - * @param {number} errors The number of errors. - * @param {number} warnings The number of warnings. - * @param {number} fixableErrors The number of fixable errors. - * @param {number} fixableWarnings The number of fixable warnings. - * @returns {string} The formatted output summary. - */ -function formatSummary(errors, warnings, fixableErrors, fixableWarnings) { - const summaryColor = errors > 0 ? "red" : "yellow"; - const summary = []; - const fixablesSummary = []; - - if (errors > 0) { - summary.push(`${errors} ${pluralize("error", errors)}`); - } - - if (warnings > 0) { - summary.push(`${warnings} ${pluralize("warning", warnings)}`); - } - - if (fixableErrors > 0) { - fixablesSummary.push(`${fixableErrors} ${pluralize("error", fixableErrors)}`); - } - - if (fixableWarnings > 0) { - fixablesSummary.push(`${fixableWarnings} ${pluralize("warning", fixableWarnings)}`); - } - - let output = chalk[summaryColor].bold(`${summary.join(" and ")} found.`); - - if (fixableErrors || fixableWarnings) { - output += chalk[summaryColor].bold(`\n${fixablesSummary.join(" and ")} potentially fixable with the \`--fix\` option.`); - } - - return output; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - let errors = 0; - let warnings = 0; - let fixableErrors = 0; - let fixableWarnings = 0; - - const resultsWithMessages = results.filter(result => result.messages.length > 0); - - let output = resultsWithMessages.reduce((resultsOutput, result) => { - const messages = result.messages.map(message => `${formatMessage(message, result)}\n\n`); - - errors += result.errorCount; - warnings += result.warningCount; - fixableErrors += result.fixableErrorCount; - fixableWarnings += result.fixableWarningCount; - - return resultsOutput.concat(messages); - }, []).join("\n"); - - output += "\n"; - output += formatSummary(errors, warnings, fixableErrors, fixableWarnings); - - return (errors + warnings) > 0 ? output : ""; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/compact.js b/tools/node_modules/eslint/lib/cli-engine/formatters/compact.js deleted file mode 100644 index 2b540bde2361c15cf174bc00599883dbb473b18f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/compact.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview Compact reporter - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "Error"; - } - return "Warning"; - -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "", - total = 0; - - results.forEach(result => { - - const messages = result.messages; - - total += messages.length; - - messages.forEach(message => { - - output += `${result.filePath}: `; - output += `line ${message.line || 0}`; - output += `, col ${message.column || 0}`; - output += `, ${getMessageType(message)}`; - output += ` - ${message.message}`; - output += message.ruleId ? ` (${message.ruleId})` : ""; - output += "\n"; - - }); - - }); - - if (total > 0) { - output += `\n${total} problem${total !== 1 ? "s" : ""}`; - } - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-message.html b/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-message.html deleted file mode 100644 index 93795a1bdc8da377f8795df5be2c61e34148574f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-message.html +++ /dev/null @@ -1,8 +0,0 @@ - - <%= lineNumber %>:<%= columnNumber %> - <%= severityName %> - <%- message %> - - <%= ruleId %> - - diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-page.html b/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-page.html deleted file mode 100644 index 4016576fa06713446ed0cceac2b29dcb0d271fcf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-page.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - - ESLint Report - - - -
-

ESLint Report

-
- <%= reportSummary %> - Generated on <%= date %> -
-
- - - <%= results %> - -
- - - diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-result.html b/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-result.html deleted file mode 100644 index f4a55933c2047ef11123379832f76f1ff3eb1c9d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/html-template-result.html +++ /dev/null @@ -1,6 +0,0 @@ - - - [+] <%- filePath %> - <%- summary %> - - diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/html.js b/tools/node_modules/eslint/lib/cli-engine/formatters/html.js deleted file mode 100644 index 69f7395550f2e2678120a958f5784c9db4e909e0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/html.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @fileoverview HTML reporter - * @author Julian Laval - */ -"use strict"; - -const lodash = require("lodash"); -const fs = require("fs"); -const path = require("path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const pageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-page.html"), "utf-8")); -const messageTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-message.html"), "utf-8")); -const resultTemplate = lodash.template(fs.readFileSync(path.join(__dirname, "html-template-result.html"), "utf-8")); - -/** - * Given a word and a count, append an s if count is not one. - * @param {string} word A word in its singular form. - * @param {int} count A number controlling whether word should be pluralized. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -/** - * Renders text along the template of x problems (x errors, x warnings) - * @param {string} totalErrors Total errors - * @param {string} totalWarnings Total warnings - * @returns {string} The formatted string, pluralized where necessary - */ -function renderSummary(totalErrors, totalWarnings) { - const totalProblems = totalErrors + totalWarnings; - let renderedText = `${totalProblems} ${pluralize("problem", totalProblems)}`; - - if (totalProblems !== 0) { - renderedText += ` (${totalErrors} ${pluralize("error", totalErrors)}, ${totalWarnings} ${pluralize("warning", totalWarnings)})`; - } - return renderedText; -} - -/** - * Get the color based on whether there are errors/warnings... - * @param {string} totalErrors Total errors - * @param {string} totalWarnings Total warnings - * @returns {int} The color code (0 = green, 1 = yellow, 2 = red) - */ -function renderColor(totalErrors, totalWarnings) { - if (totalErrors !== 0) { - return 2; - } - if (totalWarnings !== 0) { - return 1; - } - return 0; -} - -/** - * Get HTML (table rows) describing the messages. - * @param {Array} messages Messages. - * @param {int} parentIndex Index of the parent HTML row. - * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. - * @returns {string} HTML (table rows) describing the messages. - */ -function renderMessages(messages, parentIndex, rulesMeta) { - - /** - * Get HTML (table row) describing a message. - * @param {Object} message Message. - * @returns {string} HTML (table row) describing a message. - */ - return lodash.map(messages, message => { - const lineNumber = message.line || 0; - const columnNumber = message.column || 0; - let ruleUrl; - - if (rulesMeta) { - const meta = rulesMeta[message.ruleId]; - - ruleUrl = lodash.get(meta, "docs.url", null); - } - - return messageTemplate({ - parentIndex, - lineNumber, - columnNumber, - severityNumber: message.severity, - severityName: message.severity === 1 ? "Warning" : "Error", - message: message.message, - ruleId: message.ruleId, - ruleUrl - }); - }).join("\n"); -} - -// eslint-disable-next-line jsdoc/require-description -/** - * @param {Array} results Test results. - * @param {Object} rulesMeta Dictionary containing metadata for each rule executed by the analysis. - * @returns {string} HTML string describing the results. - */ -function renderResults(results, rulesMeta) { - return lodash.map(results, (result, index) => resultTemplate({ - index, - color: renderColor(result.errorCount, result.warningCount), - filePath: result.filePath, - summary: renderSummary(result.errorCount, result.warningCount) - - }) + renderMessages(result.messages, index, rulesMeta)).join("\n"); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results, data) { - let totalErrors, - totalWarnings; - - const metaData = data ? data.rulesMeta : {}; - - totalErrors = 0; - totalWarnings = 0; - - // Iterate over results to get totals - results.forEach(result => { - totalErrors += result.errorCount; - totalWarnings += result.warningCount; - }); - - return pageTemplate({ - date: new Date(), - reportColor: renderColor(totalErrors, totalWarnings), - reportSummary: renderSummary(totalErrors, totalWarnings), - results: renderResults(results, metaData) - }); -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js b/tools/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js deleted file mode 100644 index 0ca1cbaed1a3cc8741739eaafe8710a7dbe6c322..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/jslint-xml.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @fileoverview JSLint XML reporter - * @author Ian Christian Myers - */ -"use strict"; - -const xmlEscape = require("../xml-escape"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = ""; - - output += ""; - output += ""; - - results.forEach(result => { - const messages = result.messages; - - output += ``; - - messages.forEach(message => { - output += [ - `` - ].join(" "); - }); - - output += ""; - - }); - - output += ""; - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js b/tools/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js deleted file mode 100644 index 6899471547a4e30479500a16c1d3772ae066fddf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/json-with-metadata.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * @fileoverview JSON reporter, including rules metadata - * @author Chris Meyer - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results, data) { - return JSON.stringify({ - results, - metadata: data - }); -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/json.js b/tools/node_modules/eslint/lib/cli-engine/formatters/json.js deleted file mode 100644 index 82138af18748554c2db087292e2bafdee12ad143..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/json.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @fileoverview JSON reporter - * @author Burak Yigit Kaya aka BYK - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - return JSON.stringify(results); -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/junit.js b/tools/node_modules/eslint/lib/cli-engine/formatters/junit.js deleted file mode 100644 index a994b4b1980eea3426e89ab623555d854c6782c8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/junit.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @fileoverview jUnit Reporter - * @author Jamund Ferguson - */ -"use strict"; - -const xmlEscape = require("../xml-escape"); -const path = require("path"); - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "Error"; - } - return "Warning"; - -} - -/** - * Returns a full file path without extension - * @param {string} filePath input file path - * @returns {string} file path without extension - * @private - */ -function pathWithoutExt(filePath) { - return path.join(path.dirname(filePath), path.basename(filePath, path.extname(filePath))); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = ""; - - output += "\n"; - output += "\n"; - - results.forEach(result => { - - const messages = result.messages; - const classname = pathWithoutExt(result.filePath); - - if (messages.length > 0) { - output += `\n`; - messages.forEach(message => { - const type = message.fatal ? "error" : "failure"; - - output += ``; - output += `<${type} message="${xmlEscape(message.message || "")}">`; - output += ""; - output += ``; - output += "\n"; - }); - output += "\n"; - } else { - output += `\n`; - output += `\n`; - output += "\n"; - } - - }); - - output += "\n"; - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/stylish.js b/tools/node_modules/eslint/lib/cli-engine/formatters/stylish.js deleted file mode 100644 index a808448b65233fe17204b858df62293129e13772..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/stylish.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @fileoverview Stylish reporter - * @author Sindre Sorhus - */ -"use strict"; - -const chalk = require("chalk"), - stripAnsi = require("strip-ansi"), - table = require("text-table"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Given a word and a count, append an s if count is not one. - * @param {string} word A word in its singular form. - * @param {int} count A number controlling whether word should be pluralized. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "\n", - errorCount = 0, - warningCount = 0, - fixableErrorCount = 0, - fixableWarningCount = 0, - summaryColor = "yellow"; - - results.forEach(result => { - const messages = result.messages; - - if (messages.length === 0) { - return; - } - - errorCount += result.errorCount; - warningCount += result.warningCount; - fixableErrorCount += result.fixableErrorCount; - fixableWarningCount += result.fixableWarningCount; - - output += `${chalk.underline(result.filePath)}\n`; - - output += `${table( - messages.map(message => { - let messageType; - - if (message.fatal || message.severity === 2) { - messageType = chalk.red("error"); - summaryColor = "red"; - } else { - messageType = chalk.yellow("warning"); - } - - return [ - "", - message.line || 0, - message.column || 0, - messageType, - message.message.replace(/([^ ])\.$/u, "$1"), - chalk.dim(message.ruleId || "") - ]; - }), - { - align: ["", "r", "l"], - stringLength(str) { - return stripAnsi(str).length; - } - } - ).split("\n").map(el => el.replace(/(\d+)\s+(\d+)/u, (m, p1, p2) => chalk.dim(`${p1}:${p2}`))).join("\n")}\n\n`; - }); - - const total = errorCount + warningCount; - - if (total > 0) { - output += chalk[summaryColor].bold([ - "\u2716 ", total, pluralize(" problem", total), - " (", errorCount, pluralize(" error", errorCount), ", ", - warningCount, pluralize(" warning", warningCount), ")\n" - ].join("")); - - if (fixableErrorCount > 0 || fixableWarningCount > 0) { - output += chalk[summaryColor].bold([ - " ", fixableErrorCount, pluralize(" error", fixableErrorCount), " and ", - fixableWarningCount, pluralize(" warning", fixableWarningCount), - " potentially fixable with the `--fix` option.\n" - ].join("")); - } - } - - // Resets output color, for prevent change on top level - return total > 0 ? chalk.reset(output) : ""; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/table.js b/tools/node_modules/eslint/lib/cli-engine/formatters/table.js deleted file mode 100644 index a74cce0d516ecccc08a9c7524a457193e4409eb7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/table.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview "table reporter. - * @author Gajus Kuizinas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const chalk = require("chalk"), - table = require("table").table; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Given a word and a count, append an "s" if count is not one. - * @param {string} word A word. - * @param {number} count Quantity. - * @returns {string} The original word with an s on the end if count is not one. - */ -function pluralize(word, count) { - return (count === 1 ? word : `${word}s`); -} - -/** - * Draws text table. - * @param {Array} messages Error messages relating to a specific file. - * @returns {string} A text table. - */ -function drawTable(messages) { - const rows = []; - - if (messages.length === 0) { - return ""; - } - - rows.push([ - chalk.bold("Line"), - chalk.bold("Column"), - chalk.bold("Type"), - chalk.bold("Message"), - chalk.bold("Rule ID") - ]); - - messages.forEach(message => { - let messageType; - - if (message.fatal || message.severity === 2) { - messageType = chalk.red("error"); - } else { - messageType = chalk.yellow("warning"); - } - - rows.push([ - message.line || 0, - message.column || 0, - messageType, - message.message, - message.ruleId || "" - ]); - }); - - return table(rows, { - columns: { - 0: { - width: 8, - wrapWord: true - }, - 1: { - width: 8, - wrapWord: true - }, - 2: { - width: 8, - wrapWord: true - }, - 3: { - paddingRight: 5, - width: 50, - wrapWord: true - }, - 4: { - width: 20, - wrapWord: true - } - }, - drawHorizontalLine(index) { - return index === 1; - } - }); -} - -/** - * Draws a report (multiple tables). - * @param {Array} results Report results for every file. - * @returns {string} A column of text tables. - */ -function drawReport(results) { - let files; - - files = results.map(result => { - if (!result.messages.length) { - return ""; - } - - return `\n${result.filePath}\n\n${drawTable(result.messages)}`; - }); - - files = files.filter(content => content.trim()); - - return files.join(""); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(report) { - let result, - errorCount, - warningCount; - - result = ""; - errorCount = 0; - warningCount = 0; - - report.forEach(fileReport => { - errorCount += fileReport.errorCount; - warningCount += fileReport.warningCount; - }); - - if (errorCount || warningCount) { - result = drawReport(report); - } - - result += `\n${table([ - [ - chalk.red(pluralize(`${errorCount} Error`, errorCount)) - ], - [ - chalk.yellow(pluralize(`${warningCount} Warning`, warningCount)) - ] - ], { - columns: { - 0: { - width: 110, - wrapWord: true - } - }, - drawHorizontalLine() { - return true; - } - })}`; - - return result; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/tap.js b/tools/node_modules/eslint/lib/cli-engine/formatters/tap.js deleted file mode 100644 index 354872a0c92af3e142aef5eb335fe63c0636b0ab..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/tap.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview TAP reporter - * @author Jonathan Kingston - */ -"use strict"; - -const yaml = require("js-yaml"); - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns a canonical error level string based upon the error message passed in. - * @param {Object} message Individual error message provided by eslint - * @returns {string} Error level string - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "error"; - } - return "warning"; -} - -/** - * Takes in a JavaScript object and outputs a TAP diagnostics string - * @param {Object} diagnostic JavaScript object to be embedded as YAML into output. - * @returns {string} diagnostics string with YAML embedded - TAP version 13 compliant - */ -function outputDiagnostics(diagnostic) { - const prefix = " "; - let output = `${prefix}---\n`; - - output += prefix + yaml.safeDump(diagnostic).split("\n").join(`\n${prefix}`); - output += "...\n"; - return output; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - let output = `TAP version 13\n1..${results.length}\n`; - - results.forEach((result, id) => { - const messages = result.messages; - let testResult = "ok"; - let diagnostics = {}; - - if (messages.length > 0) { - messages.forEach(message => { - const severity = getMessageType(message); - const diagnostic = { - message: message.message, - severity, - data: { - line: message.line || 0, - column: message.column || 0, - ruleId: message.ruleId || "" - } - }; - - // This ensures a warning message is not flagged as error - if (severity === "error") { - testResult = "not ok"; - } - - /* - * If we have multiple messages place them under a messages key - * The first error will be logged as message key - * This is to adhere to TAP 13 loosely defined specification of having a message key - */ - if ("message" in diagnostics) { - if (typeof diagnostics.messages === "undefined") { - diagnostics.messages = []; - } - diagnostics.messages.push(diagnostic); - } else { - diagnostics = diagnostic; - } - }); - } - - output += `${testResult} ${id + 1} - ${result.filePath}\n`; - - // If we have an error include diagnostics - if (messages.length > 0) { - output += outputDiagnostics(diagnostics); - } - - }); - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/unix.js b/tools/node_modules/eslint/lib/cli-engine/formatters/unix.js deleted file mode 100644 index c6c4ebbdb9f4cc059699124339bce124e11341f6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/unix.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview unix-style formatter. - * @author oshi-shinobu - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns a canonical error level string based upon the error message passed in. - * @param {Object} message Individual error message provided by eslint - * @returns {string} Error level string - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "Error"; - } - return "Warning"; - -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "", - total = 0; - - results.forEach(result => { - - const messages = result.messages; - - total += messages.length; - - messages.forEach(message => { - - output += `${result.filePath}:`; - output += `${message.line || 0}:`; - output += `${message.column || 0}:`; - output += ` ${message.message} `; - output += `[${getMessageType(message)}${message.ruleId ? `/${message.ruleId}` : ""}]`; - output += "\n"; - - }); - - }); - - if (total > 0) { - output += `\n${total} problem${total !== 1 ? "s" : ""}`; - } - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js b/tools/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js deleted file mode 100644 index 0d49431db87926ee2a4306352ffc075bf2d46398..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/formatters/visualstudio.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview Visual Studio compatible formatter - * @author Ronald Pijnacker - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helper Functions -//------------------------------------------------------------------------------ - -/** - * Returns the severity of warning or error - * @param {Object} message message object to examine - * @returns {string} severity level - * @private - */ -function getMessageType(message) { - if (message.fatal || message.severity === 2) { - return "error"; - } - return "warning"; - -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = function(results) { - - let output = "", - total = 0; - - results.forEach(result => { - - const messages = result.messages; - - total += messages.length; - - messages.forEach(message => { - - output += result.filePath; - output += `(${message.line || 0}`; - output += message.column ? `,${message.column}` : ""; - output += `): ${getMessageType(message)}`; - output += message.ruleId ? ` ${message.ruleId}` : ""; - output += ` : ${message.message}`; - output += "\n"; - - }); - - }); - - if (total === 0) { - output += "no problems"; - } else { - output += `\n${total} problem${total !== 1 ? "s" : ""}`; - } - - return output; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/hash.js b/tools/node_modules/eslint/lib/cli-engine/hash.js deleted file mode 100644 index 6d7ef8bf1b2c64bed4499f2eab5486a0f6c07672..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/hash.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * @fileoverview Defining the hashing function in one place. - * @author Michael Ficarra - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const murmur = require("imurmurhash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * hash the given string - * @param {string} str the string to hash - * @returns {string} the hash - */ -function hash(str) { - return murmur(str).result().toString(36); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = hash; diff --git a/tools/node_modules/eslint/lib/cli-engine/index.js b/tools/node_modules/eslint/lib/cli-engine/index.js deleted file mode 100644 index 52e45a6d7910a002db7a014563e4e78e1d592172..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/index.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -const { CLIEngine } = require("./cli-engine"); - -module.exports = { - CLIEngine -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/lint-result-cache.js b/tools/node_modules/eslint/lib/cli-engine/lint-result-cache.js deleted file mode 100644 index 23a142097bab52f3f1bd0f26c6b238e0c351045f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/lint-result-cache.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @fileoverview Utility for caching lint results. - * @author Kevin Partington - */ -"use strict"; - -//----------------------------------------------------------------------------- -// Requirements -//----------------------------------------------------------------------------- - -const assert = require("assert"); -const fs = require("fs"); -const fileEntryCache = require("file-entry-cache"); -const stringify = require("json-stable-stringify-without-jsonify"); -const pkg = require("../../package.json"); -const hash = require("./hash"); - -//----------------------------------------------------------------------------- -// Helpers -//----------------------------------------------------------------------------- - -const configHashCache = new WeakMap(); -const nodeVersion = process && process.version; - -/** - * Calculates the hash of the config - * @param {ConfigArray} config The config. - * @returns {string} The hash of the config - */ -function hashOfConfigFor(config) { - if (!configHashCache.has(config)) { - configHashCache.set(config, hash(`${pkg.version}_${nodeVersion}_${stringify(config)}`)); - } - - return configHashCache.get(config); -} - -//----------------------------------------------------------------------------- -// Public Interface -//----------------------------------------------------------------------------- - -/** - * Lint result cache. This wraps around the file-entry-cache module, - * transparently removing properties that are difficult or expensive to - * serialize and adding them back in on retrieval. - */ -class LintResultCache { - - /** - * Creates a new LintResultCache instance. - * @param {string} cacheFileLocation The cache file location. - * configuration lookup by file path). - */ - constructor(cacheFileLocation) { - assert(cacheFileLocation, "Cache file location is required"); - - this.fileEntryCache = fileEntryCache.create(cacheFileLocation); - } - - /** - * Retrieve cached lint results for a given file path, if present in the - * cache. If the file is present and has not been changed, rebuild any - * missing result information. - * @param {string} filePath The file for which to retrieve lint results. - * @param {ConfigArray} config The config of the file. - * @returns {Object|null} The rebuilt lint results, or null if the file is - * changed or not in the filesystem. - */ - getCachedLintResults(filePath, config) { - - /* - * Cached lint results are valid if and only if: - * 1. The file is present in the filesystem - * 2. The file has not changed since the time it was previously linted - * 3. The ESLint configuration has not changed since the time the file - * was previously linted - * If any of these are not true, we will not reuse the lint results. - */ - - const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); - const hashOfConfig = hashOfConfigFor(config); - const changed = fileDescriptor.changed || fileDescriptor.meta.hashOfConfig !== hashOfConfig; - - if (fileDescriptor.notFound || changed) { - return null; - } - - // If source is present but null, need to reread the file from the filesystem. - if (fileDescriptor.meta.results && fileDescriptor.meta.results.source === null) { - fileDescriptor.meta.results.source = fs.readFileSync(filePath, "utf-8"); - } - - return fileDescriptor.meta.results; - } - - /** - * Set the cached lint results for a given file path, after removing any - * information that will be both unnecessary and difficult to serialize. - * Avoids caching results with an "output" property (meaning fixes were - * applied), to prevent potentially incorrect results if fixes are not - * written to disk. - * @param {string} filePath The file for which to set lint results. - * @param {ConfigArray} config The config of the file. - * @param {Object} result The lint result to be set for the file. - * @returns {void} - */ - setCachedLintResults(filePath, config, result) { - if (result && Object.prototype.hasOwnProperty.call(result, "output")) { - return; - } - - const fileDescriptor = this.fileEntryCache.getFileDescriptor(filePath); - - if (fileDescriptor && !fileDescriptor.notFound) { - - // Serialize the result, except that we want to remove the file source if present. - const resultToSerialize = Object.assign({}, result); - - /* - * Set result.source to null. - * In `getCachedLintResults`, if source is explicitly null, we will - * read the file from the filesystem to set the value again. - */ - if (Object.prototype.hasOwnProperty.call(resultToSerialize, "source")) { - resultToSerialize.source = null; - } - - fileDescriptor.meta.results = resultToSerialize; - fileDescriptor.meta.hashOfConfig = hashOfConfigFor(config); - } - } - - /** - * Persists the in-memory cache to disk. - * @returns {void} - */ - reconcile() { - this.fileEntryCache.reconcile(); - } -} - -module.exports = LintResultCache; diff --git a/tools/node_modules/eslint/lib/cli-engine/load-rules.js b/tools/node_modules/eslint/lib/cli-engine/load-rules.js deleted file mode 100644 index 81bab63fab6330cbe70e1f87f1ae164ecf5ba19d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/load-rules.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Module for loading rules from files and directories. - * @author Michael Ficarra - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"); - -const rulesDirCache = {}; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Load all rule modules from specified directory. - * @param {string} relativeRulesDir Path to rules directory, may be relative. - * @param {string} cwd Current working directory - * @returns {Object} Loaded rule modules. - */ -module.exports = function(relativeRulesDir, cwd) { - const rulesDir = path.resolve(cwd, relativeRulesDir); - - // cache will help performance as IO operation are expensive - if (rulesDirCache[rulesDir]) { - return rulesDirCache[rulesDir]; - } - - const rules = Object.create(null); - - fs.readdirSync(rulesDir).forEach(file => { - if (path.extname(file) !== ".js") { - return; - } - rules[file.slice(0, -3)] = require(path.join(rulesDir, file)); - }); - rulesDirCache[rulesDir] = rules; - - return rules; -}; diff --git a/tools/node_modules/eslint/lib/cli-engine/xml-escape.js b/tools/node_modules/eslint/lib/cli-engine/xml-escape.js deleted file mode 100644 index 175c2c0c2ddd7dec3c894d5baba5d14679b9b7e3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli-engine/xml-escape.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @fileoverview XML character escaper - * @author George Chung - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Returns the escaped value for a character - * @param {string} s string to examine - * @returns {string} severity level - * @private - */ -module.exports = function(s) { - return (`${s}`).replace(/[<>&"'\x00-\x1F\x7F\u0080-\uFFFF]/gu, c => { // eslint-disable-line no-control-regex - switch (c) { - case "<": - return "<"; - case ">": - return ">"; - case "&": - return "&"; - case "\"": - return """; - case "'": - return "'"; - default: - return `&#${c.charCodeAt(0)};`; - } - }); -}; diff --git a/tools/node_modules/eslint/lib/cli.js b/tools/node_modules/eslint/lib/cli.js deleted file mode 100644 index ce11878008f108e239dfdf3dfdf1d752e49cb340..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/cli.js +++ /dev/null @@ -1,326 +0,0 @@ -/** - * @fileoverview Main CLI object. - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* - * The CLI object should *not* call process.exit() directly. It should only return - * exit codes. This allows other programs to use the CLI object and still control - * when the program exits. - */ - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"), - { promisify } = require("util"), - { ESLint } = require("./eslint"), - CLIOptions = require("./options"), - log = require("./shared/logging"), - RuntimeInfo = require("./shared/runtime-info"); - -const debug = require("debug")("eslint:cli"); - -//------------------------------------------------------------------------------ -// Types -//------------------------------------------------------------------------------ - -/** @typedef {import("./eslint/eslint").ESLintOptions} ESLintOptions */ -/** @typedef {import("./eslint/eslint").LintMessage} LintMessage */ -/** @typedef {import("./eslint/eslint").LintResult} LintResult */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const mkdir = promisify(fs.mkdir); -const stat = promisify(fs.stat); -const writeFile = promisify(fs.writeFile); - -/** - * Predicate function for whether or not to apply fixes in quiet mode. - * If a message is a warning, do not apply a fix. - * @param {LintMessage} message The lint result. - * @returns {boolean} True if the lint message is an error (and thus should be - * autofixed), false otherwise. - */ -function quietFixPredicate(message) { - return message.severity === 2; -} - -/** - * Translates the CLI options into the options expected by the CLIEngine. - * @param {Object} cliOptions The CLI options to translate. - * @returns {ESLintOptions} The options object for the CLIEngine. - * @private - */ -function translateOptions({ - cache, - cacheFile, - cacheLocation, - config, - env, - errorOnUnmatchedPattern, - eslintrc, - ext, - fix, - fixDryRun, - fixType, - global, - ignore, - ignorePath, - ignorePattern, - inlineConfig, - parser, - parserOptions, - plugin, - quiet, - reportUnusedDisableDirectives, - resolvePluginsRelativeTo, - rule, - rulesdir -}) { - return { - allowInlineConfig: inlineConfig, - cache, - cacheLocation: cacheLocation || cacheFile, - errorOnUnmatchedPattern, - extensions: ext, - fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true), - fixTypes: fixType, - ignore, - ignorePath, - overrideConfig: { - env: env && env.reduce((obj, name) => { - obj[name] = true; - return obj; - }, {}), - globals: global && global.reduce((obj, name) => { - if (name.endsWith(":true")) { - obj[name.slice(0, -5)] = "writable"; - } else { - obj[name] = "readonly"; - } - return obj; - }, {}), - ignorePatterns: ignorePattern, - parser, - parserOptions, - plugins: plugin, - rules: rule - }, - overrideConfigFile: config, - reportUnusedDisableDirectives: reportUnusedDisableDirectives ? "error" : void 0, - resolvePluginsRelativeTo, - rulePaths: rulesdir, - useEslintrc: eslintrc - }; -} - -/** - * Count error messages. - * @param {LintResult[]} results The lint results. - * @returns {{errorCount:number;warningCount:number}} The number of error messages. - */ -function countErrors(results) { - let errorCount = 0; - let warningCount = 0; - - for (const result of results) { - errorCount += result.errorCount; - warningCount += result.warningCount; - } - - return { errorCount, warningCount }; -} - -/** - * Check if a given file path is a directory or not. - * @param {string} filePath The path to a file to check. - * @returns {Promise} `true` if the given path is a directory. - */ -async function isDirectory(filePath) { - try { - return (await stat(filePath)).isDirectory(); - } catch (error) { - if (error.code === "ENOENT" || error.code === "ENOTDIR") { - return false; - } - throw error; - } -} - -/** - * Outputs the results of the linting. - * @param {ESLint} engine The ESLint instance to use. - * @param {LintResult[]} results The results to print. - * @param {string} format The name of the formatter to use or the path to the formatter. - * @param {string} outputFile The path for the output file. - * @returns {Promise} True if the printing succeeds, false if not. - * @private - */ -async function printResults(engine, results, format, outputFile) { - let formatter; - - try { - formatter = await engine.loadFormatter(format); - } catch (e) { - log.error(e.message); - return false; - } - - const output = formatter.format(results); - - if (output) { - if (outputFile) { - const filePath = path.resolve(process.cwd(), outputFile); - - if (await isDirectory(filePath)) { - log.error("Cannot write to output file path, it is a directory: %s", outputFile); - return false; - } - - try { - await mkdir(path.dirname(filePath), { recursive: true }); - await writeFile(filePath, output); - } catch (ex) { - log.error("There was a problem writing the output file:\n%s", ex); - return false; - } - } else { - log.info(output); - } - } - - return true; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Encapsulates all CLI behavior for eslint. Makes it easier to test as well as - * for other Node.js programs to effectively run the CLI. - */ -const cli = { - - /** - * Executes the CLI based on an array of arguments that is passed in. - * @param {string|Array|Object} args The arguments to process. - * @param {string} [text] The text to lint (used for TTY). - * @returns {Promise} The exit code for the operation. - */ - async execute(args, text) { - if (Array.isArray(args)) { - debug("CLI args: %o", args.slice(2)); - } - let options; - - try { - options = CLIOptions.parse(args); - } catch (error) { - log.error(error.message); - return 2; - } - - const files = options._; - const useStdin = typeof text === "string"; - - if (options.help) { - log.info(CLIOptions.generateHelp()); - return 0; - } - if (options.version) { - log.info(RuntimeInfo.version()); - return 0; - } - if (options.envInfo) { - try { - log.info(RuntimeInfo.environment()); - return 0; - } catch (err) { - log.error(err.message); - return 2; - } - } - - if (options.printConfig) { - if (files.length) { - log.error("The --print-config option must be used with exactly one file name."); - return 2; - } - if (useStdin) { - log.error("The --print-config option is not available for piped-in code."); - return 2; - } - - const engine = new ESLint(translateOptions(options)); - const fileConfig = - await engine.calculateConfigForFile(options.printConfig); - - log.info(JSON.stringify(fileConfig, null, " ")); - return 0; - } - - debug(`Running on ${useStdin ? "text" : "files"}`); - - if (options.fix && options.fixDryRun) { - log.error("The --fix option and the --fix-dry-run option cannot be used together."); - return 2; - } - if (useStdin && options.fix) { - log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead."); - return 2; - } - if (options.fixType && !options.fix && !options.fixDryRun) { - log.error("The --fix-type option requires either --fix or --fix-dry-run."); - return 2; - } - - const engine = new ESLint(translateOptions(options)); - let results; - - if (useStdin) { - results = await engine.lintText(text, { - filePath: options.stdinFilename, - warnIgnored: true - }); - } else { - results = await engine.lintFiles(files); - } - - if (options.fix) { - debug("Fix mode enabled - applying fixes"); - await ESLint.outputFixes(results); - } - - if (options.quiet) { - debug("Quiet mode enabled - filtering out warnings"); - results = ESLint.getErrorResults(results); - } - - if (await printResults(engine, results, options.format, options.outputFile)) { - const { errorCount, warningCount } = countErrors(results); - const tooManyWarnings = - options.maxWarnings >= 0 && warningCount > options.maxWarnings; - - if (!errorCount && tooManyWarnings) { - log.error( - "ESLint found too many warnings (maximum: %s).", - options.maxWarnings - ); - } - - return (errorCount || tooManyWarnings) ? 1 : 0; - } - - return 2; - } -}; - -module.exports = cli; diff --git a/tools/node_modules/eslint/lib/eslint/eslint.js b/tools/node_modules/eslint/lib/eslint/eslint.js deleted file mode 100644 index a51ffbfe41a63716fd9ead8336c8b13c0eb962af..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/eslint/eslint.js +++ /dev/null @@ -1,662 +0,0 @@ -/** - * @fileoverview Main API Class - * @author Kai Cataldo - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const path = require("path"); -const fs = require("fs"); -const { promisify } = require("util"); -const { CLIEngine, getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); -const BuiltinRules = require("../rules"); -const { - Legacy: { - ConfigOps: { - getRuleSeverity - } - } -} = require("@eslint/eslintrc"); -const { version } = require("../../package.json"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */ -/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */ -/** @typedef {import("../shared/types").ConfigData} ConfigData */ -/** @typedef {import("../shared/types").LintMessage} LintMessage */ -/** @typedef {import("../shared/types").Plugin} Plugin */ -/** @typedef {import("../shared/types").Rule} Rule */ -/** @typedef {import("./load-formatter").Formatter} Formatter */ - -/** - * The options with which to configure the ESLint instance. - * @typedef {Object} ESLintOptions - * @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments. - * @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance - * @property {boolean} [cache] Enable result caching. - * @property {string} [cacheLocation] The cache file to use instead of .eslintcache. - * @property {string} [cwd] The value to use for the current working directory. - * @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`. - * @property {string[]} [extensions] An array of file extensions to check. - * @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean. - * @property {string[]} [fixTypes] Array of rule types to apply fixes for. - * @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file. - * @property {boolean} [ignore] False disables use of .eslintignore. - * @property {string} [ignorePath] The ignore file to use instead of .eslintignore. - * @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance - * @property {string} [overrideConfigFile] The configuration file to use. - * @property {Record} [plugins] An array of plugin implementations. - * @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives. - * @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD. - * @property {string[]} [rulePaths] An array of directories to load custom rules from. - * @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files. - */ - -/** - * A rules metadata object. - * @typedef {Object} RulesMeta - * @property {string} id The plugin ID. - * @property {Object} definition The plugin definition. - */ - -/** - * A linting result. - * @typedef {Object} LintResult - * @property {string} filePath The path to the file that was linted. - * @property {LintMessage[]} messages All of the messages for the result. - * @property {number} errorCount Number of errors for the result. - * @property {number} warningCount Number of warnings for the result. - * @property {number} fixableErrorCount Number of fixable errors for the result. - * @property {number} fixableWarningCount Number of fixable warnings for the result. - * @property {string} [source] The source code of the file that was linted. - * @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible. - * @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules. - */ - -/** - * Private members for the `ESLint` instance. - * @typedef {Object} ESLintPrivateMembers - * @property {CLIEngine} cliEngine The wrapped CLIEngine instance. - * @property {ESLintOptions} options The options used to instantiate the ESLint instance. - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const writeFile = promisify(fs.writeFile); - -/** - * The map with which to store private class members. - * @type {WeakMap} - */ -const privateMembersMap = new WeakMap(); - -/** - * Check if a given value is a non-empty string or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if `x` is a non-empty string. - */ -function isNonEmptyString(x) { - return typeof x === "string" && x.trim() !== ""; -} - -/** - * Check if a given value is an array of non-empty stringss or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if `x` is an array of non-empty stringss. - */ -function isArrayOfNonEmptyString(x) { - return Array.isArray(x) && x.every(isNonEmptyString); -} - -/** - * Check if a given value is a valid fix type or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if `x` is valid fix type. - */ -function isFixType(x) { - return x === "problem" || x === "suggestion" || x === "layout"; -} - -/** - * Check if a given value is an array of fix types or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if `x` is an array of fix types. - */ -function isFixTypeArray(x) { - return Array.isArray(x) && x.every(isFixType); -} - -/** - * The error for invalid options. - */ -class ESLintInvalidOptionsError extends Error { - constructor(messages) { - super(`Invalid Options:\n- ${messages.join("\n- ")}`); - this.code = "ESLINT_INVALID_OPTIONS"; - Error.captureStackTrace(this, ESLintInvalidOptionsError); - } -} - -/** - * Validates and normalizes options for the wrapped CLIEngine instance. - * @param {ESLintOptions} options The options to process. - * @returns {ESLintOptions} The normalized options. - */ -function processOptions({ - allowInlineConfig = true, // ↠we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored. - baseConfig = null, - cache = false, - cacheLocation = ".eslintcache", - cwd = process.cwd(), - errorOnUnmatchedPattern = true, - extensions = null, // ↠should be null by default because if it's an array then it suppresses RFC20 feature. - fix = false, - fixTypes = null, // ↠should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property. - globInputPaths = true, - ignore = true, - ignorePath = null, // ↠should be null by default because if it's a string then it may throw ENOENT. - overrideConfig = null, - overrideConfigFile = null, - plugins = {}, - reportUnusedDisableDirectives = null, // ↠should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that. - resolvePluginsRelativeTo = null, // ↠should be null by default because if it's a string then it suppresses RFC47 feature. - rulePaths = [], - useEslintrc = true, - ...unknownOptions -}) { - const errors = []; - const unknownOptionKeys = Object.keys(unknownOptions); - - if (unknownOptionKeys.length >= 1) { - errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`); - if (unknownOptionKeys.includes("cacheFile")) { - errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead."); - } - if (unknownOptionKeys.includes("configFile")) { - errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead."); - } - if (unknownOptionKeys.includes("envs")) { - errors.push("'envs' has been removed. Please use the 'overrideConfig.env' option instead."); - } - if (unknownOptionKeys.includes("globals")) { - errors.push("'globals' has been removed. Please use the 'overrideConfig.globals' option instead."); - } - if (unknownOptionKeys.includes("ignorePattern")) { - errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead."); - } - if (unknownOptionKeys.includes("parser")) { - errors.push("'parser' has been removed. Please use the 'overrideConfig.parser' option instead."); - } - if (unknownOptionKeys.includes("parserOptions")) { - errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead."); - } - if (unknownOptionKeys.includes("rules")) { - errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead."); - } - } - if (typeof allowInlineConfig !== "boolean") { - errors.push("'allowInlineConfig' must be a boolean."); - } - if (typeof baseConfig !== "object") { - errors.push("'baseConfig' must be an object or null."); - } - if (typeof cache !== "boolean") { - errors.push("'cache' must be a boolean."); - } - if (!isNonEmptyString(cacheLocation)) { - errors.push("'cacheLocation' must be a non-empty string."); - } - if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) { - errors.push("'cwd' must be an absolute path."); - } - if (typeof errorOnUnmatchedPattern !== "boolean") { - errors.push("'errorOnUnmatchedPattern' must be a boolean."); - } - if (!isArrayOfNonEmptyString(extensions) && extensions !== null) { - errors.push("'extensions' must be an array of non-empty strings or null."); - } - if (typeof fix !== "boolean" && typeof fix !== "function") { - errors.push("'fix' must be a boolean or a function."); - } - if (fixTypes !== null && !isFixTypeArray(fixTypes)) { - errors.push("'fixTypes' must be an array of any of \"problem\", \"suggestion\", and \"layout\"."); - } - if (typeof globInputPaths !== "boolean") { - errors.push("'globInputPaths' must be a boolean."); - } - if (typeof ignore !== "boolean") { - errors.push("'ignore' must be a boolean."); - } - if (!isNonEmptyString(ignorePath) && ignorePath !== null) { - errors.push("'ignorePath' must be a non-empty string or null."); - } - if (typeof overrideConfig !== "object") { - errors.push("'overrideConfig' must be an object or null."); - } - if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) { - errors.push("'overrideConfigFile' must be a non-empty string or null."); - } - if (typeof plugins !== "object") { - errors.push("'plugins' must be an object or null."); - } else if (plugins !== null && Object.keys(plugins).includes("")) { - errors.push("'plugins' must not include an empty string."); - } - if (Array.isArray(plugins)) { - errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead."); - } - if ( - reportUnusedDisableDirectives !== "error" && - reportUnusedDisableDirectives !== "warn" && - reportUnusedDisableDirectives !== "off" && - reportUnusedDisableDirectives !== null - ) { - errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null."); - } - if ( - !isNonEmptyString(resolvePluginsRelativeTo) && - resolvePluginsRelativeTo !== null - ) { - errors.push("'resolvePluginsRelativeTo' must be a non-empty string or null."); - } - if (!isArrayOfNonEmptyString(rulePaths)) { - errors.push("'rulePaths' must be an array of non-empty strings."); - } - if (typeof useEslintrc !== "boolean") { - errors.push("'useElintrc' must be a boolean."); - } - - if (errors.length > 0) { - throw new ESLintInvalidOptionsError(errors); - } - - return { - allowInlineConfig, - baseConfig, - cache, - cacheLocation, - configFile: overrideConfigFile, - cwd, - errorOnUnmatchedPattern, - extensions, - fix, - fixTypes, - globInputPaths, - ignore, - ignorePath, - reportUnusedDisableDirectives, - resolvePluginsRelativeTo, - rulePaths, - useEslintrc - }; -} - -/** - * Check if a value has one or more properties and that value is not undefined. - * @param {any} obj The value to check. - * @returns {boolean} `true` if `obj` has one or more properties that that value is not undefined. - */ -function hasDefinedProperty(obj) { - if (typeof obj === "object" && obj !== null) { - for (const key in obj) { - if (typeof obj[key] !== "undefined") { - return true; - } - } - } - return false; -} - -/** - * Create rulesMeta object. - * @param {Map} rules a map of rules from which to generate the object. - * @returns {Object} metadata for all enabled rules. - */ -function createRulesMeta(rules) { - return Array.from(rules).reduce((retVal, [id, rule]) => { - retVal[id] = rule.meta; - return retVal; - }, {}); -} - -/** @type {WeakMap} */ -const usedDeprecatedRulesCache = new WeakMap(); - -/** - * Create used deprecated rule list. - * @param {CLIEngine} cliEngine The CLIEngine instance. - * @param {string} maybeFilePath The absolute path to a lint target file or `""`. - * @returns {DeprecatedRuleInfo[]} The used deprecated rule list. - */ -function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) { - const { - configArrayFactory, - options: { cwd } - } = getCLIEngineInternalSlots(cliEngine); - const filePath = path.isAbsolute(maybeFilePath) - ? maybeFilePath - : path.join(cwd, "__placeholder__.js"); - const configArray = configArrayFactory.getConfigArrayForFile(filePath); - const config = configArray.extractConfig(filePath); - - // Most files use the same config, so cache it. - if (!usedDeprecatedRulesCache.has(config)) { - const pluginRules = configArray.pluginRules; - const retv = []; - - for (const [ruleId, ruleConf] of Object.entries(config.rules)) { - if (getRuleSeverity(ruleConf) === 0) { - continue; - } - const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId); - const meta = rule && rule.meta; - - if (meta && meta.deprecated) { - retv.push({ ruleId, replacedBy: meta.replacedBy || [] }); - } - } - - usedDeprecatedRulesCache.set(config, Object.freeze(retv)); - } - - return usedDeprecatedRulesCache.get(config); -} - -/** - * Processes the linting results generated by a CLIEngine linting report to - * match the ESLint class's API. - * @param {CLIEngine} cliEngine The CLIEngine instance. - * @param {CLIEngineLintReport} report The CLIEngine linting report to process. - * @returns {LintResult[]} The processed linting results. - */ -function processCLIEngineLintReport(cliEngine, { results }) { - const descriptor = { - configurable: true, - enumerable: true, - get() { - return getOrFindUsedDeprecatedRules(cliEngine, this.filePath); - } - }; - - for (const result of results) { - Object.defineProperty(result, "usedDeprecatedRules", descriptor); - } - - return results; -} - -/** - * An Array.prototype.sort() compatible compare function to order results by their file path. - * @param {LintResult} a The first lint result. - * @param {LintResult} b The second lint result. - * @returns {number} An integer representing the order in which the two results should occur. - */ -function compareResultsByFilePath(a, b) { - if (a.filePath < b.filePath) { - return -1; - } - - if (a.filePath > b.filePath) { - return 1; - } - - return 0; -} - -class ESLint { - - /** - * Creates a new instance of the main ESLint API. - * @param {ESLintOptions} options The options for this instance. - */ - constructor(options = {}) { - const processedOptions = processOptions(options); - const cliEngine = new CLIEngine(processedOptions); - const { - additionalPluginPool, - configArrayFactory, - lastConfigArrays - } = getCLIEngineInternalSlots(cliEngine); - let updated = false; - - /* - * Address `plugins` to add plugin implementations. - * Operate the `additionalPluginPool` internal slot directly to avoid - * using `addPlugin(id, plugin)` method that resets cache everytime. - */ - if (options.plugins) { - for (const [id, plugin] of Object.entries(options.plugins)) { - additionalPluginPool.set(id, plugin); - updated = true; - } - } - - /* - * Address `overrideConfig` to set override config. - * Operate the `configArrayFactory` internal slot directly because this - * functionality doesn't exist as the public API of CLIEngine. - */ - if (hasDefinedProperty(options.overrideConfig)) { - configArrayFactory.setOverrideConfig(options.overrideConfig); - updated = true; - } - - // Update caches. - if (updated) { - configArrayFactory.clearCache(); - lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile(); - } - - // Initialize private properties. - privateMembersMap.set(this, { - cliEngine, - options: processedOptions - }); - } - - /** - * The version text. - * @type {string} - */ - static get version() { - return version; - } - - /** - * Outputs fixes from the given results to files. - * @param {LintResult[]} results The lint results. - * @returns {Promise} Returns a promise that is used to track side effects. - */ - static async outputFixes(results) { - if (!Array.isArray(results)) { - throw new Error("'results' must be an array"); - } - - await Promise.all( - results - .filter(result => { - if (typeof result !== "object" || result === null) { - throw new Error("'results' must include only objects"); - } - return ( - typeof result.output === "string" && - path.isAbsolute(result.filePath) - ); - }) - .map(r => writeFile(r.filePath, r.output)) - ); - } - - /** - * Returns results that only contains errors. - * @param {LintResult[]} results The results to filter. - * @returns {LintResult[]} The filtered results. - */ - static getErrorResults(results) { - return CLIEngine.getErrorResults(results); - } - - /** - * Executes the current configuration on an array of file and directory names. - * @param {string[]} patterns An array of file and directory names. - * @returns {Promise} The results of linting the file patterns given. - */ - async lintFiles(patterns) { - if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) { - throw new Error("'patterns' must be a non-empty string or an array of non-empty strings"); - } - const { cliEngine } = privateMembersMap.get(this); - - return processCLIEngineLintReport( - cliEngine, - cliEngine.executeOnFiles(patterns) - ); - } - - /** - * Executes the current configuration on text. - * @param {string} code A string of JavaScript code to lint. - * @param {Object} [options] The options. - * @param {string} [options.filePath] The path to the file of the source code. - * @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path. - * @returns {Promise} The results of linting the string of code given. - */ - async lintText(code, options = {}) { - if (typeof code !== "string") { - throw new Error("'code' must be a string"); - } - if (typeof options !== "object") { - throw new Error("'options' must be an object, null, or undefined"); - } - const { - filePath, - warnIgnored = false, - ...unknownOptions - } = options || {}; - - for (const key of Object.keys(unknownOptions)) { - throw new Error(`'options' must not include the unknown option '${key}'`); - } - if (filePath !== void 0 && !isNonEmptyString(filePath)) { - throw new Error("'options.filePath' must be a non-empty string or undefined"); - } - if (typeof warnIgnored !== "boolean") { - throw new Error("'options.warnIgnored' must be a boolean or undefined"); - } - - const { cliEngine } = privateMembersMap.get(this); - - return processCLIEngineLintReport( - cliEngine, - cliEngine.executeOnText(code, filePath, warnIgnored) - ); - } - - /** - * Returns the formatter representing the given formatter name. - * @param {string} [name] The name of the formattter to load. - * The following values are allowed: - * - `undefined` ... Load `stylish` builtin formatter. - * - A builtin formatter name ... Load the builtin formatter. - * - A thirdparty formatter name: - * - `foo` → `eslint-formatter-foo` - * - `@foo` → `@foo/eslint-formatter` - * - `@foo/bar` → `@foo/eslint-formatter-bar` - * - A file path ... Load the file. - * @returns {Promise} A promise resolving to the formatter object. - * This promise will be rejected if the given formatter was not found or not - * a function. - */ - async loadFormatter(name = "stylish") { - if (typeof name !== "string") { - throw new Error("'name' must be a string"); - } - - const { cliEngine } = privateMembersMap.get(this); - const formatter = cliEngine.getFormatter(name); - - if (typeof formatter !== "function") { - throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`); - } - - return { - - /** - * The main formatter method. - * @param {LintResults[]} results The lint results to format. - * @returns {string} The formatted lint results. - */ - format(results) { - let rulesMeta = null; - - results.sort(compareResultsByFilePath); - - return formatter(results, { - get rulesMeta() { - if (!rulesMeta) { - rulesMeta = createRulesMeta(cliEngine.getRules()); - } - - return rulesMeta; - } - }); - } - }; - } - - /** - * Returns a configuration object for the given file based on the CLI options. - * This is the same logic used by the ESLint CLI executable to determine - * configuration for each file it processes. - * @param {string} filePath The path of the file to retrieve a config object for. - * @returns {Promise} A configuration object for the file. - */ - async calculateConfigForFile(filePath) { - if (!isNonEmptyString(filePath)) { - throw new Error("'filePath' must be a non-empty string"); - } - const { cliEngine } = privateMembersMap.get(this); - - return cliEngine.getConfigForFile(filePath); - } - - /** - * Checks if a given path is ignored by ESLint. - * @param {string} filePath The path of the file to check. - * @returns {Promise} Whether or not the given path is ignored. - */ - async isPathIgnored(filePath) { - if (!isNonEmptyString(filePath)) { - throw new Error("'filePath' must be a non-empty string"); - } - const { cliEngine } = privateMembersMap.get(this); - - return cliEngine.isPathIgnored(filePath); - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - ESLint, - - /** - * Get the private class members of a given ESLint instance for tests. - * @param {ESLint} instance The ESLint instance to get. - * @returns {ESLintPrivateMembers} The instance's private class members. - */ - getESLintPrivateMembers(instance) { - return privateMembersMap.get(instance); - } -}; diff --git a/tools/node_modules/eslint/lib/eslint/index.js b/tools/node_modules/eslint/lib/eslint/index.js deleted file mode 100644 index c9185ee0eba0a550d31c073b97df8fc7d41e1a13..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/eslint/index.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -const { ESLint } = require("./eslint"); - -module.exports = { - ESLint -}; diff --git a/tools/node_modules/eslint/lib/init/autoconfig.js b/tools/node_modules/eslint/lib/init/autoconfig.js deleted file mode 100644 index 0ace177aa16a425049e99679529d12baf76f8f73..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/init/autoconfig.js +++ /dev/null @@ -1,348 +0,0 @@ -/** - * @fileoverview Used for creating a suggested configuration based on project code. - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"), - recConfig = require("../../conf/eslint-recommended"), - ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"), - { Linter } = require("../linter"), - configRule = require("./config-rule"); - -const debug = require("debug")("eslint:autoconfig"); -const linter = new Linter(); - -//------------------------------------------------------------------------------ -// Data -//------------------------------------------------------------------------------ - -const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only - RECOMMENDED_CONFIG_NAME = "eslint:recommended"; - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Information about a rule configuration, in the context of a Registry. - * @typedef {Object} registryItem - * @param {ruleConfig} config A valid configuration for the rule - * @param {number} specificity The number of elements in the ruleConfig array - * @param {number} errorCount The number of errors encountered when linting with the config - */ - -/** - * This callback is used to measure execution status in a progress bar - * @callback progressCallback - * @param {number} The total number of times the callback will be called. - */ - -/** - * Create registryItems for rules - * @param {rulesConfig} rulesConfig Hash of rule names and arrays of ruleConfig items - * @returns {Object} registryItems for each rule in provided rulesConfig - */ -function makeRegistryItems(rulesConfig) { - return Object.keys(rulesConfig).reduce((accumulator, ruleId) => { - accumulator[ruleId] = rulesConfig[ruleId].map(config => ({ - config, - specificity: config.length || 1, - errorCount: void 0 - })); - return accumulator; - }, {}); -} - -/** - * Creates an object in which to store rule configs and error counts - * - * Unless a rulesConfig is provided at construction, the registry will not contain - * any rules, only methods. This will be useful for building up registries manually. - * - * Registry class - */ -class Registry { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {rulesConfig} [rulesConfig] Hash of rule names and arrays of possible configurations - */ - constructor(rulesConfig) { - this.rules = (rulesConfig) ? makeRegistryItems(rulesConfig) : {}; - } - - /** - * Populate the registry with core rule configs. - * - * It will set the registry's `rule` property to an object having rule names - * as keys and an array of registryItems as values. - * @returns {void} - */ - populateFromCoreRules() { - const rulesConfig = configRule.createCoreRuleConfigs(); - - this.rules = makeRegistryItems(rulesConfig); - } - - /** - * Creates sets of rule configurations which can be used for linting - * and initializes registry errors to zero for those configurations (side effect). - * - * This combines as many rules together as possible, such that the first sets - * in the array will have the highest number of rules configured, and later sets - * will have fewer and fewer, as not all rules have the same number of possible - * configurations. - * - * The length of the returned array will be <= MAX_CONFIG_COMBINATIONS. - * @returns {Object[]} "rules" configurations to use for linting - */ - buildRuleSets() { - let idx = 0; - const ruleIds = Object.keys(this.rules), - ruleSets = []; - - /** - * Add a rule configuration from the registry to the ruleSets - * - * This is broken out into its own function so that it doesn't need to be - * created inside of the while loop. - * @param {string} rule The ruleId to add. - * @returns {void} - */ - const addRuleToRuleSet = function(rule) { - - /* - * This check ensures that there is a rule configuration and that - * it has fewer than the max combinations allowed. - * If it has too many configs, we will only use the most basic of - * the possible configurations. - */ - const hasFewCombos = (this.rules[rule].length <= MAX_CONFIG_COMBINATIONS); - - if (this.rules[rule][idx] && (hasFewCombos || this.rules[rule][idx].specificity <= 2)) { - - /* - * If the rule has too many possible combinations, only take - * simple ones, avoiding objects. - */ - if (!hasFewCombos && typeof this.rules[rule][idx].config[1] === "object") { - return; - } - - ruleSets[idx] = ruleSets[idx] || {}; - ruleSets[idx][rule] = this.rules[rule][idx].config; - - /* - * Initialize errorCount to zero, since this is a config which - * will be linted. - */ - this.rules[rule][idx].errorCount = 0; - } - }.bind(this); - - while (ruleSets.length === idx) { - ruleIds.forEach(addRuleToRuleSet); - idx += 1; - } - - return ruleSets; - } - - /** - * Remove all items from the registry with a non-zero number of errors - * - * Note: this also removes rule configurations which were not linted - * (meaning, they have an undefined errorCount). - * @returns {void} - */ - stripFailingConfigs() { - const ruleIds = Object.keys(this.rules), - newRegistry = new Registry(); - - newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(ruleId => { - const errorFreeItems = newRegistry.rules[ruleId].filter(registryItem => (registryItem.errorCount === 0)); - - if (errorFreeItems.length > 0) { - newRegistry.rules[ruleId] = errorFreeItems; - } else { - delete newRegistry.rules[ruleId]; - } - }); - - return newRegistry; - } - - /** - * Removes rule configurations which were not included in a ruleSet - * @returns {void} - */ - stripExtraConfigs() { - const ruleIds = Object.keys(this.rules), - newRegistry = new Registry(); - - newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(ruleId => { - newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(registryItem => (typeof registryItem.errorCount !== "undefined")); - }); - - return newRegistry; - } - - /** - * Creates a registry of rules which had no error-free configs. - * The new registry is intended to be analyzed to determine whether its rules - * should be disabled or set to warning. - * @returns {Registry} A registry of failing rules. - */ - getFailingRulesRegistry() { - const ruleIds = Object.keys(this.rules), - failingRegistry = new Registry(); - - ruleIds.forEach(ruleId => { - const failingConfigs = this.rules[ruleId].filter(registryItem => (registryItem.errorCount > 0)); - - if (failingConfigs && failingConfigs.length === this.rules[ruleId].length) { - failingRegistry.rules[ruleId] = failingConfigs; - } - }); - - return failingRegistry; - } - - /** - * Create an eslint config for any rules which only have one configuration - * in the registry. - * @returns {Object} An eslint config with rules section populated - */ - createConfig() { - const ruleIds = Object.keys(this.rules), - config = { rules: {} }; - - ruleIds.forEach(ruleId => { - if (this.rules[ruleId].length === 1) { - config.rules[ruleId] = this.rules[ruleId][0].config; - } - }); - - return config; - } - - /** - * Return a cloned registry containing only configs with a desired specificity - * @param {number} specificity Only keep configs with this specificity - * @returns {Registry} A registry of rules - */ - filterBySpecificity(specificity) { - const ruleIds = Object.keys(this.rules), - newRegistry = new Registry(); - - newRegistry.rules = Object.assign({}, this.rules); - ruleIds.forEach(ruleId => { - newRegistry.rules[ruleId] = this.rules[ruleId].filter(registryItem => (registryItem.specificity === specificity)); - }); - - return newRegistry; - } - - /** - * Lint SourceCodes against all configurations in the registry, and record results - * @param {Object[]} sourceCodes SourceCode objects for each filename - * @param {Object} config ESLint config object - * @param {progressCallback} [cb] Optional callback for reporting execution status - * @returns {Registry} New registry with errorCount populated - */ - lintSourceCode(sourceCodes, config, cb) { - let lintedRegistry = new Registry(); - - lintedRegistry.rules = Object.assign({}, this.rules); - - const ruleSets = lintedRegistry.buildRuleSets(); - - lintedRegistry = lintedRegistry.stripExtraConfigs(); - - debug("Linting with all possible rule combinations"); - - const filenames = Object.keys(sourceCodes); - const totalFilesLinting = filenames.length * ruleSets.length; - - filenames.forEach(filename => { - debug(`Linting file: ${filename}`); - - let ruleSetIdx = 0; - - ruleSets.forEach(ruleSet => { - const lintConfig = Object.assign({}, config, { rules: ruleSet }); - const lintResults = linter.verify(sourceCodes[filename], lintConfig); - - lintResults.forEach(result => { - - /* - * It is possible that the error is from a configuration comment - * in a linted file, in which case there may not be a config - * set in this ruleSetIdx. - * (https://github.com/eslint/eslint/issues/5992) - * (https://github.com/eslint/eslint/issues/7860) - */ - if ( - lintedRegistry.rules[result.ruleId] && - lintedRegistry.rules[result.ruleId][ruleSetIdx] - ) { - lintedRegistry.rules[result.ruleId][ruleSetIdx].errorCount += 1; - } - }); - - ruleSetIdx += 1; - - if (cb) { - cb(totalFilesLinting); // eslint-disable-line node/callback-return - } - }); - - // Deallocate for GC - sourceCodes[filename] = null; - }); - - return lintedRegistry; - } -} - -/** - * Extract rule configuration into eslint:recommended where possible. - * - * This will return a new config with `["extends": [ ..., "eslint:recommended"]` and - * only the rules which have configurations different from the recommended config. - * @param {Object} config config object - * @returns {Object} config object using `"extends": ["eslint:recommended"]` - */ -function extendFromRecommended(config) { - const newConfig = Object.assign({}, config); - - ConfigOps.normalizeToStrings(newConfig); - - const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); - - recRules.forEach(ruleId => { - if (lodash.isEqual(recConfig.rules[ruleId], newConfig.rules[ruleId])) { - delete newConfig.rules[ruleId]; - } - }); - newConfig.extends.unshift(RECOMMENDED_CONFIG_NAME); - return newConfig; -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - Registry, - extendFromRecommended -}; diff --git a/tools/node_modules/eslint/lib/init/config-file.js b/tools/node_modules/eslint/lib/init/config-file.js deleted file mode 100644 index fc62b81525e66b10ce369ee544849cc1d5049fc5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/init/config-file.js +++ /dev/null @@ -1,143 +0,0 @@ -/** - * @fileoverview Helper to locate and load configuration files. - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - path = require("path"), - stringify = require("json-stable-stringify-without-jsonify"); - -const debug = require("debug")("eslint:config-file"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines sort order for object keys for json-stable-stringify - * - * see: https://github.com/samn/json-stable-stringify#cmp - * @param {Object} a The first comparison object ({key: akey, value: avalue}) - * @param {Object} b The second comparison object ({key: bkey, value: bvalue}) - * @returns {number} 1 or -1, used in stringify cmp method - */ -function sortByKey(a, b) { - return a.key > b.key ? 1 : -1; -} - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Writes a configuration file in JSON format. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @returns {void} - * @private - */ -function writeJSONConfigFile(config, filePath) { - debug(`Writing JSON config file: ${filePath}`); - - const content = `${stringify(config, { cmp: sortByKey, space: 4 })}\n`; - - fs.writeFileSync(filePath, content, "utf8"); -} - -/** - * Writes a configuration file in YAML format. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @returns {void} - * @private - */ -function writeYAMLConfigFile(config, filePath) { - debug(`Writing YAML config file: ${filePath}`); - - // lazy load YAML to improve performance when not used - const yaml = require("js-yaml"); - - const content = yaml.safeDump(config, { sortKeys: true }); - - fs.writeFileSync(filePath, content, "utf8"); -} - -/** - * Writes a configuration file in JavaScript format. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @throws {Error} If an error occurs linting the config file contents. - * @returns {void} - * @private - */ -function writeJSConfigFile(config, filePath) { - debug(`Writing JS config file: ${filePath}`); - - let contentToWrite; - const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};\n`; - - try { - const { CLIEngine } = require("../cli-engine"); - const linter = new CLIEngine({ - baseConfig: config, - fix: true, - useEslintrc: false - }); - const report = linter.executeOnText(stringifiedContent); - - contentToWrite = report.results[0].output || stringifiedContent; - } catch (e) { - debug("Error linting JavaScript config file, writing unlinted version"); - const errorMessage = e.message; - - contentToWrite = stringifiedContent; - e.message = "An error occurred while generating your JavaScript config file. "; - e.message += "A config file was still generated, but the config file itself may not follow your linting rules."; - e.message += `\nError: ${errorMessage}`; - throw e; - } finally { - fs.writeFileSync(filePath, contentToWrite, "utf8"); - } -} - -/** - * Writes a configuration file. - * @param {Object} config The configuration object to write. - * @param {string} filePath The filename to write to. - * @returns {void} - * @throws {Error} When an unknown file type is specified. - * @private - */ -function write(config, filePath) { - switch (path.extname(filePath)) { - case ".js": - writeJSConfigFile(config, filePath); - break; - - case ".json": - writeJSONConfigFile(config, filePath); - break; - - case ".yaml": - case ".yml": - writeYAMLConfigFile(config, filePath); - break; - - default: - throw new Error("Can't write to unknown file type."); - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - write -}; diff --git a/tools/node_modules/eslint/lib/init/config-initializer.js b/tools/node_modules/eslint/lib/init/config-initializer.js deleted file mode 100644 index a02d13562ca40e471d6cd6632e465f60424a3ca8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/init/config-initializer.js +++ /dev/null @@ -1,669 +0,0 @@ -/** - * @fileoverview Config initialization wizard. - * @author Ilya Volodin - */ - - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const util = require("util"), - path = require("path"), - inquirer = require("inquirer"), - ProgressBar = require("progress"), - semver = require("semver"), - espree = require("espree"), - recConfig = require("../../conf/eslint-recommended"), - ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"), - log = require("../shared/logging"), - naming = require("@eslint/eslintrc/lib/shared/naming"), - ModuleResolver = require("../shared/relative-module-resolver"), - autoconfig = require("./autoconfig.js"), - ConfigFile = require("./config-file"), - npmUtils = require("./npm-utils"), - { getSourceCodeOfFiles } = require("./source-code-utils"); - -const debug = require("debug")("eslint:config-initializer"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/* istanbul ignore next: hard to test fs function */ -/** - * Create .eslintrc file in the current working directory - * @param {Object} config object that contains user's answers - * @param {string} format The file format to write to. - * @returns {void} - */ -function writeFile(config, format) { - - // default is .js - let extname = ".js"; - - if (format === "YAML") { - extname = ".yml"; - } else if (format === "JSON") { - extname = ".json"; - } - - const installedESLint = config.installedESLint; - - delete config.installedESLint; - - ConfigFile.write(config, `./.eslintrc${extname}`); - log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`); - - if (installedESLint) { - log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy."); - } -} - -/** - * Get the peer dependencies of the given module. - * This adds the gotten value to cache at the first time, then reuses it. - * In a process, this function is called twice, but `npmUtils.fetchPeerDependencies` needs to access network which is relatively slow. - * @param {string} moduleName The module name to get. - * @returns {Object} The peer dependencies of the given module. - * This object is the object of `peerDependencies` field of `package.json`. - * Returns null if npm was not found. - */ -function getPeerDependencies(moduleName) { - let result = getPeerDependencies.cache.get(moduleName); - - if (!result) { - log.info(`Checking peerDependencies of ${moduleName}`); - - result = npmUtils.fetchPeerDependencies(moduleName); - getPeerDependencies.cache.set(moduleName, result); - } - - return result; -} -getPeerDependencies.cache = new Map(); - -/** - * Return necessary plugins, configs, parsers, etc. based on the config - * @param {Object} config config object - * @param {boolean} [installESLint=true] If `false` is given, it does not install eslint. - * @returns {string[]} An array of modules to be installed. - */ -function getModulesList(config, installESLint) { - const modules = {}; - - // Create a list of modules which should be installed based on config - if (config.plugins) { - for (const plugin of config.plugins) { - const moduleName = naming.normalizePackageName(plugin, "eslint-plugin"); - - modules[moduleName] = "latest"; - } - } - if (config.extends) { - const extendList = Array.isArray(config.extends) ? config.extends : [config.extends]; - - for (const extend of extendList) { - if (extend.startsWith("eslint:") || extend.startsWith("plugin:")) { - continue; - } - const moduleName = naming.normalizePackageName(extend, "eslint-config"); - - modules[moduleName] = "latest"; - Object.assign( - modules, - getPeerDependencies(`${moduleName}@latest`) - ); - } - } - - const parser = config.parser || (config.parserOptions && config.parserOptions.parser); - - if (parser) { - modules[parser] = "latest"; - } - - if (installESLint === false) { - delete modules.eslint; - } else { - const installStatus = npmUtils.checkDevDeps(["eslint"]); - - // Mark to show messages if it's new installation of eslint. - if (installStatus.eslint === false) { - log.info("Local ESLint installation not found."); - modules.eslint = modules.eslint || "latest"; - config.installedESLint = true; - } - } - - return Object.keys(modules).map(name => `${name}@${modules[name]}`); -} - -/** - * Set the `rules` of a config by examining a user's source code - * - * Note: This clones the config object and returns a new config to avoid mutating - * the original config parameter. - * @param {Object} answers answers received from inquirer - * @param {Object} config config object - * @returns {Object} config object with configured rules - */ -function configureRules(answers, config) { - const BAR_TOTAL = 20, - BAR_SOURCE_CODE_TOTAL = 4, - newConfig = Object.assign({}, config), - disabledConfigs = {}; - let sourceCodes, - registry; - - // Set up a progress bar, as this process can take a long time - const bar = new ProgressBar("Determining Config: :percent [:bar] :elapseds elapsed, eta :etas ", { - width: 30, - total: BAR_TOTAL - }); - - bar.tick(0); // Shows the progress bar - - // Get the SourceCode of all chosen files - const patterns = answers.patterns.split(/[\s]+/u); - - try { - sourceCodes = getSourceCodeOfFiles(patterns, { baseConfig: newConfig, useEslintrc: false }, total => { - bar.tick((BAR_SOURCE_CODE_TOTAL / total)); - }); - } catch (e) { - log.info("\n"); - throw e; - } - const fileQty = Object.keys(sourceCodes).length; - - if (fileQty === 0) { - log.info("\n"); - throw new Error("Automatic Configuration failed. No files were able to be parsed."); - } - - // Create a registry of rule configs - registry = new autoconfig.Registry(); - registry.populateFromCoreRules(); - - // Lint all files with each rule config in the registry - registry = registry.lintSourceCode(sourceCodes, newConfig, total => { - bar.tick((BAR_TOTAL - BAR_SOURCE_CODE_TOTAL) / total); // Subtract out ticks used at beginning - }); - debug(`\nRegistry: ${util.inspect(registry.rules, { depth: null })}`); - - // Create a list of recommended rules, because we don't want to disable them - const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId])); - - // Find and disable rules which had no error-free configuration - const failingRegistry = registry.getFailingRulesRegistry(); - - Object.keys(failingRegistry.rules).forEach(ruleId => { - - // If the rule is recommended, set it to error, otherwise disable it - disabledConfigs[ruleId] = (recRules.indexOf(ruleId) !== -1) ? 2 : 0; - }); - - // Now that we know which rules to disable, strip out configs with errors - registry = registry.stripFailingConfigs(); - - /* - * If there is only one config that results in no errors for a rule, we should use it. - * createConfig will only add rules that have one configuration in the registry. - */ - const singleConfigs = registry.createConfig().rules; - - /* - * The "sweet spot" for number of options in a config seems to be two (severity plus one option). - * Very often, a third option (usually an object) is available to address - * edge cases, exceptions, or unique situations. We will prefer to use a config with - * specificity of two. - */ - const specTwoConfigs = registry.filterBySpecificity(2).createConfig().rules; - - // Maybe a specific combination using all three options works - const specThreeConfigs = registry.filterBySpecificity(3).createConfig().rules; - - // If all else fails, try to use the default (severity only) - const defaultConfigs = registry.filterBySpecificity(1).createConfig().rules; - - // Combine configs in reverse priority order (later take precedence) - newConfig.rules = Object.assign({}, disabledConfigs, defaultConfigs, specThreeConfigs, specTwoConfigs, singleConfigs); - - // Make sure progress bar has finished (floating point rounding) - bar.update(BAR_TOTAL); - - // Log out some stats to let the user know what happened - const finalRuleIds = Object.keys(newConfig.rules); - const totalRules = finalRuleIds.length; - const enabledRules = finalRuleIds.filter(ruleId => (newConfig.rules[ruleId] !== 0)).length; - const resultMessage = [ - `\nEnabled ${enabledRules} out of ${totalRules}`, - `rules based on ${fileQty}`, - `file${(fileQty === 1) ? "." : "s."}` - ].join(" "); - - log.info(resultMessage); - - ConfigOps.normalizeToStrings(newConfig); - return newConfig; -} - -/** - * process user's answers and create config object - * @param {Object} answers answers received from inquirer - * @returns {Object} config object - */ -function processAnswers(answers) { - let config = { - rules: {}, - env: {}, - parserOptions: {}, - extends: [] - }; - - config.parserOptions.ecmaVersion = espree.latestEcmaVersion; - config.env.es2021 = true; - - // set the module type - if (answers.moduleType === "esm") { - config.parserOptions.sourceType = "module"; - } else if (answers.moduleType === "commonjs") { - config.env.commonjs = true; - } - - // add in browser and node environments if necessary - answers.env.forEach(env => { - config.env[env] = true; - }); - - // add in library information - if (answers.framework === "react") { - config.parserOptions.ecmaFeatures = { - jsx: true - }; - config.plugins = ["react"]; - config.extends.push("plugin:react/recommended"); - } else if (answers.framework === "vue") { - config.plugins = ["vue"]; - config.extends.push("plugin:vue/essential"); - } - - if (answers.typescript) { - if (answers.framework === "vue") { - config.parserOptions.parser = "@typescript-eslint/parser"; - } else { - config.parser = "@typescript-eslint/parser"; - } - - if (Array.isArray(config.plugins)) { - config.plugins.push("@typescript-eslint"); - } else { - config.plugins = ["@typescript-eslint"]; - } - } - - // setup rules based on problems/style enforcement preferences - if (answers.purpose === "problems") { - config.extends.unshift("eslint:recommended"); - } else if (answers.purpose === "style") { - if (answers.source === "prompt") { - config.extends.unshift("eslint:recommended"); - config.rules.indent = ["error", answers.indent]; - config.rules.quotes = ["error", answers.quotes]; - config.rules["linebreak-style"] = ["error", answers.linebreak]; - config.rules.semi = ["error", answers.semi ? "always" : "never"]; - } else if (answers.source === "auto") { - config = configureRules(answers, config); - config = autoconfig.extendFromRecommended(config); - } - } - if (answers.typescript && config.extends.includes("eslint:recommended")) { - config.extends.push("plugin:@typescript-eslint/eslint-recommended"); - config.extends.push("plugin:@typescript-eslint/recommended"); - } - - // normalize extends - if (config.extends.length === 0) { - delete config.extends; - } else if (config.extends.length === 1) { - config.extends = config.extends[0]; - } - - ConfigOps.normalizeToStrings(config); - return config; -} - -/** - * Get the version of the local ESLint. - * @returns {string|null} The version. If the local ESLint was not found, returns null. - */ -function getLocalESLintVersion() { - try { - const eslintPath = ModuleResolver.resolve("eslint", path.join(process.cwd(), "__placeholder__.js")); - const eslint = require(eslintPath); - - return eslint.linter.version || null; - } catch { - return null; - } -} - -/** - * Get the shareable config name of the chosen style guide. - * @param {Object} answers The answers object. - * @returns {string} The shareable config name. - */ -function getStyleGuideName(answers) { - if (answers.styleguide === "airbnb" && answers.framework !== "react") { - return "airbnb-base"; - } - return answers.styleguide; -} - -/** - * Check whether the local ESLint version conflicts with the required version of the chosen shareable config. - * @param {Object} answers The answers object. - * @returns {boolean} `true` if the local ESLint is found then it conflicts with the required version of the chosen shareable config. - */ -function hasESLintVersionConflict(answers) { - - // Get the local ESLint version. - const localESLintVersion = getLocalESLintVersion(); - - if (!localESLintVersion) { - return false; - } - - // Get the required range of ESLint version. - const configName = getStyleGuideName(answers); - const moduleName = `eslint-config-${configName}@latest`; - const peerDependencies = getPeerDependencies(moduleName) || {}; - const requiredESLintVersionRange = peerDependencies.eslint; - - if (!requiredESLintVersionRange) { - return false; - } - - answers.localESLintVersion = localESLintVersion; - answers.requiredESLintVersionRange = requiredESLintVersionRange; - - // Check the version. - if (semver.satisfies(localESLintVersion, requiredESLintVersionRange)) { - answers.installESLint = false; - return false; - } - - return true; -} - -/** - * Install modules. - * @param {string[]} modules Modules to be installed. - * @returns {void} - */ -function installModules(modules) { - log.info(`Installing ${modules.join(", ")}`); - npmUtils.installSyncSaveDev(modules); -} - -/* istanbul ignore next: no need to test inquirer */ -/** - * Ask user to install modules. - * @param {string[]} modules Array of modules to be installed. - * @param {boolean} packageJsonExists Indicates if package.json is existed. - * @returns {Promise} Answer that indicates if user wants to install. - */ -function askInstallModules(modules, packageJsonExists) { - - // If no modules, do nothing. - if (modules.length === 0) { - return Promise.resolve(); - } - - log.info("The config that you've selected requires the following dependencies:\n"); - log.info(modules.join(" ")); - return inquirer.prompt([ - { - type: "confirm", - name: "executeInstallation", - message: "Would you like to install them now with npm?", - default: true, - when() { - return modules.length && packageJsonExists; - } - } - ]).then(({ executeInstallation }) => { - if (executeInstallation) { - installModules(modules); - } - }); -} - -/* istanbul ignore next: no need to test inquirer */ -/** - * Ask use a few questions on command prompt - * @returns {Promise} The promise with the result of the prompt - */ -function promptUser() { - - return inquirer.prompt([ - { - type: "list", - name: "purpose", - message: "How would you like to use ESLint?", - default: "problems", - choices: [ - { name: "To check syntax only", value: "syntax" }, - { name: "To check syntax and find problems", value: "problems" }, - { name: "To check syntax, find problems, and enforce code style", value: "style" } - ] - }, - { - type: "list", - name: "moduleType", - message: "What type of modules does your project use?", - default: "esm", - choices: [ - { name: "JavaScript modules (import/export)", value: "esm" }, - { name: "CommonJS (require/exports)", value: "commonjs" }, - { name: "None of these", value: "none" } - ] - }, - { - type: "list", - name: "framework", - message: "Which framework does your project use?", - default: "react", - choices: [ - { name: "React", value: "react" }, - { name: "Vue.js", value: "vue" }, - { name: "None of these", value: "none" } - ] - }, - { - type: "confirm", - name: "typescript", - message: "Does your project use TypeScript?", - default: false - }, - { - type: "checkbox", - name: "env", - message: "Where does your code run?", - default: ["browser"], - choices: [ - { name: "Browser", value: "browser" }, - { name: "Node", value: "node" } - ] - }, - { - type: "list", - name: "source", - message: "How would you like to define a style for your project?", - default: "guide", - choices: [ - { name: "Use a popular style guide", value: "guide" }, - { name: "Answer questions about your style", value: "prompt" }, - { name: "Inspect your JavaScript file(s)", value: "auto" } - ], - when(answers) { - return answers.purpose === "style"; - } - }, - { - type: "list", - name: "styleguide", - message: "Which style guide do you want to follow?", - choices: [ - { name: "Airbnb: https://github.com/airbnb/javascript", value: "airbnb" }, - { name: "Standard: https://github.com/standard/standard", value: "standard" }, - { name: "Google: https://github.com/google/eslint-config-google", value: "google" } - ], - when(answers) { - answers.packageJsonExists = npmUtils.checkPackageJson(); - return answers.source === "guide" && answers.packageJsonExists; - } - }, - { - type: "input", - name: "patterns", - message: "Which file(s), path(s), or glob(s) should be examined?", - when(answers) { - return (answers.source === "auto"); - }, - validate(input) { - if (input.trim().length === 0 && input.trim() !== ",") { - return "You must tell us what code to examine. Try again."; - } - return true; - } - }, - { - type: "list", - name: "format", - message: "What format do you want your config file to be in?", - default: "JavaScript", - choices: ["JavaScript", "YAML", "JSON"] - }, - { - type: "confirm", - name: "installESLint", - message(answers) { - const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange) - ? "upgrade" - : "downgrade"; - - return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n Do you want to ${verb}?`; - }, - default: true, - when(answers) { - return answers.source === "guide" && answers.packageJsonExists && hasESLintVersionConflict(answers); - } - } - ]).then(earlyAnswers => { - - // early exit if no style guide is necessary - if (earlyAnswers.purpose !== "style") { - const config = processAnswers(earlyAnswers); - const modules = getModulesList(config); - - return askInstallModules(modules, earlyAnswers.packageJsonExists) - .then(() => writeFile(config, earlyAnswers.format)); - } - - // early exit if you are using a style guide - if (earlyAnswers.source === "guide") { - if (!earlyAnswers.packageJsonExists) { - log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again."); - return void 0; - } - if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) { - log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`); - } - if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") { - earlyAnswers.styleguide = "airbnb-base"; - } - - const config = processAnswers(earlyAnswers); - - if (Array.isArray(config.extends)) { - config.extends.push(earlyAnswers.styleguide); - } else if (config.extends) { - config.extends = [config.extends, earlyAnswers.styleguide]; - } else { - config.extends = [earlyAnswers.styleguide]; - } - - const modules = getModulesList(config); - - return askInstallModules(modules, earlyAnswers.packageJsonExists) - .then(() => writeFile(config, earlyAnswers.format)); - - } - - if (earlyAnswers.source === "auto") { - const combinedAnswers = Object.assign({}, earlyAnswers); - const config = processAnswers(combinedAnswers); - const modules = getModulesList(config); - - return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format)); - } - - // continue with the style questions otherwise... - return inquirer.prompt([ - { - type: "list", - name: "indent", - message: "What style of indentation do you use?", - default: "tab", - choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }] - }, - { - type: "list", - name: "quotes", - message: "What quotes do you use for strings?", - default: "double", - choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }] - }, - { - type: "list", - name: "linebreak", - message: "What line endings do you use?", - default: "unix", - choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }] - }, - { - type: "confirm", - name: "semi", - message: "Do you require semicolons?", - default: true - } - ]).then(answers => { - const totalAnswers = Object.assign({}, earlyAnswers, answers); - - const config = processAnswers(totalAnswers); - const modules = getModulesList(config); - - return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format)); - }); - }); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -const init = { - getModulesList, - hasESLintVersionConflict, - installModules, - processAnswers, - /* istanbul ignore next */initializeConfig() { - return promptUser(); - } -}; - -module.exports = init; diff --git a/tools/node_modules/eslint/lib/init/config-rule.js b/tools/node_modules/eslint/lib/init/config-rule.js deleted file mode 100644 index 7aec89c3df004f52d06ff5cdb734ea1cd6426994..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/init/config-rule.js +++ /dev/null @@ -1,317 +0,0 @@ -/** - * @fileoverview Create configurations for a rule - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const builtInRules = require("../rules"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Wrap all of the elements of an array into arrays. - * @param {*[]} xs Any array. - * @returns {Array[]} An array of arrays. - */ -function explodeArray(xs) { - return xs.reduce((accumulator, x) => { - accumulator.push([x]); - return accumulator; - }, []); -} - -/** - * Mix two arrays such that each element of the second array is concatenated - * onto each element of the first array. - * - * For example: - * combineArrays([a, [b, c]], [x, y]); // -> [[a, x], [a, y], [b, c, x], [b, c, y]] - * @param {Array} arr1 The first array to combine. - * @param {Array} arr2 The second array to combine. - * @returns {Array} A mixture of the elements of the first and second arrays. - */ -function combineArrays(arr1, arr2) { - const res = []; - - if (arr1.length === 0) { - return explodeArray(arr2); - } - if (arr2.length === 0) { - return explodeArray(arr1); - } - arr1.forEach(x1 => { - arr2.forEach(x2 => { - res.push([].concat(x1, x2)); - }); - }); - return res; -} - -/** - * Group together valid rule configurations based on object properties - * - * e.g.: - * groupByProperty([ - * {before: true}, - * {before: false}, - * {after: true}, - * {after: false} - * ]); - * - * will return: - * [ - * [{before: true}, {before: false}], - * [{after: true}, {after: false}] - * ] - * @param {Object[]} objects Array of objects, each with one property/value pair - * @returns {Array[]} Array of arrays of objects grouped by property - */ -function groupByProperty(objects) { - const groupedObj = objects.reduce((accumulator, obj) => { - const prop = Object.keys(obj)[0]; - - accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj]; - return accumulator; - }, {}); - - return Object.keys(groupedObj).map(prop => groupedObj[prop]); -} - - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Configuration settings for a rule. - * - * A configuration can be a single number (severity), or an array where the first - * element in the array is the severity, and is the only required element. - * Configs may also have one or more additional elements to specify rule - * configuration or options. - * @typedef {Array|number} ruleConfig - * @param {number} 0 The rule's severity (0, 1, 2). - */ - -/** - * Object whose keys are rule names and values are arrays of valid ruleConfig items - * which should be linted against the target source code to determine error counts. - * (a ruleConfigSet.ruleConfigs). - * - * e.g. rulesConfig = { - * "comma-dangle": [2, [2, "always"], [2, "always-multiline"], [2, "never"]], - * "no-console": [2] - * } - * @typedef rulesConfig - */ - - -/** - * Create valid rule configurations by combining two arrays, - * with each array containing multiple objects each with a - * single property/value pair and matching properties. - * - * e.g.: - * combinePropertyObjects( - * [{before: true}, {before: false}], - * [{after: true}, {after: false}] - * ); - * - * will return: - * [ - * {before: true, after: true}, - * {before: true, after: false}, - * {before: false, after: true}, - * {before: false, after: false} - * ] - * @param {Object[]} objArr1 Single key/value objects, all with the same key - * @param {Object[]} objArr2 Single key/value objects, all with another key - * @returns {Object[]} Combined objects for each combination of input properties and values - */ -function combinePropertyObjects(objArr1, objArr2) { - const res = []; - - if (objArr1.length === 0) { - return objArr2; - } - if (objArr2.length === 0) { - return objArr1; - } - objArr1.forEach(obj1 => { - objArr2.forEach(obj2 => { - const combinedObj = {}; - const obj1Props = Object.keys(obj1); - const obj2Props = Object.keys(obj2); - - obj1Props.forEach(prop1 => { - combinedObj[prop1] = obj1[prop1]; - }); - obj2Props.forEach(prop2 => { - combinedObj[prop2] = obj2[prop2]; - }); - res.push(combinedObj); - }); - }); - return res; -} - -/** - * Creates a new instance of a rule configuration set - * - * A rule configuration set is an array of configurations that are valid for a - * given rule. For example, the configuration set for the "semi" rule could be: - * - * ruleConfigSet.ruleConfigs // -> [[2], [2, "always"], [2, "never"]] - * - * Rule configuration set class - */ -class RuleConfigSet { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ruleConfig[]} configs Valid rule configurations - */ - constructor(configs) { - - /** - * Stored valid rule configurations for this instance - * @type {Array} - */ - this.ruleConfigs = configs || []; - } - - /** - * Add a severity level to the front of all configs in the instance. - * This should only be called after all configs have been added to the instance. - * @returns {void} - */ - addErrorSeverity() { - const severity = 2; - - this.ruleConfigs = this.ruleConfigs.map(config => { - config.unshift(severity); - return config; - }); - - // Add a single config at the beginning consisting of only the severity - this.ruleConfigs.unshift(severity); - } - - /** - * Add rule configs from an array of strings (schema enums) - * @param {string[]} enums Array of valid rule options (e.g. ["always", "never"]) - * @returns {void} - */ - addEnums(enums) { - this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, enums)); - } - - /** - * Add rule configurations from a schema object - * @param {Object} obj Schema item with type === "object" - * @returns {boolean} true if at least one schema for the object could be generated, false otherwise - */ - addObject(obj) { - const objectConfigSet = { - objectConfigs: [], - add(property, values) { - for (let idx = 0; idx < values.length; idx++) { - const optionObj = {}; - - optionObj[property] = values[idx]; - this.objectConfigs.push(optionObj); - } - }, - - combine() { - this.objectConfigs = groupByProperty(this.objectConfigs).reduce((accumulator, objArr) => combinePropertyObjects(accumulator, objArr), []); - } - }; - - /* - * The object schema could have multiple independent properties. - * If any contain enums or booleans, they can be added and then combined - */ - Object.keys(obj.properties).forEach(prop => { - if (obj.properties[prop].enum) { - objectConfigSet.add(prop, obj.properties[prop].enum); - } - if (obj.properties[prop].type && obj.properties[prop].type === "boolean") { - objectConfigSet.add(prop, [true, false]); - } - }); - objectConfigSet.combine(); - - if (objectConfigSet.objectConfigs.length > 0) { - this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, objectConfigSet.objectConfigs)); - return true; - } - - return false; - } -} - -/** - * Generate valid rule configurations based on a schema object - * @param {Object} schema A rule's schema object - * @returns {Array[]} Valid rule configurations - */ -function generateConfigsFromSchema(schema) { - const configSet = new RuleConfigSet(); - - if (Array.isArray(schema)) { - for (const opt of schema) { - if (opt.enum) { - configSet.addEnums(opt.enum); - } else if (opt.type && opt.type === "object") { - if (!configSet.addObject(opt)) { - break; - } - - // TODO (IanVS): support oneOf - } else { - - // If we don't know how to fill in this option, don't fill in any of the following options. - break; - } - } - } - configSet.addErrorSeverity(); - return configSet.ruleConfigs; -} - -/** - * Generate possible rule configurations for all of the core rules - * @param {boolean} noDeprecated Indicates whether ignores deprecated rules or not. - * @returns {rulesConfig} Hash of rule names and arrays of possible configurations - */ -function createCoreRuleConfigs(noDeprecated = false) { - return Array.from(builtInRules).reduce((accumulator, [id, rule]) => { - const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema; - const isDeprecated = (typeof rule === "function") ? rule.deprecated : rule.meta.deprecated; - - if (noDeprecated && isDeprecated) { - return accumulator; - } - - accumulator[id] = generateConfigsFromSchema(schema); - return accumulator; - }, {}); -} - - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - generateConfigsFromSchema, - createCoreRuleConfigs -}; diff --git a/tools/node_modules/eslint/lib/init/npm-utils.js b/tools/node_modules/eslint/lib/init/npm-utils.js deleted file mode 100644 index 555ea2b2b28cb269071630732d700bf5456f3afc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/init/npm-utils.js +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @fileoverview Utility for executing npm commands. - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const fs = require("fs"), - spawn = require("cross-spawn"), - path = require("path"), - log = require("../shared/logging"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Find the closest package.json file, starting at process.cwd (by default), - * and working up to root. - * @param {string} [startDir=process.cwd()] Starting directory - * @returns {string} Absolute path to closest package.json file - */ -function findPackageJson(startDir) { - let dir = path.resolve(startDir || process.cwd()); - - do { - const pkgFile = path.join(dir, "package.json"); - - if (!fs.existsSync(pkgFile) || !fs.statSync(pkgFile).isFile()) { - dir = path.join(dir, ".."); - continue; - } - return pkgFile; - } while (dir !== path.resolve(dir, "..")); - return null; -} - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Install node modules synchronously and save to devDependencies in package.json - * @param {string|string[]} packages Node module or modules to install - * @returns {void} - */ -function installSyncSaveDev(packages) { - const packageList = Array.isArray(packages) ? packages : [packages]; - const npmProcess = spawn.sync("npm", ["i", "--save-dev"].concat(packageList), - { stdio: "inherit" }); - const error = npmProcess.error; - - if (error && error.code === "ENOENT") { - const pluralS = packageList.length > 1 ? "s" : ""; - - log.error(`Could not execute npm. Please install the following package${pluralS} with a package manager of your choice: ${packageList.join(", ")}`); - } -} - -/** - * Fetch `peerDependencies` of the given package by `npm show` command. - * @param {string} packageName The package name to fetch peerDependencies. - * @returns {Object} Gotten peerDependencies. Returns null if npm was not found. - */ -function fetchPeerDependencies(packageName) { - const npmProcess = spawn.sync( - "npm", - ["show", "--json", packageName, "peerDependencies"], - { encoding: "utf8" } - ); - - const error = npmProcess.error; - - if (error && error.code === "ENOENT") { - return null; - } - const fetchedText = npmProcess.stdout.trim(); - - return JSON.parse(fetchedText || "{}"); - - -} - -/** - * Check whether node modules are include in a project's package.json. - * @param {string[]} packages Array of node module names - * @param {Object} opt Options Object - * @param {boolean} opt.dependencies Set to true to check for direct dependencies - * @param {boolean} opt.devDependencies Set to true to check for development dependencies - * @param {boolean} opt.startdir Directory to begin searching from - * @returns {Object} An object whose keys are the module names - * and values are booleans indicating installation. - */ -function check(packages, opt) { - const deps = new Set(); - const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson(); - let fileJson; - - if (!pkgJson) { - throw new Error("Could not find a package.json file. Run 'npm init' to create one."); - } - - try { - fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8")); - } catch (e) { - const error = new Error(e); - - error.messageTemplate = "failed-to-read-json"; - error.messageData = { - path: pkgJson, - message: e.message - }; - throw error; - } - - ["dependencies", "devDependencies"].forEach(key => { - if (opt[key] && typeof fileJson[key] === "object") { - Object.keys(fileJson[key]).forEach(dep => deps.add(dep)); - } - }); - - return packages.reduce((status, pkg) => { - status[pkg] = deps.has(pkg); - return status; - }, {}); -} - -/** - * Check whether node modules are included in the dependencies of a project's - * package.json. - * - * Convenience wrapper around check(). - * @param {string[]} packages Array of node modules to check. - * @param {string} rootDir The directory containing a package.json - * @returns {Object} An object whose keys are the module names - * and values are booleans indicating installation. - */ -function checkDeps(packages, rootDir) { - return check(packages, { dependencies: true, startDir: rootDir }); -} - -/** - * Check whether node modules are included in the devDependencies of a project's - * package.json. - * - * Convenience wrapper around check(). - * @param {string[]} packages Array of node modules to check. - * @returns {Object} An object whose keys are the module names - * and values are booleans indicating installation. - */ -function checkDevDeps(packages) { - return check(packages, { devDependencies: true }); -} - -/** - * Check whether package.json is found in current path. - * @param {string} [startDir] Starting directory - * @returns {boolean} Whether a package.json is found in current path. - */ -function checkPackageJson(startDir) { - return !!findPackageJson(startDir); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - installSyncSaveDev, - fetchPeerDependencies, - checkDeps, - checkDevDeps, - checkPackageJson -}; diff --git a/tools/node_modules/eslint/lib/init/source-code-utils.js b/tools/node_modules/eslint/lib/init/source-code-utils.js deleted file mode 100644 index dca6541d1ed32831791d172d1fdaa7769f6c1f76..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/init/source-code-utils.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * @fileoverview Tools for obtaining SourceCode objects. - * @author Ian VanSchooten - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { CLIEngine } = require("../cli-engine"); - -/* - * This is used for: - * - * 1. Enumerate target file because we have not expose such a API on `CLIEngine` - * (https://github.com/eslint/eslint/issues/11222). - * 2. Create `SourceCode` instances. Because we don't have any function which - * instantiate `SourceCode` so it needs to take the created `SourceCode` - * instance out after linting. - * - * TODO1: Expose the API that enumerates target files. - * TODO2: Extract the creation logic of `SourceCode` from `Linter` class. - */ -const { getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); // eslint-disable-line node/no-restricted-require - -const debug = require("debug")("eslint:source-code-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Get the SourceCode object for a single file - * @param {string} filename The fully resolved filename to get SourceCode from. - * @param {Object} engine A CLIEngine. - * @returns {Array} Array of the SourceCode object representing the file - * and fatal error message. - */ -function getSourceCodeOfFile(filename, engine) { - debug("getting sourceCode of", filename); - const results = engine.executeOnFiles([filename]); - - if (results && results.results[0] && results.results[0].messages[0] && results.results[0].messages[0].fatal) { - const msg = results.results[0].messages[0]; - - throw new Error(`(${filename}:${msg.line}:${msg.column}) ${msg.message}`); - } - - // TODO: extract the logic that creates source code objects to `SourceCode#parse(text, options)` or something like. - const { linter } = getCLIEngineInternalSlots(engine); - const sourceCode = linter.getSourceCode(); - - return sourceCode; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - - -/** - * This callback is used to measure execution status in a progress bar - * @callback progressCallback - * @param {number} The total number of times the callback will be called. - */ - -/** - * Gets the SourceCode of a single file, or set of files. - * @param {string[]|string} patterns A filename, directory name, or glob, or an array of them - * @param {Object} options A CLIEngine options object. If not provided, the default cli options will be used. - * @param {progressCallback} callback Callback for reporting execution status - * @returns {Object} The SourceCode of all processed files. - */ -function getSourceCodeOfFiles(patterns, options, callback) { - const sourceCodes = {}; - const globPatternsList = typeof patterns === "string" ? [patterns] : patterns; - const engine = new CLIEngine({ ...options, rules: {} }); - - // TODO: make file iteration as a public API and use it. - const { fileEnumerator } = getCLIEngineInternalSlots(engine); - const filenames = - Array.from(fileEnumerator.iterateFiles(globPatternsList)) - .filter(entry => !entry.ignored) - .map(entry => entry.filePath); - - if (filenames.length === 0) { - debug(`Did not find any files matching pattern(s): ${globPatternsList}`); - } - - filenames.forEach(filename => { - const sourceCode = getSourceCodeOfFile(filename, engine); - - if (sourceCode) { - debug("got sourceCode of", filename); - sourceCodes[filename] = sourceCode; - } - if (callback) { - callback(filenames.length); // eslint-disable-line node/callback-return - } - }); - - return sourceCodes; -} - -module.exports = { - getSourceCodeOfFiles -}; diff --git a/tools/node_modules/eslint/lib/linter/apply-disable-directives.js b/tools/node_modules/eslint/lib/linter/apply-disable-directives.js deleted file mode 100644 index 41d6934abba46d41466e6fc81f41d72b8510ef66..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/apply-disable-directives.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments - * @author Teddy Katz - */ - -"use strict"; - -const lodash = require("lodash"); - -/** - * Compares the locations of two objects in a source file - * @param {{line: number, column: number}} itemA The first object - * @param {{line: number, column: number}} itemB The second object - * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if - * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location. - */ -function compareLocations(itemA, itemB) { - return itemA.line - itemB.line || itemA.column - itemB.column; -} - -/** - * This is the same as the exported function, except that it - * doesn't handle disable-line and disable-next-line directives, and it always reports unused - * disable directives. - * @param {Object} options options for applying directives. This is the same as the options - * for the exported function, except that `reportUnusedDisableDirectives` is not supported - * (this function always reports unused disable directives). - * @returns {{problems: Problem[], unusedDisableDirectives: Problem[]}} An object with a list - * of filtered problems and unused eslint-disable directives - */ -function applyDirectives(options) { - const problems = []; - let nextDirectiveIndex = 0; - let currentGlobalDisableDirective = null; - const disabledRuleMap = new Map(); - - // enabledRules is only used when there is a current global disable directive. - const enabledRules = new Set(); - const usedDisableDirectives = new Set(); - - for (const problem of options.problems) { - while ( - nextDirectiveIndex < options.directives.length && - compareLocations(options.directives[nextDirectiveIndex], problem) <= 0 - ) { - const directive = options.directives[nextDirectiveIndex++]; - - switch (directive.type) { - case "disable": - if (directive.ruleId === null) { - currentGlobalDisableDirective = directive; - disabledRuleMap.clear(); - enabledRules.clear(); - } else if (currentGlobalDisableDirective) { - enabledRules.delete(directive.ruleId); - disabledRuleMap.set(directive.ruleId, directive); - } else { - disabledRuleMap.set(directive.ruleId, directive); - } - break; - - case "enable": - if (directive.ruleId === null) { - currentGlobalDisableDirective = null; - disabledRuleMap.clear(); - } else if (currentGlobalDisableDirective) { - enabledRules.add(directive.ruleId); - disabledRuleMap.delete(directive.ruleId); - } else { - disabledRuleMap.delete(directive.ruleId); - } - break; - - // no default - } - } - - if (disabledRuleMap.has(problem.ruleId)) { - usedDisableDirectives.add(disabledRuleMap.get(problem.ruleId)); - } else if (currentGlobalDisableDirective && !enabledRules.has(problem.ruleId)) { - usedDisableDirectives.add(currentGlobalDisableDirective); - } else { - problems.push(problem); - } - } - - const unusedDisableDirectives = options.directives - .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive)) - .map(directive => ({ - ruleId: null, - message: directive.ruleId - ? `Unused eslint-disable directive (no problems were reported from '${directive.ruleId}').` - : "Unused eslint-disable directive (no problems were reported).", - line: directive.unprocessedDirective.line, - column: directive.unprocessedDirective.column, - severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2, - nodeType: null - })); - - return { problems, unusedDisableDirectives }; -} - -/** - * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list - * of reported problems, determines which problems should be reported. - * @param {Object} options Information about directives and problems - * @param {{ - * type: ("disable"|"enable"|"disable-line"|"disable-next-line"), - * ruleId: (string|null), - * line: number, - * column: number - * }} options.directives Directive comments found in the file, with one-based columns. - * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable - * comment for two different rules is represented as two directives). - * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems - * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns. - * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives - * @returns {{ruleId: (string|null), line: number, column: number}[]} - * A list of reported problems that were not disabled by the directive comments. - */ -module.exports = ({ directives, problems, reportUnusedDisableDirectives = "off" }) => { - const blockDirectives = directives - .filter(directive => directive.type === "disable" || directive.type === "enable") - .map(directive => Object.assign({}, directive, { unprocessedDirective: directive })) - .sort(compareLocations); - - const lineDirectives = lodash.flatMap(directives, directive => { - switch (directive.type) { - case "disable": - case "enable": - return []; - - case "disable-line": - return [ - { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive }, - { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive } - ]; - - case "disable-next-line": - return [ - { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive }, - { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive } - ]; - - default: - throw new TypeError(`Unrecognized directive type '${directive.type}'`); - } - }).sort(compareLocations); - - const blockDirectivesResult = applyDirectives({ - problems, - directives: blockDirectives, - reportUnusedDisableDirectives - }); - const lineDirectivesResult = applyDirectives({ - problems: blockDirectivesResult.problems, - directives: lineDirectives, - reportUnusedDisableDirectives - }); - - return reportUnusedDisableDirectives !== "off" - ? lineDirectivesResult.problems - .concat(blockDirectivesResult.unusedDisableDirectives) - .concat(lineDirectivesResult.unusedDisableDirectives) - .sort(compareLocations) - : lineDirectivesResult.problems; -}; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js deleted file mode 100644 index 47427c11a3d2500d458ddeaf0830a8d9c62b64b8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js +++ /dev/null @@ -1,760 +0,0 @@ -/** - * @fileoverview A class of the code path analyzer. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"), - { breakableTypePattern } = require("../../shared/ast-utils"), - CodePath = require("./code-path"), - CodePathSegment = require("./code-path-segment"), - IdGenerator = require("./id-generator"), - debug = require("./debug-helpers"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a `case` node (not `default` node). - * @param {ASTNode} node A `SwitchCase` node to check. - * @returns {boolean} `true` if the node is a `case` node (not `default` node). - */ -function isCaseNode(node) { - return Boolean(node.test); -} - -/** - * Checks whether the given logical operator is taken into account for the code - * path analysis. - * @param {string} operator The operator found in the LogicalExpression node - * @returns {boolean} `true` if the operator is "&&" or "||" or "??" - */ -function isHandledLogicalOperator(operator) { - return operator === "&&" || operator === "||" || operator === "??"; -} - -/** - * Checks whether the given assignment operator is a logical assignment operator. - * Logical assignments are taken into account for the code path analysis - * because of their short-circuiting semantics. - * @param {string} operator The operator found in the AssignmentExpression node - * @returns {boolean} `true` if the operator is "&&=" or "||=" or "??=" - */ -function isLogicalAssignmentOperator(operator) { - return operator === "&&=" || operator === "||=" || operator === "??="; -} - -/** - * Gets the label if the parent node of a given node is a LabeledStatement. - * @param {ASTNode} node A node to get. - * @returns {string|null} The label or `null`. - */ -function getLabel(node) { - if (node.parent.type === "LabeledStatement") { - return node.parent.label.name; - } - return null; -} - -/** - * Checks whether or not a given logical expression node goes different path - * between the `true` case and the `false` case. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a test of a choice statement. - */ -function isForkingByTrueOrFalse(node) { - const parent = node.parent; - - switch (parent.type) { - case "ConditionalExpression": - case "IfStatement": - case "WhileStatement": - case "DoWhileStatement": - case "ForStatement": - return parent.test === node; - - case "LogicalExpression": - return isHandledLogicalOperator(parent.operator); - - case "AssignmentExpression": - return isLogicalAssignmentOperator(parent.operator); - - default: - return false; - } -} - -/** - * Gets the boolean value of a given literal node. - * - * This is used to detect infinity loops (e.g. `while (true) {}`). - * Statements preceded by an infinity loop are unreachable if the loop didn't - * have any `break` statement. - * @param {ASTNode} node A node to get. - * @returns {boolean|undefined} a boolean value if the node is a Literal node, - * otherwise `undefined`. - */ -function getBooleanValueIfSimpleConstant(node) { - if (node.type === "Literal") { - return Boolean(node.value); - } - return void 0; -} - -/** - * Checks that a given identifier node is a reference or not. - * - * This is used to detect the first throwable node in a `try` block. - * @param {ASTNode} node An Identifier node to check. - * @returns {boolean} `true` if the node is a reference. - */ -function isIdentifierReference(node) { - const parent = node.parent; - - switch (parent.type) { - case "LabeledStatement": - case "BreakStatement": - case "ContinueStatement": - case "ArrayPattern": - case "RestElement": - case "ImportSpecifier": - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "CatchClause": - return false; - - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "ClassDeclaration": - case "ClassExpression": - case "VariableDeclarator": - return parent.id !== node; - - case "Property": - case "MethodDefinition": - return ( - parent.key !== node || - parent.computed || - parent.shorthand - ); - - case "AssignmentPattern": - return parent.key !== node; - - default: - return true; - } -} - -/** - * Updates the current segment with the head segment. - * This is similar to local branches and tracking branches of git. - * - * To separate the current and the head is in order to not make useless segments. - * - * In this process, both "onCodePathSegmentStart" and "onCodePathSegmentEnd" - * events are fired. - * @param {CodePathAnalyzer} analyzer The instance. - * @param {ASTNode} node The current AST node. - * @returns {void} - */ -function forwardCurrentToHead(analyzer, node) { - const codePath = analyzer.codePath; - const state = CodePath.getState(codePath); - const currentSegments = state.currentSegments; - const headSegments = state.headSegments; - const end = Math.max(currentSegments.length, headSegments.length); - let i, currentSegment, headSegment; - - // Fires leaving events. - for (i = 0; i < end; ++i) { - currentSegment = currentSegments[i]; - headSegment = headSegments[i]; - - if (currentSegment !== headSegment && currentSegment) { - debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); - - if (currentSegment.reachable) { - analyzer.emitter.emit( - "onCodePathSegmentEnd", - currentSegment, - node - ); - } - } - } - - // Update state. - state.currentSegments = headSegments; - - // Fires entering events. - for (i = 0; i < end; ++i) { - currentSegment = currentSegments[i]; - headSegment = headSegments[i]; - - if (currentSegment !== headSegment && headSegment) { - debug.dump(`onCodePathSegmentStart ${headSegment.id}`); - - CodePathSegment.markUsed(headSegment); - if (headSegment.reachable) { - analyzer.emitter.emit( - "onCodePathSegmentStart", - headSegment, - node - ); - } - } - } - -} - -/** - * Updates the current segment with empty. - * This is called at the last of functions or the program. - * @param {CodePathAnalyzer} analyzer The instance. - * @param {ASTNode} node The current AST node. - * @returns {void} - */ -function leaveFromCurrentSegment(analyzer, node) { - const state = CodePath.getState(analyzer.codePath); - const currentSegments = state.currentSegments; - - for (let i = 0; i < currentSegments.length; ++i) { - const currentSegment = currentSegments[i]; - - debug.dump(`onCodePathSegmentEnd ${currentSegment.id}`); - if (currentSegment.reachable) { - analyzer.emitter.emit( - "onCodePathSegmentEnd", - currentSegment, - node - ); - } - } - - state.currentSegments = []; -} - -/** - * Updates the code path due to the position of a given node in the parent node - * thereof. - * - * For example, if the node is `parent.consequent`, this creates a fork from the - * current path. - * @param {CodePathAnalyzer} analyzer The instance. - * @param {ASTNode} node The current AST node. - * @returns {void} - */ -function preprocess(analyzer, node) { - const codePath = analyzer.codePath; - const state = CodePath.getState(codePath); - const parent = node.parent; - - switch (parent.type) { - - // The `arguments.length == 0` case is in `postprocess` function. - case "CallExpression": - if (parent.optional === true && parent.arguments.length >= 1 && parent.arguments[0] === node) { - state.makeOptionalRight(); - } - break; - case "MemberExpression": - if (parent.optional === true && parent.property === node) { - state.makeOptionalRight(); - } - break; - - case "LogicalExpression": - if ( - parent.right === node && - isHandledLogicalOperator(parent.operator) - ) { - state.makeLogicalRight(); - } - break; - - case "AssignmentExpression": - if ( - parent.right === node && - isLogicalAssignmentOperator(parent.operator) - ) { - state.makeLogicalRight(); - } - break; - - case "ConditionalExpression": - case "IfStatement": - - /* - * Fork if this node is at `consequent`/`alternate`. - * `popForkContext()` exists at `IfStatement:exit` and - * `ConditionalExpression:exit`. - */ - if (parent.consequent === node) { - state.makeIfConsequent(); - } else if (parent.alternate === node) { - state.makeIfAlternate(); - } - break; - - case "SwitchCase": - if (parent.consequent[0] === node) { - state.makeSwitchCaseBody(false, !parent.test); - } - break; - - case "TryStatement": - if (parent.handler === node) { - state.makeCatchBlock(); - } else if (parent.finalizer === node) { - state.makeFinallyBlock(); - } - break; - - case "WhileStatement": - if (parent.test === node) { - state.makeWhileTest(getBooleanValueIfSimpleConstant(node)); - } else { - assert(parent.body === node); - state.makeWhileBody(); - } - break; - - case "DoWhileStatement": - if (parent.body === node) { - state.makeDoWhileBody(); - } else { - assert(parent.test === node); - state.makeDoWhileTest(getBooleanValueIfSimpleConstant(node)); - } - break; - - case "ForStatement": - if (parent.test === node) { - state.makeForTest(getBooleanValueIfSimpleConstant(node)); - } else if (parent.update === node) { - state.makeForUpdate(); - } else if (parent.body === node) { - state.makeForBody(); - } - break; - - case "ForInStatement": - case "ForOfStatement": - if (parent.left === node) { - state.makeForInOfLeft(); - } else if (parent.right === node) { - state.makeForInOfRight(); - } else { - assert(parent.body === node); - state.makeForInOfBody(); - } - break; - - case "AssignmentPattern": - - /* - * Fork if this node is at `right`. - * `left` is executed always, so it uses the current path. - * `popForkContext()` exists at `AssignmentPattern:exit`. - */ - if (parent.right === node) { - state.pushForkContext(); - state.forkBypassPath(); - state.forkPath(); - } - break; - - default: - break; - } -} - -/** - * Updates the code path due to the type of a given node in entering. - * @param {CodePathAnalyzer} analyzer The instance. - * @param {ASTNode} node The current AST node. - * @returns {void} - */ -function processCodePathToEnter(analyzer, node) { - let codePath = analyzer.codePath; - let state = codePath && CodePath.getState(codePath); - const parent = node.parent; - - switch (node.type) { - case "Program": - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - if (codePath) { - - // Emits onCodePathSegmentStart events if updated. - forwardCurrentToHead(analyzer, node); - debug.dumpState(node, state, false); - } - - // Create the code path of this scope. - codePath = analyzer.codePath = new CodePath( - analyzer.idGenerator.next(), - codePath, - analyzer.onLooped - ); - state = CodePath.getState(codePath); - - // Emits onCodePathStart events. - debug.dump(`onCodePathStart ${codePath.id}`); - analyzer.emitter.emit("onCodePathStart", codePath, node); - break; - - case "ChainExpression": - state.pushChainContext(); - break; - case "CallExpression": - if (node.optional === true) { - state.makeOptionalNode(); - } - break; - case "MemberExpression": - if (node.optional === true) { - state.makeOptionalNode(); - } - break; - - case "LogicalExpression": - if (isHandledLogicalOperator(node.operator)) { - state.pushChoiceContext( - node.operator, - isForkingByTrueOrFalse(node) - ); - } - break; - - case "AssignmentExpression": - if (isLogicalAssignmentOperator(node.operator)) { - state.pushChoiceContext( - node.operator.slice(0, -1), // removes `=` from the end - isForkingByTrueOrFalse(node) - ); - } - break; - - case "ConditionalExpression": - case "IfStatement": - state.pushChoiceContext("test", false); - break; - - case "SwitchStatement": - state.pushSwitchContext( - node.cases.some(isCaseNode), - getLabel(node) - ); - break; - - case "TryStatement": - state.pushTryContext(Boolean(node.finalizer)); - break; - - case "SwitchCase": - - /* - * Fork if this node is after the 2st node in `cases`. - * It's similar to `else` blocks. - * The next `test` node is processed in this path. - */ - if (parent.discriminant !== node && parent.cases[0] !== node) { - state.forkPath(); - } - break; - - case "WhileStatement": - case "DoWhileStatement": - case "ForStatement": - case "ForInStatement": - case "ForOfStatement": - state.pushLoopContext(node.type, getLabel(node)); - break; - - case "LabeledStatement": - if (!breakableTypePattern.test(node.body.type)) { - state.pushBreakContext(false, node.label.name); - } - break; - - default: - break; - } - - // Emits onCodePathSegmentStart events if updated. - forwardCurrentToHead(analyzer, node); - debug.dumpState(node, state, false); -} - -/** - * Updates the code path due to the type of a given node in leaving. - * @param {CodePathAnalyzer} analyzer The instance. - * @param {ASTNode} node The current AST node. - * @returns {void} - */ -function processCodePathToExit(analyzer, node) { - const codePath = analyzer.codePath; - const state = CodePath.getState(codePath); - let dontForward = false; - - switch (node.type) { - case "ChainExpression": - state.popChainContext(); - break; - - case "IfStatement": - case "ConditionalExpression": - state.popChoiceContext(); - break; - - case "LogicalExpression": - if (isHandledLogicalOperator(node.operator)) { - state.popChoiceContext(); - } - break; - - case "AssignmentExpression": - if (isLogicalAssignmentOperator(node.operator)) { - state.popChoiceContext(); - } - break; - - case "SwitchStatement": - state.popSwitchContext(); - break; - - case "SwitchCase": - - /* - * This is the same as the process at the 1st `consequent` node in - * `preprocess` function. - * Must do if this `consequent` is empty. - */ - if (node.consequent.length === 0) { - state.makeSwitchCaseBody(true, !node.test); - } - if (state.forkContext.reachable) { - dontForward = true; - } - break; - - case "TryStatement": - state.popTryContext(); - break; - - case "BreakStatement": - forwardCurrentToHead(analyzer, node); - state.makeBreak(node.label && node.label.name); - dontForward = true; - break; - - case "ContinueStatement": - forwardCurrentToHead(analyzer, node); - state.makeContinue(node.label && node.label.name); - dontForward = true; - break; - - case "ReturnStatement": - forwardCurrentToHead(analyzer, node); - state.makeReturn(); - dontForward = true; - break; - - case "ThrowStatement": - forwardCurrentToHead(analyzer, node); - state.makeThrow(); - dontForward = true; - break; - - case "Identifier": - if (isIdentifierReference(node)) { - state.makeFirstThrowablePathInTryBlock(); - dontForward = true; - } - break; - - case "CallExpression": - case "ImportExpression": - case "MemberExpression": - case "NewExpression": - case "YieldExpression": - state.makeFirstThrowablePathInTryBlock(); - break; - - case "WhileStatement": - case "DoWhileStatement": - case "ForStatement": - case "ForInStatement": - case "ForOfStatement": - state.popLoopContext(); - break; - - case "AssignmentPattern": - state.popForkContext(); - break; - - case "LabeledStatement": - if (!breakableTypePattern.test(node.body.type)) { - state.popBreakContext(); - } - break; - - default: - break; - } - - // Emits onCodePathSegmentStart events if updated. - if (!dontForward) { - forwardCurrentToHead(analyzer, node); - } - debug.dumpState(node, state, true); -} - -/** - * Updates the code path to finalize the current code path. - * @param {CodePathAnalyzer} analyzer The instance. - * @param {ASTNode} node The current AST node. - * @returns {void} - */ -function postprocess(analyzer, node) { - switch (node.type) { - case "Program": - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": { - let codePath = analyzer.codePath; - - // Mark the current path as the final node. - CodePath.getState(codePath).makeFinal(); - - // Emits onCodePathSegmentEnd event of the current segments. - leaveFromCurrentSegment(analyzer, node); - - // Emits onCodePathEnd event of this code path. - debug.dump(`onCodePathEnd ${codePath.id}`); - analyzer.emitter.emit("onCodePathEnd", codePath, node); - debug.dumpDot(codePath); - - codePath = analyzer.codePath = analyzer.codePath.upper; - if (codePath) { - debug.dumpState(node, CodePath.getState(codePath), true); - } - break; - } - - // The `arguments.length >= 1` case is in `preprocess` function. - case "CallExpression": - if (node.optional === true && node.arguments.length === 0) { - CodePath.getState(analyzer.codePath).makeOptionalRight(); - } - break; - - default: - break; - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * The class to analyze code paths. - * This class implements the EventGenerator interface. - */ -class CodePathAnalyzer { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {EventGenerator} eventGenerator An event generator to wrap. - */ - constructor(eventGenerator) { - this.original = eventGenerator; - this.emitter = eventGenerator.emitter; - this.codePath = null; - this.idGenerator = new IdGenerator("s"); - this.currentNode = null; - this.onLooped = this.onLooped.bind(this); - } - - /** - * Does the process to enter a given AST node. - * This updates state of analysis and calls `enterNode` of the wrapped. - * @param {ASTNode} node A node which is entering. - * @returns {void} - */ - enterNode(node) { - this.currentNode = node; - - // Updates the code path due to node's position in its parent node. - if (node.parent) { - preprocess(this, node); - } - - /* - * Updates the code path. - * And emits onCodePathStart/onCodePathSegmentStart events. - */ - processCodePathToEnter(this, node); - - // Emits node events. - this.original.enterNode(node); - - this.currentNode = null; - } - - /** - * Does the process to leave a given AST node. - * This updates state of analysis and calls `leaveNode` of the wrapped. - * @param {ASTNode} node A node which is leaving. - * @returns {void} - */ - leaveNode(node) { - this.currentNode = node; - - /* - * Updates the code path. - * And emits onCodePathStart/onCodePathSegmentStart events. - */ - processCodePathToExit(this, node); - - // Emits node events. - this.original.leaveNode(node); - - // Emits the last onCodePathStart/onCodePathSegmentStart events. - postprocess(this, node); - - this.currentNode = null; - } - - /** - * This is called on a code path looped. - * Then this raises a looped event. - * @param {CodePathSegment} fromSegment A segment of prev. - * @param {CodePathSegment} toSegment A segment of next. - * @returns {void} - */ - onLooped(fromSegment, toSegment) { - if (fromSegment.reachable && toSegment.reachable) { - debug.dump(`onCodePathSegmentLoop ${fromSegment.id} -> ${toSegment.id}`); - this.emitter.emit( - "onCodePathSegmentLoop", - fromSegment, - toSegment, - this.currentNode - ); - } - } -} - -module.exports = CodePathAnalyzer; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js deleted file mode 100644 index ca96ad34189acc042504e90b46189f67efda4faf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-segment.js +++ /dev/null @@ -1,236 +0,0 @@ -/** - * @fileoverview A class of the code path segment. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("./debug-helpers"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given segment is reachable. - * @param {CodePathSegment} segment A segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A code path segment. - */ -class CodePathSegment { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} id An identifier. - * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. - * This array includes unreachable segments. - * @param {boolean} reachable A flag which shows this is reachable. - */ - constructor(id, allPrevSegments, reachable) { - - /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} - */ - this.id = id; - - /** - * An array of the next segments. - * @type {CodePathSegment[]} - */ - this.nextSegments = []; - - /** - * An array of the previous segments. - * @type {CodePathSegment[]} - */ - this.prevSegments = allPrevSegments.filter(isReachable); - - /** - * An array of the next segments. - * This array includes unreachable segments. - * @type {CodePathSegment[]} - */ - this.allNextSegments = []; - - /** - * An array of the previous segments. - * This array includes unreachable segments. - * @type {CodePathSegment[]} - */ - this.allPrevSegments = allPrevSegments; - - /** - * A flag which shows this is reachable. - * @type {boolean} - */ - this.reachable = reachable; - - // Internal data. - Object.defineProperty(this, "internal", { - value: { - used: false, - loopedPrevSegments: [] - } - }); - - /* istanbul ignore if */ - if (debug.enabled) { - this.internal.nodes = []; - } - } - - /** - * Checks a given previous segment is coming from the end of a loop. - * @param {CodePathSegment} segment A previous segment to check. - * @returns {boolean} `true` if the segment is coming from the end of a loop. - */ - isLoopedPrevSegment(segment) { - return this.internal.loopedPrevSegments.indexOf(segment) !== -1; - } - - /** - * Creates the root segment. - * @param {string} id An identifier. - * @returns {CodePathSegment} The created segment. - */ - static newRoot(id) { - return new CodePathSegment(id, [], true); - } - - /** - * Creates a segment that follows given segments. - * @param {string} id An identifier. - * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ - static newNext(id, allPrevSegments) { - return new CodePathSegment( - id, - CodePathSegment.flattenUnusedSegments(allPrevSegments), - allPrevSegments.some(isReachable) - ); - } - - /** - * Creates an unreachable segment that follows given segments. - * @param {string} id An identifier. - * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ - static newUnreachable(id, allPrevSegments) { - const segment = new CodePathSegment(id, CodePathSegment.flattenUnusedSegments(allPrevSegments), false); - - /* - * In `if (a) return a; foo();` case, the unreachable segment preceded by - * the return statement is not used but must not be remove. - */ - CodePathSegment.markUsed(segment); - - return segment; - } - - /** - * Creates a segment that follows given segments. - * This factory method does not connect with `allPrevSegments`. - * But this inherits `reachable` flag. - * @param {string} id An identifier. - * @param {CodePathSegment[]} allPrevSegments An array of the previous segments. - * @returns {CodePathSegment} The created segment. - */ - static newDisconnected(id, allPrevSegments) { - return new CodePathSegment(id, [], allPrevSegments.some(isReachable)); - } - - /** - * Makes a given segment being used. - * - * And this function registers the segment into the previous segments as a next. - * @param {CodePathSegment} segment A segment to mark. - * @returns {void} - */ - static markUsed(segment) { - if (segment.internal.used) { - return; - } - segment.internal.used = true; - - let i; - - if (segment.reachable) { - for (i = 0; i < segment.allPrevSegments.length; ++i) { - const prevSegment = segment.allPrevSegments[i]; - - prevSegment.allNextSegments.push(segment); - prevSegment.nextSegments.push(segment); - } - } else { - for (i = 0; i < segment.allPrevSegments.length; ++i) { - segment.allPrevSegments[i].allNextSegments.push(segment); - } - } - } - - /** - * Marks a previous segment as looped. - * @param {CodePathSegment} segment A segment. - * @param {CodePathSegment} prevSegment A previous segment to mark. - * @returns {void} - */ - static markPrevSegmentAsLooped(segment, prevSegment) { - segment.internal.loopedPrevSegments.push(prevSegment); - } - - /** - * Replaces unused segments with the previous segments of each unused segment. - * @param {CodePathSegment[]} segments An array of segments to replace. - * @returns {CodePathSegment[]} The replaced array. - */ - static flattenUnusedSegments(segments) { - const done = Object.create(null); - const retv = []; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - // Ignores duplicated. - if (done[segment.id]) { - continue; - } - - // Use previous segments if unused. - if (!segment.internal.used) { - for (let j = 0; j < segment.allPrevSegments.length; ++j) { - const prevSegment = segment.allPrevSegments[j]; - - if (!done[prevSegment.id]) { - done[prevSegment.id] = true; - retv.push(prevSegment); - } - } - } else { - done[segment.id] = true; - retv.push(segment); - } - } - - return retv; - } -} - -module.exports = CodePathSegment; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js deleted file mode 100644 index f75e60e28a807e40ad1e0cc31ed85c1bd1f85d59..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path-state.js +++ /dev/null @@ -1,1480 +0,0 @@ -/** - * @fileoverview A class to manage state of generating a code path. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const CodePathSegment = require("./code-path-segment"), - ForkContext = require("./fork-context"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Adds given segments into the `dest` array. - * If the `others` array does not includes the given segments, adds to the `all` - * array as well. - * - * This adds only reachable and used segments. - * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`). - * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`). - * @param {CodePathSegment[]} all The unified destination array (`finalSegments`). - * @param {CodePathSegment[]} segments Segments to add. - * @returns {void} - */ -function addToReturnedOrThrown(dest, others, all, segments) { - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - dest.push(segment); - if (others.indexOf(segment) === -1) { - all.push(segment); - } - } -} - -/** - * Gets a loop-context for a `continue` statement. - * @param {CodePathState} state A state to get. - * @param {string} label The label of a `continue` statement. - * @returns {LoopContext} A loop-context for a `continue` statement. - */ -function getContinueContext(state, label) { - if (!label) { - return state.loopContext; - } - - let context = state.loopContext; - - while (context) { - if (context.label === label) { - return context; - } - context = context.upper; - } - - /* istanbul ignore next: foolproof (syntax error) */ - return null; -} - -/** - * Gets a context for a `break` statement. - * @param {CodePathState} state A state to get. - * @param {string} label The label of a `break` statement. - * @returns {LoopContext|SwitchContext} A context for a `break` statement. - */ -function getBreakContext(state, label) { - let context = state.breakContext; - - while (context) { - if (label ? context.label === label : context.breakable) { - return context; - } - context = context.upper; - } - - /* istanbul ignore next: foolproof (syntax error) */ - return null; -} - -/** - * Gets a context for a `return` statement. - * @param {CodePathState} state A state to get. - * @returns {TryContext|CodePathState} A context for a `return` statement. - */ -function getReturnContext(state) { - let context = state.tryContext; - - while (context) { - if (context.hasFinalizer && context.position !== "finally") { - return context; - } - context = context.upper; - } - - return state; -} - -/** - * Gets a context for a `throw` statement. - * @param {CodePathState} state A state to get. - * @returns {TryContext|CodePathState} A context for a `throw` statement. - */ -function getThrowContext(state) { - let context = state.tryContext; - - while (context) { - if (context.position === "try" || - (context.hasFinalizer && context.position === "catch") - ) { - return context; - } - context = context.upper; - } - - return state; -} - -/** - * Removes a given element from a given array. - * @param {any[]} xs An array to remove the specific element. - * @param {any} x An element to be removed. - * @returns {void} - */ -function remove(xs, x) { - xs.splice(xs.indexOf(x), 1); -} - -/** - * Disconnect given segments. - * - * This is used in a process for switch statements. - * If there is the "default" chunk before other cases, the order is different - * between node's and running's. - * @param {CodePathSegment[]} prevSegments Forward segments to disconnect. - * @param {CodePathSegment[]} nextSegments Backward segments to disconnect. - * @returns {void} - */ -function removeConnection(prevSegments, nextSegments) { - for (let i = 0; i < prevSegments.length; ++i) { - const prevSegment = prevSegments[i]; - const nextSegment = nextSegments[i]; - - remove(prevSegment.nextSegments, nextSegment); - remove(prevSegment.allNextSegments, nextSegment); - remove(nextSegment.prevSegments, prevSegment); - remove(nextSegment.allPrevSegments, prevSegment); - } -} - -/** - * Creates looping path. - * @param {CodePathState} state The instance. - * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source. - * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination. - * @returns {void} - */ -function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) { - const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments); - const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments); - - const end = Math.min(fromSegments.length, toSegments.length); - - for (let i = 0; i < end; ++i) { - const fromSegment = fromSegments[i]; - const toSegment = toSegments[i]; - - if (toSegment.reachable) { - fromSegment.nextSegments.push(toSegment); - } - if (fromSegment.reachable) { - toSegment.prevSegments.push(fromSegment); - } - fromSegment.allNextSegments.push(toSegment); - toSegment.allPrevSegments.push(fromSegment); - - if (toSegment.allPrevSegments.length >= 2) { - CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment); - } - - state.notifyLooped(fromSegment, toSegment); - } -} - -/** - * Finalizes segments of `test` chunk of a ForStatement. - * - * - Adds `false` paths to paths which are leaving from the loop. - * - Sets `true` paths to paths which go to the body. - * @param {LoopContext} context A loop context to modify. - * @param {ChoiceContext} choiceContext A choice context of this loop. - * @param {CodePathSegment[]} head The current head paths. - * @returns {void} - */ -function finalizeTestSegmentsOfFor(context, choiceContext, head) { - if (!choiceContext.processed) { - choiceContext.trueForkContext.add(head); - choiceContext.falseForkContext.add(head); - choiceContext.qqForkContext.add(head); - } - - if (context.test !== true) { - context.brokenForkContext.addAll(choiceContext.falseForkContext); - } - context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A class which manages state to analyze code paths. - */ -class CodePathState { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {IdGenerator} idGenerator An id generator to generate id for code - * path segments. - * @param {Function} onLooped A callback function to notify looping. - */ - constructor(idGenerator, onLooped) { - this.idGenerator = idGenerator; - this.notifyLooped = onLooped; - this.forkContext = ForkContext.newRoot(idGenerator); - this.choiceContext = null; - this.switchContext = null; - this.tryContext = null; - this.loopContext = null; - this.breakContext = null; - this.chainContext = null; - - this.currentSegments = []; - this.initialSegment = this.forkContext.head[0]; - - // returnedSegments and thrownSegments push elements into finalSegments also. - const final = this.finalSegments = []; - const returned = this.returnedForkContext = []; - const thrown = this.thrownForkContext = []; - - returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final); - thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final); - } - - /** - * The head segments. - * @type {CodePathSegment[]} - */ - get headSegments() { - return this.forkContext.head; - } - - /** - * The parent forking context. - * This is used for the root of new forks. - * @type {ForkContext} - */ - get parentForkContext() { - const current = this.forkContext; - - return current && current.upper; - } - - /** - * Creates and stacks new forking context. - * @param {boolean} forkLeavingPath A flag which shows being in a - * "finally" block. - * @returns {ForkContext} The created context. - */ - pushForkContext(forkLeavingPath) { - this.forkContext = ForkContext.newEmpty( - this.forkContext, - forkLeavingPath - ); - - return this.forkContext; - } - - /** - * Pops and merges the last forking context. - * @returns {ForkContext} The last context. - */ - popForkContext() { - const lastContext = this.forkContext; - - this.forkContext = lastContext.upper; - this.forkContext.replaceHead(lastContext.makeNext(0, -1)); - - return lastContext; - } - - /** - * Creates a new path. - * @returns {void} - */ - forkPath() { - this.forkContext.add(this.parentForkContext.makeNext(-1, -1)); - } - - /** - * Creates a bypass path. - * This is used for such as IfStatement which does not have "else" chunk. - * @returns {void} - */ - forkBypassPath() { - this.forkContext.add(this.parentForkContext.head); - } - - //-------------------------------------------------------------------------- - // ConditionalExpression, LogicalExpression, IfStatement - //-------------------------------------------------------------------------- - - /** - * Creates a context for ConditionalExpression, LogicalExpression, AssignmentExpression (logical assignments only), - * IfStatement, WhileStatement, DoWhileStatement, or ForStatement. - * - * LogicalExpressions have cases that it goes different paths between the - * `true` case and the `false` case. - * - * For Example: - * - * if (a || b) { - * foo(); - * } else { - * bar(); - * } - * - * In this case, `b` is evaluated always in the code path of the `else` - * block, but it's not so in the code path of the `if` block. - * So there are 3 paths. - * - * a -> foo(); - * a -> b -> foo(); - * a -> b -> bar(); - * @param {string} kind A kind string. - * If the new context is LogicalExpression's or AssignmentExpression's, this is `"&&"` or `"||"` or `"??"`. - * If it's IfStatement's or ConditionalExpression's, this is `"test"`. - * Otherwise, this is `"loop"`. - * @param {boolean} isForkingAsResult A flag that shows that goes different - * paths between `true` and `false`. - * @returns {void} - */ - pushChoiceContext(kind, isForkingAsResult) { - this.choiceContext = { - upper: this.choiceContext, - kind, - isForkingAsResult, - trueForkContext: ForkContext.newEmpty(this.forkContext), - falseForkContext: ForkContext.newEmpty(this.forkContext), - qqForkContext: ForkContext.newEmpty(this.forkContext), - processed: false - }; - } - - /** - * Pops the last choice context and finalizes it. - * @returns {ChoiceContext} The popped context. - */ - popChoiceContext() { - const context = this.choiceContext; - - this.choiceContext = context.upper; - - const forkContext = this.forkContext; - const headSegments = forkContext.head; - - switch (context.kind) { - case "&&": - case "||": - case "??": - - /* - * If any result were not transferred from child contexts, - * this sets the head segments to both cases. - * The head segments are the path of the right-hand operand. - */ - if (!context.processed) { - context.trueForkContext.add(headSegments); - context.falseForkContext.add(headSegments); - context.qqForkContext.add(headSegments); - } - - /* - * Transfers results to upper context if this context is in - * test chunk. - */ - if (context.isForkingAsResult) { - const parentContext = this.choiceContext; - - parentContext.trueForkContext.addAll(context.trueForkContext); - parentContext.falseForkContext.addAll(context.falseForkContext); - parentContext.qqForkContext.addAll(context.qqForkContext); - parentContext.processed = true; - - return context; - } - - break; - - case "test": - if (!context.processed) { - - /* - * The head segments are the path of the `if` block here. - * Updates the `true` path with the end of the `if` block. - */ - context.trueForkContext.clear(); - context.trueForkContext.add(headSegments); - } else { - - /* - * The head segments are the path of the `else` block here. - * Updates the `false` path with the end of the `else` - * block. - */ - context.falseForkContext.clear(); - context.falseForkContext.add(headSegments); - } - - break; - - case "loop": - - /* - * Loops are addressed in popLoopContext(). - * This is called from popLoopContext(). - */ - return context; - - /* istanbul ignore next */ - default: - throw new Error("unreachable"); - } - - // Merges all paths. - const prevForkContext = context.trueForkContext; - - prevForkContext.addAll(context.falseForkContext); - forkContext.replaceHead(prevForkContext.makeNext(0, -1)); - - return context; - } - - /** - * Makes a code path segment of the right-hand operand of a logical - * expression. - * @returns {void} - */ - makeLogicalRight() { - const context = this.choiceContext; - const forkContext = this.forkContext; - - if (context.processed) { - - /* - * This got segments already from the child choice context. - * Creates the next path from own true/false fork context. - */ - let prevForkContext; - - switch (context.kind) { - case "&&": // if true then go to the right-hand side. - prevForkContext = context.trueForkContext; - break; - case "||": // if false then go to the right-hand side. - prevForkContext = context.falseForkContext; - break; - case "??": // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's qqForkContext. - prevForkContext = context.qqForkContext; - break; - default: - throw new Error("unreachable"); - } - - forkContext.replaceHead(prevForkContext.makeNext(0, -1)); - prevForkContext.clear(); - context.processed = false; - } else { - - /* - * This did not get segments from the child choice context. - * So addresses the head segments. - * The head segments are the path of the left-hand operand. - */ - switch (context.kind) { - case "&&": // the false path can short-circuit. - context.falseForkContext.add(forkContext.head); - break; - case "||": // the true path can short-circuit. - context.trueForkContext.add(forkContext.head); - break; - case "??": // both can short-circuit. - context.trueForkContext.add(forkContext.head); - context.falseForkContext.add(forkContext.head); - break; - default: - throw new Error("unreachable"); - } - - forkContext.replaceHead(forkContext.makeNext(-1, -1)); - } - } - - /** - * Makes a code path segment of the `if` block. - * @returns {void} - */ - makeIfConsequent() { - const context = this.choiceContext; - const forkContext = this.forkContext; - - /* - * If any result were not transferred from child contexts, - * this sets the head segments to both cases. - * The head segments are the path of the test expression. - */ - if (!context.processed) { - context.trueForkContext.add(forkContext.head); - context.falseForkContext.add(forkContext.head); - context.qqForkContext.add(forkContext.head); - } - - context.processed = false; - - // Creates new path from the `true` case. - forkContext.replaceHead( - context.trueForkContext.makeNext(0, -1) - ); - } - - /** - * Makes a code path segment of the `else` block. - * @returns {void} - */ - makeIfAlternate() { - const context = this.choiceContext; - const forkContext = this.forkContext; - - /* - * The head segments are the path of the `if` block. - * Updates the `true` path with the end of the `if` block. - */ - context.trueForkContext.clear(); - context.trueForkContext.add(forkContext.head); - context.processed = true; - - // Creates new path from the `false` case. - forkContext.replaceHead( - context.falseForkContext.makeNext(0, -1) - ); - } - - //-------------------------------------------------------------------------- - // ChainExpression - //-------------------------------------------------------------------------- - - /** - * Push a new `ChainExpression` context to the stack. - * This method is called on entering to each `ChainExpression` node. - * This context is used to count forking in the optional chain then merge them on the exiting from the `ChainExpression` node. - * @returns {void} - */ - pushChainContext() { - this.chainContext = { - upper: this.chainContext, - countChoiceContexts: 0 - }; - } - - /** - * Pop a `ChainExpression` context from the stack. - * This method is called on exiting from each `ChainExpression` node. - * This merges all forks of the last optional chaining. - * @returns {void} - */ - popChainContext() { - const context = this.chainContext; - - this.chainContext = context.upper; - - // pop all choice contexts of this. - for (let i = context.countChoiceContexts; i > 0; --i) { - this.popChoiceContext(); - } - } - - /** - * Create a choice context for optional access. - * This method is called on entering to each `(Call|Member)Expression[optional=true]` node. - * This creates a choice context as similar to `LogicalExpression[operator="??"]` node. - * @returns {void} - */ - makeOptionalNode() { - if (this.chainContext) { - this.chainContext.countChoiceContexts += 1; - this.pushChoiceContext("??", false); - } - } - - /** - * Create a fork. - * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node. - * @returns {void} - */ - makeOptionalRight() { - if (this.chainContext) { - this.makeLogicalRight(); - } - } - - //-------------------------------------------------------------------------- - // SwitchStatement - //-------------------------------------------------------------------------- - - /** - * Creates a context object of SwitchStatement and stacks it. - * @param {boolean} hasCase `true` if the switch statement has one or more - * case parts. - * @param {string|null} label The label text. - * @returns {void} - */ - pushSwitchContext(hasCase, label) { - this.switchContext = { - upper: this.switchContext, - hasCase, - defaultSegments: null, - defaultBodySegments: null, - foundDefault: false, - lastIsDefault: false, - countForks: 0 - }; - - this.pushBreakContext(true, label); - } - - /** - * Pops the last context of SwitchStatement and finalizes it. - * - * - Disposes all forking stack for `case` and `default`. - * - Creates the next code path segment from `context.brokenForkContext`. - * - If the last `SwitchCase` node is not a `default` part, creates a path - * to the `default` body. - * @returns {void} - */ - popSwitchContext() { - const context = this.switchContext; - - this.switchContext = context.upper; - - const forkContext = this.forkContext; - const brokenForkContext = this.popBreakContext().brokenForkContext; - - if (context.countForks === 0) { - - /* - * When there is only one `default` chunk and there is one or more - * `break` statements, even if forks are nothing, it needs to merge - * those. - */ - if (!brokenForkContext.empty) { - brokenForkContext.add(forkContext.makeNext(-1, -1)); - forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - - return; - } - - const lastSegments = forkContext.head; - - this.forkBypassPath(); - const lastCaseSegments = forkContext.head; - - /* - * `brokenForkContext` is used to make the next segment. - * It must add the last segment into `brokenForkContext`. - */ - brokenForkContext.add(lastSegments); - - /* - * A path which is failed in all case test should be connected to path - * of `default` chunk. - */ - if (!context.lastIsDefault) { - if (context.defaultBodySegments) { - - /* - * Remove a link from `default` label to its chunk. - * It's false route. - */ - removeConnection(context.defaultSegments, context.defaultBodySegments); - makeLooped(this, lastCaseSegments, context.defaultBodySegments); - } else { - - /* - * It handles the last case body as broken if `default` chunk - * does not exist. - */ - brokenForkContext.add(lastCaseSegments); - } - } - - // Pops the segment context stack until the entry segment. - for (let i = 0; i < context.countForks; ++i) { - this.forkContext = this.forkContext.upper; - } - - /* - * Creates a path from all brokenForkContext paths. - * This is a path after switch statement. - */ - this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - - /** - * Makes a code path segment for a `SwitchCase` node. - * @param {boolean} isEmpty `true` if the body is empty. - * @param {boolean} isDefault `true` if the body is the default case. - * @returns {void} - */ - makeSwitchCaseBody(isEmpty, isDefault) { - const context = this.switchContext; - - if (!context.hasCase) { - return; - } - - /* - * Merge forks. - * The parent fork context has two segments. - * Those are from the current case and the body of the previous case. - */ - const parentForkContext = this.forkContext; - const forkContext = this.pushForkContext(); - - forkContext.add(parentForkContext.makeNext(0, -1)); - - /* - * Save `default` chunk info. - * If the `default` label is not at the last, we must make a path from - * the last `case` to the `default` chunk. - */ - if (isDefault) { - context.defaultSegments = parentForkContext.head; - if (isEmpty) { - context.foundDefault = true; - } else { - context.defaultBodySegments = forkContext.head; - } - } else { - if (!isEmpty && context.foundDefault) { - context.foundDefault = false; - context.defaultBodySegments = forkContext.head; - } - } - - context.lastIsDefault = isDefault; - context.countForks += 1; - } - - //-------------------------------------------------------------------------- - // TryStatement - //-------------------------------------------------------------------------- - - /** - * Creates a context object of TryStatement and stacks it. - * @param {boolean} hasFinalizer `true` if the try statement has a - * `finally` block. - * @returns {void} - */ - pushTryContext(hasFinalizer) { - this.tryContext = { - upper: this.tryContext, - position: "try", - hasFinalizer, - - returnedForkContext: hasFinalizer - ? ForkContext.newEmpty(this.forkContext) - : null, - - thrownForkContext: ForkContext.newEmpty(this.forkContext), - lastOfTryIsReachable: false, - lastOfCatchIsReachable: false - }; - } - - /** - * Pops the last context of TryStatement and finalizes it. - * @returns {void} - */ - popTryContext() { - const context = this.tryContext; - - this.tryContext = context.upper; - - if (context.position === "catch") { - - // Merges two paths from the `try` block and `catch` block merely. - this.popForkContext(); - return; - } - - /* - * The following process is executed only when there is the `finally` - * block. - */ - - const returned = context.returnedForkContext; - const thrown = context.thrownForkContext; - - if (returned.empty && thrown.empty) { - return; - } - - // Separate head to normal paths and leaving paths. - const headSegments = this.forkContext.head; - - this.forkContext = this.forkContext.upper; - const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0); - const leavingSegments = headSegments.slice(headSegments.length / 2 | 0); - - // Forwards the leaving path to upper contexts. - if (!returned.empty) { - getReturnContext(this).returnedForkContext.add(leavingSegments); - } - if (!thrown.empty) { - getThrowContext(this).thrownForkContext.add(leavingSegments); - } - - // Sets the normal path as the next. - this.forkContext.replaceHead(normalSegments); - - /* - * If both paths of the `try` block and the `catch` block are - * unreachable, the next path becomes unreachable as well. - */ - if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) { - this.forkContext.makeUnreachable(); - } - } - - /** - * Makes a code path segment for a `catch` block. - * @returns {void} - */ - makeCatchBlock() { - const context = this.tryContext; - const forkContext = this.forkContext; - const thrown = context.thrownForkContext; - - // Update state. - context.position = "catch"; - context.thrownForkContext = ForkContext.newEmpty(forkContext); - context.lastOfTryIsReachable = forkContext.reachable; - - // Merge thrown paths. - thrown.add(forkContext.head); - const thrownSegments = thrown.makeNext(0, -1); - - // Fork to a bypass and the merged thrown path. - this.pushForkContext(); - this.forkBypassPath(); - this.forkContext.add(thrownSegments); - } - - /** - * Makes a code path segment for a `finally` block. - * - * In the `finally` block, parallel paths are created. The parallel paths - * are used as leaving-paths. The leaving-paths are paths from `return` - * statements and `throw` statements in a `try` block or a `catch` block. - * @returns {void} - */ - makeFinallyBlock() { - const context = this.tryContext; - let forkContext = this.forkContext; - const returned = context.returnedForkContext; - const thrown = context.thrownForkContext; - const headOfLeavingSegments = forkContext.head; - - // Update state. - if (context.position === "catch") { - - // Merges two paths from the `try` block and `catch` block. - this.popForkContext(); - forkContext = this.forkContext; - - context.lastOfCatchIsReachable = forkContext.reachable; - } else { - context.lastOfTryIsReachable = forkContext.reachable; - } - context.position = "finally"; - - if (returned.empty && thrown.empty) { - - // This path does not leave. - return; - } - - /* - * Create a parallel segment from merging returned and thrown. - * This segment will leave at the end of this finally block. - */ - const segments = forkContext.makeNext(-1, -1); - - for (let i = 0; i < forkContext.count; ++i) { - const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]]; - - for (let j = 0; j < returned.segmentsList.length; ++j) { - prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]); - } - for (let j = 0; j < thrown.segmentsList.length; ++j) { - prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]); - } - - segments.push( - CodePathSegment.newNext( - this.idGenerator.next(), - prevSegsOfLeavingSegment - ) - ); - } - - this.pushForkContext(true); - this.forkContext.add(segments); - } - - /** - * Makes a code path segment from the first throwable node to the `catch` - * block or the `finally` block. - * @returns {void} - */ - makeFirstThrowablePathInTryBlock() { - const forkContext = this.forkContext; - - if (!forkContext.reachable) { - return; - } - - const context = getThrowContext(this); - - if (context === this || - context.position !== "try" || - !context.thrownForkContext.empty - ) { - return; - } - - context.thrownForkContext.add(forkContext.head); - forkContext.replaceHead(forkContext.makeNext(-1, -1)); - } - - //-------------------------------------------------------------------------- - // Loop Statements - //-------------------------------------------------------------------------- - - /** - * Creates a context object of a loop statement and stacks it. - * @param {string} type The type of the node which was triggered. One of - * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`, - * and `ForStatement`. - * @param {string|null} label A label of the node which was triggered. - * @returns {void} - */ - pushLoopContext(type, label) { - const forkContext = this.forkContext; - const breakContext = this.pushBreakContext(true, label); - - switch (type) { - case "WhileStatement": - this.pushChoiceContext("loop", false); - this.loopContext = { - upper: this.loopContext, - type, - label, - test: void 0, - continueDestSegments: null, - brokenForkContext: breakContext.brokenForkContext - }; - break; - - case "DoWhileStatement": - this.pushChoiceContext("loop", false); - this.loopContext = { - upper: this.loopContext, - type, - label, - test: void 0, - entrySegments: null, - continueForkContext: ForkContext.newEmpty(forkContext), - brokenForkContext: breakContext.brokenForkContext - }; - break; - - case "ForStatement": - this.pushChoiceContext("loop", false); - this.loopContext = { - upper: this.loopContext, - type, - label, - test: void 0, - endOfInitSegments: null, - testSegments: null, - endOfTestSegments: null, - updateSegments: null, - endOfUpdateSegments: null, - continueDestSegments: null, - brokenForkContext: breakContext.brokenForkContext - }; - break; - - case "ForInStatement": - case "ForOfStatement": - this.loopContext = { - upper: this.loopContext, - type, - label, - prevSegments: null, - leftSegments: null, - endOfLeftSegments: null, - continueDestSegments: null, - brokenForkContext: breakContext.brokenForkContext - }; - break; - - /* istanbul ignore next */ - default: - throw new Error(`unknown type: "${type}"`); - } - } - - /** - * Pops the last context of a loop statement and finalizes it. - * @returns {void} - */ - popLoopContext() { - const context = this.loopContext; - - this.loopContext = context.upper; - - const forkContext = this.forkContext; - const brokenForkContext = this.popBreakContext().brokenForkContext; - - // Creates a looped path. - switch (context.type) { - case "WhileStatement": - case "ForStatement": - this.popChoiceContext(); - makeLooped( - this, - forkContext.head, - context.continueDestSegments - ); - break; - - case "DoWhileStatement": { - const choiceContext = this.popChoiceContext(); - - if (!choiceContext.processed) { - choiceContext.trueForkContext.add(forkContext.head); - choiceContext.falseForkContext.add(forkContext.head); - } - if (context.test !== true) { - brokenForkContext.addAll(choiceContext.falseForkContext); - } - - // `true` paths go to looping. - const segmentsList = choiceContext.trueForkContext.segmentsList; - - for (let i = 0; i < segmentsList.length; ++i) { - makeLooped( - this, - segmentsList[i], - context.entrySegments - ); - } - break; - } - - case "ForInStatement": - case "ForOfStatement": - brokenForkContext.add(forkContext.head); - makeLooped( - this, - forkContext.head, - context.leftSegments - ); - break; - - /* istanbul ignore next */ - default: - throw new Error("unreachable"); - } - - // Go next. - if (brokenForkContext.empty) { - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } else { - forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - } - - /** - * Makes a code path segment for the test part of a WhileStatement. - * @param {boolean|undefined} test The test value (only when constant). - * @returns {void} - */ - makeWhileTest(test) { - const context = this.loopContext; - const forkContext = this.forkContext; - const testSegments = forkContext.makeNext(0, -1); - - // Update state. - context.test = test; - context.continueDestSegments = testSegments; - forkContext.replaceHead(testSegments); - } - - /** - * Makes a code path segment for the body part of a WhileStatement. - * @returns {void} - */ - makeWhileBody() { - const context = this.loopContext; - const choiceContext = this.choiceContext; - const forkContext = this.forkContext; - - if (!choiceContext.processed) { - choiceContext.trueForkContext.add(forkContext.head); - choiceContext.falseForkContext.add(forkContext.head); - } - - // Update state. - if (context.test !== true) { - context.brokenForkContext.addAll(choiceContext.falseForkContext); - } - forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1)); - } - - /** - * Makes a code path segment for the body part of a DoWhileStatement. - * @returns {void} - */ - makeDoWhileBody() { - const context = this.loopContext; - const forkContext = this.forkContext; - const bodySegments = forkContext.makeNext(-1, -1); - - // Update state. - context.entrySegments = bodySegments; - forkContext.replaceHead(bodySegments); - } - - /** - * Makes a code path segment for the test part of a DoWhileStatement. - * @param {boolean|undefined} test The test value (only when constant). - * @returns {void} - */ - makeDoWhileTest(test) { - const context = this.loopContext; - const forkContext = this.forkContext; - - context.test = test; - - // Creates paths of `continue` statements. - if (!context.continueForkContext.empty) { - context.continueForkContext.add(forkContext.head); - const testSegments = context.continueForkContext.makeNext(0, -1); - - forkContext.replaceHead(testSegments); - } - } - - /** - * Makes a code path segment for the test part of a ForStatement. - * @param {boolean|undefined} test The test value (only when constant). - * @returns {void} - */ - makeForTest(test) { - const context = this.loopContext; - const forkContext = this.forkContext; - const endOfInitSegments = forkContext.head; - const testSegments = forkContext.makeNext(-1, -1); - - // Update state. - context.test = test; - context.endOfInitSegments = endOfInitSegments; - context.continueDestSegments = context.testSegments = testSegments; - forkContext.replaceHead(testSegments); - } - - /** - * Makes a code path segment for the update part of a ForStatement. - * @returns {void} - */ - makeForUpdate() { - const context = this.loopContext; - const choiceContext = this.choiceContext; - const forkContext = this.forkContext; - - // Make the next paths of the test. - if (context.testSegments) { - finalizeTestSegmentsOfFor( - context, - choiceContext, - forkContext.head - ); - } else { - context.endOfInitSegments = forkContext.head; - } - - // Update state. - const updateSegments = forkContext.makeDisconnected(-1, -1); - - context.continueDestSegments = context.updateSegments = updateSegments; - forkContext.replaceHead(updateSegments); - } - - /** - * Makes a code path segment for the body part of a ForStatement. - * @returns {void} - */ - makeForBody() { - const context = this.loopContext; - const choiceContext = this.choiceContext; - const forkContext = this.forkContext; - - // Update state. - if (context.updateSegments) { - context.endOfUpdateSegments = forkContext.head; - - // `update` -> `test` - if (context.testSegments) { - makeLooped( - this, - context.endOfUpdateSegments, - context.testSegments - ); - } - } else if (context.testSegments) { - finalizeTestSegmentsOfFor( - context, - choiceContext, - forkContext.head - ); - } else { - context.endOfInitSegments = forkContext.head; - } - - let bodySegments = context.endOfTestSegments; - - if (!bodySegments) { - - /* - * If there is not the `test` part, the `body` path comes from the - * `init` part and the `update` part. - */ - const prevForkContext = ForkContext.newEmpty(forkContext); - - prevForkContext.add(context.endOfInitSegments); - if (context.endOfUpdateSegments) { - prevForkContext.add(context.endOfUpdateSegments); - } - - bodySegments = prevForkContext.makeNext(0, -1); - } - context.continueDestSegments = context.continueDestSegments || bodySegments; - forkContext.replaceHead(bodySegments); - } - - /** - * Makes a code path segment for the left part of a ForInStatement and a - * ForOfStatement. - * @returns {void} - */ - makeForInOfLeft() { - const context = this.loopContext; - const forkContext = this.forkContext; - const leftSegments = forkContext.makeDisconnected(-1, -1); - - // Update state. - context.prevSegments = forkContext.head; - context.leftSegments = context.continueDestSegments = leftSegments; - forkContext.replaceHead(leftSegments); - } - - /** - * Makes a code path segment for the right part of a ForInStatement and a - * ForOfStatement. - * @returns {void} - */ - makeForInOfRight() { - const context = this.loopContext; - const forkContext = this.forkContext; - const temp = ForkContext.newEmpty(forkContext); - - temp.add(context.prevSegments); - const rightSegments = temp.makeNext(-1, -1); - - // Update state. - context.endOfLeftSegments = forkContext.head; - forkContext.replaceHead(rightSegments); - } - - /** - * Makes a code path segment for the body part of a ForInStatement and a - * ForOfStatement. - * @returns {void} - */ - makeForInOfBody() { - const context = this.loopContext; - const forkContext = this.forkContext; - const temp = ForkContext.newEmpty(forkContext); - - temp.add(context.endOfLeftSegments); - const bodySegments = temp.makeNext(-1, -1); - - // Make a path: `right` -> `left`. - makeLooped(this, forkContext.head, context.leftSegments); - - // Update state. - context.brokenForkContext.add(forkContext.head); - forkContext.replaceHead(bodySegments); - } - - //-------------------------------------------------------------------------- - // Control Statements - //-------------------------------------------------------------------------- - - /** - * Creates new context for BreakStatement. - * @param {boolean} breakable The flag to indicate it can break by - * an unlabeled BreakStatement. - * @param {string|null} label The label of this context. - * @returns {Object} The new context. - */ - pushBreakContext(breakable, label) { - this.breakContext = { - upper: this.breakContext, - breakable, - label, - brokenForkContext: ForkContext.newEmpty(this.forkContext) - }; - return this.breakContext; - } - - /** - * Removes the top item of the break context stack. - * @returns {Object} The removed context. - */ - popBreakContext() { - const context = this.breakContext; - const forkContext = this.forkContext; - - this.breakContext = context.upper; - - // Process this context here for other than switches and loops. - if (!context.breakable) { - const brokenForkContext = context.brokenForkContext; - - if (!brokenForkContext.empty) { - brokenForkContext.add(forkContext.head); - forkContext.replaceHead(brokenForkContext.makeNext(0, -1)); - } - } - - return context; - } - - /** - * Makes a path for a `break` statement. - * - * It registers the head segment to a context of `break`. - * It makes new unreachable segment, then it set the head with the segment. - * @param {string} label A label of the break statement. - * @returns {void} - */ - makeBreak(label) { - const forkContext = this.forkContext; - - if (!forkContext.reachable) { - return; - } - - const context = getBreakContext(this, label); - - /* istanbul ignore else: foolproof (syntax error) */ - if (context) { - context.brokenForkContext.add(forkContext.head); - } - - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - - /** - * Makes a path for a `continue` statement. - * - * It makes a looping path. - * It makes new unreachable segment, then it set the head with the segment. - * @param {string} label A label of the continue statement. - * @returns {void} - */ - makeContinue(label) { - const forkContext = this.forkContext; - - if (!forkContext.reachable) { - return; - } - - const context = getContinueContext(this, label); - - /* istanbul ignore else: foolproof (syntax error) */ - if (context) { - if (context.continueDestSegments) { - makeLooped(this, forkContext.head, context.continueDestSegments); - - // If the context is a for-in/of loop, this effects a break also. - if (context.type === "ForInStatement" || - context.type === "ForOfStatement" - ) { - context.brokenForkContext.add(forkContext.head); - } - } else { - context.continueForkContext.add(forkContext.head); - } - } - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - - /** - * Makes a path for a `return` statement. - * - * It registers the head segment to a context of `return`. - * It makes new unreachable segment, then it set the head with the segment. - * @returns {void} - */ - makeReturn() { - const forkContext = this.forkContext; - - if (forkContext.reachable) { - getReturnContext(this).returnedForkContext.add(forkContext.head); - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - } - - /** - * Makes a path for a `throw` statement. - * - * It registers the head segment to a context of `throw`. - * It makes new unreachable segment, then it set the head with the segment. - * @returns {void} - */ - makeThrow() { - const forkContext = this.forkContext; - - if (forkContext.reachable) { - getThrowContext(this).thrownForkContext.add(forkContext.head); - forkContext.replaceHead(forkContext.makeUnreachable(-1, -1)); - } - } - - /** - * Makes the final path. - * @returns {void} - */ - makeFinal() { - const segments = this.currentSegments; - - if (segments.length > 0 && segments[0].reachable) { - this.returnedForkContext.add(segments); - } - } -} - -module.exports = CodePathState; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path.js deleted file mode 100644 index 49b37c6b2272db59f2ab9c6f05639fc63858cc10..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/code-path.js +++ /dev/null @@ -1,238 +0,0 @@ -/** - * @fileoverview A class of the code path. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const CodePathState = require("./code-path-state"); -const IdGenerator = require("./id-generator"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A code path. - */ -class CodePath { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} id An identifier. - * @param {CodePath|null} upper The code path of the upper function scope. - * @param {Function} onLooped A callback function to notify looping. - */ - constructor(id, upper, onLooped) { - - /** - * The identifier of this code path. - * Rules use it to store additional information of each rule. - * @type {string} - */ - this.id = id; - - /** - * The code path of the upper function scope. - * @type {CodePath|null} - */ - this.upper = upper; - - /** - * The code paths of nested function scopes. - * @type {CodePath[]} - */ - this.childCodePaths = []; - - // Initializes internal state. - Object.defineProperty( - this, - "internal", - { value: new CodePathState(new IdGenerator(`${id}_`), onLooped) } - ); - - // Adds this into `childCodePaths` of `upper`. - if (upper) { - upper.childCodePaths.push(this); - } - } - - /** - * Gets the state of a given code path. - * @param {CodePath} codePath A code path to get. - * @returns {CodePathState} The state of the code path. - */ - static getState(codePath) { - return codePath.internal; - } - - /** - * The initial code path segment. - * @type {CodePathSegment} - */ - get initialSegment() { - return this.internal.initialSegment; - } - - /** - * Final code path segments. - * This array is a mix of `returnedSegments` and `thrownSegments`. - * @type {CodePathSegment[]} - */ - get finalSegments() { - return this.internal.finalSegments; - } - - /** - * Final code path segments which is with `return` statements. - * This array contains the last path segment if it's reachable. - * Since the reachable last path returns `undefined`. - * @type {CodePathSegment[]} - */ - get returnedSegments() { - return this.internal.returnedForkContext; - } - - /** - * Final code path segments which is with `throw` statements. - * @type {CodePathSegment[]} - */ - get thrownSegments() { - return this.internal.thrownForkContext; - } - - /** - * Current code path segments. - * @type {CodePathSegment[]} - */ - get currentSegments() { - return this.internal.currentSegments; - } - - /** - * Traverses all segments in this code path. - * - * codePath.traverseSegments(function(segment, controller) { - * // do something. - * }); - * - * This method enumerates segments in order from the head. - * - * The `controller` object has two methods. - * - * - `controller.skip()` - Skip the following segments in this branch. - * - `controller.break()` - Skip all following segments. - * @param {Object} [options] Omittable. - * @param {CodePathSegment} [options.first] The first segment to traverse. - * @param {CodePathSegment} [options.last] The last segment to traverse. - * @param {Function} callback A callback function. - * @returns {void} - */ - traverseSegments(options, callback) { - let resolvedOptions; - let resolvedCallback; - - if (typeof options === "function") { - resolvedCallback = options; - resolvedOptions = {}; - } else { - resolvedOptions = options || {}; - resolvedCallback = callback; - } - - const startSegment = resolvedOptions.first || this.internal.initialSegment; - const lastSegment = resolvedOptions.last; - - let item = null; - let index = 0; - let end = 0; - let segment = null; - const visited = Object.create(null); - const stack = [[startSegment, 0]]; - let skippedSegment = null; - let broken = false; - const controller = { - skip() { - if (stack.length <= 1) { - broken = true; - } else { - skippedSegment = stack[stack.length - 2][0]; - } - }, - break() { - broken = true; - } - }; - - /** - * Checks a given previous segment has been visited. - * @param {CodePathSegment} prevSegment A previous segment to check. - * @returns {boolean} `true` if the segment has been visited. - */ - function isVisited(prevSegment) { - return ( - visited[prevSegment.id] || - segment.isLoopedPrevSegment(prevSegment) - ); - } - - while (stack.length > 0) { - item = stack[stack.length - 1]; - segment = item[0]; - index = item[1]; - - if (index === 0) { - - // Skip if this segment has been visited already. - if (visited[segment.id]) { - stack.pop(); - continue; - } - - // Skip if all previous segments have not been visited. - if (segment !== startSegment && - segment.prevSegments.length > 0 && - !segment.prevSegments.every(isVisited) - ) { - stack.pop(); - continue; - } - - // Reset the flag of skipping if all branches have been skipped. - if (skippedSegment && segment.prevSegments.indexOf(skippedSegment) !== -1) { - skippedSegment = null; - } - visited[segment.id] = true; - - // Call the callback when the first time. - if (!skippedSegment) { - resolvedCallback.call(this, segment, controller); - if (segment === lastSegment) { - controller.skip(); - } - if (broken) { - break; - } - } - } - - // Update the stack. - end = segment.nextSegments.length - 1; - if (index < end) { - item[1] += 1; - stack.push([segment.nextSegments[index], 0]); - } else if (index === end) { - item[0] = segment.nextSegments[index]; - item[1] = 0; - } else { - stack.pop(); - } - } - } -} - -module.exports = CodePath; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js deleted file mode 100644 index a4cb99a22e0126d0153008029674fbb02bc1c48f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/debug-helpers.js +++ /dev/null @@ -1,203 +0,0 @@ -/** - * @fileoverview Helpers to debug for code path analysis. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("debug")("eslint:code-path"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets id of a given segment. - * @param {CodePathSegment} segment A segment to get. - * @returns {string} Id of the segment. - */ -/* istanbul ignore next */ -function getId(segment) { // eslint-disable-line jsdoc/require-jsdoc - return segment.id + (segment.reachable ? "" : "!"); -} - -/** - * Get string for the given node and operation. - * @param {ASTNode} node The node to convert. - * @param {"enter" | "exit" | undefined} label The operation label. - * @returns {string} The string representation. - */ -function nodeToString(node, label) { - const suffix = label ? `:${label}` : ""; - - switch (node.type) { - case "Identifier": return `${node.type}${suffix} (${node.name})`; - case "Literal": return `${node.type}${suffix} (${node.value})`; - default: return `${node.type}${suffix}`; - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - - /** - * A flag that debug dumping is enabled or not. - * @type {boolean} - */ - enabled: debug.enabled, - - /** - * Dumps given objects. - * @param {...any} args objects to dump. - * @returns {void} - */ - dump: debug, - - /** - * Dumps the current analyzing state. - * @param {ASTNode} node A node to dump. - * @param {CodePathState} state A state to dump. - * @param {boolean} leaving A flag whether or not it's leaving - * @returns {void} - */ - dumpState: !debug.enabled ? debug : /* istanbul ignore next */ function(node, state, leaving) { - for (let i = 0; i < state.currentSegments.length; ++i) { - const segInternal = state.currentSegments[i].internal; - - if (leaving) { - const last = segInternal.nodes.length - 1; - - if (last >= 0 && segInternal.nodes[last] === nodeToString(node, "enter")) { - segInternal.nodes[last] = nodeToString(node, void 0); - } else { - segInternal.nodes.push(nodeToString(node, "exit")); - } - } else { - segInternal.nodes.push(nodeToString(node, "enter")); - } - } - - debug([ - `${state.currentSegments.map(getId).join(",")})`, - `${node.type}${leaving ? ":exit" : ""}` - ].join(" ")); - }, - - /** - * Dumps a DOT code of a given code path. - * The DOT code can be visualized with Graphvis. - * @param {CodePath} codePath A code path to dump. - * @returns {void} - * @see http://www.graphviz.org - * @see http://www.webgraphviz.com - */ - dumpDot: !debug.enabled ? debug : /* istanbul ignore next */ function(codePath) { - let text = - "\n" + - "digraph {\n" + - "node[shape=box,style=\"rounded,filled\",fillcolor=white];\n" + - "initial[label=\"\",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25];\n"; - - if (codePath.returnedSegments.length > 0) { - text += "final[label=\"\",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25];\n"; - } - if (codePath.thrownSegments.length > 0) { - text += "thrown[label=\"✘\",shape=circle,width=0.3,height=0.3,fixedsize];\n"; - } - - const traceMap = Object.create(null); - const arrows = this.makeDotArrows(codePath, traceMap); - - for (const id in traceMap) { // eslint-disable-line guard-for-in - const segment = traceMap[id]; - - text += `${id}[`; - - if (segment.reachable) { - text += "label=\""; - } else { - text += "style=\"rounded,dashed,filled\",fillcolor=\"#FF9800\",label=\"<>\\n"; - } - - if (segment.internal.nodes.length > 0) { - text += segment.internal.nodes.join("\\n"); - } else { - text += "????"; - } - - text += "\"];\n"; - } - - text += `${arrows}\n`; - text += "}"; - debug("DOT", text); - }, - - /** - * Makes a DOT code of a given code path. - * The DOT code can be visualized with Graphvis. - * @param {CodePath} codePath A code path to make DOT. - * @param {Object} traceMap Optional. A map to check whether or not segments had been done. - * @returns {string} A DOT code of the code path. - */ - makeDotArrows(codePath, traceMap) { - const stack = [[codePath.initialSegment, 0]]; - const done = traceMap || Object.create(null); - let lastId = codePath.initialSegment.id; - let text = `initial->${codePath.initialSegment.id}`; - - while (stack.length > 0) { - const item = stack.pop(); - const segment = item[0]; - const index = item[1]; - - if (done[segment.id] && index === 0) { - continue; - } - done[segment.id] = segment; - - const nextSegment = segment.allNextSegments[index]; - - if (!nextSegment) { - continue; - } - - if (lastId === segment.id) { - text += `->${nextSegment.id}`; - } else { - text += `;\n${segment.id}->${nextSegment.id}`; - } - lastId = nextSegment.id; - - stack.unshift([segment, 1 + index]); - stack.push([nextSegment, 0]); - } - - codePath.returnedSegments.forEach(finalSegment => { - if (lastId === finalSegment.id) { - text += "->final"; - } else { - text += `;\n${finalSegment.id}->final`; - } - lastId = null; - }); - - codePath.thrownSegments.forEach(finalSegment => { - if (lastId === finalSegment.id) { - text += "->thrown"; - } else { - text += `;\n${finalSegment.id}->thrown`; - } - lastId = null; - }); - - return `${text};`; - } -}; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js deleted file mode 100644 index 2e872b5c0dbf5a9a779554ed858a9fb4f9484bab..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/fork-context.js +++ /dev/null @@ -1,249 +0,0 @@ -/** - * @fileoverview A class to operate forking. - * - * This is state of forking. - * This has a fork list and manages it. - * - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"), - CodePathSegment = require("./code-path-segment"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets whether or not a given segment is reachable. - * @param {CodePathSegment} segment A segment to get. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Creates new segments from the specific range of `context.segmentsList`. - * - * When `context.segmentsList` is `[[a, b], [c, d], [e, f]]`, `begin` is `0`, and - * `end` is `-1`, this creates `[g, h]`. This `g` is from `a`, `c`, and `e`. - * This `h` is from `b`, `d`, and `f`. - * @param {ForkContext} context An instance. - * @param {number} begin The first index of the previous segments. - * @param {number} end The last index of the previous segments. - * @param {Function} create A factory function of new segments. - * @returns {CodePathSegment[]} New segments. - */ -function makeSegments(context, begin, end, create) { - const list = context.segmentsList; - - const normalizedBegin = begin >= 0 ? begin : list.length + begin; - const normalizedEnd = end >= 0 ? end : list.length + end; - - const segments = []; - - for (let i = 0; i < context.count; ++i) { - const allPrevSegments = []; - - for (let j = normalizedBegin; j <= normalizedEnd; ++j) { - allPrevSegments.push(list[j][i]); - } - - segments.push(create(context.idGenerator.next(), allPrevSegments)); - } - - return segments; -} - -/** - * `segments` becomes doubly in a `finally` block. Then if a code path exits by a - * control statement (such as `break`, `continue`) from the `finally` block, the - * destination's segments may be half of the source segments. In that case, this - * merges segments. - * @param {ForkContext} context An instance. - * @param {CodePathSegment[]} segments Segments to merge. - * @returns {CodePathSegment[]} The merged segments. - */ -function mergeExtraSegments(context, segments) { - let currentSegments = segments; - - while (currentSegments.length > context.count) { - const merged = []; - - for (let i = 0, length = currentSegments.length / 2 | 0; i < length; ++i) { - merged.push(CodePathSegment.newNext( - context.idGenerator.next(), - [currentSegments[i], currentSegments[i + length]] - )); - } - currentSegments = merged; - } - return currentSegments; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A class to manage forking. - */ -class ForkContext { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {IdGenerator} idGenerator An identifier generator for segments. - * @param {ForkContext|null} upper An upper fork context. - * @param {number} count A number of parallel segments. - */ - constructor(idGenerator, upper, count) { - this.idGenerator = idGenerator; - this.upper = upper; - this.count = count; - this.segmentsList = []; - } - - /** - * The head segments. - * @type {CodePathSegment[]} - */ - get head() { - const list = this.segmentsList; - - return list.length === 0 ? [] : list[list.length - 1]; - } - - /** - * A flag which shows empty. - * @type {boolean} - */ - get empty() { - return this.segmentsList.length === 0; - } - - /** - * A flag which shows reachable. - * @type {boolean} - */ - get reachable() { - const segments = this.head; - - return segments.length > 0 && segments.some(isReachable); - } - - /** - * Creates new segments from this context. - * @param {number} begin The first index of previous segments. - * @param {number} end The last index of previous segments. - * @returns {CodePathSegment[]} New segments. - */ - makeNext(begin, end) { - return makeSegments(this, begin, end, CodePathSegment.newNext); - } - - /** - * Creates new segments from this context. - * The new segments is always unreachable. - * @param {number} begin The first index of previous segments. - * @param {number} end The last index of previous segments. - * @returns {CodePathSegment[]} New segments. - */ - makeUnreachable(begin, end) { - return makeSegments(this, begin, end, CodePathSegment.newUnreachable); - } - - /** - * Creates new segments from this context. - * The new segments don't have connections for previous segments. - * But these inherit the reachable flag from this context. - * @param {number} begin The first index of previous segments. - * @param {number} end The last index of previous segments. - * @returns {CodePathSegment[]} New segments. - */ - makeDisconnected(begin, end) { - return makeSegments(this, begin, end, CodePathSegment.newDisconnected); - } - - /** - * Adds segments into this context. - * The added segments become the head. - * @param {CodePathSegment[]} segments Segments to add. - * @returns {void} - */ - add(segments) { - assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); - - this.segmentsList.push(mergeExtraSegments(this, segments)); - } - - /** - * Replaces the head segments with given segments. - * The current head segments are removed. - * @param {CodePathSegment[]} segments Segments to add. - * @returns {void} - */ - replaceHead(segments) { - assert(segments.length >= this.count, `${segments.length} >= ${this.count}`); - - this.segmentsList.splice(-1, 1, mergeExtraSegments(this, segments)); - } - - /** - * Adds all segments of a given fork context into this context. - * @param {ForkContext} context A fork context to add. - * @returns {void} - */ - addAll(context) { - assert(context.count === this.count); - - const source = context.segmentsList; - - for (let i = 0; i < source.length; ++i) { - this.segmentsList.push(source[i]); - } - } - - /** - * Clears all segments in this context. - * @returns {void} - */ - clear() { - this.segmentsList = []; - } - - /** - * Creates the root fork context. - * @param {IdGenerator} idGenerator An identifier generator for segments. - * @returns {ForkContext} New fork context. - */ - static newRoot(idGenerator) { - const context = new ForkContext(idGenerator, null, 1); - - context.add([CodePathSegment.newRoot(idGenerator.next())]); - - return context; - } - - /** - * Creates an empty fork context preceded by a given context. - * @param {ForkContext} parentContext The parent fork context. - * @param {boolean} forkLeavingPath A flag which shows inside of `finally` block. - * @returns {ForkContext} New fork context. - */ - static newEmpty(parentContext, forkLeavingPath) { - return new ForkContext( - parentContext.idGenerator, - parentContext, - (forkLeavingPath ? 2 : 1) * parentContext.count - ); - } -} - -module.exports = ForkContext; diff --git a/tools/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js b/tools/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js deleted file mode 100644 index 4cb2e0e3d87cc1767d04541849a6a5474bbbf17c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/code-path-analysis/id-generator.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview A class of identifiers generator for code path segments. - * - * Each rule uses the identifier of code path segments to store additional - * information of the code path. - * - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A generator for unique ids. - */ -class IdGenerator { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} prefix Optional. A prefix of generated ids. - */ - constructor(prefix) { - this.prefix = String(prefix); - this.n = 0; - } - - /** - * Generates id. - * @returns {string} A generated id. - */ - next() { - this.n = 1 + this.n | 0; - - /* istanbul ignore if */ - if (this.n < 0) { - this.n = 1; - } - - return this.prefix + this.n; - } -} - -module.exports = IdGenerator; diff --git a/tools/node_modules/eslint/lib/linter/config-comment-parser.js b/tools/node_modules/eslint/lib/linter/config-comment-parser.js deleted file mode 100644 index 07bbead281cbf6cabb1712bd3f541967a2752fa2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/config-comment-parser.js +++ /dev/null @@ -1,141 +0,0 @@ -/** - * @fileoverview Config Comment Parser - * @author Nicholas C. Zakas - */ - -/* eslint-disable class-methods-use-this*/ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const levn = require("levn"), - ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"); - -const debug = require("debug")("eslint:config-comment-parser"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Object to parse ESLint configuration comments inside JavaScript files. - * @name ConfigCommentParser - */ -module.exports = class ConfigCommentParser { - - /** - * Parses a list of "name:string_value" or/and "name" options divided by comma or - * whitespace. Used for "global" and "exported" comments. - * @param {string} string The string to parse. - * @param {Comment} comment The comment node which has the string. - * @returns {Object} Result map object of names and string values, or null values if no value was provided - */ - parseStringConfig(string, comment) { - debug("Parsing String config"); - - const items = {}; - - // Collapse whitespace around `:` and `,` to make parsing easier - const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1"); - - trimmedString.split(/\s|,+/u).forEach(name => { - if (!name) { - return; - } - - // value defaults to null (if not provided), e.g: "foo" => ["foo", null] - const [key, value = null] = name.split(":"); - - items[key] = { value, comment }; - }); - return items; - } - - /** - * Parses a JSON-like config. - * @param {string} string The string to parse. - * @param {Object} location Start line and column of comments for potential error message. - * @returns {({success: true, config: Object}|{success: false, error: Problem})} Result map object - */ - parseJsonConfig(string, location) { - debug("Parsing JSON config"); - - let items = {}; - - // Parses a JSON-like comment by the same way as parsing CLI option. - try { - items = levn.parse("Object", string) || {}; - - // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`. - // Also, commaless notations have invalid severity: - // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"} - // Should ignore that case as well. - if (ConfigOps.isEverySeverityValid(items)) { - return { - success: true, - config: items - }; - } - } catch { - - debug("Levn parsing failed; falling back to manual parsing."); - - // ignore to parse the string by a fallback. - } - - /* - * Optionator cannot parse commaless notations. - * But we are supporting that. So this is a fallback for that. - */ - items = {}; - const normalizedString = string.replace(/([-a-zA-Z0-9/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,"); - - try { - items = JSON.parse(`{${normalizedString}}`); - } catch (ex) { - debug("Manual parsing failed."); - - return { - success: false, - error: { - ruleId: null, - fatal: true, - severity: 2, - message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`, - line: location.start.line, - column: location.start.column + 1 - } - }; - - } - - return { - success: true, - config: items - }; - } - - /** - * Parses a config of values separated by comma. - * @param {string} string The string to parse. - * @returns {Object} Result map of values and true values - */ - parseListConfig(string) { - debug("Parsing list config"); - - const items = {}; - - // Collapse whitespace around commas - string.replace(/\s*,\s*/gu, ",").split(/,+/u).forEach(name => { - const trimmedName = name.trim(); - - if (trimmedName) { - items[trimmedName] = true; - } - }); - return items; - } - -}; diff --git a/tools/node_modules/eslint/lib/linter/index.js b/tools/node_modules/eslint/lib/linter/index.js deleted file mode 100644 index 25fd769bde997fd15d302c66202a6afe12fc1840..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/index.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; - -const { Linter } = require("./linter"); -const interpolate = require("./interpolate"); -const SourceCodeFixer = require("./source-code-fixer"); - -module.exports = { - Linter, - - // For testers. - SourceCodeFixer, - interpolate -}; diff --git a/tools/node_modules/eslint/lib/linter/interpolate.js b/tools/node_modules/eslint/lib/linter/interpolate.js deleted file mode 100644 index 87e06a0236991defb7412df7c935da6b92848c12..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/interpolate.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @fileoverview Interpolate keys from an object into a string with {{ }} markers. - * @author Jed Fox - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = (text, data) => { - if (!data) { - return text; - } - - // Substitution content for any {{ }} markers. - return text.replace(/\{\{([^{}]+?)\}\}/gu, (fullMatch, termWithWhitespace) => { - const term = termWithWhitespace.trim(); - - if (term in data) { - return data[term]; - } - - // Preserve old behavior: If parameter name not provided, don't replace it. - return fullMatch; - }); -}; diff --git a/tools/node_modules/eslint/lib/linter/linter.js b/tools/node_modules/eslint/lib/linter/linter.js deleted file mode 100644 index 5c1a8d78aa1df02d7bb9e5561406e46bd29247db..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/linter.js +++ /dev/null @@ -1,1467 +0,0 @@ -/** - * @fileoverview Main Linter Class - * @author Gyandeep Singh - * @author aladdin-add - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const - path = require("path"), - eslintScope = require("eslint-scope"), - evk = require("eslint-visitor-keys"), - espree = require("espree"), - lodash = require("lodash"), - BuiltInEnvironments = require("@eslint/eslintrc/conf/environments"), - pkg = require("../../package.json"), - astUtils = require("../shared/ast-utils"), - ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"), - ConfigValidator = require("@eslint/eslintrc/lib/shared/config-validator"), - Traverser = require("../shared/traverser"), - { SourceCode } = require("../source-code"), - CodePathAnalyzer = require("./code-path-analysis/code-path-analyzer"), - applyDisableDirectives = require("./apply-disable-directives"), - ConfigCommentParser = require("./config-comment-parser"), - NodeEventGenerator = require("./node-event-generator"), - createReportTranslator = require("./report-translator"), - Rules = require("./rules"), - createEmitter = require("./safe-emitter"), - SourceCodeFixer = require("./source-code-fixer"), - timing = require("./timing"), - ruleReplacements = require("../../conf/replacements.json"); - -const debug = require("debug")("eslint:linter"); -const MAX_AUTOFIX_PASSES = 10; -const DEFAULT_PARSER_NAME = "espree"; -const commentParser = new ConfigCommentParser(); -const DEFAULT_ERROR_LOC = { start: { line: 1, column: 0 }, end: { line: 1, column: 1 } }; - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** @typedef {InstanceType} ConfigArray */ -/** @typedef {InstanceType} ExtractedConfig */ -/** @typedef {import("../shared/types").ConfigData} ConfigData */ -/** @typedef {import("../shared/types").Environment} Environment */ -/** @typedef {import("../shared/types").GlobalConf} GlobalConf */ -/** @typedef {import("../shared/types").LintMessage} LintMessage */ -/** @typedef {import("../shared/types").ParserOptions} ParserOptions */ -/** @typedef {import("../shared/types").Processor} Processor */ -/** @typedef {import("../shared/types").Rule} Rule */ - -/** - * @template T - * @typedef {{ [P in keyof T]-?: T[P] }} Required - */ - -/** - * @typedef {Object} DisableDirective - * @property {("disable"|"enable"|"disable-line"|"disable-next-line")} type - * @property {number} line - * @property {number} column - * @property {(string|null)} ruleId - */ - -/** - * The private data for `Linter` instance. - * @typedef {Object} LinterInternalSlots - * @property {ConfigArray|null} lastConfigArray The `ConfigArray` instance that the last `verify()` call used. - * @property {SourceCode|null} lastSourceCode The `SourceCode` instance that the last `verify()` call used. - * @property {Map} parserMap The loaded parsers. - * @property {Rules} ruleMap The loaded rules. - */ - -/** - * @typedef {Object} VerifyOptions - * @property {boolean} [allowInlineConfig] Allow/disallow inline comments' ability - * to change config once it is set. Defaults to true if not supplied. - * Useful if you want to validate JS without comments overriding rules. - * @property {boolean} [disableFixes] if `true` then the linter doesn't make `fix` - * properties into the lint result. - * @property {string} [filename] the filename of the source code. - * @property {boolean | "off" | "warn" | "error"} [reportUnusedDisableDirectives] Adds reported errors for - * unused `eslint-disable` directives. - */ - -/** - * @typedef {Object} ProcessorOptions - * @property {(filename:string, text:string) => boolean} [filterCodeBlock] the - * predicate function that selects adopt code blocks. - * @property {Processor["postprocess"]} [postprocess] postprocessor for report - * messages. If provided, this should accept an array of the message lists - * for each code block returned from the preprocessor, apply a mapping to - * the messages as appropriate, and return a one-dimensional array of - * messages. - * @property {Processor["preprocess"]} [preprocess] preprocessor for source text. - * If provided, this should accept a string of source text, and return an - * array of code blocks to lint. - */ - -/** - * @typedef {Object} FixOptions - * @property {boolean | ((message: LintMessage) => boolean)} [fix] Determines - * whether fixes should be applied. - */ - -/** - * @typedef {Object} InternalOptions - * @property {string | null} warnInlineConfig The config name what `noInlineConfig` setting came from. If `noInlineConfig` setting didn't exist, this is null. If this is a config name, then the linter warns directive comments. - * @property {"off" | "warn" | "error"} reportUnusedDisableDirectives (boolean values were normalized) - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Ensures that variables representing built-in properties of the Global Object, - * and any globals declared by special block comments, are present in the global - * scope. - * @param {Scope} globalScope The global scope. - * @param {Object} configGlobals The globals declared in configuration - * @param {{exportedVariables: Object, enabledGlobals: Object}} commentDirectives Directives from comment configuration - * @returns {void} - */ -function addDeclaredGlobals(globalScope, configGlobals, { exportedVariables, enabledGlobals }) { - - // Define configured global variables. - for (const id of new Set([...Object.keys(configGlobals), ...Object.keys(enabledGlobals)])) { - - /* - * `ConfigOps.normalizeConfigGlobal` will throw an error if a configured global value is invalid. However, these errors would - * typically be caught when validating a config anyway (validity for inline global comments is checked separately). - */ - const configValue = configGlobals[id] === void 0 ? void 0 : ConfigOps.normalizeConfigGlobal(configGlobals[id]); - const commentValue = enabledGlobals[id] && enabledGlobals[id].value; - const value = commentValue || configValue; - const sourceComments = enabledGlobals[id] && enabledGlobals[id].comments; - - if (value === "off") { - continue; - } - - let variable = globalScope.set.get(id); - - if (!variable) { - variable = new eslintScope.Variable(id, globalScope); - - globalScope.variables.push(variable); - globalScope.set.set(id, variable); - } - - variable.eslintImplicitGlobalSetting = configValue; - variable.eslintExplicitGlobal = sourceComments !== void 0; - variable.eslintExplicitGlobalComments = sourceComments; - variable.writeable = (value === "writable"); - } - - // mark all exported variables as such - Object.keys(exportedVariables).forEach(name => { - const variable = globalScope.set.get(name); - - if (variable) { - variable.eslintUsed = true; - } - }); - - /* - * "through" contains all references which definitions cannot be found. - * Since we augment the global scope using configuration, we need to update - * references and remove the ones that were added by configuration. - */ - globalScope.through = globalScope.through.filter(reference => { - const name = reference.identifier.name; - const variable = globalScope.set.get(name); - - if (variable) { - - /* - * Links the variable and the reference. - * And this reference is removed from `Scope#through`. - */ - reference.resolved = variable; - variable.references.push(reference); - - return false; - } - - return true; - }); -} - -/** - * creates a missing-rule message. - * @param {string} ruleId the ruleId to create - * @returns {string} created error message - * @private - */ -function createMissingRuleMessage(ruleId) { - return Object.prototype.hasOwnProperty.call(ruleReplacements.rules, ruleId) - ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements.rules[ruleId].join(", ")}` - : `Definition for rule '${ruleId}' was not found.`; -} - -/** - * creates a linting problem - * @param {Object} options to create linting error - * @param {string} [options.ruleId] the ruleId to report - * @param {Object} [options.loc] the loc to report - * @param {string} [options.message] the error message to report - * @param {string} [options.severity] the error message to report - * @returns {LintMessage} created problem, returns a missing-rule problem if only provided ruleId. - * @private - */ -function createLintingProblem(options) { - const { - ruleId = null, - loc = DEFAULT_ERROR_LOC, - message = createMissingRuleMessage(options.ruleId), - severity = 2 - } = options; - - return { - ruleId, - message, - line: loc.start.line, - column: loc.start.column + 1, - endLine: loc.end.line, - endColumn: loc.end.column + 1, - severity, - nodeType: null - }; -} - -/** - * Creates a collection of disable directives from a comment - * @param {Object} options to create disable directives - * @param {("disable"|"enable"|"disable-line"|"disable-next-line")} options.type The type of directive comment - * @param {{line: number, column: number}} options.loc The 0-based location of the comment token - * @param {string} options.value The value after the directive in the comment - * comment specified no specific rules, so it applies to all rules (e.g. `eslint-disable`) - * @param {function(string): {create: Function}} options.ruleMapper A map from rule IDs to defined rules - * @returns {Object} Directives and problems from the comment - */ -function createDisableDirectives(options) { - const { type, loc, value, ruleMapper } = options; - const ruleIds = Object.keys(commentParser.parseListConfig(value)); - const directiveRules = ruleIds.length ? ruleIds : [null]; - const result = { - directives: [], // valid disable directives - directiveProblems: [] // problems in directives - }; - - for (const ruleId of directiveRules) { - - // push to directives, if the rule is defined(including null, e.g. /*eslint enable*/) - if (ruleId === null || ruleMapper(ruleId) !== null) { - result.directives.push({ type, line: loc.start.line, column: loc.start.column + 1, ruleId }); - } else { - result.directiveProblems.push(createLintingProblem({ ruleId, loc })); - } - } - return result; -} - -/** - * Remove the ignored part from a given directive comment and trim it. - * @param {string} value The comment text to strip. - * @returns {string} The stripped text. - */ -function stripDirectiveComment(value) { - return value.split(/\s-{2,}\s/u)[0].trim(); -} - -/** - * Parses comments in file to extract file-specific config of rules, globals - * and environments and merges them with global config; also code blocks - * where reporting is disabled or enabled and merges them with reporting config. - * @param {string} filename The file being checked. - * @param {ASTNode} ast The top node of the AST. - * @param {function(string): {create: Function}} ruleMapper A map from rule IDs to defined rules - * @param {string|null} warnInlineConfig If a string then it should warn directive comments as disabled. The string value is the config name what the setting came from. - * @returns {{configuredRules: Object, enabledGlobals: {value:string,comment:Token}[], exportedVariables: Object, problems: Problem[], disableDirectives: DisableDirective[]}} - * A collection of the directive comments that were found, along with any problems that occurred when parsing - */ -function getDirectiveComments(filename, ast, ruleMapper, warnInlineConfig) { - const configuredRules = {}; - const enabledGlobals = Object.create(null); - const exportedVariables = {}; - const problems = []; - const disableDirectives = []; - const validator = new ConfigValidator({ - builtInRules: Rules - }); - - ast.comments.filter(token => token.type !== "Shebang").forEach(comment => { - const trimmedCommentText = stripDirectiveComment(comment.value); - const match = /^(eslint(?:-env|-enable|-disable(?:(?:-next)?-line)?)?|exported|globals?)(?:\s|$)/u.exec(trimmedCommentText); - - if (!match) { - return; - } - const directiveText = match[1]; - const lineCommentSupported = /^eslint-disable-(next-)?line$/u.test(directiveText); - - if (comment.type === "Line" && !lineCommentSupported) { - return; - } - - if (warnInlineConfig) { - const kind = comment.type === "Block" ? `/*${directiveText}*/` : `//${directiveText}`; - - problems.push(createLintingProblem({ - ruleId: null, - message: `'${kind}' has no effect because you have 'noInlineConfig' setting in ${warnInlineConfig}.`, - loc: comment.loc, - severity: 1 - })); - return; - } - - if (lineCommentSupported && comment.loc.start.line !== comment.loc.end.line) { - const message = `${directiveText} comment should not span multiple lines.`; - - problems.push(createLintingProblem({ - ruleId: null, - message, - loc: comment.loc - })); - return; - } - - const directiveValue = trimmedCommentText.slice(match.index + directiveText.length); - - switch (directiveText) { - case "eslint-disable": - case "eslint-enable": - case "eslint-disable-next-line": - case "eslint-disable-line": { - const directiveType = directiveText.slice("eslint-".length); - const options = { type: directiveType, loc: comment.loc, value: directiveValue, ruleMapper }; - const { directives, directiveProblems } = createDisableDirectives(options); - - disableDirectives.push(...directives); - problems.push(...directiveProblems); - break; - } - - case "exported": - Object.assign(exportedVariables, commentParser.parseStringConfig(directiveValue, comment)); - break; - - case "globals": - case "global": - for (const [id, { value }] of Object.entries(commentParser.parseStringConfig(directiveValue, comment))) { - let normalizedValue; - - try { - normalizedValue = ConfigOps.normalizeConfigGlobal(value); - } catch (err) { - problems.push(createLintingProblem({ - ruleId: null, - loc: comment.loc, - message: err.message - })); - continue; - } - - if (enabledGlobals[id]) { - enabledGlobals[id].comments.push(comment); - enabledGlobals[id].value = normalizedValue; - } else { - enabledGlobals[id] = { - comments: [comment], - value: normalizedValue - }; - } - } - break; - - case "eslint": { - const parseResult = commentParser.parseJsonConfig(directiveValue, comment.loc); - - if (parseResult.success) { - Object.keys(parseResult.config).forEach(name => { - const rule = ruleMapper(name); - const ruleValue = parseResult.config[name]; - - if (rule === null) { - problems.push(createLintingProblem({ ruleId: name, loc: comment.loc })); - return; - } - - try { - validator.validateRuleOptions(rule, name, ruleValue); - } catch (err) { - problems.push(createLintingProblem({ - ruleId: name, - message: err.message, - loc: comment.loc - })); - - // do not apply the config, if found invalid options. - return; - } - - configuredRules[name] = ruleValue; - }); - } else { - problems.push(parseResult.error); - } - - break; - } - - // no default - } - }); - - return { - configuredRules, - enabledGlobals, - exportedVariables, - problems, - disableDirectives - }; -} - -/** - * Normalize ECMAScript version from the initial config - * @param {number} ecmaVersion ECMAScript version from the initial config - * @returns {number} normalized ECMAScript version - */ -function normalizeEcmaVersion(ecmaVersion) { - - /* - * Calculate ECMAScript edition number from official year version starting with - * ES2015, which corresponds with ES6 (or a difference of 2009). - */ - return ecmaVersion >= 2015 ? ecmaVersion - 2009 : ecmaVersion; -} - -const eslintEnvPattern = /\/\*\s*eslint-env\s(.+?)\*\//gu; - -/** - * Checks whether or not there is a comment which has "eslint-env *" in a given text. - * @param {string} text A source code text to check. - * @returns {Object|null} A result of parseListConfig() with "eslint-env *" comment. - */ -function findEslintEnv(text) { - let match, retv; - - eslintEnvPattern.lastIndex = 0; - - while ((match = eslintEnvPattern.exec(text)) !== null) { - retv = Object.assign( - retv || {}, - commentParser.parseListConfig(stripDirectiveComment(match[1])) - ); - } - - return retv; -} - -/** - * Convert "/path/to/" to "". - * `CLIEngine#executeOnText()` method gives "/path/to/" if the filename - * was omitted because `configArray.extractConfig()` requires an absolute path. - * But the linter should pass `` to `RuleContext#getFilename()` in that - * case. - * Also, code blocks can have their virtual filename. If the parent filename was - * ``, the virtual filename is `/0_foo.js` or something like (i.e., - * it's not an absolute path). - * @param {string} filename The filename to normalize. - * @returns {string} The normalized filename. - */ -function normalizeFilename(filename) { - const parts = filename.split(path.sep); - const index = parts.lastIndexOf(""); - - return index === -1 ? filename : parts.slice(index).join(path.sep); -} - -/** - * Normalizes the possible options for `linter.verify` and `linter.verifyAndFix` to a - * consistent shape. - * @param {VerifyOptions} providedOptions Options - * @param {ConfigData} config Config. - * @returns {Required & InternalOptions} Normalized options - */ -function normalizeVerifyOptions(providedOptions, config) { - const disableInlineConfig = config.noInlineConfig === true; - const ignoreInlineConfig = providedOptions.allowInlineConfig === false; - const configNameOfNoInlineConfig = config.configNameOfNoInlineConfig - ? ` (${config.configNameOfNoInlineConfig})` - : ""; - - let reportUnusedDisableDirectives = providedOptions.reportUnusedDisableDirectives; - - if (typeof reportUnusedDisableDirectives === "boolean") { - reportUnusedDisableDirectives = reportUnusedDisableDirectives ? "error" : "off"; - } - if (typeof reportUnusedDisableDirectives !== "string") { - reportUnusedDisableDirectives = config.reportUnusedDisableDirectives ? "warn" : "off"; - } - - return { - filename: normalizeFilename(providedOptions.filename || ""), - allowInlineConfig: !ignoreInlineConfig, - warnInlineConfig: disableInlineConfig && !ignoreInlineConfig - ? `your config${configNameOfNoInlineConfig}` - : null, - reportUnusedDisableDirectives, - disableFixes: Boolean(providedOptions.disableFixes) - }; -} - -/** - * Combines the provided parserOptions with the options from environments - * @param {string} parserName The parser name which uses this options. - * @param {ParserOptions} providedOptions The provided 'parserOptions' key in a config - * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments - * @returns {ParserOptions} Resulting parser options after merge - */ -function resolveParserOptions(parserName, providedOptions, enabledEnvironments) { - const parserOptionsFromEnv = enabledEnvironments - .filter(env => env.parserOptions) - .reduce((parserOptions, env) => lodash.merge(parserOptions, env.parserOptions), {}); - const mergedParserOptions = lodash.merge(parserOptionsFromEnv, providedOptions || {}); - const isModule = mergedParserOptions.sourceType === "module"; - - if (isModule) { - - /* - * can't have global return inside of modules - * TODO: espree validate parserOptions.globalReturn when sourceType is setting to module.(@aladdin-add) - */ - mergedParserOptions.ecmaFeatures = Object.assign({}, mergedParserOptions.ecmaFeatures, { globalReturn: false }); - } - - /* - * TODO: @aladdin-add - * 1. for a 3rd-party parser, do not normalize parserOptions - * 2. for espree, no need to do this (espree will do it) - */ - mergedParserOptions.ecmaVersion = normalizeEcmaVersion(mergedParserOptions.ecmaVersion); - - return mergedParserOptions; -} - -/** - * Combines the provided globals object with the globals from environments - * @param {Record} providedGlobals The 'globals' key in a config - * @param {Environment[]} enabledEnvironments The environments enabled in configuration and with inline comments - * @returns {Record} The resolved globals object - */ -function resolveGlobals(providedGlobals, enabledEnvironments) { - return Object.assign( - {}, - ...enabledEnvironments.filter(env => env.globals).map(env => env.globals), - providedGlobals - ); -} - -/** - * Strips Unicode BOM from a given text. - * @param {string} text A text to strip. - * @returns {string} The stripped text. - */ -function stripUnicodeBOM(text) { - - /* - * Check Unicode BOM. - * In JavaScript, string data is stored as UTF-16, so BOM is 0xFEFF. - * http://www.ecma-international.org/ecma-262/6.0/#sec-unicode-format-control-characters - */ - if (text.charCodeAt(0) === 0xFEFF) { - return text.slice(1); - } - return text; -} - -/** - * Get the options for a rule (not including severity), if any - * @param {Array|number} ruleConfig rule configuration - * @returns {Array} of rule options, empty Array if none - */ -function getRuleOptions(ruleConfig) { - if (Array.isArray(ruleConfig)) { - return ruleConfig.slice(1); - } - return []; - -} - -/** - * Analyze scope of the given AST. - * @param {ASTNode} ast The `Program` node to analyze. - * @param {ParserOptions} parserOptions The parser options. - * @param {Record} visitorKeys The visitor keys. - * @returns {ScopeManager} The analysis result. - */ -function analyzeScope(ast, parserOptions, visitorKeys) { - const ecmaFeatures = parserOptions.ecmaFeatures || {}; - const ecmaVersion = parserOptions.ecmaVersion || 5; - - return eslintScope.analyze(ast, { - ignoreEval: true, - nodejsScope: ecmaFeatures.globalReturn, - impliedStrict: ecmaFeatures.impliedStrict, - ecmaVersion, - sourceType: parserOptions.sourceType || "script", - childVisitorKeys: visitorKeys || evk.KEYS, - fallback: Traverser.getKeys - }); -} - -/** - * Parses text into an AST. Moved out here because the try-catch prevents - * optimization of functions, so it's best to keep the try-catch as isolated - * as possible - * @param {string} text The text to parse. - * @param {Parser} parser The parser to parse. - * @param {ParserOptions} providedParserOptions Options to pass to the parser - * @param {string} filePath The path to the file being parsed. - * @returns {{success: false, error: Problem}|{success: true, sourceCode: SourceCode}} - * An object containing the AST and parser services if parsing was successful, or the error if parsing failed - * @private - */ -function parse(text, parser, providedParserOptions, filePath) { - const textToParse = stripUnicodeBOM(text).replace(astUtils.shebangPattern, (match, captured) => `//${captured}`); - const parserOptions = Object.assign({}, providedParserOptions, { - loc: true, - range: true, - raw: true, - tokens: true, - comment: true, - eslintVisitorKeys: true, - eslintScopeManager: true, - filePath - }); - - /* - * Check for parsing errors first. If there's a parsing error, nothing - * else can happen. However, a parsing error does not throw an error - * from this method - it's just considered a fatal error message, a - * problem that ESLint identified just like any other. - */ - try { - const parseResult = (typeof parser.parseForESLint === "function") - ? parser.parseForESLint(textToParse, parserOptions) - : { ast: parser.parse(textToParse, parserOptions) }; - const ast = parseResult.ast; - const parserServices = parseResult.services || {}; - const visitorKeys = parseResult.visitorKeys || evk.KEYS; - const scopeManager = parseResult.scopeManager || analyzeScope(ast, parserOptions, visitorKeys); - - return { - success: true, - - /* - * Save all values that `parseForESLint()` returned. - * If a `SourceCode` object is given as the first parameter instead of source code text, - * linter skips the parsing process and reuses the source code object. - * In that case, linter needs all the values that `parseForESLint()` returned. - */ - sourceCode: new SourceCode({ - text, - ast, - parserServices, - scopeManager, - visitorKeys - }) - }; - } catch (ex) { - - // If the message includes a leading line number, strip it: - const message = `Parsing error: ${ex.message.replace(/^line \d+:/iu, "").trim()}`; - - debug("%s\n%s", message, ex.stack); - - return { - success: false, - error: { - ruleId: null, - fatal: true, - severity: 2, - message, - line: ex.lineNumber, - column: ex.column - } - }; - } -} - -/** - * Gets the scope for the current node - * @param {ScopeManager} scopeManager The scope manager for this AST - * @param {ASTNode} currentNode The node to get the scope of - * @returns {eslint-scope.Scope} The scope information for this node - */ -function getScope(scopeManager, currentNode) { - - // On Program node, get the outermost scope to avoid return Node.js special function scope or ES modules scope. - const inner = currentNode.type !== "Program"; - - for (let node = currentNode; node; node = node.parent) { - const scope = scopeManager.acquire(node, inner); - - if (scope) { - if (scope.type === "function-expression-name") { - return scope.childScopes[0]; - } - return scope; - } - } - - return scopeManager.scopes[0]; -} - -/** - * Marks a variable as used in the current scope - * @param {ScopeManager} scopeManager The scope manager for this AST. The scope may be mutated by this function. - * @param {ASTNode} currentNode The node currently being traversed - * @param {Object} parserOptions The options used to parse this text - * @param {string} name The name of the variable that should be marked as used. - * @returns {boolean} True if the variable was found and marked as used, false if not. - */ -function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) { - const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn; - const specialScope = hasGlobalReturn || parserOptions.sourceType === "module"; - const currentScope = getScope(scopeManager, currentNode); - - // Special Node.js scope means we need to start one level deeper - const initialScope = currentScope.type === "global" && specialScope ? currentScope.childScopes[0] : currentScope; - - for (let scope = initialScope; scope; scope = scope.upper) { - const variable = scope.variables.find(scopeVar => scopeVar.name === name); - - if (variable) { - variable.eslintUsed = true; - return true; - } - } - - return false; -} - -/** - * Runs a rule, and gets its listeners - * @param {Rule} rule A normalized rule with a `create` method - * @param {Context} ruleContext The context that should be passed to the rule - * @returns {Object} A map of selector listeners provided by the rule - */ -function createRuleListeners(rule, ruleContext) { - try { - return rule.create(ruleContext); - } catch (ex) { - ex.message = `Error while loading rule '${ruleContext.id}': ${ex.message}`; - throw ex; - } -} - -/** - * Gets all the ancestors of a given node - * @param {ASTNode} node The node - * @returns {ASTNode[]} All the ancestor nodes in the AST, not including the provided node, starting - * from the root node and going inwards to the parent node. - */ -function getAncestors(node) { - const ancestorsStartingAtParent = []; - - for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { - ancestorsStartingAtParent.push(ancestor); - } - - return ancestorsStartingAtParent.reverse(); -} - -// methods that exist on SourceCode object -const DEPRECATED_SOURCECODE_PASSTHROUGHS = { - getSource: "getText", - getSourceLines: "getLines", - getAllComments: "getAllComments", - getNodeByRangeIndex: "getNodeByRangeIndex", - getComments: "getComments", - getCommentsBefore: "getCommentsBefore", - getCommentsAfter: "getCommentsAfter", - getCommentsInside: "getCommentsInside", - getJSDocComment: "getJSDocComment", - getFirstToken: "getFirstToken", - getFirstTokens: "getFirstTokens", - getLastToken: "getLastToken", - getLastTokens: "getLastTokens", - getTokenAfter: "getTokenAfter", - getTokenBefore: "getTokenBefore", - getTokenByRangeStart: "getTokenByRangeStart", - getTokens: "getTokens", - getTokensAfter: "getTokensAfter", - getTokensBefore: "getTokensBefore", - getTokensBetween: "getTokensBetween" -}; - -const BASE_TRAVERSAL_CONTEXT = Object.freeze( - Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).reduce( - (contextInfo, methodName) => - Object.assign(contextInfo, { - [methodName](...args) { - return this.getSourceCode()[DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]](...args); - } - }), - {} - ) -); - -/** - * Runs the given rules on the given SourceCode object - * @param {SourceCode} sourceCode A SourceCode object for the given text - * @param {Object} configuredRules The rules configuration - * @param {function(string): Rule} ruleMapper A mapper function from rule names to rules - * @param {Object} parserOptions The options that were passed to the parser - * @param {string} parserName The name of the parser in the config - * @param {Object} settings The settings that were enabled in the config - * @param {string} filename The reported filename of the code - * @param {boolean} disableFixes If true, it doesn't make `fix` properties. - * @param {string | undefined} cwd cwd of the cli - * @returns {Problem[]} An array of reported problems - */ -function runRules(sourceCode, configuredRules, ruleMapper, parserOptions, parserName, settings, filename, disableFixes, cwd) { - const emitter = createEmitter(); - const nodeQueue = []; - let currentNode = sourceCode.ast; - - Traverser.traverse(sourceCode.ast, { - enter(node, parent) { - node.parent = parent; - nodeQueue.push({ isEntering: true, node }); - }, - leave(node) { - nodeQueue.push({ isEntering: false, node }); - }, - visitorKeys: sourceCode.visitorKeys - }); - - /* - * Create a frozen object with the ruleContext properties and methods that are shared by all rules. - * All rule contexts will inherit from this object. This avoids the performance penalty of copying all the - * properties once for each rule. - */ - const sharedTraversalContext = Object.freeze( - Object.assign( - Object.create(BASE_TRAVERSAL_CONTEXT), - { - getAncestors: () => getAncestors(currentNode), - getDeclaredVariables: sourceCode.scopeManager.getDeclaredVariables.bind(sourceCode.scopeManager), - getCwd: () => cwd, - getFilename: () => filename, - getScope: () => getScope(sourceCode.scopeManager, currentNode), - getSourceCode: () => sourceCode, - markVariableAsUsed: name => markVariableAsUsed(sourceCode.scopeManager, currentNode, parserOptions, name), - parserOptions, - parserPath: parserName, - parserServices: sourceCode.parserServices, - settings - } - ) - ); - - - const lintingProblems = []; - - Object.keys(configuredRules).forEach(ruleId => { - const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]); - - // not load disabled rules - if (severity === 0) { - return; - } - - const rule = ruleMapper(ruleId); - - if (rule === null) { - lintingProblems.push(createLintingProblem({ ruleId })); - return; - } - - const messageIds = rule.meta && rule.meta.messages; - let reportTranslator = null; - const ruleContext = Object.freeze( - Object.assign( - Object.create(sharedTraversalContext), - { - id: ruleId, - options: getRuleOptions(configuredRules[ruleId]), - report(...args) { - - /* - * Create a report translator lazily. - * In a vast majority of cases, any given rule reports zero errors on a given - * piece of code. Creating a translator lazily avoids the performance cost of - * creating a new translator function for each rule that usually doesn't get - * called. - * - * Using lazy report translators improves end-to-end performance by about 3% - * with Node 8.4.0. - */ - if (reportTranslator === null) { - reportTranslator = createReportTranslator({ - ruleId, - severity, - sourceCode, - messageIds, - disableFixes - }); - } - const problem = reportTranslator(...args); - - if (problem.fix && rule.meta && !rule.meta.fixable) { - throw new Error("Fixable rules should export a `meta.fixable` property."); - } - lintingProblems.push(problem); - } - } - ) - ); - - const ruleListeners = createRuleListeners(rule, ruleContext); - - // add all the selectors from the rule as listeners - Object.keys(ruleListeners).forEach(selector => { - emitter.on( - selector, - timing.enabled - ? timing.time(ruleId, ruleListeners[selector]) - : ruleListeners[selector] - ); - }); - }); - - // only run code path analyzer if the top level node is "Program", skip otherwise - const eventGenerator = nodeQueue[0].node.type === "Program" ? new CodePathAnalyzer(new NodeEventGenerator(emitter)) : new NodeEventGenerator(emitter); - - nodeQueue.forEach(traversalInfo => { - currentNode = traversalInfo.node; - - try { - if (traversalInfo.isEntering) { - eventGenerator.enterNode(currentNode); - } else { - eventGenerator.leaveNode(currentNode); - } - } catch (err) { - err.currentNode = currentNode; - throw err; - } - }); - - return lintingProblems; -} - -/** - * Ensure the source code to be a string. - * @param {string|SourceCode} textOrSourceCode The text or source code object. - * @returns {string} The source code text. - */ -function ensureText(textOrSourceCode) { - if (typeof textOrSourceCode === "object") { - const { hasBOM, text } = textOrSourceCode; - const bom = hasBOM ? "\uFEFF" : ""; - - return bom + text; - } - - return String(textOrSourceCode); -} - -/** - * Get an environment. - * @param {LinterInternalSlots} slots The internal slots of Linter. - * @param {string} envId The environment ID to get. - * @returns {Environment|null} The environment. - */ -function getEnv(slots, envId) { - return ( - (slots.lastConfigArray && slots.lastConfigArray.pluginEnvironments.get(envId)) || - BuiltInEnvironments.get(envId) || - null - ); -} - -/** - * Get a rule. - * @param {LinterInternalSlots} slots The internal slots of Linter. - * @param {string} ruleId The rule ID to get. - * @returns {Rule|null} The rule. - */ -function getRule(slots, ruleId) { - return ( - (slots.lastConfigArray && slots.lastConfigArray.pluginRules.get(ruleId)) || - slots.ruleMap.get(ruleId) - ); -} - -/** - * Normalize the value of the cwd - * @param {string | undefined} cwd raw value of the cwd, path to a directory that should be considered as the current working directory, can be undefined. - * @returns {string | undefined} normalized cwd - */ -function normalizeCwd(cwd) { - if (cwd) { - return cwd; - } - if (typeof process === "object") { - return process.cwd(); - } - - // It's more explicit to assign the undefined - // eslint-disable-next-line no-undefined - return undefined; -} - -/** - * The map to store private data. - * @type {WeakMap} - */ -const internalSlotsMap = new WeakMap(); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Object that is responsible for verifying JavaScript text - * @name eslint - */ -class Linter { - - /** - * Initialize the Linter. - * @param {Object} [config] the config object - * @param {string} [config.cwd] path to a directory that should be considered as the current working directory, can be undefined. - */ - constructor({ cwd } = {}) { - internalSlotsMap.set(this, { - cwd: normalizeCwd(cwd), - lastConfigArray: null, - lastSourceCode: null, - parserMap: new Map([["espree", espree]]), - ruleMap: new Rules() - }); - - this.version = pkg.version; - } - - /** - * Getter for package version. - * @static - * @returns {string} The version from package.json. - */ - static get version() { - return pkg.version; - } - - /** - * Same as linter.verify, except without support for processors. - * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. - * @param {ConfigData} providedConfig An ESLintConfig instance to configure everything. - * @param {VerifyOptions} [providedOptions] The optional filename of the file being checked. - * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages. - */ - _verifyWithoutProcessors(textOrSourceCode, providedConfig, providedOptions) { - const slots = internalSlotsMap.get(this); - const config = providedConfig || {}; - const options = normalizeVerifyOptions(providedOptions, config); - let text; - - // evaluate arguments - if (typeof textOrSourceCode === "string") { - slots.lastSourceCode = null; - text = textOrSourceCode; - } else { - slots.lastSourceCode = textOrSourceCode; - text = textOrSourceCode.text; - } - - // Resolve parser. - let parserName = DEFAULT_PARSER_NAME; - let parser = espree; - - if (typeof config.parser === "object" && config.parser !== null) { - parserName = config.parser.filePath; - parser = config.parser.definition; - } else if (typeof config.parser === "string") { - if (!slots.parserMap.has(config.parser)) { - return [{ - ruleId: null, - fatal: true, - severity: 2, - message: `Configured parser '${config.parser}' was not found.`, - line: 0, - column: 0 - }]; - } - parserName = config.parser; - parser = slots.parserMap.get(config.parser); - } - - // search and apply "eslint-env *". - const envInFile = options.allowInlineConfig && !options.warnInlineConfig - ? findEslintEnv(text) - : {}; - const resolvedEnvConfig = Object.assign({ builtin: true }, config.env, envInFile); - const enabledEnvs = Object.keys(resolvedEnvConfig) - .filter(envName => resolvedEnvConfig[envName]) - .map(envName => getEnv(slots, envName)) - .filter(env => env); - - const parserOptions = resolveParserOptions(parserName, config.parserOptions || {}, enabledEnvs); - const configuredGlobals = resolveGlobals(config.globals || {}, enabledEnvs); - const settings = config.settings || {}; - - if (!slots.lastSourceCode) { - const parseResult = parse( - text, - parser, - parserOptions, - options.filename - ); - - if (!parseResult.success) { - return [parseResult.error]; - } - - slots.lastSourceCode = parseResult.sourceCode; - } else { - - /* - * If the given source code object as the first argument does not have scopeManager, analyze the scope. - * This is for backward compatibility (SourceCode is frozen so it cannot rebind). - */ - if (!slots.lastSourceCode.scopeManager) { - slots.lastSourceCode = new SourceCode({ - text: slots.lastSourceCode.text, - ast: slots.lastSourceCode.ast, - parserServices: slots.lastSourceCode.parserServices, - visitorKeys: slots.lastSourceCode.visitorKeys, - scopeManager: analyzeScope(slots.lastSourceCode.ast, parserOptions) - }); - } - } - - const sourceCode = slots.lastSourceCode; - const commentDirectives = options.allowInlineConfig - ? getDirectiveComments(options.filename, sourceCode.ast, ruleId => getRule(slots, ruleId), options.warnInlineConfig) - : { configuredRules: {}, enabledGlobals: {}, exportedVariables: {}, problems: [], disableDirectives: [] }; - - // augment global scope with declared global variables - addDeclaredGlobals( - sourceCode.scopeManager.scopes[0], - configuredGlobals, - { exportedVariables: commentDirectives.exportedVariables, enabledGlobals: commentDirectives.enabledGlobals } - ); - - const configuredRules = Object.assign({}, config.rules, commentDirectives.configuredRules); - - let lintingProblems; - - try { - lintingProblems = runRules( - sourceCode, - configuredRules, - ruleId => getRule(slots, ruleId), - parserOptions, - parserName, - settings, - options.filename, - options.disableFixes, - slots.cwd - ); - } catch (err) { - err.message += `\nOccurred while linting ${options.filename}`; - debug("An error occurred while traversing"); - debug("Filename:", options.filename); - if (err.currentNode) { - const { line } = err.currentNode.loc.start; - - debug("Line:", line); - err.message += `:${line}`; - } - debug("Parser Options:", parserOptions); - debug("Parser Path:", parserName); - debug("Settings:", settings); - throw err; - } - - return applyDisableDirectives({ - directives: commentDirectives.disableDirectives, - problems: lintingProblems - .concat(commentDirectives.problems) - .sort((problemA, problemB) => problemA.line - problemB.line || problemA.column - problemB.column), - reportUnusedDisableDirectives: options.reportUnusedDisableDirectives - }); - } - - /** - * Verifies the text against the rules specified by the second argument. - * @param {string|SourceCode} textOrSourceCode The text to parse or a SourceCode object. - * @param {ConfigData|ConfigArray} config An ESLintConfig instance to configure everything. - * @param {(string|(VerifyOptions&ProcessorOptions))} [filenameOrOptions] The optional filename of the file being checked. - * If this is not set, the filename will default to '' in the rule context. If - * an object, then it has "filename", "allowInlineConfig", and some properties. - * @returns {LintMessage[]} The results as an array of messages or an empty array if no messages. - */ - verify(textOrSourceCode, config, filenameOrOptions) { - debug("Verify"); - const options = typeof filenameOrOptions === "string" - ? { filename: filenameOrOptions } - : filenameOrOptions || {}; - - // CLIEngine passes a `ConfigArray` object. - if (config && typeof config.extractConfig === "function") { - return this._verifyWithConfigArray(textOrSourceCode, config, options); - } - - /* - * `Linter` doesn't support `overrides` property in configuration. - * So we cannot apply multiple processors. - */ - if (options.preprocess || options.postprocess) { - return this._verifyWithProcessor(textOrSourceCode, config, options); - } - return this._verifyWithoutProcessors(textOrSourceCode, config, options); - } - - /** - * Verify a given code with `ConfigArray`. - * @param {string|SourceCode} textOrSourceCode The source code. - * @param {ConfigArray} configArray The config array. - * @param {VerifyOptions&ProcessorOptions} options The options. - * @returns {LintMessage[]} The found problems. - */ - _verifyWithConfigArray(textOrSourceCode, configArray, options) { - debug("With ConfigArray: %s", options.filename); - - // Store the config array in order to get plugin envs and rules later. - internalSlotsMap.get(this).lastConfigArray = configArray; - - // Extract the final config for this file. - const config = configArray.extractConfig(options.filename); - const processor = - config.processor && - configArray.pluginProcessors.get(config.processor); - - // Verify. - if (processor) { - debug("Apply the processor: %o", config.processor); - const { preprocess, postprocess, supportsAutofix } = processor; - const disableFixes = options.disableFixes || !supportsAutofix; - - return this._verifyWithProcessor( - textOrSourceCode, - config, - { ...options, disableFixes, postprocess, preprocess }, - configArray - ); - } - return this._verifyWithoutProcessors(textOrSourceCode, config, options); - } - - /** - * Verify with a processor. - * @param {string|SourceCode} textOrSourceCode The source code. - * @param {ConfigData|ExtractedConfig} config The config array. - * @param {VerifyOptions&ProcessorOptions} options The options. - * @param {ConfigArray} [configForRecursive] The `ConfigArray` object to apply multiple processors recursively. - * @returns {LintMessage[]} The found problems. - */ - _verifyWithProcessor(textOrSourceCode, config, options, configForRecursive) { - const filename = options.filename || ""; - const filenameToExpose = normalizeFilename(filename); - const text = ensureText(textOrSourceCode); - const preprocess = options.preprocess || (rawText => [rawText]); - const postprocess = options.postprocess || lodash.flatten; - const filterCodeBlock = - options.filterCodeBlock || - (blockFilename => blockFilename.endsWith(".js")); - const originalExtname = path.extname(filename); - const messageLists = preprocess(text, filenameToExpose).map((block, i) => { - debug("A code block was found: %o", block.filename || "(unnamed)"); - - // Keep the legacy behavior. - if (typeof block === "string") { - return this._verifyWithoutProcessors(block, config, options); - } - - const blockText = block.text; - const blockName = path.join(filename, `${i}_${block.filename}`); - - // Skip this block if filtered. - if (!filterCodeBlock(blockName, blockText)) { - debug("This code block was skipped."); - return []; - } - - // Resolve configuration again if the file extension was changed. - if (configForRecursive && path.extname(blockName) !== originalExtname) { - debug("Resolving configuration again because the file extension was changed."); - return this._verifyWithConfigArray( - blockText, - configForRecursive, - { ...options, filename: blockName } - ); - } - - // Does lint. - return this._verifyWithoutProcessors( - blockText, - config, - { ...options, filename: blockName } - ); - }); - - return postprocess(messageLists, filenameToExpose); - } - - /** - * Gets the SourceCode object representing the parsed source. - * @returns {SourceCode} The SourceCode object. - */ - getSourceCode() { - return internalSlotsMap.get(this).lastSourceCode; - } - - /** - * Defines a new linting rule. - * @param {string} ruleId A unique rule identifier - * @param {Function | Rule} ruleModule Function from context to object mapping AST node types to event handlers - * @returns {void} - */ - defineRule(ruleId, ruleModule) { - internalSlotsMap.get(this).ruleMap.define(ruleId, ruleModule); - } - - /** - * Defines many new linting rules. - * @param {Record} rulesToDefine map from unique rule identifier to rule - * @returns {void} - */ - defineRules(rulesToDefine) { - Object.getOwnPropertyNames(rulesToDefine).forEach(ruleId => { - this.defineRule(ruleId, rulesToDefine[ruleId]); - }); - } - - /** - * Gets an object with all loaded rules. - * @returns {Map} All loaded rules - */ - getRules() { - const { lastConfigArray, ruleMap } = internalSlotsMap.get(this); - - return new Map(function *() { - yield* ruleMap; - - if (lastConfigArray) { - yield* lastConfigArray.pluginRules; - } - }()); - } - - /** - * Define a new parser module - * @param {string} parserId Name of the parser - * @param {Parser} parserModule The parser object - * @returns {void} - */ - defineParser(parserId, parserModule) { - internalSlotsMap.get(this).parserMap.set(parserId, parserModule); - } - - /** - * Performs multiple autofix passes over the text until as many fixes as possible - * have been applied. - * @param {string} text The source text to apply fixes to. - * @param {ConfigData|ConfigArray} config The ESLint config object to use. - * @param {VerifyOptions&ProcessorOptions&FixOptions} options The ESLint options object to use. - * @returns {{fixed:boolean,messages:LintMessage[],output:string}} The result of the fix operation as returned from the - * SourceCodeFixer. - */ - verifyAndFix(text, config, options) { - let messages = [], - fixedResult, - fixed = false, - passNumber = 0, - currentText = text; - const debugTextDescription = options && options.filename || `${text.slice(0, 10)}...`; - const shouldFix = options && typeof options.fix !== "undefined" ? options.fix : true; - - /** - * This loop continues until one of the following is true: - * - * 1. No more fixes have been applied. - * 2. Ten passes have been made. - * - * That means anytime a fix is successfully applied, there will be another pass. - * Essentially, guaranteeing a minimum of two passes. - */ - do { - passNumber++; - - debug(`Linting code for ${debugTextDescription} (pass ${passNumber})`); - messages = this.verify(currentText, config, options); - - debug(`Generating fixed text for ${debugTextDescription} (pass ${passNumber})`); - fixedResult = SourceCodeFixer.applyFixes(currentText, messages, shouldFix); - - /* - * stop if there are any syntax errors. - * 'fixedResult.output' is a empty string. - */ - if (messages.length === 1 && messages[0].fatal) { - break; - } - - // keep track if any fixes were ever applied - important for return value - fixed = fixed || fixedResult.fixed; - - // update to use the fixed output instead of the original text - currentText = fixedResult.output; - - } while ( - fixedResult.fixed && - passNumber < MAX_AUTOFIX_PASSES - ); - - /* - * If the last result had fixes, we need to lint again to be sure we have - * the most up-to-date information. - */ - if (fixedResult.fixed) { - fixedResult.messages = this.verify(currentText, config, options); - } - - // ensure the last result properly reflects if fixes were done - fixedResult.fixed = fixed; - fixedResult.output = currentText; - - return fixedResult; - } -} - -module.exports = { - Linter, - - /** - * Get the internal slots of a given Linter instance for tests. - * @param {Linter} instance The Linter instance to get. - * @returns {LinterInternalSlots} The internal slots. - */ - getLinterInternalSlots(instance) { - return internalSlotsMap.get(instance); - } -}; diff --git a/tools/node_modules/eslint/lib/linter/node-event-generator.js b/tools/node_modules/eslint/lib/linter/node-event-generator.js deleted file mode 100644 index 6f3b2513998dcd3e8de9fabb7989bca0a80e36dd..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/node-event-generator.js +++ /dev/null @@ -1,311 +0,0 @@ -/** - * @fileoverview The event generator for AST nodes. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const esquery = require("esquery"); -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * An object describing an AST selector - * @typedef {Object} ASTSelector - * @property {string} rawSelector The string that was parsed into this selector - * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering - * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector - * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match, - * or `null` if all node types could cause a match - * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector - * @property {number} identifierCount The total number of identifier queries in this selector - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the possible types of a selector - * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector - * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it - */ -function getPossibleTypes(parsedSelector) { - switch (parsedSelector.type) { - case "identifier": - return [parsedSelector.value]; - - case "matches": { - const typesForComponents = parsedSelector.selectors.map(getPossibleTypes); - - if (typesForComponents.every(Boolean)) { - return lodash.union(...typesForComponents); - } - return null; - } - - case "compound": { - const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent); - - // If all of the components could match any type, then the compound could also match any type. - if (!typesForComponents.length) { - return null; - } - - /* - * If at least one of the components could only match a particular type, the compound could only match - * the intersection of those types. - */ - return lodash.intersection(...typesForComponents); - } - - case "child": - case "descendant": - case "sibling": - case "adjacent": - return getPossibleTypes(parsedSelector.right); - - default: - return null; - - } -} - -/** - * Counts the number of class, pseudo-class, and attribute queries in this selector - * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior - * @returns {number} The number of class, pseudo-class, and attribute queries in this selector - */ -function countClassAttributes(parsedSelector) { - switch (parsedSelector.type) { - case "child": - case "descendant": - case "sibling": - case "adjacent": - return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right); - - case "compound": - case "not": - case "matches": - return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0); - - case "attribute": - case "field": - case "nth-child": - case "nth-last-child": - return 1; - - default: - return 0; - } -} - -/** - * Counts the number of identifier queries in this selector - * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior - * @returns {number} The number of identifier queries - */ -function countIdentifiers(parsedSelector) { - switch (parsedSelector.type) { - case "child": - case "descendant": - case "sibling": - case "adjacent": - return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right); - - case "compound": - case "not": - case "matches": - return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0); - - case "identifier": - return 1; - - default: - return 0; - } -} - -/** - * Compares the specificity of two selector objects, with CSS-like rules. - * @param {ASTSelector} selectorA An AST selector descriptor - * @param {ASTSelector} selectorB Another AST selector descriptor - * @returns {number} - * a value less than 0 if selectorA is less specific than selectorB - * a value greater than 0 if selectorA is more specific than selectorB - * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically - * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically - */ -function compareSpecificity(selectorA, selectorB) { - return selectorA.attributeCount - selectorB.attributeCount || - selectorA.identifierCount - selectorB.identifierCount || - (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1); -} - -/** - * Parses a raw selector string, and throws a useful error if parsing fails. - * @param {string} rawSelector A raw AST selector - * @returns {Object} An object (from esquery) describing the matching behavior of this selector - * @throws {Error} An error if the selector is invalid - */ -function tryParseSelector(rawSelector) { - try { - return esquery.parse(rawSelector.replace(/:exit$/u, "")); - } catch (err) { - if (err.location && err.location.start && typeof err.location.start.offset === "number") { - throw new SyntaxError(`Syntax error in selector "${rawSelector}" at position ${err.location.start.offset}: ${err.message}`); - } - throw err; - } -} - -/** - * Parses a raw selector string, and returns the parsed selector along with specificity and type information. - * @param {string} rawSelector A raw AST selector - * @returns {ASTSelector} A selector descriptor - */ -const parseSelector = lodash.memoize(rawSelector => { - const parsedSelector = tryParseSelector(rawSelector); - - return { - rawSelector, - isExit: rawSelector.endsWith(":exit"), - parsedSelector, - listenerTypes: getPossibleTypes(parsedSelector), - attributeCount: countClassAttributes(parsedSelector), - identifierCount: countIdentifiers(parsedSelector) - }; -}); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * The event generator for AST nodes. - * This implements below interface. - * - * ```ts - * interface EventGenerator { - * emitter: SafeEmitter; - * enterNode(node: ASTNode): void; - * leaveNode(node: ASTNode): void; - * } - * ``` - */ -class NodeEventGenerator { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {SafeEmitter} emitter - * An SafeEmitter which is the destination of events. This emitter must already - * have registered listeners for all of the events that it needs to listen for. - * (See lib/linter/safe-emitter.js for more details on `SafeEmitter`.) - * @returns {NodeEventGenerator} new instance - */ - constructor(emitter) { - this.emitter = emitter; - this.currentAncestry = []; - this.enterSelectorsByNodeType = new Map(); - this.exitSelectorsByNodeType = new Map(); - this.anyTypeEnterSelectors = []; - this.anyTypeExitSelectors = []; - - emitter.eventNames().forEach(rawSelector => { - const selector = parseSelector(rawSelector); - - if (selector.listenerTypes) { - const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType; - - selector.listenerTypes.forEach(nodeType => { - if (!typeMap.has(nodeType)) { - typeMap.set(nodeType, []); - } - typeMap.get(nodeType).push(selector); - }); - return; - } - const selectors = selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors; - - selectors.push(selector); - }); - - this.anyTypeEnterSelectors.sort(compareSpecificity); - this.anyTypeExitSelectors.sort(compareSpecificity); - this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); - this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); - } - - /** - * Checks a selector against a node, and emits it if it matches - * @param {ASTNode} node The node to check - * @param {ASTSelector} selector An AST selector descriptor - * @returns {void} - */ - applySelector(node, selector) { - if (esquery.matches(node, selector.parsedSelector, this.currentAncestry)) { - this.emitter.emit(selector.rawSelector, node); - } - } - - /** - * Applies all appropriate selectors to a node, in specificity order - * @param {ASTNode} node The node to check - * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited - * @returns {void} - */ - applySelectors(node, isExit) { - const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || []; - const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors; - - /* - * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor. - * Iterate through each of them, applying selectors in the right order. - */ - let selectorsByTypeIndex = 0; - let anyTypeSelectorsIndex = 0; - - while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) { - if ( - selectorsByTypeIndex >= selectorsByNodeType.length || - anyTypeSelectorsIndex < anyTypeSelectors.length && - compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0 - ) { - this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]); - } else { - this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]); - } - } - } - - /** - * Emits an event of entering AST node. - * @param {ASTNode} node A node which was entered. - * @returns {void} - */ - enterNode(node) { - if (node.parent) { - this.currentAncestry.unshift(node.parent); - } - this.applySelectors(node, false); - } - - /** - * Emits an event of leaving AST node. - * @param {ASTNode} node A node which was left. - * @returns {void} - */ - leaveNode(node) { - this.applySelectors(node, true); - this.currentAncestry.shift(); - } -} - -module.exports = NodeEventGenerator; diff --git a/tools/node_modules/eslint/lib/linter/report-translator.js b/tools/node_modules/eslint/lib/linter/report-translator.js deleted file mode 100644 index eef5165585b21d2e50462d79d30b36140c42eecb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/report-translator.js +++ /dev/null @@ -1,347 +0,0 @@ -/** - * @fileoverview A helper that translates context.report() calls from the rule API into generic problem objects - * @author Teddy Katz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"); -const ruleFixer = require("./rule-fixer"); -const interpolate = require("./interpolate"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * An error message description - * @typedef {Object} MessageDescriptor - * @property {ASTNode} [node] The reported node - * @property {Location} loc The location of the problem. - * @property {string} message The problem message. - * @property {Object} [data] Optional data to use to fill in placeholders in the - * message. - * @property {Function} [fix] The function to call that creates a fix command. - * @property {Array<{desc?: string, messageId?: string, fix: Function}>} suggest Suggestion descriptions and functions to create a the associated fixes. - */ - -/** - * Information about the report - * @typedef {Object} ReportInfo - * @property {string} ruleId - * @property {(0|1|2)} severity - * @property {(string|undefined)} message - * @property {(string|undefined)} [messageId] - * @property {number} line - * @property {number} column - * @property {(number|undefined)} [endLine] - * @property {(number|undefined)} [endColumn] - * @property {(string|null)} nodeType - * @property {string} source - * @property {({text: string, range: (number[]|null)}|null)} [fix] - * @property {Array<{text: string, range: (number[]|null)}|null>} [suggestions] - */ - -//------------------------------------------------------------------------------ -// Module Definition -//------------------------------------------------------------------------------ - - -/** - * Translates a multi-argument context.report() call into a single object argument call - * @param {...*} args A list of arguments passed to `context.report` - * @returns {MessageDescriptor} A normalized object containing report information - */ -function normalizeMultiArgReportCall(...args) { - - // If there is one argument, it is considered to be a new-style call already. - if (args.length === 1) { - - // Shallow clone the object to avoid surprises if reusing the descriptor - return Object.assign({}, args[0]); - } - - // If the second argument is a string, the arguments are interpreted as [node, message, data, fix]. - if (typeof args[1] === "string") { - return { - node: args[0], - message: args[1], - data: args[2], - fix: args[3] - }; - } - - // Otherwise, the arguments are interpreted as [node, loc, message, data, fix]. - return { - node: args[0], - loc: args[1], - message: args[2], - data: args[3], - fix: args[4] - }; -} - -/** - * Asserts that either a loc or a node was provided, and the node is valid if it was provided. - * @param {MessageDescriptor} descriptor A descriptor to validate - * @returns {void} - * @throws AssertionError if neither a node nor a loc was provided, or if the node is not an object - */ -function assertValidNodeInfo(descriptor) { - if (descriptor.node) { - assert(typeof descriptor.node === "object", "Node must be an object"); - } else { - assert(descriptor.loc, "Node must be provided when reporting error if location is not provided"); - } -} - -/** - * Normalizes a MessageDescriptor to always have a `loc` with `start` and `end` properties - * @param {MessageDescriptor} descriptor A descriptor for the report from a rule. - * @returns {{start: Location, end: (Location|null)}} An updated location that infers the `start` and `end` properties - * from the `node` of the original descriptor, or infers the `start` from the `loc` of the original descriptor. - */ -function normalizeReportLoc(descriptor) { - if (descriptor.loc) { - if (descriptor.loc.start) { - return descriptor.loc; - } - return { start: descriptor.loc, end: null }; - } - return descriptor.node.loc; -} - -/** - * Compares items in a fixes array by range. - * @param {Fix} a The first message. - * @param {Fix} b The second message. - * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. - * @private - */ -function compareFixesByRange(a, b) { - return a.range[0] - b.range[0] || a.range[1] - b.range[1]; -} - -/** - * Merges the given fixes array into one. - * @param {Fix[]} fixes The fixes to merge. - * @param {SourceCode} sourceCode The source code object to get the text between fixes. - * @returns {{text: string, range: number[]}} The merged fixes - */ -function mergeFixes(fixes, sourceCode) { - if (fixes.length === 0) { - return null; - } - if (fixes.length === 1) { - return fixes[0]; - } - - fixes.sort(compareFixesByRange); - - const originalText = sourceCode.text; - const start = fixes[0].range[0]; - const end = fixes[fixes.length - 1].range[1]; - let text = ""; - let lastPos = Number.MIN_SAFE_INTEGER; - - for (const fix of fixes) { - assert(fix.range[0] >= lastPos, "Fix objects must not be overlapped in a report."); - - if (fix.range[0] >= 0) { - text += originalText.slice(Math.max(0, start, lastPos), fix.range[0]); - } - text += fix.text; - lastPos = fix.range[1]; - } - text += originalText.slice(Math.max(0, start, lastPos), end); - - return { range: [start, end], text }; -} - -/** - * Gets one fix object from the given descriptor. - * If the descriptor retrieves multiple fixes, this merges those to one. - * @param {MessageDescriptor} descriptor The report descriptor. - * @param {SourceCode} sourceCode The source code object to get text between fixes. - * @returns {({text: string, range: number[]}|null)} The fix for the descriptor - */ -function normalizeFixes(descriptor, sourceCode) { - if (typeof descriptor.fix !== "function") { - return null; - } - - // @type {null | Fix | Fix[] | IterableIterator} - const fix = descriptor.fix(ruleFixer); - - // Merge to one. - if (fix && Symbol.iterator in fix) { - return mergeFixes(Array.from(fix), sourceCode); - } - return fix; -} - -/** - * Gets an array of suggestion objects from the given descriptor. - * @param {MessageDescriptor} descriptor The report descriptor. - * @param {SourceCode} sourceCode The source code object to get text between fixes. - * @param {Object} messages Object of meta messages for the rule. - * @returns {Array} The suggestions for the descriptor - */ -function mapSuggestions(descriptor, sourceCode, messages) { - if (!descriptor.suggest || !Array.isArray(descriptor.suggest)) { - return []; - } - - return descriptor.suggest.map(suggestInfo => { - const computedDesc = suggestInfo.desc || messages[suggestInfo.messageId]; - - return { - ...suggestInfo, - desc: interpolate(computedDesc, suggestInfo.data), - fix: normalizeFixes(suggestInfo, sourceCode) - }; - }); -} - -/** - * Creates information about the report from a descriptor - * @param {Object} options Information about the problem - * @param {string} options.ruleId Rule ID - * @param {(0|1|2)} options.severity Rule severity - * @param {(ASTNode|null)} options.node Node - * @param {string} options.message Error message - * @param {string} [options.messageId] The error message ID. - * @param {{start: SourceLocation, end: (SourceLocation|null)}} options.loc Start and end location - * @param {{text: string, range: (number[]|null)}} options.fix The fix object - * @param {Array<{text: string, range: (number[]|null)}>} options.suggestions The array of suggestions objects - * @returns {function(...args): ReportInfo} Function that returns information about the report - */ -function createProblem(options) { - const problem = { - ruleId: options.ruleId, - severity: options.severity, - message: options.message, - line: options.loc.start.line, - column: options.loc.start.column + 1, - nodeType: options.node && options.node.type || null - }; - - /* - * If this isn’t in the conditional, some of the tests fail - * because `messageId` is present in the problem object - */ - if (options.messageId) { - problem.messageId = options.messageId; - } - - if (options.loc.end) { - problem.endLine = options.loc.end.line; - problem.endColumn = options.loc.end.column + 1; - } - - if (options.fix) { - problem.fix = options.fix; - } - - if (options.suggestions && options.suggestions.length > 0) { - problem.suggestions = options.suggestions; - } - - return problem; -} - -/** - * Validates that suggestions are properly defined. Throws if an error is detected. - * @param {Array<{ desc?: string, messageId?: string }>} suggest The incoming suggest data. - * @param {Object} messages Object of meta messages for the rule. - * @returns {void} - */ -function validateSuggestions(suggest, messages) { - if (suggest && Array.isArray(suggest)) { - suggest.forEach(suggestion => { - if (suggestion.messageId) { - const { messageId } = suggestion; - - if (!messages) { - throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}', but no messages were present in the rule metadata.`); - } - - if (!messages[messageId]) { - throw new TypeError(`context.report() called with a suggest option with a messageId '${messageId}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`); - } - - if (suggestion.desc) { - throw new TypeError("context.report() called with a suggest option that defines both a 'messageId' and an 'desc'. Please only pass one."); - } - } else if (!suggestion.desc) { - throw new TypeError("context.report() called with a suggest option that doesn't have either a `desc` or `messageId`"); - } - - if (typeof suggestion.fix !== "function") { - throw new TypeError(`context.report() called with a suggest option without a fix function. See: ${suggestion}`); - } - }); - } -} - -/** - * Returns a function that converts the arguments of a `context.report` call from a rule into a reported - * problem for the Node.js API. - * @param {{ruleId: string, severity: number, sourceCode: SourceCode, messageIds: Object, disableFixes: boolean}} metadata Metadata for the reported problem - * @param {SourceCode} sourceCode The `SourceCode` instance for the text being linted - * @returns {function(...args): ReportInfo} Function that returns information about the report - */ - -module.exports = function createReportTranslator(metadata) { - - /* - * `createReportTranslator` gets called once per enabled rule per file. It needs to be very performant. - * The report translator itself (i.e. the function that `createReportTranslator` returns) gets - * called every time a rule reports a problem, which happens much less frequently (usually, the vast - * majority of rules don't report any problems for a given file). - */ - return (...args) => { - const descriptor = normalizeMultiArgReportCall(...args); - const messages = metadata.messageIds; - - assertValidNodeInfo(descriptor); - - let computedMessage; - - if (descriptor.messageId) { - if (!messages) { - throw new TypeError("context.report() called with a messageId, but no messages were present in the rule metadata."); - } - const id = descriptor.messageId; - - if (descriptor.message) { - throw new TypeError("context.report() called with a message and a messageId. Please only pass one."); - } - if (!messages || !Object.prototype.hasOwnProperty.call(messages, id)) { - throw new TypeError(`context.report() called with a messageId of '${id}' which is not present in the 'messages' config: ${JSON.stringify(messages, null, 2)}`); - } - computedMessage = messages[id]; - } else if (descriptor.message) { - computedMessage = descriptor.message; - } else { - throw new TypeError("Missing `message` property in report() call; add a message that describes the linting problem."); - } - - validateSuggestions(descriptor.suggest, messages); - - return createProblem({ - ruleId: metadata.ruleId, - severity: metadata.severity, - node: descriptor.node, - message: interpolate(computedMessage, descriptor.data), - messageId: descriptor.messageId, - loc: normalizeReportLoc(descriptor), - fix: metadata.disableFixes ? null : normalizeFixes(descriptor, metadata.sourceCode), - suggestions: metadata.disableFixes ? [] : mapSuggestions(descriptor, metadata.sourceCode, messages) - }); - }; -}; diff --git a/tools/node_modules/eslint/lib/linter/rule-fixer.js b/tools/node_modules/eslint/lib/linter/rule-fixer.js deleted file mode 100644 index bdd80d13b162d44a7dff17ad819196729e4e62e6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/rule-fixer.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @fileoverview An object that creates fix commands for rules. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -// none! - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Creates a fix command that inserts text at the specified index in the source text. - * @param {int} index The 0-based index at which to insert the new text. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - * @private - */ -function insertTextAt(index, text) { - return { - range: [index, index], - text - }; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Creates code fixing commands for rules. - */ - -const ruleFixer = Object.freeze({ - - /** - * Creates a fix command that inserts text after the given node or token. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to insert after. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextAfter(nodeOrToken, text) { - return this.insertTextAfterRange(nodeOrToken.range, text); - }, - - /** - * Creates a fix command that inserts text after the specified range in the source text. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to replace, first item is start of range, second - * is end of range. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextAfterRange(range, text) { - return insertTextAt(range[1], text); - }, - - /** - * Creates a fix command that inserts text before the given node or token. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to insert before. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextBefore(nodeOrToken, text) { - return this.insertTextBeforeRange(nodeOrToken.range, text); - }, - - /** - * Creates a fix command that inserts text before the specified range in the source text. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to replace, first item is start of range, second - * is end of range. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - insertTextBeforeRange(range, text) { - return insertTextAt(range[0], text); - }, - - /** - * Creates a fix command that replaces text at the node or token. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to remove. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - replaceText(nodeOrToken, text) { - return this.replaceTextRange(nodeOrToken.range, text); - }, - - /** - * Creates a fix command that replaces text at the specified range in the source text. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to replace, first item is start of range, second - * is end of range. - * @param {string} text The text to insert. - * @returns {Object} The fix command. - */ - replaceTextRange(range, text) { - return { - range, - text - }; - }, - - /** - * Creates a fix command that removes the node or token from the source. - * The fix is not applied until applyFixes() is called. - * @param {ASTNode|Token} nodeOrToken The node or token to remove. - * @returns {Object} The fix command. - */ - remove(nodeOrToken) { - return this.removeRange(nodeOrToken.range); - }, - - /** - * Creates a fix command that removes the specified range of text from the source. - * The fix is not applied until applyFixes() is called. - * @param {int[]} range The range to remove, first item is start of range, second - * is end of range. - * @returns {Object} The fix command. - */ - removeRange(range) { - return { - range, - text: "" - }; - } - -}); - - -module.exports = ruleFixer; diff --git a/tools/node_modules/eslint/lib/linter/rules.js b/tools/node_modules/eslint/lib/linter/rules.js deleted file mode 100644 index a153266efb3f4da3e571cd7f55be03b3feb279a9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/rules.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @fileoverview Defines a storage for rules. - * @author Nicholas C. Zakas - * @author aladdin-add - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const builtInRules = require("../rules"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Normalizes a rule module to the new-style API - * @param {(Function|{create: Function})} rule A rule object, which can either be a function - * ("old-style") or an object with a `create` method ("new-style") - * @returns {{create: Function}} A new-style rule. - */ -function normalizeRule(rule) { - return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class Rules { - constructor() { - this._rules = Object.create(null); - } - - /** - * Registers a rule module for rule id in storage. - * @param {string} ruleId Rule id (file name). - * @param {Function} ruleModule Rule handler. - * @returns {void} - */ - define(ruleId, ruleModule) { - this._rules[ruleId] = normalizeRule(ruleModule); - } - - /** - * Access rule handler by id (file name). - * @param {string} ruleId Rule id (file name). - * @returns {{create: Function, schema: JsonSchema[]}} - * A rule. This is normalized to always have the new-style shape with a `create` method. - */ - get(ruleId) { - if (typeof this._rules[ruleId] === "string") { - this.define(ruleId, require(this._rules[ruleId])); - } - if (this._rules[ruleId]) { - return this._rules[ruleId]; - } - if (builtInRules.has(ruleId)) { - return builtInRules.get(ruleId); - } - - return null; - } - - *[Symbol.iterator]() { - yield* builtInRules; - - for (const ruleId of Object.keys(this._rules)) { - yield [ruleId, this.get(ruleId)]; - } - } -} - -module.exports = Rules; diff --git a/tools/node_modules/eslint/lib/linter/safe-emitter.js b/tools/node_modules/eslint/lib/linter/safe-emitter.js deleted file mode 100644 index ab212230d398e4b9a9e3923d803d5260f5a701ee..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/safe-emitter.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview A variant of EventEmitter which does not give listeners information about each other - * @author Teddy Katz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * An event emitter - * @typedef {Object} SafeEmitter - * @property {function(eventName: string, listenerFunc: Function): void} on Adds a listener for a given event name - * @property {function(eventName: string, arg1?: any, arg2?: any, arg3?: any)} emit Emits an event with a given name. - * This calls all the listeners that were listening for that name, with `arg1`, `arg2`, and `arg3` as arguments. - * @property {function(): string[]} eventNames Gets the list of event names that have registered listeners. - */ - -/** - * Creates an object which can listen for and emit events. - * This is similar to the EventEmitter API in Node's standard library, but it has a few differences. - * The goal is to allow multiple modules to attach arbitrary listeners to the same emitter, without - * letting the modules know about each other at all. - * 1. It has no special keys like `error` and `newListener`, which would allow modules to detect when - * another module throws an error or registers a listener. - * 2. It calls listener functions without any `this` value. (`EventEmitter` calls listeners with a - * `this` value of the emitter instance, which would give listeners access to other listeners.) - * @returns {SafeEmitter} An emitter - */ -module.exports = () => { - const listeners = Object.create(null); - - return Object.freeze({ - on(eventName, listener) { - if (eventName in listeners) { - listeners[eventName].push(listener); - } else { - listeners[eventName] = [listener]; - } - }, - emit(eventName, ...args) { - if (eventName in listeners) { - listeners[eventName].forEach(listener => listener(...args)); - } - }, - eventNames() { - return Object.keys(listeners); - } - }); -}; diff --git a/tools/node_modules/eslint/lib/linter/source-code-fixer.js b/tools/node_modules/eslint/lib/linter/source-code-fixer.js deleted file mode 100644 index 53dc1dc6be73c486ec95c2782f30cc1102956a39..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/source-code-fixer.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * @fileoverview An object that caches and applies source code fixes. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const debug = require("debug")("eslint:source-code-fixer"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const BOM = "\uFEFF"; - -/** - * Compares items in a messages array by range. - * @param {Message} a The first message. - * @param {Message} b The second message. - * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. - * @private - */ -function compareMessagesByFixRange(a, b) { - return a.fix.range[0] - b.fix.range[0] || a.fix.range[1] - b.fix.range[1]; -} - -/** - * Compares items in a messages array by line and column. - * @param {Message} a The first message. - * @param {Message} b The second message. - * @returns {int} -1 if a comes before b, 1 if a comes after b, 0 if equal. - * @private - */ -function compareMessagesByLocation(a, b) { - return a.line - b.line || a.column - b.column; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * Utility for apply fixes to source code. - * @constructor - */ -function SourceCodeFixer() { - Object.freeze(this); -} - -/** - * Applies the fixes specified by the messages to the given text. Tries to be - * smart about the fixes and won't apply fixes over the same area in the text. - * @param {string} sourceText The text to apply the changes to. - * @param {Message[]} messages The array of messages reported by ESLint. - * @param {boolean|Function} [shouldFix=true] Determines whether each message should be fixed - * @returns {Object} An object containing the fixed text and any unfixed messages. - */ -SourceCodeFixer.applyFixes = function(sourceText, messages, shouldFix) { - debug("Applying fixes"); - - if (shouldFix === false) { - debug("shouldFix parameter was false, not attempting fixes"); - return { - fixed: false, - messages, - output: sourceText - }; - } - - // clone the array - const remainingMessages = [], - fixes = [], - bom = sourceText.startsWith(BOM) ? BOM : "", - text = bom ? sourceText.slice(1) : sourceText; - let lastPos = Number.NEGATIVE_INFINITY, - output = bom; - - /** - * Try to use the 'fix' from a problem. - * @param {Message} problem The message object to apply fixes from - * @returns {boolean} Whether fix was successfully applied - */ - function attemptFix(problem) { - const fix = problem.fix; - const start = fix.range[0]; - const end = fix.range[1]; - - // Remain it as a problem if it's overlapped or it's a negative range - if (lastPos >= start || start > end) { - remainingMessages.push(problem); - return false; - } - - // Remove BOM. - if ((start < 0 && end >= 0) || (start === 0 && fix.text.startsWith(BOM))) { - output = ""; - } - - // Make output to this fix. - output += text.slice(Math.max(0, lastPos), Math.max(0, start)); - output += fix.text; - lastPos = end; - return true; - } - - messages.forEach(problem => { - if (Object.prototype.hasOwnProperty.call(problem, "fix")) { - fixes.push(problem); - } else { - remainingMessages.push(problem); - } - }); - - if (fixes.length) { - debug("Found fixes to apply"); - let fixesWereApplied = false; - - for (const problem of fixes.sort(compareMessagesByFixRange)) { - if (typeof shouldFix !== "function" || shouldFix(problem)) { - attemptFix(problem); - - /* - * The only time attemptFix will fail is if a previous fix was - * applied which conflicts with it. So we can mark this as true. - */ - fixesWereApplied = true; - } else { - remainingMessages.push(problem); - } - } - output += text.slice(Math.max(0, lastPos)); - - return { - fixed: fixesWereApplied, - messages: remainingMessages.sort(compareMessagesByLocation), - output - }; - } - - debug("No fixes to apply"); - return { - fixed: false, - messages, - output: bom + text - }; - -}; - -module.exports = SourceCodeFixer; diff --git a/tools/node_modules/eslint/lib/linter/timing.js b/tools/node_modules/eslint/lib/linter/timing.js deleted file mode 100644 index 8396d9215b54dc4911d92336294e7da3563fd9de..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/linter/timing.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @fileoverview Tracks performance of individual rules. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/* istanbul ignore next */ -/** - * Align the string to left - * @param {string} str string to evaluate - * @param {int} len length of the string - * @param {string} ch delimiter character - * @returns {string} modified string - * @private - */ -function alignLeft(str, len, ch) { - return str + new Array(len - str.length + 1).join(ch || " "); -} - -/* istanbul ignore next */ -/** - * Align the string to right - * @param {string} str string to evaluate - * @param {int} len length of the string - * @param {string} ch delimiter character - * @returns {string} modified string - * @private - */ -function alignRight(str, len, ch) { - return new Array(len - str.length + 1).join(ch || " ") + str; -} - -//------------------------------------------------------------------------------ -// Module definition -//------------------------------------------------------------------------------ - -const enabled = !!process.env.TIMING; - -const HEADERS = ["Rule", "Time (ms)", "Relative"]; -const ALIGN = [alignLeft, alignRight, alignRight]; - -/* istanbul ignore next */ -/** - * display the data - * @param {Object} data Data object to be displayed - * @returns {void} prints modified string with console.log - * @private - */ -function display(data) { - let total = 0; - const rows = Object.keys(data) - .map(key => { - const time = data[key]; - - total += time; - return [key, time]; - }) - .sort((a, b) => b[1] - a[1]) - .slice(0, 10); - - rows.forEach(row => { - row.push(`${(row[1] * 100 / total).toFixed(1)}%`); - row[1] = row[1].toFixed(3); - }); - - rows.unshift(HEADERS); - - const widths = []; - - rows.forEach(row => { - const len = row.length; - - for (let i = 0; i < len; i++) { - const n = row[i].length; - - if (!widths[i] || n > widths[i]) { - widths[i] = n; - } - } - }); - - const table = rows.map(row => ( - row - .map((cell, index) => ALIGN[index](cell, widths[index])) - .join(" | ") - )); - - table.splice(1, 0, widths.map((width, index) => { - const extraAlignment = index !== 0 && index !== widths.length - 1 ? 2 : 1; - - return ALIGN[index](":", width + extraAlignment, "-"); - }).join("|")); - - console.log(table.join("\n")); // eslint-disable-line no-console -} - -/* istanbul ignore next */ -module.exports = (function() { - - const data = Object.create(null); - - /** - * Time the run - * @param {*} key key from the data object - * @param {Function} fn function to be called - * @returns {Function} function to be executed - * @private - */ - function time(key, fn) { - if (typeof data[key] === "undefined") { - data[key] = 0; - } - - return function(...args) { - let t = process.hrtime(); - - fn(...args); - t = process.hrtime(t); - data[key] += t[0] * 1e3 + t[1] / 1e6; - }; - } - - if (enabled) { - process.on("exit", () => { - display(data); - }); - } - - return { - time, - enabled - }; - -}()); diff --git a/tools/node_modules/eslint/lib/options.js b/tools/node_modules/eslint/lib/options.js deleted file mode 100644 index 1681f1dbd1d733fe77255df3839c1dd75dc62e89..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/options.js +++ /dev/null @@ -1,262 +0,0 @@ -/** - * @fileoverview Options configuration for optionator. - * @author George Zahariev - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const optionator = require("optionator"); - -//------------------------------------------------------------------------------ -// Initialization and Public Interface -//------------------------------------------------------------------------------ - -// exports "parse(args)", "generateHelp()", and "generateHelpForOption(optionName)" -module.exports = optionator({ - prepend: "eslint [options] file.js [file.js] [dir]", - defaults: { - concatRepeatedArrays: true, - mergeRepeatedObjects: true - }, - options: [ - { - heading: "Basic configuration" - }, - { - option: "eslintrc", - type: "Boolean", - default: "true", - description: "Disable use of configuration from .eslintrc.*" - }, - { - option: "config", - alias: "c", - type: "path::String", - description: "Use this configuration, overriding .eslintrc.* config options if present" - }, - { - option: "env", - type: "[String]", - description: "Specify environments" - }, - { - option: "ext", - type: "[String]", - description: "Specify JavaScript file extensions" - }, - { - option: "global", - type: "[String]", - description: "Define global variables" - }, - { - option: "parser", - type: "String", - description: "Specify the parser to be used" - }, - { - option: "parser-options", - type: "Object", - description: "Specify parser options" - }, - { - option: "resolve-plugins-relative-to", - type: "path::String", - description: "A folder where plugins should be resolved from, CWD by default" - }, - { - heading: "Specifying rules and plugins" - }, - { - option: "rulesdir", - type: "[path::String]", - description: "Use additional rules from this directory" - }, - { - option: "plugin", - type: "[String]", - description: "Specify plugins" - }, - { - option: "rule", - type: "Object", - description: "Specify rules" - }, - { - heading: "Fixing problems" - }, - { - option: "fix", - type: "Boolean", - default: false, - description: "Automatically fix problems" - }, - { - option: "fix-dry-run", - type: "Boolean", - default: false, - description: "Automatically fix problems without saving the changes to the file system" - }, - { - option: "fix-type", - type: "Array", - description: "Specify the types of fixes to apply (problem, suggestion, layout)" - }, - { - heading: "Ignoring files" - }, - { - option: "ignore-path", - type: "path::String", - description: "Specify path of ignore file" - }, - { - option: "ignore", - type: "Boolean", - default: "true", - description: "Disable use of ignore files and patterns" - }, - { - option: "ignore-pattern", - type: "[String]", - description: "Pattern of files to ignore (in addition to those in .eslintignore)", - concatRepeatedArrays: [true, { - oneValuePerFlag: true - }] - }, - { - heading: "Using stdin" - }, - { - option: "stdin", - type: "Boolean", - default: "false", - description: "Lint code provided on " - }, - { - option: "stdin-filename", - type: "String", - description: "Specify filename to process STDIN as" - }, - { - heading: "Handling warnings" - }, - { - option: "quiet", - type: "Boolean", - default: "false", - description: "Report errors only" - }, - { - option: "max-warnings", - type: "Int", - default: "-1", - description: "Number of warnings to trigger nonzero exit code" - }, - { - heading: "Output" - }, - { - option: "output-file", - alias: "o", - type: "path::String", - description: "Specify file to write report to" - }, - { - option: "format", - alias: "f", - type: "String", - default: "stylish", - description: "Use a specific output format" - }, - { - option: "color", - type: "Boolean", - alias: "no-color", - description: "Force enabling/disabling of color" - }, - { - heading: "Inline configuration comments" - }, - { - option: "inline-config", - type: "Boolean", - default: "true", - description: "Prevent comments from changing config or rules" - }, - { - option: "report-unused-disable-directives", - type: "Boolean", - default: void 0, - description: "Adds reported errors for unused eslint-disable directives" - }, - { - heading: "Caching" - }, - { - option: "cache", - type: "Boolean", - default: "false", - description: "Only check changed files" - }, - { - option: "cache-file", - type: "path::String", - default: ".eslintcache", - description: "Path to the cache file. Deprecated: use --cache-location" - }, - { - option: "cache-location", - type: "path::String", - description: "Path to the cache file or directory" - }, - { - heading: "Miscellaneous" - }, - { - option: "init", - type: "Boolean", - default: "false", - description: "Run config initialization wizard" - }, - { - option: "env-info", - type: "Boolean", - default: "false", - description: "Output execution environment information" - }, - { - option: "error-on-unmatched-pattern", - type: "Boolean", - default: "true", - description: "Prevent errors when pattern is unmatched" - }, - { - option: "debug", - type: "Boolean", - default: false, - description: "Output debugging information" - }, - { - option: "help", - alias: "h", - type: "Boolean", - description: "Show help" - }, - { - option: "version", - alias: "v", - type: "Boolean", - description: "Output the version number" - }, - { - option: "print-config", - type: "path::String", - description: "Print the configuration for the given file" - } - ] -}); diff --git a/tools/node_modules/eslint/lib/rule-tester/index.js b/tools/node_modules/eslint/lib/rule-tester/index.js deleted file mode 100644 index f52d14027c58ff9d46b4c0cdc5037d87aa007c2e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rule-tester/index.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; - -module.exports = { - RuleTester: require("./rule-tester") -}; diff --git a/tools/node_modules/eslint/lib/rule-tester/rule-tester.js b/tools/node_modules/eslint/lib/rule-tester/rule-tester.js deleted file mode 100644 index d1fcbca5ba06222cf1511063867351b9b40c8356..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rule-tester/rule-tester.js +++ /dev/null @@ -1,894 +0,0 @@ -/** - * @fileoverview Mocha test wrapper - * @author Ilya Volodin - */ -"use strict"; - -/* global describe, it */ - -/* - * This is a wrapper around mocha to allow for DRY unittests for eslint - * Format: - * RuleTester.run("{ruleName}", { - * valid: [ - * "{code}", - * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} } - * ], - * invalid: [ - * { code: "{code}", errors: {numErrors} }, - * { code: "{code}", errors: ["{errorMessage}"] }, - * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] } - * ] - * }); - * - * Variables: - * {code} - String that represents the code to be tested - * {options} - Arguments that are passed to the configurable rules. - * {globals} - An object representing a list of variables that are - * registered as globals - * {parser} - String representing the parser to use - * {settings} - An object representing global settings for all rules - * {numErrors} - If failing case doesn't need to check error message, - * this integer will specify how many errors should be - * received - * {errorMessage} - Message that is returned by the rule on failure - * {errorNodeType} - AST node type that is returned by they rule as - * a cause of the failure. - */ - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const - assert = require("assert"), - path = require("path"), - util = require("util"), - lodash = require("lodash"), - Traverser = require("../../lib/shared/traverser"), - { getRuleOptionsSchema, validate } = require("../shared/config-validator"), - { Linter, SourceCodeFixer, interpolate } = require("../linter"); - -const ajv = require("../shared/ajv")({ strictDefaults: true }); - -const espreePath = require.resolve("espree"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** @typedef {import("../shared/types").Parser} Parser */ - -/** - * A test case that is expected to pass lint. - * @typedef {Object} ValidTestCase - * @property {string} code Code for the test case. - * @property {any[]} [options] Options for the test case. - * @property {{ [name: string]: any }} [settings] Settings for the test case. - * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. - * @property {string} [parser] The absolute path for the parser. - * @property {{ [name: string]: any }} [parserOptions] Options for the parser. - * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables. - * @property {{ [name: string]: boolean }} [env] Environments for the test case. - */ - -/** - * A test case that is expected to fail lint. - * @typedef {Object} InvalidTestCase - * @property {string} code Code for the test case. - * @property {number | Array} errors Expected errors. - * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested. - * @property {any[]} [options] Options for the test case. - * @property {{ [name: string]: any }} [settings] Settings for the test case. - * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames. - * @property {string} [parser] The absolute path for the parser. - * @property {{ [name: string]: any }} [parserOptions] Options for the parser. - * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables. - * @property {{ [name: string]: boolean }} [env] Environments for the test case. - */ - -/** - * A description of a reported error used in a rule tester test. - * @typedef {Object} TestCaseError - * @property {string | RegExp} [message] Message. - * @property {string} [messageId] Message ID. - * @property {string} [type] The type of the reported AST node. - * @property {{ [name: string]: string }} [data] The data used to fill the message template. - * @property {number} [line] The 1-based line number of the reported start location. - * @property {number} [column] The 1-based column number of the reported start location. - * @property {number} [endLine] The 1-based line number of the reported end location. - * @property {number} [endColumn] The 1-based column number of the reported end location. - */ - -//------------------------------------------------------------------------------ -// Private Members -//------------------------------------------------------------------------------ - -/* - * testerDefaultConfig must not be modified as it allows to reset the tester to - * the initial default configuration - */ -const testerDefaultConfig = { rules: {} }; -let defaultConfig = { rules: {} }; - -/* - * List every parameters possible on a test case that are not related to eslint - * configuration - */ -const RuleTesterParameters = [ - "code", - "filename", - "options", - "errors", - "output" -]; - -/* - * All allowed property names in error objects. - */ -const errorObjectParameters = new Set([ - "message", - "messageId", - "data", - "type", - "line", - "column", - "endLine", - "endColumn", - "suggestions" -]); -const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`; - -/* - * All allowed property names in suggestion objects. - */ -const suggestionObjectParameters = new Set([ - "desc", - "messageId", - "data", - "output" -]); -const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`; - -const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); - -/** - * Clones a given value deeply. - * Note: This ignores `parent` property. - * @param {any} x A value to clone. - * @returns {any} A cloned value. - */ -function cloneDeeplyExcludesParent(x) { - if (typeof x === "object" && x !== null) { - if (Array.isArray(x)) { - return x.map(cloneDeeplyExcludesParent); - } - - const retv = {}; - - for (const key in x) { - if (key !== "parent" && hasOwnProperty(x, key)) { - retv[key] = cloneDeeplyExcludesParent(x[key]); - } - } - - return retv; - } - - return x; -} - -/** - * Freezes a given value deeply. - * @param {any} x A value to freeze. - * @returns {void} - */ -function freezeDeeply(x) { - if (typeof x === "object" && x !== null) { - if (Array.isArray(x)) { - x.forEach(freezeDeeply); - } else { - for (const key in x) { - if (key !== "parent" && hasOwnProperty(x, key)) { - freezeDeeply(x[key]); - } - } - } - Object.freeze(x); - } -} - -/** - * Replace control characters by `\u00xx` form. - * @param {string} text The text to sanitize. - * @returns {string} The sanitized text. - */ -function sanitize(text) { - return text.replace( - /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex - c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}` - ); -} - -/** - * Define `start`/`end` properties as throwing error. - * @param {string} objName Object name used for error messages. - * @param {ASTNode} node The node to define. - * @returns {void} - */ -function defineStartEndAsError(objName, node) { - Object.defineProperties(node, { - start: { - get() { - throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`); - }, - configurable: true, - enumerable: false - }, - end: { - get() { - throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`); - }, - configurable: true, - enumerable: false - } - }); -} - -/** - * Define `start`/`end` properties of all nodes of the given AST as throwing error. - * @param {ASTNode} ast The root node to errorize `start`/`end` properties. - * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast. - * @returns {void} - */ -function defineStartEndAsErrorInTree(ast, visitorKeys) { - Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") }); - ast.tokens.forEach(defineStartEndAsError.bind(null, "token")); - ast.comments.forEach(defineStartEndAsError.bind(null, "token")); -} - -/** - * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes. - * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties. - * @param {Parser} parser Parser object. - * @returns {Parser} Wrapped parser object. - */ -function wrapParser(parser) { - if (typeof parser.parseForESLint === "function") { - return { - parseForESLint(...args) { - const ret = parser.parseForESLint(...args); - - defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys); - return ret; - } - }; - } - return { - parse(...args) { - const ast = parser.parse(...args); - - defineStartEndAsErrorInTree(ast); - return ast; - } - }; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -// default separators for testing -const DESCRIBE = Symbol("describe"); -const IT = Symbol("it"); - -/** - * This is `it` default handler if `it` don't exist. - * @this {Mocha} - * @param {string} text The description of the test case. - * @param {Function} method The logic of the test case. - * @returns {any} Returned value of `method`. - */ -function itDefaultHandler(text, method) { - try { - return method.call(this); - } catch (err) { - if (err instanceof assert.AssertionError) { - err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; - } - throw err; - } -} - -/** - * This is `describe` default handler if `describe` don't exist. - * @this {Mocha} - * @param {string} text The description of the test case. - * @param {Function} method The logic of the test case. - * @returns {any} Returned value of `method`. - */ -function describeDefaultHandler(text, method) { - return method.call(this); -} - -class RuleTester { - - /** - * Creates a new instance of RuleTester. - * @param {Object} [testerConfig] Optional, extra configuration for the tester - */ - constructor(testerConfig) { - - /** - * The configuration to use for this tester. Combination of the tester - * configuration and the default configuration. - * @type {Object} - */ - this.testerConfig = lodash.merge( - - // we have to clone because merge uses the first argument for recipient - lodash.cloneDeep(defaultConfig), - testerConfig, - { rules: { "rule-tester/validate-ast": "error" } } - ); - - /** - * Rule definitions to define before tests. - * @type {Object} - */ - this.rules = {}; - this.linter = new Linter(); - } - - /** - * Set the configuration to use for all future tests - * @param {Object} config the configuration to use. - * @returns {void} - */ - static setDefaultConfig(config) { - if (typeof config !== "object") { - throw new TypeError("RuleTester.setDefaultConfig: config must be an object"); - } - defaultConfig = config; - - // Make sure the rules object exists since it is assumed to exist later - defaultConfig.rules = defaultConfig.rules || {}; - } - - /** - * Get the current configuration used for all tests - * @returns {Object} the current configuration - */ - static getDefaultConfig() { - return defaultConfig; - } - - /** - * Reset the configuration to the initial configuration of the tester removing - * any changes made until now. - * @returns {void} - */ - static resetDefaultConfig() { - defaultConfig = lodash.cloneDeep(testerDefaultConfig); - } - - - /* - * If people use `mocha test.js --watch` command, `describe` and `it` function - * instances are different for each execution. So `describe` and `it` should get fresh instance - * always. - */ - static get describe() { - return ( - this[DESCRIBE] || - (typeof describe === "function" ? describe : describeDefaultHandler) - ); - } - - static set describe(value) { - this[DESCRIBE] = value; - } - - static get it() { - return ( - this[IT] || - (typeof it === "function" ? it : itDefaultHandler) - ); - } - - static set it(value) { - this[IT] = value; - } - - /** - * Define a rule for one particular run of tests. - * @param {string} name The name of the rule to define. - * @param {Function} rule The rule definition. - * @returns {void} - */ - defineRule(name, rule) { - this.rules[name] = rule; - } - - /** - * Adds a new rule test to execute. - * @param {string} ruleName The name of the rule to run. - * @param {Function} rule The rule to test. - * @param {{ - * valid: (ValidTestCase | string)[], - * invalid: InvalidTestCase[] - * }} test The collection of tests to run. - * @returns {void} - */ - run(ruleName, rule, test) { - - const testerConfig = this.testerConfig, - requiredScenarios = ["valid", "invalid"], - scenarioErrors = [], - linter = this.linter; - - if (lodash.isNil(test) || typeof test !== "object") { - throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`); - } - - requiredScenarios.forEach(scenarioType => { - if (lodash.isNil(test[scenarioType])) { - scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`); - } - }); - - if (scenarioErrors.length > 0) { - throw new Error([ - `Test Scenarios for rule ${ruleName} is invalid:` - ].concat(scenarioErrors).join("\n")); - } - - - linter.defineRule(ruleName, Object.assign({}, rule, { - - // Create a wrapper rule that freezes the `context` properties. - create(context) { - freezeDeeply(context.options); - freezeDeeply(context.settings); - freezeDeeply(context.parserOptions); - - return (typeof rule === "function" ? rule : rule.create)(context); - } - })); - - linter.defineRules(this.rules); - - /** - * Run the rule for the given item - * @param {string|Object} item Item to run the rule against - * @returns {Object} Eslint run result - * @private - */ - function runRuleForItem(item) { - let config = lodash.cloneDeep(testerConfig), - code, filename, output, beforeAST, afterAST; - - if (typeof item === "string") { - code = item; - } else { - code = item.code; - - /* - * Assumes everything on the item is a config except for the - * parameters used by this tester - */ - const itemConfig = lodash.omit(item, RuleTesterParameters); - - /* - * Create the config object from the tester config and this item - * specific configurations. - */ - config = lodash.merge( - config, - itemConfig - ); - } - - if (item.filename) { - filename = item.filename; - } - - if (hasOwnProperty(item, "options")) { - assert(Array.isArray(item.options), "options must be an array"); - config.rules[ruleName] = [1].concat(item.options); - } else { - config.rules[ruleName] = 1; - } - - const schema = getRuleOptionsSchema(rule); - - /* - * Setup AST getters. - * The goal is to check whether or not AST was modified when - * running the rule under test. - */ - linter.defineRule("rule-tester/validate-ast", () => ({ - Program(node) { - beforeAST = cloneDeeplyExcludesParent(node); - }, - "Program:exit"(node) { - afterAST = node; - } - })); - - if (typeof config.parser === "string") { - assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths"); - } else { - config.parser = espreePath; - } - - linter.defineParser(config.parser, wrapParser(require(config.parser))); - - if (schema) { - ajv.validateSchema(schema); - - if (ajv.errors) { - const errors = ajv.errors.map(error => { - const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; - - return `\t${field}: ${error.message}`; - }).join("\n"); - - throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]); - } - - /* - * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"), - * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling - * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result, - * the schema is compiled here separately from checking for `validateSchema` errors. - */ - try { - ajv.compile(schema); - } catch (err) { - throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`); - } - } - - validate(config, "rule-tester", id => (id === ruleName ? rule : null)); - - // Verify the code. - const messages = linter.verify(code, config, filename); - const fatalErrorMessage = messages.find(m => m.fatal); - - assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`); - - // Verify if autofix makes a syntax error or not. - if (messages.some(m => m.fix)) { - output = SourceCodeFixer.applyFixes(code, messages).output; - const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal); - - assert(!errorMessageInFix, [ - "A fatal parsing error occurred in autofix.", - `Error: ${errorMessageInFix && errorMessageInFix.message}`, - "Autofix output:", - output - ].join("\n")); - } else { - output = code; - } - - return { - messages, - output, - beforeAST, - afterAST: cloneDeeplyExcludesParent(afterAST) - }; - } - - /** - * Check if the AST was changed - * @param {ASTNode} beforeAST AST node before running - * @param {ASTNode} afterAST AST node after running - * @returns {void} - * @private - */ - function assertASTDidntChange(beforeAST, afterAST) { - if (!lodash.isEqual(beforeAST, afterAST)) { - assert.fail("Rule should not modify AST."); - } - } - - /** - * Check if the template is valid or not - * all valid cases go through this - * @param {string|Object} item Item to run the rule against - * @returns {void} - * @private - */ - function testValidTemplate(item) { - const result = runRuleForItem(item); - const messages = result.messages; - - assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s", - messages.length, util.inspect(messages))); - - assertASTDidntChange(result.beforeAST, result.afterAST); - } - - /** - * Asserts that the message matches its expected value. If the expected - * value is a regular expression, it is checked against the actual - * value. - * @param {string} actual Actual value - * @param {string|RegExp} expected Expected value - * @returns {void} - * @private - */ - function assertMessageMatches(actual, expected) { - if (expected instanceof RegExp) { - - // assert.js doesn't have a built-in RegExp match function - assert.ok( - expected.test(actual), - `Expected '${actual}' to match ${expected}` - ); - } else { - assert.strictEqual(actual, expected); - } - } - - /** - * Check if the template is invalid or not - * all invalid cases go through this. - * @param {string|Object} item Item to run the rule against - * @returns {void} - * @private - */ - function testInvalidTemplate(item) { - assert.ok(item.errors || item.errors === 0, - `Did not specify errors for an invalid test of ${ruleName}`); - - const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"); - const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null; - - const result = runRuleForItem(item); - const messages = result.messages; - - if (typeof item.errors === "number") { - assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s", - item.errors, item.errors === 1 ? "" : "s", messages.length, util.inspect(messages))); - } else { - assert.strictEqual( - messages.length, item.errors.length, - util.format( - "Should have %d error%s but had %d: %s", - item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages) - ) - ); - - const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName); - - for (let i = 0, l = item.errors.length; i < l; i++) { - const error = item.errors[i]; - const message = messages[i]; - - assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested"); - - if (typeof error === "string" || error instanceof RegExp) { - - // Just an error message. - assertMessageMatches(message.message, error); - } else if (typeof error === "object" && error !== null) { - - /* - * Error object. - * This may have a message, messageId, data, node type, line, and/or - * column. - */ - - Object.keys(error).forEach(propertyName => { - assert.ok( - errorObjectParameters.has(propertyName), - `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.` - ); - }); - - if (hasOwnProperty(error, "message")) { - assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'."); - assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'."); - assertMessageMatches(message.message, error.message); - } else if (hasOwnProperty(error, "messageId")) { - assert.ok( - ruleHasMetaMessages, - "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'." - ); - if (!hasOwnProperty(rule.meta.messages, error.messageId)) { - assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`); - } - assert.strictEqual( - message.messageId, - error.messageId, - `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.` - ); - if (hasOwnProperty(error, "data")) { - - /* - * if data was provided, then directly compare the returned message to a synthetic - * interpolated message using the same message ID and data provided in the test. - * See https://github.com/eslint/eslint/issues/9890 for context. - */ - const unformattedOriginalMessage = rule.meta.messages[error.messageId]; - const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data); - - assert.strictEqual( - message.message, - rehydratedMessage, - `Hydrated message "${rehydratedMessage}" does not match "${message.message}"` - ); - } - } - - assert.ok( - hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true, - "Error must specify 'messageId' if 'data' is used." - ); - - if (error.type) { - assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`); - } - - if (hasOwnProperty(error, "line")) { - assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`); - } - - if (hasOwnProperty(error, "column")) { - assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`); - } - - if (hasOwnProperty(error, "endLine")) { - assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`); - } - - if (hasOwnProperty(error, "endColumn")) { - assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`); - } - - if (hasOwnProperty(error, "suggestions")) { - - // Support asserting there are no suggestions - if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) { - if (Array.isArray(message.suggestions) && message.suggestions.length > 0) { - assert.fail(`Error should have no suggestions on error with message: "${message.message}"`); - } - } else { - assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`); - assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`); - - error.suggestions.forEach((expectedSuggestion, index) => { - assert.ok( - typeof expectedSuggestion === "object" && expectedSuggestion !== null, - "Test suggestion in 'suggestions' array must be an object." - ); - Object.keys(expectedSuggestion).forEach(propertyName => { - assert.ok( - suggestionObjectParameters.has(propertyName), - `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.` - ); - }); - - const actualSuggestion = message.suggestions[index]; - const suggestionPrefix = `Error Suggestion at index ${index} :`; - - if (hasOwnProperty(expectedSuggestion, "desc")) { - assert.ok( - !hasOwnProperty(expectedSuggestion, "data"), - `${suggestionPrefix} Test should not specify both 'desc' and 'data'.` - ); - assert.strictEqual( - actualSuggestion.desc, - expectedSuggestion.desc, - `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.` - ); - } - - if (hasOwnProperty(expectedSuggestion, "messageId")) { - assert.ok( - ruleHasMetaMessages, - `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.` - ); - assert.ok( - hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId), - `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.` - ); - assert.strictEqual( - actualSuggestion.messageId, - expectedSuggestion.messageId, - `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.` - ); - if (hasOwnProperty(expectedSuggestion, "data")) { - const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId]; - const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data); - - assert.strictEqual( - actualSuggestion.desc, - rehydratedDesc, - `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".` - ); - } - } else { - assert.ok( - !hasOwnProperty(expectedSuggestion, "data"), - `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.` - ); - } - - if (hasOwnProperty(expectedSuggestion, "output")) { - const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output; - - assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`); - } - }); - } - } - } else { - - // Message was an unexpected type - assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`); - } - } - } - - if (hasOwnProperty(item, "output")) { - if (item.output === null) { - assert.strictEqual( - result.output, - item.code, - "Expected no autofixes to be suggested" - ); - } else { - assert.strictEqual(result.output, item.output, "Output is incorrect."); - } - } else { - assert.strictEqual( - result.output, - item.code, - "The rule fixed the code. Please add 'output' property." - ); - } - - // Rules that produce fixes must have `meta.fixable` property. - if (result.output !== item.code) { - assert.ok( - hasOwnProperty(rule, "meta"), - "Fixable rules should export a `meta.fixable` property." - ); - - // Linter throws if a rule that produced a fix has `meta` but doesn't have `meta.fixable`. - } - - assertASTDidntChange(result.beforeAST, result.afterAST); - } - - /* - * This creates a mocha test suite and pipes all supplied info through - * one of the templates above. - */ - RuleTester.describe(ruleName, () => { - RuleTester.describe("valid", () => { - test.valid.forEach(valid => { - RuleTester.it(sanitize(typeof valid === "object" ? valid.code : valid), () => { - testValidTemplate(valid); - }); - }); - }); - - RuleTester.describe("invalid", () => { - test.invalid.forEach(invalid => { - RuleTester.it(sanitize(invalid.code), () => { - testInvalidTemplate(invalid); - }); - }); - }); - }); - } -} - -RuleTester[DESCRIBE] = RuleTester[IT] = null; - -module.exports = RuleTester; diff --git a/tools/node_modules/eslint/lib/rules/accessor-pairs.js b/tools/node_modules/eslint/lib/rules/accessor-pairs.js deleted file mode 100644 index 0e0d07a00c971da3dc9e4373fcb18d75633ae8a3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/accessor-pairs.js +++ /dev/null @@ -1,354 +0,0 @@ -/** - * @fileoverview Rule to enforce getter and setter pairs in objects and classes. - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * Property name if it can be computed statically, otherwise the list of the tokens of the key node. - * @typedef {string|Token[]} Key - */ - -/** - * Accessor nodes with the same key. - * @typedef {Object} AccessorData - * @property {Key} key Accessor's key - * @property {ASTNode[]} getters List of getter nodes. - * @property {ASTNode[]} setters List of setter nodes. - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not the given lists represent the equal tokens in the same order. - * Tokens are compared by their properties, not by instance. - * @param {Token[]} left First list of tokens. - * @param {Token[]} right Second list of tokens. - * @returns {boolean} `true` if the lists have same tokens. - */ -function areEqualTokenLists(left, right) { - if (left.length !== right.length) { - return false; - } - - for (let i = 0; i < left.length; i++) { - const leftToken = left[i], - rightToken = right[i]; - - if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) { - return false; - } - } - - return true; -} - -/** - * Checks whether or not the given keys are equal. - * @param {Key} left First key. - * @param {Key} right Second key. - * @returns {boolean} `true` if the keys are equal. - */ -function areEqualKeys(left, right) { - if (typeof left === "string" && typeof right === "string") { - - // Statically computed names. - return left === right; - } - if (Array.isArray(left) && Array.isArray(right)) { - - // Token lists. - return areEqualTokenLists(left, right); - } - - return false; -} - -/** - * Checks whether or not a given node is of an accessor kind ('get' or 'set'). - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is of an accessor kind. - */ -function isAccessorKind(node) { - return node.kind === "get" || node.kind === "set"; -} - -/** - * Checks whether or not a given node is an argument of a specified method call. - * @param {ASTNode} node A node to check. - * @param {number} index An expected index of the node in arguments. - * @param {string} object An expected name of the object of the method. - * @param {string} property An expected name of the method. - * @returns {boolean} `true` if the node is an argument of the specified method call. - */ -function isArgumentOfMethodCall(node, index, object, property) { - const parent = node.parent; - - return ( - parent.type === "CallExpression" && - astUtils.isSpecificMemberAccess(parent.callee, object, property) && - parent.arguments[index] === node - ); -} - -/** - * Checks whether or not a given node is a property descriptor. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a property descriptor. - */ -function isPropertyDescriptor(node) { - - // Object.defineProperty(obj, "foo", {set: ...}) - if (isArgumentOfMethodCall(node, 2, "Object", "defineProperty") || - isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty") - ) { - return true; - } - - /* - * Object.defineProperties(obj, {foo: {set: ...}}) - * Object.create(proto, {foo: {set: ...}}) - */ - const grandparent = node.parent.parent; - - return grandparent.type === "ObjectExpression" && ( - isArgumentOfMethodCall(grandparent, 1, "Object", "create") || - isArgumentOfMethodCall(grandparent, 1, "Object", "defineProperties") - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce getter and setter pairs in objects and classes", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/accessor-pairs" - }, - - schema: [{ - type: "object", - properties: { - getWithoutSet: { - type: "boolean", - default: false - }, - setWithoutGet: { - type: "boolean", - default: true - }, - enforceForClassMembers: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }], - - messages: { - missingGetterInPropertyDescriptor: "Getter is not present in property descriptor.", - missingSetterInPropertyDescriptor: "Setter is not present in property descriptor.", - missingGetterInObjectLiteral: "Getter is not present for {{ name }}.", - missingSetterInObjectLiteral: "Setter is not present for {{ name }}.", - missingGetterInClass: "Getter is not present for class {{ name }}.", - missingSetterInClass: "Setter is not present for class {{ name }}." - } - }, - create(context) { - const config = context.options[0] || {}; - const checkGetWithoutSet = config.getWithoutSet === true; - const checkSetWithoutGet = config.setWithoutGet !== false; - const enforceForClassMembers = config.enforceForClassMembers !== false; - const sourceCode = context.getSourceCode(); - - /** - * Reports the given node. - * @param {ASTNode} node The node to report. - * @param {string} messageKind "missingGetter" or "missingSetter". - * @returns {void} - * @private - */ - function report(node, messageKind) { - if (node.type === "Property") { - context.report({ - node, - messageId: `${messageKind}InObjectLiteral`, - loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), - data: { name: astUtils.getFunctionNameWithKind(node.value) } - }); - } else if (node.type === "MethodDefinition") { - context.report({ - node, - messageId: `${messageKind}InClass`, - loc: astUtils.getFunctionHeadLoc(node.value, sourceCode), - data: { name: astUtils.getFunctionNameWithKind(node.value) } - }); - } else { - context.report({ - node, - messageId: `${messageKind}InPropertyDescriptor` - }); - } - } - - /** - * Reports each of the nodes in the given list using the same messageId. - * @param {ASTNode[]} nodes Nodes to report. - * @param {string} messageKind "missingGetter" or "missingSetter". - * @returns {void} - * @private - */ - function reportList(nodes, messageKind) { - for (const node of nodes) { - report(node, messageKind); - } - } - - /** - * Creates a new `AccessorData` object for the given getter or setter node. - * @param {ASTNode} node A getter or setter node. - * @returns {AccessorData} New `AccessorData` object that contains the given node. - * @private - */ - function createAccessorData(node) { - const name = astUtils.getStaticPropertyName(node); - const key = (name !== null) ? name : sourceCode.getTokens(node.key); - - return { - key, - getters: node.kind === "get" ? [node] : [], - setters: node.kind === "set" ? [node] : [] - }; - } - - /** - * Merges the given `AccessorData` object into the given accessors list. - * @param {AccessorData[]} accessors The list to merge into. - * @param {AccessorData} accessorData The object to merge. - * @returns {AccessorData[]} The same instance with the merged object. - * @private - */ - function mergeAccessorData(accessors, accessorData) { - const equalKeyElement = accessors.find(a => areEqualKeys(a.key, accessorData.key)); - - if (equalKeyElement) { - equalKeyElement.getters.push(...accessorData.getters); - equalKeyElement.setters.push(...accessorData.setters); - } else { - accessors.push(accessorData); - } - - return accessors; - } - - /** - * Checks accessor pairs in the given list of nodes. - * @param {ASTNode[]} nodes The list to check. - * @returns {void} - * @private - */ - function checkList(nodes) { - const accessors = nodes - .filter(isAccessorKind) - .map(createAccessorData) - .reduce(mergeAccessorData, []); - - for (const { getters, setters } of accessors) { - if (checkSetWithoutGet && setters.length && !getters.length) { - reportList(setters, "missingGetter"); - } - if (checkGetWithoutSet && getters.length && !setters.length) { - reportList(getters, "missingSetter"); - } - } - } - - /** - * Checks accessor pairs in an object literal. - * @param {ASTNode} node `ObjectExpression` node to check. - * @returns {void} - * @private - */ - function checkObjectLiteral(node) { - checkList(node.properties.filter(p => p.type === "Property")); - } - - /** - * Checks accessor pairs in a property descriptor. - * @param {ASTNode} node Property descriptor `ObjectExpression` node to check. - * @returns {void} - * @private - */ - function checkPropertyDescriptor(node) { - const namesToCheck = node.properties - .filter(p => p.type === "Property" && p.kind === "init" && !p.computed) - .map(({ key }) => key.name); - - const hasGetter = namesToCheck.includes("get"); - const hasSetter = namesToCheck.includes("set"); - - if (checkSetWithoutGet && hasSetter && !hasGetter) { - report(node, "missingGetter"); - } - if (checkGetWithoutSet && hasGetter && !hasSetter) { - report(node, "missingSetter"); - } - } - - /** - * Checks the given object expression as an object literal and as a possible property descriptor. - * @param {ASTNode} node `ObjectExpression` node to check. - * @returns {void} - * @private - */ - function checkObjectExpression(node) { - checkObjectLiteral(node); - if (isPropertyDescriptor(node)) { - checkPropertyDescriptor(node); - } - } - - /** - * Checks the given class body. - * @param {ASTNode} node `ClassBody` node to check. - * @returns {void} - * @private - */ - function checkClassBody(node) { - const methodDefinitions = node.body.filter(m => m.type === "MethodDefinition"); - - checkList(methodDefinitions.filter(m => m.static)); - checkList(methodDefinitions.filter(m => !m.static)); - } - - const listeners = {}; - - if (checkSetWithoutGet || checkGetWithoutSet) { - listeners.ObjectExpression = checkObjectExpression; - if (enforceForClassMembers) { - listeners.ClassBody = checkClassBody; - } - } - - return listeners; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-bracket-newline.js b/tools/node_modules/eslint/lib/rules/array-bracket-newline.js deleted file mode 100644 index b4b4dd430f65644a5d1b03f69c1bee189f9c6df4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/array-bracket-newline.js +++ /dev/null @@ -1,258 +0,0 @@ -/** - * @fileoverview Rule to enforce linebreaks after open and before close array brackets - * @author Jan Peer Stöcklmair - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce linebreaks after opening and before closing array brackets", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/array-bracket-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consistent"] - }, - { - type: "object", - properties: { - multiline: { - type: "boolean" - }, - minItems: { - type: ["integer", "null"], - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedOpeningLinebreak: "There should be no linebreak after '['.", - unexpectedClosingLinebreak: "There should be no linebreak before ']'.", - missingOpeningLinebreak: "A linebreak is required after '['.", - missingClosingLinebreak: "A linebreak is required before ']'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Normalizes a given option value. - * @param {string|Object|undefined} option An option value to parse. - * @returns {{multiline: boolean, minItems: number}} Normalized option object. - */ - function normalizeOptionValue(option) { - let consistent = false; - let multiline = false; - let minItems = 0; - - if (option) { - if (option === "consistent") { - consistent = true; - minItems = Number.POSITIVE_INFINITY; - } else if (option === "always" || option.minItems === 0) { - minItems = 0; - } else if (option === "never") { - minItems = Number.POSITIVE_INFINITY; - } else { - multiline = Boolean(option.multiline); - minItems = option.minItems || Number.POSITIVE_INFINITY; - } - } else { - consistent = false; - multiline = true; - minItems = Number.POSITIVE_INFINITY; - } - - return { consistent, multiline, minItems }; - } - - /** - * Normalizes a given option value. - * @param {string|Object|undefined} options An option value to parse. - * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. - */ - function normalizeOptions(options) { - const value = normalizeOptionValue(options); - - return { ArrayExpression: value, ArrayPattern: value }; - } - - /** - * Reports that there shouldn't be a linebreak after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoBeginningLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "unexpectedOpeningLinebreak", - fix(fixer) { - const nextToken = sourceCode.getTokenAfter(token, { includeComments: true }); - - if (astUtils.isCommentToken(nextToken)) { - return null; - } - - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a linebreak before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoEndingLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "unexpectedClosingLinebreak", - fix(fixer) { - const previousToken = sourceCode.getTokenBefore(token, { includeComments: true }); - - if (astUtils.isCommentToken(previousToken)) { - return null; - } - - return fixer.removeRange([previousToken.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a linebreak after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingOpeningLinebreak", - fix(fixer) { - return fixer.insertTextAfter(token, "\n"); - } - }); - } - - /** - * Reports that there should be a linebreak before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingLinebreak(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingClosingLinebreak", - fix(fixer) { - return fixer.insertTextBefore(token, "\n"); - } - }); - } - - /** - * Reports a given node if it violated this rule. - * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node. - * @returns {void} - */ - function check(node) { - const elements = node.elements; - const normalizedOptions = normalizeOptions(context.options[0]); - const options = normalizedOptions[node.type]; - const openBracket = sourceCode.getFirstToken(node); - const closeBracket = sourceCode.getLastToken(node); - const firstIncComment = sourceCode.getTokenAfter(openBracket, { includeComments: true }); - const lastIncComment = sourceCode.getTokenBefore(closeBracket, { includeComments: true }); - const first = sourceCode.getTokenAfter(openBracket); - const last = sourceCode.getTokenBefore(closeBracket); - - const needsLinebreaks = ( - elements.length >= options.minItems || - ( - options.multiline && - elements.length > 0 && - firstIncComment.loc.start.line !== lastIncComment.loc.end.line - ) || - ( - elements.length === 0 && - firstIncComment.type === "Block" && - firstIncComment.loc.start.line !== lastIncComment.loc.end.line && - firstIncComment === lastIncComment - ) || - ( - options.consistent && - openBracket.loc.end.line !== first.loc.start.line - ) - ); - - /* - * Use tokens or comments to check multiline or not. - * But use only tokens to check whether linebreaks are needed. - * This allows: - * var arr = [ // eslint-disable-line foo - * 'a' - * ] - */ - - if (needsLinebreaks) { - if (astUtils.isTokenOnSameLine(openBracket, first)) { - reportRequiredBeginningLinebreak(node, openBracket); - } - if (astUtils.isTokenOnSameLine(last, closeBracket)) { - reportRequiredEndingLinebreak(node, closeBracket); - } - } else { - if (!astUtils.isTokenOnSameLine(openBracket, first)) { - reportNoBeginningLinebreak(node, openBracket); - } - if (!astUtils.isTokenOnSameLine(last, closeBracket)) { - reportNoEndingLinebreak(node, closeBracket); - } - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - ArrayPattern: check, - ArrayExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js b/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js deleted file mode 100644 index c2b77a641f7294288cfb358580559ad2b77f914f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/array-bracket-spacing.js +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside of array brackets. - * @author Jamund Ferguson - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside array brackets", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/array-bracket-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - singleValue: { - type: "boolean" - }, - objectsInArrays: { - type: "boolean" - }, - arraysInArrays: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", - unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", - missingSpaceAfter: "A space is required after '{{tokenValue}}'.", - missingSpaceBefore: "A space is required before '{{tokenValue}}'." - } - }, - create(context) { - const spaced = context.options[0] === "always", - sourceCode = context.getSourceCode(); - - /** - * Determines whether an option is set, relative to the spacing option. - * If spaced is "always", then check whether option is set to false. - * If spaced is "never", then check whether option is set to true. - * @param {Object} option The option to exclude. - * @returns {boolean} Whether or not the property is excluded. - */ - function isOptionSet(option) { - return context.options[1] ? context.options[1][option] === !spaced : false; - } - - const options = { - spaced, - singleElementException: isOptionSet("singleValue"), - objectsInArraysException: isOptionSet("objectsInArrays"), - arraysInArraysException: isOptionSet("arraysInArrays") - }; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoBeginningSpace(node, token) { - const nextToken = sourceCode.getTokenAfter(token); - - context.report({ - node, - loc: { start: token.loc.end, end: nextToken.loc.start }, - messageId: "unexpectedSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoEndingSpace(node, token) { - const previousToken = sourceCode.getTokenBefore(token); - - context.report({ - node, - loc: { start: previousToken.loc.end, end: token.loc.start }, - messageId: "unexpectedSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.removeRange([previousToken.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a space after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - /** - * Reports that there should be a space before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingSpace(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - /** - * Determines if a node is an object type - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the node is an object type. - */ - function isObjectType(node) { - return node && (node.type === "ObjectExpression" || node.type === "ObjectPattern"); - } - - /** - * Determines if a node is an array type - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the node is an array type. - */ - function isArrayType(node) { - return node && (node.type === "ArrayExpression" || node.type === "ArrayPattern"); - } - - /** - * Validates the spacing around array brackets - * @param {ASTNode} node The node we're checking for spacing - * @returns {void} - */ - function validateArraySpacing(node) { - if (options.spaced && node.elements.length === 0) { - return; - } - - const first = sourceCode.getFirstToken(node), - second = sourceCode.getFirstToken(node, 1), - last = node.typeAnnotation - ? sourceCode.getTokenBefore(node.typeAnnotation) - : sourceCode.getLastToken(node), - penultimate = sourceCode.getTokenBefore(last), - firstElement = node.elements[0], - lastElement = node.elements[node.elements.length - 1]; - - const openingBracketMustBeSpaced = - options.objectsInArraysException && isObjectType(firstElement) || - options.arraysInArraysException && isArrayType(firstElement) || - options.singleElementException && node.elements.length === 1 - ? !options.spaced : options.spaced; - - const closingBracketMustBeSpaced = - options.objectsInArraysException && isObjectType(lastElement) || - options.arraysInArraysException && isArrayType(lastElement) || - options.singleElementException && node.elements.length === 1 - ? !options.spaced : options.spaced; - - if (astUtils.isTokenOnSameLine(first, second)) { - if (openingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(first, second)) { - reportRequiredBeginningSpace(node, first); - } - if (!openingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(first, second)) { - reportNoBeginningSpace(node, first); - } - } - - if (first !== penultimate && astUtils.isTokenOnSameLine(penultimate, last)) { - if (closingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(penultimate, last)) { - reportRequiredEndingSpace(node, last); - } - if (!closingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(penultimate, last)) { - reportNoEndingSpace(node, last); - } - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ArrayPattern: validateArraySpacing, - ArrayExpression: validateArraySpacing - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-callback-return.js b/tools/node_modules/eslint/lib/rules/array-callback-return.js deleted file mode 100644 index 4e25674f6fb27b8e5da002b101eb92cc36ca34bc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/array-callback-return.js +++ /dev/null @@ -1,285 +0,0 @@ -/** - * @fileoverview Rule to enforce return statements in callbacks of array's methods - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; -const TARGET_METHODS = /^(?:every|filter|find(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort)$/u; - -/** - * Checks a given code path segment is reachable. - * @param {CodePathSegment} segment A segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Checks a given node is a member access which has the specified name's - * property. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a member access which has - * the specified name's property. The node may be a `(Chain|Member)Expression` node. - */ -function isTargetMethod(node) { - return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS); -} - -/** - * Checks whether or not a given node is a function expression which is the - * callback of an array method, returning the method name. - * @param {ASTNode} node A node to check. This is one of - * FunctionExpression or ArrowFunctionExpression. - * @returns {string} The method name if the node is a callback method, - * null otherwise. - */ -function getArrayMethodName(node) { - let currentNode = node; - - while (currentNode) { - const parent = currentNode.parent; - - switch (parent.type) { - - /* - * Looks up the destination. e.g., - * foo.every(nativeFoo || function foo() { ... }); - */ - case "LogicalExpression": - case "ConditionalExpression": - case "ChainExpression": - currentNode = parent; - break; - - /* - * If the upper function is IIFE, checks the destination of the return value. - * e.g. - * foo.every((function() { - * // setup... - * return function callback() { ... }; - * })()); - */ - case "ReturnStatement": { - const func = astUtils.getUpperFunction(parent); - - if (func === null || !astUtils.isCallee(func)) { - return null; - } - currentNode = func.parent; - break; - } - - /* - * e.g. - * Array.from([], function() {}); - * list.every(function() {}); - */ - case "CallExpression": - if (astUtils.isArrayFromMethod(parent.callee)) { - if ( - parent.arguments.length >= 2 && - parent.arguments[1] === currentNode - ) { - return "from"; - } - } - if (isTargetMethod(parent.callee)) { - if ( - parent.arguments.length >= 1 && - parent.arguments[0] === currentNode - ) { - return astUtils.getStaticPropertyName(parent.callee); - } - } - return null; - - // Otherwise this node is not target. - default: - return null; - } - } - - /* istanbul ignore next: unreachable */ - return null; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce `return` statements in callbacks of array methods", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/array-callback-return" - }, - - schema: [ - { - type: "object", - properties: { - allowImplicit: { - type: "boolean", - default: false - }, - checkForEach: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - expectedAtEnd: "Expected to return a value at the end of {{name}}.", - expectedInside: "Expected to return a value in {{name}}.", - expectedReturnValue: "{{name}} expected a return value.", - expectedNoReturnValue: "{{name}} did not expect a return value." - } - }, - - create(context) { - - const options = context.options[0] || { allowImplicit: false, checkForEach: false }; - const sourceCode = context.getSourceCode(); - - let funcInfo = { - arrayMethodName: null, - upper: null, - codePath: null, - hasReturn: false, - shouldCheck: false, - node: null - }; - - /** - * Checks whether or not the last code path segment is reachable. - * Then reports this function if the segment is reachable. - * - * If the last code path segment is reachable, there are paths which are not - * returned or thrown. - * @param {ASTNode} node A node to check. - * @returns {void} - */ - function checkLastSegment(node) { - - if (!funcInfo.shouldCheck) { - return; - } - - let messageId = null; - - if (funcInfo.arrayMethodName === "forEach") { - if (options.checkForEach && node.type === "ArrowFunctionExpression" && node.expression) { - messageId = "expectedNoReturnValue"; - } - } else { - if (node.body.type === "BlockStatement" && funcInfo.codePath.currentSegments.some(isReachable)) { - messageId = funcInfo.hasReturn ? "expectedAtEnd" : "expectedInside"; - } - } - - if (messageId) { - let name = astUtils.getFunctionNameWithKind(node); - - name = messageId === "expectedNoReturnValue" ? lodash.upperFirst(name) : name; - context.report({ - node, - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - messageId, - data: { name } - }); - } - } - - return { - - // Stacks this function's information. - onCodePathStart(codePath, node) { - - let methodName = null; - - if (TARGET_NODE_TYPE.test(node.type)) { - methodName = getArrayMethodName(node); - } - - funcInfo = { - arrayMethodName: methodName, - upper: funcInfo, - codePath, - hasReturn: false, - shouldCheck: - methodName && - !node.async && - !node.generator, - node - }; - }, - - // Pops this function's information. - onCodePathEnd() { - funcInfo = funcInfo.upper; - }, - - // Checks the return statement is valid. - ReturnStatement(node) { - - if (!funcInfo.shouldCheck) { - return; - } - - funcInfo.hasReturn = true; - - let messageId = null; - - if (funcInfo.arrayMethodName === "forEach") { - - // if checkForEach: true, returning a value at any path inside a forEach is not allowed - if (options.checkForEach && node.argument) { - messageId = "expectedNoReturnValue"; - } - } else { - - // if allowImplicit: false, should also check node.argument - if (!options.allowImplicit && !node.argument) { - messageId = "expectedReturnValue"; - } - } - - if (messageId) { - context.report({ - node, - messageId, - data: { - name: lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node)) - } - }); - } - }, - - // Reports a given function if the last path is reachable. - "FunctionExpression:exit": checkLastSegment, - "ArrowFunctionExpression:exit": checkLastSegment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/array-element-newline.js b/tools/node_modules/eslint/lib/rules/array-element-newline.js deleted file mode 100644 index b7a967865b92a16c8f128ec4eb812bc39d543a65..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/array-element-newline.js +++ /dev/null @@ -1,301 +0,0 @@ -/** - * @fileoverview Rule to enforce line breaks after each array element - * @author Jan Peer Stöcklmair - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce line breaks after each array element", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/array-element-newline" - }, - - fixable: "whitespace", - - schema: { - definitions: { - basicConfig: { - oneOf: [ - { - enum: ["always", "never", "consistent"] - }, - { - type: "object", - properties: { - multiline: { - type: "boolean" - }, - minItems: { - type: ["integer", "null"], - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - }, - items: [ - { - oneOf: [ - { - $ref: "#/definitions/basicConfig" - }, - { - type: "object", - properties: { - ArrayExpression: { - $ref: "#/definitions/basicConfig" - }, - ArrayPattern: { - $ref: "#/definitions/basicConfig" - } - }, - additionalProperties: false, - minProperties: 1 - } - ] - } - ] - }, - - messages: { - unexpectedLineBreak: "There should be no linebreak here.", - missingLineBreak: "There should be a linebreak after this element." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Normalizes a given option value. - * @param {string|Object|undefined} providedOption An option value to parse. - * @returns {{multiline: boolean, minItems: number}} Normalized option object. - */ - function normalizeOptionValue(providedOption) { - let consistent = false; - let multiline = false; - let minItems; - - const option = providedOption || "always"; - - if (!option || option === "always" || option.minItems === 0) { - minItems = 0; - } else if (option === "never") { - minItems = Number.POSITIVE_INFINITY; - } else if (option === "consistent") { - consistent = true; - minItems = Number.POSITIVE_INFINITY; - } else { - multiline = Boolean(option.multiline); - minItems = option.minItems || Number.POSITIVE_INFINITY; - } - - return { consistent, multiline, minItems }; - } - - /** - * Normalizes a given option value. - * @param {string|Object|undefined} options An option value to parse. - * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object. - */ - function normalizeOptions(options) { - if (options && (options.ArrayExpression || options.ArrayPattern)) { - let expressionOptions, patternOptions; - - if (options.ArrayExpression) { - expressionOptions = normalizeOptionValue(options.ArrayExpression); - } - - if (options.ArrayPattern) { - patternOptions = normalizeOptionValue(options.ArrayPattern); - } - - return { ArrayExpression: expressionOptions, ArrayPattern: patternOptions }; - } - - const value = normalizeOptionValue(options); - - return { ArrayExpression: value, ArrayPattern: value }; - } - - /** - * Reports that there shouldn't be a line break after the first token - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoLineBreak(token) { - const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); - - context.report({ - loc: { - start: tokenBefore.loc.end, - end: token.loc.start - }, - messageId: "unexpectedLineBreak", - fix(fixer) { - if (astUtils.isCommentToken(tokenBefore)) { - return null; - } - - if (!astUtils.isTokenOnSameLine(tokenBefore, token)) { - return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " "); - } - - /* - * This will check if the comma is on the same line as the next element - * Following array: - * [ - * 1 - * , 2 - * , 3 - * ] - * - * will be fixed to: - * [ - * 1, 2, 3 - * ] - */ - const twoTokensBefore = sourceCode.getTokenBefore(tokenBefore, { includeComments: true }); - - if (astUtils.isCommentToken(twoTokensBefore)) { - return null; - } - - return fixer.replaceTextRange([twoTokensBefore.range[1], tokenBefore.range[0]], ""); - - } - }); - } - - /** - * Reports that there should be a line break after the first token - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredLineBreak(token) { - const tokenBefore = sourceCode.getTokenBefore(token, { includeComments: true }); - - context.report({ - loc: { - start: tokenBefore.loc.end, - end: token.loc.start - }, - messageId: "missingLineBreak", - fix(fixer) { - return fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n"); - } - }); - } - - /** - * Reports a given node if it violated this rule. - * @param {ASTNode} node A node to check. This is an ObjectExpression node or an ObjectPattern node. - * @returns {void} - */ - function check(node) { - const elements = node.elements; - const normalizedOptions = normalizeOptions(context.options[0]); - const options = normalizedOptions[node.type]; - - if (!options) { - return; - } - - let elementBreak = false; - - /* - * MULTILINE: true - * loop through every element and check - * if at least one element has linebreaks inside - * this ensures that following is not valid (due to elements are on the same line): - * - * [ - * 1, - * 2, - * 3 - * ] - */ - if (options.multiline) { - elementBreak = elements - .filter(element => element !== null) - .some(element => element.loc.start.line !== element.loc.end.line); - } - - const linebreaksCount = node.elements.map((element, i) => { - const previousElement = elements[i - 1]; - - if (i === 0 || element === null || previousElement === null) { - return false; - } - - const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken); - const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken); - const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken); - - return !astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement); - }).filter(isBreak => isBreak === true).length; - - const needsLinebreaks = ( - elements.length >= options.minItems || - ( - options.multiline && - elementBreak - ) || - ( - options.consistent && - linebreaksCount > 0 && - linebreaksCount < node.elements.length - ) - ); - - elements.forEach((element, i) => { - const previousElement = elements[i - 1]; - - if (i === 0 || element === null || previousElement === null) { - return; - } - - const commaToken = sourceCode.getFirstTokenBetween(previousElement, element, astUtils.isCommaToken); - const lastTokenOfPreviousElement = sourceCode.getTokenBefore(commaToken); - const firstTokenOfCurrentElement = sourceCode.getTokenAfter(commaToken); - - if (needsLinebreaks) { - if (astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { - reportRequiredLineBreak(firstTokenOfCurrentElement); - } - } else { - if (!astUtils.isTokenOnSameLine(lastTokenOfPreviousElement, firstTokenOfCurrentElement)) { - reportNoLineBreak(firstTokenOfCurrentElement); - } - } - }); - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - ArrayPattern: check, - ArrayExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/arrow-body-style.js b/tools/node_modules/eslint/lib/rules/arrow-body-style.js deleted file mode 100644 index be9f4ea720080ebd5fca02c10035fe3df7f5c44c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/arrow-body-style.js +++ /dev/null @@ -1,286 +0,0 @@ -/** - * @fileoverview Rule to require braces in arrow function body. - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require braces around arrow function bodies", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/arrow-body-style" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "never"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["as-needed"] - }, - { - type: "object", - properties: { - requireReturnForObjectLiteral: { type: "boolean" } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - fixable: "code", - - messages: { - unexpectedOtherBlock: "Unexpected block statement surrounding arrow body.", - unexpectedEmptyBlock: "Unexpected block statement surrounding arrow body; put a value of `undefined` immediately after the `=>`.", - unexpectedObjectBlock: "Unexpected block statement surrounding arrow body; parenthesize the returned value and move it immediately after the `=>`.", - unexpectedSingleBlock: "Unexpected block statement surrounding arrow body; move the returned value immediately after the `=>`.", - expectedBlock: "Expected block statement surrounding arrow body." - } - }, - - create(context) { - const options = context.options; - const always = options[0] === "always"; - const asNeeded = !options[0] || options[0] === "as-needed"; - const never = options[0] === "never"; - const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral; - const sourceCode = context.getSourceCode(); - let funcInfo = null; - - /** - * Checks whether the given node has ASI problem or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if it changes semantics if `;` or `}` followed by the token are removed. - */ - function hasASIProblem(token) { - return token && token.type === "Punctuator" && /^[([/`+-]/u.test(token.value); - } - - /** - * Gets the closing parenthesis which is the pair of the given opening parenthesis. - * @param {Token} token The opening parenthesis token to get. - * @returns {Token} The found closing parenthesis token. - */ - function findClosingParen(token) { - let node = sourceCode.getNodeByRangeIndex(token.range[0]); - - while (!astUtils.isParenthesised(sourceCode, node)) { - node = node.parent; - } - return sourceCode.getTokenAfter(node); - } - - /** - * Check whether the node is inside of a for loop's init - * @param {ASTNode} node node is inside for loop - * @returns {boolean} `true` if the node is inside of a for loop, else `false` - */ - function isInsideForLoopInitializer(node) { - if (node && node.parent) { - if (node.parent.type === "ForStatement" && node.parent.init === node) { - return true; - } - return isInsideForLoopInitializer(node.parent); - } - return false; - } - - /** - * Determines whether a arrow function body needs braces - * @param {ASTNode} node The arrow function node. - * @returns {void} - */ - function validate(node) { - const arrowBody = node.body; - - if (arrowBody.type === "BlockStatement") { - const blockBody = arrowBody.body; - - if (blockBody.length !== 1 && !never) { - return; - } - - if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" && - blockBody[0].argument && blockBody[0].argument.type === "ObjectExpression") { - return; - } - - if (never || asNeeded && blockBody[0].type === "ReturnStatement") { - let messageId; - - if (blockBody.length === 0) { - messageId = "unexpectedEmptyBlock"; - } else if (blockBody.length > 1) { - messageId = "unexpectedOtherBlock"; - } else if (blockBody[0].argument === null) { - messageId = "unexpectedSingleBlock"; - } else if (astUtils.isOpeningBraceToken(sourceCode.getFirstToken(blockBody[0], { skip: 1 }))) { - messageId = "unexpectedObjectBlock"; - } else { - messageId = "unexpectedSingleBlock"; - } - - context.report({ - node, - loc: arrowBody.loc.start, - messageId, - fix(fixer) { - const fixes = []; - - if (blockBody.length !== 1 || - blockBody[0].type !== "ReturnStatement" || - !blockBody[0].argument || - hasASIProblem(sourceCode.getTokenAfter(arrowBody)) - ) { - return fixes; - } - - const openingBrace = sourceCode.getFirstToken(arrowBody); - const closingBrace = sourceCode.getLastToken(arrowBody); - const firstValueToken = sourceCode.getFirstToken(blockBody[0], 1); - const lastValueToken = sourceCode.getLastToken(blockBody[0]); - const commentsExist = - sourceCode.commentsExistBetween(openingBrace, firstValueToken) || - sourceCode.commentsExistBetween(lastValueToken, closingBrace); - - /* - * Remove tokens around the return value. - * If comments don't exist, remove extra spaces as well. - */ - if (commentsExist) { - fixes.push( - fixer.remove(openingBrace), - fixer.remove(closingBrace), - fixer.remove(sourceCode.getTokenAfter(openingBrace)) // return keyword - ); - } else { - fixes.push( - fixer.removeRange([openingBrace.range[0], firstValueToken.range[0]]), - fixer.removeRange([lastValueToken.range[1], closingBrace.range[1]]) - ); - } - - /* - * If the first token of the reutrn value is `{` or the return value is a sequence expression, - * enclose the return value by parentheses to avoid syntax error. - */ - if (astUtils.isOpeningBraceToken(firstValueToken) || blockBody[0].argument.type === "SequenceExpression" || (funcInfo.hasInOperator && isInsideForLoopInitializer(node))) { - if (!astUtils.isParenthesised(sourceCode, blockBody[0].argument)) { - fixes.push( - fixer.insertTextBefore(firstValueToken, "("), - fixer.insertTextAfter(lastValueToken, ")") - ); - } - } - - /* - * If the last token of the return statement is semicolon, remove it. - * Non-block arrow body is an expression, not a statement. - */ - if (astUtils.isSemicolonToken(lastValueToken)) { - fixes.push(fixer.remove(lastValueToken)); - } - - return fixes; - } - }); - } - } else { - if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) { - context.report({ - node, - loc: arrowBody.loc.start, - messageId: "expectedBlock", - fix(fixer) { - const fixes = []; - const arrowToken = sourceCode.getTokenBefore(arrowBody, astUtils.isArrowToken); - const [firstTokenAfterArrow, secondTokenAfterArrow] = sourceCode.getTokensAfter(arrowToken, { count: 2 }); - const lastToken = sourceCode.getLastToken(node); - const isParenthesisedObjectLiteral = - astUtils.isOpeningParenToken(firstTokenAfterArrow) && - astUtils.isOpeningBraceToken(secondTokenAfterArrow); - - // If the value is object literal, remove parentheses which were forced by syntax. - if (isParenthesisedObjectLiteral) { - const openingParenToken = firstTokenAfterArrow; - const openingBraceToken = secondTokenAfterArrow; - - if (astUtils.isTokenOnSameLine(openingParenToken, openingBraceToken)) { - fixes.push(fixer.replaceText(openingParenToken, "{return ")); - } else { - - // Avoid ASI - fixes.push( - fixer.replaceText(openingParenToken, "{"), - fixer.insertTextBefore(openingBraceToken, "return ") - ); - } - - // Closing paren for the object doesn't have to be lastToken, e.g.: () => ({}).foo() - fixes.push(fixer.remove(findClosingParen(openingBraceToken))); - fixes.push(fixer.insertTextAfter(lastToken, "}")); - - } else { - fixes.push(fixer.insertTextBefore(firstTokenAfterArrow, "{return ")); - fixes.push(fixer.insertTextAfter(lastToken, "}")); - } - - return fixes; - } - }); - } - } - } - - return { - "BinaryExpression[operator='in']"() { - let info = funcInfo; - - while (info) { - info.hasInOperator = true; - info = info.upper; - } - }, - ArrowFunctionExpression() { - funcInfo = { - upper: funcInfo, - hasInOperator: false - }; - }, - "ArrowFunctionExpression:exit"(node) { - validate(node); - funcInfo = funcInfo.upper; - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/arrow-parens.js b/tools/node_modules/eslint/lib/rules/arrow-parens.js deleted file mode 100644 index bfd32447ac6f3d9dec93fd9f5ce5b2df874b1068..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/arrow-parens.js +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @fileoverview Rule to require parens in arrow function arguments. - * @author Jxck - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Get location should be reported by AST node. - * @param {ASTNode} node AST Node. - * @returns {Location} Location information. - */ -function getLocation(node) { - return { - start: node.params[0].loc.start, - end: node.params[node.params.length - 1].loc.end - }; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parentheses around arrow function arguments", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/arrow-parens" - }, - - fixable: "code", - - schema: [ - { - enum: ["always", "as-needed"] - }, - { - type: "object", - properties: { - requireForBlockBody: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedParens: "Unexpected parentheses around single function argument.", - expectedParens: "Expected parentheses around arrow function argument.", - - unexpectedParensInline: "Unexpected parentheses around single function argument having a body with no curly braces.", - expectedParensBlock: "Expected parentheses around arrow function argument having a body with curly braces." - } - }, - - create(context) { - const asNeeded = context.options[0] === "as-needed"; - const requireForBlockBody = asNeeded && context.options[1] && context.options[1].requireForBlockBody === true; - - const sourceCode = context.getSourceCode(); - - /** - * Determines whether a arrow function argument end with `)` - * @param {ASTNode} node The arrow function node. - * @returns {void} - */ - function parens(node) { - const isAsync = node.async; - const firstTokenOfParam = sourceCode.getFirstToken(node, isAsync ? 1 : 0); - - /** - * Remove the parenthesis around a parameter - * @param {Fixer} fixer Fixer - * @returns {string} fixed parameter - */ - function fixParamsWithParenthesis(fixer) { - const paramToken = sourceCode.getTokenAfter(firstTokenOfParam); - - /* - * ES8 allows Trailing commas in function parameter lists and calls - * https://github.com/eslint/eslint/issues/8834 - */ - const closingParenToken = sourceCode.getTokenAfter(paramToken, astUtils.isClosingParenToken); - const asyncToken = isAsync ? sourceCode.getTokenBefore(firstTokenOfParam) : null; - const shouldAddSpaceForAsync = asyncToken && (asyncToken.range[1] === firstTokenOfParam.range[0]); - - return fixer.replaceTextRange([ - firstTokenOfParam.range[0], - closingParenToken.range[1] - ], `${shouldAddSpaceForAsync ? " " : ""}${paramToken.value}`); - } - - /** - * Checks whether there are comments inside the params or not. - * @returns {boolean} `true` if there are comments inside of parens, else `false` - */ - function hasCommentsInParens() { - if (astUtils.isOpeningParenToken(firstTokenOfParam)) { - const closingParenToken = sourceCode.getTokenAfter(node.params[0], astUtils.isClosingParenToken); - - return closingParenToken && sourceCode.commentsExistBetween(firstTokenOfParam, closingParenToken); - } - return false; - - } - - if (hasCommentsInParens()) { - return; - } - - // "as-needed", { "requireForBlockBody": true }: x => x - if ( - requireForBlockBody && - node.params[0].type === "Identifier" && - !node.params[0].typeAnnotation && - node.body.type !== "BlockStatement" && - !node.returnType - ) { - if (astUtils.isOpeningParenToken(firstTokenOfParam)) { - context.report({ - node, - messageId: "unexpectedParensInline", - loc: getLocation(node), - fix: fixParamsWithParenthesis - }); - } - return; - } - - if ( - requireForBlockBody && - node.body.type === "BlockStatement" - ) { - if (!astUtils.isOpeningParenToken(firstTokenOfParam)) { - context.report({ - node, - messageId: "expectedParensBlock", - loc: getLocation(node), - fix(fixer) { - return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`); - } - }); - } - return; - } - - // "as-needed": x => x - if (asNeeded && - node.params[0].type === "Identifier" && - !node.params[0].typeAnnotation && - !node.returnType - ) { - if (astUtils.isOpeningParenToken(firstTokenOfParam)) { - context.report({ - node, - messageId: "unexpectedParens", - loc: getLocation(node), - fix: fixParamsWithParenthesis - }); - } - return; - } - - if (firstTokenOfParam.type === "Identifier") { - const after = sourceCode.getTokenAfter(firstTokenOfParam); - - // (x) => x - if (after.value !== ")") { - context.report({ - node, - messageId: "expectedParens", - loc: getLocation(node), - fix(fixer) { - return fixer.replaceText(firstTokenOfParam, `(${firstTokenOfParam.value})`); - } - }); - } - } - } - - return { - "ArrowFunctionExpression[params.length=1]": parens - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/arrow-spacing.js b/tools/node_modules/eslint/lib/rules/arrow-spacing.js deleted file mode 100644 index e5110c6c87d43f72b6a50bfbbefe8fb38fc23d08..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/arrow-spacing.js +++ /dev/null @@ -1,161 +0,0 @@ -/** - * @fileoverview Rule to define spacing before/after arrow function's arrow. - * @author Jxck - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after the arrow in arrow functions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/arrow-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { - type: "boolean", - default: true - }, - after: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - expectedBefore: "Missing space before =>.", - unexpectedBefore: "Unexpected space before =>.", - - expectedAfter: "Missing space after =>.", - unexpectedAfter: "Unexpected space after =>." - } - }, - - create(context) { - - // merge rules with default - const rule = Object.assign({}, context.options[0]); - - rule.before = rule.before !== false; - rule.after = rule.after !== false; - - const sourceCode = context.getSourceCode(); - - /** - * Get tokens of arrow(`=>`) and before/after arrow. - * @param {ASTNode} node The arrow function node. - * @returns {Object} Tokens of arrow and before/after arrow. - */ - function getTokens(node) { - const arrow = sourceCode.getTokenBefore(node.body, astUtils.isArrowToken); - - return { - before: sourceCode.getTokenBefore(arrow), - arrow, - after: sourceCode.getTokenAfter(arrow) - }; - } - - /** - * Count spaces before/after arrow(`=>`) token. - * @param {Object} tokens Tokens before/after arrow. - * @returns {Object} count of space before/after arrow. - */ - function countSpaces(tokens) { - const before = tokens.arrow.range[0] - tokens.before.range[1]; - const after = tokens.after.range[0] - tokens.arrow.range[1]; - - return { before, after }; - } - - /** - * Determines whether space(s) before after arrow(`=>`) is satisfy rule. - * if before/after value is `true`, there should be space(s). - * if before/after value is `false`, there should be no space. - * @param {ASTNode} node The arrow function node. - * @returns {void} - */ - function spaces(node) { - const tokens = getTokens(node); - const countSpace = countSpaces(tokens); - - if (rule.before) { - - // should be space(s) before arrow - if (countSpace.before === 0) { - context.report({ - node: tokens.before, - messageId: "expectedBefore", - fix(fixer) { - return fixer.insertTextBefore(tokens.arrow, " "); - } - }); - } - } else { - - // should be no space before arrow - if (countSpace.before > 0) { - context.report({ - node: tokens.before, - messageId: "unexpectedBefore", - fix(fixer) { - return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]); - } - }); - } - } - - if (rule.after) { - - // should be space(s) after arrow - if (countSpace.after === 0) { - context.report({ - node: tokens.after, - messageId: "expectedAfter", - fix(fixer) { - return fixer.insertTextAfter(tokens.arrow, " "); - } - }); - } - } else { - - // should be no space after arrow - if (countSpace.after > 0) { - context.report({ - node: tokens.after, - messageId: "unexpectedAfter", - fix(fixer) { - return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]); - } - }); - } - } - } - - return { - ArrowFunctionExpression: spaces - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/block-scoped-var.js b/tools/node_modules/eslint/lib/rules/block-scoped-var.js deleted file mode 100644 index 481057ba6c7c6bdc7adc1f2be5e2ddf90f2720b9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/block-scoped-var.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule to check for "block scoped" variables by binding context - * @author Matt DuVall - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the use of variables within the scope they are defined", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/block-scoped-var" - }, - - schema: [], - - messages: { - outOfScope: "'{{name}}' used outside of binding context." - } - }, - - create(context) { - let stack = []; - - /** - * Makes a block scope. - * @param {ASTNode} node A node of a scope. - * @returns {void} - */ - function enterScope(node) { - stack.push(node.range); - } - - /** - * Pops the last block scope. - * @returns {void} - */ - function exitScope() { - stack.pop(); - } - - /** - * Reports a given reference. - * @param {eslint-scope.Reference} reference A reference to report. - * @returns {void} - */ - function report(reference) { - const identifier = reference.identifier; - - context.report({ node: identifier, messageId: "outOfScope", data: { name: identifier.name } }); - } - - /** - * Finds and reports references which are outside of valid scopes. - * @param {ASTNode} node A node to get variables. - * @returns {void} - */ - function checkForVariables(node) { - if (node.kind !== "var") { - return; - } - - // Defines a predicate to check whether or not a given reference is outside of valid scope. - const scopeRange = stack[stack.length - 1]; - - /** - * Check if a reference is out of scope - * @param {ASTNode} reference node to examine - * @returns {boolean} True is its outside the scope - * @private - */ - function isOutsideOfScope(reference) { - const idRange = reference.identifier.range; - - return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1]; - } - - // Gets declared variables, and checks its references. - const variables = context.getDeclaredVariables(node); - - for (let i = 0; i < variables.length; ++i) { - - // Reports. - variables[i] - .references - .filter(isOutsideOfScope) - .forEach(report); - } - } - - return { - Program(node) { - stack = [node.range]; - }, - - // Manages scopes. - BlockStatement: enterScope, - "BlockStatement:exit": exitScope, - ForStatement: enterScope, - "ForStatement:exit": exitScope, - ForInStatement: enterScope, - "ForInStatement:exit": exitScope, - ForOfStatement: enterScope, - "ForOfStatement:exit": exitScope, - SwitchStatement: enterScope, - "SwitchStatement:exit": exitScope, - CatchClause: enterScope, - "CatchClause:exit": exitScope, - - // Finds and reports references which are outside of valid scope. - VariableDeclaration: checkForVariables - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/block-spacing.js b/tools/node_modules/eslint/lib/rules/block-spacing.js deleted file mode 100644 index c4b30b0b70b9839bd145fdd36c5e947d0d1d1a72..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/block-spacing.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @fileoverview A rule to disallow or enforce spaces inside of single line blocks. - * @author Toru Nagashima - */ - -"use strict"; - -const util = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow or enforce spaces inside of blocks after opening block and before closing block", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/block-spacing" - }, - - fixable: "whitespace", - - schema: [ - { enum: ["always", "never"] } - ], - - messages: { - missing: "Requires a space {{location}} '{{token}}'.", - extra: "Unexpected space(s) {{location}} '{{token}}'." - } - }, - - create(context) { - const always = (context.options[0] !== "never"), - messageId = always ? "missing" : "extra", - sourceCode = context.getSourceCode(); - - /** - * Gets the open brace token from a given node. - * @param {ASTNode} node A BlockStatement/SwitchStatement node to get. - * @returns {Token} The token of the open brace. - */ - function getOpenBrace(node) { - if (node.type === "SwitchStatement") { - if (node.cases.length > 0) { - return sourceCode.getTokenBefore(node.cases[0]); - } - return sourceCode.getLastToken(node, 1); - } - return sourceCode.getFirstToken(node); - } - - /** - * Checks whether or not: - * - given tokens are on same line. - * - there is/isn't a space between given tokens. - * @param {Token} left A token to check. - * @param {Token} right The token which is next to `left`. - * @returns {boolean} - * When the option is `"always"`, `true` if there are one or more spaces between given tokens. - * When the option is `"never"`, `true` if there are not any spaces between given tokens. - * If given tokens are not on same line, it's always `true`. - */ - function isValid(left, right) { - return ( - !util.isTokenOnSameLine(left, right) || - sourceCode.isSpaceBetweenTokens(left, right) === always - ); - } - - /** - * Reports invalid spacing style inside braces. - * @param {ASTNode} node A BlockStatement/SwitchStatement node to get. - * @returns {void} - */ - function checkSpacingInsideBraces(node) { - - // Gets braces and the first/last token of content. - const openBrace = getOpenBrace(node); - const closeBrace = sourceCode.getLastToken(node); - const firstToken = sourceCode.getTokenAfter(openBrace, { includeComments: true }); - const lastToken = sourceCode.getTokenBefore(closeBrace, { includeComments: true }); - - // Skip if the node is invalid or empty. - if (openBrace.type !== "Punctuator" || - openBrace.value !== "{" || - closeBrace.type !== "Punctuator" || - closeBrace.value !== "}" || - firstToken === closeBrace - ) { - return; - } - - // Skip line comments for option never - if (!always && firstToken.type === "Line") { - return; - } - - // Check. - if (!isValid(openBrace, firstToken)) { - let loc = openBrace.loc; - - if (messageId === "extra") { - loc = { - start: openBrace.loc.end, - end: firstToken.loc.start - }; - } - - context.report({ - node, - loc, - messageId, - data: { - location: "after", - token: openBrace.value - }, - fix(fixer) { - if (always) { - return fixer.insertTextBefore(firstToken, " "); - } - - return fixer.removeRange([openBrace.range[1], firstToken.range[0]]); - } - }); - } - if (!isValid(lastToken, closeBrace)) { - let loc = closeBrace.loc; - - if (messageId === "extra") { - loc = { - start: lastToken.loc.end, - end: closeBrace.loc.start - }; - } - context.report({ - node, - loc, - messageId, - data: { - location: "before", - token: closeBrace.value - }, - fix(fixer) { - if (always) { - return fixer.insertTextAfter(lastToken, " "); - } - - return fixer.removeRange([lastToken.range[1], closeBrace.range[0]]); - } - }); - } - } - - return { - BlockStatement: checkSpacingInsideBraces, - SwitchStatement: checkSpacingInsideBraces - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/brace-style.js b/tools/node_modules/eslint/lib/rules/brace-style.js deleted file mode 100644 index 07223d10d4a3b45dfea0ea6dfa56de66a3e1d406..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/brace-style.js +++ /dev/null @@ -1,188 +0,0 @@ -/** - * @fileoverview Rule to flag block statements that do not use the one true brace style - * @author Ian Christian Myers - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent brace style for blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/brace-style" - }, - - schema: [ - { - enum: ["1tbs", "stroustrup", "allman"] - }, - { - type: "object", - properties: { - allowSingleLine: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "whitespace", - - messages: { - nextLineOpen: "Opening curly brace does not appear on the same line as controlling statement.", - sameLineOpen: "Opening curly brace appears on the same line as controlling statement.", - blockSameLine: "Statement inside of curly braces should be on next line.", - nextLineClose: "Closing curly brace does not appear on the same line as the subsequent block.", - singleLineClose: "Closing curly brace should be on the same line as opening curly brace or on the line after the previous block.", - sameLineClose: "Closing curly brace appears on the same line as the subsequent block." - } - }, - - create(context) { - const style = context.options[0] || "1tbs", - params = context.options[1] || {}, - sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Fixes a place where a newline unexpectedly appears - * @param {Token} firstToken The token before the unexpected newline - * @param {Token} secondToken The token after the unexpected newline - * @returns {Function} A fixer function to remove the newlines between the tokens - */ - function removeNewlineBetween(firstToken, secondToken) { - const textRange = [firstToken.range[1], secondToken.range[0]]; - const textBetween = sourceCode.text.slice(textRange[0], textRange[1]); - - // Don't do a fix if there is a comment between the tokens - if (textBetween.trim()) { - return null; - } - return fixer => fixer.replaceTextRange(textRange, " "); - } - - /** - * Validates a pair of curly brackets based on the user's config - * @param {Token} openingCurly The opening curly bracket - * @param {Token} closingCurly The closing curly bracket - * @returns {void} - */ - function validateCurlyPair(openingCurly, closingCurly) { - const tokenBeforeOpeningCurly = sourceCode.getTokenBefore(openingCurly); - const tokenAfterOpeningCurly = sourceCode.getTokenAfter(openingCurly); - const tokenBeforeClosingCurly = sourceCode.getTokenBefore(closingCurly); - const singleLineException = params.allowSingleLine && astUtils.isTokenOnSameLine(openingCurly, closingCurly); - - if (style !== "allman" && !astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly)) { - context.report({ - node: openingCurly, - messageId: "nextLineOpen", - fix: removeNewlineBetween(tokenBeforeOpeningCurly, openingCurly) - }); - } - - if (style === "allman" && astUtils.isTokenOnSameLine(tokenBeforeOpeningCurly, openingCurly) && !singleLineException) { - context.report({ - node: openingCurly, - messageId: "sameLineOpen", - fix: fixer => fixer.insertTextBefore(openingCurly, "\n") - }); - } - - if (astUtils.isTokenOnSameLine(openingCurly, tokenAfterOpeningCurly) && tokenAfterOpeningCurly !== closingCurly && !singleLineException) { - context.report({ - node: openingCurly, - messageId: "blockSameLine", - fix: fixer => fixer.insertTextAfter(openingCurly, "\n") - }); - } - - if (tokenBeforeClosingCurly !== openingCurly && !singleLineException && astUtils.isTokenOnSameLine(tokenBeforeClosingCurly, closingCurly)) { - context.report({ - node: closingCurly, - messageId: "singleLineClose", - fix: fixer => fixer.insertTextBefore(closingCurly, "\n") - }); - } - } - - /** - * Validates the location of a token that appears before a keyword (e.g. a newline before `else`) - * @param {Token} curlyToken The closing curly token. This is assumed to precede a keyword token (such as `else` or `finally`). - * @returns {void} - */ - function validateCurlyBeforeKeyword(curlyToken) { - const keywordToken = sourceCode.getTokenAfter(curlyToken); - - if (style === "1tbs" && !astUtils.isTokenOnSameLine(curlyToken, keywordToken)) { - context.report({ - node: curlyToken, - messageId: "nextLineClose", - fix: removeNewlineBetween(curlyToken, keywordToken) - }); - } - - if (style !== "1tbs" && astUtils.isTokenOnSameLine(curlyToken, keywordToken)) { - context.report({ - node: curlyToken, - messageId: "sameLineClose", - fix: fixer => fixer.insertTextAfter(curlyToken, "\n") - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - BlockStatement(node) { - if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { - validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node)); - } - }, - ClassBody(node) { - validateCurlyPair(sourceCode.getFirstToken(node), sourceCode.getLastToken(node)); - }, - SwitchStatement(node) { - const closingCurly = sourceCode.getLastToken(node); - const openingCurly = sourceCode.getTokenBefore(node.cases.length ? node.cases[0] : closingCurly); - - validateCurlyPair(openingCurly, closingCurly); - }, - IfStatement(node) { - if (node.consequent.type === "BlockStatement" && node.alternate) { - - // Handle the keyword after the `if` block (before `else`) - validateCurlyBeforeKeyword(sourceCode.getLastToken(node.consequent)); - } - }, - TryStatement(node) { - - // Handle the keyword after the `try` block (before `catch` or `finally`) - validateCurlyBeforeKeyword(sourceCode.getLastToken(node.block)); - - if (node.handler && node.finalizer) { - - // Handle the keyword after the `catch` block (before `finally`) - validateCurlyBeforeKeyword(sourceCode.getLastToken(node.handler.body)); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/callback-return.js b/tools/node_modules/eslint/lib/rules/callback-return.js deleted file mode 100644 index ba13c9a648176856a61d0c2b12c16cf88fbc153c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/callback-return.js +++ /dev/null @@ -1,186 +0,0 @@ -/** - * @fileoverview Enforce return after a callback. - * @author Jamund Ferguson - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "require `return` statements after callbacks", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/callback-return" - }, - - schema: [{ - type: "array", - items: { type: "string" } - }], - - messages: { - missingReturn: "Expected return with your callback function." - } - }, - - create(context) { - - const callbacks = context.options[0] || ["callback", "cb", "next"], - sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Find the closest parent matching a list of types. - * @param {ASTNode} node The node whose parents we are searching - * @param {Array} types The node types to match - * @returns {ASTNode} The matched node or undefined. - */ - function findClosestParentOfType(node, types) { - if (!node.parent) { - return null; - } - if (types.indexOf(node.parent.type) === -1) { - return findClosestParentOfType(node.parent, types); - } - return node.parent; - } - - /** - * Check to see if a node contains only identifers - * @param {ASTNode} node The node to check - * @returns {boolean} Whether or not the node contains only identifers - */ - function containsOnlyIdentifiers(node) { - if (node.type === "Identifier") { - return true; - } - - if (node.type === "MemberExpression") { - if (node.object.type === "Identifier") { - return true; - } - if (node.object.type === "MemberExpression") { - return containsOnlyIdentifiers(node.object); - } - } - - return false; - } - - /** - * Check to see if a CallExpression is in our callback list. - * @param {ASTNode} node The node to check against our callback names list. - * @returns {boolean} Whether or not this function matches our callback name. - */ - function isCallback(node) { - return containsOnlyIdentifiers(node.callee) && callbacks.indexOf(sourceCode.getText(node.callee)) > -1; - } - - /** - * Determines whether or not the callback is part of a callback expression. - * @param {ASTNode} node The callback node - * @param {ASTNode} parentNode The expression node - * @returns {boolean} Whether or not this is part of a callback expression - */ - function isCallbackExpression(node, parentNode) { - - // ensure the parent node exists and is an expression - if (!parentNode || parentNode.type !== "ExpressionStatement") { - return false; - } - - // cb() - if (parentNode.expression === node) { - return true; - } - - // special case for cb && cb() and similar - if (parentNode.expression.type === "BinaryExpression" || parentNode.expression.type === "LogicalExpression") { - if (parentNode.expression.right === node) { - return true; - } - } - - return false; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - CallExpression(node) { - - // if we're not a callback we can return - if (!isCallback(node)) { - return; - } - - // find the closest block, return or loop - const closestBlock = findClosestParentOfType(node, ["BlockStatement", "ReturnStatement", "ArrowFunctionExpression"]) || {}; - - // if our parent is a return we know we're ok - if (closestBlock.type === "ReturnStatement") { - return; - } - - // arrow functions don't always have blocks and implicitly return - if (closestBlock.type === "ArrowFunctionExpression") { - return; - } - - // block statements are part of functions and most if statements - if (closestBlock.type === "BlockStatement") { - - // find the last item in the block - const lastItem = closestBlock.body[closestBlock.body.length - 1]; - - // if the callback is the last thing in a block that might be ok - if (isCallbackExpression(node, lastItem)) { - - const parentType = closestBlock.parent.type; - - // but only if the block is part of a function - if (parentType === "FunctionExpression" || - parentType === "FunctionDeclaration" || - parentType === "ArrowFunctionExpression" - ) { - return; - } - - } - - // ending a block with a return is also ok - if (lastItem.type === "ReturnStatement") { - - // but only if the callback is immediately before - if (isCallbackExpression(node, closestBlock.body[closestBlock.body.length - 2])) { - return; - } - } - - } - - // as long as you're the child of a function at this point you should be asked to return - if (findClosestParentOfType(node, ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"])) { - context.report({ node, messageId: "missingReturn" }); - } - - } - - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/camelcase.js b/tools/node_modules/eslint/lib/rules/camelcase.js deleted file mode 100644 index 04360837294a127b2ba6f2b2031b7dd2f0af3c3b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/camelcase.js +++ /dev/null @@ -1,278 +0,0 @@ -/** - * @fileoverview Rule to flag non-camelcased identifiers - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce camelcase naming convention", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/camelcase" - }, - - schema: [ - { - type: "object", - properties: { - ignoreDestructuring: { - type: "boolean", - default: false - }, - ignoreImports: { - type: "boolean", - default: false - }, - properties: { - enum: ["always", "never"] - }, - allow: { - type: "array", - items: [ - { - type: "string" - } - ], - minItems: 0, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - notCamelCase: "Identifier '{{name}}' is not in camel case." - } - }, - - create(context) { - - const options = context.options[0] || {}; - let properties = options.properties || ""; - const ignoreDestructuring = options.ignoreDestructuring; - const ignoreImports = options.ignoreImports; - const allow = options.allow || []; - - if (properties !== "always" && properties !== "never") { - properties = "always"; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // contains reported nodes to avoid reporting twice on destructuring with shorthand notation - const reported = []; - const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]); - - /** - * Checks if a string contains an underscore and isn't all upper-case - * @param {string} name The string to check. - * @returns {boolean} if the string is underscored - * @private - */ - function isUnderscored(name) { - - // if there's an underscore, it might be A_CONSTANT, which is okay - return name.includes("_") && name !== name.toUpperCase(); - } - - /** - * Checks if a string match the ignore list - * @param {string} name The string to check. - * @returns {boolean} if the string is ignored - * @private - */ - function isAllowed(name) { - return allow.some( - entry => name === entry || name.match(new RegExp(entry, "u")) - ); - } - - /** - * Checks if a parent of a node is an ObjectPattern. - * @param {ASTNode} node The node to check. - * @returns {boolean} if the node is inside an ObjectPattern - * @private - */ - function isInsideObjectPattern(node) { - let current = node; - - while (current) { - const parent = current.parent; - - if (parent && parent.type === "Property" && parent.computed && parent.key === current) { - return false; - } - - if (current.type === "ObjectPattern") { - return true; - } - - current = parent; - } - - return false; - } - - /** - * Checks whether the given node represents assignment target property in destructuring. - * - * For examples: - * ({a: b.foo} = c); // => true for `foo` - * ([a.foo] = b); // => true for `foo` - * ([a.foo = 1] = b); // => true for `foo` - * ({...a.foo} = b); // => true for `foo` - * @param {ASTNode} node An Identifier node to check - * @returns {boolean} True if the node is an assignment target property in destructuring. - */ - function isAssignmentTargetPropertyInDestructuring(node) { - if ( - node.parent.type === "MemberExpression" && - node.parent.property === node && - !node.parent.computed - ) { - const effectiveParent = node.parent.parent; - - return ( - effectiveParent.type === "Property" && - effectiveParent.value === node.parent && - effectiveParent.parent.type === "ObjectPattern" || - effectiveParent.type === "ArrayPattern" || - effectiveParent.type === "RestElement" || - ( - effectiveParent.type === "AssignmentPattern" && - effectiveParent.left === node.parent - ) - ); - } - return false; - } - - /** - * Reports an AST node as a rule violation. - * @param {ASTNode} node The node to report. - * @returns {void} - * @private - */ - function report(node) { - if (!reported.includes(node)) { - reported.push(node); - context.report({ node, messageId: "notCamelCase", data: { name: node.name } }); - } - } - - return { - - Identifier(node) { - - /* - * Leading and trailing underscores are commonly used to flag - * private/protected identifiers, strip them before checking if underscored - */ - const name = node.name, - nameIsUnderscored = isUnderscored(name.replace(/^_+|_+$/gu, "")), - effectiveParent = (node.parent.type === "MemberExpression") ? node.parent.parent : node.parent; - - // First, we ignore the node if it match the ignore list - if (isAllowed(name)) { - return; - } - - // MemberExpressions get special rules - if (node.parent.type === "MemberExpression") { - - // "never" check properties - if (properties === "never") { - return; - } - - // Always report underscored object names - if (node.parent.object.type === "Identifier" && node.parent.object.name === node.name && nameIsUnderscored) { - report(node); - - // Report AssignmentExpressions only if they are the left side of the assignment - } else if (effectiveParent.type === "AssignmentExpression" && nameIsUnderscored && (effectiveParent.right.type !== "MemberExpression" || effectiveParent.left.type === "MemberExpression" && effectiveParent.left.property.name === node.name)) { - report(node); - - } else if (isAssignmentTargetPropertyInDestructuring(node) && nameIsUnderscored) { - report(node); - } - - /* - * Properties have their own rules, and - * AssignmentPattern nodes can be treated like Properties: - * e.g.: const { no_camelcased = false } = bar; - */ - } else if (node.parent.type === "Property" || node.parent.type === "AssignmentPattern") { - - if (node.parent.parent && node.parent.parent.type === "ObjectPattern") { - if (node.parent.shorthand && node.parent.value.left && nameIsUnderscored) { - report(node); - } - - const assignmentKeyEqualsValue = node.parent.key.name === node.parent.value.name; - - if (nameIsUnderscored && node.parent.computed) { - report(node); - } - - // prevent checking righthand side of destructured object - if (node.parent.key === node && node.parent.value !== node) { - return; - } - - const valueIsUnderscored = node.parent.value.name && nameIsUnderscored; - - // ignore destructuring if the option is set, unless a new identifier is created - if (valueIsUnderscored && !(assignmentKeyEqualsValue && ignoreDestructuring)) { - report(node); - } - } - - // "never" check properties or always ignore destructuring - if (properties === "never" || (ignoreDestructuring && isInsideObjectPattern(node))) { - return; - } - - // don't check right hand side of AssignmentExpression to prevent duplicate warnings - if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && !(node.parent.right === node)) { - report(node); - } - - // Check if it's an import specifier - } else if (["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"].includes(node.parent.type)) { - - if (node.parent.type === "ImportSpecifier" && ignoreImports) { - return; - } - - // Report only if the local imported identifier is underscored - if ( - node.parent.local && - node.parent.local.name === node.name && - nameIsUnderscored - ) { - report(node); - } - - // Report anything that is underscored that isn't a CallExpression - } else if (nameIsUnderscored && !ALLOWED_PARENT_TYPES.has(effectiveParent.type)) { - report(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/capitalized-comments.js b/tools/node_modules/eslint/lib/rules/capitalized-comments.js deleted file mode 100644 index d7524b878d22756aac1e3bd90137301f2627d488..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/capitalized-comments.js +++ /dev/null @@ -1,300 +0,0 @@ -/** - * @fileoverview enforce or disallow capitalization of the first letter of a comment - * @author Kevin Partington - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const LETTER_PATTERN = require("./utils/patterns/letters"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, - WHITESPACE = /\s/gu, - MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/u; // TODO: Combine w/ max-len pattern? - -/* - * Base schema body for defining the basic capitalization rule, ignorePattern, - * and ignoreInlineComments values. - * This can be used in a few different ways in the actual schema. - */ -const SCHEMA_BODY = { - type: "object", - properties: { - ignorePattern: { - type: "string" - }, - ignoreInlineComments: { - type: "boolean" - }, - ignoreConsecutiveComments: { - type: "boolean" - } - }, - additionalProperties: false -}; -const DEFAULTS = { - ignorePattern: "", - ignoreInlineComments: false, - ignoreConsecutiveComments: false -}; - -/** - * Get normalized options for either block or line comments from the given - * user-provided options. - * - If the user-provided options is just a string, returns a normalized - * set of options using default values for all other options. - * - If the user-provided options is an object, then a normalized option - * set is returned. Options specified in overrides will take priority - * over options specified in the main options object, which will in - * turn take priority over the rule's defaults. - * @param {Object|string} rawOptions The user-provided options. - * @param {string} which Either "line" or "block". - * @returns {Object} The normalized options. - */ -function getNormalizedOptions(rawOptions, which) { - return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); -} - -/** - * Get normalized options for block and line comments. - * @param {Object|string} rawOptions The user-provided options. - * @returns {Object} An object with "Line" and "Block" keys and corresponding - * normalized options objects. - */ -function getAllNormalizedOptions(rawOptions = {}) { - return { - Line: getNormalizedOptions(rawOptions, "line"), - Block: getNormalizedOptions(rawOptions, "block") - }; -} - -/** - * Creates a regular expression for each ignorePattern defined in the rule - * options. - * - * This is done in order to avoid invoking the RegExp constructor repeatedly. - * @param {Object} normalizedOptions The normalized rule options. - * @returns {void} - */ -function createRegExpForIgnorePatterns(normalizedOptions) { - Object.keys(normalizedOptions).forEach(key => { - const ignorePatternStr = normalizedOptions[key].ignorePattern; - - if (ignorePatternStr) { - const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`, "u"); - - normalizedOptions[key].ignorePatternRegExp = regExp; - } - }); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce or disallow capitalization of the first letter of a comment", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/capitalized-comments" - }, - - fixable: "code", - - schema: [ - { enum: ["always", "never"] }, - { - oneOf: [ - SCHEMA_BODY, - { - type: "object", - properties: { - line: SCHEMA_BODY, - block: SCHEMA_BODY - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedLowercaseComment: "Comments should not begin with a lowercase character.", - unexpectedUppercaseComment: "Comments should not begin with an uppercase character." - } - }, - - create(context) { - - const capitalize = context.options[0] || "always", - normalizedOptions = getAllNormalizedOptions(context.options[1]), - sourceCode = context.getSourceCode(); - - createRegExpForIgnorePatterns(normalizedOptions); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Checks whether a comment is an inline comment. - * - * For the purpose of this rule, a comment is inline if: - * 1. The comment is preceded by a token on the same line; and - * 2. The command is followed by a token on the same line. - * - * Note that the comment itself need not be single-line! - * - * Also, it follows from this definition that only block comments can - * be considered as possibly inline. This is because line comments - * would consume any following tokens on the same line as the comment. - * @param {ASTNode} comment The comment node to check. - * @returns {boolean} True if the comment is an inline comment, false - * otherwise. - */ - function isInlineComment(comment) { - const previousToken = sourceCode.getTokenBefore(comment, { includeComments: true }), - nextToken = sourceCode.getTokenAfter(comment, { includeComments: true }); - - return Boolean( - previousToken && - nextToken && - comment.loc.start.line === previousToken.loc.end.line && - comment.loc.end.line === nextToken.loc.start.line - ); - } - - /** - * Determine if a comment follows another comment. - * @param {ASTNode} comment The comment to check. - * @returns {boolean} True if the comment follows a valid comment. - */ - function isConsecutiveComment(comment) { - const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true }); - - return Boolean( - previousTokenOrComment && - ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1 - ); - } - - /** - * Check a comment to determine if it is valid for this rule. - * @param {ASTNode} comment The comment node to process. - * @param {Object} options The options for checking this comment. - * @returns {boolean} True if the comment is valid, false otherwise. - */ - function isCommentValid(comment, options) { - - // 1. Check for default ignore pattern. - if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { - return true; - } - - // 2. Check for custom ignore pattern. - const commentWithoutAsterisks = comment.value - .replace(/\*/gu, ""); - - if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { - return true; - } - - // 3. Check for inline comments. - if (options.ignoreInlineComments && isInlineComment(comment)) { - return true; - } - - // 4. Is this a consecutive comment (and are we tolerating those)? - if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { - return true; - } - - // 5. Does the comment start with a possible URL? - if (MAYBE_URL.test(commentWithoutAsterisks)) { - return true; - } - - // 6. Is the initial word character a letter? - const commentWordCharsOnly = commentWithoutAsterisks - .replace(WHITESPACE, ""); - - if (commentWordCharsOnly.length === 0) { - return true; - } - - const firstWordChar = commentWordCharsOnly[0]; - - if (!LETTER_PATTERN.test(firstWordChar)) { - return true; - } - - // 7. Check the case of the initial word character. - const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), - isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); - - if (capitalize === "always" && isLowercase) { - return false; - } - if (capitalize === "never" && isUppercase) { - return false; - } - - return true; - } - - /** - * Process a comment to determine if it needs to be reported. - * @param {ASTNode} comment The comment node to process. - * @returns {void} - */ - function processComment(comment) { - const options = normalizedOptions[comment.type], - commentValid = isCommentValid(comment, options); - - if (!commentValid) { - const messageId = capitalize === "always" - ? "unexpectedLowercaseComment" - : "unexpectedUppercaseComment"; - - context.report({ - node: null, // Intentionally using loc instead - loc: comment.loc, - messageId, - fix(fixer) { - const match = comment.value.match(LETTER_PATTERN); - - return fixer.replaceTextRange( - - // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) - [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], - capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() - ); - } - }); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type !== "Shebang").forEach(processComment); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/class-methods-use-this.js b/tools/node_modules/eslint/lib/rules/class-methods-use-this.js deleted file mode 100644 index 2cc5cc41842c0c1a71f3d3aa03790b1d049231c0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/class-methods-use-this.js +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @fileoverview Rule to enforce that all class methods use 'this'. - * @author Patrick Williams - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce that class methods utilize `this`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/class-methods-use-this" - }, - - schema: [{ - type: "object", - properties: { - exceptMethods: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - }], - - messages: { - missingThis: "Expected 'this' to be used by class {{name}}." - } - }, - create(context) { - const config = Object.assign({}, context.options[0]); - const exceptMethods = new Set(config.exceptMethods || []); - - const stack = []; - - /** - * Initializes the current context to false and pushes it onto the stack. - * These booleans represent whether 'this' has been used in the context. - * @returns {void} - * @private - */ - function enterFunction() { - stack.push(false); - } - - /** - * Check if the node is an instance method - * @param {ASTNode} node node to check - * @returns {boolean} True if its an instance method - * @private - */ - function isInstanceMethod(node) { - return !node.static && node.kind !== "constructor" && node.type === "MethodDefinition"; - } - - /** - * Check if the node is an instance method not excluded by config - * @param {ASTNode} node node to check - * @returns {boolean} True if it is an instance method, and not excluded by config - * @private - */ - function isIncludedInstanceMethod(node) { - return isInstanceMethod(node) && - (node.computed || !exceptMethods.has(node.key.name)); - } - - /** - * Checks if we are leaving a function that is a method, and reports if 'this' has not been used. - * Static methods and the constructor are exempt. - * Then pops the context off the stack. - * @param {ASTNode} node A function node that was entered. - * @returns {void} - * @private - */ - function exitFunction(node) { - const methodUsesThis = stack.pop(); - - if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) { - context.report({ - node, - messageId: "missingThis", - data: { - name: astUtils.getFunctionNameWithKind(node) - } - }); - } - } - - /** - * Mark the current context as having used 'this'. - * @returns {void} - * @private - */ - function markThisUsed() { - if (stack.length) { - stack[stack.length - 1] = true; - } - } - - return { - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - ThisExpression: markThisUsed, - Super: markThisUsed - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/comma-dangle.js b/tools/node_modules/eslint/lib/rules/comma-dangle.js deleted file mode 100644 index e22b7f3551e114a07fc0704e01442557b1846575..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/comma-dangle.js +++ /dev/null @@ -1,340 +0,0 @@ -/** - * @fileoverview Rule to forbid or enforce dangling commas. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_OPTIONS = Object.freeze({ - arrays: "never", - objects: "never", - imports: "never", - exports: "never", - functions: "never" -}); - -/** - * Checks whether or not a trailing comma is allowed in a given node. - * If the `lastItem` is `RestElement` or `RestProperty`, it disallows trailing commas. - * @param {ASTNode} lastItem The node of the last element in the given node. - * @returns {boolean} `true` if a trailing comma is allowed. - */ -function isTrailingCommaAllowed(lastItem) { - return !( - lastItem.type === "RestElement" || - lastItem.type === "RestProperty" || - lastItem.type === "ExperimentalRestProperty" - ); -} - -/** - * Normalize option value. - * @param {string|Object|undefined} optionValue The 1st option value to normalize. - * @param {number} ecmaVersion The normalized ECMAScript version. - * @returns {Object} The normalized option value. - */ -function normalizeOptions(optionValue, ecmaVersion) { - if (typeof optionValue === "string") { - return { - arrays: optionValue, - objects: optionValue, - imports: optionValue, - exports: optionValue, - functions: (!ecmaVersion || ecmaVersion < 8) ? "ignore" : optionValue - }; - } - if (typeof optionValue === "object" && optionValue !== null) { - return { - arrays: optionValue.arrays || DEFAULT_OPTIONS.arrays, - objects: optionValue.objects || DEFAULT_OPTIONS.objects, - imports: optionValue.imports || DEFAULT_OPTIONS.imports, - exports: optionValue.exports || DEFAULT_OPTIONS.exports, - functions: optionValue.functions || DEFAULT_OPTIONS.functions - }; - } - - return DEFAULT_OPTIONS; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow trailing commas", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/comma-dangle" - }, - - fixable: "code", - - schema: { - definitions: { - value: { - enum: [ - "always-multiline", - "always", - "never", - "only-multiline" - ] - }, - valueWithIgnore: { - enum: [ - "always-multiline", - "always", - "ignore", - "never", - "only-multiline" - ] - } - }, - type: "array", - items: [ - { - oneOf: [ - { - $ref: "#/definitions/value" - }, - { - type: "object", - properties: { - arrays: { $ref: "#/definitions/valueWithIgnore" }, - objects: { $ref: "#/definitions/valueWithIgnore" }, - imports: { $ref: "#/definitions/valueWithIgnore" }, - exports: { $ref: "#/definitions/valueWithIgnore" }, - functions: { $ref: "#/definitions/valueWithIgnore" } - }, - additionalProperties: false - } - ] - } - ] - }, - - messages: { - unexpected: "Unexpected trailing comma.", - missing: "Missing trailing comma." - } - }, - - create(context) { - const options = normalizeOptions(context.options[0], context.parserOptions.ecmaVersion); - - const sourceCode = context.getSourceCode(); - - /** - * Gets the last item of the given node. - * @param {ASTNode} node The node to get. - * @returns {ASTNode|null} The last node or null. - */ - function getLastItem(node) { - switch (node.type) { - case "ObjectExpression": - case "ObjectPattern": - return lodash.last(node.properties); - case "ArrayExpression": - case "ArrayPattern": - return lodash.last(node.elements); - case "ImportDeclaration": - case "ExportNamedDeclaration": - return lodash.last(node.specifiers); - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - return lodash.last(node.params); - case "CallExpression": - case "NewExpression": - return lodash.last(node.arguments); - default: - return null; - } - } - - /** - * Gets the trailing comma token of the given node. - * If the trailing comma does not exist, this returns the token which is - * the insertion point of the trailing comma token. - * @param {ASTNode} node The node to get. - * @param {ASTNode} lastItem The last item of the node. - * @returns {Token} The trailing comma token or the insertion point. - */ - function getTrailingToken(node, lastItem) { - switch (node.type) { - case "ObjectExpression": - case "ArrayExpression": - case "CallExpression": - case "NewExpression": - return sourceCode.getLastToken(node, 1); - default: { - const nextToken = sourceCode.getTokenAfter(lastItem); - - if (astUtils.isCommaToken(nextToken)) { - return nextToken; - } - return sourceCode.getLastToken(lastItem); - } - } - } - - /** - * Checks whether or not a given node is multiline. - * This rule handles a given node as multiline when the closing parenthesis - * and the last element are not on the same line. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is multiline. - */ - function isMultiline(node) { - const lastItem = getLastItem(node); - - if (!lastItem) { - return false; - } - - const penultimateToken = getTrailingToken(node, lastItem); - const lastToken = sourceCode.getTokenAfter(penultimateToken); - - return lastToken.loc.end.line !== penultimateToken.loc.end.line; - } - - /** - * Reports a trailing comma if it exists. - * @param {ASTNode} node A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function forbidTrailingComma(node) { - const lastItem = getLastItem(node); - - if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { - return; - } - - const trailingToken = getTrailingToken(node, lastItem); - - if (astUtils.isCommaToken(trailingToken)) { - context.report({ - node: lastItem, - loc: trailingToken.loc, - messageId: "unexpected", - fix(fixer) { - return fixer.remove(trailingToken); - } - }); - } - } - - /** - * Reports the last element of a given node if it does not have a trailing - * comma. - * - * If a given node is `ArrayPattern` which has `RestElement`, the trailing - * comma is disallowed, so report if it exists. - * @param {ASTNode} node A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function forceTrailingComma(node) { - const lastItem = getLastItem(node); - - if (!lastItem || (node.type === "ImportDeclaration" && lastItem.type !== "ImportSpecifier")) { - return; - } - if (!isTrailingCommaAllowed(lastItem)) { - forbidTrailingComma(node); - return; - } - - const trailingToken = getTrailingToken(node, lastItem); - - if (trailingToken.value !== ",") { - context.report({ - node: lastItem, - loc: { - start: trailingToken.loc.end, - end: astUtils.getNextLocation(sourceCode, trailingToken.loc.end) - }, - messageId: "missing", - fix(fixer) { - return fixer.insertTextAfter(trailingToken, ","); - } - }); - } - } - - /** - * If a given node is multiline, reports the last element of a given node - * when it does not have a trailing comma. - * Otherwise, reports a trailing comma if it exists. - * @param {ASTNode} node A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function forceTrailingCommaIfMultiline(node) { - if (isMultiline(node)) { - forceTrailingComma(node); - } else { - forbidTrailingComma(node); - } - } - - /** - * Only if a given node is not multiline, reports the last element of a given node - * when it does not have a trailing comma. - * Otherwise, reports a trailing comma if it exists. - * @param {ASTNode} node A node to check. Its type is one of - * ObjectExpression, ObjectPattern, ArrayExpression, ArrayPattern, - * ImportDeclaration, and ExportNamedDeclaration. - * @returns {void} - */ - function allowTrailingCommaIfMultiline(node) { - if (!isMultiline(node)) { - forbidTrailingComma(node); - } - } - - const predicate = { - always: forceTrailingComma, - "always-multiline": forceTrailingCommaIfMultiline, - "only-multiline": allowTrailingCommaIfMultiline, - never: forbidTrailingComma, - ignore: lodash.noop - }; - - return { - ObjectExpression: predicate[options.objects], - ObjectPattern: predicate[options.objects], - - ArrayExpression: predicate[options.arrays], - ArrayPattern: predicate[options.arrays], - - ImportDeclaration: predicate[options.imports], - - ExportNamedDeclaration: predicate[options.exports], - - FunctionDeclaration: predicate[options.functions], - FunctionExpression: predicate[options.functions], - ArrowFunctionExpression: predicate[options.functions], - CallExpression: predicate[options.functions], - NewExpression: predicate[options.functions] - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/comma-spacing.js b/tools/node_modules/eslint/lib/rules/comma-spacing.js deleted file mode 100644 index 73c10a7711b904b9ddbd82855d11fa5e352f3263..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/comma-spacing.js +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @fileoverview Comma spacing - validates spacing before and after comma - * @author Vignesh Anand aka vegetableman. - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after commas", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/comma-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { - type: "boolean", - default: false - }, - after: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - missing: "A space is required {{loc}} ','.", - unexpected: "There should be no space {{loc}} ','." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - const tokensAndComments = sourceCode.tokensAndComments; - - const options = { - before: context.options[0] ? context.options[0].before : false, - after: context.options[0] ? context.options[0].after : true - }; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // list of comma tokens to ignore for the check of leading whitespace - const commaTokensToIgnore = []; - - /** - * Reports a spacing error with an appropriate message. - * @param {ASTNode} node The binary expression node to report. - * @param {string} loc Is the error "before" or "after" the comma? - * @param {ASTNode} otherNode The node at the left or right of `node` - * @returns {void} - * @private - */ - function report(node, loc, otherNode) { - context.report({ - node, - fix(fixer) { - if (options[loc]) { - if (loc === "before") { - return fixer.insertTextBefore(node, " "); - } - return fixer.insertTextAfter(node, " "); - - } - let start, end; - const newText = ""; - - if (loc === "before") { - start = otherNode.range[1]; - end = node.range[0]; - } else { - start = node.range[1]; - end = otherNode.range[0]; - } - - return fixer.replaceTextRange([start, end], newText); - - }, - messageId: options[loc] ? "missing" : "unexpected", - data: { - loc - } - }); - } - - /** - * Validates the spacing around a comma token. - * @param {Object} tokens The tokens to be validated. - * @param {Token} tokens.comma The token representing the comma. - * @param {Token} [tokens.left] The last token before the comma. - * @param {Token} [tokens.right] The first token after the comma. - * @param {Token|ASTNode} reportItem The item to use when reporting an error. - * @returns {void} - * @private - */ - function validateCommaItemSpacing(tokens, reportItem) { - if (tokens.left && astUtils.isTokenOnSameLine(tokens.left, tokens.comma) && - (options.before !== sourceCode.isSpaceBetweenTokens(tokens.left, tokens.comma)) - ) { - report(reportItem, "before", tokens.left); - } - - if (tokens.right && astUtils.isClosingParenToken(tokens.right)) { - return; - } - - if (tokens.right && !options.after && tokens.right.type === "Line") { - return; - } - - if (tokens.right && astUtils.isTokenOnSameLine(tokens.comma, tokens.right) && - (options.after !== sourceCode.isSpaceBetweenTokens(tokens.comma, tokens.right)) - ) { - report(reportItem, "after", tokens.right); - } - } - - /** - * Adds null elements of the given ArrayExpression or ArrayPattern node to the ignore list. - * @param {ASTNode} node An ArrayExpression or ArrayPattern node. - * @returns {void} - */ - function addNullElementsToIgnoreList(node) { - let previousToken = sourceCode.getFirstToken(node); - - node.elements.forEach(element => { - let token; - - if (element === null) { - token = sourceCode.getTokenAfter(previousToken); - - if (astUtils.isCommaToken(token)) { - commaTokensToIgnore.push(token); - } - } else { - token = sourceCode.getTokenAfter(element); - } - - previousToken = token; - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - "Program:exit"() { - tokensAndComments.forEach((token, i) => { - - if (!astUtils.isCommaToken(token)) { - return; - } - - if (token && token.type === "JSXText") { - return; - } - - const previousToken = tokensAndComments[i - 1]; - const nextToken = tokensAndComments[i + 1]; - - validateCommaItemSpacing({ - comma: token, - left: astUtils.isCommaToken(previousToken) || commaTokensToIgnore.indexOf(token) > -1 ? null : previousToken, - right: astUtils.isCommaToken(nextToken) ? null : nextToken - }, token); - }); - }, - ArrayExpression: addNullElementsToIgnoreList, - ArrayPattern: addNullElementsToIgnoreList - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/comma-style.js b/tools/node_modules/eslint/lib/rules/comma-style.js deleted file mode 100644 index f1a23d63b786a0bd9877836c3bf9e1e1b0e0b82d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/comma-style.js +++ /dev/null @@ -1,310 +0,0 @@ -/** - * @fileoverview Comma style - enforces comma styles of two types: last and first - * @author Vignesh Anand aka vegetableman - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent comma style", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/comma-style" - }, - - fixable: "code", - - schema: [ - { - enum: ["first", "last"] - }, - { - type: "object", - properties: { - exceptions: { - type: "object", - additionalProperties: { - type: "boolean" - } - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedLineBeforeAndAfterComma: "Bad line breaking before and after ','.", - expectedCommaFirst: "',' should be placed first.", - expectedCommaLast: "',' should be placed last." - } - }, - - create(context) { - const style = context.options[0] || "last", - sourceCode = context.getSourceCode(); - const exceptions = { - ArrayPattern: true, - ArrowFunctionExpression: true, - CallExpression: true, - FunctionDeclaration: true, - FunctionExpression: true, - ImportDeclaration: true, - ObjectPattern: true, - NewExpression: true - }; - - if (context.options.length === 2 && Object.prototype.hasOwnProperty.call(context.options[1], "exceptions")) { - const keys = Object.keys(context.options[1].exceptions); - - for (let i = 0; i < keys.length; i++) { - exceptions[keys[i]] = context.options[1].exceptions[keys[i]]; - } - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Modified text based on the style - * @param {string} styleType Style type - * @param {string} text Source code text - * @returns {string} modified text - * @private - */ - function getReplacedText(styleType, text) { - switch (styleType) { - case "between": - return `,${text.replace(astUtils.LINEBREAK_MATCHER, "")}`; - - case "first": - return `${text},`; - - case "last": - return `,${text}`; - - default: - return ""; - } - } - - /** - * Determines the fixer function for a given style. - * @param {string} styleType comma style - * @param {ASTNode} previousItemToken The token to check. - * @param {ASTNode} commaToken The token to check. - * @param {ASTNode} currentItemToken The token to check. - * @returns {Function} Fixer function - * @private - */ - function getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) { - const text = - sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) + - sourceCode.text.slice(commaToken.range[1], currentItemToken.range[0]); - const range = [previousItemToken.range[1], currentItemToken.range[0]]; - - return function(fixer) { - return fixer.replaceTextRange(range, getReplacedText(styleType, text)); - }; - } - - /** - * Validates the spacing around single items in lists. - * @param {Token} previousItemToken The last token from the previous item. - * @param {Token} commaToken The token representing the comma. - * @param {Token} currentItemToken The first token of the current item. - * @param {Token} reportItem The item to use when reporting an error. - * @returns {void} - * @private - */ - function validateCommaItemSpacing(previousItemToken, commaToken, currentItemToken, reportItem) { - - // if single line - if (astUtils.isTokenOnSameLine(commaToken, currentItemToken) && - astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { - - // do nothing. - - } else if (!astUtils.isTokenOnSameLine(commaToken, currentItemToken) && - !astUtils.isTokenOnSameLine(previousItemToken, commaToken)) { - - const comment = sourceCode.getCommentsAfter(commaToken)[0]; - const styleType = comment && comment.type === "Block" && astUtils.isTokenOnSameLine(commaToken, comment) - ? style - : "between"; - - // lone comma - context.report({ - node: reportItem, - loc: commaToken.loc, - messageId: "unexpectedLineBeforeAndAfterComma", - fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken) - }); - - } else if (style === "first" && !astUtils.isTokenOnSameLine(commaToken, currentItemToken)) { - - context.report({ - node: reportItem, - loc: commaToken.loc, - messageId: "expectedCommaFirst", - fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken) - }); - - } else if (style === "last" && astUtils.isTokenOnSameLine(commaToken, currentItemToken)) { - - context.report({ - node: reportItem, - loc: commaToken.loc, - messageId: "expectedCommaLast", - fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken) - }); - } - } - - /** - * Checks the comma placement with regards to a declaration/property/element - * @param {ASTNode} node The binary expression node to check - * @param {string} property The property of the node containing child nodes. - * @private - * @returns {void} - */ - function validateComma(node, property) { - const items = node[property], - arrayLiteral = (node.type === "ArrayExpression" || node.type === "ArrayPattern"); - - if (items.length > 1 || arrayLiteral) { - - // seed as opening [ - let previousItemToken = sourceCode.getFirstToken(node); - - items.forEach(item => { - const commaToken = item ? sourceCode.getTokenBefore(item) : previousItemToken, - currentItemToken = item ? sourceCode.getFirstToken(item) : sourceCode.getTokenAfter(commaToken), - reportItem = item || currentItemToken; - - /* - * This works by comparing three token locations: - * - previousItemToken is the last token of the previous item - * - commaToken is the location of the comma before the current item - * - currentItemToken is the first token of the current item - * - * These values get switched around if item is undefined. - * previousItemToken will refer to the last token not belonging - * to the current item, which could be a comma or an opening - * square bracket. currentItemToken could be a comma. - * - * All comparisons are done based on these tokens directly, so - * they are always valid regardless of an undefined item. - */ - if (astUtils.isCommaToken(commaToken)) { - validateCommaItemSpacing(previousItemToken, commaToken, - currentItemToken, reportItem); - } - - if (item) { - const tokenAfterItem = sourceCode.getTokenAfter(item, astUtils.isNotClosingParenToken); - - previousItemToken = tokenAfterItem - ? sourceCode.getTokenBefore(tokenAfterItem) - : sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1]; - } - }); - - /* - * Special case for array literals that have empty last items, such - * as [ 1, 2, ]. These arrays only have two items show up in the - * AST, so we need to look at the token to verify that there's no - * dangling comma. - */ - if (arrayLiteral) { - - const lastToken = sourceCode.getLastToken(node), - nextToLastToken = sourceCode.getTokenBefore(lastToken); - - if (astUtils.isCommaToken(nextToLastToken)) { - validateCommaItemSpacing( - sourceCode.getTokenBefore(nextToLastToken), - nextToLastToken, - lastToken, - lastToken - ); - } - } - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - const nodes = {}; - - if (!exceptions.VariableDeclaration) { - nodes.VariableDeclaration = function(node) { - validateComma(node, "declarations"); - }; - } - if (!exceptions.ObjectExpression) { - nodes.ObjectExpression = function(node) { - validateComma(node, "properties"); - }; - } - if (!exceptions.ObjectPattern) { - nodes.ObjectPattern = function(node) { - validateComma(node, "properties"); - }; - } - if (!exceptions.ArrayExpression) { - nodes.ArrayExpression = function(node) { - validateComma(node, "elements"); - }; - } - if (!exceptions.ArrayPattern) { - nodes.ArrayPattern = function(node) { - validateComma(node, "elements"); - }; - } - if (!exceptions.FunctionDeclaration) { - nodes.FunctionDeclaration = function(node) { - validateComma(node, "params"); - }; - } - if (!exceptions.FunctionExpression) { - nodes.FunctionExpression = function(node) { - validateComma(node, "params"); - }; - } - if (!exceptions.ArrowFunctionExpression) { - nodes.ArrowFunctionExpression = function(node) { - validateComma(node, "params"); - }; - } - if (!exceptions.CallExpression) { - nodes.CallExpression = function(node) { - validateComma(node, "arguments"); - }; - } - if (!exceptions.ImportDeclaration) { - nodes.ImportDeclaration = function(node) { - validateComma(node, "specifiers"); - }; - } - if (!exceptions.NewExpression) { - nodes.NewExpression = function(node) { - validateComma(node, "arguments"); - }; - } - - return nodes; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/complexity.js b/tools/node_modules/eslint/lib/rules/complexity.js deleted file mode 100644 index 7fc8bf9bc2ea8c6409fd2001833b5b89b44061a7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/complexity.js +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity. - * Counts the number of if, conditional, for, while, try, switch/case, - * @author Patrick Brosset - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum cyclomatic complexity allowed in a program", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/complexity" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0 - }, - max: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - complex: "{{name}} has a complexity of {{complexity}}. Maximum allowed is {{max}}." - } - }, - - create(context) { - const option = context.options[0]; - let THRESHOLD = 20; - - if ( - typeof option === "object" && - (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) - ) { - THRESHOLD = option.maximum || option.max; - } else if (typeof option === "number") { - THRESHOLD = option; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // Using a stack to store complexity (handling nested functions) - const fns = []; - - /** - * When parsing a new function, store it in our function stack - * @returns {void} - * @private - */ - function startFunction() { - fns.push(1); - } - - /** - * Evaluate the node at the end of function - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function endFunction(node) { - const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node)); - const complexity = fns.pop(); - - if (complexity > THRESHOLD) { - context.report({ - node, - messageId: "complex", - data: { name, complexity, max: THRESHOLD } - }); - } - } - - /** - * Increase the complexity of the function in context - * @returns {void} - * @private - */ - function increaseComplexity() { - if (fns.length) { - fns[fns.length - 1]++; - } - } - - /** - * Increase the switch complexity in context - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function increaseSwitchComplexity(node) { - - // Avoiding `default` - if (node.test) { - increaseComplexity(); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction, - - CatchClause: increaseComplexity, - ConditionalExpression: increaseComplexity, - LogicalExpression: increaseComplexity, - ForStatement: increaseComplexity, - ForInStatement: increaseComplexity, - ForOfStatement: increaseComplexity, - IfStatement: increaseComplexity, - SwitchCase: increaseSwitchComplexity, - WhileStatement: increaseComplexity, - DoWhileStatement: increaseComplexity - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/computed-property-spacing.js b/tools/node_modules/eslint/lib/rules/computed-property-spacing.js deleted file mode 100644 index 53fdb8f4e41f956a102cf479c71bab40b9013025..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/computed-property-spacing.js +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside computed properties. - * @author Jamund Ferguson - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside computed property brackets", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/computed-property-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - enforceForClassMembers: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.", - unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.", - - missingSpaceBefore: "A space is required before '{{tokenValue}}'.", - missingSpaceAfter: "A space is required after '{{tokenValue}}'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never" - const enforceForClassMembers = !context.options[1] || context.options[1].enforceForClassMembers; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @param {Token} tokenAfter The token after `token`. - * @returns {void} - */ - function reportNoBeginningSpace(node, token, tokenAfter) { - context.report({ - node, - loc: { start: token.loc.end, end: tokenAfter.loc.start }, - messageId: "unexpectedSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.removeRange([token.range[1], tokenAfter.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @param {Token} tokenBefore The token before `token`. - * @returns {void} - */ - function reportNoEndingSpace(node, token, tokenBefore) { - context.report({ - node, - loc: { start: tokenBefore.loc.end, end: token.loc.start }, - messageId: "unexpectedSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.removeRange([tokenBefore.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a space after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingSpaceAfter", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - /** - * Reports that there should be a space before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingSpace(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "missingSpaceBefore", - data: { - tokenValue: token.value - }, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - /** - * Returns a function that checks the spacing of a node on the property name - * that was passed in. - * @param {string} propertyName The property on the node to check for spacing - * @returns {Function} A function that will check spacing on a node - */ - function checkSpacing(propertyName) { - return function(node) { - if (!node.computed) { - return; - } - - const property = node[propertyName]; - - const before = sourceCode.getTokenBefore(property, astUtils.isOpeningBracketToken), - first = sourceCode.getTokenAfter(before, { includeComments: true }), - after = sourceCode.getTokenAfter(property, astUtils.isClosingBracketToken), - last = sourceCode.getTokenBefore(after, { includeComments: true }); - - if (astUtils.isTokenOnSameLine(before, first)) { - if (propertyNameMustBeSpaced) { - if (!sourceCode.isSpaceBetweenTokens(before, first) && astUtils.isTokenOnSameLine(before, first)) { - reportRequiredBeginningSpace(node, before); - } - } else { - if (sourceCode.isSpaceBetweenTokens(before, first)) { - reportNoBeginningSpace(node, before, first); - } - } - } - - if (astUtils.isTokenOnSameLine(last, after)) { - if (propertyNameMustBeSpaced) { - if (!sourceCode.isSpaceBetweenTokens(last, after) && astUtils.isTokenOnSameLine(last, after)) { - reportRequiredEndingSpace(node, after); - } - } else { - if (sourceCode.isSpaceBetweenTokens(last, after)) { - reportNoEndingSpace(node, after, last); - } - } - } - }; - } - - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - const listeners = { - Property: checkSpacing("key"), - MemberExpression: checkSpacing("property") - }; - - if (enforceForClassMembers) { - listeners.MethodDefinition = checkSpacing("key"); - } - - return listeners; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/consistent-return.js b/tools/node_modules/eslint/lib/rules/consistent-return.js deleted file mode 100644 index 94db253d25bacb654e2f4cb67102f3d8321a7d27..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/consistent-return.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * @fileoverview Rule to flag consistent return values - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given code path segment is unreachable. - * @param {CodePathSegment} segment A CodePathSegment to check. - * @returns {boolean} `true` if the segment is unreachable. - */ -function isUnreachable(segment) { - return !segment.reachable; -} - -/** - * Checks whether a given node is a `constructor` method in an ES6 class - * @param {ASTNode} node A node to check - * @returns {boolean} `true` if the node is a `constructor` method - */ -function isClassConstructor(node) { - return node.type === "FunctionExpression" && - node.parent && - node.parent.type === "MethodDefinition" && - node.parent.kind === "constructor"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `return` statements to either always or never specify values", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/consistent-return" - }, - - schema: [{ - type: "object", - properties: { - treatUndefinedAsUnspecified: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - - messages: { - missingReturn: "Expected to return a value at the end of {{name}}.", - missingReturnValue: "{{name}} expected a return value.", - unexpectedReturnValue: "{{name}} expected no return value." - } - }, - - create(context) { - const options = context.options[0] || {}; - const treatUndefinedAsUnspecified = options.treatUndefinedAsUnspecified === true; - let funcInfo = null; - - /** - * Checks whether of not the implicit returning is consistent if the last - * code path segment is reachable. - * @param {ASTNode} node A program/function node to check. - * @returns {void} - */ - function checkLastSegment(node) { - let loc, name; - - /* - * Skip if it expected no return value or unreachable. - * When unreachable, all paths are returned or thrown. - */ - if (!funcInfo.hasReturnValue || - funcInfo.codePath.currentSegments.every(isUnreachable) || - astUtils.isES5Constructor(node) || - isClassConstructor(node) - ) { - return; - } - - // Adjust a location and a message. - if (node.type === "Program") { - - // The head of program. - loc = { line: 1, column: 0 }; - name = "program"; - } else if (node.type === "ArrowFunctionExpression") { - - // `=>` token - loc = context.getSourceCode().getTokenBefore(node.body, astUtils.isArrowToken).loc.start; - } else if ( - node.parent.type === "MethodDefinition" || - (node.parent.type === "Property" && node.parent.method) - ) { - - // Method name. - loc = node.parent.key.loc.start; - } else { - - // Function name or `function` keyword. - loc = (node.id || node).loc.start; - } - - if (!name) { - name = astUtils.getFunctionNameWithKind(node); - } - - // Reports. - context.report({ - node, - loc, - messageId: "missingReturn", - data: { name } - }); - } - - return { - - // Initializes/Disposes state of each code path. - onCodePathStart(codePath, node) { - funcInfo = { - upper: funcInfo, - codePath, - hasReturn: false, - hasReturnValue: false, - messageId: "", - node - }; - }, - onCodePathEnd() { - funcInfo = funcInfo.upper; - }, - - // Reports a given return statement if it's inconsistent. - ReturnStatement(node) { - const argument = node.argument; - let hasReturnValue = Boolean(argument); - - if (treatUndefinedAsUnspecified && hasReturnValue) { - hasReturnValue = !astUtils.isSpecificId(argument, "undefined") && argument.operator !== "void"; - } - - if (!funcInfo.hasReturn) { - funcInfo.hasReturn = true; - funcInfo.hasReturnValue = hasReturnValue; - funcInfo.messageId = hasReturnValue ? "missingReturnValue" : "unexpectedReturnValue"; - funcInfo.data = { - name: funcInfo.node.type === "Program" - ? "Program" - : lodash.upperFirst(astUtils.getFunctionNameWithKind(funcInfo.node)) - }; - } else if (funcInfo.hasReturnValue !== hasReturnValue) { - context.report({ - node, - messageId: funcInfo.messageId, - data: funcInfo.data - }); - } - }, - - // Reports a given program/function if the implicit returning is not consistent. - "Program:exit": checkLastSegment, - "FunctionDeclaration:exit": checkLastSegment, - "FunctionExpression:exit": checkLastSegment, - "ArrowFunctionExpression:exit": checkLastSegment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/consistent-this.js b/tools/node_modules/eslint/lib/rules/consistent-this.js deleted file mode 100644 index e5bc9678daef3c4f48fd77768312432e02044e3e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/consistent-this.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @fileoverview Rule to enforce consistent naming of "this" context variables - * @author Raphael Pigulla - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce consistent naming when capturing the current execution context", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/consistent-this" - }, - - schema: { - type: "array", - items: { - type: "string", - minLength: 1 - }, - uniqueItems: true - }, - - messages: { - aliasNotAssignedToThis: "Designated alias '{{name}}' is not assigned to 'this'.", - unexpectedAlias: "Unexpected alias '{{name}}' for 'this'." - } - }, - - create(context) { - let aliases = []; - - if (context.options.length === 0) { - aliases.push("that"); - } else { - aliases = context.options; - } - - /** - * Reports that a variable declarator or assignment expression is assigning - * a non-'this' value to the specified alias. - * @param {ASTNode} node The assigning node. - * @param {string} name the name of the alias that was incorrectly used. - * @returns {void} - */ - function reportBadAssignment(node, name) { - context.report({ node, messageId: "aliasNotAssignedToThis", data: { name } }); - } - - /** - * Checks that an assignment to an identifier only assigns 'this' to the - * appropriate alias, and the alias is only assigned to 'this'. - * @param {ASTNode} node The assigning node. - * @param {Identifier} name The name of the variable assigned to. - * @param {Expression} value The value of the assignment. - * @returns {void} - */ - function checkAssignment(node, name, value) { - const isThis = value.type === "ThisExpression"; - - if (aliases.indexOf(name) !== -1) { - if (!isThis || node.operator && node.operator !== "=") { - reportBadAssignment(node, name); - } - } else if (isThis) { - context.report({ node, messageId: "unexpectedAlias", data: { name } }); - } - } - - /** - * Ensures that a variable declaration of the alias in a program or function - * is assigned to the correct value. - * @param {string} alias alias the check the assignment of. - * @param {Object} scope scope of the current code we are checking. - * @private - * @returns {void} - */ - function checkWasAssigned(alias, scope) { - const variable = scope.set.get(alias); - - if (!variable) { - return; - } - - if (variable.defs.some(def => def.node.type === "VariableDeclarator" && - def.node.init !== null)) { - return; - } - - /* - * The alias has been declared and not assigned: check it was - * assigned later in the same scope. - */ - if (!variable.references.some(reference => { - const write = reference.writeExpr; - - return ( - reference.from === scope && - write && write.type === "ThisExpression" && - write.parent.operator === "=" - ); - })) { - variable.defs.map(def => def.node).forEach(node => { - reportBadAssignment(node, alias); - }); - } - } - - /** - * Check each alias to ensure that is was assigned to the correct value. - * @returns {void} - */ - function ensureWasAssigned() { - const scope = context.getScope(); - - aliases.forEach(alias => { - checkWasAssigned(alias, scope); - }); - } - - return { - "Program:exit": ensureWasAssigned, - "FunctionExpression:exit": ensureWasAssigned, - "FunctionDeclaration:exit": ensureWasAssigned, - - VariableDeclarator(node) { - const id = node.id; - const isDestructuring = - id.type === "ArrayPattern" || id.type === "ObjectPattern"; - - if (node.init !== null && !isDestructuring) { - checkAssignment(node, id.name, node.init); - } - }, - - AssignmentExpression(node) { - if (node.left.type === "Identifier") { - checkAssignment(node, node.left.name, node.right); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/constructor-super.js b/tools/node_modules/eslint/lib/rules/constructor-super.js deleted file mode 100644 index 8787fc569a4f15db0dac686864c0f49c4fb26564..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/constructor-super.js +++ /dev/null @@ -1,412 +0,0 @@ -/** - * @fileoverview A rule to verify `super()` callings in constructor. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a given code path segment is reachable or not. - * @param {CodePathSegment} segment A code path segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Checks whether or not a given node is a constructor. - * @param {ASTNode} node A node to check. This node type is one of - * `Program`, `FunctionDeclaration`, `FunctionExpression`, and - * `ArrowFunctionExpression`. - * @returns {boolean} `true` if the node is a constructor. - */ -function isConstructorFunction(node) { - return ( - node.type === "FunctionExpression" && - node.parent.type === "MethodDefinition" && - node.parent.kind === "constructor" - ); -} - -/** - * Checks whether a given node can be a constructor or not. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node can be a constructor. - */ -function isPossibleConstructor(node) { - if (!node) { - return false; - } - - switch (node.type) { - case "ClassExpression": - case "FunctionExpression": - case "ThisExpression": - case "MemberExpression": - case "CallExpression": - case "NewExpression": - case "ChainExpression": - case "YieldExpression": - case "TaggedTemplateExpression": - case "MetaProperty": - return true; - - case "Identifier": - return node.name !== "undefined"; - - case "AssignmentExpression": - if (["=", "&&="].includes(node.operator)) { - return isPossibleConstructor(node.right); - } - - if (["||=", "??="].includes(node.operator)) { - return ( - isPossibleConstructor(node.left) || - isPossibleConstructor(node.right) - ); - } - - /** - * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). - * An assignment expression with a mathematical operator can either evaluate to a primitive value, - * or throw, depending on the operands. Thus, it cannot evaluate to a constructor function. - */ - return false; - - case "LogicalExpression": - return ( - isPossibleConstructor(node.left) || - isPossibleConstructor(node.right) - ); - - case "ConditionalExpression": - return ( - isPossibleConstructor(node.alternate) || - isPossibleConstructor(node.consequent) - ); - - case "SequenceExpression": { - const lastExpression = node.expressions[node.expressions.length - 1]; - - return isPossibleConstructor(lastExpression); - } - - default: - return false; - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "require `super()` calls in constructors", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/constructor-super" - }, - - schema: [], - - messages: { - missingSome: "Lacked a call of 'super()' in some code paths.", - missingAll: "Expected to call 'super()'.", - - duplicate: "Unexpected duplicate 'super()'.", - badSuper: "Unexpected 'super()' because 'super' is not a constructor.", - unexpected: "Unexpected 'super()'." - } - }, - - create(context) { - - /* - * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]} - * Information for each constructor. - * - upper: Information of the upper constructor. - * - hasExtends: A flag which shows whether own class has a valid `extends` - * part. - * - scope: The scope of own class. - * - codePath: The code path object of the constructor. - */ - let funcInfo = null; - - /* - * {Map} - * Information for each code path segment. - * - calledInSomePaths: A flag of be called `super()` in some code paths. - * - calledInEveryPaths: A flag of be called `super()` in all code paths. - * - validNodes: - */ - let segInfoMap = Object.create(null); - - /** - * Gets the flag which shows `super()` is called in some paths. - * @param {CodePathSegment} segment A code path segment to get. - * @returns {boolean} The flag which shows `super()` is called in some paths - */ - function isCalledInSomePath(segment) { - return segment.reachable && segInfoMap[segment.id].calledInSomePaths; - } - - /** - * Gets the flag which shows `super()` is called in all paths. - * @param {CodePathSegment} segment A code path segment to get. - * @returns {boolean} The flag which shows `super()` is called in all paths. - */ - function isCalledInEveryPath(segment) { - - /* - * If specific segment is the looped segment of the current segment, - * skip the segment. - * If not skipped, this never becomes true after a loop. - */ - if (segment.nextSegments.length === 1 && - segment.nextSegments[0].isLoopedPrevSegment(segment) - ) { - return true; - } - return segment.reachable && segInfoMap[segment.id].calledInEveryPaths; - } - - return { - - /** - * Stacks a constructor information. - * @param {CodePath} codePath A code path which was started. - * @param {ASTNode} node The current node. - * @returns {void} - */ - onCodePathStart(codePath, node) { - if (isConstructorFunction(node)) { - - // Class > ClassBody > MethodDefinition > FunctionExpression - const classNode = node.parent.parent.parent; - const superClass = classNode.superClass; - - funcInfo = { - upper: funcInfo, - isConstructor: true, - hasExtends: Boolean(superClass), - superIsConstructor: isPossibleConstructor(superClass), - codePath - }; - } else { - funcInfo = { - upper: funcInfo, - isConstructor: false, - hasExtends: false, - superIsConstructor: false, - codePath - }; - } - }, - - /** - * Pops a constructor information. - * And reports if `super()` lacked. - * @param {CodePath} codePath A code path which was ended. - * @param {ASTNode} node The current node. - * @returns {void} - */ - onCodePathEnd(codePath, node) { - const hasExtends = funcInfo.hasExtends; - - // Pop. - funcInfo = funcInfo.upper; - - if (!hasExtends) { - return; - } - - // Reports if `super()` lacked. - const segments = codePath.returnedSegments; - const calledInEveryPaths = segments.every(isCalledInEveryPath); - const calledInSomePaths = segments.some(isCalledInSomePath); - - if (!calledInEveryPaths) { - context.report({ - messageId: calledInSomePaths - ? "missingSome" - : "missingAll", - node: node.parent - }); - } - }, - - /** - * Initialize information of a given code path segment. - * @param {CodePathSegment} segment A code path segment to initialize. - * @returns {void} - */ - onCodePathSegmentStart(segment) { - if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { - return; - } - - // Initialize info. - const info = segInfoMap[segment.id] = { - calledInSomePaths: false, - calledInEveryPaths: false, - validNodes: [] - }; - - // When there are previous segments, aggregates these. - const prevSegments = segment.prevSegments; - - if (prevSegments.length > 0) { - info.calledInSomePaths = prevSegments.some(isCalledInSomePath); - info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); - } - }, - - /** - * Update information of the code path segment when a code path was - * looped. - * @param {CodePathSegment} fromSegment The code path segment of the - * end of a loop. - * @param {CodePathSegment} toSegment A code path segment of the head - * of a loop. - * @returns {void} - */ - onCodePathSegmentLoop(fromSegment, toSegment) { - if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { - return; - } - - // Update information inside of the loop. - const isRealLoop = toSegment.prevSegments.length >= 2; - - funcInfo.codePath.traverseSegments( - { first: toSegment, last: fromSegment }, - segment => { - const info = segInfoMap[segment.id]; - const prevSegments = segment.prevSegments; - - // Updates flags. - info.calledInSomePaths = prevSegments.some(isCalledInSomePath); - info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath); - - // If flags become true anew, reports the valid nodes. - if (info.calledInSomePaths || isRealLoop) { - const nodes = info.validNodes; - - info.validNodes = []; - - for (let i = 0; i < nodes.length; ++i) { - const node = nodes[i]; - - context.report({ - messageId: "duplicate", - node - }); - } - } - } - ); - }, - - /** - * Checks for a call of `super()`. - * @param {ASTNode} node A CallExpression node to check. - * @returns {void} - */ - "CallExpression:exit"(node) { - if (!(funcInfo && funcInfo.isConstructor)) { - return; - } - - // Skips except `super()`. - if (node.callee.type !== "Super") { - return; - } - - // Reports if needed. - if (funcInfo.hasExtends) { - const segments = funcInfo.codePath.currentSegments; - let duplicate = false; - let info = null; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - info = segInfoMap[segment.id]; - - duplicate = duplicate || info.calledInSomePaths; - info.calledInSomePaths = info.calledInEveryPaths = true; - } - } - - if (info) { - if (duplicate) { - context.report({ - messageId: "duplicate", - node - }); - } else if (!funcInfo.superIsConstructor) { - context.report({ - messageId: "badSuper", - node - }); - } else { - info.validNodes.push(node); - } - } - } else if (funcInfo.codePath.currentSegments.some(isReachable)) { - context.report({ - messageId: "unexpected", - node - }); - } - }, - - /** - * Set the mark to the returned path as `super()` was called. - * @param {ASTNode} node A ReturnStatement node to check. - * @returns {void} - */ - ReturnStatement(node) { - if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) { - return; - } - - // Skips if no argument. - if (!node.argument) { - return; - } - - // Returning argument is a substitute of 'super()'. - const segments = funcInfo.codePath.currentSegments; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - const info = segInfoMap[segment.id]; - - info.calledInSomePaths = info.calledInEveryPaths = true; - } - } - }, - - /** - * Resets state. - * @returns {void} - */ - "Program:exit"() { - segInfoMap = Object.create(null); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/curly.js b/tools/node_modules/eslint/lib/rules/curly.js deleted file mode 100644 index 29f00c0ad0b617ebfa765b3d48e7289355fde30e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/curly.js +++ /dev/null @@ -1,488 +0,0 @@ -/** - * @fileoverview Rule to flag statements without curly braces - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce consistent brace style for all control statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/curly" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["all"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["multi", "multi-line", "multi-or-nest"] - }, - { - enum: ["consistent"] - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - fixable: "code", - - messages: { - missingCurlyAfter: "Expected { after '{{name}}'.", - missingCurlyAfterCondition: "Expected { after '{{name}}' condition.", - unexpectedCurlyAfter: "Unnecessary { after '{{name}}'.", - unexpectedCurlyAfterCondition: "Unnecessary { after '{{name}}' condition." - } - }, - - create(context) { - - const multiOnly = (context.options[0] === "multi"); - const multiLine = (context.options[0] === "multi-line"); - const multiOrNest = (context.options[0] === "multi-or-nest"); - const consistent = (context.options[1] === "consistent"); - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Determines if a given node is a one-liner that's on the same line as it's preceding code. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is a one-liner that's on the same line as it's preceding code. - * @private - */ - function isCollapsedOneLiner(node) { - const before = sourceCode.getTokenBefore(node); - const last = sourceCode.getLastToken(node); - const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last; - - return before.loc.start.line === lastExcludingSemicolon.loc.end.line; - } - - /** - * Determines if a given node is a one-liner. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is a one-liner. - * @private - */ - function isOneLiner(node) { - if (node.type === "EmptyStatement") { - return true; - } - - const first = sourceCode.getFirstToken(node); - const last = sourceCode.getLastToken(node); - const lastExcludingSemicolon = astUtils.isSemicolonToken(last) ? sourceCode.getTokenBefore(last) : last; - - return first.loc.start.line === lastExcludingSemicolon.loc.end.line; - } - - /** - * Determines if the given node is a lexical declaration (let, const, function, or class) - * @param {ASTNode} node The node to check - * @returns {boolean} True if the node is a lexical declaration - * @private - */ - function isLexicalDeclaration(node) { - if (node.type === "VariableDeclaration") { - return node.kind === "const" || node.kind === "let"; - } - - return node.type === "FunctionDeclaration" || node.type === "ClassDeclaration"; - } - - /** - * Checks if the given token is an `else` token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is an `else` token. - */ - function isElseKeywordToken(token) { - return token.value === "else" && token.type === "Keyword"; - } - - /** - * Gets the `else` keyword token of a given `IfStatement` node. - * @param {ASTNode} node A `IfStatement` node to get. - * @returns {Token} The `else` keyword token. - */ - function getElseKeyword(node) { - return node.alternate && sourceCode.getFirstTokenBetween(node.consequent, node.alternate, isElseKeywordToken); - } - - /** - * Determines whether the given node has an `else` keyword token as the first token after. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is followed by an `else` keyword token. - */ - function isFollowedByElseKeyword(node) { - const nextToken = sourceCode.getTokenAfter(node); - - return Boolean(nextToken) && isElseKeywordToken(nextToken); - } - - /** - * Determines if a semicolon needs to be inserted after removing a set of curly brackets, in order to avoid a SyntaxError. - * @param {Token} closingBracket The } token - * @returns {boolean} `true` if a semicolon needs to be inserted after the last statement in the block. - */ - function needsSemicolon(closingBracket) { - const tokenBefore = sourceCode.getTokenBefore(closingBracket); - const tokenAfter = sourceCode.getTokenAfter(closingBracket); - const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]); - - if (astUtils.isSemicolonToken(tokenBefore)) { - - // If the last statement already has a semicolon, don't add another one. - return false; - } - - if (!tokenAfter) { - - // If there are no statements after this block, there is no need to add a semicolon. - return false; - } - - if (lastBlockNode.type === "BlockStatement" && lastBlockNode.parent.type !== "FunctionExpression" && lastBlockNode.parent.type !== "ArrowFunctionExpression") { - - /* - * If the last node surrounded by curly brackets is a BlockStatement (other than a FunctionExpression or an ArrowFunctionExpression), - * don't insert a semicolon. Otherwise, the semicolon would be parsed as a separate statement, which would cause - * a SyntaxError if it was followed by `else`. - */ - return false; - } - - if (tokenBefore.loc.end.line === tokenAfter.loc.start.line) { - - // If the next token is on the same line, insert a semicolon. - return true; - } - - if (/^[([/`+-]/u.test(tokenAfter.value)) { - - // If the next token starts with a character that would disrupt ASI, insert a semicolon. - return true; - } - - if (tokenBefore.type === "Punctuator" && (tokenBefore.value === "++" || tokenBefore.value === "--")) { - - // If the last token is ++ or --, insert a semicolon to avoid disrupting ASI. - return true; - } - - // Otherwise, do not insert a semicolon. - return false; - } - - /** - * Determines whether the code represented by the given node contains an `if` statement - * that would become associated with an `else` keyword directly appended to that code. - * - * Examples where it returns `true`: - * - * if (a) - * foo(); - * - * if (a) { - * foo(); - * } - * - * if (a) - * foo(); - * else if (b) - * bar(); - * - * while (a) - * if (b) - * if(c) - * foo(); - * else - * bar(); - * - * Examples where it returns `false`: - * - * if (a) - * foo(); - * else - * bar(); - * - * while (a) { - * if (b) - * if(c) - * foo(); - * else - * bar(); - * } - * - * while (a) - * if (b) { - * if(c) - * foo(); - * } - * else - * bar(); - * @param {ASTNode} node Node representing the code to check. - * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code. - */ - function hasUnsafeIf(node) { - switch (node.type) { - case "IfStatement": - if (!node.alternate) { - return true; - } - return hasUnsafeIf(node.alternate); - case "ForStatement": - case "ForInStatement": - case "ForOfStatement": - case "LabeledStatement": - case "WithStatement": - case "WhileStatement": - return hasUnsafeIf(node.body); - default: - return false; - } - } - - /** - * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code. - * The braces, which make the given block body, are necessary in either of the following situations: - * - * 1. The statement is a lexical declaration. - * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace: - * - * if (a) { - * if (b) - * foo(); - * } - * else - * bar(); - * - * if (a) - * while (b) - * while (c) { - * while (d) - * if (e) - * while(f) - * foo(); - * } - * else - * bar(); - * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements. - * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content) - * would change the semantics of the code or produce a syntax error. - */ - function areBracesNecessary(node) { - const statement = node.body[0]; - - return isLexicalDeclaration(statement) || - hasUnsafeIf(statement) && isFollowedByElseKeyword(node); - } - - /** - * Prepares to check the body of a node to see if it's a block statement. - * @param {ASTNode} node The node to report if there's a problem. - * @param {ASTNode} body The body node to check for blocks. - * @param {string} name The name to report if there's a problem. - * @param {{ condition: boolean }} opts Options to pass to the report functions - * @returns {Object} a prepared check object, with "actual", "expected", "check" properties. - * "actual" will be `true` or `false` whether the body is already a block statement. - * "expected" will be `true` or `false` if the body should be a block statement or not, or - * `null` if it doesn't matter, depending on the rule options. It can be modified to change - * the final behavior of "check". - * "check" will be a function reporting appropriate problems depending on the other - * properties. - */ - function prepareCheck(node, body, name, opts) { - const hasBlock = (body.type === "BlockStatement"); - let expected = null; - - if (hasBlock && (body.body.length !== 1 || areBracesNecessary(body))) { - expected = true; - } else if (multiOnly) { - expected = false; - } else if (multiLine) { - if (!isCollapsedOneLiner(body)) { - expected = true; - } - - // otherwise, the body is allowed to have braces or not to have braces - - } else if (multiOrNest) { - if (hasBlock) { - const statement = body.body[0]; - const leadingCommentsInBlock = sourceCode.getCommentsBefore(statement); - - expected = !isOneLiner(statement) || leadingCommentsInBlock.length > 0; - } else { - expected = !isOneLiner(body); - } - } else { - - // default "all" - expected = true; - } - - return { - actual: hasBlock, - expected, - check() { - if (this.expected !== null && this.expected !== this.actual) { - if (this.expected) { - context.report({ - node, - loc: (name !== "else" ? node : getElseKeyword(node)).loc.start, - messageId: opts && opts.condition ? "missingCurlyAfterCondition" : "missingCurlyAfter", - data: { - name - }, - fix: fixer => fixer.replaceText(body, `{${sourceCode.getText(body)}}`) - }); - } else { - context.report({ - node, - loc: (name !== "else" ? node : getElseKeyword(node)).loc.start, - messageId: opts && opts.condition ? "unexpectedCurlyAfterCondition" : "unexpectedCurlyAfter", - data: { - name - }, - fix(fixer) { - - /* - * `do while` expressions sometimes need a space to be inserted after `do`. - * e.g. `do{foo()} while (bar)` should be corrected to `do foo() while (bar)` - */ - const needsPrecedingSpace = node.type === "DoWhileStatement" && - sourceCode.getTokenBefore(body).range[1] === body.range[0] && - !astUtils.canTokensBeAdjacent("do", sourceCode.getFirstToken(body, { skip: 1 })); - - const openingBracket = sourceCode.getFirstToken(body); - const closingBracket = sourceCode.getLastToken(body); - const lastTokenInBlock = sourceCode.getTokenBefore(closingBracket); - - if (needsSemicolon(closingBracket)) { - - /* - * If removing braces would cause a SyntaxError due to multiple statements on the same line (or - * change the semantics of the code due to ASI), don't perform a fix. - */ - return null; - } - - const resultingBodyText = sourceCode.getText().slice(openingBracket.range[1], lastTokenInBlock.range[0]) + - sourceCode.getText(lastTokenInBlock) + - sourceCode.getText().slice(lastTokenInBlock.range[1], closingBracket.range[0]); - - return fixer.replaceText(body, (needsPrecedingSpace ? " " : "") + resultingBodyText); - } - }); - } - } - } - }; - } - - /** - * Prepares to check the bodies of a "if", "else if" and "else" chain. - * @param {ASTNode} node The first IfStatement node of the chain. - * @returns {Object[]} prepared checks for each body of the chain. See `prepareCheck` for more - * information. - */ - function prepareIfChecks(node) { - const preparedChecks = []; - - for (let currentNode = node; currentNode; currentNode = currentNode.alternate) { - preparedChecks.push(prepareCheck(currentNode, currentNode.consequent, "if", { condition: true })); - if (currentNode.alternate && currentNode.alternate.type !== "IfStatement") { - preparedChecks.push(prepareCheck(currentNode, currentNode.alternate, "else")); - break; - } - } - - if (consistent) { - - /* - * If any node should have or already have braces, make sure they - * all have braces. - * If all nodes shouldn't have braces, make sure they don't. - */ - const expected = preparedChecks.some(preparedCheck => { - if (preparedCheck.expected !== null) { - return preparedCheck.expected; - } - return preparedCheck.actual; - }); - - preparedChecks.forEach(preparedCheck => { - preparedCheck.expected = expected; - }); - } - - return preparedChecks; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - IfStatement(node) { - if (node.parent.type !== "IfStatement") { - prepareIfChecks(node).forEach(preparedCheck => { - preparedCheck.check(); - }); - } - }, - - WhileStatement(node) { - prepareCheck(node, node.body, "while", { condition: true }).check(); - }, - - DoWhileStatement(node) { - prepareCheck(node, node.body, "do").check(); - }, - - ForStatement(node) { - prepareCheck(node, node.body, "for", { condition: true }).check(); - }, - - ForInStatement(node) { - prepareCheck(node, node.body, "for-in").check(); - }, - - ForOfStatement(node) { - prepareCheck(node, node.body, "for-of").check(); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/default-case-last.js b/tools/node_modules/eslint/lib/rules/default-case-last.js deleted file mode 100644 index 80c5d6bda73958fa7a032fc5f9530c0f89bf8100..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/default-case-last.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @fileoverview Rule to enforce default clauses in switch statements to be last - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce default clauses in switch statements to be last", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/default-case-last" - }, - - schema: [], - - messages: { - notLast: "Default clause should be the last clause." - } - }, - - create(context) { - return { - SwitchStatement(node) { - const cases = node.cases, - indexOfDefault = cases.findIndex(c => c.test === null); - - if (indexOfDefault !== -1 && indexOfDefault !== cases.length - 1) { - const defaultClause = cases[indexOfDefault]; - - context.report({ node: defaultClause, messageId: "notLast" }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/default-case.js b/tools/node_modules/eslint/lib/rules/default-case.js deleted file mode 100644 index 821e0d72bd1cba5657799868e2881d6168e15a71..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/default-case.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @fileoverview require default case in switch statements - * @author Aliaksei Shytkin - */ -"use strict"; - -const DEFAULT_COMMENT_PATTERN = /^no default$/iu; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `default` cases in `switch` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/default-case" - }, - - schema: [{ - type: "object", - properties: { - commentPattern: { - type: "string" - } - }, - additionalProperties: false - }], - - messages: { - missingDefaultCase: "Expected a default case." - } - }, - - create(context) { - const options = context.options[0] || {}; - const commentPattern = options.commentPattern - ? new RegExp(options.commentPattern, "u") - : DEFAULT_COMMENT_PATTERN; - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Shortcut to get last element of array - * @param {*[]} collection Array - * @returns {*} Last element - */ - function last(collection) { - return collection[collection.length - 1]; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - SwitchStatement(node) { - - if (!node.cases.length) { - - /* - * skip check of empty switch because there is no easy way - * to extract comments inside it now - */ - return; - } - - const hasDefault = node.cases.some(v => v.test === null); - - if (!hasDefault) { - - let comment; - - const lastCase = last(node.cases); - const comments = sourceCode.getCommentsAfter(lastCase); - - if (comments.length) { - comment = last(comments); - } - - if (!comment || !commentPattern.test(comment.value.trim())) { - context.report({ node, messageId: "missingDefaultCase" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/default-param-last.js b/tools/node_modules/eslint/lib/rules/default-param-last.js deleted file mode 100644 index 12e0b5950dace6c89ca781a20f3a8e6a488dba61..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/default-param-last.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @fileoverview enforce default parameters to be last - * @author Chiawen Chen - */ - -"use strict"; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce default parameters to be last", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/default-param-last" - }, - - schema: [], - - messages: { - shouldBeLast: "Default parameters should be last." - } - }, - - create(context) { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ASTNode} node function node - * @returns {void} - */ - function handleFunction(node) { - let hasSeenPlainParam = false; - - for (let i = node.params.length - 1; i >= 0; i -= 1) { - const param = node.params[i]; - - if ( - param.type !== "AssignmentPattern" && - param.type !== "RestElement" - ) { - hasSeenPlainParam = true; - continue; - } - - if (hasSeenPlainParam && param.type === "AssignmentPattern") { - context.report({ - node: param, - messageId: "shouldBeLast" - }); - } - } - } - - return { - FunctionDeclaration: handleFunction, - FunctionExpression: handleFunction, - ArrowFunctionExpression: handleFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/dot-location.js b/tools/node_modules/eslint/lib/rules/dot-location.js deleted file mode 100644 index 0a739b1712b902949b471c258ae8bf1a35de1b47..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/dot-location.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @fileoverview Validates newlines before and after dots - * @author Greg Cochard - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent newlines before and after dots", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/dot-location" - }, - - schema: [ - { - enum: ["object", "property"] - } - ], - - fixable: "code", - - messages: { - expectedDotAfterObject: "Expected dot to be on same line as object.", - expectedDotBeforeProperty: "Expected dot to be on same line as property." - } - }, - - create(context) { - - const config = context.options[0]; - - // default to onObject if no preference is passed - const onObject = config === "object" || !config; - - const sourceCode = context.getSourceCode(); - - /** - * Reports if the dot between object and property is on the correct loccation. - * @param {ASTNode} node The `MemberExpression` node. - * @returns {void} - */ - function checkDotLocation(node) { - const property = node.property; - const dotToken = sourceCode.getTokenBefore(property); - - if (onObject) { - - // `obj` expression can be parenthesized, but those paren tokens are not a part of the `obj` node. - const tokenBeforeDot = sourceCode.getTokenBefore(dotToken); - - if (!astUtils.isTokenOnSameLine(tokenBeforeDot, dotToken)) { - context.report({ - node, - loc: dotToken.loc, - messageId: "expectedDotAfterObject", - *fix(fixer) { - if (dotToken.value.startsWith(".") && astUtils.isDecimalIntegerNumericToken(tokenBeforeDot)) { - yield fixer.insertTextAfter(tokenBeforeDot, ` ${dotToken.value}`); - } else { - yield fixer.insertTextAfter(tokenBeforeDot, dotToken.value); - } - yield fixer.remove(dotToken); - } - }); - } - } else if (!astUtils.isTokenOnSameLine(dotToken, property)) { - context.report({ - node, - loc: dotToken.loc, - messageId: "expectedDotBeforeProperty", - *fix(fixer) { - yield fixer.remove(dotToken); - yield fixer.insertTextBefore(property, dotToken.value); - } - }); - } - } - - /** - * Checks the spacing of the dot within a member expression. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkNode(node) { - if (!node.computed) { - checkDotLocation(node); - } - } - - return { - MemberExpression: checkNode - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/dot-notation.js b/tools/node_modules/eslint/lib/rules/dot-notation.js deleted file mode 100644 index 751b4628edc4d5bef1eca0f333cb9c28e96c1c58..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/dot-notation.js +++ /dev/null @@ -1,176 +0,0 @@ -/** - * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible. - * @author Josh Perez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const keywords = require("./utils/keywords"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u; - -// `null` literal must be handled separately. -const literalTypesToCheck = new Set(["string", "boolean"]); - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce dot notation whenever possible", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/dot-notation" - }, - - schema: [ - { - type: "object", - properties: { - allowKeywords: { - type: "boolean", - default: true - }, - allowPattern: { - type: "string", - default: "" - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - useDot: "[{{key}}] is better written in dot notation.", - useBrackets: ".{{key}} is a syntax error." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords; - const sourceCode = context.getSourceCode(); - - let allowPattern; - - if (options.allowPattern) { - allowPattern = new RegExp(options.allowPattern, "u"); - } - - /** - * Check if the property is valid dot notation - * @param {ASTNode} node The dot notation node - * @param {string} value Value which is to be checked - * @returns {void} - */ - function checkComputedProperty(node, value) { - if ( - validIdentifier.test(value) && - (allowKeywords || keywords.indexOf(String(value)) === -1) && - !(allowPattern && allowPattern.test(value)) - ) { - const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``; - - context.report({ - node: node.property, - messageId: "useDot", - data: { - key: formattedValue - }, - *fix(fixer) { - const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken); - const rightBracket = sourceCode.getLastToken(node); - const nextToken = sourceCode.getTokenAfter(node); - - // Don't perform any fixes if there are comments inside the brackets. - if (sourceCode.commentsExistBetween(leftBracket, rightBracket)) { - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - // Replace the brackets by an identifier. - if (!node.optional) { - yield fixer.insertTextBefore( - leftBracket, - astUtils.isDecimalInteger(node.object) ? " ." : "." - ); - } - yield fixer.replaceTextRange( - [leftBracket.range[0], rightBracket.range[1]], - value - ); - - // Insert a space after the property if it will be connected to the next token. - if ( - nextToken && - rightBracket.range[1] === nextToken.range[0] && - !astUtils.canTokensBeAdjacent(String(value), nextToken) - ) { - yield fixer.insertTextAfter(node, " "); - } - } - }); - } - } - - return { - MemberExpression(node) { - if ( - node.computed && - node.property.type === "Literal" && - (literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property)) - ) { - checkComputedProperty(node, node.property.value); - } - if ( - node.computed && - node.property.type === "TemplateLiteral" && - node.property.expressions.length === 0 - ) { - checkComputedProperty(node, node.property.quasis[0].value.cooked); - } - if ( - !allowKeywords && - !node.computed && - keywords.indexOf(String(node.property.name)) !== -1 - ) { - context.report({ - node: node.property, - messageId: "useBrackets", - data: { - key: node.property.name - }, - *fix(fixer) { - const dotToken = sourceCode.getTokenBefore(node.property); - - // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression. - if (node.object.type === "Identifier" && node.object.name === "let" && !node.optional) { - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - // Don't perform any fixes if there are comments between the dot and the property name. - if (sourceCode.commentsExistBetween(dotToken, node.property)) { - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - // Replace the identifier to brackets. - if (!node.optional) { - yield fixer.remove(dotToken); - } - yield fixer.replaceText(node.property, `["${node.property.name}"]`); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/eol-last.js b/tools/node_modules/eslint/lib/rules/eol-last.js deleted file mode 100644 index fbba6c8f5e8be58d5628ff906a5cc0d299aa9cda..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/eol-last.js +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @fileoverview Require or disallow newline at the end of files - * @author Nodeca Team - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow newline at the end of files", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/eol-last" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never", "unix", "windows"] - } - ], - - messages: { - missing: "Newline required at end of file but not found.", - unexpected: "Newline not allowed at end of file." - } - }, - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: function checkBadEOF(node) { - const sourceCode = context.getSourceCode(), - src = sourceCode.getText(), - location = { - column: lodash.last(sourceCode.lines).length, - line: sourceCode.lines.length - }, - LF = "\n", - CRLF = `\r${LF}`, - endsWithNewline = lodash.endsWith(src, LF); - - /* - * Empty source is always valid: No content in file so we don't - * need to lint for a newline on the last line of content. - */ - if (!src.length) { - return; - } - - let mode = context.options[0] || "always", - appendCRLF = false; - - if (mode === "unix") { - - // `"unix"` should behave exactly as `"always"` - mode = "always"; - } - if (mode === "windows") { - - // `"windows"` should behave exactly as `"always"`, but append CRLF in the fixer for backwards compatibility - mode = "always"; - appendCRLF = true; - } - if (mode === "always" && !endsWithNewline) { - - // File is not newline-terminated, but should be - context.report({ - node, - loc: location, - messageId: "missing", - fix(fixer) { - return fixer.insertTextAfterRange([0, src.length], appendCRLF ? CRLF : LF); - } - }); - } else if (mode === "never" && endsWithNewline) { - - // File is newline-terminated, but shouldn't be - context.report({ - node, - loc: location, - messageId: "unexpected", - fix(fixer) { - const finalEOLs = /(?:\r?\n)+$/u, - match = finalEOLs.exec(sourceCode.text), - start = match.index, - end = sourceCode.text.length; - - return fixer.replaceTextRange([start, end], ""); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/eqeqeq.js b/tools/node_modules/eslint/lib/rules/eqeqeq.js deleted file mode 100644 index 57926dbed0e0529c1a95bdb1adafbf5089288609..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/eqeqeq.js +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @fileoverview Rule to flag statements that use != and == instead of !== and === - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require the use of `===` and `!==`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/eqeqeq" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always"] - }, - { - type: "object", - properties: { - null: { - enum: ["always", "never", "ignore"] - } - }, - additionalProperties: false - } - ], - additionalItems: false - }, - { - type: "array", - items: [ - { - enum: ["smart", "allow-null"] - } - ], - additionalItems: false - } - ] - }, - - fixable: "code", - - messages: { - unexpected: "Expected '{{expectedOperator}}' and instead saw '{{actualOperator}}'." - } - }, - - create(context) { - const config = context.options[0] || "always"; - const options = context.options[1] || {}; - const sourceCode = context.getSourceCode(); - - const nullOption = (config === "always") - ? options.null || "always" - : "ignore"; - const enforceRuleForNull = (nullOption === "always"); - const enforceInverseRuleForNull = (nullOption === "never"); - - /** - * Checks if an expression is a typeof expression - * @param {ASTNode} node The node to check - * @returns {boolean} if the node is a typeof expression - */ - function isTypeOf(node) { - return node.type === "UnaryExpression" && node.operator === "typeof"; - } - - /** - * Checks if either operand of a binary expression is a typeof operation - * @param {ASTNode} node The node to check - * @returns {boolean} if one of the operands is typeof - * @private - */ - function isTypeOfBinary(node) { - return isTypeOf(node.left) || isTypeOf(node.right); - } - - /** - * Checks if operands are literals of the same type (via typeof) - * @param {ASTNode} node The node to check - * @returns {boolean} if operands are of same type - * @private - */ - function areLiteralsAndSameType(node) { - return node.left.type === "Literal" && node.right.type === "Literal" && - typeof node.left.value === typeof node.right.value; - } - - /** - * Checks if one of the operands is a literal null - * @param {ASTNode} node The node to check - * @returns {boolean} if operands are null - * @private - */ - function isNullCheck(node) { - return astUtils.isNullLiteral(node.right) || astUtils.isNullLiteral(node.left); - } - - /** - * Reports a message for this rule. - * @param {ASTNode} node The binary expression node that was checked - * @param {string} expectedOperator The operator that was expected (either '==', '!=', '===', or '!==') - * @returns {void} - * @private - */ - function report(node, expectedOperator) { - const operatorToken = sourceCode.getFirstTokenBetween( - node.left, - node.right, - token => token.value === node.operator - ); - - context.report({ - node, - loc: operatorToken.loc, - messageId: "unexpected", - data: { expectedOperator, actualOperator: node.operator }, - fix(fixer) { - - // If the comparison is a `typeof` comparison or both sides are literals with the same type, then it's safe to fix. - if (isTypeOfBinary(node) || areLiteralsAndSameType(node)) { - return fixer.replaceText(operatorToken, expectedOperator); - } - return null; - } - }); - } - - return { - BinaryExpression(node) { - const isNull = isNullCheck(node); - - if (node.operator !== "==" && node.operator !== "!=") { - if (enforceInverseRuleForNull && isNull) { - report(node, node.operator.slice(0, -1)); - } - return; - } - - if (config === "smart" && (isTypeOfBinary(node) || - areLiteralsAndSameType(node) || isNull)) { - return; - } - - if (!enforceRuleForNull && isNull) { - return; - } - - report(node, `${node.operator}=`); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/for-direction.js b/tools/node_modules/eslint/lib/rules/for-direction.js deleted file mode 100644 index c15d10e5f842a43853aa052e6acbc9ee2c950f4f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/for-direction.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview enforce "for" loop update clause moving the counter in the right direction.(for-direction) - * @author Aladdin-ADD - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce \"for\" loop update clause moving the counter in the right direction.", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/for-direction" - }, - - fixable: null, - schema: [], - - messages: { - incorrectDirection: "The update clause in this loop moves the variable in the wrong direction." - } - }, - - create(context) { - - /** - * report an error. - * @param {ASTNode} node the node to report. - * @returns {void} - */ - function report(node) { - context.report({ - node, - messageId: "incorrectDirection" - }); - } - - /** - * check the right side of the assignment - * @param {ASTNode} update UpdateExpression to check - * @param {int} dir expected direction that could either be turned around or invalidated - * @returns {int} return dir, the negated dir or zero if it's not clear for identifiers - */ - function getRightDirection(update, dir) { - if (update.right.type === "UnaryExpression") { - if (update.right.operator === "-") { - return -dir; - } - } else if (update.right.type === "Identifier") { - return 0; - } - return dir; - } - - /** - * check UpdateExpression add/sub the counter - * @param {ASTNode} update UpdateExpression to check - * @param {string} counter variable name to check - * @returns {int} if add return 1, if sub return -1, if nochange, return 0 - */ - function getUpdateDirection(update, counter) { - if (update.argument.type === "Identifier" && update.argument.name === counter) { - if (update.operator === "++") { - return 1; - } - if (update.operator === "--") { - return -1; - } - } - return 0; - } - - /** - * check AssignmentExpression add/sub the counter - * @param {ASTNode} update AssignmentExpression to check - * @param {string} counter variable name to check - * @returns {int} if add return 1, if sub return -1, if nochange, return 0 - */ - function getAssignmentDirection(update, counter) { - if (update.left.name === counter) { - if (update.operator === "+=") { - return getRightDirection(update, 1); - } - if (update.operator === "-=") { - return getRightDirection(update, -1); - } - } - return 0; - } - return { - ForStatement(node) { - - if (node.test && node.test.type === "BinaryExpression" && node.test.left.type === "Identifier" && node.update) { - const counter = node.test.left.name; - const operator = node.test.operator; - const update = node.update; - - let wrongDirection; - - if (operator === "<" || operator === "<=") { - wrongDirection = -1; - } else if (operator === ">" || operator === ">=") { - wrongDirection = 1; - } else { - return; - } - - if (update.type === "UpdateExpression") { - if (getUpdateDirection(update, counter) === wrongDirection) { - report(node); - } - } else if (update.type === "AssignmentExpression" && getAssignmentDirection(update, counter) === wrongDirection) { - report(node); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-call-spacing.js b/tools/node_modules/eslint/lib/rules/func-call-spacing.js deleted file mode 100644 index 8fe690d4a6ba21bb7321852a0da22134e516410b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/func-call-spacing.js +++ /dev/null @@ -1,230 +0,0 @@ -/** - * @fileoverview Rule to control spacing within function calls - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing between function identifiers and their invocations", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-call-spacing" - }, - - fixable: "whitespace", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["never"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["always"] - }, - { - type: "object", - properties: { - allowNewlines: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - messages: { - unexpectedWhitespace: "Unexpected whitespace between function name and paren.", - unexpectedNewline: "Unexpected newline between function name and paren.", - missing: "Missing space between function name and paren." - } - }, - - create(context) { - - const never = context.options[0] !== "always"; - const allowNewlines = !never && context.options[1] && context.options[1].allowNewlines; - const sourceCode = context.getSourceCode(); - const text = sourceCode.getText(); - - /** - * Check if open space is present in a function name - * @param {ASTNode} node node to evaluate - * @param {Token} leftToken The last token of the callee. This may be the closing parenthesis that encloses the callee. - * @param {Token} rightToken Tha first token of the arguments. this is the opening parenthesis that encloses the arguments. - * @returns {void} - * @private - */ - function checkSpacing(node, leftToken, rightToken) { - const textBetweenTokens = text.slice(leftToken.range[1], rightToken.range[0]).replace(/\/\*.*?\*\//gu, ""); - const hasWhitespace = /\s/u.test(textBetweenTokens); - const hasNewline = hasWhitespace && astUtils.LINEBREAK_MATCHER.test(textBetweenTokens); - - /* - * never allowNewlines hasWhitespace hasNewline message - * F F F F Missing space between function name and paren. - * F F F T (Invalid `!hasWhitespace && hasNewline`) - * F F T T Unexpected newline between function name and paren. - * F F T F (OK) - * F T T F (OK) - * F T T T (OK) - * F T F T (Invalid `!hasWhitespace && hasNewline`) - * F T F F Missing space between function name and paren. - * T T F F (Invalid `never && allowNewlines`) - * T T F T (Invalid `!hasWhitespace && hasNewline`) - * T T T T (Invalid `never && allowNewlines`) - * T T T F (Invalid `never && allowNewlines`) - * T F T F Unexpected space between function name and paren. - * T F T T Unexpected space between function name and paren. - * T F F T (Invalid `!hasWhitespace && hasNewline`) - * T F F F (OK) - * - * T T Unexpected space between function name and paren. - * F F Missing space between function name and paren. - * F F T Unexpected newline between function name and paren. - */ - - if (never && hasWhitespace) { - context.report({ - node, - loc: { - start: leftToken.loc.end, - end: { - line: rightToken.loc.start.line, - column: rightToken.loc.start.column - 1 - } - }, - messageId: "unexpectedWhitespace", - fix(fixer) { - - // Don't remove comments. - if (sourceCode.commentsExistBetween(leftToken, rightToken)) { - return null; - } - - // If `?.` exsits, it doesn't hide no-undexpected-multiline errors - if (node.optional) { - return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], "?."); - } - - /* - * Only autofix if there is no newline - * https://github.com/eslint/eslint/issues/7787 - */ - if (hasNewline) { - return null; - } - return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); - } - }); - } else if (!never && !hasWhitespace) { - context.report({ - node, - loc: { - start: { - line: leftToken.loc.end.line, - column: leftToken.loc.end.column - 1 - }, - end: rightToken.loc.start - }, - messageId: "missing", - fix(fixer) { - if (node.optional) { - return null; // Not sure if inserting a space to either before/after `?.` token. - } - return fixer.insertTextBefore(rightToken, " "); - } - }); - } else if (!never && !allowNewlines && hasNewline) { - context.report({ - node, - loc: { - start: leftToken.loc.end, - end: rightToken.loc.start - }, - messageId: "unexpectedNewline", - fix(fixer) { - - /* - * Only autofix if there is no newline - * https://github.com/eslint/eslint/issues/7787 - * But if `?.` exsits, it doesn't hide no-undexpected-multiline errors - */ - if (!node.optional) { - return null; - } - - // Don't remove comments. - if (sourceCode.commentsExistBetween(leftToken, rightToken)) { - return null; - } - - const range = [leftToken.range[1], rightToken.range[0]]; - const qdToken = sourceCode.getTokenAfter(leftToken); - - if (qdToken.range[0] === leftToken.range[1]) { - return fixer.replaceTextRange(range, "?. "); - } - if (qdToken.range[1] === rightToken.range[0]) { - return fixer.replaceTextRange(range, " ?."); - } - return fixer.replaceTextRange(range, " ?. "); - } - }); - } - } - - return { - "CallExpression, NewExpression"(node) { - const lastToken = sourceCode.getLastToken(node); - const lastCalleeToken = sourceCode.getLastToken(node.callee); - const parenToken = sourceCode.getFirstTokenBetween(lastCalleeToken, lastToken, astUtils.isOpeningParenToken); - const prevToken = parenToken && sourceCode.getTokenBefore(parenToken, astUtils.isNotQuestionDotToken); - - // Parens in NewExpression are optional - if (!(parenToken && parenToken.range[1] < node.range[1])) { - return; - } - - checkSpacing(node, prevToken, parenToken); - }, - - ImportExpression(node) { - const leftToken = sourceCode.getFirstToken(node); - const rightToken = sourceCode.getTokenAfter(leftToken); - - checkSpacing(node, leftToken, rightToken); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-name-matching.js b/tools/node_modules/eslint/lib/rules/func-name-matching.js deleted file mode 100644 index 755c2ee5075c6b845b0cf550e09c33b35753b4aa..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/func-name-matching.js +++ /dev/null @@ -1,249 +0,0 @@ -/** - * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned. - * @author Annie Zhang, Pavel Strashkin - */ - -"use strict"; - -//-------------------------------------------------------------------------- -// Requirements -//-------------------------------------------------------------------------- - -const astUtils = require("./utils/ast-utils"); -const esutils = require("esutils"); - -//-------------------------------------------------------------------------- -// Helpers -//-------------------------------------------------------------------------- - -/** - * Determines if a pattern is `module.exports` or `module["exports"]` - * @param {ASTNode} pattern The left side of the AssignmentExpression - * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]` - */ -function isModuleExports(pattern) { - if (pattern.type === "MemberExpression" && pattern.object.type === "Identifier" && pattern.object.name === "module") { - - // module.exports - if (pattern.property.type === "Identifier" && pattern.property.name === "exports") { - return true; - } - - // module["exports"] - if (pattern.property.type === "Literal" && pattern.property.value === "exports") { - return true; - } - } - return false; -} - -/** - * Determines if a string name is a valid identifier - * @param {string} name The string to be checked - * @param {int} ecmaVersion The ECMAScript version if specified in the parserOptions config - * @returns {boolean} True if the string is a valid identifier - */ -function isIdentifier(name, ecmaVersion) { - if (ecmaVersion >= 6) { - return esutils.keyword.isIdentifierES6(name); - } - return esutils.keyword.isIdentifierES5(name); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const alwaysOrNever = { enum: ["always", "never"] }; -const optionsObject = { - type: "object", - properties: { - considerPropertyDescriptor: { - type: "boolean" - }, - includeCommonJSModuleExports: { - type: "boolean" - } - }, - additionalProperties: false -}; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require function names to match the name of the variable or property to which they are assigned", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-name-matching" - }, - - schema: { - anyOf: [{ - type: "array", - additionalItems: false, - items: [alwaysOrNever, optionsObject] - }, { - type: "array", - additionalItems: false, - items: [optionsObject] - }] - }, - - messages: { - matchProperty: "Function name `{{funcName}}` should match property name `{{name}}`.", - matchVariable: "Function name `{{funcName}}` should match variable name `{{name}}`.", - notMatchProperty: "Function name `{{funcName}}` should not match property name `{{name}}`.", - notMatchVariable: "Function name `{{funcName}}` should not match variable name `{{name}}`." - } - }, - - create(context) { - const options = (typeof context.options[0] === "object" ? context.options[0] : context.options[1]) || {}; - const nameMatches = typeof context.options[0] === "string" ? context.options[0] : "always"; - const considerPropertyDescriptor = options.considerPropertyDescriptor; - const includeModuleExports = options.includeCommonJSModuleExports; - const ecmaVersion = context.parserOptions && context.parserOptions.ecmaVersion ? context.parserOptions.ecmaVersion : 5; - - /** - * Check whether node is a certain CallExpression. - * @param {string} objName object name - * @param {string} funcName function name - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if node matches CallExpression - */ - function isPropertyCall(objName, funcName, node) { - if (!node) { - return false; - } - return node.type === "CallExpression" && astUtils.isSpecificMemberAccess(node.callee, objName, funcName); - } - - /** - * Compares identifiers based on the nameMatches option - * @param {string} x the first identifier - * @param {string} y the second identifier - * @returns {boolean} whether the two identifiers should warn. - */ - function shouldWarn(x, y) { - return (nameMatches === "always" && x !== y) || (nameMatches === "never" && x === y); - } - - /** - * Reports - * @param {ASTNode} node The node to report - * @param {string} name The variable or property name - * @param {string} funcName The function name - * @param {boolean} isProp True if the reported node is a property assignment - * @returns {void} - */ - function report(node, name, funcName, isProp) { - let messageId; - - if (nameMatches === "always" && isProp) { - messageId = "matchProperty"; - } else if (nameMatches === "always") { - messageId = "matchVariable"; - } else if (isProp) { - messageId = "notMatchProperty"; - } else { - messageId = "notMatchVariable"; - } - context.report({ - node, - messageId, - data: { - name, - funcName - } - }); - } - - /** - * Determines whether a given node is a string literal - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if the node is a string literal - */ - function isStringLiteral(node) { - return node.type === "Literal" && typeof node.value === "string"; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclarator(node) { - if (!node.init || node.init.type !== "FunctionExpression" || node.id.type !== "Identifier") { - return; - } - if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) { - report(node, node.id.name, node.init.id.name, false); - } - }, - - AssignmentExpression(node) { - if ( - node.right.type !== "FunctionExpression" || - (node.left.computed && node.left.property.type !== "Literal") || - (!includeModuleExports && isModuleExports(node.left)) || - (node.left.type !== "Identifier" && node.left.type !== "MemberExpression") - ) { - return; - } - - const isProp = node.left.type === "MemberExpression"; - const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name; - - if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) { - report(node, name, node.right.id.name, isProp); - } - }, - - Property(node) { - if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && !isStringLiteral(node.key)) { - return; - } - - if (node.key.type === "Identifier") { - const functionName = node.value.id.name; - let propertyName = node.key.name; - - if (considerPropertyDescriptor && propertyName === "value") { - if (isPropertyCall("Object", "defineProperty", node.parent.parent) || isPropertyCall("Reflect", "defineProperty", node.parent.parent)) { - const property = node.parent.parent.arguments[1]; - - if (isStringLiteral(property) && shouldWarn(property.value, functionName)) { - report(node, property.value, functionName, true); - } - } else if (isPropertyCall("Object", "defineProperties", node.parent.parent.parent.parent)) { - propertyName = node.parent.parent.key.name; - if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - } else if (isPropertyCall("Object", "create", node.parent.parent.parent.parent)) { - propertyName = node.parent.parent.key.name; - if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - } else if (shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - } else if (shouldWarn(propertyName, functionName)) { - report(node, propertyName, functionName, true); - } - return; - } - - if ( - isStringLiteral(node.key) && - isIdentifier(node.key.value, ecmaVersion) && - shouldWarn(node.key.value, node.value.id.name) - ) { - report(node, node.key.value, node.value.id.name, true); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-names.js b/tools/node_modules/eslint/lib/rules/func-names.js deleted file mode 100644 index ecfedb9e0e99c71d431d94759bf09288d003697c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/func-names.js +++ /dev/null @@ -1,190 +0,0 @@ -/** - * @fileoverview Rule to warn when a function expression does not have a name. - * @author Kyle T. Nunery - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -/** - * Checks whether or not a given variable is a function name. - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is a function name. - */ -function isFunctionName(variable) { - return variable && variable.defs[0].type === "FunctionName"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow named `function` expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-names" - }, - - schema: { - definitions: { - value: { - enum: [ - "always", - "as-needed", - "never" - ] - } - }, - items: [ - { - $ref: "#/definitions/value" - }, - { - type: "object", - properties: { - generators: { - $ref: "#/definitions/value" - } - }, - additionalProperties: false - } - ] - }, - - messages: { - unnamed: "Unexpected unnamed {{name}}.", - named: "Unexpected named {{name}}." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - /** - * Returns the config option for the given node. - * @param {ASTNode} node A node to get the config for. - * @returns {string} The config option. - */ - function getConfigForNode(node) { - if ( - node.generator && - context.options.length > 1 && - context.options[1].generators - ) { - return context.options[1].generators; - } - - return context.options[0] || "always"; - } - - /** - * Determines whether the current FunctionExpression node is a get, set, or - * shorthand method in an object literal or a class. - * @param {ASTNode} node A node to check. - * @returns {boolean} True if the node is a get, set, or shorthand method. - */ - function isObjectOrClassMethod(node) { - const parent = node.parent; - - return (parent.type === "MethodDefinition" || ( - parent.type === "Property" && ( - parent.method || - parent.kind === "get" || - parent.kind === "set" - ) - )); - } - - /** - * Determines whether the current FunctionExpression node has a name that would be - * inferred from context in a conforming ES6 environment. - * @param {ASTNode} node A node to check. - * @returns {boolean} True if the node would have a name assigned automatically. - */ - function hasInferredName(node) { - const parent = node.parent; - - return isObjectOrClassMethod(node) || - (parent.type === "VariableDeclarator" && parent.id.type === "Identifier" && parent.init === node) || - (parent.type === "Property" && parent.value === node) || - (parent.type === "AssignmentExpression" && parent.left.type === "Identifier" && parent.right === node) || - (parent.type === "AssignmentPattern" && parent.left.type === "Identifier" && parent.right === node); - } - - /** - * Reports that an unnamed function should be named - * @param {ASTNode} node The node to report in the event of an error. - * @returns {void} - */ - function reportUnexpectedUnnamedFunction(node) { - context.report({ - node, - messageId: "unnamed", - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - data: { name: astUtils.getFunctionNameWithKind(node) } - }); - } - - /** - * Reports that a named function should be unnamed - * @param {ASTNode} node The node to report in the event of an error. - * @returns {void} - */ - function reportUnexpectedNamedFunction(node) { - context.report({ - node, - messageId: "named", - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - data: { name: astUtils.getFunctionNameWithKind(node) } - }); - } - - /** - * The listener for function nodes. - * @param {ASTNode} node function node - * @returns {void} - */ - function handleFunction(node) { - - // Skip recursive functions. - const nameVar = context.getDeclaredVariables(node)[0]; - - if (isFunctionName(nameVar) && nameVar.references.length > 0) { - return; - } - - const hasName = Boolean(node.id && node.id.name); - const config = getConfigForNode(node); - - if (config === "never") { - if (hasName && node.type !== "FunctionDeclaration") { - reportUnexpectedNamedFunction(node); - } - } else if (config === "as-needed") { - if (!hasName && !hasInferredName(node)) { - reportUnexpectedUnnamedFunction(node); - } - } else { - if (!hasName && !isObjectOrClassMethod(node)) { - reportUnexpectedUnnamedFunction(node); - } - } - } - - return { - "FunctionExpression:exit": handleFunction, - "ExportDefaultDeclaration > FunctionDeclaration": handleFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/func-style.js b/tools/node_modules/eslint/lib/rules/func-style.js deleted file mode 100644 index e150b1a76f26a64079c629591445197283a0cb50..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/func-style.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @fileoverview Rule to enforce a particular function style - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the consistent use of either `function` declarations or expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/func-style" - }, - - schema: [ - { - enum: ["declaration", "expression"] - }, - { - type: "object", - properties: { - allowArrowFunctions: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - expression: "Expected a function expression.", - declaration: "Expected a function declaration." - } - }, - - create(context) { - - const style = context.options[0], - allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions, - enforceDeclarations = (style === "declaration"), - stack = []; - - const nodesToCheck = { - FunctionDeclaration(node) { - stack.push(false); - - if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") { - context.report({ node, messageId: "expression" }); - } - }, - "FunctionDeclaration:exit"() { - stack.pop(); - }, - - FunctionExpression(node) { - stack.push(false); - - if (enforceDeclarations && node.parent.type === "VariableDeclarator") { - context.report({ node: node.parent, messageId: "declaration" }); - } - }, - "FunctionExpression:exit"() { - stack.pop(); - }, - - ThisExpression() { - if (stack.length > 0) { - stack[stack.length - 1] = true; - } - } - }; - - if (!allowArrowFunctions) { - nodesToCheck.ArrowFunctionExpression = function() { - stack.push(false); - }; - - nodesToCheck["ArrowFunctionExpression:exit"] = function(node) { - const hasThisExpr = stack.pop(); - - if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") { - context.report({ node: node.parent, messageId: "declaration" }); - } - }; - } - - return nodesToCheck; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/function-call-argument-newline.js b/tools/node_modules/eslint/lib/rules/function-call-argument-newline.js deleted file mode 100644 index b6abbe95fa98c3d75f4fe2a36ab98b50bc5eb158..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/function-call-argument-newline.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule to enforce line breaks between arguments of a function call - * @author Alexey Gonchar - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce line breaks between arguments of a function call", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/function-call-argument-newline" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never", "consistent"] - } - ], - - messages: { - unexpectedLineBreak: "There should be no line break here.", - missingLineBreak: "There should be a line break after this argument." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const checkers = { - unexpected: { - messageId: "unexpectedLineBreak", - check: (prevToken, currentToken) => prevToken.loc.end.line !== currentToken.loc.start.line, - createFix: (token, tokenBefore) => fixer => - fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], " ") - }, - missing: { - messageId: "missingLineBreak", - check: (prevToken, currentToken) => prevToken.loc.end.line === currentToken.loc.start.line, - createFix: (token, tokenBefore) => fixer => - fixer.replaceTextRange([tokenBefore.range[1], token.range[0]], "\n") - } - }; - - /** - * Check all arguments for line breaks in the CallExpression - * @param {CallExpression} node node to evaluate - * @param {{ messageId: string, check: Function }} checker selected checker - * @returns {void} - * @private - */ - function checkArguments(node, checker) { - for (let i = 1; i < node.arguments.length; i++) { - const prevArgToken = sourceCode.getLastToken(node.arguments[i - 1]); - const currentArgToken = sourceCode.getFirstToken(node.arguments[i]); - - if (checker.check(prevArgToken, currentArgToken)) { - const tokenBefore = sourceCode.getTokenBefore( - currentArgToken, - { includeComments: true } - ); - - const hasLineCommentBefore = tokenBefore.type === "Line"; - - context.report({ - node, - loc: { - start: tokenBefore.loc.end, - end: currentArgToken.loc.start - }, - messageId: checker.messageId, - fix: hasLineCommentBefore ? null : checker.createFix(currentArgToken, tokenBefore) - }); - } - } - } - - /** - * Check if open space is present in a function name - * @param {CallExpression} node node to evaluate - * @returns {void} - * @private - */ - function check(node) { - if (node.arguments.length < 2) { - return; - } - - const option = context.options[0] || "always"; - - if (option === "never") { - checkArguments(node, checkers.unexpected); - } else if (option === "always") { - checkArguments(node, checkers.missing); - } else if (option === "consistent") { - const firstArgToken = sourceCode.getLastToken(node.arguments[0]); - const secondArgToken = sourceCode.getFirstToken(node.arguments[1]); - - if (firstArgToken.loc.end.line === secondArgToken.loc.start.line) { - checkArguments(node, checkers.unexpected); - } else { - checkArguments(node, checkers.missing); - } - } - } - - return { - CallExpression: check, - NewExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/function-paren-newline.js b/tools/node_modules/eslint/lib/rules/function-paren-newline.js deleted file mode 100644 index 894c8e331a716815c2e5d460205074cdc4c5658e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/function-paren-newline.js +++ /dev/null @@ -1,281 +0,0 @@ -/** - * @fileoverview enforce consistent line breaks inside function parentheses - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent line breaks inside function parentheses", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/function-paren-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consistent", "multiline", "multiline-arguments"] - }, - { - type: "object", - properties: { - minItems: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - expectedBefore: "Expected newline before ')'.", - expectedAfter: "Expected newline after '('.", - expectedBetween: "Expected newline between arguments/params.", - unexpectedBefore: "Unexpected newline before ')'.", - unexpectedAfter: "Unexpected newline after '('." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const rawOption = context.options[0] || "multiline"; - const multilineOption = rawOption === "multiline"; - const multilineArgumentsOption = rawOption === "multiline-arguments"; - const consistentOption = rawOption === "consistent"; - let minItems; - - if (typeof rawOption === "object") { - minItems = rawOption.minItems; - } else if (rawOption === "always") { - minItems = 0; - } else if (rawOption === "never") { - minItems = Infinity; - } else { - minItems = null; - } - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Determines whether there should be newlines inside function parens - * @param {ASTNode[]} elements The arguments or parameters in the list - * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code. - * @returns {boolean} `true` if there should be newlines inside the function parens - */ - function shouldHaveNewlines(elements, hasLeftNewline) { - if (multilineArgumentsOption && elements.length === 1) { - return hasLeftNewline; - } - if (multilineOption || multilineArgumentsOption) { - return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line); - } - if (consistentOption) { - return hasLeftNewline; - } - return elements.length >= minItems; - } - - /** - * Validates parens - * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token - * @param {ASTNode[]} elements The arguments or parameters in the list - * @returns {void} - */ - function validateParens(parens, elements) { - const leftParen = parens.leftParen; - const rightParen = parens.rightParen; - const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); - const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen); - const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); - const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen); - const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); - - if (hasLeftNewline && !needsNewlines) { - context.report({ - node: leftParen, - messageId: "unexpectedAfter", - fix(fixer) { - return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim() - - // If there is a comment between the ( and the first element, don't do a fix. - ? null - : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]); - } - }); - } else if (!hasLeftNewline && needsNewlines) { - context.report({ - node: leftParen, - messageId: "expectedAfter", - fix: fixer => fixer.insertTextAfter(leftParen, "\n") - }); - } - - if (hasRightNewline && !needsNewlines) { - context.report({ - node: rightParen, - messageId: "unexpectedBefore", - fix(fixer) { - return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim() - - // If there is a comment between the last element and the ), don't do a fix. - ? null - : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]); - } - }); - } else if (!hasRightNewline && needsNewlines) { - context.report({ - node: rightParen, - messageId: "expectedBefore", - fix: fixer => fixer.insertTextBefore(rightParen, "\n") - }); - } - } - - /** - * Validates a list of arguments or parameters - * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token - * @param {ASTNode[]} elements The arguments or parameters in the list - * @returns {void} - */ - function validateArguments(parens, elements) { - const leftParen = parens.leftParen; - const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen); - const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen); - const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline); - - for (let i = 0; i <= elements.length - 2; i++) { - const currentElement = elements[i]; - const nextElement = elements[i + 1]; - const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line; - - if (!hasNewLine && needsNewlines) { - context.report({ - node: currentElement, - messageId: "expectedBetween", - fix: fixer => fixer.insertTextBefore(nextElement, "\n") - }); - } - } - } - - /** - * Gets the left paren and right paren tokens of a node. - * @param {ASTNode} node The node with parens - * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token. - * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression - * with a single parameter) - */ - function getParenTokens(node) { - switch (node.type) { - case "NewExpression": - if (!node.arguments.length && !( - astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) && - astUtils.isClosingParenToken(sourceCode.getLastToken(node)) - )) { - - // If the NewExpression does not have parens (e.g. `new Foo`), return null. - return null; - } - - // falls through - - case "CallExpression": - return { - leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken), - rightParen: sourceCode.getLastToken(node) - }; - - case "FunctionDeclaration": - case "FunctionExpression": { - const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); - const rightParen = node.params.length - ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken) - : sourceCode.getTokenAfter(leftParen); - - return { leftParen, rightParen }; - } - - case "ArrowFunctionExpression": { - const firstToken = sourceCode.getFirstToken(node); - - if (!astUtils.isOpeningParenToken(firstToken)) { - - // If the ArrowFunctionExpression has a single param without parens, return null. - return null; - } - - return { - leftParen: firstToken, - rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken) - }; - } - - case "ImportExpression": { - const leftParen = sourceCode.getFirstToken(node, 1); - const rightParen = sourceCode.getLastToken(node); - - return { leftParen, rightParen }; - } - - default: - throw new TypeError(`unexpected node with type ${node.type}`); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - [[ - "ArrowFunctionExpression", - "CallExpression", - "FunctionDeclaration", - "FunctionExpression", - "ImportExpression", - "NewExpression" - ]](node) { - const parens = getParenTokens(node); - let params; - - if (node.type === "ImportExpression") { - params = [node.source]; - } else if (astUtils.isFunction(node)) { - params = node.params; - } else { - params = node.arguments; - } - - if (parens) { - validateParens(parens, params); - - if (multilineArgumentsOption) { - validateArguments(parens, params); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/generator-star-spacing.js b/tools/node_modules/eslint/lib/rules/generator-star-spacing.js deleted file mode 100644 index 65534f727fad0ef34260772197d49d4d3332cf88..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/generator-star-spacing.js +++ /dev/null @@ -1,206 +0,0 @@ -/** - * @fileoverview Rule to check the spacing around the * in generator functions. - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const OVERRIDE_SCHEMA = { - oneOf: [ - { - enum: ["before", "after", "both", "neither"] - }, - { - type: "object", - properties: { - before: { type: "boolean" }, - after: { type: "boolean" } - }, - additionalProperties: false - } - ] -}; - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing around `*` operators in generator functions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/generator-star-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["before", "after", "both", "neither"] - }, - { - type: "object", - properties: { - before: { type: "boolean" }, - after: { type: "boolean" }, - named: OVERRIDE_SCHEMA, - anonymous: OVERRIDE_SCHEMA, - method: OVERRIDE_SCHEMA - }, - additionalProperties: false - } - ] - } - ], - - messages: { - missingBefore: "Missing space before *.", - missingAfter: "Missing space after *.", - unexpectedBefore: "Unexpected space before *.", - unexpectedAfter: "Unexpected space after *." - } - }, - - create(context) { - - const optionDefinitions = { - before: { before: true, after: false }, - after: { before: false, after: true }, - both: { before: true, after: true }, - neither: { before: false, after: false } - }; - - /** - * Returns resolved option definitions based on an option and defaults - * @param {any} option The option object or string value - * @param {Object} defaults The defaults to use if options are not present - * @returns {Object} the resolved object definition - */ - function optionToDefinition(option, defaults) { - if (!option) { - return defaults; - } - - return typeof option === "string" - ? optionDefinitions[option] - : Object.assign({}, defaults, option); - } - - const modes = (function(option) { - const defaults = optionToDefinition(option, optionDefinitions.before); - - return { - named: optionToDefinition(option.named, defaults), - anonymous: optionToDefinition(option.anonymous, defaults), - method: optionToDefinition(option.method, defaults) - }; - }(context.options[0] || {})); - - const sourceCode = context.getSourceCode(); - - /** - * Checks if the given token is a star token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a star token. - */ - function isStarToken(token) { - return token.value === "*" && token.type === "Punctuator"; - } - - /** - * Gets the generator star token of the given function node. - * @param {ASTNode} node The function node to get. - * @returns {Token} Found star token. - */ - function getStarToken(node) { - return sourceCode.getFirstToken( - (node.parent.method || node.parent.type === "MethodDefinition") ? node.parent : node, - isStarToken - ); - } - - /** - * capitalize a given string. - * @param {string} str the given string. - * @returns {string} the capitalized string. - */ - function capitalize(str) { - return str[0].toUpperCase() + str.slice(1); - } - - /** - * Checks the spacing between two tokens before or after the star token. - * @param {string} kind Either "named", "anonymous", or "method" - * @param {string} side Either "before" or "after". - * @param {Token} leftToken `function` keyword token if side is "before", or - * star token if side is "after". - * @param {Token} rightToken Star token if side is "before", or identifier - * token if side is "after". - * @returns {void} - */ - function checkSpacing(kind, side, leftToken, rightToken) { - if (!!(rightToken.range[0] - leftToken.range[1]) !== modes[kind][side]) { - const after = leftToken.value === "*"; - const spaceRequired = modes[kind][side]; - const node = after ? leftToken : rightToken; - const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`; - - context.report({ - node, - messageId, - fix(fixer) { - if (spaceRequired) { - if (after) { - return fixer.insertTextAfter(node, " "); - } - return fixer.insertTextBefore(node, " "); - } - return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); - } - }); - } - } - - /** - * Enforces the spacing around the star if node is a generator function. - * @param {ASTNode} node A function expression or declaration node. - * @returns {void} - */ - function checkFunction(node) { - if (!node.generator) { - return; - } - - const starToken = getStarToken(node); - const prevToken = sourceCode.getTokenBefore(starToken); - const nextToken = sourceCode.getTokenAfter(starToken); - - let kind = "named"; - - if (node.parent.type === "MethodDefinition" || (node.parent.type === "Property" && node.parent.method)) { - kind = "method"; - } else if (!node.id) { - kind = "anonymous"; - } - - // Only check before when preceded by `function`|`static` keyword - if (!(kind === "method" && starToken === sourceCode.getFirstToken(node.parent))) { - checkSpacing(kind, "before", prevToken, starToken); - } - - checkSpacing(kind, "after", starToken, nextToken); - } - - return { - FunctionDeclaration: checkFunction, - FunctionExpression: checkFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/getter-return.js b/tools/node_modules/eslint/lib/rules/getter-return.js deleted file mode 100644 index c54ebfb4ffb8cd509ebf8e5f489a0cb6e940b4c5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/getter-return.js +++ /dev/null @@ -1,173 +0,0 @@ -/** - * @fileoverview Enforces that a return statement is present in property getters. - * @author Aladdin-ADD(hh_2013@foxmail.com) - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ -const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u; - -/** - * Checks a given code path segment is reachable. - * @param {CodePathSegment} segment A segment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce `return` statements in getters", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/getter-return" - }, - - fixable: null, - - schema: [ - { - type: "object", - properties: { - allowImplicit: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - expected: "Expected to return a value in {{name}}.", - expectedAlways: "Expected {{name}} to always return a value." - } - }, - - create(context) { - - const options = context.options[0] || { allowImplicit: false }; - const sourceCode = context.getSourceCode(); - - let funcInfo = { - upper: null, - codePath: null, - hasReturn: false, - shouldCheck: false, - node: null - }; - - /** - * Checks whether or not the last code path segment is reachable. - * Then reports this function if the segment is reachable. - * - * If the last code path segment is reachable, there are paths which are not - * returned or thrown. - * @param {ASTNode} node A node to check. - * @returns {void} - */ - function checkLastSegment(node) { - if (funcInfo.shouldCheck && - funcInfo.codePath.currentSegments.some(isReachable) - ) { - context.report({ - node, - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - messageId: funcInfo.hasReturn ? "expectedAlways" : "expected", - data: { - name: astUtils.getFunctionNameWithKind(funcInfo.node) - } - }); - } - } - - /** - * Checks whether a node means a getter function. - * @param {ASTNode} node a node to check. - * @returns {boolean} if node means a getter, return true; else return false. - */ - function isGetter(node) { - const parent = node.parent; - - if (TARGET_NODE_TYPE.test(node.type) && node.body.type === "BlockStatement") { - if (parent.kind === "get") { - return true; - } - if (parent.type === "Property" && astUtils.getStaticPropertyName(parent) === "get" && parent.parent.type === "ObjectExpression") { - - // Object.defineProperty() - if (parent.parent.parent.type === "CallExpression" && - astUtils.getStaticPropertyName(parent.parent.parent.callee) === "defineProperty") { - return true; - } - - // Object.defineProperties() - if (parent.parent.parent.type === "Property" && - parent.parent.parent.parent.type === "ObjectExpression" && - parent.parent.parent.parent.parent.type === "CallExpression" && - astUtils.getStaticPropertyName(parent.parent.parent.parent.parent.callee) === "defineProperties") { - return true; - } - } - } - return false; - } - return { - - // Stacks this function's information. - onCodePathStart(codePath, node) { - funcInfo = { - upper: funcInfo, - codePath, - hasReturn: false, - shouldCheck: isGetter(node), - node - }; - }, - - // Pops this function's information. - onCodePathEnd() { - funcInfo = funcInfo.upper; - }, - - // Checks the return statement is valid. - ReturnStatement(node) { - if (funcInfo.shouldCheck) { - funcInfo.hasReturn = true; - - // if allowImplicit: false, should also check node.argument - if (!options.allowImplicit && !node.argument) { - context.report({ - node, - messageId: "expected", - data: { - name: astUtils.getFunctionNameWithKind(funcInfo.node) - } - }); - } - } - }, - - // Reports a given function if the last path is reachable. - "FunctionExpression:exit": checkLastSegment, - "ArrowFunctionExpression:exit": checkLastSegment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/global-require.js b/tools/node_modules/eslint/lib/rules/global-require.js deleted file mode 100644 index 09d0332007e1745bd7b1f22fe2f9512ced2713b3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/global-require.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @fileoverview Rule for disallowing require() outside of the top-level module context - * @author Jamund Ferguson - */ - -"use strict"; - -const ACCEPTABLE_PARENTS = [ - "AssignmentExpression", - "VariableDeclarator", - "MemberExpression", - "ExpressionStatement", - "CallExpression", - "ConditionalExpression", - "Program", - "VariableDeclaration", - "ChainExpression" -]; - -/** - * Finds the eslint-scope reference in the given scope. - * @param {Object} scope The scope to search. - * @param {ASTNode} node The identifier node. - * @returns {Reference|null} Returns the found reference or null if none were found. - */ -function findReference(scope, node) { - const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && - reference.identifier.range[1] === node.range[1]); - - /* istanbul ignore else: correctly returns null */ - if (references.length === 1) { - return references[0]; - } - return null; - -} - -/** - * Checks if the given identifier node is shadowed in the given scope. - * @param {Object} scope The current scope. - * @param {ASTNode} node The identifier node to check. - * @returns {boolean} Whether or not the name is shadowed. - */ -function isShadowed(scope, node) { - const reference = findReference(scope, node); - - return reference && reference.resolved && reference.resolved.defs.length > 0; -} - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "require `require()` calls to be placed at top-level module scope", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/global-require" - }, - - schema: [], - messages: { - unexpected: "Unexpected require()." - } - }, - - create(context) { - return { - CallExpression(node) { - const currentScope = context.getScope(); - - if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) { - const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1); - - if (!isGoodRequire) { - context.report({ node, messageId: "unexpected" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/grouped-accessor-pairs.js b/tools/node_modules/eslint/lib/rules/grouped-accessor-pairs.js deleted file mode 100644 index a790f83750b2eb87a4e937e75cb9ebd10833ec25..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/grouped-accessor-pairs.js +++ /dev/null @@ -1,224 +0,0 @@ -/** - * @fileoverview Rule to require grouped accessor pairs in object literals and classes - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * Property name if it can be computed statically, otherwise the list of the tokens of the key node. - * @typedef {string|Token[]} Key - */ - -/** - * Accessor nodes with the same key. - * @typedef {Object} AccessorData - * @property {Key} key Accessor's key - * @property {ASTNode[]} getters List of getter nodes. - * @property {ASTNode[]} setters List of setter nodes. - */ - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not the given lists represent the equal tokens in the same order. - * Tokens are compared by their properties, not by instance. - * @param {Token[]} left First list of tokens. - * @param {Token[]} right Second list of tokens. - * @returns {boolean} `true` if the lists have same tokens. - */ -function areEqualTokenLists(left, right) { - if (left.length !== right.length) { - return false; - } - - for (let i = 0; i < left.length; i++) { - const leftToken = left[i], - rightToken = right[i]; - - if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) { - return false; - } - } - - return true; -} - -/** - * Checks whether or not the given keys are equal. - * @param {Key} left First key. - * @param {Key} right Second key. - * @returns {boolean} `true` if the keys are equal. - */ -function areEqualKeys(left, right) { - if (typeof left === "string" && typeof right === "string") { - - // Statically computed names. - return left === right; - } - if (Array.isArray(left) && Array.isArray(right)) { - - // Token lists. - return areEqualTokenLists(left, right); - } - - return false; -} - -/** - * Checks whether or not a given node is of an accessor kind ('get' or 'set'). - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is of an accessor kind. - */ -function isAccessorKind(node) { - return node.kind === "get" || node.kind === "set"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require grouped accessor pairs in object literals and classes", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/grouped-accessor-pairs" - }, - - schema: [ - { - enum: ["anyOrder", "getBeforeSet", "setBeforeGet"] - } - ], - - messages: { - notGrouped: "Accessor pair {{ formerName }} and {{ latterName }} should be grouped.", - invalidOrder: "Expected {{ latterName }} to be before {{ formerName }}." - } - }, - - create(context) { - const order = context.options[0] || "anyOrder"; - const sourceCode = context.getSourceCode(); - - /** - * Reports the given accessor pair. - * @param {string} messageId messageId to report. - * @param {ASTNode} formerNode getter/setter node that is defined before `latterNode`. - * @param {ASTNode} latterNode getter/setter node that is defined after `formerNode`. - * @returns {void} - * @private - */ - function report(messageId, formerNode, latterNode) { - context.report({ - node: latterNode, - messageId, - loc: astUtils.getFunctionHeadLoc(latterNode.value, sourceCode), - data: { - formerName: astUtils.getFunctionNameWithKind(formerNode.value), - latterName: astUtils.getFunctionNameWithKind(latterNode.value) - } - }); - } - - /** - * Creates a new `AccessorData` object for the given getter or setter node. - * @param {ASTNode} node A getter or setter node. - * @returns {AccessorData} New `AccessorData` object that contains the given node. - * @private - */ - function createAccessorData(node) { - const name = astUtils.getStaticPropertyName(node); - const key = (name !== null) ? name : sourceCode.getTokens(node.key); - - return { - key, - getters: node.kind === "get" ? [node] : [], - setters: node.kind === "set" ? [node] : [] - }; - } - - /** - * Merges the given `AccessorData` object into the given accessors list. - * @param {AccessorData[]} accessors The list to merge into. - * @param {AccessorData} accessorData The object to merge. - * @returns {AccessorData[]} The same instance with the merged object. - * @private - */ - function mergeAccessorData(accessors, accessorData) { - const equalKeyElement = accessors.find(a => areEqualKeys(a.key, accessorData.key)); - - if (equalKeyElement) { - equalKeyElement.getters.push(...accessorData.getters); - equalKeyElement.setters.push(...accessorData.setters); - } else { - accessors.push(accessorData); - } - - return accessors; - } - - /** - * Checks accessor pairs in the given list of nodes. - * @param {ASTNode[]} nodes The list to check. - * @param {Function} shouldCheck – Predicate that returns `true` if the node should be checked. - * @returns {void} - * @private - */ - function checkList(nodes, shouldCheck) { - const accessors = nodes - .filter(shouldCheck) - .filter(isAccessorKind) - .map(createAccessorData) - .reduce(mergeAccessorData, []); - - for (const { getters, setters } of accessors) { - - // Don't report accessor properties that have duplicate getters or setters. - if (getters.length === 1 && setters.length === 1) { - const [getter] = getters, - [setter] = setters, - getterIndex = nodes.indexOf(getter), - setterIndex = nodes.indexOf(setter), - formerNode = getterIndex < setterIndex ? getter : setter, - latterNode = getterIndex < setterIndex ? setter : getter; - - if (Math.abs(getterIndex - setterIndex) > 1) { - report("notGrouped", formerNode, latterNode); - } else if ( - (order === "getBeforeSet" && getterIndex > setterIndex) || - (order === "setBeforeGet" && getterIndex < setterIndex) - ) { - report("invalidOrder", formerNode, latterNode); - } - } - } - } - - return { - ObjectExpression(node) { - checkList(node.properties, n => n.type === "Property"); - }, - ClassBody(node) { - checkList(node.body, n => n.type === "MethodDefinition" && !n.static); - checkList(node.body, n => n.type === "MethodDefinition" && n.static); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/guard-for-in.js b/tools/node_modules/eslint/lib/rules/guard-for-in.js deleted file mode 100644 index 2c0976d997b60117dc01fc41c60ecddd080be4e9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/guard-for-in.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Rule to flag for-in loops without if statements inside - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `for-in` loops to include an `if` statement", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/guard-for-in" - }, - - schema: [], - messages: { - wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." - } - }, - - create(context) { - - return { - - ForInStatement(node) { - const body = node.body; - - // empty statement - if (body.type === "EmptyStatement") { - return; - } - - // if statement - if (body.type === "IfStatement") { - return; - } - - // empty block - if (body.type === "BlockStatement" && body.body.length === 0) { - return; - } - - // block with just if statement - if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") { - return; - } - - // block that starts with if statement - if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") { - const i = body.body[0]; - - // ... whose consequent is a continue - if (i.consequent.type === "ContinueStatement") { - return; - } - - // ... whose consequent is a block that contains only a continue - if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") { - return; - } - } - - context.report({ node, messageId: "wrap" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/handle-callback-err.js b/tools/node_modules/eslint/lib/rules/handle-callback-err.js deleted file mode 100644 index b92490ad16bdafda8592f0ce7282d640773dad7e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/handle-callback-err.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @fileoverview Ensure handling of errors when we know they exist. - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "require error handling in callbacks", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/handle-callback-err" - }, - - schema: [ - { - type: "string" - } - ], - messages: { - expected: "Expected error to be handled." - } - }, - - create(context) { - - const errorArgument = context.options[0] || "err"; - - /** - * Checks if the given argument should be interpreted as a regexp pattern. - * @param {string} stringToCheck The string which should be checked. - * @returns {boolean} Whether or not the string should be interpreted as a pattern. - */ - function isPattern(stringToCheck) { - const firstChar = stringToCheck[0]; - - return firstChar === "^"; - } - - /** - * Checks if the given name matches the configured error argument. - * @param {string} name The name which should be compared. - * @returns {boolean} Whether or not the given name matches the configured error variable name. - */ - function matchesConfiguredErrorName(name) { - if (isPattern(errorArgument)) { - const regexp = new RegExp(errorArgument, "u"); - - return regexp.test(name); - } - return name === errorArgument; - } - - /** - * Get the parameters of a given function scope. - * @param {Object} scope The function scope. - * @returns {Array} All parameters of the given scope. - */ - function getParameters(scope) { - return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter"); - } - - /** - * Check to see if we're handling the error object properly. - * @param {ASTNode} node The AST node to check. - * @returns {void} - */ - function checkForError(node) { - const scope = context.getScope(), - parameters = getParameters(scope), - firstParameter = parameters[0]; - - if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) { - if (firstParameter.references.length === 0) { - context.report({ node, messageId: "expected" }); - } - } - } - - return { - FunctionDeclaration: checkForError, - FunctionExpression: checkForError, - ArrowFunctionExpression: checkForError - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/id-blacklist.js b/tools/node_modules/eslint/lib/rules/id-blacklist.js deleted file mode 100644 index 4fbba909fde453c5d792aad25985b4b05ef48e95..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/id-blacklist.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * @fileoverview Rule that warns when identifier names that are - * specified in the configuration are used. - * @author Keith Cirkel (http://keithcirkel.co.uk) - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether the given node represents assignment target in a normal assignment or destructuring. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is assignment target. - */ -function isAssignmentTarget(node) { - const parent = node.parent; - - return ( - - // normal assignment - ( - parent.type === "AssignmentExpression" && - parent.left === node - ) || - - // destructuring - parent.type === "ArrayPattern" || - parent.type === "RestElement" || - ( - parent.type === "Property" && - parent.value === node && - parent.parent.type === "ObjectPattern" - ) || - ( - parent.type === "AssignmentPattern" && - parent.left === node - ) - ); -} - -/** - * Checks whether the given node represents an imported name that is renamed in the same import/export specifier. - * - * Examples: - * import { a as b } from 'mod'; // node `a` is renamed import - * export { a as b } from 'mod'; // node `a` is renamed import - * @param {ASTNode} node `Identifier` node to check. - * @returns {boolean} `true` if the node is a renamed import. - */ -function isRenamedImport(node) { - const parent = node.parent; - - return ( - ( - parent.type === "ImportSpecifier" && - parent.imported !== parent.local && - parent.imported === node - ) || - ( - parent.type === "ExportSpecifier" && - parent.parent.source && // re-export - parent.local !== parent.exported && - parent.local === node - ) - ); -} - -/** - * Checks whether the given node is a renamed identifier node in an ObjectPattern destructuring. - * - * Examples: - * const { a : b } = foo; // node `a` is renamed node. - * @param {ASTNode} node `Identifier` node to check. - * @returns {boolean} `true` if the node is a renamed node in an ObjectPattern destructuring. - */ -function isRenamedInDestructuring(node) { - const parent = node.parent; - - return ( - ( - !parent.computed && - parent.type === "Property" && - parent.parent.type === "ObjectPattern" && - parent.value !== node && - parent.key === node - ) - ); -} - -/** - * Checks whether the given node represents shorthand definition of a property in an object literal. - * @param {ASTNode} node `Identifier` node to check. - * @returns {boolean} `true` if the node is a shorthand property definition. - */ -function isShorthandPropertyDefinition(node) { - const parent = node.parent; - - return ( - parent.type === "Property" && - parent.parent.type === "ObjectExpression" && - parent.shorthand - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - replacedBy: ["id-denylist"], - - type: "suggestion", - - docs: { - description: "disallow specified identifiers", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/id-blacklist" - }, - - schema: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - }, - messages: { - restricted: "Identifier '{{name}}' is restricted." - } - }, - - create(context) { - - const denyList = new Set(context.options); - const reportedNodes = new Set(); - - let globalScope; - - /** - * Checks whether the given name is restricted. - * @param {string} name The name to check. - * @returns {boolean} `true` if the name is restricted. - * @private - */ - function isRestricted(name) { - return denyList.has(name); - } - - /** - * Checks whether the given node represents a reference to a global variable that is not declared in the source code. - * These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables. - * @param {ASTNode} node `Identifier` node to check. - * @returns {boolean} `true` if the node is a reference to a global variable. - */ - function isReferenceToGlobalVariable(node) { - const variable = globalScope.set.get(node.name); - - return variable && variable.defs.length === 0 && - variable.references.some(ref => ref.identifier === node); - } - - /** - * Determines whether the given node should be checked. - * @param {ASTNode} node `Identifier` node. - * @returns {boolean} `true` if the node should be checked. - */ - function shouldCheck(node) { - const parent = node.parent; - - /* - * Member access has special rules for checking property names. - * Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over. - * Write access isn't allowed, because it potentially creates a new property with a restricted name. - */ - if ( - parent.type === "MemberExpression" && - parent.property === node && - !parent.computed - ) { - return isAssignmentTarget(parent); - } - - return ( - parent.type !== "CallExpression" && - parent.type !== "NewExpression" && - !isRenamedImport(node) && - !isRenamedInDestructuring(node) && - !( - isReferenceToGlobalVariable(node) && - !isShorthandPropertyDefinition(node) - ) - ); - } - - /** - * Reports an AST node as a rule violation. - * @param {ASTNode} node The node to report. - * @returns {void} - * @private - */ - function report(node) { - if (!reportedNodes.has(node)) { - context.report({ - node, - messageId: "restricted", - data: { - name: node.name - } - }); - reportedNodes.add(node); - } - } - - return { - - Program() { - globalScope = context.getScope(); - }, - - Identifier(node) { - if (isRestricted(node.name) && shouldCheck(node)) { - report(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/id-length.js b/tools/node_modules/eslint/lib/rules/id-length.js deleted file mode 100644 index 4df081ff9fe4f85011848c324784ce8090246d67..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/id-length.js +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @fileoverview Rule that warns when identifier names are shorter or longer - * than the values provided in configuration. - * @author Burak Yigit Kaya aka BYK - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce minimum and maximum identifier lengths", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/id-length" - }, - - schema: [ - { - type: "object", - properties: { - min: { - type: "integer", - default: 2 - }, - max: { - type: "integer" - }, - exceptions: { - type: "array", - uniqueItems: true, - items: { - type: "string" - } - }, - exceptionPatterns: { - type: "array", - uniqueItems: true, - items: { - type: "string" - } - }, - properties: { - enum: ["always", "never"] - } - }, - additionalProperties: false - } - ], - messages: { - tooShort: "Identifier name '{{name}}' is too short (< {{min}}).", - tooLong: "Identifier name '{{name}}' is too long (> {{max}})." - } - }, - - create(context) { - const options = context.options[0] || {}; - const minLength = typeof options.min !== "undefined" ? options.min : 2; - const maxLength = typeof options.max !== "undefined" ? options.max : Infinity; - const properties = options.properties !== "never"; - const exceptions = new Set(options.exceptions); - const exceptionPatterns = (options.exceptionPatterns || []).map(pattern => new RegExp(pattern, "u")); - const reportedNode = new Set(); - - /** - * Checks if a string matches the provided exception patterns - * @param {string} name The string to check. - * @returns {boolean} if the string is a match - * @private - */ - function matchesExceptionPattern(name) { - return exceptionPatterns.some(pattern => pattern.test(name)); - } - - const SUPPORTED_EXPRESSIONS = { - MemberExpression: properties && function(parent) { - return !parent.computed && ( - - // regular property assignment - (parent.parent.left === parent && parent.parent.type === "AssignmentExpression" || - - // or the last identifier in an ObjectPattern destructuring - parent.parent.type === "Property" && parent.parent.value === parent && - parent.parent.parent.type === "ObjectPattern" && parent.parent.parent.parent.left === parent.parent.parent) - ); - }, - AssignmentPattern(parent, node) { - return parent.left === node; - }, - VariableDeclarator(parent, node) { - return parent.id === node; - }, - Property(parent, node) { - - if (parent.parent.type === "ObjectPattern") { - return ( - parent.value !== parent.key && parent.value === node || - parent.value === parent.key && parent.key === node && properties - ); - } - return properties && !parent.computed && parent.key === node; - }, - ImportDefaultSpecifier: true, - RestElement: true, - FunctionExpression: true, - ArrowFunctionExpression: true, - ClassDeclaration: true, - FunctionDeclaration: true, - MethodDefinition: true, - CatchClause: true, - ArrayPattern: true - }; - - return { - Identifier(node) { - const name = node.name; - const parent = node.parent; - - const isShort = name.length < minLength; - const isLong = name.length > maxLength; - - if (!(isShort || isLong) || exceptions.has(name) || matchesExceptionPattern(name)) { - return; // Nothing to report - } - - const isValidExpression = SUPPORTED_EXPRESSIONS[parent.type]; - - if (isValidExpression && !reportedNode.has(node) && (isValidExpression === true || isValidExpression(parent, node))) { - reportedNode.add(node); - context.report({ - node, - messageId: isShort ? "tooShort" : "tooLong", - data: { name, min: minLength, max: maxLength } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/id-match.js b/tools/node_modules/eslint/lib/rules/id-match.js deleted file mode 100644 index b97a497fd4f8848d4e791bdf717d4a51b4dd4079..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/id-match.js +++ /dev/null @@ -1,225 +0,0 @@ -/** - * @fileoverview Rule to flag non-matching identifiers - * @author Matthieu Larcher - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require identifiers to match a specified regular expression", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/id-match" - }, - - schema: [ - { - type: "string" - }, - { - type: "object", - properties: { - properties: { - type: "boolean", - default: false - }, - onlyDeclarations: { - type: "boolean", - default: false - }, - ignoreDestructuring: { - type: "boolean", - default: false - } - } - } - ], - messages: { - notMatch: "Identifier '{{name}}' does not match the pattern '{{pattern}}'." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Options - //-------------------------------------------------------------------------- - const pattern = context.options[0] || "^.+$", - regexp = new RegExp(pattern, "u"); - - const options = context.options[1] || {}, - properties = !!options.properties, - onlyDeclarations = !!options.onlyDeclarations, - ignoreDestructuring = !!options.ignoreDestructuring; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // contains reported nodes to avoid reporting twice on destructuring with shorthand notation - const reported = new Map(); - const ALLOWED_PARENT_TYPES = new Set(["CallExpression", "NewExpression"]); - const DECLARATION_TYPES = new Set(["FunctionDeclaration", "VariableDeclarator"]); - const IMPORT_TYPES = new Set(["ImportSpecifier", "ImportNamespaceSpecifier", "ImportDefaultSpecifier"]); - - /** - * Checks if a string matches the provided pattern - * @param {string} name The string to check. - * @returns {boolean} if the string is a match - * @private - */ - function isInvalid(name) { - return !regexp.test(name); - } - - /** - * Checks if a parent of a node is an ObjectPattern. - * @param {ASTNode} node The node to check. - * @returns {boolean} if the node is inside an ObjectPattern - * @private - */ - function isInsideObjectPattern(node) { - let { parent } = node; - - while (parent) { - if (parent.type === "ObjectPattern") { - return true; - } - - parent = parent.parent; - } - - return false; - } - - /** - * Verifies if we should report an error or not based on the effective - * parent node and the identifier name. - * @param {ASTNode} effectiveParent The effective parent node of the node to be reported - * @param {string} name The identifier name of the identifier node - * @returns {boolean} whether an error should be reported or not - */ - function shouldReport(effectiveParent, name) { - return (!onlyDeclarations || DECLARATION_TYPES.has(effectiveParent.type)) && - !ALLOWED_PARENT_TYPES.has(effectiveParent.type) && isInvalid(name); - } - - /** - * Reports an AST node as a rule violation. - * @param {ASTNode} node The node to report. - * @returns {void} - * @private - */ - function report(node) { - if (!reported.has(node)) { - context.report({ - node, - messageId: "notMatch", - data: { - name: node.name, - pattern - } - }); - reported.set(node, true); - } - } - - return { - - Identifier(node) { - const name = node.name, - parent = node.parent, - effectiveParent = (parent.type === "MemberExpression") ? parent.parent : parent; - - if (parent.type === "MemberExpression") { - - if (!properties) { - return; - } - - // Always check object names - if (parent.object.type === "Identifier" && - parent.object.name === name) { - if (isInvalid(name)) { - report(node); - } - - // Report AssignmentExpressions left side's assigned variable id - } else if (effectiveParent.type === "AssignmentExpression" && - effectiveParent.left.type === "MemberExpression" && - effectiveParent.left.property.name === node.name) { - if (isInvalid(name)) { - report(node); - } - - // Report AssignmentExpressions only if they are the left side of the assignment - } else if (effectiveParent.type === "AssignmentExpression" && effectiveParent.right.type !== "MemberExpression") { - if (isInvalid(name)) { - report(node); - } - } - - /* - * Properties have their own rules, and - * AssignmentPattern nodes can be treated like Properties: - * e.g.: const { no_camelcased = false } = bar; - */ - } else if (parent.type === "Property" || parent.type === "AssignmentPattern") { - - if (parent.parent && parent.parent.type === "ObjectPattern") { - if (parent.shorthand && parent.value.left && isInvalid(name)) { - - report(node); - } - - const assignmentKeyEqualsValue = parent.key.name === parent.value.name; - - // prevent checking righthand side of destructured object - if (!assignmentKeyEqualsValue && parent.key === node) { - return; - } - - const valueIsInvalid = parent.value.name && isInvalid(name); - - // ignore destructuring if the option is set, unless a new identifier is created - if (valueIsInvalid && !(assignmentKeyEqualsValue && ignoreDestructuring)) { - report(node); - } - } - - // never check properties or always ignore destructuring - if (!properties || (ignoreDestructuring && isInsideObjectPattern(node))) { - return; - } - - // don't check right hand side of AssignmentExpression to prevent duplicate warnings - if (parent.right !== node && shouldReport(effectiveParent, name)) { - report(node); - } - - // Check if it's an import specifier - } else if (IMPORT_TYPES.has(parent.type)) { - - // Report only if the local imported identifier is invalid - if (parent.local && parent.local.name === node.name && isInvalid(name)) { - report(node); - } - - // Report anything that is invalid that isn't a CallExpression - } else if (shouldReport(effectiveParent, name)) { - report(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js b/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js deleted file mode 100644 index 409145e7dc1329c4f4e6bd1ee86c335fce54c412..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @fileoverview enforce the location of arrow function bodies - * @author Sharmila Jesupaul - */ -"use strict"; - -const { isCommentToken, isNotOpeningParenToken } = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the location of arrow function bodies", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/implicit-arrow-linebreak" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["beside", "below"] - } - ], - messages: { - expected: "Expected a linebreak before this expression.", - unexpected: "Expected no linebreak before this expression." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0] || "beside"; - - /** - * Validates the location of an arrow function body - * @param {ASTNode} node The arrow function body - * @returns {void} - */ - function validateExpression(node) { - if (node.body.type === "BlockStatement") { - return; - } - - const arrowToken = sourceCode.getTokenBefore(node.body, isNotOpeningParenToken); - const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); - - if (arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && option === "below") { - context.report({ - node: firstTokenOfBody, - messageId: "expected", - fix: fixer => fixer.insertTextBefore(firstTokenOfBody, "\n") - }); - } else if (arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && option === "beside") { - context.report({ - node: firstTokenOfBody, - messageId: "unexpected", - fix(fixer) { - if (sourceCode.getFirstTokenBetween(arrowToken, firstTokenOfBody, { includeComments: true, filter: isCommentToken })) { - return null; - } - - return fixer.replaceTextRange([arrowToken.range[1], firstTokenOfBody.range[0]], " "); - } - }); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - return { - ArrowFunctionExpression: node => validateExpression(node) - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/indent-legacy.js b/tools/node_modules/eslint/lib/rules/indent-legacy.js deleted file mode 100644 index 50010d3f7acb16dfc182501d3756813d937c5d1c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/indent-legacy.js +++ /dev/null @@ -1,1125 +0,0 @@ -/** - * @fileoverview This option sets a specific tab width for your code - * - * This rule has been ported and modified from nodeca. - * @author Vitaly Puzrin - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/* istanbul ignore next: this rule has known coverage issues, but it's deprecated and shouldn't be updated in the future anyway. */ -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent indentation", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/indent-legacy" - }, - - deprecated: true, - - replacedBy: ["indent"], - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["tab"] - }, - { - type: "integer", - minimum: 0 - } - ] - }, - { - type: "object", - properties: { - SwitchCase: { - type: "integer", - minimum: 0 - }, - VariableDeclarator: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - var: { - type: "integer", - minimum: 0 - }, - let: { - type: "integer", - minimum: 0 - }, - const: { - type: "integer", - minimum: 0 - } - } - } - ] - }, - outerIIFEBody: { - type: "integer", - minimum: 0 - }, - MemberExpression: { - type: "integer", - minimum: 0 - }, - FunctionDeclaration: { - type: "object", - properties: { - parameters: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - }, - body: { - type: "integer", - minimum: 0 - } - } - }, - FunctionExpression: { - type: "object", - properties: { - parameters: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - }, - body: { - type: "integer", - minimum: 0 - } - } - }, - CallExpression: { - type: "object", - properties: { - parameters: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - } - } - }, - ArrayExpression: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - }, - ObjectExpression: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first"] - } - ] - } - }, - additionalProperties: false - } - ], - messages: { - expected: "Expected indentation of {{expected}} but found {{actual}}." - } - }, - - create(context) { - const DEFAULT_VARIABLE_INDENT = 1; - const DEFAULT_PARAMETER_INDENT = null; // For backwards compatibility, don't check parameter indentation unless specified in the config - const DEFAULT_FUNCTION_BODY_INDENT = 1; - - let indentType = "space"; - let indentSize = 4; - const options = { - SwitchCase: 0, - VariableDeclarator: { - var: DEFAULT_VARIABLE_INDENT, - let: DEFAULT_VARIABLE_INDENT, - const: DEFAULT_VARIABLE_INDENT - }, - outerIIFEBody: null, - FunctionDeclaration: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - FunctionExpression: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - CallExpression: { - arguments: DEFAULT_PARAMETER_INDENT - }, - ArrayExpression: 1, - ObjectExpression: 1 - }; - - const sourceCode = context.getSourceCode(); - - if (context.options.length) { - if (context.options[0] === "tab") { - indentSize = 1; - indentType = "tab"; - } else /* istanbul ignore else : this will be caught by options validation */ if (typeof context.options[0] === "number") { - indentSize = context.options[0]; - indentType = "space"; - } - - if (context.options[1]) { - const opts = context.options[1]; - - options.SwitchCase = opts.SwitchCase || 0; - const variableDeclaratorRules = opts.VariableDeclarator; - - if (typeof variableDeclaratorRules === "number") { - options.VariableDeclarator = { - var: variableDeclaratorRules, - let: variableDeclaratorRules, - const: variableDeclaratorRules - }; - } else if (typeof variableDeclaratorRules === "object") { - Object.assign(options.VariableDeclarator, variableDeclaratorRules); - } - - if (typeof opts.outerIIFEBody === "number") { - options.outerIIFEBody = opts.outerIIFEBody; - } - - if (typeof opts.MemberExpression === "number") { - options.MemberExpression = opts.MemberExpression; - } - - if (typeof opts.FunctionDeclaration === "object") { - Object.assign(options.FunctionDeclaration, opts.FunctionDeclaration); - } - - if (typeof opts.FunctionExpression === "object") { - Object.assign(options.FunctionExpression, opts.FunctionExpression); - } - - if (typeof opts.CallExpression === "object") { - Object.assign(options.CallExpression, opts.CallExpression); - } - - if (typeof opts.ArrayExpression === "number" || typeof opts.ArrayExpression === "string") { - options.ArrayExpression = opts.ArrayExpression; - } - - if (typeof opts.ObjectExpression === "number" || typeof opts.ObjectExpression === "string") { - options.ObjectExpression = opts.ObjectExpression; - } - } - } - - const caseIndentStore = {}; - - /** - * Creates an error message for a line, given the expected/actual indentation. - * @param {int} expectedAmount The expected amount of indentation characters for this line - * @param {int} actualSpaces The actual number of indentation spaces that were found on this line - * @param {int} actualTabs The actual number of indentation tabs that were found on this line - * @returns {string} An error message for this line - */ - function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) { - const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" - const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" - const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" - let foundStatement; - - if (actualSpaces > 0 && actualTabs > 0) { - foundStatement = `${actualSpaces} ${foundSpacesWord} and ${actualTabs} ${foundTabsWord}`; // e.g. "1 space and 2 tabs" - } else if (actualSpaces > 0) { - - /* - * Abbreviate the message if the expected indentation is also spaces. - * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' - */ - foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; - } else if (actualTabs > 0) { - foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; - } else { - foundStatement = "0"; - } - return { - expected: expectedStatement, - actual: foundStatement - }; - } - - /** - * Reports a given indent violation - * @param {ASTNode} node Node violating the indent rule - * @param {int} needed Expected indentation character count - * @param {int} gottenSpaces Indentation space count in the actual node/code - * @param {int} gottenTabs Indentation tab count in the actual node/code - * @param {Object} [loc] Error line and column location - * @param {boolean} isLastNodeCheck Is the error for last node check - * @returns {void} - */ - function report(node, needed, gottenSpaces, gottenTabs, loc, isLastNodeCheck) { - if (gottenSpaces && gottenTabs) { - - // To avoid conflicts with `no-mixed-spaces-and-tabs`, don't report lines that have both spaces and tabs. - return; - } - - const desiredIndent = (indentType === "space" ? " " : "\t").repeat(needed); - - const textRange = isLastNodeCheck - ? [node.range[1] - node.loc.end.column, node.range[1] - node.loc.end.column + gottenSpaces + gottenTabs] - : [node.range[0] - node.loc.start.column, node.range[0] - node.loc.start.column + gottenSpaces + gottenTabs]; - - context.report({ - node, - loc, - messageId: "expected", - data: createErrorMessageData(needed, gottenSpaces, gottenTabs), - fix: fixer => fixer.replaceTextRange(textRange, desiredIndent) - }); - } - - /** - * Get the actual indent of node - * @param {ASTNode|Token} node Node to examine - * @param {boolean} [byLastLine=false] get indent of node's last line - * @returns {Object} The node's indent. Contains keys `space` and `tab`, representing the indent of each character. Also - * contains keys `goodChar` and `badChar`, where `goodChar` is the amount of the user's desired indentation character, and - * `badChar` is the amount of the other indentation character. - */ - function getNodeIndent(node, byLastLine) { - const token = byLastLine ? sourceCode.getLastToken(node) : sourceCode.getFirstToken(node); - const srcCharsBeforeNode = sourceCode.getText(token, token.loc.start.column).split(""); - const indentChars = srcCharsBeforeNode.slice(0, srcCharsBeforeNode.findIndex(char => char !== " " && char !== "\t")); - const spaces = indentChars.filter(char => char === " ").length; - const tabs = indentChars.filter(char => char === "\t").length; - - return { - space: spaces, - tab: tabs, - goodChar: indentType === "space" ? spaces : tabs, - badChar: indentType === "space" ? tabs : spaces - }; - } - - /** - * Checks node is the first in its own start line. By default it looks by start line. - * @param {ASTNode} node The node to check - * @param {boolean} [byEndLocation=false] Lookup based on start position or end - * @returns {boolean} true if its the first in the its start line - */ - function isNodeFirstInLine(node, byEndLocation) { - const firstToken = byEndLocation === true ? sourceCode.getLastToken(node, 1) : sourceCode.getTokenBefore(node), - startLine = byEndLocation === true ? node.loc.end.line : node.loc.start.line, - endLine = firstToken ? firstToken.loc.end.line : -1; - - return startLine !== endLine; - } - - /** - * Check indent for node - * @param {ASTNode} node Node to check - * @param {int} neededIndent needed indent - * @returns {void} - */ - function checkNodeIndent(node, neededIndent) { - const actualIndent = getNodeIndent(node, false); - - if ( - node.type !== "ArrayExpression" && - node.type !== "ObjectExpression" && - (actualIndent.goodChar !== neededIndent || actualIndent.badChar !== 0) && - isNodeFirstInLine(node) - ) { - report(node, neededIndent, actualIndent.space, actualIndent.tab); - } - - if (node.type === "IfStatement" && node.alternate) { - const elseToken = sourceCode.getTokenBefore(node.alternate); - - checkNodeIndent(elseToken, neededIndent); - - if (!isNodeFirstInLine(node.alternate)) { - checkNodeIndent(node.alternate, neededIndent); - } - } - - if (node.type === "TryStatement" && node.handler) { - const catchToken = sourceCode.getFirstToken(node.handler); - - checkNodeIndent(catchToken, neededIndent); - } - - if (node.type === "TryStatement" && node.finalizer) { - const finallyToken = sourceCode.getTokenBefore(node.finalizer); - - checkNodeIndent(finallyToken, neededIndent); - } - - if (node.type === "DoWhileStatement") { - const whileToken = sourceCode.getTokenAfter(node.body); - - checkNodeIndent(whileToken, neededIndent); - } - } - - /** - * Check indent for nodes list - * @param {ASTNode[]} nodes list of node objects - * @param {int} indent needed indent - * @returns {void} - */ - function checkNodesIndent(nodes, indent) { - nodes.forEach(node => checkNodeIndent(node, indent)); - } - - /** - * Check last node line indent this detects, that block closed correctly - * @param {ASTNode} node Node to examine - * @param {int} lastLineIndent needed indent - * @returns {void} - */ - function checkLastNodeLineIndent(node, lastLineIndent) { - const lastToken = sourceCode.getLastToken(node); - const endIndent = getNodeIndent(lastToken, true); - - if ((endIndent.goodChar !== lastLineIndent || endIndent.badChar !== 0) && isNodeFirstInLine(node, true)) { - report( - node, - lastLineIndent, - endIndent.space, - endIndent.tab, - { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, - true - ); - } - } - - /** - * Check last node line indent this detects, that block closed correctly - * This function for more complicated return statement case, where closing parenthesis may be followed by ';' - * @param {ASTNode} node Node to examine - * @param {int} firstLineIndent first line needed indent - * @returns {void} - */ - function checkLastReturnStatementLineIndent(node, firstLineIndent) { - - /* - * in case if return statement ends with ');' we have traverse back to ')' - * otherwise we'll measure indent for ';' and replace ')' - */ - const lastToken = sourceCode.getLastToken(node, astUtils.isClosingParenToken); - const textBeforeClosingParenthesis = sourceCode.getText(lastToken, lastToken.loc.start.column).slice(0, -1); - - if (textBeforeClosingParenthesis.trim()) { - - // There are tokens before the closing paren, don't report this case - return; - } - - const endIndent = getNodeIndent(lastToken, true); - - if (endIndent.goodChar !== firstLineIndent) { - report( - node, - firstLineIndent, - endIndent.space, - endIndent.tab, - { line: lastToken.loc.start.line, column: lastToken.loc.start.column }, - true - ); - } - } - - /** - * Check first node line indent is correct - * @param {ASTNode} node Node to examine - * @param {int} firstLineIndent needed indent - * @returns {void} - */ - function checkFirstNodeLineIndent(node, firstLineIndent) { - const startIndent = getNodeIndent(node, false); - - if ((startIndent.goodChar !== firstLineIndent || startIndent.badChar !== 0) && isNodeFirstInLine(node)) { - report( - node, - firstLineIndent, - startIndent.space, - startIndent.tab, - { line: node.loc.start.line, column: node.loc.start.column } - ); - } - } - - /** - * Returns a parent node of given node based on a specified type - * if not present then return null - * @param {ASTNode} node node to examine - * @param {string} type type that is being looked for - * @param {string} stopAtList end points for the evaluating code - * @returns {ASTNode|void} if found then node otherwise null - */ - function getParentNodeByType(node, type, stopAtList) { - let parent = node.parent; - const stopAtSet = new Set(stopAtList || ["Program"]); - - while (parent.type !== type && !stopAtSet.has(parent.type) && parent.type !== "Program") { - parent = parent.parent; - } - - return parent.type === type ? parent : null; - } - - /** - * Returns the VariableDeclarator based on the current node - * if not present then return null - * @param {ASTNode} node node to examine - * @returns {ASTNode|void} if found then node otherwise null - */ - function getVariableDeclaratorNode(node) { - return getParentNodeByType(node, "VariableDeclarator"); - } - - /** - * Check to see if the node is part of the multi-line variable declaration. - * Also if its on the same line as the varNode - * @param {ASTNode} node node to check - * @param {ASTNode} varNode variable declaration node to check against - * @returns {boolean} True if all the above condition satisfy - */ - function isNodeInVarOnTop(node, varNode) { - return varNode && - varNode.parent.loc.start.line === node.loc.start.line && - varNode.parent.declarations.length > 1; - } - - /** - * Check to see if the argument before the callee node is multi-line and - * there should only be 1 argument before the callee node - * @param {ASTNode} node node to check - * @returns {boolean} True if arguments are multi-line - */ - function isArgBeforeCalleeNodeMultiline(node) { - const parent = node.parent; - - if (parent.arguments.length >= 2 && parent.arguments[1] === node) { - return parent.arguments[0].loc.end.line > parent.arguments[0].loc.start.line; - } - - return false; - } - - /** - * Check to see if the node is a file level IIFE - * @param {ASTNode} node The function node to check. - * @returns {boolean} True if the node is the outer IIFE - */ - function isOuterIIFE(node) { - const parent = node.parent; - let stmt = parent.parent; - - /* - * Verify that the node is an IIEF - */ - if ( - parent.type !== "CallExpression" || - parent.callee !== node) { - - return false; - } - - /* - * Navigate legal ancestors to determine whether this IIEF is outer - */ - while ( - stmt.type === "UnaryExpression" && ( - stmt.operator === "!" || - stmt.operator === "~" || - stmt.operator === "+" || - stmt.operator === "-") || - stmt.type === "AssignmentExpression" || - stmt.type === "LogicalExpression" || - stmt.type === "SequenceExpression" || - stmt.type === "VariableDeclarator") { - - stmt = stmt.parent; - } - - return (( - stmt.type === "ExpressionStatement" || - stmt.type === "VariableDeclaration") && - stmt.parent && stmt.parent.type === "Program" - ); - } - - /** - * Check indent for function block content - * @param {ASTNode} node A BlockStatement node that is inside of a function. - * @returns {void} - */ - function checkIndentInFunctionBlock(node) { - - /* - * Search first caller in chain. - * Ex.: - * - * Models <- Identifier - * .User - * .find() - * .exec(function() { - * // function body - * }); - * - * Looks for 'Models' - */ - const calleeNode = node.parent; // FunctionExpression - let indent; - - if (calleeNode.parent && - (calleeNode.parent.type === "Property" || - calleeNode.parent.type === "ArrayExpression")) { - - // If function is part of array or object, comma can be put at left - indent = getNodeIndent(calleeNode, false).goodChar; - } else { - - // If function is standalone, simple calculate indent - indent = getNodeIndent(calleeNode).goodChar; - } - - if (calleeNode.parent.type === "CallExpression") { - const calleeParent = calleeNode.parent; - - if (calleeNode.type !== "FunctionExpression" && calleeNode.type !== "ArrowFunctionExpression") { - if (calleeParent && calleeParent.loc.start.line < node.loc.start.line) { - indent = getNodeIndent(calleeParent).goodChar; - } - } else { - if (isArgBeforeCalleeNodeMultiline(calleeNode) && - calleeParent.callee.loc.start.line === calleeParent.callee.loc.end.line && - !isNodeFirstInLine(calleeNode)) { - indent = getNodeIndent(calleeParent).goodChar; - } - } - } - - /* - * function body indent should be indent + indent size, unless this - * is a FunctionDeclaration, FunctionExpression, or outer IIFE and the corresponding options are enabled. - */ - let functionOffset = indentSize; - - if (options.outerIIFEBody !== null && isOuterIIFE(calleeNode)) { - functionOffset = options.outerIIFEBody * indentSize; - } else if (calleeNode.type === "FunctionExpression") { - functionOffset = options.FunctionExpression.body * indentSize; - } else if (calleeNode.type === "FunctionDeclaration") { - functionOffset = options.FunctionDeclaration.body * indentSize; - } - indent += functionOffset; - - // check if the node is inside a variable - const parentVarNode = getVariableDeclaratorNode(node); - - if (parentVarNode && isNodeInVarOnTop(node, parentVarNode)) { - indent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind]; - } - - if (node.body.length > 0) { - checkNodesIndent(node.body, indent); - } - - checkLastNodeLineIndent(node, indent - functionOffset); - } - - - /** - * Checks if the given node starts and ends on the same line - * @param {ASTNode} node The node to check - * @returns {boolean} Whether or not the block starts and ends on the same line. - */ - function isSingleLineNode(node) { - const lastToken = sourceCode.getLastToken(node), - startLine = node.loc.start.line, - endLine = lastToken.loc.end.line; - - return startLine === endLine; - } - - /** - * Check indent for array block content or object block content - * @param {ASTNode} node node to examine - * @returns {void} - */ - function checkIndentInArrayOrObjectBlock(node) { - - // Skip inline - if (isSingleLineNode(node)) { - return; - } - - let elements = (node.type === "ArrayExpression") ? node.elements : node.properties; - - // filter out empty elements example would be [ , 2] so remove first element as espree considers it as null - elements = elements.filter(elem => elem !== null); - - let nodeIndent; - let elementsIndent; - const parentVarNode = getVariableDeclaratorNode(node); - - // TODO - come up with a better strategy in future - if (isNodeFirstInLine(node)) { - const parent = node.parent; - - nodeIndent = getNodeIndent(parent).goodChar; - if (!parentVarNode || parentVarNode.loc.start.line !== node.loc.start.line) { - if (parent.type !== "VariableDeclarator" || parentVarNode === parentVarNode.parent.declarations[0]) { - if (parent.type === "VariableDeclarator" && parentVarNode.loc.start.line === parent.loc.start.line) { - nodeIndent += (indentSize * options.VariableDeclarator[parentVarNode.parent.kind]); - } else if (parent.type === "ObjectExpression" || parent.type === "ArrayExpression") { - const parentElements = node.parent.type === "ObjectExpression" ? node.parent.properties : node.parent.elements; - - if (parentElements[0] && - parentElements[0].loc.start.line === parent.loc.start.line && - parentElements[0].loc.end.line !== parent.loc.start.line) { - - /* - * If the first element of the array spans multiple lines, don't increase the expected indentation of the rest. - * e.g. [{ - * foo: 1 - * }, - * { - * bar: 1 - * }] - * the second object is not indented. - */ - } else if (typeof options[parent.type] === "number") { - nodeIndent += options[parent.type] * indentSize; - } else { - nodeIndent = parentElements[0].loc.start.column; - } - } else if (parent.type === "CallExpression" || parent.type === "NewExpression") { - if (typeof options.CallExpression.arguments === "number") { - nodeIndent += options.CallExpression.arguments * indentSize; - } else if (options.CallExpression.arguments === "first") { - if (parent.arguments.indexOf(node) !== -1) { - nodeIndent = parent.arguments[0].loc.start.column; - } - } else { - nodeIndent += indentSize; - } - } else if (parent.type === "LogicalExpression" || parent.type === "ArrowFunctionExpression") { - nodeIndent += indentSize; - } - } - } - - checkFirstNodeLineIndent(node, nodeIndent); - } else { - nodeIndent = getNodeIndent(node).goodChar; - } - - if (options[node.type] === "first") { - elementsIndent = elements.length ? elements[0].loc.start.column : 0; // If there are no elements, elementsIndent doesn't matter. - } else { - elementsIndent = nodeIndent + indentSize * options[node.type]; - } - - /* - * Check if the node is a multiple variable declaration; if so, then - * make sure indentation takes that into account. - */ - if (isNodeInVarOnTop(node, parentVarNode)) { - elementsIndent += indentSize * options.VariableDeclarator[parentVarNode.parent.kind]; - } - - checkNodesIndent(elements, elementsIndent); - - if (elements.length > 0) { - - // Skip last block line check if last item in same line - if (elements[elements.length - 1].loc.end.line === node.loc.end.line) { - return; - } - } - - checkLastNodeLineIndent(node, nodeIndent + - (isNodeInVarOnTop(node, parentVarNode) ? options.VariableDeclarator[parentVarNode.parent.kind] * indentSize : 0)); - } - - /** - * Check if the node or node body is a BlockStatement or not - * @param {ASTNode} node node to test - * @returns {boolean} True if it or its body is a block statement - */ - function isNodeBodyBlock(node) { - return node.type === "BlockStatement" || node.type === "ClassBody" || (node.body && node.body.type === "BlockStatement") || - (node.consequent && node.consequent.type === "BlockStatement"); - } - - /** - * Check indentation for blocks - * @param {ASTNode} node node to check - * @returns {void} - */ - function blockIndentationCheck(node) { - - // Skip inline blocks - if (isSingleLineNode(node)) { - return; - } - - if (node.parent && ( - node.parent.type === "FunctionExpression" || - node.parent.type === "FunctionDeclaration" || - node.parent.type === "ArrowFunctionExpression") - ) { - checkIndentInFunctionBlock(node); - return; - } - - let indent; - let nodesToCheck = []; - - /* - * For this statements we should check indent from statement beginning, - * not from the beginning of the block. - */ - const statementsWithProperties = [ - "IfStatement", "WhileStatement", "ForStatement", "ForInStatement", "ForOfStatement", "DoWhileStatement", "ClassDeclaration", "TryStatement" - ]; - - if (node.parent && statementsWithProperties.indexOf(node.parent.type) !== -1 && isNodeBodyBlock(node)) { - indent = getNodeIndent(node.parent).goodChar; - } else if (node.parent && node.parent.type === "CatchClause") { - indent = getNodeIndent(node.parent.parent).goodChar; - } else { - indent = getNodeIndent(node).goodChar; - } - - if (node.type === "IfStatement" && node.consequent.type !== "BlockStatement") { - nodesToCheck = [node.consequent]; - } else if (Array.isArray(node.body)) { - nodesToCheck = node.body; - } else { - nodesToCheck = [node.body]; - } - - if (nodesToCheck.length > 0) { - checkNodesIndent(nodesToCheck, indent + indentSize); - } - - if (node.type === "BlockStatement") { - checkLastNodeLineIndent(node, indent); - } - } - - /** - * Filter out the elements which are on the same line of each other or the node. - * basically have only 1 elements from each line except the variable declaration line. - * @param {ASTNode} node Variable declaration node - * @returns {ASTNode[]} Filtered elements - */ - function filterOutSameLineVars(node) { - return node.declarations.reduce((finalCollection, elem) => { - const lastElem = finalCollection[finalCollection.length - 1]; - - if ((elem.loc.start.line !== node.loc.start.line && !lastElem) || - (lastElem && lastElem.loc.start.line !== elem.loc.start.line)) { - finalCollection.push(elem); - } - - return finalCollection; - }, []); - } - - /** - * Check indentation for variable declarations - * @param {ASTNode} node node to examine - * @returns {void} - */ - function checkIndentInVariableDeclarations(node) { - const elements = filterOutSameLineVars(node); - const nodeIndent = getNodeIndent(node).goodChar; - const lastElement = elements[elements.length - 1]; - - const elementsIndent = nodeIndent + indentSize * options.VariableDeclarator[node.kind]; - - checkNodesIndent(elements, elementsIndent); - - // Only check the last line if there is any token after the last item - if (sourceCode.getLastToken(node).loc.end.line <= lastElement.loc.end.line) { - return; - } - - const tokenBeforeLastElement = sourceCode.getTokenBefore(lastElement); - - if (tokenBeforeLastElement.value === ",") { - - // Special case for comma-first syntax where the semicolon is indented - checkLastNodeLineIndent(node, getNodeIndent(tokenBeforeLastElement).goodChar); - } else { - checkLastNodeLineIndent(node, elementsIndent - indentSize); - } - } - - /** - * Check and decide whether to check for indentation for blockless nodes - * Scenarios are for or while statements without braces around them - * @param {ASTNode} node node to examine - * @returns {void} - */ - function blockLessNodes(node) { - if (node.body.type !== "BlockStatement") { - blockIndentationCheck(node); - } - } - - /** - * Returns the expected indentation for the case statement - * @param {ASTNode} node node to examine - * @param {int} [providedSwitchIndent] indent for switch statement - * @returns {int} indent size - */ - function expectedCaseIndent(node, providedSwitchIndent) { - const switchNode = (node.type === "SwitchStatement") ? node : node.parent; - const switchIndent = typeof providedSwitchIndent === "undefined" - ? getNodeIndent(switchNode).goodChar - : providedSwitchIndent; - let caseIndent; - - if (caseIndentStore[switchNode.loc.start.line]) { - return caseIndentStore[switchNode.loc.start.line]; - } - - if (switchNode.cases.length > 0 && options.SwitchCase === 0) { - caseIndent = switchIndent; - } else { - caseIndent = switchIndent + (indentSize * options.SwitchCase); - } - - caseIndentStore[switchNode.loc.start.line] = caseIndent; - return caseIndent; - - } - - /** - * Checks wether a return statement is wrapped in () - * @param {ASTNode} node node to examine - * @returns {boolean} the result - */ - function isWrappedInParenthesis(node) { - const regex = /^return\s*?\(\s*?\);*?/u; - - const statementWithoutArgument = sourceCode.getText(node).replace( - sourceCode.getText(node.argument), "" - ); - - return regex.test(statementWithoutArgument); - } - - return { - Program(node) { - if (node.body.length > 0) { - - // Root nodes should have no indent - checkNodesIndent(node.body, getNodeIndent(node).goodChar); - } - }, - - ClassBody: blockIndentationCheck, - - BlockStatement: blockIndentationCheck, - - WhileStatement: blockLessNodes, - - ForStatement: blockLessNodes, - - ForInStatement: blockLessNodes, - - ForOfStatement: blockLessNodes, - - DoWhileStatement: blockLessNodes, - - IfStatement(node) { - if (node.consequent.type !== "BlockStatement" && node.consequent.loc.start.line > node.loc.start.line) { - blockIndentationCheck(node); - } - }, - - VariableDeclaration(node) { - if (node.declarations[node.declarations.length - 1].loc.start.line > node.declarations[0].loc.start.line) { - checkIndentInVariableDeclarations(node); - } - }, - - ObjectExpression(node) { - checkIndentInArrayOrObjectBlock(node); - }, - - ArrayExpression(node) { - checkIndentInArrayOrObjectBlock(node); - }, - - MemberExpression(node) { - - if (typeof options.MemberExpression === "undefined") { - return; - } - - if (isSingleLineNode(node)) { - return; - } - - /* - * The typical layout of variable declarations and assignments - * alter the expectation of correct indentation. Skip them. - * TODO: Add appropriate configuration options for variable - * declarations and assignments. - */ - if (getParentNodeByType(node, "VariableDeclarator", ["FunctionExpression", "ArrowFunctionExpression"])) { - return; - } - - if (getParentNodeByType(node, "AssignmentExpression", ["FunctionExpression"])) { - return; - } - - const propertyIndent = getNodeIndent(node).goodChar + indentSize * options.MemberExpression; - - const checkNodes = [node.property]; - - const dot = sourceCode.getTokenBefore(node.property); - - if (dot.type === "Punctuator" && dot.value === ".") { - checkNodes.push(dot); - } - - checkNodesIndent(checkNodes, propertyIndent); - }, - - SwitchStatement(node) { - - // Switch is not a 'BlockStatement' - const switchIndent = getNodeIndent(node).goodChar; - const caseIndent = expectedCaseIndent(node, switchIndent); - - checkNodesIndent(node.cases, caseIndent); - - - checkLastNodeLineIndent(node, switchIndent); - }, - - SwitchCase(node) { - - // Skip inline cases - if (isSingleLineNode(node)) { - return; - } - const caseIndent = expectedCaseIndent(node); - - checkNodesIndent(node.consequent, caseIndent + indentSize); - }, - - FunctionDeclaration(node) { - if (isSingleLineNode(node)) { - return; - } - if (options.FunctionDeclaration.parameters === "first" && node.params.length) { - checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column); - } else if (options.FunctionDeclaration.parameters !== null) { - checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionDeclaration.parameters); - } - }, - - FunctionExpression(node) { - if (isSingleLineNode(node)) { - return; - } - if (options.FunctionExpression.parameters === "first" && node.params.length) { - checkNodesIndent(node.params.slice(1), node.params[0].loc.start.column); - } else if (options.FunctionExpression.parameters !== null) { - checkNodesIndent(node.params, getNodeIndent(node).goodChar + indentSize * options.FunctionExpression.parameters); - } - }, - - ReturnStatement(node) { - if (isSingleLineNode(node)) { - return; - } - - const firstLineIndent = getNodeIndent(node).goodChar; - - // in case if return statement is wrapped in parenthesis - if (isWrappedInParenthesis(node)) { - checkLastReturnStatementLineIndent(node, firstLineIndent); - } else { - checkNodeIndent(node, firstLineIndent); - } - }, - - CallExpression(node) { - if (isSingleLineNode(node)) { - return; - } - if (options.CallExpression.arguments === "first" && node.arguments.length) { - checkNodesIndent(node.arguments.slice(1), node.arguments[0].loc.start.column); - } else if (options.CallExpression.arguments !== null) { - checkNodesIndent(node.arguments, getNodeIndent(node).goodChar + indentSize * options.CallExpression.arguments); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/indent.js b/tools/node_modules/eslint/lib/rules/indent.js deleted file mode 100644 index 22b633845b596efac6d3def56599ee45c445f3d4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/indent.js +++ /dev/null @@ -1,1705 +0,0 @@ -/** - * @fileoverview This rule sets a specific indentation style and width for your code - * - * @author Teddy Katz - * @author Vitaly Puzrin - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("./utils/ast-utils"); -const createTree = require("functional-red-black-tree"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const KNOWN_NODES = new Set([ - "AssignmentExpression", - "AssignmentPattern", - "ArrayExpression", - "ArrayPattern", - "ArrowFunctionExpression", - "AwaitExpression", - "BlockStatement", - "BinaryExpression", - "BreakStatement", - "CallExpression", - "CatchClause", - "ChainExpression", - "ClassBody", - "ClassDeclaration", - "ClassExpression", - "ConditionalExpression", - "ContinueStatement", - "DoWhileStatement", - "DebuggerStatement", - "EmptyStatement", - "ExperimentalRestProperty", - "ExperimentalSpreadProperty", - "ExpressionStatement", - "ForStatement", - "ForInStatement", - "ForOfStatement", - "FunctionDeclaration", - "FunctionExpression", - "Identifier", - "IfStatement", - "Literal", - "LabeledStatement", - "LogicalExpression", - "MemberExpression", - "MetaProperty", - "MethodDefinition", - "NewExpression", - "ObjectExpression", - "ObjectPattern", - "Program", - "Property", - "RestElement", - "ReturnStatement", - "SequenceExpression", - "SpreadElement", - "Super", - "SwitchCase", - "SwitchStatement", - "TaggedTemplateExpression", - "TemplateElement", - "TemplateLiteral", - "ThisExpression", - "ThrowStatement", - "TryStatement", - "UnaryExpression", - "UpdateExpression", - "VariableDeclaration", - "VariableDeclarator", - "WhileStatement", - "WithStatement", - "YieldExpression", - "JSXFragment", - "JSXOpeningFragment", - "JSXClosingFragment", - "JSXIdentifier", - "JSXNamespacedName", - "JSXMemberExpression", - "JSXEmptyExpression", - "JSXExpressionContainer", - "JSXElement", - "JSXClosingElement", - "JSXOpeningElement", - "JSXAttribute", - "JSXSpreadAttribute", - "JSXText", - "ExportDefaultDeclaration", - "ExportNamedDeclaration", - "ExportAllDeclaration", - "ExportSpecifier", - "ImportDeclaration", - "ImportSpecifier", - "ImportDefaultSpecifier", - "ImportNamespaceSpecifier", - "ImportExpression" -]); - -/* - * General rule strategy: - * 1. An OffsetStorage instance stores a map of desired offsets, where each token has a specified offset from another - * specified token or to the first column. - * 2. As the AST is traversed, modify the desired offsets of tokens accordingly. For example, when entering a - * BlockStatement, offset all of the tokens in the BlockStatement by 1 indent level from the opening curly - * brace of the BlockStatement. - * 3. After traversing the AST, calculate the expected indentation levels of every token according to the - * OffsetStorage container. - * 4. For each line, compare the expected indentation of the first token to the actual indentation in the file, - * and report the token if the two values are not equal. - */ - - -/** - * A mutable balanced binary search tree that stores (key, value) pairs. The keys are numeric, and must be unique. - * This is intended to be a generic wrapper around a balanced binary search tree library, so that the underlying implementation - * can easily be swapped out. - */ -class BinarySearchTree { - - /** - * Creates an empty tree - */ - constructor() { - this._rbTree = createTree(); - } - - /** - * Inserts an entry into the tree. - * @param {number} key The entry's key - * @param {*} value The entry's value - * @returns {void} - */ - insert(key, value) { - const iterator = this._rbTree.find(key); - - if (iterator.valid) { - this._rbTree = iterator.update(value); - } else { - this._rbTree = this._rbTree.insert(key, value); - } - } - - /** - * Finds the entry with the largest key less than or equal to the provided key - * @param {number} key The provided key - * @returns {{key: number, value: *}|null} The found entry, or null if no such entry exists. - */ - findLe(key) { - const iterator = this._rbTree.le(key); - - return iterator && { key: iterator.key, value: iterator.value }; - } - - /** - * Deletes all of the keys in the interval [start, end) - * @param {number} start The start of the range - * @param {number} end The end of the range - * @returns {void} - */ - deleteRange(start, end) { - - // Exit without traversing the tree if the range has zero size. - if (start === end) { - return; - } - const iterator = this._rbTree.ge(start); - - while (iterator.valid && iterator.key < end) { - this._rbTree = this._rbTree.remove(iterator.key); - iterator.next(); - } - } -} - -/** - * A helper class to get token-based info related to indentation - */ -class TokenInfo { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {SourceCode} sourceCode A SourceCode object - */ - constructor(sourceCode) { - this.sourceCode = sourceCode; - this.firstTokensByLineNumber = sourceCode.tokensAndComments.reduce((map, token) => { - if (!map.has(token.loc.start.line)) { - map.set(token.loc.start.line, token); - } - if (!map.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) { - map.set(token.loc.end.line, token); - } - return map; - }, new Map()); - } - - /** - * Gets the first token on a given token's line - * @param {Token|ASTNode} token a node or token - * @returns {Token} The first token on the given line - */ - getFirstTokenOfLine(token) { - return this.firstTokensByLineNumber.get(token.loc.start.line); - } - - /** - * Determines whether a token is the first token in its line - * @param {Token} token The token - * @returns {boolean} `true` if the token is the first on its line - */ - isFirstTokenOfLine(token) { - return this.getFirstTokenOfLine(token) === token; - } - - /** - * Get the actual indent of a token - * @param {Token} token Token to examine. This should be the first token on its line. - * @returns {string} The indentation characters that precede the token - */ - getTokenIndent(token) { - return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]); - } -} - -/** - * A class to store information on desired offsets of tokens from each other - */ -class OffsetStorage { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {TokenInfo} tokenInfo a TokenInfo instance - * @param {number} indentSize The desired size of each indentation level - * @param {string} indentType The indentation character - */ - constructor(tokenInfo, indentSize, indentType) { - this._tokenInfo = tokenInfo; - this._indentSize = indentSize; - this._indentType = indentType; - - this._tree = new BinarySearchTree(); - this._tree.insert(0, { offset: 0, from: null, force: false }); - - this._lockedFirstTokens = new WeakMap(); - this._desiredIndentCache = new WeakMap(); - this._ignoredTokens = new WeakSet(); - } - - _getOffsetDescriptor(token) { - return this._tree.findLe(token.range[0]).value; - } - - /** - * Sets the offset column of token B to match the offset column of token A. - * **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In - * most cases, `setDesiredOffset` should be used instead. - * @param {Token} baseToken The first token - * @param {Token} offsetToken The second token, whose offset should be matched to the first token - * @returns {void} - */ - matchOffsetOf(baseToken, offsetToken) { - - /* - * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to - * the token that it depends on. For example, with the `ArrayExpression: first` option, the first - * token of each element in the array after the first will be mapped to the first token of the first - * element. The desired indentation of each of these tokens is computed based on the desired indentation - * of the "first" element, rather than through the normal offset mechanism. - */ - this._lockedFirstTokens.set(offsetToken, baseToken); - } - - /** - * Sets the desired offset of a token. - * - * This uses a line-based offset collapsing behavior to handle tokens on the same line. - * For example, consider the following two cases: - * - * ( - * [ - * bar - * ] - * ) - * - * ([ - * bar - * ]) - * - * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from - * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is - * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces) - * from the start of its line. - * - * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level - * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the - * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented - * by 1 indent level from the start of the line. - * - * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node, - * without needing to check which lines those tokens are on. - * - * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive - * behavior can occur. For example, consider the following cases: - * - * foo( - * ). - * bar( - * baz - * ) - * - * foo( - * ).bar( - * baz - * ) - * - * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz` - * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz` - * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no - * collapsing would occur). - * - * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and - * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed - * in the second case. - * @param {Token} token The token - * @param {Token} fromToken The token that `token` should be offset from - * @param {number} offset The desired indent level - * @returns {void} - */ - setDesiredOffset(token, fromToken, offset) { - return this.setDesiredOffsets(token.range, fromToken, offset); - } - - /** - * Sets the desired offset of all tokens in a range - * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens. - * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains - * it). This means that the offset of each token is updated O(AST depth) times. - * It would not be performant to store and update the offsets for each token independently, because the rule would end - * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files. - * - * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following - * list could represent the state of the offset tree at a given point: - * - * * Tokens starting in the interval [0, 15) are aligned with the beginning of the file - * * Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token - * * Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token - * * Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token - * * Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token - * - * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using: - * `setDesiredOffsets([30, 43], fooToken, 1);` - * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied. - * @param {Token} fromToken The token that this is offset from - * @param {number} offset The desired indent level - * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false. - * @returns {void} - */ - setDesiredOffsets(range, fromToken, offset, force) { - - /* - * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset - * descriptor. The tree for the example above would have the following nodes: - * - * * key: 0, value: { offset: 0, from: null } - * * key: 15, value: { offset: 1, from: barToken } - * * key: 30, value: { offset: 1, from: fooToken } - * * key: 43, value: { offset: 2, from: barToken } - * * key: 820, value: { offset: 1, from: bazToken } - * - * To find the offset descriptor for any given token, one needs to find the node with the largest key - * which is <= token.start. To make this operation fast, the nodes are stored in a balanced binary - * search tree indexed by key. - */ - - const descriptorToInsert = { offset, from: fromToken, force }; - - const descriptorAfterRange = this._tree.findLe(range[1]).value; - - const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1]; - const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken); - - // First, remove any existing nodes in the range from the tree. - this._tree.deleteRange(range[0] + 1, range[1]); - - // Insert a new node into the tree for this range - this._tree.insert(range[0], descriptorToInsert); - - /* - * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously, - * even if it's in the current range. - */ - if (fromTokenIsInRange) { - this._tree.insert(fromToken.range[0], fromTokenDescriptor); - this._tree.insert(fromToken.range[1], descriptorToInsert); - } - - /* - * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following - * tokens the same as it was before. - */ - this._tree.insert(range[1], descriptorAfterRange); - } - - /** - * Gets the desired indent of a token - * @param {Token} token The token - * @returns {string} The desired indent of the token - */ - getDesiredIndent(token) { - if (!this._desiredIndentCache.has(token)) { - - if (this._ignoredTokens.has(token)) { - - /* - * If the token is ignored, use the actual indent of the token as the desired indent. - * This ensures that no errors are reported for this token. - */ - this._desiredIndentCache.set( - token, - this._tokenInfo.getTokenIndent(token) - ); - } else if (this._lockedFirstTokens.has(token)) { - const firstToken = this._lockedFirstTokens.get(token); - - this._desiredIndentCache.set( - token, - - // (indentation for the first element's line) - this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) + - - // (space between the start of the first element's line and the first element) - this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column) - ); - } else { - const offsetInfo = this._getOffsetDescriptor(token); - const offset = ( - offsetInfo.from && - offsetInfo.from.loc.start.line === token.loc.start.line && - !/^\s*?\n/u.test(token.value) && - !offsetInfo.force - ) ? 0 : offsetInfo.offset * this._indentSize; - - this._desiredIndentCache.set( - token, - (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset) - ); - } - } - return this._desiredIndentCache.get(token); - } - - /** - * Ignores a token, preventing it from being reported. - * @param {Token} token The token - * @returns {void} - */ - ignoreToken(token) { - if (this._tokenInfo.isFirstTokenOfLine(token)) { - this._ignoredTokens.add(token); - } - } - - /** - * Gets the first token that the given token's indentation is dependent on - * @param {Token} token The token - * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level - */ - getFirstDependency(token) { - return this._getOffsetDescriptor(token).from; - } -} - -const ELEMENT_LIST_SCHEMA = { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["first", "off"] - } - ] -}; - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent indentation", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/indent" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["tab"] - }, - { - type: "integer", - minimum: 0 - } - ] - }, - { - type: "object", - properties: { - SwitchCase: { - type: "integer", - minimum: 0, - default: 0 - }, - VariableDeclarator: { - oneOf: [ - ELEMENT_LIST_SCHEMA, - { - type: "object", - properties: { - var: ELEMENT_LIST_SCHEMA, - let: ELEMENT_LIST_SCHEMA, - const: ELEMENT_LIST_SCHEMA - }, - additionalProperties: false - } - ] - }, - outerIIFEBody: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["off"] - } - ] - }, - MemberExpression: { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - enum: ["off"] - } - ] - }, - FunctionDeclaration: { - type: "object", - properties: { - parameters: ELEMENT_LIST_SCHEMA, - body: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - }, - FunctionExpression: { - type: "object", - properties: { - parameters: ELEMENT_LIST_SCHEMA, - body: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - }, - CallExpression: { - type: "object", - properties: { - arguments: ELEMENT_LIST_SCHEMA - }, - additionalProperties: false - }, - ArrayExpression: ELEMENT_LIST_SCHEMA, - ObjectExpression: ELEMENT_LIST_SCHEMA, - ImportDeclaration: ELEMENT_LIST_SCHEMA, - flatTernaryExpressions: { - type: "boolean", - default: false - }, - offsetTernaryExpressions: { - type: "boolean", - default: false - }, - ignoredNodes: { - type: "array", - items: { - type: "string", - not: { - pattern: ":exit$" - } - } - }, - ignoreComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}." - } - }, - - create(context) { - const DEFAULT_VARIABLE_INDENT = 1; - const DEFAULT_PARAMETER_INDENT = 1; - const DEFAULT_FUNCTION_BODY_INDENT = 1; - - let indentType = "space"; - let indentSize = 4; - const options = { - SwitchCase: 0, - VariableDeclarator: { - var: DEFAULT_VARIABLE_INDENT, - let: DEFAULT_VARIABLE_INDENT, - const: DEFAULT_VARIABLE_INDENT - }, - outerIIFEBody: 1, - FunctionDeclaration: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - FunctionExpression: { - parameters: DEFAULT_PARAMETER_INDENT, - body: DEFAULT_FUNCTION_BODY_INDENT - }, - CallExpression: { - arguments: DEFAULT_PARAMETER_INDENT - }, - MemberExpression: 1, - ArrayExpression: 1, - ObjectExpression: 1, - ImportDeclaration: 1, - flatTernaryExpressions: false, - ignoredNodes: [], - ignoreComments: false - }; - - if (context.options.length) { - if (context.options[0] === "tab") { - indentSize = 1; - indentType = "tab"; - } else { - indentSize = context.options[0]; - indentType = "space"; - } - - if (context.options[1]) { - Object.assign(options, context.options[1]); - - if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") { - options.VariableDeclarator = { - var: options.VariableDeclarator, - let: options.VariableDeclarator, - const: options.VariableDeclarator - }; - } - } - } - - const sourceCode = context.getSourceCode(); - const tokenInfo = new TokenInfo(sourceCode); - const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t"); - const parameterParens = new WeakSet(); - - /** - * Creates an error message for a line, given the expected/actual indentation. - * @param {int} expectedAmount The expected amount of indentation characters for this line - * @param {int} actualSpaces The actual number of indentation spaces that were found on this line - * @param {int} actualTabs The actual number of indentation tabs that were found on this line - * @returns {string} An error message for this line - */ - function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) { - const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs" - const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space" - const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs" - let foundStatement; - - if (actualSpaces > 0) { - - /* - * Abbreviate the message if the expected indentation is also spaces. - * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces' - */ - foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`; - } else if (actualTabs > 0) { - foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`; - } else { - foundStatement = "0"; - } - return { - expected: expectedStatement, - actual: foundStatement - }; - } - - /** - * Reports a given indent violation - * @param {Token} token Token violating the indent rule - * @param {string} neededIndent Expected indentation string - * @returns {void} - */ - function report(token, neededIndent) { - const actualIndent = Array.from(tokenInfo.getTokenIndent(token)); - const numSpaces = actualIndent.filter(char => char === " ").length; - const numTabs = actualIndent.filter(char => char === "\t").length; - - context.report({ - node: token, - messageId: "wrongIndentation", - data: createErrorMessageData(neededIndent.length, numSpaces, numTabs), - loc: { - start: { line: token.loc.start.line, column: 0 }, - end: { line: token.loc.start.line, column: token.loc.start.column } - }, - fix(fixer) { - const range = [token.range[0] - token.loc.start.column, token.range[0]]; - const newText = neededIndent; - - return fixer.replaceTextRange(range, newText); - } - }); - } - - /** - * Checks if a token's indentation is correct - * @param {Token} token Token to examine - * @param {string} desiredIndent Desired indentation of the string - * @returns {boolean} `true` if the token's indentation is correct - */ - function validateTokenIndent(token, desiredIndent) { - const indentation = tokenInfo.getTokenIndent(token); - - return indentation === desiredIndent || - - // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs. - indentation.includes(" ") && indentation.includes("\t"); - } - - /** - * Check to see if the node is a file level IIFE - * @param {ASTNode} node The function node to check. - * @returns {boolean} True if the node is the outer IIFE - */ - function isOuterIIFE(node) { - - /* - * Verify that the node is an IIFE - */ - if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) { - return false; - } - - /* - * Navigate legal ancestors to determine whether this IIFE is outer. - * A "legal ancestor" is an expression or statement that causes the function to get executed immediately. - * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator. - */ - let statement = node.parent && node.parent.parent; - - while ( - statement.type === "UnaryExpression" && ["!", "~", "+", "-"].indexOf(statement.operator) > -1 || - statement.type === "AssignmentExpression" || - statement.type === "LogicalExpression" || - statement.type === "SequenceExpression" || - statement.type === "VariableDeclarator" - ) { - statement = statement.parent; - } - - return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program"; - } - - /** - * Counts the number of linebreaks that follow the last non-whitespace character in a string - * @param {string} string The string to check - * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character, - * or the total number of linebreaks if the string is all whitespace. - */ - function countTrailingLinebreaks(string) { - const trailingWhitespace = string.match(/\s*$/u)[0]; - const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher()); - - return linebreakMatches === null ? 0 : linebreakMatches.length; - } - - /** - * Check indentation for lists of elements (arrays, objects, function params) - * @param {ASTNode[]} elements List of elements that should be offset - * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '[' - * @param {Token} endToken The end token of the list, e.g. ']' - * @param {number|string} offset The amount that the elements should be offset - * @returns {void} - */ - function addElementListIndent(elements, startToken, endToken, offset) { - - /** - * Gets the first token of a given element, including surrounding parentheses. - * @param {ASTNode} element A node in the `elements` list - * @returns {Token} The first token of this element - */ - function getFirstToken(element) { - let token = sourceCode.getTokenBefore(element); - - while (astUtils.isOpeningParenToken(token) && token !== startToken) { - token = sourceCode.getTokenBefore(token); - } - return sourceCode.getTokenAfter(token); - } - - // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden) - offsets.setDesiredOffsets( - [startToken.range[1], endToken.range[0]], - startToken, - typeof offset === "number" ? offset : 1 - ); - offsets.setDesiredOffset(endToken, startToken, 0); - - // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level. - if (offset === "first" && elements.length && !elements[0]) { - return; - } - elements.forEach((element, index) => { - if (!element) { - - // Skip holes in arrays - return; - } - if (offset === "off") { - - // Ignore the first token of every element if the "off" option is used - offsets.ignoreToken(getFirstToken(element)); - } - - // Offset the following elements correctly relative to the first element - if (index === 0) { - return; - } - if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) { - offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element)); - } else { - const previousElement = elements[index - 1]; - const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement); - const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement); - - if ( - previousElement && - previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line - ) { - offsets.setDesiredOffsets( - [previousElement.range[1], element.range[1]], - firstTokenOfPreviousElement, - 0 - ); - } - } - }); - } - - /** - * Check and decide whether to check for indentation for blockless nodes - * Scenarios are for or while statements without braces around them - * @param {ASTNode} node node to examine - * @returns {void} - */ - function addBlocklessNodeIndent(node) { - if (node.type !== "BlockStatement") { - const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken); - - let firstBodyToken = sourceCode.getFirstToken(node); - let lastBodyToken = sourceCode.getLastToken(node); - - while ( - astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) && - astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken)) - ) { - firstBodyToken = sourceCode.getTokenBefore(firstBodyToken); - lastBodyToken = sourceCode.getTokenAfter(lastBodyToken); - } - - offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1); - - /* - * For blockless nodes with semicolon-first style, don't indent the semicolon. - * e.g. - * if (foo) bar() - * ; [1, 2, 3].map(foo) - */ - const lastToken = sourceCode.getLastToken(node); - - if (node.type !== "EmptyStatement" && astUtils.isSemicolonToken(lastToken)) { - offsets.setDesiredOffset(lastToken, lastParentToken, 0); - } - } - } - - /** - * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`) - * @param {ASTNode} node A CallExpression or NewExpression node - * @returns {void} - */ - function addFunctionCallIndent(node) { - let openingParen; - - if (node.arguments.length) { - openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken); - } else { - openingParen = sourceCode.getLastToken(node, 1); - } - const closingParen = sourceCode.getLastToken(node); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - - /* - * If `?.` token exists, set desired offset for that. - * This logic is copied from `MemberExpression`'s. - */ - if (node.optional) { - const dotToken = sourceCode.getTokenAfter(node.callee, astUtils.isQuestionDotToken); - const calleeParenCount = sourceCode.getTokensBetween(node.callee, dotToken, { filter: astUtils.isClosingParenToken }).length; - const firstTokenOfCallee = calleeParenCount - ? sourceCode.getTokenBefore(node.callee, { skip: calleeParenCount - 1 }) - : sourceCode.getFirstToken(node.callee); - const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken); - const offsetBase = lastTokenOfCallee.loc.end.line === openingParen.loc.start.line - ? lastTokenOfCallee - : firstTokenOfCallee; - - offsets.setDesiredOffset(dotToken, offsetBase, 1); - } - - const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen; - const offsetToken = sourceCode.getTokenBefore(offsetAfterToken); - - offsets.setDesiredOffset(openingParen, offsetToken, 0); - - addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments); - } - - /** - * Checks the indentation of parenthesized values, given a list of tokens in a program - * @param {Token[]} tokens A list of tokens - * @returns {void} - */ - function addParensIndent(tokens) { - const parenStack = []; - const parenPairs = []; - - tokens.forEach(nextToken => { - - // Accumulate a list of parenthesis pairs - if (astUtils.isOpeningParenToken(nextToken)) { - parenStack.push(nextToken); - } else if (astUtils.isClosingParenToken(nextToken)) { - parenPairs.unshift({ left: parenStack.pop(), right: nextToken }); - } - }); - - parenPairs.forEach(pair => { - const leftParen = pair.left; - const rightParen = pair.right; - - // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments. - if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) { - const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen)); - - parenthesizedTokens.forEach(token => { - if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) { - offsets.setDesiredOffset(token, leftParen, 1); - } - }); - } - - offsets.setDesiredOffset(rightParen, leftParen, 0); - }); - } - - /** - * Ignore all tokens within an unknown node whose offset do not depend - * on another token's offset within the unknown node - * @param {ASTNode} node Unknown Node - * @returns {void} - */ - function ignoreNode(node) { - const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true })); - - unknownNodeTokens.forEach(token => { - if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) { - const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token); - - if (token === firstTokenOfLine) { - offsets.ignoreToken(token); - } else { - offsets.setDesiredOffset(token, firstTokenOfLine, 0); - } - } - }); - } - - /** - * Check whether the given token is on the first line of a statement. - * @param {Token} token The token to check. - * @param {ASTNode} leafNode The expression node that the token belongs directly. - * @returns {boolean} `true` if the token is on the first line of a statement. - */ - function isOnFirstLineOfStatement(token, leafNode) { - let node = leafNode; - - while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) { - node = node.parent; - } - node = node.parent; - - return !node || node.loc.start.line === token.loc.start.line; - } - - /** - * Check whether there are any blank (whitespace-only) lines between - * two tokens on separate lines. - * @param {Token} firstToken The first token. - * @param {Token} secondToken The second token. - * @returns {boolean} `true` if the tokens are on separate lines and - * there exists a blank line between them, `false` otherwise. - */ - function hasBlankLinesBetween(firstToken, secondToken) { - const firstTokenLine = firstToken.loc.end.line; - const secondTokenLine = secondToken.loc.start.line; - - if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) { - return false; - } - - for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) { - if (!tokenInfo.firstTokensByLineNumber.has(line)) { - return true; - } - } - - return false; - } - - const ignoredNodeFirstTokens = new Set(); - - const baseOffsetListeners = { - "ArrayExpression, ArrayPattern"(node) { - const openingBracket = sourceCode.getFirstToken(node); - const closingBracket = sourceCode.getTokenAfter(lodash.findLast(node.elements) || openingBracket, astUtils.isClosingBracketToken); - - addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression); - }, - - "ObjectExpression, ObjectPattern"(node) { - const openingCurly = sourceCode.getFirstToken(node); - const closingCurly = sourceCode.getTokenAfter( - node.properties.length ? node.properties[node.properties.length - 1] : openingCurly, - astUtils.isClosingBraceToken - ); - - addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression); - }, - - ArrowFunctionExpression(node) { - const firstToken = sourceCode.getFirstToken(node); - - if (astUtils.isOpeningParenToken(firstToken)) { - const openingParen = firstToken; - const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters); - } - addBlocklessNodeIndent(node.body); - }, - - AssignmentExpression(node) { - const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - - offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1); - offsets.ignoreToken(operator); - offsets.ignoreToken(sourceCode.getTokenAfter(operator)); - }, - - "BinaryExpression, LogicalExpression"(node) { - const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - - /* - * For backwards compatibility, don't check BinaryExpression indents, e.g. - * var foo = bar && - * baz; - */ - - const tokenAfterOperator = sourceCode.getTokenAfter(operator); - - offsets.ignoreToken(operator); - offsets.ignoreToken(tokenAfterOperator); - offsets.setDesiredOffset(tokenAfterOperator, operator, 0); - }, - - "BlockStatement, ClassBody"(node) { - let blockIndentLevel; - - if (node.parent && isOuterIIFE(node.parent)) { - blockIndentLevel = options.outerIIFEBody; - } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) { - blockIndentLevel = options.FunctionExpression.body; - } else if (node.parent && node.parent.type === "FunctionDeclaration") { - blockIndentLevel = options.FunctionDeclaration.body; - } else { - blockIndentLevel = 1; - } - - /* - * For blocks that aren't lone statements, ensure that the opening curly brace - * is aligned with the parent. - */ - if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) { - offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0); - } - - addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel); - }, - - CallExpression: addFunctionCallIndent, - - "ClassDeclaration[superClass], ClassExpression[superClass]"(node) { - const classToken = sourceCode.getFirstToken(node); - const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken); - - offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1); - }, - - ConditionalExpression(node) { - const firstToken = sourceCode.getFirstToken(node); - - // `flatTernaryExpressions` option is for the following style: - // var a = - // foo > 0 ? bar : - // foo < 0 ? baz : - // /*else*/ qiz ; - if (!options.flatTernaryExpressions || - !astUtils.isTokenOnSameLine(node.test, node.consequent) || - isOnFirstLineOfStatement(firstToken, node) - ) { - const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?"); - const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":"); - - const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken); - const lastConsequentToken = sourceCode.getTokenBefore(colonToken); - const firstAlternateToken = sourceCode.getTokenAfter(colonToken); - - offsets.setDesiredOffset(questionMarkToken, firstToken, 1); - offsets.setDesiredOffset(colonToken, firstToken, 1); - - offsets.setDesiredOffset(firstConsequentToken, firstToken, - options.offsetTernaryExpressions ? 2 : 1); - - /* - * The alternate and the consequent should usually have the same indentation. - * If they share part of a line, align the alternate against the first token of the consequent. - * This allows the alternate to be indented correctly in cases like this: - * foo ? ( - * bar - * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo` - * baz // as a result, `baz` is offset by 1 rather than 2 - * ) - */ - if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) { - offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0); - } else { - - /** - * If the alternate and consequent do not share part of a line, offset the alternate from the first - * token of the conditional expression. For example: - * foo ? bar - * : baz - * - * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up - * having no expected indentation. - */ - offsets.setDesiredOffset(firstAlternateToken, firstToken, - firstAlternateToken.type === "Punctuator" && - options.offsetTernaryExpressions ? 2 : 1); - } - } - }, - - "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement": node => addBlocklessNodeIndent(node.body), - - ExportNamedDeclaration(node) { - if (node.declaration === null) { - const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); - - // Indent the specifiers in `export {foo, bar, baz}` - addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1); - - if (node.source) { - - // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'` - offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1); - } - } - }, - - ForStatement(node) { - const forOpeningParen = sourceCode.getFirstToken(node, 1); - - if (node.init) { - offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1); - } - if (node.test) { - offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1); - } - if (node.update) { - offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1); - } - addBlocklessNodeIndent(node.body); - }, - - "FunctionDeclaration, FunctionExpression"(node) { - const closingParen = sourceCode.getTokenBefore(node.body); - const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters); - }, - - IfStatement(node) { - addBlocklessNodeIndent(node.consequent); - if (node.alternate && node.alternate.type !== "IfStatement") { - addBlocklessNodeIndent(node.alternate); - } - }, - - ImportDeclaration(node) { - if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) { - const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken); - const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken); - - addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration); - } - - const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from"); - const sourceToken = sourceCode.getLastToken(node, token => token.type === "String"); - const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";"); - - if (fromToken) { - const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1]; - - offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1); - } - }, - - ImportExpression(node) { - const openingParen = sourceCode.getFirstToken(node, 1); - const closingParen = sourceCode.getLastToken(node); - - parameterParens.add(openingParen); - parameterParens.add(closingParen); - offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0); - - addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments); - }, - - "MemberExpression, JSXMemberExpression, MetaProperty"(node) { - const object = node.type === "MetaProperty" ? node.meta : node.object; - const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken); - const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken); - - const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length; - const firstObjectToken = objectParenCount - ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 }) - : sourceCode.getFirstToken(object); - const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken); - const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken; - - if (node.computed) { - - // For computed MemberExpressions, match the closing bracket with the opening bracket. - offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0); - offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1); - } - - /* - * If the object ends on the same line that the property starts, match against the last token - * of the object, to ensure that the MemberExpression is not indented. - * - * Otherwise, match against the first token of the object, e.g. - * foo - * .bar - * .baz // <-- offset by 1 from `foo` - */ - const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line - ? lastObjectToken - : firstObjectToken; - - if (typeof options.MemberExpression === "number") { - - // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object. - offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression); - - /* - * For computed MemberExpressions, match the first token of the property against the opening bracket. - * Otherwise, match the first token of the property against the object. - */ - offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression); - } else { - - // If the MemberExpression option is off, ignore the dot and the first token of the property. - offsets.ignoreToken(firstNonObjectToken); - offsets.ignoreToken(secondNonObjectToken); - - // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens. - offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0); - offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0); - } - }, - - NewExpression(node) { - - // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo` - if (node.arguments.length > 0 || - astUtils.isClosingParenToken(sourceCode.getLastToken(node)) && - astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) { - addFunctionCallIndent(node); - } - }, - - Property(node) { - if (!node.shorthand && !node.method && node.kind === "init") { - const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken); - - offsets.ignoreToken(sourceCode.getTokenAfter(colon)); - } - }, - - SwitchStatement(node) { - const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken); - const closingCurly = sourceCode.getLastToken(node); - - offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase); - - if (node.cases.length) { - sourceCode.getTokensBetween( - node.cases[node.cases.length - 1], - closingCurly, - { includeComments: true, filter: astUtils.isCommentToken } - ).forEach(token => offsets.ignoreToken(token)); - } - }, - - SwitchCase(node) { - if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) { - const caseKeyword = sourceCode.getFirstToken(node); - const tokenAfterCurrentCase = sourceCode.getTokenAfter(node); - - offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1); - } - }, - - TemplateLiteral(node) { - node.expressions.forEach((expression, index) => { - const previousQuasi = node.quasis[index]; - const nextQuasi = node.quasis[index + 1]; - const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line - ? sourceCode.getFirstToken(previousQuasi) - : null; - - offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1); - offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0); - }); - }, - - VariableDeclaration(node) { - let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind) - ? options.VariableDeclarator[node.kind] - : DEFAULT_VARIABLE_INDENT; - - const firstToken = sourceCode.getFirstToken(node), - lastToken = sourceCode.getLastToken(node); - - if (options.VariableDeclarator[node.kind] === "first") { - if (node.declarations.length > 1) { - addElementListIndent( - node.declarations, - firstToken, - lastToken, - "first" - ); - return; - } - - variableIndent = DEFAULT_VARIABLE_INDENT; - } - - if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) { - - /* - * VariableDeclarator indentation is a bit different from other forms of indentation, in that the - * indentation of an opening bracket sometimes won't match that of a closing bracket. For example, - * the following indentations are correct: - * - * var foo = { - * ok: true - * }; - * - * var foo = { - * ok: true, - * }, - * bar = 1; - * - * Account for when exiting the AST (after indentations have already been set for the nodes in - * the declaration) by manually increasing the indentation level of the tokens in this declarator - * on the same line as the start of the declaration, provided that there are declarators that - * follow this one. - */ - offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true); - } else { - offsets.setDesiredOffsets(node.range, firstToken, variableIndent); - } - - if (astUtils.isSemicolonToken(lastToken)) { - offsets.ignoreToken(lastToken); - } - }, - - VariableDeclarator(node) { - if (node.init) { - const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken); - const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator); - - offsets.ignoreToken(equalOperator); - offsets.ignoreToken(tokenAfterOperator); - offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1); - offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0); - } - }, - - "JSXAttribute[value]"(node) { - const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "="); - - offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1); - }, - - JSXElement(node) { - if (node.closingElement) { - addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1); - } - }, - - JSXOpeningElement(node) { - const firstToken = sourceCode.getFirstToken(node); - let closingToken; - - if (node.selfClosing) { - closingToken = sourceCode.getLastToken(node, { skip: 1 }); - offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0); - } else { - closingToken = sourceCode.getLastToken(node); - } - offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node)); - addElementListIndent(node.attributes, firstToken, closingToken, 1); - }, - - JSXClosingElement(node) { - const firstToken = sourceCode.getFirstToken(node); - - offsets.setDesiredOffsets(node.name.range, firstToken, 1); - }, - - JSXFragment(node) { - const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment); - const firstClosingToken = sourceCode.getFirstToken(node.closingFragment); - - addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1); - }, - - JSXOpeningFragment(node) { - const firstToken = sourceCode.getFirstToken(node); - const closingToken = sourceCode.getLastToken(node); - - offsets.setDesiredOffsets(node.range, firstToken, 1); - offsets.matchOffsetOf(firstToken, closingToken); - }, - - JSXClosingFragment(node) { - const firstToken = sourceCode.getFirstToken(node); - const slashToken = sourceCode.getLastToken(node, { skip: 1 }); - const closingToken = sourceCode.getLastToken(node); - const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken; - - offsets.setDesiredOffsets(node.range, firstToken, 1); - offsets.matchOffsetOf(firstToken, tokenToMatch); - }, - - JSXExpressionContainer(node) { - const openingCurly = sourceCode.getFirstToken(node); - const closingCurly = sourceCode.getLastToken(node); - - offsets.setDesiredOffsets( - [openingCurly.range[1], closingCurly.range[0]], - openingCurly, - 1 - ); - }, - - JSXSpreadAttribute(node) { - const openingCurly = sourceCode.getFirstToken(node); - const closingCurly = sourceCode.getLastToken(node); - - offsets.setDesiredOffsets( - [openingCurly.range[1], closingCurly.range[0]], - openingCurly, - 1 - ); - }, - - "*"(node) { - const firstToken = sourceCode.getFirstToken(node); - - // Ensure that the children of every node are indented at least as much as the first token. - if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) { - offsets.setDesiredOffsets(node.range, firstToken, 0); - } - } - }; - - const listenerCallQueue = []; - - /* - * To ignore the indentation of a node: - * 1. Don't call the node's listener when entering it (if it has a listener) - * 2. Don't set any offsets against the first token of the node. - * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets. - */ - const offsetListeners = lodash.mapValues( - baseOffsetListeners, - - /* - * Offset listener calls are deferred until traversal is finished, and are called as - * part of the final `Program:exit` listener. This is necessary because a node might - * be matched by multiple selectors. - * - * Example: Suppose there is an offset listener for `Identifier`, and the user has - * specified in configuration that `MemberExpression > Identifier` should be ignored. - * Due to selector specificity rules, the `Identifier` listener will get called first. However, - * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener - * should not have been called at all. Without doing extra selector matching, we don't know - * whether the Identifier matches the `MemberExpression > Identifier` selector until the - * `MemberExpression > Identifier` listener is called. - * - * To avoid this, the `Identifier` listener isn't called until traversal finishes and all - * ignored nodes are known. - */ - listener => - node => - listenerCallQueue.push({ listener, node }) - ); - - // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set. - const ignoredNodes = new Set(); - - /** - * Ignores a node - * @param {ASTNode} node The node to ignore - * @returns {void} - */ - function addToIgnoredNodes(node) { - ignoredNodes.add(node); - ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node)); - } - - const ignoredNodeListeners = options.ignoredNodes.reduce( - (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }), - {} - ); - - /* - * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation - * at the end. - * - * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears - * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored, - * so those listeners wouldn't be called anyway. - */ - return Object.assign( - offsetListeners, - ignoredNodeListeners, - { - "*:exit"(node) { - - // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it. - if (!KNOWN_NODES.has(node.type)) { - addToIgnoredNodes(node); - } - }, - "Program:exit"() { - - // If ignoreComments option is enabled, ignore all comment tokens. - if (options.ignoreComments) { - sourceCode.getAllComments() - .forEach(comment => offsets.ignoreToken(comment)); - } - - // Invoke the queued offset listeners for the nodes that aren't ignored. - listenerCallQueue - .filter(nodeInfo => !ignoredNodes.has(nodeInfo.node)) - .forEach(nodeInfo => nodeInfo.listener(nodeInfo.node)); - - // Update the offsets for ignored nodes to prevent their child tokens from being reported. - ignoredNodes.forEach(ignoreNode); - - addParensIndent(sourceCode.ast.tokens); - - /* - * Create a Map from (tokenOrComment) => (precedingToken). - * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly. - */ - const precedingTokens = sourceCode.ast.comments.reduce((commentMap, comment) => { - const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); - - return commentMap.set(comment, commentMap.has(tokenOrCommentBefore) ? commentMap.get(tokenOrCommentBefore) : tokenOrCommentBefore); - }, new WeakMap()); - - sourceCode.lines.forEach((line, lineIndex) => { - const lineNumber = lineIndex + 1; - - if (!tokenInfo.firstTokensByLineNumber.has(lineNumber)) { - - // Don't check indentation on blank lines - return; - } - - const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(lineNumber); - - if (firstTokenOfLine.loc.start.line !== lineNumber) { - - // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice. - return; - } - - if (astUtils.isCommentToken(firstTokenOfLine)) { - const tokenBefore = precedingTokens.get(firstTokenOfLine); - const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0]; - const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine); - const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter); - - /* - * If a comment precedes a line that begins with a semicolon token, align to that token, i.e. - * - * let foo - * // comment - * ;(async () => {})() - */ - if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) { - offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0); - } - - // If a comment matches the expected indentation of the token immediately before or after, don't report it. - if ( - mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) || - mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter)) - ) { - return; - } - } - - // If the token matches the expected indentation, don't report it. - if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) { - return; - } - - // Otherwise, report the token/comment. - report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine)); - }); - } - } - ); - } -}; diff --git a/tools/node_modules/eslint/lib/rules/index.js b/tools/node_modules/eslint/lib/rules/index.js deleted file mode 100644 index 3cf26e51bc8392ea075fb3ec7be7a9365b778510..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/index.js +++ /dev/null @@ -1,297 +0,0 @@ -/** - * @fileoverview Collects the built-in rules into a map structure so that they can be imported all at once and without - * using the file-system directly. - * @author Peter (Somogyvari) Metz - */ - -"use strict"; - -/* eslint sort-keys: ["error", "asc"] */ - -const { LazyLoadingRuleMap } = require("./utils/lazy-loading-rule-map"); - -/** @type {Map} */ -module.exports = new LazyLoadingRuleMap(Object.entries({ - "accessor-pairs": () => require("./accessor-pairs"), - "array-bracket-newline": () => require("./array-bracket-newline"), - "array-bracket-spacing": () => require("./array-bracket-spacing"), - "array-callback-return": () => require("./array-callback-return"), - "array-element-newline": () => require("./array-element-newline"), - "arrow-body-style": () => require("./arrow-body-style"), - "arrow-parens": () => require("./arrow-parens"), - "arrow-spacing": () => require("./arrow-spacing"), - "block-scoped-var": () => require("./block-scoped-var"), - "block-spacing": () => require("./block-spacing"), - "brace-style": () => require("./brace-style"), - "callback-return": () => require("./callback-return"), - camelcase: () => require("./camelcase"), - "capitalized-comments": () => require("./capitalized-comments"), - "class-methods-use-this": () => require("./class-methods-use-this"), - "comma-dangle": () => require("./comma-dangle"), - "comma-spacing": () => require("./comma-spacing"), - "comma-style": () => require("./comma-style"), - complexity: () => require("./complexity"), - "computed-property-spacing": () => require("./computed-property-spacing"), - "consistent-return": () => require("./consistent-return"), - "consistent-this": () => require("./consistent-this"), - "constructor-super": () => require("./constructor-super"), - curly: () => require("./curly"), - "default-case": () => require("./default-case"), - "default-case-last": () => require("./default-case-last"), - "default-param-last": () => require("./default-param-last"), - "dot-location": () => require("./dot-location"), - "dot-notation": () => require("./dot-notation"), - "eol-last": () => require("./eol-last"), - eqeqeq: () => require("./eqeqeq"), - "for-direction": () => require("./for-direction"), - "func-call-spacing": () => require("./func-call-spacing"), - "func-name-matching": () => require("./func-name-matching"), - "func-names": () => require("./func-names"), - "func-style": () => require("./func-style"), - "function-call-argument-newline": () => require("./function-call-argument-newline"), - "function-paren-newline": () => require("./function-paren-newline"), - "generator-star-spacing": () => require("./generator-star-spacing"), - "getter-return": () => require("./getter-return"), - "global-require": () => require("./global-require"), - "grouped-accessor-pairs": () => require("./grouped-accessor-pairs"), - "guard-for-in": () => require("./guard-for-in"), - "handle-callback-err": () => require("./handle-callback-err"), - "id-blacklist": () => require("./id-blacklist"), - "id-denylist": () => require("./id-denylist"), - "id-length": () => require("./id-length"), - "id-match": () => require("./id-match"), - "implicit-arrow-linebreak": () => require("./implicit-arrow-linebreak"), - indent: () => require("./indent"), - "indent-legacy": () => require("./indent-legacy"), - "init-declarations": () => require("./init-declarations"), - "jsx-quotes": () => require("./jsx-quotes"), - "key-spacing": () => require("./key-spacing"), - "keyword-spacing": () => require("./keyword-spacing"), - "line-comment-position": () => require("./line-comment-position"), - "linebreak-style": () => require("./linebreak-style"), - "lines-around-comment": () => require("./lines-around-comment"), - "lines-around-directive": () => require("./lines-around-directive"), - "lines-between-class-members": () => require("./lines-between-class-members"), - "max-classes-per-file": () => require("./max-classes-per-file"), - "max-depth": () => require("./max-depth"), - "max-len": () => require("./max-len"), - "max-lines": () => require("./max-lines"), - "max-lines-per-function": () => require("./max-lines-per-function"), - "max-nested-callbacks": () => require("./max-nested-callbacks"), - "max-params": () => require("./max-params"), - "max-statements": () => require("./max-statements"), - "max-statements-per-line": () => require("./max-statements-per-line"), - "multiline-comment-style": () => require("./multiline-comment-style"), - "multiline-ternary": () => require("./multiline-ternary"), - "new-cap": () => require("./new-cap"), - "new-parens": () => require("./new-parens"), - "newline-after-var": () => require("./newline-after-var"), - "newline-before-return": () => require("./newline-before-return"), - "newline-per-chained-call": () => require("./newline-per-chained-call"), - "no-alert": () => require("./no-alert"), - "no-array-constructor": () => require("./no-array-constructor"), - "no-async-promise-executor": () => require("./no-async-promise-executor"), - "no-await-in-loop": () => require("./no-await-in-loop"), - "no-bitwise": () => require("./no-bitwise"), - "no-buffer-constructor": () => require("./no-buffer-constructor"), - "no-caller": () => require("./no-caller"), - "no-case-declarations": () => require("./no-case-declarations"), - "no-catch-shadow": () => require("./no-catch-shadow"), - "no-class-assign": () => require("./no-class-assign"), - "no-compare-neg-zero": () => require("./no-compare-neg-zero"), - "no-cond-assign": () => require("./no-cond-assign"), - "no-confusing-arrow": () => require("./no-confusing-arrow"), - "no-console": () => require("./no-console"), - "no-const-assign": () => require("./no-const-assign"), - "no-constant-condition": () => require("./no-constant-condition"), - "no-constructor-return": () => require("./no-constructor-return"), - "no-continue": () => require("./no-continue"), - "no-control-regex": () => require("./no-control-regex"), - "no-debugger": () => require("./no-debugger"), - "no-delete-var": () => require("./no-delete-var"), - "no-div-regex": () => require("./no-div-regex"), - "no-dupe-args": () => require("./no-dupe-args"), - "no-dupe-class-members": () => require("./no-dupe-class-members"), - "no-dupe-else-if": () => require("./no-dupe-else-if"), - "no-dupe-keys": () => require("./no-dupe-keys"), - "no-duplicate-case": () => require("./no-duplicate-case"), - "no-duplicate-imports": () => require("./no-duplicate-imports"), - "no-else-return": () => require("./no-else-return"), - "no-empty": () => require("./no-empty"), - "no-empty-character-class": () => require("./no-empty-character-class"), - "no-empty-function": () => require("./no-empty-function"), - "no-empty-pattern": () => require("./no-empty-pattern"), - "no-eq-null": () => require("./no-eq-null"), - "no-eval": () => require("./no-eval"), - "no-ex-assign": () => require("./no-ex-assign"), - "no-extend-native": () => require("./no-extend-native"), - "no-extra-bind": () => require("./no-extra-bind"), - "no-extra-boolean-cast": () => require("./no-extra-boolean-cast"), - "no-extra-label": () => require("./no-extra-label"), - "no-extra-parens": () => require("./no-extra-parens"), - "no-extra-semi": () => require("./no-extra-semi"), - "no-fallthrough": () => require("./no-fallthrough"), - "no-floating-decimal": () => require("./no-floating-decimal"), - "no-func-assign": () => require("./no-func-assign"), - "no-global-assign": () => require("./no-global-assign"), - "no-implicit-coercion": () => require("./no-implicit-coercion"), - "no-implicit-globals": () => require("./no-implicit-globals"), - "no-implied-eval": () => require("./no-implied-eval"), - "no-import-assign": () => require("./no-import-assign"), - "no-inline-comments": () => require("./no-inline-comments"), - "no-inner-declarations": () => require("./no-inner-declarations"), - "no-invalid-regexp": () => require("./no-invalid-regexp"), - "no-invalid-this": () => require("./no-invalid-this"), - "no-irregular-whitespace": () => require("./no-irregular-whitespace"), - "no-iterator": () => require("./no-iterator"), - "no-label-var": () => require("./no-label-var"), - "no-labels": () => require("./no-labels"), - "no-lone-blocks": () => require("./no-lone-blocks"), - "no-lonely-if": () => require("./no-lonely-if"), - "no-loop-func": () => require("./no-loop-func"), - "no-loss-of-precision": () => require("./no-loss-of-precision"), - "no-magic-numbers": () => require("./no-magic-numbers"), - "no-misleading-character-class": () => require("./no-misleading-character-class"), - "no-mixed-operators": () => require("./no-mixed-operators"), - "no-mixed-requires": () => require("./no-mixed-requires"), - "no-mixed-spaces-and-tabs": () => require("./no-mixed-spaces-and-tabs"), - "no-multi-assign": () => require("./no-multi-assign"), - "no-multi-spaces": () => require("./no-multi-spaces"), - "no-multi-str": () => require("./no-multi-str"), - "no-multiple-empty-lines": () => require("./no-multiple-empty-lines"), - "no-native-reassign": () => require("./no-native-reassign"), - "no-negated-condition": () => require("./no-negated-condition"), - "no-negated-in-lhs": () => require("./no-negated-in-lhs"), - "no-nested-ternary": () => require("./no-nested-ternary"), - "no-new": () => require("./no-new"), - "no-new-func": () => require("./no-new-func"), - "no-new-object": () => require("./no-new-object"), - "no-new-require": () => require("./no-new-require"), - "no-new-symbol": () => require("./no-new-symbol"), - "no-new-wrappers": () => require("./no-new-wrappers"), - "no-obj-calls": () => require("./no-obj-calls"), - "no-octal": () => require("./no-octal"), - "no-octal-escape": () => require("./no-octal-escape"), - "no-param-reassign": () => require("./no-param-reassign"), - "no-path-concat": () => require("./no-path-concat"), - "no-plusplus": () => require("./no-plusplus"), - "no-process-env": () => require("./no-process-env"), - "no-process-exit": () => require("./no-process-exit"), - "no-promise-executor-return": () => require("./no-promise-executor-return"), - "no-proto": () => require("./no-proto"), - "no-prototype-builtins": () => require("./no-prototype-builtins"), - "no-redeclare": () => require("./no-redeclare"), - "no-regex-spaces": () => require("./no-regex-spaces"), - "no-restricted-exports": () => require("./no-restricted-exports"), - "no-restricted-globals": () => require("./no-restricted-globals"), - "no-restricted-imports": () => require("./no-restricted-imports"), - "no-restricted-modules": () => require("./no-restricted-modules"), - "no-restricted-properties": () => require("./no-restricted-properties"), - "no-restricted-syntax": () => require("./no-restricted-syntax"), - "no-return-assign": () => require("./no-return-assign"), - "no-return-await": () => require("./no-return-await"), - "no-script-url": () => require("./no-script-url"), - "no-self-assign": () => require("./no-self-assign"), - "no-self-compare": () => require("./no-self-compare"), - "no-sequences": () => require("./no-sequences"), - "no-setter-return": () => require("./no-setter-return"), - "no-shadow": () => require("./no-shadow"), - "no-shadow-restricted-names": () => require("./no-shadow-restricted-names"), - "no-spaced-func": () => require("./no-spaced-func"), - "no-sparse-arrays": () => require("./no-sparse-arrays"), - "no-sync": () => require("./no-sync"), - "no-tabs": () => require("./no-tabs"), - "no-template-curly-in-string": () => require("./no-template-curly-in-string"), - "no-ternary": () => require("./no-ternary"), - "no-this-before-super": () => require("./no-this-before-super"), - "no-throw-literal": () => require("./no-throw-literal"), - "no-trailing-spaces": () => require("./no-trailing-spaces"), - "no-undef": () => require("./no-undef"), - "no-undef-init": () => require("./no-undef-init"), - "no-undefined": () => require("./no-undefined"), - "no-underscore-dangle": () => require("./no-underscore-dangle"), - "no-unexpected-multiline": () => require("./no-unexpected-multiline"), - "no-unmodified-loop-condition": () => require("./no-unmodified-loop-condition"), - "no-unneeded-ternary": () => require("./no-unneeded-ternary"), - "no-unreachable": () => require("./no-unreachable"), - "no-unreachable-loop": () => require("./no-unreachable-loop"), - "no-unsafe-finally": () => require("./no-unsafe-finally"), - "no-unsafe-negation": () => require("./no-unsafe-negation"), - "no-unused-expressions": () => require("./no-unused-expressions"), - "no-unused-labels": () => require("./no-unused-labels"), - "no-unused-vars": () => require("./no-unused-vars"), - "no-use-before-define": () => require("./no-use-before-define"), - "no-useless-backreference": () => require("./no-useless-backreference"), - "no-useless-call": () => require("./no-useless-call"), - "no-useless-catch": () => require("./no-useless-catch"), - "no-useless-computed-key": () => require("./no-useless-computed-key"), - "no-useless-concat": () => require("./no-useless-concat"), - "no-useless-constructor": () => require("./no-useless-constructor"), - "no-useless-escape": () => require("./no-useless-escape"), - "no-useless-rename": () => require("./no-useless-rename"), - "no-useless-return": () => require("./no-useless-return"), - "no-var": () => require("./no-var"), - "no-void": () => require("./no-void"), - "no-warning-comments": () => require("./no-warning-comments"), - "no-whitespace-before-property": () => require("./no-whitespace-before-property"), - "no-with": () => require("./no-with"), - "nonblock-statement-body-position": () => require("./nonblock-statement-body-position"), - "object-curly-newline": () => require("./object-curly-newline"), - "object-curly-spacing": () => require("./object-curly-spacing"), - "object-property-newline": () => require("./object-property-newline"), - "object-shorthand": () => require("./object-shorthand"), - "one-var": () => require("./one-var"), - "one-var-declaration-per-line": () => require("./one-var-declaration-per-line"), - "operator-assignment": () => require("./operator-assignment"), - "operator-linebreak": () => require("./operator-linebreak"), - "padded-blocks": () => require("./padded-blocks"), - "padding-line-between-statements": () => require("./padding-line-between-statements"), - "prefer-arrow-callback": () => require("./prefer-arrow-callback"), - "prefer-const": () => require("./prefer-const"), - "prefer-destructuring": () => require("./prefer-destructuring"), - "prefer-exponentiation-operator": () => require("./prefer-exponentiation-operator"), - "prefer-named-capture-group": () => require("./prefer-named-capture-group"), - "prefer-numeric-literals": () => require("./prefer-numeric-literals"), - "prefer-object-spread": () => require("./prefer-object-spread"), - "prefer-promise-reject-errors": () => require("./prefer-promise-reject-errors"), - "prefer-reflect": () => require("./prefer-reflect"), - "prefer-regex-literals": () => require("./prefer-regex-literals"), - "prefer-rest-params": () => require("./prefer-rest-params"), - "prefer-spread": () => require("./prefer-spread"), - "prefer-template": () => require("./prefer-template"), - "quote-props": () => require("./quote-props"), - quotes: () => require("./quotes"), - radix: () => require("./radix"), - "require-atomic-updates": () => require("./require-atomic-updates"), - "require-await": () => require("./require-await"), - "require-jsdoc": () => require("./require-jsdoc"), - "require-unicode-regexp": () => require("./require-unicode-regexp"), - "require-yield": () => require("./require-yield"), - "rest-spread-spacing": () => require("./rest-spread-spacing"), - semi: () => require("./semi"), - "semi-spacing": () => require("./semi-spacing"), - "semi-style": () => require("./semi-style"), - "sort-imports": () => require("./sort-imports"), - "sort-keys": () => require("./sort-keys"), - "sort-vars": () => require("./sort-vars"), - "space-before-blocks": () => require("./space-before-blocks"), - "space-before-function-paren": () => require("./space-before-function-paren"), - "space-in-parens": () => require("./space-in-parens"), - "space-infix-ops": () => require("./space-infix-ops"), - "space-unary-ops": () => require("./space-unary-ops"), - "spaced-comment": () => require("./spaced-comment"), - strict: () => require("./strict"), - "switch-colon-spacing": () => require("./switch-colon-spacing"), - "symbol-description": () => require("./symbol-description"), - "template-curly-spacing": () => require("./template-curly-spacing"), - "template-tag-spacing": () => require("./template-tag-spacing"), - "unicode-bom": () => require("./unicode-bom"), - "use-isnan": () => require("./use-isnan"), - "valid-jsdoc": () => require("./valid-jsdoc"), - "valid-typeof": () => require("./valid-typeof"), - "vars-on-top": () => require("./vars-on-top"), - "wrap-iife": () => require("./wrap-iife"), - "wrap-regex": () => require("./wrap-regex"), - "yield-star-spacing": () => require("./yield-star-spacing"), - yoda: () => require("./yoda") -})); diff --git a/tools/node_modules/eslint/lib/rules/init-declarations.js b/tools/node_modules/eslint/lib/rules/init-declarations.js deleted file mode 100644 index 6cfdf92c909155c7982fd1c1cf09234fe0090a79..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/init-declarations.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @fileoverview A rule to control the style of variable initializations. - * @author Colin Ihrig - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a for loop. - * @param {ASTNode} block A node to check. - * @returns {boolean} `true` when the node is a for loop. - */ -function isForLoop(block) { - return block.type === "ForInStatement" || - block.type === "ForOfStatement" || - block.type === "ForStatement"; -} - -/** - * Checks whether or not a given declarator node has its initializer. - * @param {ASTNode} node A declarator node to check. - * @returns {boolean} `true` when the node has its initializer. - */ -function isInitialized(node) { - const declaration = node.parent; - const block = declaration.parent; - - if (isForLoop(block)) { - if (block.type === "ForStatement") { - return block.init === declaration; - } - return block.left === declaration; - } - return Boolean(node.init); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow initialization in variable declarations", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/init-declarations" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["never"] - }, - { - type: "object", - properties: { - ignoreForLoopInit: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - messages: { - initialized: "Variable '{{idName}}' should be initialized on declaration.", - notInitialized: "Variable '{{idName}}' should not be initialized on declaration." - } - }, - - create(context) { - - const MODE_ALWAYS = "always", - MODE_NEVER = "never"; - - const mode = context.options[0] || MODE_ALWAYS; - const params = context.options[1] || {}; - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - "VariableDeclaration:exit"(node) { - - const kind = node.kind, - declarations = node.declarations; - - for (let i = 0; i < declarations.length; ++i) { - const declaration = declarations[i], - id = declaration.id, - initialized = isInitialized(declaration), - isIgnoredForLoop = params.ignoreForLoopInit && isForLoop(node.parent); - let messageId = ""; - - if (mode === MODE_ALWAYS && !initialized) { - messageId = "initialized"; - } else if (mode === MODE_NEVER && kind !== "const" && initialized && !isIgnoredForLoop) { - messageId = "notInitialized"; - } - - if (id.type === "Identifier" && messageId) { - context.report({ - node: declaration, - messageId, - data: { - idName: id.name - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/jsx-quotes.js b/tools/node_modules/eslint/lib/rules/jsx-quotes.js deleted file mode 100644 index 3b282df2f0760160a237bc33254bc9f0c3e2bbea..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/jsx-quotes.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview A rule to ensure consistent quotes used in jsx syntax. - * @author Mathias Schreck - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const QUOTE_SETTINGS = { - "prefer-double": { - quote: "\"", - description: "singlequote", - convert(str) { - return str.replace(/'/gu, "\""); - } - }, - "prefer-single": { - quote: "'", - description: "doublequote", - convert(str) { - return str.replace(/"/gu, "'"); - } - } -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the consistent use of either double or single quotes in JSX attributes", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/jsx-quotes" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["prefer-single", "prefer-double"] - } - ], - messages: { - unexpected: "Unexpected usage of {{description}}." - } - }, - - create(context) { - const quoteOption = context.options[0] || "prefer-double", - setting = QUOTE_SETTINGS[quoteOption]; - - /** - * Checks if the given string literal node uses the expected quotes - * @param {ASTNode} node A string literal node. - * @returns {boolean} Whether or not the string literal used the expected quotes. - * @public - */ - function usesExpectedQuotes(node) { - return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote); - } - - return { - JSXAttribute(node) { - const attributeValue = node.value; - - if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) { - context.report({ - node: attributeValue, - messageId: "unexpected", - data: { - description: setting.description - }, - fix(fixer) { - return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw)); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/key-spacing.js b/tools/node_modules/eslint/lib/rules/key-spacing.js deleted file mode 100644 index 57abb00b06e8a4e5df64b2a34f03ef85e0231c7e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/key-spacing.js +++ /dev/null @@ -1,670 +0,0 @@ -/** - * @fileoverview Rule to specify spacing of object literal keys and values - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a string contains a line terminator as defined in - * http://www.ecma-international.org/ecma-262/5.1/#sec-7.3 - * @param {string} str String to test. - * @returns {boolean} True if str contains a line terminator. - */ -function containsLineTerminator(str) { - return astUtils.LINEBREAK_MATCHER.test(str); -} - -/** - * Gets the last element of an array. - * @param {Array} arr An array. - * @returns {any} Last element of arr. - */ -function last(arr) { - return arr[arr.length - 1]; -} - -/** - * Checks whether a node is contained on a single line. - * @param {ASTNode} node AST Node being evaluated. - * @returns {boolean} True if the node is a single line. - */ -function isSingleLine(node) { - return (node.loc.end.line === node.loc.start.line); -} - -/** - * Checks whether the properties on a single line. - * @param {ASTNode[]} properties List of Property AST nodes. - * @returns {boolean} True if all properties is on a single line. - */ -function isSingleLineProperties(properties) { - const [firstProp] = properties, - lastProp = last(properties); - - return firstProp.loc.start.line === lastProp.loc.end.line; -} - -/** - * Initializes a single option property from the configuration with defaults for undefined values - * @param {Object} toOptions Object to be initialized - * @param {Object} fromOptions Object to be initialized from - * @returns {Object} The object with correctly initialized options and values - */ -function initOptionProperty(toOptions, fromOptions) { - toOptions.mode = fromOptions.mode || "strict"; - - // Set value of beforeColon - if (typeof fromOptions.beforeColon !== "undefined") { - toOptions.beforeColon = +fromOptions.beforeColon; - } else { - toOptions.beforeColon = 0; - } - - // Set value of afterColon - if (typeof fromOptions.afterColon !== "undefined") { - toOptions.afterColon = +fromOptions.afterColon; - } else { - toOptions.afterColon = 1; - } - - // Set align if exists - if (typeof fromOptions.align !== "undefined") { - if (typeof fromOptions.align === "object") { - toOptions.align = fromOptions.align; - } else { // "string" - toOptions.align = { - on: fromOptions.align, - mode: toOptions.mode, - beforeColon: toOptions.beforeColon, - afterColon: toOptions.afterColon - }; - } - } - - return toOptions; -} - -/** - * Initializes all the option values (singleLine, multiLine and align) from the configuration with defaults for undefined values - * @param {Object} toOptions Object to be initialized - * @param {Object} fromOptions Object to be initialized from - * @returns {Object} The object with correctly initialized options and values - */ -function initOptions(toOptions, fromOptions) { - if (typeof fromOptions.align === "object") { - - // Initialize the alignment configuration - toOptions.align = initOptionProperty({}, fromOptions.align); - toOptions.align.on = fromOptions.align.on || "colon"; - toOptions.align.mode = fromOptions.align.mode || "strict"; - - toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions)); - toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions)); - - } else { // string or undefined - toOptions.multiLine = initOptionProperty({}, (fromOptions.multiLine || fromOptions)); - toOptions.singleLine = initOptionProperty({}, (fromOptions.singleLine || fromOptions)); - - // If alignment options are defined in multiLine, pull them out into the general align configuration - if (toOptions.multiLine.align) { - toOptions.align = { - on: toOptions.multiLine.align.on, - mode: toOptions.multiLine.align.mode || toOptions.multiLine.mode, - beforeColon: toOptions.multiLine.align.beforeColon, - afterColon: toOptions.multiLine.align.afterColon - }; - } - } - - return toOptions; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing between keys and values in object literal properties", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/key-spacing" - }, - - fixable: "whitespace", - - schema: [{ - anyOf: [ - { - type: "object", - properties: { - align: { - anyOf: [ - { - enum: ["colon", "value"] - }, - { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"] - }, - on: { - enum: ["colon", "value"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - }, - mode: { - enum: ["strict", "minimum"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - singleLine: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - }, - multiLine: { - type: "object", - properties: { - align: { - anyOf: [ - { - enum: ["colon", "value"] - }, - { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"] - }, - on: { - enum: ["colon", "value"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - }, - mode: { - enum: ["strict", "minimum"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - singleLine: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - }, - multiLine: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - }, - align: { - type: "object", - properties: { - mode: { - enum: ["strict", "minimum"] - }, - on: { - enum: ["colon", "value"] - }, - beforeColon: { - type: "boolean" - }, - afterColon: { - type: "boolean" - } - }, - additionalProperties: false - } - }, - additionalProperties: false - } - ] - }], - messages: { - extraKey: "Extra space after {{computed}}key '{{key}}'.", - extraValue: "Extra space before value for {{computed}}key '{{key}}'.", - missingKey: "Missing space after {{computed}}key '{{key}}'.", - missingValue: "Missing space before value for {{computed}}key '{{key}}'." - } - }, - - create(context) { - - /** - * OPTIONS - * "key-spacing": [2, { - * beforeColon: false, - * afterColon: true, - * align: "colon" // Optional, or "value" - * } - */ - const options = context.options[0] || {}, - ruleOptions = initOptions({}, options), - multiLineOptions = ruleOptions.multiLine, - singleLineOptions = ruleOptions.singleLine, - alignmentOptions = ruleOptions.align || null; - - const sourceCode = context.getSourceCode(); - - /** - * Checks whether a property is a member of the property group it follows. - * @param {ASTNode} lastMember The last Property known to be in the group. - * @param {ASTNode} candidate The next Property that might be in the group. - * @returns {boolean} True if the candidate property is part of the group. - */ - function continuesPropertyGroup(lastMember, candidate) { - const groupEndLine = lastMember.loc.start.line, - candidateStartLine = candidate.loc.start.line; - - if (candidateStartLine - groupEndLine <= 1) { - return true; - } - - /* - * Check that the first comment is adjacent to the end of the group, the - * last comment is adjacent to the candidate property, and that successive - * comments are adjacent to each other. - */ - const leadingComments = sourceCode.getCommentsBefore(candidate); - - if ( - leadingComments.length && - leadingComments[0].loc.start.line - groupEndLine <= 1 && - candidateStartLine - last(leadingComments).loc.end.line <= 1 - ) { - for (let i = 1; i < leadingComments.length; i++) { - if (leadingComments[i].loc.start.line - leadingComments[i - 1].loc.end.line > 1) { - return false; - } - } - return true; - } - - return false; - } - - /** - * Determines if the given property is key-value property. - * @param {ASTNode} property Property node to check. - * @returns {boolean} Whether the property is a key-value property. - */ - function isKeyValueProperty(property) { - return !( - (property.method || - property.shorthand || - property.kind !== "init" || property.type !== "Property") // Could be "ExperimentalSpreadProperty" or "SpreadElement" - ); - } - - /** - * Starting from the given a node (a property.key node here) looks forward - * until it finds the last token before a colon punctuator and returns it. - * @param {ASTNode} node The node to start looking from. - * @returns {ASTNode} The last token before a colon punctuator. - */ - function getLastTokenBeforeColon(node) { - const colonToken = sourceCode.getTokenAfter(node, astUtils.isColonToken); - - return sourceCode.getTokenBefore(colonToken); - } - - /** - * Starting from the given a node (a property.key node here) looks forward - * until it finds the colon punctuator and returns it. - * @param {ASTNode} node The node to start looking from. - * @returns {ASTNode} The colon punctuator. - */ - function getNextColon(node) { - return sourceCode.getTokenAfter(node, astUtils.isColonToken); - } - - /** - * Gets an object literal property's key as the identifier name or string value. - * @param {ASTNode} property Property node whose key to retrieve. - * @returns {string} The property's key. - */ - function getKey(property) { - const key = property.key; - - if (property.computed) { - return sourceCode.getText().slice(key.range[0], key.range[1]); - } - return astUtils.getStaticPropertyName(property); - } - - /** - * Reports an appropriately-formatted error if spacing is incorrect on one - * side of the colon. - * @param {ASTNode} property Key-value pair in an object literal. - * @param {string} side Side being verified - either "key" or "value". - * @param {string} whitespace Actual whitespace string. - * @param {int} expected Expected whitespace length. - * @param {string} mode Value of the mode as "strict" or "minimum" - * @returns {void} - */ - function report(property, side, whitespace, expected, mode) { - const diff = whitespace.length - expected, - nextColon = getNextColon(property.key), - tokenBeforeColon = sourceCode.getTokenBefore(nextColon, { includeComments: true }), - tokenAfterColon = sourceCode.getTokenAfter(nextColon, { includeComments: true }), - isKeySide = side === "key", - locStart = isKeySide ? tokenBeforeColon.loc.start : tokenAfterColon.loc.start, - isExtra = diff > 0, - diffAbs = Math.abs(diff), - spaces = Array(diffAbs + 1).join(" "); - - if (( - diff && mode === "strict" || - diff < 0 && mode === "minimum" || - diff > 0 && !expected && mode === "minimum") && - !(expected && containsLineTerminator(whitespace)) - ) { - let fix; - - if (isExtra) { - let range; - - // Remove whitespace - if (isKeySide) { - range = [tokenBeforeColon.range[1], tokenBeforeColon.range[1] + diffAbs]; - } else { - range = [tokenAfterColon.range[0] - diffAbs, tokenAfterColon.range[0]]; - } - fix = function(fixer) { - return fixer.removeRange(range); - }; - } else { - - // Add whitespace - if (isKeySide) { - fix = function(fixer) { - return fixer.insertTextAfter(tokenBeforeColon, spaces); - }; - } else { - fix = function(fixer) { - return fixer.insertTextBefore(tokenAfterColon, spaces); - }; - } - } - - let messageId = ""; - - if (isExtra) { - messageId = side === "key" ? "extraKey" : "extraValue"; - } else { - messageId = side === "key" ? "missingKey" : "missingValue"; - } - - context.report({ - node: property[side], - loc: locStart, - messageId, - data: { - computed: property.computed ? "computed " : "", - key: getKey(property) - }, - fix - }); - } - } - - /** - * Gets the number of characters in a key, including quotes around string - * keys and braces around computed property keys. - * @param {ASTNode} property Property of on object literal. - * @returns {int} Width of the key. - */ - function getKeyWidth(property) { - const startToken = sourceCode.getFirstToken(property); - const endToken = getLastTokenBeforeColon(property.key); - - return endToken.range[1] - startToken.range[0]; - } - - /** - * Gets the whitespace around the colon in an object literal property. - * @param {ASTNode} property Property node from an object literal. - * @returns {Object} Whitespace before and after the property's colon. - */ - function getPropertyWhitespace(property) { - const whitespace = /(\s*):(\s*)/u.exec(sourceCode.getText().slice( - property.key.range[1], property.value.range[0] - )); - - if (whitespace) { - return { - beforeColon: whitespace[1], - afterColon: whitespace[2] - }; - } - return null; - } - - /** - * Creates groups of properties. - * @param {ASTNode} node ObjectExpression node being evaluated. - * @returns {Array.} Groups of property AST node lists. - */ - function createGroups(node) { - if (node.properties.length === 1) { - return [node.properties]; - } - - return node.properties.reduce((groups, property) => { - const currentGroup = last(groups), - prev = last(currentGroup); - - if (!prev || continuesPropertyGroup(prev, property)) { - currentGroup.push(property); - } else { - groups.push([property]); - } - - return groups; - }, [ - [] - ]); - } - - /** - * Verifies correct vertical alignment of a group of properties. - * @param {ASTNode[]} properties List of Property AST nodes. - * @returns {void} - */ - function verifyGroupAlignment(properties) { - const length = properties.length, - widths = properties.map(getKeyWidth), // Width of keys, including quotes - align = alignmentOptions.on; // "value" or "colon" - let targetWidth = Math.max(...widths), - beforeColon, afterColon, mode; - - if (alignmentOptions && length > 1) { // When aligning values within a group, use the alignment configuration. - beforeColon = alignmentOptions.beforeColon; - afterColon = alignmentOptions.afterColon; - mode = alignmentOptions.mode; - } else { - beforeColon = multiLineOptions.beforeColon; - afterColon = multiLineOptions.afterColon; - mode = alignmentOptions.mode; - } - - // Conditionally include one space before or after colon - targetWidth += (align === "colon" ? beforeColon : afterColon); - - for (let i = 0; i < length; i++) { - const property = properties[i]; - const whitespace = getPropertyWhitespace(property); - - if (whitespace) { // Object literal getters/setters lack a colon - const width = widths[i]; - - if (align === "value") { - report(property, "key", whitespace.beforeColon, beforeColon, mode); - report(property, "value", whitespace.afterColon, targetWidth - width, mode); - } else { // align = "colon" - report(property, "key", whitespace.beforeColon, targetWidth - width, mode); - report(property, "value", whitespace.afterColon, afterColon, mode); - } - } - } - } - - /** - * Verifies spacing of property conforms to specified options. - * @param {ASTNode} node Property node being evaluated. - * @param {Object} lineOptions Configured singleLine or multiLine options - * @returns {void} - */ - function verifySpacing(node, lineOptions) { - const actual = getPropertyWhitespace(node); - - if (actual) { // Object literal getters/setters lack colons - report(node, "key", actual.beforeColon, lineOptions.beforeColon, lineOptions.mode); - report(node, "value", actual.afterColon, lineOptions.afterColon, lineOptions.mode); - } - } - - /** - * Verifies spacing of each property in a list. - * @param {ASTNode[]} properties List of Property AST nodes. - * @param {Object} lineOptions Configured singleLine or multiLine options - * @returns {void} - */ - function verifyListSpacing(properties, lineOptions) { - const length = properties.length; - - for (let i = 0; i < length; i++) { - verifySpacing(properties[i], lineOptions); - } - } - - /** - * Verifies vertical alignment, taking into account groups of properties. - * @param {ASTNode} node ObjectExpression node being evaluated. - * @returns {void} - */ - function verifyAlignment(node) { - createGroups(node).forEach(group => { - const properties = group.filter(isKeyValueProperty); - - if (properties.length > 0 && isSingleLineProperties(properties)) { - verifyListSpacing(properties, multiLineOptions); - } else { - verifyGroupAlignment(properties); - } - }); - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - if (alignmentOptions) { // Verify vertical alignment - - return { - ObjectExpression(node) { - if (isSingleLine(node)) { - verifyListSpacing(node.properties.filter(isKeyValueProperty), singleLineOptions); - } else { - verifyAlignment(node); - } - } - }; - - } - - // Obey beforeColon and afterColon in each property as configured - return { - Property(node) { - verifySpacing(node, isSingleLine(node.parent) ? singleLineOptions : multiLineOptions); - } - }; - - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/keyword-spacing.js b/tools/node_modules/eslint/lib/rules/keyword-spacing.js deleted file mode 100644 index 913cf4682f903acde73b0f1075a96cbd395cdbce..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/keyword-spacing.js +++ /dev/null @@ -1,573 +0,0 @@ -/** - * @fileoverview Rule to enforce spacing before and after keywords. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"), - keywords = require("./utils/keywords"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const PREV_TOKEN = /^[)\]}>]$/u; -const NEXT_TOKEN = /^(?:[([{<~!]|\+\+?|--?)$/u; -const PREV_TOKEN_M = /^[)\]}>*]$/u; -const NEXT_TOKEN_M = /^[{*]$/u; -const TEMPLATE_OPEN_PAREN = /\$\{$/u; -const TEMPLATE_CLOSE_PAREN = /^\}/u; -const CHECK_TYPE = /^(?:JSXElement|RegularExpression|String|Template)$/u; -const KEYS = keywords.concat(["as", "async", "await", "from", "get", "let", "of", "set", "yield"]); - -// check duplications. -(function() { - KEYS.sort(); - for (let i = 1; i < KEYS.length; ++i) { - if (KEYS[i] === KEYS[i - 1]) { - throw new Error(`Duplication was found in the keyword list: ${KEYS[i]}`); - } - } -}()); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given token is a "Template" token ends with "${". - * @param {Token} token A token to check. - * @returns {boolean} `true` if the token is a "Template" token ends with "${". - */ -function isOpenParenOfTemplate(token) { - return token.type === "Template" && TEMPLATE_OPEN_PAREN.test(token.value); -} - -/** - * Checks whether or not a given token is a "Template" token starts with "}". - * @param {Token} token A token to check. - * @returns {boolean} `true` if the token is a "Template" token starts with "}". - */ -function isCloseParenOfTemplate(token) { - return token.type === "Template" && TEMPLATE_CLOSE_PAREN.test(token.value); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after keywords", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/keyword-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { type: "boolean", default: true }, - after: { type: "boolean", default: true }, - overrides: { - type: "object", - properties: KEYS.reduce((retv, key) => { - retv[key] = { - type: "object", - properties: { - before: { type: "boolean" }, - after: { type: "boolean" } - }, - additionalProperties: false - }; - return retv; - }, {}), - additionalProperties: false - } - }, - additionalProperties: false - } - ], - messages: { - expectedBefore: "Expected space(s) before \"{{value}}\".", - expectedAfter: "Expected space(s) after \"{{value}}\".", - unexpectedBefore: "Unexpected space(s) before \"{{value}}\".", - unexpectedAfter: "Unexpected space(s) after \"{{value}}\"." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Reports a given token if there are not space(s) before the token. - * @param {Token} token A token to report. - * @param {RegExp} pattern A pattern of the previous token to check. - * @returns {void} - */ - function expectSpaceBefore(token, pattern) { - const prevToken = sourceCode.getTokenBefore(token); - - if (prevToken && - (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && - !isOpenParenOfTemplate(prevToken) && - astUtils.isTokenOnSameLine(prevToken, token) && - !sourceCode.isSpaceBetweenTokens(prevToken, token) - ) { - context.report({ - loc: token.loc, - messageId: "expectedBefore", - data: token, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - } - - /** - * Reports a given token if there are space(s) before the token. - * @param {Token} token A token to report. - * @param {RegExp} pattern A pattern of the previous token to check. - * @returns {void} - */ - function unexpectSpaceBefore(token, pattern) { - const prevToken = sourceCode.getTokenBefore(token); - - if (prevToken && - (CHECK_TYPE.test(prevToken.type) || pattern.test(prevToken.value)) && - !isOpenParenOfTemplate(prevToken) && - astUtils.isTokenOnSameLine(prevToken, token) && - sourceCode.isSpaceBetweenTokens(prevToken, token) - ) { - context.report({ - loc: { start: prevToken.loc.end, end: token.loc.start }, - messageId: "unexpectedBefore", - data: token, - fix(fixer) { - return fixer.removeRange([prevToken.range[1], token.range[0]]); - } - }); - } - } - - /** - * Reports a given token if there are not space(s) after the token. - * @param {Token} token A token to report. - * @param {RegExp} pattern A pattern of the next token to check. - * @returns {void} - */ - function expectSpaceAfter(token, pattern) { - const nextToken = sourceCode.getTokenAfter(token); - - if (nextToken && - (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && - !isCloseParenOfTemplate(nextToken) && - astUtils.isTokenOnSameLine(token, nextToken) && - !sourceCode.isSpaceBetweenTokens(token, nextToken) - ) { - context.report({ - loc: token.loc, - messageId: "expectedAfter", - data: token, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - } - - /** - * Reports a given token if there are space(s) after the token. - * @param {Token} token A token to report. - * @param {RegExp} pattern A pattern of the next token to check. - * @returns {void} - */ - function unexpectSpaceAfter(token, pattern) { - const nextToken = sourceCode.getTokenAfter(token); - - if (nextToken && - (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) && - !isCloseParenOfTemplate(nextToken) && - astUtils.isTokenOnSameLine(token, nextToken) && - sourceCode.isSpaceBetweenTokens(token, nextToken) - ) { - - context.report({ - loc: { start: token.loc.end, end: nextToken.loc.start }, - messageId: "unexpectedAfter", - data: token, - fix(fixer) { - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - } - - /** - * Parses the option object and determines check methods for each keyword. - * @param {Object|undefined} options The option object to parse. - * @returns {Object} - Normalized option object. - * Keys are keywords (there are for every keyword). - * Values are instances of `{"before": function, "after": function}`. - */ - function parseOptions(options = {}) { - const before = options.before !== false; - const after = options.after !== false; - const defaultValue = { - before: before ? expectSpaceBefore : unexpectSpaceBefore, - after: after ? expectSpaceAfter : unexpectSpaceAfter - }; - const overrides = (options && options.overrides) || {}; - const retv = Object.create(null); - - for (let i = 0; i < KEYS.length; ++i) { - const key = KEYS[i]; - const override = overrides[key]; - - if (override) { - const thisBefore = ("before" in override) ? override.before : before; - const thisAfter = ("after" in override) ? override.after : after; - - retv[key] = { - before: thisBefore ? expectSpaceBefore : unexpectSpaceBefore, - after: thisAfter ? expectSpaceAfter : unexpectSpaceAfter - }; - } else { - retv[key] = defaultValue; - } - } - - return retv; - } - - const checkMethodMap = parseOptions(context.options[0]); - - /** - * Reports a given token if usage of spacing followed by the token is - * invalid. - * @param {Token} token A token to report. - * @param {RegExp} [pattern] Optional. A pattern of the previous - * token to check. - * @returns {void} - */ - function checkSpacingBefore(token, pattern) { - checkMethodMap[token.value].before(token, pattern || PREV_TOKEN); - } - - /** - * Reports a given token if usage of spacing preceded by the token is - * invalid. - * @param {Token} token A token to report. - * @param {RegExp} [pattern] Optional. A pattern of the next - * token to check. - * @returns {void} - */ - function checkSpacingAfter(token, pattern) { - checkMethodMap[token.value].after(token, pattern || NEXT_TOKEN); - } - - /** - * Reports a given token if usage of spacing around the token is invalid. - * @param {Token} token A token to report. - * @returns {void} - */ - function checkSpacingAround(token) { - checkSpacingBefore(token); - checkSpacingAfter(token); - } - - /** - * Reports the first token of a given node if the first token is a keyword - * and usage of spacing around the token is invalid. - * @param {ASTNode|null} node A node to report. - * @returns {void} - */ - function checkSpacingAroundFirstToken(node) { - const firstToken = node && sourceCode.getFirstToken(node); - - if (firstToken && firstToken.type === "Keyword") { - checkSpacingAround(firstToken); - } - } - - /** - * Reports the first token of a given node if the first token is a keyword - * and usage of spacing followed by the token is invalid. - * - * This is used for unary operators (e.g. `typeof`), `function`, and `super`. - * Other rules are handling usage of spacing preceded by those keywords. - * @param {ASTNode|null} node A node to report. - * @returns {void} - */ - function checkSpacingBeforeFirstToken(node) { - const firstToken = node && sourceCode.getFirstToken(node); - - if (firstToken && firstToken.type === "Keyword") { - checkSpacingBefore(firstToken); - } - } - - /** - * Reports the previous token of a given node if the token is a keyword and - * usage of spacing around the token is invalid. - * @param {ASTNode|null} node A node to report. - * @returns {void} - */ - function checkSpacingAroundTokenBefore(node) { - if (node) { - const token = sourceCode.getTokenBefore(node, astUtils.isKeywordToken); - - checkSpacingAround(token); - } - } - - /** - * Reports `async` or `function` keywords of a given node if usage of - * spacing around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForFunction(node) { - const firstToken = node && sourceCode.getFirstToken(node); - - if (firstToken && - ((firstToken.type === "Keyword" && firstToken.value === "function") || - firstToken.value === "async") - ) { - checkSpacingBefore(firstToken); - } - } - - /** - * Reports `class` and `extends` keywords of a given node if usage of - * spacing around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForClass(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.superClass); - } - - /** - * Reports `if` and `else` keywords of a given node if usage of spacing - * around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForIfStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.alternate); - } - - /** - * Reports `try`, `catch`, and `finally` keywords of a given node if usage - * of spacing around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForTryStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundFirstToken(node.handler); - checkSpacingAroundTokenBefore(node.finalizer); - } - - /** - * Reports `do` and `while` keywords of a given node if usage of spacing - * around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForDoWhileStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.test); - } - - /** - * Reports `for` and `in` keywords of a given node if usage of spacing - * around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForForInStatement(node) { - checkSpacingAroundFirstToken(node); - checkSpacingAroundTokenBefore(node.right); - } - - /** - * Reports `for` and `of` keywords of a given node if usage of spacing - * around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForForOfStatement(node) { - if (node.await) { - checkSpacingBefore(sourceCode.getFirstToken(node, 0)); - checkSpacingAfter(sourceCode.getFirstToken(node, 1)); - } else { - checkSpacingAroundFirstToken(node); - } - checkSpacingAround(sourceCode.getTokenBefore(node.right, astUtils.isNotOpeningParenToken)); - } - - /** - * Reports `import`, `export`, `as`, and `from` keywords of a given node if - * usage of spacing around those keywords is invalid. - * - * This rule handles the `*` token in module declarations. - * - * import*as A from "./a"; /*error Expected space(s) after "import". - * error Expected space(s) before "as". - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForModuleDeclaration(node) { - const firstToken = sourceCode.getFirstToken(node); - - checkSpacingBefore(firstToken, PREV_TOKEN_M); - checkSpacingAfter(firstToken, NEXT_TOKEN_M); - - if (node.type === "ExportDefaultDeclaration") { - checkSpacingAround(sourceCode.getTokenAfter(firstToken)); - } - - if (node.type === "ExportAllDeclaration" && node.exported) { - const asToken = sourceCode.getTokenBefore(node.exported); - - checkSpacingBefore(asToken, PREV_TOKEN_M); - } - - if (node.source) { - const fromToken = sourceCode.getTokenBefore(node.source); - - checkSpacingBefore(fromToken, PREV_TOKEN_M); - checkSpacingAfter(fromToken, NEXT_TOKEN_M); - } - } - - /** - * Reports `as` keyword of a given node if usage of spacing around this - * keyword is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForImportNamespaceSpecifier(node) { - const asToken = sourceCode.getFirstToken(node, 1); - - checkSpacingBefore(asToken, PREV_TOKEN_M); - } - - /** - * Reports `static`, `get`, and `set` keywords of a given node if usage of - * spacing around those keywords is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForProperty(node) { - if (node.static) { - checkSpacingAroundFirstToken(node); - } - if (node.kind === "get" || - node.kind === "set" || - ( - (node.method || node.type === "MethodDefinition") && - node.value.async - ) - ) { - const token = sourceCode.getTokenBefore( - node.key, - tok => { - switch (tok.value) { - case "get": - case "set": - case "async": - return true; - default: - return false; - } - } - ); - - if (!token) { - throw new Error("Failed to find token get, set, or async beside method name"); - } - - - checkSpacingAround(token); - } - } - - /** - * Reports `await` keyword of a given node if usage of spacing before - * this keyword is invalid. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function checkSpacingForAwaitExpression(node) { - checkSpacingBefore(sourceCode.getFirstToken(node)); - } - - return { - - // Statements - DebuggerStatement: checkSpacingAroundFirstToken, - WithStatement: checkSpacingAroundFirstToken, - - // Statements - Control flow - BreakStatement: checkSpacingAroundFirstToken, - ContinueStatement: checkSpacingAroundFirstToken, - ReturnStatement: checkSpacingAroundFirstToken, - ThrowStatement: checkSpacingAroundFirstToken, - TryStatement: checkSpacingForTryStatement, - - // Statements - Choice - IfStatement: checkSpacingForIfStatement, - SwitchStatement: checkSpacingAroundFirstToken, - SwitchCase: checkSpacingAroundFirstToken, - - // Statements - Loops - DoWhileStatement: checkSpacingForDoWhileStatement, - ForInStatement: checkSpacingForForInStatement, - ForOfStatement: checkSpacingForForOfStatement, - ForStatement: checkSpacingAroundFirstToken, - WhileStatement: checkSpacingAroundFirstToken, - - // Statements - Declarations - ClassDeclaration: checkSpacingForClass, - ExportNamedDeclaration: checkSpacingForModuleDeclaration, - ExportDefaultDeclaration: checkSpacingForModuleDeclaration, - ExportAllDeclaration: checkSpacingForModuleDeclaration, - FunctionDeclaration: checkSpacingForFunction, - ImportDeclaration: checkSpacingForModuleDeclaration, - VariableDeclaration: checkSpacingAroundFirstToken, - - // Expressions - ArrowFunctionExpression: checkSpacingForFunction, - AwaitExpression: checkSpacingForAwaitExpression, - ClassExpression: checkSpacingForClass, - FunctionExpression: checkSpacingForFunction, - NewExpression: checkSpacingBeforeFirstToken, - Super: checkSpacingBeforeFirstToken, - ThisExpression: checkSpacingBeforeFirstToken, - UnaryExpression: checkSpacingBeforeFirstToken, - YieldExpression: checkSpacingBeforeFirstToken, - - // Others - ImportNamespaceSpecifier: checkSpacingForImportNamespaceSpecifier, - MethodDefinition: checkSpacingForProperty, - Property: checkSpacingForProperty - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/line-comment-position.js b/tools/node_modules/eslint/lib/rules/line-comment-position.js deleted file mode 100644 index 77ee147cbec9888befe9e7e5e76f2280deadef65..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/line-comment-position.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule to enforce the position of line comments - * @author Alberto Rodríguez - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce position of line comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/line-comment-position" - }, - - schema: [ - { - oneOf: [ - { - enum: ["above", "beside"] - }, - { - type: "object", - properties: { - position: { - enum: ["above", "beside"] - }, - ignorePattern: { - type: "string" - }, - applyDefaultPatterns: { - type: "boolean" - }, - applyDefaultIgnorePatterns: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - above: "Expected comment to be above code.", - beside: "Expected comment to be beside code." - } - }, - - create(context) { - const options = context.options[0]; - - let above, - ignorePattern, - applyDefaultIgnorePatterns = true; - - if (!options || typeof options === "string") { - above = !options || options === "above"; - - } else { - above = !options.position || options.position === "above"; - ignorePattern = options.ignorePattern; - - if (Object.prototype.hasOwnProperty.call(options, "applyDefaultIgnorePatterns")) { - applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns; - } else { - applyDefaultIgnorePatterns = options.applyDefaultPatterns !== false; - } - } - - const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; - const fallThroughRegExp = /^\s*falls?\s?through/u; - const customIgnoreRegExp = new RegExp(ignorePattern, "u"); - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type === "Line").forEach(node => { - if (applyDefaultIgnorePatterns && (defaultIgnoreRegExp.test(node.value) || fallThroughRegExp.test(node.value))) { - return; - } - - if (ignorePattern && customIgnoreRegExp.test(node.value)) { - return; - } - - const previous = sourceCode.getTokenBefore(node, { includeComments: true }); - const isOnSameLine = previous && previous.loc.end.line === node.loc.start.line; - - if (above) { - if (isOnSameLine) { - context.report({ - node, - messageId: "above" - }); - } - } else { - if (!isOnSameLine) { - context.report({ - node, - messageId: "beside" - }); - } - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/linebreak-style.js b/tools/node_modules/eslint/lib/rules/linebreak-style.js deleted file mode 100644 index b3b393ead77de84984d2bdf7044ed4c0547da61a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/linebreak-style.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @fileoverview Rule to enforce a single linebreak style. - * @author Erik Mueller - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent linebreak style", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/linebreak-style" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["unix", "windows"] - } - ], - messages: { - expectedLF: "Expected linebreaks to be 'LF' but found 'CRLF'.", - expectedCRLF: "Expected linebreaks to be 'CRLF' but found 'LF'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Builds a fix function that replaces text at the specified range in the source text. - * @param {int[]} range The range to replace - * @param {string} text The text to insert. - * @returns {Function} Fixer function - * @private - */ - function createFix(range, text) { - return function(fixer) { - return fixer.replaceTextRange(range, text); - }; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: function checkForLinebreakStyle(node) { - const linebreakStyle = context.options[0] || "unix", - expectedLF = linebreakStyle === "unix", - expectedLFChars = expectedLF ? "\n" : "\r\n", - source = sourceCode.getText(), - pattern = astUtils.createGlobalLinebreakMatcher(); - let match; - - let i = 0; - - while ((match = pattern.exec(source)) !== null) { - i++; - if (match[0] === expectedLFChars) { - continue; - } - - const index = match.index; - const range = [index, index + match[0].length]; - - context.report({ - node, - loc: { - start: { - line: i, - column: sourceCode.lines[i - 1].length - }, - end: { - line: i + 1, - column: 0 - } - }, - messageId: expectedLF ? "expectedLF" : "expectedCRLF", - fix: createFix(range, expectedLFChars) - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/lines-around-comment.js b/tools/node_modules/eslint/lib/rules/lines-around-comment.js deleted file mode 100644 index 5e1b83cdd5d24c48e16614881e0fe2116e2ea0dd..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/lines-around-comment.js +++ /dev/null @@ -1,404 +0,0 @@ -/** - * @fileoverview Enforces empty lines around comments. - * @author Jamund Ferguson - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"), - astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Return an array with with any line numbers that are empty. - * @param {Array} lines An array of each line of the file. - * @returns {Array} An array of line numbers. - */ -function getEmptyLineNums(lines) { - const emptyLines = lines.map((line, i) => ({ - code: line.trim(), - num: i + 1 - })).filter(line => !line.code).map(line => line.num); - - return emptyLines; -} - -/** - * Return an array with with any line numbers that contain comments. - * @param {Array} comments An array of comment tokens. - * @returns {Array} An array of line numbers. - */ -function getCommentLineNums(comments) { - const lines = []; - - comments.forEach(token => { - const start = token.loc.start.line; - const end = token.loc.end.line; - - lines.push(start, end); - }); - return lines; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require empty lines around comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/lines-around-comment" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - beforeBlockComment: { - type: "boolean", - default: true - }, - afterBlockComment: { - type: "boolean", - default: false - }, - beforeLineComment: { - type: "boolean", - default: false - }, - afterLineComment: { - type: "boolean", - default: false - }, - allowBlockStart: { - type: "boolean", - default: false - }, - allowBlockEnd: { - type: "boolean", - default: false - }, - allowClassStart: { - type: "boolean" - }, - allowClassEnd: { - type: "boolean" - }, - allowObjectStart: { - type: "boolean" - }, - allowObjectEnd: { - type: "boolean" - }, - allowArrayStart: { - type: "boolean" - }, - allowArrayEnd: { - type: "boolean" - }, - ignorePattern: { - type: "string" - }, - applyDefaultIgnorePatterns: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - messages: { - after: "Expected line after comment.", - before: "Expected line before comment." - } - }, - - create(context) { - - const options = Object.assign({}, context.options[0]); - const ignorePattern = options.ignorePattern; - const defaultIgnoreRegExp = astUtils.COMMENTS_IGNORE_PATTERN; - const customIgnoreRegExp = new RegExp(ignorePattern, "u"); - const applyDefaultIgnorePatterns = options.applyDefaultIgnorePatterns !== false; - - options.beforeBlockComment = typeof options.beforeBlockComment !== "undefined" ? options.beforeBlockComment : true; - - const sourceCode = context.getSourceCode(); - - const lines = sourceCode.lines, - numLines = lines.length + 1, - comments = sourceCode.getAllComments(), - commentLines = getCommentLineNums(comments), - emptyLines = getEmptyLineNums(lines), - commentAndEmptyLines = commentLines.concat(emptyLines); - - /** - * Returns whether or not comments are on lines starting with or ending with code - * @param {token} token The comment token to check. - * @returns {boolean} True if the comment is not alone. - */ - function codeAroundComment(token) { - let currentToken = token; - - do { - currentToken = sourceCode.getTokenBefore(currentToken, { includeComments: true }); - } while (currentToken && astUtils.isCommentToken(currentToken)); - - if (currentToken && astUtils.isTokenOnSameLine(currentToken, token)) { - return true; - } - - currentToken = token; - do { - currentToken = sourceCode.getTokenAfter(currentToken, { includeComments: true }); - } while (currentToken && astUtils.isCommentToken(currentToken)); - - if (currentToken && astUtils.isTokenOnSameLine(token, currentToken)) { - return true; - } - - return false; - } - - /** - * Returns whether or not comments are inside a node type or not. - * @param {ASTNode} parent The Comment parent node. - * @param {string} nodeType The parent type to check against. - * @returns {boolean} True if the comment is inside nodeType. - */ - function isParentNodeType(parent, nodeType) { - return parent.type === nodeType || - (parent.body && parent.body.type === nodeType) || - (parent.consequent && parent.consequent.type === nodeType); - } - - /** - * Returns the parent node that contains the given token. - * @param {token} token The token to check. - * @returns {ASTNode} The parent node that contains the given token. - */ - function getParentNodeOfToken(token) { - return sourceCode.getNodeByRangeIndex(token.range[0]); - } - - /** - * Returns whether or not comments are at the parent start or not. - * @param {token} token The Comment token. - * @param {string} nodeType The parent type to check against. - * @returns {boolean} True if the comment is at parent start. - */ - function isCommentAtParentStart(token, nodeType) { - const parent = getParentNodeOfToken(token); - - return parent && isParentNodeType(parent, nodeType) && - token.loc.start.line - parent.loc.start.line === 1; - } - - /** - * Returns whether or not comments are at the parent end or not. - * @param {token} token The Comment token. - * @param {string} nodeType The parent type to check against. - * @returns {boolean} True if the comment is at parent end. - */ - function isCommentAtParentEnd(token, nodeType) { - const parent = getParentNodeOfToken(token); - - return parent && isParentNodeType(parent, nodeType) && - parent.loc.end.line - token.loc.end.line === 1; - } - - /** - * Returns whether or not comments are at the block start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at block start. - */ - function isCommentAtBlockStart(token) { - return isCommentAtParentStart(token, "ClassBody") || isCommentAtParentStart(token, "BlockStatement") || isCommentAtParentStart(token, "SwitchCase"); - } - - /** - * Returns whether or not comments are at the block end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at block end. - */ - function isCommentAtBlockEnd(token) { - return isCommentAtParentEnd(token, "ClassBody") || isCommentAtParentEnd(token, "BlockStatement") || isCommentAtParentEnd(token, "SwitchCase") || isCommentAtParentEnd(token, "SwitchStatement"); - } - - /** - * Returns whether or not comments are at the class start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at class start. - */ - function isCommentAtClassStart(token) { - return isCommentAtParentStart(token, "ClassBody"); - } - - /** - * Returns whether or not comments are at the class end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at class end. - */ - function isCommentAtClassEnd(token) { - return isCommentAtParentEnd(token, "ClassBody"); - } - - /** - * Returns whether or not comments are at the object start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at object start. - */ - function isCommentAtObjectStart(token) { - return isCommentAtParentStart(token, "ObjectExpression") || isCommentAtParentStart(token, "ObjectPattern"); - } - - /** - * Returns whether or not comments are at the object end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at object end. - */ - function isCommentAtObjectEnd(token) { - return isCommentAtParentEnd(token, "ObjectExpression") || isCommentAtParentEnd(token, "ObjectPattern"); - } - - /** - * Returns whether or not comments are at the array start or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at array start. - */ - function isCommentAtArrayStart(token) { - return isCommentAtParentStart(token, "ArrayExpression") || isCommentAtParentStart(token, "ArrayPattern"); - } - - /** - * Returns whether or not comments are at the array end or not. - * @param {token} token The Comment token. - * @returns {boolean} True if the comment is at array end. - */ - function isCommentAtArrayEnd(token) { - return isCommentAtParentEnd(token, "ArrayExpression") || isCommentAtParentEnd(token, "ArrayPattern"); - } - - /** - * Checks if a comment token has lines around it (ignores inline comments) - * @param {token} token The Comment token. - * @param {Object} opts Options to determine the newline. - * @param {boolean} opts.after Should have a newline after this line. - * @param {boolean} opts.before Should have a newline before this line. - * @returns {void} - */ - function checkForEmptyLine(token, opts) { - if (applyDefaultIgnorePatterns && defaultIgnoreRegExp.test(token.value)) { - return; - } - - if (ignorePattern && customIgnoreRegExp.test(token.value)) { - return; - } - - let after = opts.after, - before = opts.before; - - const prevLineNum = token.loc.start.line - 1, - nextLineNum = token.loc.end.line + 1, - commentIsNotAlone = codeAroundComment(token); - - const blockStartAllowed = options.allowBlockStart && - isCommentAtBlockStart(token) && - !(options.allowClassStart === false && - isCommentAtClassStart(token)), - blockEndAllowed = options.allowBlockEnd && isCommentAtBlockEnd(token) && !(options.allowClassEnd === false && isCommentAtClassEnd(token)), - classStartAllowed = options.allowClassStart && isCommentAtClassStart(token), - classEndAllowed = options.allowClassEnd && isCommentAtClassEnd(token), - objectStartAllowed = options.allowObjectStart && isCommentAtObjectStart(token), - objectEndAllowed = options.allowObjectEnd && isCommentAtObjectEnd(token), - arrayStartAllowed = options.allowArrayStart && isCommentAtArrayStart(token), - arrayEndAllowed = options.allowArrayEnd && isCommentAtArrayEnd(token); - - const exceptionStartAllowed = blockStartAllowed || classStartAllowed || objectStartAllowed || arrayStartAllowed; - const exceptionEndAllowed = blockEndAllowed || classEndAllowed || objectEndAllowed || arrayEndAllowed; - - // ignore top of the file and bottom of the file - if (prevLineNum < 1) { - before = false; - } - if (nextLineNum >= numLines) { - after = false; - } - - // we ignore all inline comments - if (commentIsNotAlone) { - return; - } - - const previousTokenOrComment = sourceCode.getTokenBefore(token, { includeComments: true }); - const nextTokenOrComment = sourceCode.getTokenAfter(token, { includeComments: true }); - - // check for newline before - if (!exceptionStartAllowed && before && !lodash.includes(commentAndEmptyLines, prevLineNum) && - !(astUtils.isCommentToken(previousTokenOrComment) && astUtils.isTokenOnSameLine(previousTokenOrComment, token))) { - const lineStart = token.range[0] - token.loc.start.column; - const range = [lineStart, lineStart]; - - context.report({ - node: token, - messageId: "before", - fix(fixer) { - return fixer.insertTextBeforeRange(range, "\n"); - } - }); - } - - // check for newline after - if (!exceptionEndAllowed && after && !lodash.includes(commentAndEmptyLines, nextLineNum) && - !(astUtils.isCommentToken(nextTokenOrComment) && astUtils.isTokenOnSameLine(token, nextTokenOrComment))) { - context.report({ - node: token, - messageId: "after", - fix(fixer) { - return fixer.insertTextAfter(token, "\n"); - } - }); - } - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - comments.forEach(token => { - if (token.type === "Line") { - if (options.beforeLineComment || options.afterLineComment) { - checkForEmptyLine(token, { - after: options.afterLineComment, - before: options.beforeLineComment - }); - } - } else if (token.type === "Block") { - if (options.beforeBlockComment || options.afterBlockComment) { - checkForEmptyLine(token, { - after: options.afterBlockComment, - before: options.beforeBlockComment - }); - } - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/lines-around-directive.js b/tools/node_modules/eslint/lib/rules/lines-around-directive.js deleted file mode 100644 index fb439dad6a3c7582b8f09ec717fe67fa765b37f5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/lines-around-directive.js +++ /dev/null @@ -1,201 +0,0 @@ -/** - * @fileoverview Require or disallow newlines around directives. - * @author Kai Cataldo - * @deprecated - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow newlines around directives", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/lines-around-directive" - }, - - schema: [{ - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - before: { - enum: ["always", "never"] - }, - after: { - enum: ["always", "never"] - } - }, - additionalProperties: false, - minProperties: 2 - } - ] - }], - - fixable: "whitespace", - messages: { - expected: "Expected newline {{location}} \"{{value}}\" directive.", - unexpected: "Unexpected newline {{location}} \"{{value}}\" directive." - }, - deprecated: true, - replacedBy: ["padding-line-between-statements"] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const config = context.options[0] || "always"; - const expectLineBefore = typeof config === "string" ? config : config.before; - const expectLineAfter = typeof config === "string" ? config : config.after; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if node is preceded by a blank newline. - * @param {ASTNode} node Node to check. - * @returns {boolean} Whether or not the passed in node is preceded by a blank newline. - */ - function hasNewlineBefore(node) { - const tokenBefore = sourceCode.getTokenBefore(node, { includeComments: true }); - const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0; - - return node.loc.start.line - tokenLineBefore >= 2; - } - - /** - * Gets the last token of a node that is on the same line as the rest of the node. - * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing - * semicolon on a different line. - * @param {ASTNode} node A directive node - * @returns {Token} The last token of the node on the line - */ - function getLastTokenOnLine(node) { - const lastToken = sourceCode.getLastToken(node); - const secondToLastToken = sourceCode.getTokenBefore(lastToken); - - return astUtils.isSemicolonToken(lastToken) && lastToken.loc.start.line > secondToLastToken.loc.end.line - ? secondToLastToken - : lastToken; - } - - /** - * Check if node is followed by a blank newline. - * @param {ASTNode} node Node to check. - * @returns {boolean} Whether or not the passed in node is followed by a blank newline. - */ - function hasNewlineAfter(node) { - const lastToken = getLastTokenOnLine(node); - const tokenAfter = sourceCode.getTokenAfter(lastToken, { includeComments: true }); - - return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2; - } - - /** - * Report errors for newlines around directives. - * @param {ASTNode} node Node to check. - * @param {string} location Whether the error was found before or after the directive. - * @param {boolean} expected Whether or not a newline was expected or unexpected. - * @returns {void} - */ - function reportError(node, location, expected) { - context.report({ - node, - messageId: expected ? "expected" : "unexpected", - data: { - value: node.expression.value, - location - }, - fix(fixer) { - const lastToken = getLastTokenOnLine(node); - - if (expected) { - return location === "before" ? fixer.insertTextBefore(node, "\n") : fixer.insertTextAfter(lastToken, "\n"); - } - return fixer.removeRange(location === "before" ? [node.range[0] - 1, node.range[0]] : [lastToken.range[1], lastToken.range[1] + 1]); - } - }); - } - - /** - * Check lines around directives in node - * @param {ASTNode} node node to check - * @returns {void} - */ - function checkDirectives(node) { - const directives = astUtils.getDirectivePrologue(node); - - if (!directives.length) { - return; - } - - const firstDirective = directives[0]; - const leadingComments = sourceCode.getCommentsBefore(firstDirective); - - /* - * Only check before the first directive if it is preceded by a comment or if it is at the top of - * the file and expectLineBefore is set to "never". This is to not force a newline at the top of - * the file if there are no comments as well as for compatibility with padded-blocks. - */ - if (leadingComments.length) { - if (expectLineBefore === "always" && !hasNewlineBefore(firstDirective)) { - reportError(firstDirective, "before", true); - } - - if (expectLineBefore === "never" && hasNewlineBefore(firstDirective)) { - reportError(firstDirective, "before", false); - } - } else if ( - node.type === "Program" && - expectLineBefore === "never" && - !leadingComments.length && - hasNewlineBefore(firstDirective) - ) { - reportError(firstDirective, "before", false); - } - - const lastDirective = directives[directives.length - 1]; - const statements = node.type === "Program" ? node.body : node.body.body; - - /* - * Do not check after the last directive if the body only - * contains a directive prologue and isn't followed by a comment to ensure - * this rule behaves well with padded-blocks. - */ - if (lastDirective === statements[statements.length - 1] && !lastDirective.trailingComments) { - return; - } - - if (expectLineAfter === "always" && !hasNewlineAfter(lastDirective)) { - reportError(lastDirective, "after", true); - } - - if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) { - reportError(lastDirective, "after", false); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: checkDirectives, - FunctionDeclaration: checkDirectives, - FunctionExpression: checkDirectives, - ArrowFunctionExpression: checkDirectives - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/lines-between-class-members.js b/tools/node_modules/eslint/lib/rules/lines-between-class-members.js deleted file mode 100644 index 97235303699089e20fa842051a897d33769e7bbc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/lines-between-class-members.js +++ /dev/null @@ -1,133 +0,0 @@ -/** - * @fileoverview Rule to check empty newline between class members - * @author 薛定谔的猫 - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow an empty line between class members", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/lines-between-class-members" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptAfterSingleLine: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - never: "Unexpected blank line between class members.", - always: "Expected blank line between class members." - } - }, - - create(context) { - - const options = []; - - options[0] = context.options[0] || "always"; - options[1] = context.options[1] || { exceptAfterSingleLine: false }; - - const sourceCode = context.getSourceCode(); - - /** - * Return the last token among the consecutive tokens that have no exceed max line difference in between, before the first token in the next member. - * @param {Token} prevLastToken The last token in the previous member node. - * @param {Token} nextFirstToken The first token in the next member node. - * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. - * @returns {Token} The last token among the consecutive tokens. - */ - function findLastConsecutiveTokenAfter(prevLastToken, nextFirstToken, maxLine) { - const after = sourceCode.getTokenAfter(prevLastToken, { includeComments: true }); - - if (after !== nextFirstToken && after.loc.start.line - prevLastToken.loc.end.line <= maxLine) { - return findLastConsecutiveTokenAfter(after, nextFirstToken, maxLine); - } - return prevLastToken; - } - - /** - * Return the first token among the consecutive tokens that have no exceed max line difference in between, after the last token in the previous member. - * @param {Token} nextFirstToken The first token in the next member node. - * @param {Token} prevLastToken The last token in the previous member node. - * @param {number} maxLine The maximum number of allowed line difference between consecutive tokens. - * @returns {Token} The first token among the consecutive tokens. - */ - function findFirstConsecutiveTokenBefore(nextFirstToken, prevLastToken, maxLine) { - const before = sourceCode.getTokenBefore(nextFirstToken, { includeComments: true }); - - if (before !== prevLastToken && nextFirstToken.loc.start.line - before.loc.end.line <= maxLine) { - return findFirstConsecutiveTokenBefore(before, prevLastToken, maxLine); - } - return nextFirstToken; - } - - /** - * Checks if there is a token or comment between two tokens. - * @param {Token} before The token before. - * @param {Token} after The token after. - * @returns {boolean} True if there is a token or comment between two tokens. - */ - function hasTokenOrCommentBetween(before, after) { - return sourceCode.getTokensBetween(before, after, { includeComments: true }).length !== 0; - } - - return { - ClassBody(node) { - const body = node.body; - - for (let i = 0; i < body.length - 1; i++) { - const curFirst = sourceCode.getFirstToken(body[i]); - const curLast = sourceCode.getLastToken(body[i]); - const nextFirst = sourceCode.getFirstToken(body[i + 1]); - const isMulti = !astUtils.isTokenOnSameLine(curFirst, curLast); - const skip = !isMulti && options[1].exceptAfterSingleLine; - const beforePadding = findLastConsecutiveTokenAfter(curLast, nextFirst, 1); - const afterPadding = findFirstConsecutiveTokenBefore(nextFirst, curLast, 1); - const isPadded = afterPadding.loc.start.line - beforePadding.loc.end.line > 1; - const hasTokenInPadding = hasTokenOrCommentBetween(beforePadding, afterPadding); - const curLineLastToken = findLastConsecutiveTokenAfter(curLast, nextFirst, 0); - - if ((options[0] === "always" && !skip && !isPadded) || - (options[0] === "never" && isPadded)) { - context.report({ - node: body[i + 1], - messageId: isPadded ? "never" : "always", - fix(fixer) { - if (hasTokenInPadding) { - return null; - } - return isPadded - ? fixer.replaceTextRange([beforePadding.range[1], afterPadding.range[0]], "\n") - : fixer.insertTextAfter(curLineLastToken, "\n"); - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-classes-per-file.js b/tools/node_modules/eslint/lib/rules/max-classes-per-file.js deleted file mode 100644 index bb48a546e95c6055ec2f6b0a95a5fbb68bad7504..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-classes-per-file.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Enforce a maximum number of classes per file - * @author James Garbutt - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of classes per file", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/max-classes-per-file" - }, - - schema: [ - { - type: "integer", - minimum: 1 - } - ], - - messages: { - maximumExceeded: "File has too many classes ({{ classCount }}). Maximum allowed is {{ max }}." - } - }, - create(context) { - - const maxClasses = context.options[0] || 1; - - let classCount = 0; - - return { - Program() { - classCount = 0; - }, - "Program:exit"(node) { - if (classCount > maxClasses) { - context.report({ - node, - messageId: "maximumExceeded", - data: { - classCount, - max: maxClasses - } - }); - } - }, - "ClassDeclaration, ClassExpression"() { - classCount++; - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-depth.js b/tools/node_modules/eslint/lib/rules/max-depth.js deleted file mode 100644 index 5c5296bec00b1955f2ce22679eefbf92e08d4671..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-depth.js +++ /dev/null @@ -1,154 +0,0 @@ -/** - * @fileoverview A rule to set the maximum depth block can be nested in a function. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum depth that blocks can be nested", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-depth" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0 - }, - max: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - tooDeeply: "Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const functionStack = [], - option = context.options[0]; - let maxDepth = 4; - - if ( - typeof option === "object" && - (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) - ) { - maxDepth = option.maximum || option.max; - } - if (typeof option === "number") { - maxDepth = option; - } - - /** - * When parsing a new function, store it in our function stack - * @returns {void} - * @private - */ - function startFunction() { - functionStack.push(0); - } - - /** - * When parsing is done then pop out the reference - * @returns {void} - * @private - */ - function endFunction() { - functionStack.pop(); - } - - /** - * Save the block and Evaluate the node - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function pushBlock(node) { - const len = ++functionStack[functionStack.length - 1]; - - if (len > maxDepth) { - context.report({ node, messageId: "tooDeeply", data: { depth: len, maxDepth } }); - } - } - - /** - * Pop the saved block - * @returns {void} - * @private - */ - function popBlock() { - functionStack[functionStack.length - 1]--; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - Program: startFunction, - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - - IfStatement(node) { - if (node.parent.type !== "IfStatement") { - pushBlock(node); - } - }, - SwitchStatement: pushBlock, - TryStatement: pushBlock, - DoWhileStatement: pushBlock, - WhileStatement: pushBlock, - WithStatement: pushBlock, - ForStatement: pushBlock, - ForInStatement: pushBlock, - ForOfStatement: pushBlock, - - "IfStatement:exit": popBlock, - "SwitchStatement:exit": popBlock, - "TryStatement:exit": popBlock, - "DoWhileStatement:exit": popBlock, - "WhileStatement:exit": popBlock, - "WithStatement:exit": popBlock, - "ForStatement:exit": popBlock, - "ForInStatement:exit": popBlock, - "ForOfStatement:exit": popBlock, - - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction, - "Program:exit": endFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-len.js b/tools/node_modules/eslint/lib/rules/max-len.js deleted file mode 100644 index dd76760c50504eb4dc1fd13bc8ce74bfa88a40f8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-len.js +++ /dev/null @@ -1,433 +0,0 @@ -/** - * @fileoverview Rule to check for max length on a line. - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const OPTIONS_SCHEMA = { - type: "object", - properties: { - code: { - type: "integer", - minimum: 0 - }, - comments: { - type: "integer", - minimum: 0 - }, - tabWidth: { - type: "integer", - minimum: 0 - }, - ignorePattern: { - type: "string" - }, - ignoreComments: { - type: "boolean" - }, - ignoreStrings: { - type: "boolean" - }, - ignoreUrls: { - type: "boolean" - }, - ignoreTemplateLiterals: { - type: "boolean" - }, - ignoreRegExpLiterals: { - type: "boolean" - }, - ignoreTrailingComments: { - type: "boolean" - } - }, - additionalProperties: false -}; - -const OPTIONS_OR_INTEGER_SCHEMA = { - anyOf: [ - OPTIONS_SCHEMA, - { - type: "integer", - minimum: 0 - } - ] -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce a maximum line length", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-len" - }, - - schema: [ - OPTIONS_OR_INTEGER_SCHEMA, - OPTIONS_OR_INTEGER_SCHEMA, - OPTIONS_SCHEMA - ], - messages: { - max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.", - maxComment: "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}." - } - }, - - create(context) { - - /* - * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however: - * - They're matching an entire string that we know is a URI - * - We're matching part of a string where we think there *might* be a URL - * - We're only concerned about URLs, as picking out any URI would cause - * too many false positives - * - We don't care about matching the entire URL, any small segment is fine - */ - const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u; - - const sourceCode = context.getSourceCode(); - - /** - * Computes the length of a line that may contain tabs. The width of each - * tab will be the number of spaces to the next tab stop. - * @param {string} line The line. - * @param {int} tabWidth The width of each tab stop in spaces. - * @returns {int} The computed line length. - * @private - */ - function computeLineLength(line, tabWidth) { - let extraCharacterCount = 0; - - line.replace(/\t/gu, (match, offset) => { - const totalOffset = offset + extraCharacterCount, - previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0, - spaceCount = tabWidth - previousTabStopOffset; - - extraCharacterCount += spaceCount - 1; // -1 for the replaced tab - }); - return Array.from(line).length + extraCharacterCount; - } - - // The options object must be the last option specified… - const options = Object.assign({}, context.options[context.options.length - 1]); - - // …but max code length… - if (typeof context.options[0] === "number") { - options.code = context.options[0]; - } - - // …and tabWidth can be optionally specified directly as integers. - if (typeof context.options[1] === "number") { - options.tabWidth = context.options[1]; - } - - const maxLength = typeof options.code === "number" ? options.code : 80, - tabWidth = typeof options.tabWidth === "number" ? options.tabWidth : 4, - ignoreComments = !!options.ignoreComments, - ignoreStrings = !!options.ignoreStrings, - ignoreTemplateLiterals = !!options.ignoreTemplateLiterals, - ignoreRegExpLiterals = !!options.ignoreRegExpLiterals, - ignoreTrailingComments = !!options.ignoreTrailingComments || !!options.ignoreComments, - ignoreUrls = !!options.ignoreUrls, - maxCommentLength = options.comments; - let ignorePattern = options.ignorePattern || null; - - if (ignorePattern) { - ignorePattern = new RegExp(ignorePattern, "u"); - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tells if a given comment is trailing: it starts on the current line and - * extends to or past the end of the current line. - * @param {string} line The source line we want to check for a trailing comment on - * @param {number} lineNumber The one-indexed line number for line - * @param {ASTNode} comment The comment to inspect - * @returns {boolean} If the comment is trailing on the given line - */ - function isTrailingComment(line, lineNumber, comment) { - return comment && - (comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line) && - (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length); - } - - /** - * Tells if a comment encompasses the entire line. - * @param {string} line The source line with a trailing comment - * @param {number} lineNumber The one-indexed line number this is on - * @param {ASTNode} comment The comment to remove - * @returns {boolean} If the comment covers the entire line - */ - function isFullLineComment(line, lineNumber, comment) { - const start = comment.loc.start, - end = comment.loc.end, - isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim(); - - return comment && - (start.line < lineNumber || (start.line === lineNumber && isFirstTokenOnLine)) && - (end.line > lineNumber || (end.line === lineNumber && end.column === line.length)); - } - - /** - * Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. - * @param {ASTNode} node A node to check. - * @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer. - */ - function isJSXEmptyExpressionInSingleLineContainer(node) { - if (!node || !node.parent || node.type !== "JSXEmptyExpression" || node.parent.type !== "JSXExpressionContainer") { - return false; - } - - const parent = node.parent; - - return parent.loc.start.line === parent.loc.end.line; - } - - /** - * Gets the line after the comment and any remaining trailing whitespace is - * stripped. - * @param {string} line The source line with a trailing comment - * @param {ASTNode} comment The comment to remove - * @returns {string} Line without comment and trailing whitespace - */ - function stripTrailingComment(line, comment) { - - // loc.column is zero-indexed - return line.slice(0, comment.loc.start.column).replace(/\s+$/u, ""); - } - - /** - * Ensure that an array exists at [key] on `object`, and add `value` to it. - * @param {Object} object the object to mutate - * @param {string} key the object's key - * @param {*} value the value to add - * @returns {void} - * @private - */ - function ensureArrayAndPush(object, key, value) { - if (!Array.isArray(object[key])) { - object[key] = []; - } - object[key].push(value); - } - - /** - * Retrieves an array containing all strings (" or ') in the source code. - * @returns {ASTNode[]} An array of string nodes. - */ - function getAllStrings() { - return sourceCode.ast.tokens.filter(token => (token.type === "String" || - (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute"))); - } - - /** - * Retrieves an array containing all template literals in the source code. - * @returns {ASTNode[]} An array of template literal nodes. - */ - function getAllTemplateLiterals() { - return sourceCode.ast.tokens.filter(token => token.type === "Template"); - } - - - /** - * Retrieves an array containing all RegExp literals in the source code. - * @returns {ASTNode[]} An array of RegExp literal nodes. - */ - function getAllRegExpLiterals() { - return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression"); - } - - - /** - * A reducer to group an AST node by line number, both start and end. - * @param {Object} acc the accumulator - * @param {ASTNode} node the AST node in question - * @returns {Object} the modified accumulator - * @private - */ - function groupByLineNumber(acc, node) { - for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) { - ensureArrayAndPush(acc, i, node); - } - return acc; - } - - /** - * Returns an array of all comments in the source code. - * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer, - * the element is changed with JSXExpressionContainer node. - * @returns {ASTNode[]} An array of comment nodes - */ - function getAllComments() { - const comments = []; - - sourceCode.getAllComments() - .forEach(commentNode => { - const containingNode = sourceCode.getNodeByRangeIndex(commentNode.range[0]); - - if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) { - - // push a unique node only - if (comments[comments.length - 1] !== containingNode.parent) { - comments.push(containingNode.parent); - } - } else { - comments.push(commentNode); - } - }); - - return comments; - } - - /** - * Check the program for max length - * @param {ASTNode} node Node to examine - * @returns {void} - * @private - */ - function checkProgramForMaxLength(node) { - - // split (honors line-ending) - const lines = sourceCode.lines, - - // list of comments to ignore - comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? getAllComments() : []; - - // we iterate over comments in parallel with the lines - let commentsIndex = 0; - - const strings = getAllStrings(); - const stringsByLine = strings.reduce(groupByLineNumber, {}); - - const templateLiterals = getAllTemplateLiterals(); - const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {}); - - const regExpLiterals = getAllRegExpLiterals(); - const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {}); - - lines.forEach((line, i) => { - - // i is zero-indexed, line numbers are one-indexed - const lineNumber = i + 1; - - /* - * if we're checking comment length; we need to know whether this - * line is a comment - */ - let lineIsComment = false; - let textToMeasure; - - /* - * We can short-circuit the comment checks if we're already out of - * comments to check. - */ - if (commentsIndex < comments.length) { - let comment = null; - - // iterate over comments until we find one past the current line - do { - comment = comments[++commentsIndex]; - } while (comment && comment.loc.start.line <= lineNumber); - - // and step back by one - comment = comments[--commentsIndex]; - - if (isFullLineComment(line, lineNumber, comment)) { - lineIsComment = true; - textToMeasure = line; - } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) { - textToMeasure = stripTrailingComment(line, comment); - - // ignore multiple trailing comments in the same line - let lastIndex = commentsIndex; - - while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) { - textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]); - } - } else { - textToMeasure = line; - } - } else { - textToMeasure = line; - } - if (ignorePattern && ignorePattern.test(textToMeasure) || - ignoreUrls && URL_REGEXP.test(textToMeasure) || - ignoreStrings && stringsByLine[lineNumber] || - ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] || - ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber] - ) { - - // ignore this line - return; - } - - const lineLength = computeLineLength(textToMeasure, tabWidth); - const commentLengthApplies = lineIsComment && maxCommentLength; - - if (lineIsComment && ignoreComments) { - return; - } - - const loc = { - start: { - line: lineNumber, - column: 0 - }, - end: { - line: lineNumber, - column: textToMeasure.length - } - }; - - if (commentLengthApplies) { - if (lineLength > maxCommentLength) { - context.report({ - node, - loc, - messageId: "maxComment", - data: { - lineLength, - maxCommentLength - } - }); - } - } else if (lineLength > maxLength) { - context.report({ - node, - loc, - messageId: "max", - data: { - lineLength, - maxLength - } - }); - } - }); - } - - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - Program: checkProgramForMaxLength - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-lines-per-function.js b/tools/node_modules/eslint/lib/rules/max-lines-per-function.js deleted file mode 100644 index aa423a60a1faaa3c6b1dba20cf50d47e7db4d4a9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-lines-per-function.js +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @fileoverview A rule to set the maximum number of line of code in a function. - * @author Pete Ward - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const OPTIONS_SCHEMA = { - type: "object", - properties: { - max: { - type: "integer", - minimum: 0 - }, - skipComments: { - type: "boolean" - }, - skipBlankLines: { - type: "boolean" - }, - IIFEs: { - type: "boolean" - } - }, - additionalProperties: false -}; - -const OPTIONS_OR_INTEGER_SCHEMA = { - oneOf: [ - OPTIONS_SCHEMA, - { - type: "integer", - minimum: 1 - } - ] -}; - -/** - * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values. - * @param {Array} comments An array of comment nodes. - * @returns {Map.} A map with numeric keys (source code line numbers) and comment token values. - */ -function getCommentLineNumbers(comments) { - const map = new Map(); - - comments.forEach(comment => { - for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) { - map.set(i, comment); - } - }); - return map; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of line of code in a function", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-lines-per-function" - }, - - schema: [ - OPTIONS_OR_INTEGER_SCHEMA - ], - messages: { - exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const lines = sourceCode.lines; - - const option = context.options[0]; - let maxLines = 50; - let skipComments = false; - let skipBlankLines = false; - let IIFEs = false; - - if (typeof option === "object") { - maxLines = typeof option.max === "number" ? option.max : 50; - skipComments = !!option.skipComments; - skipBlankLines = !!option.skipBlankLines; - IIFEs = !!option.IIFEs; - } else if (typeof option === "number") { - maxLines = option; - } - - const commentLineNumbers = getCommentLineNumbers(sourceCode.getAllComments()); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tells if a comment encompasses the entire line. - * @param {string} line The source line with a trailing comment - * @param {number} lineNumber The one-indexed line number this is on - * @param {ASTNode} comment The comment to remove - * @returns {boolean} If the comment covers the entire line - */ - function isFullLineComment(line, lineNumber, comment) { - const start = comment.loc.start, - end = comment.loc.end, - isFirstTokenOnLine = start.line === lineNumber && !line.slice(0, start.column).trim(), - isLastTokenOnLine = end.line === lineNumber && !line.slice(end.column).trim(); - - return comment && - (start.line < lineNumber || isFirstTokenOnLine) && - (end.line > lineNumber || isLastTokenOnLine); - } - - /** - * Identifies is a node is a FunctionExpression which is part of an IIFE - * @param {ASTNode} node Node to test - * @returns {boolean} True if it's an IIFE - */ - function isIIFE(node) { - return (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node; - } - - /** - * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property - * @param {ASTNode} node Node to test - * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property - */ - function isEmbedded(node) { - if (!node.parent) { - return false; - } - if (node !== node.parent.value) { - return false; - } - if (node.parent.type === "MethodDefinition") { - return true; - } - if (node.parent.type === "Property") { - return node.parent.method === true || node.parent.kind === "get" || node.parent.kind === "set"; - } - return false; - } - - /** - * Count the lines in the function - * @param {ASTNode} funcNode Function AST node - * @returns {void} - * @private - */ - function processFunction(funcNode) { - const node = isEmbedded(funcNode) ? funcNode.parent : funcNode; - - if (!IIFEs && isIIFE(node)) { - return; - } - let lineCount = 0; - - for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) { - const line = lines[i]; - - if (skipComments) { - if (commentLineNumbers.has(i + 1) && isFullLineComment(line, i + 1, commentLineNumbers.get(i + 1))) { - continue; - } - } - - if (skipBlankLines) { - if (line.match(/^\s*$/u)) { - continue; - } - } - - lineCount++; - } - - if (lineCount > maxLines) { - const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(funcNode)); - - context.report({ - node, - messageId: "exceed", - data: { name, lineCount, maxLines } - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: processFunction, - FunctionExpression: processFunction, - ArrowFunctionExpression: processFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-lines.js b/tools/node_modules/eslint/lib/rules/max-lines.js deleted file mode 100644 index 299377bc2dddfca2ae75ebcee5b0020ad1df4a64..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-lines.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @fileoverview enforce a maximum file length - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of lines per file", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-lines" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - max: { - type: "integer", - minimum: 0 - }, - skipComments: { - type: "boolean" - }, - skipBlankLines: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - exceed: "File has too many lines ({{actual}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - const option = context.options[0]; - let max = 300; - - if (typeof option === "object" && Object.prototype.hasOwnProperty.call(option, "max")) { - max = option.max; - } else if (typeof option === "number") { - max = option; - } - - const skipComments = option && option.skipComments; - const skipBlankLines = option && option.skipBlankLines; - - const sourceCode = context.getSourceCode(); - - /** - * Returns whether or not a token is a comment node type - * @param {Token} token The token to check - * @returns {boolean} True if the token is a comment node - */ - function isCommentNodeType(token) { - return token && (token.type === "Block" || token.type === "Line"); - } - - /** - * Returns the line numbers of a comment that don't have any code on the same line - * @param {Node} comment The comment node to check - * @returns {number[]} The line numbers - */ - function getLinesWithoutCode(comment) { - let start = comment.loc.start.line; - let end = comment.loc.end.line; - - let token; - - token = comment; - do { - token = sourceCode.getTokenBefore(token, { includeComments: true }); - } while (isCommentNodeType(token)); - - if (token && astUtils.isTokenOnSameLine(token, comment)) { - start += 1; - } - - token = comment; - do { - token = sourceCode.getTokenAfter(token, { includeComments: true }); - } while (isCommentNodeType(token)); - - if (token && astUtils.isTokenOnSameLine(comment, token)) { - end -= 1; - } - - if (start <= end) { - return lodash.range(start, end + 1); - } - return []; - } - - return { - "Program:exit"() { - let lines = sourceCode.lines.map((text, i) => ({ lineNumber: i + 1, text })); - - if (skipBlankLines) { - lines = lines.filter(l => l.text.trim() !== ""); - } - - if (skipComments) { - const comments = sourceCode.getAllComments(); - - const commentLines = lodash.flatten(comments.map(comment => getLinesWithoutCode(comment))); - - lines = lines.filter(l => !lodash.includes(commentLines, l.lineNumber)); - } - - if (lines.length > max) { - context.report({ - loc: { line: 1, column: 0 }, - messageId: "exceed", - data: { - max, - actual: lines.length - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-nested-callbacks.js b/tools/node_modules/eslint/lib/rules/max-nested-callbacks.js deleted file mode 100644 index df1baceeb412f503a81e8cd705703f057a74cf46..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-nested-callbacks.js +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @fileoverview Rule to enforce a maximum number of nested callbacks. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum depth that callbacks can be nested", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-nested-callbacks" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0 - }, - max: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - exceed: "Too many nested callbacks ({{num}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Constants - //-------------------------------------------------------------------------- - const option = context.options[0]; - let THRESHOLD = 10; - - if ( - typeof option === "object" && - (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) - ) { - THRESHOLD = option.maximum || option.max; - } else if (typeof option === "number") { - THRESHOLD = option; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const callbackStack = []; - - /** - * Checks a given function node for too many callbacks. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkFunction(node) { - const parent = node.parent; - - if (parent.type === "CallExpression") { - callbackStack.push(node); - } - - if (callbackStack.length > THRESHOLD) { - const opts = { num: callbackStack.length, max: THRESHOLD }; - - context.report({ node, messageId: "exceed", data: opts }); - } - } - - /** - * Pops the call stack. - * @returns {void} - * @private - */ - function popStack() { - callbackStack.pop(); - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - ArrowFunctionExpression: checkFunction, - "ArrowFunctionExpression:exit": popStack, - - FunctionExpression: checkFunction, - "FunctionExpression:exit": popStack - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-params.js b/tools/node_modules/eslint/lib/rules/max-params.js deleted file mode 100644 index 4eebe2d95a31e31ecf231e4a9c863a18f3404b04..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-params.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @fileoverview Rule to flag when a function has too many parameters - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of parameters in function definitions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-params" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0 - }, - max: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - } - ], - messages: { - exceed: "{{name}} has too many parameters ({{count}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0]; - let numParams = 3; - - if ( - typeof option === "object" && - (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) - ) { - numParams = option.maximum || option.max; - } - if (typeof option === "number") { - numParams = option; - } - - /** - * Checks a function to see if it has too many parameters. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkFunction(node) { - if (node.params.length > numParams) { - context.report({ - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - node, - messageId: "exceed", - data: { - name: lodash.upperFirst(astUtils.getFunctionNameWithKind(node)), - count: node.params.length, - max: numParams - } - }); - } - } - - return { - FunctionDeclaration: checkFunction, - ArrowFunctionExpression: checkFunction, - FunctionExpression: checkFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-statements-per-line.js b/tools/node_modules/eslint/lib/rules/max-statements-per-line.js deleted file mode 100644 index 5407cff3c548749991cbb9c2a0e377f61cdf6525..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-statements-per-line.js +++ /dev/null @@ -1,196 +0,0 @@ -/** - * @fileoverview Specify the maximum number of statements allowed per line. - * @author Kenneth Williams - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce a maximum number of statements allowed per line", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-statements-per-line" - }, - - schema: [ - { - type: "object", - properties: { - max: { - type: "integer", - minimum: 1, - default: 1 - } - }, - additionalProperties: false - } - ], - messages: { - exceed: "This line has {{numberOfStatementsOnThisLine}} {{statements}}. Maximum allowed is {{maxStatementsPerLine}}." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(), - options = context.options[0] || {}, - maxStatementsPerLine = typeof options.max !== "undefined" ? options.max : 1; - - let lastStatementLine = 0, - numberOfStatementsOnThisLine = 0, - firstExtraStatement; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const SINGLE_CHILD_ALLOWED = /^(?:(?:DoWhile|For|ForIn|ForOf|If|Labeled|While)Statement|Export(?:Default|Named)Declaration)$/u; - - /** - * Reports with the first extra statement, and clears it. - * @returns {void} - */ - function reportFirstExtraStatementAndClear() { - if (firstExtraStatement) { - context.report({ - node: firstExtraStatement, - messageId: "exceed", - data: { - numberOfStatementsOnThisLine, - maxStatementsPerLine, - statements: numberOfStatementsOnThisLine === 1 ? "statement" : "statements" - } - }); - } - firstExtraStatement = null; - } - - /** - * Gets the actual last token of a given node. - * @param {ASTNode} node A node to get. This is a node except EmptyStatement. - * @returns {Token} The actual last token. - */ - function getActualLastToken(node) { - return sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); - } - - /** - * Addresses a given node. - * It updates the state of this rule, then reports the node if the node violated this rule. - * @param {ASTNode} node A node to check. - * @returns {void} - */ - function enterStatement(node) { - const line = node.loc.start.line; - - /* - * Skip to allow non-block statements if this is direct child of control statements. - * `if (a) foo();` is counted as 1. - * But `if (a) foo(); else foo();` should be counted as 2. - */ - if (SINGLE_CHILD_ALLOWED.test(node.parent.type) && - node.parent.alternate !== node - ) { - return; - } - - // Update state. - if (line === lastStatementLine) { - numberOfStatementsOnThisLine += 1; - } else { - reportFirstExtraStatementAndClear(); - numberOfStatementsOnThisLine = 1; - lastStatementLine = line; - } - - // Reports if the node violated this rule. - if (numberOfStatementsOnThisLine === maxStatementsPerLine + 1) { - firstExtraStatement = firstExtraStatement || node; - } - } - - /** - * Updates the state of this rule with the end line of leaving node to check with the next statement. - * @param {ASTNode} node A node to check. - * @returns {void} - */ - function leaveStatement(node) { - const line = getActualLastToken(node).loc.end.line; - - // Update state. - if (line !== lastStatementLine) { - reportFirstExtraStatementAndClear(); - numberOfStatementsOnThisLine = 1; - lastStatementLine = line; - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - BreakStatement: enterStatement, - ClassDeclaration: enterStatement, - ContinueStatement: enterStatement, - DebuggerStatement: enterStatement, - DoWhileStatement: enterStatement, - ExpressionStatement: enterStatement, - ForInStatement: enterStatement, - ForOfStatement: enterStatement, - ForStatement: enterStatement, - FunctionDeclaration: enterStatement, - IfStatement: enterStatement, - ImportDeclaration: enterStatement, - LabeledStatement: enterStatement, - ReturnStatement: enterStatement, - SwitchStatement: enterStatement, - ThrowStatement: enterStatement, - TryStatement: enterStatement, - VariableDeclaration: enterStatement, - WhileStatement: enterStatement, - WithStatement: enterStatement, - ExportNamedDeclaration: enterStatement, - ExportDefaultDeclaration: enterStatement, - ExportAllDeclaration: enterStatement, - - "BreakStatement:exit": leaveStatement, - "ClassDeclaration:exit": leaveStatement, - "ContinueStatement:exit": leaveStatement, - "DebuggerStatement:exit": leaveStatement, - "DoWhileStatement:exit": leaveStatement, - "ExpressionStatement:exit": leaveStatement, - "ForInStatement:exit": leaveStatement, - "ForOfStatement:exit": leaveStatement, - "ForStatement:exit": leaveStatement, - "FunctionDeclaration:exit": leaveStatement, - "IfStatement:exit": leaveStatement, - "ImportDeclaration:exit": leaveStatement, - "LabeledStatement:exit": leaveStatement, - "ReturnStatement:exit": leaveStatement, - "SwitchStatement:exit": leaveStatement, - "ThrowStatement:exit": leaveStatement, - "TryStatement:exit": leaveStatement, - "VariableDeclaration:exit": leaveStatement, - "WhileStatement:exit": leaveStatement, - "WithStatement:exit": leaveStatement, - "ExportNamedDeclaration:exit": leaveStatement, - "ExportDefaultDeclaration:exit": leaveStatement, - "ExportAllDeclaration:exit": leaveStatement, - "Program:exit": reportFirstExtraStatementAndClear - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/max-statements.js b/tools/node_modules/eslint/lib/rules/max-statements.js deleted file mode 100644 index 437b393a5082f4e5d9ac8c285d1b59e45e38b58a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/max-statements.js +++ /dev/null @@ -1,175 +0,0 @@ -/** - * @fileoverview A rule to set the maximum number of statements in a function. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a maximum number of statements allowed in function blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/max-statements" - }, - - schema: [ - { - oneOf: [ - { - type: "integer", - minimum: 0 - }, - { - type: "object", - properties: { - maximum: { - type: "integer", - minimum: 0 - }, - max: { - type: "integer", - minimum: 0 - } - }, - additionalProperties: false - } - ] - }, - { - type: "object", - properties: { - ignoreTopLevelFunctions: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - messages: { - exceed: "{{name}} has too many statements ({{count}}). Maximum allowed is {{max}}." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const functionStack = [], - option = context.options[0], - ignoreTopLevelFunctions = context.options[1] && context.options[1].ignoreTopLevelFunctions || false, - topLevelFunctions = []; - let maxStatements = 10; - - if ( - typeof option === "object" && - (Object.prototype.hasOwnProperty.call(option, "maximum") || Object.prototype.hasOwnProperty.call(option, "max")) - ) { - maxStatements = option.maximum || option.max; - } else if (typeof option === "number") { - maxStatements = option; - } - - /** - * Reports a node if it has too many statements - * @param {ASTNode} node node to evaluate - * @param {int} count Number of statements in node - * @param {int} max Maximum number of statements allowed - * @returns {void} - * @private - */ - function reportIfTooManyStatements(node, count, max) { - if (count > max) { - const name = lodash.upperFirst(astUtils.getFunctionNameWithKind(node)); - - context.report({ - node, - messageId: "exceed", - data: { name, count, max } - }); - } - } - - /** - * When parsing a new function, store it in our function stack - * @returns {void} - * @private - */ - function startFunction() { - functionStack.push(0); - } - - /** - * Evaluate the node at the end of function - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function endFunction(node) { - const count = functionStack.pop(); - - if (ignoreTopLevelFunctions && functionStack.length === 0) { - topLevelFunctions.push({ node, count }); - } else { - reportIfTooManyStatements(node, count, maxStatements); - } - } - - /** - * Increment the count of the functions - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function countStatements(node) { - functionStack[functionStack.length - 1] += node.body.length; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - - BlockStatement: countStatements, - - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction, - - "Program:exit"() { - if (topLevelFunctions.length === 1) { - return; - } - - topLevelFunctions.forEach(element => { - const count = element.count; - const node = element.node; - - reportIfTooManyStatements(node, count, maxStatements); - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/multiline-comment-style.js b/tools/node_modules/eslint/lib/rules/multiline-comment-style.js deleted file mode 100644 index 9524818b8bd74dac0090253898ae26dbd67283b8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/multiline-comment-style.js +++ /dev/null @@ -1,435 +0,0 @@ -/** - * @fileoverview enforce a particular style for multiline comments - * @author Teddy Katz - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce a particular style for multiline comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/multiline-comment-style" - }, - - fixable: "whitespace", - schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }], - messages: { - expectedBlock: "Expected a block comment instead of consecutive line comments.", - expectedBareBlock: "Expected a block comment without padding stars.", - startNewline: "Expected a linebreak after '/*'.", - endNewline: "Expected a linebreak before '*/'.", - missingStar: "Expected a '*' at the start of this line.", - alignment: "Expected this line to be aligned with the start of the comment.", - expectedLines: "Expected multiple line comments instead of a block comment." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0] || "starred-block"; - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Checks if a comment line is starred. - * @param {string} line A string representing a comment line. - * @returns {boolean} Whether or not the comment line is starred. - */ - function isStarredCommentLine(line) { - return /^\s*\*/u.test(line); - } - - /** - * Checks if a comment group is in starred-block form. - * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. - * @returns {boolean} Whether or not the comment group is in starred block form. - */ - function isStarredBlockComment([firstComment]) { - if (firstComment.type !== "Block") { - return false; - } - - const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); - - // The first and last lines can only contain whitespace. - return lines.length > 0 && lines.every((line, i) => (i === 0 || i === lines.length - 1 ? /^\s*$/u : /^\s*\*/u).test(line)); - } - - /** - * Checks if a comment group is in JSDoc form. - * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment. - * @returns {boolean} Whether or not the comment group is in JSDoc form. - */ - function isJSDocComment([firstComment]) { - if (firstComment.type !== "Block") { - return false; - } - - const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); - - return /^\*\s*$/u.test(lines[0]) && - lines.slice(1, -1).every(line => /^\s* /u.test(line)) && - /^\s*$/u.test(lines[lines.length - 1]); - } - - /** - * Processes a comment group that is currently in separate-line form, calculating the offset for each line. - * @param {Token[]} commentGroup A group of comments containing multiple line comments. - * @returns {string[]} An array of the processed lines. - */ - function processSeparateLineComments(commentGroup) { - const allLinesHaveLeadingSpace = commentGroup - .map(({ value }) => value) - .filter(line => line.trim().length) - .every(line => line.startsWith(" ")); - - return commentGroup.map(({ value }) => (allLinesHaveLeadingSpace ? value.replace(/^ /u, "") : value)); - } - - /** - * Processes a comment group that is currently in starred-block form, calculating the offset for each line. - * @param {Token} comment A single block comment token in starred-block form. - * @returns {string[]} An array of the processed lines. - */ - function processStarredBlockComment(comment) { - const lines = comment.value.split(astUtils.LINEBREAK_MATCHER) - .filter((line, i, linesArr) => !(i === 0 || i === linesArr.length - 1)) - .map(line => line.replace(/^\s*$/u, "")); - const allLinesHaveLeadingSpace = lines - .map(line => line.replace(/\s*\*/u, "")) - .filter(line => line.trim().length) - .every(line => line.startsWith(" ")); - - return lines.map(line => line.replace(allLinesHaveLeadingSpace ? /\s*\* ?/u : /\s*\*/u, "")); - } - - /** - * Processes a comment group that is currently in bare-block form, calculating the offset for each line. - * @param {Token} comment A single block comment token in bare-block form. - * @returns {string[]} An array of the processed lines. - */ - function processBareBlockComment(comment) { - const lines = comment.value.split(astUtils.LINEBREAK_MATCHER).map(line => line.replace(/^\s*$/u, "")); - const leadingWhitespace = `${sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0])} `; - let offset = ""; - - /* - * Calculate the offset of the least indented line and use that as the basis for offsetting all the lines. - * The first line should not be checked because it is inline with the opening block comment delimiter. - */ - for (const [i, line] of lines.entries()) { - if (!line.trim().length || i === 0) { - continue; - } - - const [, lineOffset] = line.match(/^(\s*\*?\s*)/u); - - if (lineOffset.length < leadingWhitespace.length) { - const newOffset = leadingWhitespace.slice(lineOffset.length - leadingWhitespace.length); - - if (newOffset.length > offset.length) { - offset = newOffset; - } - } - } - - return lines.map(line => { - const match = line.match(/^(\s*\*?\s*)(.*)/u); - const [, lineOffset, lineContents] = match; - - if (lineOffset.length > leadingWhitespace.length) { - return `${lineOffset.slice(leadingWhitespace.length - (offset.length + lineOffset.length))}${lineContents}`; - } - - if (lineOffset.length < leadingWhitespace.length) { - return `${lineOffset.slice(leadingWhitespace.length)}${lineContents}`; - } - - return lineContents; - }); - } - - /** - * Gets a list of comment lines in a group, formatting leading whitespace as necessary. - * @param {Token[]} commentGroup A group of comments containing either multiple line comments or a single block comment. - * @returns {string[]} A list of comment lines. - */ - function getCommentLines(commentGroup) { - const [firstComment] = commentGroup; - - if (firstComment.type === "Line") { - return processSeparateLineComments(commentGroup); - } - - if (isStarredBlockComment(commentGroup)) { - return processStarredBlockComment(firstComment); - } - - return processBareBlockComment(firstComment); - } - - /** - * Gets the initial offset (whitespace) from the beginning of a line to a given comment token. - * @param {Token} comment The token to check. - * @returns {string} The offset from the beginning of a line to the token. - */ - function getInitialOffset(comment) { - return sourceCode.text.slice(comment.range[0] - comment.loc.start.column, comment.range[0]); - } - - /** - * Converts a comment into starred-block form - * @param {Token} firstComment The first comment of the group being converted - * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment - * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers - */ - function convertToStarredBlock(firstComment, commentLinesList) { - const initialOffset = getInitialOffset(firstComment); - - return `/*\n${commentLinesList.map(line => `${initialOffset} * ${line}`).join("\n")}\n${initialOffset} */`; - } - - /** - * Converts a comment into separate-line form - * @param {Token} firstComment The first comment of the group being converted - * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment - * @returns {string} A representation of the comment value in separate-line form - */ - function convertToSeparateLines(firstComment, commentLinesList) { - return commentLinesList.map(line => `// ${line}`).join(`\n${getInitialOffset(firstComment)}`); - } - - /** - * Converts a comment into bare-block form - * @param {Token} firstComment The first comment of the group being converted - * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment - * @returns {string} A representation of the comment value in bare-block form - */ - function convertToBlock(firstComment, commentLinesList) { - return `/* ${commentLinesList.join(`\n${getInitialOffset(firstComment)} `)} */`; - } - - /** - * Each method checks a group of comments to see if it's valid according to the given option. - * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single - * block comment or multiple line comments. - * @returns {void} - */ - const commentGroupCheckers = { - "starred-block"(commentGroup) { - const [firstComment] = commentGroup; - const commentLines = getCommentLines(commentGroup); - - if (commentLines.some(value => value.includes("*/"))) { - return; - } - - if (commentGroup.length > 1) { - context.report({ - loc: { - start: firstComment.loc.start, - end: commentGroup[commentGroup.length - 1].loc.end - }, - messageId: "expectedBlock", - fix(fixer) { - const range = [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]]; - - return commentLines.some(value => value.startsWith("/")) - ? null - : fixer.replaceTextRange(range, convertToStarredBlock(firstComment, commentLines)); - } - }); - } else { - const lines = firstComment.value.split(astUtils.LINEBREAK_MATCHER); - const expectedLeadingWhitespace = getInitialOffset(firstComment); - const expectedLinePrefix = `${expectedLeadingWhitespace} *`; - - if (!/^\*?\s*$/u.test(lines[0])) { - const start = firstComment.value.startsWith("*") ? firstComment.range[0] + 1 : firstComment.range[0]; - - context.report({ - loc: { - start: firstComment.loc.start, - end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } - }, - messageId: "startNewline", - fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`) - }); - } - - if (!/^\s*$/u.test(lines[lines.length - 1])) { - context.report({ - loc: { - start: { line: firstComment.loc.end.line, column: firstComment.loc.end.column - 2 }, - end: firstComment.loc.end - }, - messageId: "endNewline", - fix: fixer => fixer.replaceTextRange([firstComment.range[1] - 2, firstComment.range[1]], `\n${expectedLinePrefix}/`) - }); - } - - for (let lineNumber = firstComment.loc.start.line + 1; lineNumber <= firstComment.loc.end.line; lineNumber++) { - const lineText = sourceCode.lines[lineNumber - 1]; - const errorType = isStarredCommentLine(lineText) - ? "alignment" - : "missingStar"; - - if (!lineText.startsWith(expectedLinePrefix)) { - context.report({ - loc: { - start: { line: lineNumber, column: 0 }, - end: { line: lineNumber, column: lineText.length } - }, - messageId: errorType, - fix(fixer) { - const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 }); - - if (errorType === "alignment") { - const [, commentTextPrefix = ""] = lineText.match(/^(\s*\*)/u) || []; - const commentTextStartIndex = lineStartIndex + commentTextPrefix.length; - - return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], expectedLinePrefix); - } - - const [, commentTextPrefix = ""] = lineText.match(/^(\s*)/u) || []; - const commentTextStartIndex = lineStartIndex + commentTextPrefix.length; - let offset; - - for (const [idx, line] of lines.entries()) { - if (!/\S+/u.test(line)) { - continue; - } - - const lineTextToAlignWith = sourceCode.lines[firstComment.loc.start.line - 1 + idx]; - const [, prefix = "", initialOffset = ""] = lineTextToAlignWith.match(/^(\s*(?:\/?\*)?(\s*))/u) || []; - - offset = `${commentTextPrefix.slice(prefix.length)}${initialOffset}`; - - if (/^\s*\//u.test(lineText) && offset.length === 0) { - offset += " "; - } - break; - } - - return fixer.replaceTextRange([lineStartIndex, commentTextStartIndex], `${expectedLinePrefix}${offset}`); - } - }); - } - } - } - }, - "separate-lines"(commentGroup) { - const [firstComment] = commentGroup; - - if (firstComment.type !== "Block" || isJSDocComment(commentGroup)) { - return; - } - - const commentLines = getCommentLines(commentGroup); - const tokenAfter = sourceCode.getTokenAfter(firstComment, { includeComments: true }); - - if (tokenAfter && firstComment.loc.end.line === tokenAfter.loc.start.line) { - return; - } - - context.report({ - loc: { - start: firstComment.loc.start, - end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } - }, - messageId: "expectedLines", - fix(fixer) { - return fixer.replaceText(firstComment, convertToSeparateLines(firstComment, commentLines)); - } - }); - }, - "bare-block"(commentGroup) { - if (isJSDocComment(commentGroup)) { - return; - } - - const [firstComment] = commentGroup; - const commentLines = getCommentLines(commentGroup); - - // Disallows consecutive line comments in favor of using a block comment. - if (firstComment.type === "Line" && commentLines.length > 1 && - !commentLines.some(value => value.includes("*/"))) { - context.report({ - loc: { - start: firstComment.loc.start, - end: commentGroup[commentGroup.length - 1].loc.end - }, - messageId: "expectedBlock", - fix(fixer) { - return fixer.replaceTextRange( - [firstComment.range[0], commentGroup[commentGroup.length - 1].range[1]], - convertToBlock(firstComment, commentLines) - ); - } - }); - } - - // Prohibits block comments from having a * at the beginning of each line. - if (isStarredBlockComment(commentGroup)) { - context.report({ - loc: { - start: firstComment.loc.start, - end: { line: firstComment.loc.start.line, column: firstComment.loc.start.column + 2 } - }, - messageId: "expectedBareBlock", - fix(fixer) { - return fixer.replaceText(firstComment, convertToBlock(firstComment, commentLines)); - } - }); - } - } - }; - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - Program() { - return sourceCode.getAllComments() - .filter(comment => comment.type !== "Shebang") - .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value)) - .filter(comment => { - const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); - - return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line; - }) - .reduce((commentGroups, comment, index, commentList) => { - const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true }); - - if ( - comment.type === "Line" && - index && commentList[index - 1].type === "Line" && - tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 && - tokenBefore === commentList[index - 1] - ) { - commentGroups[commentGroups.length - 1].push(comment); - } else { - commentGroups.push([comment]); - } - - return commentGroups; - }, []) - .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line)) - .forEach(commentGroupCheckers[option]); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/multiline-ternary.js b/tools/node_modules/eslint/lib/rules/multiline-ternary.js deleted file mode 100644 index 6668bff4824842071fbc9a3b2e90efb20a34f25f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/multiline-ternary.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @fileoverview Enforce newlines between operands of ternary expressions - * @author Kai Cataldo - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce newlines between operands of ternary expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/multiline-ternary" - }, - - schema: [ - { - enum: ["always", "always-multiline", "never"] - } - ], - messages: { - expectedTestCons: "Expected newline between test and consequent of ternary expression.", - expectedConsAlt: "Expected newline between consequent and alternate of ternary expression.", - unexpectedTestCons: "Unexpected newline between test and consequent of ternary expression.", - unexpectedConsAlt: "Unexpected newline between consequent and alternate of ternary expression." - } - }, - - create(context) { - const option = context.options[0]; - const multiline = option !== "never"; - const allowSingleLine = option === "always-multiline"; - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ConditionalExpression(node) { - const questionToken = sourceCode.getTokenAfter(node.test, astUtils.isNotClosingParenToken); - const colonToken = sourceCode.getTokenAfter(node.consequent, astUtils.isNotClosingParenToken); - - const firstTokenOfTest = sourceCode.getFirstToken(node); - const lastTokenOfTest = sourceCode.getTokenBefore(questionToken); - const firstTokenOfConsequent = sourceCode.getTokenAfter(questionToken); - const lastTokenOfConsequent = sourceCode.getTokenBefore(colonToken); - const firstTokenOfAlternate = sourceCode.getTokenAfter(colonToken); - - const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(lastTokenOfTest, firstTokenOfConsequent); - const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(lastTokenOfConsequent, firstTokenOfAlternate); - - if (!multiline) { - if (!areTestAndConsequentOnSameLine) { - context.report({ - node: node.test, - loc: { - start: firstTokenOfTest.loc.start, - end: lastTokenOfTest.loc.end - }, - messageId: "unexpectedTestCons" - }); - } - - if (!areConsequentAndAlternateOnSameLine) { - context.report({ - node: node.consequent, - loc: { - start: firstTokenOfConsequent.loc.start, - end: lastTokenOfConsequent.loc.end - }, - messageId: "unexpectedConsAlt" - }); - } - } else { - if (allowSingleLine && node.loc.start.line === node.loc.end.line) { - return; - } - - if (areTestAndConsequentOnSameLine) { - context.report({ - node: node.test, - loc: { - start: firstTokenOfTest.loc.start, - end: lastTokenOfTest.loc.end - }, - messageId: "expectedTestCons" - }); - } - - if (areConsequentAndAlternateOnSameLine) { - context.report({ - node: node.consequent, - loc: { - start: firstTokenOfConsequent.loc.start, - end: lastTokenOfConsequent.loc.end - }, - messageId: "expectedConsAlt" - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/new-cap.js b/tools/node_modules/eslint/lib/rules/new-cap.js deleted file mode 100644 index 4249a542802de14dbc3f613ac328983542943687..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/new-cap.js +++ /dev/null @@ -1,275 +0,0 @@ -/** - * @fileoverview Rule to flag use of constructors without capital letters - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const CAPS_ALLOWED = [ - "Array", - "Boolean", - "Date", - "Error", - "Function", - "Number", - "Object", - "RegExp", - "String", - "Symbol", - "BigInt" -]; - -/** - * Ensure that if the key is provided, it must be an array. - * @param {Object} obj Object to check with `key`. - * @param {string} key Object key to check on `obj`. - * @param {*} fallback If obj[key] is not present, this will be returned. - * @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback` - */ -function checkArray(obj, key, fallback) { - - /* istanbul ignore if */ - if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) { - throw new TypeError(`${key}, if provided, must be an Array`); - } - return obj[key] || fallback; -} - -/** - * A reducer function to invert an array to an Object mapping the string form of the key, to `true`. - * @param {Object} map Accumulator object for the reduce. - * @param {string} key Object key to set to `true`. - * @returns {Object} Returns the updated Object for further reduction. - */ -function invert(map, key) { - map[key] = true; - return map; -} - -/** - * Creates an object with the cap is new exceptions as its keys and true as their values. - * @param {Object} config Rule configuration - * @returns {Object} Object with cap is new exceptions. - */ -function calculateCapIsNewExceptions(config) { - let capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED); - - if (capIsNewExceptions !== CAPS_ALLOWED) { - capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED); - } - - return capIsNewExceptions.reduce(invert, {}); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require constructor names to begin with a capital letter", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/new-cap" - }, - - schema: [ - { - type: "object", - properties: { - newIsCap: { - type: "boolean", - default: true - }, - capIsNew: { - type: "boolean", - default: true - }, - newIsCapExceptions: { - type: "array", - items: { - type: "string" - } - }, - newIsCapExceptionPattern: { - type: "string" - }, - capIsNewExceptions: { - type: "array", - items: { - type: "string" - } - }, - capIsNewExceptionPattern: { - type: "string" - }, - properties: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - messages: { - upper: "A function with a name starting with an uppercase letter should only be used as a constructor.", - lower: "A constructor name should not start with a lowercase letter." - } - }, - - create(context) { - - const config = Object.assign({}, context.options[0]); - - config.newIsCap = config.newIsCap !== false; - config.capIsNew = config.capIsNew !== false; - const skipProperties = config.properties === false; - - const newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {}); - const newIsCapExceptionPattern = config.newIsCapExceptionPattern ? new RegExp(config.newIsCapExceptionPattern, "u") : null; - - const capIsNewExceptions = calculateCapIsNewExceptions(config); - const capIsNewExceptionPattern = config.capIsNewExceptionPattern ? new RegExp(config.capIsNewExceptionPattern, "u") : null; - - const listeners = {}; - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Get exact callee name from expression - * @param {ASTNode} node CallExpression or NewExpression node - * @returns {string} name - */ - function extractNameFromExpression(node) { - return node.callee.type === "Identifier" - ? node.callee.name - : astUtils.getStaticPropertyName(node.callee) || ""; - } - - /** - * Returns the capitalization state of the string - - * Whether the first character is uppercase, lowercase, or non-alphabetic - * @param {string} str String - * @returns {string} capitalization state: "non-alpha", "lower", or "upper" - */ - function getCap(str) { - const firstChar = str.charAt(0); - - const firstCharLower = firstChar.toLowerCase(); - const firstCharUpper = firstChar.toUpperCase(); - - if (firstCharLower === firstCharUpper) { - - // char has no uppercase variant, so it's non-alphabetic - return "non-alpha"; - } - if (firstChar === firstCharLower) { - return "lower"; - } - return "upper"; - - } - - /** - * Check if capitalization is allowed for a CallExpression - * @param {Object} allowedMap Object mapping calleeName to a Boolean - * @param {ASTNode} node CallExpression node - * @param {string} calleeName Capitalized callee name from a CallExpression - * @param {Object} pattern RegExp object from options pattern - * @returns {boolean} Returns true if the callee may be capitalized - */ - function isCapAllowed(allowedMap, node, calleeName, pattern) { - const sourceText = sourceCode.getText(node.callee); - - if (allowedMap[calleeName] || allowedMap[sourceText]) { - return true; - } - - if (pattern && pattern.test(sourceText)) { - return true; - } - - const callee = astUtils.skipChainExpression(node.callee); - - if (calleeName === "UTC" && callee.type === "MemberExpression") { - - // allow if callee is Date.UTC - return callee.object.type === "Identifier" && - callee.object.name === "Date"; - } - - return skipProperties && callee.type === "MemberExpression"; - } - - /** - * Reports the given messageId for the given node. The location will be the start of the property or the callee. - * @param {ASTNode} node CallExpression or NewExpression node. - * @param {string} messageId The messageId to report. - * @returns {void} - */ - function report(node, messageId) { - let callee = astUtils.skipChainExpression(node.callee); - - if (callee.type === "MemberExpression") { - callee = callee.property; - } - - context.report({ node, loc: callee.loc, messageId }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - if (config.newIsCap) { - listeners.NewExpression = function(node) { - - const constructorName = extractNameFromExpression(node); - - if (constructorName) { - const capitalization = getCap(constructorName); - const isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName, newIsCapExceptionPattern); - - if (!isAllowed) { - report(node, "lower"); - } - } - }; - } - - if (config.capIsNew) { - listeners.CallExpression = function(node) { - - const calleeName = extractNameFromExpression(node); - - if (calleeName) { - const capitalization = getCap(calleeName); - const isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName, capIsNewExceptionPattern); - - if (!isAllowed) { - report(node, "upper"); - } - } - }; - } - - return listeners; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/new-parens.js b/tools/node_modules/eslint/lib/rules/new-parens.js deleted file mode 100644 index 405ec1b515a4d610a7806b63a36804d36049f2e9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/new-parens.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @fileoverview Rule to flag when using constructor without parentheses - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce or disallow parentheses when invoking a constructor with no arguments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/new-parens" - }, - - fixable: "code", - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "never"] - } - ], - minItems: 0, - maxItems: 1 - } - ] - }, - messages: { - missing: "Missing '()' invoking a constructor.", - unnecessary: "Unnecessary '()' invoking a constructor with no arguments." - } - }, - - create(context) { - const options = context.options; - const always = options[0] !== "never"; // Default is always - - const sourceCode = context.getSourceCode(); - - return { - NewExpression(node) { - if (node.arguments.length !== 0) { - return; // if there are arguments, there have to be parens - } - - const lastToken = sourceCode.getLastToken(node); - const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken); - - // `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens - const hasParens = hasLastParen && - astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) && - node.callee.range[1] < node.range[1]; - - if (always) { - if (!hasParens) { - context.report({ - node, - messageId: "missing", - fix: fixer => fixer.insertTextAfter(node, "()") - }); - } - } else { - if (hasParens) { - context.report({ - node, - messageId: "unnecessary", - fix: fixer => [ - fixer.remove(sourceCode.getTokenBefore(lastToken)), - fixer.remove(lastToken), - fixer.insertTextBefore(node, "("), - fixer.insertTextAfter(node, ")") - ] - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/newline-after-var.js b/tools/node_modules/eslint/lib/rules/newline-after-var.js deleted file mode 100644 index 4809d9bfc5a2daf8ae1b00c1c822df3b8316a72b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/newline-after-var.js +++ /dev/null @@ -1,255 +0,0 @@ -/** - * @fileoverview Rule to check empty newline after "var" statement - * @author Gopal Venkatesan - * @deprecated - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow an empty line after variable declarations", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/newline-after-var" - }, - schema: [ - { - enum: ["never", "always"] - } - ], - fixable: "whitespace", - messages: { - expected: "Expected blank line after variable declarations.", - unexpected: "Unexpected blank line after variable declarations." - }, - - deprecated: true, - - replacedBy: ["padding-line-between-statements"] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - // Default `mode` to "always". - const mode = context.options[0] === "never" ? "never" : "always"; - - // Cache starting and ending line numbers of comments for faster lookup - const commentEndLine = sourceCode.getAllComments().reduce((result, token) => { - result[token.loc.start.line] = token.loc.end.line; - return result; - }, {}); - - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Gets a token from the given node to compare line to the next statement. - * - * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy. - * - * - The last token is semicolon. - * - The semicolon is on a different line from the previous token of the semicolon. - * - * This behavior would address semicolon-less style code. e.g.: - * - * var foo = 1 - * - * ;(a || b).doSomething() - * @param {ASTNode} node The node to get. - * @returns {Token} The token to compare line to the next statement. - */ - function getLastToken(node) { - const lastToken = sourceCode.getLastToken(node); - - if (lastToken.type === "Punctuator" && lastToken.value === ";") { - const prevToken = sourceCode.getTokenBefore(lastToken); - - if (prevToken.loc.end.line !== lastToken.loc.start.line) { - return prevToken; - } - } - - return lastToken; - } - - /** - * Determine if provided keyword is a variable declaration - * @private - * @param {string} keyword keyword to test - * @returns {boolean} True if `keyword` is a type of var - */ - function isVar(keyword) { - return keyword === "var" || keyword === "let" || keyword === "const"; - } - - /** - * Determine if provided keyword is a variant of for specifiers - * @private - * @param {string} keyword keyword to test - * @returns {boolean} True if `keyword` is a variant of for specifier - */ - function isForTypeSpecifier(keyword) { - return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; - } - - /** - * Determine if provided keyword is an export specifiers - * @private - * @param {string} nodeType nodeType to test - * @returns {boolean} True if `nodeType` is an export specifier - */ - function isExportSpecifier(nodeType) { - return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" || - nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration"; - } - - /** - * Determine if provided node is the last of their parent block. - * @private - * @param {ASTNode} node node to test - * @returns {boolean} True if `node` is last of their parent block. - */ - function isLastNode(node) { - const token = sourceCode.getTokenAfter(node); - - return !token || (token.type === "Punctuator" && token.value === "}"); - } - - /** - * Gets the last line of a group of consecutive comments - * @param {number} commentStartLine The starting line of the group - * @returns {number} The number of the last comment line of the group - */ - function getLastCommentLineOfBlock(commentStartLine) { - const currentCommentEnd = commentEndLine[commentStartLine]; - - return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd; - } - - /** - * Determine if a token starts more than one line after a comment ends - * @param {token} token The token being checked - * @param {integer} commentStartLine The line number on which the comment starts - * @returns {boolean} True if `token` does not start immediately after a comment - */ - function hasBlankLineAfterComment(token, commentStartLine) { - return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1; - } - - /** - * Checks that a blank line exists after a variable declaration when mode is - * set to "always", or checks that there is no blank line when mode is set - * to "never" - * @private - * @param {ASTNode} node `VariableDeclaration` node to test - * @returns {void} - */ - function checkForBlankLine(node) { - - /* - * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will - * sometimes be second-last if there is a semicolon on a different line. - */ - const lastToken = getLastToken(node), - - /* - * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken - * is the last token of the node. - */ - nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node), - nextLineNum = lastToken.loc.end.line + 1; - - // Ignore if there is no following statement - if (!nextToken) { - return; - } - - // Ignore if parent of node is a for variant - if (isForTypeSpecifier(node.parent.type)) { - return; - } - - // Ignore if parent of node is an export specifier - if (isExportSpecifier(node.parent.type)) { - return; - } - - /* - * Some coding styles use multiple `var` statements, so do nothing if - * the next token is a `var` statement. - */ - if (nextToken.type === "Keyword" && isVar(nextToken.value)) { - return; - } - - // Ignore if it is last statement in a block - if (isLastNode(node)) { - return; - } - - // Next statement is not a `var`... - const noNextLineToken = nextToken.loc.start.line > nextLineNum; - const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined"); - - if (mode === "never" && noNextLineToken && !hasNextLineComment) { - context.report({ - node, - messageId: "unexpected", - data: { identifier: node.name }, - fix(fixer) { - const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER); - - return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`); - } - }); - } - - // Token on the next line, or comment without blank line - if ( - mode === "always" && ( - !noNextLineToken || - hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum) - ) - ) { - context.report({ - node, - messageId: "expected", - data: { identifier: node.name }, - fix(fixer) { - if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) { - return fixer.insertTextBefore(nextToken, "\n\n"); - } - - return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n"); - } - }); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclaration: checkForBlankLine - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/newline-before-return.js b/tools/node_modules/eslint/lib/rules/newline-before-return.js deleted file mode 100644 index 65ca32321cc823a73e484bb960c89acc71bba18d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/newline-before-return.js +++ /dev/null @@ -1,217 +0,0 @@ -/** - * @fileoverview Rule to require newlines before `return` statement - * @author Kai Cataldo - * @deprecated - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require an empty line before `return` statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/newline-before-return" - }, - - fixable: "whitespace", - schema: [], - messages: { - expected: "Expected newline before return statement." - }, - - deprecated: true, - replacedBy: ["padding-line-between-statements"] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Tests whether node is preceded by supplied tokens - * @param {ASTNode} node node to check - * @param {Array} testTokens array of tokens to test against - * @returns {boolean} Whether or not the node is preceded by one of the supplied tokens - * @private - */ - function isPrecededByTokens(node, testTokens) { - const tokenBefore = sourceCode.getTokenBefore(node); - - return testTokens.some(token => tokenBefore.value === token); - } - - /** - * Checks whether node is the first node after statement or in block - * @param {ASTNode} node node to check - * @returns {boolean} Whether or not the node is the first node after statement or in block - * @private - */ - function isFirstNode(node) { - const parentType = node.parent.type; - - if (node.parent.body) { - return Array.isArray(node.parent.body) - ? node.parent.body[0] === node - : node.parent.body === node; - } - - if (parentType === "IfStatement") { - return isPrecededByTokens(node, ["else", ")"]); - } - if (parentType === "DoWhileStatement") { - return isPrecededByTokens(node, ["do"]); - } - if (parentType === "SwitchCase") { - return isPrecededByTokens(node, [":"]); - } - return isPrecededByTokens(node, [")"]); - - } - - /** - * Returns the number of lines of comments that precede the node - * @param {ASTNode} node node to check for overlapping comments - * @param {number} lineNumTokenBefore line number of previous token, to check for overlapping comments - * @returns {number} Number of lines of comments that precede the node - * @private - */ - function calcCommentLines(node, lineNumTokenBefore) { - const comments = sourceCode.getCommentsBefore(node); - let numLinesComments = 0; - - if (!comments.length) { - return numLinesComments; - } - - comments.forEach(comment => { - numLinesComments++; - - if (comment.type === "Block") { - numLinesComments += comment.loc.end.line - comment.loc.start.line; - } - - // avoid counting lines with inline comments twice - if (comment.loc.start.line === lineNumTokenBefore) { - numLinesComments--; - } - - if (comment.loc.end.line === node.loc.start.line) { - numLinesComments--; - } - }); - - return numLinesComments; - } - - /** - * Returns the line number of the token before the node that is passed in as an argument - * @param {ASTNode} node The node to use as the start of the calculation - * @returns {number} Line number of the token before `node` - * @private - */ - function getLineNumberOfTokenBefore(node) { - const tokenBefore = sourceCode.getTokenBefore(node); - let lineNumTokenBefore; - - /** - * Global return (at the beginning of a script) is a special case. - * If there is no token before `return`, then we expect no line - * break before the return. Comments are allowed to occupy lines - * before the global return, just no blank lines. - * Setting lineNumTokenBefore to zero in that case results in the - * desired behavior. - */ - if (tokenBefore) { - lineNumTokenBefore = tokenBefore.loc.end.line; - } else { - lineNumTokenBefore = 0; // global return at beginning of script - } - - return lineNumTokenBefore; - } - - /** - * Checks whether node is preceded by a newline - * @param {ASTNode} node node to check - * @returns {boolean} Whether or not the node is preceded by a newline - * @private - */ - function hasNewlineBefore(node) { - const lineNumNode = node.loc.start.line; - const lineNumTokenBefore = getLineNumberOfTokenBefore(node); - const commentLines = calcCommentLines(node, lineNumTokenBefore); - - return (lineNumNode - lineNumTokenBefore - commentLines) > 1; - } - - /** - * Checks whether it is safe to apply a fix to a given return statement. - * - * The fix is not considered safe if the given return statement has leading comments, - * as we cannot safely determine if the newline should be added before or after the comments. - * For more information, see: https://github.com/eslint/eslint/issues/5958#issuecomment-222767211 - * @param {ASTNode} node The return statement node to check. - * @returns {boolean} `true` if it can fix the node. - * @private - */ - function canFix(node) { - const leadingComments = sourceCode.getCommentsBefore(node); - const lastLeadingComment = leadingComments[leadingComments.length - 1]; - const tokenBefore = sourceCode.getTokenBefore(node); - - if (leadingComments.length === 0) { - return true; - } - - /* - * if the last leading comment ends in the same line as the previous token and - * does not share a line with the `return` node, we can consider it safe to fix. - * Example: - * function a() { - * var b; //comment - * return; - * } - */ - if (lastLeadingComment.loc.end.line === tokenBefore.loc.end.line && - lastLeadingComment.loc.end.line !== node.loc.start.line) { - return true; - } - - return false; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ReturnStatement(node) { - if (!isFirstNode(node) && !hasNewlineBefore(node)) { - context.report({ - node, - messageId: "expected", - fix(fixer) { - if (canFix(node)) { - const tokenBefore = sourceCode.getTokenBefore(node); - const newlines = node.loc.start.line === tokenBefore.loc.end.line ? "\n\n" : "\n"; - - return fixer.insertTextBefore(node, newlines); - } - return null; - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js b/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js deleted file mode 100644 index 46c9d6c10f802d2b225d6285ea23764417da2576..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/newline-per-chained-call.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * @fileoverview Rule to ensure newline per method call when chaining calls - * @author Rajendra Patil - * @author Burak Yigit Kaya - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require a newline after each call in a method chain", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/newline-per-chained-call" - }, - - fixable: "whitespace", - - schema: [{ - type: "object", - properties: { - ignoreChainWithDepth: { - type: "integer", - minimum: 1, - maximum: 10, - default: 2 - } - }, - additionalProperties: false - }], - messages: { - expected: "Expected line break before `{{callee}}`." - } - }, - - create(context) { - - const options = context.options[0] || {}, - ignoreChainWithDepth = options.ignoreChainWithDepth || 2; - - const sourceCode = context.getSourceCode(); - - /** - * Get the prefix of a given MemberExpression node. - * If the MemberExpression node is a computed value it returns a - * left bracket. If not it returns a period. - * @param {ASTNode} node A MemberExpression node to get - * @returns {string} The prefix of the node. - */ - function getPrefix(node) { - if (node.computed) { - if (node.optional) { - return "?.["; - } - return "["; - } - if (node.optional) { - return "?."; - } - return "."; - } - - /** - * Gets the property text of a given MemberExpression node. - * If the text is multiline, this returns only the first line. - * @param {ASTNode} node A MemberExpression node to get. - * @returns {string} The property text of the node. - */ - function getPropertyText(node) { - const prefix = getPrefix(node); - const lines = sourceCode.getText(node.property).split(astUtils.LINEBREAK_MATCHER); - const suffix = node.computed && lines.length === 1 ? "]" : ""; - - return prefix + lines[0] + suffix; - } - - return { - "CallExpression:exit"(node) { - const callee = astUtils.skipChainExpression(node.callee); - - if (callee.type !== "MemberExpression") { - return; - } - - let parent = astUtils.skipChainExpression(callee.object); - let depth = 1; - - while (parent && parent.callee) { - depth += 1; - parent = astUtils.skipChainExpression(astUtils.skipChainExpression(parent.callee).object); - } - - if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) { - const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken); - - context.report({ - node: callee.property, - loc: { - start: firstTokenAfterObject.loc.start, - end: callee.loc.end - }, - messageId: "expected", - data: { - callee: getPropertyText(callee) - }, - fix(fixer) { - return fixer.insertTextBefore(firstTokenAfterObject, "\n"); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-alert.js b/tools/node_modules/eslint/lib/rules/no-alert.js deleted file mode 100644 index 702b4d2ba7cccf1ddea02bc10b4168534f0bc7e0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-alert.js +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @fileoverview Rule to flag use of alert, confirm, prompt - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { - getStaticPropertyName: getPropertyName, - getVariableByName, - skipChainExpression -} = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks if the given name is a prohibited identifier. - * @param {string} name The name to check - * @returns {boolean} Whether or not the name is prohibited. - */ -function isProhibitedIdentifier(name) { - return /^(alert|confirm|prompt)$/u.test(name); -} - -/** - * Finds the eslint-scope reference in the given scope. - * @param {Object} scope The scope to search. - * @param {ASTNode} node The identifier node. - * @returns {Reference|null} Returns the found reference or null if none were found. - */ -function findReference(scope, node) { - const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] && - reference.identifier.range[1] === node.range[1]); - - if (references.length === 1) { - return references[0]; - } - return null; -} - -/** - * Checks if the given identifier node is shadowed in the given scope. - * @param {Object} scope The current scope. - * @param {string} node The identifier node to check - * @returns {boolean} Whether or not the name is shadowed. - */ -function isShadowed(scope, node) { - const reference = findReference(scope, node); - - return reference && reference.resolved && reference.resolved.defs.length > 0; -} - -/** - * Checks if the given identifier node is a ThisExpression in the global scope or the global window property. - * @param {Object} scope The current scope. - * @param {string} node The identifier node to check - * @returns {boolean} Whether or not the node is a reference to the global object. - */ -function isGlobalThisReferenceOrGlobalWindow(scope, node) { - if (scope.type === "global" && node.type === "ThisExpression") { - return true; - } - if ( - node.type === "Identifier" && - ( - node.name === "window" || - (node.name === "globalThis" && getVariableByName(scope, "globalThis")) - ) - ) { - return !isShadowed(scope, node); - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `alert`, `confirm`, and `prompt`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-alert" - }, - - schema: [], - - messages: { - unexpected: "Unexpected {{name}}." - } - }, - - create(context) { - return { - CallExpression(node) { - const callee = skipChainExpression(node.callee), - currentScope = context.getScope(); - - // without window. - if (callee.type === "Identifier") { - const name = callee.name; - - if (!isShadowed(currentScope, callee) && isProhibitedIdentifier(callee.name)) { - context.report({ - node, - messageId: "unexpected", - data: { name } - }); - } - - } else if (callee.type === "MemberExpression" && isGlobalThisReferenceOrGlobalWindow(currentScope, callee.object)) { - const name = getPropertyName(callee); - - if (isProhibitedIdentifier(name)) { - context.report({ - node, - messageId: "unexpected", - data: { name } - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-array-constructor.js b/tools/node_modules/eslint/lib/rules/no-array-constructor.js deleted file mode 100644 index 90c6d6bbd59281a5de550ccaa3b05971ceb0ba4f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-array-constructor.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @fileoverview Disallow construction of dense arrays using the Array constructor - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `Array` constructors", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-array-constructor" - }, - - schema: [], - - messages: { - preferLiteral: "The array literal notation [] is preferable." - } - }, - - create(context) { - - /** - * Disallow construction of dense arrays using the Array constructor - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function check(node) { - if ( - node.arguments.length !== 1 && - node.callee.type === "Identifier" && - node.callee.name === "Array" - ) { - context.report({ node, messageId: "preferLiteral" }); - } - } - - return { - CallExpression: check, - NewExpression: check - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js b/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js deleted file mode 100644 index 553311e580450820d30fbf81d64764cb3be403eb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-async-promise-executor.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview disallow using an async function as a Promise executor - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow using an async function as a Promise executor", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-async-promise-executor" - }, - - fixable: null, - schema: [], - messages: { - async: "Promise executor functions should not be async." - } - }, - - create(context) { - return { - "NewExpression[callee.name='Promise'][arguments.0.async=true]"(node) { - context.report({ - node: context.getSourceCode().getFirstToken(node.arguments[0], token => token.value === "async"), - messageId: "async" - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-await-in-loop.js b/tools/node_modules/eslint/lib/rules/no-await-in-loop.js deleted file mode 100644 index 9ca89866a6e114aa7c8238530653195c9e018b4e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-await-in-loop.js +++ /dev/null @@ -1,106 +0,0 @@ -/** - * @fileoverview Rule to disallow uses of await inside of loops. - * @author Nat Mote (nmote) - */ -"use strict"; - -/** - * Check whether it should stop traversing ancestors at the given node. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if it should stop traversing. - */ -function isBoundary(node) { - const t = node.type; - - return ( - t === "FunctionDeclaration" || - t === "FunctionExpression" || - t === "ArrowFunctionExpression" || - - /* - * Don't report the await expressions on for-await-of loop since it's - * asynchronous iteration intentionally. - */ - (t === "ForOfStatement" && node.await === true) - ); -} - -/** - * Check whether the given node is in loop. - * @param {ASTNode} node A node to check. - * @param {ASTNode} parent A parent node to check. - * @returns {boolean} `true` if the node is in loop. - */ -function isLooped(node, parent) { - switch (parent.type) { - case "ForStatement": - return ( - node === parent.test || - node === parent.update || - node === parent.body - ); - - case "ForOfStatement": - case "ForInStatement": - return node === parent.body; - - case "WhileStatement": - case "DoWhileStatement": - return node === parent.test || node === parent.body; - - default: - return false; - } -} - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow `await` inside of loops", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-await-in-loop" - }, - - schema: [], - - messages: { - unexpectedAwait: "Unexpected `await` inside a loop." - } - }, - create(context) { - - /** - * Validate an await expression. - * @param {ASTNode} awaitNode An AwaitExpression or ForOfStatement node to validate. - * @returns {void} - */ - function validate(awaitNode) { - if (awaitNode.type === "ForOfStatement" && !awaitNode.await) { - return; - } - - let node = awaitNode; - let parent = node.parent; - - while (parent && !isBoundary(parent)) { - if (isLooped(node, parent)) { - context.report({ - node: awaitNode, - messageId: "unexpectedAwait" - }); - return; - } - node = parent; - parent = parent.parent; - } - } - - return { - AwaitExpression: validate, - ForOfStatement: validate - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-bitwise.js b/tools/node_modules/eslint/lib/rules/no-bitwise.js deleted file mode 100644 index a9c3360a7c5b42904b84cb9bea5719788e5c33b5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-bitwise.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @fileoverview Rule to flag bitwise identifiers - * @author Nicholas C. Zakas - */ - -"use strict"; - -/* - * - * Set of bitwise operators. - * - */ -const BITWISE_OPERATORS = [ - "^", "|", "&", "<<", ">>", ">>>", - "^=", "|=", "&=", "<<=", ">>=", ">>>=", - "~" -]; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow bitwise operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-bitwise" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { - enum: BITWISE_OPERATORS - }, - uniqueItems: true - }, - int32Hint: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected use of '{{operator}}'." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowed = options.allow || []; - const int32Hint = options.int32Hint === true; - - /** - * Reports an unexpected use of a bitwise operator. - * @param {ASTNode} node Node which contains the bitwise operator. - * @returns {void} - */ - function report(node) { - context.report({ node, messageId: "unexpected", data: { operator: node.operator } }); - } - - /** - * Checks if the given node has a bitwise operator. - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the node has a bitwise operator. - */ - function hasBitwiseOperator(node) { - return BITWISE_OPERATORS.indexOf(node.operator) !== -1; - } - - /** - * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`. - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the node has a bitwise operator. - */ - function allowedOperator(node) { - return allowed.indexOf(node.operator) !== -1; - } - - /** - * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0" - * @param {ASTNode} node The node to check. - * @returns {boolean} whether the node is used in integer typecasting. - */ - function isInt32Hint(node) { - return int32Hint && node.operator === "|" && node.right && - node.right.type === "Literal" && node.right.value === 0; - } - - /** - * Report if the given node contains a bitwise operator. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkNodeForBitwiseOperator(node) { - if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) { - report(node); - } - } - - return { - AssignmentExpression: checkNodeForBitwiseOperator, - BinaryExpression: checkNodeForBitwiseOperator, - UnaryExpression: checkNodeForBitwiseOperator - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-buffer-constructor.js b/tools/node_modules/eslint/lib/rules/no-buffer-constructor.js deleted file mode 100644 index 152dda0ceae2cec2998371c925e0f4a74adb7479..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-buffer-constructor.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @fileoverview disallow use of the Buffer() constructor - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "problem", - - docs: { - description: "disallow use of the `Buffer()` constructor", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-buffer-constructor" - }, - - schema: [], - - messages: { - deprecated: "{{expr}} is deprecated. Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead." - } - }, - - create(context) { - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - "CallExpression[callee.name='Buffer'], NewExpression[callee.name='Buffer']"(node) { - context.report({ - node, - messageId: "deprecated", - data: { expr: node.type === "CallExpression" ? "Buffer()" : "new Buffer()" } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-caller.js b/tools/node_modules/eslint/lib/rules/no-caller.js deleted file mode 100644 index 5fe1bd449857c3acf82bcf7b2605759d46e6f03e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-caller.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Rule to flag use of arguments.callee and arguments.caller. - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `arguments.caller` or `arguments.callee`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-caller" - }, - - schema: [], - - messages: { - unexpected: "Avoid arguments.{{prop}}." - } - }, - - create(context) { - - return { - - MemberExpression(node) { - const objectName = node.object.name, - propertyName = node.property.name; - - if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) { - context.report({ node, messageId: "unexpected", data: { prop: propertyName } }); - } - - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-case-declarations.js b/tools/node_modules/eslint/lib/rules/no-case-declarations.js deleted file mode 100644 index 1d54e221625e70b2dbd305e7a2a3a70a06410f35..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-case-declarations.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Rule to flag use of an lexical declarations inside a case clause - * @author Erik Arvidsson - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow lexical declarations in case clauses", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-case-declarations" - }, - - schema: [], - - messages: { - unexpected: "Unexpected lexical declaration in case block." - } - }, - - create(context) { - - /** - * Checks whether or not a node is a lexical declaration. - * @param {ASTNode} node A direct child statement of a switch case. - * @returns {boolean} Whether or not the node is a lexical declaration. - */ - function isLexicalDeclaration(node) { - switch (node.type) { - case "FunctionDeclaration": - case "ClassDeclaration": - return true; - case "VariableDeclaration": - return node.kind !== "var"; - default: - return false; - } - } - - return { - SwitchCase(node) { - for (let i = 0; i < node.consequent.length; i++) { - const statement = node.consequent[i]; - - if (isLexicalDeclaration(statement)) { - context.report({ - node: statement, - messageId: "unexpected" - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-catch-shadow.js b/tools/node_modules/eslint/lib/rules/no-catch-shadow.js deleted file mode 100644 index 4917af84e432114c5f380c5d1b12a7e3b8ed68fb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-catch-shadow.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @fileoverview Rule to flag variable leak in CatchClauses in IE 8 and earlier - * @author Ian Christian Myers - * @deprecated in ESLint v5.1.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `catch` clause parameters from shadowing variables in the outer scope", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-catch-shadow" - }, - - replacedBy: ["no-shadow"], - - deprecated: true, - schema: [], - - messages: { - mutable: "Value of '{{name}}' may be overwritten in IE 8 and earlier." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if the parameters are been shadowed - * @param {Object} scope current scope - * @param {string} name parameter name - * @returns {boolean} True is its been shadowed - */ - function paramIsShadowing(scope, name) { - return astUtils.getVariableByName(scope, name) !== null; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - "CatchClause[param!=null]"(node) { - let scope = context.getScope(); - - /* - * When ecmaVersion >= 6, CatchClause creates its own scope - * so start from one upper scope to exclude the current node - */ - if (scope.block === node) { - scope = scope.upper; - } - - if (paramIsShadowing(scope, node.param.name)) { - context.report({ node, messageId: "mutable", data: { name: node.param.name } }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-class-assign.js b/tools/node_modules/eslint/lib/rules/no-class-assign.js deleted file mode 100644 index 887058ba0f967d502c8edb99cbebe9c222c06b18..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-class-assign.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @fileoverview A rule to disallow modifying variables of class declarations - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning class members", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-class-assign" - }, - - schema: [], - - messages: { - class: "'{{name}}' is a class." - } - }, - - create(context) { - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(reference => { - context.report({ node: reference.identifier, messageId: "class", data: { name: reference.identifier.name } }); - - }); - } - - /** - * Finds and reports references that are non initializer and writable. - * @param {ASTNode} node A ClassDeclaration/ClassExpression node to check. - * @returns {void} - */ - function checkForClass(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - - return { - ClassDeclaration: checkForClass, - ClassExpression: checkForClass - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-compare-neg-zero.js b/tools/node_modules/eslint/lib/rules/no-compare-neg-zero.js deleted file mode 100644 index 0c6865ad59e8fe5d2cebf27d10d2aae4da9f1931..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-compare-neg-zero.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview The rule should warn against code that tries to compare against -0. - * @author Aladdin-ADD - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow comparing against -0", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-compare-neg-zero" - }, - - fixable: null, - schema: [], - - messages: { - unexpected: "Do not use the '{{operator}}' operator to compare against -0." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks a given node is -0 - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is -0. - */ - function isNegZero(node) { - return node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "Literal" && node.argument.value === 0; - } - const OPERATORS_TO_CHECK = new Set([">", ">=", "<", "<=", "==", "===", "!=", "!=="]); - - return { - BinaryExpression(node) { - if (OPERATORS_TO_CHECK.has(node.operator)) { - if (isNegZero(node.left) || isNegZero(node.right)) { - context.report({ - node, - messageId: "unexpected", - data: { operator: node.operator } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-cond-assign.js b/tools/node_modules/eslint/lib/rules/no-cond-assign.js deleted file mode 100644 index 3843a7ac2e3e91c319185fec72e3b6875b661d56..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-cond-assign.js +++ /dev/null @@ -1,159 +0,0 @@ -/** - * @fileoverview Rule to flag assignment in a conditional statement's test expression - * @author Stephen Murray - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const TEST_CONDITION_PARENT_TYPES = new Set(["IfStatement", "WhileStatement", "DoWhileStatement", "ForStatement", "ConditionalExpression"]); - -const NODE_DESCRIPTIONS = { - DoWhileStatement: "a 'do...while' statement", - ForStatement: "a 'for' statement", - IfStatement: "an 'if' statement", - WhileStatement: "a 'while' statement" -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assignment operators in conditional expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-cond-assign" - }, - - schema: [ - { - enum: ["except-parens", "always"] - } - ], - - messages: { - unexpected: "Unexpected assignment within {{type}}.", - - // must match JSHint's error message - missing: "Expected a conditional expression and instead saw an assignment." - } - }, - - create(context) { - - const prohibitAssign = (context.options[0] || "except-parens"); - - const sourceCode = context.getSourceCode(); - - /** - * Check whether an AST node is the test expression for a conditional statement. - * @param {!Object} node The node to test. - * @returns {boolean} `true` if the node is the text expression for a conditional statement; otherwise, `false`. - */ - function isConditionalTestExpression(node) { - return node.parent && - TEST_CONDITION_PARENT_TYPES.has(node.parent.type) && - node === node.parent.test; - } - - /** - * Given an AST node, perform a bottom-up search for the first ancestor that represents a conditional statement. - * @param {!Object} node The node to use at the start of the search. - * @returns {?Object} The closest ancestor node that represents a conditional statement. - */ - function findConditionalAncestor(node) { - let currentAncestor = node; - - do { - if (isConditionalTestExpression(currentAncestor)) { - return currentAncestor.parent; - } - } while ((currentAncestor = currentAncestor.parent) && !astUtils.isFunction(currentAncestor)); - - return null; - } - - /** - * Check whether the code represented by an AST node is enclosed in two sets of parentheses. - * @param {!Object} node The node to test. - * @returns {boolean} `true` if the code is enclosed in two sets of parentheses; otherwise, `false`. - */ - function isParenthesisedTwice(node) { - const previousToken = sourceCode.getTokenBefore(node, 1), - nextToken = sourceCode.getTokenAfter(node, 1); - - return astUtils.isParenthesised(sourceCode, node) && - previousToken && astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && - astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; - } - - /** - * Check a conditional statement's test expression for top-level assignments that are not enclosed in parentheses. - * @param {!Object} node The node for the conditional statement. - * @returns {void} - */ - function testForAssign(node) { - if (node.test && - (node.test.type === "AssignmentExpression") && - (node.type === "ForStatement" - ? !astUtils.isParenthesised(sourceCode, node.test) - : !isParenthesisedTwice(node.test) - ) - ) { - - context.report({ - node: node.test, - messageId: "missing" - }); - } - } - - /** - * Check whether an assignment expression is descended from a conditional statement's test expression. - * @param {!Object} node The node for the assignment expression. - * @returns {void} - */ - function testForConditionalAncestor(node) { - const ancestor = findConditionalAncestor(node); - - if (ancestor) { - context.report({ - node, - messageId: "unexpected", - data: { - type: NODE_DESCRIPTIONS[ancestor.type] || ancestor.type - } - }); - } - } - - if (prohibitAssign === "always") { - return { - AssignmentExpression: testForConditionalAncestor - }; - } - - return { - DoWhileStatement: testForAssign, - ForStatement: testForAssign, - IfStatement: testForAssign, - WhileStatement: testForAssign, - ConditionalExpression: testForAssign - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js b/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js deleted file mode 100644 index 9009b64fa1559a9825ea8faaeb72da0476138aae..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-confusing-arrow.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @fileoverview A rule to warn against using arrow functions when they could be - * confused with comparisons - * @author Jxck - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils.js"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a node is a conditional expression. - * @param {ASTNode} node node to test - * @returns {boolean} `true` if the node is a conditional expression. - */ -function isConditional(node) { - return node && node.type === "ConditionalExpression"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow arrow functions where they could be confused with comparisons", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-confusing-arrow" - }, - - fixable: "code", - - schema: [{ - type: "object", - properties: { - allowParens: { type: "boolean", default: true } - }, - additionalProperties: false - }], - - messages: { - confusing: "Arrow function used ambiguously with a conditional expression." - } - }, - - create(context) { - const config = context.options[0] || {}; - const allowParens = config.allowParens || (config.allowParens === void 0); - const sourceCode = context.getSourceCode(); - - - /** - * Reports if an arrow function contains an ambiguous conditional. - * @param {ASTNode} node A node to check and report. - * @returns {void} - */ - function checkArrowFunc(node) { - const body = node.body; - - if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) { - context.report({ - node, - messageId: "confusing", - fix(fixer) { - - // if `allowParens` is not set to true don't bother wrapping in parens - return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`); - } - }); - } - } - - return { - ArrowFunctionExpression: checkArrowFunc - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-console.js b/tools/node_modules/eslint/lib/rules/no-console.js deleted file mode 100644 index 56dbbc3a9fd5953243703aef31c88604f0dd4faf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-console.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * @fileoverview Rule to flag use of console object - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `console`", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-console" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { - type: "string" - }, - minItems: 1, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected console statement." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowed = options.allow || []; - - /** - * Checks whether the given reference is 'console' or not. - * @param {eslint-scope.Reference} reference The reference to check. - * @returns {boolean} `true` if the reference is 'console'. - */ - function isConsole(reference) { - const id = reference.identifier; - - return id && id.name === "console"; - } - - /** - * Checks whether the property name of the given MemberExpression node - * is allowed by options or not. - * @param {ASTNode} node The MemberExpression node to check. - * @returns {boolean} `true` if the property name of the node is allowed. - */ - function isAllowed(node) { - const propertyName = astUtils.getStaticPropertyName(node); - - return propertyName && allowed.indexOf(propertyName) !== -1; - } - - /** - * Checks whether the given reference is a member access which is not - * allowed by options or not. - * @param {eslint-scope.Reference} reference The reference to check. - * @returns {boolean} `true` if the reference is a member access which - * is not allowed by options. - */ - function isMemberAccessExceptAllowed(reference) { - const node = reference.identifier; - const parent = node.parent; - - return ( - parent.type === "MemberExpression" && - parent.object === node && - !isAllowed(parent) - ); - } - - /** - * Reports the given reference as a violation. - * @param {eslint-scope.Reference} reference The reference to report. - * @returns {void} - */ - function report(reference) { - const node = reference.identifier.parent; - - context.report({ - node, - loc: node.loc, - messageId: "unexpected" - }); - } - - return { - "Program:exit"() { - const scope = context.getScope(); - const consoleVar = astUtils.getVariableByName(scope, "console"); - const shadowed = consoleVar && consoleVar.defs.length > 0; - - /* - * 'scope.through' includes all references to undefined - * variables. If the variable 'console' is not defined, it uses - * 'scope.through'. - */ - const references = consoleVar - ? consoleVar.references - : scope.through.filter(isConsole); - - if (!shadowed) { - references - .filter(isMemberAccessExceptAllowed) - .forEach(report); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-const-assign.js b/tools/node_modules/eslint/lib/rules/no-const-assign.js deleted file mode 100644 index e4ae891705f89932e206fee395537c56f40d5f98..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-const-assign.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @fileoverview A rule to disallow modifying variables that are declared using `const` - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning `const` variables", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-const-assign" - }, - - schema: [], - - messages: { - const: "'{{name}}' is constant." - } - }, - - create(context) { - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(reference => { - context.report({ node: reference.identifier, messageId: "const", data: { name: reference.identifier.name } }); - }); - } - - return { - VariableDeclaration(node) { - if (node.kind === "const") { - context.getDeclaredVariables(node).forEach(checkVariable); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-constant-condition.js b/tools/node_modules/eslint/lib/rules/no-constant-condition.js deleted file mode 100644 index 5e5838641028fe58c894ac07210f53a89f369a78..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-constant-condition.js +++ /dev/null @@ -1,253 +0,0 @@ -/** - * @fileoverview Rule to flag use constant conditions - * @author Christian Schulz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const EQUALITY_OPERATORS = ["===", "!==", "==", "!="]; -const RELATIONAL_OPERATORS = [">", "<", ">=", "<=", "in", "instanceof"]; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow constant expressions in conditions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-constant-condition" - }, - - schema: [ - { - type: "object", - properties: { - checkLoops: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected constant condition." - } - }, - - create(context) { - const options = context.options[0] || {}, - checkLoops = options.checkLoops !== false, - loopSetStack = []; - - let loopsInCurrentScope = new Set(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - - /** - * Checks if a branch node of LogicalExpression short circuits the whole condition - * @param {ASTNode} node The branch of main condition which needs to be checked - * @param {string} operator The operator of the main LogicalExpression. - * @returns {boolean} true when condition short circuits whole condition - */ - function isLogicalIdentity(node, operator) { - switch (node.type) { - case "Literal": - return (operator === "||" && node.value === true) || - (operator === "&&" && node.value === false); - - case "UnaryExpression": - return (operator === "&&" && node.operator === "void"); - - case "LogicalExpression": - return isLogicalIdentity(node.left, node.operator) || - isLogicalIdentity(node.right, node.operator); - - // no default - } - return false; - } - - /** - * Checks if a node has a constant truthiness value. - * @param {ASTNode} node The AST node to check. - * @param {boolean} inBooleanPosition `false` if checking branch of a condition. - * `true` in all other cases - * @returns {Bool} true when node's truthiness is constant - * @private - */ - function isConstant(node, inBooleanPosition) { - - // node.elements can return null values in the case of sparse arrays ex. [,] - if (!node) { - return true; - } - switch (node.type) { - case "Literal": - case "ArrowFunctionExpression": - case "FunctionExpression": - case "ObjectExpression": - return true; - case "TemplateLiteral": - return (inBooleanPosition && node.quasis.some(quasi => quasi.value.cooked.length)) || - node.expressions.every(exp => isConstant(exp, inBooleanPosition)); - - case "ArrayExpression": { - if (node.parent.type === "BinaryExpression" && node.parent.operator === "+") { - return node.elements.every(element => isConstant(element, false)); - } - return true; - } - - case "UnaryExpression": - if (node.operator === "void") { - return true; - } - - return (node.operator === "typeof" && inBooleanPosition) || - isConstant(node.argument, true); - - case "BinaryExpression": - return isConstant(node.left, false) && - isConstant(node.right, false) && - node.operator !== "in"; - - case "LogicalExpression": { - const isLeftConstant = isConstant(node.left, inBooleanPosition); - const isRightConstant = isConstant(node.right, inBooleanPosition); - const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator)); - const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator)); - - return (isLeftConstant && isRightConstant) || - ( - - // in the case of an "OR", we need to know if the right constant value is truthy - node.operator === "||" && - isRightConstant && - node.right.value && - ( - !node.parent || - node.parent.type !== "BinaryExpression" || - !(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator)) - ) - ) || - isLeftShortCircuit || - isRightShortCircuit; - } - - case "AssignmentExpression": - return (node.operator === "=") && isConstant(node.right, inBooleanPosition); - - case "SequenceExpression": - return isConstant(node.expressions[node.expressions.length - 1], inBooleanPosition); - - // no default - } - return false; - } - - /** - * Tracks when the given node contains a constant condition. - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function trackConstantConditionLoop(node) { - if (node.test && isConstant(node.test, true)) { - loopsInCurrentScope.add(node); - } - } - - /** - * Reports when the set contains the given constant condition node - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function checkConstantConditionLoopInSet(node) { - if (loopsInCurrentScope.has(node)) { - loopsInCurrentScope.delete(node); - context.report({ node: node.test, messageId: "unexpected" }); - } - } - - /** - * Reports when the given node contains a constant condition. - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function reportIfConstant(node) { - if (node.test && isConstant(node.test, true)) { - context.report({ node: node.test, messageId: "unexpected" }); - } - } - - /** - * Stores current set of constant loops in loopSetStack temporarily - * and uses a new set to track constant loops - * @returns {void} - * @private - */ - function enterFunction() { - loopSetStack.push(loopsInCurrentScope); - loopsInCurrentScope = new Set(); - } - - /** - * Reports when the set still contains stored constant conditions - * @returns {void} - * @private - */ - function exitFunction() { - loopsInCurrentScope = loopSetStack.pop(); - } - - /** - * Checks node when checkLoops option is enabled - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function checkLoop(node) { - if (checkLoops) { - trackConstantConditionLoop(node); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ConditionalExpression: reportIfConstant, - IfStatement: reportIfConstant, - WhileStatement: checkLoop, - "WhileStatement:exit": checkConstantConditionLoopInSet, - DoWhileStatement: checkLoop, - "DoWhileStatement:exit": checkConstantConditionLoopInSet, - ForStatement: checkLoop, - "ForStatement > .test": node => checkLoop(node.parent), - "ForStatement:exit": checkConstantConditionLoopInSet, - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - YieldExpression: () => loopsInCurrentScope.clear() - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-constructor-return.js b/tools/node_modules/eslint/lib/rules/no-constructor-return.js deleted file mode 100644 index 4757770b7cc8e604020d21d7d0f8476cdfd7579d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-constructor-return.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * @fileoverview Rule to disallow returning value from constructor. - * @author Pig Fang - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow returning value from constructor", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-constructor-return" - }, - - schema: {}, - - fixable: null, - - messages: { - unexpected: "Unexpected return statement in constructor." - } - }, - - create(context) { - const stack = []; - - return { - onCodePathStart(_, node) { - stack.push(node); - }, - onCodePathEnd() { - stack.pop(); - }, - ReturnStatement(node) { - const last = stack[stack.length - 1]; - - if (!last.parent) { - return; - } - - if ( - last.parent.type === "MethodDefinition" && - last.parent.kind === "constructor" && - (node.parent.parent === last || node.argument) - ) { - context.report({ - node, - messageId: "unexpected" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-continue.js b/tools/node_modules/eslint/lib/rules/no-continue.js deleted file mode 100644 index 96718d17a3db4be287c3f6985ece1f63dc16fab4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-continue.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview Rule to flag use of continue statement - * @author Borislav Zhivkov - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `continue` statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-continue" - }, - - schema: [], - - messages: { - unexpected: "Unexpected use of continue statement." - } - }, - - create(context) { - - return { - ContinueStatement(node) { - context.report({ node, messageId: "unexpected" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-control-regex.js b/tools/node_modules/eslint/lib/rules/no-control-regex.js deleted file mode 100644 index 146c4f22d01257a2df5d9e1bce6f8872443c0e04..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-control-regex.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @fileoverview Rule to forbid control characters from regular expressions. - * @author Nicholas C. Zakas - */ - -"use strict"; - -const RegExpValidator = require("regexpp").RegExpValidator; -const collector = new (class { - constructor() { - this.ecmaVersion = 2018; - this._source = ""; - this._controlChars = []; - this._validator = new RegExpValidator(this); - } - - onPatternEnter() { - this._controlChars = []; - } - - onCharacter(start, end, cp) { - if (cp >= 0x00 && - cp <= 0x1F && - ( - this._source.codePointAt(start) === cp || - this._source.slice(start, end).startsWith("\\x") || - this._source.slice(start, end).startsWith("\\u") - ) - ) { - this._controlChars.push(`\\x${`0${cp.toString(16)}`.slice(-2)}`); - } - } - - collectControlChars(regexpStr) { - try { - this._source = regexpStr; - this._validator.validatePattern(regexpStr); // Call onCharacter hook - } catch { - - // Ignore syntax errors in RegExp. - } - return this._controlChars; - } -})(); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow control characters in regular expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-control-regex" - }, - - schema: [], - - messages: { - unexpected: "Unexpected control character(s) in regular expression: {{controlChars}}." - } - }, - - create(context) { - - /** - * Get the regex expression - * @param {ASTNode} node node to evaluate - * @returns {RegExp|null} Regex if found else null - * @private - */ - function getRegExpPattern(node) { - if (node.regex) { - return node.regex.pattern; - } - if (typeof node.value === "string" && - (node.parent.type === "NewExpression" || node.parent.type === "CallExpression") && - node.parent.callee.type === "Identifier" && - node.parent.callee.name === "RegExp" && - node.parent.arguments[0] === node - ) { - return node.value; - } - - return null; - } - - return { - Literal(node) { - const pattern = getRegExpPattern(node); - - if (pattern) { - const controlCharacters = collector.collectControlChars(pattern); - - if (controlCharacters.length > 0) { - context.report({ - node, - messageId: "unexpected", - data: { - controlChars: controlCharacters.join(", ") - } - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-debugger.js b/tools/node_modules/eslint/lib/rules/no-debugger.js deleted file mode 100644 index 95a28a862151be145972f1d81ac831461ce20654..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-debugger.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Rule to flag use of a debugger statement - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow the use of `debugger`", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-debugger" - }, - - fixable: null, - schema: [], - - messages: { - unexpected: "Unexpected 'debugger' statement." - } - }, - - create(context) { - - return { - DebuggerStatement(node) { - context.report({ - node, - messageId: "unexpected" - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-delete-var.js b/tools/node_modules/eslint/lib/rules/no-delete-var.js deleted file mode 100644 index aeab951d75ff82f525829d0c3035f0622da396d7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-delete-var.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview Rule to flag when deleting variables - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow deleting variables", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-delete-var" - }, - - schema: [], - - messages: { - unexpected: "Variables should not be deleted." - } - }, - - create(context) { - - return { - - UnaryExpression(node) { - if (node.operator === "delete" && node.argument.type === "Identifier") { - context.report({ node, messageId: "unexpected" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-div-regex.js b/tools/node_modules/eslint/lib/rules/no-div-regex.js deleted file mode 100644 index 0ccabdcc6988b419f5d8670c56648433c326d79d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-div-regex.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @fileoverview Rule to check for ambiguous div operator in regexes - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow division operators explicitly at the beginning of regular expressions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-div-regex" - }, - - fixable: "code", - - schema: [], - - messages: { - unexpected: "A regular expression literal can be confused with '/='." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - - Literal(node) { - const token = sourceCode.getFirstToken(node); - - if (token.type === "RegularExpression" && token.value[1] === "=") { - context.report({ - node, - messageId: "unexpected", - fix(fixer) { - return fixer.replaceTextRange([token.range[0] + 1, token.range[0] + 2], "[=]"); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-args.js b/tools/node_modules/eslint/lib/rules/no-dupe-args.js deleted file mode 100644 index 817277f522e7323de0c9fcc45acb8d88c86d3644..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-args.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @fileoverview Rule to flag duplicate arguments - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate arguments in `function` definitions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-args" - }, - - schema: [], - - messages: { - unexpected: "Duplicate param '{{name}}'." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks whether or not a given definition is a parameter's. - * @param {eslint-scope.DefEntry} def A definition to check. - * @returns {boolean} `true` if the definition is a parameter's. - */ - function isParameter(def) { - return def.type === "Parameter"; - } - - /** - * Determines if a given node has duplicate parameters. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkParams(node) { - const variables = context.getDeclaredVariables(node); - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - // Checks and reports duplications. - const defs = variable.defs.filter(isParameter); - - if (defs.length >= 2) { - context.report({ - node, - messageId: "unexpected", - data: { name: variable.name } - }); - } - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: checkParams, - FunctionExpression: checkParams - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-class-members.js b/tools/node_modules/eslint/lib/rules/no-dupe-class-members.js deleted file mode 100644 index b12939d57bc884b1a461c020f32842caaddb380d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-class-members.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @fileoverview A rule to disallow duplicate name in class members. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate class members", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-class-members" - }, - - schema: [], - - messages: { - unexpected: "Duplicate name '{{name}}'." - } - }, - - create(context) { - let stack = []; - - /** - * Gets state of a given member name. - * @param {string} name A name of a member. - * @param {boolean} isStatic A flag which specifies that is a static member. - * @returns {Object} A state of a given member name. - * - retv.init {boolean} A flag which shows the name is declared as normal member. - * - retv.get {boolean} A flag which shows the name is declared as getter. - * - retv.set {boolean} A flag which shows the name is declared as setter. - */ - function getState(name, isStatic) { - const stateMap = stack[stack.length - 1]; - const key = `$${name}`; // to avoid "__proto__". - - if (!stateMap[key]) { - stateMap[key] = { - nonStatic: { init: false, get: false, set: false }, - static: { init: false, get: false, set: false } - }; - } - - return stateMap[key][isStatic ? "static" : "nonStatic"]; - } - - return { - - // Initializes the stack of state of member declarations. - Program() { - stack = []; - }, - - // Initializes state of member declarations for the class. - ClassBody() { - stack.push(Object.create(null)); - }, - - // Disposes the state for the class. - "ClassBody:exit"() { - stack.pop(); - }, - - // Reports the node if its name has been declared already. - MethodDefinition(node) { - const name = astUtils.getStaticPropertyName(node); - - if (name === null || node.kind === "constructor") { - return; - } - - const state = getState(name, node.static); - let isDuplicate = false; - - if (node.kind === "get") { - isDuplicate = (state.init || state.get); - state.get = true; - } else if (node.kind === "set") { - isDuplicate = (state.init || state.set); - state.set = true; - } else { - isDuplicate = (state.init || state.get || state.set); - state.init = true; - } - - if (isDuplicate) { - context.report({ node, messageId: "unexpected", data: { name } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-else-if.js b/tools/node_modules/eslint/lib/rules/no-dupe-else-if.js deleted file mode 100644 index cbeb437da1e7ec16acbf492d42cf58d8ca70c608..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-else-if.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule to disallow duplicate conditions in if-else-if chains - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines whether the first given array is a subset of the second given array. - * @param {Function} comparator A function to compare two elements, should return `true` if they are equal. - * @param {Array} arrA The array to compare from. - * @param {Array} arrB The array to compare against. - * @returns {boolean} `true` if the array `arrA` is a subset of the array `arrB`. - */ -function isSubsetByComparator(comparator, arrA, arrB) { - return arrA.every(a => arrB.some(b => comparator(a, b))); -} - -/** - * Splits the given node by the given logical operator. - * @param {string} operator Logical operator `||` or `&&`. - * @param {ASTNode} node The node to split. - * @returns {ASTNode[]} Array of conditions that makes the node when joined by the operator. - */ -function splitByLogicalOperator(operator, node) { - if (node.type === "LogicalExpression" && node.operator === operator) { - return [...splitByLogicalOperator(operator, node.left), ...splitByLogicalOperator(operator, node.right)]; - } - return [node]; -} - -const splitByOr = splitByLogicalOperator.bind(null, "||"); -const splitByAnd = splitByLogicalOperator.bind(null, "&&"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate conditions in if-else-if chains", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-else-if" - }, - - schema: [], - - messages: { - unexpected: "This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Determines whether the two given nodes are considered to be equal. In particular, given that the nodes - * represent expressions in a boolean context, `||` and `&&` can be considered as commutative operators. - * @param {ASTNode} a First node. - * @param {ASTNode} b Second node. - * @returns {boolean} `true` if the nodes are considered to be equal. - */ - function equal(a, b) { - if (a.type !== b.type) { - return false; - } - - if ( - a.type === "LogicalExpression" && - (a.operator === "||" || a.operator === "&&") && - a.operator === b.operator - ) { - return equal(a.left, b.left) && equal(a.right, b.right) || - equal(a.left, b.right) && equal(a.right, b.left); - } - - return astUtils.equalTokens(a, b, sourceCode); - } - - const isSubset = isSubsetByComparator.bind(null, equal); - - return { - IfStatement(node) { - const test = node.test, - conditionsToCheck = test.type === "LogicalExpression" && test.operator === "&&" - ? [test, ...splitByAnd(test)] - : [test]; - let current = node, - listToCheck = conditionsToCheck.map(c => splitByOr(c).map(splitByAnd)); - - while (current.parent && current.parent.type === "IfStatement" && current.parent.alternate === current) { - current = current.parent; - - const currentOrOperands = splitByOr(current.test).map(splitByAnd); - - listToCheck = listToCheck.map(orOperands => orOperands.filter( - orOperand => !currentOrOperands.some(currentOrOperand => isSubset(currentOrOperand, orOperand)) - )); - - if (listToCheck.some(orOperands => orOperands.length === 0)) { - context.report({ node: test, messageId: "unexpected" }); - break; - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-dupe-keys.js b/tools/node_modules/eslint/lib/rules/no-dupe-keys.js deleted file mode 100644 index 89e1f2de642285d77b953c282c34898121b94fef..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-dupe-keys.js +++ /dev/null @@ -1,143 +0,0 @@ -/** - * @fileoverview Rule to flag use of duplicate keys in an object. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const GET_KIND = /^(?:init|get)$/u; -const SET_KIND = /^(?:init|set)$/u; - -/** - * The class which stores properties' information of an object. - */ -class ObjectInfo { - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ObjectInfo|null} upper The information of the outer object. - * @param {ASTNode} node The ObjectExpression node of this information. - */ - constructor(upper, node) { - this.upper = upper; - this.node = node; - this.properties = new Map(); - } - - /** - * Gets the information of the given Property node. - * @param {ASTNode} node The Property node to get. - * @returns {{get: boolean, set: boolean}} The information of the property. - */ - getPropertyInfo(node) { - const name = astUtils.getStaticPropertyName(node); - - if (!this.properties.has(name)) { - this.properties.set(name, { get: false, set: false }); - } - return this.properties.get(name); - } - - /** - * Checks whether the given property has been defined already or not. - * @param {ASTNode} node The Property node to check. - * @returns {boolean} `true` if the property has been defined. - */ - isPropertyDefined(node) { - const entry = this.getPropertyInfo(node); - - return ( - (GET_KIND.test(node.kind) && entry.get) || - (SET_KIND.test(node.kind) && entry.set) - ); - } - - /** - * Defines the given property. - * @param {ASTNode} node The Property node to define. - * @returns {void} - */ - defineProperty(node) { - const entry = this.getPropertyInfo(node); - - if (GET_KIND.test(node.kind)) { - entry.get = true; - } - if (SET_KIND.test(node.kind)) { - entry.set = true; - } - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate keys in object literals", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-dupe-keys" - }, - - schema: [], - - messages: { - unexpected: "Duplicate key '{{name}}'." - } - }, - - create(context) { - let info = null; - - return { - ObjectExpression(node) { - info = new ObjectInfo(info, node); - }, - "ObjectExpression:exit"() { - info = info.upper; - }, - - Property(node) { - const name = astUtils.getStaticPropertyName(node); - - // Skip destructuring. - if (node.parent.type !== "ObjectExpression") { - return; - } - - // Skip if the name is not static. - if (name === null) { - return; - } - - // Reports if the name is defined already. - if (info.isPropertyDefined(node)) { - context.report({ - node: info.node, - loc: node.key.loc, - messageId: "unexpected", - data: { name } - }); - } - - // Update info. - info.defineProperty(node); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-duplicate-case.js b/tools/node_modules/eslint/lib/rules/no-duplicate-case.js deleted file mode 100644 index e2d9665e7f564d8fced4fbba68fe7def57756f67..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-duplicate-case.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @fileoverview Rule to disallow a duplicate case label. - * @author Dieter Oberkofler - * @author Burak Yigit Kaya - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate case labels", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-duplicate-case" - }, - - schema: [], - - messages: { - unexpected: "Duplicate case label." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Determines whether the two given nodes are considered to be equal. - * @param {ASTNode} a First node. - * @param {ASTNode} b Second node. - * @returns {boolean} `true` if the nodes are considered to be equal. - */ - function equal(a, b) { - if (a.type !== b.type) { - return false; - } - - return astUtils.equalTokens(a, b, sourceCode); - } - return { - SwitchStatement(node) { - const previousTests = []; - - for (const switchCase of node.cases) { - if (switchCase.test) { - const test = switchCase.test; - - if (previousTests.some(previousTest => equal(previousTest, test))) { - context.report({ node: switchCase, messageId: "unexpected" }); - } else { - previousTests.push(test); - } - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-duplicate-imports.js b/tools/node_modules/eslint/lib/rules/no-duplicate-imports.js deleted file mode 100644 index 7218dc64add343f12703e3ea9f9a1a19c0cf894e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-duplicate-imports.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @fileoverview Restrict usage of duplicate imports. - * @author Simen Bekkhus - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Returns the name of the module imported or re-exported. - * @param {ASTNode} node A node to get. - * @returns {string} the name of the module, or empty string if no name. - */ -function getValue(node) { - if (node && node.source && node.source.value) { - return node.source.value.trim(); - } - - return ""; -} - -/** - * Checks if the name of the import or export exists in the given array, and reports if so. - * @param {RuleContext} context The ESLint rule context object. - * @param {ASTNode} node A node to get. - * @param {string} value The name of the imported or exported module. - * @param {string[]} array The array containing other imports or exports in the file. - * @param {string} messageId A messageId to be reported after the name of the module - * - * @returns {void} No return value - */ -function checkAndReport(context, node, value, array, messageId) { - if (array.indexOf(value) !== -1) { - context.report({ - node, - messageId, - data: { - module: value - } - }); - } -} - -/** - * @callback nodeCallback - * @param {ASTNode} node A node to handle. - */ - -/** - * Returns a function handling the imports of a given file - * @param {RuleContext} context The ESLint rule context object. - * @param {boolean} includeExports Whether or not to check for exports in addition to imports. - * @param {string[]} importsInFile The array containing other imports in the file. - * @param {string[]} exportsInFile The array containing other exports in the file. - * - * @returns {nodeCallback} A function passed to ESLint to handle the statement. - */ -function handleImports(context, includeExports, importsInFile, exportsInFile) { - return function(node) { - const value = getValue(node); - - if (value) { - checkAndReport(context, node, value, importsInFile, "import"); - - if (includeExports) { - checkAndReport(context, node, value, exportsInFile, "importAs"); - } - - importsInFile.push(value); - } - }; -} - -/** - * Returns a function handling the exports of a given file - * @param {RuleContext} context The ESLint rule context object. - * @param {string[]} importsInFile The array containing other imports in the file. - * @param {string[]} exportsInFile The array containing other exports in the file. - * - * @returns {nodeCallback} A function passed to ESLint to handle the statement. - */ -function handleExports(context, importsInFile, exportsInFile) { - return function(node) { - const value = getValue(node); - - if (value) { - checkAndReport(context, node, value, exportsInFile, "export"); - checkAndReport(context, node, value, importsInFile, "exportAs"); - - exportsInFile.push(value); - } - }; -} - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow duplicate module imports", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-duplicate-imports" - }, - - schema: [{ - type: "object", - properties: { - includeExports: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - messages: { - import: "'{{module}}' import is duplicated.", - importAs: "'{{module}}' import is duplicated as export.", - export: "'{{module}}' export is duplicated.", - exportAs: "'{{module}}' export is duplicated as import." - } - }, - - create(context) { - const includeExports = (context.options[0] || {}).includeExports, - importsInFile = [], - exportsInFile = []; - - const handlers = { - ImportDeclaration: handleImports(context, includeExports, importsInFile, exportsInFile) - }; - - if (includeExports) { - handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile); - handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile); - } - - return handlers; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-else-return.js b/tools/node_modules/eslint/lib/rules/no-else-return.js deleted file mode 100644 index 84409fac87cff8b4568ad6f435ecd1f3f1f4cbaf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-else-return.js +++ /dev/null @@ -1,404 +0,0 @@ -/** - * @fileoverview Rule to flag `else` after a `return` in `if` - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const FixTracker = require("./utils/fix-tracker"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `else` blocks after `return` statements in `if` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-else-return" - }, - - schema: [{ - type: "object", - properties: { - allowElseIf: { - type: "boolean", - default: true - } - }, - additionalProperties: false - }], - - fixable: "code", - - messages: { - unexpected: "Unnecessary 'else' after 'return'." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks whether the given names can be safely used to declare block-scoped variables - * in the given scope. Name collisions can produce redeclaration syntax errors, - * or silently change references and modify behavior of the original code. - * - * This is not a generic function. In particular, it is assumed that the scope is a function scope or - * a function's inner scope, and that the names can be valid identifiers in the given scope. - * @param {string[]} names Array of variable names. - * @param {eslint-scope.Scope} scope Function scope or a function's inner scope. - * @returns {boolean} True if all names can be safely declared, false otherwise. - */ - function isSafeToDeclare(names, scope) { - - if (names.length === 0) { - return true; - } - - const functionScope = scope.variableScope; - - /* - * If this is a function scope, scope.variables will contain parameters, implicit variables such as "arguments", - * all function-scoped variables ('var'), and block-scoped variables defined in the scope. - * If this is an inner scope, scope.variables will contain block-scoped variables defined in the scope. - * - * Redeclaring any of these would cause a syntax error, except for the implicit variables. - */ - const declaredVariables = scope.variables.filter(({ defs }) => defs.length > 0); - - if (declaredVariables.some(({ name }) => names.includes(name))) { - return false; - } - - // Redeclaring a catch variable would also cause a syntax error. - if (scope !== functionScope && scope.upper.type === "catch") { - if (scope.upper.variables.some(({ name }) => names.includes(name))) { - return false; - } - } - - /* - * Redeclaring an implicit variable, such as "arguments", would not cause a syntax error. - * However, if the variable was used, declaring a new one with the same name would change references - * and modify behavior. - */ - const usedImplicitVariables = scope.variables.filter(({ defs, references }) => - defs.length === 0 && references.length > 0); - - if (usedImplicitVariables.some(({ name }) => names.includes(name))) { - return false; - } - - /* - * Declaring a variable with a name that was already used to reference a variable from an upper scope - * would change references and modify behavior. - */ - if (scope.through.some(t => names.includes(t.identifier.name))) { - return false; - } - - /* - * If the scope is an inner scope (not the function scope), an uninitialized `var` variable declared inside - * the scope node (directly or in one of its descendants) is neither declared nor 'through' in the scope. - * - * For example, this would be a syntax error "Identifier 'a' has already been declared": - * function foo() { if (bar) { let a; if (baz) { var a; } } } - */ - if (scope !== functionScope) { - const scopeNodeRange = scope.block.range; - const variablesToCheck = functionScope.variables.filter(({ name }) => names.includes(name)); - - if (variablesToCheck.some(v => v.defs.some(({ node: { range } }) => - scopeNodeRange[0] <= range[0] && range[1] <= scopeNodeRange[1]))) { - return false; - } - } - - return true; - } - - - /** - * Checks whether the removal of `else` and its braces is safe from variable name collisions. - * @param {Node} node The 'else' node. - * @param {eslint-scope.Scope} scope The scope in which the node and the whole 'if' statement is. - * @returns {boolean} True if it is safe, false otherwise. - */ - function isSafeFromNameCollisions(node, scope) { - - if (node.type === "FunctionDeclaration") { - - // Conditional function declaration. Scope and hoisting are unpredictable, different engines work differently. - return false; - } - - if (node.type !== "BlockStatement") { - return true; - } - - const elseBlockScope = scope.childScopes.find(({ block }) => block === node); - - if (!elseBlockScope) { - - // ecmaVersion < 6, `else` block statement cannot have its own scope, no possible collisions. - return true; - } - - /* - * elseBlockScope is supposed to merge into its upper scope. elseBlockScope.variables array contains - * only block-scoped variables (such as let and const variables or class and function declarations) - * defined directly in the elseBlockScope. These are exactly the only names that could cause collisions. - */ - const namesToCheck = elseBlockScope.variables.map(({ name }) => name); - - return isSafeToDeclare(namesToCheck, scope); - } - - /** - * Display the context report if rule is violated - * @param {Node} node The 'else' node - * @returns {void} - */ - function displayReport(node) { - const currentScope = context.getScope(); - - context.report({ - node, - messageId: "unexpected", - fix: fixer => { - - if (!isSafeFromNameCollisions(node, currentScope)) { - return null; - } - - const sourceCode = context.getSourceCode(); - const startToken = sourceCode.getFirstToken(node); - const elseToken = sourceCode.getTokenBefore(startToken); - const source = sourceCode.getText(node); - const lastIfToken = sourceCode.getTokenBefore(elseToken); - let fixedSource, firstTokenOfElseBlock; - - if (startToken.type === "Punctuator" && startToken.value === "{") { - firstTokenOfElseBlock = sourceCode.getTokenAfter(startToken); - } else { - firstTokenOfElseBlock = startToken; - } - - /* - * If the if block does not have curly braces and does not end in a semicolon - * and the else block starts with (, [, /, +, ` or -, then it is not - * safe to remove the else keyword, because ASI will not add a semicolon - * after the if block - */ - const ifBlockMaybeUnsafe = node.parent.consequent.type !== "BlockStatement" && lastIfToken.value !== ";"; - const elseBlockUnsafe = /^[([/+`-]/u.test(firstTokenOfElseBlock.value); - - if (ifBlockMaybeUnsafe && elseBlockUnsafe) { - return null; - } - - const endToken = sourceCode.getLastToken(node); - const lastTokenOfElseBlock = sourceCode.getTokenBefore(endToken); - - if (lastTokenOfElseBlock.value !== ";") { - const nextToken = sourceCode.getTokenAfter(endToken); - - const nextTokenUnsafe = nextToken && /^[([/+`-]/u.test(nextToken.value); - const nextTokenOnSameLine = nextToken && nextToken.loc.start.line === lastTokenOfElseBlock.loc.start.line; - - /* - * If the else block contents does not end in a semicolon, - * and the else block starts with (, [, /, +, ` or -, then it is not - * safe to remove the else block, because ASI will not add a semicolon - * after the remaining else block contents - */ - if (nextTokenUnsafe || (nextTokenOnSameLine && nextToken.value !== "}")) { - return null; - } - } - - if (startToken.type === "Punctuator" && startToken.value === "{") { - fixedSource = source.slice(1, -1); - } else { - fixedSource = source; - } - - /* - * Extend the replacement range to include the entire - * function to avoid conflicting with no-useless-return. - * https://github.com/eslint/eslint/issues/8026 - * - * Also, to avoid name collisions between two else blocks. - */ - return new FixTracker(fixer, sourceCode) - .retainEnclosingFunction(node) - .replaceTextRange([elseToken.range[0], node.range[1]], fixedSource); - } - }); - } - - /** - * Check to see if the node is a ReturnStatement - * @param {Node} node The node being evaluated - * @returns {boolean} True if node is a return - */ - function checkForReturn(node) { - return node.type === "ReturnStatement"; - } - - /** - * Naive return checking, does not iterate through the whole - * BlockStatement because we make the assumption that the ReturnStatement - * will be the last node in the body of the BlockStatement. - * @param {Node} node The consequent/alternate node - * @returns {boolean} True if it has a return - */ - function naiveHasReturn(node) { - if (node.type === "BlockStatement") { - const body = node.body, - lastChildNode = body[body.length - 1]; - - return lastChildNode && checkForReturn(lastChildNode); - } - return checkForReturn(node); - } - - /** - * Check to see if the node is valid for evaluation, - * meaning it has an else. - * @param {Node} node The node being evaluated - * @returns {boolean} True if the node is valid - */ - function hasElse(node) { - return node.alternate && node.consequent; - } - - /** - * If the consequent is an IfStatement, check to see if it has an else - * and both its consequent and alternate path return, meaning this is - * a nested case of rule violation. If-Else not considered currently. - * @param {Node} node The consequent node - * @returns {boolean} True if this is a nested rule violation - */ - function checkForIf(node) { - return node.type === "IfStatement" && hasElse(node) && - naiveHasReturn(node.alternate) && naiveHasReturn(node.consequent); - } - - /** - * Check the consequent/body node to make sure it is not - * a ReturnStatement or an IfStatement that returns on both - * code paths. - * @param {Node} node The consequent or body node - * @returns {boolean} `true` if it is a Return/If node that always returns. - */ - function checkForReturnOrIf(node) { - return checkForReturn(node) || checkForIf(node); - } - - - /** - * Check whether a node returns in every codepath. - * @param {Node} node The node to be checked - * @returns {boolean} `true` if it returns on every codepath. - */ - function alwaysReturns(node) { - if (node.type === "BlockStatement") { - - // If we have a BlockStatement, check each consequent body node. - return node.body.some(checkForReturnOrIf); - } - - /* - * If not a block statement, make sure the consequent isn't a - * ReturnStatement or an IfStatement with returns on both paths. - */ - return checkForReturnOrIf(node); - } - - - /** - * Check the if statement, but don't catch else-if blocks. - * @returns {void} - * @param {Node} node The node for the if statement to check - * @private - */ - function checkIfWithoutElse(node) { - const parent = node.parent; - - /* - * Fixing this would require splitting one statement into two, so no error should - * be reported if this node is in a position where only one statement is allowed. - */ - if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { - return; - } - - const consequents = []; - let alternate; - - for (let currentNode = node; currentNode.type === "IfStatement"; currentNode = currentNode.alternate) { - if (!currentNode.alternate) { - return; - } - consequents.push(currentNode.consequent); - alternate = currentNode.alternate; - } - - if (consequents.every(alwaysReturns)) { - displayReport(alternate); - } - } - - /** - * Check the if statement - * @returns {void} - * @param {Node} node The node for the if statement to check - * @private - */ - function checkIfWithElse(node) { - const parent = node.parent; - - - /* - * Fixing this would require splitting one statement into two, so no error should - * be reported if this node is in a position where only one statement is allowed. - */ - if (!astUtils.STATEMENT_LIST_PARENTS.has(parent.type)) { - return; - } - - const alternate = node.alternate; - - if (alternate && alwaysReturns(node.consequent)) { - displayReport(alternate); - } - } - - const allowElseIf = !(context.options[0] && context.options[0].allowElseIf === false); - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - "IfStatement:exit": allowElseIf ? checkIfWithoutElse : checkIfWithElse - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty-character-class.js b/tools/node_modules/eslint/lib/rules/no-empty-character-class.js deleted file mode 100644 index 7dc219fe1a76c5de9cb3b13330c4f8b256b5a141..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty-character-class.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Rule to flag the use of empty character classes in regular expressions - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/* - * plain-English description of the following regexp: - * 0. `^` fix the match at the beginning of the string - * 1. `\/`: the `/` that begins the regexp - * 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following - * 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) - * 2.1. `\\.`: an escape sequence - * 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty - * 3. `\/` the `/` that ends the regexp - * 4. `[gimuy]*`: optional regexp flags - * 5. `$`: fix the match at the end of the string - */ -const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimuys]*$/u; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow empty character classes in regular expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-empty-character-class" - }, - - schema: [], - - messages: { - unexpected: "Empty class." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - - Literal(node) { - const token = sourceCode.getFirstToken(node); - - if (token.type === "RegularExpression" && !regex.test(token.value)) { - context.report({ node, messageId: "unexpected" }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty-function.js b/tools/node_modules/eslint/lib/rules/no-empty-function.js deleted file mode 100644 index c512f8cd5f45004b00c0d927ad279a8c38dcc5f8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty-function.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @fileoverview Rule to disallow empty functions. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const ALLOW_OPTIONS = Object.freeze([ - "functions", - "arrowFunctions", - "generatorFunctions", - "methods", - "generatorMethods", - "getters", - "setters", - "constructors", - "asyncFunctions", - "asyncMethods" -]); - -/** - * Gets the kind of a given function node. - * @param {ASTNode} node A function node to get. This is one of - * an ArrowFunctionExpression, a FunctionDeclaration, or a - * FunctionExpression. - * @returns {string} The kind of the function. This is one of "functions", - * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods", - * "generatorMethods", "asyncMethods", "getters", "setters", and - * "constructors". - */ -function getKind(node) { - const parent = node.parent; - let kind = ""; - - if (node.type === "ArrowFunctionExpression") { - return "arrowFunctions"; - } - - // Detects main kind. - if (parent.type === "Property") { - if (parent.kind === "get") { - return "getters"; - } - if (parent.kind === "set") { - return "setters"; - } - kind = parent.method ? "methods" : "functions"; - - } else if (parent.type === "MethodDefinition") { - if (parent.kind === "get") { - return "getters"; - } - if (parent.kind === "set") { - return "setters"; - } - if (parent.kind === "constructor") { - return "constructors"; - } - kind = "methods"; - - } else { - kind = "functions"; - } - - // Detects prefix. - let prefix = ""; - - if (node.generator) { - prefix = "generator"; - } else if (node.async) { - prefix = "async"; - } else { - return kind; - } - return prefix + kind[0].toUpperCase() + kind.slice(1); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow empty functions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-empty-function" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { enum: ALLOW_OPTIONS }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Unexpected empty {{name}}." - } - }, - - create(context) { - const options = context.options[0] || {}; - const allowed = options.allow || []; - - const sourceCode = context.getSourceCode(); - - /** - * Reports a given function node if the node matches the following patterns. - * - * - Not allowed by options. - * - The body is empty. - * - The body doesn't have any comments. - * @param {ASTNode} node A function node to report. This is one of - * an ArrowFunctionExpression, a FunctionDeclaration, or a - * FunctionExpression. - * @returns {void} - */ - function reportIfEmpty(node) { - const kind = getKind(node); - const name = astUtils.getFunctionNameWithKind(node); - const innerComments = sourceCode.getTokens(node.body, { - includeComments: true, - filter: astUtils.isCommentToken - }); - - if (allowed.indexOf(kind) === -1 && - node.body.type === "BlockStatement" && - node.body.body.length === 0 && - innerComments.length === 0 - ) { - context.report({ - node, - loc: node.body.loc, - messageId: "unexpected", - data: { name } - }); - } - } - - return { - ArrowFunctionExpression: reportIfEmpty, - FunctionDeclaration: reportIfEmpty, - FunctionExpression: reportIfEmpty - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty-pattern.js b/tools/node_modules/eslint/lib/rules/no-empty-pattern.js deleted file mode 100644 index 9f34bfde92e2e9dc225ed2ed2480a9fef96abfea..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty-pattern.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Rule to disallow an empty pattern - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow empty destructuring patterns", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-empty-pattern" - }, - - schema: [], - - messages: { - unexpected: "Unexpected empty {{type}} pattern." - } - }, - - create(context) { - return { - ObjectPattern(node) { - if (node.properties.length === 0) { - context.report({ node, messageId: "unexpected", data: { type: "object" } }); - } - }, - ArrayPattern(node) { - if (node.elements.length === 0) { - context.report({ node, messageId: "unexpected", data: { type: "array" } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-empty.js b/tools/node_modules/eslint/lib/rules/no-empty.js deleted file mode 100644 index 45bf03c13aee5f39661ce8056ebe37b558e791b4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-empty.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @fileoverview Rule to flag use of an empty block statement - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow empty block statements", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-empty" - }, - - schema: [ - { - type: "object", - properties: { - allowEmptyCatch: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "Empty {{type}} statement." - } - }, - - create(context) { - const options = context.options[0] || {}, - allowEmptyCatch = options.allowEmptyCatch || false; - - const sourceCode = context.getSourceCode(); - - return { - BlockStatement(node) { - - // if the body is not empty, we can just return immediately - if (node.body.length !== 0) { - return; - } - - // a function is generally allowed to be empty - if (astUtils.isFunction(node.parent)) { - return; - } - - if (allowEmptyCatch && node.parent.type === "CatchClause") { - return; - } - - // any other block is only allowed to be empty, if it contains a comment - if (sourceCode.getCommentsInside(node).length > 0) { - return; - } - - context.report({ node, messageId: "unexpected", data: { type: "block" } }); - }, - - SwitchStatement(node) { - - if (typeof node.cases === "undefined" || node.cases.length === 0) { - context.report({ node, messageId: "unexpected", data: { type: "switch" } }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-eq-null.js b/tools/node_modules/eslint/lib/rules/no-eq-null.js deleted file mode 100644 index b8dead96d2514c58821036667d57b7763a668d01..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-eq-null.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Rule to flag comparisons to null without a type-checking - * operator. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `null` comparisons without type-checking operators", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-eq-null" - }, - - schema: [], - - messages: { - unexpected: "Use '===' to compare with null." - } - }, - - create(context) { - - return { - - BinaryExpression(node) { - const badOperator = node.operator === "==" || node.operator === "!="; - - if (node.right.type === "Literal" && node.right.raw === "null" && badOperator || - node.left.type === "Literal" && node.left.raw === "null" && badOperator) { - context.report({ node, messageId: "unexpected" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-eval.js b/tools/node_modules/eslint/lib/rules/no-eval.js deleted file mode 100644 index a020fdee014a201c0ba77adf0a908b40e620892e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-eval.js +++ /dev/null @@ -1,277 +0,0 @@ -/** - * @fileoverview Rule to flag use of eval() statement - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const candidatesOfGlobalObject = Object.freeze([ - "global", - "window", - "globalThis" -]); - -/** - * Checks a given node is a MemberExpression node which has the specified name's - * property. - * @param {ASTNode} node A node to check. - * @param {string} name A name to check. - * @returns {boolean} `true` if the node is a MemberExpression node which has - * the specified name's property - */ -function isMember(node, name) { - return astUtils.isSpecificMemberAccess(node, null, name); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `eval()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-eval" - }, - - schema: [ - { - type: "object", - properties: { - allowIndirect: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "eval can be harmful." - } - }, - - create(context) { - const allowIndirect = Boolean( - context.options[0] && - context.options[0].allowIndirect - ); - const sourceCode = context.getSourceCode(); - let funcInfo = null; - - /** - * Pushs a variable scope (Program or Function) information to the stack. - * - * This is used in order to check whether or not `this` binding is a - * reference to the global object. - * @param {ASTNode} node A node of the scope. This is one of Program, - * FunctionDeclaration, FunctionExpression, and ArrowFunctionExpression. - * @returns {void} - */ - function enterVarScope(node) { - const strict = context.getScope().isStrict; - - funcInfo = { - upper: funcInfo, - node, - strict, - defaultThis: false, - initialized: strict - }; - } - - /** - * Pops a variable scope from the stack. - * @returns {void} - */ - function exitVarScope() { - funcInfo = funcInfo.upper; - } - - /** - * Reports a given node. - * - * `node` is `Identifier` or `MemberExpression`. - * The parent of `node` might be `CallExpression`. - * - * The location of the report is always `eval` `Identifier` (or possibly - * `Literal`). The type of the report is `CallExpression` if the parent is - * `CallExpression`. Otherwise, it's the given node type. - * @param {ASTNode} node A node to report. - * @returns {void} - */ - function report(node) { - const parent = node.parent; - const locationNode = node.type === "MemberExpression" - ? node.property - : node; - - const reportNode = parent.type === "CallExpression" && parent.callee === node - ? parent - : node; - - context.report({ - node: reportNode, - loc: locationNode.loc, - messageId: "unexpected" - }); - } - - /** - * Reports accesses of `eval` via the global object. - * @param {eslint-scope.Scope} globalScope The global scope. - * @returns {void} - */ - function reportAccessingEvalViaGlobalObject(globalScope) { - for (let i = 0; i < candidatesOfGlobalObject.length; ++i) { - const name = candidatesOfGlobalObject[i]; - const variable = astUtils.getVariableByName(globalScope, name); - - if (!variable) { - continue; - } - - const references = variable.references; - - for (let j = 0; j < references.length; ++j) { - const identifier = references[j].identifier; - let node = identifier.parent; - - // To detect code like `window.window.eval`. - while (isMember(node, name)) { - node = node.parent; - } - - // Reports. - if (isMember(node, "eval")) { - report(node); - } - } - } - } - - /** - * Reports all accesses of `eval` (excludes direct calls to eval). - * @param {eslint-scope.Scope} globalScope The global scope. - * @returns {void} - */ - function reportAccessingEval(globalScope) { - const variable = astUtils.getVariableByName(globalScope, "eval"); - - if (!variable) { - return; - } - - const references = variable.references; - - for (let i = 0; i < references.length; ++i) { - const reference = references[i]; - const id = reference.identifier; - - if (id.name === "eval" && !astUtils.isCallee(id)) { - - // Is accessing to eval (excludes direct calls to eval) - report(id); - } - } - } - - if (allowIndirect) { - - // Checks only direct calls to eval. It's simple! - return { - "CallExpression:exit"(node) { - const callee = node.callee; - - /* - * Optional call (`eval?.("code")`) is not direct eval. - * The direct eval is only step 6.a.vi of https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation - * But the optional call is https://tc39.es/ecma262/#sec-optional-chaining-chain-evaluation - */ - if (!node.optional && astUtils.isSpecificId(callee, "eval")) { - report(callee); - } - } - }; - } - - return { - "CallExpression:exit"(node) { - const callee = node.callee; - - if (astUtils.isSpecificId(callee, "eval")) { - report(callee); - } - }, - - Program(node) { - const scope = context.getScope(), - features = context.parserOptions.ecmaFeatures || {}, - strict = - scope.isStrict || - node.sourceType === "module" || - (features.globalReturn && scope.childScopes[0].isStrict); - - funcInfo = { - upper: null, - node, - strict, - defaultThis: true, - initialized: true - }; - }, - - "Program:exit"() { - const globalScope = context.getScope(); - - exitVarScope(); - reportAccessingEval(globalScope); - reportAccessingEvalViaGlobalObject(globalScope); - }, - - FunctionDeclaration: enterVarScope, - "FunctionDeclaration:exit": exitVarScope, - FunctionExpression: enterVarScope, - "FunctionExpression:exit": exitVarScope, - ArrowFunctionExpression: enterVarScope, - "ArrowFunctionExpression:exit": exitVarScope, - - ThisExpression(node) { - if (!isMember(node.parent, "eval")) { - return; - } - - /* - * `this.eval` is found. - * Checks whether or not the value of `this` is the global object. - */ - if (!funcInfo.initialized) { - funcInfo.initialized = true; - funcInfo.defaultThis = astUtils.isDefaultThisBinding( - funcInfo.node, - sourceCode - ); - } - - if (!funcInfo.strict && funcInfo.defaultThis) { - - // `this.eval` is possible built-in `eval`. - report(node.parent); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-ex-assign.js b/tools/node_modules/eslint/lib/rules/no-ex-assign.js deleted file mode 100644 index 1163920361d2d4bc999144217c8450586a7c476d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-ex-assign.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview Rule to flag assignment of the exception parameter - * @author Stephen Murray - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning exceptions in `catch` clauses", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-ex-assign" - }, - - schema: [], - - messages: { - unexpected: "Do not assign to the exception parameter." - } - }, - - create(context) { - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - astUtils.getModifyingReferences(variable.references).forEach(reference => { - context.report({ node: reference.identifier, messageId: "unexpected" }); - }); - } - - return { - CatchClause(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extend-native.js b/tools/node_modules/eslint/lib/rules/no-extend-native.js deleted file mode 100644 index db365b50924d7ab80a9cb56d69e1c1040fc9615b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extend-native.js +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @fileoverview Rule to flag adding properties to native object's prototypes. - * @author David Nelson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const globals = require("globals"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow extending native types", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-extend-native" - }, - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpected: "{{builtin}} prototype is read only, properties should not be added." - } - }, - - create(context) { - - const config = context.options[0] || {}; - const exceptions = new Set(config.exceptions || []); - const modifiedBuiltins = new Set( - Object.keys(globals.builtin) - .filter(builtin => builtin[0].toUpperCase() === builtin[0]) - .filter(builtin => !exceptions.has(builtin)) - ); - - /** - * Reports a lint error for the given node. - * @param {ASTNode} node The node to report. - * @param {string} builtin The name of the native builtin being extended. - * @returns {void} - */ - function reportNode(node, builtin) { - context.report({ - node, - messageId: "unexpected", - data: { - builtin - } - }); - } - - /** - * Check to see if the `prototype` property of the given object - * identifier node is being accessed. - * @param {ASTNode} identifierNode The Identifier representing the object - * to check. - * @returns {boolean} True if the identifier is the object of a - * MemberExpression and its `prototype` property is being accessed, - * false otherwise. - */ - function isPrototypePropertyAccessed(identifierNode) { - return Boolean( - identifierNode && - identifierNode.parent && - identifierNode.parent.type === "MemberExpression" && - identifierNode.parent.object === identifierNode && - astUtils.getStaticPropertyName(identifierNode.parent) === "prototype" - ); - } - - /** - * Check if it's an assignment to the property of the given node. - * Example: `*.prop = 0` // the `*` is the given node. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if an assignment to the property of the node. - */ - function isAssigningToPropertyOf(node) { - return ( - node.parent.type === "MemberExpression" && - node.parent.object === node && - node.parent.parent.type === "AssignmentExpression" && - node.parent.parent.left === node.parent - ); - } - - /** - * Checks if the given node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is at the first argument of the method call of `Object.defineProperty()` or `Object.defineProperties()`. - */ - function isInDefinePropertyCall(node) { - return ( - node.parent.type === "CallExpression" && - node.parent.arguments[0] === node && - astUtils.isSpecificMemberAccess(node.parent.callee, "Object", /^definePropert(?:y|ies)$/u) - ); - } - - /** - * Check to see if object prototype access is part of a prototype - * extension. There are three ways a prototype can be extended: - * 1. Assignment to prototype property (Object.prototype.foo = 1) - * 2. Object.defineProperty()/Object.defineProperties() on a prototype - * If prototype extension is detected, report the AssignmentExpression - * or CallExpression node. - * @param {ASTNode} identifierNode The Identifier representing the object - * which prototype is being accessed and possibly extended. - * @returns {void} - */ - function checkAndReportPrototypeExtension(identifierNode) { - if (!isPrototypePropertyAccessed(identifierNode)) { - return; // This is not `*.prototype` access. - } - - /* - * `identifierNode.parent` is a MamberExpression `*.prototype`. - * If it's an optional member access, it may be wrapped by a `ChainExpression` node. - */ - const prototypeNode = - identifierNode.parent.parent.type === "ChainExpression" - ? identifierNode.parent.parent - : identifierNode.parent; - - if (isAssigningToPropertyOf(prototypeNode)) { - - // `*.prototype` -> MemberExpression -> AssignmentExpression - reportNode(prototypeNode.parent.parent, identifierNode.name); - } else if (isInDefinePropertyCall(prototypeNode)) { - - // `*.prototype` -> CallExpression - reportNode(prototypeNode.parent, identifierNode.name); - } - } - - return { - - "Program:exit"() { - const globalScope = context.getScope(); - - modifiedBuiltins.forEach(builtin => { - const builtinVar = globalScope.set.get(builtin); - - if (builtinVar && builtinVar.references) { - builtinVar.references - .map(ref => ref.identifier) - .forEach(checkAndReportPrototypeExtension); - } - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-bind.js b/tools/node_modules/eslint/lib/rules/no-extra-bind.js deleted file mode 100644 index 2db440dc1ea9b7beba32f9a05c89c5700e770b0d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-bind.js +++ /dev/null @@ -1,213 +0,0 @@ -/** - * @fileoverview Rule to flag unnecessary bind calls - * @author Bence Dányi - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SIDE_EFFECT_FREE_NODE_TYPES = new Set(["Literal", "Identifier", "ThisExpression", "FunctionExpression"]); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary calls to `.bind()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-extra-bind" - }, - - schema: [], - fixable: "code", - - messages: { - unexpected: "The function binding is unnecessary." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Checks if a node is free of side effects. - * - * This check is stricter than it needs to be, in order to keep the implementation simple. - * @param {ASTNode} node A node to check. - * @returns {boolean} True if the node is known to be side-effect free, false otherwise. - */ - function isSideEffectFree(node) { - return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type); - } - - /** - * Reports a given function node. - * @param {ASTNode} node A node to report. This is a FunctionExpression or - * an ArrowFunctionExpression. - * @returns {void} - */ - function report(node) { - const memberNode = node.parent; - const callNode = memberNode.parent.type === "ChainExpression" - ? memberNode.parent.parent - : memberNode.parent; - - context.report({ - node: callNode, - messageId: "unexpected", - loc: memberNode.property.loc, - - fix(fixer) { - if (!isSideEffectFree(callNode.arguments[0])) { - return null; - } - - /* - * The list of the first/last token pair of a removal range. - * This is two parts because closing parentheses may exist between the method name and arguments. - * E.g. `(function(){}.bind ) (obj)` - * ^^^^^ ^^^^^ < removal ranges - * E.g. `(function(){}?.['bind'] ) ?.(obj)` - * ^^^^^^^^^^ ^^^^^^^ < removal ranges - */ - const tokenPairs = [ - [ - - // `.`, `?.`, or `[` token. - sourceCode.getTokenAfter( - memberNode.object, - astUtils.isNotClosingParenToken - ), - - // property name or `]` token. - sourceCode.getLastToken(memberNode) - ], - [ - - // `?.` or `(` token of arguments. - sourceCode.getTokenAfter( - memberNode, - astUtils.isNotClosingParenToken - ), - - // `)` token of arguments. - sourceCode.getLastToken(callNode) - ] - ]; - const firstTokenToRemove = tokenPairs[0][0]; - const lastTokenToRemove = tokenPairs[1][1]; - - if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) { - return null; - } - - return tokenPairs.map(([start, end]) => - fixer.removeRange([start.range[0], end.range[1]])); - } - }); - } - - /** - * Checks whether or not a given function node is the callee of `.bind()` - * method. - * - * e.g. `(function() {}.bind(foo))` - * @param {ASTNode} node A node to report. This is a FunctionExpression or - * an ArrowFunctionExpression. - * @returns {boolean} `true` if the node is the callee of `.bind()` method. - */ - function isCalleeOfBindMethod(node) { - if (!astUtils.isSpecificMemberAccess(node.parent, null, "bind")) { - return false; - } - - // The node of `*.bind` member access. - const bindNode = node.parent.parent.type === "ChainExpression" - ? node.parent.parent - : node.parent; - - return ( - bindNode.parent.type === "CallExpression" && - bindNode.parent.callee === bindNode && - bindNode.parent.arguments.length === 1 && - bindNode.parent.arguments[0].type !== "SpreadElement" - ); - } - - /** - * Adds a scope information object to the stack. - * @param {ASTNode} node A node to add. This node is a FunctionExpression - * or a FunctionDeclaration node. - * @returns {void} - */ - function enterFunction(node) { - scopeInfo = { - isBound: isCalleeOfBindMethod(node), - thisFound: false, - upper: scopeInfo - }; - } - - /** - * Removes the scope information object from the top of the stack. - * At the same time, this reports the function node if the function has - * `.bind()` and the `this` keywords found. - * @param {ASTNode} node A node to remove. This node is a - * FunctionExpression or a FunctionDeclaration node. - * @returns {void} - */ - function exitFunction(node) { - if (scopeInfo.isBound && !scopeInfo.thisFound) { - report(node); - } - - scopeInfo = scopeInfo.upper; - } - - /** - * Reports a given arrow function if the function is callee of `.bind()` - * method. - * @param {ASTNode} node A node to report. This node is an - * ArrowFunctionExpression. - * @returns {void} - */ - function exitArrowFunction(node) { - if (isCalleeOfBindMethod(node)) { - report(node); - } - } - - /** - * Set the mark as the `this` keyword was found in this scope. - * @returns {void} - */ - function markAsThisFound() { - if (scopeInfo) { - scopeInfo.thisFound = true; - } - } - - return { - "ArrowFunctionExpression:exit": exitArrowFunction, - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - ThisExpression: markAsThisFound - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js b/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js deleted file mode 100644 index 6ae3ea62ca77d67b064f113d197e03f137893f1a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-boolean-cast.js +++ /dev/null @@ -1,316 +0,0 @@ -/** - * @fileoverview Rule to flag unnecessary double negation in Boolean contexts - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const eslintUtils = require("eslint-utils"); - -const precedence = astUtils.getPrecedence; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary boolean casts", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-extra-boolean-cast" - }, - - schema: [{ - type: "object", - properties: { - enforceForLogicalOperands: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - fixable: "code", - - messages: { - unexpectedCall: "Redundant Boolean call.", - unexpectedNegation: "Redundant double negation." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - // Node types which have a test which will coerce values to booleans. - const BOOLEAN_NODE_TYPES = [ - "IfStatement", - "DoWhileStatement", - "WhileStatement", - "ConditionalExpression", - "ForStatement" - ]; - - /** - * Check if a node is a Boolean function or constructor. - * @param {ASTNode} node the node - * @returns {boolean} If the node is Boolean function or constructor - */ - function isBooleanFunctionOrConstructorCall(node) { - - // Boolean() and new Boolean() - return (node.type === "CallExpression" || node.type === "NewExpression") && - node.callee.type === "Identifier" && - node.callee.name === "Boolean"; - } - - /** - * Checks whether the node is a logical expression and that the option is enabled - * @param {ASTNode} node the node - * @returns {boolean} if the node is a logical expression and option is enabled - */ - function isLogicalContext(node) { - return node.type === "LogicalExpression" && - (node.operator === "||" || node.operator === "&&") && - (context.options.length && context.options[0].enforceForLogicalOperands === true); - - } - - - /** - * Check if a node is in a context where its value would be coerced to a boolean at runtime. - * @param {ASTNode} node The node - * @returns {boolean} If it is in a boolean context - */ - function isInBooleanContext(node) { - return ( - (isBooleanFunctionOrConstructorCall(node.parent) && - node === node.parent.arguments[0]) || - - (BOOLEAN_NODE_TYPES.indexOf(node.parent.type) !== -1 && - node === node.parent.test) || - - // ! - (node.parent.type === "UnaryExpression" && - node.parent.operator === "!") - ); - } - - /** - * Checks whether the node is a context that should report an error - * Acts recursively if it is in a logical context - * @param {ASTNode} node the node - * @returns {boolean} If the node is in one of the flagged contexts - */ - function isInFlaggedContext(node) { - if (node.parent.type === "ChainExpression") { - return isInFlaggedContext(node.parent); - } - - return isInBooleanContext(node) || - (isLogicalContext(node.parent) && - - // For nested logical statements - isInFlaggedContext(node.parent) - ); - } - - - /** - * Check if a node has comments inside. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if it has comments inside. - */ - function hasCommentsInside(node) { - return Boolean(sourceCode.getCommentsInside(node).length); - } - - /** - * Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is parenthesized. - * @private - */ - function isParenthesized(node) { - return eslintUtils.isParenthesized(1, node, sourceCode); - } - - /** - * Determines whether the given node needs to be parenthesized when replacing the previous node. - * It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list - * of possible parent node types. By the same assumption, the node's role in a particular parent is already known. - * For example, if the parent is `ConditionalExpression`, `previousNode` must be its `test` child. - * @param {ASTNode} previousNode Previous node. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node needs to be parenthesized. - */ - function needsParens(previousNode, node) { - if (previousNode.parent.type === "ChainExpression") { - return needsParens(previousNode.parent, node); - } - if (isParenthesized(previousNode)) { - - // parentheses around the previous node will stay, so there is no need for an additional pair - return false; - } - - // parent of the previous node will become parent of the replacement node - const parent = previousNode.parent; - - switch (parent.type) { - case "CallExpression": - case "NewExpression": - return node.type === "SequenceExpression"; - case "IfStatement": - case "DoWhileStatement": - case "WhileStatement": - case "ForStatement": - return false; - case "ConditionalExpression": - return precedence(node) <= precedence(parent); - case "UnaryExpression": - return precedence(node) < precedence(parent); - case "LogicalExpression": - if (astUtils.isMixedLogicalAndCoalesceExpressions(node, parent)) { - return true; - } - if (previousNode === parent.left) { - return precedence(node) < precedence(parent); - } - return precedence(node) <= precedence(parent); - - /* istanbul ignore next */ - default: - throw new Error(`Unexpected parent type: ${parent.type}`); - } - } - - return { - UnaryExpression(node) { - const parent = node.parent; - - - // Exit early if it's guaranteed not to match - if (node.operator !== "!" || - parent.type !== "UnaryExpression" || - parent.operator !== "!") { - return; - } - - - if (isInFlaggedContext(parent)) { - context.report({ - node: parent, - messageId: "unexpectedNegation", - fix(fixer) { - if (hasCommentsInside(parent)) { - return null; - } - - if (needsParens(parent, node.argument)) { - return fixer.replaceText(parent, `(${sourceCode.getText(node.argument)})`); - } - - let prefix = ""; - const tokenBefore = sourceCode.getTokenBefore(parent); - const firstReplacementToken = sourceCode.getFirstToken(node.argument); - - if ( - tokenBefore && - tokenBefore.range[1] === parent.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken) - ) { - prefix = " "; - } - - return fixer.replaceText(parent, prefix + sourceCode.getText(node.argument)); - } - }); - } - }, - - CallExpression(node) { - if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") { - return; - } - - if (isInFlaggedContext(node)) { - context.report({ - node, - messageId: "unexpectedCall", - fix(fixer) { - const parent = node.parent; - - if (node.arguments.length === 0) { - if (parent.type === "UnaryExpression" && parent.operator === "!") { - - /* - * !Boolean() -> true - */ - - if (hasCommentsInside(parent)) { - return null; - } - - const replacement = "true"; - let prefix = ""; - const tokenBefore = sourceCode.getTokenBefore(parent); - - if ( - tokenBefore && - tokenBefore.range[1] === parent.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, replacement) - ) { - prefix = " "; - } - - return fixer.replaceText(parent, prefix + replacement); - } - - /* - * Boolean() -> false - */ - - if (hasCommentsInside(node)) { - return null; - } - - return fixer.replaceText(node, "false"); - } - - if (node.arguments.length === 1) { - const argument = node.arguments[0]; - - if (argument.type === "SpreadElement" || hasCommentsInside(node)) { - return null; - } - - /* - * Boolean(expression) -> expression - */ - - if (needsParens(node, argument)) { - return fixer.replaceText(node, `(${sourceCode.getText(argument)})`); - } - - return fixer.replaceText(node, sourceCode.getText(argument)); - } - - // two or more arguments - return null; - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-label.js b/tools/node_modules/eslint/lib/rules/no-extra-label.js deleted file mode 100644 index 81406e7609573322747299c8a61350fc0fa169b7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-label.js +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @fileoverview Rule to disallow unnecessary labels - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary labels", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-extra-label" - }, - - schema: [], - fixable: "code", - - messages: { - unexpected: "This label '{{name}}' is unnecessary." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Creates a new scope with a breakable statement. - * @param {ASTNode} node A node to create. This is a BreakableStatement. - * @returns {void} - */ - function enterBreakableStatement(node) { - scopeInfo = { - label: node.parent.type === "LabeledStatement" ? node.parent.label : null, - breakable: true, - upper: scopeInfo - }; - } - - /** - * Removes the top scope of the stack. - * @returns {void} - */ - function exitBreakableStatement() { - scopeInfo = scopeInfo.upper; - } - - /** - * Creates a new scope with a labeled statement. - * - * This ignores it if the body is a breakable statement. - * In this case it's handled in the `enterBreakableStatement` function. - * @param {ASTNode} node A node to create. This is a LabeledStatement. - * @returns {void} - */ - function enterLabeledStatement(node) { - if (!astUtils.isBreakableStatement(node.body)) { - scopeInfo = { - label: node.label, - breakable: false, - upper: scopeInfo - }; - } - } - - /** - * Removes the top scope of the stack. - * - * This ignores it if the body is a breakable statement. - * In this case it's handled in the `exitBreakableStatement` function. - * @param {ASTNode} node A node. This is a LabeledStatement. - * @returns {void} - */ - function exitLabeledStatement(node) { - if (!astUtils.isBreakableStatement(node.body)) { - scopeInfo = scopeInfo.upper; - } - } - - /** - * Reports a given control node if it's unnecessary. - * @param {ASTNode} node A node. This is a BreakStatement or a - * ContinueStatement. - * @returns {void} - */ - function reportIfUnnecessary(node) { - if (!node.label) { - return; - } - - const labelNode = node.label; - - for (let info = scopeInfo; info !== null; info = info.upper) { - if (info.breakable || info.label && info.label.name === labelNode.name) { - if (info.breakable && info.label && info.label.name === labelNode.name) { - context.report({ - node: labelNode, - messageId: "unexpected", - data: labelNode, - fix(fixer) { - const breakOrContinueToken = sourceCode.getFirstToken(node); - - if (sourceCode.commentsExistBetween(breakOrContinueToken, labelNode)) { - return null; - } - - return fixer.removeRange([breakOrContinueToken.range[1], labelNode.range[1]]); - } - }); - } - return; - } - } - } - - return { - WhileStatement: enterBreakableStatement, - "WhileStatement:exit": exitBreakableStatement, - DoWhileStatement: enterBreakableStatement, - "DoWhileStatement:exit": exitBreakableStatement, - ForStatement: enterBreakableStatement, - "ForStatement:exit": exitBreakableStatement, - ForInStatement: enterBreakableStatement, - "ForInStatement:exit": exitBreakableStatement, - ForOfStatement: enterBreakableStatement, - "ForOfStatement:exit": exitBreakableStatement, - SwitchStatement: enterBreakableStatement, - "SwitchStatement:exit": exitBreakableStatement, - LabeledStatement: enterLabeledStatement, - "LabeledStatement:exit": exitLabeledStatement, - BreakStatement: reportIfUnnecessary, - ContinueStatement: reportIfUnnecessary - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-parens.js b/tools/node_modules/eslint/lib/rules/no-extra-parens.js deleted file mode 100644 index 0077ea4f6988e540b1207c5892b228cabf591310..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-parens.js +++ /dev/null @@ -1,1159 +0,0 @@ -/** - * @fileoverview Disallow parenthesising higher precedence subexpressions. - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const { isParenthesized: isParenthesizedRaw } = require("eslint-utils"); -const astUtils = require("./utils/ast-utils.js"); - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow unnecessary parentheses", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-extra-parens" - }, - - fixable: "code", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["functions"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["all"] - }, - { - type: "object", - properties: { - conditionalAssign: { type: "boolean" }, - nestedBinaryExpressions: { type: "boolean" }, - returnAssign: { type: "boolean" }, - ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] }, - enforceForArrowConditionals: { type: "boolean" }, - enforceForSequenceExpressions: { type: "boolean" }, - enforceForNewInMemberExpressions: { type: "boolean" }, - enforceForFunctionPrototypeMethods: { type: "boolean" } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - messages: { - unexpected: "Unnecessary parentheses around expression." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const tokensToIgnore = new WeakSet(); - const precedence = astUtils.getPrecedence; - const ALL_NODES = context.options[0] !== "functions"; - const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false; - const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false; - const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false; - const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX; - const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] && - context.options[1].enforceForArrowConditionals === false; - const IGNORE_SEQUENCE_EXPRESSIONS = ALL_NODES && context.options[1] && - context.options[1].enforceForSequenceExpressions === false; - const IGNORE_NEW_IN_MEMBER_EXPR = ALL_NODES && context.options[1] && - context.options[1].enforceForNewInMemberExpressions === false; - const IGNORE_FUNCTION_PROTOTYPE_METHODS = ALL_NODES && context.options[1] && - context.options[1].enforceForFunctionPrototypeMethods === false; - - const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" }); - const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" }); - - let reportsBuffer; - - /** - * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node. - * Example: function(){}.call() - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is an immediate `call` or `apply` method call. - * @private - */ - function isImmediateFunctionPrototypeMethodCall(node) { - const callNode = astUtils.skipChainExpression(node); - - if (callNode.type !== "CallExpression") { - return false; - } - const callee = astUtils.skipChainExpression(callNode.callee); - - return ( - callee.type === "MemberExpression" && - callee.object.type === "FunctionExpression" && - ["call", "apply"].includes(astUtils.getStaticPropertyName(callee)) - ); - } - - /** - * Determines if this rule should be enforced for a node given the current configuration. - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the rule should be enforced for this node. - * @private - */ - function ruleApplies(node) { - if (node.type === "JSXElement" || node.type === "JSXFragment") { - const isSingleLine = node.loc.start.line === node.loc.end.line; - - switch (IGNORE_JSX) { - - // Exclude this JSX element from linting - case "all": - return false; - - // Exclude this JSX element if it is multi-line element - case "multi-line": - return isSingleLine; - - // Exclude this JSX element if it is single-line element - case "single-line": - return !isSingleLine; - - // Nothing special to be done for JSX elements - case "none": - break; - - // no default - } - } - - if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) { - return false; - } - - if (isImmediateFunctionPrototypeMethodCall(node) && IGNORE_FUNCTION_PROTOTYPE_METHODS) { - return false; - } - - return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; - } - - /** - * Determines if a node is surrounded by parentheses. - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is parenthesised. - * @private - */ - function isParenthesised(node) { - return isParenthesizedRaw(1, node, sourceCode); - } - - /** - * Determines if a node is surrounded by parentheses twice. - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is doubly parenthesised. - * @private - */ - function isParenthesisedTwice(node) { - return isParenthesizedRaw(2, node, sourceCode); - } - - /** - * Determines if a node is surrounded by (potentially) invalid parentheses. - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is incorrectly parenthesised. - * @private - */ - function hasExcessParens(node) { - return ruleApplies(node) && isParenthesised(node); - } - - /** - * Determines if a node that is expected to be parenthesised is surrounded by - * (potentially) invalid extra parentheses. - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. - * @private - */ - function hasDoubleExcessParens(node) { - return ruleApplies(node) && isParenthesisedTwice(node); - } - - /** - * Determines if a node that is expected to be parenthesised is surrounded by - * (potentially) invalid extra parentheses with considering precedence level of the node. - * If the preference level of the node is not higher or equal to precedence lower limit, it also checks - * whether the node is surrounded by parentheses twice or not. - * @param {ASTNode} node The node to be checked. - * @param {number} precedenceLowerLimit The lower limit of precedence. - * @returns {boolean} True if the node is has an unexpected extra pair of parentheses. - * @private - */ - function hasExcessParensWithPrecedence(node, precedenceLowerLimit) { - if (ruleApplies(node) && isParenthesised(node)) { - if ( - precedence(node) >= precedenceLowerLimit || - isParenthesisedTwice(node) - ) { - return true; - } - } - return false; - } - - /** - * Determines if a node test expression is allowed to have a parenthesised assignment - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the assignment can be parenthesised. - * @private - */ - function isCondAssignException(node) { - return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression"; - } - - /** - * Determines if a node is in a return statement - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is in a return statement. - * @private - */ - function isInReturnStatement(node) { - for (let currentNode = node; currentNode; currentNode = currentNode.parent) { - if ( - currentNode.type === "ReturnStatement" || - (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement") - ) { - return true; - } - } - - return false; - } - - /** - * Determines if a constructor function is newed-up with parens - * @param {ASTNode} newExpression The NewExpression node to be checked. - * @returns {boolean} True if the constructor is called with parens. - * @private - */ - function isNewExpressionWithParens(newExpression) { - const lastToken = sourceCode.getLastToken(newExpression); - const penultimateToken = sourceCode.getTokenBefore(lastToken); - - return newExpression.arguments.length > 0 || - ( - - // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens - astUtils.isOpeningParenToken(penultimateToken) && - astUtils.isClosingParenToken(lastToken) && - newExpression.callee.range[1] < newExpression.range[1] - ); - } - - /** - * Determines if a node is or contains an assignment expression - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is or contains an assignment expression. - * @private - */ - function containsAssignment(node) { - if (node.type === "AssignmentExpression") { - return true; - } - if (node.type === "ConditionalExpression" && - (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) { - return true; - } - if ((node.left && node.left.type === "AssignmentExpression") || - (node.right && node.right.type === "AssignmentExpression")) { - return true; - } - - return false; - } - - /** - * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the assignment can be parenthesised. - * @private - */ - function isReturnAssignException(node) { - if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) { - return false; - } - - if (node.type === "ReturnStatement") { - return node.argument && containsAssignment(node.argument); - } - if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") { - return containsAssignment(node.body); - } - return containsAssignment(node); - - } - - /** - * Determines if a node following a [no LineTerminator here] restriction is - * surrounded by (potentially) invalid extra parentheses. - * @param {Token} token The token preceding the [no LineTerminator here] restriction. - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is incorrectly parenthesised. - * @private - */ - function hasExcessParensNoLineTerminator(token, node) { - if (token.loc.end.line === node.loc.start.line) { - return hasExcessParens(node); - } - - return hasDoubleExcessParens(node); - } - - /** - * Determines whether a node should be preceded by an additional space when removing parens - * @param {ASTNode} node node to evaluate; must be surrounded by parentheses - * @returns {boolean} `true` if a space should be inserted before the node - * @private - */ - function requiresLeadingSpace(node) { - const leftParenToken = sourceCode.getTokenBefore(node); - const tokenBeforeLeftParen = sourceCode.getTokenBefore(leftParenToken, { includeComments: true }); - const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParenToken, { includeComments: true }); - - return tokenBeforeLeftParen && - tokenBeforeLeftParen.range[1] === leftParenToken.range[0] && - leftParenToken.range[1] === tokenAfterLeftParen.range[0] && - !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen); - } - - /** - * Determines whether a node should be followed by an additional space when removing parens - * @param {ASTNode} node node to evaluate; must be surrounded by parentheses - * @returns {boolean} `true` if a space should be inserted after the node - * @private - */ - function requiresTrailingSpace(node) { - const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 }); - const rightParenToken = nextTwoTokens[0]; - const tokenAfterRightParen = nextTwoTokens[1]; - const tokenBeforeRightParen = sourceCode.getLastToken(node); - - return rightParenToken && tokenAfterRightParen && - !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) && - !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen); - } - - /** - * Determines if a given expression node is an IIFE - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if the given node is an IIFE - */ - function isIIFE(node) { - const maybeCallNode = astUtils.skipChainExpression(node); - - return maybeCallNode.type === "CallExpression" && maybeCallNode.callee.type === "FunctionExpression"; - } - - /** - * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment. - * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax, - * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary. - * @param {ASTNode} [node] The node to check - * @returns {boolean} `true` if the given node can be a valid assignment target - */ - function canBeAssignmentTarget(node) { - return node && (node.type === "Identifier" || node.type === "MemberExpression"); - } - - /** - * Report the node - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function report(node) { - const leftParenToken = sourceCode.getTokenBefore(node); - const rightParenToken = sourceCode.getTokenAfter(node); - - if (!isParenthesisedTwice(node)) { - if (tokensToIgnore.has(sourceCode.getFirstToken(node))) { - return; - } - - if (isIIFE(node) && !isParenthesised(node.callee)) { - return; - } - } - - /** - * Finishes reporting - * @returns {void} - * @private - */ - function finishReport() { - context.report({ - node, - loc: leftParenToken.loc, - messageId: "unexpected", - fix(fixer) { - const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]); - - return fixer.replaceTextRange([ - leftParenToken.range[0], - rightParenToken.range[1] - ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : "")); - } - }); - } - - if (reportsBuffer) { - reportsBuffer.reports.push({ node, finishReport }); - return; - } - - finishReport(); - } - - /** - * Evaluate a argument of the node. - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkArgumentWithPrecedence(node) { - if (hasExcessParensWithPrecedence(node.argument, precedence(node))) { - report(node.argument); - } - } - - /** - * Check if a member expression contains a call expression - * @param {ASTNode} node MemberExpression node to evaluate - * @returns {boolean} true if found, false if not - */ - function doesMemberExpressionContainCallExpression(node) { - let currentNode = node.object; - let currentNodeType = node.object.type; - - while (currentNodeType === "MemberExpression") { - currentNode = currentNode.object; - currentNodeType = currentNode.type; - } - - return currentNodeType === "CallExpression"; - } - - /** - * Evaluate a new call - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkCallNew(node) { - const callee = node.callee; - - if (hasExcessParensWithPrecedence(callee, precedence(node))) { - const hasNewParensException = callee.type === "NewExpression" && !isNewExpressionWithParens(callee); - - if ( - hasDoubleExcessParens(callee) || - !isIIFE(node) && - !hasNewParensException && - !( - - // Allow extra parens around a new expression if they are intervening parentheses. - node.type === "NewExpression" && - callee.type === "MemberExpression" && - doesMemberExpressionContainCallExpression(callee) - ) && - !(!node.optional && callee.type === "ChainExpression") - ) { - report(node.callee); - } - } - node.arguments - .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR)) - .forEach(report); - } - - /** - * Evaluate binary logicals - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkBinaryLogical(node) { - const prec = precedence(node); - const leftPrecedence = precedence(node.left); - const rightPrecedence = precedence(node.right); - const isExponentiation = node.operator === "**"; - const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression"); - const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression"); - - if (!shouldSkipLeft && hasExcessParens(node.left)) { - if ( - !(node.left.type === "UnaryExpression" && isExponentiation) && - !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) && - (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) || - isParenthesisedTwice(node.left) - ) { - report(node.left); - } - } - - if (!shouldSkipRight && hasExcessParens(node.right)) { - if ( - !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) && - (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) || - isParenthesisedTwice(node.right) - ) { - report(node.right); - } - } - } - - /** - * Check the parentheses around the super class of the given class definition. - * @param {ASTNode} node The node of class declarations to check. - * @returns {void} - */ - function checkClass(node) { - if (!node.superClass) { - return; - } - - /* - * If `node.superClass` is a LeftHandSideExpression, parentheses are extra. - * Otherwise, parentheses are needed. - */ - const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR - ? hasExcessParens(node.superClass) - : hasDoubleExcessParens(node.superClass); - - if (hasExtraParens) { - report(node.superClass); - } - } - - /** - * Check the parentheses around the argument of the given spread operator. - * @param {ASTNode} node The node of spread elements/properties to check. - * @returns {void} - */ - function checkSpreadOperator(node) { - if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { - report(node.argument); - } - } - - /** - * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration - * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node - * @returns {void} - */ - function checkExpressionOrExportStatement(node) { - const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node); - const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken); - const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null; - const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null; - - if ( - astUtils.isOpeningParenToken(firstToken) && - ( - astUtils.isOpeningBraceToken(secondToken) || - secondToken.type === "Keyword" && ( - secondToken.value === "function" || - secondToken.value === "class" || - secondToken.value === "let" && - tokenAfterClosingParens && - ( - astUtils.isOpeningBracketToken(tokenAfterClosingParens) || - tokenAfterClosingParens.type === "Identifier" - ) - ) || - secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function" - ) - ) { - tokensToIgnore.add(secondToken); - } - - const hasExtraParens = node.parent.type === "ExportDefaultDeclaration" - ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR) - : hasExcessParens(node); - - if (hasExtraParens) { - report(node); - } - } - - /** - * Finds the path from the given node to the specified ancestor. - * @param {ASTNode} node First node in the path. - * @param {ASTNode} ancestor Last node in the path. - * @returns {ASTNode[]} Path, including both nodes. - * @throws {Error} If the given node does not have the specified ancestor. - */ - function pathToAncestor(node, ancestor) { - const path = [node]; - let currentNode = node; - - while (currentNode !== ancestor) { - - currentNode = currentNode.parent; - - /* istanbul ignore if */ - if (currentNode === null) { - throw new Error("Nodes are not in the ancestor-descendant relationship."); - } - - path.push(currentNode); - } - - return path; - } - - /** - * Finds the path from the given node to the specified descendant. - * @param {ASTNode} node First node in the path. - * @param {ASTNode} descendant Last node in the path. - * @returns {ASTNode[]} Path, including both nodes. - * @throws {Error} If the given node does not have the specified descendant. - */ - function pathToDescendant(node, descendant) { - return pathToAncestor(descendant, node).reverse(); - } - - /** - * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer - * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop. - * @param {ASTNode} node Ancestor of an 'in' expression. - * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself. - * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis. - */ - function isSafelyEnclosingInExpression(node, child) { - switch (node.type) { - case "ArrayExpression": - case "ArrayPattern": - case "BlockStatement": - case "ObjectExpression": - case "ObjectPattern": - case "TemplateLiteral": - return true; - case "ArrowFunctionExpression": - case "FunctionExpression": - return node.params.includes(child); - case "CallExpression": - case "NewExpression": - return node.arguments.includes(child); - case "MemberExpression": - return node.computed && node.property === child; - case "ConditionalExpression": - return node.consequent === child; - default: - return false; - } - } - - /** - * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately. - * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings. - * @returns {void} - */ - function startNewReportsBuffering() { - reportsBuffer = { - upper: reportsBuffer, - inExpressionNodes: [], - reports: [] - }; - } - - /** - * Ends the current reports buffering. - * @returns {void} - */ - function endCurrentReportsBuffering() { - const { upper, inExpressionNodes, reports } = reportsBuffer; - - if (upper) { - upper.inExpressionNodes.push(...inExpressionNodes); - upper.reports.push(...reports); - } else { - - // flush remaining reports - reports.forEach(({ finishReport }) => finishReport()); - } - - reportsBuffer = upper; - } - - /** - * Checks whether the given node is in the current reports buffer. - * @param {ASTNode} node Node to check. - * @returns {boolean} True if the node is in the current buffer, false otherwise. - */ - function isInCurrentReportsBuffer(node) { - return reportsBuffer.reports.some(r => r.node === node); - } - - /** - * Removes the given node from the current reports buffer. - * @param {ASTNode} node Node to remove. - * @returns {void} - */ - function removeFromCurrentReportsBuffer(node) { - reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node); - } - - return { - ArrayExpression(node) { - node.elements - .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR)) - .forEach(report); - }, - - ArrayPattern(node) { - node.elements - .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e)) - .forEach(report); - }, - - ArrowFunctionExpression(node) { - if (isReturnAssignException(node)) { - return; - } - - if (node.body.type === "ConditionalExpression" && - IGNORE_ARROW_CONDITIONALS - ) { - return; - } - - if (node.body.type !== "BlockStatement") { - const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken); - const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken); - - if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) { - tokensToIgnore.add(firstBodyToken); - } - if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { - report(node.body); - } - } - }, - - AssignmentExpression(node) { - if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) { - report(node.left); - } - - if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) { - report(node.right); - } - }, - - BinaryExpression(node) { - if (reportsBuffer && node.operator === "in") { - reportsBuffer.inExpressionNodes.push(node); - } - - checkBinaryLogical(node); - }, - - CallExpression: checkCallNew, - - ClassBody(node) { - node.body - .filter(member => member.type === "MethodDefinition" && member.computed && member.key) - .filter(member => hasExcessParensWithPrecedence(member.key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) - .forEach(member => report(member.key)); - }, - - ConditionalExpression(node) { - if (isReturnAssignException(node)) { - return; - } - if ( - !isCondAssignException(node) && - hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" })) - ) { - report(node.test); - } - - if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { - report(node.consequent); - } - - if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { - report(node.alternate); - } - }, - - DoWhileStatement(node) { - if (hasExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - }, - - ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration), - ExpressionStatement: node => checkExpressionOrExportStatement(node.expression), - - "ForInStatement, ForOfStatement"(node) { - if (node.left.type !== "VariableDeclarator") { - const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken); - - if ( - firstLeftToken.value === "let" && ( - - /* - * If `let` is the only thing on the left side of the loop, it's the loop variable: `for ((let) of foo);` - * Removing it will cause a syntax error, because it will be parsed as the start of a VariableDeclarator. - */ - (firstLeftToken.range[1] === node.left.range[1] || /* - * If `let` is followed by a `[` token, it's a property access on the `let` value: `for ((let[foo]) of bar);` - * Removing it will cause the property access to be parsed as a destructuring declaration of `foo` instead. - */ - astUtils.isOpeningBracketToken( - sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken) - )) - ) - ) { - tokensToIgnore.add(firstLeftToken); - } - } - - if (node.type === "ForOfStatement") { - const hasExtraParens = node.right.type === "SequenceExpression" - ? hasDoubleExcessParens(node.right) - : hasExcessParens(node.right); - - if (hasExtraParens) { - report(node.right); - } - } else if (hasExcessParens(node.right)) { - report(node.right); - } - - if (hasExcessParens(node.left)) { - report(node.left); - } - }, - - ForStatement(node) { - if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - - if (node.update && hasExcessParens(node.update)) { - report(node.update); - } - - if (node.init) { - startNewReportsBuffering(); - - if (hasExcessParens(node.init)) { - report(node.init); - } - } - }, - - "ForStatement > *.init:exit"(node) { - - /* - * Removing parentheses around `in` expressions might change semantics and cause errors. - * - * For example, this valid for loop: - * for (let a = (b in c); ;); - * after removing parentheses would be treated as an invalid for-in loop: - * for (let a = b in c; ;); - */ - - if (reportsBuffer.reports.length) { - reportsBuffer.inExpressionNodes.forEach(inExpressionNode => { - const path = pathToDescendant(node, inExpressionNode); - let nodeToExclude; - - for (let i = 0; i < path.length; i++) { - const pathNode = path[i]; - - if (i < path.length - 1) { - const nextPathNode = path[i + 1]; - - if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) { - - // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]'). - return; - } - } - - if (isParenthesised(pathNode)) { - if (isInCurrentReportsBuffer(pathNode)) { - - // This node was supposed to be reported, but parentheses might be necessary. - - if (isParenthesisedTwice(pathNode)) { - - /* - * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses. - * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses. - * The remaining pair is safely enclosing the 'in' expression. - */ - return; - } - - // Exclude the outermost node only. - if (!nodeToExclude) { - nodeToExclude = pathNode; - } - - // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside. - - } else { - - // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'. - return; - } - } - } - - // Exclude the node from the list (i.e. treat parentheses as necessary) - removeFromCurrentReportsBuffer(nodeToExclude); - }); - } - - endCurrentReportsBuffering(); - }, - - IfStatement(node) { - if (hasExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - }, - - ImportExpression(node) { - const { source } = node; - - if (source.type === "SequenceExpression") { - if (hasDoubleExcessParens(source)) { - report(source); - } - } else if (hasExcessParens(source)) { - report(source); - } - }, - - LogicalExpression: checkBinaryLogical, - - MemberExpression(node) { - const nodeObjHasExcessParens = hasExcessParens(node.object) && - !( - isImmediateFunctionPrototypeMethodCall(node.parent) && - node.parent.callee === node && - IGNORE_FUNCTION_PROTOTYPE_METHODS - ); - - if ( - nodeObjHasExcessParens && - precedence(node.object) >= precedence(node) && - ( - node.computed || - !( - astUtils.isDecimalInteger(node.object) || - - // RegExp literal is allowed to have parens (#1589) - (node.object.type === "Literal" && node.object.regex) - ) - ) - ) { - report(node.object); - } - - if (nodeObjHasExcessParens && - node.object.type === "CallExpression" && - node.parent.type !== "NewExpression") { - report(node.object); - } - - if (nodeObjHasExcessParens && - !IGNORE_NEW_IN_MEMBER_EXPR && - node.object.type === "NewExpression" && - isNewExpressionWithParens(node.object)) { - report(node.object); - } - - if (nodeObjHasExcessParens && - node.optional && - node.object.type === "ChainExpression" - ) { - report(node.object); - } - - if (node.computed && hasExcessParens(node.property)) { - report(node.property); - } - }, - - NewExpression: checkCallNew, - - ObjectExpression(node) { - node.properties - .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR)) - .forEach(property => report(property.value)); - }, - - ObjectPattern(node) { - node.properties - .filter(property => { - const value = property.value; - - return canBeAssignmentTarget(value) && hasExcessParens(value); - }).forEach(property => report(property.value)); - }, - - Property(node) { - if (node.computed) { - const { key } = node; - - if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { - report(key); - } - } - }, - - RestElement(node) { - const argument = node.argument; - - if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) { - report(argument); - } - }, - - ReturnStatement(node) { - const returnToken = sourceCode.getFirstToken(node); - - if (isReturnAssignException(node)) { - return; - } - - if (node.argument && - hasExcessParensNoLineTerminator(returnToken, node.argument) && - - // RegExp literal is allowed to have parens (#1589) - !(node.argument.type === "Literal" && node.argument.regex)) { - report(node.argument); - } - }, - - SequenceExpression(node) { - const precedenceOfNode = precedence(node); - - node.expressions - .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode)) - .forEach(report); - }, - - SwitchCase(node) { - if (node.test && hasExcessParens(node.test)) { - report(node.test); - } - }, - - SwitchStatement(node) { - if (hasExcessParens(node.discriminant)) { - report(node.discriminant); - } - }, - - ThrowStatement(node) { - const throwToken = sourceCode.getFirstToken(node); - - if (hasExcessParensNoLineTerminator(throwToken, node.argument)) { - report(node.argument); - } - }, - - UnaryExpression: checkArgumentWithPrecedence, - UpdateExpression: checkArgumentWithPrecedence, - AwaitExpression: checkArgumentWithPrecedence, - - VariableDeclarator(node) { - if ( - node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) && - - // RegExp literal is allowed to have parens (#1589) - !(node.init.type === "Literal" && node.init.regex) - ) { - report(node.init); - } - }, - - WhileStatement(node) { - if (hasExcessParens(node.test) && !isCondAssignException(node)) { - report(node.test); - } - }, - - WithStatement(node) { - if (hasExcessParens(node.object)) { - report(node.object); - } - }, - - YieldExpression(node) { - if (node.argument) { - const yieldToken = sourceCode.getFirstToken(node); - - if ((precedence(node.argument) >= precedence(node) && - hasExcessParensNoLineTerminator(yieldToken, node.argument)) || - hasDoubleExcessParens(node.argument)) { - report(node.argument); - } - } - }, - - ClassDeclaration: checkClass, - ClassExpression: checkClass, - - SpreadElement: checkSpreadOperator, - SpreadProperty: checkSpreadOperator, - ExperimentalSpreadProperty: checkSpreadOperator, - - TemplateLiteral(node) { - node.expressions - .filter(e => e && hasExcessParens(e)) - .forEach(report); - }, - - AssignmentPattern(node) { - const { left, right } = node; - - if (canBeAssignmentTarget(left) && hasExcessParens(left)) { - report(left); - } - - if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) { - report(right); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-extra-semi.js b/tools/node_modules/eslint/lib/rules/no-extra-semi.js deleted file mode 100644 index e0a8df0565af98359b3cacd67005ce8a46fdcccd..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-extra-semi.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @fileoverview Rule to flag use of unnecessary semicolons - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const FixTracker = require("./utils/fix-tracker"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary semicolons", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-extra-semi" - }, - - fixable: "code", - schema: [], - - messages: { - unexpected: "Unnecessary semicolon." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Reports an unnecessary semicolon error. - * @param {Node|Token} nodeOrToken A node or a token to be reported. - * @returns {void} - */ - function report(nodeOrToken) { - context.report({ - node: nodeOrToken, - messageId: "unexpected", - fix(fixer) { - - /* - * Expand the replacement range to include the surrounding - * tokens to avoid conflicting with semi. - * https://github.com/eslint/eslint/issues/7928 - */ - return new FixTracker(fixer, context.getSourceCode()) - .retainSurroundingTokens(nodeOrToken) - .remove(nodeOrToken); - } - }); - } - - /** - * Checks for a part of a class body. - * This checks tokens from a specified token to a next MethodDefinition or the end of class body. - * @param {Token} firstToken The first token to check. - * @returns {void} - */ - function checkForPartOfClassBody(firstToken) { - for (let token = firstToken; - token.type === "Punctuator" && !astUtils.isClosingBraceToken(token); - token = sourceCode.getTokenAfter(token) - ) { - if (astUtils.isSemicolonToken(token)) { - report(token); - } - } - } - - return { - - /** - * Reports this empty statement, except if the parent node is a loop. - * @param {Node} node A EmptyStatement node to be reported. - * @returns {void} - */ - EmptyStatement(node) { - const parent = node.parent, - allowedParentTypes = [ - "ForStatement", - "ForInStatement", - "ForOfStatement", - "WhileStatement", - "DoWhileStatement", - "IfStatement", - "LabeledStatement", - "WithStatement" - ]; - - if (allowedParentTypes.indexOf(parent.type) === -1) { - report(node); - } - }, - - /** - * Checks tokens from the head of this class body to the first MethodDefinition or the end of this class body. - * @param {Node} node A ClassBody node to check. - * @returns {void} - */ - ClassBody(node) { - checkForPartOfClassBody(sourceCode.getFirstToken(node, 1)); // 0 is `{`. - }, - - /** - * Checks tokens from this MethodDefinition to the next MethodDefinition or the end of this class body. - * @param {Node} node A MethodDefinition node of the start point. - * @returns {void} - */ - MethodDefinition(node) { - checkForPartOfClassBody(sourceCode.getTokenAfter(node)); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-fallthrough.js b/tools/node_modules/eslint/lib/rules/no-fallthrough.js deleted file mode 100644 index dd1f3ed9d9a74e1b80cec1eeeccfdb295c33b939..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-fallthrough.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @fileoverview Rule to flag fall-through cases in switch statements. - * @author Matt DuVall - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu; - -/** - * Checks whether or not a given node has a fallthrough comment. - * @param {ASTNode} node A SwitchCase node to get comments. - * @param {RuleContext} context A rule context which stores comments. - * @param {RegExp} fallthroughCommentPattern A pattern to match comment to. - * @returns {boolean} `true` if the node has a valid fallthrough comment. - */ -function hasFallthroughComment(node, context, fallthroughCommentPattern) { - const sourceCode = context.getSourceCode(); - const comment = lodash.last(sourceCode.getCommentsBefore(node)); - - return Boolean(comment && fallthroughCommentPattern.test(comment.value)); -} - -/** - * Checks whether or not a given code path segment is reachable. - * @param {CodePathSegment} segment A CodePathSegment to check. - * @returns {boolean} `true` if the segment is reachable. - */ -function isReachable(segment) { - return segment.reachable; -} - -/** - * Checks whether a node and a token are separated by blank lines - * @param {ASTNode} node The node to check - * @param {Token} token The token to compare against - * @returns {boolean} `true` if there are blank lines between node and token - */ -function hasBlankLinesBetween(node, token) { - return token.loc.start.line > node.loc.end.line + 1; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow fallthrough of `case` statements", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-fallthrough" - }, - - schema: [ - { - type: "object", - properties: { - commentPattern: { - type: "string", - default: "" - } - }, - additionalProperties: false - } - ], - messages: { - case: "Expected a 'break' statement before 'case'.", - default: "Expected a 'break' statement before 'default'." - } - }, - - create(context) { - const options = context.options[0] || {}; - let currentCodePath = null; - const sourceCode = context.getSourceCode(); - - /* - * We need to use leading comments of the next SwitchCase node because - * trailing comments is wrong if semicolons are omitted. - */ - let fallthroughCase = null; - let fallthroughCommentPattern = null; - - if (options.commentPattern) { - fallthroughCommentPattern = new RegExp(options.commentPattern, "u"); - } else { - fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT; - } - - return { - onCodePathStart(codePath) { - currentCodePath = codePath; - }, - onCodePathEnd() { - currentCodePath = currentCodePath.upper; - }, - - SwitchCase(node) { - - /* - * Checks whether or not there is a fallthrough comment. - * And reports the previous fallthrough node if that does not exist. - */ - if (fallthroughCase && !hasFallthroughComment(node, context, fallthroughCommentPattern)) { - context.report({ - messageId: node.test ? "case" : "default", - node - }); - } - fallthroughCase = null; - }, - - "SwitchCase:exit"(node) { - const nextToken = sourceCode.getTokenAfter(node); - - /* - * `reachable` meant fall through because statements preceded by - * `break`, `return`, or `throw` are unreachable. - * And allows empty cases and the last case. - */ - if (currentCodePath.currentSegments.some(isReachable) && - (node.consequent.length > 0 || hasBlankLinesBetween(node, nextToken)) && - lodash.last(node.parent.cases) !== node) { - fallthroughCase = node; - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-floating-decimal.js b/tools/node_modules/eslint/lib/rules/no-floating-decimal.js deleted file mode 100644 index b1d883212e20761209ace9626df3d6b5193b78ac..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-floating-decimal.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @fileoverview Rule to flag use of a leading/trailing decimal point in a numeric literal - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow leading or trailing decimal points in numeric literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-floating-decimal" - }, - - schema: [], - fixable: "code", - messages: { - leading: "A leading decimal point can be confused with a dot.", - trailing: "A trailing decimal point can be confused with a dot." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - Literal(node) { - - if (typeof node.value === "number") { - if (node.raw.startsWith(".")) { - context.report({ - node, - messageId: "leading", - fix(fixer) { - const tokenBefore = sourceCode.getTokenBefore(node); - const needsSpaceBefore = tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, `0${node.raw}`); - - return fixer.insertTextBefore(node, needsSpaceBefore ? " 0" : "0"); - } - }); - } - if (node.raw.indexOf(".") === node.raw.length - 1) { - context.report({ - node, - messageId: "trailing", - fix: fixer => fixer.insertTextAfter(node, "0") - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-func-assign.js b/tools/node_modules/eslint/lib/rules/no-func-assign.js deleted file mode 100644 index 33d0ad9ecd14335370d46039de934569f2726e65..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-func-assign.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Rule to flag use of function declaration identifiers as variables. - * @author Ian Christian Myers - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow reassigning `function` declarations", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-func-assign" - }, - - schema: [], - - messages: { - isAFunction: "'{{name}}' is a function." - } - }, - - create(context) { - - /** - * Reports a reference if is non initializer and writable. - * @param {References} references Collection of reference to check. - * @returns {void} - */ - function checkReference(references) { - astUtils.getModifyingReferences(references).forEach(reference => { - context.report({ - node: reference.identifier, - messageId: "isAFunction", - data: { - name: reference.identifier.name - } - }); - }); - } - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.defs[0].type === "FunctionName") { - checkReference(variable.references); - } - } - - /** - * Checks parameters of a given function node. - * @param {ASTNode} node A function node to check. - * @returns {void} - */ - function checkForFunction(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - - return { - FunctionDeclaration: checkForFunction, - FunctionExpression: checkForFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-global-assign.js b/tools/node_modules/eslint/lib/rules/no-global-assign.js deleted file mode 100644 index ea854c4aa8cd9bf8fe4b6544a21d6ec40821f2c5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-global-assign.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @fileoverview Rule to disallow assignments to native objects or read-only global variables - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow assignments to native objects or read-only global variables", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-global-assign" - }, - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { type: "string" }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - globalShouldNotBeModified: "Read-only global '{{name}}' should not be modified." - } - }, - - create(context) { - const config = context.options[0]; - const exceptions = (config && config.exceptions) || []; - - /** - * Reports write references. - * @param {Reference} reference A reference to check. - * @param {int} index The index of the reference in the references. - * @param {Reference[]} references The array that the reference belongs to. - * @returns {void} - */ - function checkReference(reference, index, references) { - const identifier = reference.identifier; - - if (reference.init === false && - reference.isWrite() && - - /* - * Destructuring assignments can have multiple default value, - * so possibly there are multiple writeable references for the same identifier. - */ - (index === 0 || references[index - 1].identifier !== identifier) - ) { - context.report({ - node: identifier, - messageId: "globalShouldNotBeModified", - data: { - name: identifier.name - } - }); - } - } - - /** - * Reports write references if a given variable is read-only builtin. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) { - variable.references.forEach(checkReference); - } - } - - return { - Program() { - const globalScope = context.getScope(); - - globalScope.variables.forEach(checkVariable); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js b/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js deleted file mode 100644 index a639711ecea1558b7abd2850bc47a951f0ba4355..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-implicit-coercion.js +++ /dev/null @@ -1,305 +0,0 @@ -/** - * @fileoverview A rule to disallow the type conversions with shorter notations. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u; -const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"]; - -/** - * Parses and normalizes an option object. - * @param {Object} options An option object to parse. - * @returns {Object} The parsed and normalized option object. - */ -function parseOptions(options) { - return { - boolean: "boolean" in options ? options.boolean : true, - number: "number" in options ? options.number : true, - string: "string" in options ? options.string : true, - allow: options.allow || [] - }; -} - -/** - * Checks whether or not a node is a double logical nigating. - * @param {ASTNode} node An UnaryExpression node to check. - * @returns {boolean} Whether or not the node is a double logical nigating. - */ -function isDoubleLogicalNegating(node) { - return ( - node.operator === "!" && - node.argument.type === "UnaryExpression" && - node.argument.operator === "!" - ); -} - -/** - * Checks whether or not a node is a binary negating of `.indexOf()` method calling. - * @param {ASTNode} node An UnaryExpression node to check. - * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling. - */ -function isBinaryNegatingOfIndexOf(node) { - if (node.operator !== "~") { - return false; - } - const callNode = astUtils.skipChainExpression(node.argument); - - return ( - callNode.type === "CallExpression" && - astUtils.isSpecificMemberAccess(callNode.callee, null, INDEX_OF_PATTERN) - ); -} - -/** - * Checks whether or not a node is a multiplying by one. - * @param {BinaryExpression} node A BinaryExpression node to check. - * @returns {boolean} Whether or not the node is a multiplying by one. - */ -function isMultiplyByOne(node) { - return node.operator === "*" && ( - node.left.type === "Literal" && node.left.value === 1 || - node.right.type === "Literal" && node.right.value === 1 - ); -} - -/** - * Checks whether the result of a node is numeric or not - * @param {ASTNode} node The node to test - * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call - */ -function isNumeric(node) { - return ( - node.type === "Literal" && typeof node.value === "number" || - node.type === "CallExpression" && ( - node.callee.name === "Number" || - node.callee.name === "parseInt" || - node.callee.name === "parseFloat" - ) - ); -} - -/** - * Returns the first non-numeric operand in a BinaryExpression. Designed to be - * used from bottom to up since it walks up the BinaryExpression trees using - * node.parent to find the result. - * @param {BinaryExpression} node The BinaryExpression node to be walked up on - * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null - */ -function getNonNumericOperand(node) { - const left = node.left, - right = node.right; - - if (right.type !== "BinaryExpression" && !isNumeric(right)) { - return right; - } - - if (left.type !== "BinaryExpression" && !isNumeric(left)) { - return left; - } - - return null; -} - -/** - * Checks whether a node is an empty string literal or not. - * @param {ASTNode} node The node to check. - * @returns {boolean} Whether or not the passed in node is an - * empty string literal or not. - */ -function isEmptyString(node) { - return astUtils.isStringLiteral(node) && (node.value === "" || (node.type === "TemplateLiteral" && node.quasis.length === 1 && node.quasis[0].value.cooked === "")); -} - -/** - * Checks whether or not a node is a concatenating with an empty string. - * @param {ASTNode} node A BinaryExpression node to check. - * @returns {boolean} Whether or not the node is a concatenating with an empty string. - */ -function isConcatWithEmptyString(node) { - return node.operator === "+" && ( - (isEmptyString(node.left) && !astUtils.isStringLiteral(node.right)) || - (isEmptyString(node.right) && !astUtils.isStringLiteral(node.left)) - ); -} - -/** - * Checks whether or not a node is appended with an empty string. - * @param {ASTNode} node An AssignmentExpression node to check. - * @returns {boolean} Whether or not the node is appended with an empty string. - */ -function isAppendEmptyString(node) { - return node.operator === "+=" && isEmptyString(node.right); -} - -/** - * Returns the operand that is not an empty string from a flagged BinaryExpression. - * @param {ASTNode} node The flagged BinaryExpression node to check. - * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression. - */ -function getNonEmptyOperand(node) { - return isEmptyString(node.left) ? node.right : node.left; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow shorthand type conversions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-implicit-coercion" - }, - - fixable: "code", - - schema: [{ - type: "object", - properties: { - boolean: { - type: "boolean", - default: true - }, - number: { - type: "boolean", - default: true - }, - string: { - type: "boolean", - default: true - }, - allow: { - type: "array", - items: { - enum: ALLOWABLE_OPERATORS - }, - uniqueItems: true - } - }, - additionalProperties: false - }], - - messages: { - useRecommendation: "use `{{recommendation}}` instead." - } - }, - - create(context) { - const options = parseOptions(context.options[0] || {}); - const sourceCode = context.getSourceCode(); - - /** - * Reports an error and autofixes the node - * @param {ASTNode} node An ast node to report the error on. - * @param {string} recommendation The recommended code for the issue - * @param {bool} shouldFix Whether this report should fix the node - * @returns {void} - */ - function report(node, recommendation, shouldFix) { - context.report({ - node, - messageId: "useRecommendation", - data: { - recommendation - }, - fix(fixer) { - if (!shouldFix) { - return null; - } - - const tokenBefore = sourceCode.getTokenBefore(node); - - if ( - tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, recommendation) - ) { - return fixer.replaceText(node, ` ${recommendation}`); - } - return fixer.replaceText(node, recommendation); - } - }); - } - - return { - UnaryExpression(node) { - let operatorAllowed; - - // !!foo - operatorAllowed = options.allow.indexOf("!!") >= 0; - if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) { - const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`; - - report(node, recommendation, true); - } - - // ~foo.indexOf(bar) - operatorAllowed = options.allow.indexOf("~") >= 0; - if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) { - - // `foo?.indexOf(bar) !== -1` will be true (== found) if the `foo` is nullish. So use `>= 0` in that case. - const comparison = node.argument.type === "ChainExpression" ? ">= 0" : "!== -1"; - const recommendation = `${sourceCode.getText(node.argument)} ${comparison}`; - - report(node, recommendation, false); - } - - // +foo - operatorAllowed = options.allow.indexOf("+") >= 0; - if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) { - const recommendation = `Number(${sourceCode.getText(node.argument)})`; - - report(node, recommendation, true); - } - }, - - // Use `:exit` to prevent double reporting - "BinaryExpression:exit"(node) { - let operatorAllowed; - - // 1 * foo - operatorAllowed = options.allow.indexOf("*") >= 0; - const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && getNonNumericOperand(node); - - if (nonNumericOperand) { - const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`; - - report(node, recommendation, true); - } - - // "" + foo - operatorAllowed = options.allow.indexOf("+") >= 0; - if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) { - const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`; - - report(node, recommendation, true); - } - }, - - AssignmentExpression(node) { - - // foo += "" - const operatorAllowed = options.allow.indexOf("+") >= 0; - - if (!operatorAllowed && options.string && isAppendEmptyString(node)) { - const code = sourceCode.getText(getNonEmptyOperand(node)); - const recommendation = `${code} = String(${code})`; - - report(node, recommendation, true); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-implicit-globals.js b/tools/node_modules/eslint/lib/rules/no-implicit-globals.js deleted file mode 100644 index d4bfa3af82fc3bc9e221fc9a135a822083c85c74..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-implicit-globals.js +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @fileoverview Rule to check for implicit global variables, functions and classes. - * @author Joshua Peek - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow declarations in the global scope", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-implicit-globals" - }, - - schema: [{ - type: "object", - properties: { - lexicalBindings: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - - messages: { - globalNonLexicalBinding: "Unexpected {{kind}} declaration in the global scope, wrap in an IIFE for a local variable, assign as global property for a global variable.", - globalLexicalBinding: "Unexpected {{kind}} declaration in the global scope, wrap in a block or in an IIFE.", - globalVariableLeak: "Global variable leak, declare the variable if it is intended to be local.", - assignmentToReadonlyGlobal: "Unexpected assignment to read-only global variable.", - redeclarationOfReadonlyGlobal: "Unexpected redeclaration of read-only global variable." - } - }, - - create(context) { - - const checkLexicalBindings = context.options[0] && context.options[0].lexicalBindings === true; - - /** - * Reports the node. - * @param {ASTNode} node Node to report. - * @param {string} messageId Id of the message to report. - * @param {string|undefined} kind Declaration kind, can be 'var', 'const', 'let', function or class. - * @returns {void} - */ - function report(node, messageId, kind) { - context.report({ - node, - messageId, - data: { - kind - } - }); - } - - return { - Program() { - const scope = context.getScope(); - - scope.variables.forEach(variable => { - - // Only ESLint global variables have the `writable` key. - const isReadonlyEslintGlobalVariable = variable.writeable === false; - const isWritableEslintGlobalVariable = variable.writeable === true; - - if (isWritableEslintGlobalVariable) { - - // Everything is allowed with writable ESLint global variables. - return; - } - - variable.defs.forEach(def => { - const defNode = def.node; - - if (def.type === "FunctionName" || (def.type === "Variable" && def.parent.kind === "var")) { - if (isReadonlyEslintGlobalVariable) { - report(defNode, "redeclarationOfReadonlyGlobal"); - } else { - report( - defNode, - "globalNonLexicalBinding", - def.type === "FunctionName" ? "function" : `'${def.parent.kind}'` - ); - } - } - - if (checkLexicalBindings) { - if (def.type === "ClassName" || - (def.type === "Variable" && (def.parent.kind === "let" || def.parent.kind === "const"))) { - if (isReadonlyEslintGlobalVariable) { - report(defNode, "redeclarationOfReadonlyGlobal"); - } else { - report( - defNode, - "globalLexicalBinding", - def.type === "ClassName" ? "class" : `'${def.parent.kind}'` - ); - } - } - } - }); - }); - - // Undeclared assigned variables. - scope.implicit.variables.forEach(variable => { - const scopeVariable = scope.set.get(variable.name); - let messageId; - - if (scopeVariable) { - - // ESLint global variable - if (scopeVariable.writeable) { - return; - } - messageId = "assignmentToReadonlyGlobal"; - - } else { - - // Reference to an unknown variable, possible global leak. - messageId = "globalVariableLeak"; - } - - // def.node is an AssignmentExpression, ForInStatement or ForOfStatement. - variable.defs.forEach(def => { - report(def.node, messageId); - }); - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-implied-eval.js b/tools/node_modules/eslint/lib/rules/no-implied-eval.js deleted file mode 100644 index b8120a64887c5a38c4b30896ae986c20775ca182..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-implied-eval.js +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const { getStaticValue } = require("eslint-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `eval()`-like methods", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-implied-eval" - }, - - schema: [], - - messages: { - impliedEval: "Implied eval. Consider passing a function instead of a string." - } - }, - - create(context) { - const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]); - const EVAL_LIKE_FUNC_PATTERN = /^(?:set(?:Interval|Timeout)|execScript)$/u; - - /** - * Checks whether a node is evaluated as a string or not. - * @param {ASTNode} node A node to check. - * @returns {boolean} True if the node is evaluated as a string. - */ - function isEvaluatedString(node) { - if ( - (node.type === "Literal" && typeof node.value === "string") || - node.type === "TemplateLiteral" - ) { - return true; - } - if (node.type === "BinaryExpression" && node.operator === "+") { - return isEvaluatedString(node.left) || isEvaluatedString(node.right); - } - return false; - } - - /** - * Reports if the `CallExpression` node has evaluated argument. - * @param {ASTNode} node A CallExpression to check. - * @returns {void} - */ - function reportImpliedEvalCallExpression(node) { - const [firstArgument] = node.arguments; - - if (firstArgument) { - - const staticValue = getStaticValue(firstArgument, context.getScope()); - const isStaticString = staticValue && typeof staticValue.value === "string"; - const isString = isStaticString || isEvaluatedString(firstArgument); - - if (isString) { - context.report({ - node, - messageId: "impliedEval" - }); - } - } - - } - - /** - * Reports calls of `implied eval` via the global references. - * @param {Variable} globalVar A global variable to check. - * @returns {void} - */ - function reportImpliedEvalViaGlobal(globalVar) { - const { references, name } = globalVar; - - references.forEach(ref => { - const identifier = ref.identifier; - let node = identifier.parent; - - while (astUtils.isSpecificMemberAccess(node, null, name)) { - node = node.parent; - } - - if (astUtils.isSpecificMemberAccess(node, null, EVAL_LIKE_FUNC_PATTERN)) { - const calleeNode = node.parent.type === "ChainExpression" ? node.parent : node; - const parent = calleeNode.parent; - - if (parent.type === "CallExpression" && parent.callee === calleeNode) { - reportImpliedEvalCallExpression(parent); - } - } - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - CallExpression(node) { - if (astUtils.isSpecificId(node.callee, EVAL_LIKE_FUNC_PATTERN)) { - reportImpliedEvalCallExpression(node); - } - }, - "Program:exit"() { - const globalScope = context.getScope(); - - GLOBAL_CANDIDATES - .map(candidate => astUtils.getVariableByName(globalScope, candidate)) - .filter(globalVar => !!globalVar && globalVar.defs.length === 0) - .forEach(reportImpliedEvalViaGlobal); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-import-assign.js b/tools/node_modules/eslint/lib/rules/no-import-assign.js deleted file mode 100644 index 7a349bb730bdcda95bb45c6183220eada26aa3fd..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-import-assign.js +++ /dev/null @@ -1,239 +0,0 @@ -/** - * @fileoverview Rule to flag updates of imported bindings. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const { findVariable } = require("eslint-utils"); -const astUtils = require("./utils/ast-utils"); - -const WellKnownMutationFunctions = { - Object: /^(?:assign|definePropert(?:y|ies)|freeze|setPrototypeOf)$/u, - Reflect: /^(?:(?:define|delete)Property|set(?:PrototypeOf)?)$/u -}; - -/** - * Check if a given node is LHS of an assignment node. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is LHS. - */ -function isAssignmentLeft(node) { - const { parent } = node; - - return ( - ( - parent.type === "AssignmentExpression" && - parent.left === node - ) || - - // Destructuring assignments - parent.type === "ArrayPattern" || - ( - parent.type === "Property" && - parent.value === node && - parent.parent.type === "ObjectPattern" - ) || - parent.type === "RestElement" || - ( - parent.type === "AssignmentPattern" && - parent.left === node - ) - ); -} - -/** - * Check if a given node is the operand of mutation unary operator. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is the operand of mutation unary operator. - */ -function isOperandOfMutationUnaryOperator(node) { - const argumentNode = node.parent.type === "ChainExpression" - ? node.parent - : node; - const { parent } = argumentNode; - - return ( - ( - parent.type === "UpdateExpression" && - parent.argument === argumentNode - ) || - ( - parent.type === "UnaryExpression" && - parent.operator === "delete" && - parent.argument === argumentNode - ) - ); -} - -/** - * Check if a given node is the iteration variable of `for-in`/`for-of` syntax. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is the iteration variable. - */ -function isIterationVariable(node) { - const { parent } = node; - - return ( - ( - parent.type === "ForInStatement" && - parent.left === node - ) || - ( - parent.type === "ForOfStatement" && - parent.left === node - ) - ); -} - -/** - * Check if a given node is at the first argument of a well-known mutation function. - * - `Object.assign` - * - `Object.defineProperty` - * - `Object.defineProperties` - * - `Object.freeze` - * - `Object.setPrototypeOf` - * - `Refrect.defineProperty` - * - `Refrect.deleteProperty` - * - `Refrect.set` - * - `Refrect.setPrototypeOf` - * @param {ASTNode} node The node to check. - * @param {Scope} scope A `escope.Scope` object to find variable (whichever). - * @returns {boolean} `true` if the node is at the first argument of a well-known mutation function. - */ -function isArgumentOfWellKnownMutationFunction(node, scope) { - const { parent } = node; - - if (parent.type !== "CallExpression" || parent.arguments[0] !== node) { - return false; - } - const callee = astUtils.skipChainExpression(parent.callee); - - if ( - !astUtils.isSpecificMemberAccess(callee, "Object", WellKnownMutationFunctions.Object) && - !astUtils.isSpecificMemberAccess(callee, "Reflect", WellKnownMutationFunctions.Reflect) - ) { - return false; - } - const variable = findVariable(scope, callee.object); - - return variable !== null && variable.scope.type === "global"; -} - -/** - * Check if the identifier node is placed at to update members. - * @param {ASTNode} id The Identifier node to check. - * @param {Scope} scope A `escope.Scope` object to find variable (whichever). - * @returns {boolean} `true` if the member of `id` was updated. - */ -function isMemberWrite(id, scope) { - const { parent } = id; - - return ( - ( - parent.type === "MemberExpression" && - parent.object === id && - ( - isAssignmentLeft(parent) || - isOperandOfMutationUnaryOperator(parent) || - isIterationVariable(parent) - ) - ) || - isArgumentOfWellKnownMutationFunction(id, scope) - ); -} - -/** - * Get the mutation node. - * @param {ASTNode} id The Identifier node to get. - * @returns {ASTNode} The mutation node. - */ -function getWriteNode(id) { - let node = id.parent; - - while ( - node && - node.type !== "AssignmentExpression" && - node.type !== "UpdateExpression" && - node.type !== "UnaryExpression" && - node.type !== "CallExpression" && - node.type !== "ForInStatement" && - node.type !== "ForOfStatement" - ) { - node = node.parent; - } - - return node || id; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assigning to imported bindings", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-import-assign" - }, - - schema: [], - - messages: { - readonly: "'{{name}}' is read-only.", - readonlyMember: "The members of '{{name}}' are read-only." - } - }, - - create(context) { - return { - ImportDeclaration(node) { - const scope = context.getScope(); - - for (const variable of context.getDeclaredVariables(node)) { - const shouldCheckMembers = variable.defs.some( - d => d.node.type === "ImportNamespaceSpecifier" - ); - let prevIdNode = null; - - for (const reference of variable.references) { - const idNode = reference.identifier; - - /* - * AssignmentPattern (e.g. `[a = 0] = b`) makes two write - * references for the same identifier. This should skip - * the one of the two in order to prevent redundant reports. - */ - if (idNode === prevIdNode) { - continue; - } - prevIdNode = idNode; - - if (reference.isWrite()) { - context.report({ - node: getWriteNode(idNode), - messageId: "readonly", - data: { name: idNode.name } - }); - } else if (shouldCheckMembers && isMemberWrite(idNode, scope)) { - context.report({ - node: getWriteNode(idNode), - messageId: "readonlyMember", - data: { name: idNode.name } - }); - } - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-inline-comments.js b/tools/node_modules/eslint/lib/rules/no-inline-comments.js deleted file mode 100644 index dec278615e2e120344b366884e820b01592d22d1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-inline-comments.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @fileoverview Enforces or disallows inline comments. - * @author Greg Cochard - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow inline comments after code", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-inline-comments" - }, - - schema: [ - { - type: "object", - properties: { - ignorePattern: { - type: "string" - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedInlineComment: "Unexpected comment inline with code." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = context.options[0]; - let customIgnoreRegExp; - - if (options && options.ignorePattern) { - customIgnoreRegExp = new RegExp(options.ignorePattern, "u"); - } - - /** - * Will check that comments are not on lines starting with or ending with code - * @param {ASTNode} node The comment node to check - * @private - * @returns {void} - */ - function testCodeAroundComment(node) { - - const startLine = String(sourceCode.lines[node.loc.start.line - 1]), - endLine = String(sourceCode.lines[node.loc.end.line - 1]), - preamble = startLine.slice(0, node.loc.start.column).trim(), - postamble = endLine.slice(node.loc.end.column).trim(), - isPreambleEmpty = !preamble, - isPostambleEmpty = !postamble; - - // Nothing on both sides - if (isPreambleEmpty && isPostambleEmpty) { - return; - } - - // Matches the ignore pattern - if (customIgnoreRegExp && customIgnoreRegExp.test(node.value)) { - return; - } - - // JSX Exception - if ( - (isPreambleEmpty || preamble === "{") && - (isPostambleEmpty || postamble === "}") - ) { - const enclosingNode = sourceCode.getNodeByRangeIndex(node.range[0]); - - if (enclosingNode && enclosingNode.type === "JSXEmptyExpression") { - return; - } - } - - // Don't report ESLint directive comments - if (astUtils.isDirectiveComment(node)) { - return; - } - - context.report({ - node, - messageId: "unexpectedInlineComment" - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - sourceCode.getAllComments() - .filter(token => token.type !== "Shebang") - .forEach(testCodeAroundComment); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-inner-declarations.js b/tools/node_modules/eslint/lib/rules/no-inner-declarations.js deleted file mode 100644 index 0768bc61149cecc2040e39ed7b0219cf04912156..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-inner-declarations.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @fileoverview Rule to enforce declarations in program or function body root. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const validParent = new Set(["Program", "ExportNamedDeclaration", "ExportDefaultDeclaration"]); -const validBlockStatementParent = new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]); - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow variable or `function` declarations in nested blocks", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-inner-declarations" - }, - - schema: [ - { - enum: ["functions", "both"] - } - ], - - messages: { - moveDeclToRoot: "Move {{type}} declaration to {{body}} root." - } - }, - - create(context) { - - /** - * Ensure that a given node is at a program or function body's root. - * @param {ASTNode} node Declaration node to check. - * @returns {void} - */ - function check(node) { - const parent = node.parent; - - if ( - parent.type === "BlockStatement" && validBlockStatementParent.has(parent.parent.type) - ) { - return; - } - - if (validParent.has(parent.type)) { - return; - } - - const upperFunction = astUtils.getUpperFunction(parent); - - context.report({ - node, - messageId: "moveDeclToRoot", - data: { - type: (node.type === "FunctionDeclaration" ? "function" : "variable"), - body: (upperFunction === null ? "program" : "function body") - } - }); - } - - - return { - - FunctionDeclaration: check, - VariableDeclaration(node) { - if (context.options[0] === "both" && node.kind === "var") { - check(node); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-invalid-regexp.js b/tools/node_modules/eslint/lib/rules/no-invalid-regexp.js deleted file mode 100644 index 48b7188d49f9c5ec7f00846701e5eede631d1a1a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-invalid-regexp.js +++ /dev/null @@ -1,130 +0,0 @@ -/** - * @fileoverview Validate strings passed to the RegExp constructor - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const RegExpValidator = require("regexpp").RegExpValidator; -const validator = new RegExpValidator({ ecmaVersion: 2018 }); -const validFlags = /[gimuys]/gu; -const undefined1 = void 0; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow invalid regular expression strings in `RegExp` constructors", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-invalid-regexp" - }, - - schema: [{ - type: "object", - properties: { - allowConstructorFlags: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - }], - - messages: { - regexMessage: "{{message}}." - } - }, - - create(context) { - - const options = context.options[0]; - let allowedFlags = null; - - if (options && options.allowConstructorFlags) { - const temp = options.allowConstructorFlags.join("").replace(validFlags, ""); - - if (temp) { - allowedFlags = new RegExp(`[${temp}]`, "giu"); - } - } - - /** - * Check if node is a string - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if its a string - * @private - */ - function isString(node) { - return node && node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Check syntax error in a given pattern. - * @param {string} pattern The RegExp pattern to validate. - * @param {boolean} uFlag The Unicode flag. - * @returns {string|null} The syntax error. - */ - function validateRegExpPattern(pattern, uFlag) { - try { - validator.validatePattern(pattern, undefined1, undefined1, uFlag); - return null; - } catch (err) { - return err.message; - } - } - - /** - * Check syntax error in a given flags. - * @param {string} flags The RegExp flags to validate. - * @returns {string|null} The syntax error. - */ - function validateRegExpFlags(flags) { - try { - validator.validateFlags(flags); - return null; - } catch { - return `Invalid flags supplied to RegExp constructor '${flags}'`; - } - } - - return { - "CallExpression, NewExpression"(node) { - if (node.callee.type !== "Identifier" || node.callee.name !== "RegExp" || !isString(node.arguments[0])) { - return; - } - const pattern = node.arguments[0].value; - let flags = isString(node.arguments[1]) ? node.arguments[1].value : ""; - - if (allowedFlags) { - flags = flags.replace(allowedFlags, ""); - } - - // If flags are unknown, check both are errored or not. - const message = validateRegExpFlags(flags) || ( - flags - ? validateRegExpPattern(pattern, flags.indexOf("u") !== -1) - : validateRegExpPattern(pattern, true) && validateRegExpPattern(pattern, false) - ); - - if (message) { - context.report({ - node, - messageId: "regexMessage", - data: { message } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-invalid-this.js b/tools/node_modules/eslint/lib/rules/no-invalid-this.js deleted file mode 100644 index a79c586d71985296150978b2c2caf8b57e8c3cff..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-invalid-this.js +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @fileoverview A rule to disallow `this` keywords outside of classes or class-like objects. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `this` keywords outside of classes or class-like objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-invalid-this" - }, - - schema: [ - { - type: "object", - properties: { - capIsConstructor: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedThis: "Unexpected 'this'." - } - }, - - create(context) { - const options = context.options[0] || {}; - const capIsConstructor = options.capIsConstructor !== false; - const stack = [], - sourceCode = context.getSourceCode(); - - /** - * Gets the current checking context. - * - * The return value has a flag that whether or not `this` keyword is valid. - * The flag is initialized when got at the first time. - * @returns {{valid: boolean}} - * an object which has a flag that whether or not `this` keyword is valid. - */ - stack.getCurrent = function() { - const current = this[this.length - 1]; - - if (!current.init) { - current.init = true; - current.valid = !astUtils.isDefaultThisBinding( - current.node, - sourceCode, - { capIsConstructor } - ); - } - return current; - }; - - /** - * Pushs new checking context into the stack. - * - * The checking context is not initialized yet. - * Because most functions don't have `this` keyword. - * When `this` keyword was found, the checking context is initialized. - * @param {ASTNode} node A function node that was entered. - * @returns {void} - */ - function enterFunction(node) { - - // `this` can be invalid only under strict mode. - stack.push({ - init: !context.getScope().isStrict, - node, - valid: true - }); - } - - /** - * Pops the current checking context from the stack. - * @returns {void} - */ - function exitFunction() { - stack.pop(); - } - - return { - - /* - * `this` is invalid only under strict mode. - * Modules is always strict mode. - */ - Program(node) { - const scope = context.getScope(), - features = context.parserOptions.ecmaFeatures || {}; - - stack.push({ - init: true, - node, - valid: !( - scope.isStrict || - node.sourceType === "module" || - (features.globalReturn && scope.childScopes[0].isStrict) - ) - }); - }, - - "Program:exit"() { - stack.pop(); - }, - - FunctionDeclaration: enterFunction, - "FunctionDeclaration:exit": exitFunction, - FunctionExpression: enterFunction, - "FunctionExpression:exit": exitFunction, - - // Reports if `this` of the current context is invalid. - ThisExpression(node) { - const current = stack.getCurrent(); - - if (current && !current.valid) { - context.report({ - node, - messageId: "unexpectedThis" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js b/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js deleted file mode 100644 index 0bf69b128e6bf80ee9413e2fe4a320232ba4877a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-irregular-whitespace.js +++ /dev/null @@ -1,261 +0,0 @@ -/** - * @fileoverview Rule to disallow whitespace that is not a tab or space, whitespace inside strings and comments are allowed - * @author Jonathan Kingston - * @author Christophe Porteneuve - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const ALL_IRREGULARS = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000\u2028\u2029]/u; -const IRREGULAR_WHITESPACE = /[\f\v\u0085\ufeff\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mgu; -const IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mgu; -const LINE_BREAK = astUtils.createGlobalLinebreakMatcher(); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow irregular whitespace", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-irregular-whitespace" - }, - - schema: [ - { - type: "object", - properties: { - skipComments: { - type: "boolean", - default: false - }, - skipStrings: { - type: "boolean", - default: true - }, - skipTemplates: { - type: "boolean", - default: false - }, - skipRegExps: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - noIrregularWhitespace: "Irregular whitespace not allowed." - } - }, - - create(context) { - - // Module store of errors that we have found - let errors = []; - - // Lookup the `skipComments` option, which defaults to `false`. - const options = context.options[0] || {}; - const skipComments = !!options.skipComments; - const skipStrings = options.skipStrings !== false; - const skipRegExps = !!options.skipRegExps; - const skipTemplates = !!options.skipTemplates; - - const sourceCode = context.getSourceCode(); - const commentNodes = sourceCode.getAllComments(); - - /** - * Removes errors that occur inside a string node - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeWhitespaceError(node) { - const locStart = node.loc.start; - const locEnd = node.loc.end; - - errors = errors.filter(({ loc: { start: errorLoc } }) => { - if (errorLoc.line >= locStart.line && errorLoc.line <= locEnd.line) { - if (errorLoc.column >= locStart.column && (errorLoc.column <= locEnd.column || errorLoc.line < locEnd.line)) { - return false; - } - } - return true; - }); - } - - /** - * Checks identifier or literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeInvalidNodeErrorsInIdentifierOrLiteral(node) { - const shouldCheckStrings = skipStrings && (typeof node.value === "string"); - const shouldCheckRegExps = skipRegExps && Boolean(node.regex); - - if (shouldCheckStrings || shouldCheckRegExps) { - - // If we have irregular characters remove them from the errors list - if (ALL_IRREGULARS.test(node.raw)) { - removeWhitespaceError(node); - } - } - } - - /** - * Checks template string literal nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeInvalidNodeErrorsInTemplateLiteral(node) { - if (typeof node.value.raw === "string") { - if (ALL_IRREGULARS.test(node.value.raw)) { - removeWhitespaceError(node); - } - } - } - - /** - * Checks comment nodes for errors that we are choosing to ignore and calls the relevant methods to remove the errors - * @param {ASTNode} node to check for matching errors. - * @returns {void} - * @private - */ - function removeInvalidNodeErrorsInComment(node) { - if (ALL_IRREGULARS.test(node.value)) { - removeWhitespaceError(node); - } - } - - /** - * Checks the program source for irregular whitespace - * @param {ASTNode} node The program node - * @returns {void} - * @private - */ - function checkForIrregularWhitespace(node) { - const sourceLines = sourceCode.lines; - - sourceLines.forEach((sourceLine, lineIndex) => { - const lineNumber = lineIndex + 1; - let match; - - while ((match = IRREGULAR_WHITESPACE.exec(sourceLine)) !== null) { - errors.push({ - node, - messageId: "noIrregularWhitespace", - loc: { - start: { - line: lineNumber, - column: match.index - }, - end: { - line: lineNumber, - column: match.index + match[0].length - } - } - }); - } - }); - } - - /** - * Checks the program source for irregular line terminators - * @param {ASTNode} node The program node - * @returns {void} - * @private - */ - function checkForIrregularLineTerminators(node) { - const source = sourceCode.getText(), - sourceLines = sourceCode.lines, - linebreaks = source.match(LINE_BREAK); - let lastLineIndex = -1, - match; - - while ((match = IRREGULAR_LINE_TERMINATORS.exec(source)) !== null) { - const lineIndex = linebreaks.indexOf(match[0], lastLineIndex + 1) || 0; - - errors.push({ - node, - messageId: "noIrregularWhitespace", - loc: { - start: { - line: lineIndex + 1, - column: sourceLines[lineIndex].length - }, - end: { - line: lineIndex + 2, - column: 0 - } - } - }); - - lastLineIndex = lineIndex; - } - } - - /** - * A no-op function to act as placeholder for comment accumulation when the `skipComments` option is `false`. - * @returns {void} - * @private - */ - function noop() {} - - const nodes = {}; - - if (ALL_IRREGULARS.test(sourceCode.getText())) { - nodes.Program = function(node) { - - /* - * As we can easily fire warnings for all white space issues with - * all the source its simpler to fire them here. - * This means we can check all the application code without having - * to worry about issues caused in the parser tokens. - * When writing this code also evaluating per node was missing out - * connecting tokens in some cases. - * We can later filter the errors when they are found to be not an - * issue in nodes we don't care about. - */ - checkForIrregularWhitespace(node); - checkForIrregularLineTerminators(node); - }; - - nodes.Identifier = removeInvalidNodeErrorsInIdentifierOrLiteral; - nodes.Literal = removeInvalidNodeErrorsInIdentifierOrLiteral; - nodes.TemplateElement = skipTemplates ? removeInvalidNodeErrorsInTemplateLiteral : noop; - nodes["Program:exit"] = function() { - if (skipComments) { - - // First strip errors occurring in comment nodes. - commentNodes.forEach(removeInvalidNodeErrorsInComment); - } - - // If we have any errors remaining report on them - errors.forEach(error => context.report(error)); - }; - } else { - nodes.Program = noop; - } - - return nodes; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-iterator.js b/tools/node_modules/eslint/lib/rules/no-iterator.js deleted file mode 100644 index 9ba1e7aefdbc3b94d57d0708eec2f689e1d06167..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-iterator.js +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @fileoverview Rule to flag usage of __iterator__ property - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { getStaticPropertyName } = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of the `__iterator__` property", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-iterator" - }, - - schema: [], - - messages: { - noIterator: "Reserved name '__iterator__'." - } - }, - - create(context) { - - return { - - MemberExpression(node) { - - if (getStaticPropertyName(node) === "__iterator__") { - context.report({ - node, - messageId: "noIterator" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-label-var.js b/tools/node_modules/eslint/lib/rules/no-label-var.js deleted file mode 100644 index 570db03285cf973459dddef277137a585ed95f52..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-label-var.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @fileoverview Rule to flag labels that are the same as an identifier - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow labels that share a name with a variable", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-label-var" - }, - - schema: [], - - messages: { - identifierClashWithLabel: "Found identifier with same name as label." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if the identifier is present inside current scope - * @param {Object} scope current scope - * @param {string} name To evaluate - * @returns {boolean} True if its present - * @private - */ - function findIdentifier(scope, name) { - return astUtils.getVariableByName(scope, name) !== null; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - LabeledStatement(node) { - - // Fetch the innermost scope. - const scope = context.getScope(); - - /* - * Recursively find the identifier walking up the scope, starting - * with the innermost scope. - */ - if (findIdentifier(scope, node.label.name)) { - context.report({ - node, - messageId: "identifierClashWithLabel" - }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-labels.js b/tools/node_modules/eslint/lib/rules/no-labels.js deleted file mode 100644 index 85760d80dbedd7c2f5672cd9af79c7b688ad5e06..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-labels.js +++ /dev/null @@ -1,149 +0,0 @@ -/** - * @fileoverview Disallow Labeled Statements - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow labeled statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-labels" - }, - - schema: [ - { - type: "object", - properties: { - allowLoop: { - type: "boolean", - default: false - }, - allowSwitch: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedLabel: "Unexpected labeled statement.", - unexpectedLabelInBreak: "Unexpected label in break statement.", - unexpectedLabelInContinue: "Unexpected label in continue statement." - } - }, - - create(context) { - const options = context.options[0]; - const allowLoop = options && options.allowLoop; - const allowSwitch = options && options.allowSwitch; - let scopeInfo = null; - - /** - * Gets the kind of a given node. - * @param {ASTNode} node A node to get. - * @returns {string} The kind of the node. - */ - function getBodyKind(node) { - if (astUtils.isLoop(node)) { - return "loop"; - } - if (node.type === "SwitchStatement") { - return "switch"; - } - return "other"; - } - - /** - * Checks whether the label of a given kind is allowed or not. - * @param {string} kind A kind to check. - * @returns {boolean} `true` if the kind is allowed. - */ - function isAllowed(kind) { - switch (kind) { - case "loop": return allowLoop; - case "switch": return allowSwitch; - default: return false; - } - } - - /** - * Checks whether a given name is a label of a loop or not. - * @param {string} label A name of a label to check. - * @returns {boolean} `true` if the name is a label of a loop. - */ - function getKind(label) { - let info = scopeInfo; - - while (info) { - if (info.label === label) { - return info.kind; - } - info = info.upper; - } - - /* istanbul ignore next: syntax error */ - return "other"; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - LabeledStatement(node) { - scopeInfo = { - label: node.label.name, - kind: getBodyKind(node.body), - upper: scopeInfo - }; - }, - - "LabeledStatement:exit"(node) { - if (!isAllowed(scopeInfo.kind)) { - context.report({ - node, - messageId: "unexpectedLabel" - }); - } - - scopeInfo = scopeInfo.upper; - }, - - BreakStatement(node) { - if (node.label && !isAllowed(getKind(node.label.name))) { - context.report({ - node, - messageId: "unexpectedLabelInBreak" - }); - } - }, - - ContinueStatement(node) { - if (node.label && !isAllowed(getKind(node.label.name))) { - context.report({ - node, - messageId: "unexpectedLabelInContinue" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-lone-blocks.js b/tools/node_modules/eslint/lib/rules/no-lone-blocks.js deleted file mode 100644 index 290784b82ea2fb7eb416b50dca6ffa8f85ca86fe..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-lone-blocks.js +++ /dev/null @@ -1,128 +0,0 @@ -/** - * @fileoverview Rule to flag blocks with no reason to exist - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary nested blocks", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-lone-blocks" - }, - - schema: [], - - messages: { - redundantBlock: "Block is redundant.", - redundantNestedBlock: "Nested block is redundant." - } - }, - - create(context) { - - // A stack of lone blocks to be checked for block-level bindings - const loneBlocks = []; - let ruleDef; - - /** - * Reports a node as invalid. - * @param {ASTNode} node The node to be reported. - * @returns {void} - */ - function report(node) { - const messageId = node.parent.type === "BlockStatement" ? "redundantNestedBlock" : "redundantBlock"; - - context.report({ - node, - messageId - }); - } - - /** - * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear - * @param {ASTNode} node The node to check - * @returns {boolean} True if the node is a lone block. - */ - function isLoneBlock(node) { - return node.parent.type === "BlockStatement" || - node.parent.type === "Program" || - - // Don't report blocks in switch cases if the block is the only statement of the case. - node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1); - } - - /** - * Checks the enclosing block of the current node for block-level bindings, - * and "marks it" as valid if any. - * @returns {void} - */ - function markLoneBlock() { - if (loneBlocks.length === 0) { - return; - } - - const block = context.getAncestors().pop(); - - if (loneBlocks[loneBlocks.length - 1] === block) { - loneBlocks.pop(); - } - } - - // Default rule definition: report all lone blocks - ruleDef = { - BlockStatement(node) { - if (isLoneBlock(node)) { - report(node); - } - } - }; - - // ES6: report blocks without block-level bindings, or that's only child of another block - if (context.parserOptions.ecmaVersion >= 6) { - ruleDef = { - BlockStatement(node) { - if (isLoneBlock(node)) { - loneBlocks.push(node); - } - }, - "BlockStatement:exit"(node) { - if (loneBlocks.length > 0 && loneBlocks[loneBlocks.length - 1] === node) { - loneBlocks.pop(); - report(node); - } else if ( - node.parent.type === "BlockStatement" && - node.parent.body.length === 1 - ) { - report(node); - } - } - }; - - ruleDef.VariableDeclaration = function(node) { - if (node.kind === "let" || node.kind === "const") { - markLoneBlock(); - } - }; - - ruleDef.FunctionDeclaration = function() { - if (context.getScope().isStrict) { - markLoneBlock(); - } - }; - - ruleDef.ClassDeclaration = markLoneBlock; - } - - return ruleDef; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-lonely-if.js b/tools/node_modules/eslint/lib/rules/no-lonely-if.js deleted file mode 100644 index 6552adc5752852fde000c3831dbdd656e2be4b06..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-lonely-if.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * @fileoverview Rule to disallow if as the only statement in an else block - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `if` statements as the only statement in `else` blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-lonely-if" - }, - - schema: [], - fixable: "code", - - messages: { - unexpectedLonelyIf: "Unexpected if as the only statement in an else block." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - IfStatement(node) { - const ancestors = context.getAncestors(), - parent = ancestors.pop(), - grandparent = ancestors.pop(); - - if (parent && parent.type === "BlockStatement" && - parent.body.length === 1 && grandparent && - grandparent.type === "IfStatement" && - parent === grandparent.alternate) { - context.report({ - node, - messageId: "unexpectedLonelyIf", - fix(fixer) { - const openingElseCurly = sourceCode.getFirstToken(parent); - const closingElseCurly = sourceCode.getLastToken(parent); - const elseKeyword = sourceCode.getTokenBefore(openingElseCurly); - const tokenAfterElseBlock = sourceCode.getTokenAfter(closingElseCurly); - const lastIfToken = sourceCode.getLastToken(node.consequent); - const sourceText = sourceCode.getText(); - - if (sourceText.slice(openingElseCurly.range[1], - node.range[0]).trim() || sourceText.slice(node.range[1], closingElseCurly.range[0]).trim()) { - - // Don't fix if there are any non-whitespace characters interfering (e.g. comments) - return null; - } - - if ( - node.consequent.type !== "BlockStatement" && lastIfToken.value !== ";" && tokenAfterElseBlock && - ( - node.consequent.loc.end.line === tokenAfterElseBlock.loc.start.line || - /^[([/+`-]/u.test(tokenAfterElseBlock.value) || - lastIfToken.value === "++" || - lastIfToken.value === "--" - ) - ) { - - /* - * If the `if` statement has no block, and is not followed by a semicolon, make sure that fixing - * the issue would not change semantics due to ASI. If this would happen, don't do a fix. - */ - return null; - } - - return fixer.replaceTextRange( - [openingElseCurly.range[0], closingElseCurly.range[1]], - (elseKeyword.range[1] === openingElseCurly.range[0] ? " " : "") + sourceCode.getText(node) - ); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-loop-func.js b/tools/node_modules/eslint/lib/rules/no-loop-func.js deleted file mode 100644 index 13ebd3ee22b8d721fee98392ebe6437bc7154a2d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-loop-func.js +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @fileoverview Rule to flag creation of function inside a loop - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the containing loop node of a specified node. - * - * We don't need to check nested functions, so this ignores those. - * `Scope.through` contains references of nested functions. - * @param {ASTNode} node An AST node to get. - * @returns {ASTNode|null} The containing loop node of the specified node, or - * `null`. - */ -function getContainingLoopNode(node) { - for (let currentNode = node; currentNode.parent; currentNode = currentNode.parent) { - const parent = currentNode.parent; - - switch (parent.type) { - case "WhileStatement": - case "DoWhileStatement": - return parent; - - case "ForStatement": - - // `init` is outside of the loop. - if (parent.init !== currentNode) { - return parent; - } - break; - - case "ForInStatement": - case "ForOfStatement": - - // `right` is outside of the loop. - if (parent.right !== currentNode) { - return parent; - } - break; - - case "ArrowFunctionExpression": - case "FunctionExpression": - case "FunctionDeclaration": - - // We don't need to check nested functions. - return null; - - default: - break; - } - } - - return null; -} - -/** - * Gets the containing loop node of a given node. - * If the loop was nested, this returns the most outer loop. - * @param {ASTNode} node A node to get. This is a loop node. - * @param {ASTNode|null} excludedNode A node that the result node should not - * include. - * @returns {ASTNode} The most outer loop node. - */ -function getTopLoopNode(node, excludedNode) { - const border = excludedNode ? excludedNode.range[1] : 0; - let retv = node; - let containingLoopNode = node; - - while (containingLoopNode && containingLoopNode.range[0] >= border) { - retv = containingLoopNode; - containingLoopNode = getContainingLoopNode(containingLoopNode); - } - - return retv; -} - -/** - * Checks whether a given reference which refers to an upper scope's variable is - * safe or not. - * @param {ASTNode} loopNode A containing loop node. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is safe or not. - */ -function isSafe(loopNode, reference) { - const variable = reference.resolved; - const definition = variable && variable.defs[0]; - const declaration = definition && definition.parent; - const kind = (declaration && declaration.type === "VariableDeclaration") - ? declaration.kind - : ""; - - // Variables which are declared by `const` is safe. - if (kind === "const") { - return true; - } - - /* - * Variables which are declared by `let` in the loop is safe. - * It's a different instance from the next loop step's. - */ - if (kind === "let" && - declaration.range[0] > loopNode.range[0] && - declaration.range[1] < loopNode.range[1] - ) { - return true; - } - - /* - * WriteReferences which exist after this border are unsafe because those - * can modify the variable. - */ - const border = getTopLoopNode( - loopNode, - (kind === "let") ? declaration : null - ).range[0]; - - /** - * Checks whether a given reference is safe or not. - * The reference is every reference of the upper scope's variable we are - * looking now. - * - * It's safeafe if the reference matches one of the following condition. - * - is readonly. - * - doesn't exist inside a local function and after the border. - * @param {eslint-scope.Reference} upperRef A reference to check. - * @returns {boolean} `true` if the reference is safe. - */ - function isSafeReference(upperRef) { - const id = upperRef.identifier; - - return ( - !upperRef.isWrite() || - variable.scope.variableScope === upperRef.from.variableScope && - id.range[0] < border - ); - } - - return Boolean(variable) && variable.references.every(isSafeReference); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow function declarations that contain unsafe references inside loop statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-loop-func" - }, - - schema: [], - - messages: { - unsafeRefs: "Function declared in a loop contains unsafe references to variable(s) {{ varNames }}." - } - }, - - create(context) { - - /** - * Reports functions which match the following condition: - * - * - has a loop node in ancestors. - * - has any references which refers to an unsafe variable. - * @param {ASTNode} node The AST node to check. - * @returns {boolean} Whether or not the node is within a loop. - */ - function checkForLoops(node) { - const loopNode = getContainingLoopNode(node); - - if (!loopNode) { - return; - } - - const references = context.getScope().through; - const unsafeRefs = references.filter(r => !isSafe(loopNode, r)).map(r => r.identifier.name); - - if (unsafeRefs.length > 0) { - context.report({ - node, - messageId: "unsafeRefs", - data: { varNames: `'${unsafeRefs.join("', '")}'` } - }); - } - } - - return { - ArrowFunctionExpression: checkForLoops, - FunctionExpression: checkForLoops, - FunctionDeclaration: checkForLoops - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-loss-of-precision.js b/tools/node_modules/eslint/lib/rules/no-loss-of-precision.js deleted file mode 100644 index 9e2811809f68e788526de04076cc2df9ea744e72..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-loss-of-precision.js +++ /dev/null @@ -1,206 +0,0 @@ -/** - * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime - * @author Jacob Moore - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow literal numbers that lose precision", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-loss-of-precision" - }, - schema: [], - messages: { - noLossOfPrecision: "This number literal will lose precision at runtime." - } - }, - - create(context) { - - /** - * Returns whether the node is number literal - * @param {Node} node the node literal being evaluated - * @returns {boolean} true if the node is a number literal - */ - function isNumber(node) { - return typeof node.value === "number"; - } - - /** - * Gets the source code of the given number literal. Removes `_` numeric separators from the result. - * @param {Node} node the number `Literal` node - * @returns {string} raw source code of the literal, without numeric separators - */ - function getRaw(node) { - return node.raw.replace(/_/gu, ""); - } - - /** - * Checks whether the number is base ten - * @param {ASTNode} node the node being evaluated - * @returns {boolean} true if the node is in base ten - */ - function isBaseTen(node) { - const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"]; - - return prefixes.every(prefix => !node.raw.startsWith(prefix)) && - !/^0[0-7]+$/u.test(node.raw); - } - - /** - * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type - * @param {Node} node the node being evaluated - * @returns {boolean} true if they do not match - */ - function notBaseTenLosesPrecision(node) { - const rawString = getRaw(node).toUpperCase(); - let base = 0; - - if (rawString.startsWith("0B")) { - base = 2; - } else if (rawString.startsWith("0X")) { - base = 16; - } else { - base = 8; - } - - return !rawString.endsWith(node.value.toString(base).toUpperCase()); - } - - /** - * Adds a decimal point to the numeric string at index 1 - * @param {string} stringNumber the numeric string without any decimal point - * @returns {string} the numeric string with a decimal point in the proper place - */ - function addDecimalPointToNumber(stringNumber) { - return `${stringNumber.slice(0, 1)}.${stringNumber.slice(1)}`; - } - - /** - * Returns the number stripped of leading zeros - * @param {string} numberAsString the string representation of the number - * @returns {string} the stripped string - */ - function removeLeadingZeros(numberAsString) { - return numberAsString.replace(/^0*/u, ""); - } - - /** - * Returns the number stripped of trailing zeros - * @param {string} numberAsString the string representation of the number - * @returns {string} the stripped string - */ - function removeTrailingZeros(numberAsString) { - return numberAsString.replace(/0*$/u, ""); - } - - /** - * Converts an integer to to an object containing the the integer's coefficient and order of magnitude - * @param {string} stringInteger the string representation of the integer being converted - * @returns {Object} the object containing the the integer's coefficient and order of magnitude - */ - function normalizeInteger(stringInteger) { - const significantDigits = removeTrailingZeros(removeLeadingZeros(stringInteger)); - - return { - magnitude: stringInteger.startsWith("0") ? stringInteger.length - 2 : stringInteger.length - 1, - coefficient: addDecimalPointToNumber(significantDigits) - }; - } - - /** - * - * Converts a float to to an object containing the the floats's coefficient and order of magnitude - * @param {string} stringFloat the string representation of the float being converted - * @returns {Object} the object containing the the integer's coefficient and order of magnitude - */ - function normalizeFloat(stringFloat) { - const trimmedFloat = removeLeadingZeros(stringFloat); - - if (trimmedFloat.startsWith(".")) { - const decimalDigits = trimmedFloat.split(".").pop(); - const significantDigits = removeLeadingZeros(decimalDigits); - - return { - magnitude: significantDigits.length - decimalDigits.length - 1, - coefficient: addDecimalPointToNumber(significantDigits) - }; - - } - return { - magnitude: trimmedFloat.indexOf(".") - 1, - coefficient: addDecimalPointToNumber(trimmedFloat.replace(".", "")) - - }; - } - - - /** - * Converts a base ten number to proper scientific notation - * @param {string} stringNumber the string representation of the base ten number to be converted - * @returns {string} the number converted to scientific notation - */ - function convertNumberToScientificNotation(stringNumber) { - const splitNumber = stringNumber.replace("E", "e").split("e"); - const originalCoefficient = splitNumber[0]; - const normalizedNumber = stringNumber.includes(".") ? normalizeFloat(originalCoefficient) - : normalizeInteger(originalCoefficient); - const normalizedCoefficient = normalizedNumber.coefficient; - const magnitude = splitNumber.length > 1 ? (parseInt(splitNumber[1], 10) + normalizedNumber.magnitude) - : normalizedNumber.magnitude; - - return `${normalizedCoefficient}e${magnitude}`; - - } - - /** - * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type - * @param {Node} node the node being evaluated - * @returns {boolean} true if they do not match - */ - function baseTenLosesPrecision(node) { - const normalizedRawNumber = convertNumberToScientificNotation(getRaw(node)); - const requestedPrecision = normalizedRawNumber.split("e")[0].replace(".", "").length; - - if (requestedPrecision > 100) { - return true; - } - const storedNumber = node.value.toPrecision(requestedPrecision); - const normalizedStoredNumber = convertNumberToScientificNotation(storedNumber); - - return normalizedRawNumber !== normalizedStoredNumber; - } - - - /** - * Checks that the user-intended number equals the actual number after is has been converted to the Number type - * @param {Node} node the node being evaluated - * @returns {boolean} true if they do not match - */ - function losesPrecision(node) { - return isBaseTen(node) ? baseTenLosesPrecision(node) : notBaseTenLosesPrecision(node); - } - - - return { - Literal(node) { - if (node.value && isNumber(node) && losesPrecision(node)) { - context.report({ - messageId: "noLossOfPrecision", - node - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-magic-numbers.js b/tools/node_modules/eslint/lib/rules/no-magic-numbers.js deleted file mode 100644 index 510b3f9b26172ec7617d4a0312bc32bc2251707e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-magic-numbers.js +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @fileoverview Rule to flag statements that use magic numbers (adapted from https://github.com/danielstjules/buddy.js) - * @author Vincent Lemeunier - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -// Maximum array length by the ECMAScript Specification. -const MAX_ARRAY_LENGTH = 2 ** 32 - 1; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Convert the value to bigint if it's a string. Otherwise return the value as-is. - * @param {bigint|number|string} x The value to normalize. - * @returns {bigint|number} The normalized value. - */ -function normalizeIgnoreValue(x) { - if (typeof x === "string") { - return BigInt(x.slice(0, -1)); - } - return x; -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow magic numbers", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-magic-numbers" - }, - - schema: [{ - type: "object", - properties: { - detectObjects: { - type: "boolean", - default: false - }, - enforceConst: { - type: "boolean", - default: false - }, - ignore: { - type: "array", - items: { - anyOf: [ - { type: "number" }, - { type: "string", pattern: "^[+-]?(?:0|[1-9][0-9]*)n$" } - ] - }, - uniqueItems: true - }, - ignoreArrayIndexes: { - type: "boolean", - default: false - }, - ignoreDefaultValues: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - - messages: { - useConst: "Number constants declarations must use 'const'.", - noMagic: "No magic number: {{raw}}." - } - }, - - create(context) { - const config = context.options[0] || {}, - detectObjects = !!config.detectObjects, - enforceConst = !!config.enforceConst, - ignore = (config.ignore || []).map(normalizeIgnoreValue), - ignoreArrayIndexes = !!config.ignoreArrayIndexes, - ignoreDefaultValues = !!config.ignoreDefaultValues; - - const okTypes = detectObjects ? [] : ["ObjectExpression", "Property", "AssignmentExpression"]; - - /** - * Returns whether the rule is configured to ignore the given value - * @param {bigint|number} value The value to check - * @returns {boolean} true if the value is ignored - */ - function isIgnoredValue(value) { - return ignore.indexOf(value) !== -1; - } - - /** - * Returns whether the number is a default value assignment. - * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node - * @returns {boolean} true if the number is a default value - */ - function isDefaultValue(fullNumberNode) { - const parent = fullNumberNode.parent; - - return parent.type === "AssignmentPattern" && parent.right === fullNumberNode; - } - - /** - * Returns whether the given node is used as a radix within parseInt() or Number.parseInt() - * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node - * @returns {boolean} true if the node is radix - */ - function isParseIntRadix(fullNumberNode) { - const parent = fullNumberNode.parent; - - return parent.type === "CallExpression" && fullNumberNode === parent.arguments[1] && - ( - astUtils.isSpecificId(parent.callee, "parseInt") || - astUtils.isSpecificMemberAccess(parent.callee, "Number", "parseInt") - ); - } - - /** - * Returns whether the given node is a direct child of a JSX node. - * In particular, it aims to detect numbers used as prop values in JSX tags. - * Example: - * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node - * @returns {boolean} true if the node is a JSX number - */ - function isJSXNumber(fullNumberNode) { - return fullNumberNode.parent.type.indexOf("JSX") === 0; - } - - /** - * Returns whether the given node is used as an array index. - * Value must coerce to a valid array index name: "0", "1", "2" ... "4294967294". - * - * All other values, like "-1", "2.5", or "4294967295", are just "normal" object properties, - * which can be created and accessed on an array in addition to the array index properties, - * but they don't affect array's length and are not considered by methods such as .map(), .forEach() etc. - * - * The maximum array length by the specification is 2 ** 32 - 1 = 4294967295, - * thus the maximum valid index is 2 ** 32 - 2 = 4294967294. - * - * All notations are allowed, as long as the value coerces to one of "0", "1", "2" ... "4294967294". - * - * Valid examples: - * a[0], a[1], a[1.2e1], a[0xAB], a[0n], a[1n] - * a[-0] (same as a[0] because -0 coerces to "0") - * a[-0n] (-0n evaluates to 0n) - * - * Invalid examples: - * a[-1], a[-0xAB], a[-1n], a[2.5], a[1.23e1], a[12e-1] - * a[4294967295] (above the max index, it's an access to a regular property a["4294967295"]) - * a[999999999999999999999] (even if it wasn't above the max index, it would be a["1e+21"]) - * a[1e310] (same as a["Infinity"]) - * @param {ASTNode} fullNumberNode `Literal` or `UnaryExpression` full number node - * @param {bigint|number} value Value expressed by the fullNumberNode - * @returns {boolean} true if the node is a valid array index - */ - function isArrayIndex(fullNumberNode, value) { - const parent = fullNumberNode.parent; - - return parent.type === "MemberExpression" && parent.property === fullNumberNode && - (Number.isInteger(value) || typeof value === "bigint") && - value >= 0 && value < MAX_ARRAY_LENGTH; - } - - return { - Literal(node) { - if (!astUtils.isNumericLiteral(node)) { - return; - } - - let fullNumberNode; - let value; - let raw; - - // Treat unary minus as a part of the number - if (node.parent.type === "UnaryExpression" && node.parent.operator === "-") { - fullNumberNode = node.parent; - value = -node.value; - raw = `-${node.raw}`; - } else { - fullNumberNode = node; - value = node.value; - raw = node.raw; - } - - const parent = fullNumberNode.parent; - - // Always allow radix arguments and JSX props - if ( - isIgnoredValue(value) || - (ignoreDefaultValues && isDefaultValue(fullNumberNode)) || - isParseIntRadix(fullNumberNode) || - isJSXNumber(fullNumberNode) || - (ignoreArrayIndexes && isArrayIndex(fullNumberNode, value)) - ) { - return; - } - - if (parent.type === "VariableDeclarator") { - if (enforceConst && parent.parent.kind !== "const") { - context.report({ - node: fullNumberNode, - messageId: "useConst" - }); - } - } else if ( - okTypes.indexOf(parent.type) === -1 || - (parent.type === "AssignmentExpression" && parent.left.type === "Identifier") - ) { - context.report({ - node: fullNumberNode, - messageId: "noMagic", - data: { - raw - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js b/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js deleted file mode 100644 index 3d004615c3f0707b28935d89d00b40e2ee9f0b81..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-misleading-character-class.js +++ /dev/null @@ -1,200 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("eslint-utils"); -const { RegExpParser, visitRegExpAST } = require("regexpp"); -const { isCombiningCharacter, isEmojiModifier, isRegionalIndicatorSymbol, isSurrogatePair } = require("./utils/unicode"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Iterate character sequences of a given nodes. - * - * CharacterClassRange syntax can steal a part of character sequence, - * so this function reverts CharacterClassRange syntax and restore the sequence. - * @param {regexpp.AST.CharacterClassElement[]} nodes The node list to iterate character sequences. - * @returns {IterableIterator} The list of character sequences. - */ -function *iterateCharacterSequence(nodes) { - let seq = []; - - for (const node of nodes) { - switch (node.type) { - case "Character": - seq.push(node.value); - break; - - case "CharacterClassRange": - seq.push(node.min.value); - yield seq; - seq = [node.max.value]; - break; - - case "CharacterSet": - if (seq.length > 0) { - yield seq; - seq = []; - } - break; - - // no default - } - } - - if (seq.length > 0) { - yield seq; - } -} - -const hasCharacterSequence = { - surrogatePairWithoutUFlag(chars) { - return chars.some((c, i) => i !== 0 && isSurrogatePair(chars[i - 1], c)); - }, - - combiningClass(chars) { - return chars.some((c, i) => ( - i !== 0 && - isCombiningCharacter(c) && - !isCombiningCharacter(chars[i - 1]) - )); - }, - - emojiModifier(chars) { - return chars.some((c, i) => ( - i !== 0 && - isEmojiModifier(c) && - !isEmojiModifier(chars[i - 1]) - )); - }, - - regionalIndicatorSymbol(chars) { - return chars.some((c, i) => ( - i !== 0 && - isRegionalIndicatorSymbol(c) && - isRegionalIndicatorSymbol(chars[i - 1]) - )); - }, - - zwj(chars) { - const lastIndex = chars.length - 1; - - return chars.some((c, i) => ( - i !== 0 && - i !== lastIndex && - c === 0x200d && - chars[i - 1] !== 0x200d && - chars[i + 1] !== 0x200d - )); - } -}; - -const kinds = Object.keys(hasCharacterSequence); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow characters which are made with multiple code points in character class syntax", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-misleading-character-class" - }, - - schema: [], - - messages: { - surrogatePairWithoutUFlag: "Unexpected surrogate pair in character class. Use 'u' flag.", - combiningClass: "Unexpected combined character in character class.", - emojiModifier: "Unexpected modified Emoji in character class.", - regionalIndicatorSymbol: "Unexpected national flag in character class.", - zwj: "Unexpected joined character sequence in character class." - } - }, - create(context) { - const parser = new RegExpParser(); - - /** - * Verify a given regular expression. - * @param {Node} node The node to report. - * @param {string} pattern The regular expression pattern to verify. - * @param {string} flags The flags of the regular expression. - * @returns {void} - */ - function verify(node, pattern, flags) { - const has = { - surrogatePairWithoutUFlag: false, - combiningClass: false, - variationSelector: false, - emojiModifier: false, - regionalIndicatorSymbol: false, - zwj: false - }; - let patternNode; - - try { - patternNode = parser.parsePattern( - pattern, - 0, - pattern.length, - flags.includes("u") - ); - } catch { - - // Ignore regular expressions with syntax errors - return; - } - - visitRegExpAST(patternNode, { - onCharacterClassEnter(ccNode) { - for (const chars of iterateCharacterSequence(ccNode.elements)) { - for (const kind of kinds) { - has[kind] = has[kind] || hasCharacterSequence[kind](chars); - } - } - } - }); - - for (const kind of kinds) { - if (has[kind]) { - context.report({ node, messageId: kind }); - } - } - } - - return { - "Literal[regex]"(node) { - verify(node, node.regex.pattern, node.regex.flags); - }, - "Program"() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - - /* - * Iterate calls of RegExp. - * E.g., `new RegExp()`, `RegExp()`, `new window.RegExp()`, - * `const {RegExp: a} = window; new a()`, etc... - */ - for (const { node } of tracker.iterateGlobalReferences({ - RegExp: { [CALL]: true, [CONSTRUCT]: true } - })) { - const [patternNode, flagsNode] = node.arguments; - const pattern = getStringIfConstant(patternNode, scope); - const flags = getStringIfConstant(flagsNode, scope); - - if (typeof pattern === "string") { - verify(node, pattern, flags || ""); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-operators.js b/tools/node_modules/eslint/lib/rules/no-mixed-operators.js deleted file mode 100644 index f0290e93ece8db84babb31cbed8ccfa1e99eb755..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-mixed-operators.js +++ /dev/null @@ -1,243 +0,0 @@ -/** - * @fileoverview Rule to disallow mixed binary operators. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils.js"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const ARITHMETIC_OPERATORS = ["+", "-", "*", "/", "%", "**"]; -const BITWISE_OPERATORS = ["&", "|", "^", "~", "<<", ">>", ">>>"]; -const COMPARISON_OPERATORS = ["==", "!=", "===", "!==", ">", ">=", "<", "<="]; -const LOGICAL_OPERATORS = ["&&", "||"]; -const RELATIONAL_OPERATORS = ["in", "instanceof"]; -const TERNARY_OPERATOR = ["?:"]; -const COALESCE_OPERATOR = ["??"]; -const ALL_OPERATORS = [].concat( - ARITHMETIC_OPERATORS, - BITWISE_OPERATORS, - COMPARISON_OPERATORS, - LOGICAL_OPERATORS, - RELATIONAL_OPERATORS, - TERNARY_OPERATOR, - COALESCE_OPERATOR -); -const DEFAULT_GROUPS = [ - ARITHMETIC_OPERATORS, - BITWISE_OPERATORS, - COMPARISON_OPERATORS, - LOGICAL_OPERATORS, - RELATIONAL_OPERATORS -]; -const TARGET_NODE_TYPE = /^(?:Binary|Logical|Conditional)Expression$/u; - -/** - * Normalizes options. - * @param {Object|undefined} options A options object to normalize. - * @returns {Object} Normalized option object. - */ -function normalizeOptions(options = {}) { - const hasGroups = options.groups && options.groups.length > 0; - const groups = hasGroups ? options.groups : DEFAULT_GROUPS; - const allowSamePrecedence = options.allowSamePrecedence !== false; - - return { - groups, - allowSamePrecedence - }; -} - -/** - * Checks whether any group which includes both given operator exists or not. - * @param {Array.} groups A list of groups to check. - * @param {string} left An operator. - * @param {string} right Another operator. - * @returns {boolean} `true` if such group existed. - */ -function includesBothInAGroup(groups, left, right) { - return groups.some(group => group.indexOf(left) !== -1 && group.indexOf(right) !== -1); -} - -/** - * Checks whether the given node is a conditional expression and returns the test node else the left node. - * @param {ASTNode} node A node which can be a BinaryExpression or a LogicalExpression node. - * This parent node can be BinaryExpression, LogicalExpression - * , or a ConditionalExpression node - * @returns {ASTNode} node the appropriate node(left or test). - */ -function getChildNode(node) { - return node.type === "ConditionalExpression" ? node.test : node.left; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow mixed binary operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-mixed-operators" - }, - - schema: [ - { - type: "object", - properties: { - groups: { - type: "array", - items: { - type: "array", - items: { enum: ALL_OPERATORS }, - minItems: 2, - uniqueItems: true - }, - uniqueItems: true - }, - allowSamePrecedence: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedMixedOperator: "Unexpected mix of '{{leftOperator}}' and '{{rightOperator}}'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = normalizeOptions(context.options[0]); - - /** - * Checks whether a given node should be ignored by options or not. - * @param {ASTNode} node A node to check. This is a BinaryExpression - * node or a LogicalExpression node. This parent node is one of - * them, too. - * @returns {boolean} `true` if the node should be ignored. - */ - function shouldIgnore(node) { - const a = node; - const b = node.parent; - - return ( - !includesBothInAGroup(options.groups, a.operator, b.type === "ConditionalExpression" ? "?:" : b.operator) || - ( - options.allowSamePrecedence && - astUtils.getPrecedence(a) === astUtils.getPrecedence(b) - ) - ); - } - - /** - * Checks whether the operator of a given node is mixed with parent - * node's operator or not. - * @param {ASTNode} node A node to check. This is a BinaryExpression - * node or a LogicalExpression node. This parent node is one of - * them, too. - * @returns {boolean} `true` if the node was mixed. - */ - function isMixedWithParent(node) { - - return ( - node.operator !== node.parent.operator && - !astUtils.isParenthesised(sourceCode, node) - ); - } - - /** - * Checks whether the operator of a given node is mixed with a - * conditional expression. - * @param {ASTNode} node A node to check. This is a conditional - * expression node - * @returns {boolean} `true` if the node was mixed. - */ - function isMixedWithConditionalParent(node) { - return !astUtils.isParenthesised(sourceCode, node) && !astUtils.isParenthesised(sourceCode, node.test); - } - - /** - * Gets the operator token of a given node. - * @param {ASTNode} node A node to check. This is a BinaryExpression - * node or a LogicalExpression node. - * @returns {Token} The operator token of the node. - */ - function getOperatorToken(node) { - return sourceCode.getTokenAfter(getChildNode(node), astUtils.isNotClosingParenToken); - } - - /** - * Reports both the operator of a given node and the operator of the - * parent node. - * @param {ASTNode} node A node to check. This is a BinaryExpression - * node or a LogicalExpression node. This parent node is one of - * them, too. - * @returns {void} - */ - function reportBothOperators(node) { - const parent = node.parent; - const left = (getChildNode(parent) === node) ? node : parent; - const right = (getChildNode(parent) !== node) ? node : parent; - const data = { - leftOperator: left.operator || "?:", - rightOperator: right.operator || "?:" - }; - - context.report({ - node: left, - loc: getOperatorToken(left).loc, - messageId: "unexpectedMixedOperator", - data - }); - context.report({ - node: right, - loc: getOperatorToken(right).loc, - messageId: "unexpectedMixedOperator", - data - }); - } - - /** - * Checks between the operator of this node and the operator of the - * parent node. - * @param {ASTNode} node A node to check. - * @returns {void} - */ - function check(node) { - if (TARGET_NODE_TYPE.test(node.parent.type)) { - if (node.parent.type === "ConditionalExpression" && !shouldIgnore(node) && isMixedWithConditionalParent(node.parent)) { - reportBothOperators(node); - } else { - if (TARGET_NODE_TYPE.test(node.parent.type) && - isMixedWithParent(node) && - !shouldIgnore(node) - ) { - reportBothOperators(node); - } - } - } - - } - - return { - BinaryExpression: check, - LogicalExpression: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-requires.js b/tools/node_modules/eslint/lib/rules/no-mixed-requires.js deleted file mode 100644 index a02de9104bdd88670fa6091097b36e0c1e132537..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-mixed-requires.js +++ /dev/null @@ -1,237 +0,0 @@ -/** - * @fileoverview Rule to enforce grouped require statements for Node.JS - * @author Raphael Pigulla - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow `require` calls to be mixed with regular variable declarations", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-mixed-requires" - }, - - schema: [ - { - oneOf: [ - { - type: "boolean" - }, - { - type: "object", - properties: { - grouping: { - type: "boolean" - }, - allowCall: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - noMixRequire: "Do not mix 'require' and other declarations.", - noMixCoreModuleFileComputed: "Do not mix core, module, file and computed requires." - } - }, - - create(context) { - - const options = context.options[0]; - let grouping = false, - allowCall = false; - - if (typeof options === "object") { - grouping = options.grouping; - allowCall = options.allowCall; - } else { - grouping = !!options; - } - - /** - * Returns the list of built-in modules. - * @returns {string[]} An array of built-in Node.js modules. - */ - function getBuiltinModules() { - - /* - * This list is generated using: - * `require("repl")._builtinLibs.concat('repl').sort()` - * This particular list is as per nodejs v0.12.2 and iojs v0.7.1 - */ - return [ - "assert", "buffer", "child_process", "cluster", "crypto", - "dgram", "dns", "domain", "events", "fs", "http", "https", - "net", "os", "path", "punycode", "querystring", "readline", - "repl", "smalloc", "stream", "string_decoder", "tls", "tty", - "url", "util", "v8", "vm", "zlib" - ]; - } - - const BUILTIN_MODULES = getBuiltinModules(); - - const DECL_REQUIRE = "require", - DECL_UNINITIALIZED = "uninitialized", - DECL_OTHER = "other"; - - const REQ_CORE = "core", - REQ_FILE = "file", - REQ_MODULE = "module", - REQ_COMPUTED = "computed"; - - /** - * Determines the type of a declaration statement. - * @param {ASTNode} initExpression The init node of the VariableDeclarator. - * @returns {string} The type of declaration represented by the expression. - */ - function getDeclarationType(initExpression) { - if (!initExpression) { - - // "var x;" - return DECL_UNINITIALIZED; - } - - if (initExpression.type === "CallExpression" && - initExpression.callee.type === "Identifier" && - initExpression.callee.name === "require" - ) { - - // "var x = require('util');" - return DECL_REQUIRE; - } - if (allowCall && - initExpression.type === "CallExpression" && - initExpression.callee.type === "CallExpression" - ) { - - // "var x = require('diagnose')('sub-module');" - return getDeclarationType(initExpression.callee); - } - if (initExpression.type === "MemberExpression") { - - // "var x = require('glob').Glob;" - return getDeclarationType(initExpression.object); - } - - // "var x = 42;" - return DECL_OTHER; - } - - /** - * Determines the type of module that is loaded via require. - * @param {ASTNode} initExpression The init node of the VariableDeclarator. - * @returns {string} The module type. - */ - function inferModuleType(initExpression) { - if (initExpression.type === "MemberExpression") { - - // "var x = require('glob').Glob;" - return inferModuleType(initExpression.object); - } - if (initExpression.arguments.length === 0) { - - // "var x = require();" - return REQ_COMPUTED; - } - - const arg = initExpression.arguments[0]; - - if (arg.type !== "Literal" || typeof arg.value !== "string") { - - // "var x = require(42);" - return REQ_COMPUTED; - } - - if (BUILTIN_MODULES.indexOf(arg.value) !== -1) { - - // "var fs = require('fs');" - return REQ_CORE; - } - if (/^\.{0,2}\//u.test(arg.value)) { - - // "var utils = require('./utils');" - return REQ_FILE; - } - - // "var async = require('async');" - return REQ_MODULE; - - } - - /** - * Check if the list of variable declarations is mixed, i.e. whether it - * contains both require and other declarations. - * @param {ASTNode} declarations The list of VariableDeclarators. - * @returns {boolean} True if the declarations are mixed, false if not. - */ - function isMixed(declarations) { - const contains = {}; - - declarations.forEach(declaration => { - const type = getDeclarationType(declaration.init); - - contains[type] = true; - }); - - return !!( - contains[DECL_REQUIRE] && - (contains[DECL_UNINITIALIZED] || contains[DECL_OTHER]) - ); - } - - /** - * Check if all require declarations in the given list are of the same - * type. - * @param {ASTNode} declarations The list of VariableDeclarators. - * @returns {boolean} True if the declarations are grouped, false if not. - */ - function isGrouped(declarations) { - const found = {}; - - declarations.forEach(declaration => { - if (getDeclarationType(declaration.init) === DECL_REQUIRE) { - found[inferModuleType(declaration.init)] = true; - } - }); - - return Object.keys(found).length <= 1; - } - - - return { - - VariableDeclaration(node) { - - if (isMixed(node.declarations)) { - context.report({ - node, - messageId: "noMixRequire" - }); - } else if (grouping && !isGrouped(node.declarations)) { - context.report({ - node, - messageId: "noMixCoreModuleFileComputed" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js b/tools/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js deleted file mode 100644 index 287cbda03daf5a6795aedc74c74e883512765ce8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-mixed-spaces-and-tabs.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @fileoverview Disallow mixed spaces and tabs for indentation - * @author Jary Niebur - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow mixed spaces and tabs for indentation", - category: "Stylistic Issues", - recommended: true, - url: "https://eslint.org/docs/rules/no-mixed-spaces-and-tabs" - }, - - schema: [ - { - enum: ["smart-tabs", true, false] - } - ], - - messages: { - mixedSpacesAndTabs: "Mixed spaces and tabs." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - let smartTabs; - - switch (context.options[0]) { - case true: // Support old syntax, maybe add deprecation warning here - case "smart-tabs": - smartTabs = true; - break; - default: - smartTabs = false; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - "Program:exit"(node) { - const lines = sourceCode.lines, - comments = sourceCode.getAllComments(), - ignoredCommentLines = new Set(); - - // Add all lines except the first ones. - comments.forEach(comment => { - for (let i = comment.loc.start.line + 1; i <= comment.loc.end.line; i++) { - ignoredCommentLines.add(i); - } - }); - - /* - * At least one space followed by a tab - * or the reverse before non-tab/-space - * characters begin. - */ - let regex = /^(?=( +|\t+))\1(?:\t| )/u; - - if (smartTabs) { - - /* - * At least one space followed by a tab - * before non-tab/-space characters begin. - */ - regex = /^(?=(\t*))\1(?=( +))\2\t/u; - } - - lines.forEach((line, i) => { - const match = regex.exec(line); - - if (match) { - const lineNumber = i + 1; - const loc = { - start: { - line: lineNumber, - column: match[0].length - 2 - }, - end: { - line: lineNumber, - column: match[0].length - } - }; - - if (!ignoredCommentLines.has(lineNumber)) { - const containingNode = sourceCode.getNodeByRangeIndex(sourceCode.getIndexFromLoc(loc.start)); - - if (!(containingNode && ["Literal", "TemplateElement"].includes(containingNode.type))) { - context.report({ - node, - loc, - messageId: "mixedSpacesAndTabs" - }); - } - } - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multi-assign.js b/tools/node_modules/eslint/lib/rules/no-multi-assign.js deleted file mode 100644 index ab6430c19ef07071dc9f413cccbc9d418292d2f2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multi-assign.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @fileoverview Rule to check use of chained assignment expressions - * @author Stewart Rand - */ - -"use strict"; - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow use of chained assignment expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-multi-assign" - }, - - schema: [], - - messages: { - unexpectedChain: "Unexpected chained assignment." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - AssignmentExpression(node) { - if (["AssignmentExpression", "VariableDeclarator"].indexOf(node.parent.type) !== -1) { - context.report({ - node, - messageId: "unexpectedChain" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multi-spaces.js b/tools/node_modules/eslint/lib/rules/no-multi-spaces.js deleted file mode 100644 index d43ed7363379453975657091add4b5dca54eab0a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multi-spaces.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @fileoverview Disallow use of multiple spaces. - * @author Nicholas C. Zakas - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow multiple spaces", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-multi-spaces" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "object", - patternProperties: { - "^([A-Z][a-z]*)+$": { - type: "boolean" - } - }, - additionalProperties: false - }, - ignoreEOLComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - multipleSpaces: "Multiple spaces found before '{{displayValue}}'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = context.options[0] || {}; - const ignoreEOLComments = options.ignoreEOLComments; - const exceptions = Object.assign({ Property: true }, options.exceptions); - const hasExceptions = Object.keys(exceptions).filter(key => exceptions[key]).length > 0; - - /** - * Formats value of given comment token for error message by truncating its length. - * @param {Token} token comment token - * @returns {string} formatted value - * @private - */ - function formatReportedCommentValue(token) { - const valueLines = token.value.split("\n"); - const value = valueLines[0]; - const formattedValue = `${value.slice(0, 12)}...`; - - return valueLines.length === 1 && value.length <= 12 ? value : formattedValue; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program() { - sourceCode.tokensAndComments.forEach((leftToken, leftIndex, tokensAndComments) => { - if (leftIndex === tokensAndComments.length - 1) { - return; - } - const rightToken = tokensAndComments[leftIndex + 1]; - - // Ignore tokens that don't have 2 spaces between them or are on different lines - if ( - !sourceCode.text.slice(leftToken.range[1], rightToken.range[0]).includes(" ") || - leftToken.loc.end.line < rightToken.loc.start.line - ) { - return; - } - - // Ignore comments that are the last token on their line if `ignoreEOLComments` is active. - if ( - ignoreEOLComments && - astUtils.isCommentToken(rightToken) && - ( - leftIndex === tokensAndComments.length - 2 || - rightToken.loc.end.line < tokensAndComments[leftIndex + 2].loc.start.line - ) - ) { - return; - } - - // Ignore tokens that are in a node in the "exceptions" object - if (hasExceptions) { - const parentNode = sourceCode.getNodeByRangeIndex(rightToken.range[0] - 1); - - if (parentNode && exceptions[parentNode.type]) { - return; - } - } - - let displayValue; - - if (rightToken.type === "Block") { - displayValue = `/*${formatReportedCommentValue(rightToken)}*/`; - } else if (rightToken.type === "Line") { - displayValue = `//${formatReportedCommentValue(rightToken)}`; - } else { - displayValue = rightToken.value; - } - - context.report({ - node: rightToken, - loc: { start: leftToken.loc.end, end: rightToken.loc.start }, - messageId: "multipleSpaces", - data: { displayValue }, - fix: fixer => fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ") - }); - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multi-str.js b/tools/node_modules/eslint/lib/rules/no-multi-str.js deleted file mode 100644 index 7cf1ae367942fe89ffc21be29abca842825fb915..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multi-str.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Rule to flag when using multiline strings - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow multiline strings", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-multi-str" - }, - - schema: [], - - messages: { - multilineString: "Multiline support is limited to browsers supporting ES5 only." - } - }, - - create(context) { - - /** - * Determines if a given node is part of JSX syntax. - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node is a JSX node, false if not. - * @private - */ - function isJSXElement(node) { - return node.type.indexOf("JSX") === 0; - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - Literal(node) { - if (astUtils.LINEBREAK_MATCHER.test(node.raw) && !isJSXElement(node.parent)) { - context.report({ - node, - messageId: "multilineString" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-multiple-empty-lines.js b/tools/node_modules/eslint/lib/rules/no-multiple-empty-lines.js deleted file mode 100644 index 9cccef3088a56e1a2430913a684c11ddd49d3cda..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-multiple-empty-lines.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @fileoverview Disallows multiple blank lines. - * implementation adapted from the no-trailing-spaces rule. - * @author Greg Cochard - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow multiple empty lines", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-multiple-empty-lines" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - max: { - type: "integer", - minimum: 0 - }, - maxEOF: { - type: "integer", - minimum: 0 - }, - maxBOF: { - type: "integer", - minimum: 0 - } - }, - required: ["max"], - additionalProperties: false - } - ], - - messages: { - blankBeginningOfFile: "Too many blank lines at the beginning of file. Max of {{max}} allowed.", - blankEndOfFile: "Too many blank lines at the end of file. Max of {{max}} allowed.", - consecutiveBlank: "More than {{max}} blank {{pluralizedLines}} not allowed." - } - }, - - create(context) { - - // Use options.max or 2 as default - let max = 2, - maxEOF = max, - maxBOF = max; - - if (context.options.length) { - max = context.options[0].max; - maxEOF = typeof context.options[0].maxEOF !== "undefined" ? context.options[0].maxEOF : max; - maxBOF = typeof context.options[0].maxBOF !== "undefined" ? context.options[0].maxBOF : max; - } - - const sourceCode = context.getSourceCode(); - - // Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue - const allLines = sourceCode.lines[sourceCode.lines.length - 1] === "" ? sourceCode.lines.slice(0, -1) : sourceCode.lines; - const templateLiteralLines = new Set(); - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - TemplateLiteral(node) { - node.quasis.forEach(literalPart => { - - // Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. - for (let ignoredLine = literalPart.loc.start.line; ignoredLine < literalPart.loc.end.line; ignoredLine++) { - templateLiteralLines.add(ignoredLine); - } - }); - }, - "Program:exit"(node) { - return allLines - - // Given a list of lines, first get a list of line numbers that are non-empty. - .reduce((nonEmptyLineNumbers, line, index) => { - if (line.trim() || templateLiteralLines.has(index + 1)) { - nonEmptyLineNumbers.push(index + 1); - } - return nonEmptyLineNumbers; - }, []) - - // Add a value at the end to allow trailing empty lines to be checked. - .concat(allLines.length + 1) - - // Given two line numbers of non-empty lines, report the lines between if the difference is too large. - .reduce((lastLineNumber, lineNumber) => { - let messageId, maxAllowed; - - if (lastLineNumber === 0) { - messageId = "blankBeginningOfFile"; - maxAllowed = maxBOF; - } else if (lineNumber === allLines.length + 1) { - messageId = "blankEndOfFile"; - maxAllowed = maxEOF; - } else { - messageId = "consecutiveBlank"; - maxAllowed = max; - } - - if (lineNumber - lastLineNumber - 1 > maxAllowed) { - context.report({ - node, - loc: { - start: { line: lastLineNumber + maxAllowed + 1, column: 0 }, - end: { line: lineNumber, column: 0 } - }, - messageId, - data: { - max: maxAllowed, - pluralizedLines: maxAllowed === 1 ? "line" : "lines" - }, - fix(fixer) { - const rangeStart = sourceCode.getIndexFromLoc({ line: lastLineNumber + 1, column: 0 }); - - /* - * The end of the removal range is usually the start index of the next line. - * However, at the end of the file there is no next line, so the end of the - * range is just the length of the text. - */ - const lineNumberAfterRemovedLines = lineNumber - maxAllowed; - const rangeEnd = lineNumberAfterRemovedLines <= allLines.length - ? sourceCode.getIndexFromLoc({ line: lineNumberAfterRemovedLines, column: 0 }) - : sourceCode.text.length; - - return fixer.removeRange([rangeStart, rangeEnd]); - } - }); - } - - return lineNumber; - }, 0); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-native-reassign.js b/tools/node_modules/eslint/lib/rules/no-native-reassign.js deleted file mode 100644 index 833e3b7ce409b3ffe00005d03079a002648f9cec..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-native-reassign.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @fileoverview Rule to disallow assignments to native objects or read-only global variables - * @author Ilya Volodin - * @deprecated in ESLint v3.3.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow assignments to native objects or read-only global variables", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-native-reassign" - }, - - deprecated: true, - - replacedBy: ["no-global-assign"], - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { type: "string" }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - nativeReassign: "Read-only global '{{name}}' should not be modified." - } - }, - - create(context) { - const config = context.options[0]; - const exceptions = (config && config.exceptions) || []; - - /** - * Reports write references. - * @param {Reference} reference A reference to check. - * @param {int} index The index of the reference in the references. - * @param {Reference[]} references The array that the reference belongs to. - * @returns {void} - */ - function checkReference(reference, index, references) { - const identifier = reference.identifier; - - if (reference.init === false && - reference.isWrite() && - - /* - * Destructuring assignments can have multiple default value, - * so possibly there are multiple writeable references for the same identifier. - */ - (index === 0 || references[index - 1].identifier !== identifier) - ) { - context.report({ - node: identifier, - messageId: "nativeReassign", - data: identifier - }); - } - } - - /** - * Reports write references if a given variable is read-only builtin. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) { - variable.references.forEach(checkReference); - } - } - - return { - Program() { - const globalScope = context.getScope(); - - globalScope.variables.forEach(checkVariable); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-negated-condition.js b/tools/node_modules/eslint/lib/rules/no-negated-condition.js deleted file mode 100644 index 8a9eba881df04c667ffde3f4c80486f2dbbbf8b0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-negated-condition.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @fileoverview Rule to disallow a negated condition - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow negated conditions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-negated-condition" - }, - - schema: [], - - messages: { - unexpectedNegated: "Unexpected negated condition." - } - }, - - create(context) { - - /** - * Determines if a given node is an if-else without a condition on the else - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node has an else without an if. - * @private - */ - function hasElseWithoutCondition(node) { - return node.alternate && node.alternate.type !== "IfStatement"; - } - - /** - * Determines if a given node is a negated unary expression - * @param {Object} test The test object to check. - * @returns {boolean} True if the node is a negated unary expression. - * @private - */ - function isNegatedUnaryExpression(test) { - return test.type === "UnaryExpression" && test.operator === "!"; - } - - /** - * Determines if a given node is a negated binary expression - * @param {Test} test The test to check. - * @returns {boolean} True if the node is a negated binary expression. - * @private - */ - function isNegatedBinaryExpression(test) { - return test.type === "BinaryExpression" && - (test.operator === "!=" || test.operator === "!=="); - } - - /** - * Determines if a given node has a negated if expression - * @param {ASTNode} node The node to check. - * @returns {boolean} True if the node has a negated if expression. - * @private - */ - function isNegatedIf(node) { - return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test); - } - - return { - IfStatement(node) { - if (!hasElseWithoutCondition(node)) { - return; - } - - if (isNegatedIf(node)) { - context.report({ - node, - messageId: "unexpectedNegated" - }); - } - }, - ConditionalExpression(node) { - if (isNegatedIf(node)) { - context.report({ - node, - messageId: "unexpectedNegated" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-negated-in-lhs.js b/tools/node_modules/eslint/lib/rules/no-negated-in-lhs.js deleted file mode 100644 index 1229cedd1190dca070a478df1b585c3ea2dd94c0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-negated-in-lhs.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview A rule to disallow negated left operands of the `in` operator - * @author Michael Ficarra - * @deprecated in ESLint v3.3.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow negating the left operand in `in` expressions", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-negated-in-lhs" - }, - - replacedBy: ["no-unsafe-negation"], - - deprecated: true, - schema: [], - - messages: { - negatedLHS: "The 'in' expression's left operand is negated." - } - }, - - create(context) { - - return { - - BinaryExpression(node) { - if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") { - context.report({ node, messageId: "negatedLHS" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-nested-ternary.js b/tools/node_modules/eslint/lib/rules/no-nested-ternary.js deleted file mode 100644 index 383bb238887d2aeef9c961db29ca1c49d884e768..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-nested-ternary.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @fileoverview Rule to flag nested ternary expressions - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow nested ternary expressions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-nested-ternary" - }, - - schema: [], - - messages: { - noNestedTernary: "Do not nest ternary expressions." - } - }, - - create(context) { - - return { - ConditionalExpression(node) { - if (node.alternate.type === "ConditionalExpression" || - node.consequent.type === "ConditionalExpression") { - context.report({ - node, - messageId: "noNestedTernary" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-func.js b/tools/node_modules/eslint/lib/rules/no-new-func.js deleted file mode 100644 index 9af4e31cabf6d44fe55905bcaa1a7ac129270095..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-func.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview Rule to flag when using new Function - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators with the `Function` object", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-func" - }, - - schema: [], - - messages: { - noFunctionConstructor: "The Function constructor is eval." - } - }, - - create(context) { - - return { - "Program:exit"() { - const globalScope = context.getScope(); - const variable = globalScope.set.get("Function"); - - if (variable && variable.defs.length === 0) { - variable.references.forEach(ref => { - const node = ref.identifier; - const { parent } = node; - - if ( - parent && - (parent.type === "NewExpression" || parent.type === "CallExpression") && - node === parent.callee - ) { - context.report({ - node: parent, - messageId: "noFunctionConstructor" - }); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-object.js b/tools/node_modules/eslint/lib/rules/no-new-object.js deleted file mode 100644 index e9f915db5eaa9173dfe8a094da8dbdcd7b519252..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-object.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview A rule to disallow calls to the Object constructor - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `Object` constructors", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-object" - }, - - schema: [], - - messages: { - preferLiteral: "The object literal notation {} is preferrable." - } - }, - - create(context) { - return { - NewExpression(node) { - const variable = astUtils.getVariableByName( - context.getScope(), - node.callee.name - ); - - if (variable && variable.identifiers.length > 0) { - return; - } - - if (node.callee.name === "Object") { - context.report({ - node, - messageId: "preferLiteral" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-require.js b/tools/node_modules/eslint/lib/rules/no-new-require.js deleted file mode 100644 index 063f783e70cc3c7d0107f5d5ab2a952b777cd691..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-require.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @fileoverview Rule to disallow use of new operator with the `require` function - * @author Wil Moore III - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow `new` operators with calls to `require`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-require" - }, - - schema: [], - - messages: { - noNewRequire: "Unexpected use of new with require." - } - }, - - create(context) { - - return { - - NewExpression(node) { - if (node.callee.type === "Identifier" && node.callee.name === "require") { - context.report({ - node, - messageId: "noNewRequire" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-symbol.js b/tools/node_modules/eslint/lib/rules/no-new-symbol.js deleted file mode 100644 index aeb509c0d9c1424396f4a5a684fd62fb14cb75da..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-symbol.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @fileoverview Rule to disallow use of the new operator with the `Symbol` object - * @author Alberto Rodríguez - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow `new` operators with the `Symbol` object", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-new-symbol" - }, - - schema: [], - - messages: { - noNewSymbol: "`Symbol` cannot be called as a constructor." - } - }, - - create(context) { - - return { - "Program:exit"() { - const globalScope = context.getScope(); - const variable = globalScope.set.get("Symbol"); - - if (variable && variable.defs.length === 0) { - variable.references.forEach(ref => { - const node = ref.identifier; - const parent = node.parent; - - if (parent && parent.type === "NewExpression" && parent.callee === node) { - context.report({ - node, - messageId: "noNewSymbol" - }); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new-wrappers.js b/tools/node_modules/eslint/lib/rules/no-new-wrappers.js deleted file mode 100644 index d276c48d203fabada46a66e6faa30759de371952..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new-wrappers.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @fileoverview Rule to flag when using constructor for wrapper objects - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators with the `String`, `Number`, and `Boolean` objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-new-wrappers" - }, - - schema: [], - - messages: { - noConstructor: "Do not use {{fn}} as a constructor." - } - }, - - create(context) { - - return { - - NewExpression(node) { - const wrapperObjects = ["String", "Number", "Boolean"]; - - if (wrapperObjects.indexOf(node.callee.name) > -1) { - context.report({ - node, - messageId: "noConstructor", - data: { fn: node.callee.name } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-new.js b/tools/node_modules/eslint/lib/rules/no-new.js deleted file mode 100644 index aa8a4e2687660979eb907c13351655260cd62200..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-new.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Rule to flag statements with function invocation preceded by - * "new" and not part of assignment - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `new` operators outside of assignments or comparisons", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-new" - }, - - schema: [], - - messages: { - noNewStatement: "Do not use 'new' for side effects." - } - }, - - create(context) { - - return { - "ExpressionStatement > NewExpression"(node) { - context.report({ - node: node.parent, - messageId: "noNewStatement" - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-obj-calls.js b/tools/node_modules/eslint/lib/rules/no-obj-calls.js deleted file mode 100644 index 6eb200c9b879e626fda1d3d9edf14d1b62dea660..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-obj-calls.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @fileoverview Rule to flag use of an object property of the global object (Math and JSON) as a function - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { CALL, CONSTRUCT, ReferenceTracker } = require("eslint-utils"); -const getPropertyName = require("./utils/ast-utils").getStaticPropertyName; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const nonCallableGlobals = ["Atomics", "JSON", "Math", "Reflect"]; - -/** - * Returns the name of the node to report - * @param {ASTNode} node A node to report - * @returns {string} name to report - */ -function getReportNodeName(node) { - if (node.type === "ChainExpression") { - return getReportNodeName(node.expression); - } - if (node.type === "MemberExpression") { - return getPropertyName(node); - } - return node.name; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow calling global object properties as functions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-obj-calls" - }, - - schema: [], - - messages: { - unexpectedCall: "'{{name}}' is not a function.", - unexpectedRefCall: "'{{name}}' is reference to '{{ref}}', which is not a function." - } - }, - - create(context) { - - return { - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const traceMap = {}; - - for (const g of nonCallableGlobals) { - traceMap[g] = { - [CALL]: true, - [CONSTRUCT]: true - }; - } - - for (const { node, path } of tracker.iterateGlobalReferences(traceMap)) { - const name = getReportNodeName(node.callee); - const ref = path[0]; - const messageId = name === ref ? "unexpectedCall" : "unexpectedRefCall"; - - context.report({ node, messageId, data: { name, ref } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-octal-escape.js b/tools/node_modules/eslint/lib/rules/no-octal-escape.js deleted file mode 100644 index 5b4c7b2ebb45c883e77b19362aa62ed4c1c2866a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-octal-escape.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @fileoverview Rule to flag octal escape sequences in string literals. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow octal escape sequences in string literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-octal-escape" - }, - - schema: [], - - messages: { - octalEscapeSequence: "Don't use octal: '\\{{sequence}}'. Use '\\u....' instead." - } - }, - - create(context) { - - return { - - Literal(node) { - if (typeof node.value !== "string") { - return; - } - - // \0 represents a valid NULL character if it isn't followed by a digit. - const match = node.raw.match( - /^(?:[^\\]|\\.)*?\\([0-3][0-7]{1,2}|[4-7][0-7]|0(?=[89])|[1-7])/su - ); - - if (match) { - context.report({ - node, - messageId: "octalEscapeSequence", - data: { sequence: match[1] } - }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-octal.js b/tools/node_modules/eslint/lib/rules/no-octal.js deleted file mode 100644 index e9940befafa889a4bd9c8bc40e4beeff0278b748..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-octal.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @fileoverview Rule to flag when initializing octal literal - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow octal literals", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-octal" - }, - - schema: [], - - messages: { - noOcatal: "Octal literals should not be used." - } - }, - - create(context) { - - return { - - Literal(node) { - if (typeof node.value === "number" && /^0[0-9]/u.test(node.raw)) { - context.report({ - node, - messageId: "noOcatal" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-param-reassign.js b/tools/node_modules/eslint/lib/rules/no-param-reassign.js deleted file mode 100644 index 6874af44f389b731f5086a25ac67303d4b79e1b4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-param-reassign.js +++ /dev/null @@ -1,229 +0,0 @@ -/** - * @fileoverview Disallow reassignment of function parameters. - * @author Nat Burns - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow reassigning `function` parameters", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-param-reassign" - }, - - schema: [ - { - oneOf: [ - { - type: "object", - properties: { - props: { - enum: [false] - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - props: { - enum: [true] - }, - ignorePropertyModificationsFor: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - }, - ignorePropertyModificationsForRegex: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - assignmentToFunctionParam: "Assignment to function parameter '{{name}}'.", - assignmentToFunctionParamProp: "Assignment to property of function parameter '{{name}}'." - } - }, - - create(context) { - const props = context.options[0] && context.options[0].props; - const ignoredPropertyAssignmentsFor = context.options[0] && context.options[0].ignorePropertyModificationsFor || []; - const ignoredPropertyAssignmentsForRegex = context.options[0] && context.options[0].ignorePropertyModificationsForRegex || []; - - /** - * Checks whether or not the reference modifies properties of its variable. - * @param {Reference} reference A reference to check. - * @returns {boolean} Whether or not the reference modifies properties of its variable. - */ - function isModifyingProp(reference) { - let node = reference.identifier; - let parent = node.parent; - - while (parent && (!stopNodePattern.test(parent.type) || - parent.type === "ForInStatement" || parent.type === "ForOfStatement")) { - switch (parent.type) { - - // e.g. foo.a = 0; - case "AssignmentExpression": - return parent.left === node; - - // e.g. ++foo.a; - case "UpdateExpression": - return true; - - // e.g. delete foo.a; - case "UnaryExpression": - if (parent.operator === "delete") { - return true; - } - break; - - // e.g. for (foo.a in b) {} - case "ForInStatement": - case "ForOfStatement": - if (parent.left === node) { - return true; - } - - // this is a stop node for parent.right and parent.body - return false; - - // EXCLUDES: e.g. cache.get(foo.a).b = 0; - case "CallExpression": - if (parent.callee !== node) { - return false; - } - break; - - // EXCLUDES: e.g. cache[foo.a] = 0; - case "MemberExpression": - if (parent.property === node) { - return false; - } - break; - - // EXCLUDES: e.g. ({ [foo]: a }) = bar; - case "Property": - if (parent.key === node) { - return false; - } - - break; - - // EXCLUDES: e.g. (foo ? a : b).c = bar; - case "ConditionalExpression": - if (parent.test === node) { - return false; - } - - break; - - // no default - } - - node = parent; - parent = node.parent; - } - - return false; - } - - /** - * Tests that an identifier name matches any of the ignored property assignments. - * First we test strings in ignoredPropertyAssignmentsFor. - * Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings. - * @param {string} identifierName A string that describes the name of an identifier to - * ignore property assignments for. - * @returns {boolean} Whether the string matches an ignored property assignment regular expression or not. - */ - function isIgnoredPropertyAssignment(identifierName) { - return ignoredPropertyAssignmentsFor.includes(identifierName) || - ignoredPropertyAssignmentsForRegex.some(ignored => new RegExp(ignored, "u").test(identifierName)); - } - - /** - * Reports a reference if is non initializer and writable. - * @param {Reference} reference A reference to check. - * @param {int} index The index of the reference in the references. - * @param {Reference[]} references The array that the reference belongs to. - * @returns {void} - */ - function checkReference(reference, index, references) { - const identifier = reference.identifier; - - if (identifier && - !reference.init && - - /* - * Destructuring assignments can have multiple default value, - * so possibly there are multiple writeable references for the same identifier. - */ - (index === 0 || references[index - 1].identifier !== identifier) - ) { - if (reference.isWrite()) { - context.report({ - node: identifier, - messageId: "assignmentToFunctionParam", - data: { name: identifier.name } - }); - } else if (props && isModifyingProp(reference) && !isIgnoredPropertyAssignment(identifier.name)) { - context.report({ - node: identifier, - messageId: "assignmentToFunctionParamProp", - data: { name: identifier.name } - }); - } - } - } - - /** - * Finds and reports references that are non initializer and writable. - * @param {Variable} variable A variable to check. - * @returns {void} - */ - function checkVariable(variable) { - if (variable.defs[0].type === "Parameter") { - variable.references.forEach(checkReference); - } - } - - /** - * Checks parameters of a given function node. - * @param {ASTNode} node A function node to check. - * @returns {void} - */ - function checkForFunction(node) { - context.getDeclaredVariables(node).forEach(checkVariable); - } - - return { - - // `:exit` is needed for the `node.parent` property of identifier nodes. - "FunctionDeclaration:exit": checkForFunction, - "FunctionExpression:exit": checkForFunction, - "ArrowFunctionExpression:exit": checkForFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-path-concat.js b/tools/node_modules/eslint/lib/rules/no-path-concat.js deleted file mode 100644 index fc1f894f878988f0f995aac46034e3d071ac2e07..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-path-concat.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview Disallow string concatenation when using __dirname and __filename - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow string concatenation with `__dirname` and `__filename`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-path-concat" - }, - - schema: [], - - messages: { - usePathFunctions: "Use path.join() or path.resolve() instead of + to create paths." - } - }, - - create(context) { - - const MATCHER = /^__(?:dir|file)name$/u; - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - BinaryExpression(node) { - - const left = node.left, - right = node.right; - - if (node.operator === "+" && - ((left.type === "Identifier" && MATCHER.test(left.name)) || - (right.type === "Identifier" && MATCHER.test(right.name))) - ) { - - context.report({ - node, - messageId: "usePathFunctions" - }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-plusplus.js b/tools/node_modules/eslint/lib/rules/no-plusplus.js deleted file mode 100644 index 84d6c3e1f91d519ef13599b197edcc4a9aa5bd1f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-plusplus.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @fileoverview Rule to flag use of unary increment and decrement operators. - * @author Ian Christian Myers - * @author Brody McKee (github.com/mrmckeb) - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines whether the given node is the update node of a `ForStatement`. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is `ForStatement` update. - */ -function isForStatementUpdate(node) { - const parent = node.parent; - - return parent.type === "ForStatement" && parent.update === node; -} - -/** - * Determines whether the given node is considered to be a for loop "afterthought" by the logic of this rule. - * In particular, it returns `true` if the given node is either: - * - The update node of a `ForStatement`: for (;; i++) {} - * - An operand of a sequence expression that is the update node: for (;; foo(), i++) {} - * - An operand of a sequence expression that is child of another sequence expression, etc., - * up to the sequence expression that is the update node: for (;; foo(), (bar(), (baz(), i++))) {} - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is a for loop afterthought. - */ -function isForLoopAfterthought(node) { - const parent = node.parent; - - if (parent.type === "SequenceExpression") { - return isForLoopAfterthought(parent); - } - - return isForStatementUpdate(node); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the unary operators `++` and `--`", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-plusplus" - }, - - schema: [ - { - type: "object", - properties: { - allowForLoopAfterthoughts: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedUnaryOp: "Unary operator '{{operator}}' used." - } - }, - - create(context) { - - const config = context.options[0]; - let allowForLoopAfterthoughts = false; - - if (typeof config === "object") { - allowForLoopAfterthoughts = config.allowForLoopAfterthoughts === true; - } - - return { - - UpdateExpression(node) { - if (allowForLoopAfterthoughts && isForLoopAfterthought(node)) { - return; - } - - context.report({ - node, - messageId: "unexpectedUnaryOp", - data: { - operator: node.operator - } - }); - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-process-env.js b/tools/node_modules/eslint/lib/rules/no-process-env.js deleted file mode 100644 index 49d1734906e81f567c8edb98e99da9d6af22b637..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-process-env.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @fileoverview Disallow the use of process.env() - * @author Vignesh Anand - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow the use of `process.env`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-process-env" - }, - - schema: [], - - messages: { - unexpectedProcessEnv: "Unexpected use of process.env." - } - }, - - create(context) { - - return { - - MemberExpression(node) { - const objectName = node.object.name, - propertyName = node.property.name; - - if (objectName === "process" && !node.computed && propertyName && propertyName === "env") { - context.report({ node, messageId: "unexpectedProcessEnv" }); - } - - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-process-exit.js b/tools/node_modules/eslint/lib/rules/no-process-exit.js deleted file mode 100644 index 77c9cfd7cbd3429c6b0171fc983d380967be06b1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-process-exit.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @fileoverview Disallow the use of process.exit() - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow the use of `process.exit()`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-process-exit" - }, - - schema: [], - - messages: { - noProcessExit: "Don't use process.exit(); throw an error instead." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - "CallExpression > MemberExpression.callee[object.name = 'process'][property.name = 'exit']"(node) { - context.report({ node: node.parent, messageId: "noProcessExit" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-proto.js b/tools/node_modules/eslint/lib/rules/no-proto.js deleted file mode 100644 index 82ce02fa4e3b9eebe3f400d2f85f132ea01ed569..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-proto.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @fileoverview Rule to flag usage of __proto__ property - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { getStaticPropertyName } = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of the `__proto__` property", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-proto" - }, - - schema: [], - - messages: { - unexpectedProto: "The '__proto__' property is deprecated." - } - }, - - create(context) { - - return { - - MemberExpression(node) { - if (getStaticPropertyName(node) === "__proto__") { - context.report({ node, messageId: "unexpectedProto" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js b/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js deleted file mode 100644 index ccec86c30da072fb34f9114ee776241fa1146efb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-prototype-builtins.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @fileoverview Rule to disallow use of Object.prototype builtins on objects - * @author Andrew Levine - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow calling some `Object.prototype` methods directly on objects", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-prototype-builtins" - }, - - schema: [], - - messages: { - prototypeBuildIn: "Do not access Object.prototype method '{{prop}}' from target object." - } - }, - - create(context) { - const DISALLOWED_PROPS = [ - "hasOwnProperty", - "isPrototypeOf", - "propertyIsEnumerable" - ]; - - /** - * Reports if a disallowed property is used in a CallExpression - * @param {ASTNode} node The CallExpression node. - * @returns {void} - */ - function disallowBuiltIns(node) { - - // TODO: just use `astUtils.getStaticPropertyName(node.callee)` - const callee = astUtils.skipChainExpression(node.callee); - - if (callee.type !== "MemberExpression" || callee.computed) { - return; - } - const propName = callee.property.name; - - if (DISALLOWED_PROPS.indexOf(propName) > -1) { - context.report({ - messageId: "prototypeBuildIn", - loc: callee.property.loc, - data: { prop: propName }, - node - }); - } - } - - return { - CallExpression: disallowBuiltIns - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-redeclare.js b/tools/node_modules/eslint/lib/rules/no-redeclare.js deleted file mode 100644 index 6ddb21c9e15d9d2e30fdc51ff5d92eeac054f7e1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-redeclare.js +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @fileoverview Rule to flag when the same variable is declared more then once. - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow variable redeclaration", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-redeclare" - }, - - messages: { - redeclared: "'{{id}}' is already defined.", - redeclaredAsBuiltin: "'{{id}}' is already defined as a built-in global variable.", - redeclaredBySyntax: "'{{id}}' is already defined by a variable declaration." - }, - - schema: [ - { - type: "object", - properties: { - builtinGlobals: { type: "boolean", default: true } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const options = { - builtinGlobals: Boolean( - context.options.length === 0 || - context.options[0].builtinGlobals - ) - }; - const sourceCode = context.getSourceCode(); - - /** - * Iterate declarations of a given variable. - * @param {escope.variable} variable The variable object to iterate declarations. - * @returns {IterableIterator<{type:string,node:ASTNode,loc:SourceLocation}>} The declarations. - */ - function *iterateDeclarations(variable) { - if (options.builtinGlobals && ( - variable.eslintImplicitGlobalSetting === "readonly" || - variable.eslintImplicitGlobalSetting === "writable" - )) { - yield { type: "builtin" }; - } - - for (const id of variable.identifiers) { - yield { type: "syntax", node: id, loc: id.loc }; - } - - if (variable.eslintExplicitGlobalComments) { - for (const comment of variable.eslintExplicitGlobalComments) { - yield { - type: "comment", - node: comment, - loc: astUtils.getNameLocationInGlobalDirectiveComment( - sourceCode, - comment, - variable.name - ) - }; - } - } - } - - /** - * Find variables in a given scope and flag redeclared ones. - * @param {Scope} scope An eslint-scope scope object. - * @returns {void} - * @private - */ - function findVariablesInScope(scope) { - for (const variable of scope.variables) { - const [ - declaration, - ...extraDeclarations - ] = iterateDeclarations(variable); - - if (extraDeclarations.length === 0) { - continue; - } - - /* - * If the type of a declaration is different from the type of - * the first declaration, it shows the location of the first - * declaration. - */ - const detailMessageId = declaration.type === "builtin" - ? "redeclaredAsBuiltin" - : "redeclaredBySyntax"; - const data = { id: variable.name }; - - // Report extra declarations. - for (const { type, node, loc } of extraDeclarations) { - const messageId = type === declaration.type - ? "redeclared" - : detailMessageId; - - context.report({ node, loc, messageId, data }); - } - } - } - - /** - * Find variables in the current scope. - * @param {ASTNode} node The node of the current scope. - * @returns {void} - * @private - */ - function checkForBlock(node) { - const scope = context.getScope(); - - /* - * In ES5, some node type such as `BlockStatement` doesn't have that scope. - * `scope.block` is a different node in such a case. - */ - if (scope.block === node) { - findVariablesInScope(scope); - } - } - - return { - Program() { - const scope = context.getScope(); - - findVariablesInScope(scope); - - // Node.js or ES modules has a special scope. - if ( - scope.type === "global" && - scope.childScopes[0] && - - // The special scope's block is the Program node. - scope.block === scope.childScopes[0].block - ) { - findVariablesInScope(scope.childScopes[0]); - } - }, - - FunctionDeclaration: checkForBlock, - FunctionExpression: checkForBlock, - ArrowFunctionExpression: checkForBlock, - - BlockStatement: checkForBlock, - ForStatement: checkForBlock, - ForInStatement: checkForBlock, - ForOfStatement: checkForBlock, - SwitchStatement: checkForBlock - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-regex-spaces.js b/tools/node_modules/eslint/lib/rules/no-regex-spaces.js deleted file mode 100644 index e6d4c9efba75febf354d4e4dc498f5418b5bf76e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-regex-spaces.js +++ /dev/null @@ -1,180 +0,0 @@ -/** - * @fileoverview Rule to count multiple spaces in regular expressions - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const regexpp = require("regexpp"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const regExpParser = new regexpp.RegExpParser(); -const DOUBLE_SPACE = / {2}/u; - -/** - * Check if node is a string - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if its a string - * @private - */ -function isString(node) { - return node && node.type === "Literal" && typeof node.value === "string"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow multiple spaces in regular expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-regex-spaces" - }, - - schema: [], - fixable: "code", - - messages: { - multipleSpaces: "Spaces are hard to count. Use {{{length}}}." - } - }, - - create(context) { - - /** - * Validate regular expression - * @param {ASTNode} nodeToReport Node to report. - * @param {string} pattern Regular expression pattern to validate. - * @param {string} rawPattern Raw representation of the pattern in the source code. - * @param {number} rawPatternStartRange Start range of the pattern in the source code. - * @param {string} flags Regular expression flags. - * @returns {void} - * @private - */ - function checkRegex(nodeToReport, pattern, rawPattern, rawPatternStartRange, flags) { - - // Skip if there are no consecutive spaces in the source code, to avoid reporting e.g., RegExp(' \ '). - if (!DOUBLE_SPACE.test(rawPattern)) { - return; - } - - const characterClassNodes = []; - let regExpAST; - - try { - regExpAST = regExpParser.parsePattern(pattern, 0, pattern.length, flags.includes("u")); - } catch { - - // Ignore regular expressions with syntax errors - return; - } - - regexpp.visitRegExpAST(regExpAST, { - onCharacterClassEnter(ccNode) { - characterClassNodes.push(ccNode); - } - }); - - const spacesPattern = /( {2,})(?: [+*{?]|[^+*{?]|$)/gu; - let match; - - while ((match = spacesPattern.exec(pattern))) { - const { 1: { length }, index } = match; - - // Report only consecutive spaces that are not in character classes. - if ( - characterClassNodes.every(({ start, end }) => index < start || end <= index) - ) { - context.report({ - node: nodeToReport, - messageId: "multipleSpaces", - data: { length }, - fix(fixer) { - if (pattern !== rawPattern) { - return null; - } - return fixer.replaceTextRange( - [rawPatternStartRange + index, rawPatternStartRange + index + length], - ` {${length}}` - ); - } - }); - - // Report only the first occurrence of consecutive spaces - return; - } - } - } - - /** - * Validate regular expression literals - * @param {ASTNode} node node to validate - * @returns {void} - * @private - */ - function checkLiteral(node) { - if (node.regex) { - const pattern = node.regex.pattern; - const rawPattern = node.raw.slice(1, node.raw.lastIndexOf("/")); - const rawPatternStartRange = node.range[0] + 1; - const flags = node.regex.flags; - - checkRegex( - node, - pattern, - rawPattern, - rawPatternStartRange, - flags - ); - } - } - - /** - * Validate strings passed to the RegExp constructor - * @param {ASTNode} node node to validate - * @returns {void} - * @private - */ - function checkFunction(node) { - const scope = context.getScope(); - const regExpVar = astUtils.getVariableByName(scope, "RegExp"); - const shadowed = regExpVar && regExpVar.defs.length > 0; - const patternNode = node.arguments[0]; - const flagsNode = node.arguments[1]; - - if (node.callee.type === "Identifier" && node.callee.name === "RegExp" && isString(patternNode) && !shadowed) { - const pattern = patternNode.value; - const rawPattern = patternNode.raw.slice(1, -1); - const rawPatternStartRange = patternNode.range[0] + 1; - const flags = isString(flagsNode) ? flagsNode.value : ""; - - checkRegex( - node, - pattern, - rawPattern, - rawPatternStartRange, - flags - ); - } - } - - return { - Literal: checkLiteral, - CallExpression: checkFunction, - NewExpression: checkFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-exports.js b/tools/node_modules/eslint/lib/rules/no-restricted-exports.js deleted file mode 100644 index 6031e26de2c7e873c1f0c14dd109d6351dc04e3b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-exports.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @fileoverview Rule to disallow specified names in exports - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified names in exports", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-exports" - }, - - schema: [{ - type: "object", - properties: { - restrictedNamedExports: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true - } - }, - additionalProperties: false - }], - - messages: { - restrictedNamed: "'{{name}}' is restricted from being used as an exported name." - } - }, - - create(context) { - - const restrictedNames = new Set(context.options[0] && context.options[0].restrictedNamedExports); - - /** - * Checks and reports given exported identifier. - * @param {ASTNode} node exported `Identifer` node to check. - * @returns {void} - */ - function checkExportedName(node) { - const name = node.name; - - if (restrictedNames.has(name)) { - context.report({ - node, - messageId: "restrictedNamed", - data: { name } - }); - } - } - - return { - ExportAllDeclaration(node) { - if (node.exported) { - checkExportedName(node.exported); - } - }, - - ExportNamedDeclaration(node) { - const declaration = node.declaration; - - if (declaration) { - if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") { - checkExportedName(declaration.id); - } else if (declaration.type === "VariableDeclaration") { - context.getDeclaredVariables(declaration) - .map(v => v.defs.find(d => d.parent === declaration)) - .map(d => d.name) // Identifier nodes - .forEach(checkExportedName); - } - } else { - node.specifiers - .map(s => s.exported) - .forEach(checkExportedName); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-globals.js b/tools/node_modules/eslint/lib/rules/no-restricted-globals.js deleted file mode 100644 index 2c932a7307c0b251a96e22c17cff781fca0ac319..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-globals.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Restrict usage of specified globals. - * @author Benoît Zugmeyer - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified global variables", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-globals" - }, - - schema: { - type: "array", - items: { - oneOf: [ - { - type: "string" - }, - { - type: "object", - properties: { - name: { type: "string" }, - message: { type: "string" } - }, - required: ["name"], - additionalProperties: false - } - ] - }, - uniqueItems: true, - minItems: 0 - }, - - messages: { - defaultMessage: "Unexpected use of '{{name}}'.", - // eslint-disable-next-line eslint-plugin/report-message-format - customMessage: "Unexpected use of '{{name}}'. {{customMessage}}" - } - }, - - create(context) { - - // If no globals are restricted, we don't need to do anything - if (context.options.length === 0) { - return {}; - } - - const restrictedGlobalMessages = context.options.reduce((memo, option) => { - if (typeof option === "string") { - memo[option] = null; - } else { - memo[option.name] = option.message; - } - - return memo; - }, {}); - - /** - * Report a variable to be used as a restricted global. - * @param {Reference} reference the variable reference - * @returns {void} - * @private - */ - function reportReference(reference) { - const name = reference.identifier.name, - customMessage = restrictedGlobalMessages[name], - messageId = customMessage - ? "customMessage" - : "defaultMessage"; - - context.report({ - node: reference.identifier, - messageId, - data: { - name, - customMessage - } - }); - } - - /** - * Check if the given name is a restricted global name. - * @param {string} name name of a variable - * @returns {boolean} whether the variable is a restricted global or not - * @private - */ - function isRestricted(name) { - return Object.prototype.hasOwnProperty.call(restrictedGlobalMessages, name); - } - - return { - Program() { - const scope = context.getScope(); - - // Report variables declared elsewhere (ex: variables defined as "global" by eslint) - scope.variables.forEach(variable => { - if (!variable.defs.length && isRestricted(variable.name)) { - variable.references.forEach(reportReference); - } - }); - - // Report variables not declared at all - scope.through.forEach(reference => { - if (isRestricted(reference.identifier.name)) { - reportReference(reference); - } - }); - - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-imports.js b/tools/node_modules/eslint/lib/rules/no-restricted-imports.js deleted file mode 100644 index c205dad8bdb79d83b18e832beeaa713c7f82f808..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-imports.js +++ /dev/null @@ -1,268 +0,0 @@ -/** - * @fileoverview Restrict usage of specified node imports. - * @author Guy Ellis - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const ignore = require("ignore"); - -const arrayOfStrings = { - type: "array", - items: { type: "string" }, - uniqueItems: true -}; - -const arrayOfStringsOrObjects = { - type: "array", - items: { - anyOf: [ - { type: "string" }, - { - type: "object", - properties: { - name: { type: "string" }, - message: { - type: "string", - minLength: 1 - }, - importNames: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false, - required: ["name"] - } - ] - }, - uniqueItems: true -}; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified modules when loaded by `import`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-imports" - }, - - messages: { - path: "'{{importSource}}' import is restricted from being used.", - // eslint-disable-next-line eslint-plugin/report-message-format - pathWithCustomMessage: "'{{importSource}}' import is restricted from being used. {{customMessage}}", - - patterns: "'{{importSource}}' import is restricted from being used by a pattern.", - - everything: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted.", - // eslint-disable-next-line eslint-plugin/report-message-format - everythingWithCustomMessage: "* import is invalid because '{{importNames}}' from '{{importSource}}' is restricted. {{customMessage}}", - - importName: "'{{importName}}' import from '{{importSource}}' is restricted.", - // eslint-disable-next-line eslint-plugin/report-message-format - importNameWithCustomMessage: "'{{importName}}' import from '{{importSource}}' is restricted. {{customMessage}}" - }, - - schema: { - anyOf: [ - arrayOfStringsOrObjects, - { - type: "array", - items: [{ - type: "object", - properties: { - paths: arrayOfStringsOrObjects, - patterns: arrayOfStrings - }, - additionalProperties: false - }], - additionalItems: false - } - ] - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = Array.isArray(context.options) ? context.options : []; - const isPathAndPatternsObject = - typeof options[0] === "object" && - (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); - - const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || []; - const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; - - // if no imports are restricted we don"t need to check - if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) { - return {}; - } - - const restrictedPathMessages = restrictedPaths.reduce((memo, importSource) => { - if (typeof importSource === "string") { - memo[importSource] = { message: null }; - } else { - memo[importSource.name] = { - message: importSource.message, - importNames: importSource.importNames - }; - } - return memo; - }, {}); - - const restrictedPatternsMatcher = ignore().add(restrictedPatterns); - - /** - * Report a restricted path. - * @param {string} importSource path of the import - * @param {Map} importNames Map of import names that are being imported - * @param {node} node representing the restricted path reference - * @returns {void} - * @private - */ - function checkRestrictedPathAndReport(importSource, importNames, node) { - if (!Object.prototype.hasOwnProperty.call(restrictedPathMessages, importSource)) { - return; - } - - const customMessage = restrictedPathMessages[importSource].message; - const restrictedImportNames = restrictedPathMessages[importSource].importNames; - - if (restrictedImportNames) { - if (importNames.has("*")) { - const specifierData = importNames.get("*")[0]; - - context.report({ - node, - messageId: customMessage ? "everythingWithCustomMessage" : "everything", - loc: specifierData.loc, - data: { - importSource, - importNames: restrictedImportNames, - customMessage - } - }); - } - - restrictedImportNames.forEach(importName => { - if (importNames.has(importName)) { - const specifiers = importNames.get(importName); - - specifiers.forEach(specifier => { - context.report({ - node, - messageId: customMessage ? "importNameWithCustomMessage" : "importName", - loc: specifier.loc, - data: { - importSource, - customMessage, - importName - } - }); - }); - } - }); - } else { - context.report({ - node, - messageId: customMessage ? "pathWithCustomMessage" : "path", - data: { - importSource, - customMessage - } - }); - } - } - - /** - * Report a restricted path specifically for patterns. - * @param {node} node representing the restricted path reference - * @returns {void} - * @private - */ - function reportPathForPatterns(node) { - const importSource = node.source.value.trim(); - - context.report({ - node, - messageId: "patterns", - data: { - importSource - } - }); - } - - /** - * Check if the given importSource is restricted by a pattern. - * @param {string} importSource path of the import - * @returns {boolean} whether the variable is a restricted pattern or not - * @private - */ - function isRestrictedPattern(importSource) { - return restrictedPatterns.length > 0 && restrictedPatternsMatcher.ignores(importSource); - } - - /** - * Checks a node to see if any problems should be reported. - * @param {ASTNode} node The node to check. - * @returns {void} - * @private - */ - function checkNode(node) { - const importSource = node.source.value.trim(); - const importNames = new Map(); - - if (node.type === "ExportAllDeclaration") { - const starToken = sourceCode.getFirstToken(node, 1); - - importNames.set("*", [{ loc: starToken.loc }]); - } else if (node.specifiers) { - for (const specifier of node.specifiers) { - let name; - const specifierData = { loc: specifier.loc }; - - if (specifier.type === "ImportDefaultSpecifier") { - name = "default"; - } else if (specifier.type === "ImportNamespaceSpecifier") { - name = "*"; - } else if (specifier.imported) { - name = specifier.imported.name; - } else if (specifier.local) { - name = specifier.local.name; - } - - if (name) { - if (importNames.has(name)) { - importNames.get(name).push(specifierData); - } else { - importNames.set(name, [specifierData]); - } - } - } - } - - checkRestrictedPathAndReport(importSource, importNames, node); - - if (isRestrictedPattern(importSource)) { - reportPathForPatterns(node); - } - } - - return { - ImportDeclaration: checkNode, - ExportNamedDeclaration(node) { - if (node.source) { - checkNode(node); - } - }, - ExportAllDeclaration: checkNode - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-modules.js b/tools/node_modules/eslint/lib/rules/no-restricted-modules.js deleted file mode 100644 index d0b8a78a507fa80930e83dcf6832db9d461c84a5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-modules.js +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @fileoverview Restrict usage of specified node modules. - * @author Christian Schulz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const ignore = require("ignore"); - -const arrayOfStrings = { - type: "array", - items: { type: "string" }, - uniqueItems: true -}; - -const arrayOfStringsOrObjects = { - type: "array", - items: { - anyOf: [ - { type: "string" }, - { - type: "object", - properties: { - name: { type: "string" }, - message: { - type: "string", - minLength: 1 - } - }, - additionalProperties: false, - required: ["name"] - } - ] - }, - uniqueItems: true -}; - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow specified modules when loaded by `require`", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-modules" - }, - - schema: { - anyOf: [ - arrayOfStringsOrObjects, - { - type: "array", - items: { - type: "object", - properties: { - paths: arrayOfStringsOrObjects, - patterns: arrayOfStrings - }, - additionalProperties: false - }, - additionalItems: false - } - ] - }, - - messages: { - defaultMessage: "'{{name}}' module is restricted from being used.", - // eslint-disable-next-line eslint-plugin/report-message-format - customMessage: "'{{name}}' module is restricted from being used. {{customMessage}}", - patternMessage: "'{{name}}' module is restricted from being used by a pattern." - } - }, - - create(context) { - const options = Array.isArray(context.options) ? context.options : []; - const isPathAndPatternsObject = - typeof options[0] === "object" && - (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); - - const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : context.options) || []; - const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; - - const restrictedPathMessages = restrictedPaths.reduce((memo, importName) => { - if (typeof importName === "string") { - memo[importName] = null; - } else { - memo[importName.name] = importName.message; - } - return memo; - }, {}); - - // if no imports are restricted we don"t need to check - if (Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0) { - return {}; - } - - const ig = ignore().add(restrictedPatterns); - - - /** - * Function to check if a node is a string literal. - * @param {ASTNode} node The node to check. - * @returns {boolean} If the node is a string literal. - */ - function isStringLiteral(node) { - return node && node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Function to check if a node is a static string template literal. - * @param {ASTNode} node The node to check. - * @returns {boolean} If the node is a string template literal. - */ - function isStaticTemplateLiteral(node) { - return node && node.type === "TemplateLiteral" && node.expressions.length === 0; - } - - /** - * Function to check if a node is a require call. - * @param {ASTNode} node The node to check. - * @returns {boolean} If the node is a require call. - */ - function isRequireCall(node) { - return node.callee.type === "Identifier" && node.callee.name === "require"; - } - - /** - * Extract string from Literal or TemplateLiteral node - * @param {ASTNode} node The node to extract from - * @returns {string|null} Extracted string or null if node doesn't represent a string - */ - function getFirstArgumentString(node) { - if (isStringLiteral(node)) { - return node.value.trim(); - } - - if (isStaticTemplateLiteral(node)) { - return node.quasis[0].value.cooked.trim(); - } - - return null; - } - - /** - * Report a restricted path. - * @param {node} node representing the restricted path reference - * @param {string} name restricted path - * @returns {void} - * @private - */ - function reportPath(node, name) { - const customMessage = restrictedPathMessages[name]; - const messageId = customMessage - ? "customMessage" - : "defaultMessage"; - - context.report({ - node, - messageId, - data: { - name, - customMessage - } - }); - } - - /** - * Check if the given name is a restricted path name - * @param {string} name name of a variable - * @returns {boolean} whether the variable is a restricted path or not - * @private - */ - function isRestrictedPath(name) { - return Object.prototype.hasOwnProperty.call(restrictedPathMessages, name); - } - - return { - CallExpression(node) { - if (isRequireCall(node)) { - - // node has arguments - if (node.arguments.length) { - const name = getFirstArgumentString(node.arguments[0]); - - // if first argument is a string literal or a static string template literal - if (name) { - - // check if argument value is in restricted modules array - if (isRestrictedPath(name)) { - reportPath(node, name); - } - - if (restrictedPatterns.length > 0 && ig.ignores(name)) { - context.report({ - node, - messageId: "patternMessage", - data: { name } - }); - } - } - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-properties.js b/tools/node_modules/eslint/lib/rules/no-restricted-properties.js deleted file mode 100644 index 7ab83995a3ebbfc0bcb26fbc1cdbb877d7bf75ba..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-properties.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * @fileoverview Rule to disallow certain object properties - * @author Will Klein & Eli White - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow certain properties on certain objects", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-properties" - }, - - schema: { - type: "array", - items: { - anyOf: [ // `object` and `property` are both optional, but at least one of them must be provided. - { - type: "object", - properties: { - object: { - type: "string" - }, - property: { - type: "string" - }, - message: { - type: "string" - } - }, - additionalProperties: false, - required: ["object"] - }, - { - type: "object", - properties: { - object: { - type: "string" - }, - property: { - type: "string" - }, - message: { - type: "string" - } - }, - additionalProperties: false, - required: ["property"] - } - ] - }, - uniqueItems: true - }, - - messages: { - // eslint-disable-next-line eslint-plugin/report-message-format - restrictedObjectProperty: "'{{objectName}}.{{propertyName}}' is restricted from being used.{{message}}", - // eslint-disable-next-line eslint-plugin/report-message-format - restrictedProperty: "'{{propertyName}}' is restricted from being used.{{message}}" - } - }, - - create(context) { - const restrictedCalls = context.options; - - if (restrictedCalls.length === 0) { - return {}; - } - - const restrictedProperties = new Map(); - const globallyRestrictedObjects = new Map(); - const globallyRestrictedProperties = new Map(); - - restrictedCalls.forEach(option => { - const objectName = option.object; - const propertyName = option.property; - - if (typeof objectName === "undefined") { - globallyRestrictedProperties.set(propertyName, { message: option.message }); - } else if (typeof propertyName === "undefined") { - globallyRestrictedObjects.set(objectName, { message: option.message }); - } else { - if (!restrictedProperties.has(objectName)) { - restrictedProperties.set(objectName, new Map()); - } - - restrictedProperties.get(objectName).set(propertyName, { - message: option.message - }); - } - }); - - /** - * Checks to see whether a property access is restricted, and reports it if so. - * @param {ASTNode} node The node to report - * @param {string} objectName The name of the object - * @param {string} propertyName The name of the property - * @returns {undefined} - */ - function checkPropertyAccess(node, objectName, propertyName) { - if (propertyName === null) { - return; - } - const matchedObject = restrictedProperties.get(objectName); - const matchedObjectProperty = matchedObject ? matchedObject.get(propertyName) : globallyRestrictedObjects.get(objectName); - const globalMatchedProperty = globallyRestrictedProperties.get(propertyName); - - if (matchedObjectProperty) { - const message = matchedObjectProperty.message ? ` ${matchedObjectProperty.message}` : ""; - - context.report({ - node, - messageId: "restrictedObjectProperty", - data: { - objectName, - propertyName, - message - } - }); - } else if (globalMatchedProperty) { - const message = globalMatchedProperty.message ? ` ${globalMatchedProperty.message}` : ""; - - context.report({ - node, - messageId: "restrictedProperty", - data: { - propertyName, - message - } - }); - } - } - - /** - * Checks property accesses in a destructuring assignment expression, e.g. `var foo; ({foo} = bar);` - * @param {ASTNode} node An AssignmentExpression or AssignmentPattern node - * @returns {undefined} - */ - function checkDestructuringAssignment(node) { - if (node.right.type === "Identifier") { - const objectName = node.right.name; - - if (node.left.type === "ObjectPattern") { - node.left.properties.forEach(property => { - checkPropertyAccess(node.left, objectName, astUtils.getStaticPropertyName(property)); - }); - } - } - } - - return { - MemberExpression(node) { - checkPropertyAccess(node, node.object && node.object.name, astUtils.getStaticPropertyName(node)); - }, - VariableDeclarator(node) { - if (node.init && node.init.type === "Identifier") { - const objectName = node.init.name; - - if (node.id.type === "ObjectPattern") { - node.id.properties.forEach(property => { - checkPropertyAccess(node.id, objectName, astUtils.getStaticPropertyName(property)); - }); - } - } - }, - AssignmentExpression: checkDestructuringAssignment, - AssignmentPattern: checkDestructuringAssignment - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-restricted-syntax.js b/tools/node_modules/eslint/lib/rules/no-restricted-syntax.js deleted file mode 100644 index 9572603a82485aa90e99267adbf20a3342667096..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-restricted-syntax.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @fileoverview Rule to flag use of certain node types - * @author Burak Yigit Kaya - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified syntax", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-restricted-syntax" - }, - - schema: { - type: "array", - items: { - oneOf: [ - { - type: "string" - }, - { - type: "object", - properties: { - selector: { type: "string" }, - message: { type: "string" } - }, - required: ["selector"], - additionalProperties: false - } - ] - }, - uniqueItems: true, - minItems: 0 - }, - - messages: { - // eslint-disable-next-line eslint-plugin/report-message-format - restrictedSyntax: "{{message}}" - } - }, - - create(context) { - return context.options.reduce((result, selectorOrObject) => { - const isStringFormat = (typeof selectorOrObject === "string"); - const hasCustomMessage = !isStringFormat && Boolean(selectorOrObject.message); - - const selector = isStringFormat ? selectorOrObject : selectorOrObject.selector; - const message = hasCustomMessage ? selectorOrObject.message : `Using '${selector}' is not allowed.`; - - return Object.assign(result, { - [selector](node) { - context.report({ - node, - messageId: "restrictedSyntax", - data: { message } - }); - } - }); - }, {}); - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-return-assign.js b/tools/node_modules/eslint/lib/rules/no-return-assign.js deleted file mode 100644 index 4b57d42eb9952bb828fcaaa364df7c12a262decc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-return-assign.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @fileoverview Rule to flag when return statement contains assignment - * @author Ilya Volodin - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_TYPE = /^(?:[a-zA-Z]+?Statement|ArrowFunctionExpression|FunctionExpression|ClassExpression)$/u; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow assignment operators in `return` statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-return-assign" - }, - - schema: [ - { - enum: ["except-parens", "always"] - } - ], - - messages: { - returnAssignment: "Return statement should not contain assignment.", - arrowAssignment: "Arrow function should not return assignment." - } - }, - - create(context) { - const always = (context.options[0] || "except-parens") !== "except-parens"; - const sourceCode = context.getSourceCode(); - - return { - AssignmentExpression(node) { - if (!always && astUtils.isParenthesised(sourceCode, node)) { - return; - } - - let currentChild = node; - let parent = currentChild.parent; - - // Find ReturnStatement or ArrowFunctionExpression in ancestors. - while (parent && !SENTINEL_TYPE.test(parent.type)) { - currentChild = parent; - parent = parent.parent; - } - - // Reports. - if (parent && parent.type === "ReturnStatement") { - context.report({ - node: parent, - messageId: "returnAssignment" - }); - } else if (parent && parent.type === "ArrowFunctionExpression" && parent.body === currentChild) { - context.report({ - node: parent, - messageId: "arrowAssignment" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-return-await.js b/tools/node_modules/eslint/lib/rules/no-return-await.js deleted file mode 100644 index d1d89826856dc48d93a6beed10ae5ef40df8d1b6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-return-await.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @fileoverview Disallows unnecessary `return await` - * @author Jordan Harband - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary `return await`", - category: "Best Practices", - - recommended: false, - - url: "https://eslint.org/docs/rules/no-return-await" - }, - - fixable: null, - - schema: [ - ], - - messages: { - redundantUseOfAwait: "Redundant use of `await` on a return value." - } - }, - - create(context) { - - /** - * Reports a found unnecessary `await` expression. - * @param {ASTNode} node The node representing the `await` expression to report - * @returns {void} - */ - function reportUnnecessaryAwait(node) { - context.report({ - node: context.getSourceCode().getFirstToken(node), - loc: node.loc, - messageId: "redundantUseOfAwait" - }); - } - - /** - * Determines whether a thrown error from this node will be caught/handled within this function rather than immediately halting - * this function. For example, a statement in a `try` block will always have an error handler. A statement in - * a `catch` block will only have an error handler if there is also a `finally` block. - * @param {ASTNode} node A node representing a location where an could be thrown - * @returns {boolean} `true` if a thrown error will be caught/handled in this function - */ - function hasErrorHandler(node) { - let ancestor = node; - - while (!astUtils.isFunction(ancestor) && ancestor.type !== "Program") { - if (ancestor.parent.type === "TryStatement" && (ancestor === ancestor.parent.block || ancestor === ancestor.parent.handler && ancestor.parent.finalizer)) { - return true; - } - ancestor = ancestor.parent; - } - return false; - } - - /** - * Checks if a node is placed in tail call position. Once `return` arguments (or arrow function expressions) can be a complex expression, - * an `await` expression could or could not be unnecessary by the definition of this rule. So we're looking for `await` expressions that are in tail position. - * @param {ASTNode} node A node representing the `await` expression to check - * @returns {boolean} The checking result - */ - function isInTailCallPosition(node) { - if (node.parent.type === "ArrowFunctionExpression") { - return true; - } - if (node.parent.type === "ReturnStatement") { - return !hasErrorHandler(node.parent); - } - if (node.parent.type === "ConditionalExpression" && (node === node.parent.consequent || node === node.parent.alternate)) { - return isInTailCallPosition(node.parent); - } - if (node.parent.type === "LogicalExpression" && node === node.parent.right) { - return isInTailCallPosition(node.parent); - } - if (node.parent.type === "SequenceExpression" && node === node.parent.expressions[node.parent.expressions.length - 1]) { - return isInTailCallPosition(node.parent); - } - return false; - } - - return { - AwaitExpression(node) { - if (isInTailCallPosition(node) && !hasErrorHandler(node)) { - reportUnnecessaryAwait(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-script-url.js b/tools/node_modules/eslint/lib/rules/no-script-url.js deleted file mode 100644 index 2078fc1dcea122a685562c4140c2ca25e7f18e4c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-script-url.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @fileoverview Rule to flag when using javascript: urls - * @author Ilya Volodin - */ -/* jshint scripturl: true */ -/* eslint no-script-url: 0 */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `javascript:` urls", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-script-url" - }, - - schema: [], - - messages: { - unexpectedScriptURL: "Script URL is a form of eval." - } - }, - - create(context) { - - return { - - Literal(node) { - if (node.value && typeof node.value === "string") { - const value = node.value.toLowerCase(); - - if (value.indexOf("javascript:") === 0) { - context.report({ node, messageId: "unexpectedScriptURL" }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-self-assign.js b/tools/node_modules/eslint/lib/rules/no-self-assign.js deleted file mode 100644 index 705be324cf0944967eea6d0b16f72b3468a65d57..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-self-assign.js +++ /dev/null @@ -1,183 +0,0 @@ -/** - * @fileoverview Rule to disallow assignments where both sides are exactly the same - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SPACES = /\s+/gu; - -/** - * Traverses 2 Pattern nodes in parallel, then reports self-assignments. - * @param {ASTNode|null} left A left node to traverse. This is a Pattern or - * a Property. - * @param {ASTNode|null} right A right node to traverse. This is a Pattern or - * a Property. - * @param {boolean} props The flag to check member expressions as well. - * @param {Function} report A callback function to report. - * @returns {void} - */ -function eachSelfAssignment(left, right, props, report) { - if (!left || !right) { - - // do nothing - } else if ( - left.type === "Identifier" && - right.type === "Identifier" && - left.name === right.name - ) { - report(right); - } else if ( - left.type === "ArrayPattern" && - right.type === "ArrayExpression" - ) { - const end = Math.min(left.elements.length, right.elements.length); - - for (let i = 0; i < end; ++i) { - const leftElement = left.elements[i]; - const rightElement = right.elements[i]; - - // Avoid cases such as [...a] = [...a, 1] - if ( - leftElement && - leftElement.type === "RestElement" && - i < right.elements.length - 1 - ) { - break; - } - - eachSelfAssignment(leftElement, rightElement, props, report); - - // After a spread element, those indices are unknown. - if (rightElement && rightElement.type === "SpreadElement") { - break; - } - } - } else if ( - left.type === "RestElement" && - right.type === "SpreadElement" - ) { - eachSelfAssignment(left.argument, right.argument, props, report); - } else if ( - left.type === "ObjectPattern" && - right.type === "ObjectExpression" && - right.properties.length >= 1 - ) { - - /* - * Gets the index of the last spread property. - * It's possible to overwrite properties followed by it. - */ - let startJ = 0; - - for (let i = right.properties.length - 1; i >= 0; --i) { - const propType = right.properties[i].type; - - if (propType === "SpreadElement" || propType === "ExperimentalSpreadProperty") { - startJ = i + 1; - break; - } - } - - for (let i = 0; i < left.properties.length; ++i) { - for (let j = startJ; j < right.properties.length; ++j) { - eachSelfAssignment( - left.properties[i], - right.properties[j], - props, - report - ); - } - } - } else if ( - left.type === "Property" && - right.type === "Property" && - right.kind === "init" && - !right.method - ) { - const leftName = astUtils.getStaticPropertyName(left); - - if (leftName !== null && leftName === astUtils.getStaticPropertyName(right)) { - eachSelfAssignment(left.value, right.value, props, report); - } - } else if ( - props && - astUtils.skipChainExpression(left).type === "MemberExpression" && - astUtils.skipChainExpression(right).type === "MemberExpression" && - astUtils.isSameReference(left, right) - ) { - report(right); - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assignments where both sides are exactly the same", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-self-assign" - }, - - schema: [ - { - type: "object", - properties: { - props: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - selfAssignment: "'{{name}}' is assigned to itself." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const [{ props = true } = {}] = context.options; - - /** - * Reports a given node as self assignments. - * @param {ASTNode} node A node to report. This is an Identifier node. - * @returns {void} - */ - function report(node) { - context.report({ - node, - messageId: "selfAssignment", - data: { - name: sourceCode.getText(node).replace(SPACES, "") - } - }); - } - - return { - AssignmentExpression(node) { - if (node.operator === "=") { - eachSelfAssignment(node.left, node.right, props, report); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-self-compare.js b/tools/node_modules/eslint/lib/rules/no-self-compare.js deleted file mode 100644 index 79b6ac7ea0f28d3176b77ba7a0f5799c79951dc5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-self-compare.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * @fileoverview Rule to flag comparison where left part is the same as the right - * part. - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow comparisons where both sides are exactly the same", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-self-compare" - }, - - schema: [], - - messages: { - comparingToSelf: "Comparing to itself is potentially pointless." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Determines whether two nodes are composed of the same tokens. - * @param {ASTNode} nodeA The first node - * @param {ASTNode} nodeB The second node - * @returns {boolean} true if the nodes have identical token representations - */ - function hasSameTokens(nodeA, nodeB) { - const tokensA = sourceCode.getTokens(nodeA); - const tokensB = sourceCode.getTokens(nodeB); - - return tokensA.length === tokensB.length && - tokensA.every((token, index) => token.type === tokensB[index].type && token.value === tokensB[index].value); - } - - return { - - BinaryExpression(node) { - const operators = new Set(["===", "==", "!==", "!=", ">", "<", ">=", "<="]); - - if (operators.has(node.operator) && hasSameTokens(node.left, node.right)) { - context.report({ node, messageId: "comparingToSelf" }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-sequences.js b/tools/node_modules/eslint/lib/rules/no-sequences.js deleted file mode 100644 index d67635d117549eae28b0f669a9a29c5797e901d7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-sequences.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * @fileoverview Rule to flag use of comma operator - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow comma operators", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-sequences" - }, - - schema: [], - - messages: { - unexpectedCommaExpression: "Unexpected use of comma operator." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Parts of the grammar that are required to have parens. - */ - const parenthesized = { - DoWhileStatement: "test", - IfStatement: "test", - SwitchStatement: "discriminant", - WhileStatement: "test", - WithStatement: "object", - ArrowFunctionExpression: "body" - - /* - * Omitting CallExpression - commas are parsed as argument separators - * Omitting NewExpression - commas are parsed as argument separators - * Omitting ForInStatement - parts aren't individually parenthesised - * Omitting ForStatement - parts aren't individually parenthesised - */ - }; - - /** - * Determines whether a node is required by the grammar to be wrapped in - * parens, e.g. the test of an if statement. - * @param {ASTNode} node The AST node - * @returns {boolean} True if parens around node belong to parent node. - */ - function requiresExtraParens(node) { - return node.parent && parenthesized[node.parent.type] && - node === node.parent[parenthesized[node.parent.type]]; - } - - /** - * Check if a node is wrapped in parens. - * @param {ASTNode} node The AST node - * @returns {boolean} True if the node has a paren on each side. - */ - function isParenthesised(node) { - return astUtils.isParenthesised(sourceCode, node); - } - - /** - * Check if a node is wrapped in two levels of parens. - * @param {ASTNode} node The AST node - * @returns {boolean} True if two parens surround the node on each side. - */ - function isParenthesisedTwice(node) { - const previousToken = sourceCode.getTokenBefore(node, 1), - nextToken = sourceCode.getTokenAfter(node, 1); - - return isParenthesised(node) && previousToken && nextToken && - astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] && - astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1]; - } - - return { - SequenceExpression(node) { - - // Always allow sequences in for statement update - if (node.parent.type === "ForStatement" && - (node === node.parent.init || node === node.parent.update)) { - return; - } - - // Wrapping a sequence in extra parens indicates intent - if (requiresExtraParens(node)) { - if (isParenthesisedTwice(node)) { - return; - } - } else { - if (isParenthesised(node)) { - return; - } - } - - const firstCommaToken = sourceCode.getTokenAfter(node.expressions[0], astUtils.isCommaToken); - - context.report({ node, loc: firstCommaToken.loc, messageId: "unexpectedCommaExpression" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-setter-return.js b/tools/node_modules/eslint/lib/rules/no-setter-return.js deleted file mode 100644 index 9c79240dda1fa8f2cf962f79be6737cbf2103a44..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-setter-return.js +++ /dev/null @@ -1,224 +0,0 @@ -/** - * @fileoverview Rule to disallow returning values from setters - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const { findVariable } = require("eslint-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines whether the given identifier node is a reference to a global variable. - * @param {ASTNode} node `Identifier` node to check. - * @param {Scope} scope Scope to which the node belongs. - * @returns {boolean} True if the identifier is a reference to a global variable. - */ -function isGlobalReference(node, scope) { - const variable = findVariable(scope, node); - - return variable !== null && variable.scope.type === "global" && variable.defs.length === 0; -} - -/** - * Determines whether the given node is an argument of the specified global method call, at the given `index` position. - * E.g., for given `index === 1`, this function checks for `objectName.methodName(foo, node)`, where objectName is a global variable. - * @param {ASTNode} node The node to check. - * @param {Scope} scope Scope to which the node belongs. - * @param {string} objectName Name of the global object. - * @param {string} methodName Name of the method. - * @param {number} index The given position. - * @returns {boolean} `true` if the node is argument at the given position. - */ -function isArgumentOfGlobalMethodCall(node, scope, objectName, methodName, index) { - const callNode = node.parent; - - return callNode.type === "CallExpression" && - callNode.arguments[index] === node && - astUtils.isSpecificMemberAccess(callNode.callee, objectName, methodName) && - isGlobalReference(astUtils.skipChainExpression(callNode.callee).object, scope); -} - -/** - * Determines whether the given node is used as a property descriptor. - * @param {ASTNode} node The node to check. - * @param {Scope} scope Scope to which the node belongs. - * @returns {boolean} `true` if the node is a property descriptor. - */ -function isPropertyDescriptor(node, scope) { - if ( - isArgumentOfGlobalMethodCall(node, scope, "Object", "defineProperty", 2) || - isArgumentOfGlobalMethodCall(node, scope, "Reflect", "defineProperty", 2) - ) { - return true; - } - - const parent = node.parent; - - if ( - parent.type === "Property" && - parent.value === node - ) { - const grandparent = parent.parent; - - if ( - grandparent.type === "ObjectExpression" && - ( - isArgumentOfGlobalMethodCall(grandparent, scope, "Object", "create", 1) || - isArgumentOfGlobalMethodCall(grandparent, scope, "Object", "defineProperties", 1) - ) - ) { - return true; - } - } - - return false; -} - -/** - * Determines whether the given function node is used as a setter function. - * @param {ASTNode} node The node to check. - * @param {Scope} scope Scope to which the node belongs. - * @returns {boolean} `true` if the node is a setter. - */ -function isSetter(node, scope) { - const parent = node.parent; - - if ( - parent.kind === "set" && - parent.value === node - ) { - - // Setter in an object literal or in a class - return true; - } - - if ( - parent.type === "Property" && - parent.value === node && - astUtils.getStaticPropertyName(parent) === "set" && - parent.parent.type === "ObjectExpression" && - isPropertyDescriptor(parent.parent, scope) - ) { - - // Setter in a property descriptor - return true; - } - - return false; -} - -/** - * Finds function's outer scope. - * @param {Scope} scope Function's own scope. - * @returns {Scope} Function's outer scope. - */ -function getOuterScope(scope) { - const upper = scope.upper; - - if (upper.type === "function-expression-name") { - return upper.upper; - } - - return upper; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow returning values from setters", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-setter-return" - }, - - schema: [], - - messages: { - returnsValue: "Setter cannot return a value." - } - }, - - create(context) { - let funcInfo = null; - - /** - * Creates and pushes to the stack a function info object for the given function node. - * @param {ASTNode} node The function node. - * @returns {void} - */ - function enterFunction(node) { - const outerScope = getOuterScope(context.getScope()); - - funcInfo = { - upper: funcInfo, - isSetter: isSetter(node, outerScope) - }; - } - - /** - * Pops the current function info object from the stack. - * @returns {void} - */ - function exitFunction() { - funcInfo = funcInfo.upper; - } - - /** - * Reports the given node. - * @param {ASTNode} node Node to report. - * @returns {void} - */ - function report(node) { - context.report({ node, messageId: "returnsValue" }); - } - - return { - - /* - * Function declarations cannot be setters, but we still have to track them in the `funcInfo` stack to avoid - * false positives, because a ReturnStatement node can belong to a function declaration inside a setter. - * - * Note: A previously declared function can be referenced and actually used as a setter in a property descriptor, - * but that's out of scope for this rule. - */ - FunctionDeclaration: enterFunction, - FunctionExpression: enterFunction, - ArrowFunctionExpression(node) { - enterFunction(node); - - if (funcInfo.isSetter && node.expression) { - - // { set: foo => bar } property descriptor. Report implicit return 'bar' as the equivalent for a return statement. - report(node.body); - } - }, - - "FunctionDeclaration:exit": exitFunction, - "FunctionExpression:exit": exitFunction, - "ArrowFunctionExpression:exit": exitFunction, - - ReturnStatement(node) { - - // Global returns (e.g., at the top level of a Node module) don't have `funcInfo`. - if (funcInfo && funcInfo.isSetter && node.argument) { - report(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js b/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js deleted file mode 100644 index 9647e9a1bcdd9eca5908c8c6d0cce75546143c99..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-shadow-restricted-names.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Disallow shadowing of NaN, undefined, and Infinity (ES5 section 15.1.1) - * @author Michael Ficarra - */ -"use strict"; - -/** - * Determines if a variable safely shadows undefined. - * This is the case when a variable named `undefined` is never assigned to a value (i.e. it always shares the same value - * as the global). - * @param {eslintScope.Variable} variable The variable to check - * @returns {boolean} true if this variable safely shadows `undefined` - */ -function safelyShadowsUndefined(variable) { - return variable.name === "undefined" && - variable.references.every(ref => !ref.isWrite()) && - variable.defs.every(def => def.node.type === "VariableDeclarator" && def.node.init === null); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow identifiers from shadowing restricted names", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-shadow-restricted-names" - }, - - schema: [], - - messages: { - shadowingRestrictedName: "Shadowing of global property '{{name}}'." - } - }, - - create(context) { - - - const RESTRICTED = new Set(["undefined", "NaN", "Infinity", "arguments", "eval"]); - - return { - "VariableDeclaration, :function, CatchClause"(node) { - for (const variable of context.getDeclaredVariables(node)) { - if (variable.defs.length > 0 && RESTRICTED.has(variable.name) && !safelyShadowsUndefined(variable)) { - context.report({ - node: variable.defs[0].name, - messageId: "shadowingRestrictedName", - data: { - name: variable.name - } - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-shadow.js b/tools/node_modules/eslint/lib/rules/no-shadow.js deleted file mode 100644 index 1be8590e47abcb34ccb502a6eaca1841811e22fc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-shadow.js +++ /dev/null @@ -1,192 +0,0 @@ -/** - * @fileoverview Rule to flag on declaring variables already declared in the outer scope - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow variable declarations from shadowing variables declared in the outer scope", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-shadow" - }, - - schema: [ - { - type: "object", - properties: { - builtinGlobals: { type: "boolean", default: false }, - hoist: { enum: ["all", "functions", "never"], default: "functions" }, - allow: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - } - ], - - messages: { - noShadow: "'{{name}}' is already declared in the upper scope." - } - }, - - create(context) { - - const options = { - builtinGlobals: context.options[0] && context.options[0].builtinGlobals, - hoist: (context.options[0] && context.options[0].hoist) || "functions", - allow: (context.options[0] && context.options[0].allow) || [] - }; - - /** - * Check if variable name is allowed. - * @param {ASTNode} variable The variable to check. - * @returns {boolean} Whether or not the variable name is allowed. - */ - function isAllowed(variable) { - return options.allow.indexOf(variable.name) !== -1; - } - - /** - * Checks if a variable of the class name in the class scope of ClassDeclaration. - * - * ClassDeclaration creates two variables of its name into its outer scope and its class scope. - * So we should ignore the variable in the class scope. - * @param {Object} variable The variable to check. - * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration. - */ - function isDuplicatedClassNameVariable(variable) { - const block = variable.scope.block; - - return block.type === "ClassDeclaration" && block.id === variable.identifiers[0]; - } - - /** - * Checks if a variable is inside the initializer of scopeVar. - * - * To avoid reporting at declarations such as `var a = function a() {};`. - * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. - * @param {Object} variable The variable to check. - * @param {Object} scopeVar The scope variable to look for. - * @returns {boolean} Whether or not the variable is inside initializer of scopeVar. - */ - function isOnInitializer(variable, scopeVar) { - const outerScope = scopeVar.scope; - const outerDef = scopeVar.defs[0]; - const outer = outerDef && outerDef.parent && outerDef.parent.range; - const innerScope = variable.scope; - const innerDef = variable.defs[0]; - const inner = innerDef && innerDef.name.range; - - return ( - outer && - inner && - outer[0] < inner[0] && - inner[1] < outer[1] && - ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") && - outerScope === innerScope.upper - ); - } - - /** - * Get a range of a variable's identifier node. - * @param {Object} variable The variable to get. - * @returns {Array|undefined} The range of the variable's identifier node. - */ - function getNameRange(variable) { - const def = variable.defs[0]; - - return def && def.name.range; - } - - /** - * Checks if a variable is in TDZ of scopeVar. - * @param {Object} variable The variable to check. - * @param {Object} scopeVar The variable of TDZ. - * @returns {boolean} Whether or not the variable is in TDZ of scopeVar. - */ - function isInTdz(variable, scopeVar) { - const outerDef = scopeVar.defs[0]; - const inner = getNameRange(variable); - const outer = getNameRange(scopeVar); - - return ( - inner && - outer && - inner[1] < outer[0] && - - // Excepts FunctionDeclaration if is {"hoist":"function"}. - (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration") - ); - } - - /** - * Checks the current context for shadowed variables. - * @param {Scope} scope Fixme - * @returns {void} - */ - function checkForShadows(scope) { - const variables = scope.variables; - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration. - if (variable.identifiers.length === 0 || - isDuplicatedClassNameVariable(variable) || - isAllowed(variable) - ) { - continue; - } - - // Gets shadowed variable. - const shadowed = astUtils.getVariableByName(scope.upper, variable.name); - - if (shadowed && - (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) && - !isOnInitializer(variable, shadowed) && - !(options.hoist !== "all" && isInTdz(variable, shadowed)) - ) { - context.report({ - node: variable.identifiers[0], - messageId: "noShadow", - data: variable - }); - } - } - } - - return { - "Program:exit"() { - const globalScope = context.getScope(); - const stack = globalScope.childScopes.slice(); - - while (stack.length) { - const scope = stack.pop(); - - stack.push(...scope.childScopes); - checkForShadows(scope); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-spaced-func.js b/tools/node_modules/eslint/lib/rules/no-spaced-func.js deleted file mode 100644 index 961bc681f7eac50bfe816d7d9295982f74a26555..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-spaced-func.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * @fileoverview Rule to check that spaced function application - * @author Matt DuVall - * @deprecated in ESLint v3.3.0 - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow spacing between function identifiers and their applications (deprecated)", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-spaced-func" - }, - - deprecated: true, - - replacedBy: ["func-call-spacing"], - - fixable: "whitespace", - schema: [], - - messages: { - noSpacedFunction: "Unexpected space between function name and paren." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - /** - * Check if open space is present in a function name - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function detectOpenSpaces(node) { - const lastCalleeToken = sourceCode.getLastToken(node.callee); - let prevToken = lastCalleeToken, - parenToken = sourceCode.getTokenAfter(lastCalleeToken); - - // advances to an open parenthesis. - while ( - parenToken && - parenToken.range[1] < node.range[1] && - parenToken.value !== "(" - ) { - prevToken = parenToken; - parenToken = sourceCode.getTokenAfter(parenToken); - } - - // look for a space between the callee and the open paren - if (parenToken && - parenToken.range[1] < node.range[1] && - sourceCode.isSpaceBetweenTokens(prevToken, parenToken) - ) { - context.report({ - node, - loc: lastCalleeToken.loc.start, - messageId: "noSpacedFunction", - fix(fixer) { - return fixer.removeRange([prevToken.range[1], parenToken.range[0]]); - } - }); - } - } - - return { - CallExpression: detectOpenSpaces, - NewExpression: detectOpenSpaces - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-sparse-arrays.js b/tools/node_modules/eslint/lib/rules/no-sparse-arrays.js deleted file mode 100644 index e8407c3faede2d5a1983ea9ff011e3752701d5b7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-sparse-arrays.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @fileoverview Disallow sparse arrays - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow sparse arrays", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-sparse-arrays" - }, - - schema: [], - - messages: { - unexpectedSparseArray: "Unexpected comma in middle of array." - } - }, - - create(context) { - - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - ArrayExpression(node) { - - const emptySpot = node.elements.indexOf(null) > -1; - - if (emptySpot) { - context.report({ node, messageId: "unexpectedSparseArray" }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-sync.js b/tools/node_modules/eslint/lib/rules/no-sync.js deleted file mode 100644 index 06424e0b38f33fb39e993d253b405f0d53707355..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-sync.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @fileoverview Rule to check for properties whose identifier ends with the string Sync - * @author Matt DuVall - */ - -/* jshint node:true */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - deprecated: true, - - replacedBy: [], - - type: "suggestion", - - docs: { - description: "disallow synchronous methods", - category: "Node.js and CommonJS", - recommended: false, - url: "https://eslint.org/docs/rules/no-sync" - }, - - schema: [ - { - type: "object", - properties: { - allowAtRootLevel: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - noSync: "Unexpected sync method: '{{propertyName}}'." - } - }, - - create(context) { - const selector = context.options[0] && context.options[0].allowAtRootLevel - ? ":function MemberExpression[property.name=/.*Sync$/]" - : "MemberExpression[property.name=/.*Sync$/]"; - - return { - [selector](node) { - context.report({ - node, - messageId: "noSync", - data: { - propertyName: node.property.name - } - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-tabs.js b/tools/node_modules/eslint/lib/rules/no-tabs.js deleted file mode 100644 index ca7be261653c028eafdf62e0b9e3ec397b28e7cc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-tabs.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @fileoverview Rule to check for tabs inside a file - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const tabRegex = /\t+/gu; -const anyNonWhitespaceRegex = /\S/u; - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow all tabs", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-tabs" - }, - schema: [{ - type: "object", - properties: { - allowIndentationTabs: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - - messages: { - unexpectedTab: "Unexpected tab character." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const allowIndentationTabs = context.options && context.options[0] && context.options[0].allowIndentationTabs; - - return { - Program(node) { - sourceCode.getLines().forEach((line, index) => { - let match; - - while ((match = tabRegex.exec(line)) !== null) { - if (allowIndentationTabs && !anyNonWhitespaceRegex.test(line.slice(0, match.index))) { - continue; - } - - context.report({ - node, - loc: { - start: { - line: index + 1, - column: match.index - }, - end: { - line: index + 1, - column: match.index + match[0].length - } - }, - messageId: "unexpectedTab" - }); - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-template-curly-in-string.js b/tools/node_modules/eslint/lib/rules/no-template-curly-in-string.js deleted file mode 100644 index 539cd5be5ff9c537470c0946c09d676c6e63a51f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-template-curly-in-string.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * @fileoverview Warn when using template string syntax in regular strings - * @author Jeroen Engels - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow template literal placeholder syntax in regular strings", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-template-curly-in-string" - }, - - schema: [], - - messages: { - unexpectedTemplateExpression: "Unexpected template string expression." - } - }, - - create(context) { - const regex = /\$\{[^}]+\}/u; - - return { - Literal(node) { - if (typeof node.value === "string" && regex.test(node.value)) { - context.report({ - node, - messageId: "unexpectedTemplateExpression" - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-ternary.js b/tools/node_modules/eslint/lib/rules/no-ternary.js deleted file mode 100644 index b3ced86056614c6be7a8f0e85971dc8a69bea752..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-ternary.js +++ /dev/null @@ -1,41 +0,0 @@ -/** - * @fileoverview Rule to flag use of ternary operators. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow ternary operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-ternary" - }, - - schema: [], - - messages: { - noTernaryOperator: "Ternary operator used." - } - }, - - create(context) { - - return { - - ConditionalExpression(node) { - context.report({ node, messageId: "noTernaryOperator" }); - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-this-before-super.js b/tools/node_modules/eslint/lib/rules/no-this-before-super.js deleted file mode 100644 index 44288c0c97136e5e5ac3670243ade099b764ad6f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-this-before-super.js +++ /dev/null @@ -1,304 +0,0 @@ -/** - * @fileoverview A rule to disallow using `this`/`super` before `super()`. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a constructor. - * @param {ASTNode} node A node to check. This node type is one of - * `Program`, `FunctionDeclaration`, `FunctionExpression`, and - * `ArrowFunctionExpression`. - * @returns {boolean} `true` if the node is a constructor. - */ -function isConstructorFunction(node) { - return ( - node.type === "FunctionExpression" && - node.parent.type === "MethodDefinition" && - node.parent.kind === "constructor" - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow `this`/`super` before calling `super()` in constructors", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/no-this-before-super" - }, - - schema: [], - - messages: { - noBeforeSuper: "'{{kind}}' is not allowed before 'super()'." - } - }, - - create(context) { - - /* - * Information for each constructor. - * - upper: Information of the upper constructor. - * - hasExtends: A flag which shows whether the owner class has a valid - * `extends` part. - * - scope: The scope of the owner class. - * - codePath: The code path of this constructor. - */ - let funcInfo = null; - - /* - * Information for each code path segment. - * Each key is the id of a code path segment. - * Each value is an object: - * - superCalled: The flag which shows `super()` called in all code paths. - * - invalidNodes: The array of invalid ThisExpression and Super nodes. - */ - let segInfoMap = Object.create(null); - - /** - * Gets whether or not `super()` is called in a given code path segment. - * @param {CodePathSegment} segment A code path segment to get. - * @returns {boolean} `true` if `super()` is called. - */ - function isCalled(segment) { - return !segment.reachable || segInfoMap[segment.id].superCalled; - } - - /** - * Checks whether or not this is in a constructor. - * @returns {boolean} `true` if this is in a constructor. - */ - function isInConstructorOfDerivedClass() { - return Boolean(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends); - } - - /** - * Checks whether or not this is before `super()` is called. - * @returns {boolean} `true` if this is before `super()` is called. - */ - function isBeforeCallOfSuper() { - return ( - isInConstructorOfDerivedClass() && - !funcInfo.codePath.currentSegments.every(isCalled) - ); - } - - /** - * Sets a given node as invalid. - * @param {ASTNode} node A node to set as invalid. This is one of - * a ThisExpression and a Super. - * @returns {void} - */ - function setInvalid(node) { - const segments = funcInfo.codePath.currentSegments; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - segInfoMap[segment.id].invalidNodes.push(node); - } - } - } - - /** - * Sets the current segment as `super` was called. - * @returns {void} - */ - function setSuperCalled() { - const segments = funcInfo.codePath.currentSegments; - - for (let i = 0; i < segments.length; ++i) { - const segment = segments[i]; - - if (segment.reachable) { - segInfoMap[segment.id].superCalled = true; - } - } - } - - return { - - /** - * Adds information of a constructor into the stack. - * @param {CodePath} codePath A code path which was started. - * @param {ASTNode} node The current node. - * @returns {void} - */ - onCodePathStart(codePath, node) { - if (isConstructorFunction(node)) { - - // Class > ClassBody > MethodDefinition > FunctionExpression - const classNode = node.parent.parent.parent; - - funcInfo = { - upper: funcInfo, - isConstructor: true, - hasExtends: Boolean( - classNode.superClass && - !astUtils.isNullOrUndefined(classNode.superClass) - ), - codePath - }; - } else { - funcInfo = { - upper: funcInfo, - isConstructor: false, - hasExtends: false, - codePath - }; - } - }, - - /** - * Removes the top of stack item. - * - * And this treverses all segments of this code path then reports every - * invalid node. - * @param {CodePath} codePath A code path which was ended. - * @returns {void} - */ - onCodePathEnd(codePath) { - const isDerivedClass = funcInfo.hasExtends; - - funcInfo = funcInfo.upper; - if (!isDerivedClass) { - return; - } - - codePath.traverseSegments((segment, controller) => { - const info = segInfoMap[segment.id]; - - for (let i = 0; i < info.invalidNodes.length; ++i) { - const invalidNode = info.invalidNodes[i]; - - context.report({ - messageId: "noBeforeSuper", - node: invalidNode, - data: { - kind: invalidNode.type === "Super" ? "super" : "this" - } - }); - } - - if (info.superCalled) { - controller.skip(); - } - }); - }, - - /** - * Initialize information of a given code path segment. - * @param {CodePathSegment} segment A code path segment to initialize. - * @returns {void} - */ - onCodePathSegmentStart(segment) { - if (!isInConstructorOfDerivedClass()) { - return; - } - - // Initialize info. - segInfoMap[segment.id] = { - superCalled: ( - segment.prevSegments.length > 0 && - segment.prevSegments.every(isCalled) - ), - invalidNodes: [] - }; - }, - - /** - * Update information of the code path segment when a code path was - * looped. - * @param {CodePathSegment} fromSegment The code path segment of the - * end of a loop. - * @param {CodePathSegment} toSegment A code path segment of the head - * of a loop. - * @returns {void} - */ - onCodePathSegmentLoop(fromSegment, toSegment) { - if (!isInConstructorOfDerivedClass()) { - return; - } - - // Update information inside of the loop. - funcInfo.codePath.traverseSegments( - { first: toSegment, last: fromSegment }, - (segment, controller) => { - const info = segInfoMap[segment.id]; - - if (info.superCalled) { - info.invalidNodes = []; - controller.skip(); - } else if ( - segment.prevSegments.length > 0 && - segment.prevSegments.every(isCalled) - ) { - info.superCalled = true; - info.invalidNodes = []; - } - } - ); - }, - - /** - * Reports if this is before `super()`. - * @param {ASTNode} node A target node. - * @returns {void} - */ - ThisExpression(node) { - if (isBeforeCallOfSuper()) { - setInvalid(node); - } - }, - - /** - * Reports if this is before `super()`. - * @param {ASTNode} node A target node. - * @returns {void} - */ - Super(node) { - if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) { - setInvalid(node); - } - }, - - /** - * Marks `super()` called. - * @param {ASTNode} node A target node. - * @returns {void} - */ - "CallExpression:exit"(node) { - if (node.callee.type === "Super" && isBeforeCallOfSuper()) { - setSuperCalled(); - } - }, - - /** - * Resets state. - * @returns {void} - */ - "Program:exit"() { - segInfoMap = Object.create(null); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-throw-literal.js b/tools/node_modules/eslint/lib/rules/no-throw-literal.js deleted file mode 100644 index 29fb3718b4896bc436baf08476b277cae0eefca0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-throw-literal.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @fileoverview Rule to restrict what can be thrown as an exception. - * @author Dieter Oberkofler - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow throwing literals as exceptions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-throw-literal" - }, - - schema: [], - - messages: { - object: "Expected an error object to be thrown.", - undef: "Do not throw undefined." - } - }, - - create(context) { - - return { - - ThrowStatement(node) { - if (!astUtils.couldBeError(node.argument)) { - context.report({ node, messageId: "object" }); - } else if (node.argument.type === "Identifier") { - if (node.argument.name === "undefined") { - context.report({ node, messageId: "undef" }); - } - } - - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js b/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js deleted file mode 100644 index 98ae62c896359ce28fcc1b7ac4e015365fe09b98..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-trailing-spaces.js +++ /dev/null @@ -1,190 +0,0 @@ -/** - * @fileoverview Disallow trailing spaces at the end of lines. - * @author Nodeca Team - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow trailing whitespace at the end of lines", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-trailing-spaces" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - skipBlankLines: { - type: "boolean", - default: false - }, - ignoreComments: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - trailingSpace: "Trailing spaces not allowed." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]", - SKIP_BLANK = `^${BLANK_CLASS}*$`, - NONBLANK = `${BLANK_CLASS}+$`; - - const options = context.options[0] || {}, - skipBlankLines = options.skipBlankLines || false, - ignoreComments = options.ignoreComments || false; - - /** - * Report the error message - * @param {ASTNode} node node to report - * @param {int[]} location range information - * @param {int[]} fixRange Range based on the whole program - * @returns {void} - */ - function report(node, location, fixRange) { - - /* - * Passing node is a bit dirty, because message data will contain big - * text in `source`. But... who cares :) ? - * One more kludge will not make worse the bloody wizardry of this - * plugin. - */ - context.report({ - node, - loc: location, - messageId: "trailingSpace", - fix(fixer) { - return fixer.removeRange(fixRange); - } - }); - } - - /** - * Given a list of comment nodes, return the line numbers for those comments. - * @param {Array} comments An array of comment nodes. - * @returns {number[]} An array of line numbers containing comments. - */ - function getCommentLineNumbers(comments) { - const lines = new Set(); - - comments.forEach(comment => { - const endLine = comment.type === "Block" - ? comment.loc.end.line - 1 - : comment.loc.end.line; - - for (let i = comment.loc.start.line; i <= endLine; i++) { - lines.add(i); - } - }); - - return lines; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - Program: function checkTrailingSpaces(node) { - - /* - * Let's hack. Since Espree does not return whitespace nodes, - * fetch the source code and do matching via regexps. - */ - - const re = new RegExp(NONBLANK, "u"), - skipMatch = new RegExp(SKIP_BLANK, "u"), - lines = sourceCode.lines, - linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()), - comments = sourceCode.getAllComments(), - commentLineNumbers = getCommentLineNumbers(comments); - - let totalLength = 0, - fixRange = []; - - for (let i = 0, ii = lines.length; i < ii; i++) { - const lineNumber = i + 1; - - /* - * Always add linebreak length to line length to accommodate for line break (\n or \r\n) - * Because during the fix time they also reserve one spot in the array. - * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) - */ - const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1; - const lineLength = lines[i].length + linebreakLength; - - const matches = re.exec(lines[i]); - - if (matches) { - const location = { - start: { - line: lineNumber, - column: matches.index - }, - end: { - line: lineNumber, - column: lineLength - linebreakLength - } - }; - - const rangeStart = totalLength + location.start.column; - const rangeEnd = totalLength + location.end.column; - const containingNode = sourceCode.getNodeByRangeIndex(rangeStart); - - if (containingNode && containingNode.type === "TemplateElement" && - rangeStart > containingNode.parent.range[0] && - rangeEnd < containingNode.parent.range[1]) { - totalLength += lineLength; - continue; - } - - /* - * If the line has only whitespace, and skipBlankLines - * is true, don't report it - */ - if (skipBlankLines && skipMatch.test(lines[i])) { - totalLength += lineLength; - continue; - } - - fixRange = [rangeStart, rangeEnd]; - - if (!ignoreComments || !commentLineNumbers.has(lineNumber)) { - report(node, location, fixRange); - } - } - - totalLength += lineLength; - } - } - - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-undef-init.js b/tools/node_modules/eslint/lib/rules/no-undef-init.js deleted file mode 100644 index 5c240fef742b8375eae92be09edff4bf7f67d119..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-undef-init.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @fileoverview Rule to flag when initializing to undefined - * @author Ilya Volodin - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow initializing variables to `undefined`", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-undef-init" - }, - - schema: [], - fixable: "code", - - messages: { - unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - return { - - VariableDeclarator(node) { - const name = sourceCode.getText(node.id), - init = node.init && node.init.name, - scope = context.getScope(), - undefinedVar = astUtils.getVariableByName(scope, "undefined"), - shadowed = undefinedVar && undefinedVar.defs.length > 0, - lastToken = sourceCode.getLastToken(node); - - if (init === "undefined" && node.parent.kind !== "const" && !shadowed) { - context.report({ - node, - messageId: "unnecessaryUndefinedInit", - data: { name }, - fix(fixer) { - if (node.parent.kind === "var") { - return null; - } - - if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") { - - // Don't fix destructuring assignment to `undefined`. - return null; - } - - if (sourceCode.commentsExistBetween(node.id, lastToken)) { - return null; - } - - return fixer.removeRange([node.id.range[1], node.range[1]]); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-undef.js b/tools/node_modules/eslint/lib/rules/no-undef.js deleted file mode 100644 index 6b5140819bbd3010a86b9e2c1548a55ce3c1a71a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-undef.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @fileoverview Rule to flag references to undeclared variables. - * @author Mark Macdonald - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks if the given node is the argument of a typeof operator. - * @param {ASTNode} node The AST node being checked. - * @returns {boolean} Whether or not the node is the argument of a typeof operator. - */ -function hasTypeOfOperator(node) { - const parent = node.parent; - - return parent.type === "UnaryExpression" && parent.operator === "typeof"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-undef" - }, - - schema: [ - { - type: "object", - properties: { - typeof: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - undef: "'{{name}}' is not defined." - } - }, - - create(context) { - const options = context.options[0]; - const considerTypeOf = options && options.typeof === true || false; - - return { - "Program:exit"(/* node */) { - const globalScope = context.getScope(); - - globalScope.through.forEach(ref => { - const identifier = ref.identifier; - - if (!considerTypeOf && hasTypeOfOperator(identifier)) { - return; - } - - context.report({ - node: identifier, - messageId: "undef", - data: identifier - }); - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-undefined.js b/tools/node_modules/eslint/lib/rules/no-undefined.js deleted file mode 100644 index a075d903e21e98dde9e02bfcfdcad4d8982c936e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-undefined.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @fileoverview Rule to flag references to the undefined variable. - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `undefined` as an identifier", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-undefined" - }, - - schema: [], - - messages: { - unexpectedUndefined: "Unexpected use of undefined." - } - }, - - create(context) { - - /** - * Report an invalid "undefined" identifier node. - * @param {ASTNode} node The node to report. - * @returns {void} - */ - function report(node) { - context.report({ - node, - messageId: "unexpectedUndefined" - }); - } - - /** - * Checks the given scope for references to `undefined` and reports - * all references found. - * @param {eslint-scope.Scope} scope The scope to check. - * @returns {void} - */ - function checkScope(scope) { - const undefinedVar = scope.set.get("undefined"); - - if (!undefinedVar) { - return; - } - - const references = undefinedVar.references; - - const defs = undefinedVar.defs; - - // Report non-initializing references (those are covered in defs below) - references - .filter(ref => !ref.init) - .forEach(ref => report(ref.identifier)); - - defs.forEach(def => report(def.name)); - } - - return { - "Program:exit"() { - const globalScope = context.getScope(); - - const stack = [globalScope]; - - while (stack.length) { - const scope = stack.pop(); - - stack.push(...scope.childScopes); - checkScope(scope); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-underscore-dangle.js b/tools/node_modules/eslint/lib/rules/no-underscore-dangle.js deleted file mode 100644 index cac594e10047e84b9e0bc067ae238f79de535967..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-underscore-dangle.js +++ /dev/null @@ -1,232 +0,0 @@ -/** - * @fileoverview Rule to flag trailing underscores in variable declarations. - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow dangling underscores in identifiers", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-underscore-dangle" - }, - - schema: [ - { - type: "object", - properties: { - allow: { - type: "array", - items: { - type: "string" - } - }, - allowAfterThis: { - type: "boolean", - default: false - }, - allowAfterSuper: { - type: "boolean", - default: false - }, - allowAfterThisConstructor: { - type: "boolean", - default: false - }, - enforceInMethodNames: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedUnderscore: "Unexpected dangling '_' in '{{identifier}}'." - } - }, - - create(context) { - - const options = context.options[0] || {}; - const ALLOWED_VARIABLES = options.allow ? options.allow : []; - const allowAfterThis = typeof options.allowAfterThis !== "undefined" ? options.allowAfterThis : false; - const allowAfterSuper = typeof options.allowAfterSuper !== "undefined" ? options.allowAfterSuper : false; - const allowAfterThisConstructor = typeof options.allowAfterThisConstructor !== "undefined" ? options.allowAfterThisConstructor : false; - const enforceInMethodNames = typeof options.enforceInMethodNames !== "undefined" ? options.enforceInMethodNames : false; - - //------------------------------------------------------------------------- - // Helpers - //------------------------------------------------------------------------- - - /** - * Check if identifier is present inside the allowed option - * @param {string} identifier name of the node - * @returns {boolean} true if its is present - * @private - */ - function isAllowed(identifier) { - return ALLOWED_VARIABLES.some(ident => ident === identifier); - } - - /** - * Check if identifier has a underscore at the end - * @param {string} identifier name of the node - * @returns {boolean} true if its is present - * @private - */ - function hasTrailingUnderscore(identifier) { - const len = identifier.length; - - return identifier !== "_" && (identifier[0] === "_" || identifier[len - 1] === "_"); - } - - /** - * Check if identifier is a special case member expression - * @param {string} identifier name of the node - * @returns {boolean} true if its is a special case - * @private - */ - function isSpecialCaseIdentifierForMemberExpression(identifier) { - return identifier === "__proto__"; - } - - /** - * Check if identifier is a special case variable expression - * @param {string} identifier name of the node - * @returns {boolean} true if its is a special case - * @private - */ - function isSpecialCaseIdentifierInVariableExpression(identifier) { - - // Checks for the underscore library usage here - return identifier === "_"; - } - - /** - * Check if a node is a member reference of this.constructor - * @param {ASTNode} node node to evaluate - * @returns {boolean} true if it is a reference on this.constructor - * @private - */ - function isThisConstructorReference(node) { - return node.object.type === "MemberExpression" && - node.object.property.name === "constructor" && - node.object.object.type === "ThisExpression"; - } - - /** - * Check if function has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInFunctionDeclaration(node) { - if (node.id) { - const identifier = node.id.name; - - if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && !isAllowed(identifier)) { - context.report({ - node, - messageId: "unexpectedUnderscore", - data: { - identifier - } - }); - } - } - } - - /** - * Check if variable expression has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInVariableExpression(node) { - const identifier = node.id.name; - - if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && - !isSpecialCaseIdentifierInVariableExpression(identifier) && !isAllowed(identifier)) { - context.report({ - node, - messageId: "unexpectedUnderscore", - data: { - identifier - } - }); - } - } - - /** - * Check if member expression has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInMemberExpression(node) { - const identifier = node.property.name, - isMemberOfThis = node.object.type === "ThisExpression", - isMemberOfSuper = node.object.type === "Super", - isMemberOfThisConstructor = isThisConstructorReference(node); - - if (typeof identifier !== "undefined" && hasTrailingUnderscore(identifier) && - !(isMemberOfThis && allowAfterThis) && - !(isMemberOfSuper && allowAfterSuper) && - !(isMemberOfThisConstructor && allowAfterThisConstructor) && - !isSpecialCaseIdentifierForMemberExpression(identifier) && !isAllowed(identifier)) { - context.report({ - node, - messageId: "unexpectedUnderscore", - data: { - identifier - } - }); - } - } - - /** - * Check if method declaration or method property has a underscore at the end - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkForTrailingUnderscoreInMethod(node) { - const identifier = node.key.name; - const isMethod = node.type === "MethodDefinition" || node.type === "Property" && node.method; - - if (typeof identifier !== "undefined" && enforceInMethodNames && isMethod && hasTrailingUnderscore(identifier) && !isAllowed(identifier)) { - context.report({ - node, - messageId: "unexpectedUnderscore", - data: { - identifier - } - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - FunctionDeclaration: checkForTrailingUnderscoreInFunctionDeclaration, - VariableDeclarator: checkForTrailingUnderscoreInVariableExpression, - MemberExpression: checkForTrailingUnderscoreInMemberExpression, - MethodDefinition: checkForTrailingUnderscoreInMethod, - Property: checkForTrailingUnderscoreInMethod - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js b/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js deleted file mode 100644 index 7af3fe67090dfa23e0136e1597cb8c225cfac35c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unexpected-multiline.js +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. - * @author Glen Mailer - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow confusing multiline expressions", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unexpected-multiline" - }, - - schema: [], - messages: { - function: "Unexpected newline between function and ( of function call.", - property: "Unexpected newline between object and [ of property access.", - taggedTemplate: "Unexpected newline between template tag and template literal.", - division: "Unexpected newline between numerator and division operator." - } - }, - - create(context) { - - const REGEX_FLAG_MATCHER = /^[gimsuy]+$/u; - - const sourceCode = context.getSourceCode(); - - /** - * Check to see if there is a newline between the node and the following open bracket - * line's expression - * @param {ASTNode} node The node to check. - * @param {string} messageId The error messageId to use. - * @returns {void} - * @private - */ - function checkForBreakAfter(node, messageId) { - const openParen = sourceCode.getTokenAfter(node, astUtils.isNotClosingParenToken); - const nodeExpressionEnd = sourceCode.getTokenBefore(openParen); - - if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) { - context.report({ - node, - loc: openParen.loc, - messageId - }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - - MemberExpression(node) { - if (!node.computed || node.optional) { - return; - } - checkForBreakAfter(node.object, "property"); - }, - - TaggedTemplateExpression(node) { - const { quasi } = node; - - // handles common tags, parenthesized tags, and typescript's generic type arguments - const tokenBefore = sourceCode.getTokenBefore(quasi); - - if (tokenBefore.loc.end.line !== quasi.loc.start.line) { - context.report({ - node, - loc: { - start: quasi.loc.start, - end: { - line: quasi.loc.start.line, - column: quasi.loc.start.column + 1 - } - }, - messageId: "taggedTemplate" - }); - } - }, - - CallExpression(node) { - if (node.arguments.length === 0 || node.optional) { - return; - } - checkForBreakAfter(node.callee, "function"); - }, - - "BinaryExpression[operator='/'] > BinaryExpression[operator='/'].left"(node) { - const secondSlash = sourceCode.getTokenAfter(node, token => token.value === "/"); - const tokenAfterOperator = sourceCode.getTokenAfter(secondSlash); - - if ( - tokenAfterOperator.type === "Identifier" && - REGEX_FLAG_MATCHER.test(tokenAfterOperator.value) && - secondSlash.range[1] === tokenAfterOperator.range[0] - ) { - checkForBreakAfter(node.left, "division"); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js b/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js deleted file mode 100644 index 7031a4dd8b83fc290f86a0f944e3d0fdf0aa67ed..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unmodified-loop-condition.js +++ /dev/null @@ -1,360 +0,0 @@ -/** - * @fileoverview Rule to disallow use of unmodified expressions in loop conditions - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Traverser = require("../shared/traverser"), - astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_PATTERN = /(?:(?:Call|Class|Function|Member|New|Yield)Expression|Statement|Declaration)$/u; -const LOOP_PATTERN = /^(?:DoWhile|For|While)Statement$/u; // for-in/of statements don't have `test` property. -const GROUP_PATTERN = /^(?:BinaryExpression|ConditionalExpression)$/u; -const SKIP_PATTERN = /^(?:ArrowFunction|Class|Function)Expression$/u; -const DYNAMIC_PATTERN = /^(?:Call|Member|New|TaggedTemplate|Yield)Expression$/u; - -/** - * @typedef {Object} LoopConditionInfo - * @property {eslint-scope.Reference} reference - The reference. - * @property {ASTNode} group - BinaryExpression or ConditionalExpression nodes - * that the reference is belonging to. - * @property {Function} isInLoop - The predicate which checks a given reference - * is in this loop. - * @property {boolean} modified - The flag that the reference is modified in - * this loop. - */ - -/** - * Checks whether or not a given reference is a write reference. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is a write reference. - */ -function isWriteReference(reference) { - if (reference.init) { - const def = reference.resolved && reference.resolved.defs[0]; - - if (!def || def.type !== "Variable" || def.parent.kind !== "var") { - return false; - } - } - return reference.isWrite(); -} - -/** - * Checks whether or not a given loop condition info does not have the modified - * flag. - * @param {LoopConditionInfo} condition A loop condition info to check. - * @returns {boolean} `true` if the loop condition info is "unmodified". - */ -function isUnmodified(condition) { - return !condition.modified; -} - -/** - * Checks whether or not a given loop condition info does not have the modified - * flag and does not have the group this condition belongs to. - * @param {LoopConditionInfo} condition A loop condition info to check. - * @returns {boolean} `true` if the loop condition info is "unmodified". - */ -function isUnmodifiedAndNotBelongToGroup(condition) { - return !(condition.modified || condition.group); -} - -/** - * Checks whether or not a given reference is inside of a given node. - * @param {ASTNode} node A node to check. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is inside of the node. - */ -function isInRange(node, reference) { - const or = node.range; - const ir = reference.identifier.range; - - return or[0] <= ir[0] && ir[1] <= or[1]; -} - -/** - * Checks whether or not a given reference is inside of a loop node's condition. - * @param {ASTNode} node A node to check. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is inside of the loop node's - * condition. - */ -const isInLoop = { - WhileStatement: isInRange, - DoWhileStatement: isInRange, - ForStatement(node, reference) { - return ( - isInRange(node, reference) && - !(node.init && isInRange(node.init, reference)) - ); - } -}; - -/** - * Gets the function which encloses a given reference. - * This supports only FunctionDeclaration. - * @param {eslint-scope.Reference} reference A reference to get. - * @returns {ASTNode|null} The function node or null. - */ -function getEncloseFunctionDeclaration(reference) { - let node = reference.identifier; - - while (node) { - if (node.type === "FunctionDeclaration") { - return node.id ? node : null; - } - - node = node.parent; - } - - return null; -} - -/** - * Updates the "modified" flags of given loop conditions with given modifiers. - * @param {LoopConditionInfo[]} conditions The loop conditions to be updated. - * @param {eslint-scope.Reference[]} modifiers The references to update. - * @returns {void} - */ -function updateModifiedFlag(conditions, modifiers) { - - for (let i = 0; i < conditions.length; ++i) { - const condition = conditions[i]; - - for (let j = 0; !condition.modified && j < modifiers.length; ++j) { - const modifier = modifiers[j]; - let funcNode, funcVar; - - /* - * Besides checking for the condition being in the loop, we want to - * check the function that this modifier is belonging to is called - * in the loop. - * FIXME: This should probably be extracted to a function. - */ - const inLoop = condition.isInLoop(modifier) || Boolean( - (funcNode = getEncloseFunctionDeclaration(modifier)) && - (funcVar = astUtils.getVariableByName(modifier.from.upper, funcNode.id.name)) && - funcVar.references.some(condition.isInLoop) - ); - - condition.modified = inLoop; - } - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow unmodified loop conditions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-unmodified-loop-condition" - }, - - schema: [], - - messages: { - loopConditionNotModified: "'{{name}}' is not modified in this loop." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let groupMap = null; - - /** - * Reports a given condition info. - * @param {LoopConditionInfo} condition A loop condition info to report. - * @returns {void} - */ - function report(condition) { - const node = condition.reference.identifier; - - context.report({ - node, - messageId: "loopConditionNotModified", - data: node - }); - } - - /** - * Registers given conditions to the group the condition belongs to. - * @param {LoopConditionInfo[]} conditions A loop condition info to - * register. - * @returns {void} - */ - function registerConditionsToGroup(conditions) { - for (let i = 0; i < conditions.length; ++i) { - const condition = conditions[i]; - - if (condition.group) { - let group = groupMap.get(condition.group); - - if (!group) { - group = []; - groupMap.set(condition.group, group); - } - group.push(condition); - } - } - } - - /** - * Reports references which are inside of unmodified groups. - * @param {LoopConditionInfo[]} conditions A loop condition info to report. - * @returns {void} - */ - function checkConditionsInGroup(conditions) { - if (conditions.every(isUnmodified)) { - conditions.forEach(report); - } - } - - /** - * Checks whether or not a given group node has any dynamic elements. - * @param {ASTNode} root A node to check. - * This node is one of BinaryExpression or ConditionalExpression. - * @returns {boolean} `true` if the node is dynamic. - */ - function hasDynamicExpressions(root) { - let retv = false; - - Traverser.traverse(root, { - visitorKeys: sourceCode.visitorKeys, - enter(node) { - if (DYNAMIC_PATTERN.test(node.type)) { - retv = true; - this.break(); - } else if (SKIP_PATTERN.test(node.type)) { - this.skip(); - } - } - }); - - return retv; - } - - /** - * Creates the loop condition information from a given reference. - * @param {eslint-scope.Reference} reference A reference to create. - * @returns {LoopConditionInfo|null} Created loop condition info, or null. - */ - function toLoopCondition(reference) { - if (reference.init) { - return null; - } - - let group = null; - let child = reference.identifier; - let node = child.parent; - - while (node) { - if (SENTINEL_PATTERN.test(node.type)) { - if (LOOP_PATTERN.test(node.type) && node.test === child) { - - // This reference is inside of a loop condition. - return { - reference, - group, - isInLoop: isInLoop[node.type].bind(null, node), - modified: false - }; - } - - // This reference is outside of a loop condition. - break; - } - - /* - * If it's inside of a group, OK if either operand is modified. - * So stores the group this reference belongs to. - */ - if (GROUP_PATTERN.test(node.type)) { - - // If this expression is dynamic, no need to check. - if (hasDynamicExpressions(node)) { - break; - } else { - group = node; - } - } - - child = node; - node = node.parent; - } - - return null; - } - - /** - * Finds unmodified references which are inside of a loop condition. - * Then reports the references which are outside of groups. - * @param {eslint-scope.Variable} variable A variable to report. - * @returns {void} - */ - function checkReferences(variable) { - - // Gets references that exist in loop conditions. - const conditions = variable - .references - .map(toLoopCondition) - .filter(Boolean); - - if (conditions.length === 0) { - return; - } - - // Registers the conditions to belonging groups. - registerConditionsToGroup(conditions); - - // Check the conditions are modified. - const modifiers = variable.references.filter(isWriteReference); - - if (modifiers.length > 0) { - updateModifiedFlag(conditions, modifiers); - } - - /* - * Reports the conditions which are not belonging to groups. - * Others will be reported after all variables are done. - */ - conditions - .filter(isUnmodifiedAndNotBelongToGroup) - .forEach(report); - } - - return { - "Program:exit"() { - const queue = [context.getScope()]; - - groupMap = new Map(); - - let scope; - - while ((scope = queue.pop())) { - queue.push(...scope.childScopes); - scope.variables.forEach(checkReferences); - } - - groupMap.forEach(checkConditionsInGroup); - groupMap = null; - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js b/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js deleted file mode 100644 index 06c615f38240502304f9d821ee3ab795a88431c0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unneeded-ternary.js +++ /dev/null @@ -1,166 +0,0 @@ -/** - * @fileoverview Rule to flag no-unneeded-ternary - * @author Gyandeep Singh - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -// Operators that always result in a boolean value -const BOOLEAN_OPERATORS = new Set(["==", "===", "!=", "!==", ">", ">=", "<", "<=", "in", "instanceof"]); -const OPERATOR_INVERSES = { - "==": "!=", - "!=": "==", - "===": "!==", - "!==": "===" - - // Operators like < and >= are not true inverses, since both will return false with NaN. -}; -const OR_PRECEDENCE = astUtils.getPrecedence({ type: "LogicalExpression", operator: "||" }); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow ternary operators when simpler alternatives exist", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-unneeded-ternary" - }, - - schema: [ - { - type: "object", - properties: { - defaultAssignment: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - unnecessaryConditionalExpression: "Unnecessary use of boolean literals in conditional expression.", - unnecessaryConditionalAssignment: "Unnecessary use of conditional expression for default assignment." - } - }, - - create(context) { - const options = context.options[0] || {}; - const defaultAssignment = options.defaultAssignment !== false; - const sourceCode = context.getSourceCode(); - - /** - * Test if the node is a boolean literal - * @param {ASTNode} node The node to report. - * @returns {boolean} True if the its a boolean literal - * @private - */ - function isBooleanLiteral(node) { - return node.type === "Literal" && typeof node.value === "boolean"; - } - - /** - * Creates an expression that represents the boolean inverse of the expression represented by the original node - * @param {ASTNode} node A node representing an expression - * @returns {string} A string representing an inverted expression - */ - function invertExpression(node) { - if (node.type === "BinaryExpression" && Object.prototype.hasOwnProperty.call(OPERATOR_INVERSES, node.operator)) { - const operatorToken = sourceCode.getFirstTokenBetween( - node.left, - node.right, - token => token.value === node.operator - ); - const text = sourceCode.getText(); - - return text.slice(node.range[0], - operatorToken.range[0]) + OPERATOR_INVERSES[node.operator] + text.slice(operatorToken.range[1], node.range[1]); - } - - if (astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression" })) { - return `!(${astUtils.getParenthesisedText(sourceCode, node)})`; - } - return `!${astUtils.getParenthesisedText(sourceCode, node)}`; - } - - /** - * Tests if a given node always evaluates to a boolean value - * @param {ASTNode} node An expression node - * @returns {boolean} True if it is determined that the node will always evaluate to a boolean value - */ - function isBooleanExpression(node) { - return node.type === "BinaryExpression" && BOOLEAN_OPERATORS.has(node.operator) || - node.type === "UnaryExpression" && node.operator === "!"; - } - - /** - * Test if the node matches the pattern id ? id : expression - * @param {ASTNode} node The ConditionalExpression to check. - * @returns {boolean} True if the pattern is matched, and false otherwise - * @private - */ - function matchesDefaultAssignment(node) { - return node.test.type === "Identifier" && - node.consequent.type === "Identifier" && - node.test.name === node.consequent.name; - } - - return { - - ConditionalExpression(node) { - if (isBooleanLiteral(node.alternate) && isBooleanLiteral(node.consequent)) { - context.report({ - node, - messageId: "unnecessaryConditionalExpression", - fix(fixer) { - if (node.consequent.value === node.alternate.value) { - - // Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true` - return node.test.type === "Identifier" ? fixer.replaceText(node, node.consequent.value.toString()) : null; - } - if (node.alternate.value) { - - // Replace `foo() ? false : true` with `!(foo())` - return fixer.replaceText(node, invertExpression(node.test)); - } - - // Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise. - - return fixer.replaceText(node, isBooleanExpression(node.test) ? astUtils.getParenthesisedText(sourceCode, node.test) : `!${invertExpression(node.test)}`); - } - }); - } else if (!defaultAssignment && matchesDefaultAssignment(node)) { - context.report({ - node, - messageId: "unnecessaryConditionalAssignment", - fix: fixer => { - const shouldParenthesizeAlternate = - ( - astUtils.getPrecedence(node.alternate) < OR_PRECEDENCE || - astUtils.isCoalesceExpression(node.alternate) - ) && - !astUtils.isParenthesised(sourceCode, node.alternate); - const alternateText = shouldParenthesizeAlternate - ? `(${sourceCode.getText(node.alternate)})` - : astUtils.getParenthesisedText(sourceCode, node.alternate); - const testText = astUtils.getParenthesisedText(sourceCode, node.test); - - return fixer.replaceText(node, `${testText} || ${alternateText}`); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unreachable.js b/tools/node_modules/eslint/lib/rules/no-unreachable.js deleted file mode 100644 index 415631a6f7d726e8b9eaebce05359bcfe66e8e6d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unreachable.js +++ /dev/null @@ -1,218 +0,0 @@ -/** - * @fileoverview Checks for unreachable code due to return, throws, break, and continue. - * @author Joel Feenstra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given variable declarator has the initializer. - * @param {ASTNode} node A VariableDeclarator node to check. - * @returns {boolean} `true` if the node has the initializer. - */ -function isInitialized(node) { - return Boolean(node.init); -} - -/** - * Checks whether or not a given code path segment is unreachable. - * @param {CodePathSegment} segment A CodePathSegment to check. - * @returns {boolean} `true` if the segment is unreachable. - */ -function isUnreachable(segment) { - return !segment.reachable; -} - -/** - * The class to distinguish consecutive unreachable statements. - */ -class ConsecutiveRange { - constructor(sourceCode) { - this.sourceCode = sourceCode; - this.startNode = null; - this.endNode = null; - } - - /** - * The location object of this range. - * @type {Object} - */ - get location() { - return { - start: this.startNode.loc.start, - end: this.endNode.loc.end - }; - } - - /** - * `true` if this range is empty. - * @type {boolean} - */ - get isEmpty() { - return !(this.startNode && this.endNode); - } - - /** - * Checks whether the given node is inside of this range. - * @param {ASTNode|Token} node The node to check. - * @returns {boolean} `true` if the node is inside of this range. - */ - contains(node) { - return ( - node.range[0] >= this.startNode.range[0] && - node.range[1] <= this.endNode.range[1] - ); - } - - /** - * Checks whether the given node is consecutive to this range. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is consecutive to this range. - */ - isConsecutive(node) { - return this.contains(this.sourceCode.getTokenBefore(node)); - } - - /** - * Merges the given node to this range. - * @param {ASTNode} node The node to merge. - * @returns {void} - */ - merge(node) { - this.endNode = node; - } - - /** - * Resets this range by the given node or null. - * @param {ASTNode|null} node The node to reset, or null. - * @returns {void} - */ - reset(node) { - this.startNode = this.endNode = node; - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow unreachable code after `return`, `throw`, `continue`, and `break` statements", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unreachable" - }, - - schema: [], - - messages: { - unreachableCode: "Unreachable code." - } - }, - - create(context) { - let currentCodePath = null; - - const range = new ConsecutiveRange(context.getSourceCode()); - - /** - * Reports a given node if it's unreachable. - * @param {ASTNode} node A statement node to report. - * @returns {void} - */ - function reportIfUnreachable(node) { - let nextNode = null; - - if (node && currentCodePath.currentSegments.every(isUnreachable)) { - - // Store this statement to distinguish consecutive statements. - if (range.isEmpty) { - range.reset(node); - return; - } - - // Skip if this statement is inside of the current range. - if (range.contains(node)) { - return; - } - - // Merge if this statement is consecutive to the current range. - if (range.isConsecutive(node)) { - range.merge(node); - return; - } - - nextNode = node; - } - - /* - * Report the current range since this statement is reachable or is - * not consecutive to the current range. - */ - if (!range.isEmpty) { - context.report({ - messageId: "unreachableCode", - loc: range.location, - node: range.startNode - }); - } - - // Update the current range. - range.reset(nextNode); - } - - return { - - // Manages the current code path. - onCodePathStart(codePath) { - currentCodePath = codePath; - }, - - onCodePathEnd() { - currentCodePath = currentCodePath.upper; - }, - - // Registers for all statement nodes (excludes FunctionDeclaration). - BlockStatement: reportIfUnreachable, - BreakStatement: reportIfUnreachable, - ClassDeclaration: reportIfUnreachable, - ContinueStatement: reportIfUnreachable, - DebuggerStatement: reportIfUnreachable, - DoWhileStatement: reportIfUnreachable, - ExpressionStatement: reportIfUnreachable, - ForInStatement: reportIfUnreachable, - ForOfStatement: reportIfUnreachable, - ForStatement: reportIfUnreachable, - IfStatement: reportIfUnreachable, - ImportDeclaration: reportIfUnreachable, - LabeledStatement: reportIfUnreachable, - ReturnStatement: reportIfUnreachable, - SwitchStatement: reportIfUnreachable, - ThrowStatement: reportIfUnreachable, - TryStatement: reportIfUnreachable, - - VariableDeclaration(node) { - if (node.kind !== "var" || node.declarations.some(isInitialized)) { - reportIfUnreachable(node); - } - }, - - WhileStatement: reportIfUnreachable, - WithStatement: reportIfUnreachable, - ExportNamedDeclaration: reportIfUnreachable, - ExportDefaultDeclaration: reportIfUnreachable, - ExportAllDeclaration: reportIfUnreachable, - - "Program:exit"() { - reportIfUnreachable(); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unsafe-finally.js b/tools/node_modules/eslint/lib/rules/no-unsafe-finally.js deleted file mode 100644 index 11bf06e872a813be0166e9fb0df52c30298313fb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unsafe-finally.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * @fileoverview Rule to flag unsafe statements in finally block - * @author Onur Temizkan - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u; -const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u; -const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u; - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow control flow statements in `finally` blocks", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unsafe-finally" - }, - - schema: [], - - messages: { - unsafeUsage: "Unsafe usage of {{nodeType}}." - } - }, - create(context) { - - /** - * Checks if the node is the finalizer of a TryStatement - * @param {ASTNode} node node to check. - * @returns {boolean} - true if the node is the finalizer of a TryStatement - */ - function isFinallyBlock(node) { - return node.parent.type === "TryStatement" && node.parent.finalizer === node; - } - - /** - * Climbs up the tree if the node is not a sentinel node - * @param {ASTNode} node node to check. - * @param {string} label label of the break or continue statement - * @returns {boolean} - return whether the node is a finally block or a sentinel node - */ - function isInFinallyBlock(node, label) { - let labelInside = false; - let sentinelNodeType; - - if (node.type === "BreakStatement" && !node.label) { - sentinelNodeType = SENTINEL_NODE_TYPE_BREAK; - } else if (node.type === "ContinueStatement") { - sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE; - } else { - sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW; - } - - for ( - let currentNode = node; - currentNode && !sentinelNodeType.test(currentNode.type); - currentNode = currentNode.parent - ) { - if (currentNode.parent.label && label && (currentNode.parent.label.name === label.name)) { - labelInside = true; - } - if (isFinallyBlock(currentNode)) { - if (label && labelInside) { - return false; - } - return true; - } - } - return false; - } - - /** - * Checks whether the possibly-unsafe statement is inside a finally block. - * @param {ASTNode} node node to check. - * @returns {void} - */ - function check(node) { - if (isInFinallyBlock(node, node.label)) { - context.report({ - messageId: "unsafeUsage", - data: { - nodeType: node.type - }, - node, - line: node.loc.line, - column: node.loc.column - }); - } - } - - return { - ReturnStatement: check, - ThrowStatement: check, - BreakStatement: check, - ContinueStatement: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js b/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js deleted file mode 100644 index a9c2ee74f2c8281bb479e0316f5ea771af31b646..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unsafe-negation.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule to disallow negating the left operand of relational operators - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether the given operator is `in` or `instanceof` - * @param {string} op The operator type to check. - * @returns {boolean} `true` if the operator is `in` or `instanceof` - */ -function isInOrInstanceOfOperator(op) { - return op === "in" || op === "instanceof"; -} - -/** - * Checks whether the given operator is an ordering relational operator or not. - * @param {string} op The operator type to check. - * @returns {boolean} `true` if the operator is an ordering relational operator. - */ -function isOrderingRelationalOperator(op) { - return op === "<" || op === ">" || op === ">=" || op === "<="; -} - -/** - * Checks whether the given node is a logical negation expression or not. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is a logical negation expression. - */ -function isNegation(node) { - return node.type === "UnaryExpression" && node.operator === "!"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow negating the left operand of relational operators", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/no-unsafe-negation", - suggestion: true - }, - - schema: [ - { - type: "object", - properties: { - enforceForOrderingRelations: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: null, - - messages: { - unexpected: "Unexpected negating the left operand of '{{operator}}' operator.", - suggestNegatedExpression: "Negate '{{operator}}' expression instead of its left operand. This changes the current behavior.", - suggestParenthesisedNegation: "Wrap negation in '()' to make the intention explicit. This preserves the current behavior." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = context.options[0] || {}; - const enforceForOrderingRelations = options.enforceForOrderingRelations === true; - - return { - BinaryExpression(node) { - const operator = node.operator; - const orderingRelationRuleApplies = enforceForOrderingRelations && isOrderingRelationalOperator(operator); - - if ( - (isInOrInstanceOfOperator(operator) || orderingRelationRuleApplies) && - isNegation(node.left) && - !astUtils.isParenthesised(sourceCode, node.left) - ) { - context.report({ - node, - loc: node.left.loc, - messageId: "unexpected", - data: { operator }, - suggest: [ - { - messageId: "suggestNegatedExpression", - data: { operator }, - fix(fixer) { - const negationToken = sourceCode.getFirstToken(node.left); - const fixRange = [negationToken.range[1], node.range[1]]; - const text = sourceCode.text.slice(fixRange[0], fixRange[1]); - - return fixer.replaceTextRange(fixRange, `(${text})`); - } - }, - { - messageId: "suggestParenthesisedNegation", - fix(fixer) { - return fixer.replaceText(node.left, `(${sourceCode.getText(node.left)})`); - } - } - ] - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-expressions.js b/tools/node_modules/eslint/lib/rules/no-unused-expressions.js deleted file mode 100644 index 882a0fd1c11276c9baa3769344ea5f117e9af358..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unused-expressions.js +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @fileoverview Flag expressions in statement position that do not side effect - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Returns `true`. - * @returns {boolean} `true`. - */ -function alwaysTrue() { - return true; -} - -/** - * Returns `false`. - * @returns {boolean} `false`. - */ -function alwaysFalse() { - return false; -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unused expressions", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-unused-expressions" - }, - - schema: [ - { - type: "object", - properties: { - allowShortCircuit: { - type: "boolean", - default: false - }, - allowTernary: { - type: "boolean", - default: false - }, - allowTaggedTemplates: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - unusedExpression: "Expected an assignment or function call and instead saw an expression." - } - }, - - create(context) { - const config = context.options[0] || {}, - allowShortCircuit = config.allowShortCircuit || false, - allowTernary = config.allowTernary || false, - allowTaggedTemplates = config.allowTaggedTemplates || false; - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ASTNode} node any node - * @returns {boolean} whether the given node structurally represents a directive - */ - function looksLikeDirective(node) { - return node.type === "ExpressionStatement" && - node.expression.type === "Literal" && typeof node.expression.value === "string"; - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {Function} predicate ([a] -> Boolean) the function used to make the determination - * @param {a[]} list the input list - * @returns {a[]} the leading sequence of members in the given list that pass the given predicate - */ - function takeWhile(predicate, list) { - for (let i = 0; i < list.length; ++i) { - if (!predicate(list[i])) { - return list.slice(0, i); - } - } - return list.slice(); - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ASTNode} node a Program or BlockStatement node - * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body - */ - function directives(node) { - return takeWhile(looksLikeDirective, node.body); - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ASTNode} node any node - * @param {ASTNode[]} ancestors the given node's ancestors - * @returns {boolean} whether the given node is considered a directive in its current position - */ - function isDirective(node, ancestors) { - const parent = ancestors[ancestors.length - 1], - grandparent = ancestors[ancestors.length - 2]; - - return (parent.type === "Program" || parent.type === "BlockStatement" && - (/Function/u.test(grandparent.type))) && - directives(parent).indexOf(node) >= 0; - } - - /** - * The member functions return `true` if the type has no side-effects. - * Unknown nodes are handled as `false`, then this rule ignores those. - */ - const Checker = Object.assign(Object.create(null), { - isDisallowed(node) { - return (Checker[node.type] || alwaysFalse)(node); - }, - - ArrayExpression: alwaysTrue, - ArrowFunctionExpression: alwaysTrue, - BinaryExpression: alwaysTrue, - ChainExpression(node) { - return Checker.isDisallowed(node.expression); - }, - ClassExpression: alwaysTrue, - ConditionalExpression(node) { - if (allowTernary) { - return Checker.isDisallowed(node.consequent) || Checker.isDisallowed(node.alternate); - } - return true; - }, - FunctionExpression: alwaysTrue, - Identifier: alwaysTrue, - Literal: alwaysTrue, - LogicalExpression(node) { - if (allowShortCircuit) { - return Checker.isDisallowed(node.right); - } - return true; - }, - MemberExpression: alwaysTrue, - MetaProperty: alwaysTrue, - ObjectExpression: alwaysTrue, - SequenceExpression: alwaysTrue, - TaggedTemplateExpression() { - return !allowTaggedTemplates; - }, - TemplateLiteral: alwaysTrue, - ThisExpression: alwaysTrue, - UnaryExpression(node) { - return node.operator !== "void" && node.operator !== "delete"; - } - }); - - return { - ExpressionStatement(node) { - if (Checker.isDisallowed(node.expression) && !isDirective(node, context.getAncestors())) { - context.report({ node, messageId: "unusedExpression" }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-labels.js b/tools/node_modules/eslint/lib/rules/no-unused-labels.js deleted file mode 100644 index b33fcb786790c44f5fb9c8e017f9c06c8baafdf3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unused-labels.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @fileoverview Rule to disallow unused labels. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unused labels", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-unused-labels" - }, - - schema: [], - - fixable: "code", - - messages: { - unused: "'{{name}}:' is defined but never used." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Adds a scope info to the stack. - * @param {ASTNode} node A node to add. This is a LabeledStatement. - * @returns {void} - */ - function enterLabeledScope(node) { - scopeInfo = { - label: node.label.name, - used: false, - upper: scopeInfo - }; - } - - /** - * Removes the top of the stack. - * At the same time, this reports the label if it's never used. - * @param {ASTNode} node A node to report. This is a LabeledStatement. - * @returns {void} - */ - function exitLabeledScope(node) { - if (!scopeInfo.used) { - context.report({ - node: node.label, - messageId: "unused", - data: node.label, - fix(fixer) { - - /* - * Only perform a fix if there are no comments between the label and the body. This will be the case - * when there is exactly one token/comment (the ":") between the label and the body. - */ - if (sourceCode.getTokenAfter(node.label, { includeComments: true }) === - sourceCode.getTokenBefore(node.body, { includeComments: true })) { - return fixer.removeRange([node.range[0], node.body.range[0]]); - } - - return null; - } - }); - } - - scopeInfo = scopeInfo.upper; - } - - /** - * Marks the label of a given node as used. - * @param {ASTNode} node A node to mark. This is a BreakStatement or - * ContinueStatement. - * @returns {void} - */ - function markAsUsed(node) { - if (!node.label) { - return; - } - - const label = node.label.name; - let info = scopeInfo; - - while (info) { - if (info.label === label) { - info.used = true; - break; - } - info = info.upper; - } - } - - return { - LabeledStatement: enterLabeledScope, - "LabeledStatement:exit": exitLabeledScope, - BreakStatement: markAsUsed, - ContinueStatement: markAsUsed - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-unused-vars.js b/tools/node_modules/eslint/lib/rules/no-unused-vars.js deleted file mode 100644 index 50dcab45fe2bb65e5afece01fcf763df7d3e03c3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-unused-vars.js +++ /dev/null @@ -1,647 +0,0 @@ -/** - * @fileoverview Rule to flag declared but unused variables - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Typedefs -//------------------------------------------------------------------------------ - -/** - * Bag of data used for formatting the `unusedVar` lint message. - * @typedef {Object} UnusedVarMessageData - * @property {string} varName The name of the unused var. - * @property {'defined'|'assigned a value'} action Description of the vars state. - * @property {string} additional Any additional info to be appended at the end. - */ - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow unused variables", - category: "Variables", - recommended: true, - url: "https://eslint.org/docs/rules/no-unused-vars" - }, - - schema: [ - { - oneOf: [ - { - enum: ["all", "local"] - }, - { - type: "object", - properties: { - vars: { - enum: ["all", "local"] - }, - varsIgnorePattern: { - type: "string" - }, - args: { - enum: ["all", "after-used", "none"] - }, - ignoreRestSiblings: { - type: "boolean" - }, - argsIgnorePattern: { - type: "string" - }, - caughtErrors: { - enum: ["all", "none"] - }, - caughtErrorsIgnorePattern: { - type: "string" - } - } - } - ] - } - ], - - messages: { - unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u; - - const config = { - vars: "all", - args: "after-used", - ignoreRestSiblings: false, - caughtErrors: "none" - }; - - const firstOption = context.options[0]; - - if (firstOption) { - if (typeof firstOption === "string") { - config.vars = firstOption; - } else { - config.vars = firstOption.vars || config.vars; - config.args = firstOption.args || config.args; - config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings; - config.caughtErrors = firstOption.caughtErrors || config.caughtErrors; - - if (firstOption.varsIgnorePattern) { - config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u"); - } - - if (firstOption.argsIgnorePattern) { - config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u"); - } - - if (firstOption.caughtErrorsIgnorePattern) { - config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u"); - } - } - } - - /** - * Generates the message data about the variable being defined and unused, - * including the ignore pattern if configured. - * @param {Variable} unusedVar eslint-scope variable object. - * @returns {UnusedVarMessageData} The message data to be used with this unused variable. - */ - function getDefinedMessageData(unusedVar) { - const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type; - let type; - let pattern; - - if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) { - type = "args"; - pattern = config.caughtErrorsIgnorePattern.toString(); - } else if (defType === "Parameter" && config.argsIgnorePattern) { - type = "args"; - pattern = config.argsIgnorePattern.toString(); - } else if (defType !== "Parameter" && config.varsIgnorePattern) { - type = "vars"; - pattern = config.varsIgnorePattern.toString(); - } - - const additional = type ? `. Allowed unused ${type} must match ${pattern}` : ""; - - return { - varName: unusedVar.name, - action: "defined", - additional - }; - } - - /** - * Generate the warning message about the variable being - * assigned and unused, including the ignore pattern if configured. - * @param {Variable} unusedVar eslint-scope variable object. - * @returns {UnusedVarMessageData} The message data to be used with this unused variable. - */ - function getAssignedMessageData(unusedVar) { - const additional = config.varsIgnorePattern ? `. Allowed unused vars must match ${config.varsIgnorePattern.toString()}` : ""; - - return { - varName: unusedVar.name, - action: "assigned a value", - additional - }; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const STATEMENT_TYPE = /(?:Statement|Declaration)$/u; - - /** - * Determines if a given variable is being exported from a module. - * @param {Variable} variable eslint-scope variable object. - * @returns {boolean} True if the variable is exported, false if not. - * @private - */ - function isExported(variable) { - - const definition = variable.defs[0]; - - if (definition) { - - let node = definition.node; - - if (node.type === "VariableDeclarator") { - node = node.parent; - } else if (definition.type === "Parameter") { - return false; - } - - return node.parent.type.indexOf("Export") === 0; - } - return false; - - } - - /** - * Determines if a variable has a sibling rest property - * @param {Variable} variable eslint-scope variable object. - * @returns {boolean} True if the variable is exported, false if not. - * @private - */ - function hasRestSpreadSibling(variable) { - if (config.ignoreRestSiblings) { - return variable.defs.some(def => { - const propertyNode = def.name.parent; - const patternNode = propertyNode.parent; - - return ( - propertyNode.type === "Property" && - patternNode.type === "ObjectPattern" && - REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type) - ); - }); - } - - return false; - } - - /** - * Determines if a reference is a read operation. - * @param {Reference} ref An eslint-scope Reference - * @returns {boolean} whether the given reference represents a read operation - * @private - */ - function isReadRef(ref) { - return ref.isRead(); - } - - /** - * Determine if an identifier is referencing an enclosing function name. - * @param {Reference} ref The reference to check. - * @param {ASTNode[]} nodes The candidate function nodes. - * @returns {boolean} True if it's a self-reference, false if not. - * @private - */ - function isSelfReference(ref, nodes) { - let scope = ref.from; - - while (scope) { - if (nodes.indexOf(scope.block) >= 0) { - return true; - } - - scope = scope.upper; - } - - return false; - } - - /** - * Gets a list of function definitions for a specified variable. - * @param {Variable} variable eslint-scope variable object. - * @returns {ASTNode[]} Function nodes. - * @private - */ - function getFunctionDefinitions(variable) { - const functionDefinitions = []; - - variable.defs.forEach(def => { - const { type, node } = def; - - // FunctionDeclarations - if (type === "FunctionName") { - functionDefinitions.push(node); - } - - // FunctionExpressions - if (type === "Variable" && node.init && - (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) { - functionDefinitions.push(node.init); - } - }); - return functionDefinitions; - } - - /** - * Checks the position of given nodes. - * @param {ASTNode} inner A node which is expected as inside. - * @param {ASTNode} outer A node which is expected as outside. - * @returns {boolean} `true` if the `inner` node exists in the `outer` node. - * @private - */ - function isInside(inner, outer) { - return ( - inner.range[0] >= outer.range[0] && - inner.range[1] <= outer.range[1] - ); - } - - /** - * If a given reference is left-hand side of an assignment, this gets - * the right-hand side node of the assignment. - * - * In the following cases, this returns null. - * - * - The reference is not the LHS of an assignment expression. - * - The reference is inside of a loop. - * - The reference is inside of a function scope which is different from - * the declaration. - * @param {eslint-scope.Reference} ref A reference to check. - * @param {ASTNode} prevRhsNode The previous RHS node. - * @returns {ASTNode|null} The RHS node or null. - * @private - */ - function getRhsNode(ref, prevRhsNode) { - const id = ref.identifier; - const parent = id.parent; - const grandparent = parent.parent; - const refScope = ref.from.variableScope; - const varScope = ref.resolved.scope.variableScope; - const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id); - - /* - * Inherits the previous node if this reference is in the node. - * This is for `a = a + a`-like code. - */ - if (prevRhsNode && isInside(id, prevRhsNode)) { - return prevRhsNode; - } - - if (parent.type === "AssignmentExpression" && - grandparent.type === "ExpressionStatement" && - id === parent.left && - !canBeUsedLater - ) { - return parent.right; - } - return null; - } - - /** - * Checks whether a given function node is stored to somewhere or not. - * If the function node is stored, the function can be used later. - * @param {ASTNode} funcNode A function node to check. - * @param {ASTNode} rhsNode The RHS node of the previous assignment. - * @returns {boolean} `true` if under the following conditions: - * - the funcNode is assigned to a variable. - * - the funcNode is bound as an argument of a function call. - * - the function is bound to a property and the object satisfies above conditions. - * @private - */ - function isStorableFunction(funcNode, rhsNode) { - let node = funcNode; - let parent = funcNode.parent; - - while (parent && isInside(parent, rhsNode)) { - switch (parent.type) { - case "SequenceExpression": - if (parent.expressions[parent.expressions.length - 1] !== node) { - return false; - } - break; - - case "CallExpression": - case "NewExpression": - return parent.callee !== node; - - case "AssignmentExpression": - case "TaggedTemplateExpression": - case "YieldExpression": - return true; - - default: - if (STATEMENT_TYPE.test(parent.type)) { - - /* - * If it encountered statements, this is a complex pattern. - * Since analyzing complex patterns is hard, this returns `true` to avoid false positive. - */ - return true; - } - } - - node = parent; - parent = parent.parent; - } - - return false; - } - - /** - * Checks whether a given Identifier node exists inside of a function node which can be used later. - * - * "can be used later" means: - * - the function is assigned to a variable. - * - the function is bound to a property and the object can be used later. - * - the function is bound as an argument of a function call. - * - * If a reference exists in a function which can be used later, the reference is read when the function is called. - * @param {ASTNode} id An Identifier node to check. - * @param {ASTNode} rhsNode The RHS node of the previous assignment. - * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later. - * @private - */ - function isInsideOfStorableFunction(id, rhsNode) { - const funcNode = astUtils.getUpperFunction(id); - - return ( - funcNode && - isInside(funcNode, rhsNode) && - isStorableFunction(funcNode, rhsNode) - ); - } - - /** - * Checks whether a given reference is a read to update itself or not. - * @param {eslint-scope.Reference} ref A reference to check. - * @param {ASTNode} rhsNode The RHS node of the previous assignment. - * @returns {boolean} The reference is a read to update itself. - * @private - */ - function isReadForItself(ref, rhsNode) { - const id = ref.identifier; - const parent = id.parent; - const grandparent = parent.parent; - - return ref.isRead() && ( - - // self update. e.g. `a += 1`, `a++` - (// in RHS of an assignment for itself. e.g. `a = a + 1` - (( - parent.type === "AssignmentExpression" && - grandparent.type === "ExpressionStatement" && - parent.left === id - ) || - ( - parent.type === "UpdateExpression" && - grandparent.type === "ExpressionStatement" - ) || rhsNode && - isInside(id, rhsNode) && - !isInsideOfStorableFunction(id, rhsNode))) - ); - } - - /** - * Determine if an identifier is used either in for-in loops. - * @param {Reference} ref The reference to check. - * @returns {boolean} whether reference is used in the for-in loops - * @private - */ - function isForInRef(ref) { - let target = ref.identifier.parent; - - - // "for (var ...) { return; }" - if (target.type === "VariableDeclarator") { - target = target.parent.parent; - } - - if (target.type !== "ForInStatement") { - return false; - } - - // "for (...) { return; }" - if (target.body.type === "BlockStatement") { - target = target.body.body[0]; - - // "for (...) return;" - } else { - target = target.body; - } - - // For empty loop body - if (!target) { - return false; - } - - return target.type === "ReturnStatement"; - } - - /** - * Determines if the variable is used. - * @param {Variable} variable The variable to check. - * @returns {boolean} True if the variable is used - * @private - */ - function isUsedVariable(variable) { - const functionNodes = getFunctionDefinitions(variable), - isFunctionDefinition = functionNodes.length > 0; - let rhsNode = null; - - return variable.references.some(ref => { - if (isForInRef(ref)) { - return true; - } - - const forItself = isReadForItself(ref, rhsNode); - - rhsNode = getRhsNode(ref, rhsNode); - - return ( - isReadRef(ref) && - !forItself && - !(isFunctionDefinition && isSelfReference(ref, functionNodes)) - ); - }); - } - - /** - * Checks whether the given variable is after the last used parameter. - * @param {eslint-scope.Variable} variable The variable to check. - * @returns {boolean} `true` if the variable is defined after the last - * used parameter. - */ - function isAfterLastUsedArg(variable) { - const def = variable.defs[0]; - const params = context.getDeclaredVariables(def.node); - const posteriorParams = params.slice(params.indexOf(variable) + 1); - - // If any used parameters occur after this parameter, do not report. - return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed); - } - - /** - * Gets an array of variables without read references. - * @param {Scope} scope an eslint-scope Scope object. - * @param {Variable[]} unusedVars an array that saving result. - * @returns {Variable[]} unused variables of the scope and descendant scopes. - * @private - */ - function collectUnusedVariables(scope, unusedVars) { - const variables = scope.variables; - const childScopes = scope.childScopes; - let i, l; - - if (scope.type !== "global" || config.vars === "all") { - for (i = 0, l = variables.length; i < l; ++i) { - const variable = variables[i]; - - // skip a variable of class itself name in the class scope - if (scope.type === "class" && scope.block.id === variable.identifiers[0]) { - continue; - } - - // skip function expression names and variables marked with markVariableAsUsed() - if (scope.functionExpressionScope || variable.eslintUsed) { - continue; - } - - // skip implicit "arguments" variable - if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) { - continue; - } - - // explicit global variables don't have definitions. - const def = variable.defs[0]; - - if (def) { - const type = def.type; - - // skip catch variables - if (type === "CatchClause") { - if (config.caughtErrors === "none") { - continue; - } - - // skip ignored parameters - if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) { - continue; - } - } - - if (type === "Parameter") { - - // skip any setter argument - if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") { - continue; - } - - // if "args" option is "none", skip any parameter - if (config.args === "none") { - continue; - } - - // skip ignored parameters - if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) { - continue; - } - - // if "args" option is "after-used", skip used variables - if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) { - continue; - } - } else { - - // skip ignored variables - if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) { - continue; - } - } - } - - if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) { - unusedVars.push(variable); - } - } - } - - for (i = 0, l = childScopes.length; i < l; ++i) { - collectUnusedVariables(childScopes[i], unusedVars); - } - - return unusedVars; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - "Program:exit"(programNode) { - const unusedVars = collectUnusedVariables(context.getScope(), []); - - for (let i = 0, l = unusedVars.length; i < l; ++i) { - const unusedVar = unusedVars[i]; - - // Report the first declaration. - if (unusedVar.defs.length > 0) { - context.report({ - node: unusedVar.references.length ? unusedVar.references[ - unusedVar.references.length - 1 - ].identifier : unusedVar.identifiers[0], - messageId: "unusedVar", - data: unusedVar.references.some(ref => ref.isWrite()) - ? getAssignedMessageData(unusedVar) - : getDefinedMessageData(unusedVar) - }); - - // If there are no regular declaration, report the first `/*globals*/` comment directive. - } else if (unusedVar.eslintExplicitGlobalComments) { - const directiveComment = unusedVar.eslintExplicitGlobalComments[0]; - - context.report({ - node: programNode, - loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name), - messageId: "unusedVar", - data: getDefinedMessageData(unusedVar) - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-use-before-define.js b/tools/node_modules/eslint/lib/rules/no-use-before-define.js deleted file mode 100644 index c7300567ede0b7856495d83068b40deec22ad3c2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-use-before-define.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * @fileoverview Rule to flag use of variables before they are defined - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u; -const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u; - -/** - * Parses a given value as options. - * @param {any} options A value to parse. - * @returns {Object} The parsed options. - */ -function parseOptions(options) { - let functions = true; - let classes = true; - let variables = true; - - if (typeof options === "string") { - functions = (options !== "nofunc"); - } else if (typeof options === "object" && options !== null) { - functions = options.functions !== false; - classes = options.classes !== false; - variables = options.variables !== false; - } - - return { functions, classes, variables }; -} - -/** - * Checks whether or not a given variable is a function declaration. - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is a function declaration. - */ -function isFunction(variable) { - return variable.defs[0].type === "FunctionName"; -} - -/** - * Checks whether or not a given variable is a class declaration in an upper function scope. - * @param {eslint-scope.Variable} variable A variable to check. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the variable is a class declaration. - */ -function isOuterClass(variable, reference) { - return ( - variable.defs[0].type === "ClassName" && - variable.scope.variableScope !== reference.from.variableScope - ); -} - -/** - * Checks whether or not a given variable is a variable declaration in an upper function scope. - * @param {eslint-scope.Variable} variable A variable to check. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the variable is a variable declaration. - */ -function isOuterVariable(variable, reference) { - return ( - variable.defs[0].type === "Variable" && - variable.scope.variableScope !== reference.from.variableScope - ); -} - -/** - * Checks whether or not a given location is inside of the range of a given node. - * @param {ASTNode} node An node to check. - * @param {number} location A location to check. - * @returns {boolean} `true` if the location is inside of the range of the node. - */ -function isInRange(node, location) { - return node && node.range[0] <= location && location <= node.range[1]; -} - -/** - * Checks whether or not a given reference is inside of the initializers of a given variable. - * - * This returns `true` in the following cases: - * - * var a = a - * var [a = a] = list - * var {a = a} = obj - * for (var a in a) {} - * for (var a of a) {} - * @param {Variable} variable A variable to check. - * @param {Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is inside of the initializers. - */ -function isInInitializer(variable, reference) { - if (variable.scope !== reference.from) { - return false; - } - - let node = variable.identifiers[0].parent; - const location = reference.identifier.range[1]; - - while (node) { - if (node.type === "VariableDeclarator") { - if (isInRange(node.init, location)) { - return true; - } - if (FOR_IN_OF_TYPE.test(node.parent.parent.type) && - isInRange(node.parent.parent.right, location) - ) { - return true; - } - break; - } else if (node.type === "AssignmentPattern") { - if (isInRange(node.right, location)) { - return true; - } - } else if (SENTINEL_TYPE.test(node.type)) { - break; - } - - node = node.parent; - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow the use of variables before they are defined", - category: "Variables", - recommended: false, - url: "https://eslint.org/docs/rules/no-use-before-define" - }, - - schema: [ - { - oneOf: [ - { - enum: ["nofunc"] - }, - { - type: "object", - properties: { - functions: { type: "boolean" }, - classes: { type: "boolean" }, - variables: { type: "boolean" } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - usedBeforeDefined: "'{{name}}' was used before it was defined." - } - }, - - create(context) { - const options = parseOptions(context.options[0]); - - /** - * Determines whether a given use-before-define case should be reported according to the options. - * @param {eslint-scope.Variable} variable The variable that gets used before being defined - * @param {eslint-scope.Reference} reference The reference to the variable - * @returns {boolean} `true` if the usage should be reported - */ - function isForbidden(variable, reference) { - if (isFunction(variable)) { - return options.functions; - } - if (isOuterClass(variable, reference)) { - return options.classes; - } - if (isOuterVariable(variable, reference)) { - return options.variables; - } - return true; - } - - /** - * Finds and validates all variables in a given scope. - * @param {Scope} scope The scope object. - * @returns {void} - * @private - */ - function findVariablesInScope(scope) { - scope.references.forEach(reference => { - const variable = reference.resolved; - - /* - * Skips when the reference is: - * - initialization's. - * - referring to an undefined variable. - * - referring to a global environment variable (there're no identifiers). - * - located preceded by the variable (except in initializers). - * - allowed by options. - */ - if (reference.init || - !variable || - variable.identifiers.length === 0 || - (variable.identifiers[0].range[1] < reference.identifier.range[1] && !isInInitializer(variable, reference)) || - !isForbidden(variable, reference) - ) { - return; - } - - // Reports. - context.report({ - node: reference.identifier, - messageId: "usedBeforeDefined", - data: reference.identifier - }); - }); - - scope.childScopes.forEach(findVariablesInScope); - } - - return { - Program() { - findVariablesInScope(context.getScope()); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-backreference.js b/tools/node_modules/eslint/lib/rules/no-useless-backreference.js deleted file mode 100644 index 958e3d5dd4e4d5eafc8c1af7039d7fa784b95118..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-backreference.js +++ /dev/null @@ -1,193 +0,0 @@ -/** - * @fileoverview Rule to disallow useless backreferences in regular expressions - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { CALL, CONSTRUCT, ReferenceTracker, getStringIfConstant } = require("eslint-utils"); -const { RegExpParser, visitRegExpAST } = require("regexpp"); -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const parser = new RegExpParser(); - -/** - * Finds the path from the given `regexpp` AST node to the root node. - * @param {regexpp.Node} node Node. - * @returns {regexpp.Node[]} Array that starts with the given node and ends with the root node. - */ -function getPathToRoot(node) { - const path = []; - let current = node; - - do { - path.push(current); - current = current.parent; - } while (current); - - return path; -} - -/** - * Determines whether the given `regexpp` AST node is a lookaround node. - * @param {regexpp.Node} node Node. - * @returns {boolean} `true` if it is a lookaround node. - */ -function isLookaround(node) { - return node.type === "Assertion" && - (node.kind === "lookahead" || node.kind === "lookbehind"); -} - -/** - * Determines whether the given `regexpp` AST node is a negative lookaround node. - * @param {regexpp.Node} node Node. - * @returns {boolean} `true` if it is a negative lookaround node. - */ -function isNegativeLookaround(node) { - return isLookaround(node) && node.negate; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow useless backreferences in regular expressions", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-backreference" - }, - - schema: [], - - messages: { - nested: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' from within that group.", - forward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears later in the pattern.", - backward: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which appears before in the same lookbehind.", - disjunctive: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in another alternative.", - intoNegativeLookaround: "Backreference '{{ bref }}' will be ignored. It references group '{{ group }}' which is in a negative lookaround." - } - }, - - create(context) { - - /** - * Checks and reports useless backreferences in the given regular expression. - * @param {ASTNode} node Node that represents regular expression. A regex literal or RegExp constructor call. - * @param {string} pattern Regular expression pattern. - * @param {string} flags Regular expression flags. - * @returns {void} - */ - function checkRegex(node, pattern, flags) { - let regExpAST; - - try { - regExpAST = parser.parsePattern(pattern, 0, pattern.length, flags.includes("u")); - } catch { - - // Ignore regular expressions with syntax errors - return; - } - - visitRegExpAST(regExpAST, { - onBackreferenceEnter(bref) { - const group = bref.resolved, - brefPath = getPathToRoot(bref), - groupPath = getPathToRoot(group); - let messageId = null; - - if (brefPath.includes(group)) { - - // group is bref's ancestor => bref is nested ('nested reference') => group hasn't matched yet when bref starts to match. - messageId = "nested"; - } else { - - // Start from the root to find the lowest common ancestor. - let i = brefPath.length - 1, - j = groupPath.length - 1; - - do { - i--; - j--; - } while (brefPath[i] === groupPath[j]); - - const indexOfLowestCommonAncestor = j + 1, - groupCut = groupPath.slice(0, indexOfLowestCommonAncestor), - commonPath = groupPath.slice(indexOfLowestCommonAncestor), - lowestCommonLookaround = commonPath.find(isLookaround), - isMatchingBackward = lowestCommonLookaround && lowestCommonLookaround.kind === "lookbehind"; - - if (!isMatchingBackward && bref.end <= group.start) { - - // bref is left, group is right ('forward reference') => group hasn't matched yet when bref starts to match. - messageId = "forward"; - } else if (isMatchingBackward && group.end <= bref.start) { - - // the opposite of the previous when the regex is matching backward in a lookbehind context. - messageId = "backward"; - } else if (lodash.last(groupCut).type === "Alternative") { - - // group's and bref's ancestor nodes below the lowest common ancestor are sibling alternatives => they're disjunctive. - messageId = "disjunctive"; - } else if (groupCut.some(isNegativeLookaround)) { - - // group is in a negative lookaround which isn't bref's ancestor => group has already failed when bref starts to match. - messageId = "intoNegativeLookaround"; - } - } - - if (messageId) { - context.report({ - node, - messageId, - data: { - bref: bref.raw, - group: group.raw - } - }); - } - } - }); - } - - return { - "Literal[regex]"(node) { - const { pattern, flags } = node.regex; - - checkRegex(node, pattern, flags); - }, - Program() { - const scope = context.getScope(), - tracker = new ReferenceTracker(scope), - traceMap = { - RegExp: { - [CALL]: true, - [CONSTRUCT]: true - } - }; - - for (const { node } of tracker.iterateGlobalReferences(traceMap)) { - const [patternNode, flagsNode] = node.arguments, - pattern = getStringIfConstant(patternNode, scope), - flags = getStringIfConstant(flagsNode, scope); - - if (typeof pattern === "string") { - checkRegex(node, pattern, flags || ""); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-call.js b/tools/node_modules/eslint/lib/rules/no-useless-call.js deleted file mode 100644 index b1382a2fa28034588e48b77b136b81a617275ef7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-call.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @fileoverview A rule to disallow unnecessary `.call()` and `.apply()`. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a node is a `.call()`/`.apply()`. - * @param {ASTNode} node A CallExpression node to check. - * @returns {boolean} Whether or not the node is a `.call()`/`.apply()`. - */ -function isCallOrNonVariadicApply(node) { - const callee = astUtils.skipChainExpression(node.callee); - - return ( - callee.type === "MemberExpression" && - callee.property.type === "Identifier" && - callee.computed === false && - ( - (callee.property.name === "call" && node.arguments.length >= 1) || - (callee.property.name === "apply" && node.arguments.length === 2 && node.arguments[1].type === "ArrayExpression") - ) - ); -} - - -/** - * Checks whether or not `thisArg` is not changed by `.call()`/`.apply()`. - * @param {ASTNode|null} expectedThis The node that is the owner of the applied function. - * @param {ASTNode} thisArg The node that is given to the first argument of the `.call()`/`.apply()`. - * @param {SourceCode} sourceCode The ESLint source code object. - * @returns {boolean} Whether or not `thisArg` is not changed by `.call()`/`.apply()`. - */ -function isValidThisArg(expectedThis, thisArg, sourceCode) { - if (!expectedThis) { - return astUtils.isNullOrUndefined(thisArg); - } - return astUtils.equalTokens(expectedThis, thisArg, sourceCode); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary calls to `.call()` and `.apply()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-call" - }, - - schema: [], - - messages: { - unnecessaryCall: "Unnecessary '.{{name}}()'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - CallExpression(node) { - if (!isCallOrNonVariadicApply(node)) { - return; - } - - const callee = astUtils.skipChainExpression(node.callee); - const applied = astUtils.skipChainExpression(callee.object); - const expectedThis = (applied.type === "MemberExpression") ? applied.object : null; - const thisArg = node.arguments[0]; - - if (isValidThisArg(expectedThis, thisArg, sourceCode)) { - context.report({ node, messageId: "unnecessaryCall", data: { name: callee.property.name } }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-catch.js b/tools/node_modules/eslint/lib/rules/no-useless-catch.js deleted file mode 100644 index f303c272948489943108aaded11e19fa07918e1a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-catch.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Reports useless `catch` clauses that just rethrow their error. - * @author Teddy Katz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary `catch` clauses", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-useless-catch" - }, - - schema: [], - - messages: { - unnecessaryCatchClause: "Unnecessary catch clause.", - unnecessaryCatch: "Unnecessary try/catch wrapper." - } - }, - - create(context) { - return { - CatchClause(node) { - if ( - node.param && - node.param.type === "Identifier" && - node.body.body.length && - node.body.body[0].type === "ThrowStatement" && - node.body.body[0].argument.type === "Identifier" && - node.body.body[0].argument.name === node.param.name - ) { - if (node.parent.finalizer) { - context.report({ - node, - messageId: "unnecessaryCatchClause" - }); - } else { - context.report({ - node: node.parent, - messageId: "unnecessaryCatch" - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js b/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js deleted file mode 100644 index e0505a318efaae74b3d048ee54f9de46ef8713b9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-computed-key.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @fileoverview Rule to disallow unnecessary computed property keys in object literals - * @author Burak Yigit Kaya - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary computed property keys in objects and classes", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-computed-key" - }, - - schema: [{ - type: "object", - properties: { - enforceForClassMembers: { - type: "boolean", - default: false - } - }, - additionalProperties: false - }], - fixable: "code", - - messages: { - unnecessarilyComputedProperty: "Unnecessarily computed property [{{property}}] found." - } - }, - create(context) { - const sourceCode = context.getSourceCode(); - const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers; - - /** - * Reports a given node if it violated this rule. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function check(node) { - if (!node.computed) { - return; - } - - const key = node.key, - nodeType = typeof key.value; - - let allowedKey; - - if (node.type === "MethodDefinition") { - allowedKey = node.static ? "prototype" : "constructor"; - } else { - allowedKey = "__proto__"; - } - - if (key.type === "Literal" && (nodeType === "string" || nodeType === "number") && key.value !== allowedKey) { - context.report({ - node, - messageId: "unnecessarilyComputedProperty", - data: { property: sourceCode.getText(key) }, - fix(fixer) { - const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken); - const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken); - - // If there are comments between the brackets and the property name, don't do a fix. - if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) { - return null; - } - - const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket); - - // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} }) - const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] && - !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key)); - - const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw; - - return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey); - } - }); - } - } - - return { - Property: check, - MethodDefinition: enforceForClassMembers ? check : lodash.noop - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-concat.js b/tools/node_modules/eslint/lib/rules/no-useless-concat.js deleted file mode 100644 index cfc60c8fb51a240b3a9a8984ed71256ecced2deb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-concat.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @fileoverview disallow unnecessary concatenation of template strings - * @author Henry Zhu - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a concatenation. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a concatenation. - */ -function isConcatenation(node) { - return node.type === "BinaryExpression" && node.operator === "+"; -} - -/** - * Checks if the given token is a `+` token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a `+` token. - */ -function isConcatOperatorToken(token) { - return token.value === "+" && token.type === "Punctuator"; -} - -/** - * Get's the right most node on the left side of a BinaryExpression with + operator. - * @param {ASTNode} node A BinaryExpression node to check. - * @returns {ASTNode} node - */ -function getLeft(node) { - let left = node.left; - - while (isConcatenation(left)) { - left = left.right; - } - return left; -} - -/** - * Get's the left most node on the right side of a BinaryExpression with + operator. - * @param {ASTNode} node A BinaryExpression node to check. - * @returns {ASTNode} node - */ -function getRight(node) { - let right = node.right; - - while (isConcatenation(right)) { - right = right.left; - } - return right; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary concatenation of literals or template literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-concat" - }, - - schema: [], - - messages: { - unexpectedConcat: "Unexpected string concatenation of literals." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - BinaryExpression(node) { - - // check if not concatenation - if (node.operator !== "+") { - return; - } - - // account for the `foo + "a" + "b"` case - const left = getLeft(node); - const right = getRight(node); - - if (astUtils.isStringLiteral(left) && - astUtils.isStringLiteral(right) && - astUtils.isTokenOnSameLine(left, right) - ) { - const operatorToken = sourceCode.getFirstTokenBetween(left, right, isConcatOperatorToken); - - context.report({ - node, - loc: operatorToken.loc, - messageId: "unexpectedConcat" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-constructor.js b/tools/node_modules/eslint/lib/rules/no-useless-constructor.js deleted file mode 100644 index 4c34aeda71593769f9a41fe249604850c2d8f354..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-constructor.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * @fileoverview Rule to flag the use of redundant constructors in classes. - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether a given array of statements is a single call of `super`. - * @param {ASTNode[]} body An array of statements to check. - * @returns {boolean} `true` if the body is a single call of `super`. - */ -function isSingleSuperCall(body) { - return ( - body.length === 1 && - body[0].type === "ExpressionStatement" && - body[0].expression.type === "CallExpression" && - body[0].expression.callee.type === "Super" - ); -} - -/** - * Checks whether a given node is a pattern which doesn't have any side effects. - * Default parameters and Destructuring parameters can have side effects. - * @param {ASTNode} node A pattern node. - * @returns {boolean} `true` if the node doesn't have any side effects. - */ -function isSimple(node) { - return node.type === "Identifier" || node.type === "RestElement"; -} - -/** - * Checks whether a given array of expressions is `...arguments` or not. - * `super(...arguments)` passes all arguments through. - * @param {ASTNode[]} superArgs An array of expressions to check. - * @returns {boolean} `true` if the superArgs is `...arguments`. - */ -function isSpreadArguments(superArgs) { - return ( - superArgs.length === 1 && - superArgs[0].type === "SpreadElement" && - superArgs[0].argument.type === "Identifier" && - superArgs[0].argument.name === "arguments" - ); -} - -/** - * Checks whether given 2 nodes are identifiers which have the same name or not. - * @param {ASTNode} ctorParam A node to check. - * @param {ASTNode} superArg A node to check. - * @returns {boolean} `true` if the nodes are identifiers which have the same - * name. - */ -function isValidIdentifierPair(ctorParam, superArg) { - return ( - ctorParam.type === "Identifier" && - superArg.type === "Identifier" && - ctorParam.name === superArg.name - ); -} - -/** - * Checks whether given 2 nodes are a rest/spread pair which has the same values. - * @param {ASTNode} ctorParam A node to check. - * @param {ASTNode} superArg A node to check. - * @returns {boolean} `true` if the nodes are a rest/spread pair which has the - * same values. - */ -function isValidRestSpreadPair(ctorParam, superArg) { - return ( - ctorParam.type === "RestElement" && - superArg.type === "SpreadElement" && - isValidIdentifierPair(ctorParam.argument, superArg.argument) - ); -} - -/** - * Checks whether given 2 nodes have the same value or not. - * @param {ASTNode} ctorParam A node to check. - * @param {ASTNode} superArg A node to check. - * @returns {boolean} `true` if the nodes have the same value or not. - */ -function isValidPair(ctorParam, superArg) { - return ( - isValidIdentifierPair(ctorParam, superArg) || - isValidRestSpreadPair(ctorParam, superArg) - ); -} - -/** - * Checks whether the parameters of a constructor and the arguments of `super()` - * have the same values or not. - * @param {ASTNode} ctorParams The parameters of a constructor to check. - * @param {ASTNode} superArgs The arguments of `super()` to check. - * @returns {boolean} `true` if those have the same values. - */ -function isPassingThrough(ctorParams, superArgs) { - if (ctorParams.length !== superArgs.length) { - return false; - } - - for (let i = 0; i < ctorParams.length; ++i) { - if (!isValidPair(ctorParams[i], superArgs[i])) { - return false; - } - } - - return true; -} - -/** - * Checks whether the constructor body is a redundant super call. - * @param {Array} body constructor body content. - * @param {Array} ctorParams The params to check against super call. - * @returns {boolean} true if the constructor body is redundant - */ -function isRedundantSuperCall(body, ctorParams) { - return ( - isSingleSuperCall(body) && - ctorParams.every(isSimple) && - ( - isSpreadArguments(body[0].expression.arguments) || - isPassingThrough(ctorParams, body[0].expression.arguments) - ) - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary constructors", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-constructor" - }, - - schema: [], - - messages: { - noUselessConstructor: "Useless constructor." - } - }, - - create(context) { - - /** - * Checks whether a node is a redundant constructor - * @param {ASTNode} node node to check - * @returns {void} - */ - function checkForConstructor(node) { - if (node.kind !== "constructor") { - return; - } - - const body = node.value.body.body; - const ctorParams = node.value.params; - const superClass = node.parent.parent.superClass; - - if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) { - context.report({ - node, - messageId: "noUselessConstructor" - }); - } - } - - return { - MethodDefinition: checkForConstructor - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-escape.js b/tools/node_modules/eslint/lib/rules/no-useless-escape.js deleted file mode 100644 index 8057e44ddab46327b56f8e52e8761f5a4a98d7ae..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-escape.js +++ /dev/null @@ -1,252 +0,0 @@ -/** - * @fileoverview Look for useless escapes in strings and regexes - * @author Onur Temizkan - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Returns the union of two sets. - * @param {Set} setA The first set - * @param {Set} setB The second set - * @returns {Set} The union of the two sets - */ -function union(setA, setB) { - return new Set(function *() { - yield* setA; - yield* setB; - }()); -} - -const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS); -const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]"); -const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()Bk")); - -/** - * Parses a regular expression into a list of characters with character class info. - * @param {string} regExpText The raw text used to create the regular expression - * @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class. - * @example - * - * parseRegExp('a\\b[cd-]') - * - * returns: - * [ - * {text: 'a', index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false}, - * {text: 'b', index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false}, - * {text: 'c', index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false}, - * {text: 'd', index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false}, - * {text: '-', index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false} - * ] - */ -function parseRegExp(regExpText) { - const charList = []; - - regExpText.split("").reduce((state, char, index) => { - if (!state.escapeNextChar) { - if (char === "\\") { - return Object.assign(state, { escapeNextChar: true }); - } - if (char === "[" && !state.inCharClass) { - return Object.assign(state, { inCharClass: true, startingCharClass: true }); - } - if (char === "]" && state.inCharClass) { - if (charList.length && charList[charList.length - 1].inCharClass) { - charList[charList.length - 1].endsCharClass = true; - } - return Object.assign(state, { inCharClass: false, startingCharClass: false }); - } - } - charList.push({ - text: char, - index, - escaped: state.escapeNextChar, - inCharClass: state.inCharClass, - startsCharClass: state.startingCharClass, - endsCharClass: false - }); - return Object.assign(state, { escapeNextChar: false, startingCharClass: false }); - }, { escapeNextChar: false, inCharClass: false, startingCharClass: false }); - - return charList; -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow unnecessary escape characters", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-useless-escape", - suggestion: true - }, - - messages: { - unnecessaryEscape: "Unnecessary escape character: \\{{character}}.", - removeEscape: "Remove the `\\`. This maintains the current functionality.", - escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character." - }, - - schema: [] - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Reports a node - * @param {ASTNode} node The node to report - * @param {number} startOffset The backslash's offset from the start of the node - * @param {string} character The uselessly escaped character (not including the backslash) - * @returns {void} - */ - function report(node, startOffset, character) { - const start = sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset); - const rangeStart = sourceCode.getIndexFromLoc(node.loc.start) + startOffset; - const range = [rangeStart, rangeStart + 1]; - - context.report({ - node, - loc: { - start, - end: { line: start.line, column: start.column + 1 } - }, - messageId: "unnecessaryEscape", - data: { character }, - suggest: [ - { - messageId: "removeEscape", - fix(fixer) { - return fixer.removeRange(range); - } - }, - { - messageId: "escapeBackslash", - fix(fixer) { - return fixer.insertTextBeforeRange(range, "\\"); - } - } - ] - }); - } - - /** - * Checks if the escape character in given string slice is unnecessary. - * @private - * @param {ASTNode} node node to validate. - * @param {string} match string slice to validate. - * @returns {void} - */ - function validateString(node, match) { - const isTemplateElement = node.type === "TemplateElement"; - const escapedChar = match[0][1]; - let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar); - let isQuoteEscape; - - if (isTemplateElement) { - isQuoteEscape = escapedChar === "`"; - - if (escapedChar === "$") { - - // Warn if `\$` is not followed by `{` - isUnnecessaryEscape = match.input[match.index + 2] !== "{"; - } else if (escapedChar === "{") { - - /* - * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping - * is necessary and the rule should not warn. If preceded by `/$`, the rule - * will warn for the `/$` instead, as it is the first unnecessarily escaped character. - */ - isUnnecessaryEscape = match.input[match.index - 1] !== "$"; - } - } else { - isQuoteEscape = escapedChar === node.raw[0]; - } - - if (isUnnecessaryEscape && !isQuoteEscape) { - report(node, match.index + 1, match[0].slice(1)); - } - } - - /** - * Checks if a node has an escape. - * @param {ASTNode} node node to check. - * @returns {void} - */ - function check(node) { - const isTemplateElement = node.type === "TemplateElement"; - - if ( - isTemplateElement && - node.parent && - node.parent.parent && - node.parent.parent.type === "TaggedTemplateExpression" && - node.parent === node.parent.parent.quasi - ) { - - // Don't report tagged template literals, because the backslash character is accessible to the tag function. - return; - } - - if (typeof node.value === "string" || isTemplateElement) { - - /* - * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/. - * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25. - */ - if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") { - return; - } - - const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1); - const pattern = /\\[^\d]/gu; - let match; - - while ((match = pattern.exec(value))) { - validateString(node, match); - } - } else if (node.regex) { - parseRegExp(node.regex.pattern) - - /* - * The '-' character is a special case, because it's only valid to escape it if it's in a character - * class, and is not at either edge of the character class. To account for this, don't consider '-' - * characters to be valid in general, and filter out '-' characters that appear in the middle of a - * character class. - */ - .filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass)) - - /* - * The '^' character is also a special case; it must always be escaped outside of character classes, but - * it only needs to be escaped in character classes if it's at the beginning of the character class. To - * account for this, consider it to be a valid escape character outside of character classes, and filter - * out '^' characters that appear at the start of a character class. - */ - .filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass)) - - // Filter out characters that aren't escaped. - .filter(charInfo => charInfo.escaped) - - // Filter out characters that are valid to escape, based on their position in the regular expression. - .filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text)) - - // Report all the remaining characters. - .forEach(charInfo => report(node, charInfo.index, charInfo.text)); - } - - } - - return { - Literal: check, - TemplateElement: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-rename.js b/tools/node_modules/eslint/lib/rules/no-useless-rename.js deleted file mode 100644 index fa88f37f50b79c108784b989d25224c043d00d62..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-rename.js +++ /dev/null @@ -1,168 +0,0 @@ -/** - * @fileoverview Disallow renaming import, export, and destructured assignments to the same name. - * @author Kai Cataldo - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow renaming import, export, and destructured assignments to the same name", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-rename" - }, - - fixable: "code", - - schema: [ - { - type: "object", - properties: { - ignoreDestructuring: { type: "boolean", default: false }, - ignoreImport: { type: "boolean", default: false }, - ignoreExport: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - - messages: { - unnecessarilyRenamed: "{{type}} {{name}} unnecessarily renamed." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(), - options = context.options[0] || {}, - ignoreDestructuring = options.ignoreDestructuring === true, - ignoreImport = options.ignoreImport === true, - ignoreExport = options.ignoreExport === true; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports error for unnecessarily renamed assignments - * @param {ASTNode} node node to report - * @param {ASTNode} initial node with initial name value - * @param {ASTNode} result node with new name value - * @param {string} type the type of the offending node - * @returns {void} - */ - function reportError(node, initial, result, type) { - const name = initial.type === "Identifier" ? initial.name : initial.value; - - return context.report({ - node, - messageId: "unnecessarilyRenamed", - data: { - name, - type - }, - fix(fixer) { - if (sourceCode.commentsExistBetween(initial, result)) { - return null; - } - - const replacementText = result.type === "AssignmentPattern" - ? sourceCode.getText(result) - : name; - - return fixer.replaceTextRange([ - initial.range[0], - result.range[1] - ], replacementText); - } - }); - } - - /** - * Checks whether a destructured assignment is unnecessarily renamed - * @param {ASTNode} node node to check - * @returns {void} - */ - function checkDestructured(node) { - if (ignoreDestructuring) { - return; - } - - for (const property of node.properties) { - - /* - * TODO: Remove after babel-eslint removes ExperimentalRestProperty - * https://github.com/eslint/eslint/issues/12335 - */ - if (property.type === "ExperimentalRestProperty") { - continue; - } - - /** - * Properties using shorthand syntax and rest elements can not be renamed. - * If the property is computed, we have no idea if a rename is useless or not. - */ - if (property.shorthand || property.type === "RestElement" || property.computed) { - continue; - } - - const key = (property.key.type === "Identifier" && property.key.name) || (property.key.type === "Literal" && property.key.value); - const renamedKey = property.value.type === "AssignmentPattern" ? property.value.left.name : property.value.name; - - if (key === renamedKey) { - reportError(property, property.key, property.value, "Destructuring assignment"); - } - } - } - - /** - * Checks whether an import is unnecessarily renamed - * @param {ASTNode} node node to check - * @returns {void} - */ - function checkImport(node) { - if (ignoreImport) { - return; - } - - if (node.imported.name === node.local.name && - node.imported.range[0] !== node.local.range[0]) { - reportError(node, node.imported, node.local, "Import"); - } - } - - /** - * Checks whether an export is unnecessarily renamed - * @param {ASTNode} node node to check - * @returns {void} - */ - function checkExport(node) { - if (ignoreExport) { - return; - } - - if (node.local.name === node.exported.name && - node.local.range[0] !== node.exported.range[0]) { - reportError(node, node.local, node.exported, "Export"); - } - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ObjectPattern: checkDestructured, - ImportSpecifier: checkImport, - ExportSpecifier: checkExport - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-useless-return.js b/tools/node_modules/eslint/lib/rules/no-useless-return.js deleted file mode 100644 index 111cb21015fb8100dbfd65537524bb816a665b4a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-useless-return.js +++ /dev/null @@ -1,305 +0,0 @@ -/** - * @fileoverview Disallow redundant return statements - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"), - FixTracker = require("./utils/fix-tracker"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Removes the given element from the array. - * @param {Array} array The source array to remove. - * @param {any} element The target item to remove. - * @returns {void} - */ -function remove(array, element) { - const index = array.indexOf(element); - - if (index !== -1) { - array.splice(index, 1); - } -} - -/** - * Checks whether it can remove the given return statement or not. - * @param {ASTNode} node The return statement node to check. - * @returns {boolean} `true` if the node is removable. - */ -function isRemovable(node) { - return astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type); -} - -/** - * Checks whether the given return statement is in a `finally` block or not. - * @param {ASTNode} node The return statement node to check. - * @returns {boolean} `true` if the node is in a `finally` block. - */ -function isInFinally(node) { - for ( - let currentNode = node; - currentNode && currentNode.parent && !astUtils.isFunction(currentNode); - currentNode = currentNode.parent - ) { - if (currentNode.parent.type === "TryStatement" && currentNode.parent.finalizer === currentNode) { - return true; - } - } - - return false; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow redundant return statements", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-useless-return" - }, - - fixable: "code", - schema: [], - - messages: { - unnecessaryReturn: "Unnecessary return statement." - } - }, - - create(context) { - const segmentInfoMap = new WeakMap(); - const usedUnreachableSegments = new WeakSet(); - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Checks whether the given segment is terminated by a return statement or not. - * @param {CodePathSegment} segment The segment to check. - * @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. - */ - function isReturned(segment) { - const info = segmentInfoMap.get(segment); - - return !info || info.returned; - } - - /** - * Collects useless return statements from the given previous segments. - * - * A previous segment may be an unreachable segment. - * In that case, the information object of the unreachable segment is not - * initialized because `onCodePathSegmentStart` event is not notified for - * unreachable segments. - * This goes to the previous segments of the unreachable segment recursively - * if the unreachable segment was generated by a return statement. Otherwise, - * this ignores the unreachable segment. - * - * This behavior would simulate code paths for the case that the return - * statement does not exist. - * @param {ASTNode[]} uselessReturns The collected return statements. - * @param {CodePathSegment[]} prevSegments The previous segments to traverse. - * @param {WeakSet} [providedTraversedSegments] A set of segments that have already been traversed in this call - * @returns {ASTNode[]} `uselessReturns`. - */ - function getUselessReturns(uselessReturns, prevSegments, providedTraversedSegments) { - const traversedSegments = providedTraversedSegments || new WeakSet(); - - for (const segment of prevSegments) { - if (!segment.reachable) { - if (!traversedSegments.has(segment)) { - traversedSegments.add(segment); - getUselessReturns( - uselessReturns, - segment.allPrevSegments.filter(isReturned), - traversedSegments - ); - } - continue; - } - - uselessReturns.push(...segmentInfoMap.get(segment).uselessReturns); - } - - return uselessReturns; - } - - /** - * Removes the return statements on the given segment from the useless return - * statement list. - * - * This segment may be an unreachable segment. - * In that case, the information object of the unreachable segment is not - * initialized because `onCodePathSegmentStart` event is not notified for - * unreachable segments. - * This goes to the previous segments of the unreachable segment recursively - * if the unreachable segment was generated by a return statement. Otherwise, - * this ignores the unreachable segment. - * - * This behavior would simulate code paths for the case that the return - * statement does not exist. - * @param {CodePathSegment} segment The segment to get return statements. - * @returns {void} - */ - function markReturnStatementsOnSegmentAsUsed(segment) { - if (!segment.reachable) { - usedUnreachableSegments.add(segment); - segment.allPrevSegments - .filter(isReturned) - .filter(prevSegment => !usedUnreachableSegments.has(prevSegment)) - .forEach(markReturnStatementsOnSegmentAsUsed); - return; - } - - const info = segmentInfoMap.get(segment); - - for (const node of info.uselessReturns) { - remove(scopeInfo.uselessReturns, node); - } - info.uselessReturns = []; - } - - /** - * Removes the return statements on the current segments from the useless - * return statement list. - * - * This function will be called at every statement except FunctionDeclaration, - * BlockStatement, and BreakStatement. - * - * - FunctionDeclarations are always executed whether it's returned or not. - * - BlockStatements do nothing. - * - BreakStatements go the next merely. - * @returns {void} - */ - function markReturnStatementsOnCurrentSegmentsAsUsed() { - scopeInfo - .codePath - .currentSegments - .forEach(markReturnStatementsOnSegmentAsUsed); - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - - // Makes and pushs a new scope information. - onCodePathStart(codePath) { - scopeInfo = { - upper: scopeInfo, - uselessReturns: [], - codePath - }; - }, - - // Reports useless return statements if exist. - onCodePathEnd() { - for (const node of scopeInfo.uselessReturns) { - context.report({ - node, - loc: node.loc, - messageId: "unnecessaryReturn", - fix(fixer) { - if (isRemovable(node) && !sourceCode.getCommentsInside(node).length) { - - /* - * Extend the replacement range to include the - * entire function to avoid conflicting with - * no-else-return. - * https://github.com/eslint/eslint/issues/8026 - */ - return new FixTracker(fixer, sourceCode) - .retainEnclosingFunction(node) - .remove(node); - } - return null; - } - }); - } - - scopeInfo = scopeInfo.upper; - }, - - /* - * Initializes segments. - * NOTE: This event is notified for only reachable segments. - */ - onCodePathSegmentStart(segment) { - const info = { - uselessReturns: getUselessReturns([], segment.allPrevSegments), - returned: false - }; - - // Stores the info. - segmentInfoMap.set(segment, info); - }, - - // Adds ReturnStatement node to check whether it's useless or not. - ReturnStatement(node) { - if (node.argument) { - markReturnStatementsOnCurrentSegmentsAsUsed(); - } - if ( - node.argument || - astUtils.isInLoop(node) || - isInFinally(node) || - - // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647). - !scopeInfo.codePath.currentSegments.some(s => s.reachable) - ) { - return; - } - - for (const segment of scopeInfo.codePath.currentSegments) { - const info = segmentInfoMap.get(segment); - - if (info) { - info.uselessReturns.push(node); - info.returned = true; - } - } - scopeInfo.uselessReturns.push(node); - }, - - /* - * Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. - * Removes return statements of the current segments from the useless return statement list. - */ - ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, - ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, - LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, - WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed, - ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, - ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed, - ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-var.js b/tools/node_modules/eslint/lib/rules/no-var.js deleted file mode 100644 index f2cb96b1f708e9ed00fc01bc572f9fe14ed725f5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-var.js +++ /dev/null @@ -1,334 +0,0 @@ -/** - * @fileoverview Rule to check for the usage of var. - * @author Jamund Ferguson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Check whether a given variable is a global variable or not. - * @param {eslint-scope.Variable} variable The variable to check. - * @returns {boolean} `true` if the variable is a global variable. - */ -function isGlobal(variable) { - return Boolean(variable.scope) && variable.scope.type === "global"; -} - -/** - * Finds the nearest function scope or global scope walking up the scope - * hierarchy. - * @param {eslint-scope.Scope} scope The scope to traverse. - * @returns {eslint-scope.Scope} a function scope or global scope containing the given - * scope. - */ -function getEnclosingFunctionScope(scope) { - let currentScope = scope; - - while (currentScope.type !== "function" && currentScope.type !== "global") { - currentScope = currentScope.upper; - } - return currentScope; -} - -/** - * Checks whether the given variable has any references from a more specific - * function expression (i.e. a closure). - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is used from a closure. - */ -function isReferencedInClosure(variable) { - const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope); - - return variable.references.some(reference => - getEnclosingFunctionScope(reference.from) !== enclosingFunctionScope); -} - -/** - * Checks whether the given node is the assignee of a loop. - * @param {ASTNode} node A VariableDeclaration node to check. - * @returns {boolean} `true` if the declaration is assigned as part of loop - * iteration. - */ -function isLoopAssignee(node) { - return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") && - node === node.parent.left; -} - -/** - * Checks whether the given variable declaration is immediately initialized. - * @param {ASTNode} node A VariableDeclaration node to check. - * @returns {boolean} `true` if the declaration has an initializer. - */ -function isDeclarationInitialized(node) { - return node.declarations.every(declarator => declarator.init !== null); -} - -const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/u; - -/** - * Gets the scope node which directly contains a given node. - * @param {ASTNode} node A node to get. This is a `VariableDeclaration` or - * an `Identifier`. - * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`, - * `SwitchStatement`, `ForStatement`, `ForInStatement`, and - * `ForOfStatement`. - */ -function getScopeNode(node) { - for (let currentNode = node; currentNode; currentNode = currentNode.parent) { - if (SCOPE_NODE_TYPE.test(currentNode.type)) { - return currentNode; - } - } - - /* istanbul ignore next : unreachable */ - return null; -} - -/** - * Checks whether a given variable is redeclared or not. - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is redeclared. - */ -function isRedeclared(variable) { - return variable.defs.length >= 2; -} - -/** - * Checks whether a given variable is used from outside of the specified scope. - * @param {ASTNode} scopeNode A scope node to check. - * @returns {Function} The predicate function which checks whether a given - * variable is used from outside of the specified scope. - */ -function isUsedFromOutsideOf(scopeNode) { - - /** - * Checks whether a given reference is inside of the specified scope or not. - * @param {eslint-scope.Reference} reference A reference to check. - * @returns {boolean} `true` if the reference is inside of the specified - * scope. - */ - function isOutsideOfScope(reference) { - const scope = scopeNode.range; - const id = reference.identifier.range; - - return id[0] < scope[0] || id[1] > scope[1]; - } - - return function(variable) { - return variable.references.some(isOutsideOfScope); - }; -} - -/** - * Creates the predicate function which checks whether a variable has their references in TDZ. - * - * The predicate function would return `true`: - * - * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};) - * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};) - * - if a reference is in the expression of their initializer. E.g. (var a = a;) - * @param {ASTNode} node The initializer node of VariableDeclarator. - * @returns {Function} The predicate function. - * @private - */ -function hasReferenceInTDZ(node) { - const initStart = node.range[0]; - const initEnd = node.range[1]; - - return variable => { - const id = variable.defs[0].name; - const idStart = id.range[0]; - const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null); - const defaultStart = defaultValue && defaultValue.range[0]; - const defaultEnd = defaultValue && defaultValue.range[1]; - - return variable.references.some(reference => { - const start = reference.identifier.range[0]; - const end = reference.identifier.range[1]; - - return !reference.init && ( - start < idStart || - (defaultValue !== null && start >= defaultStart && end <= defaultEnd) || - (start >= initStart && end <= initEnd) - ); - }); - }; -} - -/** - * Checks whether a given variable has name that is allowed for 'var' declarations, - * but disallowed for `let` declarations. - * @param {eslint-scope.Variable} variable The variable to check. - * @returns {boolean} `true` if the variable has a disallowed name. - */ -function hasNameDisallowedForLetDeclarations(variable) { - return variable.name === "let"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `let` or `const` instead of `var`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/no-var" - }, - - schema: [], - fixable: "code", - - messages: { - unexpectedVar: "Unexpected var, use let or const instead." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Checks whether the variables which are defined by the given declarator node have their references in TDZ. - * @param {ASTNode} declarator The VariableDeclarator node to check. - * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ. - */ - function hasSelfReferenceInTDZ(declarator) { - if (!declarator.init) { - return false; - } - const variables = context.getDeclaredVariables(declarator); - - return variables.some(hasReferenceInTDZ(declarator.init)); - } - - /** - * Checks whether it can fix a given variable declaration or not. - * It cannot fix if the following cases: - * - * - A variable is a global variable. - * - A variable is declared on a SwitchCase node. - * - A variable is redeclared. - * - A variable is used from outside the scope. - * - A variable is used from a closure within a loop. - * - A variable might be used before it is assigned within a loop. - * - A variable might be used in TDZ. - * - A variable is declared in statement position (e.g. a single-line `IfStatement`) - * - A variable has name that is disallowed for `let` declarations. - * - * ## A variable is declared on a SwitchCase node. - * - * If this rule modifies 'var' declarations on a SwitchCase node, it - * would generate the warnings of 'no-case-declarations' rule. And the - * 'eslint:recommended' preset includes 'no-case-declarations' rule, so - * this rule doesn't modify those declarations. - * - * ## A variable is redeclared. - * - * The language spec disallows redeclarations of `let` declarations. - * Those variables would cause syntax errors. - * - * ## A variable is used from outside the scope. - * - * The language spec disallows accesses from outside of the scope for - * `let` declarations. Those variables would cause reference errors. - * - * ## A variable is used from a closure within a loop. - * - * A `var` declaration within a loop shares the same variable instance - * across all loop iterations, while a `let` declaration creates a new - * instance for each iteration. This means if a variable in a loop is - * referenced by any closure, changing it from `var` to `let` would - * change the behavior in a way that is generally unsafe. - * - * ## A variable might be used before it is assigned within a loop. - * - * Within a loop, a `let` declaration without an initializer will be - * initialized to null, while a `var` declaration will retain its value - * from the previous iteration, so it is only safe to change `var` to - * `let` if we can statically determine that the variable is always - * assigned a value before its first access in the loop body. To keep - * the implementation simple, we only convert `var` to `let` within - * loops when the variable is a loop assignee or the declaration has an - * initializer. - * @param {ASTNode} node A variable declaration node to check. - * @returns {boolean} `true` if it can fix the node. - */ - function canFix(node) { - const variables = context.getDeclaredVariables(node); - const scopeNode = getScopeNode(node); - - if (node.parent.type === "SwitchCase" || - node.declarations.some(hasSelfReferenceInTDZ) || - variables.some(isGlobal) || - variables.some(isRedeclared) || - variables.some(isUsedFromOutsideOf(scopeNode)) || - variables.some(hasNameDisallowedForLetDeclarations) - ) { - return false; - } - - if (astUtils.isInLoop(node)) { - if (variables.some(isReferencedInClosure)) { - return false; - } - if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) { - return false; - } - } - - if ( - !isLoopAssignee(node) && - !(node.parent.type === "ForStatement" && node.parent.init === node) && - !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type) - ) { - - // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed. - return false; - } - - return true; - } - - /** - * Reports a given variable declaration node. - * @param {ASTNode} node A variable declaration node to report. - * @returns {void} - */ - function report(node) { - context.report({ - node, - messageId: "unexpectedVar", - - fix(fixer) { - const varToken = sourceCode.getFirstToken(node, { filter: t => t.value === "var" }); - - return canFix(node) - ? fixer.replaceText(varToken, "let") - : null; - } - }); - } - - return { - "VariableDeclaration:exit"(node) { - if (node.kind === "var") { - report(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-void.js b/tools/node_modules/eslint/lib/rules/no-void.js deleted file mode 100644 index 99c83785552ab826e81bc6b2845965fc1172a6ae..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-void.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * @fileoverview Rule to disallow use of void operator. - * @author Mike Sidorov - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `void` operators", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-void" - }, - - messages: { - noVoid: "Expected 'undefined' and instead saw 'void'." - }, - - schema: [ - { - type: "object", - properties: { - allowAsStatement: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ] - }, - - create(context) { - const allowAsStatement = - context.options[0] && context.options[0].allowAsStatement; - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - 'UnaryExpression[operator="void"]'(node) { - if ( - allowAsStatement && - node.parent && - node.parent.type === "ExpressionStatement" - ) { - return; - } - context.report({ - node, - messageId: "noVoid" - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-warning-comments.js b/tools/node_modules/eslint/lib/rules/no-warning-comments.js deleted file mode 100644 index 0691a31f77e429bcd6ce69a6f9995b452a873b39..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-warning-comments.js +++ /dev/null @@ -1,196 +0,0 @@ -/** - * @fileoverview Rule that warns about used warning comments - * @author Alexander Schmidt - */ - -"use strict"; - -const { escapeRegExp } = require("lodash"); -const astUtils = require("./utils/ast-utils"); - -const CHAR_LIMIT = 40; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow specified warning terms in comments", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/no-warning-comments" - }, - - schema: [ - { - type: "object", - properties: { - terms: { - type: "array", - items: { - type: "string" - } - }, - location: { - enum: ["start", "anywhere"] - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedComment: "Unexpected '{{matchedTerm}}' comment: '{{comment}}'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(), - configuration = context.options[0] || {}, - warningTerms = configuration.terms || ["todo", "fixme", "xxx"], - location = configuration.location || "start", - selfConfigRegEx = /\bno-warning-comments\b/u; - - /** - * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified - * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not - * require word boundaries on that side. - * @param {string} term A term to convert to a RegExp - * @returns {RegExp} The term converted to a RegExp - */ - function convertToRegExp(term) { - const escaped = escapeRegExp(term); - const wordBoundary = "\\b"; - const eitherOrWordBoundary = `|${wordBoundary}`; - let prefix; - - /* - * If the term ends in a word character (a-z0-9_), ensure a word - * boundary at the end, so that substrings do not get falsely - * matched. eg "todo" in a string such as "mastodon". - * If the term ends in a non-word character, then \b won't match on - * the boundary to the next non-word character, which would likely - * be a space. For example `/\bFIX!\b/.test('FIX! blah') === false`. - * In these cases, use no bounding match. Same applies for the - * prefix, handled below. - */ - const suffix = /\w$/u.test(term) ? "\\b" : ""; - - if (location === "start") { - - /* - * When matching at the start, ignore leading whitespace, and - * there's no need to worry about word boundaries. - */ - prefix = "^\\s*"; - } else if (/^\w/u.test(term)) { - prefix = wordBoundary; - } else { - prefix = ""; - } - - if (location === "start") { - - /* - * For location "start" the regex should be - * ^\s*TERM\b. This checks the word boundary - * at the beginning of the comment. - */ - return new RegExp(prefix + escaped + suffix, "iu"); - } - - /* - * For location "anywhere" the regex should be - * \bTERM\b|\bTERM\b, this checks the entire comment - * for the term. - */ - return new RegExp( - prefix + - escaped + - suffix + - eitherOrWordBoundary + - term + - wordBoundary, - "iu" - ); - } - - const warningRegExps = warningTerms.map(convertToRegExp); - - /** - * Checks the specified comment for matches of the configured warning terms and returns the matches. - * @param {string} comment The comment which is checked. - * @returns {Array} All matched warning terms for this comment. - */ - function commentContainsWarningTerm(comment) { - const matches = []; - - warningRegExps.forEach((regex, index) => { - if (regex.test(comment)) { - matches.push(warningTerms[index]); - } - }); - - return matches; - } - - /** - * Checks the specified node for matching warning comments and reports them. - * @param {ASTNode} node The AST node being checked. - * @returns {void} undefined. - */ - function checkComment(node) { - const comment = node.value; - - if ( - astUtils.isDirectiveComment(node) && - selfConfigRegEx.test(comment) - ) { - return; - } - - const matches = commentContainsWarningTerm(comment); - - matches.forEach(matchedTerm => { - let commentToDisplay = ""; - let truncated = false; - - for (const c of comment.trim().split(/\s+/u)) { - const tmp = commentToDisplay ? `${commentToDisplay} ${c}` : c; - - if (tmp.length <= CHAR_LIMIT) { - commentToDisplay = tmp; - } else { - truncated = true; - break; - } - } - - context.report({ - node, - messageId: "unexpectedComment", - data: { - matchedTerm, - comment: `${commentToDisplay}${ - truncated ? "..." : "" - }` - } - }); - }); - } - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments - .filter(token => token.type !== "Shebang") - .forEach(checkComment); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js b/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js deleted file mode 100644 index 226f873c5f6bd7d50b40fff1286ff794f6b07a2a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-whitespace-before-property.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @fileoverview Rule to disallow whitespace before properties - * @author Kai Cataldo - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "disallow whitespace before properties", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/no-whitespace-before-property" - }, - - fixable: "whitespace", - schema: [], - - messages: { - unexpectedWhitespace: "Unexpected whitespace before property {{propName}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports whitespace before property token - * @param {ASTNode} node the node to report in the event of an error - * @param {Token} leftToken the left token - * @param {Token} rightToken the right token - * @returns {void} - * @private - */ - function reportError(node, leftToken, rightToken) { - context.report({ - node, - messageId: "unexpectedWhitespace", - data: { - propName: sourceCode.getText(node.property) - }, - fix(fixer) { - let replacementText = ""; - - if (!node.computed && !node.optional && astUtils.isDecimalInteger(node.object)) { - - /* - * If the object is a number literal, fixing it to something like 5.toString() would cause a SyntaxError. - * Don't fix this case. - */ - return null; - } - - // Don't fix if comments exist. - if (sourceCode.commentsExistBetween(leftToken, rightToken)) { - return null; - } - - if (node.optional) { - replacementText = "?."; - } else if (!node.computed) { - replacementText = "."; - } - - return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], replacementText); - } - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - MemberExpression(node) { - let rightToken; - let leftToken; - - if (!astUtils.isTokenOnSameLine(node.object, node.property)) { - return; - } - - if (node.computed) { - rightToken = sourceCode.getTokenBefore(node.property, astUtils.isOpeningBracketToken); - leftToken = sourceCode.getTokenBefore(rightToken, node.optional ? 1 : 0); - } else { - rightToken = sourceCode.getFirstToken(node.property); - leftToken = sourceCode.getTokenBefore(rightToken, 1); - } - - if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken)) { - reportError(node, leftToken, rightToken); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/no-with.js b/tools/node_modules/eslint/lib/rules/no-with.js deleted file mode 100644 index d3e52e02f3d15ae7f9645fe8f3422ad549605f0b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/no-with.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview Rule to flag use of with statement - * @author Nicholas C. Zakas - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `with` statements", - category: "Best Practices", - recommended: true, - url: "https://eslint.org/docs/rules/no-with" - }, - - schema: [], - - messages: { - unexpectedWith: "Unexpected use of 'with' statement." - } - }, - - create(context) { - - return { - WithStatement(node) { - context.report({ node, messageId: "unexpectedWith" }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/nonblock-statement-body-position.js b/tools/node_modules/eslint/lib/rules/nonblock-statement-body-position.js deleted file mode 100644 index 34e6eeac39de50440bcf43ee67a413dd8d040eb1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/nonblock-statement-body-position.js +++ /dev/null @@ -1,124 +0,0 @@ -/** - * @fileoverview enforce the location of single-line statements - * @author Teddy Katz - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const POSITION_SCHEMA = { enum: ["beside", "below", "any"] }; - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the location of single-line statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/nonblock-statement-body-position" - }, - - fixable: "whitespace", - - schema: [ - POSITION_SCHEMA, - { - properties: { - overrides: { - properties: { - if: POSITION_SCHEMA, - else: POSITION_SCHEMA, - while: POSITION_SCHEMA, - do: POSITION_SCHEMA, - for: POSITION_SCHEMA - }, - additionalProperties: false - } - }, - additionalProperties: false - } - ], - - messages: { - expectNoLinebreak: "Expected no linebreak before this statement.", - expectLinebreak: "Expected a linebreak before this statement." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Gets the applicable preference for a particular keyword - * @param {string} keywordName The name of a keyword, e.g. 'if' - * @returns {string} The applicable option for the keyword, e.g. 'beside' - */ - function getOption(keywordName) { - return context.options[1] && context.options[1].overrides && context.options[1].overrides[keywordName] || - context.options[0] || - "beside"; - } - - /** - * Validates the location of a single-line statement - * @param {ASTNode} node The single-line statement - * @param {string} keywordName The applicable keyword name for the single-line statement - * @returns {void} - */ - function validateStatement(node, keywordName) { - const option = getOption(keywordName); - - if (node.type === "BlockStatement" || option === "any") { - return; - } - - const tokenBefore = sourceCode.getTokenBefore(node); - - if (tokenBefore.loc.end.line === node.loc.start.line && option === "below") { - context.report({ - node, - messageId: "expectLinebreak", - fix: fixer => fixer.insertTextBefore(node, "\n") - }); - } else if (tokenBefore.loc.end.line !== node.loc.start.line && option === "beside") { - context.report({ - node, - messageId: "expectNoLinebreak", - fix(fixer) { - if (sourceCode.getText().slice(tokenBefore.range[1], node.range[0]).trim()) { - return null; - } - return fixer.replaceTextRange([tokenBefore.range[1], node.range[0]], " "); - } - }); - } - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - IfStatement(node) { - validateStatement(node.consequent, "if"); - - // Check the `else` node, but don't check 'else if' statements. - if (node.alternate && node.alternate.type !== "IfStatement") { - validateStatement(node.alternate, "else"); - } - }, - WhileStatement: node => validateStatement(node.body, "while"), - DoWhileStatement: node => validateStatement(node.body, "do"), - ForStatement: node => validateStatement(node.body, "for"), - ForInStatement: node => validateStatement(node.body, "for"), - ForOfStatement: node => validateStatement(node.body, "for") - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-curly-newline.js b/tools/node_modules/eslint/lib/rules/object-curly-newline.js deleted file mode 100644 index 616d59851d646d5085bbc77a58a61101dced609c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/object-curly-newline.js +++ /dev/null @@ -1,306 +0,0 @@ -/** - * @fileoverview Rule to require or disallow line breaks inside braces. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -// Schema objects. -const OPTION_VALUE = { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - multiline: { - type: "boolean" - }, - minProperties: { - type: "integer", - minimum: 0 - }, - consistent: { - type: "boolean" - } - }, - additionalProperties: false, - minProperties: 1 - } - ] -}; - -/** - * Normalizes a given option value. - * @param {string|Object|undefined} value An option value to parse. - * @returns {{multiline: boolean, minProperties: number, consistent: boolean}} Normalized option object. - */ -function normalizeOptionValue(value) { - let multiline = false; - let minProperties = Number.POSITIVE_INFINITY; - let consistent = false; - - if (value) { - if (value === "always") { - minProperties = 0; - } else if (value === "never") { - minProperties = Number.POSITIVE_INFINITY; - } else { - multiline = Boolean(value.multiline); - minProperties = value.minProperties || Number.POSITIVE_INFINITY; - consistent = Boolean(value.consistent); - } - } else { - consistent = true; - } - - return { multiline, minProperties, consistent }; -} - -/** - * Normalizes a given option value. - * @param {string|Object|undefined} options An option value to parse. - * @returns {{ - * ObjectExpression: {multiline: boolean, minProperties: number, consistent: boolean}, - * ObjectPattern: {multiline: boolean, minProperties: number, consistent: boolean}, - * ImportDeclaration: {multiline: boolean, minProperties: number, consistent: boolean}, - * ExportNamedDeclaration : {multiline: boolean, minProperties: number, consistent: boolean} - * }} Normalized option object. - */ -function normalizeOptions(options) { - const isNodeSpecificOption = lodash.overSome([lodash.isPlainObject, lodash.isString]); - - if (lodash.isPlainObject(options) && lodash.some(options, isNodeSpecificOption)) { - return { - ObjectExpression: normalizeOptionValue(options.ObjectExpression), - ObjectPattern: normalizeOptionValue(options.ObjectPattern), - ImportDeclaration: normalizeOptionValue(options.ImportDeclaration), - ExportNamedDeclaration: normalizeOptionValue(options.ExportDeclaration) - }; - } - - const value = normalizeOptionValue(options); - - return { ObjectExpression: value, ObjectPattern: value, ImportDeclaration: value, ExportNamedDeclaration: value }; -} - -/** - * Determines if ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration - * node needs to be checked for missing line breaks - * @param {ASTNode} node Node under inspection - * @param {Object} options option specific to node type - * @param {Token} first First object property - * @param {Token} last Last object property - * @returns {boolean} `true` if node needs to be checked for missing line breaks - */ -function areLineBreaksRequired(node, options, first, last) { - let objectProperties; - - if (node.type === "ObjectExpression" || node.type === "ObjectPattern") { - objectProperties = node.properties; - } else { - - // is ImportDeclaration or ExportNamedDeclaration - objectProperties = node.specifiers - .filter(s => s.type === "ImportSpecifier" || s.type === "ExportSpecifier"); - } - - return objectProperties.length >= options.minProperties || - ( - options.multiline && - objectProperties.length > 0 && - first.loc.start.line !== last.loc.end.line - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent line breaks inside braces", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/object-curly-newline" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - OPTION_VALUE, - { - type: "object", - properties: { - ObjectExpression: OPTION_VALUE, - ObjectPattern: OPTION_VALUE, - ImportDeclaration: OPTION_VALUE, - ExportDeclaration: OPTION_VALUE - }, - additionalProperties: false, - minProperties: 1 - } - ] - } - ], - - messages: { - unexpectedLinebreakBeforeClosingBrace: "Unexpected line break before this closing brace.", - unexpectedLinebreakAfterOpeningBrace: "Unexpected line break after this opening brace.", - expectedLinebreakBeforeClosingBrace: "Expected a line break before this closing brace.", - expectedLinebreakAfterOpeningBrace: "Expected a line break after this opening brace." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const normalizedOptions = normalizeOptions(context.options[0]); - - /** - * Reports a given node if it violated this rule. - * @param {ASTNode} node A node to check. This is an ObjectExpression, ObjectPattern, ImportDeclaration or ExportNamedDeclaration node. - * @returns {void} - */ - function check(node) { - const options = normalizedOptions[node.type]; - - if ( - (node.type === "ImportDeclaration" && - !node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) || - (node.type === "ExportNamedDeclaration" && - !node.specifiers.some(specifier => specifier.type === "ExportSpecifier")) - ) { - return; - } - - const openBrace = sourceCode.getFirstToken(node, token => token.value === "{"); - - let closeBrace; - - if (node.typeAnnotation) { - closeBrace = sourceCode.getTokenBefore(node.typeAnnotation); - } else { - closeBrace = sourceCode.getLastToken(node, token => token.value === "}"); - } - - let first = sourceCode.getTokenAfter(openBrace, { includeComments: true }); - let last = sourceCode.getTokenBefore(closeBrace, { includeComments: true }); - - const needsLineBreaks = areLineBreaksRequired(node, options, first, last); - - const hasCommentsFirstToken = astUtils.isCommentToken(first); - const hasCommentsLastToken = astUtils.isCommentToken(last); - - /* - * Use tokens or comments to check multiline or not. - * But use only tokens to check whether line breaks are needed. - * This allows: - * var obj = { // eslint-disable-line foo - * a: 1 - * } - */ - first = sourceCode.getTokenAfter(openBrace); - last = sourceCode.getTokenBefore(closeBrace); - - if (needsLineBreaks) { - if (astUtils.isTokenOnSameLine(openBrace, first)) { - context.report({ - messageId: "expectedLinebreakAfterOpeningBrace", - node, - loc: openBrace.loc, - fix(fixer) { - if (hasCommentsFirstToken) { - return null; - } - - return fixer.insertTextAfter(openBrace, "\n"); - } - }); - } - if (astUtils.isTokenOnSameLine(last, closeBrace)) { - context.report({ - messageId: "expectedLinebreakBeforeClosingBrace", - node, - loc: closeBrace.loc, - fix(fixer) { - if (hasCommentsLastToken) { - return null; - } - - return fixer.insertTextBefore(closeBrace, "\n"); - } - }); - } - } else { - const consistent = options.consistent; - const hasLineBreakBetweenOpenBraceAndFirst = !astUtils.isTokenOnSameLine(openBrace, first); - const hasLineBreakBetweenCloseBraceAndLast = !astUtils.isTokenOnSameLine(last, closeBrace); - - if ( - (!consistent && hasLineBreakBetweenOpenBraceAndFirst) || - (consistent && hasLineBreakBetweenOpenBraceAndFirst && !hasLineBreakBetweenCloseBraceAndLast) - ) { - context.report({ - messageId: "unexpectedLinebreakAfterOpeningBrace", - node, - loc: openBrace.loc, - fix(fixer) { - if (hasCommentsFirstToken) { - return null; - } - - return fixer.removeRange([ - openBrace.range[1], - first.range[0] - ]); - } - }); - } - if ( - (!consistent && hasLineBreakBetweenCloseBraceAndLast) || - (consistent && !hasLineBreakBetweenOpenBraceAndFirst && hasLineBreakBetweenCloseBraceAndLast) - ) { - context.report({ - messageId: "unexpectedLinebreakBeforeClosingBrace", - node, - loc: closeBrace.loc, - fix(fixer) { - if (hasCommentsLastToken) { - return null; - } - - return fixer.removeRange([ - last.range[1], - closeBrace.range[0] - ]); - } - }); - } - } - } - - return { - ObjectExpression: check, - ObjectPattern: check, - ImportDeclaration: check, - ExportNamedDeclaration: check - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-curly-spacing.js b/tools/node_modules/eslint/lib/rules/object-curly-spacing.js deleted file mode 100644 index c0044f5033c00571259d37add4c72ff52d2ea0f9..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/object-curly-spacing.js +++ /dev/null @@ -1,308 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside of object literals. - * @author Jamund Ferguson - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside braces", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/object-curly-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - arraysInObjects: { - type: "boolean" - }, - objectsInObjects: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - - messages: { - requireSpaceBefore: "A space is required before '{{token}}'.", - requireSpaceAfter: "A space is required after '{{token}}'.", - unexpectedSpaceBefore: "There should be no space before '{{token}}'.", - unexpectedSpaceAfter: "There should be no space after '{{token}}'." - } - }, - - create(context) { - const spaced = context.options[0] === "always", - sourceCode = context.getSourceCode(); - - /** - * Determines whether an option is set, relative to the spacing option. - * If spaced is "always", then check whether option is set to false. - * If spaced is "never", then check whether option is set to true. - * @param {Object} option The option to exclude. - * @returns {boolean} Whether or not the property is excluded. - */ - function isOptionSet(option) { - return context.options[1] ? context.options[1][option] === !spaced : false; - } - - const options = { - spaced, - arraysInObjectsException: isOptionSet("arraysInObjects"), - objectsInObjectsException: isOptionSet("objectsInObjects") - }; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports that there shouldn't be a space after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoBeginningSpace(node, token) { - const nextToken = context.getSourceCode().getTokenAfter(token, { includeComments: true }); - - context.report({ - node, - loc: { start: token.loc.end, end: nextToken.loc.start }, - messageId: "unexpectedSpaceAfter", - data: { - token: token.value - }, - fix(fixer) { - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - /** - * Reports that there shouldn't be a space before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportNoEndingSpace(node, token) { - const previousToken = context.getSourceCode().getTokenBefore(token, { includeComments: true }); - - context.report({ - node, - loc: { start: previousToken.loc.end, end: token.loc.start }, - messageId: "unexpectedSpaceBefore", - data: { - token: token.value - }, - fix(fixer) { - return fixer.removeRange([previousToken.range[1], token.range[0]]); - } - }); - } - - /** - * Reports that there should be a space after the first token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredBeginningSpace(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "requireSpaceAfter", - data: { - token: token.value - }, - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - /** - * Reports that there should be a space before the last token - * @param {ASTNode} node The node to report in the event of an error. - * @param {Token} token The token to use for the report. - * @returns {void} - */ - function reportRequiredEndingSpace(node, token) { - context.report({ - node, - loc: token.loc, - messageId: "requireSpaceBefore", - data: { - token: token.value - }, - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - /** - * Determines if spacing in curly braces is valid. - * @param {ASTNode} node The AST node to check. - * @param {Token} first The first token to check (should be the opening brace) - * @param {Token} second The second token to check (should be first after the opening brace) - * @param {Token} penultimate The penultimate token to check (should be last before closing brace) - * @param {Token} last The last token to check (should be closing brace) - * @returns {void} - */ - function validateBraceSpacing(node, first, second, penultimate, last) { - if (astUtils.isTokenOnSameLine(first, second)) { - const firstSpaced = sourceCode.isSpaceBetweenTokens(first, second); - - if (options.spaced && !firstSpaced) { - reportRequiredBeginningSpace(node, first); - } - if (!options.spaced && firstSpaced && second.type !== "Line") { - reportNoBeginningSpace(node, first); - } - } - - if (astUtils.isTokenOnSameLine(penultimate, last)) { - const shouldCheckPenultimate = ( - options.arraysInObjectsException && astUtils.isClosingBracketToken(penultimate) || - options.objectsInObjectsException && astUtils.isClosingBraceToken(penultimate) - ); - const penultimateType = shouldCheckPenultimate && sourceCode.getNodeByRangeIndex(penultimate.range[0]).type; - - const closingCurlyBraceMustBeSpaced = ( - options.arraysInObjectsException && penultimateType === "ArrayExpression" || - options.objectsInObjectsException && (penultimateType === "ObjectExpression" || penultimateType === "ObjectPattern") - ) ? !options.spaced : options.spaced; - - const lastSpaced = sourceCode.isSpaceBetweenTokens(penultimate, last); - - if (closingCurlyBraceMustBeSpaced && !lastSpaced) { - reportRequiredEndingSpace(node, last); - } - if (!closingCurlyBraceMustBeSpaced && lastSpaced) { - reportNoEndingSpace(node, last); - } - } - } - - /** - * Gets '}' token of an object node. - * - * Because the last token of object patterns might be a type annotation, - * this traverses tokens preceded by the last property, then returns the - * first '}' token. - * @param {ASTNode} node The node to get. This node is an - * ObjectExpression or an ObjectPattern. And this node has one or - * more properties. - * @returns {Token} '}' token. - */ - function getClosingBraceOfObject(node) { - const lastProperty = node.properties[node.properties.length - 1]; - - return sourceCode.getTokenAfter(lastProperty, astUtils.isClosingBraceToken); - } - - /** - * Reports a given object node if spacing in curly braces is invalid. - * @param {ASTNode} node An ObjectExpression or ObjectPattern node to check. - * @returns {void} - */ - function checkForObject(node) { - if (node.properties.length === 0) { - return; - } - - const first = sourceCode.getFirstToken(node), - last = getClosingBraceOfObject(node), - second = sourceCode.getTokenAfter(first, { includeComments: true }), - penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); - - validateBraceSpacing(node, first, second, penultimate, last); - } - - /** - * Reports a given import node if spacing in curly braces is invalid. - * @param {ASTNode} node An ImportDeclaration node to check. - * @returns {void} - */ - function checkForImport(node) { - if (node.specifiers.length === 0) { - return; - } - - let firstSpecifier = node.specifiers[0]; - const lastSpecifier = node.specifiers[node.specifiers.length - 1]; - - if (lastSpecifier.type !== "ImportSpecifier") { - return; - } - if (firstSpecifier.type !== "ImportSpecifier") { - firstSpecifier = node.specifiers[1]; - } - - const first = sourceCode.getTokenBefore(firstSpecifier), - last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), - second = sourceCode.getTokenAfter(first, { includeComments: true }), - penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); - - validateBraceSpacing(node, first, second, penultimate, last); - } - - /** - * Reports a given export node if spacing in curly braces is invalid. - * @param {ASTNode} node An ExportNamedDeclaration node to check. - * @returns {void} - */ - function checkForExport(node) { - if (node.specifiers.length === 0) { - return; - } - - const firstSpecifier = node.specifiers[0], - lastSpecifier = node.specifiers[node.specifiers.length - 1], - first = sourceCode.getTokenBefore(firstSpecifier), - last = sourceCode.getTokenAfter(lastSpecifier, astUtils.isNotCommaToken), - second = sourceCode.getTokenAfter(first, { includeComments: true }), - penultimate = sourceCode.getTokenBefore(last, { includeComments: true }); - - validateBraceSpacing(node, first, second, penultimate, last); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - // var {x} = y; - ObjectPattern: checkForObject, - - // var y = {x: 'y'} - ObjectExpression: checkForObject, - - // import {y} from 'x'; - ImportDeclaration: checkForImport, - - // export {name} from 'yo'; - ExportNamedDeclaration: checkForExport - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-property-newline.js b/tools/node_modules/eslint/lib/rules/object-property-newline.js deleted file mode 100644 index 074bc775ae35a3401f15208b509fb9dde4e0ded2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/object-property-newline.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * @fileoverview Rule to enforce placing object properties on separate lines. - * @author Vitor Balocco - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce placing object properties on separate lines", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/object-property-newline" - }, - - schema: [ - { - type: "object", - properties: { - allowAllPropertiesOnSameLine: { - type: "boolean", - default: false - }, - allowMultiplePropertiesPerLine: { // Deprecated - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "whitespace", - - messages: { - propertiesOnNewlineAll: "Object properties must go on a new line if they aren't all on the same line.", - propertiesOnNewline: "Object properties must go on a new line." - } - }, - - create(context) { - const allowSameLine = context.options[0] && ( - (context.options[0].allowAllPropertiesOnSameLine || context.options[0].allowMultiplePropertiesPerLine /* Deprecated */) - ); - const messageId = allowSameLine - ? "propertiesOnNewlineAll" - : "propertiesOnNewline"; - - const sourceCode = context.getSourceCode(); - - return { - ObjectExpression(node) { - if (allowSameLine) { - if (node.properties.length > 1) { - const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]); - const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]); - - if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) { - - // All keys and values are on the same line - return; - } - } - } - - for (let i = 1; i < node.properties.length; i++) { - const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.properties[i - 1]); - const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.properties[i]); - - if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) { - context.report({ - node, - loc: firstTokenOfCurrentProperty.loc.start, - messageId, - fix(fixer) { - const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty); - const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]]; - - // Don't perform a fix if there are any comments between the comma and the next property. - if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) { - return null; - } - - return fixer.replaceTextRange(rangeAfterComma, "\n"); - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/object-shorthand.js b/tools/node_modules/eslint/lib/rules/object-shorthand.js deleted file mode 100644 index 3999ff8b99fb29e35a1278cb55a2099eeb332a12..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/object-shorthand.js +++ /dev/null @@ -1,508 +0,0 @@ -/** - * @fileoverview Rule to enforce concise object methods and properties. - * @author Jamund Ferguson - */ - -"use strict"; - -const OPTIONS = { - always: "always", - never: "never", - methods: "methods", - properties: "properties", - consistent: "consistent", - consistentAsNeeded: "consistent-as-needed" -}; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow method and property shorthand syntax for object literals", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/object-shorthand" - }, - - fixable: "code", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "methods", "properties", "never", "consistent", "consistent-as-needed"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["always", "methods", "properties"] - }, - { - type: "object", - properties: { - avoidQuotes: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - }, - { - type: "array", - items: [ - { - enum: ["always", "methods"] - }, - { - type: "object", - properties: { - ignoreConstructors: { - type: "boolean" - }, - avoidQuotes: { - type: "boolean" - }, - avoidExplicitReturnArrows: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - messages: { - expectedAllPropertiesShorthanded: "Expected shorthand for all properties.", - expectedLiteralMethodLongform: "Expected longform method syntax for string literal keys.", - expectedPropertyShorthand: "Expected property shorthand.", - expectedPropertyLongform: "Expected longform property syntax.", - expectedMethodShorthand: "Expected method shorthand.", - expectedMethodLongform: "Expected longform method syntax.", - unexpectedMix: "Unexpected mix of shorthand and non-shorthand properties." - } - }, - - create(context) { - const APPLY = context.options[0] || OPTIONS.always; - const APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always; - const APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always; - const APPLY_NEVER = APPLY === OPTIONS.never; - const APPLY_CONSISTENT = APPLY === OPTIONS.consistent; - const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded; - - const PARAMS = context.options[1] || {}; - const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors; - const AVOID_QUOTES = PARAMS.avoidQuotes; - const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows; - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const CTOR_PREFIX_REGEX = /[^_$0-9]/u; - - /** - * Determines if the first character of the name is a capital letter. - * @param {string} name The name of the node to evaluate. - * @returns {boolean} True if the first character of the property name is a capital letter, false if not. - * @private - */ - function isConstructor(name) { - const match = CTOR_PREFIX_REGEX.exec(name); - - // Not a constructor if name has no characters apart from '_', '$' and digits e.g. '_', '$$', '_8' - if (!match) { - return false; - } - - const firstChar = name.charAt(match.index); - - return firstChar === firstChar.toUpperCase(); - } - - /** - * Determines if the property can have a shorthand form. - * @param {ASTNode} property Property AST node - * @returns {boolean} True if the property can have a shorthand form - * @private - * - */ - function canHaveShorthand(property) { - return (property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadElement" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty"); - } - - /** - * Checks whether a node is a string literal. - * @param {ASTNode} node Any AST node. - * @returns {boolean} `true` if it is a string literal. - */ - function isStringLiteral(node) { - return node.type === "Literal" && typeof node.value === "string"; - } - - /** - * Determines if the property is a shorthand or not. - * @param {ASTNode} property Property AST node - * @returns {boolean} True if the property is considered shorthand, false if not. - * @private - * - */ - function isShorthand(property) { - - // property.method is true when `{a(){}}`. - return (property.shorthand || property.method); - } - - /** - * Determines if the property's key and method or value are named equally. - * @param {ASTNode} property Property AST node - * @returns {boolean} True if the key and value are named equally, false if not. - * @private - * - */ - function isRedundant(property) { - const value = property.value; - - if (value.type === "FunctionExpression") { - return !value.id; // Only anonymous should be shorthand method. - } - if (value.type === "Identifier") { - return astUtils.getStaticPropertyName(property) === value.name; - } - - return false; - } - - /** - * Ensures that an object's properties are consistently shorthand, or not shorthand at all. - * @param {ASTNode} node Property AST node - * @param {boolean} checkRedundancy Whether to check longform redundancy - * @returns {void} - * - */ - function checkConsistency(node, checkRedundancy) { - - // We are excluding getters/setters and spread properties as they are considered neither longform nor shorthand. - const properties = node.properties.filter(canHaveShorthand); - - // Do we still have properties left after filtering the getters and setters? - if (properties.length > 0) { - const shorthandProperties = properties.filter(isShorthand); - - /* - * If we do not have an equal number of longform properties as - * shorthand properties, we are using the annotations inconsistently - */ - if (shorthandProperties.length !== properties.length) { - - // We have at least 1 shorthand property - if (shorthandProperties.length > 0) { - context.report({ node, messageId: "unexpectedMix" }); - } else if (checkRedundancy) { - - /* - * If all properties of the object contain a method or value with a name matching it's key, - * all the keys are redundant. - */ - const canAlwaysUseShorthand = properties.every(isRedundant); - - if (canAlwaysUseShorthand) { - context.report({ node, messageId: "expectedAllPropertiesShorthanded" }); - } - } - } - } - } - - /** - * Fixes a FunctionExpression node by making it into a shorthand property. - * @param {SourceCodeFixer} fixer The fixer object - * @param {ASTNode} node A `Property` node that has a `FunctionExpression` or `ArrowFunctionExpression` as its value - * @returns {Object} A fix for this node - */ - function makeFunctionShorthand(fixer, node) { - const firstKeyToken = node.computed - ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken) - : sourceCode.getFirstToken(node.key); - const lastKeyToken = node.computed - ? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken) - : sourceCode.getLastToken(node.key); - const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); - let keyPrefix = ""; - - // key: /* */ () => {} - if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) { - return null; - } - - if (node.value.async) { - keyPrefix += "async "; - } - if (node.value.generator) { - keyPrefix += "*"; - } - - const fixRange = [firstKeyToken.range[0], node.range[1]]; - const methodPrefix = keyPrefix + keyText; - - if (node.value.type === "FunctionExpression") { - const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function"); - const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken; - - return fixer.replaceTextRange( - fixRange, - methodPrefix + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1]) - ); - } - - const arrowToken = sourceCode.getTokenBefore(node.value.body, astUtils.isArrowToken); - const fnBody = sourceCode.text.slice(arrowToken.range[1], node.value.range[1]); - - let shouldAddParensAroundParameters = false; - let tokenBeforeParams; - - if (node.value.params.length === 0) { - tokenBeforeParams = sourceCode.getFirstToken(node.value, astUtils.isOpeningParenToken); - } else { - tokenBeforeParams = sourceCode.getTokenBefore(node.value.params[0]); - } - - if (node.value.params.length === 1) { - const hasParen = astUtils.isOpeningParenToken(tokenBeforeParams); - const isTokenOutsideNode = tokenBeforeParams.range[0] < node.range[0]; - - shouldAddParensAroundParameters = !hasParen || isTokenOutsideNode; - } - - const sliceStart = shouldAddParensAroundParameters - ? node.value.params[0].range[0] - : tokenBeforeParams.range[0]; - const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1]; - - const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd); - const newParamText = shouldAddParensAroundParameters ? `(${oldParamText})` : oldParamText; - - return fixer.replaceTextRange( - fixRange, - methodPrefix + newParamText + fnBody - ); - - } - - /** - * Fixes a FunctionExpression node by making it into a longform property. - * @param {SourceCodeFixer} fixer The fixer object - * @param {ASTNode} node A `Property` node that has a `FunctionExpression` as its value - * @returns {Object} A fix for this node - */ - function makeFunctionLongform(fixer, node) { - const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key); - const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key); - const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]); - let functionHeader = "function"; - - if (node.value.async) { - functionHeader = `async ${functionHeader}`; - } - if (node.value.generator) { - functionHeader = `${functionHeader}*`; - } - - return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`); - } - - /* - * To determine whether a given arrow function has a lexical identifier (`this`, `arguments`, `super`, or `new.target`), - * create a stack of functions that define these identifiers (i.e. all functions except arrow functions) as the AST is - * traversed. Whenever a new function is encountered, create a new entry on the stack (corresponding to a different lexical - * scope of `this`), and whenever a function is exited, pop that entry off the stack. When an arrow function is entered, - * keep a reference to it on the current stack entry, and remove that reference when the arrow function is exited. - * When a lexical identifier is encountered, mark all the arrow functions on the current stack entry by adding them - * to an `arrowsWithLexicalIdentifiers` set. Any arrow function in that set will not be reported by this rule, - * because converting it into a method would change the value of one of the lexical identifiers. - */ - const lexicalScopeStack = []; - const arrowsWithLexicalIdentifiers = new WeakSet(); - const argumentsIdentifiers = new WeakSet(); - - /** - * Enters a function. This creates a new lexical identifier scope, so a new Set of arrow functions is pushed onto the stack. - * Also, this marks all `arguments` identifiers so that they can be detected later. - * @returns {void} - */ - function enterFunction() { - lexicalScopeStack.unshift(new Set()); - context.getScope().variables.filter(variable => variable.name === "arguments").forEach(variable => { - variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier)); - }); - } - - /** - * Exits a function. This pops the current set of arrow functions off the lexical scope stack. - * @returns {void} - */ - function exitFunction() { - lexicalScopeStack.shift(); - } - - /** - * Marks the current function as having a lexical keyword. This implies that all arrow functions - * in the current lexical scope contain a reference to this lexical keyword. - * @returns {void} - */ - function reportLexicalIdentifier() { - lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction)); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: enterFunction, - FunctionDeclaration: enterFunction, - FunctionExpression: enterFunction, - "Program:exit": exitFunction, - "FunctionDeclaration:exit": exitFunction, - "FunctionExpression:exit": exitFunction, - - ArrowFunctionExpression(node) { - lexicalScopeStack[0].add(node); - }, - "ArrowFunctionExpression:exit"(node) { - lexicalScopeStack[0].delete(node); - }, - - ThisExpression: reportLexicalIdentifier, - Super: reportLexicalIdentifier, - MetaProperty(node) { - if (node.meta.name === "new" && node.property.name === "target") { - reportLexicalIdentifier(); - } - }, - Identifier(node) { - if (argumentsIdentifiers.has(node)) { - reportLexicalIdentifier(); - } - }, - - ObjectExpression(node) { - if (APPLY_CONSISTENT) { - checkConsistency(node, false); - } else if (APPLY_CONSISTENT_AS_NEEDED) { - checkConsistency(node, true); - } - }, - - "Property:exit"(node) { - const isConciseProperty = node.method || node.shorthand; - - // Ignore destructuring assignment - if (node.parent.type === "ObjectPattern") { - return; - } - - // getters and setters are ignored - if (node.kind === "get" || node.kind === "set") { - return; - } - - // only computed methods can fail the following checks - if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") { - return; - } - - //-------------------------------------------------------------- - // Checks for property/method shorthand. - if (isConciseProperty) { - if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) { - const messageId = APPLY_NEVER ? "expectedMethodLongform" : "expectedLiteralMethodLongform"; - - // { x() {} } should be written as { x: function() {} } - context.report({ - node, - messageId, - fix: fixer => makeFunctionLongform(fixer, node) - }); - } else if (APPLY_NEVER) { - - // { x } should be written as { x: x } - context.report({ - node, - messageId: "expectedPropertyLongform", - fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`) - }); - } - } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) { - if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) { - return; - } - if (AVOID_QUOTES && isStringLiteral(node.key)) { - return; - } - - // {[x]: function(){}} should be written as {[x]() {}} - if (node.value.type === "FunctionExpression" || - node.value.type === "ArrowFunctionExpression" && - node.value.body.type === "BlockStatement" && - AVOID_EXPLICIT_RETURN_ARROWS && - !arrowsWithLexicalIdentifiers.has(node.value) - ) { - context.report({ - node, - messageId: "expectedMethodShorthand", - fix: fixer => makeFunctionShorthand(fixer, node) - }); - } - } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) { - - // {x: x} should be written as {x} - context.report({ - node, - messageId: "expectedPropertyShorthand", - fix(fixer) { - return fixer.replaceText(node, node.value.name); - } - }); - } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) { - if (AVOID_QUOTES) { - return; - } - - // {"x": x} should be written as {x} - context.report({ - node, - messageId: "expectedPropertyShorthand", - fix(fixer) { - return fixer.replaceText(node, node.value.name); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/one-var-declaration-per-line.js b/tools/node_modules/eslint/lib/rules/one-var-declaration-per-line.js deleted file mode 100644 index db4674760a0f273a5d622fe6c96c924a75bb966f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/one-var-declaration-per-line.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @fileoverview Rule to check multiple var declarations per line - * @author Alberto Rodríguez - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow newlines around variable declarations", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/one-var-declaration-per-line" - }, - - schema: [ - { - enum: ["always", "initializations"] - } - ], - - fixable: "whitespace", - - messages: { - expectVarOnNewline: "Expected variable declaration to be on a new line." - } - }, - - create(context) { - - const always = context.options[0] === "always"; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - - /** - * Determine if provided keyword is a variant of for specifiers - * @private - * @param {string} keyword keyword to test - * @returns {boolean} True if `keyword` is a variant of for specifier - */ - function isForTypeSpecifier(keyword) { - return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement"; - } - - /** - * Checks newlines around variable declarations. - * @private - * @param {ASTNode} node `VariableDeclaration` node to test - * @returns {void} - */ - function checkForNewLine(node) { - if (isForTypeSpecifier(node.parent.type)) { - return; - } - - const declarations = node.declarations; - let prev; - - declarations.forEach(current => { - if (prev && prev.loc.end.line === current.loc.start.line) { - if (always || prev.init || current.init) { - context.report({ - node, - messageId: "expectVarOnNewline", - loc: current.loc, - fix: fixer => fixer.insertTextBefore(current, "\n") - }); - } - } - prev = current; - }); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclaration: checkForNewLine - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/one-var.js b/tools/node_modules/eslint/lib/rules/one-var.js deleted file mode 100644 index c31a0d2b13c187987a0478413d522824673713f2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/one-var.js +++ /dev/null @@ -1,535 +0,0 @@ -/** - * @fileoverview A rule to control the use of single variable declarations. - * @author Ian Christian Myers - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce variables to be declared either together or separately in functions", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/one-var" - }, - - fixable: "code", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never", "consecutive"] - }, - { - type: "object", - properties: { - separateRequires: { - type: "boolean" - }, - var: { - enum: ["always", "never", "consecutive"] - }, - let: { - enum: ["always", "never", "consecutive"] - }, - const: { - enum: ["always", "never", "consecutive"] - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - initialized: { - enum: ["always", "never", "consecutive"] - }, - uninitialized: { - enum: ["always", "never", "consecutive"] - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - combineUninitialized: "Combine this with the previous '{{type}}' statement with uninitialized variables.", - combineInitialized: "Combine this with the previous '{{type}}' statement with initialized variables.", - splitUninitialized: "Split uninitialized '{{type}}' declarations into multiple statements.", - splitInitialized: "Split initialized '{{type}}' declarations into multiple statements.", - splitRequires: "Split requires to be separated into a single block.", - combine: "Combine this with the previous '{{type}}' statement.", - split: "Split '{{type}}' declarations into multiple statements." - } - }, - - create(context) { - const MODE_ALWAYS = "always"; - const MODE_NEVER = "never"; - const MODE_CONSECUTIVE = "consecutive"; - const mode = context.options[0] || MODE_ALWAYS; - - const options = {}; - - if (typeof mode === "string") { // simple options configuration with just a string - options.var = { uninitialized: mode, initialized: mode }; - options.let = { uninitialized: mode, initialized: mode }; - options.const = { uninitialized: mode, initialized: mode }; - } else if (typeof mode === "object") { // options configuration is an object - options.separateRequires = !!mode.separateRequires; - options.var = { uninitialized: mode.var, initialized: mode.var }; - options.let = { uninitialized: mode.let, initialized: mode.let }; - options.const = { uninitialized: mode.const, initialized: mode.const }; - if (Object.prototype.hasOwnProperty.call(mode, "uninitialized")) { - options.var.uninitialized = mode.uninitialized; - options.let.uninitialized = mode.uninitialized; - options.const.uninitialized = mode.uninitialized; - } - if (Object.prototype.hasOwnProperty.call(mode, "initialized")) { - options.var.initialized = mode.initialized; - options.let.initialized = mode.initialized; - options.const.initialized = mode.initialized; - } - } - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - const functionStack = []; - const blockStack = []; - - /** - * Increments the blockStack counter. - * @returns {void} - * @private - */ - function startBlock() { - blockStack.push({ - let: { initialized: false, uninitialized: false }, - const: { initialized: false, uninitialized: false } - }); - } - - /** - * Increments the functionStack counter. - * @returns {void} - * @private - */ - function startFunction() { - functionStack.push({ initialized: false, uninitialized: false }); - startBlock(); - } - - /** - * Decrements the blockStack counter. - * @returns {void} - * @private - */ - function endBlock() { - blockStack.pop(); - } - - /** - * Decrements the functionStack counter. - * @returns {void} - * @private - */ - function endFunction() { - functionStack.pop(); - endBlock(); - } - - /** - * Check if a variable declaration is a require. - * @param {ASTNode} decl variable declaration Node - * @returns {bool} if decl is a require, return true; else return false. - * @private - */ - function isRequire(decl) { - return decl.init && decl.init.type === "CallExpression" && decl.init.callee.name === "require"; - } - - /** - * Records whether initialized/uninitialized/required variables are defined in current scope. - * @param {string} statementType node.kind, one of: "var", "let", or "const" - * @param {ASTNode[]} declarations List of declarations - * @param {Object} currentScope The scope being investigated - * @returns {void} - * @private - */ - function recordTypes(statementType, declarations, currentScope) { - for (let i = 0; i < declarations.length; i++) { - if (declarations[i].init === null) { - if (options[statementType] && options[statementType].uninitialized === MODE_ALWAYS) { - currentScope.uninitialized = true; - } - } else { - if (options[statementType] && options[statementType].initialized === MODE_ALWAYS) { - if (options.separateRequires && isRequire(declarations[i])) { - currentScope.required = true; - } else { - currentScope.initialized = true; - } - } - } - } - } - - /** - * Determines the current scope (function or block) - * @param {string} statementType node.kind, one of: "var", "let", or "const" - * @returns {Object} The scope associated with statementType - */ - function getCurrentScope(statementType) { - let currentScope; - - if (statementType === "var") { - currentScope = functionStack[functionStack.length - 1]; - } else if (statementType === "let") { - currentScope = blockStack[blockStack.length - 1].let; - } else if (statementType === "const") { - currentScope = blockStack[blockStack.length - 1].const; - } - return currentScope; - } - - /** - * Counts the number of initialized and uninitialized declarations in a list of declarations - * @param {ASTNode[]} declarations List of declarations - * @returns {Object} Counts of 'uninitialized' and 'initialized' declarations - * @private - */ - function countDeclarations(declarations) { - const counts = { uninitialized: 0, initialized: 0 }; - - for (let i = 0; i < declarations.length; i++) { - if (declarations[i].init === null) { - counts.uninitialized++; - } else { - counts.initialized++; - } - } - return counts; - } - - /** - * Determines if there is more than one var statement in the current scope. - * @param {string} statementType node.kind, one of: "var", "let", or "const" - * @param {ASTNode[]} declarations List of declarations - * @returns {boolean} Returns true if it is the first var declaration, false if not. - * @private - */ - function hasOnlyOneStatement(statementType, declarations) { - - const declarationCounts = countDeclarations(declarations); - const currentOptions = options[statementType] || {}; - const currentScope = getCurrentScope(statementType); - const hasRequires = declarations.some(isRequire); - - if (currentOptions.uninitialized === MODE_ALWAYS && currentOptions.initialized === MODE_ALWAYS) { - if (currentScope.uninitialized || currentScope.initialized) { - if (!hasRequires) { - return false; - } - } - } - - if (declarationCounts.uninitialized > 0) { - if (currentOptions.uninitialized === MODE_ALWAYS && currentScope.uninitialized) { - return false; - } - } - if (declarationCounts.initialized > 0) { - if (currentOptions.initialized === MODE_ALWAYS && currentScope.initialized) { - if (!hasRequires) { - return false; - } - } - } - if (currentScope.required && hasRequires) { - return false; - } - recordTypes(statementType, declarations, currentScope); - return true; - } - - /** - * Fixer to join VariableDeclaration's into a single declaration - * @param {VariableDeclarator[]} declarations The `VariableDeclaration` to join - * @returns {Function} The fixer function - */ - function joinDeclarations(declarations) { - const declaration = declarations[0]; - const body = Array.isArray(declaration.parent.parent.body) ? declaration.parent.parent.body : []; - const currentIndex = body.findIndex(node => node.range[0] === declaration.parent.range[0]); - const previousNode = body[currentIndex - 1]; - - return fixer => { - const type = sourceCode.getTokenBefore(declaration); - const prevSemi = sourceCode.getTokenBefore(type); - const res = []; - - if (previousNode && previousNode.kind === sourceCode.getText(type)) { - if (prevSemi.value === ";") { - res.push(fixer.replaceText(prevSemi, ",")); - } else { - res.push(fixer.insertTextAfter(prevSemi, ",")); - } - res.push(fixer.replaceText(type, "")); - } - - return res; - }; - } - - /** - * Fixer to split a VariableDeclaration into individual declarations - * @param {VariableDeclaration} declaration The `VariableDeclaration` to split - * @returns {Function} The fixer function - */ - function splitDeclarations(declaration) { - return fixer => declaration.declarations.map(declarator => { - const tokenAfterDeclarator = sourceCode.getTokenAfter(declarator); - - if (tokenAfterDeclarator === null) { - return null; - } - - const afterComma = sourceCode.getTokenAfter(tokenAfterDeclarator, { includeComments: true }); - - if (tokenAfterDeclarator.value !== ",") { - return null; - } - - /* - * `var x,y` - * tokenAfterDeclarator ^^ afterComma - */ - if (afterComma.range[0] === tokenAfterDeclarator.range[1]) { - return fixer.replaceText(tokenAfterDeclarator, `; ${declaration.kind} `); - } - - /* - * `var x, - * tokenAfterDeclarator ^ - * y` - * ^ afterComma - */ - if ( - afterComma.loc.start.line > tokenAfterDeclarator.loc.end.line || - afterComma.type === "Line" || - afterComma.type === "Block" - ) { - let lastComment = afterComma; - - while (lastComment.type === "Line" || lastComment.type === "Block") { - lastComment = sourceCode.getTokenAfter(lastComment, { includeComments: true }); - } - - return fixer.replaceTextRange( - [tokenAfterDeclarator.range[0], lastComment.range[0]], - `;${sourceCode.text.slice(tokenAfterDeclarator.range[1], lastComment.range[0])}${declaration.kind} ` - ); - } - - return fixer.replaceText(tokenAfterDeclarator, `; ${declaration.kind}`); - }).filter(x => x); - } - - /** - * Checks a given VariableDeclaration node for errors. - * @param {ASTNode} node The VariableDeclaration node to check - * @returns {void} - * @private - */ - function checkVariableDeclaration(node) { - const parent = node.parent; - const type = node.kind; - - if (!options[type]) { - return; - } - - const declarations = node.declarations; - const declarationCounts = countDeclarations(declarations); - const mixedRequires = declarations.some(isRequire) && !declarations.every(isRequire); - - if (options[type].initialized === MODE_ALWAYS) { - if (options.separateRequires && mixedRequires) { - context.report({ - node, - messageId: "splitRequires" - }); - } - } - - // consecutive - const nodeIndex = (parent.body && parent.body.length > 0 && parent.body.indexOf(node)) || 0; - - if (nodeIndex > 0) { - const previousNode = parent.body[nodeIndex - 1]; - const isPreviousNodeDeclaration = previousNode.type === "VariableDeclaration"; - const declarationsWithPrevious = declarations.concat(previousNode.declarations || []); - - if ( - isPreviousNodeDeclaration && - previousNode.kind === type && - !(declarationsWithPrevious.some(isRequire) && !declarationsWithPrevious.every(isRequire)) - ) { - const previousDeclCounts = countDeclarations(previousNode.declarations); - - if (options[type].initialized === MODE_CONSECUTIVE && options[type].uninitialized === MODE_CONSECUTIVE) { - context.report({ - node, - messageId: "combine", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } else if (options[type].initialized === MODE_CONSECUTIVE && declarationCounts.initialized > 0 && previousDeclCounts.initialized > 0) { - context.report({ - node, - messageId: "combineInitialized", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } else if (options[type].uninitialized === MODE_CONSECUTIVE && - declarationCounts.uninitialized > 0 && - previousDeclCounts.uninitialized > 0) { - context.report({ - node, - messageId: "combineUninitialized", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } - } - } - - // always - if (!hasOnlyOneStatement(type, declarations)) { - if (options[type].initialized === MODE_ALWAYS && options[type].uninitialized === MODE_ALWAYS) { - context.report({ - node, - messageId: "combine", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } else { - if (options[type].initialized === MODE_ALWAYS && declarationCounts.initialized > 0) { - context.report({ - node, - messageId: "combineInitialized", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } - if (options[type].uninitialized === MODE_ALWAYS && declarationCounts.uninitialized > 0) { - if (node.parent.left === node && (node.parent.type === "ForInStatement" || node.parent.type === "ForOfStatement")) { - return; - } - context.report({ - node, - messageId: "combineUninitialized", - data: { - type - }, - fix: joinDeclarations(declarations) - }); - } - } - } - - // never - if (parent.type !== "ForStatement" || parent.init !== node) { - const totalDeclarations = declarationCounts.uninitialized + declarationCounts.initialized; - - if (totalDeclarations > 1) { - if (options[type].initialized === MODE_NEVER && options[type].uninitialized === MODE_NEVER) { - - // both initialized and uninitialized - context.report({ - node, - messageId: "split", - data: { - type - }, - fix: splitDeclarations(node) - }); - } else if (options[type].initialized === MODE_NEVER && declarationCounts.initialized > 0) { - - // initialized - context.report({ - node, - messageId: "splitInitialized", - data: { - type - }, - fix: splitDeclarations(node) - }); - } else if (options[type].uninitialized === MODE_NEVER && declarationCounts.uninitialized > 0) { - - // uninitialized - context.report({ - node, - messageId: "splitUninitialized", - data: { - type - }, - fix: splitDeclarations(node) - }); - } - } - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - Program: startFunction, - FunctionDeclaration: startFunction, - FunctionExpression: startFunction, - ArrowFunctionExpression: startFunction, - BlockStatement: startBlock, - ForStatement: startBlock, - ForInStatement: startBlock, - ForOfStatement: startBlock, - SwitchStatement: startBlock, - VariableDeclaration: checkVariableDeclaration, - "ForStatement:exit": endBlock, - "ForOfStatement:exit": endBlock, - "ForInStatement:exit": endBlock, - "SwitchStatement:exit": endBlock, - "BlockStatement:exit": endBlock, - "Program:exit": endFunction, - "FunctionDeclaration:exit": endFunction, - "FunctionExpression:exit": endFunction, - "ArrowFunctionExpression:exit": endFunction - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/operator-assignment.js b/tools/node_modules/eslint/lib/rules/operator-assignment.js deleted file mode 100644 index fdb0884922b6548d58ab8c11c6d3465ab0d8fd7c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/operator-assignment.js +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @fileoverview Rule to replace assignment expressions with operator assignment - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether an operator is commutative and has an operator assignment - * shorthand form. - * @param {string} operator Operator to check. - * @returns {boolean} True if the operator is commutative and has a - * shorthand form. - */ -function isCommutativeOperatorWithShorthand(operator) { - return ["*", "&", "^", "|"].indexOf(operator) >= 0; -} - -/** - * Checks whether an operator is not commutative and has an operator assignment - * shorthand form. - * @param {string} operator Operator to check. - * @returns {boolean} True if the operator is not commutative and has - * a shorthand form. - */ -function isNonCommutativeOperatorWithShorthand(operator) { - return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].indexOf(operator) >= 0; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -/** - * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) - * toString calls regardless of whether assignment shorthand is used) - * @param {ASTNode} node The node on the left side of the expression - * @returns {boolean} `true` if the node can be fixed - */ -function canBeFixed(node) { - return ( - node.type === "Identifier" || - ( - node.type === "MemberExpression" && - (node.object.type === "Identifier" || node.object.type === "ThisExpression") && - (!node.computed || node.property.type === "Literal") - ) - ); -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow assignment operator shorthand where possible", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/operator-assignment" - }, - - schema: [ - { - enum: ["always", "never"] - } - ], - - fixable: "code", - messages: { - replaced: "Assignment can be replaced with operator assignment.", - unexpected: "Unexpected operator assignment shorthand." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - /** - * Returns the operator token of an AssignmentExpression or BinaryExpression - * @param {ASTNode} node An AssignmentExpression or BinaryExpression node - * @returns {Token} The operator token in the node - */ - function getOperatorToken(node) { - return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); - } - - /** - * Ensures that an assignment uses the shorthand form where possible. - * @param {ASTNode} node An AssignmentExpression node. - * @returns {void} - */ - function verify(node) { - if (node.operator !== "=" || node.right.type !== "BinaryExpression") { - return; - } - - const left = node.left; - const expr = node.right; - const operator = expr.operator; - - if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { - if (astUtils.isSameReference(left, expr.left, true)) { - context.report({ - node, - messageId: "replaced", - fix(fixer) { - if (canBeFixed(left) && canBeFixed(expr.left)) { - const equalsToken = getOperatorToken(node); - const operatorToken = getOperatorToken(expr); - const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); - const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]); - - // Check for comments that would be removed. - if (sourceCode.commentsExistBetween(equalsToken, operatorToken)) { - return null; - } - - return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`); - } - return null; - } - }); - } else if (astUtils.isSameReference(left, expr.right, true) && isCommutativeOperatorWithShorthand(operator)) { - - /* - * This case can't be fixed safely. - * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would - * change the execution order of the valueOf() functions. - */ - context.report({ - node, - messageId: "replaced" - }); - } - } - } - - /** - * Warns if an assignment expression uses operator assignment shorthand. - * @param {ASTNode} node An AssignmentExpression node. - * @returns {void} - */ - function prohibit(node) { - if (node.operator !== "=" && !astUtils.isLogicalAssignmentOperator(node.operator)) { - context.report({ - node, - messageId: "unexpected", - fix(fixer) { - if (canBeFixed(node.left)) { - const firstToken = sourceCode.getFirstToken(node); - const operatorToken = getOperatorToken(node); - const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); - const newOperator = node.operator.slice(0, -1); - let rightText; - - // Check for comments that would be duplicated. - if (sourceCode.commentsExistBetween(firstToken, operatorToken)) { - return null; - } - - // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. - if ( - astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) && - !astUtils.isParenthesised(sourceCode, node.right) - ) { - rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; - } else { - const tokenAfterOperator = sourceCode.getTokenAfter(operatorToken, { includeComments: true }); - let rightTextPrefix = ""; - - if ( - operatorToken.range[1] === tokenAfterOperator.range[0] && - !astUtils.canTokensBeAdjacent({ type: "Punctuator", value: newOperator }, tokenAfterOperator) - ) { - rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar - } - - rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`; - } - - return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); - } - return null; - } - }); - } - } - - return { - AssignmentExpression: context.options[0] !== "never" ? verify : prohibit - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/operator-linebreak.js b/tools/node_modules/eslint/lib/rules/operator-linebreak.js deleted file mode 100644 index 3395feae655f64d4348ffcab8fe227e3c22c82c3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/operator-linebreak.js +++ /dev/null @@ -1,250 +0,0 @@ -/** - * @fileoverview Operator linebreak - enforces operator linebreak style of two types: after and before - * @author Benoît Zugmeyer - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent linebreak style for operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/operator-linebreak" - }, - - schema: [ - { - enum: ["after", "before", "none", null] - }, - { - type: "object", - properties: { - overrides: { - type: "object", - properties: { - anyOf: { - type: "string", - enum: ["after", "before", "none", "ignore"] - } - } - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - operatorAtBeginning: "'{{operator}}' should be placed at the beginning of the line.", - operatorAtEnd: "'{{operator}}' should be placed at the end of the line.", - badLinebreak: "Bad line breaking before and after '{{operator}}'.", - noLinebreak: "There should be no line break before or after '{{operator}}'." - } - }, - - create(context) { - - const usedDefaultGlobal = !context.options[0]; - const globalStyle = context.options[0] || "after"; - const options = context.options[1] || {}; - const styleOverrides = options.overrides ? Object.assign({}, options.overrides) : {}; - - if (usedDefaultGlobal && !styleOverrides["?"]) { - styleOverrides["?"] = "before"; - } - - if (usedDefaultGlobal && !styleOverrides[":"]) { - styleOverrides[":"] = "before"; - } - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Gets a fixer function to fix rule issues - * @param {Token} operatorToken The operator token of an expression - * @param {string} desiredStyle The style for the rule. One of 'before', 'after', 'none' - * @returns {Function} A fixer function - */ - function getFixer(operatorToken, desiredStyle) { - return fixer => { - const tokenBefore = sourceCode.getTokenBefore(operatorToken); - const tokenAfter = sourceCode.getTokenAfter(operatorToken); - const textBefore = sourceCode.text.slice(tokenBefore.range[1], operatorToken.range[0]); - const textAfter = sourceCode.text.slice(operatorToken.range[1], tokenAfter.range[0]); - const hasLinebreakBefore = !astUtils.isTokenOnSameLine(tokenBefore, operatorToken); - const hasLinebreakAfter = !astUtils.isTokenOnSameLine(operatorToken, tokenAfter); - let newTextBefore, newTextAfter; - - if (hasLinebreakBefore !== hasLinebreakAfter && desiredStyle !== "none") { - - // If there is a comment before and after the operator, don't do a fix. - if (sourceCode.getTokenBefore(operatorToken, { includeComments: true }) !== tokenBefore && - sourceCode.getTokenAfter(operatorToken, { includeComments: true }) !== tokenAfter) { - - return null; - } - - /* - * If there is only one linebreak and it's on the wrong side of the operator, swap the text before and after the operator. - * foo && - * bar - * would get fixed to - * foo - * && bar - */ - newTextBefore = textAfter; - newTextAfter = textBefore; - } else { - const LINEBREAK_REGEX = astUtils.createGlobalLinebreakMatcher(); - - // Otherwise, if no linebreak is desired and no comments interfere, replace the linebreaks with empty strings. - newTextBefore = desiredStyle === "before" || textBefore.trim() ? textBefore : textBefore.replace(LINEBREAK_REGEX, ""); - newTextAfter = desiredStyle === "after" || textAfter.trim() ? textAfter : textAfter.replace(LINEBREAK_REGEX, ""); - - // If there was no change (due to interfering comments), don't output a fix. - if (newTextBefore === textBefore && newTextAfter === textAfter) { - return null; - } - } - - if (newTextAfter === "" && tokenAfter.type === "Punctuator" && "+-".includes(operatorToken.value) && tokenAfter.value === operatorToken.value) { - - // To avoid accidentally creating a ++ or -- operator, insert a space if the operator is a +/- and the following token is a unary +/-. - newTextAfter += " "; - } - - return fixer.replaceTextRange([tokenBefore.range[1], tokenAfter.range[0]], newTextBefore + operatorToken.value + newTextAfter); - }; - } - - /** - * Checks the operator placement - * @param {ASTNode} node The node to check - * @param {ASTNode} leftSide The node that comes before the operator in `node` - * @private - * @returns {void} - */ - function validateNode(node, leftSide) { - - /* - * When the left part of a binary expression is a single expression wrapped in - * parentheses (ex: `(a) + b`), leftToken will be the last token of the expression - * and operatorToken will be the closing parenthesis. - * The leftToken should be the last closing parenthesis, and the operatorToken - * should be the token right after that. - */ - const operatorToken = sourceCode.getTokenAfter(leftSide, astUtils.isNotClosingParenToken); - const leftToken = sourceCode.getTokenBefore(operatorToken); - const rightToken = sourceCode.getTokenAfter(operatorToken); - const operator = operatorToken.value; - const operatorStyleOverride = styleOverrides[operator]; - const style = operatorStyleOverride || globalStyle; - const fix = getFixer(operatorToken, style); - - // if single line - if (astUtils.isTokenOnSameLine(leftToken, operatorToken) && - astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - - // do nothing. - - } else if (operatorStyleOverride !== "ignore" && !astUtils.isTokenOnSameLine(leftToken, operatorToken) && - !astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - - // lone operator - context.report({ - node, - loc: operatorToken.loc, - messageId: "badLinebreak", - data: { - operator - }, - fix - }); - - } else if (style === "before" && astUtils.isTokenOnSameLine(leftToken, operatorToken)) { - - context.report({ - node, - loc: operatorToken.loc, - messageId: "operatorAtBeginning", - data: { - operator - }, - fix - }); - - } else if (style === "after" && astUtils.isTokenOnSameLine(operatorToken, rightToken)) { - - context.report({ - node, - loc: operatorToken.loc, - messageId: "operatorAtEnd", - data: { - operator - }, - fix - }); - - } else if (style === "none") { - - context.report({ - node, - loc: operatorToken.loc, - messageId: "noLinebreak", - data: { - operator - }, - fix - }); - - } - } - - /** - * Validates a binary expression using `validateNode` - * @param {BinaryExpression|LogicalExpression|AssignmentExpression} node node to be validated - * @returns {void} - */ - function validateBinaryExpression(node) { - validateNode(node, node.left); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - BinaryExpression: validateBinaryExpression, - LogicalExpression: validateBinaryExpression, - AssignmentExpression: validateBinaryExpression, - VariableDeclarator(node) { - if (node.init) { - validateNode(node, node.id); - } - }, - ConditionalExpression(node) { - validateNode(node, node.test); - validateNode(node, node.consequent); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/padded-blocks.js b/tools/node_modules/eslint/lib/rules/padded-blocks.js deleted file mode 100644 index fa65eae4e0222d5001831d9cebcca0cdbccb031d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/padded-blocks.js +++ /dev/null @@ -1,297 +0,0 @@ -/** - * @fileoverview A rule to ensure blank lines within blocks. - * @author Mathias Schreck - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow padding within blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/padded-blocks" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - blocks: { - enum: ["always", "never"] - }, - switches: { - enum: ["always", "never"] - }, - classes: { - enum: ["always", "never"] - } - }, - additionalProperties: false, - minProperties: 1 - } - ] - }, - { - type: "object", - properties: { - allowSingleLineBlocks: { - type: "boolean" - } - } - } - ], - - messages: { - alwaysPadBlock: "Block must be padded by blank lines.", - neverPadBlock: "Block must not be padded by blank lines." - } - }, - - create(context) { - const options = {}; - const typeOptions = context.options[0] || "always"; - const exceptOptions = context.options[1] || {}; - - if (typeof typeOptions === "string") { - const shouldHavePadding = typeOptions === "always"; - - options.blocks = shouldHavePadding; - options.switches = shouldHavePadding; - options.classes = shouldHavePadding; - } else { - if (Object.prototype.hasOwnProperty.call(typeOptions, "blocks")) { - options.blocks = typeOptions.blocks === "always"; - } - if (Object.prototype.hasOwnProperty.call(typeOptions, "switches")) { - options.switches = typeOptions.switches === "always"; - } - if (Object.prototype.hasOwnProperty.call(typeOptions, "classes")) { - options.classes = typeOptions.classes === "always"; - } - } - - if (Object.prototype.hasOwnProperty.call(exceptOptions, "allowSingleLineBlocks")) { - options.allowSingleLineBlocks = exceptOptions.allowSingleLineBlocks === true; - } - - const sourceCode = context.getSourceCode(); - - /** - * Gets the open brace token from a given node. - * @param {ASTNode} node A BlockStatement or SwitchStatement node from which to get the open brace. - * @returns {Token} The token of the open brace. - */ - function getOpenBrace(node) { - if (node.type === "SwitchStatement") { - return sourceCode.getTokenBefore(node.cases[0]); - } - return sourceCode.getFirstToken(node); - } - - /** - * Checks if the given parameter is a comment node - * @param {ASTNode|Token} node An AST node or token - * @returns {boolean} True if node is a comment - */ - function isComment(node) { - return node.type === "Line" || node.type === "Block"; - } - - /** - * Checks if there is padding between two tokens - * @param {Token} first The first token - * @param {Token} second The second token - * @returns {boolean} True if there is at least a line between the tokens - */ - function isPaddingBetweenTokens(first, second) { - return second.loc.start.line - first.loc.end.line >= 2; - } - - - /** - * Checks if the given token has a blank line after it. - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the token is followed by a blank line. - */ - function getFirstBlockToken(token) { - let prev, - first = token; - - do { - prev = first; - first = sourceCode.getTokenAfter(first, { includeComments: true }); - } while (isComment(first) && first.loc.start.line === prev.loc.end.line); - - return first; - } - - /** - * Checks if the given token is preceded by a blank line. - * @param {Token} token The token to check - * @returns {boolean} Whether or not the token is preceded by a blank line - */ - function getLastBlockToken(token) { - let last = token, - next; - - do { - next = last; - last = sourceCode.getTokenBefore(last, { includeComments: true }); - } while (isComment(last) && last.loc.end.line === next.loc.start.line); - - return last; - } - - /** - * Checks if a node should be padded, according to the rule config. - * @param {ASTNode} node The AST node to check. - * @returns {boolean} True if the node should be padded, false otherwise. - */ - function requirePaddingFor(node) { - switch (node.type) { - case "BlockStatement": - return options.blocks; - case "SwitchStatement": - return options.switches; - case "ClassBody": - return options.classes; - - /* istanbul ignore next */ - default: - throw new Error("unreachable"); - } - } - - /** - * Checks the given BlockStatement node to be padded if the block is not empty. - * @param {ASTNode} node The AST node of a BlockStatement. - * @returns {void} undefined. - */ - function checkPadding(node) { - const openBrace = getOpenBrace(node), - firstBlockToken = getFirstBlockToken(openBrace), - tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true }), - closeBrace = sourceCode.getLastToken(node), - lastBlockToken = getLastBlockToken(closeBrace), - tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true }), - blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken), - blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast); - - if (options.allowSingleLineBlocks && astUtils.isTokenOnSameLine(tokenBeforeFirst, tokenAfterLast)) { - return; - } - - if (requirePaddingFor(node)) { - - if (!blockHasTopPadding) { - context.report({ - node, - loc: { - start: tokenBeforeFirst.loc.start, - end: firstBlockToken.loc.start - }, - fix(fixer) { - return fixer.insertTextAfter(tokenBeforeFirst, "\n"); - }, - messageId: "alwaysPadBlock" - }); - } - if (!blockHasBottomPadding) { - context.report({ - node, - loc: { - end: tokenAfterLast.loc.start, - start: lastBlockToken.loc.end - }, - fix(fixer) { - return fixer.insertTextBefore(tokenAfterLast, "\n"); - }, - messageId: "alwaysPadBlock" - }); - } - } else { - if (blockHasTopPadding) { - - context.report({ - node, - loc: { - start: tokenBeforeFirst.loc.start, - end: firstBlockToken.loc.start - }, - fix(fixer) { - return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], "\n"); - }, - messageId: "neverPadBlock" - }); - } - - if (blockHasBottomPadding) { - - context.report({ - node, - loc: { - end: tokenAfterLast.loc.start, - start: lastBlockToken.loc.end - }, - messageId: "neverPadBlock", - fix(fixer) { - return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], "\n"); - } - }); - } - } - } - - const rule = {}; - - if (Object.prototype.hasOwnProperty.call(options, "switches")) { - rule.SwitchStatement = function(node) { - if (node.cases.length === 0) { - return; - } - checkPadding(node); - }; - } - - if (Object.prototype.hasOwnProperty.call(options, "blocks")) { - rule.BlockStatement = function(node) { - if (node.body.length === 0) { - return; - } - checkPadding(node); - }; - } - - if (Object.prototype.hasOwnProperty.call(options, "classes")) { - rule.ClassBody = function(node) { - if (node.body.length === 0) { - return; - } - checkPadding(node); - }; - } - - return rule; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js b/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js deleted file mode 100644 index c97b9956b7136e9c5997de8526157fb70333878b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/padding-line-between-statements.js +++ /dev/null @@ -1,632 +0,0 @@ -/** - * @fileoverview Rule to require or disallow newlines between statements - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const LT = `[${Array.from(astUtils.LINEBREAKS).join("")}]`; -const PADDING_LINE_SEQUENCE = new RegExp( - String.raw`^(\s*?${LT})\s*${LT}(\s*;?)$`, - "u" -); -const CJS_EXPORT = /^(?:module\s*\.\s*)?exports(?:\s*\.|\s*\[|$)/u; -const CJS_IMPORT = /^require\(/u; - -/** - * Creates tester which check if a node starts with specific keyword. - * @param {string} keyword The keyword to test. - * @returns {Object} the created tester. - * @private - */ -function newKeywordTester(keyword) { - return { - test: (node, sourceCode) => - sourceCode.getFirstToken(node).value === keyword - }; -} - -/** - * Creates tester which check if a node starts with specific keyword and spans a single line. - * @param {string} keyword The keyword to test. - * @returns {Object} the created tester. - * @private - */ -function newSinglelineKeywordTester(keyword) { - return { - test: (node, sourceCode) => - node.loc.start.line === node.loc.end.line && - sourceCode.getFirstToken(node).value === keyword - }; -} - -/** - * Creates tester which check if a node starts with specific keyword and spans multiple lines. - * @param {string} keyword The keyword to test. - * @returns {Object} the created tester. - * @private - */ -function newMultilineKeywordTester(keyword) { - return { - test: (node, sourceCode) => - node.loc.start.line !== node.loc.end.line && - sourceCode.getFirstToken(node).value === keyword - }; -} - -/** - * Creates tester which check if a node is specific type. - * @param {string} type The node type to test. - * @returns {Object} the created tester. - * @private - */ -function newNodeTypeTester(type) { - return { - test: node => - node.type === type - }; -} - -/** - * Checks the given node is an expression statement of IIFE. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is an expression statement of IIFE. - * @private - */ -function isIIFEStatement(node) { - if (node.type === "ExpressionStatement") { - let call = astUtils.skipChainExpression(node.expression); - - if (call.type === "UnaryExpression") { - call = astUtils.skipChainExpression(call.argument); - } - return call.type === "CallExpression" && astUtils.isFunction(call.callee); - } - return false; -} - -/** - * Checks whether the given node is a block-like statement. - * This checks the last token of the node is the closing brace of a block. - * @param {SourceCode} sourceCode The source code to get tokens. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is a block-like statement. - * @private - */ -function isBlockLikeStatement(sourceCode, node) { - - // do-while with a block is a block-like statement. - if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") { - return true; - } - - /* - * IIFE is a block-like statement specially from - * JSCS#disallowPaddingNewLinesAfterBlocks. - */ - if (isIIFEStatement(node)) { - return true; - } - - // Checks the last token is a closing brace of blocks. - const lastToken = sourceCode.getLastToken(node, astUtils.isNotSemicolonToken); - const belongingNode = lastToken && astUtils.isClosingBraceToken(lastToken) - ? sourceCode.getNodeByRangeIndex(lastToken.range[0]) - : null; - - return Boolean(belongingNode) && ( - belongingNode.type === "BlockStatement" || - belongingNode.type === "SwitchStatement" - ); -} - -/** - * Check whether the given node is a directive or not. - * @param {ASTNode} node The node to check. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {boolean} `true` if the node is a directive. - */ -function isDirective(node, sourceCode) { - return ( - node.type === "ExpressionStatement" && - ( - node.parent.type === "Program" || - ( - node.parent.type === "BlockStatement" && - astUtils.isFunction(node.parent.parent) - ) - ) && - node.expression.type === "Literal" && - typeof node.expression.value === "string" && - !astUtils.isParenthesised(sourceCode, node.expression) - ); -} - -/** - * Check whether the given node is a part of directive prologue or not. - * @param {ASTNode} node The node to check. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {boolean} `true` if the node is a part of directive prologue. - */ -function isDirectivePrologue(node, sourceCode) { - if (isDirective(node, sourceCode)) { - for (const sibling of node.parent.body) { - if (sibling === node) { - break; - } - if (!isDirective(sibling, sourceCode)) { - return false; - } - } - return true; - } - return false; -} - -/** - * Gets the actual last token. - * - * If a semicolon is semicolon-less style's semicolon, this ignores it. - * For example: - * - * foo() - * ;[1, 2, 3].forEach(bar) - * @param {SourceCode} sourceCode The source code to get tokens. - * @param {ASTNode} node The node to get. - * @returns {Token} The actual last token. - * @private - */ -function getActualLastToken(sourceCode, node) { - const semiToken = sourceCode.getLastToken(node); - const prevToken = sourceCode.getTokenBefore(semiToken); - const nextToken = sourceCode.getTokenAfter(semiToken); - const isSemicolonLessStyle = Boolean( - prevToken && - nextToken && - prevToken.range[0] >= node.range[0] && - astUtils.isSemicolonToken(semiToken) && - semiToken.loc.start.line !== prevToken.loc.end.line && - semiToken.loc.end.line === nextToken.loc.start.line - ); - - return isSemicolonLessStyle ? prevToken : semiToken; -} - -/** - * This returns the concatenation of the first 2 captured strings. - * @param {string} _ Unused. Whole matched string. - * @param {string} trailingSpaces The trailing spaces of the first line. - * @param {string} indentSpaces The indentation spaces of the last line. - * @returns {string} The concatenation of trailingSpaces and indentSpaces. - * @private - */ -function replacerToRemovePaddingLines(_, trailingSpaces, indentSpaces) { - return trailingSpaces + indentSpaces; -} - -/** - * Check and report statements for `any` configuration. - * It does nothing. - * @returns {void} - * @private - */ -function verifyForAny() { -} - -/** - * Check and report statements for `never` configuration. - * This autofix removes blank lines between the given 2 statements. - * However, if comments exist between 2 blank lines, it does not remove those - * blank lines automatically. - * @param {RuleContext} context The rule context to report. - * @param {ASTNode} _ Unused. The previous node to check. - * @param {ASTNode} nextNode The next node to check. - * @param {Array} paddingLines The array of token pairs that blank - * lines exist between the pair. - * @returns {void} - * @private - */ -function verifyForNever(context, _, nextNode, paddingLines) { - if (paddingLines.length === 0) { - return; - } - - context.report({ - node: nextNode, - messageId: "unexpectedBlankLine", - fix(fixer) { - if (paddingLines.length >= 2) { - return null; - } - - const prevToken = paddingLines[0][0]; - const nextToken = paddingLines[0][1]; - const start = prevToken.range[1]; - const end = nextToken.range[0]; - const text = context.getSourceCode().text - .slice(start, end) - .replace(PADDING_LINE_SEQUENCE, replacerToRemovePaddingLines); - - return fixer.replaceTextRange([start, end], text); - } - }); -} - -/** - * Check and report statements for `always` configuration. - * This autofix inserts a blank line between the given 2 statements. - * If the `prevNode` has trailing comments, it inserts a blank line after the - * trailing comments. - * @param {RuleContext} context The rule context to report. - * @param {ASTNode} prevNode The previous node to check. - * @param {ASTNode} nextNode The next node to check. - * @param {Array} paddingLines The array of token pairs that blank - * lines exist between the pair. - * @returns {void} - * @private - */ -function verifyForAlways(context, prevNode, nextNode, paddingLines) { - if (paddingLines.length > 0) { - return; - } - - context.report({ - node: nextNode, - messageId: "expectedBlankLine", - fix(fixer) { - const sourceCode = context.getSourceCode(); - let prevToken = getActualLastToken(sourceCode, prevNode); - const nextToken = sourceCode.getFirstTokenBetween( - prevToken, - nextNode, - { - includeComments: true, - - /** - * Skip the trailing comments of the previous node. - * This inserts a blank line after the last trailing comment. - * - * For example: - * - * foo(); // trailing comment. - * // comment. - * bar(); - * - * Get fixed to: - * - * foo(); // trailing comment. - * - * // comment. - * bar(); - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is not a trailing comment. - * @private - */ - filter(token) { - if (astUtils.isTokenOnSameLine(prevToken, token)) { - prevToken = token; - return false; - } - return true; - } - } - ) || nextNode; - const insertText = astUtils.isTokenOnSameLine(prevToken, nextToken) - ? "\n\n" - : "\n"; - - return fixer.insertTextAfter(prevToken, insertText); - } - }); -} - -/** - * Types of blank lines. - * `any`, `never`, and `always` are defined. - * Those have `verify` method to check and report statements. - * @private - */ -const PaddingTypes = { - any: { verify: verifyForAny }, - never: { verify: verifyForNever }, - always: { verify: verifyForAlways } -}; - -/** - * Types of statements. - * Those have `test` method to check it matches to the given statement. - * @private - */ -const StatementTypes = { - "*": { test: () => true }, - "block-like": { - test: (node, sourceCode) => isBlockLikeStatement(sourceCode, node) - }, - "cjs-export": { - test: (node, sourceCode) => - node.type === "ExpressionStatement" && - node.expression.type === "AssignmentExpression" && - CJS_EXPORT.test(sourceCode.getText(node.expression.left)) - }, - "cjs-import": { - test: (node, sourceCode) => - node.type === "VariableDeclaration" && - node.declarations.length > 0 && - Boolean(node.declarations[0].init) && - CJS_IMPORT.test(sourceCode.getText(node.declarations[0].init)) - }, - directive: { - test: isDirectivePrologue - }, - expression: { - test: (node, sourceCode) => - node.type === "ExpressionStatement" && - !isDirectivePrologue(node, sourceCode) - }, - iife: { - test: isIIFEStatement - }, - "multiline-block-like": { - test: (node, sourceCode) => - node.loc.start.line !== node.loc.end.line && - isBlockLikeStatement(sourceCode, node) - }, - "multiline-expression": { - test: (node, sourceCode) => - node.loc.start.line !== node.loc.end.line && - node.type === "ExpressionStatement" && - !isDirectivePrologue(node, sourceCode) - }, - - "multiline-const": newMultilineKeywordTester("const"), - "multiline-let": newMultilineKeywordTester("let"), - "multiline-var": newMultilineKeywordTester("var"), - "singleline-const": newSinglelineKeywordTester("const"), - "singleline-let": newSinglelineKeywordTester("let"), - "singleline-var": newSinglelineKeywordTester("var"), - - block: newNodeTypeTester("BlockStatement"), - empty: newNodeTypeTester("EmptyStatement"), - function: newNodeTypeTester("FunctionDeclaration"), - - break: newKeywordTester("break"), - case: newKeywordTester("case"), - class: newKeywordTester("class"), - const: newKeywordTester("const"), - continue: newKeywordTester("continue"), - debugger: newKeywordTester("debugger"), - default: newKeywordTester("default"), - do: newKeywordTester("do"), - export: newKeywordTester("export"), - for: newKeywordTester("for"), - if: newKeywordTester("if"), - import: newKeywordTester("import"), - let: newKeywordTester("let"), - return: newKeywordTester("return"), - switch: newKeywordTester("switch"), - throw: newKeywordTester("throw"), - try: newKeywordTester("try"), - var: newKeywordTester("var"), - while: newKeywordTester("while"), - with: newKeywordTester("with") -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow padding lines between statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/padding-line-between-statements" - }, - - fixable: "whitespace", - - schema: { - definitions: { - paddingType: { - enum: Object.keys(PaddingTypes) - }, - statementType: { - anyOf: [ - { enum: Object.keys(StatementTypes) }, - { - type: "array", - items: { enum: Object.keys(StatementTypes) }, - minItems: 1, - uniqueItems: true, - additionalItems: false - } - ] - } - }, - type: "array", - items: { - type: "object", - properties: { - blankLine: { $ref: "#/definitions/paddingType" }, - prev: { $ref: "#/definitions/statementType" }, - next: { $ref: "#/definitions/statementType" } - }, - additionalProperties: false, - required: ["blankLine", "prev", "next"] - }, - additionalItems: false - }, - - messages: { - unexpectedBlankLine: "Unexpected blank line before this statement.", - expectedBlankLine: "Expected blank line before this statement." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const configureList = context.options || []; - let scopeInfo = null; - - /** - * Processes to enter to new scope. - * This manages the current previous statement. - * @returns {void} - * @private - */ - function enterScope() { - scopeInfo = { - upper: scopeInfo, - prevNode: null - }; - } - - /** - * Processes to exit from the current scope. - * @returns {void} - * @private - */ - function exitScope() { - scopeInfo = scopeInfo.upper; - } - - /** - * Checks whether the given node matches the given type. - * @param {ASTNode} node The statement node to check. - * @param {string|string[]} type The statement type to check. - * @returns {boolean} `true` if the statement node matched the type. - * @private - */ - function match(node, type) { - let innerStatementNode = node; - - while (innerStatementNode.type === "LabeledStatement") { - innerStatementNode = innerStatementNode.body; - } - if (Array.isArray(type)) { - return type.some(match.bind(null, innerStatementNode)); - } - return StatementTypes[type].test(innerStatementNode, sourceCode); - } - - /** - * Finds the last matched configure from configureList. - * @param {ASTNode} prevNode The previous statement to match. - * @param {ASTNode} nextNode The current statement to match. - * @returns {Object} The tester of the last matched configure. - * @private - */ - function getPaddingType(prevNode, nextNode) { - for (let i = configureList.length - 1; i >= 0; --i) { - const configure = configureList[i]; - const matched = - match(prevNode, configure.prev) && - match(nextNode, configure.next); - - if (matched) { - return PaddingTypes[configure.blankLine]; - } - } - return PaddingTypes.any; - } - - /** - * Gets padding line sequences between the given 2 statements. - * Comments are separators of the padding line sequences. - * @param {ASTNode} prevNode The previous statement to count. - * @param {ASTNode} nextNode The current statement to count. - * @returns {Array} The array of token pairs. - * @private - */ - function getPaddingLineSequences(prevNode, nextNode) { - const pairs = []; - let prevToken = getActualLastToken(sourceCode, prevNode); - - if (nextNode.loc.start.line - prevToken.loc.end.line >= 2) { - do { - const token = sourceCode.getTokenAfter( - prevToken, - { includeComments: true } - ); - - if (token.loc.start.line - prevToken.loc.end.line >= 2) { - pairs.push([prevToken, token]); - } - prevToken = token; - - } while (prevToken.range[0] < nextNode.range[0]); - } - - return pairs; - } - - /** - * Verify padding lines between the given node and the previous node. - * @param {ASTNode} node The node to verify. - * @returns {void} - * @private - */ - function verify(node) { - const parentType = node.parent.type; - const validParent = - astUtils.STATEMENT_LIST_PARENTS.has(parentType) || - parentType === "SwitchStatement"; - - if (!validParent) { - return; - } - - // Save this node as the current previous statement. - const prevNode = scopeInfo.prevNode; - - // Verify. - if (prevNode) { - const type = getPaddingType(prevNode, node); - const paddingLines = getPaddingLineSequences(prevNode, node); - - type.verify(context, prevNode, node, paddingLines); - } - - scopeInfo.prevNode = node; - } - - /** - * Verify padding lines between the given node and the previous node. - * Then process to enter to new scope. - * @param {ASTNode} node The node to verify. - * @returns {void} - * @private - */ - function verifyThenEnterScope(node) { - verify(node); - enterScope(); - } - - return { - Program: enterScope, - BlockStatement: enterScope, - SwitchStatement: enterScope, - "Program:exit": exitScope, - "BlockStatement:exit": exitScope, - "SwitchStatement:exit": exitScope, - - ":statement": verify, - - SwitchCase: verifyThenEnterScope, - "SwitchCase:exit": exitScope - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-arrow-callback.js b/tools/node_modules/eslint/lib/rules/prefer-arrow-callback.js deleted file mode 100644 index ee5cfe3c8c7fd9b68d0b1e84a89c61dd1ffc7186..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-arrow-callback.js +++ /dev/null @@ -1,379 +0,0 @@ -/** - * @fileoverview A rule to suggest using arrow functions as callbacks. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given variable is a function name. - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is a function name. - */ -function isFunctionName(variable) { - return variable && variable.defs[0].type === "FunctionName"; -} - -/** - * Checks whether or not a given MetaProperty node equals to a given value. - * @param {ASTNode} node A MetaProperty node to check. - * @param {string} metaName The name of `MetaProperty.meta`. - * @param {string} propertyName The name of `MetaProperty.property`. - * @returns {boolean} `true` if the node is the specific value. - */ -function checkMetaProperty(node, metaName, propertyName) { - return node.meta.name === metaName && node.property.name === propertyName; -} - -/** - * Gets the variable object of `arguments` which is defined implicitly. - * @param {eslint-scope.Scope} scope A scope to get. - * @returns {eslint-scope.Variable} The found variable object. - */ -function getVariableOfArguments(scope) { - const variables = scope.variables; - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - if (variable.name === "arguments") { - - /* - * If there was a parameter which is named "arguments", the - * implicit "arguments" is not defined. - * So does fast return with null. - */ - return (variable.identifiers.length === 0) ? variable : null; - } - } - - /* istanbul ignore next */ - return null; -} - -/** - * Checks whether or not a given node is a callback. - * @param {ASTNode} node A node to check. - * @returns {Object} - * {boolean} retv.isCallback - `true` if the node is a callback. - * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`. - */ -function getCallbackInfo(node) { - const retv = { isCallback: false, isLexicalThis: false }; - let currentNode = node; - let parent = node.parent; - let bound = false; - - while (currentNode) { - switch (parent.type) { - - // Checks parents recursively. - - case "LogicalExpression": - case "ChainExpression": - case "ConditionalExpression": - break; - - // Checks whether the parent node is `.bind(this)` call. - case "MemberExpression": - if ( - parent.object === currentNode && - !parent.property.computed && - parent.property.type === "Identifier" && - parent.property.name === "bind" - ) { - const maybeCallee = parent.parent.type === "ChainExpression" - ? parent.parent - : parent; - - if (astUtils.isCallee(maybeCallee)) { - if (!bound) { - bound = true; // Use only the first `.bind()` to make `isLexicalThis` value. - retv.isLexicalThis = ( - maybeCallee.parent.arguments.length === 1 && - maybeCallee.parent.arguments[0].type === "ThisExpression" - ); - } - parent = maybeCallee.parent; - } else { - return retv; - } - } else { - return retv; - } - break; - - // Checks whether the node is a callback. - case "CallExpression": - case "NewExpression": - if (parent.callee !== currentNode) { - retv.isCallback = true; - } - return retv; - - default: - return retv; - } - - currentNode = parent; - parent = parent.parent; - } - - /* istanbul ignore next */ - throw new Error("unreachable"); -} - -/** - * Checks whether a simple list of parameters contains any duplicates. This does not handle complex - * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate - * parameter names anyway. Instead, it always returns `false` for complex parameter lists. - * @param {ASTNode[]} paramsList The list of parameters for a function - * @returns {boolean} `true` if the list of parameters contains any duplicates - */ -function hasDuplicateParams(paramsList) { - return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require using arrow functions for callbacks", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-arrow-callback" - }, - - schema: [ - { - type: "object", - properties: { - allowNamedFunctions: { - type: "boolean", - default: false - }, - allowUnboundThis: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - preferArrowCallback: "Unexpected function expression." - } - }, - - create(context) { - const options = context.options[0] || {}; - - const allowUnboundThis = options.allowUnboundThis !== false; // default to true - const allowNamedFunctions = options.allowNamedFunctions; - const sourceCode = context.getSourceCode(); - - /* - * {Array<{this: boolean, super: boolean, meta: boolean}>} - * - this - A flag which shows there are one or more ThisExpression. - * - super - A flag which shows there are one or more Super. - * - meta - A flag which shows there are one or more MethProperty. - */ - let stack = []; - - /** - * Pushes new function scope with all `false` flags. - * @returns {void} - */ - function enterScope() { - stack.push({ this: false, super: false, meta: false }); - } - - /** - * Pops a function scope from the stack. - * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope. - */ - function exitScope() { - return stack.pop(); - } - - return { - - // Reset internal state. - Program() { - stack = []; - }, - - // If there are below, it cannot replace with arrow functions merely. - ThisExpression() { - const info = stack[stack.length - 1]; - - if (info) { - info.this = true; - } - }, - - Super() { - const info = stack[stack.length - 1]; - - if (info) { - info.super = true; - } - }, - - MetaProperty(node) { - const info = stack[stack.length - 1]; - - if (info && checkMetaProperty(node, "new", "target")) { - info.meta = true; - } - }, - - // To skip nested scopes. - FunctionDeclaration: enterScope, - "FunctionDeclaration:exit": exitScope, - - // Main. - FunctionExpression: enterScope, - "FunctionExpression:exit"(node) { - const scopeInfo = exitScope(); - - // Skip named function expressions - if (allowNamedFunctions && node.id && node.id.name) { - return; - } - - // Skip generators. - if (node.generator) { - return; - } - - // Skip recursive functions. - const nameVar = context.getDeclaredVariables(node)[0]; - - if (isFunctionName(nameVar) && nameVar.references.length > 0) { - return; - } - - // Skip if it's using arguments. - const variable = getVariableOfArguments(context.getScope()); - - if (variable && variable.references.length > 0) { - return; - } - - // Reports if it's a callback which can replace with arrows. - const callbackInfo = getCallbackInfo(node); - - if (callbackInfo.isCallback && - (!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) && - !scopeInfo.super && - !scopeInfo.meta - ) { - context.report({ - node, - messageId: "preferArrowCallback", - *fix(fixer) { - if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) { - - /* - * If the callback function does not have .bind(this) and contains a reference to `this`, there - * is no way to determine what `this` should be, so don't perform any fixes. - * If the callback function has duplicates in its list of parameters (possible in sloppy mode), - * don't replace it with an arrow function, because this is a SyntaxError with arrow functions. - */ - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - // Remove `.bind(this)` if exists. - if (callbackInfo.isLexicalThis) { - const memberNode = node.parent; - - /* - * If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically. - * E.g. `(foo || function(){}).bind(this)` - */ - if (memberNode.type !== "MemberExpression") { - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - const callNode = memberNode.parent; - const firstTokenToRemove = sourceCode.getTokenAfter(memberNode.object, astUtils.isNotClosingParenToken); - const lastTokenToRemove = sourceCode.getLastToken(callNode); - - /* - * If the member expression is parenthesized, don't remove the right paren. - * E.g. `(function(){}.bind)(this)` - * ^^^^^^^^^^^^ - */ - if (astUtils.isParenthesised(sourceCode, memberNode)) { - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - // If comments exist in the `.bind(this)`, don't remove those. - if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) { - return; // eslint-disable-line eslint-plugin/fixer-return -- false positive - } - - yield fixer.removeRange([firstTokenToRemove.range[0], lastTokenToRemove.range[1]]); - } - - // Convert the function expression to an arrow function. - const functionToken = sourceCode.getFirstToken(node, node.async ? 1 : 0); - const leftParenToken = sourceCode.getTokenAfter(functionToken, astUtils.isOpeningParenToken); - - if (sourceCode.commentsExistBetween(functionToken, leftParenToken)) { - - // Remove only extra tokens to keep comments. - yield fixer.remove(functionToken); - if (node.id) { - yield fixer.remove(node.id); - } - } else { - - // Remove extra tokens and spaces. - yield fixer.removeRange([functionToken.range[0], leftParenToken.range[0]]); - } - yield fixer.insertTextBefore(node.body, "=> "); - - // Get the node that will become the new arrow function. - let replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node; - - if (replacedNode.type === "ChainExpression") { - replacedNode = replacedNode.parent; - } - - /* - * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then - * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even - * though `foo || function() {}` is valid. - */ - if ( - replacedNode.parent.type !== "CallExpression" && - replacedNode.parent.type !== "ConditionalExpression" && - !astUtils.isParenthesised(sourceCode, replacedNode) && - !astUtils.isParenthesised(sourceCode, node) - ) { - yield fixer.insertTextBefore(replacedNode, "("); - yield fixer.insertTextAfter(replacedNode, ")"); - } - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-const.js b/tools/node_modules/eslint/lib/rules/prefer-const.js deleted file mode 100644 index 439a4db3c963f6be6f11a3d41d7d92b04d58022d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-const.js +++ /dev/null @@ -1,476 +0,0 @@ -/** - * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u; -const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/u; -const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/u; - -/** - * Checks whether a given node is located at `ForStatement.init` or not. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is located at `ForStatement.init`. - */ -function isInitOfForStatement(node) { - return node.parent.type === "ForStatement" && node.parent.init === node; -} - -/** - * Checks whether a given Identifier node becomes a VariableDeclaration or not. - * @param {ASTNode} identifier An Identifier node to check. - * @returns {boolean} `true` if the node can become a VariableDeclaration. - */ -function canBecomeVariableDeclaration(identifier) { - let node = identifier.parent; - - while (PATTERN_TYPE.test(node.type)) { - node = node.parent; - } - - return ( - node.type === "VariableDeclarator" || - ( - node.type === "AssignmentExpression" && - node.parent.type === "ExpressionStatement" && - DECLARATION_HOST_TYPE.test(node.parent.parent.type) - ) - ); -} - -/** - * Checks if an property or element is from outer scope or function parameters - * in destructing pattern. - * @param {string} name A variable name to be checked. - * @param {eslint-scope.Scope} initScope A scope to start find. - * @returns {boolean} Indicates if the variable is from outer scope or function parameters. - */ -function isOuterVariableInDestructing(name, initScope) { - - if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) { - return true; - } - - const variable = astUtils.getVariableByName(initScope, name); - - if (variable !== null) { - return variable.defs.some(def => def.type === "Parameter"); - } - - return false; -} - -/** - * Gets the VariableDeclarator/AssignmentExpression node that a given reference - * belongs to. - * This is used to detect a mix of reassigned and never reassigned in a - * destructuring. - * @param {eslint-scope.Reference} reference A reference to get. - * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or - * null. - */ -function getDestructuringHost(reference) { - if (!reference.isWrite()) { - return null; - } - let node = reference.identifier.parent; - - while (PATTERN_TYPE.test(node.type)) { - node = node.parent; - } - - if (!DESTRUCTURING_HOST_TYPE.test(node.type)) { - return null; - } - return node; -} - -/** - * Determines if a destructuring assignment node contains - * any MemberExpression nodes. This is used to determine if a - * variable that is only written once using destructuring can be - * safely converted into a const declaration. - * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check. - * @returns {boolean} True if the destructuring pattern contains - * a MemberExpression, false if not. - */ -function hasMemberExpressionAssignment(node) { - switch (node.type) { - case "ObjectPattern": - return node.properties.some(prop => { - if (prop) { - - /* - * Spread elements have an argument property while - * others have a value property. Because different - * parsers use different node types for spread elements, - * we just check if there is an argument property. - */ - return hasMemberExpressionAssignment(prop.argument || prop.value); - } - - return false; - }); - - case "ArrayPattern": - return node.elements.some(element => { - if (element) { - return hasMemberExpressionAssignment(element); - } - - return false; - }); - - case "AssignmentPattern": - return hasMemberExpressionAssignment(node.left); - - case "MemberExpression": - return true; - - // no default - } - - return false; -} - -/** - * Gets an identifier node of a given variable. - * - * If the initialization exists or one or more reading references exist before - * the first assignment, the identifier node is the node of the declaration. - * Otherwise, the identifier node is the node of the first assignment. - * - * If the variable should not change to const, this function returns null. - * - If the variable is reassigned. - * - If the variable is never initialized nor assigned. - * - If the variable is initialized in a different scope from the declaration. - * - If the unique assignment of the variable cannot change to a declaration. - * e.g. `if (a) b = 1` / `return (b = 1)` - * - If the variable is declared in the global scope and `eslintUsed` is `true`. - * `/*exported foo` directive comment makes such variables. This rule does not - * warn such variables because this rule cannot distinguish whether the - * exported variables are reassigned or not. - * @param {eslint-scope.Variable} variable A variable to get. - * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. - * @returns {ASTNode|null} - * An Identifier node if the variable should change to const. - * Otherwise, null. - */ -function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) { - if (variable.eslintUsed && variable.scope.type === "global") { - return null; - } - - // Finds the unique WriteReference. - let writer = null; - let isReadBeforeInit = false; - const references = variable.references; - - for (let i = 0; i < references.length; ++i) { - const reference = references[i]; - - if (reference.isWrite()) { - const isReassigned = ( - writer !== null && - writer.identifier !== reference.identifier - ); - - if (isReassigned) { - return null; - } - - const destructuringHost = getDestructuringHost(reference); - - if (destructuringHost !== null && destructuringHost.left !== void 0) { - const leftNode = destructuringHost.left; - let hasOuterVariables = false, - hasNonIdentifiers = false; - - if (leftNode.type === "ObjectPattern") { - const properties = leftNode.properties; - - hasOuterVariables = properties - .filter(prop => prop.value) - .map(prop => prop.value.name) - .some(name => isOuterVariableInDestructing(name, variable.scope)); - - hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); - - } else if (leftNode.type === "ArrayPattern") { - const elements = leftNode.elements; - - hasOuterVariables = elements - .map(element => element && element.name) - .some(name => isOuterVariableInDestructing(name, variable.scope)); - - hasNonIdentifiers = hasMemberExpressionAssignment(leftNode); - } - - if (hasOuterVariables || hasNonIdentifiers) { - return null; - } - - } - - writer = reference; - - } else if (reference.isRead() && writer === null) { - if (ignoreReadBeforeAssign) { - return null; - } - isReadBeforeInit = true; - } - } - - /* - * If the assignment is from a different scope, ignore it. - * If the assignment cannot change to a declaration, ignore it. - */ - const shouldBeConst = ( - writer !== null && - writer.from === variable.scope && - canBecomeVariableDeclaration(writer.identifier) - ); - - if (!shouldBeConst) { - return null; - } - - if (isReadBeforeInit) { - return variable.defs[0].name; - } - - return writer.identifier; -} - -/** - * Groups by the VariableDeclarator/AssignmentExpression node that each - * reference of given variables belongs to. - * This is used to detect a mix of reassigned and never reassigned in a - * destructuring. - * @param {eslint-scope.Variable[]} variables Variables to group by destructuring. - * @param {boolean} ignoreReadBeforeAssign - * The value of `ignoreReadBeforeAssign` option. - * @returns {Map} Grouped identifier nodes. - */ -function groupByDestructuring(variables, ignoreReadBeforeAssign) { - const identifierMap = new Map(); - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - const references = variable.references; - const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign); - let prevId = null; - - for (let j = 0; j < references.length; ++j) { - const reference = references[j]; - const id = reference.identifier; - - /* - * Avoid counting a reference twice or more for default values of - * destructuring. - */ - if (id === prevId) { - continue; - } - prevId = id; - - // Add the identifier node into the destructuring group. - const group = getDestructuringHost(reference); - - if (group) { - if (identifierMap.has(group)) { - identifierMap.get(group).push(identifier); - } else { - identifierMap.set(group, [identifier]); - } - } - } - } - - return identifierMap; -} - -/** - * Finds the nearest parent of node with a given type. - * @param {ASTNode} node The node to search from. - * @param {string} type The type field of the parent node. - * @param {Function} shouldStop A predicate that returns true if the traversal should stop, and false otherwise. - * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists. - */ -function findUp(node, type, shouldStop) { - if (!node || shouldStop(node)) { - return null; - } - if (node.type === type) { - return node; - } - return findUp(node.parent, type, shouldStop); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `const` declarations for variables that are never reassigned after declared", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-const" - }, - - fixable: "code", - - schema: [ - { - type: "object", - properties: { - destructuring: { enum: ["any", "all"], default: "any" }, - ignoreReadBeforeAssign: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - messages: { - useConst: "'{{name}}' is never reassigned. Use 'const' instead." - } - }, - - create(context) { - const options = context.options[0] || {}; - const sourceCode = context.getSourceCode(); - const shouldMatchAnyDestructuredVariable = options.destructuring !== "all"; - const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true; - const variables = []; - let reportCount = 0; - let checkedId = null; - let checkedName = ""; - - - /** - * Reports given identifier nodes if all of the nodes should be declared - * as const. - * - * The argument 'nodes' is an array of Identifier nodes. - * This node is the result of 'getIdentifierIfShouldBeConst()', so it's - * nullable. In simple declaration or assignment cases, the length of - * the array is 1. In destructuring cases, the length of the array can - * be 2 or more. - * @param {(eslint-scope.Reference|null)[]} nodes - * References which are grouped by destructuring to report. - * @returns {void} - */ - function checkGroup(nodes) { - const nodesToReport = nodes.filter(Boolean); - - if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) { - const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement")); - const isVarDecParentNull = varDeclParent === null; - - if (!isVarDecParentNull && varDeclParent.declarations.length > 0) { - const firstDeclaration = varDeclParent.declarations[0]; - - if (firstDeclaration.init) { - const firstDecParent = firstDeclaration.init.parent; - - /* - * First we check the declaration type and then depending on - * if the type is a "VariableDeclarator" or its an "ObjectPattern" - * we compare the name and id from the first identifier, if the names are different - * we assign the new name, id and reset the count of reportCount and nodeCount in - * order to check each block for the number of reported errors and base our fix - * based on comparing nodes.length and nodesToReport.length. - */ - - if (firstDecParent.type === "VariableDeclarator") { - - if (firstDecParent.id.name !== checkedName) { - checkedName = firstDecParent.id.name; - reportCount = 0; - } - - if (firstDecParent.id.type === "ObjectPattern") { - if (firstDecParent.init.name !== checkedName) { - checkedName = firstDecParent.init.name; - reportCount = 0; - } - } - - if (firstDecParent.id !== checkedId) { - checkedId = firstDecParent.id; - reportCount = 0; - } - } - } - } - - let shouldFix = varDeclParent && - - // Don't do a fix unless all variables in the declarations are initialized (or it's in a for-in or for-of loop) - (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || - varDeclParent.declarations.every(declaration => declaration.init)) && - - /* - * If options.destructuring is "all", then this warning will not occur unless - * every assignment in the destructuring should be const. In that case, it's safe - * to apply the fix. - */ - nodesToReport.length === nodes.length; - - if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) { - - if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) { - - /* - * Add nodesToReport.length to a count, then comparing the count to the length - * of the declarations in the current block. - */ - - reportCount += nodesToReport.length; - - shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length); - } - } - - nodesToReport.forEach(node => { - context.report({ - node, - messageId: "useConst", - data: node, - fix: shouldFix - ? fixer => fixer.replaceText( - sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind), - "const" - ) - : null - }); - }); - } - } - - return { - "Program:exit"() { - groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup); - }, - - VariableDeclaration(node) { - if (node.kind === "let" && !isInitOfForStatement(node)) { - variables.push(...context.getDeclaredVariables(node)); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-destructuring.js b/tools/node_modules/eslint/lib/rules/prefer-destructuring.js deleted file mode 100644 index 66e412fd3e3922a702264889610ae0cfeff3abba..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-destructuring.js +++ /dev/null @@ -1,279 +0,0 @@ -/** - * @fileoverview Prefer destructuring from arrays and objects - * @author Alex LaFroscia - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require destructuring from arrays and/or objects", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-destructuring" - }, - - fixable: "code", - - schema: [ - { - - /* - * old support {array: Boolean, object: Boolean} - * new support {VariableDeclarator: {}, AssignmentExpression: {}} - */ - oneOf: [ - { - type: "object", - properties: { - VariableDeclarator: { - type: "object", - properties: { - array: { - type: "boolean" - }, - object: { - type: "boolean" - } - }, - additionalProperties: false - }, - AssignmentExpression: { - type: "object", - properties: { - array: { - type: "boolean" - }, - object: { - type: "boolean" - } - }, - additionalProperties: false - } - }, - additionalProperties: false - }, - { - type: "object", - properties: { - array: { - type: "boolean" - }, - object: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - }, - { - type: "object", - properties: { - enforceForRenamedProperties: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - - messages: { - preferDestructuring: "Use {{type}} destructuring." - } - }, - create(context) { - - const enabledTypes = context.options[0]; - const enforceForRenamedProperties = context.options[1] && context.options[1].enforceForRenamedProperties; - let normalizedOptions = { - VariableDeclarator: { array: true, object: true }, - AssignmentExpression: { array: true, object: true } - }; - - if (enabledTypes) { - normalizedOptions = typeof enabledTypes.array !== "undefined" || typeof enabledTypes.object !== "undefined" - ? { VariableDeclarator: enabledTypes, AssignmentExpression: enabledTypes } - : enabledTypes; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator" - * @param {string} destructuringType "array" or "object" - * @returns {boolean} `true` if the destructuring type should be checked for the given node - */ - function shouldCheck(nodeType, destructuringType) { - return normalizedOptions && - normalizedOptions[nodeType] && - normalizedOptions[nodeType][destructuringType]; - } - - /** - * Determines if the given node is accessing an array index - * - * This is used to differentiate array index access from object property - * access. - * @param {ASTNode} node the node to evaluate - * @returns {boolean} whether or not the node is an integer - */ - function isArrayIndexAccess(node) { - return Number.isInteger(node.property.value); - } - - /** - * Report that the given node should use destructuring - * @param {ASTNode} reportNode the node to report - * @param {string} type the type of destructuring that should have been done - * @param {Function|null} fix the fix function or null to pass to context.report - * @returns {void} - */ - function report(reportNode, type, fix) { - context.report({ - node: reportNode, - messageId: "preferDestructuring", - data: { type }, - fix - }); - } - - /** - * Determines if a node should be fixed into object destructuring - * - * The fixer only fixes the simplest case of object destructuring, - * like: `let x = a.x`; - * - * Assignment expression is not fixed. - * Array destructuring is not fixed. - * Renamed property is not fixed. - * @param {ASTNode} node the the node to evaluate - * @returns {boolean} whether or not the node should be fixed - */ - function shouldFix(node) { - return node.type === "VariableDeclarator" && - node.id.type === "Identifier" && - node.init.type === "MemberExpression" && - !node.init.computed && - node.init.property.type === "Identifier" && - node.id.name === node.init.property.name; - } - - /** - * Fix a node into object destructuring. - * This function only handles the simplest case of object destructuring, - * see {@link shouldFix}. - * @param {SourceCodeFixer} fixer the fixer object - * @param {ASTNode} node the node to be fixed. - * @returns {Object} a fix for the node - */ - function fixIntoObjectDestructuring(fixer, node) { - const rightNode = node.init; - const sourceCode = context.getSourceCode(); - - // Don't fix if that would remove any comments. Only comments inside `rightNode.object` can be preserved. - if (sourceCode.getCommentsInside(node).length > sourceCode.getCommentsInside(rightNode.object).length) { - return null; - } - - return fixer.replaceText( - node, - `{${rightNode.property.name}} = ${sourceCode.getText(rightNode.object)}` - ); - } - - /** - * Check that the `prefer-destructuring` rules are followed based on the - * given left- and right-hand side of the assignment. - * - * Pulled out into a separate method so that VariableDeclarators and - * AssignmentExpressions can share the same verification logic. - * @param {ASTNode} leftNode the left-hand side of the assignment - * @param {ASTNode} rightNode the right-hand side of the assignment - * @param {ASTNode} reportNode the node to report the error on - * @returns {void} - */ - function performCheck(leftNode, rightNode, reportNode) { - if (rightNode.type !== "MemberExpression" || rightNode.object.type === "Super") { - return; - } - - if (isArrayIndexAccess(rightNode)) { - if (shouldCheck(reportNode.type, "array")) { - report(reportNode, "array", null); - } - return; - } - - const fix = shouldFix(reportNode) - ? fixer => fixIntoObjectDestructuring(fixer, reportNode) - : null; - - if (shouldCheck(reportNode.type, "object") && enforceForRenamedProperties) { - report(reportNode, "object", fix); - return; - } - - if (shouldCheck(reportNode.type, "object")) { - const property = rightNode.property; - - if ( - (property.type === "Literal" && leftNode.name === property.value) || - (property.type === "Identifier" && leftNode.name === property.name && !rightNode.computed) - ) { - report(reportNode, "object", fix); - } - } - } - - /** - * Check if a given variable declarator is coming from an property access - * that should be using destructuring instead - * @param {ASTNode} node the variable declarator to check - * @returns {void} - */ - function checkVariableDeclarator(node) { - - // Skip if variable is declared without assignment - if (!node.init) { - return; - } - - // We only care about member expressions past this point - if (node.init.type !== "MemberExpression") { - return; - } - - performCheck(node.id, node.init, node); - } - - /** - * Run the `prefer-destructuring` check on an AssignmentExpression - * @param {ASTNode} node the AssignmentExpression node - * @returns {void} - */ - function checkAssigmentExpression(node) { - if (node.operator === "=") { - performCheck(node.left, node.right, node); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - VariableDeclarator: checkVariableDeclarator, - AssignmentExpression: checkAssigmentExpression - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js b/tools/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js deleted file mode 100644 index d1a00d6209ef025872f4096bcb3238b086f3969e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-exponentiation-operator.js +++ /dev/null @@ -1,189 +0,0 @@ -/** - * @fileoverview Rule to disallow Math.pow in favor of the ** operator - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const { CALL, ReferenceTracker } = require("eslint-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ type: "BinaryExpression", operator: "**" }); - -/** - * Determines whether the given node needs parens if used as the base in an exponentiation binary expression. - * @param {ASTNode} base The node to check. - * @returns {boolean} `true` if the node needs to be parenthesised. - */ -function doesBaseNeedParens(base) { - return ( - - // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c - astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR || - - // An unary operator cannot be used immediately before an exponentiation expression - base.type === "UnaryExpression" - ); -} - -/** - * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression. - * @param {ASTNode} exponent The node to check. - * @returns {boolean} `true` if the node needs to be parenthesised. - */ -function doesExponentNeedParens(exponent) { - - // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c - return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR; -} - -/** - * Determines whether an exponentiation binary expression at the place of the given node would need parens. - * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression. - * @param {SourceCode} sourceCode A SourceCode object. - * @returns {boolean} `true` if the expression needs to be parenthesised. - */ -function doesExponentiationExpressionNeedParens(node, sourceCode) { - const parent = node.parent.type === "ChainExpression" ? node.parent.parent : node.parent; - - const needsParens = ( - parent.type === "ClassDeclaration" || - ( - parent.type.endsWith("Expression") && - astUtils.getPrecedence(parent) >= PRECEDENCE_OF_EXPONENTIATION_EXPR && - !(parent.type === "BinaryExpression" && parent.operator === "**" && parent.right === node) && - !((parent.type === "CallExpression" || parent.type === "NewExpression") && parent.arguments.includes(node)) && - !(parent.type === "MemberExpression" && parent.computed && parent.property === node) && - !(parent.type === "ArrayExpression") - ) - ); - - return needsParens && !astUtils.isParenthesised(sourceCode, node); -} - -/** - * Optionally parenthesizes given text. - * @param {string} text The text to parenthesize. - * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised. - * @returns {string} parenthesised or unchanged text. - */ -function parenthesizeIfShould(text, shouldParenthesize) { - return shouldParenthesize ? `(${text})` : text; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow the use of `Math.pow` in favor of the `**` operator", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-exponentiation-operator" - }, - - schema: [], - fixable: "code", - - messages: { - useExponentiation: "Use the '**' operator instead of 'Math.pow'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - /** - * Reports the given node. - * @param {ASTNode} node 'Math.pow()' node to report. - * @returns {void} - */ - function report(node) { - context.report({ - node, - messageId: "useExponentiation", - fix(fixer) { - if ( - node.arguments.length !== 2 || - node.arguments.some(arg => arg.type === "SpreadElement") || - sourceCode.getCommentsInside(node).length > 0 - ) { - return null; - } - - const base = node.arguments[0], - exponent = node.arguments[1], - baseText = sourceCode.getText(base), - exponentText = sourceCode.getText(exponent), - shouldParenthesizeBase = doesBaseNeedParens(base), - shouldParenthesizeExponent = doesExponentNeedParens(exponent), - shouldParenthesizeAll = doesExponentiationExpressionNeedParens(node, sourceCode); - - let prefix = "", - suffix = ""; - - if (!shouldParenthesizeAll) { - if (!shouldParenthesizeBase) { - const firstReplacementToken = sourceCode.getFirstToken(base), - tokenBefore = sourceCode.getTokenBefore(node); - - if ( - tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken) - ) { - prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c - } - } - if (!shouldParenthesizeExponent) { - const lastReplacementToken = sourceCode.getLastToken(exponent), - tokenAfter = sourceCode.getTokenAfter(node); - - if ( - tokenAfter && - node.range[1] === tokenAfter.range[0] && - !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter) - ) { - suffix = " "; // Math.pow(a, b)in c -> a**b in c - } - } - } - - const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase), - exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent), - replacement = parenthesizeIfShould(`${baseReplacement}**${exponentReplacement}`, shouldParenthesizeAll); - - return fixer.replaceText(node, `${prefix}${replacement}${suffix}`); - } - }); - } - - return { - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const trackMap = { - Math: { - pow: { [CALL]: true } - } - }; - - for (const { node } of tracker.iterateGlobalReferences(trackMap)) { - report(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-named-capture-group.js b/tools/node_modules/eslint/lib/rules/prefer-named-capture-group.js deleted file mode 100644 index 7d0aa3f9dc094d6ad02a39def39f34305cbce404..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-named-capture-group.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @fileoverview Rule to enforce requiring named capture groups in regular expression. - * @author Pig Fang - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { - CALL, - CONSTRUCT, - ReferenceTracker, - getStringIfConstant -} = require("eslint-utils"); -const regexpp = require("regexpp"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const parser = new regexpp.RegExpParser(); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce using named capture group in regular expression", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-named-capture-group" - }, - - schema: [], - - messages: { - required: "Capture group '{{group}}' should be converted to a named or non-capturing group." - } - }, - - create(context) { - - /** - * Function to check regular expression. - * @param {string} pattern The regular expression pattern to be check. - * @param {ASTNode} node AST node which contains regular expression. - * @param {boolean} uFlag Flag indicates whether unicode mode is enabled or not. - * @returns {void} - */ - function checkRegex(pattern, node, uFlag) { - let ast; - - try { - ast = parser.parsePattern(pattern, 0, pattern.length, uFlag); - } catch { - - // ignore regex syntax errors - return; - } - - regexpp.visitRegExpAST(ast, { - onCapturingGroupEnter(group) { - if (!group.name) { - context.report({ - node, - messageId: "required", - data: { - group: group.raw - } - }); - } - } - }); - } - - return { - Literal(node) { - if (node.regex) { - checkRegex(node.regex.pattern, node, node.regex.flags.includes("u")); - } - }, - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const traceMap = { - RegExp: { - [CALL]: true, - [CONSTRUCT]: true - } - }; - - for (const { node } of tracker.iterateGlobalReferences(traceMap)) { - const regex = getStringIfConstant(node.arguments[0]); - const flags = getStringIfConstant(node.arguments[1]); - - if (regex) { - checkRegex(regex, node, flags && flags.includes("u")); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-numeric-literals.js b/tools/node_modules/eslint/lib/rules/prefer-numeric-literals.js deleted file mode 100644 index cc82e6653c03b3b0d2594d984f2b5128db8853d6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-numeric-literals.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals - * @author Annie Zhang, Henry Zhu - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const radixMap = new Map([ - [2, { system: "binary", literalPrefix: "0b" }], - [8, { system: "octal", literalPrefix: "0o" }], - [16, { system: "hexadecimal", literalPrefix: "0x" }] -]); - -/** - * Checks to see if a CallExpression's callee node is `parseInt` or - * `Number.parseInt`. - * @param {ASTNode} calleeNode The callee node to evaluate. - * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`, - * false otherwise. - */ -function isParseInt(calleeNode) { - return ( - astUtils.isSpecificId(calleeNode, "parseInt") || - astUtils.isSpecificMemberAccess(calleeNode, "Number", "parseInt") - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-numeric-literals" - }, - - schema: [], - - messages: { - useLiteral: "Use {{system}} literals instead of {{functionName}}()." - }, - - fixable: "code" - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - - "CallExpression[arguments.length=2]"(node) { - const [strNode, radixNode] = node.arguments, - str = astUtils.getStaticStringValue(strNode), - radix = radixNode.value; - - if ( - str !== null && - astUtils.isStringLiteral(strNode) && - radixNode.type === "Literal" && - typeof radix === "number" && - radixMap.has(radix) && - isParseInt(node.callee) - ) { - - const { system, literalPrefix } = radixMap.get(radix); - - context.report({ - node, - messageId: "useLiteral", - data: { - system, - functionName: sourceCode.getText(node.callee) - }, - fix(fixer) { - if (sourceCode.getCommentsInside(node).length) { - return null; - } - - const replacement = `${literalPrefix}${str}`; - - if (+replacement !== parseInt(str, radix)) { - - /* - * If the newly-produced literal would be invalid, (e.g. 0b1234), - * or it would yield an incorrect parseInt result for some other reason, don't make a fix. - * - * If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+` - * per the specification doesn't support numeric separators. Thus, the above condition will be `true` - * (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value. - * Consequently, no autofixes will be made. This is correct behavior because `parseInt` also - * doesn't support numeric separators, but it does parse part of the string before the first `_`, - * so the autofix would be invalid: - * - * parseInt("1_1", 2) // === 1 - * 0b1_1 // === 3 - */ - return null; - } - - const tokenBefore = sourceCode.getTokenBefore(node), - tokenAfter = sourceCode.getTokenAfter(node); - let prefix = "", - suffix = ""; - - if ( - tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, replacement) - ) { - prefix = " "; - } - - if ( - tokenAfter && - node.range[1] === tokenAfter.range[0] && - !astUtils.canTokensBeAdjacent(replacement, tokenAfter) - ) { - suffix = " "; - } - - return fixer.replaceText(node, `${prefix}${replacement}${suffix}`); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-object-spread.js b/tools/node_modules/eslint/lib/rules/prefer-object-spread.js deleted file mode 100644 index ab252c73ae3aafcd805b3e6cad6c1faa99a2f269..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-object-spread.js +++ /dev/null @@ -1,299 +0,0 @@ -/** - * @fileoverview Prefers object spread property over Object.assign - * @author Sharmila Jesupaul - * See LICENSE file in root directory for full license. - */ - -"use strict"; - -const { CALL, ReferenceTracker } = require("eslint-utils"); -const { - isCommaToken, - isOpeningParenToken, - isClosingParenToken, - isParenthesised -} = require("./utils/ast-utils"); - -const ANY_SPACE = /\s/u; - -/** - * Helper that checks if the Object.assign call has array spread - * @param {ASTNode} node The node that the rule warns on - * @returns {boolean} - Returns true if the Object.assign call has array spread - */ -function hasArraySpread(node) { - return node.arguments.some(arg => arg.type === "SpreadElement"); -} - -/** - * Determines whether the given node is an accessor property (getter/setter). - * @param {ASTNode} node Node to check. - * @returns {boolean} `true` if the node is a getter or a setter. - */ -function isAccessorProperty(node) { - return node.type === "Property" && - (node.kind === "get" || node.kind === "set"); -} - -/** - * Determines whether the given object expression node has accessor properties (getters/setters). - * @param {ASTNode} node `ObjectExpression` node to check. - * @returns {boolean} `true` if the node has at least one getter/setter. - */ -function hasAccessors(node) { - return node.properties.some(isAccessorProperty); -} - -/** - * Determines whether the given call expression node has object expression arguments with accessor properties (getters/setters). - * @param {ASTNode} node `CallExpression` node to check. - * @returns {boolean} `true` if the node has at least one argument that is an object expression with at least one getter/setter. - */ -function hasArgumentsWithAccessors(node) { - return node.arguments - .filter(arg => arg.type === "ObjectExpression") - .some(hasAccessors); -} - -/** - * Helper that checks if the node needs parentheses to be valid JS. - * The default is to wrap the node in parentheses to avoid parsing errors. - * @param {ASTNode} node The node that the rule warns on - * @param {Object} sourceCode in context sourcecode object - * @returns {boolean} - Returns true if the node needs parentheses - */ -function needsParens(node, sourceCode) { - const parent = node.parent; - - switch (parent.type) { - case "VariableDeclarator": - case "ArrayExpression": - case "ReturnStatement": - case "CallExpression": - case "Property": - return false; - case "AssignmentExpression": - return parent.left === node && !isParenthesised(sourceCode, node); - default: - return !isParenthesised(sourceCode, node); - } -} - -/** - * Determines if an argument needs parentheses. The default is to not add parens. - * @param {ASTNode} node The node to be checked. - * @param {Object} sourceCode in context sourcecode object - * @returns {boolean} True if the node needs parentheses - */ -function argNeedsParens(node, sourceCode) { - switch (node.type) { - case "AssignmentExpression": - case "ArrowFunctionExpression": - case "ConditionalExpression": - return !isParenthesised(sourceCode, node); - default: - return false; - } -} - -/** - * Get the parenthesis tokens of a given ObjectExpression node. - * This includes the braces of the object literal and enclosing parentheses. - * @param {ASTNode} node The node to get. - * @param {Token} leftArgumentListParen The opening paren token of the argument list. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {Token[]} The parenthesis tokens of the node. This is sorted by the location. - */ -function getParenTokens(node, leftArgumentListParen, sourceCode) { - const parens = [sourceCode.getFirstToken(node), sourceCode.getLastToken(node)]; - let leftNext = sourceCode.getTokenBefore(node); - let rightNext = sourceCode.getTokenAfter(node); - - // Note: don't include the parens of the argument list. - while ( - leftNext && - rightNext && - leftNext.range[0] > leftArgumentListParen.range[0] && - isOpeningParenToken(leftNext) && - isClosingParenToken(rightNext) - ) { - parens.push(leftNext, rightNext); - leftNext = sourceCode.getTokenBefore(leftNext); - rightNext = sourceCode.getTokenAfter(rightNext); - } - - return parens.sort((a, b) => a.range[0] - b.range[0]); -} - -/** - * Get the range of a given token and around whitespaces. - * @param {Token} token The token to get range. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {number} The end of the range of the token and around whitespaces. - */ -function getStartWithSpaces(token, sourceCode) { - const text = sourceCode.text; - let start = token.range[0]; - - // If the previous token is a line comment then skip this step to avoid commenting this token out. - { - const prevToken = sourceCode.getTokenBefore(token, { includeComments: true }); - - if (prevToken && prevToken.type === "Line") { - return start; - } - } - - // Detect spaces before the token. - while (ANY_SPACE.test(text[start - 1] || "")) { - start -= 1; - } - - return start; -} - -/** - * Get the range of a given token and around whitespaces. - * @param {Token} token The token to get range. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {number} The start of the range of the token and around whitespaces. - */ -function getEndWithSpaces(token, sourceCode) { - const text = sourceCode.text; - let end = token.range[1]; - - // Detect spaces after the token. - while (ANY_SPACE.test(text[end] || "")) { - end += 1; - } - - return end; -} - -/** - * Autofixes the Object.assign call to use an object spread instead. - * @param {ASTNode|null} node The node that the rule warns on, i.e. the Object.assign call - * @param {string} sourceCode sourceCode of the Object.assign call - * @returns {Function} autofixer - replaces the Object.assign with a spread object. - */ -function defineFixer(node, sourceCode) { - return function *(fixer) { - const leftParen = sourceCode.getTokenAfter(node.callee, isOpeningParenToken); - const rightParen = sourceCode.getLastToken(node); - - // Remove everything before the opening paren: callee `Object.assign`, type arguments, and whitespace between the callee and the paren. - yield fixer.removeRange([node.range[0], leftParen.range[0]]); - - // Replace the parens of argument list to braces. - if (needsParens(node, sourceCode)) { - yield fixer.replaceText(leftParen, "({"); - yield fixer.replaceText(rightParen, "})"); - } else { - yield fixer.replaceText(leftParen, "{"); - yield fixer.replaceText(rightParen, "}"); - } - - // Process arguments. - for (const argNode of node.arguments) { - const innerParens = getParenTokens(argNode, leftParen, sourceCode); - const left = innerParens.shift(); - const right = innerParens.pop(); - - if (argNode.type === "ObjectExpression") { - const maybeTrailingComma = sourceCode.getLastToken(argNode, 1); - const maybeArgumentComma = sourceCode.getTokenAfter(right); - - /* - * Make bare this object literal. - * And remove spaces inside of the braces for better formatting. - */ - for (const innerParen of innerParens) { - yield fixer.remove(innerParen); - } - const leftRange = [left.range[0], getEndWithSpaces(left, sourceCode)]; - const rightRange = [ - Math.max(getStartWithSpaces(right, sourceCode), leftRange[1]), // Ensure ranges don't overlap - right.range[1] - ]; - - yield fixer.removeRange(leftRange); - yield fixer.removeRange(rightRange); - - // Remove the comma of this argument if it's duplication. - if ( - (argNode.properties.length === 0 || isCommaToken(maybeTrailingComma)) && - isCommaToken(maybeArgumentComma) - ) { - yield fixer.remove(maybeArgumentComma); - } - } else { - - // Make spread. - if (argNeedsParens(argNode, sourceCode)) { - yield fixer.insertTextBefore(left, "...("); - yield fixer.insertTextAfter(right, ")"); - } else { - yield fixer.insertTextBefore(left, "..."); - } - } - } - }; -} - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: - "disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead.", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-object-spread" - }, - - schema: [], - fixable: "code", - - messages: { - useSpreadMessage: "Use an object spread instead of `Object.assign` eg: `{ ...foo }`.", - useLiteralMessage: "Use an object literal instead of `Object.assign`. eg: `{ foo: bar }`." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const trackMap = { - Object: { - assign: { [CALL]: true } - } - }; - - // Iterate all calls of `Object.assign` (only of the global variable `Object`). - for (const { node } of tracker.iterateGlobalReferences(trackMap)) { - if ( - node.arguments.length >= 1 && - node.arguments[0].type === "ObjectExpression" && - !hasArraySpread(node) && - !( - node.arguments.length > 1 && - hasArgumentsWithAccessors(node) - ) - ) { - const messageId = node.arguments.length === 1 - ? "useLiteralMessage" - : "useSpreadMessage"; - const fix = defineFixer(node, sourceCode); - - context.report({ node, messageId, fix }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js b/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js deleted file mode 100644 index ec16e445555dbfb3861d3315cdbf6ef31901d92d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-promise-reject-errors.js +++ /dev/null @@ -1,131 +0,0 @@ -/** - * @fileoverview restrict values that can be used as Promise rejection reasons - * @author Teddy Katz - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require using Error objects as Promise rejection reasons", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-promise-reject-errors" - }, - - fixable: null, - - schema: [ - { - type: "object", - properties: { - allowEmptyReject: { type: "boolean", default: false } - }, - additionalProperties: false - } - ], - - messages: { - rejectAnError: "Expected the Promise rejection reason to be an Error." - } - }, - - create(context) { - - const ALLOW_EMPTY_REJECT = context.options.length && context.options[0].allowEmptyReject; - - //---------------------------------------------------------------------- - // Helpers - //---------------------------------------------------------------------- - - /** - * Checks the argument of a reject() or Promise.reject() CallExpression, and reports it if it can't be an Error - * @param {ASTNode} callExpression A CallExpression node which is used to reject a Promise - * @returns {void} - */ - function checkRejectCall(callExpression) { - if (!callExpression.arguments.length && ALLOW_EMPTY_REJECT) { - return; - } - if ( - !callExpression.arguments.length || - !astUtils.couldBeError(callExpression.arguments[0]) || - callExpression.arguments[0].type === "Identifier" && callExpression.arguments[0].name === "undefined" - ) { - context.report({ - node: callExpression, - messageId: "rejectAnError" - }); - } - } - - /** - * Determines whether a function call is a Promise.reject() call - * @param {ASTNode} node A CallExpression node - * @returns {boolean} `true` if the call is a Promise.reject() call - */ - function isPromiseRejectCall(node) { - return astUtils.isSpecificMemberAccess(node.callee, "Promise", "reject"); - } - - //---------------------------------------------------------------------- - // Public - //---------------------------------------------------------------------- - - return { - - // Check `Promise.reject(value)` calls. - CallExpression(node) { - if (isPromiseRejectCall(node)) { - checkRejectCall(node); - } - }, - - /* - * Check for `new Promise((resolve, reject) => {})`, and check for reject() calls. - * This function is run on "NewExpression:exit" instead of "NewExpression" to ensure that - * the nodes in the expression already have the `parent` property. - */ - "NewExpression:exit"(node) { - if ( - node.callee.type === "Identifier" && node.callee.name === "Promise" && - node.arguments.length && astUtils.isFunction(node.arguments[0]) && - node.arguments[0].params.length > 1 && node.arguments[0].params[1].type === "Identifier" - ) { - context.getDeclaredVariables(node.arguments[0]) - - /* - * Find the first variable that matches the second parameter's name. - * If the first parameter has the same name as the second parameter, then the variable will actually - * be "declared" when the first parameter is evaluated, but then it will be immediately overwritten - * by the second parameter. It's not possible for an expression with the variable to be evaluated before - * the variable is overwritten, because functions with duplicate parameters cannot have destructuring or - * default assignments in their parameter lists. Therefore, it's not necessary to explicitly account for - * this case. - */ - .find(variable => variable.name === node.arguments[0].params[1].name) - - // Get the references to that variable. - .references - - // Only check the references that read the parameter's value. - .filter(ref => ref.isRead()) - - // Only check the references that are used as the callee in a function call, e.g. `reject(foo)`. - .filter(ref => ref.identifier.parent.type === "CallExpression" && ref.identifier === ref.identifier.parent.callee) - - // Check the argument of the function call to determine whether it's an Error. - .forEach(ref => checkRejectCall(ref.identifier.parent)); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-reflect.js b/tools/node_modules/eslint/lib/rules/prefer-reflect.js deleted file mode 100644 index fb2de923bea37961e783f8d89dbd4f511145816e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-reflect.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule to suggest using "Reflect" api over Function/Object methods - * @author Keith Cirkel - * @deprecated in ESLint v3.9.0 - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `Reflect` methods where applicable", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-reflect" - }, - - deprecated: true, - - replacedBy: [], - - schema: [ - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - enum: [ - "apply", - "call", - "delete", - "defineProperty", - "getOwnPropertyDescriptor", - "getPrototypeOf", - "setPrototypeOf", - "isExtensible", - "getOwnPropertyNames", - "preventExtensions" - ] - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - preferReflect: "Avoid using {{existing}}, instead use {{substitute}}." - } - }, - - create(context) { - const existingNames = { - apply: "Function.prototype.apply", - call: "Function.prototype.call", - defineProperty: "Object.defineProperty", - getOwnPropertyDescriptor: "Object.getOwnPropertyDescriptor", - getPrototypeOf: "Object.getPrototypeOf", - setPrototypeOf: "Object.setPrototypeOf", - isExtensible: "Object.isExtensible", - getOwnPropertyNames: "Object.getOwnPropertyNames", - preventExtensions: "Object.preventExtensions" - }; - - const reflectSubstitutes = { - apply: "Reflect.apply", - call: "Reflect.apply", - defineProperty: "Reflect.defineProperty", - getOwnPropertyDescriptor: "Reflect.getOwnPropertyDescriptor", - getPrototypeOf: "Reflect.getPrototypeOf", - setPrototypeOf: "Reflect.setPrototypeOf", - isExtensible: "Reflect.isExtensible", - getOwnPropertyNames: "Reflect.getOwnPropertyNames", - preventExtensions: "Reflect.preventExtensions" - }; - - const exceptions = (context.options[0] || {}).exceptions || []; - - /** - * Reports the Reflect violation based on the `existing` and `substitute` - * @param {Object} node The node that violates the rule. - * @param {string} existing The existing method name that has been used. - * @param {string} substitute The Reflect substitute that should be used. - * @returns {void} - */ - function report(node, existing, substitute) { - context.report({ - node, - messageId: "preferReflect", - data: { - existing, - substitute - } - }); - } - - return { - CallExpression(node) { - const methodName = (node.callee.property || {}).name; - const isReflectCall = (node.callee.object || {}).name === "Reflect"; - const hasReflectSubsitute = Object.prototype.hasOwnProperty.call(reflectSubstitutes, methodName); - const userConfiguredException = exceptions.indexOf(methodName) !== -1; - - if (hasReflectSubsitute && !isReflectCall && !userConfiguredException) { - report(node, existingNames[methodName], reflectSubstitutes[methodName]); - } - }, - UnaryExpression(node) { - const isDeleteOperator = node.operator === "delete"; - const targetsIdentifier = node.argument.type === "Identifier"; - const userConfiguredException = exceptions.indexOf("delete") !== -1; - - if (isDeleteOperator && !targetsIdentifier && !userConfiguredException) { - report(node, "the delete keyword", "Reflect.deleteProperty"); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-regex-literals.js b/tools/node_modules/eslint/lib/rules/prefer-regex-literals.js deleted file mode 100644 index d9b3b45776a489b7fef3746ea60f4700c960529e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-regex-literals.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals - * @author Milos Djermanovic - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const { CALL, CONSTRUCT, ReferenceTracker, findVariable } = require("eslint-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines whether the given node is a string literal. - * @param {ASTNode} node Node to check. - * @returns {boolean} True if the node is a string literal. - */ -function isStringLiteral(node) { - return node.type === "Literal" && typeof node.value === "string"; -} - -/** - * Determines whether the given node is a template literal without expressions. - * @param {ASTNode} node Node to check. - * @returns {boolean} True if the node is a template literal without expressions. - */ -function isStaticTemplateLiteral(node) { - return node.type === "TemplateLiteral" && node.expressions.length === 0; -} - - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow use of the `RegExp` constructor in favor of regular expression literals", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-regex-literals" - }, - - schema: [], - - messages: { - unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor." - } - }, - - create(context) { - - /** - * Determines whether the given identifier node is a reference to a global variable. - * @param {ASTNode} node `Identifier` node to check. - * @returns {boolean} True if the identifier is a reference to a global variable. - */ - function isGlobalReference(node) { - const scope = context.getScope(); - const variable = findVariable(scope, node); - - return variable !== null && variable.scope.type === "global" && variable.defs.length === 0; - } - - /** - * Determines whether the given node is a String.raw`` tagged template expression - * with a static template literal. - * @param {ASTNode} node Node to check. - * @returns {boolean} True if the node is String.raw`` with a static template. - */ - function isStringRawTaggedStaticTemplateLiteral(node) { - return node.type === "TaggedTemplateExpression" && - astUtils.isSpecificMemberAccess(node.tag, "String", "raw") && - isGlobalReference(astUtils.skipChainExpression(node.tag).object) && - isStaticTemplateLiteral(node.quasi); - } - - /** - * Determines whether the given node is considered to be a static string by the logic of this rule. - * @param {ASTNode} node Node to check. - * @returns {boolean} True if the node is a static string. - */ - function isStaticString(node) { - return isStringLiteral(node) || - isStaticTemplateLiteral(node) || - isStringRawTaggedStaticTemplateLiteral(node); - } - - return { - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const traceMap = { - RegExp: { - [CALL]: true, - [CONSTRUCT]: true - } - }; - - for (const { node } of tracker.iterateGlobalReferences(traceMap)) { - const args = node.arguments; - - if ( - (args.length === 1 || args.length === 2) && - args.every(isStaticString) - ) { - context.report({ node, messageId: "unexpectedRegExp" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-rest-params.js b/tools/node_modules/eslint/lib/rules/prefer-rest-params.js deleted file mode 100644 index 3ecea732af8b94c734be50889e75d35a99dd1740..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-rest-params.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @fileoverview Rule to - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the variable object of `arguments` which is defined implicitly. - * @param {eslint-scope.Scope} scope A scope to get. - * @returns {eslint-scope.Variable} The found variable object. - */ -function getVariableOfArguments(scope) { - const variables = scope.variables; - - for (let i = 0; i < variables.length; ++i) { - const variable = variables[i]; - - if (variable.name === "arguments") { - - /* - * If there was a parameter which is named "arguments", the implicit "arguments" is not defined. - * So does fast return with null. - */ - return (variable.identifiers.length === 0) ? variable : null; - } - } - - /* istanbul ignore next : unreachable */ - return null; -} - -/** - * Checks if the given reference is not normal member access. - * - * - arguments .... true // not member access - * - arguments[i] .... true // computed member access - * - arguments[0] .... true // computed member access - * - arguments.length .... false // normal member access - * @param {eslint-scope.Reference} reference The reference to check. - * @returns {boolean} `true` if the reference is not normal member access. - */ -function isNotNormalMemberAccess(reference) { - const id = reference.identifier; - const parent = id.parent; - - return !( - parent.type === "MemberExpression" && - parent.object === id && - !parent.computed - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require rest parameters instead of `arguments`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-rest-params" - }, - - schema: [], - - messages: { - preferRestParams: "Use the rest parameters instead of 'arguments'." - } - }, - - create(context) { - - /** - * Reports a given reference. - * @param {eslint-scope.Reference} reference A reference to report. - * @returns {void} - */ - function report(reference) { - context.report({ - node: reference.identifier, - loc: reference.identifier.loc, - messageId: "preferRestParams" - }); - } - - /** - * Reports references of the implicit `arguments` variable if exist. - * @returns {void} - */ - function checkForArguments() { - const argumentsVar = getVariableOfArguments(context.getScope()); - - if (argumentsVar) { - argumentsVar - .references - .filter(isNotNormalMemberAccess) - .forEach(report); - } - } - - return { - "FunctionDeclaration:exit": checkForArguments, - "FunctionExpression:exit": checkForArguments - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-spread.js b/tools/node_modules/eslint/lib/rules/prefer-spread.js deleted file mode 100644 index d3c3c4d22972a12e85c0466162541c4392c2894b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-spread.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @fileoverview A rule to suggest using of the spread operator instead of `.apply()`. - * @author Toru Nagashima - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a node is a `.apply()` for variadic. - * @param {ASTNode} node A CallExpression node to check. - * @returns {boolean} Whether or not the node is a `.apply()` for variadic. - */ -function isVariadicApplyCalling(node) { - return ( - astUtils.isSpecificMemberAccess(node.callee, null, "apply") && - node.arguments.length === 2 && - node.arguments[1].type !== "ArrayExpression" && - node.arguments[1].type !== "SpreadElement" - ); -} - -/** - * Checks whether or not `thisArg` is not changed by `.apply()`. - * @param {ASTNode|null} expectedThis The node that is the owner of the applied function. - * @param {ASTNode} thisArg The node that is given to the first argument of the `.apply()`. - * @param {RuleContext} context The ESLint rule context object. - * @returns {boolean} Whether or not `thisArg` is not changed by `.apply()`. - */ -function isValidThisArg(expectedThis, thisArg, context) { - if (!expectedThis) { - return astUtils.isNullOrUndefined(thisArg); - } - return astUtils.equalTokens(expectedThis, thisArg, context); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require spread operators instead of `.apply()`", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-spread" - }, - - schema: [], - fixable: null, - - messages: { - preferSpread: "Use the spread operator instead of '.apply()'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - CallExpression(node) { - if (!isVariadicApplyCalling(node)) { - return; - } - - const applied = astUtils.skipChainExpression(astUtils.skipChainExpression(node.callee).object); - const expectedThis = (applied.type === "MemberExpression") ? applied.object : null; - const thisArg = node.arguments[0]; - - if (isValidThisArg(expectedThis, thisArg, sourceCode)) { - context.report({ - node, - messageId: "preferSpread" - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/prefer-template.js b/tools/node_modules/eslint/lib/rules/prefer-template.js deleted file mode 100644 index e8f980ebd38c6ff95289fa03aac5605a19f6fec0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/prefer-template.js +++ /dev/null @@ -1,283 +0,0 @@ -/** - * @fileoverview A rule to suggest using template literals instead of string concatenation. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Checks whether or not a given node is a concatenation. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a concatenation. - */ -function isConcatenation(node) { - return node.type === "BinaryExpression" && node.operator === "+"; -} - -/** - * Gets the top binary expression node for concatenation in parents of a given node. - * @param {ASTNode} node A node to get. - * @returns {ASTNode} the top binary expression node in parents of a given node. - */ -function getTopConcatBinaryExpression(node) { - let currentNode = node; - - while (isConcatenation(currentNode.parent)) { - currentNode = currentNode.parent; - } - return currentNode; -} - -/** - * Determines whether a given node is a octal escape sequence - * @param {ASTNode} node A node to check - * @returns {boolean} `true` if the node is an octal escape sequence - */ -function isOctalEscapeSequence(node) { - - // No need to check TemplateLiterals – would throw error with octal escape - const isStringLiteral = node.type === "Literal" && typeof node.value === "string"; - - if (!isStringLiteral) { - return false; - } - - return astUtils.hasOctalEscapeSequence(node.raw); -} - -/** - * Checks whether or not a node contains a octal escape sequence - * @param {ASTNode} node A node to check - * @returns {boolean} `true` if the node contains an octal escape sequence - */ -function hasOctalEscapeSequence(node) { - if (isConcatenation(node)) { - return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right); - } - - return isOctalEscapeSequence(node); -} - -/** - * Checks whether or not a given binary expression has string literals. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node has string literals. - */ -function hasStringLiteral(node) { - if (isConcatenation(node)) { - - // `left` is deeper than `right` normally. - return hasStringLiteral(node.right) || hasStringLiteral(node.left); - } - return astUtils.isStringLiteral(node); -} - -/** - * Checks whether or not a given binary expression has non string literals. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node has non string literals. - */ -function hasNonStringLiteral(node) { - if (isConcatenation(node)) { - - // `left` is deeper than `right` normally. - return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left); - } - return !astUtils.isStringLiteral(node); -} - -/** - * Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal. - * @param {ASTNode} node The node that will be fixed to a template literal - * @returns {boolean} `true` if the node will start with a template curly. - */ -function startsWithTemplateCurly(node) { - if (node.type === "BinaryExpression") { - return startsWithTemplateCurly(node.left); - } - if (node.type === "TemplateLiteral") { - return node.expressions.length && node.quasis.length && node.quasis[0].range[0] === node.quasis[0].range[1]; - } - return node.type !== "Literal" || typeof node.value !== "string"; -} - -/** - * Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal. - * @param {ASTNode} node The node that will be fixed to a template literal - * @returns {boolean} `true` if the node will end with a template curly. - */ -function endsWithTemplateCurly(node) { - if (node.type === "BinaryExpression") { - return startsWithTemplateCurly(node.right); - } - if (node.type === "TemplateLiteral") { - return node.expressions.length && node.quasis.length && node.quasis[node.quasis.length - 1].range[0] === node.quasis[node.quasis.length - 1].range[1]; - } - return node.type !== "Literal" || typeof node.value !== "string"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require template literals instead of string concatenation", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/prefer-template" - }, - - schema: [], - fixable: "code", - - messages: { - unexpectedStringConcatenation: "Unexpected string concatenation." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let done = Object.create(null); - - /** - * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens. - * @param {ASTNode} node1 The first node - * @param {ASTNode} node2 The second node - * @returns {string} The text between the nodes, excluding other tokens - */ - function getTextBetween(node1, node2) { - const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2); - const sourceText = sourceCode.getText(); - - return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), ""); - } - - /** - * Returns a template literal form of the given node. - * @param {ASTNode} currentNode A node that should be converted to a template literal - * @param {string} textBeforeNode Text that should appear before the node - * @param {string} textAfterNode Text that should appear after the node - * @returns {string} A string form of this node, represented as a template literal - */ - function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) { - if (currentNode.type === "Literal" && typeof currentNode.value === "string") { - - /* - * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted - * as a template placeholder. However, if the code already contains a backslash before the ${ or ` - * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause - * an actual backslash character to appear before the dollar sign). - */ - return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => { - if (matched.lastIndexOf("\\") % 2) { - return `\\${matched}`; - } - return matched; - - // Unescape any quotes that appear in the original Literal that no longer need to be escaped. - }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode.raw[0])}\``; - } - - if (currentNode.type === "TemplateLiteral") { - return sourceCode.getText(currentNode); - } - - if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) { - const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+"); - const textBeforePlus = getTextBetween(currentNode.left, plusSign); - const textAfterPlus = getTextBetween(plusSign, currentNode.right); - const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left); - const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right); - - if (leftEndsWithCurly) { - - // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket. - // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}` - return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) + - getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1); - } - if (rightStartsWithCurly) { - - // Otherwise, if the right side of the expression starts with a template curly, add the text there. - // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz` - return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) + - getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1); - } - - /* - * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put - * the text between them. - */ - return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; - } - - return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``; - } - - /** - * Returns a fixer object that converts a non-string binary expression to a template literal - * @param {SourceCodeFixer} fixer The fixer object - * @param {ASTNode} node A node that should be converted to a template literal - * @returns {Object} A fix for this binary expression - */ - function fixNonStringBinaryExpression(fixer, node) { - const topBinaryExpr = getTopConcatBinaryExpression(node.parent); - - if (hasOctalEscapeSequence(topBinaryExpr)) { - return null; - } - - return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null)); - } - - /** - * Reports if a given node is string concatenation with non string literals. - * @param {ASTNode} node A node to check. - * @returns {void} - */ - function checkForStringConcat(node) { - if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) { - return; - } - - const topBinaryExpr = getTopConcatBinaryExpression(node.parent); - - // Checks whether or not this node had been checked already. - if (done[topBinaryExpr.range[0]]) { - return; - } - done[topBinaryExpr.range[0]] = true; - - if (hasNonStringLiteral(topBinaryExpr)) { - context.report({ - node: topBinaryExpr, - messageId: "unexpectedStringConcatenation", - fix: fixer => fixNonStringBinaryExpression(fixer, node) - }); - } - } - - return { - Program() { - done = Object.create(null); - }, - - Literal: checkForStringConcat, - TemplateLiteral: checkForStringConcat - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/quote-props.js b/tools/node_modules/eslint/lib/rules/quote-props.js deleted file mode 100644 index fab7bdc9c1555b38ca454f67fbcab0ed86985da6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/quote-props.js +++ /dev/null @@ -1,307 +0,0 @@ -/** - * @fileoverview Rule to flag non-quoted property names in object literals. - * @author Mathias Bynens - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const espree = require("espree"); -const astUtils = require("./utils/ast-utils"); -const keywords = require("./utils/keywords"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require quotes around object literal property names", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/quote-props" - }, - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["always", "as-needed", "consistent", "consistent-as-needed"] - } - ], - minItems: 0, - maxItems: 1 - }, - { - type: "array", - items: [ - { - enum: ["always", "as-needed", "consistent", "consistent-as-needed"] - }, - { - type: "object", - properties: { - keywords: { - type: "boolean" - }, - unnecessary: { - type: "boolean" - }, - numbers: { - type: "boolean" - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - fixable: "code", - messages: { - requireQuotesDueToReservedWord: "Properties should be quoted as '{{property}}' is a reserved word.", - inconsistentlyQuotedProperty: "Inconsistently quoted property '{{key}}' found.", - unnecessarilyQuotedProperty: "Unnecessarily quoted property '{{property}}' found.", - unquotedReservedProperty: "Unquoted reserved word '{{property}}' used as key.", - unquotedNumericProperty: "Unquoted number literal '{{property}}' used as key.", - unquotedPropertyFound: "Unquoted property '{{property}}' found.", - redundantQuoting: "Properties shouldn't be quoted as all quotes are redundant." - } - }, - - create(context) { - - const MODE = context.options[0], - KEYWORDS = context.options[1] && context.options[1].keywords, - CHECK_UNNECESSARY = !context.options[1] || context.options[1].unnecessary !== false, - NUMBERS = context.options[1] && context.options[1].numbers, - - sourceCode = context.getSourceCode(); - - - /** - * Checks whether a certain string constitutes an ES3 token - * @param {string} tokenStr The string to be checked. - * @returns {boolean} `true` if it is an ES3 token. - */ - function isKeyword(tokenStr) { - return keywords.indexOf(tokenStr) >= 0; - } - - /** - * Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary) - * @param {string} rawKey The raw key value from the source - * @param {espreeTokens} tokens The espree-tokenized node key - * @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked - * @returns {boolean} Whether or not a key has redundant quotes. - * @private - */ - function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) { - return tokens.length === 1 && tokens[0].start === 0 && tokens[0].end === rawKey.length && - (["Identifier", "Keyword", "Null", "Boolean"].indexOf(tokens[0].type) >= 0 || - (tokens[0].type === "Numeric" && !skipNumberLiterals && String(+tokens[0].value) === tokens[0].value)); - } - - /** - * Returns a string representation of a property node with quotes removed - * @param {ASTNode} key Key AST Node, which may or may not be quoted - * @returns {string} A replacement string for this property - */ - function getUnquotedKey(key) { - return key.type === "Identifier" ? key.name : key.value; - } - - /** - * Returns a string representation of a property node with quotes added - * @param {ASTNode} key Key AST Node, which may or may not be quoted - * @returns {string} A replacement string for this property - */ - function getQuotedKey(key) { - if (key.type === "Literal" && typeof key.value === "string") { - - // If the key is already a string literal, don't replace the quotes with double quotes. - return sourceCode.getText(key); - } - - // Otherwise, the key is either an identifier or a number literal. - return `"${key.type === "Identifier" ? key.name : key.value}"`; - } - - /** - * Ensures that a property's key is quoted only when necessary - * @param {ASTNode} node Property AST node - * @returns {void} - */ - function checkUnnecessaryQuotes(node) { - const key = node.key; - - if (node.method || node.computed || node.shorthand) { - return; - } - - if (key.type === "Literal" && typeof key.value === "string") { - let tokens; - - try { - tokens = espree.tokenize(key.value); - } catch { - return; - } - - if (tokens.length !== 1) { - return; - } - - const isKeywordToken = isKeyword(tokens[0].value); - - if (isKeywordToken && KEYWORDS) { - return; - } - - if (CHECK_UNNECESSARY && areQuotesRedundant(key.value, tokens, NUMBERS)) { - context.report({ - node, - messageId: "unnecessarilyQuotedProperty", - data: { property: key.value }, - fix: fixer => fixer.replaceText(key, getUnquotedKey(key)) - }); - } - } else if (KEYWORDS && key.type === "Identifier" && isKeyword(key.name)) { - context.report({ - node, - messageId: "unquotedReservedProperty", - data: { property: key.name }, - fix: fixer => fixer.replaceText(key, getQuotedKey(key)) - }); - } else if (NUMBERS && key.type === "Literal" && astUtils.isNumericLiteral(key)) { - context.report({ - node, - messageId: "unquotedNumericProperty", - data: { property: key.value }, - fix: fixer => fixer.replaceText(key, getQuotedKey(key)) - }); - } - } - - /** - * Ensures that a property's key is quoted - * @param {ASTNode} node Property AST node - * @returns {void} - */ - function checkOmittedQuotes(node) { - const key = node.key; - - if (!node.method && !node.computed && !node.shorthand && !(key.type === "Literal" && typeof key.value === "string")) { - context.report({ - node, - messageId: "unquotedPropertyFound", - data: { property: key.name || key.value }, - fix: fixer => fixer.replaceText(key, getQuotedKey(key)) - }); - } - } - - /** - * Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes - * @param {ASTNode} node Property AST node - * @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy - * @returns {void} - */ - function checkConsistency(node, checkQuotesRedundancy) { - const quotedProps = [], - unquotedProps = []; - let keywordKeyName = null, - necessaryQuotes = false; - - node.properties.forEach(property => { - const key = property.key; - - if (!key || property.method || property.computed || property.shorthand) { - return; - } - - if (key.type === "Literal" && typeof key.value === "string") { - - quotedProps.push(property); - - if (checkQuotesRedundancy) { - let tokens; - - try { - tokens = espree.tokenize(key.value); - } catch { - necessaryQuotes = true; - return; - } - - necessaryQuotes = necessaryQuotes || !areQuotesRedundant(key.value, tokens) || KEYWORDS && isKeyword(tokens[0].value); - } - } else if (KEYWORDS && checkQuotesRedundancy && key.type === "Identifier" && isKeyword(key.name)) { - unquotedProps.push(property); - necessaryQuotes = true; - keywordKeyName = key.name; - } else { - unquotedProps.push(property); - } - }); - - if (checkQuotesRedundancy && quotedProps.length && !necessaryQuotes) { - quotedProps.forEach(property => { - context.report({ - node: property, - messageId: "redundantQuoting", - fix: fixer => fixer.replaceText(property.key, getUnquotedKey(property.key)) - }); - }); - } else if (unquotedProps.length && keywordKeyName) { - unquotedProps.forEach(property => { - context.report({ - node: property, - messageId: "requireQuotesDueToReservedWord", - data: { property: keywordKeyName }, - fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) - }); - }); - } else if (quotedProps.length && unquotedProps.length) { - unquotedProps.forEach(property => { - context.report({ - node: property, - messageId: "inconsistentlyQuotedProperty", - data: { key: property.key.name || property.key.value }, - fix: fixer => fixer.replaceText(property.key, getQuotedKey(property.key)) - }); - }); - } - } - - return { - Property(node) { - if (MODE === "always" || !MODE) { - checkOmittedQuotes(node); - } - if (MODE === "as-needed") { - checkUnnecessaryQuotes(node); - } - }, - ObjectExpression(node) { - if (MODE === "consistent") { - checkConsistency(node, false); - } - if (MODE === "consistent-as-needed") { - checkConsistency(node, true); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/quotes.js b/tools/node_modules/eslint/lib/rules/quotes.js deleted file mode 100644 index d1f4443b9033c99b9eada4e72c87a9bf1be77c0e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/quotes.js +++ /dev/null @@ -1,332 +0,0 @@ -/** - * @fileoverview A rule to choose between single and double quote marks - * @author Matt DuVall , Brandon Payton - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Constants -//------------------------------------------------------------------------------ - -const QUOTE_SETTINGS = { - double: { - quote: "\"", - alternateQuote: "'", - description: "doublequote" - }, - single: { - quote: "'", - alternateQuote: "\"", - description: "singlequote" - }, - backtick: { - quote: "`", - alternateQuote: "\"", - description: "backtick" - } -}; - -// An unescaped newline is a newline preceded by an even number of backslashes. -const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`, "u"); - -/** - * Switches quoting of javascript string between ' " and ` - * escaping and unescaping as necessary. - * Only escaping of the minimal set of characters is changed. - * Note: escaping of newlines when switching from backtick to other quotes is not handled. - * @param {string} str A string to convert. - * @returns {string} The string with changed quotes. - * @private - */ -QUOTE_SETTINGS.double.convert = -QUOTE_SETTINGS.single.convert = -QUOTE_SETTINGS.backtick.convert = function(str) { - const newQuote = this.quote; - const oldQuote = str[0]; - - if (newQuote === oldQuote) { - return str; - } - return newQuote + str.slice(1, -1).replace(/\\(\$\{|\r\n?|\n|.)|["'`]|\$\{|(\r\n?|\n)/gu, (match, escaped, newline) => { - if (escaped === oldQuote || oldQuote === "`" && escaped === "${") { - return escaped; // unescape - } - if (match === newQuote || newQuote === "`" && match === "${") { - return `\\${match}`; // escape - } - if (newline && oldQuote === "`") { - return "\\n"; // escape newlines - } - return match; - }) + newQuote; -}; - -const AVOID_ESCAPE = "avoid-escape"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce the consistent use of either backticks, double, or single quotes", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/quotes" - }, - - fixable: "code", - - schema: [ - { - enum: ["single", "double", "backtick"] - }, - { - anyOf: [ - { - enum: ["avoid-escape"] - }, - { - type: "object", - properties: { - avoidEscape: { - type: "boolean" - }, - allowTemplateLiterals: { - type: "boolean" - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - wrongQuotes: "Strings must use {{description}}." - } - }, - - create(context) { - - const quoteOption = context.options[0], - settings = QUOTE_SETTINGS[quoteOption || "double"], - options = context.options[1], - allowTemplateLiterals = options && options.allowTemplateLiterals === true, - sourceCode = context.getSourceCode(); - let avoidEscape = options && options.avoidEscape === true; - - // deprecated - if (options === AVOID_ESCAPE) { - avoidEscape = true; - } - - /** - * Determines if a given node is part of JSX syntax. - * - * This function returns `true` in the following cases: - * - * - `
` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`. - * - `
foo
` ... If the literal is a text content, the parent of the literal is `JSXElement`. - * - `<>foo` ... If the literal is a text content, the parent of the literal is `JSXFragment`. - * - * In particular, this function returns `false` in the following cases: - * - * - `
` - * - `
{"foo"}
` - * - * In both cases, inside of the braces is handled as normal JavaScript. - * The braces are `JSXExpressionContainer` nodes. - * @param {ASTNode} node The Literal node to check. - * @returns {boolean} True if the node is a part of JSX, false if not. - * @private - */ - function isJSXLiteral(node) { - return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment"; - } - - /** - * Checks whether or not a given node is a directive. - * The directive is a `ExpressionStatement` which has only a string literal. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is a directive. - * @private - */ - function isDirective(node) { - return ( - node.type === "ExpressionStatement" && - node.expression.type === "Literal" && - typeof node.expression.value === "string" - ); - } - - /** - * Checks whether or not a given node is a part of directive prologues. - * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is a part of directive prologues. - * @private - */ - function isPartOfDirectivePrologue(node) { - const block = node.parent.parent; - - if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) { - return false; - } - - // Check the node is at a prologue. - for (let i = 0; i < block.body.length; ++i) { - const statement = block.body[i]; - - if (statement === node.parent) { - return true; - } - if (!isDirective(statement)) { - break; - } - } - - return false; - } - - /** - * Checks whether or not a given node is allowed as non backtick. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is allowed as non backtick. - * @private - */ - function isAllowedAsNonBacktick(node) { - const parent = node.parent; - - switch (parent.type) { - - // Directive Prologues. - case "ExpressionStatement": - return isPartOfDirectivePrologue(node); - - // LiteralPropertyName. - case "Property": - case "MethodDefinition": - return parent.key === node && !parent.computed; - - // ModuleSpecifier. - case "ImportDeclaration": - case "ExportNamedDeclaration": - case "ExportAllDeclaration": - return parent.source === node; - - // Others don't allow. - default: - return false; - } - } - - /** - * Checks whether or not a given TemplateLiteral node is actually using any of the special features provided by template literal strings. - * @param {ASTNode} node A TemplateLiteral node to check. - * @returns {boolean} Whether or not the TemplateLiteral node is using any of the special features provided by template literal strings. - * @private - */ - function isUsingFeatureOfTemplateLiteral(node) { - const hasTag = node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi; - - if (hasTag) { - return true; - } - - const hasStringInterpolation = node.expressions.length > 0; - - if (hasStringInterpolation) { - return true; - } - - const isMultilineString = node.quasis.length >= 1 && UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw); - - if (isMultilineString) { - return true; - } - - return false; - } - - return { - - Literal(node) { - const val = node.value, - rawVal = node.raw; - - if (settings && typeof val === "string") { - let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) || - isJSXLiteral(node) || - astUtils.isSurroundedBy(rawVal, settings.quote); - - if (!isValid && avoidEscape) { - isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0; - } - - if (!isValid) { - context.report({ - node, - messageId: "wrongQuotes", - data: { - description: settings.description - }, - fix(fixer) { - if (quoteOption === "backtick" && astUtils.hasOctalEscapeSequence(rawVal)) { - - // An octal escape sequence in a template literal would produce syntax error, even in non-strict mode. - return null; - } - - return fixer.replaceText(node, settings.convert(node.raw)); - } - }); - } - } - }, - - TemplateLiteral(node) { - - // Don't throw an error if backticks are expected or a template literal feature is in use. - if ( - allowTemplateLiterals || - quoteOption === "backtick" || - isUsingFeatureOfTemplateLiteral(node) - ) { - return; - } - - context.report({ - node, - messageId: "wrongQuotes", - data: { - description: settings.description - }, - fix(fixer) { - if (isPartOfDirectivePrologue(node)) { - - /* - * TemplateLiterals in a directive prologue aren't actually directives, but if they're - * in the directive prologue, then fixing them might turn them into directives and change - * the behavior of the code. - */ - return null; - } - return fixer.replaceText(node, settings.convert(sourceCode.getText(node))); - } - }); - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/radix.js b/tools/node_modules/eslint/lib/rules/radix.js deleted file mode 100644 index e322566238809b3b403475d1669b76b8bf598da3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/radix.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * @fileoverview Rule to flag use of parseInt without a radix argument - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const MODE_ALWAYS = "always", - MODE_AS_NEEDED = "as-needed"; - -const validRadixValues = new Set(Array.from({ length: 37 - 2 }, (_, index) => index + 2)); - -/** - * Checks whether a given variable is shadowed or not. - * @param {eslint-scope.Variable} variable A variable to check. - * @returns {boolean} `true` if the variable is shadowed. - */ -function isShadowed(variable) { - return variable.defs.length >= 1; -} - -/** - * Checks whether a given node is a MemberExpression of `parseInt` method or not. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a MemberExpression of `parseInt` - * method. - */ -function isParseIntMethod(node) { - return ( - node.type === "MemberExpression" && - !node.computed && - node.property.type === "Identifier" && - node.property.name === "parseInt" - ); -} - -/** - * Checks whether a given node is a valid value of radix or not. - * - * The following values are invalid. - * - * - A literal except integers between 2 and 36. - * - undefined. - * @param {ASTNode} radix A node of radix to check. - * @returns {boolean} `true` if the node is valid. - */ -function isValidRadix(radix) { - return !( - (radix.type === "Literal" && !validRadixValues.has(radix.value)) || - (radix.type === "Identifier" && radix.name === "undefined") - ); -} - -/** - * Checks whether a given node is a default value of radix or not. - * @param {ASTNode} radix A node of radix to check. - * @returns {boolean} `true` if the node is the literal node of `10`. - */ -function isDefaultRadix(radix) { - return radix.type === "Literal" && radix.value === 10; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the consistent use of the radix argument when using `parseInt()`", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/radix" - }, - - schema: [ - { - enum: ["always", "as-needed"] - } - ], - - messages: { - missingParameters: "Missing parameters.", - redundantRadix: "Redundant radix parameter.", - missingRadix: "Missing radix parameter.", - invalidRadix: "Invalid radix parameter, must be an integer between 2 and 36." - } - }, - - create(context) { - const mode = context.options[0] || MODE_ALWAYS; - - /** - * Checks the arguments of a given CallExpression node and reports it if it - * offends this rule. - * @param {ASTNode} node A CallExpression node to check. - * @returns {void} - */ - function checkArguments(node) { - const args = node.arguments; - - switch (args.length) { - case 0: - context.report({ - node, - messageId: "missingParameters" - }); - break; - - case 1: - if (mode === MODE_ALWAYS) { - context.report({ - node, - messageId: "missingRadix" - }); - } - break; - - default: - if (mode === MODE_AS_NEEDED && isDefaultRadix(args[1])) { - context.report({ - node, - messageId: "redundantRadix" - }); - } else if (!isValidRadix(args[1])) { - context.report({ - node, - messageId: "invalidRadix" - }); - } - break; - } - } - - return { - "Program:exit"() { - const scope = context.getScope(); - let variable; - - // Check `parseInt()` - variable = astUtils.getVariableByName(scope, "parseInt"); - if (variable && !isShadowed(variable)) { - variable.references.forEach(reference => { - const node = reference.identifier; - - if (astUtils.isCallee(node)) { - checkArguments(node.parent); - } - }); - } - - // Check `Number.parseInt()` - variable = astUtils.getVariableByName(scope, "Number"); - if (variable && !isShadowed(variable)) { - variable.references.forEach(reference => { - const node = reference.identifier.parent; - const maybeCallee = node.parent.type === "ChainExpression" - ? node.parent - : node; - - if (isParseIntMethod(node) && astUtils.isCallee(maybeCallee)) { - checkArguments(maybeCallee.parent); - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-atomic-updates.js b/tools/node_modules/eslint/lib/rules/require-atomic-updates.js deleted file mode 100644 index 4f6acceab804d1b2ac32363dd089b466dd20b491..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/require-atomic-updates.js +++ /dev/null @@ -1,283 +0,0 @@ -/** - * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield` - * @author Teddy Katz - * @author Toru Nagashima - */ -"use strict"; - -/** - * Make the map from identifiers to each reference. - * @param {escope.Scope} scope The scope to get references. - * @param {Map} [outReferenceMap] The map from identifier nodes to each reference object. - * @returns {Map} `referenceMap`. - */ -function createReferenceMap(scope, outReferenceMap = new Map()) { - for (const reference of scope.references) { - outReferenceMap.set(reference.identifier, reference); - } - for (const childScope of scope.childScopes) { - if (childScope.type !== "function") { - createReferenceMap(childScope, outReferenceMap); - } - } - - return outReferenceMap; -} - -/** - * Get `reference.writeExpr` of a given reference. - * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a` - * @param {escope.Reference} reference The reference to get. - * @returns {Expression|null} The `reference.writeExpr`. - */ -function getWriteExpr(reference) { - if (reference.writeExpr) { - return reference.writeExpr; - } - let node = reference.identifier; - - while (node) { - const t = node.parent.type; - - if (t === "AssignmentExpression" && node.parent.left === node) { - return node.parent.right; - } - if (t === "MemberExpression" && node.parent.object === node) { - node = node.parent; - continue; - } - - break; - } - - return null; -} - -/** - * Checks if an expression is a variable that can only be observed within the given function. - * @param {Variable|null} variable The variable to check - * @param {boolean} isMemberAccess If `true` then this is a member access. - * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure. - */ -function isLocalVariableWithoutEscape(variable, isMemberAccess) { - if (!variable) { - return false; // A global variable which was not defined. - } - - // If the reference is a property access and the variable is a parameter, it handles the variable is not local. - if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) { - return false; - } - - const functionScope = variable.scope.variableScope; - - return variable.references.every(reference => - reference.from.variableScope === functionScope); -} - -class SegmentInfo { - constructor() { - this.info = new WeakMap(); - } - - /** - * Initialize the segment information. - * @param {PathSegment} segment The segment to initialize. - * @returns {void} - */ - initialize(segment) { - const outdatedReadVariableNames = new Set(); - const freshReadVariableNames = new Set(); - - for (const prevSegment of segment.prevSegments) { - const info = this.info.get(prevSegment); - - if (info) { - info.outdatedReadVariableNames.forEach(Set.prototype.add, outdatedReadVariableNames); - info.freshReadVariableNames.forEach(Set.prototype.add, freshReadVariableNames); - } - } - - this.info.set(segment, { outdatedReadVariableNames, freshReadVariableNames }); - } - - /** - * Mark a given variable as read on given segments. - * @param {PathSegment[]} segments The segments that it read the variable on. - * @param {string} variableName The variable name to be read. - * @returns {void} - */ - markAsRead(segments, variableName) { - for (const segment of segments) { - const info = this.info.get(segment); - - if (info) { - info.freshReadVariableNames.add(variableName); - } - } - } - - /** - * Move `freshReadVariableNames` to `outdatedReadVariableNames`. - * @param {PathSegment[]} segments The segments to process. - * @returns {void} - */ - makeOutdated(segments) { - for (const segment of segments) { - const info = this.info.get(segment); - - if (info) { - info.freshReadVariableNames.forEach(Set.prototype.add, info.outdatedReadVariableNames); - info.freshReadVariableNames.clear(); - } - } - } - - /** - * Check if a given variable is outdated on the current segments. - * @param {PathSegment[]} segments The current segments. - * @param {string} variableName The variable name to check. - * @returns {boolean} `true` if the variable is outdated on the segments. - */ - isOutdated(segments, variableName) { - for (const segment of segments) { - const info = this.info.get(segment); - - if (info && info.outdatedReadVariableNames.has(variableName)) { - return true; - } - } - return false; - } -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/require-atomic-updates" - }, - - fixable: null, - schema: [], - - messages: { - nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const assignmentReferences = new Map(); - const segmentInfo = new SegmentInfo(); - let stack = null; - - return { - onCodePathStart(codePath) { - const scope = context.getScope(); - const shouldVerify = - scope.type === "function" && - (scope.block.async || scope.block.generator); - - stack = { - upper: stack, - codePath, - referenceMap: shouldVerify ? createReferenceMap(scope) : null - }; - }, - onCodePathEnd() { - stack = stack.upper; - }, - - // Initialize the segment information. - onCodePathSegmentStart(segment) { - segmentInfo.initialize(segment); - }, - - // Handle references to prepare verification. - Identifier(node) { - const { codePath, referenceMap } = stack; - const reference = referenceMap && referenceMap.get(node); - - // Ignore if this is not a valid variable reference. - if (!reference) { - return; - } - const name = reference.identifier.name; - const variable = reference.resolved; - const writeExpr = getWriteExpr(reference); - const isMemberAccess = reference.identifier.parent.type === "MemberExpression"; - - // Add a fresh read variable. - if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) { - segmentInfo.markAsRead(codePath.currentSegments, name); - } - - /* - * Register the variable to verify after ESLint traversed the `writeExpr` node - * if this reference is an assignment to a variable which is referred from other closure. - */ - if (writeExpr && - writeExpr.parent.right === writeExpr && // ↠exclude variable declarations. - !isLocalVariableWithoutEscape(variable, isMemberAccess) - ) { - let refs = assignmentReferences.get(writeExpr); - - if (!refs) { - refs = []; - assignmentReferences.set(writeExpr, refs); - } - - refs.push(reference); - } - }, - - /* - * Verify assignments. - * If the reference exists in `outdatedReadVariableNames` list, report it. - */ - ":expression:exit"(node) { - const { codePath, referenceMap } = stack; - - // referenceMap exists if this is in a resumable function scope. - if (!referenceMap) { - return; - } - - // Mark the read variables on this code path as outdated. - if (node.type === "AwaitExpression" || node.type === "YieldExpression") { - segmentInfo.makeOutdated(codePath.currentSegments); - } - - // Verify. - const references = assignmentReferences.get(node); - - if (references) { - assignmentReferences.delete(node); - - for (const reference of references) { - const name = reference.identifier.name; - - if (segmentInfo.isOutdated(codePath.currentSegments, name)) { - context.report({ - node: node.parent, - messageId: "nonAtomicUpdate", - data: { - value: sourceCode.getText(node.parent.left) - } - }); - } - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-await.js b/tools/node_modules/eslint/lib/rules/require-await.js deleted file mode 100644 index 9b5acc78c814ea02077c8784d65b8097fac2dc5a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/require-await.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @fileoverview Rule to disallow async functions which have no `await` expression. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Capitalize the 1st letter of the given text. - * @param {string} text The text to capitalize. - * @returns {string} The text that the 1st letter was capitalized. - */ -function capitalizeFirstLetter(text) { - return text[0].toUpperCase() + text.slice(1); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "disallow async functions which have no `await` expression", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/require-await" - }, - - schema: [], - - messages: { - missingAwait: "{{name}} has no 'await' expression." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - let scopeInfo = null; - - /** - * Push the scope info object to the stack. - * @returns {void} - */ - function enterFunction() { - scopeInfo = { - upper: scopeInfo, - hasAwait: false - }; - } - - /** - * Pop the top scope info object from the stack. - * Also, it reports the function if needed. - * @param {ASTNode} node The node to report. - * @returns {void} - */ - function exitFunction(node) { - if (!node.generator && node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) { - context.report({ - node, - loc: astUtils.getFunctionHeadLoc(node, sourceCode), - messageId: "missingAwait", - data: { - name: capitalizeFirstLetter( - astUtils.getFunctionNameWithKind(node) - ) - } - }); - } - - scopeInfo = scopeInfo.upper; - } - - return { - FunctionDeclaration: enterFunction, - FunctionExpression: enterFunction, - ArrowFunctionExpression: enterFunction, - "FunctionDeclaration:exit": exitFunction, - "FunctionExpression:exit": exitFunction, - "ArrowFunctionExpression:exit": exitFunction, - - AwaitExpression() { - if (!scopeInfo) { - return; - } - - scopeInfo.hasAwait = true; - }, - ForOfStatement(node) { - if (!scopeInfo) { - return; - } - - if (node.await) { - scopeInfo.hasAwait = true; - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-jsdoc.js b/tools/node_modules/eslint/lib/rules/require-jsdoc.js deleted file mode 100644 index e581b2bee4646a43863abab8e83072a7f7e1d958..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/require-jsdoc.js +++ /dev/null @@ -1,121 +0,0 @@ -/** - * @fileoverview Rule to check for jsdoc presence. - * @author Gyandeep Singh - */ -"use strict"; - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require JSDoc comments", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/require-jsdoc" - }, - - schema: [ - { - type: "object", - properties: { - require: { - type: "object", - properties: { - ClassDeclaration: { - type: "boolean", - default: false - }, - MethodDefinition: { - type: "boolean", - default: false - }, - FunctionDeclaration: { - type: "boolean", - default: true - }, - ArrowFunctionExpression: { - type: "boolean", - default: false - }, - FunctionExpression: { - type: "boolean", - default: false - } - }, - additionalProperties: false, - default: {} - } - }, - additionalProperties: false - } - ], - - deprecated: true, - replacedBy: [], - - messages: { - missingJSDocComment: "Missing JSDoc comment." - } - }, - - create(context) { - const source = context.getSourceCode(); - const DEFAULT_OPTIONS = { - FunctionDeclaration: true, - MethodDefinition: false, - ClassDeclaration: false, - ArrowFunctionExpression: false, - FunctionExpression: false - }; - const options = Object.assign(DEFAULT_OPTIONS, context.options[0] && context.options[0].require); - - /** - * Report the error message - * @param {ASTNode} node node to report - * @returns {void} - */ - function report(node) { - context.report({ node, messageId: "missingJSDocComment" }); - } - - /** - * Check if the jsdoc comment is present or not. - * @param {ASTNode} node node to examine - * @returns {void} - */ - function checkJsDoc(node) { - const jsdocComment = source.getJSDocComment(node); - - if (!jsdocComment) { - report(node); - } - } - - return { - FunctionDeclaration(node) { - if (options.FunctionDeclaration) { - checkJsDoc(node); - } - }, - FunctionExpression(node) { - if ( - (options.MethodDefinition && node.parent.type === "MethodDefinition") || - (options.FunctionExpression && (node.parent.type === "VariableDeclarator" || (node.parent.type === "Property" && node === node.parent.value))) - ) { - checkJsDoc(node); - } - }, - ClassDeclaration(node) { - if (options.ClassDeclaration) { - checkJsDoc(node); - } - }, - ArrowFunctionExpression(node) { - if (options.ArrowFunctionExpression && node.parent.type === "VariableDeclarator") { - checkJsDoc(node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-unicode-regexp.js b/tools/node_modules/eslint/lib/rules/require-unicode-regexp.js deleted file mode 100644 index 880405e9a25dbfe5c90f85f454f615f2cee9bb77..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/require-unicode-regexp.js +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @fileoverview Rule to enforce the use of `u` flag on RegExp. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const { - CALL, - CONSTRUCT, - ReferenceTracker, - getStringIfConstant -} = require("eslint-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce the use of `u` flag on RegExp", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/require-unicode-regexp" - }, - - messages: { - requireUFlag: "Use the 'u' flag." - }, - - schema: [] - }, - - create(context) { - return { - "Literal[regex]"(node) { - const flags = node.regex.flags || ""; - - if (!flags.includes("u")) { - context.report({ node, messageId: "requireUFlag" }); - } - }, - - Program() { - const scope = context.getScope(); - const tracker = new ReferenceTracker(scope); - const trackMap = { - RegExp: { [CALL]: true, [CONSTRUCT]: true } - }; - - for (const { node } of tracker.iterateGlobalReferences(trackMap)) { - const flagsNode = node.arguments[1]; - const flags = getStringIfConstant(flagsNode, scope); - - if (!flagsNode || (typeof flags === "string" && !flags.includes("u"))) { - context.report({ node, messageId: "requireUFlag" }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/require-yield.js b/tools/node_modules/eslint/lib/rules/require-yield.js deleted file mode 100644 index af2344dfa6b8ff7e0d2eba7e4dfc813e6fec314f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/require-yield.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * @fileoverview Rule to flag the generator functions that does not have yield. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require generator functions to contain `yield`", - category: "ECMAScript 6", - recommended: true, - url: "https://eslint.org/docs/rules/require-yield" - }, - - schema: [], - - messages: { - missingYield: "This generator function does not have 'yield'." - } - }, - - create(context) { - const stack = []; - - /** - * If the node is a generator function, start counting `yield` keywords. - * @param {Node} node A function node to check. - * @returns {void} - */ - function beginChecking(node) { - if (node.generator) { - stack.push(0); - } - } - - /** - * If the node is a generator function, end counting `yield` keywords, then - * reports result. - * @param {Node} node A function node to check. - * @returns {void} - */ - function endChecking(node) { - if (!node.generator) { - return; - } - - const countYield = stack.pop(); - - if (countYield === 0 && node.body.body.length > 0) { - context.report({ node, messageId: "missingYield" }); - } - } - - return { - FunctionDeclaration: beginChecking, - "FunctionDeclaration:exit": endChecking, - FunctionExpression: beginChecking, - "FunctionExpression:exit": endChecking, - - // Increases the count of `yield` keyword. - YieldExpression() { - - /* istanbul ignore else */ - if (stack.length > 0) { - stack[stack.length - 1] += 1; - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/rest-spread-spacing.js b/tools/node_modules/eslint/lib/rules/rest-spread-spacing.js deleted file mode 100644 index 8cb9814f0c9129e1328eb4933f115bd1559e4a8e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/rest-spread-spacing.js +++ /dev/null @@ -1,120 +0,0 @@ -/** - * @fileoverview Enforce spacing between rest and spread operators and their expressions. - * @author Kai Cataldo - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce spacing between rest and spread operators and their expressions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/rest-spread-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - } - ], - - messages: { - unexpectedWhitespace: "Unexpected whitespace after {{type}} operator.", - expectedWhitespace: "Expected whitespace after {{type}} operator." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(), - alwaysSpace = context.options[0] === "always"; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Checks whitespace between rest/spread operators and their expressions - * @param {ASTNode} node The node to check - * @returns {void} - */ - function checkWhiteSpace(node) { - const operator = sourceCode.getFirstToken(node), - nextToken = sourceCode.getTokenAfter(operator), - hasWhitespace = sourceCode.isSpaceBetweenTokens(operator, nextToken); - let type; - - switch (node.type) { - case "SpreadElement": - type = "spread"; - if (node.parent.type === "ObjectExpression") { - type += " property"; - } - break; - case "RestElement": - type = "rest"; - if (node.parent.type === "ObjectPattern") { - type += " property"; - } - break; - case "ExperimentalSpreadProperty": - type = "spread property"; - break; - case "ExperimentalRestProperty": - type = "rest property"; - break; - default: - return; - } - - if (alwaysSpace && !hasWhitespace) { - context.report({ - node, - loc: operator.loc, - messageId: "expectedWhitespace", - data: { - type - }, - fix(fixer) { - return fixer.replaceTextRange([operator.range[1], nextToken.range[0]], " "); - } - }); - } else if (!alwaysSpace && hasWhitespace) { - context.report({ - node, - loc: { - start: operator.loc.end, - end: nextToken.loc.start - }, - messageId: "unexpectedWhitespace", - data: { - type - }, - fix(fixer) { - return fixer.removeRange([operator.range[1], nextToken.range[0]]); - } - }); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - SpreadElement: checkWhiteSpace, - RestElement: checkWhiteSpace, - ExperimentalSpreadProperty: checkWhiteSpace, - ExperimentalRestProperty: checkWhiteSpace - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/semi-spacing.js b/tools/node_modules/eslint/lib/rules/semi-spacing.js deleted file mode 100644 index 936e7661ef4fb3ce1827cc793d976c62e0463527..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/semi-spacing.js +++ /dev/null @@ -1,243 +0,0 @@ -/** - * @fileoverview Validates spacing before and after semicolon - * @author Mathias Schreck - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before and after semicolons", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/semi-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - before: { - type: "boolean", - default: false - }, - after: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedWhitespaceBefore: "Unexpected whitespace before semicolon.", - unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.", - missingWhitespaceBefore: "Missing whitespace before semicolon.", - missingWhitespaceAfter: "Missing whitespace after semicolon." - } - }, - - create(context) { - - const config = context.options[0], - sourceCode = context.getSourceCode(); - let requireSpaceBefore = false, - requireSpaceAfter = true; - - if (typeof config === "object") { - requireSpaceBefore = config.before; - requireSpaceAfter = config.after; - } - - /** - * Checks if a given token has leading whitespace. - * @param {Object} token The token to check. - * @returns {boolean} True if the given token has leading space, false if not. - */ - function hasLeadingSpace(token) { - const tokenBefore = sourceCode.getTokenBefore(token); - - return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token); - } - - /** - * Checks if a given token has trailing whitespace. - * @param {Object} token The token to check. - * @returns {boolean} True if the given token has trailing space, false if not. - */ - function hasTrailingSpace(token) { - const tokenAfter = sourceCode.getTokenAfter(token); - - return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter); - } - - /** - * Checks if the given token is the last token in its line. - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the token is the last in its line. - */ - function isLastTokenInCurrentLine(token) { - const tokenAfter = sourceCode.getTokenAfter(token); - - return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter)); - } - - /** - * Checks if the given token is the first token in its line - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the token is the first in its line. - */ - function isFirstTokenInCurrentLine(token) { - const tokenBefore = sourceCode.getTokenBefore(token); - - return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore)); - } - - /** - * Checks if the next token of a given token is a closing parenthesis. - * @param {Token} token The token to check. - * @returns {boolean} Whether or not the next token of a given token is a closing parenthesis. - */ - function isBeforeClosingParen(token) { - const nextToken = sourceCode.getTokenAfter(token); - - return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken)); - } - - /** - * Report location example : - * - * for unexpected space `before` - * - * var a = 'b' ; - * ^^^ - * - * for unexpected space `after` - * - * var a = 'b'; c = 10; - * ^^ - * - * Reports if the given token has invalid spacing. - * @param {Token} token The semicolon token to check. - * @param {ASTNode} node The corresponding node of the token. - * @returns {void} - */ - function checkSemicolonSpacing(token, node) { - if (astUtils.isSemicolonToken(token)) { - if (hasLeadingSpace(token)) { - if (!requireSpaceBefore) { - const tokenBefore = sourceCode.getTokenBefore(token); - const loc = { - start: tokenBefore.loc.end, - end: token.loc.start - }; - - context.report({ - node, - loc, - messageId: "unexpectedWhitespaceBefore", - fix(fixer) { - - return fixer.removeRange([tokenBefore.range[1], token.range[0]]); - } - }); - } - } else { - if (requireSpaceBefore) { - const loc = token.loc; - - context.report({ - node, - loc, - messageId: "missingWhitespaceBefore", - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - } - - if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) { - if (hasTrailingSpace(token)) { - if (!requireSpaceAfter) { - const tokenAfter = sourceCode.getTokenAfter(token); - const loc = { - start: token.loc.end, - end: tokenAfter.loc.start - }; - - context.report({ - node, - loc, - messageId: "unexpectedWhitespaceAfter", - fix(fixer) { - - return fixer.removeRange([token.range[1], tokenAfter.range[0]]); - } - }); - } - } else { - if (requireSpaceAfter) { - const loc = token.loc; - - context.report({ - node, - loc, - messageId: "missingWhitespaceAfter", - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - } - } - } - } - - /** - * Checks the spacing of the semicolon with the assumption that the last token is the semicolon. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkNode(node) { - const token = sourceCode.getLastToken(node); - - checkSemicolonSpacing(token, node); - } - - return { - VariableDeclaration: checkNode, - ExpressionStatement: checkNode, - BreakStatement: checkNode, - ContinueStatement: checkNode, - DebuggerStatement: checkNode, - ReturnStatement: checkNode, - ThrowStatement: checkNode, - ImportDeclaration: checkNode, - ExportNamedDeclaration: checkNode, - ExportAllDeclaration: checkNode, - ExportDefaultDeclaration: checkNode, - ForStatement(node) { - if (node.init) { - checkSemicolonSpacing(sourceCode.getTokenAfter(node.init), node); - } - - if (node.test) { - checkSemicolonSpacing(sourceCode.getTokenAfter(node.test), node); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/semi-style.js b/tools/node_modules/eslint/lib/rules/semi-style.js deleted file mode 100644 index 0c9bec4c85ede81e29c4493f42234263df2fe5fc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/semi-style.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @fileoverview Rule to enforce location of semicolons. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -const SELECTOR = `:matches(${ - [ - "BreakStatement", "ContinueStatement", "DebuggerStatement", - "DoWhileStatement", "ExportAllDeclaration", - "ExportDefaultDeclaration", "ExportNamedDeclaration", - "ExpressionStatement", "ImportDeclaration", "ReturnStatement", - "ThrowStatement", "VariableDeclaration" - ].join(",") -})`; - -/** - * Get the child node list of a given node. - * This returns `Program#body`, `BlockStatement#body`, or `SwitchCase#consequent`. - * This is used to check whether a node is the first/last child. - * @param {Node} node A node to get child node list. - * @returns {Node[]|null} The child node list. - */ -function getChildren(node) { - const t = node.type; - - if (t === "BlockStatement" || t === "Program") { - return node.body; - } - if (t === "SwitchCase") { - return node.consequent; - } - return null; -} - -/** - * Check whether a given node is the last statement in the parent block. - * @param {Node} node A node to check. - * @returns {boolean} `true` if the node is the last statement in the parent block. - */ -function isLastChild(node) { - const t = node.parent.type; - - if (t === "IfStatement" && node.parent.consequent === node && node.parent.alternate) { // before `else` keyword. - return true; - } - if (t === "DoWhileStatement") { // before `while` keyword. - return true; - } - const nodeList = getChildren(node.parent); - - return nodeList !== null && nodeList[nodeList.length - 1] === node; // before `}` or etc. -} - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce location of semicolons", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/semi-style" - }, - - schema: [{ enum: ["last", "first"] }], - fixable: "whitespace", - - messages: { - expectedSemiColon: "Expected this semicolon to be at {{pos}}." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const option = context.options[0] || "last"; - - /** - * Check the given semicolon token. - * @param {Token} semiToken The semicolon token to check. - * @param {"first"|"last"} expected The expected location to check. - * @returns {void} - */ - function check(semiToken, expected) { - const prevToken = sourceCode.getTokenBefore(semiToken); - const nextToken = sourceCode.getTokenAfter(semiToken); - const prevIsSameLine = !prevToken || astUtils.isTokenOnSameLine(prevToken, semiToken); - const nextIsSameLine = !nextToken || astUtils.isTokenOnSameLine(semiToken, nextToken); - - if ((expected === "last" && !prevIsSameLine) || (expected === "first" && !nextIsSameLine)) { - context.report({ - loc: semiToken.loc, - messageId: "expectedSemiColon", - data: { - pos: (expected === "last") - ? "the end of the previous line" - : "the beginning of the next line" - }, - fix(fixer) { - if (prevToken && nextToken && sourceCode.commentsExistBetween(prevToken, nextToken)) { - return null; - } - - const start = prevToken ? prevToken.range[1] : semiToken.range[0]; - const end = nextToken ? nextToken.range[0] : semiToken.range[1]; - const text = (expected === "last") ? ";\n" : "\n;"; - - return fixer.replaceTextRange([start, end], text); - } - }); - } - } - - return { - [SELECTOR](node) { - if (option === "first" && isLastChild(node)) { - return; - } - - const lastToken = sourceCode.getLastToken(node); - - if (astUtils.isSemicolonToken(lastToken)) { - check(lastToken, option); - } - }, - - ForStatement(node) { - const firstSemi = node.init && sourceCode.getTokenAfter(node.init, astUtils.isSemicolonToken); - const secondSemi = node.test && sourceCode.getTokenAfter(node.test, astUtils.isSemicolonToken); - - if (firstSemi) { - check(firstSemi, "last"); - } - if (secondSemi) { - check(secondSemi, "last"); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/semi.js b/tools/node_modules/eslint/lib/rules/semi.js deleted file mode 100644 index d2f0670427b3ab66b3aebf8e488b1c1d419f2438..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/semi.js +++ /dev/null @@ -1,336 +0,0 @@ -/** - * @fileoverview Rule to flag missing semicolons. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const FixTracker = require("./utils/fix-tracker"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow semicolons instead of ASI", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/semi" - }, - - fixable: "code", - - schema: { - anyOf: [ - { - type: "array", - items: [ - { - enum: ["never"] - }, - { - type: "object", - properties: { - beforeStatementContinuationChars: { - enum: ["always", "any", "never"] - } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - }, - { - type: "array", - items: [ - { - enum: ["always"] - }, - { - type: "object", - properties: { - omitLastInOneLineBlock: { type: "boolean" } - }, - additionalProperties: false - } - ], - minItems: 0, - maxItems: 2 - } - ] - }, - - messages: { - missingSemi: "Missing semicolon.", - extraSemi: "Extra semicolon." - } - }, - - create(context) { - - const OPT_OUT_PATTERN = /^[-[(/+`]/u; // One of [(/+-` - const options = context.options[1]; - const never = context.options[0] === "never"; - const exceptOneLine = Boolean(options && options.omitLastInOneLineBlock); - const beforeStatementContinuationChars = options && options.beforeStatementContinuationChars || "any"; - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Reports a semicolon error with appropriate location and message. - * @param {ASTNode} node The node with an extra or missing semicolon. - * @param {boolean} missing True if the semicolon is missing. - * @returns {void} - */ - function report(node, missing) { - const lastToken = sourceCode.getLastToken(node); - let messageId, - fix, - loc; - - if (!missing) { - messageId = "missingSemi"; - loc = { - start: lastToken.loc.end, - end: astUtils.getNextLocation(sourceCode, lastToken.loc.end) - }; - fix = function(fixer) { - return fixer.insertTextAfter(lastToken, ";"); - }; - } else { - messageId = "extraSemi"; - loc = lastToken.loc; - fix = function(fixer) { - - /* - * Expand the replacement range to include the surrounding - * tokens to avoid conflicting with no-extra-semi. - * https://github.com/eslint/eslint/issues/7928 - */ - return new FixTracker(fixer, sourceCode) - .retainSurroundingTokens(lastToken) - .remove(lastToken); - }; - } - - context.report({ - node, - loc, - messageId, - fix - }); - - } - - /** - * Check whether a given semicolon token is redundant. - * @param {Token} semiToken A semicolon token to check. - * @returns {boolean} `true` if the next token is `;` or `}`. - */ - function isRedundantSemi(semiToken) { - const nextToken = sourceCode.getTokenAfter(semiToken); - - return ( - !nextToken || - astUtils.isClosingBraceToken(nextToken) || - astUtils.isSemicolonToken(nextToken) - ); - } - - /** - * Check whether a given token is the closing brace of an arrow function. - * @param {Token} lastToken A token to check. - * @returns {boolean} `true` if the token is the closing brace of an arrow function. - */ - function isEndOfArrowBlock(lastToken) { - if (!astUtils.isClosingBraceToken(lastToken)) { - return false; - } - const node = sourceCode.getNodeByRangeIndex(lastToken.range[0]); - - return ( - node.type === "BlockStatement" && - node.parent.type === "ArrowFunctionExpression" - ); - } - - /** - * Check whether a given node is on the same line with the next token. - * @param {Node} node A statement node to check. - * @returns {boolean} `true` if the node is on the same line with the next token. - */ - function isOnSameLineWithNextToken(node) { - const prevToken = sourceCode.getLastToken(node, 1); - const nextToken = sourceCode.getTokenAfter(node); - - return !!nextToken && astUtils.isTokenOnSameLine(prevToken, nextToken); - } - - /** - * Check whether a given node can connect the next line if the next line is unreliable. - * @param {Node} node A statement node to check. - * @returns {boolean} `true` if the node can connect the next line. - */ - function maybeAsiHazardAfter(node) { - const t = node.type; - - if (t === "DoWhileStatement" || - t === "BreakStatement" || - t === "ContinueStatement" || - t === "DebuggerStatement" || - t === "ImportDeclaration" || - t === "ExportAllDeclaration" - ) { - return false; - } - if (t === "ReturnStatement") { - return Boolean(node.argument); - } - if (t === "ExportNamedDeclaration") { - return Boolean(node.declaration); - } - if (isEndOfArrowBlock(sourceCode.getLastToken(node, 1))) { - return false; - } - - return true; - } - - /** - * Check whether a given token can connect the previous statement. - * @param {Token} token A token to check. - * @returns {boolean} `true` if the token is one of `[`, `(`, `/`, `+`, `-`, ```, `++`, and `--`. - */ - function maybeAsiHazardBefore(token) { - return ( - Boolean(token) && - OPT_OUT_PATTERN.test(token.value) && - token.value !== "++" && - token.value !== "--" - ); - } - - /** - * Check if the semicolon of a given node is unnecessary, only true if: - * - next token is a valid statement divider (`;` or `}`). - * - next token is on a new line and the node is not connectable to the new line. - * @param {Node} node A statement node to check. - * @returns {boolean} whether the semicolon is unnecessary. - */ - function canRemoveSemicolon(node) { - if (isRedundantSemi(sourceCode.getLastToken(node))) { - return true; // `;;` or `;}` - } - if (isOnSameLineWithNextToken(node)) { - return false; // One liner. - } - if (beforeStatementContinuationChars === "never" && !maybeAsiHazardAfter(node)) { - return true; // ASI works. This statement doesn't connect to the next. - } - if (!maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { - return true; // ASI works. The next token doesn't connect to this statement. - } - - return false; - } - - /** - * Checks a node to see if it's in a one-liner block statement. - * @param {ASTNode} node The node to check. - * @returns {boolean} whether the node is in a one-liner block statement. - */ - function isOneLinerBlock(node) { - const parent = node.parent; - const nextToken = sourceCode.getTokenAfter(node); - - if (!nextToken || nextToken.value !== "}") { - return false; - } - return ( - !!parent && - parent.type === "BlockStatement" && - parent.loc.start.line === parent.loc.end.line - ); - } - - /** - * Checks a node to see if it's followed by a semicolon. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkForSemicolon(node) { - const isSemi = astUtils.isSemicolonToken(sourceCode.getLastToken(node)); - - if (never) { - if (isSemi && canRemoveSemicolon(node)) { - report(node, true); - } else if (!isSemi && beforeStatementContinuationChars === "always" && maybeAsiHazardBefore(sourceCode.getTokenAfter(node))) { - report(node); - } - } else { - const oneLinerBlock = (exceptOneLine && isOneLinerBlock(node)); - - if (isSemi && oneLinerBlock) { - report(node, true); - } else if (!isSemi && !oneLinerBlock) { - report(node); - } - } - } - - /** - * Checks to see if there's a semicolon after a variable declaration. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkForSemicolonForVariableDeclaration(node) { - const parent = node.parent; - - if ((parent.type !== "ForStatement" || parent.init !== node) && - (!/^For(?:In|Of)Statement/u.test(parent.type) || parent.left !== node) - ) { - checkForSemicolon(node); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - VariableDeclaration: checkForSemicolonForVariableDeclaration, - ExpressionStatement: checkForSemicolon, - ReturnStatement: checkForSemicolon, - ThrowStatement: checkForSemicolon, - DoWhileStatement: checkForSemicolon, - DebuggerStatement: checkForSemicolon, - BreakStatement: checkForSemicolon, - ContinueStatement: checkForSemicolon, - ImportDeclaration: checkForSemicolon, - ExportAllDeclaration: checkForSemicolon, - ExportNamedDeclaration(node) { - if (!node.declaration) { - checkForSemicolon(node); - } - }, - ExportDefaultDeclaration(node) { - if (!/(?:Class|Function)Declaration/u.test(node.declaration.type)) { - checkForSemicolon(node); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/sort-imports.js b/tools/node_modules/eslint/lib/rules/sort-imports.js deleted file mode 100644 index 4c3ddec766960a1a395d00b5ff6bc5d605953429..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/sort-imports.js +++ /dev/null @@ -1,241 +0,0 @@ -/** - * @fileoverview Rule to require sorting of import declarations - * @author Christian Schuller - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce sorted import declarations within modules", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/sort-imports" - }, - - schema: [ - { - type: "object", - properties: { - ignoreCase: { - type: "boolean", - default: false - }, - memberSyntaxSortOrder: { - type: "array", - items: { - enum: ["none", "all", "multiple", "single"] - }, - uniqueItems: true, - minItems: 4, - maxItems: 4 - }, - ignoreDeclarationSort: { - type: "boolean", - default: false - }, - ignoreMemberSort: { - type: "boolean", - default: false - }, - allowSeparatedGroups: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - sortImportsAlphabetically: "Imports should be sorted alphabetically.", - sortMembersAlphabetically: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", - unexpectedSyntaxOrder: "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax." - } - }, - - create(context) { - - const configuration = context.options[0] || {}, - ignoreCase = configuration.ignoreCase || false, - ignoreDeclarationSort = configuration.ignoreDeclarationSort || false, - ignoreMemberSort = configuration.ignoreMemberSort || false, - memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"], - allowSeparatedGroups = configuration.allowSeparatedGroups || false, - sourceCode = context.getSourceCode(); - let previousDeclaration = null; - - /** - * Gets the used member syntax style. - * - * import "my-module.js" --> none - * import * as myModule from "my-module.js" --> all - * import {myMember} from "my-module.js" --> single - * import {foo, bar} from "my-module.js" --> multiple - * @param {ASTNode} node the ImportDeclaration node. - * @returns {string} used member parameter style, ["all", "multiple", "single"] - */ - function usedMemberSyntax(node) { - if (node.specifiers.length === 0) { - return "none"; - } - if (node.specifiers[0].type === "ImportNamespaceSpecifier") { - return "all"; - } - if (node.specifiers.length === 1) { - return "single"; - } - return "multiple"; - - } - - /** - * Gets the group by member parameter index for given declaration. - * @param {ASTNode} node the ImportDeclaration node. - * @returns {number} the declaration group by member index. - */ - function getMemberParameterGroupIndex(node) { - return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node)); - } - - /** - * Gets the local name of the first imported module. - * @param {ASTNode} node the ImportDeclaration node. - * @returns {?string} the local name of the first imported module. - */ - function getFirstLocalMemberName(node) { - if (node.specifiers[0]) { - return node.specifiers[0].local.name; - } - return null; - - } - - /** - * Calculates number of lines between two nodes. It is assumed that the given `left` node appears before - * the given `right` node in the source code. Lines are counted from the end of the `left` node till the - * start of the `right` node. If the given nodes are on the same line, it returns `0`, same as if they were - * on two consecutive lines. - * @param {ASTNode} left node that appears before the given `right` node. - * @param {ASTNode} right node that appears after the given `left` node. - * @returns {number} number of lines between nodes. - */ - function getNumberOfLinesBetween(left, right) { - return Math.max(right.loc.start.line - left.loc.end.line - 1, 0); - } - - return { - ImportDeclaration(node) { - if (!ignoreDeclarationSort) { - if ( - previousDeclaration && - allowSeparatedGroups && - getNumberOfLinesBetween(previousDeclaration, node) > 0 - ) { - - // reset declaration sort - previousDeclaration = null; - } - - if (previousDeclaration) { - const currentMemberSyntaxGroupIndex = getMemberParameterGroupIndex(node), - previousMemberSyntaxGroupIndex = getMemberParameterGroupIndex(previousDeclaration); - let currentLocalMemberName = getFirstLocalMemberName(node), - previousLocalMemberName = getFirstLocalMemberName(previousDeclaration); - - if (ignoreCase) { - previousLocalMemberName = previousLocalMemberName && previousLocalMemberName.toLowerCase(); - currentLocalMemberName = currentLocalMemberName && currentLocalMemberName.toLowerCase(); - } - - /* - * When the current declaration uses a different member syntax, - * then check if the ordering is correct. - * Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name. - */ - if (currentMemberSyntaxGroupIndex !== previousMemberSyntaxGroupIndex) { - if (currentMemberSyntaxGroupIndex < previousMemberSyntaxGroupIndex) { - context.report({ - node, - messageId: "unexpectedSyntaxOrder", - data: { - syntaxA: memberSyntaxSortOrder[currentMemberSyntaxGroupIndex], - syntaxB: memberSyntaxSortOrder[previousMemberSyntaxGroupIndex] - } - }); - } - } else { - if (previousLocalMemberName && - currentLocalMemberName && - currentLocalMemberName < previousLocalMemberName - ) { - context.report({ - node, - messageId: "sortImportsAlphabetically" - }); - } - } - } - - previousDeclaration = node; - } - - if (!ignoreMemberSort) { - const importSpecifiers = node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"); - const getSortableName = ignoreCase ? specifier => specifier.local.name.toLowerCase() : specifier => specifier.local.name; - const firstUnsortedIndex = importSpecifiers.map(getSortableName).findIndex((name, index, array) => array[index - 1] > name); - - if (firstUnsortedIndex !== -1) { - context.report({ - node: importSpecifiers[firstUnsortedIndex], - messageId: "sortMembersAlphabetically", - data: { memberName: importSpecifiers[firstUnsortedIndex].local.name }, - fix(fixer) { - if (importSpecifiers.some(specifier => - sourceCode.getCommentsBefore(specifier).length || sourceCode.getCommentsAfter(specifier).length)) { - - // If there are comments in the ImportSpecifier list, don't rearrange the specifiers. - return null; - } - - return fixer.replaceTextRange( - [importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]], - importSpecifiers - - // Clone the importSpecifiers array to avoid mutating it - .slice() - - // Sort the array into the desired order - .sort((specifierA, specifierB) => { - const aName = getSortableName(specifierA); - const bName = getSortableName(specifierB); - - return aName > bName ? 1 : -1; - }) - - // Build a string out of the sorted list of import specifiers and the text between the originals - .reduce((sourceText, specifier, index) => { - const textAfterSpecifier = index === importSpecifiers.length - 1 - ? "" - : sourceCode.getText().slice(importSpecifiers[index].range[1], importSpecifiers[index + 1].range[0]); - - return sourceText + sourceCode.getText(specifier) + textAfterSpecifier; - }, "") - ); - } - }); - } - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/sort-keys.js b/tools/node_modules/eslint/lib/rules/sort-keys.js deleted file mode 100644 index 8a95ee25d6194824d752897bb6b9c014364c2e3b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/sort-keys.js +++ /dev/null @@ -1,187 +0,0 @@ -/** - * @fileoverview Rule to require object keys to be sorted - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"), - naturalCompare = require("natural-compare"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets the property name of the given `Property` node. - * - * - If the property's key is an `Identifier` node, this returns the key's name - * whether it's a computed property or not. - * - If the property has a static name, this returns the static name. - * - Otherwise, this returns null. - * @param {ASTNode} node The `Property` node to get. - * @returns {string|null} The property name or null. - * @private - */ -function getPropertyName(node) { - const staticName = astUtils.getStaticPropertyName(node); - - if (staticName !== null) { - return staticName; - } - - return node.key.name || null; -} - -/** - * Functions which check that the given 2 names are in specific order. - * - * Postfix `I` is meant insensitive. - * Postfix `N` is meant natural. - * @private - */ -const isValidOrders = { - asc(a, b) { - return a <= b; - }, - ascI(a, b) { - return a.toLowerCase() <= b.toLowerCase(); - }, - ascN(a, b) { - return naturalCompare(a, b) <= 0; - }, - ascIN(a, b) { - return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0; - }, - desc(a, b) { - return isValidOrders.asc(b, a); - }, - descI(a, b) { - return isValidOrders.ascI(b, a); - }, - descN(a, b) { - return isValidOrders.ascN(b, a); - }, - descIN(a, b) { - return isValidOrders.ascIN(b, a); - } -}; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require object keys to be sorted", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/sort-keys" - }, - - schema: [ - { - enum: ["asc", "desc"] - }, - { - type: "object", - properties: { - caseSensitive: { - type: "boolean", - default: true - }, - natural: { - type: "boolean", - default: false - }, - minKeys: { - type: "integer", - minimum: 2, - default: 2 - } - }, - additionalProperties: false - } - ], - - messages: { - sortKeys: "Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'." - } - }, - - create(context) { - - // Parse options. - const order = context.options[0] || "asc"; - const options = context.options[1]; - const insensitive = options && options.caseSensitive === false; - const natural = options && options.natural; - const minKeys = options && options.minKeys; - const isValidOrder = isValidOrders[ - order + (insensitive ? "I" : "") + (natural ? "N" : "") - ]; - - // The stack to save the previous property's name for each object literals. - let stack = null; - - return { - ObjectExpression(node) { - stack = { - upper: stack, - prevName: null, - numKeys: node.properties.length - }; - }, - - "ObjectExpression:exit"() { - stack = stack.upper; - }, - - SpreadElement(node) { - if (node.parent.type === "ObjectExpression") { - stack.prevName = null; - } - }, - - Property(node) { - if (node.parent.type === "ObjectPattern") { - return; - } - - const prevName = stack.prevName; - const numKeys = stack.numKeys; - const thisName = getPropertyName(node); - - if (thisName !== null) { - stack.prevName = thisName; - } - - if (prevName === null || thisName === null || numKeys < minKeys) { - return; - } - - if (!isValidOrder(prevName, thisName)) { - context.report({ - node, - loc: node.key.loc, - messageId: "sortKeys", - data: { - thisName, - prevName, - order, - insensitive: insensitive ? "insensitive " : "", - natural: natural ? "natural " : "" - } - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/sort-vars.js b/tools/node_modules/eslint/lib/rules/sort-vars.js deleted file mode 100644 index 7add2cf74b29400e4a238518fa1866e5addf0329..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/sort-vars.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @fileoverview Rule to require sorting of variables within a single Variable Declaration block - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require variables within the same declaration block to be sorted", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/sort-vars" - }, - - schema: [ - { - type: "object", - properties: { - ignoreCase: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code", - - messages: { - sortVars: "Variables within the same declaration block should be sorted alphabetically." - } - }, - - create(context) { - - const configuration = context.options[0] || {}, - ignoreCase = configuration.ignoreCase || false, - sourceCode = context.getSourceCode(); - - return { - VariableDeclaration(node) { - const idDeclarations = node.declarations.filter(decl => decl.id.type === "Identifier"); - const getSortableName = ignoreCase ? decl => decl.id.name.toLowerCase() : decl => decl.id.name; - const unfixable = idDeclarations.some(decl => decl.init !== null && decl.init.type !== "Literal"); - let fixed = false; - - idDeclarations.slice(1).reduce((memo, decl) => { - const lastVariableName = getSortableName(memo), - currentVariableName = getSortableName(decl); - - if (currentVariableName < lastVariableName) { - context.report({ - node: decl, - messageId: "sortVars", - fix(fixer) { - if (unfixable || fixed) { - return null; - } - return fixer.replaceTextRange( - [idDeclarations[0].range[0], idDeclarations[idDeclarations.length - 1].range[1]], - idDeclarations - - // Clone the idDeclarations array to avoid mutating it - .slice() - - // Sort the array into the desired order - .sort((declA, declB) => { - const aName = getSortableName(declA); - const bName = getSortableName(declB); - - return aName > bName ? 1 : -1; - }) - - // Build a string out of the sorted list of identifier declarations and the text between the originals - .reduce((sourceText, identifier, index) => { - const textAfterIdentifier = index === idDeclarations.length - 1 - ? "" - : sourceCode.getText().slice(idDeclarations[index].range[1], idDeclarations[index + 1].range[0]); - - return sourceText + sourceCode.getText(identifier) + textAfterIdentifier; - }, "") - - ); - } - }); - fixed = true; - return memo; - } - return decl; - - }, idDeclarations[0]); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-before-blocks.js b/tools/node_modules/eslint/lib/rules/space-before-blocks.js deleted file mode 100644 index 9b56481bf355fbbb45a31a846f4401249d11fed6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/space-before-blocks.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @fileoverview A rule to ensure whitespace before blocks. - * @author Mathias Schreck - */ - -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before blocks", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-before-blocks" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - keywords: { - enum: ["always", "never", "off"] - }, - functions: { - enum: ["always", "never", "off"] - }, - classes: { - enum: ["always", "never", "off"] - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedSpace: "Unexpected space before opening brace.", - missingSpace: "Missing space before opening brace." - } - }, - - create(context) { - const config = context.options[0], - sourceCode = context.getSourceCode(); - let alwaysFunctions = true, - alwaysKeywords = true, - alwaysClasses = true, - neverFunctions = false, - neverKeywords = false, - neverClasses = false; - - if (typeof config === "object") { - alwaysFunctions = config.functions === "always"; - alwaysKeywords = config.keywords === "always"; - alwaysClasses = config.classes === "always"; - neverFunctions = config.functions === "never"; - neverKeywords = config.keywords === "never"; - neverClasses = config.classes === "never"; - } else if (config === "never") { - alwaysFunctions = false; - alwaysKeywords = false; - alwaysClasses = false; - neverFunctions = true; - neverKeywords = true; - neverClasses = true; - } - - /** - * Checks whether or not a given token is an arrow operator (=>) or a keyword - * in order to avoid to conflict with `arrow-spacing` and `keyword-spacing`. - * @param {Token} token A token to check. - * @returns {boolean} `true` if the token is an arrow operator. - */ - function isConflicted(token) { - return (token.type === "Punctuator" && token.value === "=>") || token.type === "Keyword"; - } - - /** - * Checks the given BlockStatement node has a preceding space if it doesn’t start on a new line. - * @param {ASTNode|Token} node The AST node of a BlockStatement. - * @returns {void} undefined. - */ - function checkPrecedingSpace(node) { - const precedingToken = sourceCode.getTokenBefore(node); - - if (precedingToken && !isConflicted(precedingToken) && astUtils.isTokenOnSameLine(precedingToken, node)) { - const hasSpace = sourceCode.isSpaceBetweenTokens(precedingToken, node); - const parent = context.getAncestors().pop(); - let requireSpace; - let requireNoSpace; - - if (parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration") { - requireSpace = alwaysFunctions; - requireNoSpace = neverFunctions; - } else if (node.type === "ClassBody") { - requireSpace = alwaysClasses; - requireNoSpace = neverClasses; - } else { - requireSpace = alwaysKeywords; - requireNoSpace = neverKeywords; - } - - if (requireSpace && !hasSpace) { - context.report({ - node, - messageId: "missingSpace", - fix(fixer) { - return fixer.insertTextBefore(node, " "); - } - }); - } else if (requireNoSpace && hasSpace) { - context.report({ - node, - messageId: "unexpectedSpace", - fix(fixer) { - return fixer.removeRange([precedingToken.range[1], node.range[0]]); - } - }); - } - } - } - - /** - * Checks if the CaseBlock of an given SwitchStatement node has a preceding space. - * @param {ASTNode} node The node of a SwitchStatement. - * @returns {void} undefined. - */ - function checkSpaceBeforeCaseBlock(node) { - const cases = node.cases; - let openingBrace; - - if (cases.length > 0) { - openingBrace = sourceCode.getTokenBefore(cases[0]); - } else { - openingBrace = sourceCode.getLastToken(node, 1); - } - - checkPrecedingSpace(openingBrace); - } - - return { - BlockStatement: checkPrecedingSpace, - ClassBody: checkPrecedingSpace, - SwitchStatement: checkSpaceBeforeCaseBlock - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-before-function-paren.js b/tools/node_modules/eslint/lib/rules/space-before-function-paren.js deleted file mode 100644 index 1021a110cfd3f0488a46a597a368d6bb2b787f9f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/space-before-function-paren.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * @fileoverview Rule to validate spacing before function paren. - * @author Mathias Schreck - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before `function` definition opening parenthesis", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-before-function-paren" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - anonymous: { - enum: ["always", "never", "ignore"] - }, - named: { - enum: ["always", "never", "ignore"] - }, - asyncArrow: { - enum: ["always", "never", "ignore"] - } - }, - additionalProperties: false - } - ] - } - ], - - messages: { - unexpectedSpace: "Unexpected space before function parentheses.", - missingSpace: "Missing space before function parentheses." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const baseConfig = typeof context.options[0] === "string" ? context.options[0] : "always"; - const overrideConfig = typeof context.options[0] === "object" ? context.options[0] : {}; - - /** - * Determines whether a function has a name. - * @param {ASTNode} node The function node. - * @returns {boolean} Whether the function has a name. - */ - function isNamedFunction(node) { - if (node.id) { - return true; - } - - const parent = node.parent; - - return parent.type === "MethodDefinition" || - (parent.type === "Property" && - ( - parent.kind === "get" || - parent.kind === "set" || - parent.method - ) - ); - } - - /** - * Gets the config for a given function - * @param {ASTNode} node The function node - * @returns {string} "always", "never", or "ignore" - */ - function getConfigForFunction(node) { - if (node.type === "ArrowFunctionExpression") { - - // Always ignore non-async functions and arrow functions without parens, e.g. async foo => bar - if (node.async && astUtils.isOpeningParenToken(sourceCode.getFirstToken(node, { skip: 1 }))) { - return overrideConfig.asyncArrow || baseConfig; - } - } else if (isNamedFunction(node)) { - return overrideConfig.named || baseConfig; - - // `generator-star-spacing` should warn anonymous generators. E.g. `function* () {}` - } else if (!node.generator) { - return overrideConfig.anonymous || baseConfig; - } - - return "ignore"; - } - - /** - * Checks the parens of a function node - * @param {ASTNode} node A function node - * @returns {void} - */ - function checkFunction(node) { - const functionConfig = getConfigForFunction(node); - - if (functionConfig === "ignore") { - return; - } - - const rightToken = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken); - const leftToken = sourceCode.getTokenBefore(rightToken); - const hasSpacing = sourceCode.isSpaceBetweenTokens(leftToken, rightToken); - - if (hasSpacing && functionConfig === "never") { - context.report({ - node, - loc: { - start: leftToken.loc.end, - end: rightToken.loc.start - }, - messageId: "unexpectedSpace", - fix(fixer) { - const comments = sourceCode.getCommentsBefore(rightToken); - - // Don't fix anything if there's a single line comment between the left and the right token - if (comments.some(comment => comment.type === "Line")) { - return null; - } - return fixer.replaceTextRange( - [leftToken.range[1], rightToken.range[0]], - comments.reduce((text, comment) => text + sourceCode.getText(comment), "") - ); - } - }); - } else if (!hasSpacing && functionConfig === "always") { - context.report({ - node, - loc: rightToken.loc, - messageId: "missingSpace", - fix: fixer => fixer.insertTextAfter(leftToken, " ") - }); - } - } - - return { - ArrowFunctionExpression: checkFunction, - FunctionDeclaration: checkFunction, - FunctionExpression: checkFunction - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-in-parens.js b/tools/node_modules/eslint/lib/rules/space-in-parens.js deleted file mode 100644 index b0a604d955d788ff8c81a07907d8cc4015f4e44c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/space-in-parens.js +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @fileoverview Disallows or enforces spaces inside of parentheses. - * @author Jonathan Rajavuori - */ -"use strict"; - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing inside parentheses", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-in-parens" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - enum: ["{}", "[]", "()", "empty"] - }, - uniqueItems: true - } - }, - additionalProperties: false - } - ], - - messages: { - missingOpeningSpace: "There must be a space after this paren.", - missingClosingSpace: "There must be a space before this paren.", - rejectedOpeningSpace: "There should be no space after this paren.", - rejectedClosingSpace: "There should be no space before this paren." - } - }, - - create(context) { - const ALWAYS = context.options[0] === "always", - exceptionsArrayOptions = (context.options[1] && context.options[1].exceptions) || [], - options = {}; - - let exceptions; - - if (exceptionsArrayOptions.length) { - options.braceException = exceptionsArrayOptions.includes("{}"); - options.bracketException = exceptionsArrayOptions.includes("[]"); - options.parenException = exceptionsArrayOptions.includes("()"); - options.empty = exceptionsArrayOptions.includes("empty"); - } - - /** - * Produces an object with the opener and closer exception values - * @returns {Object} `openers` and `closers` exception values - * @private - */ - function getExceptions() { - const openers = [], - closers = []; - - if (options.braceException) { - openers.push("{"); - closers.push("}"); - } - - if (options.bracketException) { - openers.push("["); - closers.push("]"); - } - - if (options.parenException) { - openers.push("("); - closers.push(")"); - } - - if (options.empty) { - openers.push(")"); - closers.push("("); - } - - return { - openers, - closers - }; - } - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - const sourceCode = context.getSourceCode(); - - /** - * Determines if a token is one of the exceptions for the opener paren - * @param {Object} token The token to check - * @returns {boolean} True if the token is one of the exceptions for the opener paren - */ - function isOpenerException(token) { - return exceptions.openers.includes(token.value); - } - - /** - * Determines if a token is one of the exceptions for the closer paren - * @param {Object} token The token to check - * @returns {boolean} True if the token is one of the exceptions for the closer paren - */ - function isCloserException(token) { - return exceptions.closers.includes(token.value); - } - - /** - * Determines if an opening paren is immediately followed by a required space - * @param {Object} openingParenToken The paren token - * @param {Object} tokenAfterOpeningParen The token after it - * @returns {boolean} True if the opening paren is missing a required space - */ - function openerMissingSpace(openingParenToken, tokenAfterOpeningParen) { - if (sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) { - return false; - } - - if (!options.empty && astUtils.isClosingParenToken(tokenAfterOpeningParen)) { - return false; - } - - if (ALWAYS) { - return !isOpenerException(tokenAfterOpeningParen); - } - return isOpenerException(tokenAfterOpeningParen); - } - - /** - * Determines if an opening paren is immediately followed by a disallowed space - * @param {Object} openingParenToken The paren token - * @param {Object} tokenAfterOpeningParen The token after it - * @returns {boolean} True if the opening paren has a disallowed space - */ - function openerRejectsSpace(openingParenToken, tokenAfterOpeningParen) { - if (!astUtils.isTokenOnSameLine(openingParenToken, tokenAfterOpeningParen)) { - return false; - } - - if (tokenAfterOpeningParen.type === "Line") { - return false; - } - - if (!sourceCode.isSpaceBetweenTokens(openingParenToken, tokenAfterOpeningParen)) { - return false; - } - - if (ALWAYS) { - return isOpenerException(tokenAfterOpeningParen); - } - return !isOpenerException(tokenAfterOpeningParen); - } - - /** - * Determines if a closing paren is immediately preceded by a required space - * @param {Object} tokenBeforeClosingParen The token before the paren - * @param {Object} closingParenToken The paren token - * @returns {boolean} True if the closing paren is missing a required space - */ - function closerMissingSpace(tokenBeforeClosingParen, closingParenToken) { - if (sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) { - return false; - } - - if (!options.empty && astUtils.isOpeningParenToken(tokenBeforeClosingParen)) { - return false; - } - - if (ALWAYS) { - return !isCloserException(tokenBeforeClosingParen); - } - return isCloserException(tokenBeforeClosingParen); - } - - /** - * Determines if a closer paren is immediately preceded by a disallowed space - * @param {Object} tokenBeforeClosingParen The token before the paren - * @param {Object} closingParenToken The paren token - * @returns {boolean} True if the closing paren has a disallowed space - */ - function closerRejectsSpace(tokenBeforeClosingParen, closingParenToken) { - if (!astUtils.isTokenOnSameLine(tokenBeforeClosingParen, closingParenToken)) { - return false; - } - - if (!sourceCode.isSpaceBetweenTokens(tokenBeforeClosingParen, closingParenToken)) { - return false; - } - - if (ALWAYS) { - return isCloserException(tokenBeforeClosingParen); - } - return !isCloserException(tokenBeforeClosingParen); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - Program: function checkParenSpaces(node) { - exceptions = getExceptions(); - const tokens = sourceCode.tokensAndComments; - - tokens.forEach((token, i) => { - const prevToken = tokens[i - 1]; - const nextToken = tokens[i + 1]; - - // if token is not an opening or closing paren token, do nothing - if (!astUtils.isOpeningParenToken(token) && !astUtils.isClosingParenToken(token)) { - return; - } - - // if token is an opening paren and is not followed by a required space - if (token.value === "(" && openerMissingSpace(token, nextToken)) { - context.report({ - node, - loc: token.loc, - messageId: "missingOpeningSpace", - fix(fixer) { - return fixer.insertTextAfter(token, " "); - } - }); - } - - // if token is an opening paren and is followed by a disallowed space - if (token.value === "(" && openerRejectsSpace(token, nextToken)) { - context.report({ - node, - loc: { start: token.loc.end, end: nextToken.loc.start }, - messageId: "rejectedOpeningSpace", - fix(fixer) { - return fixer.removeRange([token.range[1], nextToken.range[0]]); - } - }); - } - - // if token is a closing paren and is not preceded by a required space - if (token.value === ")" && closerMissingSpace(prevToken, token)) { - context.report({ - node, - loc: token.loc, - messageId: "missingClosingSpace", - fix(fixer) { - return fixer.insertTextBefore(token, " "); - } - }); - } - - // if token is a closing paren and is preceded by a disallowed space - if (token.value === ")" && closerRejectsSpace(prevToken, token)) { - context.report({ - node, - loc: { start: prevToken.loc.end, end: token.loc.start }, - messageId: "rejectedClosingSpace", - fix(fixer) { - return fixer.removeRange([prevToken.range[1], token.range[0]]); - } - }); - } - }); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-infix-ops.js b/tools/node_modules/eslint/lib/rules/space-infix-ops.js deleted file mode 100644 index 471c22210eb613cfa7d655f9fd862189fb0776f8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/space-infix-ops.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @fileoverview Require spaces around infix operators - * @author Michael Ficarra - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require spacing around infix operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-infix-ops" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - int32Hint: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - missingSpace: "Operator '{{operator}}' must be spaced." - } - }, - - create(context) { - const int32Hint = context.options[0] ? context.options[0].int32Hint === true : false; - const sourceCode = context.getSourceCode(); - - /** - * Returns the first token which violates the rule - * @param {ASTNode} left The left node of the main node - * @param {ASTNode} right The right node of the main node - * @param {string} op The operator of the main node - * @returns {Object} The violator token or null - * @private - */ - function getFirstNonSpacedToken(left, right, op) { - const operator = sourceCode.getFirstTokenBetween(left, right, token => token.value === op); - const prev = sourceCode.getTokenBefore(operator); - const next = sourceCode.getTokenAfter(operator); - - if (!sourceCode.isSpaceBetweenTokens(prev, operator) || !sourceCode.isSpaceBetweenTokens(operator, next)) { - return operator; - } - - return null; - } - - /** - * Reports an AST node as a rule violation - * @param {ASTNode} mainNode The node to report - * @param {Object} culpritToken The token which has a problem - * @returns {void} - * @private - */ - function report(mainNode, culpritToken) { - context.report({ - node: mainNode, - loc: culpritToken.loc, - messageId: "missingSpace", - data: { - operator: culpritToken.value - }, - fix(fixer) { - const previousToken = sourceCode.getTokenBefore(culpritToken); - const afterToken = sourceCode.getTokenAfter(culpritToken); - let fixString = ""; - - if (culpritToken.range[0] - previousToken.range[1] === 0) { - fixString = " "; - } - - fixString += culpritToken.value; - - if (afterToken.range[0] - culpritToken.range[1] === 0) { - fixString += " "; - } - - return fixer.replaceText(culpritToken, fixString); - } - }); - } - - /** - * Check if the node is binary then report - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkBinary(node) { - const leftNode = (node.left.typeAnnotation) ? node.left.typeAnnotation : node.left; - const rightNode = node.right; - - // search for = in AssignmentPattern nodes - const operator = node.operator || "="; - - const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, operator); - - if (nonSpacedNode) { - if (!(int32Hint && sourceCode.getText(node).endsWith("|0"))) { - report(node, nonSpacedNode); - } - } - } - - /** - * Check if the node is conditional - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkConditional(node) { - const nonSpacedConsequentNode = getFirstNonSpacedToken(node.test, node.consequent, "?"); - const nonSpacedAlternateNode = getFirstNonSpacedToken(node.consequent, node.alternate, ":"); - - if (nonSpacedConsequentNode) { - report(node, nonSpacedConsequentNode); - } else if (nonSpacedAlternateNode) { - report(node, nonSpacedAlternateNode); - } - } - - /** - * Check if the node is a variable - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkVar(node) { - const leftNode = (node.id.typeAnnotation) ? node.id.typeAnnotation : node.id; - const rightNode = node.init; - - if (rightNode) { - const nonSpacedNode = getFirstNonSpacedToken(leftNode, rightNode, "="); - - if (nonSpacedNode) { - report(node, nonSpacedNode); - } - } - } - - return { - AssignmentExpression: checkBinary, - AssignmentPattern: checkBinary, - BinaryExpression: checkBinary, - LogicalExpression: checkBinary, - ConditionalExpression: checkConditional, - VariableDeclarator: checkVar - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/space-unary-ops.js b/tools/node_modules/eslint/lib/rules/space-unary-ops.js deleted file mode 100644 index f417eea58d8eb69d15fc6d34d19f0558ab858791..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/space-unary-ops.js +++ /dev/null @@ -1,321 +0,0 @@ -/** - * @fileoverview This rule shoud require or disallow spaces before or after unary operations. - * @author Marcin Kumorek - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce consistent spacing before or after unary operators", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/space-unary-ops" - }, - - fixable: "whitespace", - - schema: [ - { - type: "object", - properties: { - words: { - type: "boolean", - default: true - }, - nonwords: { - type: "boolean", - default: false - }, - overrides: { - type: "object", - additionalProperties: { - type: "boolean" - } - } - }, - additionalProperties: false - } - ], - messages: { - unexpectedBefore: "Unexpected space before unary operator '{{operator}}'.", - unexpectedAfter: "Unexpected space after unary operator '{{operator}}'.", - unexpectedAfterWord: "Unexpected space after unary word operator '{{word}}'.", - wordOperator: "Unary word operator '{{word}}' must be followed by whitespace.", - operator: "Unary operator '{{operator}}' must be followed by whitespace.", - beforeUnaryExpressions: "Space is required before unary expressions '{{token}}'." - } - }, - - create(context) { - const options = context.options[0] || { words: true, nonwords: false }; - - const sourceCode = context.getSourceCode(); - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - /** - * Check if the node is the first "!" in a "!!" convert to Boolean expression - * @param {ASTnode} node AST node - * @returns {boolean} Whether or not the node is first "!" in "!!" - */ - function isFirstBangInBangBangExpression(node) { - return node && node.type === "UnaryExpression" && node.argument.operator === "!" && - node.argument && node.argument.type === "UnaryExpression" && node.argument.operator === "!"; - } - - /** - * Checks if an override exists for a given operator. - * @param {string} operator Operator - * @returns {boolean} Whether or not an override has been provided for the operator - */ - function overrideExistsForOperator(operator) { - return options.overrides && Object.prototype.hasOwnProperty.call(options.overrides, operator); - } - - /** - * Gets the value that the override was set to for this operator - * @param {string} operator Operator - * @returns {boolean} Whether or not an override enforces a space with this operator - */ - function overrideEnforcesSpaces(operator) { - return options.overrides[operator]; - } - - /** - * Verify Unary Word Operator has spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ - function verifyWordHasSpaces(node, firstToken, secondToken, word) { - if (secondToken.range[0] === firstToken.range[1]) { - context.report({ - node, - messageId: "wordOperator", - data: { - word - }, - fix(fixer) { - return fixer.insertTextAfter(firstToken, " "); - } - }); - } - } - - /** - * Verify Unary Word Operator doesn't have spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ - function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) { - if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { - if (secondToken.range[0] > firstToken.range[1]) { - context.report({ - node, - messageId: "unexpectedAfterWord", - data: { - word - }, - fix(fixer) { - return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); - } - }); - } - } - } - - /** - * Check Unary Word Operators for spaces after the word operator - * @param {ASTnode} node AST node - * @param {Object} firstToken first token from the AST node - * @param {Object} secondToken second token from the AST node - * @param {string} word The word to be used for reporting - * @returns {void} - */ - function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) { - if (overrideExistsForOperator(word)) { - if (overrideEnforcesSpaces(word)) { - verifyWordHasSpaces(node, firstToken, secondToken, word); - } else { - verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); - } - } else if (options.words) { - verifyWordHasSpaces(node, firstToken, secondToken, word); - } else { - verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); - } - } - - /** - * Verifies YieldExpressions satisfy spacing requirements - * @param {ASTnode} node AST node - * @returns {void} - */ - function checkForSpacesAfterYield(node) { - const tokens = sourceCode.getFirstTokens(node, 3), - word = "yield"; - - if (!node.argument || node.delegate) { - return; - } - - checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word); - } - - /** - * Verifies AwaitExpressions satisfy spacing requirements - * @param {ASTNode} node AwaitExpression AST node - * @returns {void} - */ - function checkForSpacesAfterAwait(node) { - const tokens = sourceCode.getFirstTokens(node, 3); - - checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], "await"); - } - - /** - * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator - * @param {ASTnode} node AST node - * @param {Object} firstToken First token in the expression - * @param {Object} secondToken Second token in the expression - * @returns {void} - */ - function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { - if (node.prefix) { - if (isFirstBangInBangBangExpression(node)) { - return; - } - if (firstToken.range[1] === secondToken.range[0]) { - context.report({ - node, - messageId: "operator", - data: { - operator: firstToken.value - }, - fix(fixer) { - return fixer.insertTextAfter(firstToken, " "); - } - }); - } - } else { - if (firstToken.range[1] === secondToken.range[0]) { - context.report({ - node, - messageId: "beforeUnaryExpressions", - data: { - token: secondToken.value - }, - fix(fixer) { - return fixer.insertTextBefore(secondToken, " "); - } - }); - } - } - } - - /** - * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator - * @param {ASTnode} node AST node - * @param {Object} firstToken First token in the expression - * @param {Object} secondToken Second token in the expression - * @returns {void} - */ - function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { - if (node.prefix) { - if (secondToken.range[0] > firstToken.range[1]) { - context.report({ - node, - messageId: "unexpectedAfter", - data: { - operator: firstToken.value - }, - fix(fixer) { - if (astUtils.canTokensBeAdjacent(firstToken, secondToken)) { - return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); - } - return null; - } - }); - } - } else { - if (secondToken.range[0] > firstToken.range[1]) { - context.report({ - node, - messageId: "unexpectedBefore", - data: { - operator: secondToken.value - }, - fix(fixer) { - return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); - } - }); - } - } - } - - /** - * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements - * @param {ASTnode} node AST node - * @returns {void} - */ - function checkForSpaces(node) { - const tokens = node.type === "UpdateExpression" && !node.prefix - ? sourceCode.getLastTokens(node, 2) - : sourceCode.getFirstTokens(node, 2); - const firstToken = tokens[0]; - const secondToken = tokens[1]; - - if ((node.type === "NewExpression" || node.prefix) && firstToken.type === "Keyword") { - checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, firstToken.value); - return; - } - - const operator = node.prefix ? tokens[0].value : tokens[1].value; - - if (overrideExistsForOperator(operator)) { - if (overrideEnforcesSpaces(operator)) { - verifyNonWordsHaveSpaces(node, firstToken, secondToken); - } else { - verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); - } - } else if (options.nonwords) { - verifyNonWordsHaveSpaces(node, firstToken, secondToken); - } else { - verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); - } - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - UnaryExpression: checkForSpaces, - UpdateExpression: checkForSpaces, - NewExpression: checkForSpaces, - YieldExpression: checkForSpacesAfterYield, - AwaitExpression: checkForSpacesAfterAwait - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/spaced-comment.js b/tools/node_modules/eslint/lib/rules/spaced-comment.js deleted file mode 100644 index d3221f0ea798ac62708d73a8f658270d3736ab63..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/spaced-comment.js +++ /dev/null @@ -1,382 +0,0 @@ -/** - * @fileoverview Source code for spaced-comments rule - * @author Gyandeep Singh - */ -"use strict"; - -const lodash = require("lodash"); -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Escapes the control characters of a given string. - * @param {string} s A string to escape. - * @returns {string} An escaped string. - */ -function escape(s) { - return `(?:${lodash.escapeRegExp(s)})`; -} - -/** - * Escapes the control characters of a given string. - * And adds a repeat flag. - * @param {string} s A string to escape. - * @returns {string} An escaped string. - */ -function escapeAndRepeat(s) { - return `${escape(s)}+`; -} - -/** - * Parses `markers` option. - * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments. - * @param {string[]} [markers] A marker list. - * @returns {string[]} A marker list. - */ -function parseMarkersOption(markers) { - - // `*` is a marker for JSDoc comments. - if (markers.indexOf("*") === -1) { - return markers.concat("*"); - } - - return markers; -} - -/** - * Creates string pattern for exceptions. - * Generated pattern: - * - * 1. A space or an exception pattern sequence. - * @param {string[]} exceptions An exception pattern list. - * @returns {string} A regular expression string for exceptions. - */ -function createExceptionsPattern(exceptions) { - let pattern = ""; - - /* - * A space or an exception pattern sequence. - * [] ==> "\s" - * ["-"] ==> "(?:\s|\-+$)" - * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)" - * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24) - */ - if (exceptions.length === 0) { - - // a space. - pattern += "\\s"; - } else { - - // a space or... - pattern += "(?:\\s|"; - - if (exceptions.length === 1) { - - // a sequence of the exception pattern. - pattern += escapeAndRepeat(exceptions[0]); - } else { - - // a sequence of one of the exception patterns. - pattern += "(?:"; - pattern += exceptions.map(escapeAndRepeat).join("|"); - pattern += ")"; - } - pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`; - } - - return pattern; -} - -/** - * Creates RegExp object for `always` mode. - * Generated pattern for beginning of comment: - * - * 1. First, a marker or nothing. - * 2. Next, a space or an exception pattern sequence. - * @param {string[]} markers A marker list. - * @param {string[]} exceptions An exception pattern list. - * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode. - */ -function createAlwaysStylePattern(markers, exceptions) { - let pattern = "^"; - - /* - * A marker or nothing. - * ["*"] ==> "\*?" - * ["*", "!"] ==> "(?:\*|!)?" - * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F - */ - if (markers.length === 1) { - - // the marker. - pattern += escape(markers[0]); - } else { - - // one of markers. - pattern += "(?:"; - pattern += markers.map(escape).join("|"); - pattern += ")"; - } - - pattern += "?"; // or nothing. - pattern += createExceptionsPattern(exceptions); - - return new RegExp(pattern, "u"); -} - -/** - * Creates RegExp object for `never` mode. - * Generated pattern for beginning of comment: - * - * 1. First, a marker or nothing (captured). - * 2. Next, a space or a tab. - * @param {string[]} markers A marker list. - * @returns {RegExp} A RegExp object for `never` mode. - */ -function createNeverStylePattern(markers) { - const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`; - - return new RegExp(pattern, "u"); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce consistent spacing after the `//` or `/*` in a comment", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/spaced-comment" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - } - }, - markers: { - type: "array", - items: { - type: "string" - } - }, - line: { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - } - }, - markers: { - type: "array", - items: { - type: "string" - } - } - }, - additionalProperties: false - }, - block: { - type: "object", - properties: { - exceptions: { - type: "array", - items: { - type: "string" - } - }, - markers: { - type: "array", - items: { - type: "string" - } - }, - balanced: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - }, - additionalProperties: false - } - ], - - messages: { - unexpectedSpaceAfterMarker: "Unexpected space or tab after marker ({{refChar}}) in comment.", - expectedExceptionAfter: "Expected exception block, space or tab after '{{refChar}}' in comment.", - unexpectedSpaceBefore: "Unexpected space or tab before '*/' in comment.", - unexpectedSpaceAfter: "Unexpected space or tab after '{{refChar}}' in comment.", - expectedSpaceBefore: "Expected space or tab before '*/' in comment.", - expectedSpaceAfter: "Expected space or tab after '{{refChar}}' in comment." - } - }, - - create(context) { - - const sourceCode = context.getSourceCode(); - - // Unless the first option is never, require a space - const requireSpace = context.options[0] !== "never"; - - /* - * Parse the second options. - * If markers don't include `"*"`, it's added automatically for JSDoc - * comments. - */ - const config = context.options[1] || {}; - const balanced = config.block && config.block.balanced; - - const styleRules = ["block", "line"].reduce((rule, type) => { - const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []); - const exceptions = config[type] && config[type].exceptions || config.exceptions || []; - const endNeverPattern = "[ \t]+$"; - - // Create RegExp object for valid patterns. - rule[type] = { - beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers), - endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`, "u") : new RegExp(endNeverPattern, "u"), - hasExceptions: exceptions.length > 0, - captureMarker: new RegExp(`^(${markers.map(escape).join("|")})`, "u"), - markers: new Set(markers) - }; - - return rule; - }, {}); - - /** - * Reports a beginning spacing error with an appropriate message. - * @param {ASTNode} node A comment node to check. - * @param {string} messageId An error message to report. - * @param {Array} match An array of match results for markers. - * @param {string} refChar Character used for reference in the error message. - * @returns {void} - */ - function reportBegin(node, messageId, match, refChar) { - const type = node.type.toLowerCase(), - commentIdentifier = type === "block" ? "/*" : "//"; - - context.report({ - node, - fix(fixer) { - const start = node.range[0]; - let end = start + 2; - - if (requireSpace) { - if (match) { - end += match[0].length; - } - return fixer.insertTextAfterRange([start, end], " "); - } - end += match[0].length; - return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : "")); - - }, - messageId, - data: { refChar } - }); - } - - /** - * Reports an ending spacing error with an appropriate message. - * @param {ASTNode} node A comment node to check. - * @param {string} messageId An error message to report. - * @param {string} match An array of the matched whitespace characters. - * @returns {void} - */ - function reportEnd(node, messageId, match) { - context.report({ - node, - fix(fixer) { - if (requireSpace) { - return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " "); - } - const end = node.range[1] - 2, - start = end - match[0].length; - - return fixer.replaceTextRange([start, end], ""); - - }, - messageId - }); - } - - /** - * Reports a given comment if it's invalid. - * @param {ASTNode} node a comment node to check. - * @returns {void} - */ - function checkCommentForSpace(node) { - const type = node.type.toLowerCase(), - rule = styleRules[type], - commentIdentifier = type === "block" ? "/*" : "//"; - - // Ignores empty comments and comments that consist only of a marker. - if (node.value.length === 0 || rule.markers.has(node.value)) { - return; - } - - const beginMatch = rule.beginRegex.exec(node.value); - const endMatch = rule.endRegex.exec(node.value); - - // Checks. - if (requireSpace) { - if (!beginMatch) { - const hasMarker = rule.captureMarker.exec(node.value); - const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier; - - if (rule.hasExceptions) { - reportBegin(node, "expectedExceptionAfter", hasMarker, marker); - } else { - reportBegin(node, "expectedSpaceAfter", hasMarker, marker); - } - } - - if (balanced && type === "block" && !endMatch) { - reportEnd(node, "expectedSpaceBefore"); - } - } else { - if (beginMatch) { - if (!beginMatch[1]) { - reportBegin(node, "unexpectedSpaceAfter", beginMatch, commentIdentifier); - } else { - reportBegin(node, "unexpectedSpaceAfterMarker", beginMatch, beginMatch[1]); - } - } - - if (balanced && type === "block" && endMatch) { - reportEnd(node, "unexpectedSpaceBefore", endMatch); - } - } - } - - return { - Program() { - const comments = sourceCode.getAllComments(); - - comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/strict.js b/tools/node_modules/eslint/lib/rules/strict.js deleted file mode 100644 index b0d6cf9172a74bdbb3aefd0877216d99b6e05a2b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/strict.js +++ /dev/null @@ -1,277 +0,0 @@ -/** - * @fileoverview Rule to control usage of strict mode directives. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets all of the Use Strict Directives in the Directive Prologue of a group of - * statements. - * @param {ASTNode[]} statements Statements in the program or function body. - * @returns {ASTNode[]} All of the Use Strict Directives. - */ -function getUseStrictDirectives(statements) { - const directives = []; - - for (let i = 0; i < statements.length; i++) { - const statement = statements[i]; - - if ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - statement.expression.value === "use strict" - ) { - directives[i] = statement; - } else { - break; - } - } - - return directives; -} - -/** - * Checks whether a given parameter is a simple parameter. - * @param {ASTNode} node A pattern node to check. - * @returns {boolean} `true` if the node is an Identifier node. - */ -function isSimpleParameter(node) { - return node.type === "Identifier"; -} - -/** - * Checks whether a given parameter list is a simple parameter list. - * @param {ASTNode[]} params A parameter list to check. - * @returns {boolean} `true` if the every parameter is an Identifier node. - */ -function isSimpleParameterList(params) { - return params.every(isSimpleParameter); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require or disallow strict mode directives", - category: "Strict Mode", - recommended: false, - url: "https://eslint.org/docs/rules/strict" - }, - - schema: [ - { - enum: ["never", "global", "function", "safe"] - } - ], - - fixable: "code", - messages: { - function: "Use the function form of 'use strict'.", - global: "Use the global form of 'use strict'.", - multiple: "Multiple 'use strict' directives.", - never: "Strict mode is not permitted.", - unnecessary: "Unnecessary 'use strict' directive.", - module: "'use strict' is unnecessary inside of modules.", - implied: "'use strict' is unnecessary when implied strict mode is enabled.", - unnecessaryInClasses: "'use strict' is unnecessary inside of classes.", - nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.", - wrap: "Wrap {{name}} in a function with 'use strict' directive." - } - }, - - create(context) { - - const ecmaFeatures = context.parserOptions.ecmaFeatures || {}, - scopes = [], - classScopes = []; - let mode = context.options[0] || "safe"; - - if (ecmaFeatures.impliedStrict) { - mode = "implied"; - } else if (mode === "safe") { - mode = ecmaFeatures.globalReturn ? "global" : "function"; - } - - /** - * Determines whether a reported error should be fixed, depending on the error type. - * @param {string} errorType The type of error - * @returns {boolean} `true` if the reported error should be fixed - */ - function shouldFix(errorType) { - return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses"; - } - - /** - * Gets a fixer function to remove a given 'use strict' directive. - * @param {ASTNode} node The directive that should be removed - * @returns {Function} A fixer function - */ - function getFixFunction(node) { - return fixer => fixer.remove(node); - } - - /** - * Report a slice of an array of nodes with a given message. - * @param {ASTNode[]} nodes Nodes. - * @param {string} start Index to start from. - * @param {string} end Index to end before. - * @param {string} messageId Message to display. - * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) - * @returns {void} - */ - function reportSlice(nodes, start, end, messageId, fix) { - nodes.slice(start, end).forEach(node => { - context.report({ node, messageId, fix: fix ? getFixFunction(node) : null }); - }); - } - - /** - * Report all nodes in an array with a given message. - * @param {ASTNode[]} nodes Nodes. - * @param {string} messageId Message id to display. - * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) - * @returns {void} - */ - function reportAll(nodes, messageId, fix) { - reportSlice(nodes, 0, nodes.length, messageId, fix); - } - - /** - * Report all nodes in an array, except the first, with a given message. - * @param {ASTNode[]} nodes Nodes. - * @param {string} messageId Message id to display. - * @param {boolean} fix `true` if the directive should be fixed (i.e. removed) - * @returns {void} - */ - function reportAllExceptFirst(nodes, messageId, fix) { - reportSlice(nodes, 1, nodes.length, messageId, fix); - } - - /** - * Entering a function in 'function' mode pushes a new nested scope onto the - * stack. The new scope is true if the nested function is strict mode code. - * @param {ASTNode} node The function declaration or expression. - * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node. - * @returns {void} - */ - function enterFunctionInFunctionMode(node, useStrictDirectives) { - const isInClass = classScopes.length > 0, - isParentGlobal = scopes.length === 0 && classScopes.length === 0, - isParentStrict = scopes.length > 0 && scopes[scopes.length - 1], - isStrict = useStrictDirectives.length > 0; - - if (isStrict) { - if (!isSimpleParameterList(node.params)) { - context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" }); - } else if (isParentStrict) { - context.report({ node: useStrictDirectives[0], messageId: "unnecessary", fix: getFixFunction(useStrictDirectives[0]) }); - } else if (isInClass) { - context.report({ node: useStrictDirectives[0], messageId: "unnecessaryInClasses", fix: getFixFunction(useStrictDirectives[0]) }); - } - - reportAllExceptFirst(useStrictDirectives, "multiple", true); - } else if (isParentGlobal) { - if (isSimpleParameterList(node.params)) { - context.report({ node, messageId: "function" }); - } else { - context.report({ - node, - messageId: "wrap", - data: { name: astUtils.getFunctionNameWithKind(node) } - }); - } - } - - scopes.push(isParentStrict || isStrict); - } - - /** - * Exiting a function in 'function' mode pops its scope off the stack. - * @returns {void} - */ - function exitFunctionInFunctionMode() { - scopes.pop(); - } - - /** - * Enter a function and either: - * - Push a new nested scope onto the stack (in 'function' mode). - * - Report all the Use Strict Directives (in the other modes). - * @param {ASTNode} node The function declaration or expression. - * @returns {void} - */ - function enterFunction(node) { - const isBlock = node.body.type === "BlockStatement", - useStrictDirectives = isBlock - ? getUseStrictDirectives(node.body.body) : []; - - if (mode === "function") { - enterFunctionInFunctionMode(node, useStrictDirectives); - } else if (useStrictDirectives.length > 0) { - if (isSimpleParameterList(node.params)) { - reportAll(useStrictDirectives, mode, shouldFix(mode)); - } else { - context.report({ node: useStrictDirectives[0], messageId: "nonSimpleParameterList" }); - reportAllExceptFirst(useStrictDirectives, "multiple", true); - } - } - } - - const rule = { - Program(node) { - const useStrictDirectives = getUseStrictDirectives(node.body); - - if (node.sourceType === "module") { - mode = "module"; - } - - if (mode === "global") { - if (node.body.length > 0 && useStrictDirectives.length === 0) { - context.report({ node, messageId: "global" }); - } - reportAllExceptFirst(useStrictDirectives, "multiple", true); - } else { - reportAll(useStrictDirectives, mode, shouldFix(mode)); - } - }, - FunctionDeclaration: enterFunction, - FunctionExpression: enterFunction, - ArrowFunctionExpression: enterFunction - }; - - if (mode === "function") { - Object.assign(rule, { - - // Inside of class bodies are always strict mode. - ClassBody() { - classScopes.push(true); - }, - "ClassBody:exit"() { - classScopes.pop(); - }, - - "FunctionDeclaration:exit": exitFunctionInFunctionMode, - "FunctionExpression:exit": exitFunctionInFunctionMode, - "ArrowFunctionExpression:exit": exitFunctionInFunctionMode - }); - } - - return rule; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js b/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js deleted file mode 100644 index c90641573c6010e06bf3941555aa9481c480ade3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/switch-colon-spacing.js +++ /dev/null @@ -1,141 +0,0 @@ -/** - * @fileoverview Rule to enforce spacing around colons of switch statements. - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "enforce spacing around colons of switch statements", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/switch-colon-spacing" - }, - - schema: [ - { - type: "object", - properties: { - before: { type: "boolean", default: false }, - after: { type: "boolean", default: true } - }, - additionalProperties: false - } - ], - fixable: "whitespace", - messages: { - expectedBefore: "Expected space(s) before this colon.", - expectedAfter: "Expected space(s) after this colon.", - unexpectedBefore: "Unexpected space(s) before this colon.", - unexpectedAfter: "Unexpected space(s) after this colon." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const options = context.options[0] || {}; - const beforeSpacing = options.before === true; // false by default - const afterSpacing = options.after !== false; // true by default - - /** - * Get the colon token of the given SwitchCase node. - * @param {ASTNode} node The SwitchCase node to get. - * @returns {Token} The colon token of the node. - */ - function getColonToken(node) { - if (node.test) { - return sourceCode.getTokenAfter(node.test, astUtils.isColonToken); - } - return sourceCode.getFirstToken(node, 1); - } - - /** - * Check whether the spacing between the given 2 tokens is valid or not. - * @param {Token} left The left token to check. - * @param {Token} right The right token to check. - * @param {boolean} expected The expected spacing to check. `true` if there should be a space. - * @returns {boolean} `true` if the spacing between the tokens is valid. - */ - function isValidSpacing(left, right, expected) { - return ( - astUtils.isClosingBraceToken(right) || - !astUtils.isTokenOnSameLine(left, right) || - sourceCode.isSpaceBetweenTokens(left, right) === expected - ); - } - - /** - * Check whether comments exist between the given 2 tokens. - * @param {Token} left The left token to check. - * @param {Token} right The right token to check. - * @returns {boolean} `true` if comments exist between the given 2 tokens. - */ - function commentsExistBetween(left, right) { - return sourceCode.getFirstTokenBetween( - left, - right, - { - includeComments: true, - filter: astUtils.isCommentToken - } - ) !== null; - } - - /** - * Fix the spacing between the given 2 tokens. - * @param {RuleFixer} fixer The fixer to fix. - * @param {Token} left The left token of fix range. - * @param {Token} right The right token of fix range. - * @param {boolean} spacing The spacing style. `true` if there should be a space. - * @returns {Fix|null} The fix object. - */ - function fix(fixer, left, right, spacing) { - if (commentsExistBetween(left, right)) { - return null; - } - if (spacing) { - return fixer.insertTextAfter(left, " "); - } - return fixer.removeRange([left.range[1], right.range[0]]); - } - - return { - SwitchCase(node) { - const colonToken = getColonToken(node); - const beforeToken = sourceCode.getTokenBefore(colonToken); - const afterToken = sourceCode.getTokenAfter(colonToken); - - if (!isValidSpacing(beforeToken, colonToken, beforeSpacing)) { - context.report({ - node, - loc: colonToken.loc, - messageId: beforeSpacing ? "expectedBefore" : "unexpectedBefore", - fix: fixer => fix(fixer, beforeToken, colonToken, beforeSpacing) - }); - } - if (!isValidSpacing(colonToken, afterToken, afterSpacing)) { - context.report({ - node, - loc: colonToken.loc, - messageId: afterSpacing ? "expectedAfter" : "unexpectedAfter", - fix: fixer => fix(fixer, colonToken, afterToken, afterSpacing) - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/symbol-description.js b/tools/node_modules/eslint/lib/rules/symbol-description.js deleted file mode 100644 index 155cea4dc0bceb8d7012203068f760b6d2731e3f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/symbol-description.js +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @fileoverview Rule to enforce description with the `Symbol` object - * @author Jarek Rencz - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require symbol descriptions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/symbol-description" - }, - fixable: null, - schema: [], - messages: { - expected: "Expected Symbol to have a description." - } - }, - - create(context) { - - /** - * Reports if node does not conform the rule in case rule is set to - * report missing description - * @param {ASTNode} node A CallExpression node to check. - * @returns {void} - */ - function checkArgument(node) { - if (node.arguments.length === 0) { - context.report({ - node, - messageId: "expected" - }); - } - } - - return { - "Program:exit"() { - const scope = context.getScope(); - const variable = astUtils.getVariableByName(scope, "Symbol"); - - if (variable && variable.defs.length === 0) { - variable.references.forEach(reference => { - const node = reference.identifier; - - if (astUtils.isCallee(node)) { - checkArgument(node.parent); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/template-curly-spacing.js b/tools/node_modules/eslint/lib/rules/template-curly-spacing.js deleted file mode 100644 index 26043bc912210a6930045fe77b448105b63bd5d5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/template-curly-spacing.js +++ /dev/null @@ -1,141 +0,0 @@ -/** - * @fileoverview Rule to enforce spacing around embedded expressions of template strings - * @author Toru Nagashima - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing around embedded expressions of template strings", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/template-curly-spacing" - }, - - fixable: "whitespace", - - schema: [ - { enum: ["always", "never"] } - ], - messages: { - expectedBefore: "Expected space(s) before '}'.", - expectedAfter: "Expected space(s) after '${'.", - unexpectedBefore: "Unexpected space(s) before '}'.", - unexpectedAfter: "Unexpected space(s) after '${'." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - const always = context.options[0] === "always"; - - /** - * Checks spacing before `}` of a given token. - * @param {Token} token A token to check. This is a Template token. - * @returns {void} - */ - function checkSpacingBefore(token) { - if (!token.value.startsWith("}")) { - return; // starts with a backtick, this is the first template element in the template literal - } - - const prevToken = sourceCode.getTokenBefore(token, { includeComments: true }), - hasSpace = sourceCode.isSpaceBetween(prevToken, token); - - if (!astUtils.isTokenOnSameLine(prevToken, token)) { - return; - } - - if (always && !hasSpace) { - context.report({ - loc: { - start: token.loc.start, - end: { - line: token.loc.start.line, - column: token.loc.start.column + 1 - } - }, - messageId: "expectedBefore", - fix: fixer => fixer.insertTextBefore(token, " ") - }); - } - - if (!always && hasSpace) { - context.report({ - loc: { - start: prevToken.loc.end, - end: token.loc.start - }, - messageId: "unexpectedBefore", - fix: fixer => fixer.removeRange([prevToken.range[1], token.range[0]]) - }); - } - } - - /** - * Checks spacing after `${` of a given token. - * @param {Token} token A token to check. This is a Template token. - * @returns {void} - */ - function checkSpacingAfter(token) { - if (!token.value.endsWith("${")) { - return; // ends with a backtick, this is the last template element in the template literal - } - - const nextToken = sourceCode.getTokenAfter(token, { includeComments: true }), - hasSpace = sourceCode.isSpaceBetween(token, nextToken); - - if (!astUtils.isTokenOnSameLine(token, nextToken)) { - return; - } - - if (always && !hasSpace) { - context.report({ - loc: { - start: { - line: token.loc.end.line, - column: token.loc.end.column - 2 - }, - end: token.loc.end - }, - messageId: "expectedAfter", - fix: fixer => fixer.insertTextAfter(token, " ") - }); - } - - if (!always && hasSpace) { - context.report({ - loc: { - start: token.loc.end, - end: nextToken.loc.start - }, - messageId: "unexpectedAfter", - fix: fixer => fixer.removeRange([token.range[1], nextToken.range[0]]) - }); - } - } - - return { - TemplateElement(node) { - const token = sourceCode.getFirstToken(node); - - checkSpacingBefore(token); - checkSpacingAfter(token); - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/template-tag-spacing.js b/tools/node_modules/eslint/lib/rules/template-tag-spacing.js deleted file mode 100644 index 16f586255af567b0bab8cc0dedd7a46207108cf4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/template-tag-spacing.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @fileoverview Rule to check spacing between template tags and their literals - * @author Jonathan Wilsson - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing between template tags and their literals", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/template-tag-spacing" - }, - - fixable: "whitespace", - - schema: [ - { enum: ["always", "never"] } - ], - messages: { - unexpected: "Unexpected space between template tag and template literal.", - missing: "Missing space between template tag and template literal." - } - }, - - create(context) { - const never = context.options[0] !== "always"; - const sourceCode = context.getSourceCode(); - - /** - * Check if a space is present between a template tag and its literal - * @param {ASTNode} node node to evaluate - * @returns {void} - * @private - */ - function checkSpacing(node) { - const tagToken = sourceCode.getTokenBefore(node.quasi); - const literalToken = sourceCode.getFirstToken(node.quasi); - const hasWhitespace = sourceCode.isSpaceBetweenTokens(tagToken, literalToken); - - if (never && hasWhitespace) { - context.report({ - node, - loc: { - start: tagToken.loc.end, - end: literalToken.loc.start - }, - messageId: "unexpected", - fix(fixer) { - const comments = sourceCode.getCommentsBefore(node.quasi); - - // Don't fix anything if there's a single line comment after the template tag - if (comments.some(comment => comment.type === "Line")) { - return null; - } - - return fixer.replaceTextRange( - [tagToken.range[1], literalToken.range[0]], - comments.reduce((text, comment) => text + sourceCode.getText(comment), "") - ); - } - }); - } else if (!never && !hasWhitespace) { - context.report({ - node, - loc: { - start: node.loc.start, - end: literalToken.loc.start - }, - messageId: "missing", - fix(fixer) { - return fixer.insertTextAfter(tagToken, " "); - } - }); - } - } - - return { - TaggedTemplateExpression: checkSpacing - }; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/unicode-bom.js b/tools/node_modules/eslint/lib/rules/unicode-bom.js deleted file mode 100644 index 39642f85193e90ab525ae4c5f66365e13eca2980..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/unicode-bom.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * @fileoverview Require or disallow Unicode BOM - * @author Andrew Johnston - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow Unicode byte order mark (BOM)", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/unicode-bom" - }, - - fixable: "whitespace", - - schema: [ - { - enum: ["always", "never"] - } - ], - messages: { - expected: "Expected Unicode BOM (Byte Order Mark).", - unexpected: "Unexpected Unicode BOM (Byte Order Mark)." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - Program: function checkUnicodeBOM(node) { - - const sourceCode = context.getSourceCode(), - location = { column: 0, line: 1 }, - requireBOM = context.options[0] || "never"; - - if (!sourceCode.hasBOM && (requireBOM === "always")) { - context.report({ - node, - loc: location, - messageId: "expected", - fix(fixer) { - return fixer.insertTextBeforeRange([0, 1], "\uFEFF"); - } - }); - } else if (sourceCode.hasBOM && (requireBOM === "never")) { - context.report({ - node, - loc: location, - messageId: "unexpected", - fix(fixer) { - return fixer.removeRange([-1, 0]); - } - }); - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/use-isnan.js b/tools/node_modules/eslint/lib/rules/use-isnan.js deleted file mode 100644 index 53ffeb7e6d153e7b57e5e2685baacbcdc7856bd7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/use-isnan.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @fileoverview Rule to flag comparisons to the value NaN - * @author James Allardice - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Determines if the given node is a NaN `Identifier` node. - * @param {ASTNode|null} node The node to check. - * @returns {boolean} `true` if the node is 'NaN' identifier. - */ -function isNaNIdentifier(node) { - return Boolean(node) && node.type === "Identifier" && node.name === "NaN"; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "require calls to `isNaN()` when checking for `NaN`", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/use-isnan" - }, - - schema: [ - { - type: "object", - properties: { - enforceForSwitchCase: { - type: "boolean", - default: true - }, - enforceForIndexOf: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - messages: { - comparisonWithNaN: "Use the isNaN function to compare with NaN.", - switchNaN: "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch.", - caseNaN: "'case NaN' can never match. Use Number.isNaN before the switch.", - indexOfNaN: "Array prototype method '{{ methodName }}' cannot find NaN." - } - }, - - create(context) { - - const enforceForSwitchCase = !context.options[0] || context.options[0].enforceForSwitchCase; - const enforceForIndexOf = context.options[0] && context.options[0].enforceForIndexOf; - - /** - * Checks the given `BinaryExpression` node for `foo === NaN` and other comparisons. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkBinaryExpression(node) { - if ( - /^(?:[<>]|[!=]=)=?$/u.test(node.operator) && - (isNaNIdentifier(node.left) || isNaNIdentifier(node.right)) - ) { - context.report({ node, messageId: "comparisonWithNaN" }); - } - } - - /** - * Checks the discriminant and all case clauses of the given `SwitchStatement` node for `switch(NaN)` and `case NaN:` - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkSwitchStatement(node) { - if (isNaNIdentifier(node.discriminant)) { - context.report({ node, messageId: "switchNaN" }); - } - - for (const switchCase of node.cases) { - if (isNaNIdentifier(switchCase.test)) { - context.report({ node: switchCase, messageId: "caseNaN" }); - } - } - } - - /** - * Checks the the given `CallExpression` node for `.indexOf(NaN)` and `.lastIndexOf(NaN)`. - * @param {ASTNode} node The node to check. - * @returns {void} - */ - function checkCallExpression(node) { - const callee = astUtils.skipChainExpression(node.callee); - - if (callee.type === "MemberExpression") { - const methodName = astUtils.getStaticPropertyName(callee); - - if ( - (methodName === "indexOf" || methodName === "lastIndexOf") && - node.arguments.length === 1 && - isNaNIdentifier(node.arguments[0]) - ) { - context.report({ node, messageId: "indexOfNaN", data: { methodName } }); - } - } - } - - const listeners = { - BinaryExpression: checkBinaryExpression - }; - - if (enforceForSwitchCase) { - listeners.SwitchStatement = checkSwitchStatement; - } - - if (enforceForIndexOf) { - listeners.CallExpression = checkCallExpression; - } - - return listeners; - } -}; diff --git a/tools/node_modules/eslint/lib/rules/utils/ast-utils.js b/tools/node_modules/eslint/lib/rules/utils/ast-utils.js deleted file mode 100644 index fb8beb25211ee7e8a47bad33db0aaed3d3f1445c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/ast-utils.js +++ /dev/null @@ -1,1794 +0,0 @@ -/** - * @fileoverview Common utils for AST. - * @author Gyandeep Singh - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const esutils = require("esutils"); -const espree = require("espree"); -const lodash = require("lodash"); -const { - breakableTypePattern, - createGlobalLinebreakMatcher, - lineBreakPattern, - shebangPattern -} = require("../../shared/ast-utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u; -const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u; -const arrayOrTypedArrayPattern = /Array$/u; -const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u; -const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u; -const thisTagPattern = /^[\s*]*@this/mu; - - -const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u; -const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]); - -// A set of node types that can contain a list of statements -const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "SwitchCase"]); - -const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u; -const OCTAL_ESCAPE_PATTERN = /^(?:[^\\]|\\[^0-7]|\\0(?![0-9]))*\\(?:[1-7]|0[0-9])/u; - -const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]); - -/** - * Checks reference if is non initializer and writable. - * @param {Reference} reference A reference to check. - * @param {int} index The index of the reference in the references. - * @param {Reference[]} references The array that the reference belongs to. - * @returns {boolean} Success/Failure - * @private - */ -function isModifyingReference(reference, index, references) { - const identifier = reference.identifier; - - /* - * Destructuring assignments can have multiple default value, so - * possibly there are multiple writeable references for the same - * identifier. - */ - const modifyingDifferentIdentifier = index === 0 || - references[index - 1].identifier !== identifier; - - return (identifier && - reference.init === false && - reference.isWrite() && - modifyingDifferentIdentifier - ); -} - -/** - * Checks whether the given string starts with uppercase or not. - * @param {string} s The string to check. - * @returns {boolean} `true` if the string starts with uppercase. - */ -function startsWithUpperCase(s) { - return s[0] !== s[0].toLocaleLowerCase(); -} - -/** - * Checks whether or not a node is a constructor. - * @param {ASTNode} node A function node to check. - * @returns {boolean} Wehether or not a node is a constructor. - */ -function isES5Constructor(node) { - return (node.id && startsWithUpperCase(node.id.name)); -} - -/** - * Finds a function node from ancestors of a node. - * @param {ASTNode} node A start node to find. - * @returns {Node|null} A found function node. - */ -function getUpperFunction(node) { - for (let currentNode = node; currentNode; currentNode = currentNode.parent) { - if (anyFunctionPattern.test(currentNode.type)) { - return currentNode; - } - } - return null; -} - -/** - * Checks whether a given node is a function node or not. - * The following types are function nodes: - * - * - ArrowFunctionExpression - * - FunctionDeclaration - * - FunctionExpression - * @param {ASTNode|null} node A node to check. - * @returns {boolean} `true` if the node is a function node. - */ -function isFunction(node) { - return Boolean(node && anyFunctionPattern.test(node.type)); -} - -/** - * Checks whether a given node is a loop node or not. - * The following types are loop nodes: - * - * - DoWhileStatement - * - ForInStatement - * - ForOfStatement - * - ForStatement - * - WhileStatement - * @param {ASTNode|null} node A node to check. - * @returns {boolean} `true` if the node is a loop node. - */ -function isLoop(node) { - return Boolean(node && anyLoopPattern.test(node.type)); -} - -/** - * Checks whether the given node is in a loop or not. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is in a loop. - */ -function isInLoop(node) { - for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) { - if (isLoop(currentNode)) { - return true; - } - } - - return false; -} - -/** - * Determines whether the given node is a `null` literal. - * @param {ASTNode} node The node to check - * @returns {boolean} `true` if the node is a `null` literal - */ -function isNullLiteral(node) { - - /* - * Checking `node.value === null` does not guarantee that a literal is a null literal. - * When parsing values that cannot be represented in the current environment (e.g. unicode - * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to - * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check - * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020 - */ - return node.type === "Literal" && node.value === null && !node.regex && !node.bigint; -} - -/** - * Checks whether or not a node is `null` or `undefined`. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is a `null` or `undefined`. - * @public - */ -function isNullOrUndefined(node) { - return ( - isNullLiteral(node) || - (node.type === "Identifier" && node.name === "undefined") || - (node.type === "UnaryExpression" && node.operator === "void") - ); -} - -/** - * Checks whether or not a node is callee. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is callee. - */ -function isCallee(node) { - return node.parent.type === "CallExpression" && node.parent.callee === node; -} - -/** - * Returns the result of the string conversion applied to the evaluated value of the given expression node, - * if it can be determined statically. - * - * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only. - * In all other cases, this function returns `null`. - * @param {ASTNode} node Expression node. - * @returns {string|null} String value if it can be determined. Otherwise, `null`. - */ -function getStaticStringValue(node) { - switch (node.type) { - case "Literal": - if (node.value === null) { - if (isNullLiteral(node)) { - return String(node.value); // "null" - } - if (node.regex) { - return `/${node.regex.pattern}/${node.regex.flags}`; - } - if (node.bigint) { - return node.bigint; - } - - // Otherwise, this is an unknown literal. The function will return null. - - } else { - return String(node.value); - } - break; - case "TemplateLiteral": - if (node.expressions.length === 0 && node.quasis.length === 1) { - return node.quasis[0].value.cooked; - } - break; - - // no default - } - - return null; -} - -/** - * Gets the property name of a given node. - * The node can be a MemberExpression, a Property, or a MethodDefinition. - * - * If the name is dynamic, this returns `null`. - * - * For examples: - * - * a.b // => "b" - * a["b"] // => "b" - * a['b'] // => "b" - * a[`b`] // => "b" - * a[100] // => "100" - * a[b] // => null - * a["a" + "b"] // => null - * a[tag`b`] // => null - * a[`${b}`] // => null - * - * let a = {b: 1} // => "b" - * let a = {["b"]: 1} // => "b" - * let a = {['b']: 1} // => "b" - * let a = {[`b`]: 1} // => "b" - * let a = {[100]: 1} // => "100" - * let a = {[b]: 1} // => null - * let a = {["a" + "b"]: 1} // => null - * let a = {[tag`b`]: 1} // => null - * let a = {[`${b}`]: 1} // => null - * @param {ASTNode} node The node to get. - * @returns {string|null} The property name if static. Otherwise, null. - */ -function getStaticPropertyName(node) { - let prop; - - switch (node && node.type) { - case "ChainExpression": - return getStaticPropertyName(node.expression); - - case "Property": - case "MethodDefinition": - prop = node.key; - break; - - case "MemberExpression": - prop = node.property; - break; - - // no default - } - - if (prop) { - if (prop.type === "Identifier" && !node.computed) { - return prop.name; - } - - return getStaticStringValue(prop); - } - - return null; -} - -/** - * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it. - * @param {ASTNode} node The node to address. - * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node. - */ -function skipChainExpression(node) { - return node && node.type === "ChainExpression" ? node.expression : node; -} - -/** - * Check if the `actual` is an expected value. - * @param {string} actual The string value to check. - * @param {string | RegExp} expected The expected string value or pattern. - * @returns {boolean} `true` if the `actual` is an expected value. - */ -function checkText(actual, expected) { - return typeof expected === "string" - ? actual === expected - : expected.test(actual); -} - -/** - * Check if a given node is an Identifier node with a given name. - * @param {ASTNode} node The node to check. - * @param {string | RegExp} name The expected name or the expected pattern of the object name. - * @returns {boolean} `true` if the node is an Identifier node with the name. - */ -function isSpecificId(node, name) { - return node.type === "Identifier" && checkText(node.name, name); -} - -/** - * Check if a given node is member access with a given object name and property name pair. - * This is regardless of optional or not. - * @param {ASTNode} node The node to check. - * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object. - * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property. - * @returns {boolean} `true` if the node is member access with the object name and property name pair. - * The node is a `MemberExpression` or `ChainExpression`. - */ -function isSpecificMemberAccess(node, objectName, propertyName) { - const checkNode = skipChainExpression(node); - - if (checkNode.type !== "MemberExpression") { - return false; - } - - if (objectName && !isSpecificId(checkNode.object, objectName)) { - return false; - } - - if (propertyName) { - const actualPropertyName = getStaticPropertyName(checkNode); - - if (typeof actualPropertyName !== "string" || !checkText(actualPropertyName, propertyName)) { - return false; - } - } - - return true; -} - -/** - * Check if two literal nodes are the same value. - * @param {ASTNode} left The Literal node to compare. - * @param {ASTNode} right The other Literal node to compare. - * @returns {boolean} `true` if the two literal nodes are the same value. - */ -function equalLiteralValue(left, right) { - - // RegExp literal. - if (left.regex || right.regex) { - return Boolean( - left.regex && - right.regex && - left.regex.pattern === right.regex.pattern && - left.regex.flags === right.regex.flags - ); - } - - // BigInt literal. - if (left.bigint || right.bigint) { - return left.bigint === right.bigint; - } - - return left.value === right.value; -} - -/** - * Check if two expressions reference the same value. For example: - * a = a - * a.b = a.b - * a[0] = a[0] - * a['b'] = a['b'] - * @param {ASTNode} left The left side of the comparison. - * @param {ASTNode} right The right side of the comparison. - * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility. - * @returns {boolean} `true` if both sides match and reference the same value. - */ -function isSameReference(left, right, disableStaticComputedKey = false) { - if (left.type !== right.type) { - - // Handle `a.b` and `a?.b` are samely. - if (left.type === "ChainExpression") { - return isSameReference(left.expression, right, disableStaticComputedKey); - } - if (right.type === "ChainExpression") { - return isSameReference(left, right.expression, disableStaticComputedKey); - } - - return false; - } - - switch (left.type) { - case "Super": - case "ThisExpression": - return true; - - case "Identifier": - return left.name === right.name; - case "Literal": - return equalLiteralValue(left, right); - - case "ChainExpression": - return isSameReference(left.expression, right.expression, disableStaticComputedKey); - - case "MemberExpression": { - if (!disableStaticComputedKey) { - const nameA = getStaticPropertyName(left); - - // x.y = x["y"] - if (nameA !== null) { - return ( - isSameReference(left.object, right.object, disableStaticComputedKey) && - nameA === getStaticPropertyName(right) - ); - } - } - - /* - * x[0] = x[0] - * x[y] = x[y] - * x.y = x.y - */ - return ( - left.computed === right.computed && - isSameReference(left.object, right.object, disableStaticComputedKey) && - isSameReference(left.property, right.property, disableStaticComputedKey) - ); - } - - default: - return false; - } -} - -/** - * Checks whether or not a node is `Reflect.apply`. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is a `Reflect.apply`. - */ -function isReflectApply(node) { - return isSpecificMemberAccess(node, "Reflect", "apply"); -} - -/** - * Checks whether or not a node is `Array.from`. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is a `Array.from`. - */ -function isArrayFromMethod(node) { - return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from"); -} - -/** - * Checks whether or not a node is a method which has `thisArg`. - * @param {ASTNode} node A node to check. - * @returns {boolean} Whether or not the node is a method which has `thisArg`. - */ -function isMethodWhichHasThisArg(node) { - return isSpecificMemberAccess(node, null, arrayMethodPattern); -} - -/** - * Creates the negate function of the given function. - * @param {Function} f The function to negate. - * @returns {Function} Negated function. - */ -function negate(f) { - return token => !f(token); -} - -/** - * Checks whether or not a node has a `@this` tag in its comments. - * @param {ASTNode} node A node to check. - * @param {SourceCode} sourceCode A SourceCode instance to get comments. - * @returns {boolean} Whether or not the node has a `@this` tag in its comments. - */ -function hasJSDocThisTag(node, sourceCode) { - const jsdocComment = sourceCode.getJSDocComment(node); - - if (jsdocComment && thisTagPattern.test(jsdocComment.value)) { - return true; - } - - // Checks `@this` in its leading comments for callbacks, - // because callbacks don't have its JSDoc comment. - // e.g. - // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); }); - return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value)); -} - -/** - * Determines if a node is surrounded by parentheses. - * @param {SourceCode} sourceCode The ESLint source code object - * @param {ASTNode} node The node to be checked. - * @returns {boolean} True if the node is parenthesised. - * @private - */ -function isParenthesised(sourceCode, node) { - const previousToken = sourceCode.getTokenBefore(node), - nextToken = sourceCode.getTokenAfter(node); - - return Boolean(previousToken && nextToken) && - previousToken.value === "(" && previousToken.range[1] <= node.range[0] && - nextToken.value === ")" && nextToken.range[0] >= node.range[1]; -} - -/** - * Checks if the given token is an arrow token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is an arrow token. - */ -function isArrowToken(token) { - return token.value === "=>" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a comma token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a comma token. - */ -function isCommaToken(token) { - return token.value === "," && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a dot token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a dot token. - */ -function isDotToken(token) { - return token.value === "." && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a `?.` token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a `?.` token. - */ -function isQuestionDotToken(token) { - return token.value === "?." && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a semicolon token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a semicolon token. - */ -function isSemicolonToken(token) { - return token.value === ";" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a colon token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a colon token. - */ -function isColonToken(token) { - return token.value === ":" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is an opening parenthesis token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is an opening parenthesis token. - */ -function isOpeningParenToken(token) { - return token.value === "(" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a closing parenthesis token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a closing parenthesis token. - */ -function isClosingParenToken(token) { - return token.value === ")" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is an opening square bracket token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is an opening square bracket token. - */ -function isOpeningBracketToken(token) { - return token.value === "[" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a closing square bracket token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a closing square bracket token. - */ -function isClosingBracketToken(token) { - return token.value === "]" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is an opening brace token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is an opening brace token. - */ -function isOpeningBraceToken(token) { - return token.value === "{" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a closing brace token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a closing brace token. - */ -function isClosingBraceToken(token) { - return token.value === "}" && token.type === "Punctuator"; -} - -/** - * Checks if the given token is a comment token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a comment token. - */ -function isCommentToken(token) { - return token.type === "Line" || token.type === "Block" || token.type === "Shebang"; -} - -/** - * Checks if the given token is a keyword token or not. - * @param {Token} token The token to check. - * @returns {boolean} `true` if the token is a keyword token. - */ -function isKeywordToken(token) { - return token.type === "Keyword"; -} - -/** - * Gets the `(` token of the given function node. - * @param {ASTNode} node The function node to get. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {Token} `(` token. - */ -function getOpeningParenOfParams(node, sourceCode) { - return node.id - ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) - : sourceCode.getFirstToken(node, isOpeningParenToken); -} - -/** - * Checks whether or not the tokens of two given nodes are same. - * @param {ASTNode} left A node 1 to compare. - * @param {ASTNode} right A node 2 to compare. - * @param {SourceCode} sourceCode The ESLint source code object. - * @returns {boolean} the source code for the given node. - */ -function equalTokens(left, right, sourceCode) { - const tokensL = sourceCode.getTokens(left); - const tokensR = sourceCode.getTokens(right); - - if (tokensL.length !== tokensR.length) { - return false; - } - for (let i = 0; i < tokensL.length; ++i) { - if (tokensL[i].type !== tokensR[i].type || - tokensL[i].value !== tokensR[i].value - ) { - return false; - } - } - - return true; -} - -/** - * Check if the given node is a true logical expression or not. - * - * The three binary expressions logical-or (`||`), logical-and (`&&`), and - * coalesce (`??`) are known as `ShortCircuitExpression`. - * But ESTree represents those by `LogicalExpression` node. - * - * This function rejects coalesce expressions of `LogicalExpression` node. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is `&&` or `||`. - * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression - */ -function isLogicalExpression(node) { - return ( - node.type === "LogicalExpression" && - (node.operator === "&&" || node.operator === "||") - ); -} - -/** - * Check if the given node is a nullish coalescing expression or not. - * - * The three binary expressions logical-or (`||`), logical-and (`&&`), and - * coalesce (`??`) are known as `ShortCircuitExpression`. - * But ESTree represents those by `LogicalExpression` node. - * - * This function finds only coalesce expressions of `LogicalExpression` node. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is `??`. - */ -function isCoalesceExpression(node) { - return node.type === "LogicalExpression" && node.operator === "??"; -} - -/** - * Check if given two nodes are the pair of a logical expression and a coalesce expression. - * @param {ASTNode} left A node to check. - * @param {ASTNode} right Another node to check. - * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression. - */ -function isMixedLogicalAndCoalesceExpressions(left, right) { - return ( - (isLogicalExpression(left) && isCoalesceExpression(right)) || - (isCoalesceExpression(left) && isLogicalExpression(right)) - ); -} - -/** - * Checks if the given operator is a logical assignment operator. - * @param {string} operator The operator to check. - * @returns {boolean} `true` if the operator is a logical assignment operator. - */ -function isLogicalAssignmentOperator(operator) { - return LOGICAL_ASSIGNMENT_OPERATORS.has(operator); -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - COMMENTS_IGNORE_PATTERN, - LINEBREAKS, - LINEBREAK_MATCHER: lineBreakPattern, - SHEBANG_MATCHER: shebangPattern, - STATEMENT_LIST_PARENTS, - - /** - * Determines whether two adjacent tokens are on the same line. - * @param {Object} left The left token object. - * @param {Object} right The right token object. - * @returns {boolean} Whether or not the tokens are on the same line. - * @public - */ - isTokenOnSameLine(left, right) { - return left.loc.end.line === right.loc.start.line; - }, - - isNullOrUndefined, - isCallee, - isES5Constructor, - getUpperFunction, - isFunction, - isLoop, - isInLoop, - isArrayFromMethod, - isParenthesised, - createGlobalLinebreakMatcher, - equalTokens, - - isArrowToken, - isClosingBraceToken, - isClosingBracketToken, - isClosingParenToken, - isColonToken, - isCommaToken, - isCommentToken, - isDotToken, - isQuestionDotToken, - isKeywordToken, - isNotClosingBraceToken: negate(isClosingBraceToken), - isNotClosingBracketToken: negate(isClosingBracketToken), - isNotClosingParenToken: negate(isClosingParenToken), - isNotColonToken: negate(isColonToken), - isNotCommaToken: negate(isCommaToken), - isNotDotToken: negate(isDotToken), - isNotQuestionDotToken: negate(isQuestionDotToken), - isNotOpeningBraceToken: negate(isOpeningBraceToken), - isNotOpeningBracketToken: negate(isOpeningBracketToken), - isNotOpeningParenToken: negate(isOpeningParenToken), - isNotSemicolonToken: negate(isSemicolonToken), - isOpeningBraceToken, - isOpeningBracketToken, - isOpeningParenToken, - isSemicolonToken, - - /** - * Checks whether or not a given node is a string literal. - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is a string literal. - */ - isStringLiteral(node) { - return ( - (node.type === "Literal" && typeof node.value === "string") || - node.type === "TemplateLiteral" - ); - }, - - /** - * Checks whether a given node is a breakable statement or not. - * The node is breakable if the node is one of the following type: - * - * - DoWhileStatement - * - ForInStatement - * - ForOfStatement - * - ForStatement - * - SwitchStatement - * - WhileStatement - * @param {ASTNode} node A node to check. - * @returns {boolean} `true` if the node is breakable. - */ - isBreakableStatement(node) { - return breakableTypePattern.test(node.type); - }, - - /** - * Gets references which are non initializer and writable. - * @param {Reference[]} references An array of references. - * @returns {Reference[]} An array of only references which are non initializer and writable. - * @public - */ - getModifyingReferences(references) { - return references.filter(isModifyingReference); - }, - - /** - * Validate that a string passed in is surrounded by the specified character - * @param {string} val The text to check. - * @param {string} character The character to see if it's surrounded by. - * @returns {boolean} True if the text is surrounded by the character, false if not. - * @private - */ - isSurroundedBy(val, character) { - return val[0] === character && val[val.length - 1] === character; - }, - - /** - * Returns whether the provided node is an ESLint directive comment or not - * @param {Line|Block} node The comment token to be checked - * @returns {boolean} `true` if the node is an ESLint directive comment - */ - isDirectiveComment(node) { - const comment = node.value.trim(); - - return ( - node.type === "Line" && comment.indexOf("eslint-") === 0 || - node.type === "Block" && ( - comment.indexOf("global ") === 0 || - comment.indexOf("eslint ") === 0 || - comment.indexOf("eslint-") === 0 - ) - ); - }, - - /** - * Gets the trailing statement of a given node. - * - * if (code) - * consequent; - * - * When taking this `IfStatement`, returns `consequent;` statement. - * @param {ASTNode} A node to get. - * @returns {ASTNode|null} The trailing statement's node. - */ - getTrailingStatement: esutils.ast.trailingStatement, - - /** - * Finds the variable by a given name in a given scope and its upper scopes. - * @param {eslint-scope.Scope} initScope A scope to start find. - * @param {string} name A variable name to find. - * @returns {eslint-scope.Variable|null} A found variable or `null`. - */ - getVariableByName(initScope, name) { - let scope = initScope; - - while (scope) { - const variable = scope.set.get(name); - - if (variable) { - return variable; - } - - scope = scope.upper; - } - - return null; - }, - - /** - * Checks whether or not a given function node is the default `this` binding. - * - * First, this checks the node: - * - * - The function name does not start with uppercase. It's a convention to capitalize the names - * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`. - * - The function does not have a JSDoc comment that has a @this tag. - * - * Next, this checks the location of the node. - * If the location is below, this judges `this` is valid. - * - * - The location is not on an object literal. - * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous - * functions only, as the name of the variable is considered to be the name of the function in this case. - * This check is not performed if `capIsConstructor` is set to `false`. - * - The location is not on an ES2015 class. - * - Its `bind`/`call`/`apply` method is not called directly. - * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given. - * @param {ASTNode} node A function node to check. - * @param {SourceCode} sourceCode A SourceCode instance to get comments. - * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts - * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors. - * @returns {boolean} The function node is the default `this` binding. - */ - isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) { - if ( - (capIsConstructor && isES5Constructor(node)) || - hasJSDocThisTag(node, sourceCode) - ) { - return false; - } - const isAnonymous = node.id === null; - let currentNode = node; - - while (currentNode) { - const parent = currentNode.parent; - - switch (parent.type) { - - /* - * Looks up the destination. - * e.g., obj.foo = nativeFoo || function foo() { ... }; - */ - case "LogicalExpression": - case "ConditionalExpression": - case "ChainExpression": - currentNode = parent; - break; - - /* - * If the upper function is IIFE, checks the destination of the return value. - * e.g. - * obj.foo = (function() { - * // setup... - * return function foo() { ... }; - * })(); - * obj.foo = (() => - * function foo() { ... } - * )(); - */ - case "ReturnStatement": { - const func = getUpperFunction(parent); - - if (func === null || !isCallee(func)) { - return true; - } - currentNode = func.parent; - break; - } - case "ArrowFunctionExpression": - if (currentNode !== parent.body || !isCallee(parent)) { - return true; - } - currentNode = parent.parent; - break; - - /* - * e.g. - * var obj = { foo() { ... } }; - * var obj = { foo: function() { ... } }; - * class A { constructor() { ... } } - * class A { foo() { ... } } - * class A { get foo() { ... } } - * class A { set foo() { ... } } - * class A { static foo() { ... } } - */ - case "Property": - case "MethodDefinition": - return parent.value !== currentNode; - - /* - * e.g. - * obj.foo = function foo() { ... }; - * Foo = function() { ... }; - * [obj.foo = function foo() { ... }] = a; - * [Foo = function() { ... }] = a; - */ - case "AssignmentExpression": - case "AssignmentPattern": - if (parent.left.type === "MemberExpression") { - return false; - } - if ( - capIsConstructor && - isAnonymous && - parent.left.type === "Identifier" && - startsWithUpperCase(parent.left.name) - ) { - return false; - } - return true; - - /* - * e.g. - * var Foo = function() { ... }; - */ - case "VariableDeclarator": - return !( - capIsConstructor && - isAnonymous && - parent.init === currentNode && - parent.id.type === "Identifier" && - startsWithUpperCase(parent.id.name) - ); - - /* - * e.g. - * var foo = function foo() { ... }.bind(obj); - * (function foo() { ... }).call(obj); - * (function foo() { ... }).apply(obj, []); - */ - case "MemberExpression": - if ( - parent.object === currentNode && - isSpecificMemberAccess(parent, null, bindOrCallOrApplyPattern) - ) { - const maybeCalleeNode = parent.parent.type === "ChainExpression" - ? parent.parent - : parent; - - return !( - isCallee(maybeCalleeNode) && - maybeCalleeNode.parent.arguments.length >= 1 && - !isNullOrUndefined(maybeCalleeNode.parent.arguments[0]) - ); - } - return true; - - /* - * e.g. - * Reflect.apply(function() {}, obj, []); - * Array.from([], function() {}, obj); - * list.forEach(function() {}, obj); - */ - case "CallExpression": - if (isReflectApply(parent.callee)) { - return ( - parent.arguments.length !== 3 || - parent.arguments[0] !== currentNode || - isNullOrUndefined(parent.arguments[1]) - ); - } - if (isArrayFromMethod(parent.callee)) { - return ( - parent.arguments.length !== 3 || - parent.arguments[1] !== currentNode || - isNullOrUndefined(parent.arguments[2]) - ); - } - if (isMethodWhichHasThisArg(parent.callee)) { - return ( - parent.arguments.length !== 2 || - parent.arguments[0] !== currentNode || - isNullOrUndefined(parent.arguments[1]) - ); - } - return true; - - // Otherwise `this` is default. - default: - return true; - } - } - - /* istanbul ignore next */ - return true; - }, - - /** - * Get the precedence level based on the node type - * @param {ASTNode} node node to evaluate - * @returns {int} precedence level - * @private - */ - getPrecedence(node) { - switch (node.type) { - case "SequenceExpression": - return 0; - - case "AssignmentExpression": - case "ArrowFunctionExpression": - case "YieldExpression": - return 1; - - case "ConditionalExpression": - return 3; - - case "LogicalExpression": - switch (node.operator) { - case "||": - case "??": - return 4; - case "&&": - return 5; - - // no default - } - - /* falls through */ - - case "BinaryExpression": - - switch (node.operator) { - case "|": - return 6; - case "^": - return 7; - case "&": - return 8; - case "==": - case "!=": - case "===": - case "!==": - return 9; - case "<": - case "<=": - case ">": - case ">=": - case "in": - case "instanceof": - return 10; - case "<<": - case ">>": - case ">>>": - return 11; - case "+": - case "-": - return 12; - case "*": - case "/": - case "%": - return 13; - case "**": - return 15; - - // no default - } - - /* falls through */ - - case "UnaryExpression": - case "AwaitExpression": - return 16; - - case "UpdateExpression": - return 17; - - case "CallExpression": - case "ChainExpression": - case "ImportExpression": - return 18; - - case "NewExpression": - return 19; - - default: - return 20; - } - }, - - /** - * Checks whether the given node is an empty block node or not. - * @param {ASTNode|null} node The node to check. - * @returns {boolean} `true` if the node is an empty block. - */ - isEmptyBlock(node) { - return Boolean(node && node.type === "BlockStatement" && node.body.length === 0); - }, - - /** - * Checks whether the given node is an empty function node or not. - * @param {ASTNode|null} node The node to check. - * @returns {boolean} `true` if the node is an empty function. - */ - isEmptyFunction(node) { - return isFunction(node) && module.exports.isEmptyBlock(node.body); - }, - - /** - * Get directives from directive prologue of a Program or Function node. - * @param {ASTNode} node The node to check. - * @returns {ASTNode[]} The directives found in the directive prologue. - */ - getDirectivePrologue(node) { - const directives = []; - - // Directive prologues only occur at the top of files or functions. - if ( - node.type === "Program" || - node.type === "FunctionDeclaration" || - node.type === "FunctionExpression" || - - /* - * Do not check arrow functions with implicit return. - * `() => "use strict";` returns the string `"use strict"`. - */ - (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement") - ) { - const statements = node.type === "Program" ? node.body : node.body.body; - - for (const statement of statements) { - if ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" - ) { - directives.push(statement); - } else { - break; - } - } - } - - return directives; - }, - - - /** - * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added - * after the node will be parsed as a decimal point, rather than a property-access dot. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if this node is a decimal integer. - * @example - * - * 0 // true - * 5 // true - * 50 // true - * 5_000 // true - * 1_234_56 // true - * 08 // true - * 0192 // true - * 5. // false - * .5 // false - * 5.0 // false - * 5.00_00 // false - * 05 // false - * 0x5 // false - * 0b101 // false - * 0b11_01 // false - * 0o5 // false - * 5e0 // false - * 5e1_000 // false - * 5n // false - * 1_000n // false - * '5' // false - */ - isDecimalInteger(node) { - return node.type === "Literal" && typeof node.value === "number" && - DECIMAL_INTEGER_PATTERN.test(node.raw); - }, - - /** - * Determines whether this token is a decimal integer numeric token. - * This is similar to isDecimalInteger(), but for tokens. - * @param {Token} token The token to check. - * @returns {boolean} `true` if this token is a decimal integer. - */ - isDecimalIntegerNumericToken(token) { - return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value); - }, - - /** - * Gets the name and kind of the given function node. - * - * - `function foo() {}` .................... `function 'foo'` - * - `(function foo() {})` .................. `function 'foo'` - * - `(function() {})` ...................... `function` - * - `function* foo() {}` ................... `generator function 'foo'` - * - `(function* foo() {})` ................. `generator function 'foo'` - * - `(function*() {})` ..................... `generator function` - * - `() => {}` ............................. `arrow function` - * - `async () => {}` ....................... `async arrow function` - * - `({ foo: function foo() {} })` ......... `method 'foo'` - * - `({ foo: function() {} })` ............. `method 'foo'` - * - `({ ['foo']: function() {} })` ......... `method 'foo'` - * - `({ [foo]: function() {} })` ........... `method` - * - `({ foo() {} })` ....................... `method 'foo'` - * - `({ foo: function* foo() {} })` ........ `generator method 'foo'` - * - `({ foo: function*() {} })` ............ `generator method 'foo'` - * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'` - * - `({ [foo]: function*() {} })` .......... `generator method` - * - `({ *foo() {} })` ...................... `generator method 'foo'` - * - `({ foo: async function foo() {} })` ... `async method 'foo'` - * - `({ foo: async function() {} })` ....... `async method 'foo'` - * - `({ ['foo']: async function() {} })` ... `async method 'foo'` - * - `({ [foo]: async function() {} })` ..... `async method` - * - `({ async foo() {} })` ................. `async method 'foo'` - * - `({ get foo() {} })` ................... `getter 'foo'` - * - `({ set foo(a) {} })` .................. `setter 'foo'` - * - `class A { constructor() {} }` ......... `constructor` - * - `class A { foo() {} }` ................. `method 'foo'` - * - `class A { *foo() {} }` ................ `generator method 'foo'` - * - `class A { async foo() {} }` ........... `async method 'foo'` - * - `class A { ['foo']() {} }` ............. `method 'foo'` - * - `class A { *['foo']() {} }` ............ `generator method 'foo'` - * - `class A { async ['foo']() {} }` ....... `async method 'foo'` - * - `class A { [foo]() {} }` ............... `method` - * - `class A { *[foo]() {} }` .............. `generator method` - * - `class A { async [foo]() {} }` ......... `async method` - * - `class A { get foo() {} }` ............. `getter 'foo'` - * - `class A { set foo(a) {} }` ............ `setter 'foo'` - * - `class A { static foo() {} }` .......... `static method 'foo'` - * - `class A { static *foo() {} }` ......... `static generator method 'foo'` - * - `class A { static async foo() {} }` .... `static async method 'foo'` - * - `class A { static get foo() {} }` ...... `static getter 'foo'` - * - `class A { static set foo(a) {} }` ..... `static setter 'foo'` - * @param {ASTNode} node The function node to get. - * @returns {string} The name and kind of the function node. - */ - getFunctionNameWithKind(node) { - const parent = node.parent; - const tokens = []; - - if (parent.type === "MethodDefinition" && parent.static) { - tokens.push("static"); - } - if (node.async) { - tokens.push("async"); - } - if (node.generator) { - tokens.push("generator"); - } - - if (node.type === "ArrowFunctionExpression") { - tokens.push("arrow", "function"); - } else if (parent.type === "Property" || parent.type === "MethodDefinition") { - if (parent.kind === "constructor") { - return "constructor"; - } - if (parent.kind === "get") { - tokens.push("getter"); - } else if (parent.kind === "set") { - tokens.push("setter"); - } else { - tokens.push("method"); - } - } else { - tokens.push("function"); - } - - if (node.id) { - tokens.push(`'${node.id.name}'`); - } else { - const name = getStaticPropertyName(parent); - - if (name !== null) { - tokens.push(`'${name}'`); - } - } - - return tokens.join(" "); - }, - - /** - * Gets the location of the given function node for reporting. - * - * - `function foo() {}` - * ^^^^^^^^^^^^ - * - `(function foo() {})` - * ^^^^^^^^^^^^ - * - `(function() {})` - * ^^^^^^^^ - * - `function* foo() {}` - * ^^^^^^^^^^^^^ - * - `(function* foo() {})` - * ^^^^^^^^^^^^^ - * - `(function*() {})` - * ^^^^^^^^^ - * - `() => {}` - * ^^ - * - `async () => {}` - * ^^ - * - `({ foo: function foo() {} })` - * ^^^^^^^^^^^^^^^^^ - * - `({ foo: function() {} })` - * ^^^^^^^^^^^^^ - * - `({ ['foo']: function() {} })` - * ^^^^^^^^^^^^^^^^^ - * - `({ [foo]: function() {} })` - * ^^^^^^^^^^^^^^^ - * - `({ foo() {} })` - * ^^^ - * - `({ foo: function* foo() {} })` - * ^^^^^^^^^^^^^^^^^^ - * - `({ foo: function*() {} })` - * ^^^^^^^^^^^^^^ - * - `({ ['foo']: function*() {} })` - * ^^^^^^^^^^^^^^^^^^ - * - `({ [foo]: function*() {} })` - * ^^^^^^^^^^^^^^^^ - * - `({ *foo() {} })` - * ^^^^ - * - `({ foo: async function foo() {} })` - * ^^^^^^^^^^^^^^^^^^^^^^^ - * - `({ foo: async function() {} })` - * ^^^^^^^^^^^^^^^^^^^ - * - `({ ['foo']: async function() {} })` - * ^^^^^^^^^^^^^^^^^^^^^^^ - * - `({ [foo]: async function() {} })` - * ^^^^^^^^^^^^^^^^^^^^^ - * - `({ async foo() {} })` - * ^^^^^^^^^ - * - `({ get foo() {} })` - * ^^^^^^^ - * - `({ set foo(a) {} })` - * ^^^^^^^ - * - `class A { constructor() {} }` - * ^^^^^^^^^^^ - * - `class A { foo() {} }` - * ^^^ - * - `class A { *foo() {} }` - * ^^^^ - * - `class A { async foo() {} }` - * ^^^^^^^^^ - * - `class A { ['foo']() {} }` - * ^^^^^^^ - * - `class A { *['foo']() {} }` - * ^^^^^^^^ - * - `class A { async ['foo']() {} }` - * ^^^^^^^^^^^^^ - * - `class A { [foo]() {} }` - * ^^^^^ - * - `class A { *[foo]() {} }` - * ^^^^^^ - * - `class A { async [foo]() {} }` - * ^^^^^^^^^^^ - * - `class A { get foo() {} }` - * ^^^^^^^ - * - `class A { set foo(a) {} }` - * ^^^^^^^ - * - `class A { static foo() {} }` - * ^^^^^^^^^^ - * - `class A { static *foo() {} }` - * ^^^^^^^^^^^ - * - `class A { static async foo() {} }` - * ^^^^^^^^^^^^^^^^ - * - `class A { static get foo() {} }` - * ^^^^^^^^^^^^^^ - * - `class A { static set foo(a) {} }` - * ^^^^^^^^^^^^^^ - * @param {ASTNode} node The function node to get. - * @param {SourceCode} sourceCode The source code object to get tokens. - * @returns {string} The location of the function node for reporting. - */ - getFunctionHeadLoc(node, sourceCode) { - const parent = node.parent; - let start = null; - let end = null; - - if (node.type === "ArrowFunctionExpression") { - const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken); - - start = arrowToken.loc.start; - end = arrowToken.loc.end; - } else if (parent.type === "Property" || parent.type === "MethodDefinition") { - start = parent.loc.start; - end = getOpeningParenOfParams(node, sourceCode).loc.start; - } else { - start = node.loc.start; - end = getOpeningParenOfParams(node, sourceCode).loc.start; - } - - return { - start: Object.assign({}, start), - end: Object.assign({}, end) - }; - }, - - /** - * Gets next location when the result is not out of bound, otherwise returns null. - * - * Assumptions: - * - * - The given location represents a valid location in the given source code. - * - Columns are 0-based. - * - Lines are 1-based. - * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location. - * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end. - * The start (column 0) of that extra line is considered to be a valid location. - * - * Examples of successive locations (line, column): - * - * code: foo - * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null - * - * code: foo - * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null - * - * code: foo - * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null - * - * code: ab - * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null - * - * code: ab - * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null - * - * code: ab - * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null - * - * code: a - * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null - * - * code: - * locations: (1, 0) -> (2, 0) -> null - * - * code: - * locations: (1, 0) -> null - * @param {SourceCode} sourceCode The sourceCode - * @param {{line: number, column: number}} location The location - * @returns {{line: number, column: number} | null} Next location - */ - getNextLocation(sourceCode, { line, column }) { - if (column < sourceCode.lines[line - 1].length) { - return { - line, - column: column + 1 - }; - } - - if (line < sourceCode.lines.length) { - return { - line: line + 1, - column: 0 - }; - } - - return null; - }, - - /** - * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses - * surrounding the node. - * @param {SourceCode} sourceCode The source code object - * @param {ASTNode} node An expression node - * @returns {string} The text representing the node, with all surrounding parentheses included - */ - getParenthesisedText(sourceCode, node) { - let leftToken = sourceCode.getFirstToken(node); - let rightToken = sourceCode.getLastToken(node); - - while ( - sourceCode.getTokenBefore(leftToken) && - sourceCode.getTokenBefore(leftToken).type === "Punctuator" && - sourceCode.getTokenBefore(leftToken).value === "(" && - sourceCode.getTokenAfter(rightToken) && - sourceCode.getTokenAfter(rightToken).type === "Punctuator" && - sourceCode.getTokenAfter(rightToken).value === ")" - ) { - leftToken = sourceCode.getTokenBefore(leftToken); - rightToken = sourceCode.getTokenAfter(rightToken); - } - - return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]); - }, - - /* - * Determine if a node has a possiblity to be an Error object - * @param {ASTNode} node ASTNode to check - * @returns {boolean} True if there is a chance it contains an Error obj - */ - couldBeError(node) { - switch (node.type) { - case "Identifier": - case "CallExpression": - case "NewExpression": - case "MemberExpression": - case "TaggedTemplateExpression": - case "YieldExpression": - case "AwaitExpression": - case "ChainExpression": - return true; // possibly an error object. - - case "AssignmentExpression": - if (["=", "&&="].includes(node.operator)) { - return module.exports.couldBeError(node.right); - } - - if (["||=", "??="].includes(node.operator)) { - return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right); - } - - /** - * All other assignment operators are mathematical assignment operators (arithmetic or bitwise). - * An assignment expression with a mathematical operator can either evaluate to a primitive value, - * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object. - */ - return false; - - case "SequenceExpression": { - const exprs = node.expressions; - - return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]); - } - - case "LogicalExpression": - return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right); - - case "ConditionalExpression": - return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate); - - default: - return false; - } - }, - - /** - * Check if a given node is a numeric literal or not. - * @param {ASTNode} node The node to check. - * @returns {boolean} `true` if the node is a number or bigint literal. - */ - isNumericLiteral(node) { - return ( - node.type === "Literal" && - (typeof node.value === "number" || Boolean(node.bigint)) - ); - }, - - /** - * Determines whether two tokens can safely be placed next to each other without merging into a single token - * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used. - * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used. - * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed - * next to each other, behavior is undefined (although it should return `true` in most cases). - */ - canTokensBeAdjacent(leftValue, rightValue) { - const espreeOptions = { - ecmaVersion: espree.latestEcmaVersion, - comment: true, - range: true - }; - - let leftToken; - - if (typeof leftValue === "string") { - let tokens; - - try { - tokens = espree.tokenize(leftValue, espreeOptions); - } catch { - return false; - } - - const comments = tokens.comments; - - leftToken = tokens[tokens.length - 1]; - if (comments.length) { - const lastComment = comments[comments.length - 1]; - - if (lastComment.range[0] > leftToken.range[0]) { - leftToken = lastComment; - } - } - } else { - leftToken = leftValue; - } - - if (leftToken.type === "Shebang") { - return false; - } - - let rightToken; - - if (typeof rightValue === "string") { - let tokens; - - try { - tokens = espree.tokenize(rightValue, espreeOptions); - } catch { - return false; - } - - const comments = tokens.comments; - - rightToken = tokens[0]; - if (comments.length) { - const firstComment = comments[0]; - - if (firstComment.range[0] < rightToken.range[0]) { - rightToken = firstComment; - } - } - } else { - rightToken = rightValue; - } - - if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") { - if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") { - const PLUS_TOKENS = new Set(["+", "++"]); - const MINUS_TOKENS = new Set(["-", "--"]); - - return !( - PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) || - MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value) - ); - } - if (leftToken.type === "Punctuator" && leftToken.value === "/") { - return !["Block", "Line", "RegularExpression"].includes(rightToken.type); - } - return true; - } - - if ( - leftToken.type === "String" || rightToken.type === "String" || - leftToken.type === "Template" || rightToken.type === "Template" - ) { - return true; - } - - if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) { - return true; - } - - if (leftToken.type === "Block" || rightToken.type === "Block" || rightToken.type === "Line") { - return true; - } - - return false; - }, - - /** - * Get the `loc` object of a given name in a `/*globals` directive comment. - * @param {SourceCode} sourceCode The source code to convert index to loc. - * @param {Comment} comment The `/*globals` directive comment which include the name. - * @param {string} name The name to find. - * @returns {SourceLocation} The `loc` object. - */ - getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) { - const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(name)}(?:$|[\\s,:])`, "gu"); - - // To ignore the first text "global". - namePattern.lastIndex = comment.value.indexOf("global") + 6; - - // Search a given variable name. - const match = namePattern.exec(comment.value); - - // Convert the index to loc. - const start = sourceCode.getLocFromIndex( - comment.range[0] + - "/*".length + - (match ? match.index + 1 : 0) - ); - const end = { - line: start.line, - column: start.column + (match ? name.length : 1) - }; - - return { start, end }; - }, - - /** - * Determines whether the given raw string contains an octal escape sequence. - * - * "\1", "\2" ... "\7" - * "\00", "\01" ... "\09" - * - * "\0", when not followed by a digit, is not an octal escape sequence. - * @param {string} rawString A string in its raw representation. - * @returns {boolean} `true` if the string contains at least one octal escape sequence. - */ - hasOctalEscapeSequence(rawString) { - return OCTAL_ESCAPE_PATTERN.test(rawString); - }, - - isLogicalExpression, - isCoalesceExpression, - isMixedLogicalAndCoalesceExpressions, - isNullLiteral, - getStaticStringValue, - getStaticPropertyName, - skipChainExpression, - isSpecificId, - isSpecificMemberAccess, - equalLiteralValue, - isSameReference, - isLogicalAssignmentOperator -}; diff --git a/tools/node_modules/eslint/lib/rules/utils/fix-tracker.js b/tools/node_modules/eslint/lib/rules/utils/fix-tracker.js deleted file mode 100644 index 589870b39b52154d3bf97a2310303fa7185e70eb..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/fix-tracker.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @fileoverview Helper class to aid in constructing fix commands. - * @author Alan Pierce - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./ast-utils"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -/** - * A helper class to combine fix options into a fix command. Currently, it - * exposes some "retain" methods that extend the range of the text being - * replaced so that other fixes won't touch that region in the same pass. - */ -class FixTracker { - - /** - * Create a new FixTracker. - * @param {ruleFixer} fixer A ruleFixer instance. - * @param {SourceCode} sourceCode A SourceCode object for the current code. - */ - constructor(fixer, sourceCode) { - this.fixer = fixer; - this.sourceCode = sourceCode; - this.retainedRange = null; - } - - /** - * Mark the given range as "retained", meaning that other fixes may not - * may not modify this region in the same pass. - * @param {int[]} range The range to retain. - * @returns {FixTracker} The same RuleFixer, for chained calls. - */ - retainRange(range) { - this.retainedRange = range; - return this; - } - - /** - * Given a node, find the function containing it (or the entire program) and - * mark it as retained, meaning that other fixes may not modify it in this - * pass. This is useful for avoiding conflicts in fixes that modify control - * flow. - * @param {ASTNode} node The node to use as a starting point. - * @returns {FixTracker} The same RuleFixer, for chained calls. - */ - retainEnclosingFunction(node) { - const functionNode = astUtils.getUpperFunction(node); - - return this.retainRange(functionNode ? functionNode.range : this.sourceCode.ast.range); - } - - /** - * Given a node or token, find the token before and afterward, and mark that - * range as retained, meaning that other fixes may not modify it in this - * pass. This is useful for avoiding conflicts in fixes that make a small - * change to the code where the AST should not be changed. - * @param {ASTNode|Token} nodeOrToken The node or token to use as a starting - * point. The token to the left and right are use in the range. - * @returns {FixTracker} The same RuleFixer, for chained calls. - */ - retainSurroundingTokens(nodeOrToken) { - const tokenBefore = this.sourceCode.getTokenBefore(nodeOrToken) || nodeOrToken; - const tokenAfter = this.sourceCode.getTokenAfter(nodeOrToken) || nodeOrToken; - - return this.retainRange([tokenBefore.range[0], tokenAfter.range[1]]); - } - - /** - * Create a fix command that replaces the given range with the given text, - * accounting for any retained ranges. - * @param {int[]} range The range to remove in the fix. - * @param {string} text The text to insert in place of the range. - * @returns {Object} The fix command. - */ - replaceTextRange(range, text) { - let actualRange; - - if (this.retainedRange) { - actualRange = [ - Math.min(this.retainedRange[0], range[0]), - Math.max(this.retainedRange[1], range[1]) - ]; - } else { - actualRange = range; - } - - return this.fixer.replaceTextRange( - actualRange, - this.sourceCode.text.slice(actualRange[0], range[0]) + - text + - this.sourceCode.text.slice(range[1], actualRange[1]) - ); - } - - /** - * Create a fix command that removes the given node or token, accounting for - * any retained ranges. - * @param {ASTNode|Token} nodeOrToken The node or token to remove. - * @returns {Object} The fix command. - */ - remove(nodeOrToken) { - return this.replaceTextRange(nodeOrToken.range, ""); - } -} - -module.exports = FixTracker; diff --git a/tools/node_modules/eslint/lib/rules/utils/keywords.js b/tools/node_modules/eslint/lib/rules/utils/keywords.js deleted file mode 100644 index 3fbb77771df5c91aa91cecd426d6947a2d3f4c6f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/keywords.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @fileoverview A shared list of ES3 keywords. - * @author Josh Perez - */ -"use strict"; - -module.exports = [ - "abstract", - "boolean", - "break", - "byte", - "case", - "catch", - "char", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "double", - "else", - "enum", - "export", - "extends", - "false", - "final", - "finally", - "float", - "for", - "function", - "goto", - "if", - "implements", - "import", - "in", - "instanceof", - "int", - "interface", - "long", - "native", - "new", - "null", - "package", - "private", - "protected", - "public", - "return", - "short", - "static", - "super", - "switch", - "synchronized", - "this", - "throw", - "throws", - "transient", - "true", - "try", - "typeof", - "var", - "void", - "volatile", - "while", - "with" -]; diff --git a/tools/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js b/tools/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js deleted file mode 100644 index d426d85c59a7b385c0b7163d2e5c38c57fb0bc48..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/lazy-loading-rule-map.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @fileoverview `Map` to load rules lazily. - * @author Toru Nagashima - */ -"use strict"; - -const debug = require("debug")("eslint:rules"); - -/** @typedef {import("./types").Rule} Rule */ - -/** - * The `Map` object that loads each rule when it's accessed. - * @example - * const rules = new LazyLoadingRuleMap([ - * ["eqeqeq", () => require("eqeqeq")], - * ["semi", () => require("semi")], - * ["no-unused-vars", () => require("no-unused-vars")], - * ]) - * - * rules.get("semi") // call `() => require("semi")` here. - * - * @extends {Map Rule>} - */ -class LazyLoadingRuleMap extends Map { - - /** - * Initialize this map. - * @param {Array<[string, function(): Rule]>} loaders The rule loaders. - */ - constructor(loaders) { - let remaining = loaders.length; - - super( - debug.enabled - ? loaders.map(([ruleId, load]) => { - let cache = null; - - return [ - ruleId, - () => { - if (!cache) { - debug("Loading rule %o (remaining=%d)", ruleId, --remaining); - cache = load(); - } - return cache; - } - ]; - }) - : loaders - ); - - // `super(...iterable)` uses `this.set()`, so disable it here. - Object.defineProperty(LazyLoadingRuleMap.prototype, "set", { - configurable: true, - value: void 0 - }); - } - - /** - * Get a rule. - * Each rule will be loaded on the first access. - * @param {string} ruleId The rule ID to get. - * @returns {Rule|undefined} The rule. - */ - get(ruleId) { - const load = super.get(ruleId); - - return load && load(); - } - - /** - * Iterate rules. - * @returns {IterableIterator} Rules. - */ - *values() { - for (const load of super.values()) { - yield load(); - } - } - - /** - * Iterate rules. - * @returns {IterableIterator<[string, Rule]>} Rules. - */ - *entries() { - for (const [ruleId, load] of super.entries()) { - yield [ruleId, load()]; - } - } - - /** - * Call a function with each rule. - * @param {Function} callbackFn The callback function. - * @param {any} [thisArg] The object to pass to `this` of the callback function. - * @returns {void} - */ - forEach(callbackFn, thisArg) { - for (const [ruleId, load] of super.entries()) { - callbackFn.call(thisArg, load(), ruleId, this); - } - } -} - -// Forbid mutation. -Object.defineProperties(LazyLoadingRuleMap.prototype, { - clear: { configurable: true, value: void 0 }, - delete: { configurable: true, value: void 0 }, - [Symbol.iterator]: { - configurable: true, - writable: true, - value: LazyLoadingRuleMap.prototype.entries - } -}); - -module.exports = { LazyLoadingRuleMap }; diff --git a/tools/node_modules/eslint/lib/rules/utils/patterns/letters.js b/tools/node_modules/eslint/lib/rules/utils/patterns/letters.js deleted file mode 100644 index 9bb2de31010db5501448448b15e3bc9f7ef11abc..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/patterns/letters.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @fileoverview Pattern for detecting any letter (even letters outside of ASCII). - * NOTE: This file was generated using this script in JSCS based on the Unicode 7.0.0 standard: https://github.com/jscs-dev/node-jscs/blob/f5ed14427deb7e7aac84f3056a5aab2d9f3e563e/publish/helpers/generate-patterns.js - * Do not edit this file by hand-- please use https://github.com/mathiasbynens/regenerate to regenerate the regular expression exported from this file. - * @author Kevin Partington - * @license MIT License (from JSCS). See below. - */ - -/* - * The MIT License (MIT) - * - * Copyright 2013-2016 Dulin Marat and other contributors - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -"use strict"; - -module.exports = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/u; diff --git a/tools/node_modules/eslint/lib/rules/utils/unicode/index.js b/tools/node_modules/eslint/lib/rules/utils/unicode/index.js deleted file mode 100644 index 02eea502dfe6691a199e5ff645c52cfeb2261950..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/unicode/index.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -module.exports = { - isCombiningCharacter: require("./is-combining-character"), - isEmojiModifier: require("./is-emoji-modifier"), - isRegionalIndicatorSymbol: require("./is-regional-indicator-symbol"), - isSurrogatePair: require("./is-surrogate-pair") -}; diff --git a/tools/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js deleted file mode 100644 index 0498b99a21ed45630a1c762fff5dc559f0ba6616..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/unicode/is-combining-character.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether a given character is a combining mark or not. - * @param {number} codePoint The character code to check. - * @returns {boolean} `true` if the character belongs to the category, any of `Mc`, `Me`, and `Mn`. - */ -module.exports = function isCombiningCharacter(codePoint) { - return /^[\p{Mc}\p{Me}\p{Mn}]$/u.test(String.fromCodePoint(codePoint)); -}; diff --git a/tools/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js deleted file mode 100644 index 1bd5f557dcc4ab311481486746c99579240004f0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/unicode/is-emoji-modifier.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether a given character is an emoji modifier. - * @param {number} code The character code to check. - * @returns {boolean} `true` if the character is an emoji modifier. - */ -module.exports = function isEmojiModifier(code) { - return code >= 0x1F3FB && code <= 0x1F3FF; -}; diff --git a/tools/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js deleted file mode 100644 index c48ed46ef8fded27d051f7d52a392576b851feed..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/unicode/is-regional-indicator-symbol.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether a given character is a regional indicator symbol. - * @param {number} code The character code to check. - * @returns {boolean} `true` if the character is a regional indicator symbol. - */ -module.exports = function isRegionalIndicatorSymbol(code) { - return code >= 0x1F1E6 && code <= 0x1F1FF; -}; diff --git a/tools/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js b/tools/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js deleted file mode 100644 index b8e5c1cacdb6a9f81ef2151e79612fd0690dc405..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/utils/unicode/is-surrogate-pair.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * @author Toru Nagashima - */ -"use strict"; - -/** - * Check whether given two characters are a surrogate pair. - * @param {number} lead The code of the lead character. - * @param {number} tail The code of the tail character. - * @returns {boolean} `true` if the character pair is a surrogate pair. - */ -module.exports = function isSurrogatePair(lead, tail) { - return lead >= 0xD800 && lead < 0xDC00 && tail >= 0xDC00 && tail < 0xE000; -}; diff --git a/tools/node_modules/eslint/lib/rules/valid-jsdoc.js b/tools/node_modules/eslint/lib/rules/valid-jsdoc.js deleted file mode 100644 index 9ec6938e35af7d3a85b1429f1bd4738f2d86fa5b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/valid-jsdoc.js +++ /dev/null @@ -1,515 +0,0 @@ -/** - * @fileoverview Validates JSDoc comments are syntactically correct - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const doctrine = require("doctrine"); - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "enforce valid JSDoc comments", - category: "Possible Errors", - recommended: false, - url: "https://eslint.org/docs/rules/valid-jsdoc" - }, - - schema: [ - { - type: "object", - properties: { - prefer: { - type: "object", - additionalProperties: { - type: "string" - } - }, - preferType: { - type: "object", - additionalProperties: { - type: "string" - } - }, - requireReturn: { - type: "boolean", - default: true - }, - requireParamDescription: { - type: "boolean", - default: true - }, - requireReturnDescription: { - type: "boolean", - default: true - }, - matchDescription: { - type: "string" - }, - requireReturnType: { - type: "boolean", - default: true - }, - requireParamType: { - type: "boolean", - default: true - } - }, - additionalProperties: false - } - ], - - fixable: "code", - messages: { - unexpectedTag: "Unexpected @{{title}} tag; function has no return statement.", - expected: "Expected JSDoc for '{{name}}' but found '{{jsdocName}}'.", - use: "Use @{{name}} instead.", - useType: "Use '{{expectedTypeName}}' instead of '{{currentTypeName}}'.", - syntaxError: "JSDoc syntax error.", - missingBrace: "JSDoc type missing brace.", - missingParamDesc: "Missing JSDoc parameter description for '{{name}}'.", - missingParamType: "Missing JSDoc parameter type for '{{name}}'.", - missingReturnType: "Missing JSDoc return type.", - missingReturnDesc: "Missing JSDoc return description.", - missingReturn: "Missing JSDoc @{{returns}} for function.", - missingParam: "Missing JSDoc for parameter '{{name}}'.", - duplicateParam: "Duplicate JSDoc parameter '{{name}}'.", - unsatisfiedDesc: "JSDoc description does not satisfy the regex pattern." - }, - - deprecated: true, - replacedBy: [] - }, - - create(context) { - - const options = context.options[0] || {}, - prefer = options.prefer || {}, - sourceCode = context.getSourceCode(), - - // these both default to true, so you have to explicitly make them false - requireReturn = options.requireReturn !== false, - requireParamDescription = options.requireParamDescription !== false, - requireReturnDescription = options.requireReturnDescription !== false, - requireReturnType = options.requireReturnType !== false, - requireParamType = options.requireParamType !== false, - preferType = options.preferType || {}, - checkPreferType = Object.keys(preferType).length !== 0; - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // Using a stack to store if a function returns or not (handling nested functions) - const fns = []; - - /** - * Check if node type is a Class - * @param {ASTNode} node node to check. - * @returns {boolean} True is its a class - * @private - */ - function isTypeClass(node) { - return node.type === "ClassExpression" || node.type === "ClassDeclaration"; - } - - /** - * When parsing a new function, store it in our function stack. - * @param {ASTNode} node A function node to check. - * @returns {void} - * @private - */ - function startFunction(node) { - fns.push({ - returnPresent: (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") || - isTypeClass(node) || node.async - }); - } - - /** - * Indicate that return has been found in the current function. - * @param {ASTNode} node The return node. - * @returns {void} - * @private - */ - function addReturn(node) { - const functionState = fns[fns.length - 1]; - - if (functionState && node.argument !== null) { - functionState.returnPresent = true; - } - } - - /** - * Check if return tag type is void or undefined - * @param {Object} tag JSDoc tag - * @returns {boolean} True if its of type void or undefined - * @private - */ - function isValidReturnType(tag) { - return tag.type === null || tag.type.name === "void" || tag.type.type === "UndefinedLiteral"; - } - - /** - * Check if type should be validated based on some exceptions - * @param {Object} type JSDoc tag - * @returns {boolean} True if it can be validated - * @private - */ - function canTypeBeValidated(type) { - return type !== "UndefinedLiteral" && // {undefined} as there is no name property available. - type !== "NullLiteral" && // {null} - type !== "NullableLiteral" && // {?} - type !== "FunctionType" && // {function(a)} - type !== "AllLiteral"; // {*} - } - - /** - * Extract the current and expected type based on the input type object - * @param {Object} type JSDoc tag - * @returns {{currentType: Doctrine.Type, expectedTypeName: string}} The current type annotation and - * the expected name of the annotation - * @private - */ - function getCurrentExpectedTypes(type) { - let currentType; - - if (type.name) { - currentType = type; - } else if (type.expression) { - currentType = type.expression; - } - - return { - currentType, - expectedTypeName: currentType && preferType[currentType.name] - }; - } - - /** - * Gets the location of a JSDoc node in a file - * @param {Token} jsdocComment The comment that this node is parsed from - * @param {{range: number[]}} parsedJsdocNode A tag or other node which was parsed from this comment - * @returns {{start: SourceLocation, end: SourceLocation}} The 0-based source location for the tag - */ - function getAbsoluteRange(jsdocComment, parsedJsdocNode) { - return { - start: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[0]), - end: sourceCode.getLocFromIndex(jsdocComment.range[0] + 2 + parsedJsdocNode.range[1]) - }; - } - - /** - * Validate type for a given JSDoc node - * @param {Object} jsdocNode JSDoc node - * @param {Object} type JSDoc tag - * @returns {void} - * @private - */ - function validateType(jsdocNode, type) { - if (!type || !canTypeBeValidated(type.type)) { - return; - } - - const typesToCheck = []; - let elements = []; - - switch (type.type) { - case "TypeApplication": // {Array.} - elements = type.applications[0].type === "UnionType" ? type.applications[0].elements : type.applications; - typesToCheck.push(getCurrentExpectedTypes(type)); - break; - case "RecordType": // {{20:String}} - elements = type.fields; - break; - case "UnionType": // {String|number|Test} - case "ArrayType": // {[String, number, Test]} - elements = type.elements; - break; - case "FieldType": // Array.<{count: number, votes: number}> - if (type.value) { - typesToCheck.push(getCurrentExpectedTypes(type.value)); - } - break; - default: - typesToCheck.push(getCurrentExpectedTypes(type)); - } - - elements.forEach(validateType.bind(null, jsdocNode)); - - typesToCheck.forEach(typeToCheck => { - if (typeToCheck.expectedTypeName && - typeToCheck.expectedTypeName !== typeToCheck.currentType.name) { - context.report({ - node: jsdocNode, - messageId: "useType", - loc: getAbsoluteRange(jsdocNode, typeToCheck.currentType), - data: { - currentTypeName: typeToCheck.currentType.name, - expectedTypeName: typeToCheck.expectedTypeName - }, - fix(fixer) { - return fixer.replaceTextRange( - typeToCheck.currentType.range.map(indexInComment => jsdocNode.range[0] + 2 + indexInComment), - typeToCheck.expectedTypeName - ); - } - }); - } - }); - } - - /** - * Validate the JSDoc node and output warnings if anything is wrong. - * @param {ASTNode} node The AST node to check. - * @returns {void} - * @private - */ - function checkJSDoc(node) { - const jsdocNode = sourceCode.getJSDocComment(node), - functionData = fns.pop(), - paramTagsByName = Object.create(null), - paramTags = []; - let hasReturns = false, - returnsTag, - hasConstructor = false, - isInterface = false, - isOverride = false, - isAbstract = false; - - // make sure only to validate JSDoc comments - if (jsdocNode) { - let jsdoc; - - try { - jsdoc = doctrine.parse(jsdocNode.value, { - strict: true, - unwrap: true, - sloppy: true, - range: true - }); - } catch (ex) { - - if (/braces/iu.test(ex.message)) { - context.report({ node: jsdocNode, messageId: "missingBrace" }); - } else { - context.report({ node: jsdocNode, messageId: "syntaxError" }); - } - - return; - } - - jsdoc.tags.forEach(tag => { - - switch (tag.title.toLowerCase()) { - - case "param": - case "arg": - case "argument": - paramTags.push(tag); - break; - - case "return": - case "returns": - hasReturns = true; - returnsTag = tag; - break; - - case "constructor": - case "class": - hasConstructor = true; - break; - - case "override": - case "inheritdoc": - isOverride = true; - break; - - case "abstract": - case "virtual": - isAbstract = true; - break; - - case "interface": - isInterface = true; - break; - - // no default - } - - // check tag preferences - if (Object.prototype.hasOwnProperty.call(prefer, tag.title) && tag.title !== prefer[tag.title]) { - const entireTagRange = getAbsoluteRange(jsdocNode, tag); - - context.report({ - node: jsdocNode, - messageId: "use", - loc: { - start: entireTagRange.start, - end: { - line: entireTagRange.start.line, - column: entireTagRange.start.column + `@${tag.title}`.length - } - }, - data: { name: prefer[tag.title] }, - fix(fixer) { - return fixer.replaceTextRange( - [ - jsdocNode.range[0] + tag.range[0] + 3, - jsdocNode.range[0] + tag.range[0] + tag.title.length + 3 - ], - prefer[tag.title] - ); - } - }); - } - - // validate the types - if (checkPreferType && tag.type) { - validateType(jsdocNode, tag.type); - } - }); - - paramTags.forEach(param => { - if (requireParamType && !param.type) { - context.report({ - node: jsdocNode, - messageId: "missingParamType", - loc: getAbsoluteRange(jsdocNode, param), - data: { name: param.name } - }); - } - if (!param.description && requireParamDescription) { - context.report({ - node: jsdocNode, - messageId: "missingParamDesc", - loc: getAbsoluteRange(jsdocNode, param), - data: { name: param.name } - }); - } - if (paramTagsByName[param.name]) { - context.report({ - node: jsdocNode, - messageId: "duplicateParam", - loc: getAbsoluteRange(jsdocNode, param), - data: { name: param.name } - }); - } else if (param.name.indexOf(".") === -1) { - paramTagsByName[param.name] = param; - } - }); - - if (hasReturns) { - if (!requireReturn && !functionData.returnPresent && (returnsTag.type === null || !isValidReturnType(returnsTag)) && !isAbstract) { - context.report({ - node: jsdocNode, - messageId: "unexpectedTag", - loc: getAbsoluteRange(jsdocNode, returnsTag), - data: { - title: returnsTag.title - } - }); - } else { - if (requireReturnType && !returnsTag.type) { - context.report({ node: jsdocNode, messageId: "missingReturnType" }); - } - - if (!isValidReturnType(returnsTag) && !returnsTag.description && requireReturnDescription) { - context.report({ node: jsdocNode, messageId: "missingReturnDesc" }); - } - } - } - - // check for functions missing @returns - if (!isOverride && !hasReturns && !hasConstructor && !isInterface && - node.parent.kind !== "get" && node.parent.kind !== "constructor" && - node.parent.kind !== "set" && !isTypeClass(node)) { - if (requireReturn || (functionData.returnPresent && !node.async)) { - context.report({ - node: jsdocNode, - messageId: "missingReturn", - data: { - returns: prefer.returns || "returns" - } - }); - } - } - - // check the parameters - const jsdocParamNames = Object.keys(paramTagsByName); - - if (node.params) { - node.params.forEach((param, paramsIndex) => { - const bindingParam = param.type === "AssignmentPattern" - ? param.left - : param; - - // TODO(nzakas): Figure out logical things to do with destructured, default, rest params - if (bindingParam.type === "Identifier") { - const name = bindingParam.name; - - if (jsdocParamNames[paramsIndex] && (name !== jsdocParamNames[paramsIndex])) { - context.report({ - node: jsdocNode, - messageId: "expected", - loc: getAbsoluteRange(jsdocNode, paramTagsByName[jsdocParamNames[paramsIndex]]), - data: { - name, - jsdocName: jsdocParamNames[paramsIndex] - } - }); - } else if (!paramTagsByName[name] && !isOverride) { - context.report({ - node: jsdocNode, - messageId: "missingParam", - data: { - name - } - }); - } - } - }); - } - - if (options.matchDescription) { - const regex = new RegExp(options.matchDescription, "u"); - - if (!regex.test(jsdoc.description)) { - context.report({ node: jsdocNode, messageId: "unsatisfiedDesc" }); - } - } - - } - - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - ArrowFunctionExpression: startFunction, - FunctionExpression: startFunction, - FunctionDeclaration: startFunction, - ClassExpression: startFunction, - ClassDeclaration: startFunction, - "ArrowFunctionExpression:exit": checkJSDoc, - "FunctionExpression:exit": checkJSDoc, - "FunctionDeclaration:exit": checkJSDoc, - "ClassExpression:exit": checkJSDoc, - "ClassDeclaration:exit": checkJSDoc, - ReturnStatement: addReturn - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/valid-typeof.js b/tools/node_modules/eslint/lib/rules/valid-typeof.js deleted file mode 100644 index a0f20f74d0ec6149815214d9a6f3d69a7e036172..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/valid-typeof.js +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @fileoverview Ensures that the results of typeof are compared against a valid string - * @author Ian Christian Myers - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "problem", - - docs: { - description: "enforce comparing `typeof` expressions against valid strings", - category: "Possible Errors", - recommended: true, - url: "https://eslint.org/docs/rules/valid-typeof" - }, - - schema: [ - { - type: "object", - properties: { - requireStringLiterals: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - messages: { - invalidValue: "Invalid typeof comparison value.", - notString: "Typeof comparisons should be to string literals." - } - }, - - create(context) { - - const VALID_TYPES = ["symbol", "undefined", "object", "boolean", "number", "string", "function", "bigint"], - OPERATORS = ["==", "===", "!=", "!=="]; - - const requireStringLiterals = context.options[0] && context.options[0].requireStringLiterals; - - /** - * Determines whether a node is a typeof expression. - * @param {ASTNode} node The node - * @returns {boolean} `true` if the node is a typeof expression - */ - function isTypeofExpression(node) { - return node.type === "UnaryExpression" && node.operator === "typeof"; - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - - UnaryExpression(node) { - if (isTypeofExpression(node)) { - const parent = context.getAncestors().pop(); - - if (parent.type === "BinaryExpression" && OPERATORS.indexOf(parent.operator) !== -1) { - const sibling = parent.left === node ? parent.right : parent.left; - - if (sibling.type === "Literal" || sibling.type === "TemplateLiteral" && !sibling.expressions.length) { - const value = sibling.type === "Literal" ? sibling.value : sibling.quasis[0].value.cooked; - - if (VALID_TYPES.indexOf(value) === -1) { - context.report({ node: sibling, messageId: "invalidValue" }); - } - } else if (requireStringLiterals && !isTypeofExpression(sibling)) { - context.report({ node: sibling, messageId: "notString" }); - } - } - } - } - - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/vars-on-top.js b/tools/node_modules/eslint/lib/rules/vars-on-top.js deleted file mode 100644 index 28ddae442b517a43f66a709dfa9d8e104c6db70f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/vars-on-top.js +++ /dev/null @@ -1,144 +0,0 @@ -/** - * @fileoverview Rule to enforce var declarations are only at the top of a function. - * @author Danny Fritz - * @author Gyandeep Singh - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: "require `var` declarations be placed at the top of their containing scope", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/vars-on-top" - }, - - schema: [], - messages: { - top: "All 'var' declarations must be at the top of the function scope." - } - }, - - create(context) { - - //-------------------------------------------------------------------------- - // Helpers - //-------------------------------------------------------------------------- - - // eslint-disable-next-line jsdoc/require-description - /** - * @param {ASTNode} node any node - * @returns {boolean} whether the given node structurally represents a directive - */ - function looksLikeDirective(node) { - return node.type === "ExpressionStatement" && - node.expression.type === "Literal" && typeof node.expression.value === "string"; - } - - /** - * Check to see if its a ES6 import declaration - * @param {ASTNode} node any node - * @returns {boolean} whether the given node represents a import declaration - */ - function looksLikeImport(node) { - return node.type === "ImportDeclaration" || node.type === "ImportSpecifier" || - node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier"; - } - - /** - * Checks whether a given node is a variable declaration or not. - * @param {ASTNode} node any node - * @returns {boolean} `true` if the node is a variable declaration. - */ - function isVariableDeclaration(node) { - return ( - node.type === "VariableDeclaration" || - ( - node.type === "ExportNamedDeclaration" && - node.declaration && - node.declaration.type === "VariableDeclaration" - ) - ); - } - - /** - * Checks whether this variable is on top of the block body - * @param {ASTNode} node The node to check - * @param {ASTNode[]} statements collection of ASTNodes for the parent node block - * @returns {boolean} True if var is on top otherwise false - */ - function isVarOnTop(node, statements) { - const l = statements.length; - let i = 0; - - // skip over directives - for (; i < l; ++i) { - if (!looksLikeDirective(statements[i]) && !looksLikeImport(statements[i])) { - break; - } - } - - for (; i < l; ++i) { - if (!isVariableDeclaration(statements[i])) { - return false; - } - if (statements[i] === node) { - return true; - } - } - - return false; - } - - /** - * Checks whether variable is on top at the global level - * @param {ASTNode} node The node to check - * @param {ASTNode} parent Parent of the node - * @returns {void} - */ - function globalVarCheck(node, parent) { - if (!isVarOnTop(node, parent.body)) { - context.report({ node, messageId: "top" }); - } - } - - /** - * Checks whether variable is on top at functional block scope level - * @param {ASTNode} node The node to check - * @param {ASTNode} parent Parent of the node - * @param {ASTNode} grandParent Parent of the node's parent - * @returns {void} - */ - function blockScopeVarCheck(node, parent, grandParent) { - if (!(/Function/u.test(grandParent.type) && - parent.type === "BlockStatement" && - isVarOnTop(node, parent.body))) { - context.report({ node, messageId: "top" }); - } - } - - //-------------------------------------------------------------------------- - // Public API - //-------------------------------------------------------------------------- - - return { - "VariableDeclaration[kind='var']"(node) { - if (node.parent.type === "ExportNamedDeclaration") { - globalVarCheck(node.parent, node.parent.parent); - } else if (node.parent.type === "Program") { - globalVarCheck(node, node.parent); - } else { - blockScopeVarCheck(node, node.parent, node.parent.parent); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/wrap-iife.js b/tools/node_modules/eslint/lib/rules/wrap-iife.js deleted file mode 100644 index 07e5b84a4a5ae45873152b4b34fe5ccae31dd9d0..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/wrap-iife.js +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @fileoverview Rule to flag when IIFE is not wrapped in parens - * @author Ilya Volodin - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const astUtils = require("./utils/ast-utils"); -const eslintUtils = require("eslint-utils"); - -//---------------------------------------------------------------------- -// Helpers -//---------------------------------------------------------------------- - -/** - * Check if the given node is callee of a `NewExpression` node - * @param {ASTNode} node node to check - * @returns {boolean} True if the node is callee of a `NewExpression` node - * @private - */ -function isCalleeOfNewExpression(node) { - const maybeCallee = node.parent.type === "ChainExpression" - ? node.parent - : node; - - return ( - maybeCallee.parent.type === "NewExpression" && - maybeCallee.parent.callee === maybeCallee - ); -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parentheses around immediate `function` invocations", - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/wrap-iife" - }, - - schema: [ - { - enum: ["outside", "inside", "any"] - }, - { - type: "object", - properties: { - functionPrototypeMethods: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code", - messages: { - wrapInvocation: "Wrap an immediate function invocation in parentheses.", - wrapExpression: "Wrap only the function expression in parens.", - moveInvocation: "Move the invocation into the parens that contain the function." - } - }, - - create(context) { - - const style = context.options[0] || "outside"; - const includeFunctionPrototypeMethods = context.options[1] && context.options[1].functionPrototypeMethods; - - const sourceCode = context.getSourceCode(); - - /** - * Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if() - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if it is wrapped in any parens - * @private - */ - function isWrappedInAnyParens(node) { - return astUtils.isParenthesised(sourceCode, node); - } - - /** - * Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count - * @param {ASTNode} node node to evaluate - * @returns {boolean} True if it is wrapped in grouping parens - * @private - */ - function isWrappedInGroupingParens(node) { - return eslintUtils.isParenthesized(1, node, sourceCode); - } - - /** - * Get the function node from an IIFE - * @param {ASTNode} node node to evaluate - * @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist - */ - function getFunctionNodeFromIIFE(node) { - const callee = astUtils.skipChainExpression(node.callee); - - if (callee.type === "FunctionExpression") { - return callee; - } - - if (includeFunctionPrototypeMethods && - callee.type === "MemberExpression" && - callee.object.type === "FunctionExpression" && - (astUtils.getStaticPropertyName(callee) === "call" || astUtils.getStaticPropertyName(callee) === "apply") - ) { - return callee.object; - } - - return null; - } - - - return { - CallExpression(node) { - const innerNode = getFunctionNodeFromIIFE(node); - - if (!innerNode) { - return; - } - - const isCallExpressionWrapped = isWrappedInAnyParens(node), - isFunctionExpressionWrapped = isWrappedInAnyParens(innerNode); - - if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) { - context.report({ - node, - messageId: "wrapInvocation", - fix(fixer) { - const nodeToSurround = style === "inside" ? innerNode : node; - - return fixer.replaceText(nodeToSurround, `(${sourceCode.getText(nodeToSurround)})`); - } - }); - } else if (style === "inside" && !isFunctionExpressionWrapped) { - context.report({ - node, - messageId: "wrapExpression", - fix(fixer) { - - // The outer call expression will always be wrapped at this point. - - if (isWrappedInGroupingParens(node) && !isCalleeOfNewExpression(node)) { - - /* - * Parenthesize the function expression and remove unnecessary grouping parens around the call expression. - * Replace the range between the end of the function expression and the end of the call expression. - * for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`. - */ - - const parenAfter = sourceCode.getTokenAfter(node); - - return fixer.replaceTextRange( - [innerNode.range[1], parenAfter.range[1]], - `)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}` - ); - } - - /* - * Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens. - * These parens cannot be removed, so just parenthesize the function expression. - */ - - return fixer.replaceText(innerNode, `(${sourceCode.getText(innerNode)})`); - } - }); - } else if (style === "outside" && !isCallExpressionWrapped) { - context.report({ - node, - messageId: "moveInvocation", - fix(fixer) { - - /* - * The inner function expression will always be wrapped at this point. - * It's only necessary to replace the range between the end of the function expression - * and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)` - * should get replaced with `(bar))`. - */ - const parenAfter = sourceCode.getTokenAfter(innerNode); - - return fixer.replaceTextRange( - [parenAfter.range[0], node.range[1]], - `${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})` - ); - } - }); - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/wrap-regex.js b/tools/node_modules/eslint/lib/rules/wrap-regex.js deleted file mode 100644 index 4ecbcecbbeb0b394b787a5772de935702dc5f3c8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/wrap-regex.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @fileoverview Rule to flag when regex literals are not wrapped in parens - * @author Matt DuVall - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require parenthesis around regex literals", - category: "Stylistic Issues", - recommended: false, - url: "https://eslint.org/docs/rules/wrap-regex" - }, - - schema: [], - fixable: "code", - - messages: { - requireParens: "Wrap the regexp literal in parens to disambiguate the slash." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - return { - - Literal(node) { - const token = sourceCode.getFirstToken(node), - nodeType = token.type; - - if (nodeType === "RegularExpression") { - const beforeToken = sourceCode.getTokenBefore(node); - const afterToken = sourceCode.getTokenAfter(node); - const ancestors = context.getAncestors(); - const grandparent = ancestors[ancestors.length - 1]; - - if (grandparent.type === "MemberExpression" && grandparent.object === node && - !(beforeToken && beforeToken.value === "(" && afterToken && afterToken.value === ")")) { - context.report({ - node, - messageId: "requireParens", - fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`) - }); - } - } - } - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/yield-star-spacing.js b/tools/node_modules/eslint/lib/rules/yield-star-spacing.js deleted file mode 100644 index 20b8e9ea91eb2ec27f9ae2a60cf5c9303eed3387..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/yield-star-spacing.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * @fileoverview Rule to check the spacing around the * in yield* expressions. - * @author Bryan Smith - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "layout", - - docs: { - description: "require or disallow spacing around the `*` in `yield*` expressions", - category: "ECMAScript 6", - recommended: false, - url: "https://eslint.org/docs/rules/yield-star-spacing" - }, - - fixable: "whitespace", - - schema: [ - { - oneOf: [ - { - enum: ["before", "after", "both", "neither"] - }, - { - type: "object", - properties: { - before: { type: "boolean" }, - after: { type: "boolean" } - }, - additionalProperties: false - } - ] - } - ], - messages: { - missingBefore: "Missing space before *.", - missingAfter: "Missing space after *.", - unexpectedBefore: "Unexpected space before *.", - unexpectedAfter: "Unexpected space after *." - } - }, - - create(context) { - const sourceCode = context.getSourceCode(); - - const mode = (function(option) { - if (!option || typeof option === "string") { - return { - before: { before: true, after: false }, - after: { before: false, after: true }, - both: { before: true, after: true }, - neither: { before: false, after: false } - }[option || "after"]; - } - return option; - }(context.options[0])); - - /** - * Checks the spacing between two tokens before or after the star token. - * @param {string} side Either "before" or "after". - * @param {Token} leftToken `function` keyword token if side is "before", or - * star token if side is "after". - * @param {Token} rightToken Star token if side is "before", or identifier - * token if side is "after". - * @returns {void} - */ - function checkSpacing(side, leftToken, rightToken) { - if (sourceCode.isSpaceBetweenTokens(leftToken, rightToken) !== mode[side]) { - const after = leftToken.value === "*"; - const spaceRequired = mode[side]; - const node = after ? leftToken : rightToken; - let messageId = ""; - - if (spaceRequired) { - messageId = side === "before" ? "missingBefore" : "missingAfter"; - } else { - messageId = side === "before" ? "unexpectedBefore" : "unexpectedAfter"; - } - - context.report({ - node, - messageId, - fix(fixer) { - if (spaceRequired) { - if (after) { - return fixer.insertTextAfter(node, " "); - } - return fixer.insertTextBefore(node, " "); - } - return fixer.removeRange([leftToken.range[1], rightToken.range[0]]); - } - }); - } - } - - /** - * Enforces the spacing around the star if node is a yield* expression. - * @param {ASTNode} node A yield expression node. - * @returns {void} - */ - function checkExpression(node) { - if (!node.delegate) { - return; - } - - const tokens = sourceCode.getFirstTokens(node, 3); - const yieldToken = tokens[0]; - const starToken = tokens[1]; - const nextToken = tokens[2]; - - checkSpacing("before", yieldToken, starToken); - checkSpacing("after", starToken, nextToken); - } - - return { - YieldExpression: checkExpression - }; - - } -}; diff --git a/tools/node_modules/eslint/lib/rules/yoda.js b/tools/node_modules/eslint/lib/rules/yoda.js deleted file mode 100644 index 87dd5ed6c5736d0d675b16a996607c9e210f8ff7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/rules/yoda.js +++ /dev/null @@ -1,352 +0,0 @@ -/** - * @fileoverview Rule to require or disallow yoda comparisons - * @author Nicholas C. Zakas - */ -"use strict"; - -//-------------------------------------------------------------------------- -// Requirements -//-------------------------------------------------------------------------- - -const astUtils = require("./utils/ast-utils"); - -//-------------------------------------------------------------------------- -// Helpers -//-------------------------------------------------------------------------- - -/** - * Determines whether an operator is a comparison operator. - * @param {string} operator The operator to check. - * @returns {boolean} Whether or not it is a comparison operator. - */ -function isComparisonOperator(operator) { - return /^(==|===|!=|!==|<|>|<=|>=)$/u.test(operator); -} - -/** - * Determines whether an operator is an equality operator. - * @param {string} operator The operator to check. - * @returns {boolean} Whether or not it is an equality operator. - */ -function isEqualityOperator(operator) { - return /^(==|===)$/u.test(operator); -} - -/** - * Determines whether an operator is one used in a range test. - * Allowed operators are `<` and `<=`. - * @param {string} operator The operator to check. - * @returns {boolean} Whether the operator is used in range tests. - */ -function isRangeTestOperator(operator) { - return ["<", "<="].indexOf(operator) >= 0; -} - -/** - * Determines whether a non-Literal node is a negative number that should be - * treated as if it were a single Literal node. - * @param {ASTNode} node Node to test. - * @returns {boolean} True if the node is a negative number that looks like a - * real literal and should be treated as such. - */ -function isNegativeNumericLiteral(node) { - return ( - node.type === "UnaryExpression" && - node.operator === "-" && - node.prefix && - astUtils.isNumericLiteral(node.argument) - ); -} - -/** - * Determines whether a node is a Template Literal which can be determined statically. - * @param {ASTNode} node Node to test - * @returns {boolean} True if the node is a Template Literal without expression. - */ -function isStaticTemplateLiteral(node) { - return node.type === "TemplateLiteral" && node.expressions.length === 0; -} - -/** - * Determines whether a non-Literal node should be treated as a single Literal node. - * @param {ASTNode} node Node to test - * @returns {boolean} True if the node should be treated as a single Literal node. - */ -function looksLikeLiteral(node) { - return isNegativeNumericLiteral(node) || isStaticTemplateLiteral(node); -} - -/** - * Attempts to derive a Literal node from nodes that are treated like literals. - * @param {ASTNode} node Node to normalize. - * @returns {ASTNode} One of the following options. - * 1. The original node if the node is already a Literal - * 2. A normalized Literal node with the negative number as the value if the - * node represents a negative number literal. - * 3. A normalized Literal node with the string as the value if the node is - * a Template Literal without expression. - * 4. Otherwise `null`. - */ -function getNormalizedLiteral(node) { - if (node.type === "Literal") { - return node; - } - - if (isNegativeNumericLiteral(node)) { - return { - type: "Literal", - value: -node.argument.value, - raw: `-${node.argument.value}` - }; - } - - if (isStaticTemplateLiteral(node)) { - return { - type: "Literal", - value: node.quasis[0].value.cooked, - raw: node.quasis[0].value.raw - }; - } - - return null; -} - -//------------------------------------------------------------------------------ -// Rule Definition -//------------------------------------------------------------------------------ - -module.exports = { - meta: { - type: "suggestion", - - docs: { - description: 'require or disallow "Yoda" conditions', - category: "Best Practices", - recommended: false, - url: "https://eslint.org/docs/rules/yoda" - }, - - schema: [ - { - enum: ["always", "never"] - }, - { - type: "object", - properties: { - exceptRange: { - type: "boolean", - default: false - }, - onlyEquality: { - type: "boolean", - default: false - } - }, - additionalProperties: false - } - ], - - fixable: "code", - messages: { - expected: - "Expected literal to be on the {{expectedSide}} side of {{operator}}." - } - }, - - create(context) { - - // Default to "never" (!always) if no option - const always = context.options[0] === "always"; - const exceptRange = - context.options[1] && context.options[1].exceptRange; - const onlyEquality = - context.options[1] && context.options[1].onlyEquality; - - const sourceCode = context.getSourceCode(); - - /** - * Determines whether node represents a range test. - * A range test is a "between" test like `(0 <= x && x < 1)` or an "outside" - * test like `(x < 0 || 1 <= x)`. It must be wrapped in parentheses, and - * both operators must be `<` or `<=`. Finally, the literal on the left side - * must be less than or equal to the literal on the right side so that the - * test makes any sense. - * @param {ASTNode} node LogicalExpression node to test. - * @returns {boolean} Whether node is a range test. - */ - function isRangeTest(node) { - const left = node.left, - right = node.right; - - /** - * Determines whether node is of the form `0 <= x && x < 1`. - * @returns {boolean} Whether node is a "between" range test. - */ - function isBetweenTest() { - if (node.operator === "&&" && astUtils.isSameReference(left.right, right.left)) { - const leftLiteral = getNormalizedLiteral(left.left); - const rightLiteral = getNormalizedLiteral(right.right); - - if (leftLiteral === null && rightLiteral === null) { - return false; - } - - if (rightLiteral === null || leftLiteral === null) { - return true; - } - - if (leftLiteral.value <= rightLiteral.value) { - return true; - } - } - return false; - } - - /** - * Determines whether node is of the form `x < 0 || 1 <= x`. - * @returns {boolean} Whether node is an "outside" range test. - */ - function isOutsideTest() { - if (node.operator === "||" && astUtils.isSameReference(left.left, right.right)) { - const leftLiteral = getNormalizedLiteral(left.right); - const rightLiteral = getNormalizedLiteral(right.left); - - if (leftLiteral === null && rightLiteral === null) { - return false; - } - - if (rightLiteral === null || leftLiteral === null) { - return true; - } - - if (leftLiteral.value <= rightLiteral.value) { - return true; - } - } - - return false; - } - - /** - * Determines whether node is wrapped in parentheses. - * @returns {boolean} Whether node is preceded immediately by an open - * paren token and followed immediately by a close - * paren token. - */ - function isParenWrapped() { - return astUtils.isParenthesised(sourceCode, node); - } - - return ( - node.type === "LogicalExpression" && - left.type === "BinaryExpression" && - right.type === "BinaryExpression" && - isRangeTestOperator(left.operator) && - isRangeTestOperator(right.operator) && - (isBetweenTest() || isOutsideTest()) && - isParenWrapped() - ); - } - - const OPERATOR_FLIP_MAP = { - "===": "===", - "!==": "!==", - "==": "==", - "!=": "!=", - "<": ">", - ">": "<", - "<=": ">=", - ">=": "<=" - }; - - /** - * Returns a string representation of a BinaryExpression node with its sides/operator flipped around. - * @param {ASTNode} node The BinaryExpression node - * @returns {string} A string representation of the node with the sides and operator flipped - */ - function getFlippedString(node) { - const tokenBefore = sourceCode.getTokenBefore(node); - const operatorToken = sourceCode.getFirstTokenBetween( - node.left, - node.right, - token => token.value === node.operator - ); - const textBeforeOperator = sourceCode - .getText() - .slice( - sourceCode.getTokenBefore(operatorToken).range[1], - operatorToken.range[0] - ); - const textAfterOperator = sourceCode - .getText() - .slice( - operatorToken.range[1], - sourceCode.getTokenAfter(operatorToken).range[0] - ); - const leftText = sourceCode - .getText() - .slice( - node.range[0], - sourceCode.getTokenBefore(operatorToken).range[1] - ); - const firstRightToken = sourceCode.getTokenAfter(operatorToken); - const rightText = sourceCode - .getText() - .slice(firstRightToken.range[0], node.range[1]); - - let prefix = ""; - - if ( - tokenBefore && - tokenBefore.range[1] === node.range[0] && - !astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken) - ) { - prefix = " "; - } - - return ( - prefix + - rightText + - textBeforeOperator + - OPERATOR_FLIP_MAP[operatorToken.value] + - textAfterOperator + - leftText - ); - } - - //-------------------------------------------------------------------------- - // Public - //-------------------------------------------------------------------------- - - return { - BinaryExpression(node) { - const expectedLiteral = always ? node.left : node.right; - const expectedNonLiteral = always ? node.right : node.left; - - // If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error. - if ( - (expectedNonLiteral.type === "Literal" || - looksLikeLiteral(expectedNonLiteral)) && - !( - expectedLiteral.type === "Literal" || - looksLikeLiteral(expectedLiteral) - ) && - !(!isEqualityOperator(node.operator) && onlyEquality) && - isComparisonOperator(node.operator) && - !(exceptRange && isRangeTest(context.getAncestors().pop())) - ) { - context.report({ - node, - messageId: "expected", - data: { - operator: node.operator, - expectedSide: always ? "left" : "right" - }, - fix: fixer => - fixer.replaceText(node, getFlippedString(node)) - }); - } - } - }; - } -}; diff --git a/tools/node_modules/eslint/lib/shared/ajv.js b/tools/node_modules/eslint/lib/shared/ajv.js deleted file mode 100644 index 3fb0fbdd33c146f1f279ca3c173c7cc5a3abc7d6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/ajv.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * @fileoverview The instance of Ajv validator. - * @author Evgeny Poberezkin - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Ajv = require("ajv"), - metaSchema = require("ajv/lib/refs/json-schema-draft-04.json"); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = (additionalOptions = {}) => { - const ajv = new Ajv({ - meta: false, - useDefaults: true, - validateSchema: false, - missingRefs: "ignore", - verbose: true, - schemaId: "auto", - ...additionalOptions - }); - - ajv.addMetaSchema(metaSchema); - // eslint-disable-next-line no-underscore-dangle - ajv._opts.defaultMeta = metaSchema.id; - - return ajv; -}; diff --git a/tools/node_modules/eslint/lib/shared/ast-utils.js b/tools/node_modules/eslint/lib/shared/ast-utils.js deleted file mode 100644 index 4ebd49c3ce6a6b51aa4da2fb50ca7769f0deff66..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/ast-utils.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @fileoverview Common utils for AST. - * - * This file contains only shared items for core and rules. - * If you make a utility for rules, please see `../rules/utils/ast-utils.js`. - * - * @author Toru Nagashima - */ -"use strict"; - -const breakableTypePattern = /^(?:(?:Do)?While|For(?:In|Of)?|Switch)Statement$/u; -const lineBreakPattern = /\r\n|[\r\n\u2028\u2029]/u; -const shebangPattern = /^#!([^\r\n]+)/u; - -/** - * Creates a version of the `lineBreakPattern` regex with the global flag. - * Global regexes are mutable, so this needs to be a function instead of a constant. - * @returns {RegExp} A global regular expression that matches line terminators - */ -function createGlobalLinebreakMatcher() { - return new RegExp(lineBreakPattern.source, "gu"); -} - -module.exports = { - breakableTypePattern, - lineBreakPattern, - createGlobalLinebreakMatcher, - shebangPattern -}; diff --git a/tools/node_modules/eslint/lib/shared/config-validator.js b/tools/node_modules/eslint/lib/shared/config-validator.js deleted file mode 100644 index 03b32f1c9183ed495a1e5428106a990f9e951b58..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/config-validator.js +++ /dev/null @@ -1,338 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * @fileoverview Validates configs. - * @author Brandon Mills - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const - util = require("util"), - configSchema = require("../../conf/config-schema"), - BuiltInEnvironments = require("@eslint/eslintrc/conf/environments"), - BuiltInRules = require("../rules"), - ConfigOps = require("@eslint/eslintrc/lib/shared/config-ops"), - { emitDeprecationWarning } = require("./deprecation-warnings"); - -const ajv = require("./ajv")(); -const ruleValidators = new WeakMap(); -const noop = Function.prototype; - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ -let validateSchema; -const severityMap = { - error: 2, - warn: 1, - off: 0 -}; - -/** - * Gets a complete options schema for a rule. - * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object - * @returns {Object} JSON Schema for the rule's options. - */ -function getRuleOptionsSchema(rule) { - if (!rule) { - return null; - } - - const schema = rule.schema || rule.meta && rule.meta.schema; - - // Given a tuple of schemas, insert warning level at the beginning - if (Array.isArray(schema)) { - if (schema.length) { - return { - type: "array", - items: schema, - minItems: 0, - maxItems: schema.length - }; - } - return { - type: "array", - minItems: 0, - maxItems: 0 - }; - - } - - // Given a full schema, leave it alone - return schema || null; -} - -/** - * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. - * @param {options} options The given options for the rule. - * @returns {number|string} The rule's severity value - */ -function validateRuleSeverity(options) { - const severity = Array.isArray(options) ? options[0] : options; - const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; - - if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { - return normSeverity; - } - - throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); - -} - -/** - * Validates the non-severity options passed to a rule, based on its schema. - * @param {{create: Function}} rule The rule to validate - * @param {Array} localOptions The options for the rule, excluding severity - * @returns {void} - */ -function validateRuleSchema(rule, localOptions) { - if (!ruleValidators.has(rule)) { - const schema = getRuleOptionsSchema(rule); - - if (schema) { - ruleValidators.set(rule, ajv.compile(schema)); - } - } - - const validateRule = ruleValidators.get(rule); - - if (validateRule) { - validateRule(localOptions); - if (validateRule.errors) { - throw new Error(validateRule.errors.map( - error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` - ).join("")); - } - } -} - -/** - * Validates a rule's options against its schema. - * @param {{create: Function}|null} rule The rule that the config is being validated for - * @param {string} ruleId The rule's unique name. - * @param {Array|number} options The given options for the rule. - * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, - * no source is prepended to the message. - * @returns {void} - */ -function validateRuleOptions(rule, ruleId, options, source = null) { - try { - const severity = validateRuleSeverity(options); - - if (severity !== 0) { - validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); - } - } catch (err) { - const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; - - if (typeof source === "string") { - throw new Error(`${source}:\n\t${enhancedMessage}`); - } else { - throw new Error(enhancedMessage); - } - } -} - -/** - * Validates an environment object - * @param {Object} environment The environment config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments. - * @returns {void} - */ -function validateEnvironment( - environment, - source, - getAdditionalEnv = noop -) { - - // not having an environment is ok - if (!environment) { - return; - } - - Object.keys(environment).forEach(id => { - const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null; - - if (!env) { - const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; - - throw new Error(message); - } - }); -} - -/** - * Validates a rules config object - * @param {Object} rulesConfig The rules config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules - * @returns {void} - */ -function validateRules( - rulesConfig, - source, - getAdditionalRule = noop -) { - if (!rulesConfig) { - return; - } - - Object.keys(rulesConfig).forEach(id => { - const rule = getAdditionalRule(id) || BuiltInRules.get(id) || null; - - validateRuleOptions(rule, id, rulesConfig[id], source); - }); -} - -/** - * Validates a `globals` section of a config file - * @param {Object} globalsConfig The `globals` section - * @param {string|null} source The name of the configuration source to report in the event of an error. - * @returns {void} - */ -function validateGlobals(globalsConfig, source = null) { - if (!globalsConfig) { - return; - } - - Object.entries(globalsConfig) - .forEach(([configuredGlobal, configuredValue]) => { - try { - ConfigOps.normalizeConfigGlobal(configuredValue); - } catch (err) { - throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); - } - }); -} - -/** - * Validate `processor` configuration. - * @param {string|undefined} processorName The processor name. - * @param {string} source The name of config file. - * @param {function(id:string): Processor} getProcessor The getter of defined processors. - * @returns {void} - */ -function validateProcessor(processorName, source, getProcessor) { - if (processorName && !getProcessor(processorName)) { - throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); - } -} - -/** - * Formats an array of schema validation errors. - * @param {Array} errors An array of error messages to format. - * @returns {string} Formatted error message - */ -function formatErrors(errors) { - return errors.map(error => { - if (error.keyword === "additionalProperties") { - const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; - - return `Unexpected top-level property "${formattedPropertyPath}"`; - } - if (error.keyword === "type") { - const formattedField = error.dataPath.slice(1); - const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; - const formattedValue = JSON.stringify(error.data); - - return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; - } - - const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; - - return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; - }).map(message => `\t- ${message}.\n`).join(""); -} - -/** - * Validates the top level properties of the config object. - * @param {Object} config The config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @returns {void} - */ -function validateConfigSchema(config, source = null) { - validateSchema = validateSchema || ajv.compile(configSchema); - - if (!validateSchema(config)) { - throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`); - } - - if (Object.hasOwnProperty.call(config, "ecmaFeatures")) { - emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); - } -} - -/** - * Validates an entire config object. - * @param {Object} config The config object to validate. - * @param {string} source The name of the configuration source to report in any errors. - * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules. - * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs. - * @returns {void} - */ -function validate(config, source, getAdditionalRule, getAdditionalEnv) { - validateConfigSchema(config, source); - validateRules(config.rules, source, getAdditionalRule); - validateEnvironment(config.env, source, getAdditionalEnv); - validateGlobals(config.globals, source); - - for (const override of config.overrides || []) { - validateRules(override.rules, source, getAdditionalRule); - validateEnvironment(override.env, source, getAdditionalEnv); - validateGlobals(config.globals, source); - } -} - -const validated = new WeakSet(); - -/** - * Validate config array object. - * @param {ConfigArray} configArray The config array to validate. - * @returns {void} - */ -function validateConfigArray(configArray) { - const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); - const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); - const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); - - // Validate. - for (const element of configArray) { - if (validated.has(element)) { - continue; - } - validated.add(element); - - validateEnvironment(element.env, element.name, getPluginEnv); - validateGlobals(element.globals, element.name); - validateProcessor(element.processor, element.name, getPluginProcessor); - validateRules(element.rules, element.name, getPluginRule); - } -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - getRuleOptionsSchema, - validate, - validateConfigArray, - validateConfigSchema, - validateRuleOptions -}; diff --git a/tools/node_modules/eslint/lib/shared/deprecation-warnings.js b/tools/node_modules/eslint/lib/shared/deprecation-warnings.js deleted file mode 100644 index e1481a2e9aa0b8cc34edbdd3d2c236ea146163b2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/deprecation-warnings.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * @fileoverview Provide the function that emits deprecation warnings. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const path = require("path"); -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -// Defitions for deprecation warnings. -const deprecationWarningMessages = { - ESLINT_LEGACY_ECMAFEATURES: - "The 'ecmaFeatures' config file property is deprecated and has no effect.", - ESLINT_PERSONAL_CONFIG_LOAD: - "'~/.eslintrc.*' config files have been deprecated. " + - "Please use a config file per project or the '--config' option.", - ESLINT_PERSONAL_CONFIG_SUPPRESS: - "'~/.eslintrc.*' config files have been deprecated. " + - "Please remove it or add 'root:true' to the config files in your " + - "projects in order to avoid loading '~/.eslintrc.*' accidentally." -}; - -/** - * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted - * for each unique file path, but repeated invocations with the same file path have no effect. - * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. - * @param {string} source The name of the configuration source to report the warning for. - * @param {string} errorCode The warning message to show. - * @returns {void} - */ -const emitDeprecationWarning = lodash.memoize((source, errorCode) => { - const rel = path.relative(process.cwd(), source); - const message = deprecationWarningMessages[errorCode]; - - process.emitWarning( - `${message} (found in "${rel}")`, - "DeprecationWarning", - errorCode - ); -}, (...args) => JSON.stringify(args)); - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - emitDeprecationWarning -}; diff --git a/tools/node_modules/eslint/lib/shared/logging.js b/tools/node_modules/eslint/lib/shared/logging.js deleted file mode 100644 index 6aa1f5a1e59c77b630f0f17ef74440a3cc1e158d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/logging.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * @fileoverview Handle logging for ESLint - * @author Gyandeep Singh - */ - -"use strict"; - -/* eslint no-console: "off" */ - -/* istanbul ignore next */ -module.exports = { - - /** - * Cover for console.log - * @param {...any} args The elements to log. - * @returns {void} - */ - info(...args) { - console.log(...args); - }, - - /** - * Cover for console.error - * @param {...any} args The elements to log. - * @returns {void} - */ - error(...args) { - console.error(...args); - } -}; diff --git a/tools/node_modules/eslint/lib/shared/relative-module-resolver.js b/tools/node_modules/eslint/lib/shared/relative-module-resolver.js deleted file mode 100644 index cd743f3795b2daad89a2983c8d6382b882df18d3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/relative-module-resolver.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - * STOP!!! DO NOT MODIFY. - * - * This file is part of the ongoing work to move the eslintrc-style config - * system into the @eslint/eslintrc package. This file needs to remain - * unchanged in order for this work to proceed. - * - * If you think you need to change this file, please contact @nzakas first. - * - * Thanks in advance for your cooperation. - */ - -/** - * Utility for resolving a module relative to another module - * @author Teddy Katz - */ - -"use strict"; - -const Module = require("module"); - -/* - * `Module.createRequire` is added in v12.2.0. It supports URL as well. - * We only support the case where the argument is a filepath, not a URL. - */ -// eslint-disable-next-line node/no-unsupported-features/node-builtins, node/no-deprecated-api -const createRequire = Module.createRequire || Module.createRequireFromPath; - -module.exports = { - - /** - * Resolves a Node module relative to another module - * @param {string} moduleName The name of a Node module, or a path to a Node module. - * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be - * a file rather than a directory, but the file need not actually exist. - * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` - */ - resolve(moduleName, relativeToPath) { - try { - return createRequire(relativeToPath).resolve(moduleName); - } catch (error) { - - // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future. - if ( - typeof error === "object" && - error !== null && - error.code === "MODULE_NOT_FOUND" && - !error.requireStack && - error.message.includes(moduleName) - ) { - error.message += `\nRequire stack:\n- ${relativeToPath}`; - } - throw error; - } - } -}; diff --git a/tools/node_modules/eslint/lib/shared/runtime-info.js b/tools/node_modules/eslint/lib/shared/runtime-info.js deleted file mode 100644 index feed005330e622cbdeb1b0dc0b744009fac68f6c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/runtime-info.js +++ /dev/null @@ -1,163 +0,0 @@ -/** - * @fileoverview Utility to get information about the execution environment. - * @author Kai Cataldo - */ - -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const path = require("path"); -const spawn = require("cross-spawn"); -const { isEmpty } = require("lodash"); -const log = require("../shared/logging"); -const packageJson = require("../../package.json"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Generates and returns execution environment information. - * @returns {string} A string that contains execution environment information. - */ -function environment() { - const cache = new Map(); - - /** - * Checks if a path is a child of a directory. - * @param {string} parentPath The parent path to check. - * @param {string} childPath The path to check. - * @returns {boolean} Whether or not the given path is a child of a directory. - */ - function isChildOfDirectory(parentPath, childPath) { - return !path.relative(parentPath, childPath).startsWith(".."); - } - - /** - * Synchronously executes a shell command and formats the result. - * @param {string} cmd The command to execute. - * @param {Array} args The arguments to be executed with the command. - * @returns {string} The version returned by the command. - */ - function execCommand(cmd, args) { - const key = [cmd, ...args].join(" "); - - if (cache.has(key)) { - return cache.get(key); - } - - const process = spawn.sync(cmd, args, { encoding: "utf8" }); - - if (process.error) { - throw process.error; - } - - const result = process.stdout.trim(); - - cache.set(key, result); - return result; - } - - /** - * Normalizes a version number. - * @param {string} versionStr The string to normalize. - * @returns {string} The normalized version number. - */ - function normalizeVersionStr(versionStr) { - return versionStr.startsWith("v") ? versionStr : `v${versionStr}`; - } - - /** - * Gets bin version. - * @param {string} bin The bin to check. - * @returns {string} The normalized version returned by the command. - */ - function getBinVersion(bin) { - const binArgs = ["--version"]; - - try { - return normalizeVersionStr(execCommand(bin, binArgs)); - } catch (e) { - log.error(`Error finding ${bin} version running the command \`${bin} ${binArgs.join(" ")}\``); - throw e; - } - } - - /** - * Gets installed npm package version. - * @param {string} pkg The package to check. - * @param {boolean} global Whether to check globally or not. - * @returns {string} The normalized version returned by the command. - */ - function getNpmPackageVersion(pkg, { global = false } = {}) { - const npmBinArgs = ["bin", "-g"]; - const npmLsArgs = ["ls", "--depth=0", "--json", "eslint"]; - - if (global) { - npmLsArgs.push("-g"); - } - - try { - const parsedStdout = JSON.parse(execCommand("npm", npmLsArgs)); - - /* - * Checking globally returns an empty JSON object, while local checks - * include the name and version of the local project. - */ - if (isEmpty(parsedStdout) || !(parsedStdout.dependencies && parsedStdout.dependencies.eslint)) { - return "Not found"; - } - - const [, processBinPath] = process.argv; - let npmBinPath; - - try { - npmBinPath = execCommand("npm", npmBinArgs); - } catch (e) { - log.error(`Error finding npm binary path when running command \`npm ${npmBinArgs.join(" ")}\``); - throw e; - } - - const isGlobal = isChildOfDirectory(npmBinPath, processBinPath); - let pkgVersion = parsedStdout.dependencies.eslint.version; - - if ((global && isGlobal) || (!global && !isGlobal)) { - pkgVersion += " (Currently used)"; - } - - return normalizeVersionStr(pkgVersion); - } catch (e) { - log.error(`Error finding ${pkg} version running the command \`npm ${npmLsArgs.join(" ")}\``); - throw e; - } - } - - return [ - "Environment Info:", - "", - `Node version: ${getBinVersion("node")}`, - `npm version: ${getBinVersion("npm")}`, - `Local ESLint version: ${getNpmPackageVersion("eslint", { global: false })}`, - `Global ESLint version: ${getNpmPackageVersion("eslint", { global: true })}` - ].join("\n"); -} - -/** - * Returns version of currently executing ESLint. - * @returns {string} The version from the currently executing ESLint's package.json. - */ -function version() { - return `v${packageJson.version}`; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -module.exports = { - environment, - version -}; diff --git a/tools/node_modules/eslint/lib/shared/traverser.js b/tools/node_modules/eslint/lib/shared/traverser.js deleted file mode 100644 index 32f76779507c5a361d2df73e52151453104ea36d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/traverser.js +++ /dev/null @@ -1,195 +0,0 @@ -/** - * @fileoverview Traverser to traverse AST trees. - * @author Nicholas C. Zakas - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const vk = require("eslint-visitor-keys"); -const debug = require("debug")("eslint:traverser"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Do nothing. - * @returns {void} - */ -function noop() { - - // do nothing. -} - -/** - * Check whether the given value is an ASTNode or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an ASTNode. - */ -function isNode(x) { - return x !== null && typeof x === "object" && typeof x.type === "string"; -} - -/** - * Get the visitor keys of a given node. - * @param {Object} visitorKeys The map of visitor keys. - * @param {ASTNode} node The node to get their visitor keys. - * @returns {string[]} The visitor keys of the node. - */ -function getVisitorKeys(visitorKeys, node) { - let keys = visitorKeys[node.type]; - - if (!keys) { - keys = vk.getKeys(node); - debug("Unknown node type \"%s\": Estimated visitor keys %j", node.type, keys); - } - - return keys; -} - -/** - * The traverser class to traverse AST trees. - */ -class Traverser { - constructor() { - this._current = null; - this._parents = []; - this._skipped = false; - this._broken = false; - this._visitorKeys = null; - this._enter = null; - this._leave = null; - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @returns {ASTNode} The current node. - */ - current() { - return this._current; - } - - // eslint-disable-next-line jsdoc/require-description - /** - * @returns {ASTNode[]} The ancestor nodes. - */ - parents() { - return this._parents.slice(0); - } - - /** - * Break the current traversal. - * @returns {void} - */ - break() { - this._broken = true; - } - - /** - * Skip child nodes for the current traversal. - * @returns {void} - */ - skip() { - this._skipped = true; - } - - /** - * Traverse the given AST tree. - * @param {ASTNode} node The root node to traverse. - * @param {Object} options The option object. - * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. - * @param {Function} [options.enter=noop] The callback function which is called on entering each node. - * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. - * @returns {void} - */ - traverse(node, options) { - this._current = null; - this._parents = []; - this._skipped = false; - this._broken = false; - this._visitorKeys = options.visitorKeys || vk.KEYS; - this._enter = options.enter || noop; - this._leave = options.leave || noop; - this._traverse(node, null); - } - - /** - * Traverse the given AST tree recursively. - * @param {ASTNode} node The current node. - * @param {ASTNode|null} parent The parent node. - * @returns {void} - * @private - */ - _traverse(node, parent) { - if (!isNode(node)) { - return; - } - - this._current = node; - this._skipped = false; - this._enter(node, parent); - - if (!this._skipped && !this._broken) { - const keys = getVisitorKeys(this._visitorKeys, node); - - if (keys.length >= 1) { - this._parents.push(node); - for (let i = 0; i < keys.length && !this._broken; ++i) { - const child = node[keys[i]]; - - if (Array.isArray(child)) { - for (let j = 0; j < child.length && !this._broken; ++j) { - this._traverse(child[j], node); - } - } else { - this._traverse(child, node); - } - } - this._parents.pop(); - } - } - - if (!this._broken) { - this._leave(node, parent); - } - - this._current = parent; - } - - /** - * Calculates the keys to use for traversal. - * @param {ASTNode} node The node to read keys from. - * @returns {string[]} An array of keys to visit on the node. - * @private - */ - static getKeys(node) { - return vk.getKeys(node); - } - - /** - * Traverse the given AST tree. - * @param {ASTNode} node The root node to traverse. - * @param {Object} options The option object. - * @param {Object} [options.visitorKeys=DEFAULT_VISITOR_KEYS] The keys of each node types to traverse child nodes. Default is `./default-visitor-keys.json`. - * @param {Function} [options.enter=noop] The callback function which is called on entering each node. - * @param {Function} [options.leave=noop] The callback function which is called on leaving each node. - * @returns {void} - */ - static traverse(node, options) { - new Traverser().traverse(node, options); - } - - /** - * The default visitor keys. - * @type {Object} - */ - static get DEFAULT_VISITOR_KEYS() { - return vk.KEYS; - } -} - -module.exports = Traverser; diff --git a/tools/node_modules/eslint/lib/shared/types.js b/tools/node_modules/eslint/lib/shared/types.js deleted file mode 100644 index 8ad3b1b64ce1e3c635ab7c8f9babe952b7bc119d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/shared/types.js +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @fileoverview Define common types for input completion. - * @author Toru Nagashima - */ -"use strict"; - -/** @type {any} */ -module.exports = {}; - -/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */ -/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */ -/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */ - -/** - * @typedef {Object} EcmaFeatures - * @property {boolean} [globalReturn] Enabling `return` statements at the top-level. - * @property {boolean} [jsx] Enabling JSX syntax. - * @property {boolean} [impliedStrict] Enabling strict mode always. - */ - -/** - * @typedef {Object} ParserOptions - * @property {EcmaFeatures} [ecmaFeatures] The optional features. - * @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number). - * @property {"script"|"module"} [sourceType] The source code type. - */ - -/** - * @typedef {Object} ConfigData - * @property {Record} [env] The environment settings. - * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. - * @property {Record} [globals] The global variable settings. - * @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint. - * @property {boolean} [noInlineConfig] The flag that disables directive comments. - * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. - * @property {string} [parser] The path to a parser or the package name of a parser. - * @property {ParserOptions} [parserOptions] The parser options. - * @property {string[]} [plugins] The plugin specifiers. - * @property {string} [processor] The processor specifier. - * @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments. - * @property {boolean} [root] The root flag. - * @property {Record} [rules] The rule settings. - * @property {Object} [settings] The shared settings. - */ - -/** - * @typedef {Object} OverrideConfigData - * @property {Record} [env] The environment settings. - * @property {string | string[]} [excludedFiles] The glob pattarns for excluded files. - * @property {string | string[]} [extends] The path to other config files or the package name of shareable configs. - * @property {string | string[]} files The glob pattarns for target files. - * @property {Record} [globals] The global variable settings. - * @property {boolean} [noInlineConfig] The flag that disables directive comments. - * @property {OverrideConfigData[]} [overrides] The override settings per kind of files. - * @property {string} [parser] The path to a parser or the package name of a parser. - * @property {ParserOptions} [parserOptions] The parser options. - * @property {string[]} [plugins] The plugin specifiers. - * @property {string} [processor] The processor specifier. - * @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments. - * @property {Record} [rules] The rule settings. - * @property {Object} [settings] The shared settings. - */ - -/** - * @typedef {Object} ParseResult - * @property {Object} ast The AST. - * @property {ScopeManager} [scopeManager] The scope manager of the AST. - * @property {Record} [services] The services that the parser provides. - * @property {Record} [visitorKeys] The visitor keys of the AST. - */ - -/** - * @typedef {Object} Parser - * @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables. - * @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment. - */ - -/** - * @typedef {Object} Environment - * @property {Record} [globals] The definition of global variables. - * @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment. - */ - -/** - * @typedef {Object} LintMessage - * @property {number} column The 1-based column number. - * @property {number} [endColumn] The 1-based column number of the end location. - * @property {number} [endLine] The 1-based line number of the end location. - * @property {boolean} fatal If `true` then this is a fatal error. - * @property {{range:[number,number], text:string}} [fix] Information for autofix. - * @property {number} line The 1-based line number. - * @property {string} message The error message. - * @property {string|null} ruleId The ID of the rule which makes this message. - * @property {0|1|2} severity The severity of this message. - * @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions. - */ - -/** - * @typedef {Object} SuggestionResult - * @property {string} desc A short description. - * @property {string} [messageId] Id referencing a message for the description. - * @property {{ text: string, range: number[] }} fix fix result info - */ - -/** - * @typedef {Object} Processor - * @property {(text:string, filename:string) => Array} [preprocess] The function to extract code blocks. - * @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages. - * @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix. - */ - -/** - * @typedef {Object} RuleMetaDocs - * @property {string} category The category of the rule. - * @property {string} description The description of the rule. - * @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset. - * @property {string} url The URL of the rule documentation. - */ - -/** - * @typedef {Object} RuleMeta - * @property {boolean} [deprecated] If `true` then the rule has been deprecated. - * @property {RuleMetaDocs} docs The document information of the rule. - * @property {"code"|"whitespace"} [fixable] The autofix type. - * @property {Record} [messages] The messages the rule reports. - * @property {string[]} [replacedBy] The IDs of the alternative rules. - * @property {Array|Object} schema The option schema of the rule. - * @property {"problem"|"suggestion"|"layout"} type The rule type. - */ - -/** - * @typedef {Object} Rule - * @property {Function} create The factory of the rule. - * @property {RuleMeta} meta The meta data of the rule. - */ - -/** - * @typedef {Object} Plugin - * @property {Record} [configs] The definition of plugin configs. - * @property {Record} [environments] The definition of plugin environments. - * @property {Record} [processors] The definition of plugin processors. - * @property {Record} [rules] The definition of plugin rules. - */ - -/** - * Information of deprecated rules. - * @typedef {Object} DeprecatedRuleInfo - * @property {string} ruleId The rule ID. - * @property {string[]} replacedBy The rule IDs that replace this deprecated rule. - */ diff --git a/tools/node_modules/eslint/lib/source-code/index.js b/tools/node_modules/eslint/lib/source-code/index.js deleted file mode 100644 index 76e27869f321ac2dacb7d90f3a0ee598389791e2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/index.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; - -module.exports = { - SourceCode: require("./source-code") -}; diff --git a/tools/node_modules/eslint/lib/source-code/source-code.js b/tools/node_modules/eslint/lib/source-code/source-code.js deleted file mode 100644 index 6b20495b6fc807a07b82cc9c4325c9f5f78203fd..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/source-code.js +++ /dev/null @@ -1,586 +0,0 @@ -/** - * @fileoverview Abstraction of JavaScript source code. - * @author Nicholas C. Zakas - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const - { isCommentToken } = require("eslint-utils"), - TokenStore = require("./token-store"), - astUtils = require("../shared/ast-utils"), - Traverser = require("../shared/traverser"), - lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Private -//------------------------------------------------------------------------------ - -/** - * Validates that the given AST has the required information. - * @param {ASTNode} ast The Program node of the AST to check. - * @throws {Error} If the AST doesn't contain the correct information. - * @returns {void} - * @private - */ -function validate(ast) { - if (!ast.tokens) { - throw new Error("AST is missing the tokens array."); - } - - if (!ast.comments) { - throw new Error("AST is missing the comments array."); - } - - if (!ast.loc) { - throw new Error("AST is missing location information."); - } - - if (!ast.range) { - throw new Error("AST is missing range information"); - } -} - -/** - * Check to see if its a ES6 export declaration. - * @param {ASTNode} astNode An AST node. - * @returns {boolean} whether the given node represents an export declaration. - * @private - */ -function looksLikeExport(astNode) { - return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" || - astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier"; -} - -/** - * Merges two sorted lists into a larger sorted list in O(n) time. - * @param {Token[]} tokens The list of tokens. - * @param {Token[]} comments The list of comments. - * @returns {Token[]} A sorted list of tokens and comments. - * @private - */ -function sortedMerge(tokens, comments) { - const result = []; - let tokenIndex = 0; - let commentIndex = 0; - - while (tokenIndex < tokens.length || commentIndex < comments.length) { - if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) { - result.push(tokens[tokenIndex++]); - } else { - result.push(comments[commentIndex++]); - } - } - - return result; -} - -/** - * Determines if two nodes or tokens overlap. - * @param {ASTNode|Token} first The first node or token to check. - * @param {ASTNode|Token} second The second node or token to check. - * @returns {boolean} True if the two nodes or tokens overlap. - * @private - */ -function nodesOrTokensOverlap(first, second) { - return (first.range[0] <= second.range[0] && first.range[1] >= second.range[0]) || - (second.range[0] <= first.range[0] && second.range[1] >= first.range[0]); -} - -/** - * Determines if two nodes or tokens have at least one whitespace character - * between them. Order does not matter. Returns false if the given nodes or - * tokens overlap. - * @param {SourceCode} sourceCode The source code object. - * @param {ASTNode|Token} first The first node or token to check between. - * @param {ASTNode|Token} second The second node or token to check between. - * @param {boolean} checkInsideOfJSXText If `true` is present, check inside of JSXText tokens for backward compatibility. - * @returns {boolean} True if there is a whitespace character between - * any of the tokens found between the two given nodes or tokens. - * @public - */ -function isSpaceBetween(sourceCode, first, second, checkInsideOfJSXText) { - if (nodesOrTokensOverlap(first, second)) { - return false; - } - - const [startingNodeOrToken, endingNodeOrToken] = first.range[1] <= second.range[0] - ? [first, second] - : [second, first]; - const firstToken = sourceCode.getLastToken(startingNodeOrToken) || startingNodeOrToken; - const finalToken = sourceCode.getFirstToken(endingNodeOrToken) || endingNodeOrToken; - let currentToken = firstToken; - - while (currentToken !== finalToken) { - const nextToken = sourceCode.getTokenAfter(currentToken, { includeComments: true }); - - if ( - currentToken.range[1] !== nextToken.range[0] || - - /* - * For backward compatibility, check spaces in JSXText. - * https://github.com/eslint/eslint/issues/12614 - */ - ( - checkInsideOfJSXText && - nextToken !== finalToken && - nextToken.type === "JSXText" && - /\s/u.test(nextToken.value) - ) - ) { - return true; - } - - currentToken = nextToken; - } - - return false; -} - -//------------------------------------------------------------------------------ -// Public Interface -//------------------------------------------------------------------------------ - -class SourceCode extends TokenStore { - - /** - * Represents parsed source code. - * @param {string|Object} textOrConfig The source code text or config object. - * @param {string} textOrConfig.text The source code text. - * @param {ASTNode} textOrConfig.ast The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. - * @param {Object|null} textOrConfig.parserServices The parser services. - * @param {ScopeManager|null} textOrConfig.scopeManager The scope of this source code. - * @param {Object|null} textOrConfig.visitorKeys The visitor keys to traverse AST. - * @param {ASTNode} [astIfNoConfig] The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped. - */ - constructor(textOrConfig, astIfNoConfig) { - let text, ast, parserServices, scopeManager, visitorKeys; - - // Process overloading. - if (typeof textOrConfig === "string") { - text = textOrConfig; - ast = astIfNoConfig; - } else if (typeof textOrConfig === "object" && textOrConfig !== null) { - text = textOrConfig.text; - ast = textOrConfig.ast; - parserServices = textOrConfig.parserServices; - scopeManager = textOrConfig.scopeManager; - visitorKeys = textOrConfig.visitorKeys; - } - - validate(ast); - super(ast.tokens, ast.comments); - - /** - * The flag to indicate that the source code has Unicode BOM. - * @type boolean - */ - this.hasBOM = (text.charCodeAt(0) === 0xFEFF); - - /** - * The original text source code. - * BOM was stripped from this text. - * @type string - */ - this.text = (this.hasBOM ? text.slice(1) : text); - - /** - * The parsed AST for the source code. - * @type ASTNode - */ - this.ast = ast; - - /** - * The parser services of this source code. - * @type {Object} - */ - this.parserServices = parserServices || {}; - - /** - * The scope of this source code. - * @type {ScopeManager|null} - */ - this.scopeManager = scopeManager || null; - - /** - * The visitor keys to traverse AST. - * @type {Object} - */ - this.visitorKeys = visitorKeys || Traverser.DEFAULT_VISITOR_KEYS; - - // Check the source text for the presence of a shebang since it is parsed as a standard line comment. - const shebangMatched = this.text.match(astUtils.shebangPattern); - const hasShebang = shebangMatched && ast.comments.length && ast.comments[0].value === shebangMatched[1]; - - if (hasShebang) { - ast.comments[0].type = "Shebang"; - } - - this.tokensAndComments = sortedMerge(ast.tokens, ast.comments); - - /** - * The source code split into lines according to ECMA-262 specification. - * This is done to avoid each rule needing to do so separately. - * @type string[] - */ - this.lines = []; - this.lineStartIndices = [0]; - - const lineEndingPattern = astUtils.createGlobalLinebreakMatcher(); - let match; - - /* - * Previously, this was implemented using a regex that - * matched a sequence of non-linebreak characters followed by a - * linebreak, then adding the lengths of the matches. However, - * this caused a catastrophic backtracking issue when the end - * of a file contained a large number of non-newline characters. - * To avoid this, the current implementation just matches newlines - * and uses match.index to get the correct line start indices. - */ - while ((match = lineEndingPattern.exec(this.text))) { - this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index)); - this.lineStartIndices.push(match.index + match[0].length); - } - this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1])); - - // Cache for comments found using getComments(). - this._commentCache = new WeakMap(); - - // don't allow modification of this object - Object.freeze(this); - Object.freeze(this.lines); - } - - /** - * Split the source code into multiple lines based on the line delimiters. - * @param {string} text Source code as a string. - * @returns {string[]} Array of source code lines. - * @public - */ - static splitLines(text) { - return text.split(astUtils.createGlobalLinebreakMatcher()); - } - - /** - * Gets the source code for the given node. - * @param {ASTNode} [node] The AST node to get the text for. - * @param {int} [beforeCount] The number of characters before the node to retrieve. - * @param {int} [afterCount] The number of characters after the node to retrieve. - * @returns {string} The text representing the AST node. - * @public - */ - getText(node, beforeCount, afterCount) { - if (node) { - return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0), - node.range[1] + (afterCount || 0)); - } - return this.text; - } - - /** - * Gets the entire source text split into an array of lines. - * @returns {Array} The source text as an array of lines. - * @public - */ - getLines() { - return this.lines; - } - - /** - * Retrieves an array containing all comments in the source code. - * @returns {ASTNode[]} An array of comment nodes. - * @public - */ - getAllComments() { - return this.ast.comments; - } - - /** - * Gets all comments for the given node. - * @param {ASTNode} node The AST node to get the comments for. - * @returns {Object} An object containing a leading and trailing array - * of comments indexed by their position. - * @public - * @deprecated replaced by getCommentsBefore(), getCommentsAfter(), and getCommentsInside(). - */ - getComments(node) { - if (this._commentCache.has(node)) { - return this._commentCache.get(node); - } - - const comments = { - leading: [], - trailing: [] - }; - - /* - * Return all comments as leading comments of the Program node when - * there is no executable code. - */ - if (node.type === "Program") { - if (node.body.length === 0) { - comments.leading = node.comments; - } - } else { - - /* - * Return comments as trailing comments of nodes that only contain - * comments (to mimic the comment attachment behavior present in Espree). - */ - if ((node.type === "BlockStatement" || node.type === "ClassBody") && node.body.length === 0 || - node.type === "ObjectExpression" && node.properties.length === 0 || - node.type === "ArrayExpression" && node.elements.length === 0 || - node.type === "SwitchStatement" && node.cases.length === 0 - ) { - comments.trailing = this.getTokens(node, { - includeComments: true, - filter: isCommentToken - }); - } - - /* - * Iterate over tokens before and after node and collect comment tokens. - * Do not include comments that exist outside of the parent node - * to avoid duplication. - */ - let currentToken = this.getTokenBefore(node, { includeComments: true }); - - while (currentToken && isCommentToken(currentToken)) { - if (node.parent && (currentToken.start < node.parent.start)) { - break; - } - comments.leading.push(currentToken); - currentToken = this.getTokenBefore(currentToken, { includeComments: true }); - } - - comments.leading.reverse(); - - currentToken = this.getTokenAfter(node, { includeComments: true }); - - while (currentToken && isCommentToken(currentToken)) { - if (node.parent && (currentToken.end > node.parent.end)) { - break; - } - comments.trailing.push(currentToken); - currentToken = this.getTokenAfter(currentToken, { includeComments: true }); - } - } - - this._commentCache.set(node, comments); - return comments; - } - - /** - * Retrieves the JSDoc comment for a given node. - * @param {ASTNode} node The AST node to get the comment for. - * @returns {Token|null} The Block comment token containing the JSDoc comment - * for the given node or null if not found. - * @public - * @deprecated - */ - getJSDocComment(node) { - - /** - * Checks for the presence of a JSDoc comment for the given node and returns it. - * @param {ASTNode} astNode The AST node to get the comment for. - * @returns {Token|null} The Block comment token containing the JSDoc comment - * for the given node or null if not found. - * @private - */ - const findJSDocComment = astNode => { - const tokenBefore = this.getTokenBefore(astNode, { includeComments: true }); - - if ( - tokenBefore && - isCommentToken(tokenBefore) && - tokenBefore.type === "Block" && - tokenBefore.value.charAt(0) === "*" && - astNode.loc.start.line - tokenBefore.loc.end.line <= 1 - ) { - return tokenBefore; - } - - return null; - }; - let parent = node.parent; - - switch (node.type) { - case "ClassDeclaration": - case "FunctionDeclaration": - return findJSDocComment(looksLikeExport(parent) ? parent : node); - - case "ClassExpression": - return findJSDocComment(parent.parent); - - case "ArrowFunctionExpression": - case "FunctionExpression": - if (parent.type !== "CallExpression" && parent.type !== "NewExpression") { - while ( - !this.getCommentsBefore(parent).length && - !/Function/u.test(parent.type) && - parent.type !== "MethodDefinition" && - parent.type !== "Property" - ) { - parent = parent.parent; - - if (!parent) { - break; - } - } - - if (parent && parent.type !== "FunctionDeclaration" && parent.type !== "Program") { - return findJSDocComment(parent); - } - } - - return findJSDocComment(node); - - // falls through - default: - return null; - } - } - - /** - * Gets the deepest node containing a range index. - * @param {int} index Range index of the desired node. - * @returns {ASTNode} The node if found or null if not found. - * @public - */ - getNodeByRangeIndex(index) { - let result = null; - - Traverser.traverse(this.ast, { - visitorKeys: this.visitorKeys, - enter(node) { - if (node.range[0] <= index && index < node.range[1]) { - result = node; - } else { - this.skip(); - } - }, - leave(node) { - if (node === result) { - this.break(); - } - } - }); - - return result; - } - - /** - * Determines if two nodes or tokens have at least one whitespace character - * between them. Order does not matter. Returns false if the given nodes or - * tokens overlap. - * @param {ASTNode|Token} first The first node or token to check between. - * @param {ASTNode|Token} second The second node or token to check between. - * @returns {boolean} True if there is a whitespace character between - * any of the tokens found between the two given nodes or tokens. - * @public - */ - isSpaceBetween(first, second) { - return isSpaceBetween(this, first, second, false); - } - - /** - * Determines if two nodes or tokens have at least one whitespace character - * between them. Order does not matter. Returns false if the given nodes or - * tokens overlap. - * For backward compatibility, this method returns true if there are - * `JSXText` tokens that contain whitespaces between the two. - * @param {ASTNode|Token} first The first node or token to check between. - * @param {ASTNode|Token} second The second node or token to check between. - * @returns {boolean} True if there is a whitespace character between - * any of the tokens found between the two given nodes or tokens. - * @deprecated in favor of isSpaceBetween(). - * @public - */ - isSpaceBetweenTokens(first, second) { - return isSpaceBetween(this, first, second, true); - } - - /** - * Converts a source text index into a (line, column) pair. - * @param {number} index The index of a character in a file - * @returns {Object} A {line, column} location object with a 0-indexed column - * @public - */ - getLocFromIndex(index) { - if (typeof index !== "number") { - throw new TypeError("Expected `index` to be a number."); - } - - if (index < 0 || index > this.text.length) { - throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`); - } - - /* - * For an argument of this.text.length, return the location one "spot" past the last character - * of the file. If the last character is a linebreak, the location will be column 0 of the next - * line; otherwise, the location will be in the next column on the same line. - * - * See getIndexFromLoc for the motivation for this special case. - */ - if (index === this.text.length) { - return { line: this.lines.length, column: this.lines[this.lines.length - 1].length }; - } - - /* - * To figure out which line rangeIndex is on, determine the last index at which rangeIndex could - * be inserted into lineIndices to keep the list sorted. - */ - const lineNumber = lodash.sortedLastIndex(this.lineStartIndices, index); - - return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] }; - } - - /** - * Converts a (line, column) pair into a range index. - * @param {Object} loc A line/column location - * @param {number} loc.line The line number of the location (1-indexed) - * @param {number} loc.column The column number of the location (0-indexed) - * @returns {number} The range index of the location in the file. - * @public - */ - getIndexFromLoc(loc) { - if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") { - throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties."); - } - - if (loc.line <= 0) { - throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`); - } - - if (loc.line > this.lineStartIndices.length) { - throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`); - } - - const lineStartIndex = this.lineStartIndices[loc.line - 1]; - const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line]; - const positionIndex = lineStartIndex + loc.column; - - /* - * By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of - * the given line, provided that the line number is valid element of this.lines. Since the - * last element of this.lines is an empty string for files with trailing newlines, add a - * special case where getting the index for the first location after the end of the file - * will return the length of the file, rather than throwing an error. This allows rules to - * use getIndexFromLoc consistently without worrying about edge cases at the end of a file. - */ - if ( - loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex || - loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex - ) { - throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`); - } - - return positionIndex; - } -} - -module.exports = SourceCode; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js deleted file mode 100644 index 7255a62260b29ad7ce3084d154ad308ffe447dc4..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/backward-token-comment-cursor.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens and comments in reverse. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens and comments in reverse. - */ -module.exports = class BackwardTokenCommentCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.comments = comments; - this.tokenIndex = utils.getLastIndex(tokens, indexMap, endLoc); - this.commentIndex = utils.search(comments, endLoc) - 1; - this.border = startLoc; - } - - /** @inheritdoc */ - moveNext() { - const token = (this.tokenIndex >= 0) ? this.tokens[this.tokenIndex] : null; - const comment = (this.commentIndex >= 0) ? this.comments[this.commentIndex] : null; - - if (token && (!comment || token.range[1] > comment.range[1])) { - this.current = token; - this.tokenIndex -= 1; - } else if (comment) { - this.current = comment; - this.commentIndex -= 1; - } else { - this.current = null; - } - - return Boolean(this.current) && (this.border === -1 || this.current.range[0] >= this.border); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js deleted file mode 100644 index 454a2449701cf130de30a3029f9414000427b91a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/backward-token-cursor.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens only in reverse. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens only in reverse. - */ -module.exports = class BackwardTokenCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.index = utils.getLastIndex(tokens, indexMap, endLoc); - this.indexEnd = utils.getFirstIndex(tokens, indexMap, startLoc); - } - - /** @inheritdoc */ - moveNext() { - if (this.index >= this.indexEnd) { - this.current = this.tokens[this.index]; - this.index -= 1; - return true; - } - return false; - } - - /* - * - * Shorthand for performance. - * - */ - - /** @inheritdoc */ - getOneToken() { - return (this.index >= this.indexEnd) ? this.tokens[this.index] : null; - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/cursor.js deleted file mode 100644 index 4e1595c6dcb8a35ffab970d9a519352f0283f71e..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/cursor.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @fileoverview Define the abstract class about cursors which iterate tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The abstract class about cursors which iterate tokens. - * - * This class has 2 abstract methods. - * - * - `current: Token | Comment | null` ... The current token. - * - `moveNext(): boolean` ... Moves this cursor to the next token. If the next token didn't exist, it returns `false`. - * - * This is similar to ES2015 Iterators. - * However, Iterators were slow (at 2017-01), so I created this class as similar to C# IEnumerable. - * - * There are the following known sub classes. - * - * - ForwardTokenCursor .......... The cursor which iterates tokens only. - * - BackwardTokenCursor ......... The cursor which iterates tokens only in reverse. - * - ForwardTokenCommentCursor ... The cursor which iterates tokens and comments. - * - BackwardTokenCommentCursor .. The cursor which iterates tokens and comments in reverse. - * - DecorativeCursor - * - FilterCursor ............ The cursor which ignores the specified tokens. - * - SkipCursor .............. The cursor which ignores the first few tokens. - * - LimitCursor ............. The cursor which limits the count of tokens. - * - */ -module.exports = class Cursor { - - /** - * Initializes this cursor. - */ - constructor() { - this.current = null; - } - - /** - * Gets the first token. - * This consumes this cursor. - * @returns {Token|Comment} The first token or null. - */ - getOneToken() { - return this.moveNext() ? this.current : null; - } - - /** - * Gets the first tokens. - * This consumes this cursor. - * @returns {(Token|Comment)[]} All tokens. - */ - getAllTokens() { - const tokens = []; - - while (this.moveNext()) { - tokens.push(this.current); - } - - return tokens; - } - - /** - * Moves this cursor to the next token. - * @returns {boolean} `true` if the next token exists. - * @abstract - */ - /* istanbul ignore next */ - moveNext() { // eslint-disable-line class-methods-use-this - throw new Error("Not implemented."); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/cursors.js b/tools/node_modules/eslint/lib/source-code/token-store/cursors.js deleted file mode 100644 index 30c72b69b8f9629125ce7455632df68de8639cdd..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/cursors.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * @fileoverview Define 2 token factories; forward and backward. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const BackwardTokenCommentCursor = require("./backward-token-comment-cursor"); -const BackwardTokenCursor = require("./backward-token-cursor"); -const FilterCursor = require("./filter-cursor"); -const ForwardTokenCommentCursor = require("./forward-token-comment-cursor"); -const ForwardTokenCursor = require("./forward-token-cursor"); -const LimitCursor = require("./limit-cursor"); -const SkipCursor = require("./skip-cursor"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * The cursor factory. - * @private - */ -class CursorFactory { - - /** - * Initializes this cursor. - * @param {Function} TokenCursor The class of the cursor which iterates tokens only. - * @param {Function} TokenCommentCursor The class of the cursor which iterates the mix of tokens and comments. - */ - constructor(TokenCursor, TokenCommentCursor) { - this.TokenCursor = TokenCursor; - this.TokenCommentCursor = TokenCommentCursor; - } - - /** - * Creates a base cursor instance that can be decorated by createCursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {boolean} includeComments The flag to iterate comments as well. - * @returns {Cursor} The created base cursor. - */ - createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments) { - const Cursor = includeComments ? this.TokenCommentCursor : this.TokenCursor; - - return new Cursor(tokens, comments, indexMap, startLoc, endLoc); - } - - /** - * Creates a cursor that iterates tokens with normalized options. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {boolean} includeComments The flag to iterate comments as well. - * @param {Function|null} filter The predicate function to choose tokens. - * @param {number} skip The count of tokens the cursor skips. - * @param {number} count The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. - * @returns {Cursor} The created cursor. - */ - createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, count) { - let cursor = this.createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments); - - if (filter) { - cursor = new FilterCursor(cursor, filter); - } - if (skip >= 1) { - cursor = new SkipCursor(cursor, skip); - } - if (count >= 0) { - cursor = new LimitCursor(cursor, count); - } - - return cursor; - } -} - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -exports.forward = new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor); -exports.backward = new CursorFactory(BackwardTokenCursor, BackwardTokenCommentCursor); diff --git a/tools/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js deleted file mode 100644 index 3ee7b0b39755e162f7dfa85c26a1beff6d400e08..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/decorative-cursor.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * @fileoverview Define the abstract class about cursors which manipulate another cursor. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The abstract class about cursors which manipulate another cursor. - */ -module.exports = class DecorativeCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor The cursor to be decorated. - */ - constructor(cursor) { - super(); - this.cursor = cursor; - } - - /** @inheritdoc */ - moveNext() { - const retv = this.cursor.moveNext(); - - this.current = this.cursor.current; - - return retv; - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/filter-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/filter-cursor.js deleted file mode 100644 index 08c4f22031af8641ed6a7e30da082883777a4045..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/filter-cursor.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @fileoverview Define the cursor which ignores specified tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const DecorativeCursor = require("./decorative-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The decorative cursor which ignores specified tokens. - */ -module.exports = class FilterCursor extends DecorativeCursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor The cursor to be decorated. - * @param {Function} predicate The predicate function to decide tokens this cursor iterates. - */ - constructor(cursor, predicate) { - super(cursor); - this.predicate = predicate; - } - - /** @inheritdoc */ - moveNext() { - const predicate = this.predicate; - - while (super.moveNext()) { - if (predicate(this.current)) { - return true; - } - } - return false; - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js deleted file mode 100644 index 50c7a394f384764726ed43484f6d6d2d4431b25c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/forward-token-comment-cursor.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens and comments. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens and comments. - */ -module.exports = class ForwardTokenCommentCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.comments = comments; - this.tokenIndex = utils.getFirstIndex(tokens, indexMap, startLoc); - this.commentIndex = utils.search(comments, startLoc); - this.border = endLoc; - } - - /** @inheritdoc */ - moveNext() { - const token = (this.tokenIndex < this.tokens.length) ? this.tokens[this.tokenIndex] : null; - const comment = (this.commentIndex < this.comments.length) ? this.comments[this.commentIndex] : null; - - if (token && (!comment || token.range[0] < comment.range[0])) { - this.current = token; - this.tokenIndex += 1; - } else if (comment) { - this.current = comment; - this.commentIndex += 1; - } else { - this.current = null; - } - - return Boolean(this.current) && (this.border === -1 || this.current.range[1] <= this.border); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js deleted file mode 100644 index e8c18609621fbad00fb1672592d837225c3aa581..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/forward-token-cursor.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens only. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const Cursor = require("./cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens only. - */ -module.exports = class ForwardTokenCursor extends Cursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc) { - super(); - this.tokens = tokens; - this.index = utils.getFirstIndex(tokens, indexMap, startLoc); - this.indexEnd = utils.getLastIndex(tokens, indexMap, endLoc); - } - - /** @inheritdoc */ - moveNext() { - if (this.index <= this.indexEnd) { - this.current = this.tokens[this.index]; - this.index += 1; - return true; - } - return false; - } - - /* - * - * Shorthand for performance. - * - */ - - /** @inheritdoc */ - getOneToken() { - return (this.index <= this.indexEnd) ? this.tokens[this.index] : null; - } - - /** @inheritdoc */ - getAllTokens() { - return this.tokens.slice(this.index, this.indexEnd + 1); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/index.js b/tools/node_modules/eslint/lib/source-code/token-store/index.js deleted file mode 100644 index 25db8a4f4dbe5916f19582f1732f278802edc04c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/index.js +++ /dev/null @@ -1,627 +0,0 @@ -/** - * @fileoverview Object to handle access and retrieval of tokens. - * @author Brandon Mills - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const assert = require("assert"); -const { isCommentToken } = require("eslint-utils"); -const cursors = require("./cursors"); -const ForwardTokenCursor = require("./forward-token-cursor"); -const PaddedTokenCursor = require("./padded-token-cursor"); -const utils = require("./utils"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -const TOKENS = Symbol("tokens"); -const COMMENTS = Symbol("comments"); -const INDEX_MAP = Symbol("indexMap"); - -/** - * Creates the map from locations to indices in `tokens`. - * - * The first/last location of tokens is mapped to the index of the token. - * The first/last location of comments is mapped to the index of the next token of each comment. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @returns {Object} The map from locations to indices in `tokens`. - * @private - */ -function createIndexMap(tokens, comments) { - const map = Object.create(null); - let tokenIndex = 0; - let commentIndex = 0; - let nextStart = 0; - let range = null; - - while (tokenIndex < tokens.length || commentIndex < comments.length) { - nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER; - while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) { - map[range[0]] = tokenIndex; - map[range[1] - 1] = tokenIndex; - tokenIndex += 1; - } - - nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER; - while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) { - map[range[0]] = tokenIndex; - map[range[1] - 1] = tokenIndex; - commentIndex += 1; - } - } - - return map; -} - -/** - * Creates the cursor iterates tokens with options. - * @param {CursorFactory} factory The cursor factory to initialize cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`. - * @param {boolean} [opts.includeComments=false] The flag to iterate comments as well. - * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. - * @param {number} [opts.skip=0] The count of tokens the cursor skips. - * @returns {Cursor} The created cursor. - * @private - */ -function createCursorWithSkip(factory, tokens, comments, indexMap, startLoc, endLoc, opts) { - let includeComments = false; - let skip = 0; - let filter = null; - - if (typeof opts === "number") { - skip = opts | 0; - } else if (typeof opts === "function") { - filter = opts; - } else if (opts) { - includeComments = !!opts.includeComments; - skip = opts.skip | 0; - filter = opts.filter || null; - } - assert(skip >= 0, "options.skip should be zero or a positive integer."); - assert(!filter || typeof filter === "function", "options.filter should be a function."); - - return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, -1); -} - -/** - * Creates the cursor iterates tokens with options. - * @param {CursorFactory} factory The cursor factory to initialize cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`. - * @param {boolean} [opts.includeComments] The flag to iterate comments as well. - * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. - * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. - * @returns {Cursor} The created cursor. - * @private - */ -function createCursorWithCount(factory, tokens, comments, indexMap, startLoc, endLoc, opts) { - let includeComments = false; - let count = 0; - let countExists = false; - let filter = null; - - if (typeof opts === "number") { - count = opts | 0; - countExists = true; - } else if (typeof opts === "function") { - filter = opts; - } else if (opts) { - includeComments = !!opts.includeComments; - count = opts.count | 0; - countExists = typeof opts.count === "number"; - filter = opts.filter || null; - } - assert(count >= 0, "options.count should be zero or a positive integer."); - assert(!filter || typeof filter === "function", "options.filter should be a function."); - - return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, 0, countExists ? count : -1); -} - -/** - * Creates the cursor iterates tokens with options. - * This is overload function of the below. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {Function|Object} opts The option object. If this is a function then it's `opts.filter`. - * @param {boolean} [opts.includeComments] The flag to iterate comments as well. - * @param {Function|null} [opts.filter=null] The predicate function to choose tokens. - * @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility. - * @returns {Cursor} The created cursor. - * @private - */ -/** - * Creates the cursor iterates tokens with options. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {number} [beforeCount=0] The number of tokens before the node to retrieve. - * @param {boolean} [afterCount=0] The number of tokens after the node to retrieve. - * @returns {Cursor} The created cursor. - * @private - */ -function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { - if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") { - return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc); - } - if (typeof beforeCount === "number" || typeof beforeCount === "undefined") { - return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount | 0, afterCount | 0); - } - return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount); -} - -/** - * Gets comment tokens that are adjacent to the current cursor position. - * @param {Cursor} cursor A cursor instance. - * @returns {Array} An array of comment tokens adjacent to the current cursor position. - * @private - */ -function getAdjacentCommentTokensFromCursor(cursor) { - const tokens = []; - let currentToken = cursor.getOneToken(); - - while (currentToken && isCommentToken(currentToken)) { - tokens.push(currentToken); - currentToken = cursor.getOneToken(); - } - - return tokens; -} - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The token store. - * - * This class provides methods to get tokens by locations as fast as possible. - * The methods are a part of public API, so we should be careful if it changes this class. - * - * People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens. - * Also people can get a mix of tokens and comments in O(log k), the k is the number of comments. - * Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost. - * This uses binary-searching instead for comments. - */ -module.exports = class TokenStore { - - /** - * Initializes this token store. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - */ - constructor(tokens, comments) { - this[TOKENS] = tokens; - this[COMMENTS] = comments; - this[INDEX_MAP] = createIndexMap(tokens, comments); - } - - //-------------------------------------------------------------------------- - // Gets single token. - //-------------------------------------------------------------------------- - - /** - * Gets the token starting at the specified index. - * @param {number} offset Index of the start of the token's range. - * @param {Object} [options=0] The option object. - * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. - * @returns {Token|null} The token starting at index, or null if no such token. - */ - getTokenByRangeStart(offset, options) { - const includeComments = options && options.includeComments; - const token = cursors.forward.createBaseCursor( - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - offset, - -1, - includeComments - ).getOneToken(); - - if (token && token.range[0] === offset) { - return token; - } - return null; - } - - /** - * Gets the first token of the given node. - * @param {ASTNode} node The AST node. - * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] The predicate function to choose tokens. - * @param {number} [options.skip=0] The count of tokens the cursor skips. - * @returns {Token|null} An object representing the token. - */ - getFirstToken(node, options) { - return createCursorWithSkip( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getOneToken(); - } - - /** - * Gets the last token of the given node. - * @param {ASTNode} node The AST node. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getLastToken(node, options) { - return createCursorWithSkip( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getOneToken(); - } - - /** - * Gets the token that precedes a given node or token. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getTokenBefore(node, options) { - return createCursorWithSkip( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - -1, - node.range[0], - options - ).getOneToken(); - } - - /** - * Gets the token that follows a given node or token. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getTokenAfter(node, options) { - return createCursorWithSkip( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[1], - -1, - options - ).getOneToken(); - } - - /** - * Gets the first token between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getFirstTokenBetween(left, right, options) { - return createCursorWithSkip( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getOneToken(); - } - - /** - * Gets the last token between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken() - * @returns {Token|null} An object representing the token. - */ - getLastTokenBetween(left, right, options) { - return createCursorWithSkip( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getOneToken(); - } - - /** - * Gets the token that precedes a given node or token in the token stream. - * This is defined for backward compatibility. Use `includeComments` option instead. - * TODO: We have a plan to remove this in a future major version. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number} [skip=0] A number of tokens to skip. - * @returns {Token|null} An object representing the token. - * @deprecated - */ - getTokenOrCommentBefore(node, skip) { - return this.getTokenBefore(node, { includeComments: true, skip }); - } - - /** - * Gets the token that follows a given node or token in the token stream. - * This is defined for backward compatibility. Use `includeComments` option instead. - * TODO: We have a plan to remove this in a future major version. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number} [skip=0] A number of tokens to skip. - * @returns {Token|null} An object representing the token. - * @deprecated - */ - getTokenOrCommentAfter(node, skip) { - return this.getTokenAfter(node, { includeComments: true, skip }); - } - - //-------------------------------------------------------------------------- - // Gets multiple tokens. - //-------------------------------------------------------------------------- - - /** - * Gets the first `count` tokens of the given node. - * @param {ASTNode} node The AST node. - * @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] The predicate function to choose tokens. - * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. - * @returns {Token[]} Tokens. - */ - getFirstTokens(node, options) { - return createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getAllTokens(); - } - - /** - * Gets the last `count` tokens of the given node. - * @param {ASTNode} node The AST node. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens. - */ - getLastTokens(node, options) { - return createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - options - ).getAllTokens().reverse(); - } - - /** - * Gets the `count` tokens that precedes a given node or token. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens. - */ - getTokensBefore(node, options) { - return createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - -1, - node.range[0], - options - ).getAllTokens().reverse(); - } - - /** - * Gets the `count` tokens that follows a given node or token. - * @param {ASTNode|Token|Comment} node The AST node or token. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens. - */ - getTokensAfter(node, options) { - return createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[1], - -1, - options - ).getAllTokens(); - } - - /** - * Gets the first `count` tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens between left and right. - */ - getFirstTokensBetween(left, right, options) { - return createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getAllTokens(); - } - - /** - * Gets the last `count` tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens() - * @returns {Token[]} Tokens between left and right. - */ - getLastTokensBetween(left, right, options) { - return createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - options - ).getAllTokens().reverse(); - } - - /** - * Gets all tokens that are related to the given node. - * @param {ASTNode} node The AST node. - * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] The predicate function to choose tokens. - * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. - * @returns {Token[]} Array of objects representing tokens. - */ - /** - * Gets all tokens that are related to the given node. - * @param {ASTNode} node The AST node. - * @param {int} [beforeCount=0] The number of tokens before the node to retrieve. - * @param {int} [afterCount=0] The number of tokens after the node to retrieve. - * @returns {Token[]} Array of objects representing tokens. - */ - getTokens(node, beforeCount, afterCount) { - return createCursorWithPadding( - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - node.range[0], - node.range[1], - beforeCount, - afterCount - ).getAllTokens(); - } - - /** - * Gets all of the tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {Function|Object} options The option object. If this is a function then it's `options.filter`. - * @param {boolean} [options.includeComments=false] The flag to iterate comments as well. - * @param {Function|null} [options.filter=null] The predicate function to choose tokens. - * @param {number} [options.count=0] The maximum count of tokens the cursor iterates. - * @returns {Token[]} Tokens between left and right. - */ - /** - * Gets all of the tokens between two non-overlapping nodes. - * @param {ASTNode|Token|Comment} left Node before the desired token range. - * @param {ASTNode|Token|Comment} right Node after the desired token range. - * @param {int} [padding=0] Number of extra tokens on either side of center. - * @returns {Token[]} Tokens between left and right. - */ - getTokensBetween(left, right, padding) { - return createCursorWithPadding( - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - left.range[1], - right.range[0], - padding, - padding - ).getAllTokens(); - } - - //-------------------------------------------------------------------------- - // Others. - //-------------------------------------------------------------------------- - - /** - * Checks whether any comments exist or not between the given 2 nodes. - * @param {ASTNode} left The node to check. - * @param {ASTNode} right The node to check. - * @returns {boolean} `true` if one or more comments exist. - */ - commentsExistBetween(left, right) { - const index = utils.search(this[COMMENTS], left.range[1]); - - return ( - index < this[COMMENTS].length && - this[COMMENTS][index].range[1] <= right.range[0] - ); - } - - /** - * Gets all comment tokens directly before the given node or token. - * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. - * @returns {Array} An array of comments in occurrence order. - */ - getCommentsBefore(nodeOrToken) { - const cursor = createCursorWithCount( - cursors.backward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - -1, - nodeOrToken.range[0], - { includeComments: true } - ); - - return getAdjacentCommentTokensFromCursor(cursor).reverse(); - } - - /** - * Gets all comment tokens directly after the given node or token. - * @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens. - * @returns {Array} An array of comments in occurrence order. - */ - getCommentsAfter(nodeOrToken) { - const cursor = createCursorWithCount( - cursors.forward, - this[TOKENS], - this[COMMENTS], - this[INDEX_MAP], - nodeOrToken.range[1], - -1, - { includeComments: true } - ); - - return getAdjacentCommentTokensFromCursor(cursor); - } - - /** - * Gets all comment tokens inside the given node. - * @param {ASTNode} node The AST node to get the comments for. - * @returns {Array} An array of comments in occurrence order. - */ - getCommentsInside(node) { - return this.getTokens(node, { - includeComments: true, - filter: isCommentToken - }); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/limit-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/limit-cursor.js deleted file mode 100644 index 0fd92a77657ab30e5effc6907256d5531e91cab5..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/limit-cursor.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @fileoverview Define the cursor which limits the number of tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const DecorativeCursor = require("./decorative-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The decorative cursor which limits the number of tokens. - */ -module.exports = class LimitCursor extends DecorativeCursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor The cursor to be decorated. - * @param {number} count The count of tokens this cursor iterates. - */ - constructor(cursor, count) { - super(cursor); - this.count = count; - } - - /** @inheritdoc */ - moveNext() { - if (this.count > 0) { - this.count -= 1; - return super.moveNext(); - } - return false; - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js deleted file mode 100644 index 89349fa1c6952656a219745b72d672f3215bceb2..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/padded-token-cursor.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @fileoverview Define the cursor which iterates tokens only, with inflated range. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const ForwardTokenCursor = require("./forward-token-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The cursor which iterates tokens only, with inflated range. - * This is for the backward compatibility of padding options. - */ -module.exports = class PaddedTokenCursor extends ForwardTokenCursor { - - /** - * Initializes this cursor. - * @param {Token[]} tokens The array of tokens. - * @param {Comment[]} comments The array of comments. - * @param {Object} indexMap The map from locations to indices in `tokens`. - * @param {number} startLoc The start location of the iteration range. - * @param {number} endLoc The end location of the iteration range. - * @param {number} beforeCount The number of tokens this cursor iterates before start. - * @param {number} afterCount The number of tokens this cursor iterates after end. - */ - constructor(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) { - super(tokens, comments, indexMap, startLoc, endLoc); - this.index = Math.max(0, this.index - beforeCount); - this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/skip-cursor.js b/tools/node_modules/eslint/lib/source-code/token-store/skip-cursor.js deleted file mode 100644 index f068f531c1e3df68dee5d0ae5feb93db75343bd8..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/skip-cursor.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * @fileoverview Define the cursor which ignores the first few tokens. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const DecorativeCursor = require("./decorative-cursor"); - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * The decorative cursor which ignores the first few tokens. - */ -module.exports = class SkipCursor extends DecorativeCursor { - - /** - * Initializes this cursor. - * @param {Cursor} cursor The cursor to be decorated. - * @param {number} count The count of tokens this cursor skips. - */ - constructor(cursor, count) { - super(cursor); - this.count = count; - } - - /** @inheritdoc */ - moveNext() { - while (this.count > 0) { - this.count -= 1; - if (!super.moveNext()) { - return false; - } - } - return super.moveNext(); - } -}; diff --git a/tools/node_modules/eslint/lib/source-code/token-store/utils.js b/tools/node_modules/eslint/lib/source-code/token-store/utils.js deleted file mode 100644 index 21e1d6ff7c3b6d1504fdc7f03798738d56099acf..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/lib/source-code/token-store/utils.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * @fileoverview Define utility functions for token store. - * @author Toru Nagashima - */ -"use strict"; - -//------------------------------------------------------------------------------ -// Requirements -//------------------------------------------------------------------------------ - -const lodash = require("lodash"); - -//------------------------------------------------------------------------------ -// Helpers -//------------------------------------------------------------------------------ - -/** - * Gets `token.range[0]` from the given token. - * @param {Node|Token|Comment} token The token to get. - * @returns {number} The start location. - * @private - */ -function getStartLocation(token) { - return token.range[0]; -} - -//------------------------------------------------------------------------------ -// Exports -//------------------------------------------------------------------------------ - -/** - * Binary-searches the index of the first token which is after the given location. - * If it was not found, this returns `tokens.length`. - * @param {(Token|Comment)[]} tokens It searches the token in this list. - * @param {number} location The location to search. - * @returns {number} The found index or `tokens.length`. - */ -exports.search = function search(tokens, location) { - return lodash.sortedIndexBy( - tokens, - { range: [location] }, - getStartLocation - ); -}; - -/** - * Gets the index of the `startLoc` in `tokens`. - * `startLoc` can be the value of `node.range[1]`, so this checks about `startLoc - 1` as well. - * @param {(Token|Comment)[]} tokens The tokens to find an index. - * @param {Object} indexMap The map from locations to indices. - * @param {number} startLoc The location to get an index. - * @returns {number} The index. - */ -exports.getFirstIndex = function getFirstIndex(tokens, indexMap, startLoc) { - if (startLoc in indexMap) { - return indexMap[startLoc]; - } - if ((startLoc - 1) in indexMap) { - const index = indexMap[startLoc - 1]; - const token = (index >= 0 && index < tokens.length) ? tokens[index] : null; - - /* - * For the map of "comment's location -> token's index", it points the next token of a comment. - * In that case, +1 is unnecessary. - */ - if (token && token.range[0] >= startLoc) { - return index; - } - return index + 1; - } - return 0; -}; - -/** - * Gets the index of the `endLoc` in `tokens`. - * The information of end locations are recorded at `endLoc - 1` in `indexMap`, so this checks about `endLoc - 1` as well. - * @param {(Token|Comment)[]} tokens The tokens to find an index. - * @param {Object} indexMap The map from locations to indices. - * @param {number} endLoc The location to get an index. - * @returns {number} The index. - */ -exports.getLastIndex = function getLastIndex(tokens, indexMap, endLoc) { - if (endLoc in indexMap) { - return indexMap[endLoc] - 1; - } - if ((endLoc - 1) in indexMap) { - const index = indexMap[endLoc - 1]; - const token = (index >= 0 && index < tokens.length) ? tokens[index] : null; - - /* - * For the map of "comment's location -> token's index", it points the next token of a comment. - * In that case, -1 is necessary. - */ - if (token && token.range[1] > endLoc) { - return index - 1; - } - return index; - } - return tokens.length - 1; -}; diff --git a/tools/node_modules/eslint/messages/all-files-ignored.txt b/tools/node_modules/eslint/messages/all-files-ignored.txt deleted file mode 100644 index 3f4c8ced4c9adaef2ca1d5fac0c1d4575e8f6664..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/all-files-ignored.txt +++ /dev/null @@ -1,8 +0,0 @@ -You are linting "<%= pattern %>", but all of the files matching the glob pattern "<%= pattern %>" are ignored. - -If you don't want to lint these files, remove the pattern "<%= pattern %>" from the list of arguments passed to ESLint. - -If you do want to lint these files, try the following solutions: - -* Check your .eslintignore file, or the eslintIgnore property in package.json, to ensure that the files are not configured to be ignored. -* Explicitly list the files from this glob that you'd like to lint on the command-line, rather than providing a glob as an argument. diff --git a/tools/node_modules/eslint/messages/extend-config-missing.txt b/tools/node_modules/eslint/messages/extend-config-missing.txt deleted file mode 100644 index 4defd7ac4d159d19d67e1bfe42df545fb963d958..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/extend-config-missing.txt +++ /dev/null @@ -1,5 +0,0 @@ -ESLint couldn't find the config "<%- configName %>" to extend from. Please check that the name of the config is correct. - -The config "<%- configName %>" was referenced from the config file in "<%- importerName %>". - -If you still have problems, please stop by https://eslint.org/chat/help to chat with the team. diff --git a/tools/node_modules/eslint/messages/failed-to-read-json.txt b/tools/node_modules/eslint/messages/failed-to-read-json.txt deleted file mode 100644 index b5e2b861cfcf234f53c89c1a4c2fb1937b16143c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/failed-to-read-json.txt +++ /dev/null @@ -1,3 +0,0 @@ -Failed to read JSON file at <%= path %>: - -<%= message %> diff --git a/tools/node_modules/eslint/messages/file-not-found.txt b/tools/node_modules/eslint/messages/file-not-found.txt deleted file mode 100644 index 639498eb5c65d05865e18996f62efc2a98c31693..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/file-not-found.txt +++ /dev/null @@ -1,2 +0,0 @@ -No files matching the pattern "<%= pattern %>"<% if (globDisabled) { %> (with disabling globs)<% } %> were found. -Please check for typing mistakes in the pattern. diff --git a/tools/node_modules/eslint/messages/no-config-found.txt b/tools/node_modules/eslint/messages/no-config-found.txt deleted file mode 100644 index b46a7e5a7a6f3f9c3374039451e9544913874919..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/no-config-found.txt +++ /dev/null @@ -1,7 +0,0 @@ -ESLint couldn't find a configuration file. To set up a configuration file for this project, please run: - - eslint --init - -ESLint looked for configuration files in <%= directoryPath %> and its ancestors. If it found none, it then looked in your home directory. - -If you think you already have a configuration file or if you need more help, please stop by the ESLint chat room: https://eslint.org/chat/help diff --git a/tools/node_modules/eslint/messages/plugin-conflict.txt b/tools/node_modules/eslint/messages/plugin-conflict.txt deleted file mode 100644 index 3ab4b340ef2dabfad7459c13bf9eea50c039707d..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/plugin-conflict.txt +++ /dev/null @@ -1,7 +0,0 @@ -ESLint couldn't determine the plugin "<%- pluginId %>" uniquely. -<% for (const { filePath, importerName } of plugins) { %> -- <%= filePath %> (loaded in "<%= importerName %>")<% } %> - -Please remove the "plugins" setting from either config or remove either plugin installation. - -If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. diff --git a/tools/node_modules/eslint/messages/plugin-invalid.txt b/tools/node_modules/eslint/messages/plugin-invalid.txt deleted file mode 100644 index 3ee251821bef27a5d8e1f67ee94fe73fb9a3d0d7..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/plugin-invalid.txt +++ /dev/null @@ -1,8 +0,0 @@ -"<%- configName %>" is invalid syntax for a config specifier. - -* If your intention is to extend from a configuration exported from the plugin, add the configuration name after a slash: e.g. "<%- configName %>/myConfig". -* If this is the name of a shareable config instead of a plugin, remove the "plugin:" prefix: i.e. "<%- configName.slice("plugin:".length) %>". - -"<%- configName %>" was referenced from the config file in "<%- importerName %>". - -If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. diff --git a/tools/node_modules/eslint/messages/plugin-missing.txt b/tools/node_modules/eslint/messages/plugin-missing.txt deleted file mode 100644 index aa25f59ac440ba84ef27d728cbd8865375d04946..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/plugin-missing.txt +++ /dev/null @@ -1,11 +0,0 @@ -ESLint couldn't find the plugin "<%- pluginName %>". - -(The package "<%- pluginName %>" was not found when loaded as a Node module from the directory "<%- resolvePluginsRelativeTo %>".) - -It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: - - npm install <%- pluginName %>@latest --save-dev - -The plugin "<%- pluginName %>" was referenced from the config file in "<%- importerName %>". - -If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. diff --git a/tools/node_modules/eslint/messages/print-config-with-directory-path.txt b/tools/node_modules/eslint/messages/print-config-with-directory-path.txt deleted file mode 100644 index 1afc9b1e88be8f9078b10d2853aad693f078f68b..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/print-config-with-directory-path.txt +++ /dev/null @@ -1,2 +0,0 @@ -The '--print-config' CLI option requires a path to a source code file rather than a directory. -See also: https://eslint.org/docs/user-guide/command-line-interface#--print-config diff --git a/tools/node_modules/eslint/messages/whitespace-found.txt b/tools/node_modules/eslint/messages/whitespace-found.txt deleted file mode 100644 index 3eed1af58665a3cd0369b024fbf25cab5901d415..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/messages/whitespace-found.txt +++ /dev/null @@ -1,3 +0,0 @@ -ESLint couldn't find the plugin "<%- pluginName %>". because there is whitespace in the name. Please check your configuration and remove all whitespace from the plugin name. - -If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/LICENSE b/tools/node_modules/eslint/node_modules/@babel/code-frame/LICENSE deleted file mode 100644 index f31575ec773bb199aeb7c0d0f1612cfe1c7038f1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2014-present Sebastian McKenzie and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/README.md b/tools/node_modules/eslint/node_modules/@babel/code-frame/README.md deleted file mode 100644 index 185f93d24719990274df4f3d974508e5e61cdd8a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @babel/code-frame - -> Generate errors that contain a code frame that point to source locations. - -See our website [@babel/code-frame](https://babeljs.io/docs/en/next/babel-code-frame.html) for more information. - -## Install - -Using npm: - -```sh -npm install --save-dev @babel/code-frame -``` - -or using yarn: - -```sh -yarn add @babel/code-frame --dev -``` diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/lib/index.js b/tools/node_modules/eslint/node_modules/@babel/code-frame/lib/index.js deleted file mode 100644 index 2dd96e5758c777331c0d7eb902c8a12b78f1669c..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/lib/index.js +++ /dev/null @@ -1,167 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.codeFrameColumns = codeFrameColumns; -exports.default = _default; - -var _highlight = _interopRequireWildcard(require("@babel/highlight")); - -function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - -let deprecationWarningShown = false; - -function getDefs(chalk) { - return { - gutter: chalk.grey, - marker: chalk.red.bold, - message: chalk.red.bold - }; -} - -const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - -function getMarkerLines(loc, source, opts) { - const startLoc = Object.assign({ - column: 0, - line: -1 - }, loc.start); - const endLoc = Object.assign(Object.assign({}, startLoc), loc.end); - const { - linesAbove = 2, - linesBelow = 3 - } = opts || {}; - const startLine = startLoc.line; - const startColumn = startLoc.column; - const endLine = endLoc.line; - const endColumn = endLoc.column; - let start = Math.max(startLine - (linesAbove + 1), 0); - let end = Math.min(source.length, endLine + linesBelow); - - if (startLine === -1) { - start = 0; - } - - if (endLine === -1) { - end = source.length; - } - - const lineDiff = endLine - startLine; - const markerLines = {}; - - if (lineDiff) { - for (let i = 0; i <= lineDiff; i++) { - const lineNumber = i + startLine; - - if (!startColumn) { - markerLines[lineNumber] = true; - } else if (i === 0) { - const sourceLength = source[lineNumber - 1].length; - markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; - } else if (i === lineDiff) { - markerLines[lineNumber] = [0, endColumn]; - } else { - const sourceLength = source[lineNumber - i].length; - markerLines[lineNumber] = [0, sourceLength]; - } - } - } else { - if (startColumn === endColumn) { - if (startColumn) { - markerLines[startLine] = [startColumn, 0]; - } else { - markerLines[startLine] = true; - } - } else { - markerLines[startLine] = [startColumn, endColumn - startColumn]; - } - } - - return { - start, - end, - markerLines - }; -} - -function codeFrameColumns(rawLines, loc, opts = {}) { - const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); - const chalk = (0, _highlight.getChalk)(opts); - const defs = getDefs(chalk); - - const maybeHighlight = (chalkFn, string) => { - return highlighted ? chalkFn(string) : string; - }; - - const lines = rawLines.split(NEWLINE); - const { - start, - end, - markerLines - } = getMarkerLines(loc, lines, opts); - const hasColumns = loc.start && typeof loc.start.column === "number"; - const numberMaxWidth = String(end).length; - const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; - let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { - const number = start + 1 + index; - const paddedNumber = ` ${number}`.slice(-numberMaxWidth); - const gutter = ` ${paddedNumber} | `; - const hasMarker = markerLines[number]; - const lastMarkerLine = !markerLines[number + 1]; - - if (hasMarker) { - let markerLine = ""; - - if (Array.isArray(hasMarker)) { - const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); - const numberOfMarkers = hasMarker[1] || 1; - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); - - if (lastMarkerLine && opts.message) { - markerLine += " " + maybeHighlight(defs.message, opts.message); - } - } - - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); - } else { - return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; - } - }).join("\n"); - - if (opts.message && !hasColumns) { - frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; - } - - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; - } -} - -function _default(rawLines, lineNumber, colNumber, opts = {}) { - if (!deprecationWarningShown) { - deprecationWarningShown = true; - const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; - - if (process.emitWarning) { - process.emitWarning(message, "DeprecationWarning"); - } else { - const deprecationError = new Error(message); - deprecationError.name = "DeprecationWarning"; - console.warn(new Error(message)); - } - } - - colNumber = Math.max(colNumber, 0); - const location = { - start: { - column: colNumber, - line: lineNumber - } - }; - return codeFrameColumns(rawLines, location, opts); -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/code-frame/package.json b/tools/node_modules/eslint/node_modules/@babel/code-frame/package.json deleted file mode 100644 index 05e388a35497122a4c5a3dafb80fd7f80ff671a6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/code-frame/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "bugs": { - "url": "https://github.com/babel/babel/issues" - }, - "bundleDependencies": false, - "dependencies": { - "@babel/highlight": "^7.10.1" - }, - "deprecated": false, - "description": "Generate errors that contain a code frame that point to source locations.", - "devDependencies": { - "chalk": "^2.0.0", - "strip-ansi": "^4.0.0" - }, - "gitHead": "88f57a7ea659d25232bf62de1efceb5d6299b8cf", - "homepage": "https://babeljs.io/", - "license": "MIT", - "main": "lib/index.js", - "name": "@babel/code-frame", - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/babel/babel.git", - "directory": "packages/babel-code-frame" - }, - "version": "7.10.1" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/LICENSE b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/LICENSE deleted file mode 100644 index f31575ec773bb199aeb7c0d0f1612cfe1c7038f1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2014-present Sebastian McKenzie and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/README.md b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/README.md deleted file mode 100644 index ab2dad173149e874cea3dee201a275aac7b053ed..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @babel/helper-validator-identifier - -> Validate identifier/keywords name - -See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/en/next/babel-helper-validator-identifier.html) for more information. - -## Install - -Using npm: - -```sh -npm install --save-dev @babel/helper-validator-identifier -``` - -or using yarn: - -```sh -yarn add @babel/helper-validator-identifier --dev -``` diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/identifier.js b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/identifier.js deleted file mode 100644 index 51ec76370ccfc623feb6ecd8f1169600a9c45c19..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/identifier.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isIdentifierStart = isIdentifierStart; -exports.isIdentifierChar = isIdentifierChar; -exports.isIdentifierName = isIdentifierName; -let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; -let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; -const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; -const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; -const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; - -function isInAstralSet(code, set) { - let pos = 0x10000; - - for (let i = 0, length = set.length; i < length; i += 2) { - pos += set[i]; - if (pos > code) return false; - pos += set[i + 1]; - if (pos >= code) return true; - } - - return false; -} - -function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code <= 90) return true; - if (code < 97) return code === 95; - if (code <= 122) return true; - - if (code <= 0xffff) { - return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - } - - return isInAstralSet(code, astralIdentifierStartCodes); -} - -function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code <= 90) return true; - if (code < 97) return code === 95; - if (code <= 122) return true; - - if (code <= 0xffff) { - return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - } - - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); -} - -function isIdentifierName(name) { - let isFirst = true; - - for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { - const char = _Array$from[_i]; - const cp = char.codePointAt(0); - - if (isFirst) { - if (!isIdentifierStart(cp)) { - return false; - } - - isFirst = false; - } else if (!isIdentifierChar(cp)) { - return false; - } - } - - return !isFirst; -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/index.js b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/index.js deleted file mode 100644 index 7b623c90a6e164c669cedff262de4048c2290857..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/index.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -Object.defineProperty(exports, "isIdentifierName", { - enumerable: true, - get: function () { - return _identifier.isIdentifierName; - } -}); -Object.defineProperty(exports, "isIdentifierChar", { - enumerable: true, - get: function () { - return _identifier.isIdentifierChar; - } -}); -Object.defineProperty(exports, "isIdentifierStart", { - enumerable: true, - get: function () { - return _identifier.isIdentifierStart; - } -}); -Object.defineProperty(exports, "isReservedWord", { - enumerable: true, - get: function () { - return _keyword.isReservedWord; - } -}); -Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { - enumerable: true, - get: function () { - return _keyword.isStrictBindOnlyReservedWord; - } -}); -Object.defineProperty(exports, "isStrictBindReservedWord", { - enumerable: true, - get: function () { - return _keyword.isStrictBindReservedWord; - } -}); -Object.defineProperty(exports, "isStrictReservedWord", { - enumerable: true, - get: function () { - return _keyword.isStrictReservedWord; - } -}); -Object.defineProperty(exports, "isKeyword", { - enumerable: true, - get: function () { - return _keyword.isKeyword; - } -}); - -var _identifier = require("./identifier"); - -var _keyword = require("./keyword"); \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/keyword.js b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/keyword.js deleted file mode 100644 index 110cee4002896b7024e15c0e92f505eb40b9afa6..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/lib/keyword.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isReservedWord = isReservedWord; -exports.isStrictReservedWord = isStrictReservedWord; -exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; -exports.isStrictBindReservedWord = isStrictBindReservedWord; -exports.isKeyword = isKeyword; -const reservedWords = { - keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], - strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], - strictBind: ["eval", "arguments"] -}; -const keywords = new Set(reservedWords.keyword); -const reservedWordsStrictSet = new Set(reservedWords.strict); -const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); - -function isReservedWord(word, inModule) { - return inModule && word === "await" || word === "enum"; -} - -function isStrictReservedWord(word, inModule) { - return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); -} - -function isStrictBindOnlyReservedWord(word) { - return reservedWordsStrictBindSet.has(word); -} - -function isStrictBindReservedWord(word, inModule) { - return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); -} - -function isKeyword(word) { - return keywords.has(word); -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/package.json b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/package.json deleted file mode 100644 index 7ca0be602c99a6fb1926fe6ef1562cfacbb787ce..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "bugs": { - "url": "https://github.com/babel/babel/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Validate identifier/keywords name", - "devDependencies": { - "charcodes": "^0.2.0", - "unicode-13.0.0": "^0.8.0" - }, - "exports": "./lib/index.js", - "gitHead": "88f57a7ea659d25232bf62de1efceb5d6299b8cf", - "homepage": "https://github.com/babel/babel#readme", - "license": "MIT", - "main": "./lib/index.js", - "name": "@babel/helper-validator-identifier", - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/babel/babel.git", - "directory": "packages/babel-helper-validator-identifier" - }, - "version": "7.10.1" -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js b/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js deleted file mode 100644 index e0f5b1656b97de1e6d23bc6c3daebc1e91849d82..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/helper-validator-identifier/scripts/generate-identifier-regex.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; - -// Always use the latest available version of Unicode! -// https://tc39.github.io/ecma262/#sec-conformance -const version = "13.0.0"; - -const start = require("unicode-" + - version + - "/Binary_Property/ID_Start/code-points.js").filter(function(ch) { - return ch > 0x7f; -}); -let last = -1; -const cont = [0x200c, 0x200d].concat( - require("unicode-" + - version + - "/Binary_Property/ID_Continue/code-points.js").filter(function(ch) { - return ch > 0x7f && search(start, ch, last + 1) == -1; - }) -); - -function search(arr, ch, starting) { - for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) { - if (arr[i] === ch) return i; - } - return -1; -} - -function pad(str, width) { - while (str.length < width) str = "0" + str; - return str; -} - -function esc(code) { - const hex = code.toString(16); - if (hex.length <= 2) return "\\x" + pad(hex, 2); - else return "\\u" + pad(hex, 4); -} - -function generate(chars) { - const astral = []; - let re = ""; - for (let i = 0, at = 0x10000; i < chars.length; i++) { - const from = chars[i]; - let to = from; - while (i < chars.length - 1 && chars[i + 1] == to + 1) { - i++; - to++; - } - if (to <= 0xffff) { - if (from == to) re += esc(from); - else if (from + 1 == to) re += esc(from) + esc(to); - else re += esc(from) + "-" + esc(to); - } else { - astral.push(from - at, to - from); - at = to; - } - } - return { nonASCII: re, astral: astral }; -} - -const startData = generate(start); -const contData = generate(cont); - -console.log("/* prettier-ignore */"); -console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";'); -console.log("/* prettier-ignore */"); -console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";'); -console.log("/* prettier-ignore */"); -console.log( - "const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";" -); -console.log("/* prettier-ignore */"); -console.log( - "const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";" -); diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/LICENSE b/tools/node_modules/eslint/node_modules/@babel/highlight/LICENSE deleted file mode 100644 index f31575ec773bb199aeb7c0d0f1612cfe1c7038f1..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2014-present Sebastian McKenzie and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/README.md b/tools/node_modules/eslint/node_modules/@babel/highlight/README.md deleted file mode 100644 index 72dae6094590f32c82ba8b0a0e732e160df6f582..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @babel/highlight - -> Syntax highlight JavaScript strings for output in terminals. - -See our website [@babel/highlight](https://babeljs.io/docs/en/next/babel-highlight.html) for more information. - -## Install - -Using npm: - -```sh -npm install --save-dev @babel/highlight -``` - -or using yarn: - -```sh -yarn add @babel/highlight --dev -``` diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/lib/index.js b/tools/node_modules/eslint/node_modules/@babel/highlight/lib/index.js deleted file mode 100644 index b0d1be7f553b64c5abe292db5339741ba29ace6f..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/lib/index.js +++ /dev/null @@ -1,107 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.shouldHighlight = shouldHighlight; -exports.getChalk = getChalk; -exports.default = highlight; - -var _jsTokens = _interopRequireWildcard(require("js-tokens")); - -var _helperValidatorIdentifier = require("@babel/helper-validator-identifier"); - -var _chalk = _interopRequireDefault(require("chalk")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - -function getDefs(chalk) { - return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold - }; -} - -const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; -const JSX_TAG = /^[a-z][\w-]*$/i; -const BRACKET = /^[()[\]{}]$/; - -function getTokenType(match) { - const [offset, text] = match.slice(-2); - const token = (0, _jsTokens.matchToToken)(match); - - if (token.type === "name") { - if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isReservedWord)(token.value)) { - return "keyword"; - } - - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); - } else { - return args[0]; - } - }); -} - -function shouldHighlight(options) { - return _chalk.default.supportsColor || options.forceColor; -} - -function getChalk(options) { - let chalk = _chalk.default; - - if (options.forceColor) { - chalk = new _chalk.default.constructor({ - enabled: true, - level: 1 - }); - } - - return chalk; -} - -function highlight(code, options = {}) { - if (shouldHighlight(options)) { - const chalk = getChalk(options); - const defs = getDefs(chalk); - return highlightTokens(defs, code); - } else { - return code; - } -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/index.js b/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/index.js deleted file mode 100644 index 1cc5fa89a951596647e711d84cf88b1410e4d3ea..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/index.js +++ /dev/null @@ -1,228 +0,0 @@ -'use strict'; -const escapeStringRegexp = require('escape-string-regexp'); -const ansiStyles = require('ansi-styles'); -const stdoutColor = require('supports-color').stdout; - -const template = require('./templates.js'); - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); - -const styles = Object.create(null); - -function applyOptions(obj, options) { - options = options || {}; - - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} - -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = Chalk; - - return chalk.template; - } - - applyOptions(this, options); -} - -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} - -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} - -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; - -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } - - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } - - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, styles); - -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - - const self = this; - - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); - - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); - - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; - - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto - - return builder; -} - -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); - - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } - - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; - - return str; -} - -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } - - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; - - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } - - return template(chalk, parts.join('')); -} - -Object.defineProperties(Chalk.prototype, styles); - -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/index.js.flow b/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/index.js.flow deleted file mode 100644 index 622caaa2e803f3b451f617a391b61383925e05d3..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/index.js.flow +++ /dev/null @@ -1,93 +0,0 @@ -// @flow strict - -type TemplateStringsArray = $ReadOnlyArray; - -export type Level = $Values<{ - None: 0, - Basic: 1, - Ansi256: 2, - TrueColor: 3 -}>; - -export type ChalkOptions = {| - enabled?: boolean, - level?: Level -|}; - -export type ColorSupport = {| - level: Level, - hasBasic: boolean, - has256: boolean, - has16m: boolean -|}; - -export interface Chalk { - (...text: string[]): string, - (text: TemplateStringsArray, ...placeholders: string[]): string, - constructor(options?: ChalkOptions): Chalk, - enabled: boolean, - level: Level, - rgb(r: number, g: number, b: number): Chalk, - hsl(h: number, s: number, l: number): Chalk, - hsv(h: number, s: number, v: number): Chalk, - hwb(h: number, w: number, b: number): Chalk, - bgHex(color: string): Chalk, - bgKeyword(color: string): Chalk, - bgRgb(r: number, g: number, b: number): Chalk, - bgHsl(h: number, s: number, l: number): Chalk, - bgHsv(h: number, s: number, v: number): Chalk, - bgHwb(h: number, w: number, b: number): Chalk, - hex(color: string): Chalk, - keyword(color: string): Chalk, - - +reset: Chalk, - +bold: Chalk, - +dim: Chalk, - +italic: Chalk, - +underline: Chalk, - +inverse: Chalk, - +hidden: Chalk, - +strikethrough: Chalk, - - +visible: Chalk, - - +black: Chalk, - +red: Chalk, - +green: Chalk, - +yellow: Chalk, - +blue: Chalk, - +magenta: Chalk, - +cyan: Chalk, - +white: Chalk, - +gray: Chalk, - +grey: Chalk, - +blackBright: Chalk, - +redBright: Chalk, - +greenBright: Chalk, - +yellowBright: Chalk, - +blueBright: Chalk, - +magentaBright: Chalk, - +cyanBright: Chalk, - +whiteBright: Chalk, - - +bgBlack: Chalk, - +bgRed: Chalk, - +bgGreen: Chalk, - +bgYellow: Chalk, - +bgBlue: Chalk, - +bgMagenta: Chalk, - +bgCyan: Chalk, - +bgWhite: Chalk, - +bgBlackBright: Chalk, - +bgRedBright: Chalk, - +bgGreenBright: Chalk, - +bgYellowBright: Chalk, - +bgBlueBright: Chalk, - +bgMagentaBright: Chalk, - +bgCyanBright: Chalk, - +bgWhiteBrigh: Chalk, - - supportsColor: ColorSupport -}; - -declare module.exports: Chalk; diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/license b/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/license deleted file mode 100644 index e7af2f77107d73046421ef56c4684cbfdd3c1e89..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/package.json b/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/package.json deleted file mode 100644 index 270fecdc347d42c8b15f56da6dbaf7b0dfb64b5a..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/package.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "bugs": { - "url": "https://github.com/chalk/chalk/issues" - }, - "bundleDependencies": false, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "deprecated": false, - "description": "Terminal string styling done right", - "devDependencies": { - "ava": "*", - "coveralls": "^3.0.0", - "execa": "^0.9.0", - "flow-bin": "^0.68.0", - "import-fresh": "^2.0.0", - "matcha": "^0.7.0", - "nyc": "^11.0.2", - "resolve-from": "^4.0.0", - "typescript": "^2.5.3", - "xo": "*" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "templates.js", - "types/index.d.ts", - "index.js.flow" - ], - "homepage": "https://github.com/chalk/chalk#readme", - "keywords": [ - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "str", - "ansi", - "style", - "styles", - "tty", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "license": "MIT", - "name": "chalk", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/chalk.git" - }, - "scripts": { - "bench": "matcha benchmark.js", - "coveralls": "nyc report --reporter=text-lcov | coveralls", - "test": "xo && tsc --project types && flow --max-warnings=0 && nyc ava" - }, - "types": "types/index.d.ts", - "version": "2.4.2", - "xo": { - "envs": [ - "node", - "mocha" - ], - "ignores": [ - "test/_flow.js" - ] - } -} \ No newline at end of file diff --git a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/readme.md b/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/readme.md deleted file mode 100644 index d298e2c48d64a0ce10744fbae5129782f00d6908..0000000000000000000000000000000000000000 --- a/tools/node_modules/eslint/node_modules/@babel/highlight/node_modules/chalk/readme.md +++ /dev/null @@ -1,314 +0,0 @@ -

-
-
- Chalk -
-
-
-

- -> Terminal string styling done right - -[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) [![Mentioned in Awesome Node.js](https://awesome.re/mentioned-badge.svg)](https://github.com/sindresorhus/awesome-nodejs) - -### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0) - - - - -## Highlights - -- Expressive API -- Highly performant -- Ability to nest styles -- [256/Truecolor color support](#256-and-truecolor-color-support) -- Auto-detects color support -- Doesn't extend `String.prototype` -- Clean and focused -- Actively maintained -- [Used by ~23,000 packages](https://www.npmjs.com/browse/depended/chalk) as of December 31, 2017 - - -## Install - -```console -$ npm install chalk -``` - - - - - - -## Usage - -```js -const chalk = require('chalk'); - -console.log(chalk.blue('Hello world!')); -``` - -Chalk comes with an easy to use composable API where you just chain and nest the styles you want. - -```js -const chalk = require('chalk'); -const log = console.log; - -// Combine styled and normal strings -log(chalk.blue('Hello') + ' World' + chalk.red('!')); - -// Compose multiple styles using the chainable API -log(chalk.blue.bgRed.bold('Hello world!')); - -// Pass in multiple arguments -log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); - -// Nest styles -log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); - -// Nest styles of the same type even (color, underline, background) -log(chalk.green( - 'I am a green line ' + - chalk.blue.underline.bold('with a blue substring') + - ' that becomes green again!' -)); - -// ES2015 template literal -log(` -CPU: ${chalk.red('90%')} -RAM: ${chalk.green('40%')} -DISK: ${chalk.yellow('70%')} -`); - -// ES2015 tagged template literal -log(chalk` -CPU: {red ${cpu.totalPercent}%} -RAM: {green ${ram.used / ram.total * 100}%} -DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} -`); - -// Use RGB colors in terminal emulators that support it. -log(chalk.keyword('orange')('Yay for orange colored text!')); -log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); -log(chalk.hex('#DEADED').bold('Bold gray!')); -``` - -Easily define your own themes: - -```js -const chalk = require('chalk'); - -const error = chalk.bold.red; -const warning = chalk.keyword('orange'); - -console.log(error('Error!')); -console.log(warning('Warning!')); -``` - -Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): - -```js -const name = 'Sindre'; -console.log(chalk.green('Hello %s'), name); -//=> 'Hello Sindre' -``` - - -## API - -### chalk.`